vendor.js 1.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486
  1. "use strict";
  2. const _export_sfc = (sfc, props) => {
  3. const target = sfc.__vccOpts || sfc;
  4. for (const [key, val] of props) {
  5. target[key] = val;
  6. }
  7. return target;
  8. };
  9. /**
  10. * @vue/shared v3.4.21
  11. * (c) 2018-present Yuxi (Evan) You and Vue contributors
  12. * @license MIT
  13. **/
  14. function makeMap(str, expectsLowerCase) {
  15. const set2 = new Set(str.split(","));
  16. return expectsLowerCase ? (val) => set2.has(val.toLowerCase()) : (val) => set2.has(val);
  17. }
  18. const EMPTY_OBJ = Object.freeze({});
  19. const EMPTY_ARR = Object.freeze([]);
  20. const NOOP = () => {
  21. };
  22. const NO = () => false;
  23. const isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter
  24. (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97);
  25. const isModelListener = (key) => key.startsWith("onUpdate:");
  26. const extend = Object.assign;
  27. const remove = (arr, el) => {
  28. const i2 = arr.indexOf(el);
  29. if (i2 > -1) {
  30. arr.splice(i2, 1);
  31. }
  32. };
  33. const hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  34. const hasOwn = (val, key) => hasOwnProperty$1.call(val, key);
  35. const isArray = Array.isArray;
  36. const isMap = (val) => toTypeString(val) === "[object Map]";
  37. const isSet = (val) => toTypeString(val) === "[object Set]";
  38. const isFunction = (val) => typeof val === "function";
  39. const isString = (val) => typeof val === "string";
  40. const isSymbol = (val) => typeof val === "symbol";
  41. const isObject$1 = (val) => val !== null && typeof val === "object";
  42. const isPromise$2 = (val) => {
  43. return (isObject$1(val) || isFunction(val)) && isFunction(val.then) && isFunction(val.catch);
  44. };
  45. const objectToString = Object.prototype.toString;
  46. const toTypeString = (value) => objectToString.call(value);
  47. const toRawType = (value) => {
  48. return toTypeString(value).slice(8, -1);
  49. };
  50. const isPlainObject = (val) => toTypeString(val) === "[object Object]";
  51. const isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key;
  52. const isReservedProp = /* @__PURE__ */ makeMap(
  53. // the leading comma is intentional so empty string "" is also included
  54. ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"
  55. );
  56. const isBuiltInDirective = /* @__PURE__ */ makeMap(
  57. "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo"
  58. );
  59. const cacheStringFunction = (fn2) => {
  60. const cache = /* @__PURE__ */ Object.create(null);
  61. return (str) => {
  62. const hit = cache[str];
  63. return hit || (cache[str] = fn2(str));
  64. };
  65. };
  66. const camelizeRE = /-(\w)/g;
  67. const camelize = cacheStringFunction((str) => {
  68. return str.replace(camelizeRE, (_2, c2) => c2 ? c2.toUpperCase() : "");
  69. });
  70. const hyphenateRE = /\B([A-Z])/g;
  71. const hyphenate = cacheStringFunction(
  72. (str) => str.replace(hyphenateRE, "-$1").toLowerCase()
  73. );
  74. const capitalize = cacheStringFunction((str) => {
  75. return str.charAt(0).toUpperCase() + str.slice(1);
  76. });
  77. const toHandlerKey = cacheStringFunction((str) => {
  78. const s2 = str ? `on${capitalize(str)}` : ``;
  79. return s2;
  80. });
  81. const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
  82. const invokeArrayFns$1 = (fns, arg) => {
  83. for (let i2 = 0; i2 < fns.length; i2++) {
  84. fns[i2](arg);
  85. }
  86. };
  87. const def = (obj, key, value) => {
  88. Object.defineProperty(obj, key, {
  89. configurable: true,
  90. enumerable: false,
  91. value
  92. });
  93. };
  94. const looseToNumber = (val) => {
  95. const n2 = parseFloat(val);
  96. return isNaN(n2) ? val : n2;
  97. };
  98. function normalizeStyle(value) {
  99. if (isArray(value)) {
  100. const res = {};
  101. for (let i2 = 0; i2 < value.length; i2++) {
  102. const item = value[i2];
  103. const normalized = isString(item) ? parseStringStyle(item) : normalizeStyle(item);
  104. if (normalized) {
  105. for (const key in normalized) {
  106. res[key] = normalized[key];
  107. }
  108. }
  109. }
  110. return res;
  111. } else if (isString(value) || isObject$1(value)) {
  112. return value;
  113. }
  114. }
  115. const listDelimiterRE = /;(?![^(]*\))/g;
  116. const propertyDelimiterRE = /:([^]+)/;
  117. const styleCommentRE = /\/\*[^]*?\*\//g;
  118. function parseStringStyle(cssText) {
  119. const ret = {};
  120. cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => {
  121. if (item) {
  122. const tmp = item.split(propertyDelimiterRE);
  123. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  124. }
  125. });
  126. return ret;
  127. }
  128. function normalizeClass(value) {
  129. let res = "";
  130. if (isString(value)) {
  131. res = value;
  132. } else if (isArray(value)) {
  133. for (let i2 = 0; i2 < value.length; i2++) {
  134. const normalized = normalizeClass(value[i2]);
  135. if (normalized) {
  136. res += normalized + " ";
  137. }
  138. }
  139. } else if (isObject$1(value)) {
  140. for (const name in value) {
  141. if (value[name]) {
  142. res += name + " ";
  143. }
  144. }
  145. }
  146. return res.trim();
  147. }
  148. const toDisplayString = (val) => {
  149. return isString(val) ? val : val == null ? "" : isArray(val) || isObject$1(val) && (val.toString === objectToString || !isFunction(val.toString)) ? JSON.stringify(val, replacer, 2) : String(val);
  150. };
  151. const replacer = (_key, val) => {
  152. if (val && val.__v_isRef) {
  153. return replacer(_key, val.value);
  154. } else if (isMap(val)) {
  155. return {
  156. [`Map(${val.size})`]: [...val.entries()].reduce(
  157. (entries, [key, val2], i2) => {
  158. entries[stringifySymbol(key, i2) + " =>"] = val2;
  159. return entries;
  160. },
  161. {}
  162. )
  163. };
  164. } else if (isSet(val)) {
  165. return {
  166. [`Set(${val.size})`]: [...val.values()].map((v2) => stringifySymbol(v2))
  167. };
  168. } else if (isSymbol(val)) {
  169. return stringifySymbol(val);
  170. } else if (isObject$1(val) && !isArray(val) && !isPlainObject(val)) {
  171. return String(val);
  172. }
  173. return val;
  174. };
  175. const stringifySymbol = (v2, i2 = "") => {
  176. var _a;
  177. return isSymbol(v2) ? `Symbol(${(_a = v2.description) != null ? _a : i2})` : v2;
  178. };
  179. const SLOT_DEFAULT_NAME = "d";
  180. const ON_SHOW = "onShow";
  181. const ON_HIDE = "onHide";
  182. const ON_LAUNCH = "onLaunch";
  183. const ON_ERROR = "onError";
  184. const ON_THEME_CHANGE = "onThemeChange";
  185. const ON_PAGE_NOT_FOUND = "onPageNotFound";
  186. const ON_UNHANDLE_REJECTION = "onUnhandledRejection";
  187. const ON_EXIT = "onExit";
  188. const ON_LOAD = "onLoad";
  189. const ON_READY = "onReady";
  190. const ON_UNLOAD = "onUnload";
  191. const ON_INIT = "onInit";
  192. const ON_SAVE_EXIT_STATE = "onSaveExitState";
  193. const ON_RESIZE = "onResize";
  194. const ON_BACK_PRESS = "onBackPress";
  195. const ON_PAGE_SCROLL = "onPageScroll";
  196. const ON_TAB_ITEM_TAP = "onTabItemTap";
  197. const ON_REACH_BOTTOM = "onReachBottom";
  198. const ON_PULL_DOWN_REFRESH = "onPullDownRefresh";
  199. const ON_SHARE_TIMELINE = "onShareTimeline";
  200. const ON_SHARE_CHAT = "onShareChat";
  201. const ON_ADD_TO_FAVORITES = "onAddToFavorites";
  202. const ON_SHARE_APP_MESSAGE = "onShareAppMessage";
  203. const ON_NAVIGATION_BAR_BUTTON_TAP = "onNavigationBarButtonTap";
  204. const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = "onNavigationBarSearchInputClicked";
  205. const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = "onNavigationBarSearchInputChanged";
  206. const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = "onNavigationBarSearchInputConfirmed";
  207. const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = "onNavigationBarSearchInputFocusChanged";
  208. const VIRTUAL_HOST_STYLE = "virtualHostStyle";
  209. const VIRTUAL_HOST_CLASS = "virtualHostClass";
  210. const VIRTUAL_HOST_HIDDEN = "virtualHostHidden";
  211. const VIRTUAL_HOST_ID = "virtualHostId";
  212. function hasLeadingSlash(str) {
  213. return str.indexOf("/") === 0;
  214. }
  215. function addLeadingSlash(str) {
  216. return hasLeadingSlash(str) ? str : "/" + str;
  217. }
  218. const invokeArrayFns = (fns, arg) => {
  219. let ret;
  220. for (let i2 = 0; i2 < fns.length; i2++) {
  221. ret = fns[i2](arg);
  222. }
  223. return ret;
  224. };
  225. function once(fn2, ctx = null) {
  226. let res;
  227. return (...args) => {
  228. if (fn2) {
  229. res = fn2.apply(ctx, args);
  230. fn2 = null;
  231. }
  232. return res;
  233. };
  234. }
  235. function getValueByDataPath(obj, path) {
  236. if (!isString(path)) {
  237. return;
  238. }
  239. path = path.replace(/\[(\d+)\]/g, ".$1");
  240. const parts = path.split(".");
  241. let key = parts[0];
  242. if (!obj) {
  243. obj = {};
  244. }
  245. if (parts.length === 1) {
  246. return obj[key];
  247. }
  248. return getValueByDataPath(obj[key], parts.slice(1).join("."));
  249. }
  250. function sortObject(obj) {
  251. let sortObj = {};
  252. if (isPlainObject(obj)) {
  253. Object.keys(obj).sort().forEach((key) => {
  254. const _key = key;
  255. sortObj[_key] = obj[_key];
  256. });
  257. }
  258. return !Object.keys(sortObj) ? obj : sortObj;
  259. }
  260. const customizeRE = /:/g;
  261. function customizeEvent(str) {
  262. return camelize(str.replace(customizeRE, "-"));
  263. }
  264. const encode = encodeURIComponent;
  265. function stringifyQuery(obj, encodeStr = encode) {
  266. const res = obj ? Object.keys(obj).map((key) => {
  267. let val = obj[key];
  268. if (typeof val === void 0 || val === null) {
  269. val = "";
  270. } else if (isPlainObject(val)) {
  271. val = JSON.stringify(val);
  272. }
  273. return encodeStr(key) + "=" + encodeStr(val);
  274. }).filter((x) => x.length > 0).join("&") : null;
  275. return res ? `?${res}` : "";
  276. }
  277. const PAGE_HOOKS = [
  278. ON_INIT,
  279. ON_LOAD,
  280. ON_SHOW,
  281. ON_HIDE,
  282. ON_UNLOAD,
  283. ON_BACK_PRESS,
  284. ON_PAGE_SCROLL,
  285. ON_TAB_ITEM_TAP,
  286. ON_REACH_BOTTOM,
  287. ON_PULL_DOWN_REFRESH,
  288. ON_SHARE_TIMELINE,
  289. ON_SHARE_APP_MESSAGE,
  290. ON_SHARE_CHAT,
  291. ON_ADD_TO_FAVORITES,
  292. ON_SAVE_EXIT_STATE,
  293. ON_NAVIGATION_BAR_BUTTON_TAP,
  294. ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED,
  295. ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED,
  296. ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED,
  297. ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED
  298. ];
  299. function isRootHook(name) {
  300. return PAGE_HOOKS.indexOf(name) > -1;
  301. }
  302. const UniLifecycleHooks = [
  303. ON_SHOW,
  304. ON_HIDE,
  305. ON_LAUNCH,
  306. ON_ERROR,
  307. ON_THEME_CHANGE,
  308. ON_PAGE_NOT_FOUND,
  309. ON_UNHANDLE_REJECTION,
  310. ON_EXIT,
  311. ON_INIT,
  312. ON_LOAD,
  313. ON_READY,
  314. ON_UNLOAD,
  315. ON_RESIZE,
  316. ON_BACK_PRESS,
  317. ON_PAGE_SCROLL,
  318. ON_TAB_ITEM_TAP,
  319. ON_REACH_BOTTOM,
  320. ON_PULL_DOWN_REFRESH,
  321. ON_SHARE_TIMELINE,
  322. ON_ADD_TO_FAVORITES,
  323. ON_SHARE_APP_MESSAGE,
  324. ON_SHARE_CHAT,
  325. ON_SAVE_EXIT_STATE,
  326. ON_NAVIGATION_BAR_BUTTON_TAP,
  327. ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED,
  328. ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED,
  329. ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED,
  330. ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED
  331. ];
  332. const MINI_PROGRAM_PAGE_RUNTIME_HOOKS = /* @__PURE__ */ (() => {
  333. return {
  334. onPageScroll: 1,
  335. onShareAppMessage: 1 << 1,
  336. onShareTimeline: 1 << 2
  337. };
  338. })();
  339. function isUniLifecycleHook(name, value, checkType = true) {
  340. if (checkType && !isFunction(value)) {
  341. return false;
  342. }
  343. if (UniLifecycleHooks.indexOf(name) > -1) {
  344. return true;
  345. } else if (name.indexOf("on") === 0) {
  346. return true;
  347. }
  348. return false;
  349. }
  350. let vueApp;
  351. const createVueAppHooks = [];
  352. function onCreateVueApp(hook) {
  353. if (vueApp) {
  354. return hook(vueApp);
  355. }
  356. createVueAppHooks.push(hook);
  357. }
  358. function invokeCreateVueAppHook(app) {
  359. vueApp = app;
  360. createVueAppHooks.forEach((hook) => hook(app));
  361. }
  362. const invokeCreateErrorHandler = once((app, createErrorHandler2) => {
  363. return createErrorHandler2(app);
  364. });
  365. const E$1 = function() {
  366. };
  367. E$1.prototype = {
  368. _id: 1,
  369. on: function(name, callback, ctx) {
  370. var e2 = this.e || (this.e = {});
  371. (e2[name] || (e2[name] = [])).push({
  372. fn: callback,
  373. ctx,
  374. _id: this._id
  375. });
  376. return this._id++;
  377. },
  378. once: function(name, callback, ctx) {
  379. var self2 = this;
  380. function listener() {
  381. self2.off(name, listener);
  382. callback.apply(ctx, arguments);
  383. }
  384. listener._ = callback;
  385. return this.on(name, listener, ctx);
  386. },
  387. emit: function(name) {
  388. var data = [].slice.call(arguments, 1);
  389. var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
  390. var i2 = 0;
  391. var len = evtArr.length;
  392. for (i2; i2 < len; i2++) {
  393. evtArr[i2].fn.apply(evtArr[i2].ctx, data);
  394. }
  395. return this;
  396. },
  397. off: function(name, event) {
  398. var e2 = this.e || (this.e = {});
  399. var evts = e2[name];
  400. var liveEvents = [];
  401. if (evts && event) {
  402. for (var i2 = evts.length - 1; i2 >= 0; i2--) {
  403. if (evts[i2].fn === event || evts[i2].fn._ === event || evts[i2]._id === event) {
  404. evts.splice(i2, 1);
  405. break;
  406. }
  407. }
  408. liveEvents = evts;
  409. }
  410. liveEvents.length ? e2[name] = liveEvents : delete e2[name];
  411. return this;
  412. }
  413. };
  414. var E$1$1 = E$1;
  415. const LOCALE_ZH_HANS = "zh-Hans";
  416. const LOCALE_ZH_HANT = "zh-Hant";
  417. const LOCALE_EN = "en";
  418. const LOCALE_FR = "fr";
  419. const LOCALE_ES = "es";
  420. function include(str, parts) {
  421. return !!parts.find((part) => str.indexOf(part) !== -1);
  422. }
  423. function startsWith$1(str, parts) {
  424. return parts.find((part) => str.indexOf(part) === 0);
  425. }
  426. function normalizeLocale(locale, messages) {
  427. if (!locale) {
  428. return;
  429. }
  430. locale = locale.trim().replace(/_/g, "-");
  431. if (messages && messages[locale]) {
  432. return locale;
  433. }
  434. locale = locale.toLowerCase();
  435. if (locale === "chinese") {
  436. return LOCALE_ZH_HANS;
  437. }
  438. if (locale.indexOf("zh") === 0) {
  439. if (locale.indexOf("-hans") > -1) {
  440. return LOCALE_ZH_HANS;
  441. }
  442. if (locale.indexOf("-hant") > -1) {
  443. return LOCALE_ZH_HANT;
  444. }
  445. if (include(locale, ["-tw", "-hk", "-mo", "-cht"])) {
  446. return LOCALE_ZH_HANT;
  447. }
  448. return LOCALE_ZH_HANS;
  449. }
  450. let locales = [LOCALE_EN, LOCALE_FR, LOCALE_ES];
  451. if (messages && Object.keys(messages).length > 0) {
  452. locales = Object.keys(messages);
  453. }
  454. const lang = startsWith$1(locale, locales);
  455. if (lang) {
  456. return lang;
  457. }
  458. }
  459. function getLocaleLanguage$1() {
  460. var _a;
  461. let localeLanguage = "";
  462. {
  463. const appBaseInfo = ((_a = wx.getAppBaseInfo) === null || _a === void 0 ? void 0 : _a.call(wx)) || wx.getSystemInfoSync();
  464. const language = appBaseInfo && appBaseInfo.language ? appBaseInfo.language : LOCALE_EN;
  465. localeLanguage = normalizeLocale(language) || LOCALE_EN;
  466. }
  467. return localeLanguage;
  468. }
  469. function validateProtocolFail(name, msg) {
  470. console.warn(`${name}: ${msg}`);
  471. }
  472. function validateProtocol(name, data, protocol, onFail) {
  473. if (!onFail) {
  474. onFail = validateProtocolFail;
  475. }
  476. for (const key in protocol) {
  477. const errMsg = validateProp$1(key, data[key], protocol[key], !hasOwn(data, key));
  478. if (isString(errMsg)) {
  479. onFail(name, errMsg);
  480. }
  481. }
  482. }
  483. function validateProtocols(name, args, protocol, onFail) {
  484. if (!protocol) {
  485. return;
  486. }
  487. if (!isArray(protocol)) {
  488. return validateProtocol(name, args[0] || /* @__PURE__ */ Object.create(null), protocol, onFail);
  489. }
  490. const len = protocol.length;
  491. const argsLen = args.length;
  492. for (let i2 = 0; i2 < len; i2++) {
  493. const opts = protocol[i2];
  494. const data = /* @__PURE__ */ Object.create(null);
  495. if (argsLen > i2) {
  496. data[opts.name] = args[i2];
  497. }
  498. validateProtocol(name, data, { [opts.name]: opts }, onFail);
  499. }
  500. }
  501. function validateProp$1(name, value, prop, isAbsent) {
  502. if (!isPlainObject(prop)) {
  503. prop = { type: prop };
  504. }
  505. const { type, required, validator } = prop;
  506. if (required && isAbsent) {
  507. return 'Missing required args: "' + name + '"';
  508. }
  509. if (value == null && !required) {
  510. return;
  511. }
  512. if (type != null) {
  513. let isValid2 = false;
  514. const types = isArray(type) ? type : [type];
  515. const expectedTypes = [];
  516. for (let i2 = 0; i2 < types.length && !isValid2; i2++) {
  517. const { valid, expectedType } = assertType$1(value, types[i2]);
  518. expectedTypes.push(expectedType || "");
  519. isValid2 = valid;
  520. }
  521. if (!isValid2) {
  522. return getInvalidTypeMessage$1(name, value, expectedTypes);
  523. }
  524. }
  525. if (validator) {
  526. return validator(value);
  527. }
  528. }
  529. const isSimpleType$1 = /* @__PURE__ */ makeMap("String,Number,Boolean,Function,Symbol");
  530. function assertType$1(value, type) {
  531. let valid;
  532. const expectedType = getType$1(type);
  533. if (isSimpleType$1(expectedType)) {
  534. const t2 = typeof value;
  535. valid = t2 === expectedType.toLowerCase();
  536. if (!valid && t2 === "object") {
  537. valid = value instanceof type;
  538. }
  539. } else if (expectedType === "Object") {
  540. valid = isObject$1(value);
  541. } else if (expectedType === "Array") {
  542. valid = isArray(value);
  543. } else {
  544. {
  545. valid = value instanceof type;
  546. }
  547. }
  548. return {
  549. valid,
  550. expectedType
  551. };
  552. }
  553. function getInvalidTypeMessage$1(name, value, expectedTypes) {
  554. let message = `Invalid args: type check failed for args "${name}". Expected ${expectedTypes.map(capitalize).join(", ")}`;
  555. const expectedType = expectedTypes[0];
  556. const receivedType = toRawType(value);
  557. const expectedValue = styleValue$1(value, expectedType);
  558. const receivedValue = styleValue$1(value, receivedType);
  559. if (expectedTypes.length === 1 && isExplicable$1(expectedType) && !isBoolean$1(expectedType, receivedType)) {
  560. message += ` with value ${expectedValue}`;
  561. }
  562. message += `, got ${receivedType} `;
  563. if (isExplicable$1(receivedType)) {
  564. message += `with value ${receivedValue}.`;
  565. }
  566. return message;
  567. }
  568. function getType$1(ctor) {
  569. const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
  570. return match ? match[1] : "";
  571. }
  572. function styleValue$1(value, type) {
  573. if (type === "String") {
  574. return `"${value}"`;
  575. } else if (type === "Number") {
  576. return `${Number(value)}`;
  577. } else {
  578. return `${value}`;
  579. }
  580. }
  581. function isExplicable$1(type) {
  582. const explicitTypes = ["string", "number", "boolean"];
  583. return explicitTypes.some((elem) => type.toLowerCase() === elem);
  584. }
  585. function isBoolean$1(...args) {
  586. return args.some((elem) => elem.toLowerCase() === "boolean");
  587. }
  588. function tryCatch(fn2) {
  589. return function() {
  590. try {
  591. return fn2.apply(fn2, arguments);
  592. } catch (e2) {
  593. console.error(e2);
  594. }
  595. };
  596. }
  597. let invokeCallbackId = 1;
  598. const invokeCallbacks = {};
  599. function addInvokeCallback(id, name, callback, keepAlive = false) {
  600. invokeCallbacks[id] = {
  601. name,
  602. keepAlive,
  603. callback
  604. };
  605. return id;
  606. }
  607. function invokeCallback(id, res, extras) {
  608. if (typeof id === "number") {
  609. const opts = invokeCallbacks[id];
  610. if (opts) {
  611. if (!opts.keepAlive) {
  612. delete invokeCallbacks[id];
  613. }
  614. return opts.callback(res, extras);
  615. }
  616. }
  617. return res;
  618. }
  619. const API_SUCCESS = "success";
  620. const API_FAIL = "fail";
  621. const API_COMPLETE = "complete";
  622. function getApiCallbacks(args) {
  623. const apiCallbacks = {};
  624. for (const name in args) {
  625. const fn2 = args[name];
  626. if (isFunction(fn2)) {
  627. apiCallbacks[name] = tryCatch(fn2);
  628. delete args[name];
  629. }
  630. }
  631. return apiCallbacks;
  632. }
  633. function normalizeErrMsg(errMsg, name) {
  634. if (!errMsg || errMsg.indexOf(":fail") === -1) {
  635. return name + ":ok";
  636. }
  637. return name + errMsg.substring(errMsg.indexOf(":fail"));
  638. }
  639. function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
  640. if (!isPlainObject(args)) {
  641. args = {};
  642. }
  643. const { success, fail, complete } = getApiCallbacks(args);
  644. const hasSuccess = isFunction(success);
  645. const hasFail = isFunction(fail);
  646. const hasComplete = isFunction(complete);
  647. const callbackId = invokeCallbackId++;
  648. addInvokeCallback(callbackId, name, (res) => {
  649. res = res || {};
  650. res.errMsg = normalizeErrMsg(res.errMsg, name);
  651. isFunction(beforeAll) && beforeAll(res);
  652. if (res.errMsg === name + ":ok") {
  653. isFunction(beforeSuccess) && beforeSuccess(res, args);
  654. hasSuccess && success(res);
  655. } else {
  656. hasFail && fail(res);
  657. }
  658. hasComplete && complete(res);
  659. });
  660. return callbackId;
  661. }
  662. const HOOK_SUCCESS = "success";
  663. const HOOK_FAIL = "fail";
  664. const HOOK_COMPLETE = "complete";
  665. const globalInterceptors = {};
  666. const scopedInterceptors = {};
  667. function wrapperHook(hook, params) {
  668. return function(data) {
  669. return hook(data, params) || data;
  670. };
  671. }
  672. function queue$1(hooks, data, params) {
  673. let promise = false;
  674. for (let i2 = 0; i2 < hooks.length; i2++) {
  675. const hook = hooks[i2];
  676. if (promise) {
  677. promise = Promise.resolve(wrapperHook(hook, params));
  678. } else {
  679. const res = hook(data, params);
  680. if (isPromise$2(res)) {
  681. promise = Promise.resolve(res);
  682. }
  683. if (res === false) {
  684. return {
  685. then() {
  686. },
  687. catch() {
  688. }
  689. };
  690. }
  691. }
  692. }
  693. return promise || {
  694. then(callback) {
  695. return callback(data);
  696. },
  697. catch() {
  698. }
  699. };
  700. }
  701. function wrapperOptions(interceptors2, options = {}) {
  702. [HOOK_SUCCESS, HOOK_FAIL, HOOK_COMPLETE].forEach((name) => {
  703. const hooks = interceptors2[name];
  704. if (!isArray(hooks)) {
  705. return;
  706. }
  707. const oldCallback = options[name];
  708. options[name] = function callbackInterceptor(res) {
  709. queue$1(hooks, res, options).then((res2) => {
  710. return isFunction(oldCallback) && oldCallback(res2) || res2;
  711. });
  712. };
  713. });
  714. return options;
  715. }
  716. function wrapperReturnValue(method, returnValue) {
  717. const returnValueHooks = [];
  718. if (isArray(globalInterceptors.returnValue)) {
  719. returnValueHooks.push(...globalInterceptors.returnValue);
  720. }
  721. const interceptor = scopedInterceptors[method];
  722. if (interceptor && isArray(interceptor.returnValue)) {
  723. returnValueHooks.push(...interceptor.returnValue);
  724. }
  725. returnValueHooks.forEach((hook) => {
  726. returnValue = hook(returnValue) || returnValue;
  727. });
  728. return returnValue;
  729. }
  730. function getApiInterceptorHooks(method) {
  731. const interceptor = /* @__PURE__ */ Object.create(null);
  732. Object.keys(globalInterceptors).forEach((hook) => {
  733. if (hook !== "returnValue") {
  734. interceptor[hook] = globalInterceptors[hook].slice();
  735. }
  736. });
  737. const scopedInterceptor = scopedInterceptors[method];
  738. if (scopedInterceptor) {
  739. Object.keys(scopedInterceptor).forEach((hook) => {
  740. if (hook !== "returnValue") {
  741. interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
  742. }
  743. });
  744. }
  745. return interceptor;
  746. }
  747. function invokeApi(method, api, options, params) {
  748. const interceptor = getApiInterceptorHooks(method);
  749. if (interceptor && Object.keys(interceptor).length) {
  750. if (isArray(interceptor.invoke)) {
  751. const res = queue$1(interceptor.invoke, options);
  752. return res.then((options2) => {
  753. return api(wrapperOptions(getApiInterceptorHooks(method), options2), ...params);
  754. });
  755. } else {
  756. return api(wrapperOptions(interceptor, options), ...params);
  757. }
  758. }
  759. return api(options, ...params);
  760. }
  761. function hasCallback(args) {
  762. if (isPlainObject(args) && [API_SUCCESS, API_FAIL, API_COMPLETE].find((cb) => isFunction(args[cb]))) {
  763. return true;
  764. }
  765. return false;
  766. }
  767. function handlePromise(promise) {
  768. return promise;
  769. }
  770. function promisify$1(name, fn2) {
  771. return (args = {}, ...rest) => {
  772. if (hasCallback(args)) {
  773. return wrapperReturnValue(name, invokeApi(name, fn2, extend({}, args), rest));
  774. }
  775. return wrapperReturnValue(name, handlePromise(new Promise((resolve2, reject) => {
  776. invokeApi(name, fn2, extend({}, args, { success: resolve2, fail: reject }), rest);
  777. })));
  778. };
  779. }
  780. function formatApiArgs(args, options) {
  781. args[0];
  782. {
  783. return;
  784. }
  785. }
  786. function invokeSuccess(id, name, res) {
  787. const result = {
  788. errMsg: name + ":ok"
  789. };
  790. return invokeCallback(id, extend(res || {}, result));
  791. }
  792. function invokeFail(id, name, errMsg, errRes = {}) {
  793. const errMsgPrefix = name + ":fail";
  794. let apiErrMsg = "";
  795. if (!errMsg) {
  796. apiErrMsg = errMsgPrefix;
  797. } else if (errMsg.indexOf(errMsgPrefix) === 0) {
  798. apiErrMsg = errMsg;
  799. } else {
  800. apiErrMsg = errMsgPrefix + " " + errMsg;
  801. }
  802. {
  803. delete errRes.errCode;
  804. }
  805. let res = extend({ errMsg: apiErrMsg }, errRes);
  806. return invokeCallback(id, res);
  807. }
  808. function beforeInvokeApi(name, args, protocol, options) {
  809. {
  810. validateProtocols(name, args, protocol);
  811. }
  812. const errMsg = formatApiArgs(args);
  813. if (errMsg) {
  814. return errMsg;
  815. }
  816. }
  817. function parseErrMsg(errMsg) {
  818. if (!errMsg || isString(errMsg)) {
  819. return errMsg;
  820. }
  821. if (errMsg.stack) {
  822. if (typeof globalThis === "undefined" || !globalThis.harmonyChannel) {
  823. console.error(errMsg.message + "\n" + errMsg.stack);
  824. }
  825. return errMsg.message;
  826. }
  827. return errMsg;
  828. }
  829. function wrapperTaskApi(name, fn2, protocol, options) {
  830. return (args) => {
  831. const id = createAsyncApiCallback(name, args, options);
  832. const errMsg = beforeInvokeApi(name, [args], protocol);
  833. if (errMsg) {
  834. return invokeFail(id, name, errMsg);
  835. }
  836. return fn2(args, {
  837. resolve: (res) => invokeSuccess(id, name, res),
  838. reject: (errMsg2, errRes) => invokeFail(id, name, parseErrMsg(errMsg2), errRes)
  839. });
  840. };
  841. }
  842. function wrapperSyncApi(name, fn2, protocol, options) {
  843. return (...args) => {
  844. const errMsg = beforeInvokeApi(name, args, protocol);
  845. if (errMsg) {
  846. throw new Error(errMsg);
  847. }
  848. return fn2.apply(null, args);
  849. };
  850. }
  851. function wrapperAsyncApi(name, fn2, protocol, options) {
  852. return wrapperTaskApi(name, fn2, protocol, options);
  853. }
  854. function defineSyncApi(name, fn2, protocol, options) {
  855. return wrapperSyncApi(name, fn2, protocol);
  856. }
  857. function defineAsyncApi(name, fn2, protocol, options) {
  858. return promisify$1(name, wrapperAsyncApi(name, fn2, protocol, options));
  859. }
  860. const API_UPX2PX = "upx2px";
  861. const Upx2pxProtocol = [
  862. {
  863. name: "upx",
  864. type: [Number, String],
  865. required: true
  866. }
  867. ];
  868. const EPS = 1e-4;
  869. const BASE_DEVICE_WIDTH = 750;
  870. let isIOS = false;
  871. let deviceWidth = 0;
  872. let deviceDPR = 0;
  873. function checkDeviceWidth() {
  874. var _a, _b;
  875. let windowWidth, pixelRatio, platform;
  876. {
  877. const windowInfo = ((_a = wx.getWindowInfo) === null || _a === void 0 ? void 0 : _a.call(wx)) || wx.getSystemInfoSync();
  878. const deviceInfo = ((_b = wx.getDeviceInfo) === null || _b === void 0 ? void 0 : _b.call(wx)) || wx.getSystemInfoSync();
  879. windowWidth = windowInfo.windowWidth;
  880. pixelRatio = windowInfo.pixelRatio;
  881. platform = deviceInfo.platform;
  882. }
  883. deviceWidth = windowWidth;
  884. deviceDPR = pixelRatio;
  885. isIOS = platform === "ios";
  886. }
  887. const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => {
  888. if (deviceWidth === 0) {
  889. checkDeviceWidth();
  890. }
  891. number = Number(number);
  892. if (number === 0) {
  893. return 0;
  894. }
  895. let width = newDeviceWidth || deviceWidth;
  896. let result = number / BASE_DEVICE_WIDTH * width;
  897. if (result < 0) {
  898. result = -result;
  899. }
  900. result = Math.floor(result + EPS);
  901. if (result === 0) {
  902. if (deviceDPR === 1 || !isIOS) {
  903. result = 1;
  904. } else {
  905. result = 0.5;
  906. }
  907. }
  908. return number < 0 ? -result : result;
  909. }, Upx2pxProtocol);
  910. function __f__(type, filename, ...args) {
  911. if (filename) {
  912. args.push(filename);
  913. }
  914. console[type].apply(console, args);
  915. }
  916. const API_ADD_INTERCEPTOR = "addInterceptor";
  917. const API_REMOVE_INTERCEPTOR = "removeInterceptor";
  918. const AddInterceptorProtocol = [
  919. {
  920. name: "method",
  921. type: [String, Object],
  922. required: true
  923. }
  924. ];
  925. const RemoveInterceptorProtocol = AddInterceptorProtocol;
  926. function mergeInterceptorHook(interceptors2, interceptor) {
  927. Object.keys(interceptor).forEach((hook) => {
  928. if (isFunction(interceptor[hook])) {
  929. interceptors2[hook] = mergeHook(interceptors2[hook], interceptor[hook]);
  930. }
  931. });
  932. }
  933. function removeInterceptorHook(interceptors2, interceptor) {
  934. if (!interceptors2 || !interceptor) {
  935. return;
  936. }
  937. Object.keys(interceptor).forEach((name) => {
  938. const hooks = interceptors2[name];
  939. const hook = interceptor[name];
  940. if (isArray(hooks) && isFunction(hook)) {
  941. remove(hooks, hook);
  942. }
  943. });
  944. }
  945. function mergeHook(parentVal, childVal) {
  946. const res = childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal;
  947. return res ? dedupeHooks(res) : res;
  948. }
  949. function dedupeHooks(hooks) {
  950. const res = [];
  951. for (let i2 = 0; i2 < hooks.length; i2++) {
  952. if (res.indexOf(hooks[i2]) === -1) {
  953. res.push(hooks[i2]);
  954. }
  955. }
  956. return res;
  957. }
  958. const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
  959. if (isString(method) && isPlainObject(interceptor)) {
  960. mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
  961. } else if (isPlainObject(method)) {
  962. mergeInterceptorHook(globalInterceptors, method);
  963. }
  964. }, AddInterceptorProtocol);
  965. const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
  966. if (isString(method)) {
  967. if (isPlainObject(interceptor)) {
  968. removeInterceptorHook(scopedInterceptors[method], interceptor);
  969. } else {
  970. delete scopedInterceptors[method];
  971. }
  972. } else if (isPlainObject(method)) {
  973. removeInterceptorHook(globalInterceptors, method);
  974. }
  975. }, RemoveInterceptorProtocol);
  976. const interceptors = {};
  977. const API_ON = "$on";
  978. const OnProtocol = [
  979. {
  980. name: "event",
  981. type: String,
  982. required: true
  983. },
  984. {
  985. name: "callback",
  986. type: Function,
  987. required: true
  988. }
  989. ];
  990. const API_ONCE = "$once";
  991. const OnceProtocol = OnProtocol;
  992. const API_OFF = "$off";
  993. const OffProtocol = [
  994. {
  995. name: "event",
  996. type: [String, Array]
  997. },
  998. {
  999. name: "callback",
  1000. type: [Function, Number]
  1001. }
  1002. ];
  1003. const API_EMIT = "$emit";
  1004. const EmitProtocol = [
  1005. {
  1006. name: "event",
  1007. type: String,
  1008. required: true
  1009. }
  1010. ];
  1011. class EventBus {
  1012. constructor() {
  1013. this.$emitter = new E$1$1();
  1014. }
  1015. on(name, callback) {
  1016. return this.$emitter.on(name, callback);
  1017. }
  1018. once(name, callback) {
  1019. return this.$emitter.once(name, callback);
  1020. }
  1021. off(name, callback) {
  1022. if (!name) {
  1023. this.$emitter.e = {};
  1024. return;
  1025. }
  1026. this.$emitter.off(name, callback);
  1027. }
  1028. emit(name, ...args) {
  1029. this.$emitter.emit(name, ...args);
  1030. }
  1031. }
  1032. const eventBus = new EventBus();
  1033. const $on = defineSyncApi(API_ON, (name, callback) => {
  1034. eventBus.on(name, callback);
  1035. return () => eventBus.off(name, callback);
  1036. }, OnProtocol);
  1037. const $once = defineSyncApi(API_ONCE, (name, callback) => {
  1038. eventBus.once(name, callback);
  1039. return () => eventBus.off(name, callback);
  1040. }, OnceProtocol);
  1041. const $off = defineSyncApi(API_OFF, (name, callback) => {
  1042. if (!isArray(name))
  1043. name = name ? [name] : [];
  1044. name.forEach((n2) => {
  1045. eventBus.off(n2, callback);
  1046. });
  1047. }, OffProtocol);
  1048. const $emit = defineSyncApi(API_EMIT, (name, ...args) => {
  1049. eventBus.emit(name, ...args);
  1050. }, EmitProtocol);
  1051. let cid;
  1052. let cidErrMsg;
  1053. let enabled;
  1054. function normalizePushMessage(message) {
  1055. try {
  1056. return JSON.parse(message);
  1057. } catch (e2) {
  1058. }
  1059. return message;
  1060. }
  1061. function invokePushCallback(args) {
  1062. if (args.type === "enabled") {
  1063. enabled = true;
  1064. } else if (args.type === "clientId") {
  1065. cid = args.cid;
  1066. cidErrMsg = args.errMsg;
  1067. invokeGetPushCidCallbacks(cid, args.errMsg);
  1068. } else if (args.type === "pushMsg") {
  1069. const message = {
  1070. type: "receive",
  1071. data: normalizePushMessage(args.message)
  1072. };
  1073. for (let i2 = 0; i2 < onPushMessageCallbacks.length; i2++) {
  1074. const callback = onPushMessageCallbacks[i2];
  1075. callback(message);
  1076. if (message.stopped) {
  1077. break;
  1078. }
  1079. }
  1080. } else if (args.type === "click") {
  1081. onPushMessageCallbacks.forEach((callback) => {
  1082. callback({
  1083. type: "click",
  1084. data: normalizePushMessage(args.message)
  1085. });
  1086. });
  1087. }
  1088. }
  1089. const getPushCidCallbacks = [];
  1090. function invokeGetPushCidCallbacks(cid2, errMsg) {
  1091. getPushCidCallbacks.forEach((callback) => {
  1092. callback(cid2, errMsg);
  1093. });
  1094. getPushCidCallbacks.length = 0;
  1095. }
  1096. const API_GET_PUSH_CLIENT_ID = "getPushClientId";
  1097. const getPushClientId = defineAsyncApi(API_GET_PUSH_CLIENT_ID, (_2, { resolve: resolve2, reject }) => {
  1098. Promise.resolve().then(() => {
  1099. if (typeof enabled === "undefined") {
  1100. enabled = false;
  1101. cid = "";
  1102. cidErrMsg = "uniPush is not enabled";
  1103. }
  1104. getPushCidCallbacks.push((cid2, errMsg) => {
  1105. if (cid2) {
  1106. resolve2({ cid: cid2 });
  1107. } else {
  1108. reject(errMsg);
  1109. }
  1110. });
  1111. if (typeof cid !== "undefined") {
  1112. invokeGetPushCidCallbacks(cid, cidErrMsg);
  1113. }
  1114. });
  1115. });
  1116. const onPushMessageCallbacks = [];
  1117. const onPushMessage = (fn2) => {
  1118. if (onPushMessageCallbacks.indexOf(fn2) === -1) {
  1119. onPushMessageCallbacks.push(fn2);
  1120. }
  1121. };
  1122. const offPushMessage = (fn2) => {
  1123. if (!fn2) {
  1124. onPushMessageCallbacks.length = 0;
  1125. } else {
  1126. const index2 = onPushMessageCallbacks.indexOf(fn2);
  1127. if (index2 > -1) {
  1128. onPushMessageCallbacks.splice(index2, 1);
  1129. }
  1130. }
  1131. };
  1132. const SYNC_API_RE = /^\$|__f__|getLocale|setLocale|sendNativeEvent|restoreGlobal|requireGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|rpx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getDeviceInfo|getAppBaseInfo|getWindowInfo|getSystemSetting|getAppAuthorizeSetting/;
  1133. const CONTEXT_API_RE = /^create|Manager$/;
  1134. const CONTEXT_API_RE_EXC = ["createBLEConnection"];
  1135. const TASK_APIS = ["request", "downloadFile", "uploadFile", "connectSocket"];
  1136. const ASYNC_API = ["createBLEConnection"];
  1137. const CALLBACK_API_RE = /^on|^off/;
  1138. function isContextApi(name) {
  1139. return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1;
  1140. }
  1141. function isSyncApi(name) {
  1142. return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1;
  1143. }
  1144. function isCallbackApi(name) {
  1145. return CALLBACK_API_RE.test(name) && name !== "onPush";
  1146. }
  1147. function isTaskApi(name) {
  1148. return TASK_APIS.indexOf(name) !== -1;
  1149. }
  1150. function shouldPromise(name) {
  1151. if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
  1152. return false;
  1153. }
  1154. return true;
  1155. }
  1156. if (!Promise.prototype.finally) {
  1157. Promise.prototype.finally = function(onfinally) {
  1158. const promise = this.constructor;
  1159. return this.then((value) => promise.resolve(onfinally && onfinally()).then(() => value), (reason) => promise.resolve(onfinally && onfinally()).then(() => {
  1160. throw reason;
  1161. }));
  1162. };
  1163. }
  1164. function promisify(name, api) {
  1165. if (!shouldPromise(name)) {
  1166. return api;
  1167. }
  1168. if (!isFunction(api)) {
  1169. return api;
  1170. }
  1171. return function promiseApi(options = {}, ...rest) {
  1172. if (isFunction(options.success) || isFunction(options.fail) || isFunction(options.complete)) {
  1173. return wrapperReturnValue(name, invokeApi(name, api, extend({}, options), rest));
  1174. }
  1175. return wrapperReturnValue(name, handlePromise(new Promise((resolve2, reject) => {
  1176. invokeApi(name, api, extend({}, options, {
  1177. success: resolve2,
  1178. fail: reject
  1179. }), rest);
  1180. })));
  1181. };
  1182. }
  1183. const CALLBACKS = ["success", "fail", "cancel", "complete"];
  1184. function initWrapper(protocols2) {
  1185. function processCallback(methodName, method, returnValue) {
  1186. return function(res) {
  1187. return method(processReturnValue(methodName, res, returnValue));
  1188. };
  1189. }
  1190. function processArgs(methodName, fromArgs, argsOption = {}, returnValue = {}, keepFromArgs = false) {
  1191. if (isPlainObject(fromArgs)) {
  1192. const toArgs = keepFromArgs === true ? fromArgs : {};
  1193. if (isFunction(argsOption)) {
  1194. argsOption = argsOption(fromArgs, toArgs) || {};
  1195. }
  1196. for (const key in fromArgs) {
  1197. if (hasOwn(argsOption, key)) {
  1198. let keyOption = argsOption[key];
  1199. if (isFunction(keyOption)) {
  1200. keyOption = keyOption(fromArgs[key], fromArgs, toArgs);
  1201. }
  1202. if (!keyOption) {
  1203. console.warn(`微信小程序 ${methodName} 暂不支持 ${key}`);
  1204. } else if (isString(keyOption)) {
  1205. toArgs[keyOption] = fromArgs[key];
  1206. } else if (isPlainObject(keyOption)) {
  1207. toArgs[keyOption.name ? keyOption.name : key] = keyOption.value;
  1208. }
  1209. } else if (CALLBACKS.indexOf(key) !== -1) {
  1210. const callback = fromArgs[key];
  1211. if (isFunction(callback)) {
  1212. toArgs[key] = processCallback(methodName, callback, returnValue);
  1213. }
  1214. } else {
  1215. if (!keepFromArgs && !hasOwn(toArgs, key)) {
  1216. toArgs[key] = fromArgs[key];
  1217. }
  1218. }
  1219. }
  1220. return toArgs;
  1221. } else if (isFunction(fromArgs)) {
  1222. if (isFunction(argsOption)) {
  1223. argsOption(fromArgs, {});
  1224. }
  1225. fromArgs = processCallback(methodName, fromArgs, returnValue);
  1226. }
  1227. return fromArgs;
  1228. }
  1229. function processReturnValue(methodName, res, returnValue, keepReturnValue = false) {
  1230. if (isFunction(protocols2.returnValue)) {
  1231. res = protocols2.returnValue(methodName, res);
  1232. }
  1233. const realKeepReturnValue = keepReturnValue || false;
  1234. return processArgs(methodName, res, returnValue, {}, realKeepReturnValue);
  1235. }
  1236. return function wrapper(methodName, method) {
  1237. const hasProtocol = hasOwn(protocols2, methodName);
  1238. if (!hasProtocol && typeof wx[methodName] !== "function") {
  1239. return method;
  1240. }
  1241. const needWrapper = hasProtocol || isFunction(protocols2.returnValue) || isContextApi(methodName) || isTaskApi(methodName);
  1242. const hasMethod = hasProtocol || isFunction(method);
  1243. if (!hasProtocol && !method) {
  1244. return function() {
  1245. console.error(`微信小程序 暂不支持${methodName}`);
  1246. };
  1247. }
  1248. if (!needWrapper || !hasMethod) {
  1249. return method;
  1250. }
  1251. const protocol = protocols2[methodName];
  1252. return function(arg1, arg2) {
  1253. let options = protocol || {};
  1254. if (isFunction(protocol)) {
  1255. options = protocol(arg1);
  1256. }
  1257. arg1 = processArgs(methodName, arg1, options.args, options.returnValue);
  1258. const args = [arg1];
  1259. if (typeof arg2 !== "undefined") {
  1260. args.push(arg2);
  1261. }
  1262. const returnValue = wx[options.name || methodName].apply(wx, args);
  1263. if (isContextApi(methodName) || isTaskApi(methodName)) {
  1264. if (returnValue && !returnValue.__v_skip) {
  1265. returnValue.__v_skip = true;
  1266. }
  1267. }
  1268. if (isSyncApi(methodName)) {
  1269. return processReturnValue(methodName, returnValue, options.returnValue, isContextApi(methodName));
  1270. }
  1271. return returnValue;
  1272. };
  1273. };
  1274. }
  1275. const getLocale = () => {
  1276. const app = isFunction(getApp) && getApp({ allowDefault: true });
  1277. if (app && app.$vm) {
  1278. return app.$vm.$locale;
  1279. }
  1280. return getLocaleLanguage$1();
  1281. };
  1282. const setLocale = (locale) => {
  1283. const app = isFunction(getApp) && getApp();
  1284. if (!app) {
  1285. return false;
  1286. }
  1287. const oldLocale = app.$vm.$locale;
  1288. if (oldLocale !== locale) {
  1289. app.$vm.$locale = locale;
  1290. onLocaleChangeCallbacks.forEach((fn2) => fn2({ locale }));
  1291. return true;
  1292. }
  1293. return false;
  1294. };
  1295. const onLocaleChangeCallbacks = [];
  1296. const onLocaleChange = (fn2) => {
  1297. if (onLocaleChangeCallbacks.indexOf(fn2) === -1) {
  1298. onLocaleChangeCallbacks.push(fn2);
  1299. }
  1300. };
  1301. if (typeof global !== "undefined") {
  1302. global.getLocale = getLocale;
  1303. }
  1304. const UUID_KEY = "__DC_STAT_UUID";
  1305. let deviceId;
  1306. function useDeviceId(global2 = wx) {
  1307. return function addDeviceId(_2, toRes) {
  1308. deviceId = deviceId || global2.getStorageSync(UUID_KEY);
  1309. if (!deviceId) {
  1310. deviceId = Date.now() + "" + Math.floor(Math.random() * 1e7);
  1311. wx.setStorage({
  1312. key: UUID_KEY,
  1313. data: deviceId
  1314. });
  1315. }
  1316. toRes.deviceId = deviceId;
  1317. };
  1318. }
  1319. function addSafeAreaInsets(fromRes, toRes) {
  1320. if (fromRes.safeArea) {
  1321. const safeArea = fromRes.safeArea;
  1322. toRes.safeAreaInsets = {
  1323. top: safeArea.top,
  1324. left: safeArea.left,
  1325. right: fromRes.windowWidth - safeArea.right,
  1326. bottom: fromRes.screenHeight - safeArea.bottom
  1327. };
  1328. }
  1329. }
  1330. function getOSInfo(system, platform) {
  1331. let osName = "";
  1332. let osVersion = "";
  1333. if (platform && false) {
  1334. osName = platform;
  1335. osVersion = system;
  1336. } else {
  1337. osName = system.split(" ")[0] || platform;
  1338. osVersion = system.split(" ")[1] || "";
  1339. }
  1340. osName = osName.toLowerCase();
  1341. switch (osName) {
  1342. case "harmony":
  1343. case "ohos":
  1344. case "openharmony":
  1345. osName = "harmonyos";
  1346. break;
  1347. case "iphone os":
  1348. osName = "ios";
  1349. break;
  1350. case "mac":
  1351. case "darwin":
  1352. osName = "macos";
  1353. break;
  1354. case "windows_nt":
  1355. osName = "windows";
  1356. break;
  1357. }
  1358. return {
  1359. osName,
  1360. osVersion
  1361. };
  1362. }
  1363. function populateParameters(fromRes, toRes) {
  1364. const { brand = "", model = "", system = "", language = "", theme, version: version2, platform, fontSizeSetting, SDKVersion, pixelRatio, deviceOrientation } = fromRes;
  1365. const { osName, osVersion } = getOSInfo(system, platform);
  1366. let hostVersion = version2;
  1367. let deviceType = getGetDeviceType(fromRes, model);
  1368. let deviceBrand = getDeviceBrand(brand);
  1369. let _hostName = getHostName(fromRes);
  1370. let _deviceOrientation = deviceOrientation;
  1371. let _devicePixelRatio = pixelRatio;
  1372. let _SDKVersion = SDKVersion;
  1373. const hostLanguage = (language || "").replace(/_/g, "-");
  1374. const parameters = {
  1375. appId: "__UNI__90F7D71",
  1376. appName: "签约",
  1377. appVersion: "1.0.0",
  1378. appVersionCode: 100,
  1379. appLanguage: getAppLanguage(hostLanguage),
  1380. uniCompileVersion: "4.75",
  1381. uniCompilerVersion: "4.75",
  1382. uniRuntimeVersion: "4.75",
  1383. uniPlatform: "mp-weixin",
  1384. deviceBrand,
  1385. deviceModel: model,
  1386. deviceType,
  1387. devicePixelRatio: _devicePixelRatio,
  1388. deviceOrientation: _deviceOrientation,
  1389. osName,
  1390. osVersion,
  1391. hostTheme: theme,
  1392. hostVersion,
  1393. hostLanguage,
  1394. hostName: _hostName,
  1395. hostSDKVersion: _SDKVersion,
  1396. hostFontSizeSetting: fontSizeSetting,
  1397. windowTop: 0,
  1398. windowBottom: 0,
  1399. // TODO
  1400. osLanguage: void 0,
  1401. osTheme: void 0,
  1402. ua: void 0,
  1403. hostPackageName: void 0,
  1404. browserName: void 0,
  1405. browserVersion: void 0,
  1406. isUniAppX: false
  1407. };
  1408. extend(toRes, parameters);
  1409. }
  1410. function getGetDeviceType(fromRes, model) {
  1411. let deviceType = fromRes.deviceType || "phone";
  1412. {
  1413. const deviceTypeMaps = {
  1414. ipad: "pad",
  1415. windows: "pc",
  1416. mac: "pc"
  1417. };
  1418. const deviceTypeMapsKeys = Object.keys(deviceTypeMaps);
  1419. const _model = model.toLowerCase();
  1420. for (let index2 = 0; index2 < deviceTypeMapsKeys.length; index2++) {
  1421. const _m = deviceTypeMapsKeys[index2];
  1422. if (_model.indexOf(_m) !== -1) {
  1423. deviceType = deviceTypeMaps[_m];
  1424. break;
  1425. }
  1426. }
  1427. }
  1428. return deviceType;
  1429. }
  1430. function getDeviceBrand(brand) {
  1431. let deviceBrand = brand;
  1432. if (deviceBrand) {
  1433. deviceBrand = deviceBrand.toLowerCase();
  1434. }
  1435. return deviceBrand;
  1436. }
  1437. function getAppLanguage(defaultLanguage) {
  1438. return getLocale ? getLocale() : defaultLanguage;
  1439. }
  1440. function getHostName(fromRes) {
  1441. const _platform = "WeChat";
  1442. let _hostName = fromRes.hostName || _platform;
  1443. {
  1444. if (fromRes.environment) {
  1445. _hostName = fromRes.environment;
  1446. } else if (fromRes.host && fromRes.host.env) {
  1447. _hostName = fromRes.host.env;
  1448. }
  1449. }
  1450. return _hostName;
  1451. }
  1452. const getSystemInfo = {
  1453. returnValue: (fromRes, toRes) => {
  1454. addSafeAreaInsets(fromRes, toRes);
  1455. useDeviceId()(fromRes, toRes);
  1456. populateParameters(fromRes, toRes);
  1457. }
  1458. };
  1459. const getSystemInfoSync = getSystemInfo;
  1460. const redirectTo = {};
  1461. const previewImage = {
  1462. args(fromArgs, toArgs) {
  1463. let currentIndex = parseInt(fromArgs.current);
  1464. if (isNaN(currentIndex)) {
  1465. return;
  1466. }
  1467. const urls = fromArgs.urls;
  1468. if (!isArray(urls)) {
  1469. return;
  1470. }
  1471. const len = urls.length;
  1472. if (!len) {
  1473. return;
  1474. }
  1475. if (currentIndex < 0) {
  1476. currentIndex = 0;
  1477. } else if (currentIndex >= len) {
  1478. currentIndex = len - 1;
  1479. }
  1480. if (currentIndex > 0) {
  1481. toArgs.current = urls[currentIndex];
  1482. toArgs.urls = urls.filter((item, index2) => index2 < currentIndex ? item !== urls[currentIndex] : true);
  1483. } else {
  1484. toArgs.current = urls[0];
  1485. }
  1486. return {
  1487. indicator: false,
  1488. loop: false
  1489. };
  1490. }
  1491. };
  1492. const showActionSheet = {
  1493. args(fromArgs, toArgs) {
  1494. toArgs.alertText = fromArgs.title;
  1495. }
  1496. };
  1497. const getDeviceInfo = {
  1498. returnValue: (fromRes, toRes) => {
  1499. const { brand, model, system = "", platform = "" } = fromRes;
  1500. let deviceType = getGetDeviceType(fromRes, model);
  1501. let deviceBrand = getDeviceBrand(brand);
  1502. useDeviceId()(fromRes, toRes);
  1503. const { osName, osVersion } = getOSInfo(system, platform);
  1504. toRes = sortObject(extend(toRes, {
  1505. deviceType,
  1506. deviceBrand,
  1507. deviceModel: model,
  1508. osName,
  1509. osVersion
  1510. }));
  1511. }
  1512. };
  1513. const getAppBaseInfo = {
  1514. returnValue: (fromRes, toRes) => {
  1515. const { version: version2, language, SDKVersion, theme } = fromRes;
  1516. let _hostName = getHostName(fromRes);
  1517. let hostLanguage = (language || "").replace(/_/g, "-");
  1518. const parameters = {
  1519. hostVersion: version2,
  1520. hostLanguage,
  1521. hostName: _hostName,
  1522. hostSDKVersion: SDKVersion,
  1523. hostTheme: theme,
  1524. appId: "__UNI__90F7D71",
  1525. appName: "签约",
  1526. appVersion: "1.0.0",
  1527. appVersionCode: 100,
  1528. appLanguage: getAppLanguage(hostLanguage),
  1529. isUniAppX: false,
  1530. uniPlatform: "mp-weixin",
  1531. uniCompileVersion: "4.75",
  1532. uniCompilerVersion: "4.75",
  1533. uniRuntimeVersion: "4.75"
  1534. };
  1535. extend(toRes, parameters);
  1536. }
  1537. };
  1538. const getWindowInfo = {
  1539. returnValue: (fromRes, toRes) => {
  1540. addSafeAreaInsets(fromRes, toRes);
  1541. toRes = sortObject(extend(toRes, {
  1542. windowTop: 0,
  1543. windowBottom: 0
  1544. }));
  1545. }
  1546. };
  1547. const getAppAuthorizeSetting = {
  1548. returnValue: function(fromRes, toRes) {
  1549. const { locationReducedAccuracy } = fromRes;
  1550. toRes.locationAccuracy = "unsupported";
  1551. if (locationReducedAccuracy === true) {
  1552. toRes.locationAccuracy = "reduced";
  1553. } else if (locationReducedAccuracy === false) {
  1554. toRes.locationAccuracy = "full";
  1555. }
  1556. }
  1557. };
  1558. const onError = {
  1559. args(fromArgs) {
  1560. const app = getApp({ allowDefault: true }) || {};
  1561. if (!app.$vm) {
  1562. if (!wx.$onErrorHandlers) {
  1563. wx.$onErrorHandlers = [];
  1564. }
  1565. wx.$onErrorHandlers.push(fromArgs);
  1566. } else {
  1567. injectHook(ON_ERROR, fromArgs, app.$vm.$);
  1568. }
  1569. }
  1570. };
  1571. const offError = {
  1572. args(fromArgs) {
  1573. const app = getApp({ allowDefault: true }) || {};
  1574. if (!app.$vm) {
  1575. if (!wx.$onErrorHandlers) {
  1576. return;
  1577. }
  1578. const index2 = wx.$onErrorHandlers.findIndex((fn2) => fn2 === fromArgs);
  1579. if (index2 !== -1) {
  1580. wx.$onErrorHandlers.splice(index2, 1);
  1581. }
  1582. } else if (fromArgs.__weh) {
  1583. const onErrors = app.$vm.$[ON_ERROR];
  1584. if (onErrors) {
  1585. const index2 = onErrors.indexOf(fromArgs.__weh);
  1586. if (index2 > -1) {
  1587. onErrors.splice(index2, 1);
  1588. }
  1589. }
  1590. }
  1591. }
  1592. };
  1593. const onSocketOpen = {
  1594. args() {
  1595. if (wx.__uni_console__) {
  1596. if (wx.__uni_console_warned__) {
  1597. return;
  1598. }
  1599. wx.__uni_console_warned__ = true;
  1600. console.warn(`开发模式下小程序日志回显会使用 socket 连接,为了避免冲突,建议使用 SocketTask 的方式去管理 WebSocket 或手动关闭日志回显功能。[详情](https://uniapp.dcloud.net.cn/tutorial/run/mp-log.html)`);
  1601. }
  1602. }
  1603. };
  1604. const onSocketMessage = onSocketOpen;
  1605. const baseApis = {
  1606. $on,
  1607. $off,
  1608. $once,
  1609. $emit,
  1610. upx2px,
  1611. rpx2px: upx2px,
  1612. interceptors,
  1613. addInterceptor,
  1614. removeInterceptor,
  1615. onCreateVueApp,
  1616. invokeCreateVueAppHook,
  1617. getLocale,
  1618. setLocale,
  1619. onLocaleChange,
  1620. getPushClientId,
  1621. onPushMessage,
  1622. offPushMessage,
  1623. invokePushCallback,
  1624. __f__
  1625. };
  1626. function initUni(api, protocols2, platform = wx) {
  1627. const wrapper = initWrapper(protocols2);
  1628. const UniProxyHandlers = {
  1629. get(target, key) {
  1630. if (hasOwn(target, key)) {
  1631. return target[key];
  1632. }
  1633. if (hasOwn(api, key)) {
  1634. return promisify(key, api[key]);
  1635. }
  1636. if (hasOwn(baseApis, key)) {
  1637. return promisify(key, baseApis[key]);
  1638. }
  1639. return promisify(key, wrapper(key, platform[key]));
  1640. }
  1641. };
  1642. return new Proxy({}, UniProxyHandlers);
  1643. }
  1644. function initGetProvider(providers) {
  1645. return function getProvider2({ service, success, fail, complete }) {
  1646. let res;
  1647. if (providers[service]) {
  1648. res = {
  1649. errMsg: "getProvider:ok",
  1650. service,
  1651. provider: providers[service]
  1652. };
  1653. isFunction(success) && success(res);
  1654. } else {
  1655. res = {
  1656. errMsg: "getProvider:fail:服务[" + service + "]不存在"
  1657. };
  1658. isFunction(fail) && fail(res);
  1659. }
  1660. isFunction(complete) && complete(res);
  1661. };
  1662. }
  1663. const objectKeys = [
  1664. "qy",
  1665. "env",
  1666. "error",
  1667. "version",
  1668. "lanDebug",
  1669. "cloud",
  1670. "serviceMarket",
  1671. "router",
  1672. "worklet",
  1673. "__webpack_require_UNI_MP_PLUGIN__"
  1674. ];
  1675. const singlePageDisableKey = ["lanDebug", "router", "worklet"];
  1676. const launchOption = wx.getLaunchOptionsSync ? wx.getLaunchOptionsSync() : null;
  1677. function isWxKey(key) {
  1678. if (launchOption && launchOption.scene === 1154 && singlePageDisableKey.includes(key)) {
  1679. return false;
  1680. }
  1681. return objectKeys.indexOf(key) > -1 || typeof wx[key] === "function";
  1682. }
  1683. function initWx() {
  1684. const newWx = {};
  1685. for (const key in wx) {
  1686. if (isWxKey(key)) {
  1687. newWx[key] = wx[key];
  1688. }
  1689. }
  1690. if (typeof globalThis !== "undefined" && typeof requireMiniProgram === "undefined") {
  1691. globalThis.wx = newWx;
  1692. }
  1693. return newWx;
  1694. }
  1695. const mocks$1 = ["__route__", "__wxExparserNodeId__", "__wxWebviewId__"];
  1696. const getProvider = initGetProvider({
  1697. oauth: ["weixin"],
  1698. share: ["weixin"],
  1699. payment: ["wxpay"],
  1700. push: ["weixin"]
  1701. });
  1702. function initComponentMocks(component) {
  1703. const res = /* @__PURE__ */ Object.create(null);
  1704. mocks$1.forEach((name) => {
  1705. res[name] = component[name];
  1706. });
  1707. return res;
  1708. }
  1709. function createSelectorQuery() {
  1710. const query = wx$2.createSelectorQuery();
  1711. const oldIn = query.in;
  1712. query.in = function newIn(component) {
  1713. if (component.$scope) {
  1714. return oldIn.call(this, component.$scope);
  1715. }
  1716. return oldIn.call(this, initComponentMocks(component));
  1717. };
  1718. return query;
  1719. }
  1720. const wx$2 = initWx();
  1721. if (!wx$2.canIUse("getAppBaseInfo")) {
  1722. wx$2.getAppBaseInfo = wx$2.getSystemInfoSync;
  1723. }
  1724. if (!wx$2.canIUse("getWindowInfo")) {
  1725. wx$2.getWindowInfo = wx$2.getSystemInfoSync;
  1726. }
  1727. if (!wx$2.canIUse("getDeviceInfo")) {
  1728. wx$2.getDeviceInfo = wx$2.getSystemInfoSync;
  1729. }
  1730. let baseInfo = wx$2.getAppBaseInfo && wx$2.getAppBaseInfo();
  1731. if (!baseInfo) {
  1732. baseInfo = wx$2.getSystemInfoSync();
  1733. }
  1734. const host = baseInfo ? baseInfo.host : null;
  1735. const shareVideoMessage = host && host.env === "SAAASDK" ? wx$2.miniapp.shareVideoMessage : wx$2.shareVideoMessage;
  1736. var shims = /* @__PURE__ */ Object.freeze({
  1737. __proto__: null,
  1738. createSelectorQuery,
  1739. getProvider,
  1740. shareVideoMessage
  1741. });
  1742. const compressImage = {
  1743. args(fromArgs, toArgs) {
  1744. if (fromArgs.compressedHeight && !toArgs.compressHeight) {
  1745. toArgs.compressHeight = fromArgs.compressedHeight;
  1746. }
  1747. if (fromArgs.compressedWidth && !toArgs.compressWidth) {
  1748. toArgs.compressWidth = fromArgs.compressedWidth;
  1749. }
  1750. }
  1751. };
  1752. var protocols = /* @__PURE__ */ Object.freeze({
  1753. __proto__: null,
  1754. compressImage,
  1755. getAppAuthorizeSetting,
  1756. getAppBaseInfo,
  1757. getDeviceInfo,
  1758. getSystemInfo,
  1759. getSystemInfoSync,
  1760. getWindowInfo,
  1761. offError,
  1762. onError,
  1763. onSocketMessage,
  1764. onSocketOpen,
  1765. previewImage,
  1766. redirectTo,
  1767. showActionSheet
  1768. });
  1769. const wx$1 = initWx();
  1770. var index = initUni(shims, protocols, wx$1);
  1771. /**
  1772. * @dcloudio/uni-mp-vue v3.4.21
  1773. * (c) 2018-present Yuxi (Evan) You and Vue contributors
  1774. * @license MIT
  1775. **/
  1776. function warn$2(msg, ...args) {
  1777. console.warn(`[Vue warn] ${msg}`, ...args);
  1778. }
  1779. let activeEffectScope;
  1780. class EffectScope {
  1781. constructor(detached = false) {
  1782. this.detached = detached;
  1783. this._active = true;
  1784. this.effects = [];
  1785. this.cleanups = [];
  1786. this.parent = activeEffectScope;
  1787. if (!detached && activeEffectScope) {
  1788. this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(
  1789. this
  1790. ) - 1;
  1791. }
  1792. }
  1793. get active() {
  1794. return this._active;
  1795. }
  1796. run(fn2) {
  1797. if (this._active) {
  1798. const currentEffectScope = activeEffectScope;
  1799. try {
  1800. activeEffectScope = this;
  1801. return fn2();
  1802. } finally {
  1803. activeEffectScope = currentEffectScope;
  1804. }
  1805. } else {
  1806. warn$2(`cannot run an inactive effect scope.`);
  1807. }
  1808. }
  1809. /**
  1810. * This should only be called on non-detached scopes
  1811. * @internal
  1812. */
  1813. on() {
  1814. activeEffectScope = this;
  1815. }
  1816. /**
  1817. * This should only be called on non-detached scopes
  1818. * @internal
  1819. */
  1820. off() {
  1821. activeEffectScope = this.parent;
  1822. }
  1823. stop(fromParent) {
  1824. if (this._active) {
  1825. let i2, l2;
  1826. for (i2 = 0, l2 = this.effects.length; i2 < l2; i2++) {
  1827. this.effects[i2].stop();
  1828. }
  1829. for (i2 = 0, l2 = this.cleanups.length; i2 < l2; i2++) {
  1830. this.cleanups[i2]();
  1831. }
  1832. if (this.scopes) {
  1833. for (i2 = 0, l2 = this.scopes.length; i2 < l2; i2++) {
  1834. this.scopes[i2].stop(true);
  1835. }
  1836. }
  1837. if (!this.detached && this.parent && !fromParent) {
  1838. const last = this.parent.scopes.pop();
  1839. if (last && last !== this) {
  1840. this.parent.scopes[this.index] = last;
  1841. last.index = this.index;
  1842. }
  1843. }
  1844. this.parent = void 0;
  1845. this._active = false;
  1846. }
  1847. }
  1848. }
  1849. function effectScope(detached) {
  1850. return new EffectScope(detached);
  1851. }
  1852. function recordEffectScope(effect2, scope = activeEffectScope) {
  1853. if (scope && scope.active) {
  1854. scope.effects.push(effect2);
  1855. }
  1856. }
  1857. function getCurrentScope() {
  1858. return activeEffectScope;
  1859. }
  1860. let activeEffect;
  1861. class ReactiveEffect {
  1862. constructor(fn2, trigger2, scheduler, scope) {
  1863. this.fn = fn2;
  1864. this.trigger = trigger2;
  1865. this.scheduler = scheduler;
  1866. this.active = true;
  1867. this.deps = [];
  1868. this._dirtyLevel = 4;
  1869. this._trackId = 0;
  1870. this._runnings = 0;
  1871. this._shouldSchedule = false;
  1872. this._depsLength = 0;
  1873. recordEffectScope(this, scope);
  1874. }
  1875. get dirty() {
  1876. if (this._dirtyLevel === 2 || this._dirtyLevel === 3) {
  1877. this._dirtyLevel = 1;
  1878. pauseTracking();
  1879. for (let i2 = 0; i2 < this._depsLength; i2++) {
  1880. const dep = this.deps[i2];
  1881. if (dep.computed) {
  1882. triggerComputed(dep.computed);
  1883. if (this._dirtyLevel >= 4) {
  1884. break;
  1885. }
  1886. }
  1887. }
  1888. if (this._dirtyLevel === 1) {
  1889. this._dirtyLevel = 0;
  1890. }
  1891. resetTracking();
  1892. }
  1893. return this._dirtyLevel >= 4;
  1894. }
  1895. set dirty(v2) {
  1896. this._dirtyLevel = v2 ? 4 : 0;
  1897. }
  1898. run() {
  1899. this._dirtyLevel = 0;
  1900. if (!this.active) {
  1901. return this.fn();
  1902. }
  1903. let lastShouldTrack = shouldTrack;
  1904. let lastEffect = activeEffect;
  1905. try {
  1906. shouldTrack = true;
  1907. activeEffect = this;
  1908. this._runnings++;
  1909. preCleanupEffect(this);
  1910. return this.fn();
  1911. } finally {
  1912. postCleanupEffect(this);
  1913. this._runnings--;
  1914. activeEffect = lastEffect;
  1915. shouldTrack = lastShouldTrack;
  1916. }
  1917. }
  1918. stop() {
  1919. var _a;
  1920. if (this.active) {
  1921. preCleanupEffect(this);
  1922. postCleanupEffect(this);
  1923. (_a = this.onStop) == null ? void 0 : _a.call(this);
  1924. this.active = false;
  1925. }
  1926. }
  1927. }
  1928. function triggerComputed(computed2) {
  1929. return computed2.value;
  1930. }
  1931. function preCleanupEffect(effect2) {
  1932. effect2._trackId++;
  1933. effect2._depsLength = 0;
  1934. }
  1935. function postCleanupEffect(effect2) {
  1936. if (effect2.deps.length > effect2._depsLength) {
  1937. for (let i2 = effect2._depsLength; i2 < effect2.deps.length; i2++) {
  1938. cleanupDepEffect(effect2.deps[i2], effect2);
  1939. }
  1940. effect2.deps.length = effect2._depsLength;
  1941. }
  1942. }
  1943. function cleanupDepEffect(dep, effect2) {
  1944. const trackId = dep.get(effect2);
  1945. if (trackId !== void 0 && effect2._trackId !== trackId) {
  1946. dep.delete(effect2);
  1947. if (dep.size === 0) {
  1948. dep.cleanup();
  1949. }
  1950. }
  1951. }
  1952. let shouldTrack = true;
  1953. let pauseScheduleStack = 0;
  1954. const trackStack = [];
  1955. function pauseTracking() {
  1956. trackStack.push(shouldTrack);
  1957. shouldTrack = false;
  1958. }
  1959. function resetTracking() {
  1960. const last = trackStack.pop();
  1961. shouldTrack = last === void 0 ? true : last;
  1962. }
  1963. function pauseScheduling() {
  1964. pauseScheduleStack++;
  1965. }
  1966. function resetScheduling() {
  1967. pauseScheduleStack--;
  1968. while (!pauseScheduleStack && queueEffectSchedulers.length) {
  1969. queueEffectSchedulers.shift()();
  1970. }
  1971. }
  1972. function trackEffect(effect2, dep, debuggerEventExtraInfo) {
  1973. var _a;
  1974. if (dep.get(effect2) !== effect2._trackId) {
  1975. dep.set(effect2, effect2._trackId);
  1976. const oldDep = effect2.deps[effect2._depsLength];
  1977. if (oldDep !== dep) {
  1978. if (oldDep) {
  1979. cleanupDepEffect(oldDep, effect2);
  1980. }
  1981. effect2.deps[effect2._depsLength++] = dep;
  1982. } else {
  1983. effect2._depsLength++;
  1984. }
  1985. {
  1986. (_a = effect2.onTrack) == null ? void 0 : _a.call(effect2, extend({ effect: effect2 }, debuggerEventExtraInfo));
  1987. }
  1988. }
  1989. }
  1990. const queueEffectSchedulers = [];
  1991. function triggerEffects(dep, dirtyLevel, debuggerEventExtraInfo) {
  1992. var _a;
  1993. pauseScheduling();
  1994. for (const effect2 of dep.keys()) {
  1995. let tracking;
  1996. if (effect2._dirtyLevel < dirtyLevel && (tracking != null ? tracking : tracking = dep.get(effect2) === effect2._trackId)) {
  1997. effect2._shouldSchedule || (effect2._shouldSchedule = effect2._dirtyLevel === 0);
  1998. effect2._dirtyLevel = dirtyLevel;
  1999. }
  2000. if (effect2._shouldSchedule && (tracking != null ? tracking : tracking = dep.get(effect2) === effect2._trackId)) {
  2001. {
  2002. (_a = effect2.onTrigger) == null ? void 0 : _a.call(effect2, extend({ effect: effect2 }, debuggerEventExtraInfo));
  2003. }
  2004. effect2.trigger();
  2005. if ((!effect2._runnings || effect2.allowRecurse) && effect2._dirtyLevel !== 2) {
  2006. effect2._shouldSchedule = false;
  2007. if (effect2.scheduler) {
  2008. queueEffectSchedulers.push(effect2.scheduler);
  2009. }
  2010. }
  2011. }
  2012. }
  2013. resetScheduling();
  2014. }
  2015. const createDep = (cleanup, computed2) => {
  2016. const dep = /* @__PURE__ */ new Map();
  2017. dep.cleanup = cleanup;
  2018. dep.computed = computed2;
  2019. return dep;
  2020. };
  2021. const targetMap = /* @__PURE__ */ new WeakMap();
  2022. const ITERATE_KEY = Symbol("iterate");
  2023. const MAP_KEY_ITERATE_KEY = Symbol("Map key iterate");
  2024. function track(target, type, key) {
  2025. if (shouldTrack && activeEffect) {
  2026. let depsMap = targetMap.get(target);
  2027. if (!depsMap) {
  2028. targetMap.set(target, depsMap = /* @__PURE__ */ new Map());
  2029. }
  2030. let dep = depsMap.get(key);
  2031. if (!dep) {
  2032. depsMap.set(key, dep = createDep(() => depsMap.delete(key)));
  2033. }
  2034. trackEffect(
  2035. activeEffect,
  2036. dep,
  2037. {
  2038. target,
  2039. type,
  2040. key
  2041. }
  2042. );
  2043. }
  2044. }
  2045. function trigger(target, type, key, newValue, oldValue, oldTarget) {
  2046. const depsMap = targetMap.get(target);
  2047. if (!depsMap) {
  2048. return;
  2049. }
  2050. let deps = [];
  2051. if (type === "clear") {
  2052. deps = [...depsMap.values()];
  2053. } else if (key === "length" && isArray(target)) {
  2054. const newLength = Number(newValue);
  2055. depsMap.forEach((dep, key2) => {
  2056. if (key2 === "length" || !isSymbol(key2) && key2 >= newLength) {
  2057. deps.push(dep);
  2058. }
  2059. });
  2060. } else {
  2061. if (key !== void 0) {
  2062. deps.push(depsMap.get(key));
  2063. }
  2064. switch (type) {
  2065. case "add":
  2066. if (!isArray(target)) {
  2067. deps.push(depsMap.get(ITERATE_KEY));
  2068. if (isMap(target)) {
  2069. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  2070. }
  2071. } else if (isIntegerKey(key)) {
  2072. deps.push(depsMap.get("length"));
  2073. }
  2074. break;
  2075. case "delete":
  2076. if (!isArray(target)) {
  2077. deps.push(depsMap.get(ITERATE_KEY));
  2078. if (isMap(target)) {
  2079. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  2080. }
  2081. }
  2082. break;
  2083. case "set":
  2084. if (isMap(target)) {
  2085. deps.push(depsMap.get(ITERATE_KEY));
  2086. }
  2087. break;
  2088. }
  2089. }
  2090. pauseScheduling();
  2091. for (const dep of deps) {
  2092. if (dep) {
  2093. triggerEffects(
  2094. dep,
  2095. 4,
  2096. {
  2097. target,
  2098. type,
  2099. key,
  2100. newValue,
  2101. oldValue,
  2102. oldTarget
  2103. }
  2104. );
  2105. }
  2106. }
  2107. resetScheduling();
  2108. }
  2109. const isNonTrackableKeys = /* @__PURE__ */ makeMap(`__proto__,__v_isRef,__isVue`);
  2110. const builtInSymbols = new Set(
  2111. /* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol)
  2112. );
  2113. const arrayInstrumentations = /* @__PURE__ */ createArrayInstrumentations();
  2114. function createArrayInstrumentations() {
  2115. const instrumentations = {};
  2116. ["includes", "indexOf", "lastIndexOf"].forEach((key) => {
  2117. instrumentations[key] = function(...args) {
  2118. const arr = toRaw(this);
  2119. for (let i2 = 0, l2 = this.length; i2 < l2; i2++) {
  2120. track(arr, "get", i2 + "");
  2121. }
  2122. const res = arr[key](...args);
  2123. if (res === -1 || res === false) {
  2124. return arr[key](...args.map(toRaw));
  2125. } else {
  2126. return res;
  2127. }
  2128. };
  2129. });
  2130. ["push", "pop", "shift", "unshift", "splice"].forEach((key) => {
  2131. instrumentations[key] = function(...args) {
  2132. pauseTracking();
  2133. pauseScheduling();
  2134. const res = toRaw(this)[key].apply(this, args);
  2135. resetScheduling();
  2136. resetTracking();
  2137. return res;
  2138. };
  2139. });
  2140. return instrumentations;
  2141. }
  2142. function hasOwnProperty(key) {
  2143. const obj = toRaw(this);
  2144. track(obj, "has", key);
  2145. return obj.hasOwnProperty(key);
  2146. }
  2147. class BaseReactiveHandler {
  2148. constructor(_isReadonly = false, _isShallow = false) {
  2149. this._isReadonly = _isReadonly;
  2150. this._isShallow = _isShallow;
  2151. }
  2152. get(target, key, receiver) {
  2153. const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow;
  2154. if (key === "__v_isReactive") {
  2155. return !isReadonly2;
  2156. } else if (key === "__v_isReadonly") {
  2157. return isReadonly2;
  2158. } else if (key === "__v_isShallow") {
  2159. return isShallow2;
  2160. } else if (key === "__v_raw") {
  2161. if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || // receiver is not the reactive proxy, but has the same prototype
  2162. // this means the reciever is a user proxy of the reactive proxy
  2163. Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) {
  2164. return target;
  2165. }
  2166. return;
  2167. }
  2168. const targetIsArray = isArray(target);
  2169. if (!isReadonly2) {
  2170. if (targetIsArray && hasOwn(arrayInstrumentations, key)) {
  2171. return Reflect.get(arrayInstrumentations, key, receiver);
  2172. }
  2173. if (key === "hasOwnProperty") {
  2174. return hasOwnProperty;
  2175. }
  2176. }
  2177. const res = Reflect.get(target, key, receiver);
  2178. if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
  2179. return res;
  2180. }
  2181. if (!isReadonly2) {
  2182. track(target, "get", key);
  2183. }
  2184. if (isShallow2) {
  2185. return res;
  2186. }
  2187. if (isRef(res)) {
  2188. return targetIsArray && isIntegerKey(key) ? res : res.value;
  2189. }
  2190. if (isObject$1(res)) {
  2191. return isReadonly2 ? readonly(res) : reactive(res);
  2192. }
  2193. return res;
  2194. }
  2195. }
  2196. class MutableReactiveHandler extends BaseReactiveHandler {
  2197. constructor(isShallow2 = false) {
  2198. super(false, isShallow2);
  2199. }
  2200. set(target, key, value, receiver) {
  2201. let oldValue = target[key];
  2202. if (!this._isShallow) {
  2203. const isOldValueReadonly = isReadonly(oldValue);
  2204. if (!isShallow(value) && !isReadonly(value)) {
  2205. oldValue = toRaw(oldValue);
  2206. value = toRaw(value);
  2207. }
  2208. if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
  2209. if (isOldValueReadonly) {
  2210. return false;
  2211. } else {
  2212. oldValue.value = value;
  2213. return true;
  2214. }
  2215. }
  2216. }
  2217. const hadKey = isArray(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn(target, key);
  2218. const result = Reflect.set(target, key, value, receiver);
  2219. if (target === toRaw(receiver)) {
  2220. if (!hadKey) {
  2221. trigger(target, "add", key, value);
  2222. } else if (hasChanged(value, oldValue)) {
  2223. trigger(target, "set", key, value, oldValue);
  2224. }
  2225. }
  2226. return result;
  2227. }
  2228. deleteProperty(target, key) {
  2229. const hadKey = hasOwn(target, key);
  2230. const oldValue = target[key];
  2231. const result = Reflect.deleteProperty(target, key);
  2232. if (result && hadKey) {
  2233. trigger(target, "delete", key, void 0, oldValue);
  2234. }
  2235. return result;
  2236. }
  2237. has(target, key) {
  2238. const result = Reflect.has(target, key);
  2239. if (!isSymbol(key) || !builtInSymbols.has(key)) {
  2240. track(target, "has", key);
  2241. }
  2242. return result;
  2243. }
  2244. ownKeys(target) {
  2245. track(
  2246. target,
  2247. "iterate",
  2248. isArray(target) ? "length" : ITERATE_KEY
  2249. );
  2250. return Reflect.ownKeys(target);
  2251. }
  2252. }
  2253. class ReadonlyReactiveHandler extends BaseReactiveHandler {
  2254. constructor(isShallow2 = false) {
  2255. super(true, isShallow2);
  2256. }
  2257. set(target, key) {
  2258. {
  2259. warn$2(
  2260. `Set operation on key "${String(key)}" failed: target is readonly.`,
  2261. target
  2262. );
  2263. }
  2264. return true;
  2265. }
  2266. deleteProperty(target, key) {
  2267. {
  2268. warn$2(
  2269. `Delete operation on key "${String(key)}" failed: target is readonly.`,
  2270. target
  2271. );
  2272. }
  2273. return true;
  2274. }
  2275. }
  2276. const mutableHandlers = /* @__PURE__ */ new MutableReactiveHandler();
  2277. const readonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler();
  2278. const shallowReactiveHandlers = /* @__PURE__ */ new MutableReactiveHandler(
  2279. true
  2280. );
  2281. const shallowReadonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(true);
  2282. const toShallow = (value) => value;
  2283. const getProto = (v2) => Reflect.getPrototypeOf(v2);
  2284. function get(target, key, isReadonly2 = false, isShallow2 = false) {
  2285. target = target["__v_raw"];
  2286. const rawTarget = toRaw(target);
  2287. const rawKey = toRaw(key);
  2288. if (!isReadonly2) {
  2289. if (hasChanged(key, rawKey)) {
  2290. track(rawTarget, "get", key);
  2291. }
  2292. track(rawTarget, "get", rawKey);
  2293. }
  2294. const { has: has2 } = getProto(rawTarget);
  2295. const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive;
  2296. if (has2.call(rawTarget, key)) {
  2297. return wrap(target.get(key));
  2298. } else if (has2.call(rawTarget, rawKey)) {
  2299. return wrap(target.get(rawKey));
  2300. } else if (target !== rawTarget) {
  2301. target.get(key);
  2302. }
  2303. }
  2304. function has(key, isReadonly2 = false) {
  2305. const target = this["__v_raw"];
  2306. const rawTarget = toRaw(target);
  2307. const rawKey = toRaw(key);
  2308. if (!isReadonly2) {
  2309. if (hasChanged(key, rawKey)) {
  2310. track(rawTarget, "has", key);
  2311. }
  2312. track(rawTarget, "has", rawKey);
  2313. }
  2314. return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey);
  2315. }
  2316. function size(target, isReadonly2 = false) {
  2317. target = target["__v_raw"];
  2318. !isReadonly2 && track(toRaw(target), "iterate", ITERATE_KEY);
  2319. return Reflect.get(target, "size", target);
  2320. }
  2321. function add(value) {
  2322. value = toRaw(value);
  2323. const target = toRaw(this);
  2324. const proto = getProto(target);
  2325. const hadKey = proto.has.call(target, value);
  2326. if (!hadKey) {
  2327. target.add(value);
  2328. trigger(target, "add", value, value);
  2329. }
  2330. return this;
  2331. }
  2332. function set$1(key, value) {
  2333. value = toRaw(value);
  2334. const target = toRaw(this);
  2335. const { has: has2, get: get22 } = getProto(target);
  2336. let hadKey = has2.call(target, key);
  2337. if (!hadKey) {
  2338. key = toRaw(key);
  2339. hadKey = has2.call(target, key);
  2340. } else {
  2341. checkIdentityKeys(target, has2, key);
  2342. }
  2343. const oldValue = get22.call(target, key);
  2344. target.set(key, value);
  2345. if (!hadKey) {
  2346. trigger(target, "add", key, value);
  2347. } else if (hasChanged(value, oldValue)) {
  2348. trigger(target, "set", key, value, oldValue);
  2349. }
  2350. return this;
  2351. }
  2352. function deleteEntry(key) {
  2353. const target = toRaw(this);
  2354. const { has: has2, get: get22 } = getProto(target);
  2355. let hadKey = has2.call(target, key);
  2356. if (!hadKey) {
  2357. key = toRaw(key);
  2358. hadKey = has2.call(target, key);
  2359. } else {
  2360. checkIdentityKeys(target, has2, key);
  2361. }
  2362. const oldValue = get22 ? get22.call(target, key) : void 0;
  2363. const result = target.delete(key);
  2364. if (hadKey) {
  2365. trigger(target, "delete", key, void 0, oldValue);
  2366. }
  2367. return result;
  2368. }
  2369. function clear() {
  2370. const target = toRaw(this);
  2371. const hadItems = target.size !== 0;
  2372. const oldTarget = isMap(target) ? new Map(target) : new Set(target);
  2373. const result = target.clear();
  2374. if (hadItems) {
  2375. trigger(target, "clear", void 0, void 0, oldTarget);
  2376. }
  2377. return result;
  2378. }
  2379. function createForEach(isReadonly2, isShallow2) {
  2380. return function forEach(callback, thisArg) {
  2381. const observed = this;
  2382. const target = observed["__v_raw"];
  2383. const rawTarget = toRaw(target);
  2384. const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive;
  2385. !isReadonly2 && track(rawTarget, "iterate", ITERATE_KEY);
  2386. return target.forEach((value, key) => {
  2387. return callback.call(thisArg, wrap(value), wrap(key), observed);
  2388. });
  2389. };
  2390. }
  2391. function createIterableMethod(method, isReadonly2, isShallow2) {
  2392. return function(...args) {
  2393. const target = this["__v_raw"];
  2394. const rawTarget = toRaw(target);
  2395. const targetIsMap = isMap(rawTarget);
  2396. const isPair = method === "entries" || method === Symbol.iterator && targetIsMap;
  2397. const isKeyOnly = method === "keys" && targetIsMap;
  2398. const innerIterator = target[method](...args);
  2399. const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive;
  2400. !isReadonly2 && track(
  2401. rawTarget,
  2402. "iterate",
  2403. isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY
  2404. );
  2405. return {
  2406. // iterator protocol
  2407. next() {
  2408. const { value, done } = innerIterator.next();
  2409. return done ? { value, done } : {
  2410. value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
  2411. done
  2412. };
  2413. },
  2414. // iterable protocol
  2415. [Symbol.iterator]() {
  2416. return this;
  2417. }
  2418. };
  2419. };
  2420. }
  2421. function createReadonlyMethod(type) {
  2422. return function(...args) {
  2423. {
  2424. const key = args[0] ? `on key "${args[0]}" ` : ``;
  2425. warn$2(
  2426. `${capitalize(type)} operation ${key}failed: target is readonly.`,
  2427. toRaw(this)
  2428. );
  2429. }
  2430. return type === "delete" ? false : type === "clear" ? void 0 : this;
  2431. };
  2432. }
  2433. function createInstrumentations() {
  2434. const mutableInstrumentations2 = {
  2435. get(key) {
  2436. return get(this, key);
  2437. },
  2438. get size() {
  2439. return size(this);
  2440. },
  2441. has,
  2442. add,
  2443. set: set$1,
  2444. delete: deleteEntry,
  2445. clear,
  2446. forEach: createForEach(false, false)
  2447. };
  2448. const shallowInstrumentations2 = {
  2449. get(key) {
  2450. return get(this, key, false, true);
  2451. },
  2452. get size() {
  2453. return size(this);
  2454. },
  2455. has,
  2456. add,
  2457. set: set$1,
  2458. delete: deleteEntry,
  2459. clear,
  2460. forEach: createForEach(false, true)
  2461. };
  2462. const readonlyInstrumentations2 = {
  2463. get(key) {
  2464. return get(this, key, true);
  2465. },
  2466. get size() {
  2467. return size(this, true);
  2468. },
  2469. has(key) {
  2470. return has.call(this, key, true);
  2471. },
  2472. add: createReadonlyMethod("add"),
  2473. set: createReadonlyMethod("set"),
  2474. delete: createReadonlyMethod("delete"),
  2475. clear: createReadonlyMethod("clear"),
  2476. forEach: createForEach(true, false)
  2477. };
  2478. const shallowReadonlyInstrumentations2 = {
  2479. get(key) {
  2480. return get(this, key, true, true);
  2481. },
  2482. get size() {
  2483. return size(this, true);
  2484. },
  2485. has(key) {
  2486. return has.call(this, key, true);
  2487. },
  2488. add: createReadonlyMethod("add"),
  2489. set: createReadonlyMethod("set"),
  2490. delete: createReadonlyMethod("delete"),
  2491. clear: createReadonlyMethod("clear"),
  2492. forEach: createForEach(true, true)
  2493. };
  2494. const iteratorMethods = [
  2495. "keys",
  2496. "values",
  2497. "entries",
  2498. Symbol.iterator
  2499. ];
  2500. iteratorMethods.forEach((method) => {
  2501. mutableInstrumentations2[method] = createIterableMethod(method, false, false);
  2502. readonlyInstrumentations2[method] = createIterableMethod(method, true, false);
  2503. shallowInstrumentations2[method] = createIterableMethod(method, false, true);
  2504. shallowReadonlyInstrumentations2[method] = createIterableMethod(
  2505. method,
  2506. true,
  2507. true
  2508. );
  2509. });
  2510. return [
  2511. mutableInstrumentations2,
  2512. readonlyInstrumentations2,
  2513. shallowInstrumentations2,
  2514. shallowReadonlyInstrumentations2
  2515. ];
  2516. }
  2517. const [
  2518. mutableInstrumentations,
  2519. readonlyInstrumentations,
  2520. shallowInstrumentations,
  2521. shallowReadonlyInstrumentations
  2522. ] = /* @__PURE__ */ createInstrumentations();
  2523. function createInstrumentationGetter(isReadonly2, shallow) {
  2524. const instrumentations = shallow ? isReadonly2 ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly2 ? readonlyInstrumentations : mutableInstrumentations;
  2525. return (target, key, receiver) => {
  2526. if (key === "__v_isReactive") {
  2527. return !isReadonly2;
  2528. } else if (key === "__v_isReadonly") {
  2529. return isReadonly2;
  2530. } else if (key === "__v_raw") {
  2531. return target;
  2532. }
  2533. return Reflect.get(
  2534. hasOwn(instrumentations, key) && key in target ? instrumentations : target,
  2535. key,
  2536. receiver
  2537. );
  2538. };
  2539. }
  2540. const mutableCollectionHandlers = {
  2541. get: /* @__PURE__ */ createInstrumentationGetter(false, false)
  2542. };
  2543. const shallowCollectionHandlers = {
  2544. get: /* @__PURE__ */ createInstrumentationGetter(false, true)
  2545. };
  2546. const readonlyCollectionHandlers = {
  2547. get: /* @__PURE__ */ createInstrumentationGetter(true, false)
  2548. };
  2549. const shallowReadonlyCollectionHandlers = {
  2550. get: /* @__PURE__ */ createInstrumentationGetter(true, true)
  2551. };
  2552. function checkIdentityKeys(target, has2, key) {
  2553. const rawKey = toRaw(key);
  2554. if (rawKey !== key && has2.call(target, rawKey)) {
  2555. const type = toRawType(target);
  2556. warn$2(
  2557. `Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.`
  2558. );
  2559. }
  2560. }
  2561. const reactiveMap = /* @__PURE__ */ new WeakMap();
  2562. const shallowReactiveMap = /* @__PURE__ */ new WeakMap();
  2563. const readonlyMap = /* @__PURE__ */ new WeakMap();
  2564. const shallowReadonlyMap = /* @__PURE__ */ new WeakMap();
  2565. function targetTypeMap(rawType) {
  2566. switch (rawType) {
  2567. case "Object":
  2568. case "Array":
  2569. return 1;
  2570. case "Map":
  2571. case "Set":
  2572. case "WeakMap":
  2573. case "WeakSet":
  2574. return 2;
  2575. default:
  2576. return 0;
  2577. }
  2578. }
  2579. function getTargetType(value) {
  2580. return value["__v_skip"] || !Object.isExtensible(value) ? 0 : targetTypeMap(toRawType(value));
  2581. }
  2582. function reactive(target) {
  2583. if (isReadonly(target)) {
  2584. return target;
  2585. }
  2586. return createReactiveObject(
  2587. target,
  2588. false,
  2589. mutableHandlers,
  2590. mutableCollectionHandlers,
  2591. reactiveMap
  2592. );
  2593. }
  2594. function shallowReactive(target) {
  2595. return createReactiveObject(
  2596. target,
  2597. false,
  2598. shallowReactiveHandlers,
  2599. shallowCollectionHandlers,
  2600. shallowReactiveMap
  2601. );
  2602. }
  2603. function readonly(target) {
  2604. return createReactiveObject(
  2605. target,
  2606. true,
  2607. readonlyHandlers,
  2608. readonlyCollectionHandlers,
  2609. readonlyMap
  2610. );
  2611. }
  2612. function shallowReadonly(target) {
  2613. return createReactiveObject(
  2614. target,
  2615. true,
  2616. shallowReadonlyHandlers,
  2617. shallowReadonlyCollectionHandlers,
  2618. shallowReadonlyMap
  2619. );
  2620. }
  2621. function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) {
  2622. if (!isObject$1(target)) {
  2623. {
  2624. warn$2(`value cannot be made reactive: ${String(target)}`);
  2625. }
  2626. return target;
  2627. }
  2628. if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) {
  2629. return target;
  2630. }
  2631. const existingProxy = proxyMap.get(target);
  2632. if (existingProxy) {
  2633. return existingProxy;
  2634. }
  2635. const targetType = getTargetType(target);
  2636. if (targetType === 0) {
  2637. return target;
  2638. }
  2639. const proxy = new Proxy(
  2640. target,
  2641. targetType === 2 ? collectionHandlers : baseHandlers
  2642. );
  2643. proxyMap.set(target, proxy);
  2644. return proxy;
  2645. }
  2646. function isReactive(value) {
  2647. if (isReadonly(value)) {
  2648. return isReactive(value["__v_raw"]);
  2649. }
  2650. return !!(value && value["__v_isReactive"]);
  2651. }
  2652. function isReadonly(value) {
  2653. return !!(value && value["__v_isReadonly"]);
  2654. }
  2655. function isShallow(value) {
  2656. return !!(value && value["__v_isShallow"]);
  2657. }
  2658. function isProxy(value) {
  2659. return isReactive(value) || isReadonly(value);
  2660. }
  2661. function toRaw(observed) {
  2662. const raw = observed && observed["__v_raw"];
  2663. return raw ? toRaw(raw) : observed;
  2664. }
  2665. function markRaw(value) {
  2666. if (Object.isExtensible(value)) {
  2667. def(value, "__v_skip", true);
  2668. }
  2669. return value;
  2670. }
  2671. const toReactive = (value) => isObject$1(value) ? reactive(value) : value;
  2672. const toReadonly = (value) => isObject$1(value) ? readonly(value) : value;
  2673. const COMPUTED_SIDE_EFFECT_WARN = `Computed is still dirty after getter evaluation, likely because a computed is mutating its own dependency in its getter. State mutations in computed getters should be avoided. Check the docs for more details: https://vuejs.org/guide/essentials/computed.html#getters-should-be-side-effect-free`;
  2674. class ComputedRefImpl {
  2675. constructor(getter, _setter, isReadonly2, isSSR) {
  2676. this.getter = getter;
  2677. this._setter = _setter;
  2678. this.dep = void 0;
  2679. this.__v_isRef = true;
  2680. this["__v_isReadonly"] = false;
  2681. this.effect = new ReactiveEffect(
  2682. () => getter(this._value),
  2683. () => triggerRefValue(
  2684. this,
  2685. this.effect._dirtyLevel === 2 ? 2 : 3
  2686. )
  2687. );
  2688. this.effect.computed = this;
  2689. this.effect.active = this._cacheable = !isSSR;
  2690. this["__v_isReadonly"] = isReadonly2;
  2691. }
  2692. get value() {
  2693. const self2 = toRaw(this);
  2694. if ((!self2._cacheable || self2.effect.dirty) && hasChanged(self2._value, self2._value = self2.effect.run())) {
  2695. triggerRefValue(self2, 4);
  2696. }
  2697. trackRefValue(self2);
  2698. if (self2.effect._dirtyLevel >= 2) {
  2699. if (this._warnRecursive) {
  2700. warn$2(COMPUTED_SIDE_EFFECT_WARN, `
  2701. getter: `, this.getter);
  2702. }
  2703. triggerRefValue(self2, 2);
  2704. }
  2705. return self2._value;
  2706. }
  2707. set value(newValue) {
  2708. this._setter(newValue);
  2709. }
  2710. // #region polyfill _dirty for backward compatibility third party code for Vue <= 3.3.x
  2711. get _dirty() {
  2712. return this.effect.dirty;
  2713. }
  2714. set _dirty(v2) {
  2715. this.effect.dirty = v2;
  2716. }
  2717. // #endregion
  2718. }
  2719. function computed$1(getterOrOptions, debugOptions, isSSR = false) {
  2720. let getter;
  2721. let setter;
  2722. const onlyGetter = isFunction(getterOrOptions);
  2723. if (onlyGetter) {
  2724. getter = getterOrOptions;
  2725. setter = () => {
  2726. warn$2("Write operation failed: computed value is readonly");
  2727. };
  2728. } else {
  2729. getter = getterOrOptions.get;
  2730. setter = getterOrOptions.set;
  2731. }
  2732. const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
  2733. if (debugOptions && !isSSR) {
  2734. cRef.effect.onTrack = debugOptions.onTrack;
  2735. cRef.effect.onTrigger = debugOptions.onTrigger;
  2736. }
  2737. return cRef;
  2738. }
  2739. function trackRefValue(ref2) {
  2740. var _a;
  2741. if (shouldTrack && activeEffect) {
  2742. ref2 = toRaw(ref2);
  2743. trackEffect(
  2744. activeEffect,
  2745. (_a = ref2.dep) != null ? _a : ref2.dep = createDep(
  2746. () => ref2.dep = void 0,
  2747. ref2 instanceof ComputedRefImpl ? ref2 : void 0
  2748. ),
  2749. {
  2750. target: ref2,
  2751. type: "get",
  2752. key: "value"
  2753. }
  2754. );
  2755. }
  2756. }
  2757. function triggerRefValue(ref2, dirtyLevel = 4, newVal) {
  2758. ref2 = toRaw(ref2);
  2759. const dep = ref2.dep;
  2760. if (dep) {
  2761. triggerEffects(
  2762. dep,
  2763. dirtyLevel,
  2764. {
  2765. target: ref2,
  2766. type: "set",
  2767. key: "value",
  2768. newValue: newVal
  2769. }
  2770. );
  2771. }
  2772. }
  2773. function isRef(r2) {
  2774. return !!(r2 && r2.__v_isRef === true);
  2775. }
  2776. function ref(value) {
  2777. return createRef(value, false);
  2778. }
  2779. function createRef(rawValue, shallow) {
  2780. if (isRef(rawValue)) {
  2781. return rawValue;
  2782. }
  2783. return new RefImpl(rawValue, shallow);
  2784. }
  2785. class RefImpl {
  2786. constructor(value, __v_isShallow) {
  2787. this.__v_isShallow = __v_isShallow;
  2788. this.dep = void 0;
  2789. this.__v_isRef = true;
  2790. this._rawValue = __v_isShallow ? value : toRaw(value);
  2791. this._value = __v_isShallow ? value : toReactive(value);
  2792. }
  2793. get value() {
  2794. trackRefValue(this);
  2795. return this._value;
  2796. }
  2797. set value(newVal) {
  2798. const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal);
  2799. newVal = useDirectValue ? newVal : toRaw(newVal);
  2800. if (hasChanged(newVal, this._rawValue)) {
  2801. this._rawValue = newVal;
  2802. this._value = useDirectValue ? newVal : toReactive(newVal);
  2803. triggerRefValue(this, 4, newVal);
  2804. }
  2805. }
  2806. }
  2807. function unref(ref2) {
  2808. return isRef(ref2) ? ref2.value : ref2;
  2809. }
  2810. const shallowUnwrapHandlers = {
  2811. get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
  2812. set: (target, key, value, receiver) => {
  2813. const oldValue = target[key];
  2814. if (isRef(oldValue) && !isRef(value)) {
  2815. oldValue.value = value;
  2816. return true;
  2817. } else {
  2818. return Reflect.set(target, key, value, receiver);
  2819. }
  2820. }
  2821. };
  2822. function proxyRefs(objectWithRefs) {
  2823. return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers);
  2824. }
  2825. const stack = [];
  2826. function pushWarningContext(vnode) {
  2827. stack.push(vnode);
  2828. }
  2829. function popWarningContext() {
  2830. stack.pop();
  2831. }
  2832. function warn$1(msg, ...args) {
  2833. pauseTracking();
  2834. const instance = stack.length ? stack[stack.length - 1].component : null;
  2835. const appWarnHandler = instance && instance.appContext.config.warnHandler;
  2836. const trace = getComponentTrace();
  2837. if (appWarnHandler) {
  2838. callWithErrorHandling(
  2839. appWarnHandler,
  2840. instance,
  2841. 11,
  2842. [
  2843. msg + args.map((a2) => {
  2844. var _a, _b;
  2845. return (_b = (_a = a2.toString) == null ? void 0 : _a.call(a2)) != null ? _b : JSON.stringify(a2);
  2846. }).join(""),
  2847. instance && instance.proxy,
  2848. trace.map(
  2849. ({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`
  2850. ).join("\n"),
  2851. trace
  2852. ]
  2853. );
  2854. } else {
  2855. const warnArgs = [`[Vue warn]: ${msg}`, ...args];
  2856. if (trace.length && // avoid spamming console during tests
  2857. true) {
  2858. warnArgs.push(`
  2859. `, ...formatTrace(trace));
  2860. }
  2861. console.warn(...warnArgs);
  2862. }
  2863. resetTracking();
  2864. }
  2865. function getComponentTrace() {
  2866. let currentVNode = stack[stack.length - 1];
  2867. if (!currentVNode) {
  2868. return [];
  2869. }
  2870. const normalizedStack = [];
  2871. while (currentVNode) {
  2872. const last = normalizedStack[0];
  2873. if (last && last.vnode === currentVNode) {
  2874. last.recurseCount++;
  2875. } else {
  2876. normalizedStack.push({
  2877. vnode: currentVNode,
  2878. recurseCount: 0
  2879. });
  2880. }
  2881. const parentInstance = currentVNode.component && currentVNode.component.parent;
  2882. currentVNode = parentInstance && parentInstance.vnode;
  2883. }
  2884. return normalizedStack;
  2885. }
  2886. function formatTrace(trace) {
  2887. const logs = [];
  2888. trace.forEach((entry, i2) => {
  2889. logs.push(...i2 === 0 ? [] : [`
  2890. `], ...formatTraceEntry(entry));
  2891. });
  2892. return logs;
  2893. }
  2894. function formatTraceEntry({ vnode, recurseCount }) {
  2895. const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
  2896. const isRoot = vnode.component ? vnode.component.parent == null : false;
  2897. const open = ` at <${formatComponentName(
  2898. vnode.component,
  2899. vnode.type,
  2900. isRoot
  2901. )}`;
  2902. const close = `>` + postfix;
  2903. return vnode.props ? [open, ...formatProps(vnode.props), close] : [open + close];
  2904. }
  2905. function formatProps(props) {
  2906. const res = [];
  2907. const keys = Object.keys(props);
  2908. keys.slice(0, 3).forEach((key) => {
  2909. res.push(...formatProp(key, props[key]));
  2910. });
  2911. if (keys.length > 3) {
  2912. res.push(` ...`);
  2913. }
  2914. return res;
  2915. }
  2916. function formatProp(key, value, raw) {
  2917. if (isString(value)) {
  2918. value = JSON.stringify(value);
  2919. return raw ? value : [`${key}=${value}`];
  2920. } else if (typeof value === "number" || typeof value === "boolean" || value == null) {
  2921. return raw ? value : [`${key}=${value}`];
  2922. } else if (isRef(value)) {
  2923. value = formatProp(key, toRaw(value.value), true);
  2924. return raw ? value : [`${key}=Ref<`, value, `>`];
  2925. } else if (isFunction(value)) {
  2926. return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
  2927. } else {
  2928. value = toRaw(value);
  2929. return raw ? value : [`${key}=`, value];
  2930. }
  2931. }
  2932. const ErrorTypeStrings = {
  2933. ["sp"]: "serverPrefetch hook",
  2934. ["bc"]: "beforeCreate hook",
  2935. ["c"]: "created hook",
  2936. ["bm"]: "beforeMount hook",
  2937. ["m"]: "mounted hook",
  2938. ["bu"]: "beforeUpdate hook",
  2939. ["u"]: "updated",
  2940. ["bum"]: "beforeUnmount hook",
  2941. ["um"]: "unmounted hook",
  2942. ["a"]: "activated hook",
  2943. ["da"]: "deactivated hook",
  2944. ["ec"]: "errorCaptured hook",
  2945. ["rtc"]: "renderTracked hook",
  2946. ["rtg"]: "renderTriggered hook",
  2947. [0]: "setup function",
  2948. [1]: "render function",
  2949. [2]: "watcher getter",
  2950. [3]: "watcher callback",
  2951. [4]: "watcher cleanup function",
  2952. [5]: "native event handler",
  2953. [6]: "component event handler",
  2954. [7]: "vnode hook",
  2955. [8]: "directive hook",
  2956. [9]: "transition hook",
  2957. [10]: "app errorHandler",
  2958. [11]: "app warnHandler",
  2959. [12]: "ref function",
  2960. [13]: "async component loader",
  2961. [14]: "scheduler flush. This is likely a Vue internals bug. Please open an issue at https://github.com/vuejs/core ."
  2962. };
  2963. function callWithErrorHandling(fn2, instance, type, args) {
  2964. try {
  2965. return args ? fn2(...args) : fn2();
  2966. } catch (err) {
  2967. handleError(err, instance, type);
  2968. }
  2969. }
  2970. function callWithAsyncErrorHandling(fn2, instance, type, args) {
  2971. if (isFunction(fn2)) {
  2972. const res = callWithErrorHandling(fn2, instance, type, args);
  2973. if (res && isPromise$2(res)) {
  2974. res.catch((err) => {
  2975. handleError(err, instance, type);
  2976. });
  2977. }
  2978. return res;
  2979. }
  2980. const values = [];
  2981. for (let i2 = 0; i2 < fn2.length; i2++) {
  2982. values.push(callWithAsyncErrorHandling(fn2[i2], instance, type, args));
  2983. }
  2984. return values;
  2985. }
  2986. function handleError(err, instance, type, throwInDev = true) {
  2987. const contextVNode = instance ? instance.vnode : null;
  2988. if (instance) {
  2989. let cur = instance.parent;
  2990. const exposedInstance = instance.proxy;
  2991. const errorInfo = ErrorTypeStrings[type] || type;
  2992. while (cur) {
  2993. const errorCapturedHooks = cur.ec;
  2994. if (errorCapturedHooks) {
  2995. for (let i2 = 0; i2 < errorCapturedHooks.length; i2++) {
  2996. if (errorCapturedHooks[i2](err, exposedInstance, errorInfo) === false) {
  2997. return;
  2998. }
  2999. }
  3000. }
  3001. cur = cur.parent;
  3002. }
  3003. const appErrorHandler = instance.appContext.config.errorHandler;
  3004. if (appErrorHandler) {
  3005. callWithErrorHandling(
  3006. appErrorHandler,
  3007. null,
  3008. 10,
  3009. [err, exposedInstance, errorInfo]
  3010. );
  3011. return;
  3012. }
  3013. }
  3014. logError(err, type, contextVNode, throwInDev);
  3015. }
  3016. function logError(err, type, contextVNode, throwInDev = true) {
  3017. {
  3018. const info = ErrorTypeStrings[type] || type;
  3019. if (contextVNode) {
  3020. pushWarningContext(contextVNode);
  3021. }
  3022. warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
  3023. if (contextVNode) {
  3024. popWarningContext();
  3025. }
  3026. if (throwInDev) {
  3027. console.error(err);
  3028. } else {
  3029. console.error(err);
  3030. }
  3031. }
  3032. }
  3033. let isFlushing = false;
  3034. let isFlushPending = false;
  3035. const queue = [];
  3036. let flushIndex = 0;
  3037. const pendingPostFlushCbs = [];
  3038. let activePostFlushCbs = null;
  3039. let postFlushIndex = 0;
  3040. const resolvedPromise = /* @__PURE__ */ Promise.resolve();
  3041. let currentFlushPromise = null;
  3042. const RECURSION_LIMIT = 100;
  3043. function nextTick$1(fn2) {
  3044. const p2 = currentFlushPromise || resolvedPromise;
  3045. return fn2 ? p2.then(this ? fn2.bind(this) : fn2) : p2;
  3046. }
  3047. function findInsertionIndex(id) {
  3048. let start = flushIndex + 1;
  3049. let end = queue.length;
  3050. while (start < end) {
  3051. const middle = start + end >>> 1;
  3052. const middleJob = queue[middle];
  3053. const middleJobId = getId(middleJob);
  3054. if (middleJobId < id || middleJobId === id && middleJob.pre) {
  3055. start = middle + 1;
  3056. } else {
  3057. end = middle;
  3058. }
  3059. }
  3060. return start;
  3061. }
  3062. function queueJob(job) {
  3063. if (!queue.length || !queue.includes(
  3064. job,
  3065. isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex
  3066. )) {
  3067. if (job.id == null) {
  3068. queue.push(job);
  3069. } else {
  3070. queue.splice(findInsertionIndex(job.id), 0, job);
  3071. }
  3072. queueFlush();
  3073. }
  3074. }
  3075. function queueFlush() {
  3076. if (!isFlushing && !isFlushPending) {
  3077. isFlushPending = true;
  3078. currentFlushPromise = resolvedPromise.then(flushJobs);
  3079. }
  3080. }
  3081. function hasQueueJob(job) {
  3082. return queue.indexOf(job) > -1;
  3083. }
  3084. function invalidateJob(job) {
  3085. const i2 = queue.indexOf(job);
  3086. if (i2 > flushIndex) {
  3087. queue.splice(i2, 1);
  3088. }
  3089. }
  3090. function queuePostFlushCb(cb) {
  3091. if (!isArray(cb)) {
  3092. if (!activePostFlushCbs || !activePostFlushCbs.includes(
  3093. cb,
  3094. cb.allowRecurse ? postFlushIndex + 1 : postFlushIndex
  3095. )) {
  3096. pendingPostFlushCbs.push(cb);
  3097. }
  3098. } else {
  3099. pendingPostFlushCbs.push(...cb);
  3100. }
  3101. queueFlush();
  3102. }
  3103. function flushPreFlushCbs(instance, seen, i2 = isFlushing ? flushIndex + 1 : 0) {
  3104. {
  3105. seen = seen || /* @__PURE__ */ new Map();
  3106. }
  3107. for (; i2 < queue.length; i2++) {
  3108. const cb = queue[i2];
  3109. if (cb && cb.pre) {
  3110. if (checkRecursiveUpdates(seen, cb)) {
  3111. continue;
  3112. }
  3113. queue.splice(i2, 1);
  3114. i2--;
  3115. cb();
  3116. }
  3117. }
  3118. }
  3119. function flushPostFlushCbs(seen) {
  3120. if (pendingPostFlushCbs.length) {
  3121. const deduped = [...new Set(pendingPostFlushCbs)].sort(
  3122. (a2, b2) => getId(a2) - getId(b2)
  3123. );
  3124. pendingPostFlushCbs.length = 0;
  3125. if (activePostFlushCbs) {
  3126. activePostFlushCbs.push(...deduped);
  3127. return;
  3128. }
  3129. activePostFlushCbs = deduped;
  3130. {
  3131. seen = seen || /* @__PURE__ */ new Map();
  3132. }
  3133. for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
  3134. if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
  3135. continue;
  3136. }
  3137. activePostFlushCbs[postFlushIndex]();
  3138. }
  3139. activePostFlushCbs = null;
  3140. postFlushIndex = 0;
  3141. }
  3142. }
  3143. const getId = (job) => job.id == null ? Infinity : job.id;
  3144. const comparator = (a2, b2) => {
  3145. const diff2 = getId(a2) - getId(b2);
  3146. if (diff2 === 0) {
  3147. if (a2.pre && !b2.pre)
  3148. return -1;
  3149. if (b2.pre && !a2.pre)
  3150. return 1;
  3151. }
  3152. return diff2;
  3153. };
  3154. function flushJobs(seen) {
  3155. isFlushPending = false;
  3156. isFlushing = true;
  3157. {
  3158. seen = seen || /* @__PURE__ */ new Map();
  3159. }
  3160. queue.sort(comparator);
  3161. const check = (job) => checkRecursiveUpdates(seen, job);
  3162. try {
  3163. for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
  3164. const job = queue[flushIndex];
  3165. if (job && job.active !== false) {
  3166. if (check(job)) {
  3167. continue;
  3168. }
  3169. callWithErrorHandling(job, null, 14);
  3170. }
  3171. }
  3172. } finally {
  3173. flushIndex = 0;
  3174. queue.length = 0;
  3175. flushPostFlushCbs(seen);
  3176. isFlushing = false;
  3177. currentFlushPromise = null;
  3178. if (queue.length || pendingPostFlushCbs.length) {
  3179. flushJobs(seen);
  3180. }
  3181. }
  3182. }
  3183. function checkRecursiveUpdates(seen, fn2) {
  3184. if (!seen.has(fn2)) {
  3185. seen.set(fn2, 1);
  3186. } else {
  3187. const count = seen.get(fn2);
  3188. if (count > RECURSION_LIMIT) {
  3189. const instance = fn2.ownerInstance;
  3190. const componentName = instance && getComponentName(instance.type);
  3191. handleError(
  3192. `Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function.`,
  3193. null,
  3194. 10
  3195. );
  3196. return true;
  3197. } else {
  3198. seen.set(fn2, count + 1);
  3199. }
  3200. }
  3201. }
  3202. let devtools;
  3203. let buffer = [];
  3204. let devtoolsNotInstalled = false;
  3205. function emit$1(event, ...args) {
  3206. if (devtools) {
  3207. devtools.emit(event, ...args);
  3208. } else if (!devtoolsNotInstalled) {
  3209. buffer.push({ event, args });
  3210. }
  3211. }
  3212. function setDevtoolsHook(hook, target) {
  3213. var _a, _b;
  3214. devtools = hook;
  3215. if (devtools) {
  3216. devtools.enabled = true;
  3217. buffer.forEach(({ event, args }) => devtools.emit(event, ...args));
  3218. buffer = [];
  3219. } else if (
  3220. // handle late devtools injection - only do this if we are in an actual
  3221. // browser environment to avoid the timer handle stalling test runner exit
  3222. // (#4815)
  3223. typeof window !== "undefined" && // some envs mock window but not fully
  3224. window.HTMLElement && // also exclude jsdom
  3225. !((_b = (_a = window.navigator) == null ? void 0 : _a.userAgent) == null ? void 0 : _b.includes("jsdom"))
  3226. ) {
  3227. const replay = target.__VUE_DEVTOOLS_HOOK_REPLAY__ = target.__VUE_DEVTOOLS_HOOK_REPLAY__ || [];
  3228. replay.push((newHook) => {
  3229. setDevtoolsHook(newHook, target);
  3230. });
  3231. setTimeout(() => {
  3232. if (!devtools) {
  3233. target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;
  3234. devtoolsNotInstalled = true;
  3235. buffer = [];
  3236. }
  3237. }, 3e3);
  3238. } else {
  3239. devtoolsNotInstalled = true;
  3240. buffer = [];
  3241. }
  3242. }
  3243. function devtoolsInitApp(app, version2) {
  3244. emit$1("app:init", app, version2, {
  3245. Fragment: Fragment$1,
  3246. Text,
  3247. Comment,
  3248. Static
  3249. });
  3250. }
  3251. const devtoolsComponentAdded = /* @__PURE__ */ createDevtoolsComponentHook(
  3252. "component:added"
  3253. /* COMPONENT_ADDED */
  3254. );
  3255. const devtoolsComponentUpdated = /* @__PURE__ */ createDevtoolsComponentHook(
  3256. "component:updated"
  3257. /* COMPONENT_UPDATED */
  3258. );
  3259. const _devtoolsComponentRemoved = /* @__PURE__ */ createDevtoolsComponentHook(
  3260. "component:removed"
  3261. /* COMPONENT_REMOVED */
  3262. );
  3263. const devtoolsComponentRemoved = (component) => {
  3264. if (devtools && typeof devtools.cleanupBuffer === "function" && // remove the component if it wasn't buffered
  3265. !devtools.cleanupBuffer(component)) {
  3266. _devtoolsComponentRemoved(component);
  3267. }
  3268. };
  3269. /*! #__NO_SIDE_EFFECTS__ */
  3270. // @__NO_SIDE_EFFECTS__
  3271. function createDevtoolsComponentHook(hook) {
  3272. return (component) => {
  3273. emit$1(
  3274. hook,
  3275. component.appContext.app,
  3276. component.uid,
  3277. // fixed by xxxxxx
  3278. // 为 0 是 App,无 parent 是 Page 指向 App
  3279. component.uid === 0 ? void 0 : component.parent ? component.parent.uid : 0,
  3280. component
  3281. );
  3282. };
  3283. }
  3284. const devtoolsPerfStart = /* @__PURE__ */ createDevtoolsPerformanceHook(
  3285. "perf:start"
  3286. /* PERFORMANCE_START */
  3287. );
  3288. const devtoolsPerfEnd = /* @__PURE__ */ createDevtoolsPerformanceHook(
  3289. "perf:end"
  3290. /* PERFORMANCE_END */
  3291. );
  3292. function createDevtoolsPerformanceHook(hook) {
  3293. return (component, type, time) => {
  3294. emit$1(hook, component.appContext.app, component.uid, component, type, time);
  3295. };
  3296. }
  3297. function devtoolsComponentEmit(component, event, params) {
  3298. emit$1(
  3299. "component:emit",
  3300. component.appContext.app,
  3301. component,
  3302. event,
  3303. params
  3304. );
  3305. }
  3306. function emit(instance, event, ...rawArgs) {
  3307. if (instance.isUnmounted)
  3308. return;
  3309. const props = instance.vnode.props || EMPTY_OBJ;
  3310. {
  3311. const {
  3312. emitsOptions,
  3313. propsOptions: [propsOptions]
  3314. } = instance;
  3315. if (emitsOptions) {
  3316. if (!(event in emitsOptions) && true) {
  3317. if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
  3318. warn$1(
  3319. `Component emitted event "${event}" but it is neither declared in the emits option nor as an "${toHandlerKey(event)}" prop.`
  3320. );
  3321. }
  3322. } else {
  3323. const validator = emitsOptions[event];
  3324. if (isFunction(validator)) {
  3325. const isValid2 = validator(...rawArgs);
  3326. if (!isValid2) {
  3327. warn$1(
  3328. `Invalid event arguments: event validation failed for event "${event}".`
  3329. );
  3330. }
  3331. }
  3332. }
  3333. }
  3334. }
  3335. let args = rawArgs;
  3336. const isModelListener2 = event.startsWith("update:");
  3337. const modelArg = isModelListener2 && event.slice(7);
  3338. if (modelArg && modelArg in props) {
  3339. const modifiersKey = `${modelArg === "modelValue" ? "model" : modelArg}Modifiers`;
  3340. const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
  3341. if (trim) {
  3342. args = rawArgs.map((a2) => isString(a2) ? a2.trim() : a2);
  3343. }
  3344. if (number) {
  3345. args = rawArgs.map(looseToNumber);
  3346. }
  3347. }
  3348. {
  3349. devtoolsComponentEmit(instance, event, args);
  3350. }
  3351. {
  3352. const lowerCaseEvent = event.toLowerCase();
  3353. if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
  3354. warn$1(
  3355. `Event "${lowerCaseEvent}" is emitted in component ${formatComponentName(
  3356. instance,
  3357. instance.type
  3358. )} but the handler is registered for "${event}". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates. You should probably use "${hyphenate(
  3359. event
  3360. )}" instead of "${event}".`
  3361. );
  3362. }
  3363. }
  3364. let handlerName;
  3365. let handler = props[handlerName = toHandlerKey(event)] || // also try camelCase event handler (#2249)
  3366. props[handlerName = toHandlerKey(camelize(event))];
  3367. if (!handler && isModelListener2) {
  3368. handler = props[handlerName = toHandlerKey(hyphenate(event))];
  3369. }
  3370. if (handler) {
  3371. callWithAsyncErrorHandling(
  3372. handler,
  3373. instance,
  3374. 6,
  3375. args
  3376. );
  3377. }
  3378. const onceHandler = props[handlerName + `Once`];
  3379. if (onceHandler) {
  3380. if (!instance.emitted) {
  3381. instance.emitted = {};
  3382. } else if (instance.emitted[handlerName]) {
  3383. return;
  3384. }
  3385. instance.emitted[handlerName] = true;
  3386. callWithAsyncErrorHandling(
  3387. onceHandler,
  3388. instance,
  3389. 6,
  3390. args
  3391. );
  3392. }
  3393. }
  3394. function normalizeEmitsOptions(comp, appContext, asMixin = false) {
  3395. const cache = appContext.emitsCache;
  3396. const cached = cache.get(comp);
  3397. if (cached !== void 0) {
  3398. return cached;
  3399. }
  3400. const raw = comp.emits;
  3401. let normalized = {};
  3402. let hasExtends = false;
  3403. if (!isFunction(comp)) {
  3404. const extendEmits = (raw2) => {
  3405. const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true);
  3406. if (normalizedFromExtend) {
  3407. hasExtends = true;
  3408. extend(normalized, normalizedFromExtend);
  3409. }
  3410. };
  3411. if (!asMixin && appContext.mixins.length) {
  3412. appContext.mixins.forEach(extendEmits);
  3413. }
  3414. if (comp.extends) {
  3415. extendEmits(comp.extends);
  3416. }
  3417. if (comp.mixins) {
  3418. comp.mixins.forEach(extendEmits);
  3419. }
  3420. }
  3421. if (!raw && !hasExtends) {
  3422. if (isObject$1(comp)) {
  3423. cache.set(comp, null);
  3424. }
  3425. return null;
  3426. }
  3427. if (isArray(raw)) {
  3428. raw.forEach((key) => normalized[key] = null);
  3429. } else {
  3430. extend(normalized, raw);
  3431. }
  3432. if (isObject$1(comp)) {
  3433. cache.set(comp, normalized);
  3434. }
  3435. return normalized;
  3436. }
  3437. function isEmitListener(options, key) {
  3438. if (!options || !isOn(key)) {
  3439. return false;
  3440. }
  3441. key = key.slice(2).replace(/Once$/, "");
  3442. return hasOwn(options, key[0].toLowerCase() + key.slice(1)) || hasOwn(options, hyphenate(key)) || hasOwn(options, key);
  3443. }
  3444. let currentRenderingInstance = null;
  3445. function setCurrentRenderingInstance(instance) {
  3446. const prev = currentRenderingInstance;
  3447. currentRenderingInstance = instance;
  3448. instance && instance.type.__scopeId || null;
  3449. return prev;
  3450. }
  3451. const COMPONENTS = "components";
  3452. function resolveComponent(name, maybeSelfReference) {
  3453. return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
  3454. }
  3455. function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
  3456. const instance = currentRenderingInstance || currentInstance;
  3457. if (instance) {
  3458. const Component2 = instance.type;
  3459. if (type === COMPONENTS) {
  3460. const selfName = getComponentName(
  3461. Component2,
  3462. false
  3463. );
  3464. if (selfName && (selfName === name || selfName === camelize(name) || selfName === capitalize(camelize(name)))) {
  3465. return Component2;
  3466. }
  3467. }
  3468. const res = (
  3469. // local registration
  3470. // check instance[type] first which is resolved for options API
  3471. resolve(instance[type] || Component2[type], name) || // global registration
  3472. resolve(instance.appContext[type], name)
  3473. );
  3474. if (!res && maybeSelfReference) {
  3475. return Component2;
  3476. }
  3477. if (warnMissing && !res) {
  3478. const extra = type === COMPONENTS ? `
  3479. If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.` : ``;
  3480. warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
  3481. }
  3482. return res;
  3483. } else {
  3484. warn$1(
  3485. `resolve${capitalize(type.slice(0, -1))} can only be used in render() or setup().`
  3486. );
  3487. }
  3488. }
  3489. function resolve(registry, name) {
  3490. return registry && (registry[name] || registry[camelize(name)] || registry[capitalize(camelize(name))]);
  3491. }
  3492. const INITIAL_WATCHER_VALUE = {};
  3493. function watch(source, cb, options) {
  3494. if (!isFunction(cb)) {
  3495. warn$1(
  3496. `\`watch(fn, options?)\` signature has been moved to a separate API. Use \`watchEffect(fn, options?)\` instead. \`watch\` now only supports \`watch(source, cb, options?) signature.`
  3497. );
  3498. }
  3499. return doWatch(source, cb, options);
  3500. }
  3501. function doWatch(source, cb, {
  3502. immediate,
  3503. deep,
  3504. flush,
  3505. once: once2,
  3506. onTrack,
  3507. onTrigger
  3508. } = EMPTY_OBJ) {
  3509. if (cb && once2) {
  3510. const _cb = cb;
  3511. cb = (...args) => {
  3512. _cb(...args);
  3513. unwatch();
  3514. };
  3515. }
  3516. if (deep !== void 0 && typeof deep === "number") {
  3517. warn$1(
  3518. `watch() "deep" option with number value will be used as watch depth in future versions. Please use a boolean instead to avoid potential breakage.`
  3519. );
  3520. }
  3521. if (!cb) {
  3522. if (immediate !== void 0) {
  3523. warn$1(
  3524. `watch() "immediate" option is only respected when using the watch(source, callback, options?) signature.`
  3525. );
  3526. }
  3527. if (deep !== void 0) {
  3528. warn$1(
  3529. `watch() "deep" option is only respected when using the watch(source, callback, options?) signature.`
  3530. );
  3531. }
  3532. if (once2 !== void 0) {
  3533. warn$1(
  3534. `watch() "once" option is only respected when using the watch(source, callback, options?) signature.`
  3535. );
  3536. }
  3537. }
  3538. const warnInvalidSource = (s2) => {
  3539. warn$1(
  3540. `Invalid watch source: `,
  3541. s2,
  3542. `A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.`
  3543. );
  3544. };
  3545. const instance = currentInstance;
  3546. const reactiveGetter = (source2) => deep === true ? source2 : (
  3547. // for deep: false, only traverse root-level properties
  3548. traverse(source2, deep === false ? 1 : void 0)
  3549. );
  3550. let getter;
  3551. let forceTrigger = false;
  3552. let isMultiSource = false;
  3553. if (isRef(source)) {
  3554. getter = () => source.value;
  3555. forceTrigger = isShallow(source);
  3556. } else if (isReactive(source)) {
  3557. getter = () => reactiveGetter(source);
  3558. forceTrigger = true;
  3559. } else if (isArray(source)) {
  3560. isMultiSource = true;
  3561. forceTrigger = source.some((s2) => isReactive(s2) || isShallow(s2));
  3562. getter = () => source.map((s2) => {
  3563. if (isRef(s2)) {
  3564. return s2.value;
  3565. } else if (isReactive(s2)) {
  3566. return reactiveGetter(s2);
  3567. } else if (isFunction(s2)) {
  3568. return callWithErrorHandling(s2, instance, 2);
  3569. } else {
  3570. warnInvalidSource(s2);
  3571. }
  3572. });
  3573. } else if (isFunction(source)) {
  3574. if (cb) {
  3575. getter = () => callWithErrorHandling(source, instance, 2);
  3576. } else {
  3577. getter = () => {
  3578. if (cleanup) {
  3579. cleanup();
  3580. }
  3581. return callWithAsyncErrorHandling(
  3582. source,
  3583. instance,
  3584. 3,
  3585. [onCleanup]
  3586. );
  3587. };
  3588. }
  3589. } else {
  3590. getter = NOOP;
  3591. warnInvalidSource(source);
  3592. }
  3593. if (cb && deep) {
  3594. const baseGetter = getter;
  3595. getter = () => traverse(baseGetter());
  3596. }
  3597. let cleanup;
  3598. let onCleanup = (fn2) => {
  3599. cleanup = effect2.onStop = () => {
  3600. callWithErrorHandling(fn2, instance, 4);
  3601. cleanup = effect2.onStop = void 0;
  3602. };
  3603. };
  3604. let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE;
  3605. const job = () => {
  3606. if (!effect2.active || !effect2.dirty) {
  3607. return;
  3608. }
  3609. if (cb) {
  3610. const newValue = effect2.run();
  3611. if (deep || forceTrigger || (isMultiSource ? newValue.some((v2, i2) => hasChanged(v2, oldValue[i2])) : hasChanged(newValue, oldValue)) || false) {
  3612. if (cleanup) {
  3613. cleanup();
  3614. }
  3615. callWithAsyncErrorHandling(cb, instance, 3, [
  3616. newValue,
  3617. // pass undefined as the old value when it's changed for the first time
  3618. oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue,
  3619. onCleanup
  3620. ]);
  3621. oldValue = newValue;
  3622. }
  3623. } else {
  3624. effect2.run();
  3625. }
  3626. };
  3627. job.allowRecurse = !!cb;
  3628. let scheduler;
  3629. if (flush === "sync") {
  3630. scheduler = job;
  3631. } else if (flush === "post") {
  3632. scheduler = () => queuePostRenderEffect$1(job, instance && instance.suspense);
  3633. } else {
  3634. job.pre = true;
  3635. if (instance)
  3636. job.id = instance.uid;
  3637. scheduler = () => queueJob(job);
  3638. }
  3639. const effect2 = new ReactiveEffect(getter, NOOP, scheduler);
  3640. const scope = getCurrentScope();
  3641. const unwatch = () => {
  3642. effect2.stop();
  3643. if (scope) {
  3644. remove(scope.effects, effect2);
  3645. }
  3646. };
  3647. {
  3648. effect2.onTrack = onTrack;
  3649. effect2.onTrigger = onTrigger;
  3650. }
  3651. if (cb) {
  3652. if (immediate) {
  3653. job();
  3654. } else {
  3655. oldValue = effect2.run();
  3656. }
  3657. } else if (flush === "post") {
  3658. queuePostRenderEffect$1(
  3659. effect2.run.bind(effect2),
  3660. instance && instance.suspense
  3661. );
  3662. } else {
  3663. effect2.run();
  3664. }
  3665. return unwatch;
  3666. }
  3667. function instanceWatch(source, value, options) {
  3668. const publicThis = this.proxy;
  3669. const getter = isString(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis);
  3670. let cb;
  3671. if (isFunction(value)) {
  3672. cb = value;
  3673. } else {
  3674. cb = value.handler;
  3675. options = value;
  3676. }
  3677. const reset = setCurrentInstance(this);
  3678. const res = doWatch(getter, cb.bind(publicThis), options);
  3679. reset();
  3680. return res;
  3681. }
  3682. function createPathGetter(ctx, path) {
  3683. const segments = path.split(".");
  3684. return () => {
  3685. let cur = ctx;
  3686. for (let i2 = 0; i2 < segments.length && cur; i2++) {
  3687. cur = cur[segments[i2]];
  3688. }
  3689. return cur;
  3690. };
  3691. }
  3692. function traverse(value, depth, currentDepth = 0, seen) {
  3693. if (!isObject$1(value) || value["__v_skip"]) {
  3694. return value;
  3695. }
  3696. if (depth && depth > 0) {
  3697. if (currentDepth >= depth) {
  3698. return value;
  3699. }
  3700. currentDepth++;
  3701. }
  3702. seen = seen || /* @__PURE__ */ new Set();
  3703. if (seen.has(value)) {
  3704. return value;
  3705. }
  3706. seen.add(value);
  3707. if (isRef(value)) {
  3708. traverse(value.value, depth, currentDepth, seen);
  3709. } else if (isArray(value)) {
  3710. for (let i2 = 0; i2 < value.length; i2++) {
  3711. traverse(value[i2], depth, currentDepth, seen);
  3712. }
  3713. } else if (isSet(value) || isMap(value)) {
  3714. value.forEach((v2) => {
  3715. traverse(v2, depth, currentDepth, seen);
  3716. });
  3717. } else if (isPlainObject(value)) {
  3718. for (const key in value) {
  3719. traverse(value[key], depth, currentDepth, seen);
  3720. }
  3721. }
  3722. return value;
  3723. }
  3724. function validateDirectiveName(name) {
  3725. if (isBuiltInDirective(name)) {
  3726. warn$1("Do not use built-in directive ids as custom directive id: " + name);
  3727. }
  3728. }
  3729. function createAppContext() {
  3730. return {
  3731. app: null,
  3732. config: {
  3733. isNativeTag: NO,
  3734. performance: false,
  3735. globalProperties: {},
  3736. optionMergeStrategies: {},
  3737. errorHandler: void 0,
  3738. warnHandler: void 0,
  3739. compilerOptions: {}
  3740. },
  3741. mixins: [],
  3742. components: {},
  3743. directives: {},
  3744. provides: /* @__PURE__ */ Object.create(null),
  3745. optionsCache: /* @__PURE__ */ new WeakMap(),
  3746. propsCache: /* @__PURE__ */ new WeakMap(),
  3747. emitsCache: /* @__PURE__ */ new WeakMap()
  3748. };
  3749. }
  3750. let uid$1 = 0;
  3751. function createAppAPI(render, hydrate) {
  3752. return function createApp2(rootComponent, rootProps = null) {
  3753. if (!isFunction(rootComponent)) {
  3754. rootComponent = extend({}, rootComponent);
  3755. }
  3756. if (rootProps != null && !isObject$1(rootProps)) {
  3757. warn$1(`root props passed to app.mount() must be an object.`);
  3758. rootProps = null;
  3759. }
  3760. const context = createAppContext();
  3761. const installedPlugins = /* @__PURE__ */ new WeakSet();
  3762. const app = context.app = {
  3763. _uid: uid$1++,
  3764. _component: rootComponent,
  3765. _props: rootProps,
  3766. _container: null,
  3767. _context: context,
  3768. _instance: null,
  3769. version: version$1,
  3770. get config() {
  3771. return context.config;
  3772. },
  3773. set config(v2) {
  3774. {
  3775. warn$1(
  3776. `app.config cannot be replaced. Modify individual options instead.`
  3777. );
  3778. }
  3779. },
  3780. use(plugin2, ...options) {
  3781. if (installedPlugins.has(plugin2)) {
  3782. warn$1(`Plugin has already been applied to target app.`);
  3783. } else if (plugin2 && isFunction(plugin2.install)) {
  3784. installedPlugins.add(plugin2);
  3785. plugin2.install(app, ...options);
  3786. } else if (isFunction(plugin2)) {
  3787. installedPlugins.add(plugin2);
  3788. plugin2(app, ...options);
  3789. } else {
  3790. warn$1(
  3791. `A plugin must either be a function or an object with an "install" function.`
  3792. );
  3793. }
  3794. return app;
  3795. },
  3796. mixin(mixin) {
  3797. {
  3798. if (!context.mixins.includes(mixin)) {
  3799. context.mixins.push(mixin);
  3800. } else {
  3801. warn$1(
  3802. "Mixin has already been applied to target app" + (mixin.name ? `: ${mixin.name}` : "")
  3803. );
  3804. }
  3805. }
  3806. return app;
  3807. },
  3808. component(name, component) {
  3809. {
  3810. validateComponentName(name, context.config);
  3811. }
  3812. if (!component) {
  3813. return context.components[name];
  3814. }
  3815. if (context.components[name]) {
  3816. warn$1(`Component "${name}" has already been registered in target app.`);
  3817. }
  3818. context.components[name] = component;
  3819. return app;
  3820. },
  3821. directive(name, directive) {
  3822. {
  3823. validateDirectiveName(name);
  3824. }
  3825. if (!directive) {
  3826. return context.directives[name];
  3827. }
  3828. if (context.directives[name]) {
  3829. warn$1(`Directive "${name}" has already been registered in target app.`);
  3830. }
  3831. context.directives[name] = directive;
  3832. return app;
  3833. },
  3834. // fixed by xxxxxx
  3835. mount() {
  3836. },
  3837. // fixed by xxxxxx
  3838. unmount() {
  3839. },
  3840. provide(key, value) {
  3841. if (key in context.provides) {
  3842. warn$1(
  3843. `App already provides property with key "${String(key)}". It will be overwritten with the new value.`
  3844. );
  3845. }
  3846. context.provides[key] = value;
  3847. return app;
  3848. },
  3849. runWithContext(fn2) {
  3850. const lastApp = currentApp;
  3851. currentApp = app;
  3852. try {
  3853. return fn2();
  3854. } finally {
  3855. currentApp = lastApp;
  3856. }
  3857. }
  3858. };
  3859. return app;
  3860. };
  3861. }
  3862. let currentApp = null;
  3863. function provide(key, value) {
  3864. if (!currentInstance) {
  3865. {
  3866. warn$1(`provide() can only be used inside setup().`);
  3867. }
  3868. } else {
  3869. let provides = currentInstance.provides;
  3870. const parentProvides = currentInstance.parent && currentInstance.parent.provides;
  3871. if (parentProvides === provides) {
  3872. provides = currentInstance.provides = Object.create(parentProvides);
  3873. }
  3874. provides[key] = value;
  3875. if (currentInstance.type.mpType === "app") {
  3876. currentInstance.appContext.app.provide(key, value);
  3877. }
  3878. }
  3879. }
  3880. function inject(key, defaultValue, treatDefaultAsFactory = false) {
  3881. const instance = currentInstance || currentRenderingInstance;
  3882. if (instance || currentApp) {
  3883. const provides = instance ? instance.parent == null ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : currentApp._context.provides;
  3884. if (provides && key in provides) {
  3885. return provides[key];
  3886. } else if (arguments.length > 1) {
  3887. return treatDefaultAsFactory && isFunction(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue;
  3888. } else {
  3889. warn$1(`injection "${String(key)}" not found.`);
  3890. }
  3891. } else {
  3892. warn$1(`inject() can only be used inside setup() or functional components.`);
  3893. }
  3894. }
  3895. const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
  3896. function onActivated(hook, target) {
  3897. registerKeepAliveHook(hook, "a", target);
  3898. }
  3899. function onDeactivated(hook, target) {
  3900. registerKeepAliveHook(hook, "da", target);
  3901. }
  3902. function registerKeepAliveHook(hook, type, target = currentInstance) {
  3903. const wrappedHook = hook.__wdc || (hook.__wdc = () => {
  3904. let current = target;
  3905. while (current) {
  3906. if (current.isDeactivated) {
  3907. return;
  3908. }
  3909. current = current.parent;
  3910. }
  3911. return hook();
  3912. });
  3913. injectHook(type, wrappedHook, target);
  3914. if (target) {
  3915. let current = target.parent;
  3916. while (current && current.parent) {
  3917. if (isKeepAlive(current.parent.vnode)) {
  3918. injectToKeepAliveRoot(wrappedHook, type, target, current);
  3919. }
  3920. current = current.parent;
  3921. }
  3922. }
  3923. }
  3924. function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
  3925. const injected = injectHook(
  3926. type,
  3927. hook,
  3928. keepAliveRoot,
  3929. true
  3930. /* prepend */
  3931. );
  3932. onUnmounted(() => {
  3933. remove(keepAliveRoot[type], injected);
  3934. }, target);
  3935. }
  3936. function injectHook(type, hook, target = currentInstance, prepend = false) {
  3937. if (target) {
  3938. if (isRootHook(type)) {
  3939. target = target.root;
  3940. }
  3941. const hooks = target[type] || (target[type] = []);
  3942. const wrappedHook = hook.__weh || (hook.__weh = (...args) => {
  3943. if (target.isUnmounted) {
  3944. return;
  3945. }
  3946. pauseTracking();
  3947. const reset = setCurrentInstance(target);
  3948. const res = callWithAsyncErrorHandling(hook, target, type, args);
  3949. reset();
  3950. resetTracking();
  3951. return res;
  3952. });
  3953. if (prepend) {
  3954. hooks.unshift(wrappedHook);
  3955. } else {
  3956. hooks.push(wrappedHook);
  3957. }
  3958. return wrappedHook;
  3959. } else {
  3960. const apiName = toHandlerKey(
  3961. (ErrorTypeStrings[type] || type.replace(/^on/, "")).replace(/ hook$/, "")
  3962. );
  3963. warn$1(
  3964. `${apiName} is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup().`
  3965. );
  3966. }
  3967. }
  3968. const createHook = (lifecycle) => (hook, target = currentInstance) => (
  3969. // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
  3970. (!isInSSRComponentSetup || lifecycle === "sp") && injectHook(lifecycle, (...args) => hook(...args), target)
  3971. );
  3972. const onBeforeMount = createHook("bm");
  3973. const onMounted = createHook("m");
  3974. const onBeforeUpdate = createHook("bu");
  3975. const onUpdated = createHook("u");
  3976. const onBeforeUnmount = createHook("bum");
  3977. const onUnmounted = createHook("um");
  3978. const onServerPrefetch = createHook("sp");
  3979. const onRenderTriggered = createHook(
  3980. "rtg"
  3981. );
  3982. const onRenderTracked = createHook(
  3983. "rtc"
  3984. );
  3985. function onErrorCaptured(hook, target = currentInstance) {
  3986. injectHook("ec", hook, target);
  3987. }
  3988. const getPublicInstance = (i2) => {
  3989. if (!i2)
  3990. return null;
  3991. if (isStatefulComponent(i2))
  3992. return getExposeProxy(i2) || i2.proxy;
  3993. return getPublicInstance(i2.parent);
  3994. };
  3995. function getComponentInternalInstance(i2) {
  3996. return i2;
  3997. }
  3998. const publicPropertiesMap = (
  3999. // Move PURE marker to new line to workaround compiler discarding it
  4000. // due to type annotation
  4001. /* @__PURE__ */ extend(/* @__PURE__ */ Object.create(null), {
  4002. // fixed by xxxxxx
  4003. $: getComponentInternalInstance,
  4004. // fixed by xxxxxx vue-i18n 在 dev 模式,访问了 $el,故模拟一个假的
  4005. // $el: i => i.vnode.el,
  4006. $el: (i2) => i2.__$el || (i2.__$el = {}),
  4007. $data: (i2) => i2.data,
  4008. $props: (i2) => shallowReadonly(i2.props),
  4009. $attrs: (i2) => shallowReadonly(i2.attrs),
  4010. $slots: (i2) => shallowReadonly(i2.slots),
  4011. $refs: (i2) => shallowReadonly(i2.refs),
  4012. $parent: (i2) => getPublicInstance(i2.parent),
  4013. $root: (i2) => getPublicInstance(i2.root),
  4014. $emit: (i2) => i2.emit,
  4015. $options: (i2) => resolveMergedOptions(i2),
  4016. $forceUpdate: (i2) => i2.f || (i2.f = () => {
  4017. i2.effect.dirty = true;
  4018. queueJob(i2.update);
  4019. }),
  4020. // $nextTick: i => i.n || (i.n = nextTick.bind(i.proxy!)),// fixed by xxxxxx
  4021. $watch: (i2) => instanceWatch.bind(i2)
  4022. })
  4023. );
  4024. const isReservedPrefix = (key) => key === "_" || key === "$";
  4025. const hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key);
  4026. const PublicInstanceProxyHandlers = {
  4027. get({ _: instance }, key) {
  4028. const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
  4029. if (key === "__isVue") {
  4030. return true;
  4031. }
  4032. let normalizedProps;
  4033. if (key[0] !== "$") {
  4034. const n2 = accessCache[key];
  4035. if (n2 !== void 0) {
  4036. switch (n2) {
  4037. case 1:
  4038. return setupState[key];
  4039. case 2:
  4040. return data[key];
  4041. case 4:
  4042. return ctx[key];
  4043. case 3:
  4044. return props[key];
  4045. }
  4046. } else if (hasSetupBinding(setupState, key)) {
  4047. accessCache[key] = 1;
  4048. return setupState[key];
  4049. } else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  4050. accessCache[key] = 2;
  4051. return data[key];
  4052. } else if (
  4053. // only cache other properties when instance has declared (thus stable)
  4054. // props
  4055. (normalizedProps = instance.propsOptions[0]) && hasOwn(normalizedProps, key)
  4056. ) {
  4057. accessCache[key] = 3;
  4058. return props[key];
  4059. } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  4060. accessCache[key] = 4;
  4061. return ctx[key];
  4062. } else if (shouldCacheAccess) {
  4063. accessCache[key] = 0;
  4064. }
  4065. }
  4066. const publicGetter = publicPropertiesMap[key];
  4067. let cssModule, globalProperties;
  4068. if (publicGetter) {
  4069. if (key === "$attrs") {
  4070. track(instance, "get", key);
  4071. } else if (key === "$slots") {
  4072. track(instance, "get", key);
  4073. }
  4074. return publicGetter(instance);
  4075. } else if (
  4076. // css module (injected by vue-loader)
  4077. (cssModule = type.__cssModules) && (cssModule = cssModule[key])
  4078. ) {
  4079. return cssModule;
  4080. } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  4081. accessCache[key] = 4;
  4082. return ctx[key];
  4083. } else if (
  4084. // global properties
  4085. globalProperties = appContext.config.globalProperties, hasOwn(globalProperties, key)
  4086. ) {
  4087. {
  4088. return globalProperties[key];
  4089. }
  4090. } else if (currentRenderingInstance && (!isString(key) || // #1091 avoid internal isRef/isVNode checks on component instance leading
  4091. // to infinite warning loop
  4092. key.indexOf("__v") !== 0)) {
  4093. if (data !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn(data, key)) {
  4094. warn$1(
  4095. `Property ${JSON.stringify(
  4096. key
  4097. )} must be accessed via $data because it starts with a reserved character ("$" or "_") and is not proxied on the render context.`
  4098. );
  4099. } else if (instance === currentRenderingInstance) {
  4100. warn$1(
  4101. `Property ${JSON.stringify(key)} was accessed during render but is not defined on instance.`
  4102. );
  4103. }
  4104. }
  4105. },
  4106. set({ _: instance }, key, value) {
  4107. const { data, setupState, ctx } = instance;
  4108. if (hasSetupBinding(setupState, key)) {
  4109. setupState[key] = value;
  4110. return true;
  4111. } else if (setupState.__isScriptSetup && hasOwn(setupState, key)) {
  4112. warn$1(`Cannot mutate <script setup> binding "${key}" from Options API.`);
  4113. return false;
  4114. } else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  4115. data[key] = value;
  4116. return true;
  4117. } else if (hasOwn(instance.props, key)) {
  4118. warn$1(`Attempting to mutate prop "${key}". Props are readonly.`);
  4119. return false;
  4120. }
  4121. if (key[0] === "$" && key.slice(1) in instance) {
  4122. warn$1(
  4123. `Attempting to mutate public property "${key}". Properties starting with $ are reserved and readonly.`
  4124. );
  4125. return false;
  4126. } else {
  4127. if (key in instance.appContext.config.globalProperties) {
  4128. Object.defineProperty(ctx, key, {
  4129. enumerable: true,
  4130. configurable: true,
  4131. value
  4132. });
  4133. } else {
  4134. ctx[key] = value;
  4135. }
  4136. }
  4137. return true;
  4138. },
  4139. has({
  4140. _: { data, setupState, accessCache, ctx, appContext, propsOptions }
  4141. }, key) {
  4142. let normalizedProps;
  4143. return !!accessCache[key] || data !== EMPTY_OBJ && hasOwn(data, key) || hasSetupBinding(setupState, key) || (normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key) || hasOwn(ctx, key) || hasOwn(publicPropertiesMap, key) || hasOwn(appContext.config.globalProperties, key);
  4144. },
  4145. defineProperty(target, key, descriptor) {
  4146. if (descriptor.get != null) {
  4147. target._.accessCache[key] = 0;
  4148. } else if (hasOwn(descriptor, "value")) {
  4149. this.set(target, key, descriptor.value, null);
  4150. }
  4151. return Reflect.defineProperty(target, key, descriptor);
  4152. }
  4153. };
  4154. {
  4155. PublicInstanceProxyHandlers.ownKeys = (target) => {
  4156. warn$1(
  4157. `Avoid app logic that relies on enumerating keys on a component instance. The keys will be empty in production mode to avoid performance overhead.`
  4158. );
  4159. return Reflect.ownKeys(target);
  4160. };
  4161. }
  4162. function createDevRenderContext(instance) {
  4163. const target = {};
  4164. Object.defineProperty(target, `_`, {
  4165. configurable: true,
  4166. enumerable: false,
  4167. get: () => instance
  4168. });
  4169. Object.keys(publicPropertiesMap).forEach((key) => {
  4170. Object.defineProperty(target, key, {
  4171. configurable: true,
  4172. enumerable: false,
  4173. get: () => publicPropertiesMap[key](instance),
  4174. // intercepted by the proxy so no need for implementation,
  4175. // but needed to prevent set errors
  4176. set: NOOP
  4177. });
  4178. });
  4179. return target;
  4180. }
  4181. function exposePropsOnRenderContext(instance) {
  4182. const {
  4183. ctx,
  4184. propsOptions: [propsOptions]
  4185. } = instance;
  4186. if (propsOptions) {
  4187. Object.keys(propsOptions).forEach((key) => {
  4188. Object.defineProperty(ctx, key, {
  4189. enumerable: true,
  4190. configurable: true,
  4191. get: () => instance.props[key],
  4192. set: NOOP
  4193. });
  4194. });
  4195. }
  4196. }
  4197. function exposeSetupStateOnRenderContext(instance) {
  4198. const { ctx, setupState } = instance;
  4199. Object.keys(toRaw(setupState)).forEach((key) => {
  4200. if (!setupState.__isScriptSetup) {
  4201. if (isReservedPrefix(key[0])) {
  4202. warn$1(
  4203. `setup() return property ${JSON.stringify(
  4204. key
  4205. )} should not start with "$" or "_" which are reserved prefixes for Vue internals.`
  4206. );
  4207. return;
  4208. }
  4209. Object.defineProperty(ctx, key, {
  4210. enumerable: true,
  4211. configurable: true,
  4212. get: () => setupState[key],
  4213. set: NOOP
  4214. });
  4215. }
  4216. });
  4217. }
  4218. function normalizePropsOrEmits(props) {
  4219. return isArray(props) ? props.reduce(
  4220. (normalized, p2) => (normalized[p2] = null, normalized),
  4221. {}
  4222. ) : props;
  4223. }
  4224. function createDuplicateChecker() {
  4225. const cache = /* @__PURE__ */ Object.create(null);
  4226. return (type, key) => {
  4227. if (cache[key]) {
  4228. warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
  4229. } else {
  4230. cache[key] = type;
  4231. }
  4232. };
  4233. }
  4234. let shouldCacheAccess = true;
  4235. function applyOptions$1(instance) {
  4236. const options = resolveMergedOptions(instance);
  4237. const publicThis = instance.proxy;
  4238. const ctx = instance.ctx;
  4239. shouldCacheAccess = false;
  4240. if (options.beforeCreate) {
  4241. callHook$1(options.beforeCreate, instance, "bc");
  4242. }
  4243. const {
  4244. // state
  4245. data: dataOptions,
  4246. computed: computedOptions,
  4247. methods,
  4248. watch: watchOptions,
  4249. provide: provideOptions,
  4250. inject: injectOptions,
  4251. // lifecycle
  4252. created,
  4253. beforeMount,
  4254. mounted,
  4255. beforeUpdate,
  4256. updated,
  4257. activated,
  4258. deactivated,
  4259. beforeDestroy,
  4260. beforeUnmount,
  4261. destroyed,
  4262. unmounted,
  4263. render,
  4264. renderTracked,
  4265. renderTriggered,
  4266. errorCaptured,
  4267. serverPrefetch,
  4268. // public API
  4269. expose,
  4270. inheritAttrs,
  4271. // assets
  4272. components,
  4273. directives,
  4274. filters
  4275. } = options;
  4276. const checkDuplicateProperties = createDuplicateChecker();
  4277. {
  4278. const [propsOptions] = instance.propsOptions;
  4279. if (propsOptions) {
  4280. for (const key in propsOptions) {
  4281. checkDuplicateProperties("Props", key);
  4282. }
  4283. }
  4284. }
  4285. function initInjections() {
  4286. if (injectOptions) {
  4287. resolveInjections(injectOptions, ctx, checkDuplicateProperties);
  4288. }
  4289. }
  4290. {
  4291. initInjections();
  4292. }
  4293. if (methods) {
  4294. for (const key in methods) {
  4295. const methodHandler = methods[key];
  4296. if (isFunction(methodHandler)) {
  4297. {
  4298. Object.defineProperty(ctx, key, {
  4299. value: methodHandler.bind(publicThis),
  4300. configurable: true,
  4301. enumerable: true,
  4302. writable: true
  4303. });
  4304. }
  4305. {
  4306. checkDuplicateProperties("Methods", key);
  4307. }
  4308. } else {
  4309. warn$1(
  4310. `Method "${key}" has type "${typeof methodHandler}" in the component definition. Did you reference the function correctly?`
  4311. );
  4312. }
  4313. }
  4314. }
  4315. if (dataOptions) {
  4316. if (!isFunction(dataOptions)) {
  4317. warn$1(
  4318. `The data option must be a function. Plain object usage is no longer supported.`
  4319. );
  4320. }
  4321. const data = dataOptions.call(publicThis, publicThis);
  4322. if (isPromise$2(data)) {
  4323. warn$1(
  4324. `data() returned a Promise - note data() cannot be async; If you intend to perform data fetching before component renders, use async setup() + <Suspense>.`
  4325. );
  4326. }
  4327. if (!isObject$1(data)) {
  4328. warn$1(`data() should return an object.`);
  4329. } else {
  4330. instance.data = reactive(data);
  4331. {
  4332. for (const key in data) {
  4333. checkDuplicateProperties("Data", key);
  4334. if (!isReservedPrefix(key[0])) {
  4335. Object.defineProperty(ctx, key, {
  4336. configurable: true,
  4337. enumerable: true,
  4338. get: () => data[key],
  4339. set: NOOP
  4340. });
  4341. }
  4342. }
  4343. }
  4344. }
  4345. }
  4346. shouldCacheAccess = true;
  4347. if (computedOptions) {
  4348. for (const key in computedOptions) {
  4349. const opt = computedOptions[key];
  4350. const get22 = isFunction(opt) ? opt.bind(publicThis, publicThis) : isFunction(opt.get) ? opt.get.bind(publicThis, publicThis) : NOOP;
  4351. if (get22 === NOOP) {
  4352. warn$1(`Computed property "${key}" has no getter.`);
  4353. }
  4354. const set2 = !isFunction(opt) && isFunction(opt.set) ? opt.set.bind(publicThis) : () => {
  4355. warn$1(
  4356. `Write operation failed: computed property "${key}" is readonly.`
  4357. );
  4358. };
  4359. const c2 = computed({
  4360. get: get22,
  4361. set: set2
  4362. });
  4363. Object.defineProperty(ctx, key, {
  4364. enumerable: true,
  4365. configurable: true,
  4366. get: () => c2.value,
  4367. set: (v2) => c2.value = v2
  4368. });
  4369. {
  4370. checkDuplicateProperties("Computed", key);
  4371. }
  4372. }
  4373. }
  4374. if (watchOptions) {
  4375. for (const key in watchOptions) {
  4376. createWatcher(watchOptions[key], ctx, publicThis, key);
  4377. }
  4378. }
  4379. function initProvides() {
  4380. if (provideOptions) {
  4381. const provides = isFunction(provideOptions) ? provideOptions.call(publicThis) : provideOptions;
  4382. Reflect.ownKeys(provides).forEach((key) => {
  4383. provide(key, provides[key]);
  4384. });
  4385. }
  4386. }
  4387. {
  4388. initProvides();
  4389. }
  4390. {
  4391. if (created) {
  4392. callHook$1(created, instance, "c");
  4393. }
  4394. }
  4395. function registerLifecycleHook(register2, hook) {
  4396. if (isArray(hook)) {
  4397. hook.forEach((_hook) => register2(_hook.bind(publicThis)));
  4398. } else if (hook) {
  4399. register2(hook.bind(publicThis));
  4400. }
  4401. }
  4402. registerLifecycleHook(onBeforeMount, beforeMount);
  4403. registerLifecycleHook(onMounted, mounted);
  4404. registerLifecycleHook(onBeforeUpdate, beforeUpdate);
  4405. registerLifecycleHook(onUpdated, updated);
  4406. registerLifecycleHook(onActivated, activated);
  4407. registerLifecycleHook(onDeactivated, deactivated);
  4408. registerLifecycleHook(onErrorCaptured, errorCaptured);
  4409. registerLifecycleHook(onRenderTracked, renderTracked);
  4410. registerLifecycleHook(onRenderTriggered, renderTriggered);
  4411. registerLifecycleHook(onBeforeUnmount, beforeUnmount);
  4412. registerLifecycleHook(onUnmounted, unmounted);
  4413. registerLifecycleHook(onServerPrefetch, serverPrefetch);
  4414. if (isArray(expose)) {
  4415. if (expose.length) {
  4416. const exposed = instance.exposed || (instance.exposed = {});
  4417. expose.forEach((key) => {
  4418. Object.defineProperty(exposed, key, {
  4419. get: () => publicThis[key],
  4420. set: (val) => publicThis[key] = val
  4421. });
  4422. });
  4423. } else if (!instance.exposed) {
  4424. instance.exposed = {};
  4425. }
  4426. }
  4427. if (render && instance.render === NOOP) {
  4428. instance.render = render;
  4429. }
  4430. if (inheritAttrs != null) {
  4431. instance.inheritAttrs = inheritAttrs;
  4432. }
  4433. if (components)
  4434. instance.components = components;
  4435. if (directives)
  4436. instance.directives = directives;
  4437. if (instance.ctx.$onApplyOptions) {
  4438. instance.ctx.$onApplyOptions(options, instance, publicThis);
  4439. }
  4440. }
  4441. function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP) {
  4442. if (isArray(injectOptions)) {
  4443. injectOptions = normalizeInject(injectOptions);
  4444. }
  4445. for (const key in injectOptions) {
  4446. const opt = injectOptions[key];
  4447. let injected;
  4448. if (isObject$1(opt)) {
  4449. if ("default" in opt) {
  4450. injected = inject(
  4451. opt.from || key,
  4452. opt.default,
  4453. true
  4454. );
  4455. } else {
  4456. injected = inject(opt.from || key);
  4457. }
  4458. } else {
  4459. injected = inject(opt);
  4460. }
  4461. if (isRef(injected)) {
  4462. Object.defineProperty(ctx, key, {
  4463. enumerable: true,
  4464. configurable: true,
  4465. get: () => injected.value,
  4466. set: (v2) => injected.value = v2
  4467. });
  4468. } else {
  4469. ctx[key] = injected;
  4470. }
  4471. {
  4472. checkDuplicateProperties("Inject", key);
  4473. }
  4474. }
  4475. }
  4476. function callHook$1(hook, instance, type) {
  4477. callWithAsyncErrorHandling(
  4478. isArray(hook) ? hook.map((h2) => h2.bind(instance.proxy)) : hook.bind(instance.proxy),
  4479. instance,
  4480. type
  4481. );
  4482. }
  4483. function createWatcher(raw, ctx, publicThis, key) {
  4484. const getter = key.includes(".") ? createPathGetter(publicThis, key) : () => publicThis[key];
  4485. if (isString(raw)) {
  4486. const handler = ctx[raw];
  4487. if (isFunction(handler)) {
  4488. watch(getter, handler);
  4489. } else {
  4490. warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
  4491. }
  4492. } else if (isFunction(raw)) {
  4493. watch(getter, raw.bind(publicThis));
  4494. } else if (isObject$1(raw)) {
  4495. if (isArray(raw)) {
  4496. raw.forEach((r2) => createWatcher(r2, ctx, publicThis, key));
  4497. } else {
  4498. const handler = isFunction(raw.handler) ? raw.handler.bind(publicThis) : ctx[raw.handler];
  4499. if (isFunction(handler)) {
  4500. watch(getter, handler, raw);
  4501. } else {
  4502. warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
  4503. }
  4504. }
  4505. } else {
  4506. warn$1(`Invalid watch option: "${key}"`, raw);
  4507. }
  4508. }
  4509. function resolveMergedOptions(instance) {
  4510. const base = instance.type;
  4511. const { mixins, extends: extendsOptions } = base;
  4512. const {
  4513. mixins: globalMixins,
  4514. optionsCache: cache,
  4515. config: { optionMergeStrategies }
  4516. } = instance.appContext;
  4517. const cached = cache.get(base);
  4518. let resolved;
  4519. if (cached) {
  4520. resolved = cached;
  4521. } else if (!globalMixins.length && !mixins && !extendsOptions) {
  4522. {
  4523. resolved = base;
  4524. }
  4525. } else {
  4526. resolved = {};
  4527. if (globalMixins.length) {
  4528. globalMixins.forEach(
  4529. (m2) => mergeOptions(resolved, m2, optionMergeStrategies, true)
  4530. );
  4531. }
  4532. mergeOptions(resolved, base, optionMergeStrategies);
  4533. }
  4534. if (isObject$1(base)) {
  4535. cache.set(base, resolved);
  4536. }
  4537. return resolved;
  4538. }
  4539. function mergeOptions(to, from, strats, asMixin = false) {
  4540. const { mixins, extends: extendsOptions } = from;
  4541. if (extendsOptions) {
  4542. mergeOptions(to, extendsOptions, strats, true);
  4543. }
  4544. if (mixins) {
  4545. mixins.forEach(
  4546. (m2) => mergeOptions(to, m2, strats, true)
  4547. );
  4548. }
  4549. for (const key in from) {
  4550. if (asMixin && key === "expose") {
  4551. warn$1(
  4552. `"expose" option is ignored when declared in mixins or extends. It should only be declared in the base component itself.`
  4553. );
  4554. } else {
  4555. const strat = internalOptionMergeStrats[key] || strats && strats[key];
  4556. to[key] = strat ? strat(to[key], from[key]) : from[key];
  4557. }
  4558. }
  4559. return to;
  4560. }
  4561. const internalOptionMergeStrats = {
  4562. data: mergeDataFn,
  4563. props: mergeEmitsOrPropsOptions,
  4564. emits: mergeEmitsOrPropsOptions,
  4565. // objects
  4566. methods: mergeObjectOptions,
  4567. computed: mergeObjectOptions,
  4568. // lifecycle
  4569. beforeCreate: mergeAsArray$1,
  4570. created: mergeAsArray$1,
  4571. beforeMount: mergeAsArray$1,
  4572. mounted: mergeAsArray$1,
  4573. beforeUpdate: mergeAsArray$1,
  4574. updated: mergeAsArray$1,
  4575. beforeDestroy: mergeAsArray$1,
  4576. beforeUnmount: mergeAsArray$1,
  4577. destroyed: mergeAsArray$1,
  4578. unmounted: mergeAsArray$1,
  4579. activated: mergeAsArray$1,
  4580. deactivated: mergeAsArray$1,
  4581. errorCaptured: mergeAsArray$1,
  4582. serverPrefetch: mergeAsArray$1,
  4583. // assets
  4584. components: mergeObjectOptions,
  4585. directives: mergeObjectOptions,
  4586. // watch
  4587. watch: mergeWatchOptions,
  4588. // provide / inject
  4589. provide: mergeDataFn,
  4590. inject: mergeInject
  4591. };
  4592. function mergeDataFn(to, from) {
  4593. if (!from) {
  4594. return to;
  4595. }
  4596. if (!to) {
  4597. return from;
  4598. }
  4599. return function mergedDataFn() {
  4600. return extend(
  4601. isFunction(to) ? to.call(this, this) : to,
  4602. isFunction(from) ? from.call(this, this) : from
  4603. );
  4604. };
  4605. }
  4606. function mergeInject(to, from) {
  4607. return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
  4608. }
  4609. function normalizeInject(raw) {
  4610. if (isArray(raw)) {
  4611. const res = {};
  4612. for (let i2 = 0; i2 < raw.length; i2++) {
  4613. res[raw[i2]] = raw[i2];
  4614. }
  4615. return res;
  4616. }
  4617. return raw;
  4618. }
  4619. function mergeAsArray$1(to, from) {
  4620. return to ? [...new Set([].concat(to, from))] : from;
  4621. }
  4622. function mergeObjectOptions(to, from) {
  4623. return to ? extend(/* @__PURE__ */ Object.create(null), to, from) : from;
  4624. }
  4625. function mergeEmitsOrPropsOptions(to, from) {
  4626. if (to) {
  4627. if (isArray(to) && isArray(from)) {
  4628. return [.../* @__PURE__ */ new Set([...to, ...from])];
  4629. }
  4630. return extend(
  4631. /* @__PURE__ */ Object.create(null),
  4632. normalizePropsOrEmits(to),
  4633. normalizePropsOrEmits(from != null ? from : {})
  4634. );
  4635. } else {
  4636. return from;
  4637. }
  4638. }
  4639. function mergeWatchOptions(to, from) {
  4640. if (!to)
  4641. return from;
  4642. if (!from)
  4643. return to;
  4644. const merged = extend(/* @__PURE__ */ Object.create(null), to);
  4645. for (const key in from) {
  4646. merged[key] = mergeAsArray$1(to[key], from[key]);
  4647. }
  4648. return merged;
  4649. }
  4650. function initProps$1(instance, rawProps, isStateful, isSSR = false) {
  4651. const props = {};
  4652. const attrs = {};
  4653. instance.propsDefaults = /* @__PURE__ */ Object.create(null);
  4654. setFullProps(instance, rawProps, props, attrs);
  4655. for (const key in instance.propsOptions[0]) {
  4656. if (!(key in props)) {
  4657. props[key] = void 0;
  4658. }
  4659. }
  4660. {
  4661. validateProps(rawProps || {}, props, instance);
  4662. }
  4663. if (isStateful) {
  4664. instance.props = isSSR ? props : shallowReactive(props);
  4665. } else {
  4666. if (!instance.type.props) {
  4667. instance.props = attrs;
  4668. } else {
  4669. instance.props = props;
  4670. }
  4671. }
  4672. instance.attrs = attrs;
  4673. }
  4674. function isInHmrContext(instance) {
  4675. }
  4676. function updateProps(instance, rawProps, rawPrevProps, optimized) {
  4677. const {
  4678. props,
  4679. attrs,
  4680. vnode: { patchFlag }
  4681. } = instance;
  4682. const rawCurrentProps = toRaw(props);
  4683. const [options] = instance.propsOptions;
  4684. let hasAttrsChanged = false;
  4685. if (
  4686. // always force full diff in dev
  4687. // - #1942 if hmr is enabled with sfc component
  4688. // - vite#872 non-sfc component used by sfc component
  4689. !isInHmrContext() && (optimized || patchFlag > 0) && !(patchFlag & 16)
  4690. ) {
  4691. if (patchFlag & 8) {
  4692. const propsToUpdate = instance.vnode.dynamicProps;
  4693. for (let i2 = 0; i2 < propsToUpdate.length; i2++) {
  4694. let key = propsToUpdate[i2];
  4695. if (isEmitListener(instance.emitsOptions, key)) {
  4696. continue;
  4697. }
  4698. const value = rawProps[key];
  4699. if (options) {
  4700. if (hasOwn(attrs, key)) {
  4701. if (value !== attrs[key]) {
  4702. attrs[key] = value;
  4703. hasAttrsChanged = true;
  4704. }
  4705. } else {
  4706. const camelizedKey = camelize(key);
  4707. props[camelizedKey] = resolvePropValue$1(
  4708. options,
  4709. rawCurrentProps,
  4710. camelizedKey,
  4711. value,
  4712. instance,
  4713. false
  4714. );
  4715. }
  4716. } else {
  4717. if (value !== attrs[key]) {
  4718. attrs[key] = value;
  4719. hasAttrsChanged = true;
  4720. }
  4721. }
  4722. }
  4723. }
  4724. } else {
  4725. if (setFullProps(instance, rawProps, props, attrs)) {
  4726. hasAttrsChanged = true;
  4727. }
  4728. let kebabKey;
  4729. for (const key in rawCurrentProps) {
  4730. if (!rawProps || // for camelCase
  4731. !hasOwn(rawProps, key) && // it's possible the original props was passed in as kebab-case
  4732. // and converted to camelCase (#955)
  4733. ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey))) {
  4734. if (options) {
  4735. if (rawPrevProps && // for camelCase
  4736. (rawPrevProps[key] !== void 0 || // for kebab-case
  4737. rawPrevProps[kebabKey] !== void 0)) {
  4738. props[key] = resolvePropValue$1(
  4739. options,
  4740. rawCurrentProps,
  4741. key,
  4742. void 0,
  4743. instance,
  4744. true
  4745. );
  4746. }
  4747. } else {
  4748. delete props[key];
  4749. }
  4750. }
  4751. }
  4752. if (attrs !== rawCurrentProps) {
  4753. for (const key in attrs) {
  4754. if (!rawProps || !hasOwn(rawProps, key) && true) {
  4755. delete attrs[key];
  4756. hasAttrsChanged = true;
  4757. }
  4758. }
  4759. }
  4760. }
  4761. if (hasAttrsChanged) {
  4762. trigger(instance, "set", "$attrs");
  4763. }
  4764. {
  4765. validateProps(rawProps || {}, props, instance);
  4766. }
  4767. }
  4768. function setFullProps(instance, rawProps, props, attrs) {
  4769. const [options, needCastKeys] = instance.propsOptions;
  4770. let hasAttrsChanged = false;
  4771. let rawCastValues;
  4772. if (rawProps) {
  4773. for (let key in rawProps) {
  4774. if (isReservedProp(key)) {
  4775. continue;
  4776. }
  4777. const value = rawProps[key];
  4778. let camelKey;
  4779. if (options && hasOwn(options, camelKey = camelize(key))) {
  4780. if (!needCastKeys || !needCastKeys.includes(camelKey)) {
  4781. props[camelKey] = value;
  4782. } else {
  4783. (rawCastValues || (rawCastValues = {}))[camelKey] = value;
  4784. }
  4785. } else if (!isEmitListener(instance.emitsOptions, key)) {
  4786. if (!(key in attrs) || value !== attrs[key]) {
  4787. attrs[key] = value;
  4788. hasAttrsChanged = true;
  4789. }
  4790. }
  4791. }
  4792. }
  4793. if (needCastKeys) {
  4794. const rawCurrentProps = toRaw(props);
  4795. const castValues = rawCastValues || EMPTY_OBJ;
  4796. for (let i2 = 0; i2 < needCastKeys.length; i2++) {
  4797. const key = needCastKeys[i2];
  4798. props[key] = resolvePropValue$1(
  4799. options,
  4800. rawCurrentProps,
  4801. key,
  4802. castValues[key],
  4803. instance,
  4804. !hasOwn(castValues, key)
  4805. );
  4806. }
  4807. }
  4808. return hasAttrsChanged;
  4809. }
  4810. function resolvePropValue$1(options, props, key, value, instance, isAbsent) {
  4811. const opt = options[key];
  4812. if (opt != null) {
  4813. const hasDefault = hasOwn(opt, "default");
  4814. if (hasDefault && value === void 0) {
  4815. const defaultValue = opt.default;
  4816. if (opt.type !== Function && !opt.skipFactory && isFunction(defaultValue)) {
  4817. const { propsDefaults } = instance;
  4818. if (key in propsDefaults) {
  4819. value = propsDefaults[key];
  4820. } else {
  4821. const reset = setCurrentInstance(instance);
  4822. value = propsDefaults[key] = defaultValue.call(
  4823. null,
  4824. props
  4825. );
  4826. reset();
  4827. }
  4828. } else {
  4829. value = defaultValue;
  4830. }
  4831. }
  4832. if (opt[
  4833. 0
  4834. /* shouldCast */
  4835. ]) {
  4836. if (isAbsent && !hasDefault) {
  4837. value = false;
  4838. } else if (opt[
  4839. 1
  4840. /* shouldCastTrue */
  4841. ] && (value === "" || value === hyphenate(key))) {
  4842. value = true;
  4843. }
  4844. }
  4845. }
  4846. return value;
  4847. }
  4848. function normalizePropsOptions(comp, appContext, asMixin = false) {
  4849. const cache = appContext.propsCache;
  4850. const cached = cache.get(comp);
  4851. if (cached) {
  4852. return cached;
  4853. }
  4854. const raw = comp.props;
  4855. const normalized = {};
  4856. const needCastKeys = [];
  4857. let hasExtends = false;
  4858. if (!isFunction(comp)) {
  4859. const extendProps = (raw2) => {
  4860. hasExtends = true;
  4861. const [props, keys] = normalizePropsOptions(raw2, appContext, true);
  4862. extend(normalized, props);
  4863. if (keys)
  4864. needCastKeys.push(...keys);
  4865. };
  4866. if (!asMixin && appContext.mixins.length) {
  4867. appContext.mixins.forEach(extendProps);
  4868. }
  4869. if (comp.extends) {
  4870. extendProps(comp.extends);
  4871. }
  4872. if (comp.mixins) {
  4873. comp.mixins.forEach(extendProps);
  4874. }
  4875. }
  4876. if (!raw && !hasExtends) {
  4877. if (isObject$1(comp)) {
  4878. cache.set(comp, EMPTY_ARR);
  4879. }
  4880. return EMPTY_ARR;
  4881. }
  4882. if (isArray(raw)) {
  4883. for (let i2 = 0; i2 < raw.length; i2++) {
  4884. if (!isString(raw[i2])) {
  4885. warn$1(`props must be strings when using array syntax.`, raw[i2]);
  4886. }
  4887. const normalizedKey = camelize(raw[i2]);
  4888. if (validatePropName(normalizedKey)) {
  4889. normalized[normalizedKey] = EMPTY_OBJ;
  4890. }
  4891. }
  4892. } else if (raw) {
  4893. if (!isObject$1(raw)) {
  4894. warn$1(`invalid props options`, raw);
  4895. }
  4896. for (const key in raw) {
  4897. const normalizedKey = camelize(key);
  4898. if (validatePropName(normalizedKey)) {
  4899. const opt = raw[key];
  4900. const prop = normalized[normalizedKey] = isArray(opt) || isFunction(opt) ? { type: opt } : extend({}, opt);
  4901. if (prop) {
  4902. const booleanIndex = getTypeIndex(Boolean, prop.type);
  4903. const stringIndex = getTypeIndex(String, prop.type);
  4904. prop[
  4905. 0
  4906. /* shouldCast */
  4907. ] = booleanIndex > -1;
  4908. prop[
  4909. 1
  4910. /* shouldCastTrue */
  4911. ] = stringIndex < 0 || booleanIndex < stringIndex;
  4912. if (booleanIndex > -1 || hasOwn(prop, "default")) {
  4913. needCastKeys.push(normalizedKey);
  4914. }
  4915. }
  4916. }
  4917. }
  4918. }
  4919. const res = [normalized, needCastKeys];
  4920. if (isObject$1(comp)) {
  4921. cache.set(comp, res);
  4922. }
  4923. return res;
  4924. }
  4925. function validatePropName(key) {
  4926. if (key[0] !== "$" && !isReservedProp(key)) {
  4927. return true;
  4928. } else {
  4929. warn$1(`Invalid prop name: "${key}" is a reserved property.`);
  4930. }
  4931. return false;
  4932. }
  4933. function getType(ctor) {
  4934. if (ctor === null) {
  4935. return "null";
  4936. }
  4937. if (typeof ctor === "function") {
  4938. return ctor.name || "";
  4939. } else if (typeof ctor === "object") {
  4940. const name = ctor.constructor && ctor.constructor.name;
  4941. return name || "";
  4942. }
  4943. return "";
  4944. }
  4945. function isSameType(a2, b2) {
  4946. return getType(a2) === getType(b2);
  4947. }
  4948. function getTypeIndex(type, expectedTypes) {
  4949. if (isArray(expectedTypes)) {
  4950. return expectedTypes.findIndex((t2) => isSameType(t2, type));
  4951. } else if (isFunction(expectedTypes)) {
  4952. return isSameType(expectedTypes, type) ? 0 : -1;
  4953. }
  4954. return -1;
  4955. }
  4956. function validateProps(rawProps, props, instance) {
  4957. const resolvedValues = toRaw(props);
  4958. const options = instance.propsOptions[0];
  4959. for (const key in options) {
  4960. let opt = options[key];
  4961. if (opt == null)
  4962. continue;
  4963. validateProp(
  4964. key,
  4965. resolvedValues[key],
  4966. opt,
  4967. shallowReadonly(resolvedValues),
  4968. !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key))
  4969. );
  4970. }
  4971. }
  4972. function validateProp(name, value, prop, props, isAbsent) {
  4973. const { type, required, validator, skipCheck } = prop;
  4974. if (required && isAbsent) {
  4975. warn$1('Missing required prop: "' + name + '"');
  4976. return;
  4977. }
  4978. if (value == null && !required) {
  4979. return;
  4980. }
  4981. if (type != null && type !== true && !skipCheck) {
  4982. let isValid2 = false;
  4983. const types = isArray(type) ? type : [type];
  4984. const expectedTypes = [];
  4985. for (let i2 = 0; i2 < types.length && !isValid2; i2++) {
  4986. const { valid, expectedType } = assertType(value, types[i2]);
  4987. expectedTypes.push(expectedType || "");
  4988. isValid2 = valid;
  4989. }
  4990. if (!isValid2) {
  4991. warn$1(getInvalidTypeMessage(name, value, expectedTypes));
  4992. return;
  4993. }
  4994. }
  4995. if (validator && !validator(value, props)) {
  4996. warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
  4997. }
  4998. }
  4999. const isSimpleType = /* @__PURE__ */ makeMap(
  5000. "String,Number,Boolean,Function,Symbol,BigInt"
  5001. );
  5002. function assertType(value, type) {
  5003. let valid;
  5004. const expectedType = getType(type);
  5005. if (isSimpleType(expectedType)) {
  5006. const t2 = typeof value;
  5007. valid = t2 === expectedType.toLowerCase();
  5008. if (!valid && t2 === "object") {
  5009. valid = value instanceof type;
  5010. }
  5011. } else if (expectedType === "Object") {
  5012. valid = isObject$1(value);
  5013. } else if (expectedType === "Array") {
  5014. valid = isArray(value);
  5015. } else if (expectedType === "null") {
  5016. valid = value === null;
  5017. } else {
  5018. valid = value instanceof type;
  5019. }
  5020. return {
  5021. valid,
  5022. expectedType
  5023. };
  5024. }
  5025. function getInvalidTypeMessage(name, value, expectedTypes) {
  5026. if (expectedTypes.length === 0) {
  5027. return `Prop type [] for prop "${name}" won't match anything. Did you mean to use type Array instead?`;
  5028. }
  5029. let message = `Invalid prop: type check failed for prop "${name}". Expected ${expectedTypes.map(capitalize).join(" | ")}`;
  5030. const expectedType = expectedTypes[0];
  5031. const receivedType = toRawType(value);
  5032. const expectedValue = styleValue(value, expectedType);
  5033. const receivedValue = styleValue(value, receivedType);
  5034. if (expectedTypes.length === 1 && isExplicable(expectedType) && !isBoolean(expectedType, receivedType)) {
  5035. message += ` with value ${expectedValue}`;
  5036. }
  5037. message += `, got ${receivedType} `;
  5038. if (isExplicable(receivedType)) {
  5039. message += `with value ${receivedValue}.`;
  5040. }
  5041. return message;
  5042. }
  5043. function styleValue(value, type) {
  5044. if (type === "String") {
  5045. return `"${value}"`;
  5046. } else if (type === "Number") {
  5047. return `${Number(value)}`;
  5048. } else {
  5049. return `${value}`;
  5050. }
  5051. }
  5052. function isExplicable(type) {
  5053. const explicitTypes = ["string", "number", "boolean"];
  5054. return explicitTypes.some((elem) => type.toLowerCase() === elem);
  5055. }
  5056. function isBoolean(...args) {
  5057. return args.some((elem) => elem.toLowerCase() === "boolean");
  5058. }
  5059. let supported;
  5060. let perf;
  5061. function startMeasure(instance, type) {
  5062. if (instance.appContext.config.performance && isSupported$1()) {
  5063. perf.mark(`vue-${type}-${instance.uid}`);
  5064. }
  5065. {
  5066. devtoolsPerfStart(instance, type, isSupported$1() ? perf.now() : Date.now());
  5067. }
  5068. }
  5069. function endMeasure(instance, type) {
  5070. if (instance.appContext.config.performance && isSupported$1()) {
  5071. const startTag = `vue-${type}-${instance.uid}`;
  5072. const endTag = startTag + `:end`;
  5073. perf.mark(endTag);
  5074. perf.measure(
  5075. `<${formatComponentName(instance, instance.type)}> ${type}`,
  5076. startTag,
  5077. endTag
  5078. );
  5079. perf.clearMarks(startTag);
  5080. perf.clearMarks(endTag);
  5081. }
  5082. {
  5083. devtoolsPerfEnd(instance, type, isSupported$1() ? perf.now() : Date.now());
  5084. }
  5085. }
  5086. function isSupported$1() {
  5087. if (supported !== void 0) {
  5088. return supported;
  5089. }
  5090. if (typeof window !== "undefined" && window.performance) {
  5091. supported = true;
  5092. perf = window.performance;
  5093. } else {
  5094. supported = false;
  5095. }
  5096. return supported;
  5097. }
  5098. const queuePostRenderEffect$1 = queuePostFlushCb;
  5099. const Fragment$1 = Symbol.for("v-fgt");
  5100. const Text = Symbol.for("v-txt");
  5101. const Comment = Symbol.for("v-cmt");
  5102. const Static = Symbol.for("v-stc");
  5103. function isVNode(value) {
  5104. return value ? value.__v_isVNode === true : false;
  5105. }
  5106. const InternalObjectKey = `__vInternal`;
  5107. function guardReactiveProps(props) {
  5108. if (!props)
  5109. return null;
  5110. return isProxy(props) || InternalObjectKey in props ? extend({}, props) : props;
  5111. }
  5112. const emptyAppContext = createAppContext();
  5113. let uid = 0;
  5114. function createComponentInstance(vnode, parent, suspense) {
  5115. const type = vnode.type;
  5116. const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
  5117. const instance = {
  5118. uid: uid++,
  5119. vnode,
  5120. type,
  5121. parent,
  5122. appContext,
  5123. root: null,
  5124. // to be immediately set
  5125. next: null,
  5126. subTree: null,
  5127. // will be set synchronously right after creation
  5128. effect: null,
  5129. update: null,
  5130. // will be set synchronously right after creation
  5131. scope: new EffectScope(
  5132. true
  5133. /* detached */
  5134. ),
  5135. render: null,
  5136. proxy: null,
  5137. exposed: null,
  5138. exposeProxy: null,
  5139. withProxy: null,
  5140. provides: parent ? parent.provides : Object.create(appContext.provides),
  5141. accessCache: null,
  5142. renderCache: [],
  5143. // local resolved assets
  5144. components: null,
  5145. directives: null,
  5146. // resolved props and emits options
  5147. propsOptions: normalizePropsOptions(type, appContext),
  5148. emitsOptions: normalizeEmitsOptions(type, appContext),
  5149. // emit
  5150. emit: null,
  5151. // to be set immediately
  5152. emitted: null,
  5153. // props default value
  5154. propsDefaults: EMPTY_OBJ,
  5155. // inheritAttrs
  5156. inheritAttrs: type.inheritAttrs,
  5157. // state
  5158. ctx: EMPTY_OBJ,
  5159. data: EMPTY_OBJ,
  5160. props: EMPTY_OBJ,
  5161. attrs: EMPTY_OBJ,
  5162. slots: EMPTY_OBJ,
  5163. refs: EMPTY_OBJ,
  5164. setupState: EMPTY_OBJ,
  5165. setupContext: null,
  5166. attrsProxy: null,
  5167. slotsProxy: null,
  5168. // suspense related
  5169. suspense,
  5170. suspenseId: suspense ? suspense.pendingId : 0,
  5171. asyncDep: null,
  5172. asyncResolved: false,
  5173. // lifecycle hooks
  5174. // not using enums here because it results in computed properties
  5175. isMounted: false,
  5176. isUnmounted: false,
  5177. isDeactivated: false,
  5178. bc: null,
  5179. c: null,
  5180. bm: null,
  5181. m: null,
  5182. bu: null,
  5183. u: null,
  5184. um: null,
  5185. bum: null,
  5186. da: null,
  5187. a: null,
  5188. rtg: null,
  5189. rtc: null,
  5190. ec: null,
  5191. sp: null,
  5192. // fixed by xxxxxx 用于存储uni-app的元素缓存
  5193. $uniElements: /* @__PURE__ */ new Map(),
  5194. $templateUniElementRefs: [],
  5195. $templateUniElementStyles: {},
  5196. $eS: {},
  5197. $eA: {}
  5198. };
  5199. {
  5200. instance.ctx = createDevRenderContext(instance);
  5201. }
  5202. instance.root = parent ? parent.root : instance;
  5203. instance.emit = emit.bind(null, instance);
  5204. if (vnode.ce) {
  5205. vnode.ce(instance);
  5206. }
  5207. return instance;
  5208. }
  5209. let currentInstance = null;
  5210. const getCurrentInstance = () => currentInstance || currentRenderingInstance;
  5211. let internalSetCurrentInstance;
  5212. let setInSSRSetupState;
  5213. {
  5214. internalSetCurrentInstance = (i2) => {
  5215. currentInstance = i2;
  5216. };
  5217. setInSSRSetupState = (v2) => {
  5218. isInSSRComponentSetup = v2;
  5219. };
  5220. }
  5221. const setCurrentInstance = (instance) => {
  5222. const prev = currentInstance;
  5223. internalSetCurrentInstance(instance);
  5224. instance.scope.on();
  5225. return () => {
  5226. instance.scope.off();
  5227. internalSetCurrentInstance(prev);
  5228. };
  5229. };
  5230. const unsetCurrentInstance = () => {
  5231. currentInstance && currentInstance.scope.off();
  5232. internalSetCurrentInstance(null);
  5233. };
  5234. const isBuiltInTag = /* @__PURE__ */ makeMap("slot,component");
  5235. function validateComponentName(name, { isNativeTag }) {
  5236. if (isBuiltInTag(name) || isNativeTag(name)) {
  5237. warn$1(
  5238. "Do not use built-in or reserved HTML elements as component id: " + name
  5239. );
  5240. }
  5241. }
  5242. function isStatefulComponent(instance) {
  5243. return instance.vnode.shapeFlag & 4;
  5244. }
  5245. let isInSSRComponentSetup = false;
  5246. function setupComponent(instance, isSSR = false) {
  5247. isSSR && setInSSRSetupState(isSSR);
  5248. const {
  5249. props
  5250. /*, children*/
  5251. } = instance.vnode;
  5252. const isStateful = isStatefulComponent(instance);
  5253. initProps$1(instance, props, isStateful, isSSR);
  5254. const setupResult = isStateful ? setupStatefulComponent(instance, isSSR) : void 0;
  5255. isSSR && setInSSRSetupState(false);
  5256. return setupResult;
  5257. }
  5258. function setupStatefulComponent(instance, isSSR) {
  5259. const Component2 = instance.type;
  5260. {
  5261. if (Component2.name) {
  5262. validateComponentName(Component2.name, instance.appContext.config);
  5263. }
  5264. if (Component2.components) {
  5265. const names = Object.keys(Component2.components);
  5266. for (let i2 = 0; i2 < names.length; i2++) {
  5267. validateComponentName(names[i2], instance.appContext.config);
  5268. }
  5269. }
  5270. if (Component2.directives) {
  5271. const names = Object.keys(Component2.directives);
  5272. for (let i2 = 0; i2 < names.length; i2++) {
  5273. validateDirectiveName(names[i2]);
  5274. }
  5275. }
  5276. if (Component2.compilerOptions && isRuntimeOnly()) {
  5277. warn$1(
  5278. `"compilerOptions" is only supported when using a build of Vue that includes the runtime compiler. Since you are using a runtime-only build, the options should be passed via your build tool config instead.`
  5279. );
  5280. }
  5281. }
  5282. instance.accessCache = /* @__PURE__ */ Object.create(null);
  5283. instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
  5284. {
  5285. exposePropsOnRenderContext(instance);
  5286. }
  5287. const { setup } = Component2;
  5288. if (setup) {
  5289. const setupContext = instance.setupContext = setup.length > 1 ? createSetupContext(instance) : null;
  5290. const reset = setCurrentInstance(instance);
  5291. pauseTracking();
  5292. const setupResult = callWithErrorHandling(
  5293. setup,
  5294. instance,
  5295. 0,
  5296. [
  5297. shallowReadonly(instance.props),
  5298. setupContext
  5299. ]
  5300. );
  5301. resetTracking();
  5302. reset();
  5303. if (isPromise$2(setupResult)) {
  5304. setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
  5305. {
  5306. warn$1(
  5307. `setup() returned a Promise, but the version of Vue you are using does not support it yet.`
  5308. );
  5309. }
  5310. } else {
  5311. handleSetupResult(instance, setupResult, isSSR);
  5312. }
  5313. } else {
  5314. finishComponentSetup(instance, isSSR);
  5315. }
  5316. }
  5317. function handleSetupResult(instance, setupResult, isSSR) {
  5318. if (isFunction(setupResult)) {
  5319. {
  5320. instance.render = setupResult;
  5321. }
  5322. } else if (isObject$1(setupResult)) {
  5323. if (isVNode(setupResult)) {
  5324. warn$1(
  5325. `setup() should not return VNodes directly - return a render function instead.`
  5326. );
  5327. }
  5328. {
  5329. instance.devtoolsRawSetupState = setupResult;
  5330. }
  5331. instance.setupState = proxyRefs(setupResult);
  5332. {
  5333. exposeSetupStateOnRenderContext(instance);
  5334. }
  5335. } else if (setupResult !== void 0) {
  5336. warn$1(
  5337. `setup() should return an object. Received: ${setupResult === null ? "null" : typeof setupResult}`
  5338. );
  5339. }
  5340. finishComponentSetup(instance, isSSR);
  5341. }
  5342. let compile;
  5343. const isRuntimeOnly = () => !compile;
  5344. function finishComponentSetup(instance, isSSR, skipOptions) {
  5345. const Component2 = instance.type;
  5346. if (!instance.render) {
  5347. instance.render = Component2.render || NOOP;
  5348. }
  5349. {
  5350. const reset = setCurrentInstance(instance);
  5351. pauseTracking();
  5352. try {
  5353. applyOptions$1(instance);
  5354. } finally {
  5355. resetTracking();
  5356. reset();
  5357. }
  5358. }
  5359. if (!Component2.render && instance.render === NOOP && !isSSR) {
  5360. if (Component2.template) {
  5361. warn$1(
  5362. `Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js".`
  5363. );
  5364. } else {
  5365. warn$1(`Component is missing template or render function.`);
  5366. }
  5367. }
  5368. }
  5369. function getAttrsProxy(instance) {
  5370. return instance.attrsProxy || (instance.attrsProxy = new Proxy(
  5371. instance.attrs,
  5372. {
  5373. get(target, key) {
  5374. track(instance, "get", "$attrs");
  5375. return target[key];
  5376. },
  5377. set() {
  5378. warn$1(`setupContext.attrs is readonly.`);
  5379. return false;
  5380. },
  5381. deleteProperty() {
  5382. warn$1(`setupContext.attrs is readonly.`);
  5383. return false;
  5384. }
  5385. }
  5386. ));
  5387. }
  5388. function getSlotsProxy(instance) {
  5389. return instance.slotsProxy || (instance.slotsProxy = new Proxy(instance.slots, {
  5390. get(target, key) {
  5391. track(instance, "get", "$slots");
  5392. return target[key];
  5393. }
  5394. }));
  5395. }
  5396. function createSetupContext(instance) {
  5397. const expose = (exposed) => {
  5398. {
  5399. if (instance.exposed) {
  5400. warn$1(`expose() should be called only once per setup().`);
  5401. }
  5402. if (exposed != null) {
  5403. let exposedType = typeof exposed;
  5404. if (exposedType === "object") {
  5405. if (isArray(exposed)) {
  5406. exposedType = "array";
  5407. } else if (isRef(exposed)) {
  5408. exposedType = "ref";
  5409. }
  5410. }
  5411. if (exposedType !== "object") {
  5412. warn$1(
  5413. `expose() should be passed a plain object, received ${exposedType}.`
  5414. );
  5415. }
  5416. }
  5417. }
  5418. instance.exposed = exposed || {};
  5419. };
  5420. {
  5421. return Object.freeze({
  5422. get attrs() {
  5423. return getAttrsProxy(instance);
  5424. },
  5425. get slots() {
  5426. return getSlotsProxy(instance);
  5427. },
  5428. get emit() {
  5429. return (event, ...args) => instance.emit(event, ...args);
  5430. },
  5431. expose
  5432. });
  5433. }
  5434. }
  5435. function getExposeProxy(instance) {
  5436. if (instance.exposed) {
  5437. return instance.exposeProxy || (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
  5438. get(target, key) {
  5439. if (key in target) {
  5440. return target[key];
  5441. }
  5442. return instance.proxy[key];
  5443. },
  5444. has(target, key) {
  5445. return key in target || key in publicPropertiesMap;
  5446. }
  5447. }));
  5448. }
  5449. }
  5450. const classifyRE = /(?:^|[-_])(\w)/g;
  5451. const classify = (str) => str.replace(classifyRE, (c2) => c2.toUpperCase()).replace(/[-_]/g, "");
  5452. function getComponentName(Component2, includeInferred = true) {
  5453. return isFunction(Component2) ? Component2.displayName || Component2.name : Component2.name || includeInferred && Component2.__name;
  5454. }
  5455. function formatComponentName(instance, Component2, isRoot = false) {
  5456. let name = getComponentName(Component2);
  5457. if (!name && Component2.__file) {
  5458. const match = Component2.__file.match(/([^/\\]+)\.\w+$/);
  5459. if (match) {
  5460. name = match[1];
  5461. }
  5462. }
  5463. if (!name && instance && instance.parent) {
  5464. const inferFromRegistry = (registry) => {
  5465. for (const key in registry) {
  5466. if (registry[key] === Component2) {
  5467. return key;
  5468. }
  5469. }
  5470. };
  5471. name = inferFromRegistry(
  5472. instance.components || instance.parent.type.components
  5473. ) || inferFromRegistry(instance.appContext.components);
  5474. }
  5475. return name ? classify(name) : isRoot ? `App` : `Anonymous`;
  5476. }
  5477. const computed = (getterOrOptions, debugOptions) => {
  5478. const c2 = computed$1(getterOrOptions, debugOptions, isInSSRComponentSetup);
  5479. {
  5480. const i2 = getCurrentInstance();
  5481. if (i2 && i2.appContext.config.warnRecursiveComputed) {
  5482. c2._warnRecursive = true;
  5483. }
  5484. }
  5485. return c2;
  5486. };
  5487. const version$1 = "3.4.21";
  5488. const warn = warn$1;
  5489. function unwrapper(target) {
  5490. return unref(target);
  5491. }
  5492. const ARRAYTYPE = "[object Array]";
  5493. const OBJECTTYPE = "[object Object]";
  5494. function diff(current, pre) {
  5495. const result = {};
  5496. syncKeys(current, pre);
  5497. _diff(current, pre, "", result);
  5498. return result;
  5499. }
  5500. function syncKeys(current, pre) {
  5501. current = unwrapper(current);
  5502. if (current === pre)
  5503. return;
  5504. const rootCurrentType = toTypeString(current);
  5505. const rootPreType = toTypeString(pre);
  5506. if (rootCurrentType == OBJECTTYPE && rootPreType == OBJECTTYPE) {
  5507. for (let key in pre) {
  5508. const currentValue = current[key];
  5509. if (currentValue === void 0) {
  5510. current[key] = null;
  5511. } else {
  5512. syncKeys(currentValue, pre[key]);
  5513. }
  5514. }
  5515. } else if (rootCurrentType == ARRAYTYPE && rootPreType == ARRAYTYPE) {
  5516. if (current.length >= pre.length) {
  5517. pre.forEach((item, index2) => {
  5518. syncKeys(current[index2], item);
  5519. });
  5520. }
  5521. }
  5522. }
  5523. function _diff(current, pre, path, result) {
  5524. current = unwrapper(current);
  5525. if (current === pre)
  5526. return;
  5527. const rootCurrentType = toTypeString(current);
  5528. const rootPreType = toTypeString(pre);
  5529. if (rootCurrentType == OBJECTTYPE) {
  5530. if (rootPreType != OBJECTTYPE || Object.keys(current).length < Object.keys(pre).length) {
  5531. setResult(result, path, current);
  5532. } else {
  5533. for (let key in current) {
  5534. const currentValue = unwrapper(current[key]);
  5535. const preValue = pre[key];
  5536. const currentType = toTypeString(currentValue);
  5537. const preType = toTypeString(preValue);
  5538. if (currentType != ARRAYTYPE && currentType != OBJECTTYPE) {
  5539. if (currentValue != preValue) {
  5540. setResult(
  5541. result,
  5542. (path == "" ? "" : path + ".") + key,
  5543. currentValue
  5544. );
  5545. }
  5546. } else if (currentType == ARRAYTYPE) {
  5547. if (preType != ARRAYTYPE) {
  5548. setResult(
  5549. result,
  5550. (path == "" ? "" : path + ".") + key,
  5551. currentValue
  5552. );
  5553. } else {
  5554. if (currentValue.length < preValue.length) {
  5555. setResult(
  5556. result,
  5557. (path == "" ? "" : path + ".") + key,
  5558. currentValue
  5559. );
  5560. } else {
  5561. currentValue.forEach((item, index2) => {
  5562. _diff(
  5563. item,
  5564. preValue[index2],
  5565. (path == "" ? "" : path + ".") + key + "[" + index2 + "]",
  5566. result
  5567. );
  5568. });
  5569. }
  5570. }
  5571. } else if (currentType == OBJECTTYPE) {
  5572. if (preType != OBJECTTYPE || Object.keys(currentValue).length < Object.keys(preValue).length) {
  5573. setResult(
  5574. result,
  5575. (path == "" ? "" : path + ".") + key,
  5576. currentValue
  5577. );
  5578. } else {
  5579. for (let subKey in currentValue) {
  5580. _diff(
  5581. currentValue[subKey],
  5582. preValue[subKey],
  5583. (path == "" ? "" : path + ".") + key + "." + subKey,
  5584. result
  5585. );
  5586. }
  5587. }
  5588. }
  5589. }
  5590. }
  5591. } else if (rootCurrentType == ARRAYTYPE) {
  5592. if (rootPreType != ARRAYTYPE) {
  5593. setResult(result, path, current);
  5594. } else {
  5595. if (current.length < pre.length) {
  5596. setResult(result, path, current);
  5597. } else {
  5598. current.forEach((item, index2) => {
  5599. _diff(item, pre[index2], path + "[" + index2 + "]", result);
  5600. });
  5601. }
  5602. }
  5603. } else {
  5604. setResult(result, path, current);
  5605. }
  5606. }
  5607. function setResult(result, k, v2) {
  5608. result[k] = v2;
  5609. }
  5610. function hasComponentEffect(instance) {
  5611. return queue.includes(instance.update);
  5612. }
  5613. function flushCallbacks(instance) {
  5614. const ctx = instance.ctx;
  5615. const callbacks = ctx.__next_tick_callbacks;
  5616. if (callbacks && callbacks.length) {
  5617. const copies = callbacks.slice(0);
  5618. callbacks.length = 0;
  5619. for (let i2 = 0; i2 < copies.length; i2++) {
  5620. copies[i2]();
  5621. }
  5622. }
  5623. }
  5624. function nextTick(instance, fn2) {
  5625. const ctx = instance.ctx;
  5626. if (!ctx.__next_tick_pending && !hasComponentEffect(instance)) {
  5627. return nextTick$1(fn2 && fn2.bind(instance.proxy));
  5628. }
  5629. let _resolve;
  5630. if (!ctx.__next_tick_callbacks) {
  5631. ctx.__next_tick_callbacks = [];
  5632. }
  5633. ctx.__next_tick_callbacks.push(() => {
  5634. if (fn2) {
  5635. callWithErrorHandling(
  5636. fn2.bind(instance.proxy),
  5637. instance,
  5638. 14
  5639. );
  5640. } else if (_resolve) {
  5641. _resolve(instance.proxy);
  5642. }
  5643. });
  5644. return new Promise((resolve2) => {
  5645. _resolve = resolve2;
  5646. });
  5647. }
  5648. function clone(src, seen) {
  5649. src = unwrapper(src);
  5650. const type = typeof src;
  5651. if (type === "object" && src !== null) {
  5652. let copy = seen.get(src);
  5653. if (typeof copy !== "undefined") {
  5654. return copy;
  5655. }
  5656. if (isArray(src)) {
  5657. const len = src.length;
  5658. copy = new Array(len);
  5659. seen.set(src, copy);
  5660. for (let i2 = 0; i2 < len; i2++) {
  5661. copy[i2] = clone(src[i2], seen);
  5662. }
  5663. } else {
  5664. copy = {};
  5665. seen.set(src, copy);
  5666. for (const name in src) {
  5667. if (hasOwn(src, name)) {
  5668. copy[name] = clone(src[name], seen);
  5669. }
  5670. }
  5671. }
  5672. return copy;
  5673. }
  5674. if (type !== "symbol") {
  5675. return src;
  5676. }
  5677. }
  5678. function deepCopy(src) {
  5679. return clone(src, typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : /* @__PURE__ */ new Map());
  5680. }
  5681. function getMPInstanceData(instance, keys) {
  5682. const data = instance.data;
  5683. const ret = /* @__PURE__ */ Object.create(null);
  5684. keys.forEach((key) => {
  5685. ret[key] = data[key];
  5686. });
  5687. return ret;
  5688. }
  5689. function patch(instance, data, oldData) {
  5690. if (!data) {
  5691. return;
  5692. }
  5693. data = deepCopy(data);
  5694. data.$eS = instance.$eS || {};
  5695. data.$eA = instance.$eA || {};
  5696. const ctx = instance.ctx;
  5697. const mpType = ctx.mpType;
  5698. if (mpType === "page" || mpType === "component") {
  5699. data.r0 = 1;
  5700. const mpInstance = ctx.$scope;
  5701. const keys = Object.keys(data);
  5702. const diffData = diff(data, oldData || getMPInstanceData(mpInstance, keys));
  5703. if (Object.keys(diffData).length) {
  5704. ctx.__next_tick_pending = true;
  5705. mpInstance.setData(diffData, () => {
  5706. ctx.__next_tick_pending = false;
  5707. flushCallbacks(instance);
  5708. });
  5709. flushPreFlushCbs();
  5710. } else {
  5711. flushCallbacks(instance);
  5712. }
  5713. }
  5714. }
  5715. function initAppConfig(appConfig) {
  5716. appConfig.globalProperties.$nextTick = function $nextTick(fn2) {
  5717. return nextTick(this.$, fn2);
  5718. };
  5719. }
  5720. function onApplyOptions(options, instance, publicThis) {
  5721. instance.appContext.config.globalProperties.$applyOptions(
  5722. options,
  5723. instance,
  5724. publicThis
  5725. );
  5726. const computedOptions = options.computed;
  5727. if (computedOptions) {
  5728. const keys = Object.keys(computedOptions);
  5729. if (keys.length) {
  5730. const ctx = instance.ctx;
  5731. if (!ctx.$computedKeys) {
  5732. ctx.$computedKeys = [];
  5733. }
  5734. ctx.$computedKeys.push(...keys);
  5735. }
  5736. }
  5737. delete instance.ctx.$onApplyOptions;
  5738. }
  5739. function setRef$1(instance, isUnmount = false) {
  5740. const {
  5741. setupState,
  5742. $templateRefs,
  5743. $templateUniElementRefs,
  5744. ctx: { $scope, $mpPlatform }
  5745. } = instance;
  5746. if ($mpPlatform === "mp-alipay") {
  5747. return;
  5748. }
  5749. if (!$scope || !$templateRefs && !$templateUniElementRefs) {
  5750. return;
  5751. }
  5752. if (isUnmount) {
  5753. $templateRefs && $templateRefs.forEach(
  5754. (templateRef) => setTemplateRef(templateRef, null, setupState)
  5755. );
  5756. $templateUniElementRefs && $templateUniElementRefs.forEach(
  5757. (templateRef) => setTemplateRef(templateRef, null, setupState)
  5758. );
  5759. return;
  5760. }
  5761. const check = $mpPlatform === "mp-baidu" || $mpPlatform === "mp-toutiao";
  5762. const doSetByRefs = (refs) => {
  5763. if (refs.length === 0) {
  5764. return [];
  5765. }
  5766. const mpComponents = (
  5767. // 字节小程序 selectAllComponents 可能返回 null
  5768. // https://github.com/dcloudio/uni-app/issues/3954
  5769. ($scope.selectAllComponents(".r") || []).concat(
  5770. $scope.selectAllComponents(".r-i-f") || []
  5771. )
  5772. );
  5773. return refs.filter((templateRef) => {
  5774. const refValue = findComponentPublicInstance(mpComponents, templateRef.i);
  5775. if (check && refValue === null) {
  5776. return true;
  5777. }
  5778. setTemplateRef(templateRef, refValue, setupState);
  5779. return false;
  5780. });
  5781. };
  5782. const doSet = () => {
  5783. if ($templateRefs) {
  5784. const refs = doSetByRefs($templateRefs);
  5785. if (refs.length && instance.proxy && instance.proxy.$scope) {
  5786. instance.proxy.$scope.setData({ r1: 1 }, () => {
  5787. doSetByRefs(refs);
  5788. });
  5789. }
  5790. }
  5791. };
  5792. if ($templateUniElementRefs && $templateUniElementRefs.length) {
  5793. nextTick(instance, () => {
  5794. $templateUniElementRefs.forEach((templateRef) => {
  5795. if (isArray(templateRef.v)) {
  5796. templateRef.v.forEach((v2) => {
  5797. setTemplateRef(templateRef, v2, setupState);
  5798. });
  5799. } else {
  5800. setTemplateRef(templateRef, templateRef.v, setupState);
  5801. }
  5802. });
  5803. });
  5804. }
  5805. if ($scope._$setRef) {
  5806. $scope._$setRef(doSet);
  5807. } else {
  5808. nextTick(instance, doSet);
  5809. }
  5810. }
  5811. function toSkip(value) {
  5812. if (isObject$1(value)) {
  5813. markRaw(value);
  5814. }
  5815. return value;
  5816. }
  5817. function findComponentPublicInstance(mpComponents, id) {
  5818. const mpInstance = mpComponents.find(
  5819. (com) => com && (com.properties || com.props).uI === id
  5820. );
  5821. if (mpInstance) {
  5822. const vm = mpInstance.$vm;
  5823. if (vm) {
  5824. return getExposeProxy(vm.$) || vm;
  5825. }
  5826. return toSkip(mpInstance);
  5827. }
  5828. return null;
  5829. }
  5830. function setTemplateRef({ r: r2, f: f2 }, refValue, setupState) {
  5831. if (isFunction(r2)) {
  5832. r2(refValue, {});
  5833. } else {
  5834. const _isString = isString(r2);
  5835. const _isRef = isRef(r2);
  5836. if (_isString || _isRef) {
  5837. if (f2) {
  5838. if (!_isRef) {
  5839. return;
  5840. }
  5841. if (!isArray(r2.value)) {
  5842. r2.value = [];
  5843. }
  5844. const existing = r2.value;
  5845. if (existing.indexOf(refValue) === -1) {
  5846. existing.push(refValue);
  5847. if (!refValue) {
  5848. return;
  5849. }
  5850. if (refValue.$) {
  5851. onBeforeUnmount(() => remove(existing, refValue), refValue.$);
  5852. }
  5853. }
  5854. } else if (_isString) {
  5855. if (hasOwn(setupState, r2)) {
  5856. setupState[r2] = refValue;
  5857. }
  5858. } else if (isRef(r2)) {
  5859. r2.value = refValue;
  5860. } else {
  5861. warnRef(r2);
  5862. }
  5863. } else {
  5864. warnRef(r2);
  5865. }
  5866. }
  5867. }
  5868. function warnRef(ref2) {
  5869. warn("Invalid template ref type:", ref2, `(${typeof ref2})`);
  5870. }
  5871. const queuePostRenderEffect = queuePostFlushCb;
  5872. function mountComponent(initialVNode, options) {
  5873. const instance = initialVNode.component = createComponentInstance(initialVNode, options.parentComponent, null);
  5874. instance.renderer = options.mpType ? options.mpType : "component";
  5875. {
  5876. instance.ctx.$onApplyOptions = onApplyOptions;
  5877. instance.ctx.$children = [];
  5878. }
  5879. if (options.mpType === "app") {
  5880. instance.render = NOOP;
  5881. }
  5882. if (options.onBeforeSetup) {
  5883. options.onBeforeSetup(instance, options);
  5884. }
  5885. {
  5886. pushWarningContext(initialVNode);
  5887. startMeasure(instance, `mount`);
  5888. }
  5889. {
  5890. startMeasure(instance, `init`);
  5891. }
  5892. setupComponent(instance);
  5893. {
  5894. endMeasure(instance, `init`);
  5895. }
  5896. {
  5897. if (options.parentComponent && instance.proxy) {
  5898. options.parentComponent.ctx.$children.push(getExposeProxy(instance) || instance.proxy);
  5899. }
  5900. }
  5901. setupRenderEffect(instance);
  5902. {
  5903. popWarningContext();
  5904. endMeasure(instance, `mount`);
  5905. }
  5906. return instance.proxy;
  5907. }
  5908. const getFunctionalFallthrough = (attrs) => {
  5909. let res;
  5910. for (const key in attrs) {
  5911. if (key === "class" || key === "style" || isOn(key)) {
  5912. (res || (res = {}))[key] = attrs[key];
  5913. }
  5914. }
  5915. return res;
  5916. };
  5917. function renderComponentRoot(instance) {
  5918. const {
  5919. type: Component2,
  5920. vnode,
  5921. proxy,
  5922. withProxy,
  5923. props,
  5924. propsOptions: [propsOptions],
  5925. slots,
  5926. attrs,
  5927. emit: emit2,
  5928. render,
  5929. renderCache,
  5930. data,
  5931. setupState,
  5932. ctx,
  5933. uid: uid2,
  5934. appContext: {
  5935. app: {
  5936. config: {
  5937. globalProperties: { pruneComponentPropsCache: pruneComponentPropsCache2 }
  5938. }
  5939. }
  5940. },
  5941. inheritAttrs
  5942. } = instance;
  5943. instance.$uniElementIds = /* @__PURE__ */ new Map();
  5944. instance.$templateRefs = [];
  5945. instance.$templateUniElementRefs = [];
  5946. instance.$templateUniElementStyles = {};
  5947. instance.$ei = 0;
  5948. pruneComponentPropsCache2(uid2);
  5949. instance.__counter = instance.__counter === 0 ? 1 : 0;
  5950. let result;
  5951. const prev = setCurrentRenderingInstance(instance);
  5952. try {
  5953. if (vnode.shapeFlag & 4) {
  5954. fallthroughAttrs(inheritAttrs, props, propsOptions, attrs);
  5955. const proxyToUse = withProxy || proxy;
  5956. result = render.call(
  5957. proxyToUse,
  5958. proxyToUse,
  5959. renderCache,
  5960. props,
  5961. setupState,
  5962. data,
  5963. ctx
  5964. );
  5965. } else {
  5966. fallthroughAttrs(
  5967. inheritAttrs,
  5968. props,
  5969. propsOptions,
  5970. Component2.props ? attrs : getFunctionalFallthrough(attrs)
  5971. );
  5972. const render2 = Component2;
  5973. result = render2.length > 1 ? render2(props, { attrs, slots, emit: emit2 }) : render2(
  5974. props,
  5975. null
  5976. /* we know it doesn't need it */
  5977. );
  5978. }
  5979. } catch (err) {
  5980. handleError(err, instance, 1);
  5981. result = false;
  5982. }
  5983. setRef$1(instance);
  5984. setCurrentRenderingInstance(prev);
  5985. return result;
  5986. }
  5987. function fallthroughAttrs(inheritAttrs, props, propsOptions, fallthroughAttrs2) {
  5988. if (props && fallthroughAttrs2 && inheritAttrs !== false) {
  5989. const keys = Object.keys(fallthroughAttrs2).filter(
  5990. (key) => key !== "class" && key !== "style"
  5991. );
  5992. if (!keys.length) {
  5993. return;
  5994. }
  5995. if (propsOptions && keys.some(isModelListener)) {
  5996. keys.forEach((key) => {
  5997. if (!isModelListener(key) || !(key.slice(9) in propsOptions)) {
  5998. props[key] = fallthroughAttrs2[key];
  5999. }
  6000. });
  6001. } else {
  6002. keys.forEach((key) => props[key] = fallthroughAttrs2[key]);
  6003. }
  6004. }
  6005. }
  6006. const updateComponentPreRender = (instance) => {
  6007. pauseTracking();
  6008. flushPreFlushCbs();
  6009. resetTracking();
  6010. };
  6011. function componentUpdateScopedSlotsFn() {
  6012. const scopedSlotsData = this.$scopedSlotsData;
  6013. if (!scopedSlotsData || scopedSlotsData.length === 0) {
  6014. return;
  6015. }
  6016. const mpInstance = this.ctx.$scope;
  6017. const oldData = mpInstance.data;
  6018. const diffData = /* @__PURE__ */ Object.create(null);
  6019. scopedSlotsData.forEach(({ path, index: index2, data }) => {
  6020. const oldScopedSlotData = getValueByDataPath(oldData, path);
  6021. const diffPath = isString(index2) ? `${path}.${index2}` : `${path}[${index2}]`;
  6022. if (typeof oldScopedSlotData === "undefined" || typeof oldScopedSlotData[index2] === "undefined") {
  6023. diffData[diffPath] = data;
  6024. } else {
  6025. const diffScopedSlotData = diff(
  6026. data,
  6027. oldScopedSlotData[index2]
  6028. );
  6029. Object.keys(diffScopedSlotData).forEach((name) => {
  6030. diffData[diffPath + "." + name] = diffScopedSlotData[name];
  6031. });
  6032. }
  6033. });
  6034. scopedSlotsData.length = 0;
  6035. if (Object.keys(diffData).length) {
  6036. mpInstance.setData(diffData);
  6037. }
  6038. }
  6039. function toggleRecurse({ effect: effect2, update: update3 }, allowed) {
  6040. effect2.allowRecurse = update3.allowRecurse = allowed;
  6041. }
  6042. function setupRenderEffect(instance) {
  6043. const updateScopedSlots = componentUpdateScopedSlotsFn.bind(
  6044. instance
  6045. );
  6046. instance.$updateScopedSlots = () => nextTick$1(() => queueJob(updateScopedSlots));
  6047. const componentUpdateFn = () => {
  6048. if (!instance.isMounted) {
  6049. onBeforeUnmount(() => {
  6050. setRef$1(instance, true);
  6051. }, instance);
  6052. {
  6053. startMeasure(instance, `patch`);
  6054. }
  6055. patch(instance, renderComponentRoot(instance));
  6056. {
  6057. endMeasure(instance, `patch`);
  6058. }
  6059. {
  6060. devtoolsComponentAdded(instance);
  6061. }
  6062. } else {
  6063. const { next, bu, u: u2 } = instance;
  6064. {
  6065. pushWarningContext(next || instance.vnode);
  6066. }
  6067. toggleRecurse(instance, false);
  6068. updateComponentPreRender();
  6069. if (bu) {
  6070. invokeArrayFns$1(bu);
  6071. }
  6072. toggleRecurse(instance, true);
  6073. {
  6074. startMeasure(instance, `patch`);
  6075. }
  6076. patch(instance, renderComponentRoot(instance));
  6077. {
  6078. endMeasure(instance, `patch`);
  6079. }
  6080. if (u2) {
  6081. queuePostRenderEffect(u2);
  6082. }
  6083. {
  6084. devtoolsComponentUpdated(instance);
  6085. }
  6086. {
  6087. popWarningContext();
  6088. }
  6089. }
  6090. };
  6091. const effect2 = instance.effect = new ReactiveEffect(
  6092. componentUpdateFn,
  6093. NOOP,
  6094. () => queueJob(update3),
  6095. instance.scope
  6096. // track it in component's effect scope
  6097. );
  6098. const update3 = instance.update = () => {
  6099. if (effect2.dirty) {
  6100. effect2.run();
  6101. }
  6102. };
  6103. update3.id = instance.uid;
  6104. toggleRecurse(instance, true);
  6105. {
  6106. effect2.onTrack = instance.rtc ? (e2) => invokeArrayFns$1(instance.rtc, e2) : void 0;
  6107. effect2.onTrigger = instance.rtg ? (e2) => invokeArrayFns$1(instance.rtg, e2) : void 0;
  6108. update3.ownerInstance = instance;
  6109. }
  6110. {
  6111. update3();
  6112. }
  6113. }
  6114. function unmountComponent(instance) {
  6115. const { bum, scope, update: update3, um } = instance;
  6116. if (bum) {
  6117. invokeArrayFns$1(bum);
  6118. }
  6119. {
  6120. const parentInstance = instance.parent;
  6121. if (parentInstance) {
  6122. const $children = parentInstance.ctx.$children;
  6123. const target = getExposeProxy(instance) || instance.proxy;
  6124. const index2 = $children.indexOf(target);
  6125. if (index2 > -1) {
  6126. $children.splice(index2, 1);
  6127. }
  6128. }
  6129. }
  6130. scope.stop();
  6131. if (update3) {
  6132. update3.active = false;
  6133. }
  6134. if (um) {
  6135. queuePostRenderEffect(um);
  6136. }
  6137. queuePostRenderEffect(() => {
  6138. instance.isUnmounted = true;
  6139. });
  6140. {
  6141. devtoolsComponentRemoved(instance);
  6142. }
  6143. }
  6144. const oldCreateApp = createAppAPI();
  6145. function getTarget() {
  6146. if (typeof window !== "undefined") {
  6147. return window;
  6148. }
  6149. if (typeof globalThis !== "undefined") {
  6150. return globalThis;
  6151. }
  6152. if (typeof global !== "undefined") {
  6153. return global;
  6154. }
  6155. if (typeof my !== "undefined") {
  6156. return my;
  6157. }
  6158. }
  6159. function createVueApp(rootComponent, rootProps = null) {
  6160. const target = getTarget();
  6161. target.__VUE__ = true;
  6162. {
  6163. setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target);
  6164. }
  6165. const app = oldCreateApp(rootComponent, rootProps);
  6166. const appContext = app._context;
  6167. initAppConfig(appContext.config);
  6168. const createVNode2 = (initialVNode) => {
  6169. initialVNode.appContext = appContext;
  6170. initialVNode.shapeFlag = 6;
  6171. return initialVNode;
  6172. };
  6173. const createComponent2 = function createComponent22(initialVNode, options) {
  6174. return mountComponent(createVNode2(initialVNode), options);
  6175. };
  6176. const destroyComponent = function destroyComponent2(component) {
  6177. return component && unmountComponent(component.$);
  6178. };
  6179. app.mount = function mount() {
  6180. rootComponent.render = NOOP;
  6181. const instance = mountComponent(
  6182. createVNode2({ type: rootComponent }),
  6183. {
  6184. mpType: "app",
  6185. mpInstance: null,
  6186. parentComponent: null,
  6187. slots: [],
  6188. props: null
  6189. }
  6190. );
  6191. app._instance = instance.$;
  6192. {
  6193. devtoolsInitApp(app, version$1);
  6194. }
  6195. instance.$app = app;
  6196. instance.$createComponent = createComponent2;
  6197. instance.$destroyComponent = destroyComponent;
  6198. appContext.$appInstance = instance;
  6199. return instance;
  6200. };
  6201. app.unmount = function unmount() {
  6202. warn(`Cannot unmount an app.`);
  6203. };
  6204. return app;
  6205. }
  6206. function injectLifecycleHook(name, hook, publicThis, instance) {
  6207. if (isFunction(hook)) {
  6208. injectHook(name, hook.bind(publicThis), instance);
  6209. }
  6210. }
  6211. function initHooks$1(options, instance, publicThis) {
  6212. const mpType = options.mpType || publicThis.$mpType;
  6213. if (!mpType || mpType === "component" || // instance.renderer 标识页面是否作为组件渲染
  6214. mpType === "page" && instance.renderer === "component") {
  6215. return;
  6216. }
  6217. Object.keys(options).forEach((name) => {
  6218. if (isUniLifecycleHook(name, options[name], false)) {
  6219. const hooks = options[name];
  6220. if (isArray(hooks)) {
  6221. hooks.forEach((hook) => injectLifecycleHook(name, hook, publicThis, instance));
  6222. } else {
  6223. injectLifecycleHook(name, hooks, publicThis, instance);
  6224. }
  6225. }
  6226. });
  6227. }
  6228. function applyOptions$2(options, instance, publicThis) {
  6229. initHooks$1(options, instance, publicThis);
  6230. }
  6231. function set(target, key, val) {
  6232. return target[key] = val;
  6233. }
  6234. function $callMethod(method, ...args) {
  6235. const fn2 = this[method];
  6236. if (fn2) {
  6237. return fn2(...args);
  6238. }
  6239. console.error(`method ${method} not found`);
  6240. return null;
  6241. }
  6242. function createErrorHandler(app) {
  6243. const userErrorHandler = app.config.errorHandler;
  6244. return function errorHandler(err, instance, info) {
  6245. if (userErrorHandler) {
  6246. userErrorHandler(err, instance, info);
  6247. }
  6248. const appInstance = app._instance;
  6249. if (!appInstance || !appInstance.proxy) {
  6250. throw err;
  6251. }
  6252. if (appInstance[ON_ERROR]) {
  6253. {
  6254. appInstance.proxy.$callHook(ON_ERROR, err);
  6255. }
  6256. } else {
  6257. logError(err, info, instance ? instance.$.vnode : null, false);
  6258. }
  6259. };
  6260. }
  6261. function mergeAsArray(to, from) {
  6262. return to ? [...new Set([].concat(to, from))] : from;
  6263. }
  6264. function initOptionMergeStrategies(optionMergeStrategies) {
  6265. UniLifecycleHooks.forEach((name) => {
  6266. optionMergeStrategies[name] = mergeAsArray;
  6267. });
  6268. }
  6269. let realAtob;
  6270. const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6271. const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/;
  6272. if (typeof atob !== "function") {
  6273. realAtob = function(str) {
  6274. str = String(str).replace(/[\t\n\f\r ]+/g, "");
  6275. if (!b64re.test(str)) {
  6276. throw new Error("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
  6277. }
  6278. str += "==".slice(2 - (str.length & 3));
  6279. var bitmap;
  6280. var result = "";
  6281. var r1;
  6282. var r2;
  6283. var i2 = 0;
  6284. for (; i2 < str.length; ) {
  6285. bitmap = b64.indexOf(str.charAt(i2++)) << 18 | b64.indexOf(str.charAt(i2++)) << 12 | (r1 = b64.indexOf(str.charAt(i2++))) << 6 | (r2 = b64.indexOf(str.charAt(i2++)));
  6286. result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) : r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) : String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255);
  6287. }
  6288. return result;
  6289. };
  6290. } else {
  6291. realAtob = atob;
  6292. }
  6293. function b64DecodeUnicode(str) {
  6294. return decodeURIComponent(realAtob(str).split("").map(function(c2) {
  6295. return "%" + ("00" + c2.charCodeAt(0).toString(16)).slice(-2);
  6296. }).join(""));
  6297. }
  6298. function getCurrentUserInfo() {
  6299. const token = index.getStorageSync("uni_id_token") || "";
  6300. const tokenArr = token.split(".");
  6301. if (!token || tokenArr.length !== 3) {
  6302. return {
  6303. uid: null,
  6304. role: [],
  6305. permission: [],
  6306. tokenExpired: 0
  6307. };
  6308. }
  6309. let userInfo;
  6310. try {
  6311. userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1]));
  6312. } catch (error) {
  6313. throw new Error("获取当前用户信息出错,详细错误信息为:" + error.message);
  6314. }
  6315. userInfo.tokenExpired = userInfo.exp * 1e3;
  6316. delete userInfo.exp;
  6317. delete userInfo.iat;
  6318. return userInfo;
  6319. }
  6320. function uniIdMixin(globalProperties) {
  6321. globalProperties.uniIDHasRole = function(roleId) {
  6322. const { role } = getCurrentUserInfo();
  6323. return role.indexOf(roleId) > -1;
  6324. };
  6325. globalProperties.uniIDHasPermission = function(permissionId) {
  6326. const { permission } = getCurrentUserInfo();
  6327. return this.uniIDHasRole("admin") || permission.indexOf(permissionId) > -1;
  6328. };
  6329. globalProperties.uniIDTokenValid = function() {
  6330. const { tokenExpired } = getCurrentUserInfo();
  6331. return tokenExpired > Date.now();
  6332. };
  6333. }
  6334. function initApp(app) {
  6335. const appConfig = app.config;
  6336. appConfig.errorHandler = invokeCreateErrorHandler(app, createErrorHandler);
  6337. initOptionMergeStrategies(appConfig.optionMergeStrategies);
  6338. const globalProperties = appConfig.globalProperties;
  6339. {
  6340. uniIdMixin(globalProperties);
  6341. }
  6342. {
  6343. globalProperties.$set = set;
  6344. globalProperties.$applyOptions = applyOptions$2;
  6345. globalProperties.$callMethod = $callMethod;
  6346. }
  6347. {
  6348. index.invokeCreateVueAppHook(app);
  6349. }
  6350. }
  6351. const propsCaches = /* @__PURE__ */ Object.create(null);
  6352. function renderProps(props) {
  6353. const { uid: uid2, __counter } = getCurrentInstance();
  6354. const propsId = (propsCaches[uid2] || (propsCaches[uid2] = [])).push(guardReactiveProps(props)) - 1;
  6355. return uid2 + "," + propsId + "," + __counter;
  6356. }
  6357. function pruneComponentPropsCache(uid2) {
  6358. delete propsCaches[uid2];
  6359. }
  6360. function findComponentPropsData(up) {
  6361. if (!up) {
  6362. return;
  6363. }
  6364. const [uid2, propsId] = up.split(",");
  6365. if (!propsCaches[uid2]) {
  6366. return;
  6367. }
  6368. return propsCaches[uid2][parseInt(propsId)];
  6369. }
  6370. var plugin = {
  6371. install(app) {
  6372. initApp(app);
  6373. app.config.globalProperties.pruneComponentPropsCache = pruneComponentPropsCache;
  6374. const oldMount = app.mount;
  6375. app.mount = function mount(rootContainer) {
  6376. const instance = oldMount.call(app, rootContainer);
  6377. const createApp2 = getCreateApp();
  6378. if (createApp2) {
  6379. createApp2(instance);
  6380. } else {
  6381. if (typeof createMiniProgramApp !== "undefined") {
  6382. createMiniProgramApp(instance);
  6383. }
  6384. }
  6385. return instance;
  6386. };
  6387. }
  6388. };
  6389. function getCreateApp() {
  6390. const method = "createApp";
  6391. if (typeof global !== "undefined" && typeof global[method] !== "undefined") {
  6392. return global[method];
  6393. } else if (typeof my !== "undefined") {
  6394. return my[method];
  6395. }
  6396. }
  6397. function stringifyStyle(value) {
  6398. if (isString(value)) {
  6399. return value;
  6400. }
  6401. return stringify$1(normalizeStyle(value));
  6402. }
  6403. function stringify$1(styles) {
  6404. let ret = "";
  6405. if (!styles || isString(styles)) {
  6406. return ret;
  6407. }
  6408. for (const key in styles) {
  6409. ret += `${key.startsWith(`--`) ? key : hyphenate(key)}:${styles[key]};`;
  6410. }
  6411. return ret;
  6412. }
  6413. function vOn(value, key) {
  6414. const instance = getCurrentInstance();
  6415. const ctx = instance.ctx;
  6416. const extraKey = typeof key !== "undefined" && (ctx.$mpPlatform === "mp-weixin" || ctx.$mpPlatform === "mp-qq" || ctx.$mpPlatform === "mp-xhs") && (isString(key) || typeof key === "number") ? "_" + key : "";
  6417. const name = "e" + instance.$ei++ + extraKey;
  6418. const mpInstance = ctx.$scope;
  6419. if (!value) {
  6420. delete mpInstance[name];
  6421. return name;
  6422. }
  6423. const existingInvoker = mpInstance[name];
  6424. if (existingInvoker) {
  6425. existingInvoker.value = value;
  6426. } else {
  6427. mpInstance[name] = createInvoker(value, instance);
  6428. }
  6429. return name;
  6430. }
  6431. function createInvoker(initialValue, instance) {
  6432. const invoker = (e2) => {
  6433. patchMPEvent(e2);
  6434. let args = [e2];
  6435. if (instance && instance.ctx.$getTriggerEventDetail) {
  6436. if (typeof e2.detail === "number") {
  6437. e2.detail = instance.ctx.$getTriggerEventDetail(e2.detail);
  6438. }
  6439. }
  6440. if (e2.detail && e2.detail.__args__) {
  6441. args = e2.detail.__args__;
  6442. }
  6443. const eventValue = invoker.value;
  6444. const invoke = () => callWithAsyncErrorHandling(patchStopImmediatePropagation(e2, eventValue), instance, 5, args);
  6445. const eventTarget = e2.target;
  6446. const eventSync = eventTarget ? eventTarget.dataset ? String(eventTarget.dataset.eventsync) === "true" : false : false;
  6447. if (bubbles.includes(e2.type) && !eventSync) {
  6448. setTimeout(invoke);
  6449. } else {
  6450. const res = invoke();
  6451. if (e2.type === "input" && (isArray(res) || isPromise$2(res))) {
  6452. return;
  6453. }
  6454. return res;
  6455. }
  6456. };
  6457. invoker.value = initialValue;
  6458. return invoker;
  6459. }
  6460. const bubbles = [
  6461. // touch事件暂不做延迟,否则在 Android 上会影响性能,比如一些拖拽跟手手势等
  6462. // 'touchstart',
  6463. // 'touchmove',
  6464. // 'touchcancel',
  6465. // 'touchend',
  6466. "tap",
  6467. "longpress",
  6468. "longtap",
  6469. "transitionend",
  6470. "animationstart",
  6471. "animationiteration",
  6472. "animationend",
  6473. "touchforcechange"
  6474. ];
  6475. function patchMPEvent(event, instance) {
  6476. if (event.type && event.target) {
  6477. event.preventDefault = NOOP;
  6478. event.stopPropagation = NOOP;
  6479. event.stopImmediatePropagation = NOOP;
  6480. if (!hasOwn(event, "detail")) {
  6481. event.detail = {};
  6482. }
  6483. if (hasOwn(event, "markerId")) {
  6484. event.detail = typeof event.detail === "object" ? event.detail : {};
  6485. event.detail.markerId = event.markerId;
  6486. }
  6487. if (isPlainObject(event.detail) && hasOwn(event.detail, "checked") && !hasOwn(event.detail, "value")) {
  6488. event.detail.value = event.detail.checked;
  6489. }
  6490. if (isPlainObject(event.detail)) {
  6491. event.target = extend({}, event.target, event.detail);
  6492. }
  6493. }
  6494. }
  6495. function patchStopImmediatePropagation(e2, value) {
  6496. if (isArray(value)) {
  6497. const originalStop = e2.stopImmediatePropagation;
  6498. e2.stopImmediatePropagation = () => {
  6499. originalStop && originalStop.call(e2);
  6500. e2._stopped = true;
  6501. };
  6502. return value.map((fn2) => (e3) => !e3._stopped && fn2(e3));
  6503. } else {
  6504. return value;
  6505. }
  6506. }
  6507. function vFor(source, renderItem) {
  6508. let ret;
  6509. if (isArray(source) || isString(source)) {
  6510. ret = new Array(source.length);
  6511. for (let i2 = 0, l2 = source.length; i2 < l2; i2++) {
  6512. ret[i2] = renderItem(source[i2], i2, i2);
  6513. }
  6514. } else if (typeof source === "number") {
  6515. if (!Number.isInteger(source)) {
  6516. warn(`The v-for range expect an integer value but got ${source}.`);
  6517. return [];
  6518. }
  6519. ret = new Array(source);
  6520. for (let i2 = 0; i2 < source; i2++) {
  6521. ret[i2] = renderItem(i2 + 1, i2, i2);
  6522. }
  6523. } else if (isObject$1(source)) {
  6524. if (source[Symbol.iterator]) {
  6525. ret = Array.from(source, (item, i2) => renderItem(item, i2, i2));
  6526. } else {
  6527. const keys = Object.keys(source);
  6528. ret = new Array(keys.length);
  6529. for (let i2 = 0, l2 = keys.length; i2 < l2; i2++) {
  6530. const key = keys[i2];
  6531. ret[i2] = renderItem(source[key], key, i2);
  6532. }
  6533. }
  6534. } else {
  6535. ret = [];
  6536. }
  6537. return ret;
  6538. }
  6539. function setRef(ref2, id, opts = {}) {
  6540. const { $templateRefs } = getCurrentInstance();
  6541. $templateRefs.push({ i: id, r: ref2, k: opts.k, f: opts.f });
  6542. }
  6543. const o$1 = (value, key) => vOn(value, key);
  6544. const f$1 = (source, renderItem) => vFor(source, renderItem);
  6545. const s$1 = (value) => stringifyStyle(value);
  6546. const e$1 = (target, ...sources) => extend(target, ...sources);
  6547. const n$1 = (value) => normalizeClass(value);
  6548. const t$1 = (val) => toDisplayString(val);
  6549. const p$1 = (props) => renderProps(props);
  6550. const sr = (ref2, id, opts) => setRef(ref2, id, opts);
  6551. function createApp$1(rootComponent, rootProps = null) {
  6552. rootComponent && (rootComponent.mpType = "app");
  6553. return createVueApp(rootComponent, rootProps).use(plugin);
  6554. }
  6555. const createSSRApp = createApp$1;
  6556. function initVueIds(vueIds, mpInstance) {
  6557. if (!vueIds) {
  6558. return;
  6559. }
  6560. const ids = vueIds.split(",");
  6561. const len = ids.length;
  6562. if (len === 1) {
  6563. mpInstance._$vueId = ids[0];
  6564. } else if (len === 2) {
  6565. mpInstance._$vueId = ids[0];
  6566. mpInstance._$vuePid = ids[1];
  6567. }
  6568. }
  6569. const EXTRAS = ["externalClasses"];
  6570. function initExtraOptions(miniProgramComponentOptions, vueOptions) {
  6571. EXTRAS.forEach((name) => {
  6572. if (hasOwn(vueOptions, name)) {
  6573. miniProgramComponentOptions[name] = vueOptions[name];
  6574. }
  6575. });
  6576. }
  6577. const WORKLET_RE = /_(.*)_worklet_factory_/;
  6578. function initWorkletMethods(mpMethods, vueMethods) {
  6579. if (vueMethods) {
  6580. Object.keys(vueMethods).forEach((name) => {
  6581. const matches = name.match(WORKLET_RE);
  6582. if (matches) {
  6583. const workletName = matches[1];
  6584. mpMethods[name] = vueMethods[name];
  6585. mpMethods[workletName] = vueMethods[workletName];
  6586. }
  6587. });
  6588. }
  6589. }
  6590. function initWxsCallMethods(methods, wxsCallMethods) {
  6591. if (!isArray(wxsCallMethods)) {
  6592. return;
  6593. }
  6594. wxsCallMethods.forEach((callMethod) => {
  6595. methods[callMethod] = function(args) {
  6596. return this.$vm[callMethod](args);
  6597. };
  6598. });
  6599. }
  6600. function selectAllComponents(mpInstance, selector, $refs) {
  6601. const components = mpInstance.selectAllComponents(selector);
  6602. components.forEach((component) => {
  6603. const ref2 = component.properties.uR;
  6604. $refs[ref2] = component.$vm || component;
  6605. });
  6606. }
  6607. function initRefs(instance, mpInstance) {
  6608. Object.defineProperty(instance, "refs", {
  6609. get() {
  6610. const $refs = {};
  6611. selectAllComponents(mpInstance, ".r", $refs);
  6612. const forComponents = mpInstance.selectAllComponents(".r-i-f");
  6613. forComponents.forEach((component) => {
  6614. const ref2 = component.properties.uR;
  6615. if (!ref2) {
  6616. return;
  6617. }
  6618. if (!$refs[ref2]) {
  6619. $refs[ref2] = [];
  6620. }
  6621. $refs[ref2].push(component.$vm || component);
  6622. });
  6623. return $refs;
  6624. }
  6625. });
  6626. }
  6627. function findVmByVueId(instance, vuePid) {
  6628. const $children = instance.$children;
  6629. for (let i2 = $children.length - 1; i2 >= 0; i2--) {
  6630. const childVm = $children[i2];
  6631. if (childVm.$scope._$vueId === vuePid) {
  6632. return childVm;
  6633. }
  6634. }
  6635. let parentVm;
  6636. for (let i2 = $children.length - 1; i2 >= 0; i2--) {
  6637. parentVm = findVmByVueId($children[i2], vuePid);
  6638. if (parentVm) {
  6639. return parentVm;
  6640. }
  6641. }
  6642. }
  6643. function getLocaleLanguage() {
  6644. var _a;
  6645. let localeLanguage = "";
  6646. {
  6647. const appBaseInfo = ((_a = wx.getAppBaseInfo) === null || _a === void 0 ? void 0 : _a.call(wx)) || wx.getSystemInfoSync();
  6648. const language = appBaseInfo && appBaseInfo.language ? appBaseInfo.language : LOCALE_EN;
  6649. localeLanguage = normalizeLocale(language) || LOCALE_EN;
  6650. }
  6651. return localeLanguage;
  6652. }
  6653. const MP_METHODS = [
  6654. "createSelectorQuery",
  6655. "createIntersectionObserver",
  6656. "selectAllComponents",
  6657. "selectComponent"
  6658. ];
  6659. function createEmitFn(oldEmit, ctx) {
  6660. return function emit2(event, ...args) {
  6661. const scope = ctx.$scope;
  6662. if (scope && event) {
  6663. const detail = { __args__: args };
  6664. {
  6665. scope.triggerEvent(event, detail);
  6666. }
  6667. }
  6668. return oldEmit.apply(this, [event, ...args]);
  6669. };
  6670. }
  6671. function initBaseInstance(instance, options) {
  6672. const ctx = instance.ctx;
  6673. ctx.mpType = options.mpType;
  6674. ctx.$mpType = options.mpType;
  6675. ctx.$mpPlatform = "mp-weixin";
  6676. ctx.$scope = options.mpInstance;
  6677. {
  6678. Object.defineProperties(ctx, {
  6679. // only id
  6680. [VIRTUAL_HOST_ID]: {
  6681. get() {
  6682. const id = this.$scope.data[VIRTUAL_HOST_ID];
  6683. return id === void 0 ? "" : id;
  6684. }
  6685. }
  6686. });
  6687. }
  6688. ctx.$mp = {};
  6689. {
  6690. ctx._self = {};
  6691. }
  6692. instance.slots = {};
  6693. if (isArray(options.slots) && options.slots.length) {
  6694. options.slots.forEach((name) => {
  6695. instance.slots[name] = true;
  6696. });
  6697. if (instance.slots[SLOT_DEFAULT_NAME]) {
  6698. instance.slots.default = true;
  6699. }
  6700. }
  6701. ctx.getOpenerEventChannel = function() {
  6702. {
  6703. return options.mpInstance.getOpenerEventChannel();
  6704. }
  6705. };
  6706. ctx.$hasHook = hasHook;
  6707. ctx.$callHook = callHook;
  6708. instance.emit = createEmitFn(instance.emit, ctx);
  6709. }
  6710. function initComponentInstance(instance, options) {
  6711. initBaseInstance(instance, options);
  6712. const ctx = instance.ctx;
  6713. MP_METHODS.forEach((method) => {
  6714. ctx[method] = function(...args) {
  6715. const mpInstance = ctx.$scope;
  6716. if (mpInstance && mpInstance[method]) {
  6717. return mpInstance[method].apply(mpInstance, args);
  6718. }
  6719. };
  6720. });
  6721. }
  6722. function initMocks(instance, mpInstance, mocks2) {
  6723. const ctx = instance.ctx;
  6724. mocks2.forEach((mock) => {
  6725. if (hasOwn(mpInstance, mock)) {
  6726. instance[mock] = ctx[mock] = mpInstance[mock];
  6727. }
  6728. });
  6729. }
  6730. function hasHook(name) {
  6731. const hooks = this.$[name];
  6732. if (hooks && hooks.length) {
  6733. return true;
  6734. }
  6735. return false;
  6736. }
  6737. function callHook(name, args) {
  6738. if (name === "mounted") {
  6739. callHook.call(this, "bm");
  6740. this.$.isMounted = true;
  6741. name = "m";
  6742. }
  6743. const hooks = this.$[name];
  6744. return hooks && invokeArrayFns(hooks, args);
  6745. }
  6746. const PAGE_INIT_HOOKS = [
  6747. ON_LOAD,
  6748. ON_SHOW,
  6749. ON_HIDE,
  6750. ON_UNLOAD,
  6751. ON_RESIZE,
  6752. ON_TAB_ITEM_TAP,
  6753. ON_REACH_BOTTOM,
  6754. ON_PULL_DOWN_REFRESH,
  6755. ON_ADD_TO_FAVORITES
  6756. // 'onReady', // lifetimes.ready
  6757. // 'onPageScroll', // 影响性能,开发者手动注册
  6758. // 'onShareTimeline', // 右上角菜单,开发者手动注册
  6759. // 'onShareAppMessage' // 右上角菜单,开发者手动注册
  6760. ];
  6761. function findHooks(vueOptions, hooks = /* @__PURE__ */ new Set()) {
  6762. if (vueOptions) {
  6763. Object.keys(vueOptions).forEach((name) => {
  6764. if (isUniLifecycleHook(name, vueOptions[name])) {
  6765. hooks.add(name);
  6766. }
  6767. });
  6768. {
  6769. const { extends: extendsOptions, mixins } = vueOptions;
  6770. if (mixins) {
  6771. mixins.forEach((mixin) => findHooks(mixin, hooks));
  6772. }
  6773. if (extendsOptions) {
  6774. findHooks(extendsOptions, hooks);
  6775. }
  6776. }
  6777. }
  6778. return hooks;
  6779. }
  6780. function initHook(mpOptions, hook, excludes) {
  6781. if (excludes.indexOf(hook) === -1 && !hasOwn(mpOptions, hook)) {
  6782. mpOptions[hook] = function(args) {
  6783. return this.$vm && this.$vm.$callHook(hook, args);
  6784. };
  6785. }
  6786. }
  6787. const EXCLUDE_HOOKS = [ON_READY];
  6788. function initHooks(mpOptions, hooks, excludes = EXCLUDE_HOOKS) {
  6789. hooks.forEach((hook) => initHook(mpOptions, hook, excludes));
  6790. }
  6791. function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) {
  6792. findHooks(vueOptions).forEach((hook) => initHook(mpOptions, hook, excludes));
  6793. }
  6794. function initRuntimeHooks(mpOptions, runtimeHooks) {
  6795. if (!runtimeHooks) {
  6796. return;
  6797. }
  6798. const hooks = Object.keys(MINI_PROGRAM_PAGE_RUNTIME_HOOKS);
  6799. hooks.forEach((hook) => {
  6800. if (runtimeHooks & MINI_PROGRAM_PAGE_RUNTIME_HOOKS[hook]) {
  6801. initHook(mpOptions, hook, []);
  6802. }
  6803. });
  6804. }
  6805. const findMixinRuntimeHooks = /* @__PURE__ */ once(() => {
  6806. const runtimeHooks = [];
  6807. const app = isFunction(getApp) && getApp({ allowDefault: true });
  6808. if (app && app.$vm && app.$vm.$) {
  6809. const mixins = app.$vm.$.appContext.mixins;
  6810. if (isArray(mixins)) {
  6811. const hooks = Object.keys(MINI_PROGRAM_PAGE_RUNTIME_HOOKS);
  6812. mixins.forEach((mixin) => {
  6813. hooks.forEach((hook) => {
  6814. if (hasOwn(mixin, hook) && !runtimeHooks.includes(hook)) {
  6815. runtimeHooks.push(hook);
  6816. }
  6817. });
  6818. });
  6819. }
  6820. }
  6821. return runtimeHooks;
  6822. });
  6823. function initMixinRuntimeHooks(mpOptions) {
  6824. initHooks(mpOptions, findMixinRuntimeHooks());
  6825. }
  6826. const HOOKS = [
  6827. ON_SHOW,
  6828. ON_HIDE,
  6829. ON_ERROR,
  6830. ON_THEME_CHANGE,
  6831. ON_PAGE_NOT_FOUND,
  6832. ON_UNHANDLE_REJECTION
  6833. ];
  6834. function parseApp(instance, parseAppOptions) {
  6835. const internalInstance = instance.$;
  6836. const appOptions = {
  6837. globalData: instance.$options && instance.$options.globalData || {},
  6838. $vm: instance,
  6839. // mp-alipay 组件 data 初始化比 onLaunch 早,提前挂载
  6840. onLaunch(options) {
  6841. this.$vm = instance;
  6842. const ctx = internalInstance.ctx;
  6843. if (this.$vm && ctx.$scope && ctx.$callHook) {
  6844. return;
  6845. }
  6846. initBaseInstance(internalInstance, {
  6847. mpType: "app",
  6848. mpInstance: this,
  6849. slots: []
  6850. });
  6851. ctx.globalData = this.globalData;
  6852. instance.$callHook(ON_LAUNCH, options);
  6853. }
  6854. };
  6855. const onErrorHandlers = wx.$onErrorHandlers;
  6856. if (onErrorHandlers) {
  6857. onErrorHandlers.forEach((fn2) => {
  6858. injectHook(ON_ERROR, fn2, internalInstance);
  6859. });
  6860. onErrorHandlers.length = 0;
  6861. }
  6862. initLocale(instance);
  6863. const vueOptions = instance.$.type;
  6864. initHooks(appOptions, HOOKS);
  6865. initUnknownHooks(appOptions, vueOptions);
  6866. {
  6867. const methods = vueOptions.methods;
  6868. methods && extend(appOptions, methods);
  6869. }
  6870. return appOptions;
  6871. }
  6872. function initCreateApp(parseAppOptions) {
  6873. return function createApp2(vm) {
  6874. return App(parseApp(vm));
  6875. };
  6876. }
  6877. function initCreateSubpackageApp(parseAppOptions) {
  6878. return function createApp2(vm) {
  6879. const appOptions = parseApp(vm);
  6880. const app = isFunction(getApp) && getApp({
  6881. allowDefault: true
  6882. });
  6883. if (!app)
  6884. return;
  6885. vm.$.ctx.$scope = app;
  6886. const globalData = app.globalData;
  6887. if (globalData) {
  6888. Object.keys(appOptions.globalData).forEach((name) => {
  6889. if (!hasOwn(globalData, name)) {
  6890. globalData[name] = appOptions.globalData[name];
  6891. }
  6892. });
  6893. }
  6894. Object.keys(appOptions).forEach((name) => {
  6895. if (!hasOwn(app, name)) {
  6896. app[name] = appOptions[name];
  6897. }
  6898. });
  6899. initAppLifecycle(appOptions, vm);
  6900. };
  6901. }
  6902. function initAppLifecycle(appOptions, vm) {
  6903. if (isFunction(appOptions.onLaunch)) {
  6904. const args = wx.getLaunchOptionsSync && wx.getLaunchOptionsSync();
  6905. appOptions.onLaunch(args);
  6906. }
  6907. if (isFunction(appOptions.onShow) && wx.onAppShow) {
  6908. wx.onAppShow((args) => {
  6909. vm.$callHook("onShow", args);
  6910. });
  6911. }
  6912. if (isFunction(appOptions.onHide) && wx.onAppHide) {
  6913. wx.onAppHide((args) => {
  6914. vm.$callHook("onHide", args);
  6915. });
  6916. }
  6917. }
  6918. function initLocale(appVm) {
  6919. const locale = ref(getLocaleLanguage());
  6920. Object.defineProperty(appVm, "$locale", {
  6921. get() {
  6922. return locale.value;
  6923. },
  6924. set(v2) {
  6925. locale.value = v2;
  6926. }
  6927. });
  6928. }
  6929. const builtInProps = [
  6930. // 百度小程序,快手小程序自定义组件不支持绑定动态事件,动态dataset,故通过props传递事件信息
  6931. // event-opts
  6932. "eO",
  6933. // 组件 ref
  6934. "uR",
  6935. // 组件 ref-in-for
  6936. "uRIF",
  6937. // 组件 id
  6938. "uI",
  6939. // 组件类型 m: 小程序组件
  6940. "uT",
  6941. // 组件 props
  6942. "uP",
  6943. // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots
  6944. "uS"
  6945. ];
  6946. function initDefaultProps(options, isBehavior = false) {
  6947. const properties = {};
  6948. if (!isBehavior) {
  6949. let observerSlots = function(newVal) {
  6950. const $slots = /* @__PURE__ */ Object.create(null);
  6951. newVal && newVal.forEach((slotName) => {
  6952. $slots[slotName] = true;
  6953. });
  6954. this.setData({
  6955. $slots
  6956. });
  6957. };
  6958. builtInProps.forEach((name) => {
  6959. properties[name] = {
  6960. type: null,
  6961. value: ""
  6962. };
  6963. });
  6964. properties.uS = {
  6965. type: null,
  6966. value: []
  6967. };
  6968. {
  6969. properties.uS.observer = observerSlots;
  6970. }
  6971. }
  6972. if (options.behaviors) {
  6973. if (options.behaviors.includes("wx://form-field")) {
  6974. if (!options.properties || !options.properties.name) {
  6975. properties.name = {
  6976. type: null,
  6977. value: ""
  6978. };
  6979. }
  6980. if (!options.properties || !options.properties.value) {
  6981. properties.value = {
  6982. type: null,
  6983. value: ""
  6984. };
  6985. }
  6986. }
  6987. }
  6988. return properties;
  6989. }
  6990. function initVirtualHostProps(options) {
  6991. const properties = {};
  6992. {
  6993. if (options && options.virtualHost) {
  6994. properties[VIRTUAL_HOST_STYLE] = {
  6995. type: null,
  6996. value: ""
  6997. };
  6998. properties[VIRTUAL_HOST_CLASS] = {
  6999. type: null,
  7000. value: ""
  7001. };
  7002. properties[VIRTUAL_HOST_HIDDEN] = {
  7003. type: null,
  7004. value: ""
  7005. };
  7006. properties[VIRTUAL_HOST_ID] = {
  7007. type: null,
  7008. value: ""
  7009. };
  7010. }
  7011. }
  7012. return properties;
  7013. }
  7014. function initProps(mpComponentOptions) {
  7015. if (!mpComponentOptions.properties) {
  7016. mpComponentOptions.properties = {};
  7017. }
  7018. extend(mpComponentOptions.properties, initDefaultProps(mpComponentOptions), initVirtualHostProps(mpComponentOptions.options));
  7019. }
  7020. const PROP_TYPES = [String, Number, Boolean, Object, Array, null];
  7021. function parsePropType(type, defaultValue) {
  7022. if (isArray(type) && type.length === 1) {
  7023. return type[0];
  7024. }
  7025. return type;
  7026. }
  7027. function normalizePropType(type, defaultValue) {
  7028. const res = parsePropType(type);
  7029. return PROP_TYPES.indexOf(res) !== -1 ? res : null;
  7030. }
  7031. function initPageProps({ properties }, rawProps) {
  7032. if (isArray(rawProps)) {
  7033. rawProps.forEach((key) => {
  7034. properties[key] = {
  7035. type: String,
  7036. value: ""
  7037. };
  7038. });
  7039. } else if (isPlainObject(rawProps)) {
  7040. Object.keys(rawProps).forEach((key) => {
  7041. const opts = rawProps[key];
  7042. if (isPlainObject(opts)) {
  7043. let value = opts.default;
  7044. if (isFunction(value)) {
  7045. value = value();
  7046. }
  7047. const type = opts.type;
  7048. opts.type = normalizePropType(type);
  7049. properties[key] = {
  7050. type: opts.type,
  7051. value
  7052. };
  7053. } else {
  7054. properties[key] = {
  7055. type: normalizePropType(opts)
  7056. };
  7057. }
  7058. });
  7059. }
  7060. }
  7061. function findPropsData(properties, isPage2) {
  7062. return (isPage2 ? findPagePropsData(properties) : findComponentPropsData(resolvePropValue(properties.uP))) || {};
  7063. }
  7064. function findPagePropsData(properties) {
  7065. const propsData = {};
  7066. if (isPlainObject(properties)) {
  7067. Object.keys(properties).forEach((name) => {
  7068. if (builtInProps.indexOf(name) === -1) {
  7069. propsData[name] = resolvePropValue(properties[name]);
  7070. }
  7071. });
  7072. }
  7073. return propsData;
  7074. }
  7075. function initFormField(vm) {
  7076. const vueOptions = vm.$options;
  7077. if (isArray(vueOptions.behaviors) && vueOptions.behaviors.includes("uni://form-field")) {
  7078. vm.$watch("modelValue", () => {
  7079. vm.$scope && vm.$scope.setData({
  7080. name: vm.name,
  7081. value: vm.modelValue
  7082. });
  7083. }, {
  7084. immediate: true
  7085. });
  7086. }
  7087. }
  7088. function resolvePropValue(prop) {
  7089. return prop;
  7090. }
  7091. function initData(_2) {
  7092. return {};
  7093. }
  7094. function initPropsObserver(componentOptions) {
  7095. const observe = function observe2() {
  7096. const up = this.properties.uP;
  7097. if (!up) {
  7098. return;
  7099. }
  7100. if (this.$vm) {
  7101. updateComponentProps(resolvePropValue(up), this.$vm.$);
  7102. } else if (resolvePropValue(this.properties.uT) === "m") {
  7103. updateMiniProgramComponentProperties(resolvePropValue(up), this);
  7104. }
  7105. };
  7106. {
  7107. if (!componentOptions.observers) {
  7108. componentOptions.observers = {};
  7109. }
  7110. componentOptions.observers.uP = observe;
  7111. }
  7112. }
  7113. function updateMiniProgramComponentProperties(up, mpInstance) {
  7114. const prevProps = mpInstance.properties;
  7115. const nextProps = findComponentPropsData(up) || {};
  7116. if (hasPropsChanged(prevProps, nextProps, false)) {
  7117. mpInstance.setData(nextProps);
  7118. }
  7119. }
  7120. function updateComponentProps(up, instance) {
  7121. const prevProps = toRaw(instance.props);
  7122. const nextProps = findComponentPropsData(up) || {};
  7123. if (hasPropsChanged(prevProps, nextProps)) {
  7124. updateProps(instance, nextProps, prevProps, false);
  7125. if (hasQueueJob(instance.update)) {
  7126. invalidateJob(instance.update);
  7127. }
  7128. {
  7129. instance.update();
  7130. }
  7131. }
  7132. }
  7133. function hasPropsChanged(prevProps, nextProps, checkLen = true) {
  7134. const nextKeys = Object.keys(nextProps);
  7135. if (checkLen && nextKeys.length !== Object.keys(prevProps).length) {
  7136. return true;
  7137. }
  7138. for (let i2 = 0; i2 < nextKeys.length; i2++) {
  7139. const key = nextKeys[i2];
  7140. if (nextProps[key] !== prevProps[key]) {
  7141. return true;
  7142. }
  7143. }
  7144. return false;
  7145. }
  7146. function initBehaviors(vueOptions) {
  7147. const vueBehaviors = vueOptions.behaviors;
  7148. let vueProps = vueOptions.props;
  7149. if (!vueProps) {
  7150. vueOptions.props = vueProps = [];
  7151. }
  7152. const behaviors = [];
  7153. if (isArray(vueBehaviors)) {
  7154. vueBehaviors.forEach((behavior) => {
  7155. behaviors.push(behavior.replace("uni://", "wx://"));
  7156. if (behavior === "uni://form-field") {
  7157. if (isArray(vueProps)) {
  7158. vueProps.push("name");
  7159. vueProps.push("modelValue");
  7160. } else {
  7161. vueProps.name = {
  7162. type: String,
  7163. default: ""
  7164. };
  7165. vueProps.modelValue = {
  7166. type: [String, Number, Boolean, Array, Object, Date],
  7167. default: ""
  7168. };
  7169. }
  7170. }
  7171. });
  7172. }
  7173. return behaviors;
  7174. }
  7175. function applyOptions(componentOptions, vueOptions) {
  7176. componentOptions.data = initData();
  7177. componentOptions.behaviors = initBehaviors(vueOptions);
  7178. }
  7179. function parseComponent(vueOptions, { parse, mocks: mocks2, isPage: isPage2, isPageInProject, initRelation: initRelation2, handleLink: handleLink2, initLifetimes: initLifetimes2 }) {
  7180. vueOptions = vueOptions.default || vueOptions;
  7181. const options = {
  7182. multipleSlots: true,
  7183. // styleIsolation: 'apply-shared',
  7184. addGlobalClass: true,
  7185. pureDataPattern: /^uP$/
  7186. };
  7187. if (isArray(vueOptions.mixins)) {
  7188. vueOptions.mixins.forEach((item) => {
  7189. if (isObject$1(item.options)) {
  7190. extend(options, item.options);
  7191. }
  7192. });
  7193. }
  7194. if (vueOptions.options) {
  7195. extend(options, vueOptions.options);
  7196. }
  7197. const mpComponentOptions = {
  7198. options,
  7199. lifetimes: initLifetimes2({ mocks: mocks2, isPage: isPage2, initRelation: initRelation2, vueOptions }),
  7200. pageLifetimes: {
  7201. show() {
  7202. this.$vm && this.$vm.$callHook("onPageShow");
  7203. },
  7204. hide() {
  7205. this.$vm && this.$vm.$callHook("onPageHide");
  7206. },
  7207. resize(size2) {
  7208. this.$vm && this.$vm.$callHook("onPageResize", size2);
  7209. }
  7210. },
  7211. methods: {
  7212. __l: handleLink2
  7213. }
  7214. };
  7215. {
  7216. applyOptions(mpComponentOptions, vueOptions);
  7217. }
  7218. initProps(mpComponentOptions);
  7219. initPropsObserver(mpComponentOptions);
  7220. initExtraOptions(mpComponentOptions, vueOptions);
  7221. initWxsCallMethods(mpComponentOptions.methods, vueOptions.wxsCallMethods);
  7222. {
  7223. initWorkletMethods(mpComponentOptions.methods, vueOptions.methods);
  7224. }
  7225. if (parse) {
  7226. parse(mpComponentOptions, { handleLink: handleLink2 });
  7227. }
  7228. return mpComponentOptions;
  7229. }
  7230. function initCreateComponent(parseOptions2) {
  7231. return function createComponent2(vueComponentOptions) {
  7232. return Component(parseComponent(vueComponentOptions, parseOptions2));
  7233. };
  7234. }
  7235. let $createComponentFn;
  7236. let $destroyComponentFn;
  7237. function getAppVm() {
  7238. return getApp().$vm;
  7239. }
  7240. function $createComponent(initialVNode, options) {
  7241. if (!$createComponentFn) {
  7242. $createComponentFn = getAppVm().$createComponent;
  7243. }
  7244. const proxy = $createComponentFn(initialVNode, options);
  7245. return getExposeProxy(proxy.$) || proxy;
  7246. }
  7247. function $destroyComponent(instance) {
  7248. if (!$destroyComponentFn) {
  7249. $destroyComponentFn = getAppVm().$destroyComponent;
  7250. }
  7251. return $destroyComponentFn(instance);
  7252. }
  7253. function parsePage(vueOptions, parseOptions2) {
  7254. const { parse, mocks: mocks2, isPage: isPage2, initRelation: initRelation2, handleLink: handleLink2, initLifetimes: initLifetimes2 } = parseOptions2;
  7255. const miniProgramPageOptions = parseComponent(vueOptions, {
  7256. mocks: mocks2,
  7257. isPage: isPage2,
  7258. isPageInProject: true,
  7259. initRelation: initRelation2,
  7260. handleLink: handleLink2,
  7261. initLifetimes: initLifetimes2
  7262. });
  7263. initPageProps(miniProgramPageOptions, (vueOptions.default || vueOptions).props);
  7264. const methods = miniProgramPageOptions.methods;
  7265. methods.onLoad = function(query) {
  7266. {
  7267. this.options = query;
  7268. }
  7269. this.$page = {
  7270. fullPath: addLeadingSlash(this.route + stringifyQuery(query))
  7271. };
  7272. return this.$vm && this.$vm.$callHook(ON_LOAD, query);
  7273. };
  7274. initHooks(methods, PAGE_INIT_HOOKS);
  7275. {
  7276. initUnknownHooks(methods, vueOptions);
  7277. }
  7278. initRuntimeHooks(methods, vueOptions.__runtimeHooks);
  7279. initMixinRuntimeHooks(methods);
  7280. parse && parse(miniProgramPageOptions, { handleLink: handleLink2 });
  7281. return miniProgramPageOptions;
  7282. }
  7283. function initCreatePage(parseOptions2) {
  7284. return function createPage2(vuePageOptions) {
  7285. return Component(parsePage(vuePageOptions, parseOptions2));
  7286. };
  7287. }
  7288. function initCreatePluginApp(parseAppOptions) {
  7289. return function createApp2(vm) {
  7290. initAppLifecycle(parseApp(vm), vm);
  7291. };
  7292. }
  7293. const MPPage = Page;
  7294. const MPComponent = Component;
  7295. function initTriggerEvent(mpInstance) {
  7296. const oldTriggerEvent = mpInstance.triggerEvent;
  7297. const newTriggerEvent = function(event, ...args) {
  7298. return oldTriggerEvent.apply(mpInstance, [
  7299. customizeEvent(event),
  7300. ...args
  7301. ]);
  7302. };
  7303. try {
  7304. mpInstance.triggerEvent = newTriggerEvent;
  7305. } catch (error) {
  7306. mpInstance._triggerEvent = newTriggerEvent;
  7307. }
  7308. }
  7309. function initMiniProgramHook(name, options, isComponent) {
  7310. const oldHook = options[name];
  7311. if (!oldHook) {
  7312. options[name] = function() {
  7313. initTriggerEvent(this);
  7314. };
  7315. } else {
  7316. options[name] = function(...args) {
  7317. initTriggerEvent(this);
  7318. return oldHook.apply(this, args);
  7319. };
  7320. }
  7321. }
  7322. Page = function(options) {
  7323. initMiniProgramHook(ON_LOAD, options);
  7324. return MPPage(options);
  7325. };
  7326. Component = function(options) {
  7327. initMiniProgramHook("created", options);
  7328. const isVueComponent = options.properties && options.properties.uP;
  7329. if (!isVueComponent) {
  7330. initProps(options);
  7331. initPropsObserver(options);
  7332. }
  7333. return MPComponent(options);
  7334. };
  7335. function initLifetimes({ mocks: mocks2, isPage: isPage2, initRelation: initRelation2, vueOptions }) {
  7336. return {
  7337. attached() {
  7338. let properties = this.properties;
  7339. initVueIds(properties.uI, this);
  7340. const relationOptions = {
  7341. vuePid: this._$vuePid
  7342. };
  7343. initRelation2(this, relationOptions);
  7344. const mpInstance = this;
  7345. const isMiniProgramPage = isPage2(mpInstance);
  7346. let propsData = properties;
  7347. this.$vm = $createComponent({
  7348. type: vueOptions,
  7349. props: findPropsData(propsData, isMiniProgramPage)
  7350. }, {
  7351. mpType: isMiniProgramPage ? "page" : "component",
  7352. mpInstance,
  7353. slots: properties.uS || {},
  7354. // vueSlots
  7355. parentComponent: relationOptions.parent && relationOptions.parent.$,
  7356. onBeforeSetup(instance, options) {
  7357. initRefs(instance, mpInstance);
  7358. initMocks(instance, mpInstance, mocks2);
  7359. initComponentInstance(instance, options);
  7360. }
  7361. });
  7362. if (!isMiniProgramPage) {
  7363. initFormField(this.$vm);
  7364. }
  7365. },
  7366. ready() {
  7367. if (this.$vm) {
  7368. {
  7369. this.$vm.$callHook("mounted");
  7370. this.$vm.$callHook(ON_READY);
  7371. }
  7372. }
  7373. },
  7374. detached() {
  7375. if (this.$vm) {
  7376. pruneComponentPropsCache(this.$vm.$.uid);
  7377. $destroyComponent(this.$vm);
  7378. }
  7379. }
  7380. };
  7381. }
  7382. const mocks = ["__route__", "__wxExparserNodeId__", "__wxWebviewId__"];
  7383. function isPage(mpInstance) {
  7384. return !!mpInstance.route;
  7385. }
  7386. function initRelation(mpInstance, detail) {
  7387. mpInstance.triggerEvent("__l", detail);
  7388. }
  7389. function handleLink(event) {
  7390. const detail = event.detail || event.value;
  7391. const vuePid = detail.vuePid;
  7392. let parentVm;
  7393. if (vuePid) {
  7394. parentVm = findVmByVueId(this.$vm, vuePid);
  7395. }
  7396. if (!parentVm) {
  7397. parentVm = this.$vm;
  7398. }
  7399. detail.parent = parentVm;
  7400. }
  7401. var parseOptions$1 = /* @__PURE__ */ Object.freeze({
  7402. __proto__: null,
  7403. handleLink,
  7404. initLifetimes,
  7405. initRelation,
  7406. isPage,
  7407. mocks
  7408. });
  7409. const createApp = initCreateApp();
  7410. const createPage = initCreatePage(parseOptions$1);
  7411. const createComponent = initCreateComponent(parseOptions$1);
  7412. const createPluginApp = initCreatePluginApp();
  7413. const createSubpackageApp = initCreateSubpackageApp();
  7414. {
  7415. wx.createApp = global.createApp = createApp;
  7416. wx.createPage = createPage;
  7417. wx.createComponent = createComponent;
  7418. wx.createPluginApp = global.createPluginApp = createPluginApp;
  7419. wx.createSubpackageApp = global.createSubpackageApp = createSubpackageApp;
  7420. }
  7421. /*!
  7422. * vuex v4.1.0
  7423. * (c) 2022 Evan You
  7424. * @license MIT
  7425. */
  7426. var storeKey = "store";
  7427. function useStore(key) {
  7428. if (key === void 0)
  7429. key = null;
  7430. return inject(key !== null ? key : storeKey);
  7431. }
  7432. function forEachValue(obj, fn2) {
  7433. Object.keys(obj).forEach(function(key) {
  7434. return fn2(obj[key], key);
  7435. });
  7436. }
  7437. function isObject(obj) {
  7438. return obj !== null && typeof obj === "object";
  7439. }
  7440. function isPromise$1(val) {
  7441. return val && typeof val.then === "function";
  7442. }
  7443. function assert(condition, msg) {
  7444. if (!condition) {
  7445. throw new Error("[vuex] " + msg);
  7446. }
  7447. }
  7448. function partial(fn2, arg) {
  7449. return function() {
  7450. return fn2(arg);
  7451. };
  7452. }
  7453. function genericSubscribe(fn2, subs, options) {
  7454. if (subs.indexOf(fn2) < 0) {
  7455. options && options.prepend ? subs.unshift(fn2) : subs.push(fn2);
  7456. }
  7457. return function() {
  7458. var i2 = subs.indexOf(fn2);
  7459. if (i2 > -1) {
  7460. subs.splice(i2, 1);
  7461. }
  7462. };
  7463. }
  7464. function resetStore(store, hot) {
  7465. store._actions = /* @__PURE__ */ Object.create(null);
  7466. store._mutations = /* @__PURE__ */ Object.create(null);
  7467. store._wrappedGetters = /* @__PURE__ */ Object.create(null);
  7468. store._modulesNamespaceMap = /* @__PURE__ */ Object.create(null);
  7469. var state = store.state;
  7470. installModule(store, state, [], store._modules.root, true);
  7471. resetStoreState(store, state, hot);
  7472. }
  7473. function resetStoreState(store, state, hot) {
  7474. var oldState = store._state;
  7475. var oldScope = store._scope;
  7476. store.getters = {};
  7477. store._makeLocalGettersCache = /* @__PURE__ */ Object.create(null);
  7478. var wrappedGetters = store._wrappedGetters;
  7479. var computedObj = {};
  7480. var computedCache = {};
  7481. var scope = effectScope(true);
  7482. scope.run(function() {
  7483. forEachValue(wrappedGetters, function(fn2, key) {
  7484. computedObj[key] = partial(fn2, store);
  7485. computedCache[key] = computed(function() {
  7486. return computedObj[key]();
  7487. });
  7488. Object.defineProperty(store.getters, key, {
  7489. get: function() {
  7490. return computedCache[key].value;
  7491. },
  7492. enumerable: true
  7493. // for local getters
  7494. });
  7495. });
  7496. });
  7497. store._state = reactive({
  7498. data: state
  7499. });
  7500. store._scope = scope;
  7501. if (store.strict) {
  7502. enableStrictMode(store);
  7503. }
  7504. if (oldState) {
  7505. if (hot) {
  7506. store._withCommit(function() {
  7507. oldState.data = null;
  7508. });
  7509. }
  7510. }
  7511. if (oldScope) {
  7512. oldScope.stop();
  7513. }
  7514. }
  7515. function installModule(store, rootState, path, module2, hot) {
  7516. var isRoot = !path.length;
  7517. var namespace = store._modules.getNamespace(path);
  7518. if (module2.namespaced) {
  7519. if (store._modulesNamespaceMap[namespace] && true) {
  7520. console.error("[vuex] duplicate namespace " + namespace + " for the namespaced module " + path.join("/"));
  7521. }
  7522. store._modulesNamespaceMap[namespace] = module2;
  7523. }
  7524. if (!isRoot && !hot) {
  7525. var parentState = getNestedState(rootState, path.slice(0, -1));
  7526. var moduleName = path[path.length - 1];
  7527. store._withCommit(function() {
  7528. {
  7529. if (moduleName in parentState) {
  7530. console.warn(
  7531. '[vuex] state field "' + moduleName + '" was overridden by a module with the same name at "' + path.join(".") + '"'
  7532. );
  7533. }
  7534. }
  7535. parentState[moduleName] = module2.state;
  7536. });
  7537. }
  7538. var local = module2.context = makeLocalContext(store, namespace, path);
  7539. module2.forEachMutation(function(mutation, key) {
  7540. var namespacedType = namespace + key;
  7541. registerMutation(store, namespacedType, mutation, local);
  7542. });
  7543. module2.forEachAction(function(action, key) {
  7544. var type = action.root ? key : namespace + key;
  7545. var handler = action.handler || action;
  7546. registerAction(store, type, handler, local);
  7547. });
  7548. module2.forEachGetter(function(getter, key) {
  7549. var namespacedType = namespace + key;
  7550. registerGetter(store, namespacedType, getter, local);
  7551. });
  7552. module2.forEachChild(function(child, key) {
  7553. installModule(store, rootState, path.concat(key), child, hot);
  7554. });
  7555. }
  7556. function makeLocalContext(store, namespace, path) {
  7557. var noNamespace = namespace === "";
  7558. var local = {
  7559. dispatch: noNamespace ? store.dispatch : function(_type, _payload, _options) {
  7560. var args = unifyObjectStyle(_type, _payload, _options);
  7561. var payload = args.payload;
  7562. var options = args.options;
  7563. var type = args.type;
  7564. if (!options || !options.root) {
  7565. type = namespace + type;
  7566. if (!store._actions[type]) {
  7567. console.error("[vuex] unknown local action type: " + args.type + ", global type: " + type);
  7568. return;
  7569. }
  7570. }
  7571. return store.dispatch(type, payload);
  7572. },
  7573. commit: noNamespace ? store.commit : function(_type, _payload, _options) {
  7574. var args = unifyObjectStyle(_type, _payload, _options);
  7575. var payload = args.payload;
  7576. var options = args.options;
  7577. var type = args.type;
  7578. if (!options || !options.root) {
  7579. type = namespace + type;
  7580. if (!store._mutations[type]) {
  7581. console.error("[vuex] unknown local mutation type: " + args.type + ", global type: " + type);
  7582. return;
  7583. }
  7584. }
  7585. store.commit(type, payload, options);
  7586. }
  7587. };
  7588. Object.defineProperties(local, {
  7589. getters: {
  7590. get: noNamespace ? function() {
  7591. return store.getters;
  7592. } : function() {
  7593. return makeLocalGetters(store, namespace);
  7594. }
  7595. },
  7596. state: {
  7597. get: function() {
  7598. return getNestedState(store.state, path);
  7599. }
  7600. }
  7601. });
  7602. return local;
  7603. }
  7604. function makeLocalGetters(store, namespace) {
  7605. if (!store._makeLocalGettersCache[namespace]) {
  7606. var gettersProxy = {};
  7607. var splitPos = namespace.length;
  7608. Object.keys(store.getters).forEach(function(type) {
  7609. if (type.slice(0, splitPos) !== namespace) {
  7610. return;
  7611. }
  7612. var localType = type.slice(splitPos);
  7613. Object.defineProperty(gettersProxy, localType, {
  7614. get: function() {
  7615. return store.getters[type];
  7616. },
  7617. enumerable: true
  7618. });
  7619. });
  7620. store._makeLocalGettersCache[namespace] = gettersProxy;
  7621. }
  7622. return store._makeLocalGettersCache[namespace];
  7623. }
  7624. function registerMutation(store, type, handler, local) {
  7625. var entry = store._mutations[type] || (store._mutations[type] = []);
  7626. entry.push(function wrappedMutationHandler(payload) {
  7627. handler.call(store, local.state, payload);
  7628. });
  7629. }
  7630. function registerAction(store, type, handler, local) {
  7631. var entry = store._actions[type] || (store._actions[type] = []);
  7632. entry.push(function wrappedActionHandler(payload) {
  7633. var res = handler.call(store, {
  7634. dispatch: local.dispatch,
  7635. commit: local.commit,
  7636. getters: local.getters,
  7637. state: local.state,
  7638. rootGetters: store.getters,
  7639. rootState: store.state
  7640. }, payload);
  7641. if (!isPromise$1(res)) {
  7642. res = Promise.resolve(res);
  7643. }
  7644. if (store._devtoolHook) {
  7645. return res.catch(function(err) {
  7646. store._devtoolHook.emit("vuex:error", err);
  7647. throw err;
  7648. });
  7649. } else {
  7650. return res;
  7651. }
  7652. });
  7653. }
  7654. function registerGetter(store, type, rawGetter, local) {
  7655. if (store._wrappedGetters[type]) {
  7656. {
  7657. console.error("[vuex] duplicate getter key: " + type);
  7658. }
  7659. return;
  7660. }
  7661. store._wrappedGetters[type] = function wrappedGetter(store2) {
  7662. return rawGetter(
  7663. local.state,
  7664. // local state
  7665. local.getters,
  7666. // local getters
  7667. store2.state,
  7668. // root state
  7669. store2.getters
  7670. // root getters
  7671. );
  7672. };
  7673. }
  7674. function enableStrictMode(store) {
  7675. watch(function() {
  7676. return store._state.data;
  7677. }, function() {
  7678. {
  7679. assert(store._committing, "do not mutate vuex store state outside mutation handlers.");
  7680. }
  7681. }, { deep: true, flush: "sync" });
  7682. }
  7683. function getNestedState(state, path) {
  7684. return path.reduce(function(state2, key) {
  7685. return state2[key];
  7686. }, state);
  7687. }
  7688. function unifyObjectStyle(type, payload, options) {
  7689. if (isObject(type) && type.type) {
  7690. options = payload;
  7691. payload = type;
  7692. type = type.type;
  7693. }
  7694. {
  7695. assert(typeof type === "string", "expects string as the type, but found " + typeof type + ".");
  7696. }
  7697. return { type, payload, options };
  7698. }
  7699. var Module = function Module2(rawModule, runtime) {
  7700. this.runtime = runtime;
  7701. this._children = /* @__PURE__ */ Object.create(null);
  7702. this._rawModule = rawModule;
  7703. var rawState = rawModule.state;
  7704. this.state = (typeof rawState === "function" ? rawState() : rawState) || {};
  7705. };
  7706. var prototypeAccessors$1 = { namespaced: { configurable: true } };
  7707. prototypeAccessors$1.namespaced.get = function() {
  7708. return !!this._rawModule.namespaced;
  7709. };
  7710. Module.prototype.addChild = function addChild(key, module2) {
  7711. this._children[key] = module2;
  7712. };
  7713. Module.prototype.removeChild = function removeChild(key) {
  7714. delete this._children[key];
  7715. };
  7716. Module.prototype.getChild = function getChild(key) {
  7717. return this._children[key];
  7718. };
  7719. Module.prototype.hasChild = function hasChild(key) {
  7720. return key in this._children;
  7721. };
  7722. Module.prototype.update = function update(rawModule) {
  7723. this._rawModule.namespaced = rawModule.namespaced;
  7724. if (rawModule.actions) {
  7725. this._rawModule.actions = rawModule.actions;
  7726. }
  7727. if (rawModule.mutations) {
  7728. this._rawModule.mutations = rawModule.mutations;
  7729. }
  7730. if (rawModule.getters) {
  7731. this._rawModule.getters = rawModule.getters;
  7732. }
  7733. };
  7734. Module.prototype.forEachChild = function forEachChild(fn2) {
  7735. forEachValue(this._children, fn2);
  7736. };
  7737. Module.prototype.forEachGetter = function forEachGetter(fn2) {
  7738. if (this._rawModule.getters) {
  7739. forEachValue(this._rawModule.getters, fn2);
  7740. }
  7741. };
  7742. Module.prototype.forEachAction = function forEachAction(fn2) {
  7743. if (this._rawModule.actions) {
  7744. forEachValue(this._rawModule.actions, fn2);
  7745. }
  7746. };
  7747. Module.prototype.forEachMutation = function forEachMutation(fn2) {
  7748. if (this._rawModule.mutations) {
  7749. forEachValue(this._rawModule.mutations, fn2);
  7750. }
  7751. };
  7752. Object.defineProperties(Module.prototype, prototypeAccessors$1);
  7753. var ModuleCollection = function ModuleCollection2(rawRootModule) {
  7754. this.register([], rawRootModule, false);
  7755. };
  7756. ModuleCollection.prototype.get = function get2(path) {
  7757. return path.reduce(function(module2, key) {
  7758. return module2.getChild(key);
  7759. }, this.root);
  7760. };
  7761. ModuleCollection.prototype.getNamespace = function getNamespace(path) {
  7762. var module2 = this.root;
  7763. return path.reduce(function(namespace, key) {
  7764. module2 = module2.getChild(key);
  7765. return namespace + (module2.namespaced ? key + "/" : "");
  7766. }, "");
  7767. };
  7768. ModuleCollection.prototype.update = function update$1(rawRootModule) {
  7769. update2([], this.root, rawRootModule);
  7770. };
  7771. ModuleCollection.prototype.register = function register(path, rawModule, runtime) {
  7772. var this$1$1 = this;
  7773. if (runtime === void 0)
  7774. runtime = true;
  7775. {
  7776. assertRawModule(path, rawModule);
  7777. }
  7778. var newModule = new Module(rawModule, runtime);
  7779. if (path.length === 0) {
  7780. this.root = newModule;
  7781. } else {
  7782. var parent = this.get(path.slice(0, -1));
  7783. parent.addChild(path[path.length - 1], newModule);
  7784. }
  7785. if (rawModule.modules) {
  7786. forEachValue(rawModule.modules, function(rawChildModule, key) {
  7787. this$1$1.register(path.concat(key), rawChildModule, runtime);
  7788. });
  7789. }
  7790. };
  7791. ModuleCollection.prototype.unregister = function unregister(path) {
  7792. var parent = this.get(path.slice(0, -1));
  7793. var key = path[path.length - 1];
  7794. var child = parent.getChild(key);
  7795. if (!child) {
  7796. {
  7797. console.warn(
  7798. "[vuex] trying to unregister module '" + key + "', which is not registered"
  7799. );
  7800. }
  7801. return;
  7802. }
  7803. if (!child.runtime) {
  7804. return;
  7805. }
  7806. parent.removeChild(key);
  7807. };
  7808. ModuleCollection.prototype.isRegistered = function isRegistered(path) {
  7809. var parent = this.get(path.slice(0, -1));
  7810. var key = path[path.length - 1];
  7811. if (parent) {
  7812. return parent.hasChild(key);
  7813. }
  7814. return false;
  7815. };
  7816. function update2(path, targetModule, newModule) {
  7817. {
  7818. assertRawModule(path, newModule);
  7819. }
  7820. targetModule.update(newModule);
  7821. if (newModule.modules) {
  7822. for (var key in newModule.modules) {
  7823. if (!targetModule.getChild(key)) {
  7824. {
  7825. console.warn(
  7826. "[vuex] trying to add a new module '" + key + "' on hot reloading, manual reload is needed"
  7827. );
  7828. }
  7829. return;
  7830. }
  7831. update2(
  7832. path.concat(key),
  7833. targetModule.getChild(key),
  7834. newModule.modules[key]
  7835. );
  7836. }
  7837. }
  7838. }
  7839. var functionAssert = {
  7840. assert: function(value) {
  7841. return typeof value === "function";
  7842. },
  7843. expected: "function"
  7844. };
  7845. var objectAssert = {
  7846. assert: function(value) {
  7847. return typeof value === "function" || typeof value === "object" && typeof value.handler === "function";
  7848. },
  7849. expected: 'function or object with "handler" function'
  7850. };
  7851. var assertTypes = {
  7852. getters: functionAssert,
  7853. mutations: functionAssert,
  7854. actions: objectAssert
  7855. };
  7856. function assertRawModule(path, rawModule) {
  7857. Object.keys(assertTypes).forEach(function(key) {
  7858. if (!rawModule[key]) {
  7859. return;
  7860. }
  7861. var assertOptions = assertTypes[key];
  7862. forEachValue(rawModule[key], function(value, type) {
  7863. assert(
  7864. assertOptions.assert(value),
  7865. makeAssertionMessage(path, key, type, value, assertOptions.expected)
  7866. );
  7867. });
  7868. });
  7869. }
  7870. function makeAssertionMessage(path, key, type, value, expected) {
  7871. var buf = key + " should be " + expected + ' but "' + key + "." + type + '"';
  7872. if (path.length > 0) {
  7873. buf += ' in module "' + path.join(".") + '"';
  7874. }
  7875. buf += " is " + JSON.stringify(value) + ".";
  7876. return buf;
  7877. }
  7878. function createStore(options) {
  7879. return new Store(options);
  7880. }
  7881. var Store = function Store2(options) {
  7882. var this$1$1 = this;
  7883. if (options === void 0)
  7884. options = {};
  7885. {
  7886. assert(typeof Promise !== "undefined", "vuex requires a Promise polyfill in this browser.");
  7887. assert(this instanceof Store2, "store must be called with the new operator.");
  7888. }
  7889. var plugins = options.plugins;
  7890. if (plugins === void 0)
  7891. plugins = [];
  7892. var strict = options.strict;
  7893. if (strict === void 0)
  7894. strict = false;
  7895. var devtools2 = options.devtools;
  7896. this._committing = false;
  7897. this._actions = /* @__PURE__ */ Object.create(null);
  7898. this._actionSubscribers = [];
  7899. this._mutations = /* @__PURE__ */ Object.create(null);
  7900. this._wrappedGetters = /* @__PURE__ */ Object.create(null);
  7901. this._modules = new ModuleCollection(options);
  7902. this._modulesNamespaceMap = /* @__PURE__ */ Object.create(null);
  7903. this._subscribers = [];
  7904. this._makeLocalGettersCache = /* @__PURE__ */ Object.create(null);
  7905. this._scope = null;
  7906. this._devtools = devtools2;
  7907. var store = this;
  7908. var ref2 = this;
  7909. var dispatch2 = ref2.dispatch;
  7910. var commit2 = ref2.commit;
  7911. this.dispatch = function boundDispatch(type, payload) {
  7912. return dispatch2.call(store, type, payload);
  7913. };
  7914. this.commit = function boundCommit(type, payload, options2) {
  7915. return commit2.call(store, type, payload, options2);
  7916. };
  7917. this.strict = strict;
  7918. var state = this._modules.root.state;
  7919. installModule(this, state, [], this._modules.root);
  7920. resetStoreState(this, state);
  7921. plugins.forEach(function(plugin2) {
  7922. return plugin2(this$1$1);
  7923. });
  7924. };
  7925. var prototypeAccessors = { state: { configurable: true } };
  7926. Store.prototype.install = function install(app, injectKey) {
  7927. app.provide(injectKey || storeKey, this);
  7928. app.config.globalProperties.$store = this;
  7929. this._devtools !== void 0 ? this._devtools : true;
  7930. };
  7931. prototypeAccessors.state.get = function() {
  7932. return this._state.data;
  7933. };
  7934. prototypeAccessors.state.set = function(v2) {
  7935. {
  7936. assert(false, "use store.replaceState() to explicit replace store state.");
  7937. }
  7938. };
  7939. Store.prototype.commit = function commit(_type, _payload, _options) {
  7940. var this$1$1 = this;
  7941. var ref2 = unifyObjectStyle(_type, _payload, _options);
  7942. var type = ref2.type;
  7943. var payload = ref2.payload;
  7944. var options = ref2.options;
  7945. var mutation = { type, payload };
  7946. var entry = this._mutations[type];
  7947. if (!entry) {
  7948. {
  7949. console.error("[vuex] unknown mutation type: " + type);
  7950. }
  7951. return;
  7952. }
  7953. this._withCommit(function() {
  7954. entry.forEach(function commitIterator(handler) {
  7955. handler(payload);
  7956. });
  7957. });
  7958. this._subscribers.slice().forEach(function(sub) {
  7959. return sub(mutation, this$1$1.state);
  7960. });
  7961. if (options && options.silent) {
  7962. console.warn(
  7963. "[vuex] mutation type: " + type + ". Silent option has been removed. Use the filter functionality in the vue-devtools"
  7964. );
  7965. }
  7966. };
  7967. Store.prototype.dispatch = function dispatch(_type, _payload) {
  7968. var this$1$1 = this;
  7969. var ref2 = unifyObjectStyle(_type, _payload);
  7970. var type = ref2.type;
  7971. var payload = ref2.payload;
  7972. var action = { type, payload };
  7973. var entry = this._actions[type];
  7974. if (!entry) {
  7975. {
  7976. console.error("[vuex] unknown action type: " + type);
  7977. }
  7978. return;
  7979. }
  7980. try {
  7981. this._actionSubscribers.slice().filter(function(sub) {
  7982. return sub.before;
  7983. }).forEach(function(sub) {
  7984. return sub.before(action, this$1$1.state);
  7985. });
  7986. } catch (e2) {
  7987. {
  7988. console.warn("[vuex] error in before action subscribers: ");
  7989. console.error(e2);
  7990. }
  7991. }
  7992. var result = entry.length > 1 ? Promise.all(entry.map(function(handler) {
  7993. return handler(payload);
  7994. })) : entry[0](payload);
  7995. return new Promise(function(resolve2, reject) {
  7996. result.then(function(res) {
  7997. try {
  7998. this$1$1._actionSubscribers.filter(function(sub) {
  7999. return sub.after;
  8000. }).forEach(function(sub) {
  8001. return sub.after(action, this$1$1.state);
  8002. });
  8003. } catch (e2) {
  8004. {
  8005. console.warn("[vuex] error in after action subscribers: ");
  8006. console.error(e2);
  8007. }
  8008. }
  8009. resolve2(res);
  8010. }, function(error) {
  8011. try {
  8012. this$1$1._actionSubscribers.filter(function(sub) {
  8013. return sub.error;
  8014. }).forEach(function(sub) {
  8015. return sub.error(action, this$1$1.state, error);
  8016. });
  8017. } catch (e2) {
  8018. {
  8019. console.warn("[vuex] error in error action subscribers: ");
  8020. console.error(e2);
  8021. }
  8022. }
  8023. reject(error);
  8024. });
  8025. });
  8026. };
  8027. Store.prototype.subscribe = function subscribe(fn2, options) {
  8028. return genericSubscribe(fn2, this._subscribers, options);
  8029. };
  8030. Store.prototype.subscribeAction = function subscribeAction(fn2, options) {
  8031. var subs = typeof fn2 === "function" ? { before: fn2 } : fn2;
  8032. return genericSubscribe(subs, this._actionSubscribers, options);
  8033. };
  8034. Store.prototype.watch = function watch$1(getter, cb, options) {
  8035. var this$1$1 = this;
  8036. {
  8037. assert(typeof getter === "function", "store.watch only accepts a function.");
  8038. }
  8039. return watch(function() {
  8040. return getter(this$1$1.state, this$1$1.getters);
  8041. }, cb, Object.assign({}, options));
  8042. };
  8043. Store.prototype.replaceState = function replaceState(state) {
  8044. var this$1$1 = this;
  8045. this._withCommit(function() {
  8046. this$1$1._state.data = state;
  8047. });
  8048. };
  8049. Store.prototype.registerModule = function registerModule(path, rawModule, options) {
  8050. if (options === void 0)
  8051. options = {};
  8052. if (typeof path === "string") {
  8053. path = [path];
  8054. }
  8055. {
  8056. assert(Array.isArray(path), "module path must be a string or an Array.");
  8057. assert(path.length > 0, "cannot register the root module by using registerModule.");
  8058. }
  8059. this._modules.register(path, rawModule);
  8060. installModule(this, this.state, path, this._modules.get(path), options.preserveState);
  8061. resetStoreState(this, this.state);
  8062. };
  8063. Store.prototype.unregisterModule = function unregisterModule(path) {
  8064. var this$1$1 = this;
  8065. if (typeof path === "string") {
  8066. path = [path];
  8067. }
  8068. {
  8069. assert(Array.isArray(path), "module path must be a string or an Array.");
  8070. }
  8071. this._modules.unregister(path);
  8072. this._withCommit(function() {
  8073. var parentState = getNestedState(this$1$1.state, path.slice(0, -1));
  8074. delete parentState[path[path.length - 1]];
  8075. });
  8076. resetStore(this);
  8077. };
  8078. Store.prototype.hasModule = function hasModule(path) {
  8079. if (typeof path === "string") {
  8080. path = [path];
  8081. }
  8082. {
  8083. assert(Array.isArray(path), "module path must be a string or an Array.");
  8084. }
  8085. return this._modules.isRegistered(path);
  8086. };
  8087. Store.prototype.hotUpdate = function hotUpdate(newOptions) {
  8088. this._modules.update(newOptions);
  8089. resetStore(this, true);
  8090. };
  8091. Store.prototype._withCommit = function _withCommit(fn2) {
  8092. var committing = this._committing;
  8093. this._committing = true;
  8094. fn2();
  8095. this._committing = committing;
  8096. };
  8097. Object.defineProperties(Store.prototype, prototypeAccessors);
  8098. const isFiniteNumber = Number.isFinite || function(value) {
  8099. return typeof value === "number" && isFinite(value);
  8100. };
  8101. const isSafeInteger = Number.isSafeInteger || function(value) {
  8102. return typeof value === "number" && Math.abs(value) <= MAX_SAFE_INTEGER;
  8103. };
  8104. const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  8105. let ErrorTypes = /* @__PURE__ */ function(ErrorTypes2) {
  8106. ErrorTypes2["NETWORK_ERROR"] = "networkError";
  8107. ErrorTypes2["MEDIA_ERROR"] = "mediaError";
  8108. ErrorTypes2["KEY_SYSTEM_ERROR"] = "keySystemError";
  8109. ErrorTypes2["MUX_ERROR"] = "muxError";
  8110. ErrorTypes2["OTHER_ERROR"] = "otherError";
  8111. return ErrorTypes2;
  8112. }({});
  8113. let ErrorDetails = /* @__PURE__ */ function(ErrorDetails2) {
  8114. ErrorDetails2["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  8115. ErrorDetails2["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  8116. ErrorDetails2["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  8117. ErrorDetails2["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  8118. ErrorDetails2["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  8119. ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  8120. ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  8121. ErrorDetails2["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  8122. ErrorDetails2["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  8123. ErrorDetails2["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  8124. ErrorDetails2["KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR"] = "keySystemDestroyMediaKeysError";
  8125. ErrorDetails2["KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR"] = "keySystemDestroyCloseSessionError";
  8126. ErrorDetails2["KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR"] = "keySystemDestroyRemoveSessionError";
  8127. ErrorDetails2["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  8128. ErrorDetails2["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  8129. ErrorDetails2["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  8130. ErrorDetails2["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  8131. ErrorDetails2["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  8132. ErrorDetails2["LEVEL_LOAD_ERROR"] = "levelLoadError";
  8133. ErrorDetails2["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  8134. ErrorDetails2["LEVEL_PARSING_ERROR"] = "levelParsingError";
  8135. ErrorDetails2["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  8136. ErrorDetails2["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  8137. ErrorDetails2["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  8138. ErrorDetails2["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  8139. ErrorDetails2["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  8140. ErrorDetails2["FRAG_LOAD_ERROR"] = "fragLoadError";
  8141. ErrorDetails2["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  8142. ErrorDetails2["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  8143. ErrorDetails2["FRAG_PARSING_ERROR"] = "fragParsingError";
  8144. ErrorDetails2["FRAG_GAP"] = "fragGap";
  8145. ErrorDetails2["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  8146. ErrorDetails2["KEY_LOAD_ERROR"] = "keyLoadError";
  8147. ErrorDetails2["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  8148. ErrorDetails2["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  8149. ErrorDetails2["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  8150. ErrorDetails2["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  8151. ErrorDetails2["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  8152. ErrorDetails2["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  8153. ErrorDetails2["BUFFER_FULL_ERROR"] = "bufferFullError";
  8154. ErrorDetails2["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  8155. ErrorDetails2["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  8156. ErrorDetails2["ASSET_LIST_LOAD_ERROR"] = "assetListLoadError";
  8157. ErrorDetails2["ASSET_LIST_LOAD_TIMEOUT"] = "assetListLoadTimeout";
  8158. ErrorDetails2["ASSET_LIST_PARSING_ERROR"] = "assetListParsingError";
  8159. ErrorDetails2["INTERSTITIAL_ASSET_ITEM_ERROR"] = "interstitialAssetItemError";
  8160. ErrorDetails2["INTERNAL_EXCEPTION"] = "internalException";
  8161. ErrorDetails2["INTERNAL_ABORTED"] = "aborted";
  8162. ErrorDetails2["ATTACH_MEDIA_ERROR"] = "attachMediaError";
  8163. ErrorDetails2["UNKNOWN"] = "unknown";
  8164. return ErrorDetails2;
  8165. }({});
  8166. let Events = /* @__PURE__ */ function(Events2) {
  8167. Events2["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  8168. Events2["MEDIA_ATTACHED"] = "hlsMediaAttached";
  8169. Events2["MEDIA_DETACHING"] = "hlsMediaDetaching";
  8170. Events2["MEDIA_DETACHED"] = "hlsMediaDetached";
  8171. Events2["MEDIA_ENDED"] = "hlsMediaEnded";
  8172. Events2["STALL_RESOLVED"] = "hlsStallResolved";
  8173. Events2["BUFFER_RESET"] = "hlsBufferReset";
  8174. Events2["BUFFER_CODECS"] = "hlsBufferCodecs";
  8175. Events2["BUFFER_CREATED"] = "hlsBufferCreated";
  8176. Events2["BUFFER_APPENDING"] = "hlsBufferAppending";
  8177. Events2["BUFFER_APPENDED"] = "hlsBufferAppended";
  8178. Events2["BUFFER_EOS"] = "hlsBufferEos";
  8179. Events2["BUFFERED_TO_END"] = "hlsBufferedToEnd";
  8180. Events2["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  8181. Events2["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  8182. Events2["MANIFEST_LOADING"] = "hlsManifestLoading";
  8183. Events2["MANIFEST_LOADED"] = "hlsManifestLoaded";
  8184. Events2["MANIFEST_PARSED"] = "hlsManifestParsed";
  8185. Events2["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  8186. Events2["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  8187. Events2["LEVEL_LOADING"] = "hlsLevelLoading";
  8188. Events2["LEVEL_LOADED"] = "hlsLevelLoaded";
  8189. Events2["LEVEL_UPDATED"] = "hlsLevelUpdated";
  8190. Events2["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  8191. Events2["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  8192. Events2["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  8193. Events2["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  8194. Events2["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  8195. Events2["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  8196. Events2["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  8197. Events2["AUDIO_TRACK_UPDATED"] = "hlsAudioTrackUpdated";
  8198. Events2["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  8199. Events2["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  8200. Events2["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  8201. Events2["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  8202. Events2["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  8203. Events2["SUBTITLE_TRACK_UPDATED"] = "hlsSubtitleTrackUpdated";
  8204. Events2["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  8205. Events2["CUES_PARSED"] = "hlsCuesParsed";
  8206. Events2["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  8207. Events2["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  8208. Events2["FRAG_LOADING"] = "hlsFragLoading";
  8209. Events2["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  8210. Events2["FRAG_LOADED"] = "hlsFragLoaded";
  8211. Events2["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  8212. Events2["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  8213. Events2["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  8214. Events2["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  8215. Events2["FRAG_PARSED"] = "hlsFragParsed";
  8216. Events2["FRAG_BUFFERED"] = "hlsFragBuffered";
  8217. Events2["FRAG_CHANGED"] = "hlsFragChanged";
  8218. Events2["FPS_DROP"] = "hlsFpsDrop";
  8219. Events2["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  8220. Events2["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  8221. Events2["ERROR"] = "hlsError";
  8222. Events2["DESTROYING"] = "hlsDestroying";
  8223. Events2["KEY_LOADING"] = "hlsKeyLoading";
  8224. Events2["KEY_LOADED"] = "hlsKeyLoaded";
  8225. Events2["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  8226. Events2["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  8227. Events2["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  8228. Events2["ASSET_LIST_LOADING"] = "hlsAssetListLoading";
  8229. Events2["ASSET_LIST_LOADED"] = "hlsAssetListLoaded";
  8230. Events2["INTERSTITIALS_UPDATED"] = "hlsInterstitialsUpdated";
  8231. Events2["INTERSTITIALS_BUFFERED_TO_BOUNDARY"] = "hlsInterstitialsBufferedToBoundary";
  8232. Events2["INTERSTITIAL_ASSET_PLAYER_CREATED"] = "hlsInterstitialAssetPlayerCreated";
  8233. Events2["INTERSTITIAL_STARTED"] = "hlsInterstitialStarted";
  8234. Events2["INTERSTITIAL_ASSET_STARTED"] = "hlsInterstitialAssetStarted";
  8235. Events2["INTERSTITIAL_ASSET_ENDED"] = "hlsInterstitialAssetEnded";
  8236. Events2["INTERSTITIAL_ASSET_ERROR"] = "hlsInterstitialAssetError";
  8237. Events2["INTERSTITIAL_ENDED"] = "hlsInterstitialEnded";
  8238. Events2["INTERSTITIALS_PRIMARY_RESUMED"] = "hlsInterstitialsPrimaryResumed";
  8239. Events2["PLAYOUT_LIMIT_REACHED"] = "hlsPlayoutLimitReached";
  8240. Events2["EVENT_CUE_ENTER"] = "hlsEventCueEnter";
  8241. return Events2;
  8242. }({});
  8243. var PlaylistContextType = {
  8244. MANIFEST: "manifest",
  8245. LEVEL: "level",
  8246. AUDIO_TRACK: "audioTrack",
  8247. SUBTITLE_TRACK: "subtitleTrack"
  8248. };
  8249. var PlaylistLevelType = {
  8250. MAIN: "main",
  8251. AUDIO: "audio",
  8252. SUBTITLE: "subtitle"
  8253. };
  8254. class EWMA {
  8255. // About half of the estimated value will be from the last |halfLife| samples by weight.
  8256. constructor(halfLife, estimate = 0, weight = 0) {
  8257. this.halfLife = void 0;
  8258. this.alpha_ = void 0;
  8259. this.estimate_ = void 0;
  8260. this.totalWeight_ = void 0;
  8261. this.halfLife = halfLife;
  8262. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  8263. this.estimate_ = estimate;
  8264. this.totalWeight_ = weight;
  8265. }
  8266. sample(weight, value) {
  8267. const adjAlpha = Math.pow(this.alpha_, weight);
  8268. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  8269. this.totalWeight_ += weight;
  8270. }
  8271. getTotalWeight() {
  8272. return this.totalWeight_;
  8273. }
  8274. getEstimate() {
  8275. if (this.alpha_) {
  8276. const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  8277. if (zeroFactor) {
  8278. return this.estimate_ / zeroFactor;
  8279. }
  8280. }
  8281. return this.estimate_;
  8282. }
  8283. }
  8284. class EwmaBandWidthEstimator {
  8285. constructor(slow, fast, defaultEstimate, defaultTTFB = 100) {
  8286. this.defaultEstimate_ = void 0;
  8287. this.minWeight_ = void 0;
  8288. this.minDelayMs_ = void 0;
  8289. this.slow_ = void 0;
  8290. this.fast_ = void 0;
  8291. this.defaultTTFB_ = void 0;
  8292. this.ttfb_ = void 0;
  8293. this.defaultEstimate_ = defaultEstimate;
  8294. this.minWeight_ = 1e-3;
  8295. this.minDelayMs_ = 50;
  8296. this.slow_ = new EWMA(slow);
  8297. this.fast_ = new EWMA(fast);
  8298. this.defaultTTFB_ = defaultTTFB;
  8299. this.ttfb_ = new EWMA(slow);
  8300. }
  8301. update(slow, fast) {
  8302. const {
  8303. slow_,
  8304. fast_,
  8305. ttfb_
  8306. } = this;
  8307. if (slow_.halfLife !== slow) {
  8308. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  8309. }
  8310. if (fast_.halfLife !== fast) {
  8311. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  8312. }
  8313. if (ttfb_.halfLife !== slow) {
  8314. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  8315. }
  8316. }
  8317. sample(durationMs, numBytes) {
  8318. durationMs = Math.max(durationMs, this.minDelayMs_);
  8319. const numBits = 8 * numBytes;
  8320. const durationS = durationMs / 1e3;
  8321. const bandwidthInBps = numBits / durationS;
  8322. this.fast_.sample(durationS, bandwidthInBps);
  8323. this.slow_.sample(durationS, bandwidthInBps);
  8324. }
  8325. sampleTTFB(ttfb) {
  8326. const seconds = ttfb / 1e3;
  8327. const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  8328. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  8329. }
  8330. canEstimate() {
  8331. return this.fast_.getTotalWeight() >= this.minWeight_;
  8332. }
  8333. getEstimate() {
  8334. if (this.canEstimate()) {
  8335. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  8336. } else {
  8337. return this.defaultEstimate_;
  8338. }
  8339. }
  8340. getEstimateTTFB() {
  8341. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  8342. return this.ttfb_.getEstimate();
  8343. } else {
  8344. return this.defaultTTFB_;
  8345. }
  8346. }
  8347. get defaultEstimate() {
  8348. return this.defaultEstimate_;
  8349. }
  8350. destroy() {
  8351. }
  8352. }
  8353. function _defineProperty(e2, r2, t2) {
  8354. return (r2 = _toPropertyKey(r2)) in e2 ? Object.defineProperty(e2, r2, {
  8355. value: t2,
  8356. enumerable: true,
  8357. configurable: true,
  8358. writable: true
  8359. }) : e2[r2] = t2, e2;
  8360. }
  8361. function _extends() {
  8362. return _extends = Object.assign ? Object.assign.bind() : function(n2) {
  8363. for (var e2 = 1; e2 < arguments.length; e2++) {
  8364. var t2 = arguments[e2];
  8365. for (var r2 in t2)
  8366. ({}).hasOwnProperty.call(t2, r2) && (n2[r2] = t2[r2]);
  8367. }
  8368. return n2;
  8369. }, _extends.apply(null, arguments);
  8370. }
  8371. function ownKeys(e2, r2) {
  8372. var t2 = Object.keys(e2);
  8373. if (Object.getOwnPropertySymbols) {
  8374. var o2 = Object.getOwnPropertySymbols(e2);
  8375. r2 && (o2 = o2.filter(function(r3) {
  8376. return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
  8377. })), t2.push.apply(t2, o2);
  8378. }
  8379. return t2;
  8380. }
  8381. function _objectSpread2(e2) {
  8382. for (var r2 = 1; r2 < arguments.length; r2++) {
  8383. var t2 = null != arguments[r2] ? arguments[r2] : {};
  8384. r2 % 2 ? ownKeys(Object(t2), true).forEach(function(r3) {
  8385. _defineProperty(e2, r3, t2[r3]);
  8386. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys(Object(t2)).forEach(function(r3) {
  8387. Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t2, r3));
  8388. });
  8389. }
  8390. return e2;
  8391. }
  8392. function _toPrimitive(t2, r2) {
  8393. if ("object" != typeof t2 || !t2)
  8394. return t2;
  8395. var e2 = t2[Symbol.toPrimitive];
  8396. if (void 0 !== e2) {
  8397. var i2 = e2.call(t2, r2);
  8398. if ("object" != typeof i2)
  8399. return i2;
  8400. throw new TypeError("@@toPrimitive must return a primitive value.");
  8401. }
  8402. return ("string" === r2 ? String : Number)(t2);
  8403. }
  8404. function _toPropertyKey(t2) {
  8405. var i2 = _toPrimitive(t2, "string");
  8406. return "symbol" == typeof i2 ? i2 : i2 + "";
  8407. }
  8408. class Logger {
  8409. constructor(label, logger2) {
  8410. this.trace = void 0;
  8411. this.debug = void 0;
  8412. this.log = void 0;
  8413. this.warn = void 0;
  8414. this.info = void 0;
  8415. this.error = void 0;
  8416. const lb = `[${label}]:`;
  8417. this.trace = noop;
  8418. this.debug = logger2.debug.bind(null, lb);
  8419. this.log = logger2.log.bind(null, lb);
  8420. this.warn = logger2.warn.bind(null, lb);
  8421. this.info = logger2.info.bind(null, lb);
  8422. this.error = logger2.error.bind(null, lb);
  8423. }
  8424. }
  8425. const noop = function noop2() {
  8426. };
  8427. const fakeLogger = {
  8428. trace: noop,
  8429. debug: noop,
  8430. log: noop,
  8431. warn: noop,
  8432. info: noop,
  8433. error: noop
  8434. };
  8435. function createLogger() {
  8436. return _extends({}, fakeLogger);
  8437. }
  8438. function consolePrintFn(type, id) {
  8439. const func = self.console[type];
  8440. return func ? func.bind(self.console, `${id ? "[" + id + "] " : ""}[${type}] >`) : noop;
  8441. }
  8442. function getLoggerFn(key, debugConfig, id) {
  8443. return debugConfig[key] ? debugConfig[key].bind(debugConfig) : consolePrintFn(key, id);
  8444. }
  8445. const exportedLogger = createLogger();
  8446. function enableLogs(debugConfig, context, id) {
  8447. const newLogger = createLogger();
  8448. if (typeof console === "object" && debugConfig === true || typeof debugConfig === "object") {
  8449. const keys = [
  8450. // Remove out from list here to hard-disable a log-level
  8451. // 'trace',
  8452. "debug",
  8453. "log",
  8454. "info",
  8455. "warn",
  8456. "error"
  8457. ];
  8458. keys.forEach((key) => {
  8459. newLogger[key] = getLoggerFn(key, debugConfig, id);
  8460. });
  8461. try {
  8462. newLogger.log(`Debug logs enabled for "${context}" in hls.js version ${"1.6.7"}`);
  8463. } catch (e2) {
  8464. return createLogger();
  8465. }
  8466. keys.forEach((key) => {
  8467. exportedLogger[key] = getLoggerFn(key, debugConfig);
  8468. });
  8469. } else {
  8470. _extends(exportedLogger, newLogger);
  8471. }
  8472. return newLogger;
  8473. }
  8474. const logger = exportedLogger;
  8475. function getMediaSource(preferManagedMediaSource = true) {
  8476. if (typeof self === "undefined")
  8477. return void 0;
  8478. const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  8479. return mms || self.MediaSource || self.WebKitMediaSource;
  8480. }
  8481. function isManagedMediaSource(source) {
  8482. return typeof self !== "undefined" && source === self.ManagedMediaSource;
  8483. }
  8484. function isCompatibleTrackChange(currentTracks, requiredTracks) {
  8485. const trackNames = Object.keys(currentTracks);
  8486. const requiredTrackNames = Object.keys(requiredTracks);
  8487. const trackCount = trackNames.length;
  8488. const requiredTrackCount = requiredTrackNames.length;
  8489. return !trackCount || !requiredTrackCount || trackCount === requiredTrackCount && !trackNames.some((name) => requiredTrackNames.indexOf(name) === -1);
  8490. }
  8491. function utf8ArrayToStr(array, exitOnNull = false) {
  8492. if (typeof TextDecoder !== "undefined") {
  8493. const decoder = new TextDecoder("utf-8");
  8494. const decoded = decoder.decode(array);
  8495. if (exitOnNull) {
  8496. const idx = decoded.indexOf("\0");
  8497. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  8498. }
  8499. return decoded.replace(/\0/g, "");
  8500. }
  8501. const len = array.length;
  8502. let c2;
  8503. let char2;
  8504. let char3;
  8505. let out = "";
  8506. let i2 = 0;
  8507. while (i2 < len) {
  8508. c2 = array[i2++];
  8509. if (c2 === 0 && exitOnNull) {
  8510. return out;
  8511. } else if (c2 === 0 || c2 === 3) {
  8512. continue;
  8513. }
  8514. switch (c2 >> 4) {
  8515. case 0:
  8516. case 1:
  8517. case 2:
  8518. case 3:
  8519. case 4:
  8520. case 5:
  8521. case 6:
  8522. case 7:
  8523. out += String.fromCharCode(c2);
  8524. break;
  8525. case 12:
  8526. case 13:
  8527. char2 = array[i2++];
  8528. out += String.fromCharCode((c2 & 31) << 6 | char2 & 63);
  8529. break;
  8530. case 14:
  8531. char2 = array[i2++];
  8532. char3 = array[i2++];
  8533. out += String.fromCharCode((c2 & 15) << 12 | (char2 & 63) << 6 | (char3 & 63) << 0);
  8534. break;
  8535. }
  8536. }
  8537. return out;
  8538. }
  8539. const Hex = {
  8540. hexDump: function(array) {
  8541. let str = "";
  8542. for (let i2 = 0; i2 < array.length; i2++) {
  8543. let h2 = array[i2].toString(16);
  8544. if (h2.length < 2) {
  8545. h2 = "0" + h2;
  8546. }
  8547. str += h2;
  8548. }
  8549. return str;
  8550. }
  8551. };
  8552. function hexToArrayBuffer(str) {
  8553. return Uint8Array.from(str.replace(/^0x/, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")).buffer;
  8554. }
  8555. function getDefaultExportFromCjs$1(x) {
  8556. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
  8557. }
  8558. var urlToolkit = { exports: {} };
  8559. var hasRequiredUrlToolkit;
  8560. function requireUrlToolkit() {
  8561. if (hasRequiredUrlToolkit)
  8562. return urlToolkit.exports;
  8563. hasRequiredUrlToolkit = 1;
  8564. (function(module2, exports2) {
  8565. (function(root) {
  8566. var URL_REGEX = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  8567. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  8568. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  8569. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  8570. var URLToolkit = {
  8571. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  8572. // E.g
  8573. // With opts.alwaysNormalize = false (default, spec compliant)
  8574. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  8575. // With opts.alwaysNormalize = true (not spec compliant)
  8576. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  8577. buildAbsoluteURL: function(baseURL, relativeURL, opts) {
  8578. opts = opts || {};
  8579. baseURL = baseURL.trim();
  8580. relativeURL = relativeURL.trim();
  8581. if (!relativeURL) {
  8582. if (!opts.alwaysNormalize) {
  8583. return baseURL;
  8584. }
  8585. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  8586. if (!basePartsForNormalise) {
  8587. throw new Error("Error trying to parse base URL.");
  8588. }
  8589. basePartsForNormalise.path = URLToolkit.normalizePath(
  8590. basePartsForNormalise.path
  8591. );
  8592. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  8593. }
  8594. var relativeParts = URLToolkit.parseURL(relativeURL);
  8595. if (!relativeParts) {
  8596. throw new Error("Error trying to parse relative URL.");
  8597. }
  8598. if (relativeParts.scheme) {
  8599. if (!opts.alwaysNormalize) {
  8600. return relativeURL;
  8601. }
  8602. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  8603. return URLToolkit.buildURLFromParts(relativeParts);
  8604. }
  8605. var baseParts = URLToolkit.parseURL(baseURL);
  8606. if (!baseParts) {
  8607. throw new Error("Error trying to parse base URL.");
  8608. }
  8609. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== "/") {
  8610. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  8611. baseParts.netLoc = pathParts[1];
  8612. baseParts.path = pathParts[2];
  8613. }
  8614. if (baseParts.netLoc && !baseParts.path) {
  8615. baseParts.path = "/";
  8616. }
  8617. var builtParts = {
  8618. // 2c) Otherwise, the embedded URL inherits the scheme of
  8619. // the base URL.
  8620. scheme: baseParts.scheme,
  8621. netLoc: relativeParts.netLoc,
  8622. path: null,
  8623. params: relativeParts.params,
  8624. query: relativeParts.query,
  8625. fragment: relativeParts.fragment
  8626. };
  8627. if (!relativeParts.netLoc) {
  8628. builtParts.netLoc = baseParts.netLoc;
  8629. if (relativeParts.path[0] !== "/") {
  8630. if (!relativeParts.path) {
  8631. builtParts.path = baseParts.path;
  8632. if (!relativeParts.params) {
  8633. builtParts.params = baseParts.params;
  8634. if (!relativeParts.query) {
  8635. builtParts.query = baseParts.query;
  8636. }
  8637. }
  8638. } else {
  8639. var baseURLPath = baseParts.path;
  8640. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf("/") + 1) + relativeParts.path;
  8641. builtParts.path = URLToolkit.normalizePath(newPath);
  8642. }
  8643. }
  8644. }
  8645. if (builtParts.path === null) {
  8646. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  8647. }
  8648. return URLToolkit.buildURLFromParts(builtParts);
  8649. },
  8650. parseURL: function(url) {
  8651. var parts = URL_REGEX.exec(url);
  8652. if (!parts) {
  8653. return null;
  8654. }
  8655. return {
  8656. scheme: parts[1] || "",
  8657. netLoc: parts[2] || "",
  8658. path: parts[3] || "",
  8659. params: parts[4] || "",
  8660. query: parts[5] || "",
  8661. fragment: parts[6] || ""
  8662. };
  8663. },
  8664. normalizePath: function(path) {
  8665. path = path.split("").reverse().join("").replace(SLASH_DOT_REGEX, "");
  8666. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, "")).length) {
  8667. }
  8668. return path.split("").reverse().join("");
  8669. },
  8670. buildURLFromParts: function(parts) {
  8671. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  8672. }
  8673. };
  8674. module2.exports = URLToolkit;
  8675. })();
  8676. })(urlToolkit);
  8677. return urlToolkit.exports;
  8678. }
  8679. var urlToolkitExports = requireUrlToolkit();
  8680. class LoadStats {
  8681. constructor() {
  8682. this.aborted = false;
  8683. this.loaded = 0;
  8684. this.retry = 0;
  8685. this.total = 0;
  8686. this.chunkCount = 0;
  8687. this.bwEstimate = 0;
  8688. this.loading = {
  8689. start: 0,
  8690. first: 0,
  8691. end: 0
  8692. };
  8693. this.parsing = {
  8694. start: 0,
  8695. end: 0
  8696. };
  8697. this.buffering = {
  8698. start: 0,
  8699. first: 0,
  8700. end: 0
  8701. };
  8702. }
  8703. }
  8704. var ElementaryStreamTypes = {
  8705. AUDIO: "audio",
  8706. VIDEO: "video",
  8707. AUDIOVIDEO: "audiovideo"
  8708. };
  8709. class BaseSegment {
  8710. constructor(base) {
  8711. this._byteRange = null;
  8712. this._url = null;
  8713. this._stats = null;
  8714. this._streams = null;
  8715. this.base = void 0;
  8716. this.relurl = void 0;
  8717. if (typeof base === "string") {
  8718. base = {
  8719. url: base
  8720. };
  8721. }
  8722. this.base = base;
  8723. makeEnumerable(this, "stats");
  8724. }
  8725. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  8726. setByteRange(value, previous) {
  8727. const params = value.split("@", 2);
  8728. let start;
  8729. if (params.length === 1) {
  8730. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  8731. } else {
  8732. start = parseInt(params[1]);
  8733. }
  8734. this._byteRange = [start, parseInt(params[0]) + start];
  8735. }
  8736. get baseurl() {
  8737. return this.base.url;
  8738. }
  8739. get byteRange() {
  8740. if (this._byteRange === null) {
  8741. return [];
  8742. }
  8743. return this._byteRange;
  8744. }
  8745. get byteRangeStartOffset() {
  8746. return this.byteRange[0];
  8747. }
  8748. get byteRangeEndOffset() {
  8749. return this.byteRange[1];
  8750. }
  8751. get elementaryStreams() {
  8752. if (this._streams === null) {
  8753. this._streams = {
  8754. [ElementaryStreamTypes.AUDIO]: null,
  8755. [ElementaryStreamTypes.VIDEO]: null,
  8756. [ElementaryStreamTypes.AUDIOVIDEO]: null
  8757. };
  8758. }
  8759. return this._streams;
  8760. }
  8761. set elementaryStreams(value) {
  8762. this._streams = value;
  8763. }
  8764. get hasStats() {
  8765. return this._stats !== null;
  8766. }
  8767. get hasStreams() {
  8768. return this._streams !== null;
  8769. }
  8770. get stats() {
  8771. if (this._stats === null) {
  8772. this._stats = new LoadStats();
  8773. }
  8774. return this._stats;
  8775. }
  8776. set stats(value) {
  8777. this._stats = value;
  8778. }
  8779. get url() {
  8780. if (!this._url && this.baseurl && this.relurl) {
  8781. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  8782. alwaysNormalize: true
  8783. });
  8784. }
  8785. return this._url || "";
  8786. }
  8787. set url(value) {
  8788. this._url = value;
  8789. }
  8790. clearElementaryStreamInfo() {
  8791. const {
  8792. elementaryStreams
  8793. } = this;
  8794. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  8795. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  8796. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  8797. }
  8798. }
  8799. function isMediaFragment(frag) {
  8800. return frag.sn !== "initSegment";
  8801. }
  8802. class Fragment extends BaseSegment {
  8803. constructor(type, base) {
  8804. super(base);
  8805. this._decryptdata = null;
  8806. this._programDateTime = null;
  8807. this._ref = null;
  8808. this._bitrate = void 0;
  8809. this.rawProgramDateTime = null;
  8810. this.tagList = [];
  8811. this.duration = 0;
  8812. this.sn = 0;
  8813. this.levelkeys = void 0;
  8814. this.type = void 0;
  8815. this.loader = null;
  8816. this.keyLoader = null;
  8817. this.level = -1;
  8818. this.cc = 0;
  8819. this.startPTS = void 0;
  8820. this.endPTS = void 0;
  8821. this.startDTS = void 0;
  8822. this.endDTS = void 0;
  8823. this.start = 0;
  8824. this.playlistOffset = 0;
  8825. this.deltaPTS = void 0;
  8826. this.maxStartPTS = void 0;
  8827. this.minEndPTS = void 0;
  8828. this.data = void 0;
  8829. this.bitrateTest = false;
  8830. this.title = null;
  8831. this.initSegment = null;
  8832. this.endList = void 0;
  8833. this.gap = void 0;
  8834. this.urlId = 0;
  8835. this.type = type;
  8836. }
  8837. get byteLength() {
  8838. if (this.hasStats) {
  8839. const total = this.stats.total;
  8840. if (total) {
  8841. return total;
  8842. }
  8843. }
  8844. if (this.byteRange) {
  8845. const start = this.byteRange[0];
  8846. const end = this.byteRange[1];
  8847. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  8848. return end - start;
  8849. }
  8850. }
  8851. return null;
  8852. }
  8853. get bitrate() {
  8854. if (this.byteLength) {
  8855. return this.byteLength * 8 / this.duration;
  8856. }
  8857. if (this._bitrate) {
  8858. return this._bitrate;
  8859. }
  8860. return null;
  8861. }
  8862. set bitrate(value) {
  8863. this._bitrate = value;
  8864. }
  8865. get decryptdata() {
  8866. const {
  8867. levelkeys
  8868. } = this;
  8869. if (!levelkeys && !this._decryptdata) {
  8870. return null;
  8871. }
  8872. if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
  8873. const key = this.levelkeys.identity;
  8874. if (key) {
  8875. this._decryptdata = key.getDecryptData(this.sn);
  8876. } else {
  8877. const keyFormats = Object.keys(this.levelkeys);
  8878. if (keyFormats.length === 1) {
  8879. return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
  8880. }
  8881. }
  8882. }
  8883. return this._decryptdata;
  8884. }
  8885. get end() {
  8886. return this.start + this.duration;
  8887. }
  8888. get endProgramDateTime() {
  8889. if (this.programDateTime === null) {
  8890. return null;
  8891. }
  8892. const duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  8893. return this.programDateTime + duration * 1e3;
  8894. }
  8895. get encrypted() {
  8896. var _this$_decryptdata;
  8897. if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
  8898. return true;
  8899. } else if (this.levelkeys) {
  8900. const keyFormats = Object.keys(this.levelkeys);
  8901. const len = keyFormats.length;
  8902. if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
  8903. return true;
  8904. }
  8905. }
  8906. return false;
  8907. }
  8908. get programDateTime() {
  8909. if (this._programDateTime === null && this.rawProgramDateTime) {
  8910. this.programDateTime = Date.parse(this.rawProgramDateTime);
  8911. }
  8912. return this._programDateTime;
  8913. }
  8914. set programDateTime(value) {
  8915. if (!isFiniteNumber(value)) {
  8916. this._programDateTime = this.rawProgramDateTime = null;
  8917. return;
  8918. }
  8919. this._programDateTime = value;
  8920. }
  8921. get ref() {
  8922. if (!isMediaFragment(this)) {
  8923. return null;
  8924. }
  8925. if (!this._ref) {
  8926. this._ref = {
  8927. base: this.base,
  8928. start: this.start,
  8929. duration: this.duration,
  8930. sn: this.sn,
  8931. programDateTime: this.programDateTime
  8932. };
  8933. }
  8934. return this._ref;
  8935. }
  8936. addStart(value) {
  8937. this.setStart(this.start + value);
  8938. }
  8939. setStart(value) {
  8940. this.start = value;
  8941. if (this._ref) {
  8942. this._ref.start = value;
  8943. }
  8944. }
  8945. setDuration(value) {
  8946. this.duration = value;
  8947. if (this._ref) {
  8948. this._ref.duration = value;
  8949. }
  8950. }
  8951. setKeyFormat(keyFormat) {
  8952. if (this.levelkeys) {
  8953. const key = this.levelkeys[keyFormat];
  8954. if (key && !this._decryptdata) {
  8955. this._decryptdata = key.getDecryptData(this.sn);
  8956. }
  8957. }
  8958. }
  8959. abortRequests() {
  8960. var _this$loader, _this$keyLoader;
  8961. (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
  8962. (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  8963. }
  8964. setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial2 = false) {
  8965. const {
  8966. elementaryStreams
  8967. } = this;
  8968. const info = elementaryStreams[type];
  8969. if (!info) {
  8970. elementaryStreams[type] = {
  8971. startPTS,
  8972. endPTS,
  8973. startDTS,
  8974. endDTS,
  8975. partial: partial2
  8976. };
  8977. return;
  8978. }
  8979. info.startPTS = Math.min(info.startPTS, startPTS);
  8980. info.endPTS = Math.max(info.endPTS, endPTS);
  8981. info.startDTS = Math.min(info.startDTS, startDTS);
  8982. info.endDTS = Math.max(info.endDTS, endDTS);
  8983. }
  8984. }
  8985. class Part extends BaseSegment {
  8986. constructor(partAttrs, frag, base, index2, previous) {
  8987. super(base);
  8988. this.fragOffset = 0;
  8989. this.duration = 0;
  8990. this.gap = false;
  8991. this.independent = false;
  8992. this.relurl = void 0;
  8993. this.fragment = void 0;
  8994. this.index = void 0;
  8995. this.duration = partAttrs.decimalFloatingPoint("DURATION");
  8996. this.gap = partAttrs.bool("GAP");
  8997. this.independent = partAttrs.bool("INDEPENDENT");
  8998. this.relurl = partAttrs.enumeratedString("URI");
  8999. this.fragment = frag;
  9000. this.index = index2;
  9001. const byteRange = partAttrs.enumeratedString("BYTERANGE");
  9002. if (byteRange) {
  9003. this.setByteRange(byteRange, previous);
  9004. }
  9005. if (previous) {
  9006. this.fragOffset = previous.fragOffset + previous.duration;
  9007. }
  9008. }
  9009. get start() {
  9010. return this.fragment.start + this.fragOffset;
  9011. }
  9012. get end() {
  9013. return this.start + this.duration;
  9014. }
  9015. get loaded() {
  9016. const {
  9017. elementaryStreams
  9018. } = this;
  9019. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  9020. }
  9021. }
  9022. function getOwnPropertyDescriptorFromPrototypeChain(object, property) {
  9023. const prototype = Object.getPrototypeOf(object);
  9024. if (prototype) {
  9025. const propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, property);
  9026. if (propertyDescriptor) {
  9027. return propertyDescriptor;
  9028. }
  9029. return getOwnPropertyDescriptorFromPrototypeChain(prototype, property);
  9030. }
  9031. }
  9032. function makeEnumerable(object, property) {
  9033. const d2 = getOwnPropertyDescriptorFromPrototypeChain(object, property);
  9034. if (d2) {
  9035. d2.enumerable = true;
  9036. Object.defineProperty(object, property, d2);
  9037. }
  9038. }
  9039. const UINT32_MAX$1 = Math.pow(2, 32) - 1;
  9040. const push = [].push;
  9041. const RemuxerTrackIdConfig = {
  9042. video: 1,
  9043. audio: 2,
  9044. id3: 3,
  9045. text: 4
  9046. };
  9047. function bin2str(data) {
  9048. return String.fromCharCode.apply(null, data);
  9049. }
  9050. function readUint16(buffer2, offset) {
  9051. const val = buffer2[offset] << 8 | buffer2[offset + 1];
  9052. return val < 0 ? 65536 + val : val;
  9053. }
  9054. function readUint32(buffer2, offset) {
  9055. const val = readSint32(buffer2, offset);
  9056. return val < 0 ? 4294967296 + val : val;
  9057. }
  9058. function readUint64(buffer2, offset) {
  9059. let result = readUint32(buffer2, offset);
  9060. result *= Math.pow(2, 32);
  9061. result += readUint32(buffer2, offset + 4);
  9062. return result;
  9063. }
  9064. function readSint32(buffer2, offset) {
  9065. return buffer2[offset] << 24 | buffer2[offset + 1] << 16 | buffer2[offset + 2] << 8 | buffer2[offset + 3];
  9066. }
  9067. function hasMoofData(data) {
  9068. const end = data.byteLength;
  9069. for (let i2 = 0; i2 < end; ) {
  9070. const size2 = readUint32(data, i2);
  9071. if (size2 > 8 && data[i2 + 4] === 109 && data[i2 + 5] === 111 && data[i2 + 6] === 111 && data[i2 + 7] === 102) {
  9072. return true;
  9073. }
  9074. i2 = size2 > 1 ? i2 + size2 : end;
  9075. }
  9076. return false;
  9077. }
  9078. function findBox(data, path) {
  9079. const results = [];
  9080. if (!path.length) {
  9081. return results;
  9082. }
  9083. const end = data.byteLength;
  9084. for (let i2 = 0; i2 < end; ) {
  9085. const size2 = readUint32(data, i2);
  9086. const type = bin2str(data.subarray(i2 + 4, i2 + 8));
  9087. const endbox = size2 > 1 ? i2 + size2 : end;
  9088. if (type === path[0]) {
  9089. if (path.length === 1) {
  9090. results.push(data.subarray(i2 + 8, endbox));
  9091. } else {
  9092. const subresults = findBox(data.subarray(i2 + 8, endbox), path.slice(1));
  9093. if (subresults.length) {
  9094. push.apply(results, subresults);
  9095. }
  9096. }
  9097. }
  9098. i2 = endbox;
  9099. }
  9100. return results;
  9101. }
  9102. function parseSegmentIndex(sidx) {
  9103. const references = [];
  9104. const version2 = sidx[0];
  9105. let index2 = 8;
  9106. const timescale = readUint32(sidx, index2);
  9107. index2 += 4;
  9108. let earliestPresentationTime = 0;
  9109. let firstOffset = 0;
  9110. if (version2 === 0) {
  9111. earliestPresentationTime = readUint32(sidx, index2);
  9112. firstOffset = readUint32(sidx, index2 + 4);
  9113. index2 += 8;
  9114. } else {
  9115. earliestPresentationTime = readUint64(sidx, index2);
  9116. firstOffset = readUint64(sidx, index2 + 8);
  9117. index2 += 16;
  9118. }
  9119. index2 += 2;
  9120. let startByte = sidx.length + firstOffset;
  9121. const referencesCount = readUint16(sidx, index2);
  9122. index2 += 2;
  9123. for (let i2 = 0; i2 < referencesCount; i2++) {
  9124. let referenceIndex = index2;
  9125. const referenceInfo = readUint32(sidx, referenceIndex);
  9126. referenceIndex += 4;
  9127. const referenceSize = referenceInfo & 2147483647;
  9128. const referenceType = (referenceInfo & 2147483648) >>> 31;
  9129. if (referenceType === 1) {
  9130. logger.warn("SIDX has hierarchical references (not supported)");
  9131. return null;
  9132. }
  9133. const subsegmentDuration = readUint32(sidx, referenceIndex);
  9134. referenceIndex += 4;
  9135. references.push({
  9136. referenceSize,
  9137. subsegmentDuration,
  9138. // unscaled
  9139. info: {
  9140. duration: subsegmentDuration / timescale,
  9141. start: startByte,
  9142. end: startByte + referenceSize - 1
  9143. }
  9144. });
  9145. startByte += referenceSize;
  9146. referenceIndex += 4;
  9147. index2 = referenceIndex;
  9148. }
  9149. return {
  9150. earliestPresentationTime,
  9151. timescale,
  9152. version: version2,
  9153. referencesCount,
  9154. references
  9155. };
  9156. }
  9157. function parseInitSegment(initSegment) {
  9158. const result = [];
  9159. const traks = findBox(initSegment, ["moov", "trak"]);
  9160. for (let i2 = 0; i2 < traks.length; i2++) {
  9161. const trak = traks[i2];
  9162. const tkhd = findBox(trak, ["tkhd"])[0];
  9163. if (tkhd) {
  9164. let version2 = tkhd[0];
  9165. const trackId = readUint32(tkhd, version2 === 0 ? 12 : 20);
  9166. const mdhd = findBox(trak, ["mdia", "mdhd"])[0];
  9167. if (mdhd) {
  9168. version2 = mdhd[0];
  9169. const timescale = readUint32(mdhd, version2 === 0 ? 12 : 20);
  9170. const hdlr = findBox(trak, ["mdia", "hdlr"])[0];
  9171. if (hdlr) {
  9172. const hdlrType = bin2str(hdlr.subarray(8, 12));
  9173. const type = {
  9174. soun: ElementaryStreamTypes.AUDIO,
  9175. vide: ElementaryStreamTypes.VIDEO
  9176. }[hdlrType];
  9177. const stsdBox = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
  9178. const stsd = parseStsd(stsdBox);
  9179. if (type) {
  9180. result[trackId] = {
  9181. timescale,
  9182. type,
  9183. stsd
  9184. };
  9185. result[type] = _objectSpread2({
  9186. timescale,
  9187. id: trackId
  9188. }, stsd);
  9189. } else {
  9190. result[trackId] = {
  9191. timescale,
  9192. type: hdlrType,
  9193. stsd
  9194. };
  9195. }
  9196. }
  9197. }
  9198. }
  9199. }
  9200. const trex = findBox(initSegment, ["moov", "mvex", "trex"]);
  9201. trex.forEach((trex2) => {
  9202. const trackId = readUint32(trex2, 4);
  9203. const track2 = result[trackId];
  9204. if (track2) {
  9205. track2.default = {
  9206. duration: readUint32(trex2, 12),
  9207. flags: readUint32(trex2, 20)
  9208. };
  9209. }
  9210. });
  9211. return result;
  9212. }
  9213. function parseStsd(stsd) {
  9214. const sampleEntries = stsd.subarray(8);
  9215. const sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  9216. const fourCC = bin2str(sampleEntries.subarray(4, 8));
  9217. let codec = fourCC;
  9218. let supplemental;
  9219. const encrypted = fourCC === "enca" || fourCC === "encv";
  9220. if (encrypted) {
  9221. const encBox = findBox(sampleEntries, [fourCC])[0];
  9222. const encBoxChildren = encBox.subarray(fourCC === "enca" ? 28 : 78);
  9223. const sinfs = findBox(encBoxChildren, ["sinf"]);
  9224. sinfs.forEach((sinf) => {
  9225. const schm = findBox(sinf, ["schm"])[0];
  9226. if (schm) {
  9227. const scheme = bin2str(schm.subarray(4, 8));
  9228. if (scheme === "cbcs" || scheme === "cenc") {
  9229. const frma = findBox(sinf, ["frma"])[0];
  9230. if (frma) {
  9231. codec = bin2str(frma);
  9232. }
  9233. }
  9234. }
  9235. });
  9236. }
  9237. const codecFourCC = codec;
  9238. switch (codec) {
  9239. case "avc1":
  9240. case "avc2":
  9241. case "avc3":
  9242. case "avc4": {
  9243. const avcCBox = findBox(sampleEntriesEnd, ["avcC"])[0];
  9244. if (avcCBox && avcCBox.length > 3) {
  9245. codec += "." + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  9246. supplemental = parseSupplementalDoViCodec(codecFourCC === "avc1" ? "dva1" : "dvav", sampleEntriesEnd);
  9247. }
  9248. break;
  9249. }
  9250. case "mp4a": {
  9251. const codecBox = findBox(sampleEntries, [fourCC])[0];
  9252. const esdsBox = findBox(codecBox.subarray(28), ["esds"])[0];
  9253. if (esdsBox && esdsBox.length > 7) {
  9254. let i2 = 4;
  9255. if (esdsBox[i2++] !== 3) {
  9256. break;
  9257. }
  9258. i2 = skipBERInteger(esdsBox, i2);
  9259. i2 += 2;
  9260. const flags = esdsBox[i2++];
  9261. if (flags & 128) {
  9262. i2 += 2;
  9263. }
  9264. if (flags & 64) {
  9265. i2 += esdsBox[i2++];
  9266. }
  9267. if (esdsBox[i2++] !== 4) {
  9268. break;
  9269. }
  9270. i2 = skipBERInteger(esdsBox, i2);
  9271. const objectType = esdsBox[i2++];
  9272. if (objectType === 64) {
  9273. codec += "." + toHex(objectType);
  9274. } else {
  9275. break;
  9276. }
  9277. i2 += 12;
  9278. if (esdsBox[i2++] !== 5) {
  9279. break;
  9280. }
  9281. i2 = skipBERInteger(esdsBox, i2);
  9282. const firstByte = esdsBox[i2++];
  9283. let audioObjectType = (firstByte & 248) >> 3;
  9284. if (audioObjectType === 31) {
  9285. audioObjectType += 1 + ((firstByte & 7) << 3) + ((esdsBox[i2] & 224) >> 5);
  9286. }
  9287. codec += "." + audioObjectType;
  9288. }
  9289. break;
  9290. }
  9291. case "hvc1":
  9292. case "hev1": {
  9293. const hvcCBox = findBox(sampleEntriesEnd, ["hvcC"])[0];
  9294. if (hvcCBox && hvcCBox.length > 12) {
  9295. const profileByte = hvcCBox[1];
  9296. const profileSpace = ["", "A", "B", "C"][profileByte >> 6];
  9297. const generalProfileIdc = profileByte & 31;
  9298. const profileCompat = readUint32(hvcCBox, 2);
  9299. const tierFlag = (profileByte & 32) >> 5 ? "H" : "L";
  9300. const levelIDC = hvcCBox[12];
  9301. const constraintIndicator = hvcCBox.subarray(6, 12);
  9302. codec += "." + profileSpace + generalProfileIdc;
  9303. codec += "." + reverse32BitInt(profileCompat).toString(16).toUpperCase();
  9304. codec += "." + tierFlag + levelIDC;
  9305. let constraintString = "";
  9306. for (let i2 = constraintIndicator.length; i2--; ) {
  9307. const byte = constraintIndicator[i2];
  9308. if (byte || constraintString) {
  9309. const encodedByte = byte.toString(16).toUpperCase();
  9310. constraintString = "." + encodedByte + constraintString;
  9311. }
  9312. }
  9313. codec += constraintString;
  9314. }
  9315. supplemental = parseSupplementalDoViCodec(codecFourCC == "hev1" ? "dvhe" : "dvh1", sampleEntriesEnd);
  9316. break;
  9317. }
  9318. case "dvh1":
  9319. case "dvhe":
  9320. case "dvav":
  9321. case "dva1":
  9322. case "dav1": {
  9323. codec = parseSupplementalDoViCodec(codec, sampleEntriesEnd) || codec;
  9324. break;
  9325. }
  9326. case "vp09": {
  9327. const vpcCBox = findBox(sampleEntriesEnd, ["vpcC"])[0];
  9328. if (vpcCBox && vpcCBox.length > 6) {
  9329. const profile = vpcCBox[4];
  9330. const level = vpcCBox[5];
  9331. const bitDepth = vpcCBox[6] >> 4 & 15;
  9332. codec += "." + addLeadingZero(profile) + "." + addLeadingZero(level) + "." + addLeadingZero(bitDepth);
  9333. }
  9334. break;
  9335. }
  9336. case "av01": {
  9337. const av1CBox = findBox(sampleEntriesEnd, ["av1C"])[0];
  9338. if (av1CBox && av1CBox.length > 2) {
  9339. const profile = av1CBox[1] >>> 5;
  9340. const level = av1CBox[1] & 31;
  9341. const tierFlag = av1CBox[2] >>> 7 ? "H" : "M";
  9342. const highBitDepth = (av1CBox[2] & 64) >> 6;
  9343. const twelveBit = (av1CBox[2] & 32) >> 5;
  9344. const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  9345. const monochrome = (av1CBox[2] & 16) >> 4;
  9346. const chromaSubsamplingX = (av1CBox[2] & 8) >> 3;
  9347. const chromaSubsamplingY = (av1CBox[2] & 4) >> 2;
  9348. const chromaSamplePosition = av1CBox[2] & 3;
  9349. const colorPrimaries = 1;
  9350. const transferCharacteristics = 1;
  9351. const matrixCoefficients = 1;
  9352. const videoFullRangeFlag = 0;
  9353. codec += "." + profile + "." + addLeadingZero(level) + tierFlag + "." + addLeadingZero(bitDepth) + "." + monochrome + "." + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + "." + addLeadingZero(colorPrimaries) + "." + addLeadingZero(transferCharacteristics) + "." + addLeadingZero(matrixCoefficients) + "." + videoFullRangeFlag;
  9354. supplemental = parseSupplementalDoViCodec("dav1", sampleEntriesEnd);
  9355. }
  9356. break;
  9357. }
  9358. }
  9359. return {
  9360. codec,
  9361. encrypted,
  9362. supplemental
  9363. };
  9364. }
  9365. function parseSupplementalDoViCodec(fourCC, sampleEntriesEnd) {
  9366. const dvvCResult = findBox(sampleEntriesEnd, ["dvvC"]);
  9367. const dvXCBox = dvvCResult.length ? dvvCResult[0] : findBox(sampleEntriesEnd, ["dvcC"])[0];
  9368. if (dvXCBox) {
  9369. const doViProfile = dvXCBox[2] >> 1 & 127;
  9370. const doViLevel = dvXCBox[2] << 5 & 32 | dvXCBox[3] >> 3 & 31;
  9371. return fourCC + "." + addLeadingZero(doViProfile) + "." + addLeadingZero(doViLevel);
  9372. }
  9373. }
  9374. function reverse32BitInt(val) {
  9375. let result = 0;
  9376. for (let i2 = 0; i2 < 32; i2++) {
  9377. result |= (val >> i2 & 1) << 32 - 1 - i2;
  9378. }
  9379. return result >>> 0;
  9380. }
  9381. function skipBERInteger(bytes, i2) {
  9382. const limit = i2 + 5;
  9383. while (bytes[i2++] & 128 && i2 < limit) {
  9384. }
  9385. return i2;
  9386. }
  9387. function toHex(x) {
  9388. return ("0" + x.toString(16).toUpperCase()).slice(-2);
  9389. }
  9390. function addLeadingZero(num) {
  9391. return (num < 10 ? "0" : "") + num;
  9392. }
  9393. function patchEncyptionData(initSegment, decryptdata) {
  9394. if (!initSegment || !decryptdata) {
  9395. return initSegment;
  9396. }
  9397. const keyId = decryptdata.keyId;
  9398. if (keyId && decryptdata.isCommonEncryption) {
  9399. const traks = findBox(initSegment, ["moov", "trak"]);
  9400. traks.forEach((trak) => {
  9401. const stsd = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
  9402. const sampleEntries = stsd.subarray(8);
  9403. let encBoxes = findBox(sampleEntries, ["enca"]);
  9404. const isAudio = encBoxes.length > 0;
  9405. if (!isAudio) {
  9406. encBoxes = findBox(sampleEntries, ["encv"]);
  9407. }
  9408. encBoxes.forEach((enc) => {
  9409. const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  9410. const sinfBoxes = findBox(encBoxChildren, ["sinf"]);
  9411. sinfBoxes.forEach((sinf) => {
  9412. const tenc = parseSinf(sinf);
  9413. if (tenc) {
  9414. const tencKeyId = tenc.subarray(8, 24);
  9415. if (!tencKeyId.some((b2) => b2 !== 0)) {
  9416. logger.log(`[eme] Patching keyId in 'enc${isAudio ? "a" : "v"}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`);
  9417. tenc.set(keyId, 8);
  9418. }
  9419. }
  9420. });
  9421. });
  9422. });
  9423. }
  9424. return initSegment;
  9425. }
  9426. function parseSinf(sinf) {
  9427. const schm = findBox(sinf, ["schm"])[0];
  9428. if (schm) {
  9429. const scheme = bin2str(schm.subarray(4, 8));
  9430. if (scheme === "cbcs" || scheme === "cenc") {
  9431. return findBox(sinf, ["schi", "tenc"])[0];
  9432. }
  9433. }
  9434. return null;
  9435. }
  9436. function getSampleData(data, initData2, logger2) {
  9437. const tracks = {};
  9438. const trafs = findBox(data, ["moof", "traf"]);
  9439. for (let i2 = 0; i2 < trafs.length; i2++) {
  9440. const traf = trafs[i2];
  9441. const tfhd = findBox(traf, ["tfhd"])[0];
  9442. const id = readUint32(tfhd, 4);
  9443. const track2 = initData2[id];
  9444. if (!track2) {
  9445. continue;
  9446. }
  9447. const trackTimes = tracks[id] || (tracks[id] = {
  9448. start: NaN,
  9449. duration: 0,
  9450. sampleCount: 0,
  9451. timescale: track2.timescale,
  9452. type: track2.type
  9453. });
  9454. const tfdt = findBox(traf, ["tfdt"])[0];
  9455. if (tfdt) {
  9456. const version2 = tfdt[0];
  9457. let baseTime = readUint32(tfdt, 4);
  9458. if (version2 === 1) {
  9459. if (baseTime === UINT32_MAX$1) {
  9460. logger2.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);
  9461. } else {
  9462. baseTime *= UINT32_MAX$1 + 1;
  9463. baseTime += readUint32(tfdt, 8);
  9464. }
  9465. }
  9466. if (isFiniteNumber(baseTime) && (!isFiniteNumber(trackTimes.start) || baseTime < trackTimes.start)) {
  9467. trackTimes.start = baseTime;
  9468. }
  9469. }
  9470. const trackDefault = track2.default;
  9471. const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  9472. let defaultSampleDuration = (trackDefault == null ? void 0 : trackDefault.duration) || 0;
  9473. if (tfhdFlags & 8) {
  9474. if (tfhdFlags & 2) {
  9475. defaultSampleDuration = readUint32(tfhd, 12);
  9476. } else {
  9477. defaultSampleDuration = readUint32(tfhd, 8);
  9478. }
  9479. }
  9480. const truns = findBox(traf, ["trun"]);
  9481. let sampleDTS = trackTimes.start || 0;
  9482. let rawDuration = 0;
  9483. let sampleDuration = defaultSampleDuration;
  9484. for (let j2 = 0; j2 < truns.length; j2++) {
  9485. const trun = truns[j2];
  9486. const sampleCount = readUint32(trun, 4);
  9487. const sampleIndex = trackTimes.sampleCount;
  9488. trackTimes.sampleCount += sampleCount;
  9489. const dataOffsetPresent = trun[3] & 1;
  9490. const firstSampleFlagsPresent = trun[3] & 4;
  9491. const sampleDurationPresent = trun[2] & 1;
  9492. const sampleSizePresent = trun[2] & 2;
  9493. const sampleFlagsPresent = trun[2] & 4;
  9494. const sampleCompositionTimeOffsetPresent = trun[2] & 8;
  9495. let offset = 8;
  9496. let remaining = sampleCount;
  9497. if (dataOffsetPresent) {
  9498. offset += 4;
  9499. }
  9500. if (firstSampleFlagsPresent && sampleCount) {
  9501. const isNonSyncSample = trun[offset + 1] & 1;
  9502. if (!isNonSyncSample && trackTimes.keyFrameIndex === void 0) {
  9503. trackTimes.keyFrameIndex = sampleIndex;
  9504. }
  9505. offset += 4;
  9506. if (sampleDurationPresent) {
  9507. sampleDuration = readUint32(trun, offset);
  9508. offset += 4;
  9509. } else {
  9510. sampleDuration = defaultSampleDuration;
  9511. }
  9512. if (sampleSizePresent) {
  9513. offset += 4;
  9514. }
  9515. if (sampleCompositionTimeOffsetPresent) {
  9516. offset += 4;
  9517. }
  9518. sampleDTS += sampleDuration;
  9519. rawDuration += sampleDuration;
  9520. remaining--;
  9521. }
  9522. while (remaining--) {
  9523. if (sampleDurationPresent) {
  9524. sampleDuration = readUint32(trun, offset);
  9525. offset += 4;
  9526. } else {
  9527. sampleDuration = defaultSampleDuration;
  9528. }
  9529. if (sampleSizePresent) {
  9530. offset += 4;
  9531. }
  9532. if (sampleFlagsPresent) {
  9533. const isNonSyncSample = trun[offset + 1] & 1;
  9534. if (!isNonSyncSample) {
  9535. if (trackTimes.keyFrameIndex === void 0) {
  9536. trackTimes.keyFrameIndex = trackTimes.sampleCount - (remaining + 1);
  9537. trackTimes.keyFrameStart = sampleDTS;
  9538. }
  9539. }
  9540. offset += 4;
  9541. }
  9542. if (sampleCompositionTimeOffsetPresent) {
  9543. offset += 4;
  9544. }
  9545. sampleDTS += sampleDuration;
  9546. rawDuration += sampleDuration;
  9547. }
  9548. if (!rawDuration && defaultSampleDuration) {
  9549. rawDuration += defaultSampleDuration * sampleCount;
  9550. }
  9551. }
  9552. trackTimes.duration += rawDuration;
  9553. }
  9554. if (!Object.keys(tracks).some((trackId) => tracks[trackId].duration)) {
  9555. let sidxMinStart = Infinity;
  9556. let sidxMaxEnd = 0;
  9557. const sidxs = findBox(data, ["sidx"]);
  9558. for (let i2 = 0; i2 < sidxs.length; i2++) {
  9559. const sidx = parseSegmentIndex(sidxs[i2]);
  9560. if (sidx != null && sidx.references) {
  9561. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  9562. const subSegmentDuration = sidx.references.reduce((dur, ref2) => dur + ref2.info.duration || 0, 0);
  9563. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  9564. }
  9565. }
  9566. if (sidxMaxEnd && isFiniteNumber(sidxMaxEnd)) {
  9567. Object.keys(tracks).forEach((trackId) => {
  9568. if (!tracks[trackId].duration) {
  9569. tracks[trackId].duration = sidxMaxEnd * tracks[trackId].timescale - tracks[trackId].start;
  9570. }
  9571. });
  9572. }
  9573. }
  9574. return tracks;
  9575. }
  9576. function segmentValidRange(data) {
  9577. const segmentedRange = {
  9578. valid: null,
  9579. remainder: null
  9580. };
  9581. const moofs = findBox(data, ["moof"]);
  9582. if (moofs.length < 2) {
  9583. segmentedRange.remainder = data;
  9584. return segmentedRange;
  9585. }
  9586. const last = moofs[moofs.length - 1];
  9587. segmentedRange.valid = data.slice(0, last.byteOffset - 8);
  9588. segmentedRange.remainder = data.slice(last.byteOffset - 8);
  9589. return segmentedRange;
  9590. }
  9591. function appendUint8Array(data1, data2) {
  9592. const temp = new Uint8Array(data1.length + data2.length);
  9593. temp.set(data1);
  9594. temp.set(data2, data1.length);
  9595. return temp;
  9596. }
  9597. function parseSamples(timeOffset, track2) {
  9598. const seiSamples = [];
  9599. const videoData = track2.samples;
  9600. const timescale = track2.timescale;
  9601. const trackId = track2.id;
  9602. let isHEVCFlavor = false;
  9603. const moofs = findBox(videoData, ["moof"]);
  9604. moofs.map((moof) => {
  9605. const moofOffset = moof.byteOffset - 8;
  9606. const trafs = findBox(moof, ["traf"]);
  9607. trafs.map((traf) => {
  9608. const baseTime = findBox(traf, ["tfdt"]).map((tfdt) => {
  9609. const version2 = tfdt[0];
  9610. let result = readUint32(tfdt, 4);
  9611. if (version2 === 1) {
  9612. result *= Math.pow(2, 32);
  9613. result += readUint32(tfdt, 8);
  9614. }
  9615. return result / timescale;
  9616. })[0];
  9617. if (baseTime !== void 0) {
  9618. timeOffset = baseTime;
  9619. }
  9620. return findBox(traf, ["tfhd"]).map((tfhd) => {
  9621. const id = readUint32(tfhd, 4);
  9622. const tfhdFlags = readUint32(tfhd, 0) & 16777215;
  9623. const baseDataOffsetPresent = (tfhdFlags & 1) !== 0;
  9624. const sampleDescriptionIndexPresent = (tfhdFlags & 2) !== 0;
  9625. const defaultSampleDurationPresent = (tfhdFlags & 8) !== 0;
  9626. let defaultSampleDuration = 0;
  9627. const defaultSampleSizePresent = (tfhdFlags & 16) !== 0;
  9628. let defaultSampleSize = 0;
  9629. const defaultSampleFlagsPresent = (tfhdFlags & 32) !== 0;
  9630. let tfhdOffset = 8;
  9631. if (id === trackId) {
  9632. if (baseDataOffsetPresent) {
  9633. tfhdOffset += 8;
  9634. }
  9635. if (sampleDescriptionIndexPresent) {
  9636. tfhdOffset += 4;
  9637. }
  9638. if (defaultSampleDurationPresent) {
  9639. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  9640. tfhdOffset += 4;
  9641. }
  9642. if (defaultSampleSizePresent) {
  9643. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  9644. tfhdOffset += 4;
  9645. }
  9646. if (defaultSampleFlagsPresent) {
  9647. tfhdOffset += 4;
  9648. }
  9649. if (track2.type === "video") {
  9650. isHEVCFlavor = isHEVC(track2.codec);
  9651. }
  9652. findBox(traf, ["trun"]).map((trun) => {
  9653. const version2 = trun[0];
  9654. const flags = readUint32(trun, 0) & 16777215;
  9655. const dataOffsetPresent = (flags & 1) !== 0;
  9656. let dataOffset = 0;
  9657. const firstSampleFlagsPresent = (flags & 4) !== 0;
  9658. const sampleDurationPresent = (flags & 256) !== 0;
  9659. let sampleDuration = 0;
  9660. const sampleSizePresent = (flags & 512) !== 0;
  9661. let sampleSize = 0;
  9662. const sampleFlagsPresent = (flags & 1024) !== 0;
  9663. const sampleCompositionOffsetsPresent = (flags & 2048) !== 0;
  9664. let compositionOffset = 0;
  9665. const sampleCount = readUint32(trun, 4);
  9666. let trunOffset = 8;
  9667. if (dataOffsetPresent) {
  9668. dataOffset = readUint32(trun, trunOffset);
  9669. trunOffset += 4;
  9670. }
  9671. if (firstSampleFlagsPresent) {
  9672. trunOffset += 4;
  9673. }
  9674. let sampleOffset = dataOffset + moofOffset;
  9675. for (let ix = 0; ix < sampleCount; ix++) {
  9676. if (sampleDurationPresent) {
  9677. sampleDuration = readUint32(trun, trunOffset);
  9678. trunOffset += 4;
  9679. } else {
  9680. sampleDuration = defaultSampleDuration;
  9681. }
  9682. if (sampleSizePresent) {
  9683. sampleSize = readUint32(trun, trunOffset);
  9684. trunOffset += 4;
  9685. } else {
  9686. sampleSize = defaultSampleSize;
  9687. }
  9688. if (sampleFlagsPresent) {
  9689. trunOffset += 4;
  9690. }
  9691. if (sampleCompositionOffsetsPresent) {
  9692. if (version2 === 0) {
  9693. compositionOffset = readUint32(trun, trunOffset);
  9694. } else {
  9695. compositionOffset = readSint32(trun, trunOffset);
  9696. }
  9697. trunOffset += 4;
  9698. }
  9699. if (track2.type === ElementaryStreamTypes.VIDEO) {
  9700. let naluTotalSize = 0;
  9701. while (naluTotalSize < sampleSize) {
  9702. const naluSize = readUint32(videoData, sampleOffset);
  9703. sampleOffset += 4;
  9704. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  9705. const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  9706. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  9707. }
  9708. sampleOffset += naluSize;
  9709. naluTotalSize += naluSize + 4;
  9710. }
  9711. }
  9712. timeOffset += sampleDuration / timescale;
  9713. }
  9714. });
  9715. }
  9716. });
  9717. });
  9718. });
  9719. return seiSamples;
  9720. }
  9721. function isHEVC(codec) {
  9722. if (!codec) {
  9723. return false;
  9724. }
  9725. const baseCodec = codec.substring(0, 4);
  9726. return baseCodec === "hvc1" || baseCodec === "hev1" || // Dolby Vision
  9727. baseCodec === "dvh1" || baseCodec === "dvhe";
  9728. }
  9729. function isSEIMessage(isHEVCFlavor, naluHeader) {
  9730. if (isHEVCFlavor) {
  9731. const naluType = naluHeader >> 1 & 63;
  9732. return naluType === 39 || naluType === 40;
  9733. } else {
  9734. const naluType = naluHeader & 31;
  9735. return naluType === 6;
  9736. }
  9737. }
  9738. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  9739. const data = discardEPB(unescapedData);
  9740. let seiPtr = 0;
  9741. seiPtr += headerSize;
  9742. let payloadType = 0;
  9743. let payloadSize = 0;
  9744. let b2 = 0;
  9745. while (seiPtr < data.length) {
  9746. payloadType = 0;
  9747. do {
  9748. if (seiPtr >= data.length) {
  9749. break;
  9750. }
  9751. b2 = data[seiPtr++];
  9752. payloadType += b2;
  9753. } while (b2 === 255);
  9754. payloadSize = 0;
  9755. do {
  9756. if (seiPtr >= data.length) {
  9757. break;
  9758. }
  9759. b2 = data[seiPtr++];
  9760. payloadSize += b2;
  9761. } while (b2 === 255);
  9762. const leftOver = data.length - seiPtr;
  9763. let payPtr = seiPtr;
  9764. if (payloadSize < leftOver) {
  9765. seiPtr += payloadSize;
  9766. } else if (payloadSize > leftOver) {
  9767. logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);
  9768. break;
  9769. }
  9770. if (payloadType === 4) {
  9771. const countryCode = data[payPtr++];
  9772. if (countryCode === 181) {
  9773. const providerCode = readUint16(data, payPtr);
  9774. payPtr += 2;
  9775. if (providerCode === 49) {
  9776. const userStructure = readUint32(data, payPtr);
  9777. payPtr += 4;
  9778. if (userStructure === 1195456820) {
  9779. const userDataType = data[payPtr++];
  9780. if (userDataType === 3) {
  9781. const firstByte = data[payPtr++];
  9782. const totalCCs = 31 & firstByte;
  9783. const enabled2 = 64 & firstByte;
  9784. const totalBytes = enabled2 ? 2 + totalCCs * 3 : 0;
  9785. const byteArray = new Uint8Array(totalBytes);
  9786. if (enabled2) {
  9787. byteArray[0] = firstByte;
  9788. for (let i2 = 1; i2 < totalBytes; i2++) {
  9789. byteArray[i2] = data[payPtr++];
  9790. }
  9791. }
  9792. samples.push({
  9793. type: userDataType,
  9794. payloadType,
  9795. pts,
  9796. bytes: byteArray
  9797. });
  9798. }
  9799. }
  9800. }
  9801. }
  9802. } else if (payloadType === 5) {
  9803. if (payloadSize > 16) {
  9804. const uuidStrArray = [];
  9805. for (let i2 = 0; i2 < 16; i2++) {
  9806. const _b = data[payPtr++].toString(16);
  9807. uuidStrArray.push(_b.length == 1 ? "0" + _b : _b);
  9808. if (i2 === 3 || i2 === 5 || i2 === 7 || i2 === 9) {
  9809. uuidStrArray.push("-");
  9810. }
  9811. }
  9812. const length = payloadSize - 16;
  9813. const userDataBytes = new Uint8Array(length);
  9814. for (let i2 = 0; i2 < length; i2++) {
  9815. userDataBytes[i2] = data[payPtr++];
  9816. }
  9817. samples.push({
  9818. payloadType,
  9819. pts,
  9820. uuid: uuidStrArray.join(""),
  9821. userData: utf8ArrayToStr(userDataBytes),
  9822. userDataBytes
  9823. });
  9824. }
  9825. }
  9826. }
  9827. }
  9828. function discardEPB(data) {
  9829. const length = data.byteLength;
  9830. const EPBPositions = [];
  9831. let i2 = 1;
  9832. while (i2 < length - 2) {
  9833. if (data[i2] === 0 && data[i2 + 1] === 0 && data[i2 + 2] === 3) {
  9834. EPBPositions.push(i2 + 2);
  9835. i2 += 2;
  9836. } else {
  9837. i2++;
  9838. }
  9839. }
  9840. if (EPBPositions.length === 0) {
  9841. return data;
  9842. }
  9843. const newLength = length - EPBPositions.length;
  9844. const newData = new Uint8Array(newLength);
  9845. let sourceIndex = 0;
  9846. for (i2 = 0; i2 < newLength; sourceIndex++, i2++) {
  9847. if (sourceIndex === EPBPositions[0]) {
  9848. sourceIndex++;
  9849. EPBPositions.shift();
  9850. }
  9851. newData[i2] = data[sourceIndex];
  9852. }
  9853. return newData;
  9854. }
  9855. function parseEmsg(data) {
  9856. const version2 = data[0];
  9857. let schemeIdUri = "";
  9858. let value = "";
  9859. let timeScale = 0;
  9860. let presentationTimeDelta = 0;
  9861. let presentationTime = 0;
  9862. let eventDuration = 0;
  9863. let id = 0;
  9864. let offset = 0;
  9865. if (version2 === 0) {
  9866. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  9867. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  9868. offset += 1;
  9869. }
  9870. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  9871. offset += 1;
  9872. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  9873. value += bin2str(data.subarray(offset, offset + 1));
  9874. offset += 1;
  9875. }
  9876. value += bin2str(data.subarray(offset, offset + 1));
  9877. offset += 1;
  9878. timeScale = readUint32(data, 12);
  9879. presentationTimeDelta = readUint32(data, 16);
  9880. eventDuration = readUint32(data, 20);
  9881. id = readUint32(data, 24);
  9882. offset = 28;
  9883. } else if (version2 === 1) {
  9884. offset += 4;
  9885. timeScale = readUint32(data, offset);
  9886. offset += 4;
  9887. const leftPresentationTime = readUint32(data, offset);
  9888. offset += 4;
  9889. const rightPresentationTime = readUint32(data, offset);
  9890. offset += 4;
  9891. presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;
  9892. if (!isSafeInteger(presentationTime)) {
  9893. presentationTime = Number.MAX_SAFE_INTEGER;
  9894. logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box");
  9895. }
  9896. eventDuration = readUint32(data, offset);
  9897. offset += 4;
  9898. id = readUint32(data, offset);
  9899. offset += 4;
  9900. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  9901. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  9902. offset += 1;
  9903. }
  9904. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  9905. offset += 1;
  9906. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  9907. value += bin2str(data.subarray(offset, offset + 1));
  9908. offset += 1;
  9909. }
  9910. value += bin2str(data.subarray(offset, offset + 1));
  9911. offset += 1;
  9912. }
  9913. const payload = data.subarray(offset, data.byteLength);
  9914. return {
  9915. schemeIdUri,
  9916. value,
  9917. timeScale,
  9918. presentationTime,
  9919. presentationTimeDelta,
  9920. eventDuration,
  9921. id,
  9922. payload
  9923. };
  9924. }
  9925. function mp4Box(type, ...payload) {
  9926. const len = payload.length;
  9927. let size2 = 8;
  9928. let i2 = len;
  9929. while (i2--) {
  9930. size2 += payload[i2].byteLength;
  9931. }
  9932. const result = new Uint8Array(size2);
  9933. result[0] = size2 >> 24 & 255;
  9934. result[1] = size2 >> 16 & 255;
  9935. result[2] = size2 >> 8 & 255;
  9936. result[3] = size2 & 255;
  9937. result.set(type, 4);
  9938. for (i2 = 0, size2 = 8; i2 < len; i2++) {
  9939. result.set(payload[i2], size2);
  9940. size2 += payload[i2].byteLength;
  9941. }
  9942. return result;
  9943. }
  9944. function mp4pssh(systemId, keyids, data) {
  9945. if (systemId.byteLength !== 16) {
  9946. throw new RangeError("Invalid system id");
  9947. }
  9948. let version2;
  9949. let kids;
  9950. {
  9951. version2 = 0;
  9952. kids = new Uint8Array();
  9953. }
  9954. let kidCount;
  9955. if (version2 > 0) {
  9956. kidCount = new Uint8Array(4);
  9957. if (keyids.length > 0) {
  9958. new DataView(kidCount.buffer).setUint32(0, keyids.length, false);
  9959. }
  9960. } else {
  9961. kidCount = new Uint8Array();
  9962. }
  9963. const dataSize = new Uint8Array(4);
  9964. if (data && data.byteLength > 0) {
  9965. new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);
  9966. }
  9967. return mp4Box(
  9968. [112, 115, 115, 104],
  9969. new Uint8Array([
  9970. version2,
  9971. 0,
  9972. 0,
  9973. 0
  9974. // Flags
  9975. ]),
  9976. systemId,
  9977. // 16 bytes
  9978. kidCount,
  9979. kids,
  9980. dataSize,
  9981. data || new Uint8Array()
  9982. );
  9983. }
  9984. const userAgentHevcSupportIsInaccurate = () => {
  9985. return /\(Windows.+Firefox\//i.test(navigator.userAgent);
  9986. };
  9987. const sampleEntryCodesISO = {
  9988. audio: {
  9989. a3ds: 1,
  9990. "ac-3": 0.95,
  9991. "ac-4": 1,
  9992. alac: 0.9,
  9993. alaw: 1,
  9994. dra1: 1,
  9995. "dts+": 1,
  9996. "dts-": 1,
  9997. dtsc: 1,
  9998. dtse: 1,
  9999. dtsh: 1,
  10000. "ec-3": 0.9,
  10001. enca: 1,
  10002. fLaC: 0.9,
  10003. // MP4-RA listed codec entry for FLAC
  10004. flac: 0.9,
  10005. // legacy browser codec name for FLAC
  10006. FLAC: 0.9,
  10007. // some manifests may list "FLAC" with Apple's tools
  10008. g719: 1,
  10009. g726: 1,
  10010. m4ae: 1,
  10011. mha1: 1,
  10012. mha2: 1,
  10013. mhm1: 1,
  10014. mhm2: 1,
  10015. mlpa: 1,
  10016. mp4a: 1,
  10017. "raw ": 1,
  10018. Opus: 1,
  10019. opus: 1,
  10020. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  10021. samr: 1,
  10022. sawb: 1,
  10023. sawp: 1,
  10024. sevc: 1,
  10025. sqcp: 1,
  10026. ssmv: 1,
  10027. twos: 1,
  10028. ulaw: 1
  10029. },
  10030. video: {
  10031. avc1: 1,
  10032. avc2: 1,
  10033. avc3: 1,
  10034. avc4: 1,
  10035. avcp: 1,
  10036. av01: 0.8,
  10037. dav1: 0.8,
  10038. drac: 1,
  10039. dva1: 1,
  10040. dvav: 1,
  10041. dvh1: 0.7,
  10042. dvhe: 0.7,
  10043. encv: 1,
  10044. hev1: 0.75,
  10045. hvc1: 0.75,
  10046. mjp2: 1,
  10047. mp4v: 1,
  10048. mvc1: 1,
  10049. mvc2: 1,
  10050. mvc3: 1,
  10051. mvc4: 1,
  10052. resv: 1,
  10053. rv60: 1,
  10054. s263: 1,
  10055. svc1: 1,
  10056. svc2: 1,
  10057. "vc-1": 1,
  10058. vp08: 1,
  10059. vp09: 0.9
  10060. },
  10061. text: {
  10062. stpp: 1,
  10063. wvtt: 1
  10064. }
  10065. };
  10066. function isCodecType(codec, type) {
  10067. const typeCodes = sampleEntryCodesISO[type];
  10068. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  10069. }
  10070. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) {
  10071. return !codecs.split(",").some((codec) => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource));
  10072. }
  10073. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) {
  10074. var _MediaSource$isTypeSu;
  10075. const MediaSource = getMediaSource(preferManagedMediaSource);
  10076. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  10077. }
  10078. function mimeTypeForCodec(codec, type) {
  10079. return `${type}/mp4;codecs=${codec}`;
  10080. }
  10081. function videoCodecPreferenceValue(videoCodec) {
  10082. if (videoCodec) {
  10083. const fourCC = videoCodec.substring(0, 4);
  10084. return sampleEntryCodesISO.video[fourCC];
  10085. }
  10086. return 2;
  10087. }
  10088. function codecsSetSelectionPreferenceValue(codecSet) {
  10089. const limitedHevcSupport = userAgentHevcSupportIsInaccurate();
  10090. return codecSet.split(",").reduce((num, fourCC) => {
  10091. const lowerPriority = limitedHevcSupport && isHEVC(fourCC);
  10092. const preferenceValue = lowerPriority ? 9 : sampleEntryCodesISO.video[fourCC];
  10093. if (preferenceValue) {
  10094. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  10095. }
  10096. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  10097. }, 0);
  10098. }
  10099. const CODEC_COMPATIBLE_NAMES = {};
  10100. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {
  10101. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  10102. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  10103. }
  10104. const codecsToCheck = {
  10105. // Idealy fLaC and Opus would be first (spec-compliant) but
  10106. // some browsers will report that fLaC is supported then fail.
  10107. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  10108. flac: ["flac", "fLaC", "FLAC"],
  10109. opus: ["opus", "Opus"],
  10110. // Replace audio codec info if browser does not support mp4a.40.34,
  10111. // and demuxer can fallback to 'audio/mpeg' or 'audio/mp4;codecs="mp3"'
  10112. "mp4a.40.34": ["mp3"]
  10113. }[lowerCaseCodec];
  10114. for (let i2 = 0; i2 < codecsToCheck.length; i2++) {
  10115. var _getMediaSource;
  10116. if (isCodecMediaSourceSupported(codecsToCheck[i2], "audio", preferManagedMediaSource)) {
  10117. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i2];
  10118. return codecsToCheck[i2];
  10119. } else if (codecsToCheck[i2] === "mp3" && (_getMediaSource = getMediaSource(preferManagedMediaSource)) != null && _getMediaSource.isTypeSupported("audio/mpeg")) {
  10120. return "";
  10121. }
  10122. }
  10123. return lowerCaseCodec;
  10124. }
  10125. const AUDIO_CODEC_REGEXP = /flac|opus|mp4a\.40\.34/i;
  10126. function getCodecCompatibleName(codec, preferManagedMediaSource = true) {
  10127. return codec.replace(AUDIO_CODEC_REGEXP, (m2) => getCodecCompatibleNameLower(m2.toLowerCase(), preferManagedMediaSource));
  10128. }
  10129. function replaceVideoCodec(originalCodecs, newVideoCodec) {
  10130. const codecs = [];
  10131. if (originalCodecs) {
  10132. const allCodecs = originalCodecs.split(",");
  10133. for (let i2 = 0; i2 < allCodecs.length; i2++) {
  10134. if (!isCodecType(allCodecs[i2], "video")) {
  10135. codecs.push(allCodecs[i2]);
  10136. }
  10137. }
  10138. }
  10139. if (newVideoCodec) {
  10140. codecs.push(newVideoCodec);
  10141. }
  10142. return codecs.join(",");
  10143. }
  10144. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  10145. if (parsedCodec && (parsedCodec.length > 4 || ["ac-3", "ec-3", "alac", "fLaC", "Opus"].indexOf(parsedCodec) !== -1)) {
  10146. if (isCodecSupportedAsType(parsedCodec, "audio") || isCodecSupportedAsType(parsedCodec, "video")) {
  10147. return parsedCodec;
  10148. }
  10149. }
  10150. if (levelCodec) {
  10151. const levelCodecs = levelCodec.split(",");
  10152. if (levelCodecs.length > 1) {
  10153. if (parsedCodec) {
  10154. for (let i2 = levelCodecs.length; i2--; ) {
  10155. if (levelCodecs[i2].substring(0, 4) === parsedCodec.substring(0, 4)) {
  10156. return levelCodecs[i2];
  10157. }
  10158. }
  10159. }
  10160. return levelCodecs[0];
  10161. }
  10162. }
  10163. return levelCodec || parsedCodec;
  10164. }
  10165. function isCodecSupportedAsType(codec, type) {
  10166. return isCodecType(codec, type) && isCodecMediaSourceSupported(codec, type);
  10167. }
  10168. function convertAVC1ToAVCOTI(videoCodecs) {
  10169. const codecs = videoCodecs.split(",");
  10170. for (let i2 = 0; i2 < codecs.length; i2++) {
  10171. const avcdata = codecs[i2].split(".");
  10172. if (avcdata.length > 2 && avcdata[0] === "avc1") {
  10173. codecs[i2] = `avc1.${parseInt(avcdata[1]).toString(16)}${("000" + parseInt(avcdata[2]).toString(16)).slice(-4)}`;
  10174. }
  10175. }
  10176. return codecs.join(",");
  10177. }
  10178. function fillInMissingAV01Params(videoCodec) {
  10179. if (videoCodec.startsWith("av01.")) {
  10180. const av1params = videoCodec.split(".");
  10181. const placeholders = ["0", "111", "01", "01", "01", "0"];
  10182. for (let i2 = av1params.length; i2 > 4 && i2 < 10; i2++) {
  10183. av1params[i2] = placeholders[i2 - 4];
  10184. }
  10185. return av1params.join(".");
  10186. }
  10187. return videoCodec;
  10188. }
  10189. function getM2TSSupportedAudioTypes(preferManagedMediaSource) {
  10190. const MediaSource = getMediaSource(preferManagedMediaSource) || {
  10191. isTypeSupported: () => false
  10192. };
  10193. return {
  10194. mpeg: MediaSource.isTypeSupported("audio/mpeg"),
  10195. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  10196. ac3: MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"')
  10197. };
  10198. }
  10199. function getCodecsForMimeType(mimeType) {
  10200. return mimeType.replace(/^.+codecs=["']?([^"']+).*$/, "$1");
  10201. }
  10202. const SUPPORTED_INFO_DEFAULT = {
  10203. supported: true,
  10204. configurations: [],
  10205. decodingInfoResults: [{
  10206. supported: true,
  10207. powerEfficient: true,
  10208. smooth: true
  10209. }]
  10210. };
  10211. function getUnsupportedResult(error, configurations) {
  10212. return {
  10213. supported: false,
  10214. configurations,
  10215. decodingInfoResults: [{
  10216. supported: false,
  10217. smooth: false,
  10218. powerEfficient: false
  10219. }],
  10220. error
  10221. };
  10222. }
  10223. function requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) {
  10224. const videoCodecs = level.videoCodec;
  10225. const audioGroups = level.audioCodec ? level.audioGroups : null;
  10226. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  10227. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  10228. const maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2;
  10229. let audioChannels = null;
  10230. if (audioGroups != null && audioGroups.length) {
  10231. try {
  10232. if (audioGroups.length === 1 && audioGroups[0]) {
  10233. audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;
  10234. } else {
  10235. audioChannels = audioGroups.reduce((acc, groupId) => {
  10236. if (groupId) {
  10237. const audioTrackGroup = audioTracksByGroup.groups[groupId];
  10238. if (!audioTrackGroup) {
  10239. throw new Error(`Audio track group ${groupId} not found`);
  10240. }
  10241. Object.keys(audioTrackGroup.channels).forEach((key) => {
  10242. acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];
  10243. });
  10244. }
  10245. return acc;
  10246. }, {
  10247. 2: 0
  10248. });
  10249. }
  10250. } catch (error) {
  10251. return true;
  10252. }
  10253. }
  10254. return videoCodecs !== void 0 && // Force media capabilities check for HEVC to avoid failure on Windows
  10255. (videoCodecs.split(",").some((videoCodec) => isHEVC(videoCodec)) || level.width > 1920 && level.height > 1088 || level.height > 1920 && level.width > 1088 || level.frameRate > Math.max(currentFrameRate, 30) || level.videoRange !== "SDR" && level.videoRange !== currentVideoRange || level.bitrate > Math.max(currentBw, 8e6)) || !!audioChannels && isFiniteNumber(maxChannels) && Object.keys(audioChannels).some((channels) => parseInt(channels) > maxChannels);
  10256. }
  10257. function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities, cache = {}) {
  10258. const videoCodecs = level.videoCodec;
  10259. if (!videoCodecs && !level.audioCodec || !mediaCapabilities) {
  10260. return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  10261. }
  10262. const configurations = [];
  10263. const videoDecodeList = makeVideoConfigurations(level);
  10264. const videoCount = videoDecodeList.length;
  10265. const audioDecodeList = makeAudioConfigurations(level, audioTracksByGroup, videoCount > 0);
  10266. const audioCount = audioDecodeList.length;
  10267. for (let i2 = videoCount || 1 * audioCount || 1; i2--; ) {
  10268. const configuration = {
  10269. type: "media-source"
  10270. };
  10271. if (videoCount) {
  10272. configuration.video = videoDecodeList[i2 % videoCount];
  10273. }
  10274. if (audioCount) {
  10275. configuration.audio = audioDecodeList[i2 % audioCount];
  10276. const audioBitrate = configuration.audio.bitrate;
  10277. if (configuration.video && audioBitrate) {
  10278. configuration.video.bitrate -= audioBitrate;
  10279. }
  10280. }
  10281. configurations.push(configuration);
  10282. }
  10283. if (videoCodecs) {
  10284. const ua = navigator.userAgent;
  10285. if (videoCodecs.split(",").some((videoCodec) => isHEVC(videoCodec)) && userAgentHevcSupportIsInaccurate()) {
  10286. return Promise.resolve(getUnsupportedResult(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${ua})`), configurations));
  10287. }
  10288. }
  10289. return Promise.all(configurations.map((configuration) => {
  10290. const decodingInfoKey = getMediaDecodingInfoKey(configuration);
  10291. return cache[decodingInfoKey] || (cache[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  10292. })).then((decodingInfoResults) => ({
  10293. supported: !decodingInfoResults.some((info) => !info.supported),
  10294. configurations,
  10295. decodingInfoResults
  10296. })).catch((error) => ({
  10297. supported: false,
  10298. configurations,
  10299. decodingInfoResults: [],
  10300. error
  10301. }));
  10302. }
  10303. function makeVideoConfigurations(level) {
  10304. var _level$videoCodec;
  10305. const videoCodecs = (_level$videoCodec = level.videoCodec) == null ? void 0 : _level$videoCodec.split(",");
  10306. const bitrate = getVariantDecodingBitrate(level);
  10307. const width = level.width || 640;
  10308. const height = level.height || 480;
  10309. const framerate = level.frameRate || 30;
  10310. const videoRange = level.videoRange.toLowerCase();
  10311. return videoCodecs ? videoCodecs.map((videoCodec) => {
  10312. const videoConfiguration = {
  10313. contentType: mimeTypeForCodec(fillInMissingAV01Params(videoCodec), "video"),
  10314. width,
  10315. height,
  10316. bitrate,
  10317. framerate
  10318. };
  10319. if (videoRange !== "sdr") {
  10320. videoConfiguration.transferFunction = videoRange;
  10321. }
  10322. return videoConfiguration;
  10323. }) : [];
  10324. }
  10325. function makeAudioConfigurations(level, audioTracksByGroup, hasVideo) {
  10326. var _level$audioCodec;
  10327. const audioCodecs = (_level$audioCodec = level.audioCodec) == null ? void 0 : _level$audioCodec.split(",");
  10328. const combinedBitrate = getVariantDecodingBitrate(level);
  10329. if (audioCodecs && level.audioGroups) {
  10330. return level.audioGroups.reduce((configurations, audioGroupId) => {
  10331. var _audioTracksByGroup$g;
  10332. const tracks = audioGroupId ? (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks : null;
  10333. if (tracks) {
  10334. return tracks.reduce((configs, audioTrack) => {
  10335. if (audioTrack.groupId === audioGroupId) {
  10336. const channelsNumber = parseFloat(audioTrack.channels || "");
  10337. audioCodecs.forEach((audioCodec) => {
  10338. const audioConfiguration = {
  10339. contentType: mimeTypeForCodec(audioCodec, "audio"),
  10340. bitrate: hasVideo ? estimatedAudioBitrate(audioCodec, combinedBitrate) : combinedBitrate
  10341. };
  10342. if (channelsNumber) {
  10343. audioConfiguration.channels = "" + channelsNumber;
  10344. }
  10345. configs.push(audioConfiguration);
  10346. });
  10347. }
  10348. return configs;
  10349. }, configurations);
  10350. }
  10351. return configurations;
  10352. }, []);
  10353. }
  10354. return [];
  10355. }
  10356. function estimatedAudioBitrate(audioCodec, levelBitrate) {
  10357. if (levelBitrate <= 1) {
  10358. return 1;
  10359. }
  10360. let audioBitrate = 128e3;
  10361. if (audioCodec === "ec-3") {
  10362. audioBitrate = 768e3;
  10363. } else if (audioCodec === "ac-3") {
  10364. audioBitrate = 64e4;
  10365. }
  10366. return Math.min(levelBitrate / 2, audioBitrate);
  10367. }
  10368. function getVariantDecodingBitrate(level) {
  10369. return Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate) / 1e3) * 1e3 || 1;
  10370. }
  10371. function getMediaDecodingInfoKey(config) {
  10372. let key = "";
  10373. const {
  10374. audio,
  10375. video
  10376. } = config;
  10377. if (video) {
  10378. const codec = getCodecsForMimeType(video.contentType);
  10379. key += `${codec}_r${video.height}x${video.width}f${Math.ceil(video.framerate)}${video.transferFunction || "sd"}_${Math.ceil(video.bitrate / 1e5)}`;
  10380. }
  10381. if (audio) {
  10382. const codec = getCodecsForMimeType(audio.contentType);
  10383. key += `${video ? "_" : ""}${codec}_c${audio.channels}`;
  10384. }
  10385. return key;
  10386. }
  10387. const HdcpLevels = ["NONE", "TYPE-0", "TYPE-1", null];
  10388. function isHdcpLevel(value) {
  10389. return HdcpLevels.indexOf(value) > -1;
  10390. }
  10391. const VideoRangeValues = ["SDR", "PQ", "HLG"];
  10392. function isVideoRange(value) {
  10393. return !!value && VideoRangeValues.indexOf(value) > -1;
  10394. }
  10395. var HlsSkip = {
  10396. No: "",
  10397. Yes: "YES",
  10398. v2: "v2"
  10399. };
  10400. function getSkipValue(details) {
  10401. const {
  10402. canSkipUntil,
  10403. canSkipDateRanges,
  10404. age
  10405. } = details;
  10406. const playlistRecentEnough = age < canSkipUntil / 2;
  10407. if (canSkipUntil && playlistRecentEnough) {
  10408. if (canSkipDateRanges) {
  10409. return HlsSkip.v2;
  10410. }
  10411. return HlsSkip.Yes;
  10412. }
  10413. return HlsSkip.No;
  10414. }
  10415. class HlsUrlParameters {
  10416. constructor(msn, part, skip) {
  10417. this.msn = void 0;
  10418. this.part = void 0;
  10419. this.skip = void 0;
  10420. this.msn = msn;
  10421. this.part = part;
  10422. this.skip = skip;
  10423. }
  10424. addDirectives(uri) {
  10425. const url = new self.URL(uri);
  10426. if (this.msn !== void 0) {
  10427. url.searchParams.set("_HLS_msn", this.msn.toString());
  10428. }
  10429. if (this.part !== void 0) {
  10430. url.searchParams.set("_HLS_part", this.part.toString());
  10431. }
  10432. if (this.skip) {
  10433. url.searchParams.set("_HLS_skip", this.skip);
  10434. }
  10435. return url.href;
  10436. }
  10437. }
  10438. class Level {
  10439. constructor(data) {
  10440. this._attrs = void 0;
  10441. this.audioCodec = void 0;
  10442. this.bitrate = void 0;
  10443. this.codecSet = void 0;
  10444. this.url = void 0;
  10445. this.frameRate = void 0;
  10446. this.height = void 0;
  10447. this.id = void 0;
  10448. this.name = void 0;
  10449. this.supplemental = void 0;
  10450. this.videoCodec = void 0;
  10451. this.width = void 0;
  10452. this.details = void 0;
  10453. this.fragmentError = 0;
  10454. this.loadError = 0;
  10455. this.loaded = void 0;
  10456. this.realBitrate = 0;
  10457. this.supportedPromise = void 0;
  10458. this.supportedResult = void 0;
  10459. this._avgBitrate = 0;
  10460. this._audioGroups = void 0;
  10461. this._subtitleGroups = void 0;
  10462. this._urlId = 0;
  10463. this.url = [data.url];
  10464. this._attrs = [data.attrs];
  10465. this.bitrate = data.bitrate;
  10466. if (data.details) {
  10467. this.details = data.details;
  10468. }
  10469. this.id = data.id || 0;
  10470. this.name = data.name;
  10471. this.width = data.width || 0;
  10472. this.height = data.height || 0;
  10473. this.frameRate = data.attrs.optionalFloat("FRAME-RATE", 0);
  10474. this._avgBitrate = data.attrs.decimalInteger("AVERAGE-BANDWIDTH");
  10475. this.audioCodec = data.audioCodec;
  10476. this.videoCodec = data.videoCodec;
  10477. this.codecSet = [data.videoCodec, data.audioCodec].filter((c2) => !!c2).map((s2) => s2.substring(0, 4)).join(",");
  10478. if ("supplemental" in data) {
  10479. var _data$supplemental;
  10480. this.supplemental = data.supplemental;
  10481. const supplementalVideo = (_data$supplemental = data.supplemental) == null ? void 0 : _data$supplemental.videoCodec;
  10482. if (supplementalVideo && supplementalVideo !== data.videoCodec) {
  10483. this.codecSet += `,${supplementalVideo.substring(0, 4)}`;
  10484. }
  10485. }
  10486. this.addGroupId("audio", data.attrs.AUDIO);
  10487. this.addGroupId("text", data.attrs.SUBTITLES);
  10488. }
  10489. get maxBitrate() {
  10490. return Math.max(this.realBitrate, this.bitrate);
  10491. }
  10492. get averageBitrate() {
  10493. return this._avgBitrate || this.realBitrate || this.bitrate;
  10494. }
  10495. get attrs() {
  10496. return this._attrs[0];
  10497. }
  10498. get codecs() {
  10499. return this.attrs.CODECS || "";
  10500. }
  10501. get pathwayId() {
  10502. return this.attrs["PATHWAY-ID"] || ".";
  10503. }
  10504. get videoRange() {
  10505. return this.attrs["VIDEO-RANGE"] || "SDR";
  10506. }
  10507. get score() {
  10508. return this.attrs.optionalFloat("SCORE", 0);
  10509. }
  10510. get uri() {
  10511. return this.url[0] || "";
  10512. }
  10513. hasAudioGroup(groupId) {
  10514. return hasGroup(this._audioGroups, groupId);
  10515. }
  10516. hasSubtitleGroup(groupId) {
  10517. return hasGroup(this._subtitleGroups, groupId);
  10518. }
  10519. get audioGroups() {
  10520. return this._audioGroups;
  10521. }
  10522. get subtitleGroups() {
  10523. return this._subtitleGroups;
  10524. }
  10525. addGroupId(type, groupId) {
  10526. if (!groupId) {
  10527. return;
  10528. }
  10529. if (type === "audio") {
  10530. let audioGroups = this._audioGroups;
  10531. if (!audioGroups) {
  10532. audioGroups = this._audioGroups = [];
  10533. }
  10534. if (audioGroups.indexOf(groupId) === -1) {
  10535. audioGroups.push(groupId);
  10536. }
  10537. } else if (type === "text") {
  10538. let subtitleGroups = this._subtitleGroups;
  10539. if (!subtitleGroups) {
  10540. subtitleGroups = this._subtitleGroups = [];
  10541. }
  10542. if (subtitleGroups.indexOf(groupId) === -1) {
  10543. subtitleGroups.push(groupId);
  10544. }
  10545. }
  10546. }
  10547. // Deprecated methods (retained for backwards compatibility)
  10548. get urlId() {
  10549. return 0;
  10550. }
  10551. set urlId(value) {
  10552. }
  10553. get audioGroupIds() {
  10554. return this.audioGroups ? [this.audioGroupId] : void 0;
  10555. }
  10556. get textGroupIds() {
  10557. return this.subtitleGroups ? [this.textGroupId] : void 0;
  10558. }
  10559. get audioGroupId() {
  10560. var _this$audioGroups;
  10561. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  10562. }
  10563. get textGroupId() {
  10564. var _this$subtitleGroups;
  10565. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  10566. }
  10567. addFallback() {
  10568. }
  10569. }
  10570. function hasGroup(groups, groupId) {
  10571. if (!groupId || !groups) {
  10572. return false;
  10573. }
  10574. return groups.indexOf(groupId) !== -1;
  10575. }
  10576. function isHdrSupported() {
  10577. if (typeof matchMedia === "function") {
  10578. const mediaQueryList = matchMedia("(dynamic-range: high)");
  10579. const badQuery = matchMedia("bad query");
  10580. if (mediaQueryList.media !== badQuery.media) {
  10581. return mediaQueryList.matches === true;
  10582. }
  10583. }
  10584. return false;
  10585. }
  10586. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  10587. let preferHDR = false;
  10588. let allowedVideoRanges = [];
  10589. if (currentVideoRange) {
  10590. preferHDR = currentVideoRange !== "SDR";
  10591. allowedVideoRanges = [currentVideoRange];
  10592. }
  10593. if (videoPreference) {
  10594. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  10595. const allowAutoPreferHDR = allowedVideoRanges.join("") !== "SDR" && !videoPreference.videoCodec;
  10596. preferHDR = videoPreference.preferHDR !== void 0 ? videoPreference.preferHDR : allowAutoPreferHDR && isHdrSupported();
  10597. if (!preferHDR) {
  10598. allowedVideoRanges = ["SDR"];
  10599. }
  10600. }
  10601. return {
  10602. preferHDR,
  10603. allowedVideoRanges
  10604. };
  10605. }
  10606. const omitCircularRefsReplacer = (replacer2) => {
  10607. const known = /* @__PURE__ */ new WeakSet();
  10608. return (_2, value) => {
  10609. if (replacer2) {
  10610. value = replacer2(_2, value);
  10611. }
  10612. if (typeof value === "object" && value !== null) {
  10613. if (known.has(value)) {
  10614. return;
  10615. }
  10616. known.add(value);
  10617. }
  10618. return value;
  10619. };
  10620. };
  10621. const stringify = (object, replacer2) => JSON.stringify(object, omitCircularRefsReplacer(replacer2));
  10622. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  10623. const codecSets = Object.keys(codecTiers);
  10624. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  10625. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  10626. const videoCodecPreference = videoPreference == null ? void 0 : videoPreference.videoCodec;
  10627. const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  10628. let hasStereo = false;
  10629. let hasCurrentVideoRange = false;
  10630. let minHeight = Infinity;
  10631. let minFramerate = Infinity;
  10632. let minBitrate = Infinity;
  10633. let minIndex = Infinity;
  10634. let selectedScore = 0;
  10635. let videoRanges = [];
  10636. const {
  10637. preferHDR,
  10638. allowedVideoRanges
  10639. } = getVideoSelectionOptions(currentVideoRange, videoPreference);
  10640. for (let i2 = codecSets.length; i2--; ) {
  10641. const tier = codecTiers[codecSets[i2]];
  10642. hasStereo || (hasStereo = tier.channels[2] > 0);
  10643. minHeight = Math.min(minHeight, tier.minHeight);
  10644. minFramerate = Math.min(minFramerate, tier.minFramerate);
  10645. minBitrate = Math.min(minBitrate, tier.minBitrate);
  10646. const matchingVideoRanges = allowedVideoRanges.filter((range) => tier.videoRanges[range] > 0);
  10647. if (matchingVideoRanges.length > 0) {
  10648. hasCurrentVideoRange = true;
  10649. }
  10650. }
  10651. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  10652. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  10653. const maxHeight = Math.max(1080, minHeight);
  10654. const maxFramerate = Math.max(30, minFramerate);
  10655. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  10656. currentBw = Math.max(minBitrate, currentBw);
  10657. if (!hasCurrentVideoRange) {
  10658. currentVideoRange = void 0;
  10659. }
  10660. const hasMultipleSets = codecSets.length > 1;
  10661. const codecSet = codecSets.reduce((selected, candidate) => {
  10662. const candidateTier = codecTiers[candidate];
  10663. if (candidate === selected) {
  10664. return selected;
  10665. }
  10666. videoRanges = hasCurrentVideoRange ? allowedVideoRanges.filter((range) => candidateTier.videoRanges[range] > 0) : [];
  10667. if (hasMultipleSets) {
  10668. if (candidateTier.minBitrate > currentBw) {
  10669. logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);
  10670. return selected;
  10671. }
  10672. if (!candidateTier.hasDefaultAudio) {
  10673. logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);
  10674. return selected;
  10675. }
  10676. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  10677. logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`);
  10678. return selected;
  10679. }
  10680. if (channelsPreference && !preferStereo) {
  10681. if (!candidateTier.channels[channelsPreference]) {
  10682. logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);
  10683. return selected;
  10684. }
  10685. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels["2"] === 0) {
  10686. logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);
  10687. return selected;
  10688. }
  10689. if (candidateTier.minHeight > maxHeight) {
  10690. logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);
  10691. return selected;
  10692. }
  10693. if (candidateTier.minFramerate > maxFramerate) {
  10694. logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);
  10695. return selected;
  10696. }
  10697. if (!videoRanges.some((range) => candidateTier.videoRanges[range] > 0)) {
  10698. logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${stringify(videoRanges)} found`);
  10699. return selected;
  10700. }
  10701. if (videoCodecPreference && candidate.indexOf(videoCodecPreference.substring(0, 4)) % 5 !== 0) {
  10702. logStartCodecCandidateIgnored(candidate, `video codec preference "${videoCodecPreference}" not found`);
  10703. return selected;
  10704. }
  10705. if (candidateTier.maxScore < selectedScore) {
  10706. logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);
  10707. return selected;
  10708. }
  10709. }
  10710. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  10711. return selected;
  10712. }
  10713. minIndex = candidateTier.minIndex;
  10714. selectedScore = candidateTier.maxScore;
  10715. return candidate;
  10716. }, void 0);
  10717. return {
  10718. codecSet,
  10719. videoRanges,
  10720. preferHDR,
  10721. minFramerate,
  10722. minBitrate,
  10723. minIndex
  10724. };
  10725. }
  10726. function logStartCodecCandidateIgnored(codeSet, reason) {
  10727. logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`);
  10728. }
  10729. function getAudioTracksByGroup(allAudioTracks) {
  10730. return allAudioTracks.reduce((audioTracksByGroup, track2) => {
  10731. let trackGroup = audioTracksByGroup.groups[track2.groupId];
  10732. if (!trackGroup) {
  10733. trackGroup = audioTracksByGroup.groups[track2.groupId] = {
  10734. tracks: [],
  10735. channels: {
  10736. 2: 0
  10737. },
  10738. hasDefault: false,
  10739. hasAutoSelect: false
  10740. };
  10741. }
  10742. trackGroup.tracks.push(track2);
  10743. const channelsKey = track2.channels || "2";
  10744. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  10745. trackGroup.hasDefault = trackGroup.hasDefault || track2.default;
  10746. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track2.autoselect;
  10747. if (trackGroup.hasDefault) {
  10748. audioTracksByGroup.hasDefaultAudio = true;
  10749. }
  10750. if (trackGroup.hasAutoSelect) {
  10751. audioTracksByGroup.hasAutoSelectAudio = true;
  10752. }
  10753. return audioTracksByGroup;
  10754. }, {
  10755. hasDefaultAudio: false,
  10756. hasAutoSelectAudio: false,
  10757. groups: {}
  10758. });
  10759. }
  10760. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  10761. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level, index2) => {
  10762. if (!level.codecSet) {
  10763. return tiers;
  10764. }
  10765. const audioGroups = level.audioGroups;
  10766. let tier = tiers[level.codecSet];
  10767. if (!tier) {
  10768. tiers[level.codecSet] = tier = {
  10769. minBitrate: Infinity,
  10770. minHeight: Infinity,
  10771. minFramerate: Infinity,
  10772. minIndex: index2,
  10773. maxScore: 0,
  10774. videoRanges: {
  10775. SDR: 0
  10776. },
  10777. channels: {
  10778. "2": 0
  10779. },
  10780. hasDefaultAudio: !audioGroups,
  10781. fragmentError: 0
  10782. };
  10783. }
  10784. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  10785. const lesserWidthOrHeight = Math.min(level.height, level.width);
  10786. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  10787. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  10788. tier.minIndex = Math.min(tier.minIndex, index2);
  10789. tier.maxScore = Math.max(tier.maxScore, level.score);
  10790. tier.fragmentError += level.fragmentError;
  10791. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  10792. if (audioGroups) {
  10793. audioGroups.forEach((audioGroupId) => {
  10794. if (!audioGroupId) {
  10795. return;
  10796. }
  10797. const audioGroup = audioTracksByGroup.groups[audioGroupId];
  10798. if (!audioGroup) {
  10799. return;
  10800. }
  10801. tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio;
  10802. Object.keys(audioGroup.channels).forEach((channels) => {
  10803. tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels];
  10804. });
  10805. });
  10806. }
  10807. return tiers;
  10808. }, {});
  10809. }
  10810. function getBasicSelectionOption(option) {
  10811. if (!option) {
  10812. return option;
  10813. }
  10814. const {
  10815. lang,
  10816. assocLang,
  10817. characteristics,
  10818. channels,
  10819. audioCodec
  10820. } = option;
  10821. return {
  10822. lang,
  10823. assocLang,
  10824. characteristics,
  10825. channels,
  10826. audioCodec
  10827. };
  10828. }
  10829. function findMatchingOption(option, tracks, matchPredicate) {
  10830. if ("attrs" in option) {
  10831. const index2 = tracks.indexOf(option);
  10832. if (index2 !== -1) {
  10833. return index2;
  10834. }
  10835. }
  10836. for (let i2 = 0; i2 < tracks.length; i2++) {
  10837. const track2 = tracks[i2];
  10838. if (matchesOption(option, track2, matchPredicate)) {
  10839. return i2;
  10840. }
  10841. }
  10842. return -1;
  10843. }
  10844. function matchesOption(option, track2, matchPredicate) {
  10845. const {
  10846. groupId,
  10847. name,
  10848. lang,
  10849. assocLang,
  10850. default: isDefault
  10851. } = option;
  10852. const forced = option.forced;
  10853. return (groupId === void 0 || track2.groupId === groupId) && (name === void 0 || track2.name === name) && (lang === void 0 || languagesMatch(lang, track2.lang)) && (lang === void 0 || track2.assocLang === assocLang) && (isDefault === void 0 || track2.default === isDefault) && (forced === void 0 || track2.forced === forced) && (!("characteristics" in option) || characteristicsMatch(option.characteristics || "", track2.characteristics)) && (matchPredicate === void 0 || matchPredicate(option, track2));
  10854. }
  10855. function languagesMatch(languageA, languageB = "--") {
  10856. if (languageA.length === languageB.length) {
  10857. return languageA === languageB;
  10858. }
  10859. return languageA.startsWith(languageB) || languageB.startsWith(languageA);
  10860. }
  10861. function characteristicsMatch(characteristicsA, characteristicsB = "") {
  10862. const arrA = characteristicsA.split(",");
  10863. const arrB = characteristicsB.split(",");
  10864. return arrA.length === arrB.length && !arrA.some((el) => arrB.indexOf(el) === -1);
  10865. }
  10866. function audioMatchPredicate(option, track2) {
  10867. const {
  10868. audioCodec,
  10869. channels
  10870. } = option;
  10871. return (audioCodec === void 0 || (track2.audioCodec || "").substring(0, 4) === audioCodec.substring(0, 4)) && (channels === void 0 || channels === (track2.channels || "2"));
  10872. }
  10873. function findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) {
  10874. const currentLevel = levels[searchIndex];
  10875. const variants = levels.reduce((variantMap, level, index2) => {
  10876. const uri = level.uri;
  10877. const renditions2 = variantMap[uri] || (variantMap[uri] = []);
  10878. renditions2.push(index2);
  10879. return variantMap;
  10880. }, {});
  10881. const renditions = variants[currentLevel.uri];
  10882. if (renditions.length > 1) {
  10883. searchIndex = Math.max.apply(Math, renditions);
  10884. }
  10885. const currentVideoRange = currentLevel.videoRange;
  10886. const currentFrameRate = currentLevel.frameRate;
  10887. const currentVideoCodec = currentLevel.codecSet.substring(0, 4);
  10888. const matchingVideo = searchDownAndUpList(levels, searchIndex, (level) => {
  10889. if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) {
  10890. return false;
  10891. }
  10892. const audioGroups = level.audioGroups;
  10893. const tracks = allAudioTracks.filter((track2) => !audioGroups || audioGroups.indexOf(track2.groupId) !== -1);
  10894. return findMatchingOption(option, tracks, matchPredicate) > -1;
  10895. });
  10896. if (matchingVideo > -1) {
  10897. return matchingVideo;
  10898. }
  10899. return searchDownAndUpList(levels, searchIndex, (level) => {
  10900. const audioGroups = level.audioGroups;
  10901. const tracks = allAudioTracks.filter((track2) => !audioGroups || audioGroups.indexOf(track2.groupId) !== -1);
  10902. return findMatchingOption(option, tracks, matchPredicate) > -1;
  10903. });
  10904. }
  10905. function searchDownAndUpList(arr, searchIndex, predicate) {
  10906. for (let i2 = searchIndex; i2 > -1; i2--) {
  10907. if (predicate(arr[i2])) {
  10908. return i2;
  10909. }
  10910. }
  10911. for (let i2 = searchIndex + 1; i2 < arr.length; i2++) {
  10912. if (predicate(arr[i2])) {
  10913. return i2;
  10914. }
  10915. }
  10916. return -1;
  10917. }
  10918. function useAlternateAudio(audioTrackUrl, hls) {
  10919. var _hls$loadLevelObj;
  10920. return !!audioTrackUrl && audioTrackUrl !== ((_hls$loadLevelObj = hls.loadLevelObj) == null ? void 0 : _hls$loadLevelObj.uri);
  10921. }
  10922. class AbrController extends Logger {
  10923. constructor(_hls) {
  10924. super("abr", _hls.logger);
  10925. this.hls = void 0;
  10926. this.lastLevelLoadSec = 0;
  10927. this.lastLoadedFragLevel = -1;
  10928. this.firstSelection = -1;
  10929. this._nextAutoLevel = -1;
  10930. this.nextAutoLevelKey = "";
  10931. this.audioTracksByGroup = null;
  10932. this.codecTiers = null;
  10933. this.timer = -1;
  10934. this.fragCurrent = null;
  10935. this.partCurrent = null;
  10936. this.bitrateTestDelay = 0;
  10937. this.rebufferNotice = -1;
  10938. this.supportedCache = {};
  10939. this.bwEstimator = void 0;
  10940. this._abandonRulesCheck = (levelLoaded) => {
  10941. var _ref;
  10942. const {
  10943. fragCurrent: frag,
  10944. partCurrent: part,
  10945. hls
  10946. } = this;
  10947. const {
  10948. autoLevelEnabled,
  10949. media
  10950. } = hls;
  10951. if (!frag || !media) {
  10952. return;
  10953. }
  10954. const now2 = performance.now();
  10955. const stats = part ? part.stats : frag.stats;
  10956. const duration = part ? part.duration : frag.duration;
  10957. const timeLoading = now2 - stats.loading.start;
  10958. const minAutoLevel = hls.minAutoLevel;
  10959. const loadingFragForLevel = frag.level;
  10960. const currentAutoLevel = this._nextAutoLevel;
  10961. if (stats.aborted || stats.loaded && stats.loaded === stats.total || loadingFragForLevel <= minAutoLevel) {
  10962. this.clearTimer();
  10963. this._nextAutoLevel = -1;
  10964. return;
  10965. }
  10966. if (!autoLevelEnabled) {
  10967. return;
  10968. }
  10969. const fragBlockingSwitch = currentAutoLevel > -1 && currentAutoLevel !== loadingFragForLevel;
  10970. const levelChange = !!levelLoaded || fragBlockingSwitch;
  10971. if (!levelChange && (media.paused || !media.playbackRate || !media.readyState)) {
  10972. return;
  10973. }
  10974. const bufferInfo = hls.mainForwardBufferInfo;
  10975. if (!levelChange && bufferInfo === null) {
  10976. return;
  10977. }
  10978. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  10979. const playbackRate = Math.abs(media.playbackRate);
  10980. if (timeLoading <= Math.max(ttfbEstimate, 1e3 * (duration / (playbackRate * 2)))) {
  10981. return;
  10982. }
  10983. const bufferStarvationDelay = bufferInfo ? bufferInfo.len / playbackRate : 0;
  10984. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  10985. const loadedFirstByte = stats.loaded && ttfb > -1;
  10986. const bwEstimate = this.getBwEstimate();
  10987. const levels = hls.levels;
  10988. const level = levels[loadingFragForLevel];
  10989. const expectedLen = Math.max(stats.loaded, Math.round(duration * (frag.bitrate || level.averageBitrate) / 8));
  10990. let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  10991. if (timeStreaming < 1 && loadedFirstByte) {
  10992. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  10993. }
  10994. const loadRate = loadedFirstByte ? stats.loaded * 1e3 / timeStreaming : 0;
  10995. const ttfbSeconds = ttfbEstimate / 1e3;
  10996. const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbSeconds;
  10997. if (fragLoadedDelay <= bufferStarvationDelay) {
  10998. return;
  10999. }
  11000. const bwe = loadRate ? loadRate * 8 : bwEstimate;
  11001. const live = ((_ref = (levelLoaded == null ? void 0 : levelLoaded.details) || this.hls.latestLevelDetails) == null ? void 0 : _ref.live) === true;
  11002. const abrBandWidthUpFactor = this.hls.config.abrBandWidthUpFactor;
  11003. let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  11004. let nextLoadLevel;
  11005. for (nextLoadLevel = loadingFragForLevel - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  11006. const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  11007. const requiresLevelLoad = !levels[nextLoadLevel].details || live;
  11008. fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbSeconds, bwe, duration * levelNextBitrate, requiresLevelLoad);
  11009. if (fragLevelNextLoadedDelay < Math.min(bufferStarvationDelay, duration + ttfbSeconds)) {
  11010. break;
  11011. }
  11012. }
  11013. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  11014. return;
  11015. }
  11016. if (fragLevelNextLoadedDelay > duration * 10) {
  11017. return;
  11018. }
  11019. if (loadedFirstByte) {
  11020. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  11021. } else {
  11022. this.bwEstimator.sampleTTFB(timeLoading);
  11023. }
  11024. const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  11025. if (this.getBwEstimate() * abrBandWidthUpFactor > nextLoadLevelBitrate) {
  11026. this.resetEstimator(nextLoadLevelBitrate);
  11027. }
  11028. const bestSwitchLevel = this.findBestLevel(nextLoadLevelBitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
  11029. if (bestSwitchLevel > -1) {
  11030. nextLoadLevel = bestSwitchLevel;
  11031. }
  11032. this.warn(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of level ${loadingFragForLevel} is loading too slowly;
  11033. Fragment duration: ${frag.duration.toFixed(3)}
  11034. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
  11035. Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
  11036. Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s
  11037. TTFB estimate: ${ttfb | 0} ms
  11038. Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : "Unknown"} bps
  11039. New BW estimate: ${this.getBwEstimate() | 0} bps
  11040. Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
  11041. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  11042. this.clearTimer();
  11043. const abortAndSwitch = () => {
  11044. this.clearTimer();
  11045. if (this.fragCurrent === frag && this.hls.loadLevel === nextLoadLevel && nextLoadLevel > 0) {
  11046. const bufferStarvationDelay2 = this.getStarvationDelay();
  11047. this.warn(`Aborting inflight request ${nextLoadLevel > 0 ? "and switching down" : ""}
  11048. Fragment duration: ${frag.duration.toFixed(3)} s
  11049. Time to underbuffer: ${bufferStarvationDelay2.toFixed(3)} s`);
  11050. frag.abortRequests();
  11051. this.fragCurrent = this.partCurrent = null;
  11052. if (nextLoadLevel > minAutoLevel) {
  11053. let lowestSwitchLevel = this.findBestLevel(this.hls.levels[minAutoLevel].bitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay2, 1, 1);
  11054. if (lowestSwitchLevel === -1) {
  11055. lowestSwitchLevel = minAutoLevel;
  11056. }
  11057. this.hls.nextLoadLevel = this.hls.nextAutoLevel = lowestSwitchLevel;
  11058. this.resetEstimator(this.hls.levels[lowestSwitchLevel].bitrate);
  11059. }
  11060. }
  11061. };
  11062. if (fragBlockingSwitch || fragLoadedDelay > fragLevelNextLoadedDelay * 2) {
  11063. abortAndSwitch();
  11064. } else {
  11065. this.timer = self.setInterval(abortAndSwitch, fragLevelNextLoadedDelay * 1e3);
  11066. }
  11067. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  11068. frag,
  11069. part,
  11070. stats
  11071. });
  11072. };
  11073. this.hls = _hls;
  11074. this.bwEstimator = this.initEstimator();
  11075. this.registerListeners();
  11076. }
  11077. resetEstimator(abrEwmaDefaultEstimate) {
  11078. if (abrEwmaDefaultEstimate) {
  11079. this.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
  11080. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  11081. }
  11082. this.firstSelection = -1;
  11083. this.bwEstimator = this.initEstimator();
  11084. }
  11085. initEstimator() {
  11086. const config = this.hls.config;
  11087. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  11088. }
  11089. registerListeners() {
  11090. const {
  11091. hls
  11092. } = this;
  11093. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  11094. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  11095. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  11096. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  11097. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  11098. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  11099. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  11100. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  11101. hls.on(Events.ERROR, this.onError, this);
  11102. }
  11103. unregisterListeners() {
  11104. const {
  11105. hls
  11106. } = this;
  11107. if (!hls) {
  11108. return;
  11109. }
  11110. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  11111. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  11112. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  11113. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  11114. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  11115. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  11116. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  11117. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  11118. hls.off(Events.ERROR, this.onError, this);
  11119. }
  11120. destroy() {
  11121. this.unregisterListeners();
  11122. this.clearTimer();
  11123. this.hls = this._abandonRulesCheck = this.supportedCache = null;
  11124. this.fragCurrent = this.partCurrent = null;
  11125. }
  11126. onManifestLoading(event, data) {
  11127. this.lastLoadedFragLevel = -1;
  11128. this.firstSelection = -1;
  11129. this.lastLevelLoadSec = 0;
  11130. this.supportedCache = {};
  11131. this.fragCurrent = this.partCurrent = null;
  11132. this.onLevelsUpdated();
  11133. this.clearTimer();
  11134. }
  11135. onLevelsUpdated() {
  11136. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  11137. this.lastLoadedFragLevel = this.fragCurrent.level;
  11138. }
  11139. this._nextAutoLevel = -1;
  11140. this.onMaxAutoLevelUpdated();
  11141. this.codecTiers = null;
  11142. this.audioTracksByGroup = null;
  11143. }
  11144. onMaxAutoLevelUpdated() {
  11145. this.firstSelection = -1;
  11146. this.nextAutoLevelKey = "";
  11147. }
  11148. onFragLoading(event, data) {
  11149. const frag = data.frag;
  11150. if (this.ignoreFragment(frag)) {
  11151. return;
  11152. }
  11153. if (!frag.bitrateTest) {
  11154. var _data$part;
  11155. this.fragCurrent = frag;
  11156. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  11157. }
  11158. this.clearTimer();
  11159. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  11160. }
  11161. onLevelSwitching(event, data) {
  11162. this.clearTimer();
  11163. }
  11164. onError(event, data) {
  11165. if (data.fatal) {
  11166. return;
  11167. }
  11168. switch (data.details) {
  11169. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  11170. case ErrorDetails.BUFFER_APPEND_ERROR:
  11171. this.lastLoadedFragLevel = -1;
  11172. this.firstSelection = -1;
  11173. break;
  11174. case ErrorDetails.FRAG_LOAD_TIMEOUT: {
  11175. const frag = data.frag;
  11176. const {
  11177. fragCurrent,
  11178. partCurrent: part
  11179. } = this;
  11180. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  11181. const now2 = performance.now();
  11182. const stats = part ? part.stats : frag.stats;
  11183. const timeLoading = now2 - stats.loading.start;
  11184. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  11185. const loadedFirstByte = stats.loaded && ttfb > -1;
  11186. if (loadedFirstByte) {
  11187. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  11188. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  11189. } else {
  11190. this.bwEstimator.sampleTTFB(timeLoading);
  11191. }
  11192. }
  11193. break;
  11194. }
  11195. }
  11196. }
  11197. getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  11198. const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  11199. const playlistLoadSec = isSwitch ? timeToFirstByteSec + this.lastLevelLoadSec : 0;
  11200. return fragLoadSec + playlistLoadSec;
  11201. }
  11202. onLevelLoaded(event, data) {
  11203. const config = this.hls.config;
  11204. const {
  11205. loading
  11206. } = data.stats;
  11207. const timeLoadingMs = loading.end - loading.first;
  11208. if (isFiniteNumber(timeLoadingMs)) {
  11209. this.lastLevelLoadSec = timeLoadingMs / 1e3;
  11210. }
  11211. if (data.details.live) {
  11212. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  11213. } else {
  11214. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  11215. }
  11216. if (this.timer > -1) {
  11217. this._abandonRulesCheck(data.levelInfo);
  11218. }
  11219. }
  11220. onFragLoaded(event, {
  11221. frag,
  11222. part
  11223. }) {
  11224. const stats = part ? part.stats : frag.stats;
  11225. if (frag.type === PlaylistLevelType.MAIN) {
  11226. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  11227. }
  11228. if (this.ignoreFragment(frag)) {
  11229. return;
  11230. }
  11231. this.clearTimer();
  11232. if (frag.level === this._nextAutoLevel) {
  11233. this._nextAutoLevel = -1;
  11234. }
  11235. this.firstSelection = -1;
  11236. if (this.hls.config.abrMaxWithRealBitrate) {
  11237. const duration = part ? part.duration : frag.duration;
  11238. const level = this.hls.levels[frag.level];
  11239. const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  11240. const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  11241. level.loaded = {
  11242. bytes: loadedBytes,
  11243. duration: loadedDuration
  11244. };
  11245. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  11246. }
  11247. if (frag.bitrateTest) {
  11248. const fragBufferedData = {
  11249. stats,
  11250. frag,
  11251. part,
  11252. id: frag.type
  11253. };
  11254. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  11255. frag.bitrateTest = false;
  11256. } else {
  11257. this.lastLoadedFragLevel = frag.level;
  11258. }
  11259. }
  11260. onFragBuffered(event, data) {
  11261. const {
  11262. frag,
  11263. part
  11264. } = data;
  11265. const stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  11266. if (stats.aborted) {
  11267. return;
  11268. }
  11269. if (this.ignoreFragment(frag)) {
  11270. return;
  11271. }
  11272. const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  11273. this.bwEstimator.sample(processingMs, stats.loaded);
  11274. stats.bwEstimate = this.getBwEstimate();
  11275. if (frag.bitrateTest) {
  11276. this.bitrateTestDelay = processingMs / 1e3;
  11277. } else {
  11278. this.bitrateTestDelay = 0;
  11279. }
  11280. }
  11281. ignoreFragment(frag) {
  11282. return frag.type !== PlaylistLevelType.MAIN || frag.sn === "initSegment";
  11283. }
  11284. clearTimer() {
  11285. if (this.timer > -1) {
  11286. self.clearInterval(this.timer);
  11287. this.timer = -1;
  11288. }
  11289. }
  11290. get firstAutoLevel() {
  11291. const {
  11292. maxAutoLevel,
  11293. minAutoLevel
  11294. } = this.hls;
  11295. const bwEstimate = this.getBwEstimate();
  11296. const maxStartDelay = this.hls.config.maxStarvationDelay;
  11297. const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  11298. if (abrAutoLevel > -1) {
  11299. return abrAutoLevel;
  11300. }
  11301. const firstLevel = this.hls.firstLevel;
  11302. const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  11303. this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);
  11304. return clamped;
  11305. }
  11306. get forcedAutoLevel() {
  11307. if (this.nextAutoLevelKey) {
  11308. return -1;
  11309. }
  11310. return this._nextAutoLevel;
  11311. }
  11312. // return next auto level
  11313. get nextAutoLevel() {
  11314. const forcedAutoLevel = this.forcedAutoLevel;
  11315. const bwEstimator = this.bwEstimator;
  11316. const useEstimate = bwEstimator.canEstimate();
  11317. const loadedFirstFrag = this.lastLoadedFragLevel > -1;
  11318. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  11319. return forcedAutoLevel;
  11320. }
  11321. const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  11322. if (forcedAutoLevel !== -1) {
  11323. const levels = this.hls.levels;
  11324. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  11325. return forcedAutoLevel;
  11326. }
  11327. }
  11328. this._nextAutoLevel = nextABRAutoLevel;
  11329. this.nextAutoLevelKey = this.getAutoLevelKey();
  11330. return nextABRAutoLevel;
  11331. }
  11332. getAutoLevelKey() {
  11333. return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  11334. }
  11335. getNextABRAutoLevel() {
  11336. const {
  11337. fragCurrent,
  11338. partCurrent,
  11339. hls
  11340. } = this;
  11341. if (hls.levels.length <= 1) {
  11342. return hls.loadLevel;
  11343. }
  11344. const {
  11345. maxAutoLevel,
  11346. config,
  11347. minAutoLevel
  11348. } = hls;
  11349. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  11350. const avgbw = this.getBwEstimate();
  11351. const bufferStarvationDelay = this.getStarvationDelay();
  11352. let bwFactor = config.abrBandWidthFactor;
  11353. let bwUpFactor = config.abrBandWidthUpFactor;
  11354. if (bufferStarvationDelay) {
  11355. const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  11356. if (_bestLevel >= 0) {
  11357. this.rebufferNotice = -1;
  11358. return _bestLevel;
  11359. }
  11360. }
  11361. let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  11362. if (!bufferStarvationDelay) {
  11363. const bitrateTestDelay = this.bitrateTestDelay;
  11364. if (bitrateTestDelay) {
  11365. const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  11366. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  11367. this.info(`bitrate test took ${Math.round(1e3 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1e3 * maxStarvationDelay)} ms`);
  11368. bwFactor = bwUpFactor = 1;
  11369. }
  11370. }
  11371. const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  11372. if (this.rebufferNotice !== bestLevel) {
  11373. this.rebufferNotice = bestLevel;
  11374. this.info(`${bufferStarvationDelay ? "rebuffering expected" : "buffer is empty"}, optimal quality level ${bestLevel}`);
  11375. }
  11376. if (bestLevel > -1) {
  11377. return bestLevel;
  11378. }
  11379. const minLevel = hls.levels[minAutoLevel];
  11380. const autoLevel = hls.loadLevelObj;
  11381. if (autoLevel && (minLevel == null ? void 0 : minLevel.bitrate) < autoLevel.bitrate) {
  11382. return minAutoLevel;
  11383. }
  11384. return hls.loadLevel;
  11385. }
  11386. getStarvationDelay() {
  11387. const hls = this.hls;
  11388. const media = hls.media;
  11389. if (!media) {
  11390. return Infinity;
  11391. }
  11392. const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1;
  11393. const bufferInfo = hls.mainForwardBufferInfo;
  11394. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  11395. }
  11396. getBwEstimate() {
  11397. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  11398. }
  11399. findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  11400. var _this$hls$latestLevel;
  11401. const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  11402. const lastLoadedFragLevel = this.lastLoadedFragLevel;
  11403. const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  11404. const {
  11405. fragCurrent,
  11406. partCurrent
  11407. } = this;
  11408. const {
  11409. levels,
  11410. allAudioTracks,
  11411. loadLevel,
  11412. config
  11413. } = this.hls;
  11414. if (levels.length === 1) {
  11415. return 0;
  11416. }
  11417. const level = levels[selectionBaseLevel];
  11418. const live = !!((_this$hls$latestLevel = this.hls.latestLevelDetails) != null && _this$hls$latestLevel.live);
  11419. const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  11420. let currentCodecSet;
  11421. let currentVideoRange = "SDR";
  11422. let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  11423. const {
  11424. audioPreference,
  11425. videoPreference
  11426. } = config;
  11427. const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  11428. let minStartIndex = -1;
  11429. if (firstSelection) {
  11430. if (this.firstSelection !== -1) {
  11431. return this.firstSelection;
  11432. }
  11433. const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  11434. const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  11435. const {
  11436. codecSet,
  11437. videoRanges,
  11438. minFramerate,
  11439. minBitrate,
  11440. minIndex,
  11441. preferHDR
  11442. } = startTier;
  11443. minStartIndex = minIndex;
  11444. currentCodecSet = codecSet;
  11445. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  11446. currentFrameRate = minFramerate;
  11447. currentBw = Math.max(currentBw, minBitrate);
  11448. this.log(`picked start tier ${stringify(startTier)}`);
  11449. } else {
  11450. currentCodecSet = level == null ? void 0 : level.codecSet;
  11451. currentVideoRange = level == null ? void 0 : level.videoRange;
  11452. }
  11453. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  11454. const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1e3;
  11455. const levelsSkipped = [];
  11456. for (let i2 = maxAutoLevel; i2 >= minAutoLevel; i2--) {
  11457. var _levelInfo$supportedR, _levelInfo$supportedR2;
  11458. const levelInfo = levels[i2];
  11459. const upSwitch = i2 > selectionBaseLevel;
  11460. if (!levelInfo) {
  11461. continue;
  11462. }
  11463. if (config.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) {
  11464. const mediaCapabilities = navigator.mediaCapabilities;
  11465. if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === "function" && requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference)) {
  11466. levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities, this.supportedCache);
  11467. levelInfo.supportedPromise.then((decodingInfo) => {
  11468. if (!this.hls) {
  11469. return;
  11470. }
  11471. levelInfo.supportedResult = decodingInfo;
  11472. const levels2 = this.hls.levels;
  11473. const index2 = levels2.indexOf(levelInfo);
  11474. if (decodingInfo.error) {
  11475. this.warn(`MediaCapabilities decodingInfo error: "${decodingInfo.error}" for level ${index2} ${stringify(decodingInfo)}`);
  11476. } else if (!decodingInfo.supported) {
  11477. this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${index2} ${stringify(decodingInfo)}`);
  11478. if (index2 > -1 && levels2.length > 1) {
  11479. this.log(`Removing unsupported level ${index2}`);
  11480. this.hls.removeLevel(index2);
  11481. if (this.hls.loadLevel === -1) {
  11482. this.hls.nextLoadLevel = 0;
  11483. }
  11484. }
  11485. } else if (decodingInfo.decodingInfoResults.some((info) => info.smooth === false || info.powerEfficient === false)) {
  11486. this.log(`MediaCapabilities decodingInfo for level ${index2} not smooth or powerEfficient: ${stringify(decodingInfo)}`);
  11487. }
  11488. });
  11489. } else {
  11490. levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;
  11491. }
  11492. }
  11493. if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || (_levelInfo$supportedR = levelInfo.supportedResult) != null && (_levelInfo$supportedR2 = _levelInfo$supportedR.decodingInfoResults) != null && _levelInfo$supportedR2.some((info) => info.smooth === false)) {
  11494. if (!firstSelection || i2 !== minStartIndex) {
  11495. levelsSkipped.push(i2);
  11496. continue;
  11497. }
  11498. }
  11499. const levelDetails = levelInfo.details;
  11500. const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  11501. let adjustedbw;
  11502. if (!upSwitch) {
  11503. adjustedbw = bwFactor * currentBw;
  11504. } else {
  11505. adjustedbw = bwUpFactor * currentBw;
  11506. }
  11507. const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levelInfo.averageBitrate : levelInfo.maxBitrate;
  11508. const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === void 0);
  11509. const canSwitchWithinTolerance = (
  11510. // if adjusted bw is greater than level bitrate AND
  11511. adjustedbw >= bitrate && // no level change, or new level has no error history
  11512. (i2 === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  11513. // 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 ...
  11514. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  11515. (fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)
  11516. );
  11517. if (canSwitchWithinTolerance) {
  11518. const forcedAutoLevel = this.forcedAutoLevel;
  11519. if (i2 !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  11520. if (levelsSkipped.length) {
  11521. this.trace(`Skipped level(s) ${levelsSkipped.join(",")} of ${maxAutoLevel} max with CODECS and VIDEO-RANGE:"${levels[levelsSkipped[0]].codecs}" ${levels[levelsSkipped[0]].videoRange}; not compatible with "${currentCodecSet}" ${currentVideoRange}`);
  11522. }
  11523. this.info(`switch candidate:${selectionBaseLevel}->${i2} adjustedbw(${Math.round(adjustedbw)})-bitrate=${Math.round(adjustedbw - bitrate)} ttfb:${ttfbEstimateSec.toFixed(1)} avgDuration:${avgDuration.toFixed(1)} maxFetchDuration:${maxFetchDuration.toFixed(1)} fetchDuration:${fetchDuration.toFixed(1)} firstSelection:${firstSelection} codecSet:${levelInfo.codecSet} videoRange:${levelInfo.videoRange} hls.loadLevel:${loadLevel}`);
  11524. }
  11525. if (firstSelection) {
  11526. this.firstSelection = i2;
  11527. }
  11528. return i2;
  11529. }
  11530. }
  11531. return -1;
  11532. }
  11533. set nextAutoLevel(nextLevel) {
  11534. const value = this.deriveNextAutoLevel(nextLevel);
  11535. if (this._nextAutoLevel !== value) {
  11536. this.nextAutoLevelKey = "";
  11537. this._nextAutoLevel = value;
  11538. }
  11539. }
  11540. deriveNextAutoLevel(nextLevel) {
  11541. const {
  11542. maxAutoLevel,
  11543. minAutoLevel
  11544. } = this.hls;
  11545. return Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  11546. }
  11547. }
  11548. const BinarySearch = {
  11549. /**
  11550. * Searches for an item in an array which matches a certain condition.
  11551. * This requires the condition to only match one item in the array,
  11552. * and for the array to be ordered.
  11553. *
  11554. * @param list The array to search.
  11555. * @param comparisonFn
  11556. * Called and provided a candidate item as the first argument.
  11557. * Should return:
  11558. * > -1 if the item should be located at a lower index than the provided item.
  11559. * > 1 if the item should be located at a higher index than the provided item.
  11560. * > 0 if the item is the item you're looking for.
  11561. *
  11562. * @returns the object if found, otherwise returns null
  11563. */
  11564. search: function(list, comparisonFn) {
  11565. let minIndex = 0;
  11566. let maxIndex = list.length - 1;
  11567. let currentIndex = null;
  11568. let currentElement = null;
  11569. while (minIndex <= maxIndex) {
  11570. currentIndex = (minIndex + maxIndex) / 2 | 0;
  11571. currentElement = list[currentIndex];
  11572. const comparisonResult = comparisonFn(currentElement);
  11573. if (comparisonResult > 0) {
  11574. minIndex = currentIndex + 1;
  11575. } else if (comparisonResult < 0) {
  11576. maxIndex = currentIndex - 1;
  11577. } else {
  11578. return currentElement;
  11579. }
  11580. }
  11581. return null;
  11582. }
  11583. };
  11584. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  11585. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  11586. return null;
  11587. }
  11588. const startPDT = fragments[0].programDateTime;
  11589. if (PDTValue < (startPDT || 0)) {
  11590. return null;
  11591. }
  11592. const endPDT = fragments[fragments.length - 1].endProgramDateTime;
  11593. if (PDTValue >= (endPDT || 0)) {
  11594. return null;
  11595. }
  11596. for (let seg = 0; seg < fragments.length; ++seg) {
  11597. const frag = fragments[seg];
  11598. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  11599. return frag;
  11600. }
  11601. }
  11602. return null;
  11603. }
  11604. function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 5e-3) {
  11605. let fragNext = null;
  11606. if (fragPrevious) {
  11607. fragNext = fragments[1 + fragPrevious.sn - fragments[0].sn] || null;
  11608. const bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  11609. if (bufferEdgeError > 0 && bufferEdgeError < 15e-7) {
  11610. bufferEnd += 15e-7;
  11611. }
  11612. if (fragNext && fragPrevious.level !== fragNext.level && fragNext.end <= fragPrevious.end) {
  11613. fragNext = fragments[2 + fragPrevious.sn - fragments[0].sn] || null;
  11614. }
  11615. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  11616. fragNext = fragments[0];
  11617. }
  11618. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  11619. return fragNext;
  11620. }
  11621. const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  11622. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  11623. return foundFragment;
  11624. }
  11625. return fragNext;
  11626. }
  11627. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  11628. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  11629. const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {
  11630. if (tag[0] === "INF") {
  11631. duration += parseFloat(tag[1]);
  11632. }
  11633. return duration;
  11634. }, nextFragLookupTolerance);
  11635. return fragNext.start <= firstDuration;
  11636. }
  11637. return false;
  11638. }
  11639. function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {
  11640. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  11641. return 0;
  11642. }
  11643. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  11644. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  11645. return 1;
  11646. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  11647. return -1;
  11648. }
  11649. return 0;
  11650. }
  11651. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  11652. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1e3;
  11653. const endProgramDateTime = candidate.endProgramDateTime || 0;
  11654. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  11655. }
  11656. function findNearestWithCC(details, cc, pos) {
  11657. if (details) {
  11658. if (details.startCC <= cc && details.endCC >= cc) {
  11659. let fragments = details.fragments;
  11660. const {
  11661. fragmentHint
  11662. } = details;
  11663. if (fragmentHint) {
  11664. fragments = fragments.concat(fragmentHint);
  11665. }
  11666. let closest;
  11667. BinarySearch.search(fragments, (candidate) => {
  11668. if (candidate.cc < cc) {
  11669. return 1;
  11670. }
  11671. if (candidate.cc > cc) {
  11672. return -1;
  11673. }
  11674. closest = candidate;
  11675. if (candidate.end <= pos) {
  11676. return 1;
  11677. }
  11678. if (candidate.start > pos) {
  11679. return -1;
  11680. }
  11681. return 0;
  11682. });
  11683. return closest || null;
  11684. }
  11685. }
  11686. return null;
  11687. }
  11688. function isTimeoutError(error) {
  11689. switch (error.details) {
  11690. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  11691. case ErrorDetails.KEY_LOAD_TIMEOUT:
  11692. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  11693. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  11694. return true;
  11695. }
  11696. return false;
  11697. }
  11698. function getRetryConfig(loadPolicy, error) {
  11699. const isTimeout = isTimeoutError(error);
  11700. return loadPolicy.default[`${isTimeout ? "timeout" : "error"}Retry`];
  11701. }
  11702. function getRetryDelay(retryConfig, retryCount) {
  11703. const backoffFactor = retryConfig.backoff === "linear" ? 1 : Math.pow(2, retryCount);
  11704. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  11705. }
  11706. function getLoaderConfigWithoutReties(loderConfig) {
  11707. return _objectSpread2(_objectSpread2({}, loderConfig), {
  11708. errorRetry: null,
  11709. timeoutRetry: null
  11710. });
  11711. }
  11712. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  11713. if (!retryConfig) {
  11714. return false;
  11715. }
  11716. const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  11717. const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  11718. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  11719. }
  11720. function retryForHttpStatus(httpStatus) {
  11721. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  11722. }
  11723. var NetworkErrorAction = {
  11724. DoNothing: 0,
  11725. SendEndCallback: 1,
  11726. SendAlternateToPenaltyBox: 2,
  11727. RemoveAlternatePermanently: 3,
  11728. InsertDiscontinuity: 4,
  11729. RetryRequest: 5
  11730. };
  11731. var ErrorActionFlags = {
  11732. None: 0,
  11733. MoveAllAlternatesMatchingHost: 1,
  11734. MoveAllAlternatesMatchingHDCP: 2,
  11735. SwitchToSDR: 4
  11736. };
  11737. class ErrorController extends Logger {
  11738. constructor(hls) {
  11739. super("error-controller", hls.logger);
  11740. this.hls = void 0;
  11741. this.playlistError = 0;
  11742. this.penalizedRenditions = {};
  11743. this.hls = hls;
  11744. this.registerListeners();
  11745. }
  11746. registerListeners() {
  11747. const hls = this.hls;
  11748. hls.on(Events.ERROR, this.onError, this);
  11749. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  11750. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  11751. }
  11752. unregisterListeners() {
  11753. const hls = this.hls;
  11754. if (!hls) {
  11755. return;
  11756. }
  11757. hls.off(Events.ERROR, this.onError, this);
  11758. hls.off(Events.ERROR, this.onErrorOut, this);
  11759. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  11760. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  11761. }
  11762. destroy() {
  11763. this.unregisterListeners();
  11764. this.hls = null;
  11765. this.penalizedRenditions = {};
  11766. }
  11767. startLoad(startPosition) {
  11768. }
  11769. stopLoad() {
  11770. this.playlistError = 0;
  11771. }
  11772. getVariantLevelIndex(frag) {
  11773. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  11774. }
  11775. onManifestLoading() {
  11776. this.playlistError = 0;
  11777. this.penalizedRenditions = {};
  11778. }
  11779. onLevelUpdated() {
  11780. this.playlistError = 0;
  11781. }
  11782. onError(event, data) {
  11783. var _data$frag;
  11784. if (data.fatal) {
  11785. return;
  11786. }
  11787. const hls = this.hls;
  11788. const context = data.context;
  11789. switch (data.details) {
  11790. case ErrorDetails.FRAG_LOAD_ERROR:
  11791. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  11792. case ErrorDetails.KEY_LOAD_ERROR:
  11793. case ErrorDetails.KEY_LOAD_TIMEOUT:
  11794. data.errorAction = this.getFragRetryOrSwitchAction(data);
  11795. return;
  11796. case ErrorDetails.FRAG_PARSING_ERROR:
  11797. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  11798. data.errorAction = createDoNothingErrorAction();
  11799. return;
  11800. }
  11801. case ErrorDetails.FRAG_GAP:
  11802. case ErrorDetails.FRAG_DECRYPT_ERROR: {
  11803. data.errorAction = this.getFragRetryOrSwitchAction(data);
  11804. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  11805. return;
  11806. }
  11807. case ErrorDetails.LEVEL_EMPTY_ERROR:
  11808. case ErrorDetails.LEVEL_PARSING_ERROR:
  11809. {
  11810. var _data$context, _data$context$levelDe;
  11811. const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  11812. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  11813. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  11814. } else {
  11815. data.levelRetry = false;
  11816. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  11817. }
  11818. }
  11819. return;
  11820. case ErrorDetails.LEVEL_LOAD_ERROR:
  11821. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  11822. if (typeof (context == null ? void 0 : context.level) === "number") {
  11823. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  11824. }
  11825. return;
  11826. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  11827. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  11828. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  11829. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  11830. if (context) {
  11831. const level = hls.loadLevelObj;
  11832. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  11833. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  11834. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  11835. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  11836. return;
  11837. }
  11838. }
  11839. return;
  11840. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  11841. {
  11842. const level = hls.loadLevelObj;
  11843. const restrictedHdcpLevel = level == null ? void 0 : level.attrs["HDCP-LEVEL"];
  11844. if (restrictedHdcpLevel) {
  11845. data.errorAction = {
  11846. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  11847. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  11848. hdcpLevel: restrictedHdcpLevel
  11849. };
  11850. } else {
  11851. this.keySystemError(data);
  11852. }
  11853. }
  11854. return;
  11855. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  11856. case ErrorDetails.REMUX_ALLOC_ERROR:
  11857. case ErrorDetails.BUFFER_APPEND_ERROR:
  11858. if (!data.errorAction) {
  11859. var _data$level;
  11860. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  11861. }
  11862. return;
  11863. case ErrorDetails.INTERNAL_EXCEPTION:
  11864. case ErrorDetails.BUFFER_APPENDING_ERROR:
  11865. case ErrorDetails.BUFFER_FULL_ERROR:
  11866. case ErrorDetails.LEVEL_SWITCH_ERROR:
  11867. case ErrorDetails.BUFFER_STALLED_ERROR:
  11868. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  11869. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  11870. data.errorAction = createDoNothingErrorAction();
  11871. return;
  11872. }
  11873. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  11874. this.keySystemError(data);
  11875. }
  11876. }
  11877. keySystemError(data) {
  11878. const levelIndex = this.getVariantLevelIndex(data.frag);
  11879. data.levelRetry = false;
  11880. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  11881. }
  11882. getPlaylistRetryOrSwitchAction(data, levelIndex) {
  11883. const hls = this.hls;
  11884. const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  11885. const retryCount = this.playlistError++;
  11886. const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  11887. if (retry) {
  11888. return {
  11889. action: NetworkErrorAction.RetryRequest,
  11890. flags: ErrorActionFlags.None,
  11891. retryConfig,
  11892. retryCount
  11893. };
  11894. }
  11895. const errorAction = this.getLevelSwitchAction(data, levelIndex);
  11896. if (retryConfig) {
  11897. errorAction.retryConfig = retryConfig;
  11898. errorAction.retryCount = retryCount;
  11899. }
  11900. return errorAction;
  11901. }
  11902. getFragRetryOrSwitchAction(data) {
  11903. const hls = this.hls;
  11904. const variantLevelIndex = this.getVariantLevelIndex(data.frag);
  11905. const level = hls.levels[variantLevelIndex];
  11906. const {
  11907. fragLoadPolicy,
  11908. keyLoadPolicy
  11909. } = hls.config;
  11910. const retryConfig = getRetryConfig(data.details.startsWith("key") ? keyLoadPolicy : fragLoadPolicy, data);
  11911. const fragmentErrors = hls.levels.reduce((acc, level2) => acc + level2.fragmentError, 0);
  11912. if (level) {
  11913. if (data.details !== ErrorDetails.FRAG_GAP) {
  11914. level.fragmentError++;
  11915. }
  11916. const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  11917. if (retry) {
  11918. return {
  11919. action: NetworkErrorAction.RetryRequest,
  11920. flags: ErrorActionFlags.None,
  11921. retryConfig,
  11922. retryCount: fragmentErrors
  11923. };
  11924. }
  11925. }
  11926. const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  11927. if (retryConfig) {
  11928. errorAction.retryConfig = retryConfig;
  11929. errorAction.retryCount = fragmentErrors;
  11930. }
  11931. return errorAction;
  11932. }
  11933. getLevelSwitchAction(data, levelIndex) {
  11934. const hls = this.hls;
  11935. if (levelIndex === null || levelIndex === void 0) {
  11936. levelIndex = hls.loadLevel;
  11937. }
  11938. const level = this.hls.levels[levelIndex];
  11939. if (level) {
  11940. var _data$frag2, _data$context2;
  11941. const errorDetails = data.details;
  11942. level.loadError++;
  11943. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  11944. level.fragmentError++;
  11945. }
  11946. let nextLevel = -1;
  11947. const {
  11948. levels,
  11949. loadLevel,
  11950. minAutoLevel,
  11951. maxAutoLevel
  11952. } = hls;
  11953. if (!hls.autoLevelEnabled && !hls.config.preserveManualLevelOnError) {
  11954. hls.loadLevel = -1;
  11955. }
  11956. const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  11957. const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === "audio" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  11958. const findAudioCodecAlternate = isAudioCodecError && levels.some(({
  11959. audioCodec
  11960. }) => level.audioCodec !== audioCodec);
  11961. const isVideoCodecError = data.sourceBufferName === "video" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  11962. const findVideoCodecAlternate = isVideoCodecError && levels.some(({
  11963. codecSet,
  11964. audioCodec
  11965. }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);
  11966. const {
  11967. type: playlistErrorType,
  11968. groupId: playlistErrorGroupId
  11969. } = (_data$context2 = data.context) != null ? _data$context2 : {};
  11970. for (let i2 = levels.length; i2--; ) {
  11971. const candidate = (i2 + loadLevel) % levels.length;
  11972. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  11973. var _level$audioGroups, _level$subtitleGroups;
  11974. const levelCandidate = levels[candidate];
  11975. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  11976. const levelDetails = levels[candidate].details;
  11977. if (levelDetails) {
  11978. const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  11979. if (fragCandidate != null && fragCandidate.gap) {
  11980. continue;
  11981. }
  11982. }
  11983. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  11984. continue;
  11985. } else if (fragErrorType === PlaylistLevelType.AUDIO && (_level$audioGroups = level.audioGroups) != null && _level$audioGroups.some((groupId) => levelCandidate.hasAudioGroup(groupId)) || fragErrorType === PlaylistLevelType.SUBTITLE && (_level$subtitleGroups = level.subtitleGroups) != null && _level$subtitleGroups.some((groupId) => levelCandidate.hasSubtitleGroup(groupId)) || findAudioCodecAlternate && level.audioCodec === levelCandidate.audioCodec || !findAudioCodecAlternate && level.audioCodec !== levelCandidate.audioCodec || findVideoCodecAlternate && level.codecSet === levelCandidate.codecSet) {
  11986. continue;
  11987. }
  11988. nextLevel = candidate;
  11989. break;
  11990. }
  11991. }
  11992. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  11993. data.levelRetry = true;
  11994. this.playlistError = 0;
  11995. return {
  11996. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  11997. flags: ErrorActionFlags.None,
  11998. nextAutoLevel: nextLevel
  11999. };
  12000. }
  12001. }
  12002. return {
  12003. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  12004. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  12005. };
  12006. }
  12007. onErrorOut(event, data) {
  12008. var _data$errorAction;
  12009. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  12010. case NetworkErrorAction.DoNothing:
  12011. break;
  12012. case NetworkErrorAction.SendAlternateToPenaltyBox:
  12013. this.sendAlternateToPenaltyBox(data);
  12014. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  12015. data.fatal = true;
  12016. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  12017. this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`);
  12018. this.hls.recoverMediaError();
  12019. }
  12020. break;
  12021. }
  12022. if (data.fatal) {
  12023. this.hls.stopLoad();
  12024. return;
  12025. }
  12026. }
  12027. sendAlternateToPenaltyBox(data) {
  12028. const hls = this.hls;
  12029. const errorAction = data.errorAction;
  12030. if (!errorAction) {
  12031. return;
  12032. }
  12033. const {
  12034. flags,
  12035. hdcpLevel,
  12036. nextAutoLevel
  12037. } = errorAction;
  12038. switch (flags) {
  12039. case ErrorActionFlags.None:
  12040. this.switchLevel(data, nextAutoLevel);
  12041. break;
  12042. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  12043. if (hdcpLevel) {
  12044. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  12045. errorAction.resolved = true;
  12046. }
  12047. this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`);
  12048. break;
  12049. }
  12050. if (!errorAction.resolved) {
  12051. this.switchLevel(data, nextAutoLevel);
  12052. }
  12053. }
  12054. switchLevel(data, levelIndex) {
  12055. if (levelIndex !== void 0 && data.errorAction) {
  12056. this.warn(`switching to level ${levelIndex} after ${data.details}`);
  12057. this.hls.nextAutoLevel = levelIndex;
  12058. data.errorAction.resolved = true;
  12059. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  12060. if (data.details === ErrorDetails.BUFFER_ADD_CODEC_ERROR && data.mimeType && data.sourceBufferName !== "audiovideo") {
  12061. const codec = getCodecsForMimeType(data.mimeType);
  12062. const levels = this.hls.levels;
  12063. for (let i2 = levels.length; i2--; ) {
  12064. if (levels[i2][`${data.sourceBufferName}Codec`] === codec) {
  12065. this.hls.removeLevel(i2);
  12066. }
  12067. }
  12068. }
  12069. }
  12070. }
  12071. }
  12072. function createDoNothingErrorAction(resolved) {
  12073. const errorAction = {
  12074. action: NetworkErrorAction.DoNothing,
  12075. flags: ErrorActionFlags.None
  12076. };
  12077. if (resolved) {
  12078. errorAction.resolved = true;
  12079. }
  12080. return errorAction;
  12081. }
  12082. var FragmentState = {
  12083. NOT_LOADED: "NOT_LOADED",
  12084. APPENDING: "APPENDING",
  12085. PARTIAL: "PARTIAL",
  12086. OK: "OK"
  12087. };
  12088. class FragmentTracker {
  12089. constructor(hls) {
  12090. this.activePartLists = /* @__PURE__ */ Object.create(null);
  12091. this.endListFragments = /* @__PURE__ */ Object.create(null);
  12092. this.fragments = /* @__PURE__ */ Object.create(null);
  12093. this.timeRanges = /* @__PURE__ */ Object.create(null);
  12094. this.bufferPadding = 0.2;
  12095. this.hls = void 0;
  12096. this.hasGaps = false;
  12097. this.hls = hls;
  12098. this._registerListeners();
  12099. }
  12100. _registerListeners() {
  12101. const {
  12102. hls
  12103. } = this;
  12104. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  12105. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  12106. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  12107. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  12108. }
  12109. _unregisterListeners() {
  12110. const {
  12111. hls
  12112. } = this;
  12113. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  12114. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  12115. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  12116. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  12117. }
  12118. destroy() {
  12119. this._unregisterListeners();
  12120. this.fragments = // @ts-ignore
  12121. this.activePartLists = // @ts-ignore
  12122. this.endListFragments = this.timeRanges = null;
  12123. }
  12124. /**
  12125. * Return a Fragment or Part with an appended range that matches the position and levelType
  12126. * Otherwise, return null
  12127. */
  12128. getAppendedFrag(position, levelType) {
  12129. const activeParts = this.activePartLists[levelType];
  12130. if (activeParts) {
  12131. for (let i2 = activeParts.length; i2--; ) {
  12132. const activePart = activeParts[i2];
  12133. if (!activePart) {
  12134. break;
  12135. }
  12136. const appendedPTS = activePart.end;
  12137. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  12138. return activePart;
  12139. }
  12140. }
  12141. }
  12142. return this.getBufferedFrag(position, levelType);
  12143. }
  12144. /**
  12145. * Return a buffered Fragment that matches the position and levelType.
  12146. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  12147. * If not found any Fragment, return null
  12148. */
  12149. getBufferedFrag(position, levelType) {
  12150. return this.getFragAtPos(position, levelType, true);
  12151. }
  12152. getFragAtPos(position, levelType, buffered) {
  12153. const {
  12154. fragments
  12155. } = this;
  12156. const keys = Object.keys(fragments);
  12157. for (let i2 = keys.length; i2--; ) {
  12158. const fragmentEntity = fragments[keys[i2]];
  12159. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && (!buffered || fragmentEntity.buffered)) {
  12160. const frag = fragmentEntity.body;
  12161. if (frag.start <= position && position <= frag.end) {
  12162. return frag;
  12163. }
  12164. }
  12165. }
  12166. return null;
  12167. }
  12168. /**
  12169. * Partial fragments effected by coded frame eviction will be removed
  12170. * The browser will unload parts of the buffer to free up memory for new buffer data
  12171. * 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)
  12172. */
  12173. detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart, removeAppending) {
  12174. if (this.timeRanges) {
  12175. this.timeRanges[elementaryStream] = timeRange;
  12176. }
  12177. const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  12178. Object.keys(this.fragments).forEach((key) => {
  12179. const fragmentEntity = this.fragments[key];
  12180. if (!fragmentEntity) {
  12181. return;
  12182. }
  12183. if (appendedPartSn >= fragmentEntity.body.sn) {
  12184. return;
  12185. }
  12186. if (!fragmentEntity.buffered && (!fragmentEntity.loaded || removeAppending)) {
  12187. if (fragmentEntity.body.type === playlistType) {
  12188. this.removeFragment(fragmentEntity.body);
  12189. }
  12190. return;
  12191. }
  12192. const esData = fragmentEntity.range[elementaryStream];
  12193. if (!esData) {
  12194. return;
  12195. }
  12196. if (esData.time.length === 0) {
  12197. this.removeFragment(fragmentEntity.body);
  12198. return;
  12199. }
  12200. esData.time.some((time) => {
  12201. const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  12202. if (isNotBuffered) {
  12203. this.removeFragment(fragmentEntity.body);
  12204. }
  12205. return isNotBuffered;
  12206. });
  12207. });
  12208. }
  12209. /**
  12210. * Checks if the fragment passed in is loaded in the buffer properly
  12211. * Partially loaded fragments will be registered as a partial fragment
  12212. */
  12213. detectPartialFragments(data) {
  12214. const timeRanges = this.timeRanges;
  12215. if (!timeRanges || data.frag.sn === "initSegment") {
  12216. return;
  12217. }
  12218. const frag = data.frag;
  12219. const fragKey = getFragmentKey(frag);
  12220. const fragmentEntity = this.fragments[fragKey];
  12221. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  12222. return;
  12223. }
  12224. const isFragHint = !frag.relurl;
  12225. Object.keys(timeRanges).forEach((elementaryStream) => {
  12226. const streamInfo = frag.elementaryStreams[elementaryStream];
  12227. if (!streamInfo) {
  12228. return;
  12229. }
  12230. const timeRange = timeRanges[elementaryStream];
  12231. const partial2 = isFragHint || streamInfo.partial === true;
  12232. fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, data.part, partial2, timeRange);
  12233. });
  12234. fragmentEntity.loaded = null;
  12235. if (Object.keys(fragmentEntity.range).length) {
  12236. fragmentEntity.buffered = true;
  12237. const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  12238. if (endList) {
  12239. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  12240. }
  12241. if (!isPartial(fragmentEntity)) {
  12242. this.removeParts(frag.sn - 1, frag.type);
  12243. }
  12244. } else {
  12245. this.removeFragment(fragmentEntity.body);
  12246. }
  12247. }
  12248. removeParts(snToKeep, levelType) {
  12249. const activeParts = this.activePartLists[levelType];
  12250. if (!activeParts) {
  12251. return;
  12252. }
  12253. this.activePartLists[levelType] = filterParts(activeParts, (part) => part.fragment.sn >= snToKeep);
  12254. }
  12255. fragBuffered(frag, force) {
  12256. const fragKey = getFragmentKey(frag);
  12257. let fragmentEntity = this.fragments[fragKey];
  12258. if (!fragmentEntity && force) {
  12259. fragmentEntity = this.fragments[fragKey] = {
  12260. body: frag,
  12261. appendedPTS: null,
  12262. loaded: null,
  12263. buffered: false,
  12264. range: /* @__PURE__ */ Object.create(null)
  12265. };
  12266. if (frag.gap) {
  12267. this.hasGaps = true;
  12268. }
  12269. }
  12270. if (fragmentEntity) {
  12271. fragmentEntity.loaded = null;
  12272. fragmentEntity.buffered = true;
  12273. }
  12274. }
  12275. getBufferedTimes(fragment, part, partial2, timeRange) {
  12276. const buffered = {
  12277. time: [],
  12278. partial: partial2
  12279. };
  12280. const startPTS = fragment.start;
  12281. const endPTS = fragment.end;
  12282. const minEndPTS = fragment.minEndPTS || endPTS;
  12283. const maxStartPTS = fragment.maxStartPTS || startPTS;
  12284. for (let i2 = 0; i2 < timeRange.length; i2++) {
  12285. const startTime = timeRange.start(i2) - this.bufferPadding;
  12286. const endTime = timeRange.end(i2) + this.bufferPadding;
  12287. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  12288. buffered.time.push({
  12289. startPTS: Math.max(startPTS, timeRange.start(i2)),
  12290. endPTS: Math.min(endPTS, timeRange.end(i2))
  12291. });
  12292. break;
  12293. } else if (startPTS < endTime && endPTS > startTime) {
  12294. const start = Math.max(startPTS, timeRange.start(i2));
  12295. const end = Math.min(endPTS, timeRange.end(i2));
  12296. if (end > start) {
  12297. buffered.partial = true;
  12298. buffered.time.push({
  12299. startPTS: start,
  12300. endPTS: end
  12301. });
  12302. }
  12303. } else if (endPTS <= startTime) {
  12304. break;
  12305. }
  12306. }
  12307. return buffered;
  12308. }
  12309. /**
  12310. * Gets the partial fragment for a certain time
  12311. */
  12312. getPartialFragment(time) {
  12313. let bestFragment = null;
  12314. let timePadding;
  12315. let startTime;
  12316. let endTime;
  12317. let bestOverlap = 0;
  12318. const {
  12319. bufferPadding,
  12320. fragments
  12321. } = this;
  12322. Object.keys(fragments).forEach((key) => {
  12323. const fragmentEntity = fragments[key];
  12324. if (!fragmentEntity) {
  12325. return;
  12326. }
  12327. if (isPartial(fragmentEntity)) {
  12328. startTime = fragmentEntity.body.start - bufferPadding;
  12329. endTime = fragmentEntity.body.end + bufferPadding;
  12330. if (time >= startTime && time <= endTime) {
  12331. timePadding = Math.min(time - startTime, endTime - time);
  12332. if (bestOverlap <= timePadding) {
  12333. bestFragment = fragmentEntity.body;
  12334. bestOverlap = timePadding;
  12335. }
  12336. }
  12337. }
  12338. });
  12339. return bestFragment;
  12340. }
  12341. isEndListAppended(type) {
  12342. const lastFragmentEntity = this.endListFragments[type];
  12343. return lastFragmentEntity !== void 0 && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  12344. }
  12345. getState(fragment) {
  12346. const fragKey = getFragmentKey(fragment);
  12347. const fragmentEntity = this.fragments[fragKey];
  12348. if (fragmentEntity) {
  12349. if (!fragmentEntity.buffered) {
  12350. return FragmentState.APPENDING;
  12351. } else if (isPartial(fragmentEntity)) {
  12352. return FragmentState.PARTIAL;
  12353. } else {
  12354. return FragmentState.OK;
  12355. }
  12356. }
  12357. return FragmentState.NOT_LOADED;
  12358. }
  12359. isTimeBuffered(startPTS, endPTS, timeRange) {
  12360. let startTime;
  12361. let endTime;
  12362. for (let i2 = 0; i2 < timeRange.length; i2++) {
  12363. startTime = timeRange.start(i2) - this.bufferPadding;
  12364. endTime = timeRange.end(i2) + this.bufferPadding;
  12365. if (startPTS >= startTime && endPTS <= endTime) {
  12366. return true;
  12367. }
  12368. if (endPTS <= startTime) {
  12369. return false;
  12370. }
  12371. }
  12372. return false;
  12373. }
  12374. onManifestLoading() {
  12375. this.removeAllFragments();
  12376. }
  12377. onFragLoaded(event, data) {
  12378. if (data.frag.sn === "initSegment" || data.frag.bitrateTest) {
  12379. return;
  12380. }
  12381. const frag = data.frag;
  12382. const loaded = data.part ? null : data;
  12383. const fragKey = getFragmentKey(frag);
  12384. this.fragments[fragKey] = {
  12385. body: frag,
  12386. appendedPTS: null,
  12387. loaded,
  12388. buffered: false,
  12389. range: /* @__PURE__ */ Object.create(null)
  12390. };
  12391. }
  12392. onBufferAppended(event, data) {
  12393. const {
  12394. frag,
  12395. part,
  12396. timeRanges,
  12397. type
  12398. } = data;
  12399. if (frag.sn === "initSegment") {
  12400. return;
  12401. }
  12402. const playlistType = frag.type;
  12403. if (part) {
  12404. let activeParts = this.activePartLists[playlistType];
  12405. if (!activeParts) {
  12406. this.activePartLists[playlistType] = activeParts = [];
  12407. }
  12408. activeParts.push(part);
  12409. }
  12410. this.timeRanges = timeRanges;
  12411. const timeRange = timeRanges[type];
  12412. this.detectEvictedFragments(type, timeRange, playlistType, part);
  12413. }
  12414. onFragBuffered(event, data) {
  12415. this.detectPartialFragments(data);
  12416. }
  12417. hasFragment(fragment) {
  12418. const fragKey = getFragmentKey(fragment);
  12419. return !!this.fragments[fragKey];
  12420. }
  12421. hasFragments(type) {
  12422. const {
  12423. fragments
  12424. } = this;
  12425. const keys = Object.keys(fragments);
  12426. if (!type) {
  12427. return keys.length > 0;
  12428. }
  12429. for (let i2 = keys.length; i2--; ) {
  12430. const fragmentEntity = fragments[keys[i2]];
  12431. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === type) {
  12432. return true;
  12433. }
  12434. }
  12435. return false;
  12436. }
  12437. hasParts(type) {
  12438. var _this$activePartLists;
  12439. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  12440. }
  12441. removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  12442. if (withGapOnly && !this.hasGaps) {
  12443. return;
  12444. }
  12445. Object.keys(this.fragments).forEach((key) => {
  12446. const fragmentEntity = this.fragments[key];
  12447. if (!fragmentEntity) {
  12448. return;
  12449. }
  12450. const frag = fragmentEntity.body;
  12451. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  12452. return;
  12453. }
  12454. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  12455. this.removeFragment(frag);
  12456. }
  12457. });
  12458. }
  12459. removeFragment(fragment) {
  12460. const fragKey = getFragmentKey(fragment);
  12461. fragment.clearElementaryStreamInfo();
  12462. const activeParts = this.activePartLists[fragment.type];
  12463. if (activeParts) {
  12464. const snToRemove = fragment.sn;
  12465. this.activePartLists[fragment.type] = filterParts(activeParts, (part) => part.fragment.sn !== snToRemove);
  12466. }
  12467. delete this.fragments[fragKey];
  12468. if (fragment.endList) {
  12469. delete this.endListFragments[fragment.type];
  12470. }
  12471. }
  12472. removeAllFragments() {
  12473. var _this$hls, _this$hls$latestLevel;
  12474. this.fragments = /* @__PURE__ */ Object.create(null);
  12475. this.endListFragments = /* @__PURE__ */ Object.create(null);
  12476. this.activePartLists = /* @__PURE__ */ Object.create(null);
  12477. this.hasGaps = false;
  12478. const partlist = (_this$hls = this.hls) == null ? void 0 : (_this$hls$latestLevel = _this$hls.latestLevelDetails) == null ? void 0 : _this$hls$latestLevel.partList;
  12479. if (partlist) {
  12480. partlist.forEach((part) => part.clearElementaryStreamInfo());
  12481. }
  12482. }
  12483. }
  12484. function isPartial(fragmentEntity) {
  12485. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  12486. 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));
  12487. }
  12488. function getFragmentKey(fragment) {
  12489. return `${fragment.type}_${fragment.level}_${fragment.sn}`;
  12490. }
  12491. function filterParts(partList, predicate) {
  12492. return partList.filter((part) => {
  12493. const keep = predicate(part);
  12494. if (!keep) {
  12495. part.clearElementaryStreamInfo();
  12496. }
  12497. return keep;
  12498. });
  12499. }
  12500. var DecrypterAesMode = {
  12501. cbc: 0,
  12502. ctr: 1
  12503. };
  12504. class AESCrypto {
  12505. constructor(subtle, iv, aesMode) {
  12506. this.subtle = void 0;
  12507. this.aesIV = void 0;
  12508. this.aesMode = void 0;
  12509. this.subtle = subtle;
  12510. this.aesIV = iv;
  12511. this.aesMode = aesMode;
  12512. }
  12513. decrypt(data, key) {
  12514. switch (this.aesMode) {
  12515. case DecrypterAesMode.cbc:
  12516. return this.subtle.decrypt({
  12517. name: "AES-CBC",
  12518. iv: this.aesIV
  12519. }, key, data);
  12520. case DecrypterAesMode.ctr:
  12521. return this.subtle.decrypt(
  12522. {
  12523. name: "AES-CTR",
  12524. counter: this.aesIV,
  12525. length: 64
  12526. },
  12527. //64 : NIST SP800-38A standard suggests that the counter should occupy half of the counter block
  12528. key,
  12529. data
  12530. );
  12531. default:
  12532. throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`);
  12533. }
  12534. }
  12535. }
  12536. function removePadding(array) {
  12537. const outputBytes = array.byteLength;
  12538. const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  12539. if (paddingBytes) {
  12540. return array.slice(0, outputBytes - paddingBytes);
  12541. }
  12542. return array;
  12543. }
  12544. class AESDecryptor {
  12545. constructor() {
  12546. this.rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
  12547. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  12548. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  12549. this.sBox = new Uint32Array(256);
  12550. this.invSBox = new Uint32Array(256);
  12551. this.key = new Uint32Array(0);
  12552. this.ksRows = 0;
  12553. this.keySize = 0;
  12554. this.keySchedule = void 0;
  12555. this.invKeySchedule = void 0;
  12556. this.initTable();
  12557. }
  12558. // Using view.getUint32() also swaps the byte order.
  12559. uint8ArrayToUint32Array_(arrayBuffer) {
  12560. const view2 = new DataView(arrayBuffer);
  12561. const newArray = new Uint32Array(4);
  12562. for (let i2 = 0; i2 < 4; i2++) {
  12563. newArray[i2] = view2.getUint32(i2 * 4);
  12564. }
  12565. return newArray;
  12566. }
  12567. initTable() {
  12568. const sBox = this.sBox;
  12569. const invSBox = this.invSBox;
  12570. const subMix = this.subMix;
  12571. const subMix0 = subMix[0];
  12572. const subMix1 = subMix[1];
  12573. const subMix2 = subMix[2];
  12574. const subMix3 = subMix[3];
  12575. const invSubMix = this.invSubMix;
  12576. const invSubMix0 = invSubMix[0];
  12577. const invSubMix1 = invSubMix[1];
  12578. const invSubMix2 = invSubMix[2];
  12579. const invSubMix3 = invSubMix[3];
  12580. const d2 = new Uint32Array(256);
  12581. let x = 0;
  12582. let xi = 0;
  12583. let i2 = 0;
  12584. for (i2 = 0; i2 < 256; i2++) {
  12585. if (i2 < 128) {
  12586. d2[i2] = i2 << 1;
  12587. } else {
  12588. d2[i2] = i2 << 1 ^ 283;
  12589. }
  12590. }
  12591. for (i2 = 0; i2 < 256; i2++) {
  12592. let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  12593. sx = sx >>> 8 ^ sx & 255 ^ 99;
  12594. sBox[x] = sx;
  12595. invSBox[sx] = x;
  12596. const x2 = d2[x];
  12597. const x4 = d2[x2];
  12598. const x8 = d2[x4];
  12599. let t2 = d2[sx] * 257 ^ sx * 16843008;
  12600. subMix0[x] = t2 << 24 | t2 >>> 8;
  12601. subMix1[x] = t2 << 16 | t2 >>> 16;
  12602. subMix2[x] = t2 << 8 | t2 >>> 24;
  12603. subMix3[x] = t2;
  12604. t2 = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008;
  12605. invSubMix0[sx] = t2 << 24 | t2 >>> 8;
  12606. invSubMix1[sx] = t2 << 16 | t2 >>> 16;
  12607. invSubMix2[sx] = t2 << 8 | t2 >>> 24;
  12608. invSubMix3[sx] = t2;
  12609. if (!x) {
  12610. x = xi = 1;
  12611. } else {
  12612. x = x2 ^ d2[d2[d2[x8 ^ x2]]];
  12613. xi ^= d2[d2[xi]];
  12614. }
  12615. }
  12616. }
  12617. expandKey(keyBuffer) {
  12618. const key = this.uint8ArrayToUint32Array_(keyBuffer);
  12619. let sameKey = true;
  12620. let offset = 0;
  12621. while (offset < key.length && sameKey) {
  12622. sameKey = key[offset] === this.key[offset];
  12623. offset++;
  12624. }
  12625. if (sameKey) {
  12626. return;
  12627. }
  12628. this.key = key;
  12629. const keySize = this.keySize = key.length;
  12630. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  12631. throw new Error("Invalid aes key size=" + keySize);
  12632. }
  12633. const ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  12634. let ksRow;
  12635. let invKsRow;
  12636. const keySchedule = this.keySchedule = new Uint32Array(ksRows);
  12637. const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  12638. const sbox = this.sBox;
  12639. const rcon = this.rcon;
  12640. const invSubMix = this.invSubMix;
  12641. const invSubMix0 = invSubMix[0];
  12642. const invSubMix1 = invSubMix[1];
  12643. const invSubMix2 = invSubMix[2];
  12644. const invSubMix3 = invSubMix[3];
  12645. let prev;
  12646. let t2;
  12647. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  12648. if (ksRow < keySize) {
  12649. prev = keySchedule[ksRow] = key[ksRow];
  12650. continue;
  12651. }
  12652. t2 = prev;
  12653. if (ksRow % keySize === 0) {
  12654. t2 = t2 << 8 | t2 >>> 24;
  12655. t2 = sbox[t2 >>> 24] << 24 | sbox[t2 >>> 16 & 255] << 16 | sbox[t2 >>> 8 & 255] << 8 | sbox[t2 & 255];
  12656. t2 ^= rcon[ksRow / keySize | 0] << 24;
  12657. } else if (keySize > 6 && ksRow % keySize === 4) {
  12658. t2 = sbox[t2 >>> 24] << 24 | sbox[t2 >>> 16 & 255] << 16 | sbox[t2 >>> 8 & 255] << 8 | sbox[t2 & 255];
  12659. }
  12660. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t2) >>> 0;
  12661. }
  12662. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  12663. ksRow = ksRows - invKsRow;
  12664. if (invKsRow & 3) {
  12665. t2 = keySchedule[ksRow];
  12666. } else {
  12667. t2 = keySchedule[ksRow - 4];
  12668. }
  12669. if (invKsRow < 4 || ksRow <= 4) {
  12670. invKeySchedule[invKsRow] = t2;
  12671. } else {
  12672. invKeySchedule[invKsRow] = invSubMix0[sbox[t2 >>> 24]] ^ invSubMix1[sbox[t2 >>> 16 & 255]] ^ invSubMix2[sbox[t2 >>> 8 & 255]] ^ invSubMix3[sbox[t2 & 255]];
  12673. }
  12674. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  12675. }
  12676. }
  12677. // Adding this as a method greatly improves performance.
  12678. networkToHostOrderSwap(word) {
  12679. return word << 24 | (word & 65280) << 8 | (word & 16711680) >> 8 | word >>> 24;
  12680. }
  12681. decrypt(inputArrayBuffer, offset, aesIV) {
  12682. const nRounds = this.keySize + 6;
  12683. const invKeySchedule = this.invKeySchedule;
  12684. const invSBOX = this.invSBox;
  12685. const invSubMix = this.invSubMix;
  12686. const invSubMix0 = invSubMix[0];
  12687. const invSubMix1 = invSubMix[1];
  12688. const invSubMix2 = invSubMix[2];
  12689. const invSubMix3 = invSubMix[3];
  12690. const initVector = this.uint8ArrayToUint32Array_(aesIV);
  12691. let initVector0 = initVector[0];
  12692. let initVector1 = initVector[1];
  12693. let initVector2 = initVector[2];
  12694. let initVector3 = initVector[3];
  12695. const inputInt32 = new Int32Array(inputArrayBuffer);
  12696. const outputInt32 = new Int32Array(inputInt32.length);
  12697. let t0, t1, t2, t3;
  12698. let s0, s1, s2, s3;
  12699. let inputWords0, inputWords1, inputWords2, inputWords3;
  12700. let ksRow, i2;
  12701. const swapWord = this.networkToHostOrderSwap;
  12702. while (offset < inputInt32.length) {
  12703. inputWords0 = swapWord(inputInt32[offset]);
  12704. inputWords1 = swapWord(inputInt32[offset + 1]);
  12705. inputWords2 = swapWord(inputInt32[offset + 2]);
  12706. inputWords3 = swapWord(inputInt32[offset + 3]);
  12707. s0 = inputWords0 ^ invKeySchedule[0];
  12708. s1 = inputWords3 ^ invKeySchedule[1];
  12709. s2 = inputWords2 ^ invKeySchedule[2];
  12710. s3 = inputWords1 ^ invKeySchedule[3];
  12711. ksRow = 4;
  12712. for (i2 = 1; i2 < nRounds; i2++) {
  12713. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 255] ^ invSubMix2[s2 >> 8 & 255] ^ invSubMix3[s3 & 255] ^ invKeySchedule[ksRow];
  12714. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 255] ^ invSubMix2[s3 >> 8 & 255] ^ invSubMix3[s0 & 255] ^ invKeySchedule[ksRow + 1];
  12715. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 255] ^ invSubMix2[s0 >> 8 & 255] ^ invSubMix3[s1 & 255] ^ invKeySchedule[ksRow + 2];
  12716. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 255] ^ invSubMix2[s1 >> 8 & 255] ^ invSubMix3[s2 & 255] ^ invKeySchedule[ksRow + 3];
  12717. s0 = t0;
  12718. s1 = t1;
  12719. s2 = t2;
  12720. s3 = t3;
  12721. ksRow = ksRow + 4;
  12722. }
  12723. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 255] << 16 ^ invSBOX[s2 >> 8 & 255] << 8 ^ invSBOX[s3 & 255] ^ invKeySchedule[ksRow];
  12724. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 255] << 16 ^ invSBOX[s3 >> 8 & 255] << 8 ^ invSBOX[s0 & 255] ^ invKeySchedule[ksRow + 1];
  12725. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 255] << 16 ^ invSBOX[s0 >> 8 & 255] << 8 ^ invSBOX[s1 & 255] ^ invKeySchedule[ksRow + 2];
  12726. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 255] << 16 ^ invSBOX[s1 >> 8 & 255] << 8 ^ invSBOX[s2 & 255] ^ invKeySchedule[ksRow + 3];
  12727. outputInt32[offset] = swapWord(t0 ^ initVector0);
  12728. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  12729. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  12730. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  12731. initVector0 = inputWords0;
  12732. initVector1 = inputWords1;
  12733. initVector2 = inputWords2;
  12734. initVector3 = inputWords3;
  12735. offset = offset + 4;
  12736. }
  12737. return outputInt32.buffer;
  12738. }
  12739. }
  12740. class FastAESKey {
  12741. constructor(subtle, key, aesMode) {
  12742. this.subtle = void 0;
  12743. this.key = void 0;
  12744. this.aesMode = void 0;
  12745. this.subtle = subtle;
  12746. this.key = key;
  12747. this.aesMode = aesMode;
  12748. }
  12749. expandKey() {
  12750. const subtleAlgoName = getSubtleAlgoName(this.aesMode);
  12751. return this.subtle.importKey("raw", this.key, {
  12752. name: subtleAlgoName
  12753. }, false, ["encrypt", "decrypt"]);
  12754. }
  12755. }
  12756. function getSubtleAlgoName(aesMode) {
  12757. switch (aesMode) {
  12758. case DecrypterAesMode.cbc:
  12759. return "AES-CBC";
  12760. case DecrypterAesMode.ctr:
  12761. return "AES-CTR";
  12762. default:
  12763. throw new Error(`[FastAESKey] invalid aes mode ${aesMode}`);
  12764. }
  12765. }
  12766. const CHUNK_SIZE = 16;
  12767. class Decrypter {
  12768. constructor(config, {
  12769. removePKCS7Padding = true
  12770. } = {}) {
  12771. this.logEnabled = true;
  12772. this.removePKCS7Padding = void 0;
  12773. this.subtle = null;
  12774. this.softwareDecrypter = null;
  12775. this.key = null;
  12776. this.fastAesKey = null;
  12777. this.remainderData = null;
  12778. this.currentIV = null;
  12779. this.currentResult = null;
  12780. this.useSoftware = void 0;
  12781. this.enableSoftwareAES = void 0;
  12782. this.enableSoftwareAES = config.enableSoftwareAES;
  12783. this.removePKCS7Padding = removePKCS7Padding;
  12784. if (removePKCS7Padding) {
  12785. try {
  12786. const browserCrypto = self.crypto;
  12787. if (browserCrypto) {
  12788. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  12789. }
  12790. } catch (e2) {
  12791. }
  12792. }
  12793. this.useSoftware = !this.subtle;
  12794. }
  12795. destroy() {
  12796. this.subtle = null;
  12797. this.softwareDecrypter = null;
  12798. this.key = null;
  12799. this.fastAesKey = null;
  12800. this.remainderData = null;
  12801. this.currentIV = null;
  12802. this.currentResult = null;
  12803. }
  12804. isSync() {
  12805. return this.useSoftware;
  12806. }
  12807. flush() {
  12808. const {
  12809. currentResult,
  12810. remainderData
  12811. } = this;
  12812. if (!currentResult || remainderData) {
  12813. this.reset();
  12814. return null;
  12815. }
  12816. const data = new Uint8Array(currentResult);
  12817. this.reset();
  12818. if (this.removePKCS7Padding) {
  12819. return removePadding(data);
  12820. }
  12821. return data;
  12822. }
  12823. reset() {
  12824. this.currentResult = null;
  12825. this.currentIV = null;
  12826. this.remainderData = null;
  12827. if (this.softwareDecrypter) {
  12828. this.softwareDecrypter = null;
  12829. }
  12830. }
  12831. decrypt(data, key, iv, aesMode) {
  12832. if (this.useSoftware) {
  12833. return new Promise((resolve2, reject) => {
  12834. const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
  12835. this.softwareDecrypt(dataView, key, iv, aesMode);
  12836. const decryptResult = this.flush();
  12837. if (decryptResult) {
  12838. resolve2(decryptResult.buffer);
  12839. } else {
  12840. reject(new Error("[softwareDecrypt] Failed to decrypt data"));
  12841. }
  12842. });
  12843. }
  12844. return this.webCryptoDecrypt(new Uint8Array(data), key, iv, aesMode);
  12845. }
  12846. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  12847. // data is handled in the flush() call
  12848. softwareDecrypt(data, key, iv, aesMode) {
  12849. const {
  12850. currentIV,
  12851. currentResult,
  12852. remainderData
  12853. } = this;
  12854. if (aesMode !== DecrypterAesMode.cbc || key.byteLength !== 16) {
  12855. logger.warn("SoftwareDecrypt: can only handle AES-128-CBC");
  12856. return null;
  12857. }
  12858. this.logOnce("JS AES decrypt");
  12859. if (remainderData) {
  12860. data = appendUint8Array(remainderData, data);
  12861. this.remainderData = null;
  12862. }
  12863. const currentChunk = this.getValidChunk(data);
  12864. if (!currentChunk.length) {
  12865. return null;
  12866. }
  12867. if (currentIV) {
  12868. iv = currentIV;
  12869. }
  12870. let softwareDecrypter = this.softwareDecrypter;
  12871. if (!softwareDecrypter) {
  12872. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  12873. }
  12874. softwareDecrypter.expandKey(key);
  12875. const result = currentResult;
  12876. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  12877. this.currentIV = currentChunk.slice(-16).buffer;
  12878. if (!result) {
  12879. return null;
  12880. }
  12881. return result;
  12882. }
  12883. webCryptoDecrypt(data, key, iv, aesMode) {
  12884. if (this.key !== key || !this.fastAesKey) {
  12885. if (!this.subtle) {
  12886. return Promise.resolve(this.onWebCryptoError(data, key, iv, aesMode));
  12887. }
  12888. this.key = key;
  12889. this.fastAesKey = new FastAESKey(this.subtle, key, aesMode);
  12890. }
  12891. return this.fastAesKey.expandKey().then((aesKey) => {
  12892. if (!this.subtle) {
  12893. return Promise.reject(new Error("web crypto not initialized"));
  12894. }
  12895. this.logOnce("WebCrypto AES decrypt");
  12896. const crypto2 = new AESCrypto(this.subtle, new Uint8Array(iv), aesMode);
  12897. return crypto2.decrypt(data.buffer, aesKey);
  12898. }).catch((err) => {
  12899. logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);
  12900. return this.onWebCryptoError(data, key, iv, aesMode);
  12901. });
  12902. }
  12903. onWebCryptoError(data, key, iv, aesMode) {
  12904. const enableSoftwareAES = this.enableSoftwareAES;
  12905. if (enableSoftwareAES) {
  12906. this.useSoftware = true;
  12907. this.logEnabled = true;
  12908. this.softwareDecrypt(data, key, iv, aesMode);
  12909. const decryptResult = this.flush();
  12910. if (decryptResult) {
  12911. return decryptResult.buffer;
  12912. }
  12913. }
  12914. throw new Error("WebCrypto" + (enableSoftwareAES ? " and softwareDecrypt" : "") + ": failed to decrypt data");
  12915. }
  12916. getValidChunk(data) {
  12917. let currentChunk = data;
  12918. const splitPoint = data.length - data.length % CHUNK_SIZE;
  12919. if (splitPoint !== data.length) {
  12920. currentChunk = data.slice(0, splitPoint);
  12921. this.remainderData = data.slice(splitPoint);
  12922. }
  12923. return currentChunk;
  12924. }
  12925. logOnce(msg) {
  12926. if (!this.logEnabled) {
  12927. return;
  12928. }
  12929. logger.log(`[decrypter]: ${msg}`);
  12930. this.logEnabled = false;
  12931. }
  12932. }
  12933. const MIN_CHUNK_SIZE = Math.pow(2, 17);
  12934. class FragmentLoader {
  12935. constructor(config) {
  12936. this.config = void 0;
  12937. this.loader = null;
  12938. this.partLoadTimeout = -1;
  12939. this.config = config;
  12940. }
  12941. destroy() {
  12942. if (this.loader) {
  12943. this.loader.destroy();
  12944. this.loader = null;
  12945. }
  12946. }
  12947. abort() {
  12948. if (this.loader) {
  12949. this.loader.abort();
  12950. }
  12951. }
  12952. load(frag, onProgress) {
  12953. const url = frag.url;
  12954. if (!url) {
  12955. return Promise.reject(new LoadError({
  12956. type: ErrorTypes.NETWORK_ERROR,
  12957. details: ErrorDetails.FRAG_LOAD_ERROR,
  12958. fatal: false,
  12959. frag,
  12960. error: new Error(`Fragment does not have a ${url ? "part list" : "url"}`),
  12961. networkDetails: null
  12962. }));
  12963. }
  12964. this.abort();
  12965. const config = this.config;
  12966. const FragmentILoader = config.fLoader;
  12967. const DefaultILoader = config.loader;
  12968. return new Promise((resolve2, reject) => {
  12969. if (this.loader) {
  12970. this.loader.destroy();
  12971. }
  12972. if (frag.gap) {
  12973. if (frag.tagList.some((tags) => tags[0] === "GAP")) {
  12974. reject(createGapLoadError(frag));
  12975. return;
  12976. } else {
  12977. frag.gap = false;
  12978. }
  12979. }
  12980. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  12981. const loaderContext = createLoaderContext(frag);
  12982. frag.loader = loader;
  12983. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  12984. const loaderConfig = {
  12985. loadPolicy,
  12986. timeout: loadPolicy.maxLoadTimeMs,
  12987. maxRetry: 0,
  12988. retryDelay: 0,
  12989. maxRetryDelay: 0,
  12990. highWaterMark: frag.sn === "initSegment" ? Infinity : MIN_CHUNK_SIZE
  12991. };
  12992. frag.stats = loader.stats;
  12993. const callbacks = {
  12994. onSuccess: (response, stats, context, networkDetails) => {
  12995. this.resetLoader(frag, loader);
  12996. let payload = response.data;
  12997. if (context.resetIV && frag.decryptdata) {
  12998. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  12999. payload = payload.slice(16);
  13000. }
  13001. resolve2({
  13002. frag,
  13003. part: null,
  13004. payload,
  13005. networkDetails
  13006. });
  13007. },
  13008. onError: (response, context, networkDetails, stats) => {
  13009. this.resetLoader(frag, loader);
  13010. reject(new LoadError({
  13011. type: ErrorTypes.NETWORK_ERROR,
  13012. details: ErrorDetails.FRAG_LOAD_ERROR,
  13013. fatal: false,
  13014. frag,
  13015. response: _objectSpread2({
  13016. url,
  13017. data: void 0
  13018. }, response),
  13019. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  13020. networkDetails,
  13021. stats
  13022. }));
  13023. },
  13024. onAbort: (stats, context, networkDetails) => {
  13025. this.resetLoader(frag, loader);
  13026. reject(new LoadError({
  13027. type: ErrorTypes.NETWORK_ERROR,
  13028. details: ErrorDetails.INTERNAL_ABORTED,
  13029. fatal: false,
  13030. frag,
  13031. error: new Error("Aborted"),
  13032. networkDetails,
  13033. stats
  13034. }));
  13035. },
  13036. onTimeout: (stats, context, networkDetails) => {
  13037. this.resetLoader(frag, loader);
  13038. reject(new LoadError({
  13039. type: ErrorTypes.NETWORK_ERROR,
  13040. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  13041. fatal: false,
  13042. frag,
  13043. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  13044. networkDetails,
  13045. stats
  13046. }));
  13047. }
  13048. };
  13049. if (onProgress) {
  13050. callbacks.onProgress = (stats, context, data, networkDetails) => onProgress({
  13051. frag,
  13052. part: null,
  13053. payload: data,
  13054. networkDetails
  13055. });
  13056. }
  13057. loader.load(loaderContext, loaderConfig, callbacks);
  13058. });
  13059. }
  13060. loadPart(frag, part, onProgress) {
  13061. this.abort();
  13062. const config = this.config;
  13063. const FragmentILoader = config.fLoader;
  13064. const DefaultILoader = config.loader;
  13065. return new Promise((resolve2, reject) => {
  13066. if (this.loader) {
  13067. this.loader.destroy();
  13068. }
  13069. if (frag.gap || part.gap) {
  13070. reject(createGapLoadError(frag, part));
  13071. return;
  13072. }
  13073. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  13074. const loaderContext = createLoaderContext(frag, part);
  13075. frag.loader = loader;
  13076. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  13077. const loaderConfig = {
  13078. loadPolicy,
  13079. timeout: loadPolicy.maxLoadTimeMs,
  13080. maxRetry: 0,
  13081. retryDelay: 0,
  13082. maxRetryDelay: 0,
  13083. highWaterMark: MIN_CHUNK_SIZE
  13084. };
  13085. part.stats = loader.stats;
  13086. loader.load(loaderContext, loaderConfig, {
  13087. onSuccess: (response, stats, context, networkDetails) => {
  13088. this.resetLoader(frag, loader);
  13089. this.updateStatsFromPart(frag, part);
  13090. const partLoadedData = {
  13091. frag,
  13092. part,
  13093. payload: response.data,
  13094. networkDetails
  13095. };
  13096. onProgress(partLoadedData);
  13097. resolve2(partLoadedData);
  13098. },
  13099. onError: (response, context, networkDetails, stats) => {
  13100. this.resetLoader(frag, loader);
  13101. reject(new LoadError({
  13102. type: ErrorTypes.NETWORK_ERROR,
  13103. details: ErrorDetails.FRAG_LOAD_ERROR,
  13104. fatal: false,
  13105. frag,
  13106. part,
  13107. response: _objectSpread2({
  13108. url: loaderContext.url,
  13109. data: void 0
  13110. }, response),
  13111. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  13112. networkDetails,
  13113. stats
  13114. }));
  13115. },
  13116. onAbort: (stats, context, networkDetails) => {
  13117. frag.stats.aborted = part.stats.aborted;
  13118. this.resetLoader(frag, loader);
  13119. reject(new LoadError({
  13120. type: ErrorTypes.NETWORK_ERROR,
  13121. details: ErrorDetails.INTERNAL_ABORTED,
  13122. fatal: false,
  13123. frag,
  13124. part,
  13125. error: new Error("Aborted"),
  13126. networkDetails,
  13127. stats
  13128. }));
  13129. },
  13130. onTimeout: (stats, context, networkDetails) => {
  13131. this.resetLoader(frag, loader);
  13132. reject(new LoadError({
  13133. type: ErrorTypes.NETWORK_ERROR,
  13134. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  13135. fatal: false,
  13136. frag,
  13137. part,
  13138. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  13139. networkDetails,
  13140. stats
  13141. }));
  13142. }
  13143. });
  13144. });
  13145. }
  13146. updateStatsFromPart(frag, part) {
  13147. const fragStats = frag.stats;
  13148. const partStats = part.stats;
  13149. const partTotal = partStats.total;
  13150. fragStats.loaded += partStats.loaded;
  13151. if (partTotal) {
  13152. const estTotalParts = Math.round(frag.duration / part.duration);
  13153. const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  13154. const estRemainingParts = estTotalParts - estLoadedParts;
  13155. const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  13156. fragStats.total = fragStats.loaded + estRemainingBytes;
  13157. } else {
  13158. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  13159. }
  13160. const fragLoading = fragStats.loading;
  13161. const partLoading = partStats.loading;
  13162. if (fragLoading.start) {
  13163. fragLoading.first += partLoading.first - partLoading.start;
  13164. } else {
  13165. fragLoading.start = partLoading.start;
  13166. fragLoading.first = partLoading.first;
  13167. }
  13168. fragLoading.end = partLoading.end;
  13169. }
  13170. resetLoader(frag, loader) {
  13171. frag.loader = null;
  13172. if (this.loader === loader) {
  13173. self.clearTimeout(this.partLoadTimeout);
  13174. this.loader = null;
  13175. }
  13176. loader.destroy();
  13177. }
  13178. }
  13179. function createLoaderContext(frag, part = null) {
  13180. const segment = part || frag;
  13181. const loaderContext = {
  13182. frag,
  13183. part,
  13184. responseType: "arraybuffer",
  13185. url: segment.url,
  13186. headers: {},
  13187. rangeStart: 0,
  13188. rangeEnd: 0
  13189. };
  13190. const start = segment.byteRangeStartOffset;
  13191. const end = segment.byteRangeEndOffset;
  13192. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  13193. var _frag$decryptdata;
  13194. let byteRangeStart = start;
  13195. let byteRangeEnd = end;
  13196. if (frag.sn === "initSegment" && isMethodFullSegmentAesCbc((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method)) {
  13197. const fragmentLen = end - start;
  13198. if (fragmentLen % 16) {
  13199. byteRangeEnd = end + (16 - fragmentLen % 16);
  13200. }
  13201. if (start !== 0) {
  13202. loaderContext.resetIV = true;
  13203. byteRangeStart = start - 16;
  13204. }
  13205. }
  13206. loaderContext.rangeStart = byteRangeStart;
  13207. loaderContext.rangeEnd = byteRangeEnd;
  13208. }
  13209. return loaderContext;
  13210. }
  13211. function createGapLoadError(frag, part) {
  13212. const error = new Error(`GAP ${frag.gap ? "tag" : "attribute"} found`);
  13213. const errorData = {
  13214. type: ErrorTypes.MEDIA_ERROR,
  13215. details: ErrorDetails.FRAG_GAP,
  13216. fatal: false,
  13217. frag,
  13218. error,
  13219. networkDetails: null
  13220. };
  13221. if (part) {
  13222. errorData.part = part;
  13223. }
  13224. (part ? part : frag).stats.aborted = true;
  13225. return new LoadError(errorData);
  13226. }
  13227. function isMethodFullSegmentAesCbc(method) {
  13228. return method === "AES-128" || method === "AES-256";
  13229. }
  13230. class LoadError extends Error {
  13231. constructor(data) {
  13232. super(data.error.message);
  13233. this.data = void 0;
  13234. this.data = data;
  13235. }
  13236. }
  13237. class TaskLoop extends Logger {
  13238. constructor(label, logger2) {
  13239. super(label, logger2);
  13240. this._boundTick = void 0;
  13241. this._tickTimer = null;
  13242. this._tickInterval = null;
  13243. this._tickCallCount = 0;
  13244. this._boundTick = this.tick.bind(this);
  13245. }
  13246. destroy() {
  13247. this.onHandlerDestroying();
  13248. this.onHandlerDestroyed();
  13249. }
  13250. onHandlerDestroying() {
  13251. this.clearNextTick();
  13252. this.clearInterval();
  13253. }
  13254. onHandlerDestroyed() {
  13255. }
  13256. hasInterval() {
  13257. return !!this._tickInterval;
  13258. }
  13259. hasNextTick() {
  13260. return !!this._tickTimer;
  13261. }
  13262. /**
  13263. * @param millis - Interval time (ms)
  13264. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  13265. */
  13266. setInterval(millis) {
  13267. if (!this._tickInterval) {
  13268. this._tickCallCount = 0;
  13269. this._tickInterval = self.setInterval(this._boundTick, millis);
  13270. return true;
  13271. }
  13272. return false;
  13273. }
  13274. /**
  13275. * @returns True when interval was cleared, false when none was set (no effect)
  13276. */
  13277. clearInterval() {
  13278. if (this._tickInterval) {
  13279. self.clearInterval(this._tickInterval);
  13280. this._tickInterval = null;
  13281. return true;
  13282. }
  13283. return false;
  13284. }
  13285. /**
  13286. * @returns True when timeout was cleared, false when none was set (no effect)
  13287. */
  13288. clearNextTick() {
  13289. if (this._tickTimer) {
  13290. self.clearTimeout(this._tickTimer);
  13291. this._tickTimer = null;
  13292. return true;
  13293. }
  13294. return false;
  13295. }
  13296. /**
  13297. * Will call the subclass doTick implementation in this main loop tick
  13298. * or in the next one (via setTimeout(,0)) in case it has already been called
  13299. * in this tick (in case this is a re-entrant call).
  13300. */
  13301. tick() {
  13302. this._tickCallCount++;
  13303. if (this._tickCallCount === 1) {
  13304. this.doTick();
  13305. if (this._tickCallCount > 1) {
  13306. this.tickImmediate();
  13307. }
  13308. this._tickCallCount = 0;
  13309. }
  13310. }
  13311. tickImmediate() {
  13312. this.clearNextTick();
  13313. this._tickTimer = self.setTimeout(this._boundTick, 0);
  13314. }
  13315. /**
  13316. * For subclass to implement task logic
  13317. * @abstract
  13318. */
  13319. doTick() {
  13320. }
  13321. }
  13322. class ChunkMetadata {
  13323. constructor(level, sn2, id, size2 = 0, part = -1, partial2 = false) {
  13324. this.level = void 0;
  13325. this.sn = void 0;
  13326. this.part = void 0;
  13327. this.id = void 0;
  13328. this.size = void 0;
  13329. this.partial = void 0;
  13330. this.transmuxing = getNewPerformanceTiming();
  13331. this.buffering = {
  13332. audio: getNewPerformanceTiming(),
  13333. video: getNewPerformanceTiming(),
  13334. audiovideo: getNewPerformanceTiming()
  13335. };
  13336. this.level = level;
  13337. this.sn = sn2;
  13338. this.id = id;
  13339. this.size = size2;
  13340. this.part = part;
  13341. this.partial = partial2;
  13342. }
  13343. }
  13344. function getNewPerformanceTiming() {
  13345. return {
  13346. start: 0,
  13347. executeStart: 0,
  13348. executeEnd: 0,
  13349. end: 0
  13350. };
  13351. }
  13352. const noopBuffered = {
  13353. length: 0,
  13354. start: () => 0,
  13355. end: () => 0
  13356. };
  13357. class BufferHelper {
  13358. /**
  13359. * Return true if `media`'s buffered include `position`
  13360. */
  13361. static isBuffered(media, position) {
  13362. if (media) {
  13363. const buffered = BufferHelper.getBuffered(media);
  13364. for (let i2 = buffered.length; i2--; ) {
  13365. if (position >= buffered.start(i2) && position <= buffered.end(i2)) {
  13366. return true;
  13367. }
  13368. }
  13369. }
  13370. return false;
  13371. }
  13372. static bufferedRanges(media) {
  13373. if (media) {
  13374. const timeRanges = BufferHelper.getBuffered(media);
  13375. return BufferHelper.timeRangesToArray(timeRanges);
  13376. }
  13377. return [];
  13378. }
  13379. static timeRangesToArray(timeRanges) {
  13380. const buffered = [];
  13381. for (let i2 = 0; i2 < timeRanges.length; i2++) {
  13382. buffered.push({
  13383. start: timeRanges.start(i2),
  13384. end: timeRanges.end(i2)
  13385. });
  13386. }
  13387. return buffered;
  13388. }
  13389. static bufferInfo(media, pos, maxHoleDuration) {
  13390. if (media) {
  13391. const buffered = BufferHelper.bufferedRanges(media);
  13392. if (buffered.length) {
  13393. return BufferHelper.bufferedInfo(buffered, pos, maxHoleDuration);
  13394. }
  13395. }
  13396. return {
  13397. len: 0,
  13398. start: pos,
  13399. end: pos,
  13400. bufferedIndex: -1
  13401. };
  13402. }
  13403. static bufferedInfo(buffered, pos, maxHoleDuration) {
  13404. pos = Math.max(0, pos);
  13405. if (buffered.length > 1) {
  13406. buffered.sort((a2, b2) => a2.start - b2.start || b2.end - a2.end);
  13407. }
  13408. let bufferedIndex = -1;
  13409. let buffered2 = [];
  13410. if (maxHoleDuration) {
  13411. for (let i2 = 0; i2 < buffered.length; i2++) {
  13412. if (pos >= buffered[i2].start && pos <= buffered[i2].end) {
  13413. bufferedIndex = i2;
  13414. }
  13415. const buf2len = buffered2.length;
  13416. if (buf2len) {
  13417. const buf2end = buffered2[buf2len - 1].end;
  13418. if (buffered[i2].start - buf2end < maxHoleDuration) {
  13419. if (buffered[i2].end > buf2end) {
  13420. buffered2[buf2len - 1].end = buffered[i2].end;
  13421. }
  13422. } else {
  13423. buffered2.push(buffered[i2]);
  13424. }
  13425. } else {
  13426. buffered2.push(buffered[i2]);
  13427. }
  13428. }
  13429. } else {
  13430. buffered2 = buffered;
  13431. }
  13432. let bufferLen = 0;
  13433. let nextStart;
  13434. let bufferStart = pos;
  13435. let bufferEnd = pos;
  13436. for (let i2 = 0; i2 < buffered2.length; i2++) {
  13437. const start = buffered2[i2].start;
  13438. const end = buffered2[i2].end;
  13439. if (bufferedIndex === -1 && pos >= start && pos <= end) {
  13440. bufferedIndex = i2;
  13441. }
  13442. if (pos + maxHoleDuration >= start && pos < end) {
  13443. bufferStart = start;
  13444. bufferEnd = end;
  13445. bufferLen = bufferEnd - pos;
  13446. } else if (pos + maxHoleDuration < start) {
  13447. nextStart = start;
  13448. break;
  13449. }
  13450. }
  13451. return {
  13452. len: bufferLen,
  13453. start: bufferStart || 0,
  13454. end: bufferEnd || 0,
  13455. nextStart,
  13456. buffered,
  13457. bufferedIndex
  13458. };
  13459. }
  13460. /**
  13461. * Safe method to get buffered property.
  13462. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  13463. */
  13464. static getBuffered(media) {
  13465. try {
  13466. return media.buffered || noopBuffered;
  13467. } catch (e2) {
  13468. logger.log("failed to get media.buffered", e2);
  13469. return noopBuffered;
  13470. }
  13471. }
  13472. }
  13473. const VARIABLE_REPLACEMENT_REGEX = /\{\$([a-zA-Z0-9-_]+)\}/g;
  13474. function hasVariableReferences(str) {
  13475. return VARIABLE_REPLACEMENT_REGEX.test(str);
  13476. }
  13477. function substituteVariables(parsed, value) {
  13478. if (parsed.variableList !== null || parsed.hasVariableRefs) {
  13479. const variableList = parsed.variableList;
  13480. return value.replace(VARIABLE_REPLACEMENT_REGEX, (variableReference) => {
  13481. const variableName = variableReference.substring(2, variableReference.length - 1);
  13482. const variableValue = variableList == null ? void 0 : variableList[variableName];
  13483. if (variableValue === void 0) {
  13484. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${variableName}"`));
  13485. return variableReference;
  13486. }
  13487. return variableValue;
  13488. });
  13489. }
  13490. return value;
  13491. }
  13492. function addVariableDefinition(parsed, attr, parentUrl) {
  13493. let variableList = parsed.variableList;
  13494. if (!variableList) {
  13495. parsed.variableList = variableList = {};
  13496. }
  13497. let NAME;
  13498. let VALUE;
  13499. if ("QUERYPARAM" in attr) {
  13500. NAME = attr.QUERYPARAM;
  13501. try {
  13502. const searchParams = new self.URL(parentUrl).searchParams;
  13503. if (searchParams.has(NAME)) {
  13504. VALUE = searchParams.get(NAME);
  13505. } else {
  13506. throw new Error(`"${NAME}" does not match any query parameter in URI: "${parentUrl}"`);
  13507. }
  13508. } catch (error) {
  13509. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${error.message}`));
  13510. }
  13511. } else {
  13512. NAME = attr.NAME;
  13513. VALUE = attr.VALUE;
  13514. }
  13515. if (NAME in variableList) {
  13516. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${NAME}"`));
  13517. } else {
  13518. variableList[NAME] = VALUE || "";
  13519. }
  13520. }
  13521. function importVariableDefinition(parsed, attr, sourceVariableList) {
  13522. const IMPORT = attr.IMPORT;
  13523. if (sourceVariableList && IMPORT in sourceVariableList) {
  13524. let variableList = parsed.variableList;
  13525. if (!variableList) {
  13526. parsed.variableList = variableList = {};
  13527. }
  13528. variableList[IMPORT] = sourceVariableList[IMPORT];
  13529. } else {
  13530. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${IMPORT}"`));
  13531. }
  13532. }
  13533. const DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  13534. const ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  13535. class AttrList {
  13536. constructor(attrs, parsed) {
  13537. if (typeof attrs === "string") {
  13538. attrs = AttrList.parseAttrList(attrs, parsed);
  13539. }
  13540. _extends(this, attrs);
  13541. }
  13542. get clientAttrs() {
  13543. return Object.keys(this).filter((attr) => attr.substring(0, 2) === "X-");
  13544. }
  13545. decimalInteger(attrName) {
  13546. const intValue = parseInt(this[attrName], 10);
  13547. if (intValue > Number.MAX_SAFE_INTEGER) {
  13548. return Infinity;
  13549. }
  13550. return intValue;
  13551. }
  13552. hexadecimalInteger(attrName) {
  13553. if (this[attrName]) {
  13554. let stringValue = (this[attrName] || "0x").slice(2);
  13555. stringValue = (stringValue.length & 1 ? "0" : "") + stringValue;
  13556. const value = new Uint8Array(stringValue.length / 2);
  13557. for (let i2 = 0; i2 < stringValue.length / 2; i2++) {
  13558. value[i2] = parseInt(stringValue.slice(i2 * 2, i2 * 2 + 2), 16);
  13559. }
  13560. return value;
  13561. }
  13562. return null;
  13563. }
  13564. hexadecimalIntegerAsNumber(attrName) {
  13565. const intValue = parseInt(this[attrName], 16);
  13566. if (intValue > Number.MAX_SAFE_INTEGER) {
  13567. return Infinity;
  13568. }
  13569. return intValue;
  13570. }
  13571. decimalFloatingPoint(attrName) {
  13572. return parseFloat(this[attrName]);
  13573. }
  13574. optionalFloat(attrName, defaultValue) {
  13575. const value = this[attrName];
  13576. return value ? parseFloat(value) : defaultValue;
  13577. }
  13578. enumeratedString(attrName) {
  13579. return this[attrName];
  13580. }
  13581. enumeratedStringList(attrName, dict) {
  13582. const attrValue = this[attrName];
  13583. return (attrValue ? attrValue.split(/[ ,]+/) : []).reduce((result, identifier) => {
  13584. result[identifier.toLowerCase()] = true;
  13585. return result;
  13586. }, dict);
  13587. }
  13588. bool(attrName) {
  13589. return this[attrName] === "YES";
  13590. }
  13591. decimalResolution(attrName) {
  13592. const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  13593. if (res === null) {
  13594. return void 0;
  13595. }
  13596. return {
  13597. width: parseInt(res[1], 10),
  13598. height: parseInt(res[2], 10)
  13599. };
  13600. }
  13601. static parseAttrList(input, parsed) {
  13602. let match;
  13603. const attrs = {};
  13604. const quote = '"';
  13605. ATTR_LIST_REGEX.lastIndex = 0;
  13606. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  13607. const name = match[1].trim();
  13608. let value = match[2];
  13609. const quotedString = value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1;
  13610. let hexadecimalSequence = false;
  13611. if (quotedString) {
  13612. value = value.slice(1, -1);
  13613. } else {
  13614. switch (name) {
  13615. case "IV":
  13616. case "SCTE35-CMD":
  13617. case "SCTE35-IN":
  13618. case "SCTE35-OUT":
  13619. hexadecimalSequence = true;
  13620. }
  13621. }
  13622. if (parsed && (quotedString || hexadecimalSequence)) {
  13623. {
  13624. value = substituteVariables(parsed, value);
  13625. }
  13626. } else if (!hexadecimalSequence && !quotedString) {
  13627. switch (name) {
  13628. case "CLOSED-CAPTIONS":
  13629. if (value === "NONE") {
  13630. break;
  13631. }
  13632. case "ALLOWED-CPC":
  13633. case "CLASS":
  13634. case "ASSOC-LANGUAGE":
  13635. case "AUDIO":
  13636. case "BYTERANGE":
  13637. case "CHANNELS":
  13638. case "CHARACTERISTICS":
  13639. case "CODECS":
  13640. case "DATA-ID":
  13641. case "END-DATE":
  13642. case "GROUP-ID":
  13643. case "ID":
  13644. case "IMPORT":
  13645. case "INSTREAM-ID":
  13646. case "KEYFORMAT":
  13647. case "KEYFORMATVERSIONS":
  13648. case "LANGUAGE":
  13649. case "NAME":
  13650. case "PATHWAY-ID":
  13651. case "QUERYPARAM":
  13652. case "RECENTLY-REMOVED-DATERANGES":
  13653. case "SERVER-URI":
  13654. case "STABLE-RENDITION-ID":
  13655. case "STABLE-VARIANT-ID":
  13656. case "START-DATE":
  13657. case "SUBTITLES":
  13658. case "SUPPLEMENTAL-CODECS":
  13659. case "URI":
  13660. case "VALUE":
  13661. case "VIDEO":
  13662. case "X-ASSET-LIST":
  13663. case "X-ASSET-URI":
  13664. logger.warn(`${input}: attribute ${name} is missing quotes`);
  13665. }
  13666. }
  13667. attrs[name] = value;
  13668. }
  13669. return attrs;
  13670. }
  13671. }
  13672. const CLASS_INTERSTITIAL = "com.apple.hls.interstitial";
  13673. function isDateRangeCueAttribute(attrName) {
  13674. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "CUE" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  13675. }
  13676. function isSCTE35Attribute(attrName) {
  13677. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN" || attrName === "SCTE35-CMD";
  13678. }
  13679. class DateRange {
  13680. constructor(dateRangeAttr, dateRangeWithSameId, tagCount = 0) {
  13681. var _dateRangeWithSameId$;
  13682. this.attr = void 0;
  13683. this.tagAnchor = void 0;
  13684. this.tagOrder = void 0;
  13685. this._startDate = void 0;
  13686. this._endDate = void 0;
  13687. this._dateAtEnd = void 0;
  13688. this._cue = void 0;
  13689. this._badValueForSameId = void 0;
  13690. this.tagAnchor = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagAnchor) || null;
  13691. this.tagOrder = (_dateRangeWithSameId$ = dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagOrder) != null ? _dateRangeWithSameId$ : tagCount;
  13692. if (dateRangeWithSameId) {
  13693. const previousAttr = dateRangeWithSameId.attr;
  13694. for (const key in previousAttr) {
  13695. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  13696. logger.warn(`DATERANGE tag attribute: "${key}" does not match for tags with ID: "${dateRangeAttr.ID}"`);
  13697. this._badValueForSameId = key;
  13698. break;
  13699. }
  13700. }
  13701. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  13702. }
  13703. this.attr = dateRangeAttr;
  13704. if (dateRangeWithSameId) {
  13705. this._startDate = dateRangeWithSameId._startDate;
  13706. this._cue = dateRangeWithSameId._cue;
  13707. this._endDate = dateRangeWithSameId._endDate;
  13708. this._dateAtEnd = dateRangeWithSameId._dateAtEnd;
  13709. } else {
  13710. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  13711. }
  13712. if ("END-DATE" in this.attr) {
  13713. const endDate = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.endDate) || new Date(this.attr["END-DATE"]);
  13714. if (isFiniteNumber(endDate.getTime())) {
  13715. this._endDate = endDate;
  13716. }
  13717. }
  13718. }
  13719. get id() {
  13720. return this.attr.ID;
  13721. }
  13722. get class() {
  13723. return this.attr.CLASS;
  13724. }
  13725. get cue() {
  13726. const _cue = this._cue;
  13727. if (_cue === void 0) {
  13728. return this._cue = this.attr.enumeratedStringList(this.attr.CUE ? "CUE" : "X-CUE", {
  13729. pre: false,
  13730. post: false,
  13731. once: false
  13732. });
  13733. }
  13734. return _cue;
  13735. }
  13736. get startTime() {
  13737. const {
  13738. tagAnchor
  13739. } = this;
  13740. if (tagAnchor === null || tagAnchor.programDateTime === null) {
  13741. logger.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${tagAnchor}`);
  13742. return NaN;
  13743. }
  13744. return tagAnchor.start + (this.startDate.getTime() - tagAnchor.programDateTime) / 1e3;
  13745. }
  13746. get startDate() {
  13747. return this._startDate;
  13748. }
  13749. get endDate() {
  13750. const dateAtEnd = this._endDate || this._dateAtEnd;
  13751. if (dateAtEnd) {
  13752. return dateAtEnd;
  13753. }
  13754. const duration = this.duration;
  13755. if (duration !== null) {
  13756. return this._dateAtEnd = new Date(this._startDate.getTime() + duration * 1e3);
  13757. }
  13758. return null;
  13759. }
  13760. get duration() {
  13761. if ("DURATION" in this.attr) {
  13762. const duration = this.attr.decimalFloatingPoint("DURATION");
  13763. if (isFiniteNumber(duration)) {
  13764. return duration;
  13765. }
  13766. } else if (this._endDate) {
  13767. return (this._endDate.getTime() - this._startDate.getTime()) / 1e3;
  13768. }
  13769. return null;
  13770. }
  13771. get plannedDuration() {
  13772. if ("PLANNED-DURATION" in this.attr) {
  13773. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  13774. }
  13775. return null;
  13776. }
  13777. get endOnNext() {
  13778. return this.attr.bool("END-ON-NEXT");
  13779. }
  13780. get isInterstitial() {
  13781. return this.class === CLASS_INTERSTITIAL;
  13782. }
  13783. get isValid() {
  13784. return !!this.id && !this._badValueForSameId && isFiniteNumber(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class) && (!this.attr.CUE || !this.cue.pre && !this.cue.post || this.cue.pre !== this.cue.post) && (!this.isInterstitial || "X-ASSET-URI" in this.attr || "X-ASSET-LIST" in this.attr);
  13785. }
  13786. }
  13787. const DEFAULT_TARGET_DURATION = 10;
  13788. class LevelDetails {
  13789. constructor(baseUrl) {
  13790. this.PTSKnown = false;
  13791. this.alignedSliding = false;
  13792. this.averagetargetduration = void 0;
  13793. this.endCC = 0;
  13794. this.endSN = 0;
  13795. this.fragments = void 0;
  13796. this.fragmentHint = void 0;
  13797. this.partList = null;
  13798. this.dateRanges = void 0;
  13799. this.dateRangeTagCount = 0;
  13800. this.live = true;
  13801. this.requestScheduled = -1;
  13802. this.ageHeader = 0;
  13803. this.advancedDateTime = void 0;
  13804. this.updated = true;
  13805. this.advanced = true;
  13806. this.misses = 0;
  13807. this.startCC = 0;
  13808. this.startSN = 0;
  13809. this.startTimeOffset = null;
  13810. this.targetduration = 0;
  13811. this.totalduration = 0;
  13812. this.type = null;
  13813. this.url = void 0;
  13814. this.m3u8 = "";
  13815. this.version = null;
  13816. this.canBlockReload = false;
  13817. this.canSkipUntil = 0;
  13818. this.canSkipDateRanges = false;
  13819. this.skippedSegments = 0;
  13820. this.recentlyRemovedDateranges = void 0;
  13821. this.partHoldBack = 0;
  13822. this.holdBack = 0;
  13823. this.partTarget = 0;
  13824. this.preloadHint = void 0;
  13825. this.renditionReports = void 0;
  13826. this.tuneInGoal = 0;
  13827. this.deltaUpdateFailed = void 0;
  13828. this.driftStartTime = 0;
  13829. this.driftEndTime = 0;
  13830. this.driftStart = 0;
  13831. this.driftEnd = 0;
  13832. this.encryptedFragments = void 0;
  13833. this.playlistParsingError = null;
  13834. this.variableList = null;
  13835. this.hasVariableRefs = false;
  13836. this.appliedTimelineOffset = void 0;
  13837. this.fragments = [];
  13838. this.encryptedFragments = [];
  13839. this.dateRanges = {};
  13840. this.url = baseUrl;
  13841. }
  13842. reloaded(previous) {
  13843. if (!previous) {
  13844. this.advanced = true;
  13845. this.updated = true;
  13846. return;
  13847. }
  13848. const partSnDiff = this.lastPartSn - previous.lastPartSn;
  13849. const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  13850. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  13851. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  13852. if (this.updated || this.advanced) {
  13853. this.misses = Math.floor(previous.misses * 0.6);
  13854. } else {
  13855. this.misses = previous.misses + 1;
  13856. }
  13857. }
  13858. get hasProgramDateTime() {
  13859. if (this.fragments.length) {
  13860. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  13861. }
  13862. return false;
  13863. }
  13864. get levelTargetDuration() {
  13865. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  13866. }
  13867. get drift() {
  13868. const runTime = this.driftEndTime - this.driftStartTime;
  13869. if (runTime > 0) {
  13870. const runDuration = this.driftEnd - this.driftStart;
  13871. return runDuration * 1e3 / runTime;
  13872. }
  13873. return 1;
  13874. }
  13875. get edge() {
  13876. return this.partEnd || this.fragmentEnd;
  13877. }
  13878. get partEnd() {
  13879. var _this$partList;
  13880. if ((_this$partList = this.partList) != null && _this$partList.length) {
  13881. return this.partList[this.partList.length - 1].end;
  13882. }
  13883. return this.fragmentEnd;
  13884. }
  13885. get fragmentEnd() {
  13886. var _this$fragments;
  13887. if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
  13888. return this.fragments[this.fragments.length - 1].end;
  13889. }
  13890. return 0;
  13891. }
  13892. get fragmentStart() {
  13893. var _this$fragments2;
  13894. if ((_this$fragments2 = this.fragments) != null && _this$fragments2.length) {
  13895. return this.fragments[0].start;
  13896. }
  13897. return 0;
  13898. }
  13899. get age() {
  13900. if (this.advancedDateTime) {
  13901. return Math.max(Date.now() - this.advancedDateTime, 0) / 1e3;
  13902. }
  13903. return 0;
  13904. }
  13905. get lastPartIndex() {
  13906. var _this$partList2;
  13907. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  13908. return this.partList[this.partList.length - 1].index;
  13909. }
  13910. return -1;
  13911. }
  13912. get maxPartIndex() {
  13913. const partList = this.partList;
  13914. if (partList) {
  13915. const lastIndex = this.lastPartIndex;
  13916. if (lastIndex !== -1) {
  13917. for (let i2 = partList.length; i2--; ) {
  13918. if (partList[i2].index > lastIndex) {
  13919. return partList[i2].index;
  13920. }
  13921. }
  13922. return lastIndex;
  13923. }
  13924. }
  13925. return 0;
  13926. }
  13927. get lastPartSn() {
  13928. var _this$partList3;
  13929. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  13930. return this.partList[this.partList.length - 1].fragment.sn;
  13931. }
  13932. return this.endSN;
  13933. }
  13934. get expired() {
  13935. if (this.live && this.age && this.misses < 3) {
  13936. const playlistWindowDuration = this.partEnd - this.fragmentStart;
  13937. return this.age > Math.max(playlistWindowDuration, this.totalduration) + this.levelTargetDuration;
  13938. }
  13939. return false;
  13940. }
  13941. }
  13942. function isFullSegmentEncryption(method) {
  13943. return method === "AES-128" || method === "AES-256" || method === "AES-256-CTR";
  13944. }
  13945. function getAesModeFromFullSegmentMethod(method) {
  13946. switch (method) {
  13947. case "AES-128":
  13948. case "AES-256":
  13949. return DecrypterAesMode.cbc;
  13950. case "AES-256-CTR":
  13951. return DecrypterAesMode.ctr;
  13952. default:
  13953. throw new Error(`invalid full segment method ${method}`);
  13954. }
  13955. }
  13956. function base64Decode(base64encodedStr) {
  13957. return Uint8Array.from(atob(base64encodedStr), (c2) => c2.charCodeAt(0));
  13958. }
  13959. function strToUtf8array(str) {
  13960. return Uint8Array.from(unescape(encodeURIComponent(str)), (c2) => c2.charCodeAt(0));
  13961. }
  13962. function getKeyIdBytes(str) {
  13963. const keyIdbytes = strToUtf8array(str).subarray(0, 16);
  13964. const paddedkeyIdbytes = new Uint8Array(16);
  13965. paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);
  13966. return paddedkeyIdbytes;
  13967. }
  13968. function changeEndianness(keyId) {
  13969. const swap = function swap2(array, from, to) {
  13970. const cur = array[from];
  13971. array[from] = array[to];
  13972. array[to] = cur;
  13973. };
  13974. swap(keyId, 0, 3);
  13975. swap(keyId, 1, 2);
  13976. swap(keyId, 4, 5);
  13977. swap(keyId, 6, 7);
  13978. }
  13979. function convertDataUriToArrayBytes(uri) {
  13980. const colonsplit = uri.split(":");
  13981. let keydata = null;
  13982. if (colonsplit[0] === "data" && colonsplit.length === 2) {
  13983. const semicolonsplit = colonsplit[1].split(";");
  13984. const commasplit = semicolonsplit[semicolonsplit.length - 1].split(",");
  13985. if (commasplit.length === 2) {
  13986. const isbase64 = commasplit[0] === "base64";
  13987. const data = commasplit[1];
  13988. if (isbase64) {
  13989. semicolonsplit.splice(-1, 1);
  13990. keydata = base64Decode(data);
  13991. } else {
  13992. keydata = getKeyIdBytes(data);
  13993. }
  13994. }
  13995. }
  13996. return keydata;
  13997. }
  13998. const optionalSelf = typeof self !== "undefined" ? self : void 0;
  13999. var KeySystems = {
  14000. CLEARKEY: "org.w3.clearkey",
  14001. FAIRPLAY: "com.apple.fps",
  14002. PLAYREADY: "com.microsoft.playready",
  14003. WIDEVINE: "com.widevine.alpha"
  14004. };
  14005. var KeySystemFormats = {
  14006. CLEARKEY: "org.w3.clearkey",
  14007. FAIRPLAY: "com.apple.streamingkeydelivery",
  14008. PLAYREADY: "com.microsoft.playready",
  14009. WIDEVINE: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
  14010. };
  14011. function keySystemFormatToKeySystemDomain(format2) {
  14012. switch (format2) {
  14013. case KeySystemFormats.FAIRPLAY:
  14014. return KeySystems.FAIRPLAY;
  14015. case KeySystemFormats.PLAYREADY:
  14016. return KeySystems.PLAYREADY;
  14017. case KeySystemFormats.WIDEVINE:
  14018. return KeySystems.WIDEVINE;
  14019. case KeySystemFormats.CLEARKEY:
  14020. return KeySystems.CLEARKEY;
  14021. }
  14022. }
  14023. function keySystemDomainToKeySystemFormat(keySystem) {
  14024. switch (keySystem) {
  14025. case KeySystems.FAIRPLAY:
  14026. return KeySystemFormats.FAIRPLAY;
  14027. case KeySystems.PLAYREADY:
  14028. return KeySystemFormats.PLAYREADY;
  14029. case KeySystems.WIDEVINE:
  14030. return KeySystemFormats.WIDEVINE;
  14031. case KeySystems.CLEARKEY:
  14032. return KeySystemFormats.CLEARKEY;
  14033. }
  14034. }
  14035. function getKeySystemsForConfig(config) {
  14036. const {
  14037. drmSystems,
  14038. widevineLicenseUrl
  14039. } = config;
  14040. const keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter((keySystem) => !!drmSystems[keySystem]) : [];
  14041. if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {
  14042. keySystemsToAttempt.push(KeySystems.WIDEVINE);
  14043. }
  14044. return keySystemsToAttempt;
  14045. }
  14046. const requestMediaKeySystemAccess = function(_optionalSelf$navigat) {
  14047. if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) {
  14048. return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
  14049. } else {
  14050. return null;
  14051. }
  14052. }();
  14053. function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
  14054. let initDataTypes;
  14055. switch (keySystem) {
  14056. case KeySystems.FAIRPLAY:
  14057. initDataTypes = ["cenc", "sinf"];
  14058. break;
  14059. case KeySystems.WIDEVINE:
  14060. case KeySystems.PLAYREADY:
  14061. initDataTypes = ["cenc"];
  14062. break;
  14063. case KeySystems.CLEARKEY:
  14064. initDataTypes = ["cenc", "keyids"];
  14065. break;
  14066. default:
  14067. throw new Error(`Unknown key-system: ${keySystem}`);
  14068. }
  14069. return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions);
  14070. }
  14071. function createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) {
  14072. const baseConfig = {
  14073. initDataTypes,
  14074. persistentState: drmSystemOptions.persistentState || "optional",
  14075. distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || "optional",
  14076. sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || "temporary"],
  14077. audioCapabilities: audioCodecs.map((codec) => ({
  14078. contentType: `audio/mp4; codecs=${codec}`,
  14079. robustness: drmSystemOptions.audioRobustness || "",
  14080. encryptionScheme: drmSystemOptions.audioEncryptionScheme || null
  14081. })),
  14082. videoCapabilities: videoCodecs.map((codec) => ({
  14083. contentType: `video/mp4; codecs=${codec}`,
  14084. robustness: drmSystemOptions.videoRobustness || "",
  14085. encryptionScheme: drmSystemOptions.videoEncryptionScheme || null
  14086. }))
  14087. };
  14088. return [baseConfig];
  14089. }
  14090. function isPersistentSessionType(drmSystemOptions) {
  14091. var _drmSystemOptions$ses;
  14092. return drmSystemOptions.sessionType === "persistent-license" || !!((_drmSystemOptions$ses = drmSystemOptions.sessionTypes) != null && _drmSystemOptions$ses.some((type) => type === "persistent-license"));
  14093. }
  14094. function parsePlayReadyWRM(keyBytes) {
  14095. const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);
  14096. const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));
  14097. const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf("<"), keyByteStr.length);
  14098. const parser = new DOMParser();
  14099. const xmlDoc = parser.parseFromString(xmlKeyBytes, "text/xml");
  14100. const keyData = xmlDoc.getElementsByTagName("KID")[0];
  14101. if (keyData) {
  14102. const keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute("VALUE");
  14103. if (keyId) {
  14104. const keyIdArray = base64Decode(keyId).subarray(0, 16);
  14105. changeEndianness(keyIdArray);
  14106. return keyIdArray;
  14107. }
  14108. }
  14109. return null;
  14110. }
  14111. let keyUriToKeyIdMap = {};
  14112. class LevelKey {
  14113. static clearKeyUriToKeyIdMap() {
  14114. keyUriToKeyIdMap = {};
  14115. }
  14116. constructor(method, uri, format2, formatversions = [1], iv = null, keyId) {
  14117. this.uri = void 0;
  14118. this.method = void 0;
  14119. this.keyFormat = void 0;
  14120. this.keyFormatVersions = void 0;
  14121. this.encrypted = void 0;
  14122. this.isCommonEncryption = void 0;
  14123. this.iv = null;
  14124. this.key = null;
  14125. this.keyId = null;
  14126. this.pssh = null;
  14127. this.method = method;
  14128. this.uri = uri;
  14129. this.keyFormat = format2;
  14130. this.keyFormatVersions = formatversions;
  14131. this.iv = iv;
  14132. this.encrypted = method ? method !== "NONE" : false;
  14133. this.isCommonEncryption = this.encrypted && !isFullSegmentEncryption(method);
  14134. if (keyId != null && keyId.startsWith("0x")) {
  14135. this.keyId = new Uint8Array(hexToArrayBuffer(keyId));
  14136. }
  14137. }
  14138. matches(key) {
  14139. var _key$iv, _this$iv;
  14140. return key.uri === this.uri && key.method === this.method && key.encrypted === this.encrypted && key.keyFormat === this.keyFormat && key.keyFormatVersions.join(",") === this.keyFormatVersions.join(",") && ((_key$iv = key.iv) == null ? void 0 : _key$iv.join(",")) === ((_this$iv = this.iv) == null ? void 0 : _this$iv.join(","));
  14141. }
  14142. isSupported() {
  14143. if (this.method) {
  14144. if (isFullSegmentEncryption(this.method) || this.method === "NONE") {
  14145. return true;
  14146. }
  14147. if (this.keyFormat === "identity") {
  14148. return this.method === "SAMPLE-AES";
  14149. } else {
  14150. switch (this.keyFormat) {
  14151. case KeySystemFormats.FAIRPLAY:
  14152. case KeySystemFormats.WIDEVINE:
  14153. case KeySystemFormats.PLAYREADY:
  14154. case KeySystemFormats.CLEARKEY:
  14155. return ["ISO-23001-7", "SAMPLE-AES", "SAMPLE-AES-CENC", "SAMPLE-AES-CTR"].indexOf(this.method) !== -1;
  14156. }
  14157. }
  14158. }
  14159. return false;
  14160. }
  14161. getDecryptData(sn2) {
  14162. if (!this.encrypted || !this.uri) {
  14163. return null;
  14164. }
  14165. if (isFullSegmentEncryption(this.method) && this.uri && !this.iv) {
  14166. if (typeof sn2 !== "number") {
  14167. logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`);
  14168. sn2 = 0;
  14169. }
  14170. const iv = createInitializationVector(sn2);
  14171. const decryptdata = new LevelKey(this.method, this.uri, "identity", this.keyFormatVersions, iv);
  14172. return decryptdata;
  14173. }
  14174. if (this.pssh && this.keyId) {
  14175. return this;
  14176. }
  14177. const keyBytes = convertDataUriToArrayBytes(this.uri);
  14178. if (keyBytes) {
  14179. switch (this.keyFormat) {
  14180. case KeySystemFormats.WIDEVINE:
  14181. this.pssh = keyBytes;
  14182. if (!this.keyId && keyBytes.length >= 22) {
  14183. const offset = keyBytes.length - 22;
  14184. this.keyId = keyBytes.subarray(offset, offset + 16);
  14185. }
  14186. break;
  14187. case KeySystemFormats.PLAYREADY: {
  14188. const PlayReadyKeySystemUUID = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]);
  14189. this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);
  14190. this.keyId = parsePlayReadyWRM(keyBytes);
  14191. break;
  14192. }
  14193. default: {
  14194. let keydata = keyBytes.subarray(0, 16);
  14195. if (keydata.length !== 16) {
  14196. const padded = new Uint8Array(16);
  14197. padded.set(keydata, 16 - keydata.length);
  14198. keydata = padded;
  14199. }
  14200. this.keyId = keydata;
  14201. break;
  14202. }
  14203. }
  14204. }
  14205. if (!this.keyId || this.keyId.byteLength !== 16) {
  14206. let keyId = keyUriToKeyIdMap[this.uri];
  14207. if (!keyId) {
  14208. const val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;
  14209. keyId = new Uint8Array(16);
  14210. const dv = new DataView(keyId.buffer, 12, 4);
  14211. dv.setUint32(0, val);
  14212. keyUriToKeyIdMap[this.uri] = keyId;
  14213. }
  14214. this.keyId = keyId;
  14215. }
  14216. return this;
  14217. }
  14218. }
  14219. function createInitializationVector(segmentNumber) {
  14220. const uint8View = new Uint8Array(16);
  14221. for (let i2 = 12; i2 < 16; i2++) {
  14222. uint8View[i2] = segmentNumber >> 8 * (15 - i2) & 255;
  14223. }
  14224. return uint8View;
  14225. }
  14226. const 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;
  14227. const MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  14228. const IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m;
  14229. const LEVEL_PLAYLIST_REGEX_FAST = new RegExp([
  14230. /#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  14231. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  14232. /(?!#) *(\S[^\r\n]*)/.source,
  14233. // segment URI, group 3 => the URI (note newline is not eaten)
  14234. /#.*/.source
  14235. // All other non-segment oriented tags will match with all groups empty
  14236. ].join("|"), "g");
  14237. const LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source, /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source, /#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join("|"));
  14238. class M3U8Parser {
  14239. static findGroup(groups, mediaGroupId) {
  14240. for (let i2 = 0; i2 < groups.length; i2++) {
  14241. const group = groups[i2];
  14242. if (group.id === mediaGroupId) {
  14243. return group;
  14244. }
  14245. }
  14246. }
  14247. static resolve(url, baseUrl) {
  14248. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  14249. alwaysNormalize: true
  14250. });
  14251. }
  14252. static isMediaPlaylist(str) {
  14253. return IS_MEDIA_PLAYLIST.test(str);
  14254. }
  14255. static parseMasterPlaylist(string, baseurl) {
  14256. const hasVariableRefs = hasVariableReferences(string);
  14257. const parsed = {
  14258. contentSteering: null,
  14259. levels: [],
  14260. playlistParsingError: null,
  14261. sessionData: null,
  14262. sessionKeys: null,
  14263. startTimeOffset: null,
  14264. variableList: null,
  14265. hasVariableRefs
  14266. };
  14267. const levelsWithKnownCodecs = [];
  14268. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  14269. let result;
  14270. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  14271. if (result[1]) {
  14272. var _level$unknownCodecs;
  14273. const attrs = new AttrList(result[1], parsed);
  14274. const uri = substituteVariables(parsed, result[2]);
  14275. const level = {
  14276. attrs,
  14277. bitrate: attrs.decimalInteger("BANDWIDTH") || attrs.decimalInteger("AVERAGE-BANDWIDTH"),
  14278. name: attrs.NAME,
  14279. url: M3U8Parser.resolve(uri, baseurl)
  14280. };
  14281. const resolution = attrs.decimalResolution("RESOLUTION");
  14282. if (resolution) {
  14283. level.width = resolution.width;
  14284. level.height = resolution.height;
  14285. }
  14286. setCodecs(attrs.CODECS, level);
  14287. const supplementalCodecs = attrs["SUPPLEMENTAL-CODECS"];
  14288. if (supplementalCodecs) {
  14289. level.supplemental = {};
  14290. setCodecs(supplementalCodecs, level.supplemental);
  14291. }
  14292. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  14293. levelsWithKnownCodecs.push(level);
  14294. }
  14295. parsed.levels.push(level);
  14296. } else if (result[3]) {
  14297. const tag = result[3];
  14298. const attributes = result[4];
  14299. switch (tag) {
  14300. case "SESSION-DATA": {
  14301. const sessionAttrs = new AttrList(attributes, parsed);
  14302. const dataId = sessionAttrs["DATA-ID"];
  14303. if (dataId) {
  14304. if (parsed.sessionData === null) {
  14305. parsed.sessionData = {};
  14306. }
  14307. parsed.sessionData[dataId] = sessionAttrs;
  14308. }
  14309. break;
  14310. }
  14311. case "SESSION-KEY": {
  14312. const sessionKey = parseKey(attributes, baseurl, parsed);
  14313. if (sessionKey.encrypted && sessionKey.isSupported()) {
  14314. if (parsed.sessionKeys === null) {
  14315. parsed.sessionKeys = [];
  14316. }
  14317. parsed.sessionKeys.push(sessionKey);
  14318. } else {
  14319. logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`);
  14320. }
  14321. break;
  14322. }
  14323. case "DEFINE": {
  14324. {
  14325. const variableAttributes = new AttrList(attributes, parsed);
  14326. addVariableDefinition(parsed, variableAttributes, baseurl);
  14327. }
  14328. break;
  14329. }
  14330. case "CONTENT-STEERING": {
  14331. const contentSteeringAttributes = new AttrList(attributes, parsed);
  14332. parsed.contentSteering = {
  14333. uri: M3U8Parser.resolve(contentSteeringAttributes["SERVER-URI"], baseurl),
  14334. pathwayId: contentSteeringAttributes["PATHWAY-ID"] || "."
  14335. };
  14336. break;
  14337. }
  14338. case "START": {
  14339. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  14340. break;
  14341. }
  14342. }
  14343. }
  14344. }
  14345. const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  14346. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  14347. if (parsed.levels.length === 0) {
  14348. parsed.playlistParsingError = new Error("no levels found in manifest");
  14349. }
  14350. return parsed;
  14351. }
  14352. static parseMasterPlaylistMedia(string, baseurl, parsed) {
  14353. let result;
  14354. const results = {};
  14355. const levels = parsed.levels;
  14356. const groupsByType = {
  14357. AUDIO: levels.map((level) => ({
  14358. id: level.attrs.AUDIO,
  14359. audioCodec: level.audioCodec
  14360. })),
  14361. SUBTITLES: levels.map((level) => ({
  14362. id: level.attrs.SUBTITLES,
  14363. textCodec: level.textCodec
  14364. })),
  14365. "CLOSED-CAPTIONS": []
  14366. };
  14367. let id = 0;
  14368. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  14369. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  14370. const attrs = new AttrList(result[1], parsed);
  14371. const type = attrs.TYPE;
  14372. if (type) {
  14373. const groups = groupsByType[type];
  14374. const medias = results[type] || [];
  14375. results[type] = medias;
  14376. const lang = attrs.LANGUAGE;
  14377. const assocLang = attrs["ASSOC-LANGUAGE"];
  14378. const channels = attrs.CHANNELS;
  14379. const characteristics = attrs.CHARACTERISTICS;
  14380. const instreamId = attrs["INSTREAM-ID"];
  14381. const media = {
  14382. attrs,
  14383. bitrate: 0,
  14384. id: id++,
  14385. groupId: attrs["GROUP-ID"] || "",
  14386. name: attrs.NAME || lang || "",
  14387. type,
  14388. default: attrs.bool("DEFAULT"),
  14389. autoselect: attrs.bool("AUTOSELECT"),
  14390. forced: attrs.bool("FORCED"),
  14391. lang,
  14392. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ""
  14393. };
  14394. if (assocLang) {
  14395. media.assocLang = assocLang;
  14396. }
  14397. if (channels) {
  14398. media.channels = channels;
  14399. }
  14400. if (characteristics) {
  14401. media.characteristics = characteristics;
  14402. }
  14403. if (instreamId) {
  14404. media.instreamId = instreamId;
  14405. }
  14406. if (groups != null && groups.length) {
  14407. const groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  14408. assignCodec(media, groupCodec, "audioCodec");
  14409. assignCodec(media, groupCodec, "textCodec");
  14410. }
  14411. medias.push(media);
  14412. }
  14413. }
  14414. return results;
  14415. }
  14416. static parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  14417. var _LEVEL_PLAYLIST_REGEX;
  14418. const base = {
  14419. url: baseurl
  14420. };
  14421. const level = new LevelDetails(baseurl);
  14422. const fragments = level.fragments;
  14423. const programDateTimes = [];
  14424. let currentInitSegment = null;
  14425. let currentSN = 0;
  14426. let currentPart = 0;
  14427. let totalduration = 0;
  14428. let discontinuityCounter = 0;
  14429. let currentBitrate = 0;
  14430. let prevFrag = null;
  14431. let frag = new Fragment(type, base);
  14432. let result;
  14433. let i2;
  14434. let levelkeys;
  14435. let firstPdtIndex = -1;
  14436. let createNextFrag = false;
  14437. let nextByteRange = null;
  14438. let serverControlAttrs;
  14439. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  14440. level.m3u8 = string;
  14441. level.hasVariableRefs = hasVariableReferences(string);
  14442. if (((_LEVEL_PLAYLIST_REGEX = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) == null ? void 0 : _LEVEL_PLAYLIST_REGEX[0]) !== "#EXTM3U") {
  14443. level.playlistParsingError = new Error("Missing format identifier #EXTM3U");
  14444. return level;
  14445. }
  14446. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  14447. if (createNextFrag) {
  14448. createNextFrag = false;
  14449. frag = new Fragment(type, base);
  14450. frag.playlistOffset = totalduration;
  14451. frag.start = totalduration;
  14452. frag.sn = currentSN;
  14453. frag.cc = discontinuityCounter;
  14454. if (currentBitrate) {
  14455. frag.bitrate = currentBitrate;
  14456. }
  14457. frag.level = id;
  14458. if (currentInitSegment) {
  14459. frag.initSegment = currentInitSegment;
  14460. if (currentInitSegment.rawProgramDateTime) {
  14461. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  14462. currentInitSegment.rawProgramDateTime = null;
  14463. }
  14464. if (nextByteRange) {
  14465. frag.setByteRange(nextByteRange);
  14466. nextByteRange = null;
  14467. }
  14468. }
  14469. }
  14470. const duration = result[1];
  14471. if (duration) {
  14472. frag.duration = parseFloat(duration);
  14473. const title = (" " + result[2]).slice(1);
  14474. frag.title = title || null;
  14475. frag.tagList.push(title ? ["INF", duration, title] : ["INF", duration]);
  14476. } else if (result[3]) {
  14477. if (isFiniteNumber(frag.duration)) {
  14478. frag.playlistOffset = totalduration;
  14479. frag.start = totalduration;
  14480. if (levelkeys) {
  14481. setFragLevelKeys(frag, levelkeys, level);
  14482. }
  14483. frag.sn = currentSN;
  14484. frag.level = id;
  14485. frag.cc = discontinuityCounter;
  14486. fragments.push(frag);
  14487. const uri = (" " + result[3]).slice(1);
  14488. frag.relurl = substituteVariables(level, uri);
  14489. assignProgramDateTime(frag, prevFrag, programDateTimes);
  14490. prevFrag = frag;
  14491. totalduration += frag.duration;
  14492. currentSN++;
  14493. currentPart = 0;
  14494. createNextFrag = true;
  14495. }
  14496. } else {
  14497. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  14498. if (!result) {
  14499. logger.warn("No matches on slow regex match for level playlist!");
  14500. continue;
  14501. }
  14502. for (i2 = 1; i2 < result.length; i2++) {
  14503. if (result[i2] !== void 0) {
  14504. break;
  14505. }
  14506. }
  14507. const tag = (" " + result[i2]).slice(1);
  14508. const value1 = (" " + result[i2 + 1]).slice(1);
  14509. const value2 = result[i2 + 2] ? (" " + result[i2 + 2]).slice(1) : null;
  14510. switch (tag) {
  14511. case "BYTERANGE":
  14512. if (prevFrag) {
  14513. frag.setByteRange(value1, prevFrag);
  14514. } else {
  14515. frag.setByteRange(value1);
  14516. }
  14517. break;
  14518. case "PROGRAM-DATE-TIME":
  14519. frag.rawProgramDateTime = value1;
  14520. frag.tagList.push(["PROGRAM-DATE-TIME", value1]);
  14521. if (firstPdtIndex === -1) {
  14522. firstPdtIndex = fragments.length;
  14523. }
  14524. break;
  14525. case "PLAYLIST-TYPE":
  14526. if (level.type) {
  14527. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  14528. }
  14529. level.type = value1.toUpperCase();
  14530. break;
  14531. case "MEDIA-SEQUENCE":
  14532. if (level.startSN !== 0) {
  14533. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  14534. } else if (fragments.length > 0) {
  14535. assignMustAppearBeforeSegmentsError(level, tag, result);
  14536. }
  14537. currentSN = level.startSN = parseInt(value1);
  14538. break;
  14539. case "SKIP": {
  14540. if (level.skippedSegments) {
  14541. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  14542. }
  14543. const skipAttrs = new AttrList(value1, level);
  14544. const skippedSegments = skipAttrs.decimalInteger("SKIPPED-SEGMENTS");
  14545. if (isFiniteNumber(skippedSegments)) {
  14546. level.skippedSegments += skippedSegments;
  14547. for (let _i = skippedSegments; _i--; ) {
  14548. fragments.push(null);
  14549. }
  14550. currentSN += skippedSegments;
  14551. }
  14552. const recentlyRemovedDateranges = skipAttrs.enumeratedString("RECENTLY-REMOVED-DATERANGES");
  14553. if (recentlyRemovedDateranges) {
  14554. level.recentlyRemovedDateranges = (level.recentlyRemovedDateranges || []).concat(recentlyRemovedDateranges.split(" "));
  14555. }
  14556. break;
  14557. }
  14558. case "TARGETDURATION":
  14559. if (level.targetduration !== 0) {
  14560. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  14561. }
  14562. level.targetduration = Math.max(parseInt(value1), 1);
  14563. break;
  14564. case "VERSION":
  14565. if (level.version !== null) {
  14566. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  14567. }
  14568. level.version = parseInt(value1);
  14569. break;
  14570. case "INDEPENDENT-SEGMENTS":
  14571. break;
  14572. case "ENDLIST":
  14573. if (!level.live) {
  14574. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  14575. }
  14576. level.live = false;
  14577. break;
  14578. case "#":
  14579. if (value1 || value2) {
  14580. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  14581. }
  14582. break;
  14583. case "DISCONTINUITY":
  14584. discontinuityCounter++;
  14585. frag.tagList.push(["DIS"]);
  14586. break;
  14587. case "GAP":
  14588. frag.gap = true;
  14589. frag.tagList.push([tag]);
  14590. break;
  14591. case "BITRATE":
  14592. frag.tagList.push([tag, value1]);
  14593. currentBitrate = parseInt(value1) * 1e3;
  14594. if (isFiniteNumber(currentBitrate)) {
  14595. frag.bitrate = currentBitrate;
  14596. } else {
  14597. currentBitrate = 0;
  14598. }
  14599. break;
  14600. case "DATERANGE": {
  14601. const dateRangeAttr = new AttrList(value1, level);
  14602. const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID], level.dateRangeTagCount);
  14603. level.dateRangeTagCount++;
  14604. if (dateRange.isValid || level.skippedSegments) {
  14605. level.dateRanges[dateRange.id] = dateRange;
  14606. } else {
  14607. logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`);
  14608. }
  14609. frag.tagList.push(["EXT-X-DATERANGE", value1]);
  14610. break;
  14611. }
  14612. case "DEFINE": {
  14613. {
  14614. const variableAttributes = new AttrList(value1, level);
  14615. if ("IMPORT" in variableAttributes) {
  14616. importVariableDefinition(level, variableAttributes, multivariantVariableList);
  14617. } else {
  14618. addVariableDefinition(level, variableAttributes, baseurl);
  14619. }
  14620. }
  14621. break;
  14622. }
  14623. case "DISCONTINUITY-SEQUENCE":
  14624. if (level.startCC !== 0) {
  14625. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  14626. } else if (fragments.length > 0) {
  14627. assignMustAppearBeforeSegmentsError(level, tag, result);
  14628. }
  14629. level.startCC = discontinuityCounter = parseInt(value1);
  14630. break;
  14631. case "KEY": {
  14632. const levelKey = parseKey(value1, baseurl, level);
  14633. if (levelKey.isSupported()) {
  14634. if (levelKey.method === "NONE") {
  14635. levelkeys = void 0;
  14636. break;
  14637. }
  14638. if (!levelkeys) {
  14639. levelkeys = {};
  14640. }
  14641. const currentKey = levelkeys[levelKey.keyFormat];
  14642. if (!(currentKey != null && currentKey.matches(levelKey))) {
  14643. if (currentKey) {
  14644. levelkeys = _extends({}, levelkeys);
  14645. }
  14646. levelkeys[levelKey.keyFormat] = levelKey;
  14647. }
  14648. } else {
  14649. logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${value1}"`);
  14650. }
  14651. break;
  14652. }
  14653. case "START":
  14654. level.startTimeOffset = parseStartTimeOffset(value1);
  14655. break;
  14656. case "MAP": {
  14657. const mapAttrs = new AttrList(value1, level);
  14658. if (frag.duration) {
  14659. const init = new Fragment(type, base);
  14660. setInitSegment(init, mapAttrs, id, levelkeys);
  14661. currentInitSegment = init;
  14662. frag.initSegment = currentInitSegment;
  14663. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  14664. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  14665. }
  14666. } else {
  14667. const end = frag.byteRangeEndOffset;
  14668. if (end) {
  14669. const start = frag.byteRangeStartOffset;
  14670. nextByteRange = `${end - start}@${start}`;
  14671. } else {
  14672. nextByteRange = null;
  14673. }
  14674. setInitSegment(frag, mapAttrs, id, levelkeys);
  14675. currentInitSegment = frag;
  14676. createNextFrag = true;
  14677. }
  14678. currentInitSegment.cc = discontinuityCounter;
  14679. break;
  14680. }
  14681. case "SERVER-CONTROL": {
  14682. if (serverControlAttrs) {
  14683. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  14684. }
  14685. serverControlAttrs = new AttrList(value1);
  14686. level.canBlockReload = serverControlAttrs.bool("CAN-BLOCK-RELOAD");
  14687. level.canSkipUntil = serverControlAttrs.optionalFloat("CAN-SKIP-UNTIL", 0);
  14688. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool("CAN-SKIP-DATERANGES");
  14689. level.partHoldBack = serverControlAttrs.optionalFloat("PART-HOLD-BACK", 0);
  14690. level.holdBack = serverControlAttrs.optionalFloat("HOLD-BACK", 0);
  14691. break;
  14692. }
  14693. case "PART-INF": {
  14694. if (level.partTarget) {
  14695. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  14696. }
  14697. const partInfAttrs = new AttrList(value1);
  14698. level.partTarget = partInfAttrs.decimalFloatingPoint("PART-TARGET");
  14699. break;
  14700. }
  14701. case "PART": {
  14702. let partList = level.partList;
  14703. if (!partList) {
  14704. partList = level.partList = [];
  14705. }
  14706. const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : void 0;
  14707. const index2 = currentPart++;
  14708. const partAttrs = new AttrList(value1, level);
  14709. const part = new Part(partAttrs, frag, base, index2, previousFragmentPart);
  14710. partList.push(part);
  14711. frag.duration += part.duration;
  14712. break;
  14713. }
  14714. case "PRELOAD-HINT": {
  14715. const preloadHintAttrs = new AttrList(value1, level);
  14716. level.preloadHint = preloadHintAttrs;
  14717. break;
  14718. }
  14719. case "RENDITION-REPORT": {
  14720. const renditionReportAttrs = new AttrList(value1, level);
  14721. level.renditionReports = level.renditionReports || [];
  14722. level.renditionReports.push(renditionReportAttrs);
  14723. break;
  14724. }
  14725. default:
  14726. logger.warn(`line parsed but not handled: ${result}`);
  14727. break;
  14728. }
  14729. }
  14730. }
  14731. if (prevFrag && !prevFrag.relurl) {
  14732. fragments.pop();
  14733. totalduration -= prevFrag.duration;
  14734. if (level.partList) {
  14735. level.fragmentHint = prevFrag;
  14736. }
  14737. } else if (level.partList) {
  14738. assignProgramDateTime(frag, prevFrag, programDateTimes);
  14739. frag.cc = discontinuityCounter;
  14740. level.fragmentHint = frag;
  14741. if (levelkeys) {
  14742. setFragLevelKeys(frag, levelkeys, level);
  14743. }
  14744. }
  14745. if (!level.targetduration) {
  14746. level.playlistParsingError = new Error(`#EXT-X-TARGETDURATION is required`);
  14747. }
  14748. const fragmentLength = fragments.length;
  14749. const firstFragment = fragments[0];
  14750. const lastFragment = fragments[fragmentLength - 1];
  14751. totalduration += level.skippedSegments * level.targetduration;
  14752. if (totalduration > 0 && fragmentLength && lastFragment) {
  14753. level.averagetargetduration = totalduration / fragmentLength;
  14754. const lastSn = lastFragment.sn;
  14755. level.endSN = lastSn !== "initSegment" ? lastSn : 0;
  14756. if (!level.live) {
  14757. lastFragment.endList = true;
  14758. }
  14759. if (firstFragment && level.startCC === void 0) {
  14760. level.startCC = firstFragment.cc;
  14761. }
  14762. if (firstPdtIndex > 0) {
  14763. backfillProgramDateTimes(fragments, firstPdtIndex);
  14764. if (firstFragment) {
  14765. programDateTimes.unshift(firstFragment);
  14766. }
  14767. }
  14768. } else {
  14769. level.endSN = 0;
  14770. level.startCC = 0;
  14771. }
  14772. if (level.fragmentHint) {
  14773. totalduration += level.fragmentHint.duration;
  14774. }
  14775. level.totalduration = totalduration;
  14776. if (programDateTimes.length && level.dateRangeTagCount && firstFragment) {
  14777. mapDateRanges(programDateTimes, level);
  14778. }
  14779. level.endCC = discontinuityCounter;
  14780. return level;
  14781. }
  14782. }
  14783. function mapDateRanges(programDateTimes, details) {
  14784. const programDateTimeCount = programDateTimes.length;
  14785. if (!programDateTimeCount) {
  14786. return;
  14787. }
  14788. const lastProgramDateTime = programDateTimes[programDateTimeCount - 1];
  14789. const playlistEnd = details.live ? Infinity : details.totalduration;
  14790. const dateRangeIds = Object.keys(details.dateRanges);
  14791. for (let i2 = dateRangeIds.length; i2--; ) {
  14792. const dateRange = details.dateRanges[dateRangeIds[i2]];
  14793. const startDateTime = dateRange.startDate.getTime();
  14794. dateRange.tagAnchor = lastProgramDateTime.ref;
  14795. for (let j2 = programDateTimeCount; j2--; ) {
  14796. const fragIndex = findFragmentWithStartDate(details, startDateTime, programDateTimes, j2, playlistEnd);
  14797. if (fragIndex !== -1) {
  14798. dateRange.tagAnchor = details.fragments[fragIndex].ref;
  14799. break;
  14800. }
  14801. }
  14802. }
  14803. }
  14804. function findFragmentWithStartDate(details, startDateTime, programDateTimes, index2, endTime) {
  14805. const pdtFragment = programDateTimes[index2];
  14806. if (pdtFragment) {
  14807. const pdtStart = pdtFragment.programDateTime;
  14808. if (startDateTime >= pdtStart || index2 === 0) {
  14809. var _programDateTimes;
  14810. const durationBetweenPdt = (((_programDateTimes = programDateTimes[index2 + 1]) == null ? void 0 : _programDateTimes.start) || endTime) - pdtFragment.start;
  14811. if (startDateTime <= pdtStart + durationBetweenPdt * 1e3) {
  14812. const startIndex = programDateTimes[index2].sn - details.startSN;
  14813. const fragments = details.fragments;
  14814. if (fragments.length > programDateTimes.length) {
  14815. const endSegment = programDateTimes[index2 + 1] || fragments[fragments.length - 1];
  14816. const endIndex = endSegment.sn - details.startSN;
  14817. for (let i2 = endIndex; i2 > startIndex; i2--) {
  14818. const fragStartDateTime = fragments[i2].programDateTime;
  14819. if (startDateTime >= fragStartDateTime && startDateTime < fragStartDateTime + fragments[i2].duration * 1e3) {
  14820. return i2;
  14821. }
  14822. }
  14823. }
  14824. return startIndex;
  14825. }
  14826. }
  14827. }
  14828. return -1;
  14829. }
  14830. function parseKey(keyTagAttributes, baseurl, parsed) {
  14831. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  14832. const keyAttrs = new AttrList(keyTagAttributes, parsed);
  14833. const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : "";
  14834. const decrypturi = keyAttrs.URI;
  14835. const decryptiv = keyAttrs.hexadecimalInteger("IV");
  14836. const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  14837. const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : "identity";
  14838. if (decrypturi && keyAttrs.IV && !decryptiv) {
  14839. logger.error(`Invalid IV: ${keyAttrs.IV}`);
  14840. }
  14841. const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : "";
  14842. const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : "1").split("/").map(Number).filter(Number.isFinite);
  14843. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv, keyAttrs.KEYID);
  14844. }
  14845. function parseStartTimeOffset(startAttributes) {
  14846. const startAttrs = new AttrList(startAttributes);
  14847. const startTimeOffset = startAttrs.decimalFloatingPoint("TIME-OFFSET");
  14848. if (isFiniteNumber(startTimeOffset)) {
  14849. return startTimeOffset;
  14850. }
  14851. return null;
  14852. }
  14853. function setCodecs(codecsAttributeValue, level) {
  14854. let codecs = (codecsAttributeValue || "").split(/[ ,]+/).filter((c2) => c2);
  14855. ["video", "audio", "text"].forEach((type) => {
  14856. const filtered = codecs.filter((codec) => isCodecType(codec, type));
  14857. if (filtered.length) {
  14858. level[`${type}Codec`] = filtered.map((c2) => c2.split("/")[0]).join(",");
  14859. codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);
  14860. }
  14861. });
  14862. level.unknownCodecs = codecs;
  14863. }
  14864. function assignCodec(media, groupItem, codecProperty) {
  14865. const codecValue = groupItem[codecProperty];
  14866. if (codecValue) {
  14867. media[codecProperty] = codecValue;
  14868. }
  14869. }
  14870. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  14871. let fragPrev = fragments[firstPdtIndex];
  14872. for (let i2 = firstPdtIndex; i2--; ) {
  14873. const frag = fragments[i2];
  14874. if (!frag) {
  14875. return;
  14876. }
  14877. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1e3;
  14878. fragPrev = frag;
  14879. }
  14880. }
  14881. function assignProgramDateTime(frag, prevFrag, programDateTimes) {
  14882. if (frag.rawProgramDateTime) {
  14883. programDateTimes.push(frag);
  14884. } else if (prevFrag != null && prevFrag.programDateTime) {
  14885. frag.programDateTime = prevFrag.endProgramDateTime;
  14886. }
  14887. }
  14888. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  14889. frag.relurl = mapAttrs.URI;
  14890. if (mapAttrs.BYTERANGE) {
  14891. frag.setByteRange(mapAttrs.BYTERANGE);
  14892. }
  14893. frag.level = id;
  14894. frag.sn = "initSegment";
  14895. if (levelkeys) {
  14896. frag.levelkeys = levelkeys;
  14897. }
  14898. frag.initSegment = null;
  14899. }
  14900. function setFragLevelKeys(frag, levelkeys, level) {
  14901. frag.levelkeys = levelkeys;
  14902. const {
  14903. encryptedFragments
  14904. } = level;
  14905. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some((format2) => levelkeys[format2].isCommonEncryption)) {
  14906. encryptedFragments.push(frag);
  14907. }
  14908. }
  14909. function assignMultipleMediaPlaylistTagOccuranceError(level, tag, result) {
  14910. level.playlistParsingError = new Error(`#EXT-X-${tag} must not appear more than once (${result[0]})`);
  14911. }
  14912. function assignMustAppearBeforeSegmentsError(level, tag, result) {
  14913. level.playlistParsingError = new Error(`#EXT-X-${tag} must appear before the first Media Segment (${result[0]})`);
  14914. }
  14915. function updateFromToPTS(fragFrom, fragTo) {
  14916. const fragToPTS = fragTo.startPTS;
  14917. if (isFiniteNumber(fragToPTS)) {
  14918. let duration = 0;
  14919. let frag;
  14920. if (fragTo.sn > fragFrom.sn) {
  14921. duration = fragToPTS - fragFrom.start;
  14922. frag = fragFrom;
  14923. } else {
  14924. duration = fragFrom.start - fragToPTS;
  14925. frag = fragTo;
  14926. }
  14927. if (frag.duration !== duration) {
  14928. frag.setDuration(duration);
  14929. }
  14930. } else if (fragTo.sn > fragFrom.sn) {
  14931. const contiguous = fragFrom.cc === fragTo.cc;
  14932. if (contiguous && fragFrom.minEndPTS) {
  14933. fragTo.setStart(fragFrom.start + (fragFrom.minEndPTS - fragFrom.start));
  14934. } else {
  14935. fragTo.setStart(fragFrom.start + fragFrom.duration);
  14936. }
  14937. } else {
  14938. fragTo.setStart(Math.max(fragFrom.start - fragTo.duration, 0));
  14939. }
  14940. }
  14941. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  14942. const parsedMediaDuration = endPTS - startPTS;
  14943. if (parsedMediaDuration <= 0) {
  14944. logger.warn("Fragment should have a positive duration", frag);
  14945. endPTS = startPTS + frag.duration;
  14946. endDTS = startDTS + frag.duration;
  14947. }
  14948. let maxStartPTS = startPTS;
  14949. let minEndPTS = endPTS;
  14950. const fragStartPts = frag.startPTS;
  14951. const fragEndPts = frag.endPTS;
  14952. if (isFiniteNumber(fragStartPts)) {
  14953. const deltaPTS = Math.abs(fragStartPts - startPTS);
  14954. if (!isFiniteNumber(frag.deltaPTS)) {
  14955. frag.deltaPTS = deltaPTS;
  14956. } else {
  14957. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  14958. }
  14959. maxStartPTS = Math.max(startPTS, fragStartPts);
  14960. startPTS = Math.min(startPTS, fragStartPts);
  14961. startDTS = Math.min(startDTS, frag.startDTS);
  14962. minEndPTS = Math.min(endPTS, fragEndPts);
  14963. endPTS = Math.max(endPTS, fragEndPts);
  14964. endDTS = Math.max(endDTS, frag.endDTS);
  14965. }
  14966. const drift = startPTS - frag.start;
  14967. if (frag.start !== 0) {
  14968. frag.setStart(startPTS);
  14969. }
  14970. frag.setDuration(endPTS - frag.start);
  14971. frag.startPTS = startPTS;
  14972. frag.maxStartPTS = maxStartPTS;
  14973. frag.startDTS = startDTS;
  14974. frag.endPTS = endPTS;
  14975. frag.minEndPTS = minEndPTS;
  14976. frag.endDTS = endDTS;
  14977. const sn2 = frag.sn;
  14978. if (!details || sn2 < details.startSN || sn2 > details.endSN) {
  14979. return 0;
  14980. }
  14981. let i2;
  14982. const fragIdx = sn2 - details.startSN;
  14983. const fragments = details.fragments;
  14984. fragments[fragIdx] = frag;
  14985. for (i2 = fragIdx; i2 > 0; i2--) {
  14986. updateFromToPTS(fragments[i2], fragments[i2 - 1]);
  14987. }
  14988. for (i2 = fragIdx; i2 < fragments.length - 1; i2++) {
  14989. updateFromToPTS(fragments[i2], fragments[i2 + 1]);
  14990. }
  14991. if (details.fragmentHint) {
  14992. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  14993. }
  14994. details.PTSKnown = details.alignedSliding = true;
  14995. return drift;
  14996. }
  14997. function mergeDetails(oldDetails, newDetails) {
  14998. if (oldDetails === newDetails) {
  14999. return;
  15000. }
  15001. let currentInitSegment = null;
  15002. const oldFragments = oldDetails.fragments;
  15003. for (let i2 = oldFragments.length - 1; i2 >= 0; i2--) {
  15004. const oldInit = oldFragments[i2].initSegment;
  15005. if (oldInit) {
  15006. currentInitSegment = oldInit;
  15007. break;
  15008. }
  15009. }
  15010. if (oldDetails.fragmentHint) {
  15011. delete oldDetails.fragmentHint.endPTS;
  15012. }
  15013. let PTSFrag;
  15014. mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag, newFragIndex, newFragments2) => {
  15015. if ((!newDetails.startCC || newDetails.skippedSegments) && newFrag.cc !== oldFrag.cc) {
  15016. const ccOffset = oldFrag.cc - newFrag.cc;
  15017. for (let i2 = newFragIndex; i2 < newFragments2.length; i2++) {
  15018. newFragments2[i2].cc += ccOffset;
  15019. }
  15020. newDetails.endCC = newFragments2[newFragments2.length - 1].cc;
  15021. }
  15022. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  15023. newFrag.setStart(newFrag.startPTS = oldFrag.startPTS);
  15024. newFrag.startDTS = oldFrag.startDTS;
  15025. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  15026. newFrag.endPTS = oldFrag.endPTS;
  15027. newFrag.endDTS = oldFrag.endDTS;
  15028. newFrag.minEndPTS = oldFrag.minEndPTS;
  15029. newFrag.setDuration(oldFrag.endPTS - oldFrag.startPTS);
  15030. if (newFrag.duration) {
  15031. PTSFrag = newFrag;
  15032. }
  15033. newDetails.PTSKnown = newDetails.alignedSliding = true;
  15034. }
  15035. if (oldFrag.hasStreams) {
  15036. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  15037. }
  15038. newFrag.loader = oldFrag.loader;
  15039. if (oldFrag.hasStats) {
  15040. newFrag.stats = oldFrag.stats;
  15041. }
  15042. if (oldFrag.initSegment) {
  15043. newFrag.initSegment = oldFrag.initSegment;
  15044. currentInitSegment = oldFrag.initSegment;
  15045. }
  15046. });
  15047. const newFragments = newDetails.fragments;
  15048. const fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments;
  15049. if (currentInitSegment) {
  15050. fragmentsToCheck.forEach((frag) => {
  15051. var _currentInitSegment;
  15052. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  15053. frag.initSegment = currentInitSegment;
  15054. }
  15055. });
  15056. }
  15057. if (newDetails.skippedSegments) {
  15058. newDetails.deltaUpdateFailed = newFragments.some((frag) => !frag);
  15059. if (newDetails.deltaUpdateFailed) {
  15060. logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");
  15061. for (let i2 = newDetails.skippedSegments; i2--; ) {
  15062. newFragments.shift();
  15063. }
  15064. newDetails.startSN = newFragments[0].sn;
  15065. } else {
  15066. if (newDetails.canSkipDateRanges) {
  15067. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails);
  15068. }
  15069. const programDateTimes = oldDetails.fragments.filter((frag) => frag.rawProgramDateTime);
  15070. if (oldDetails.hasProgramDateTime && !newDetails.hasProgramDateTime) {
  15071. for (let i2 = 1; i2 < fragmentsToCheck.length; i2++) {
  15072. if (fragmentsToCheck[i2].programDateTime === null) {
  15073. assignProgramDateTime(fragmentsToCheck[i2], fragmentsToCheck[i2 - 1], programDateTimes);
  15074. }
  15075. }
  15076. }
  15077. mapDateRanges(programDateTimes, newDetails);
  15078. }
  15079. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  15080. }
  15081. if (!newDetails.startCC) {
  15082. var _fragPriorToNewStart$;
  15083. const fragPriorToNewStart = getFragmentWithSN(oldDetails, newDetails.startSN - 1);
  15084. newDetails.startCC = (_fragPriorToNewStart$ = fragPriorToNewStart == null ? void 0 : fragPriorToNewStart.cc) != null ? _fragPriorToNewStart$ : newFragments[0].cc;
  15085. }
  15086. mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {
  15087. newPart.elementaryStreams = oldPart.elementaryStreams;
  15088. newPart.stats = oldPart.stats;
  15089. });
  15090. if (PTSFrag) {
  15091. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  15092. } else {
  15093. adjustSliding(oldDetails, newDetails);
  15094. }
  15095. if (newFragments.length) {
  15096. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  15097. }
  15098. newDetails.driftStartTime = oldDetails.driftStartTime;
  15099. newDetails.driftStart = oldDetails.driftStart;
  15100. const advancedDateTime = newDetails.advancedDateTime;
  15101. if (newDetails.advanced && advancedDateTime) {
  15102. const edge = newDetails.edge;
  15103. if (!newDetails.driftStart) {
  15104. newDetails.driftStartTime = advancedDateTime;
  15105. newDetails.driftStart = edge;
  15106. }
  15107. newDetails.driftEndTime = advancedDateTime;
  15108. newDetails.driftEnd = edge;
  15109. } else {
  15110. newDetails.driftEndTime = oldDetails.driftEndTime;
  15111. newDetails.driftEnd = oldDetails.driftEnd;
  15112. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  15113. }
  15114. if (newDetails.requestScheduled === -1) {
  15115. newDetails.requestScheduled = oldDetails.requestScheduled;
  15116. }
  15117. }
  15118. function mergeDateRanges(oldDateRanges, newDetails) {
  15119. const {
  15120. dateRanges: deltaDateRanges,
  15121. recentlyRemovedDateranges
  15122. } = newDetails;
  15123. const dateRanges = _extends({}, oldDateRanges);
  15124. if (recentlyRemovedDateranges) {
  15125. recentlyRemovedDateranges.forEach((id) => {
  15126. delete dateRanges[id];
  15127. });
  15128. }
  15129. const mergeIds = Object.keys(dateRanges);
  15130. const mergeCount = mergeIds.length;
  15131. if (mergeCount) {
  15132. Object.keys(deltaDateRanges).forEach((id) => {
  15133. const mergedDateRange = dateRanges[id];
  15134. const dateRange = new DateRange(deltaDateRanges[id].attr, mergedDateRange);
  15135. if (dateRange.isValid) {
  15136. dateRanges[id] = dateRange;
  15137. if (!mergedDateRange) {
  15138. dateRange.tagOrder += mergeCount;
  15139. }
  15140. } else {
  15141. logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${stringify(deltaDateRanges[id].attr)}"`);
  15142. }
  15143. });
  15144. }
  15145. return dateRanges;
  15146. }
  15147. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  15148. if (oldParts && newParts) {
  15149. let delta = 0;
  15150. for (let i2 = 0, len = oldParts.length; i2 <= len; i2++) {
  15151. const oldPart = oldParts[i2];
  15152. const newPart = newParts[i2 + delta];
  15153. if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {
  15154. intersectionFn(oldPart, newPart);
  15155. } else {
  15156. delta--;
  15157. }
  15158. }
  15159. }
  15160. }
  15161. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  15162. const skippedSegments = newDetails.skippedSegments;
  15163. const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  15164. const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  15165. const delta = newDetails.startSN - oldDetails.startSN;
  15166. const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  15167. const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  15168. for (let i2 = start; i2 <= end; i2++) {
  15169. const oldFrag = oldFrags[delta + i2];
  15170. let newFrag = newFrags[i2];
  15171. if (skippedSegments && !newFrag && oldFrag) {
  15172. newFrag = newDetails.fragments[i2] = oldFrag;
  15173. }
  15174. if (oldFrag && newFrag) {
  15175. intersectionFn(oldFrag, newFrag, i2, newFrags);
  15176. if (oldFrag.url && oldFrag.url !== newFrag.url) {
  15177. newDetails.playlistParsingError = getSequenceError(`media sequence mismatch ${newFrag.sn}:`, oldDetails, newDetails, oldFrag, newFrag);
  15178. return;
  15179. } else if (oldFrag.cc !== newFrag.cc) {
  15180. newDetails.playlistParsingError = getSequenceError(`discontinuity sequence mismatch (${oldFrag.cc}!=${newFrag.cc})`, oldDetails, newDetails, oldFrag, newFrag);
  15181. return;
  15182. }
  15183. }
  15184. }
  15185. }
  15186. function getSequenceError(message, oldDetails, newDetails, oldFrag, newFrag) {
  15187. return new Error(`${message} ${newFrag.url}
  15188. Playlist starting @${oldDetails.startSN}
  15189. ${oldDetails.m3u8}
  15190. Playlist starting @${newDetails.startSN}
  15191. ${newDetails.m3u8}`);
  15192. }
  15193. function adjustSliding(oldDetails, newDetails, matchingStableVariantOrRendition = true) {
  15194. const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  15195. const oldFragments = oldDetails.fragments;
  15196. const advancedOrStable = delta >= 0;
  15197. let sliding = 0;
  15198. if (advancedOrStable && delta < oldFragments.length) {
  15199. sliding = oldFragments[delta].start;
  15200. } else if (advancedOrStable && newDetails.startSN === oldDetails.endSN + 1) {
  15201. sliding = oldDetails.fragmentEnd;
  15202. } else if (advancedOrStable && matchingStableVariantOrRendition) {
  15203. sliding = oldDetails.fragmentStart + delta * newDetails.levelTargetDuration;
  15204. } else if (!newDetails.skippedSegments && newDetails.fragmentStart === 0) {
  15205. sliding = oldDetails.fragmentStart;
  15206. } else {
  15207. return;
  15208. }
  15209. addSliding(newDetails, sliding);
  15210. }
  15211. function addSliding(details, sliding) {
  15212. if (sliding) {
  15213. const fragments = details.fragments;
  15214. for (let i2 = details.skippedSegments; i2 < fragments.length; i2++) {
  15215. fragments[i2].addStart(sliding);
  15216. }
  15217. if (details.fragmentHint) {
  15218. details.fragmentHint.addStart(sliding);
  15219. }
  15220. }
  15221. }
  15222. function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {
  15223. let reloadInterval = 1e3 * newDetails.targetduration;
  15224. if (newDetails.updated) {
  15225. const fragments = newDetails.fragments;
  15226. const liveEdgeMaxTargetDurations = 4;
  15227. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  15228. const lastSegmentDuration = fragments[fragments.length - 1].duration * 1e3;
  15229. if (lastSegmentDuration < reloadInterval) {
  15230. reloadInterval = lastSegmentDuration;
  15231. }
  15232. }
  15233. } else {
  15234. reloadInterval /= 2;
  15235. }
  15236. return Math.round(reloadInterval);
  15237. }
  15238. function getFragmentWithSN(details, sn2, fragCurrent) {
  15239. if (!details) {
  15240. return null;
  15241. }
  15242. let fragment = details.fragments[sn2 - details.startSN];
  15243. if (fragment) {
  15244. return fragment;
  15245. }
  15246. fragment = details.fragmentHint;
  15247. if (fragment && fragment.sn === sn2) {
  15248. return fragment;
  15249. }
  15250. if (sn2 < details.startSN && fragCurrent && fragCurrent.sn === sn2) {
  15251. return fragCurrent;
  15252. }
  15253. return null;
  15254. }
  15255. function getPartWith(details, sn2, partIndex) {
  15256. if (!details) {
  15257. return null;
  15258. }
  15259. return findPart(details.partList, sn2, partIndex);
  15260. }
  15261. function findPart(partList, sn2, partIndex) {
  15262. if (partList) {
  15263. for (let i2 = partList.length; i2--; ) {
  15264. const part = partList[i2];
  15265. if (part.index === partIndex && part.fragment.sn === sn2) {
  15266. return part;
  15267. }
  15268. }
  15269. }
  15270. return null;
  15271. }
  15272. function reassignFragmentLevelIndexes(levels) {
  15273. levels.forEach((level, index2) => {
  15274. var _level$details;
  15275. (_level$details = level.details) == null ? void 0 : _level$details.fragments.forEach((fragment) => {
  15276. fragment.level = index2;
  15277. if (fragment.initSegment) {
  15278. fragment.initSegment.level = index2;
  15279. }
  15280. });
  15281. });
  15282. }
  15283. function findFirstFragWithCC(fragments, cc) {
  15284. for (let i2 = 0, len = fragments.length; i2 < len; i2++) {
  15285. var _fragments$i;
  15286. if (((_fragments$i = fragments[i2]) == null ? void 0 : _fragments$i.cc) === cc) {
  15287. return fragments[i2];
  15288. }
  15289. }
  15290. return null;
  15291. }
  15292. function shouldAlignOnDiscontinuities(refDetails, details) {
  15293. if (refDetails) {
  15294. if (details.startCC < refDetails.endCC && details.endCC > refDetails.startCC) {
  15295. return true;
  15296. }
  15297. }
  15298. return false;
  15299. }
  15300. function adjustFragmentStart(frag, sliding) {
  15301. if (frag) {
  15302. const start = frag.start + sliding;
  15303. frag.start = frag.startPTS = start;
  15304. frag.endPTS = start + frag.duration;
  15305. }
  15306. }
  15307. function adjustSlidingStart(sliding, details) {
  15308. const fragments = details.fragments;
  15309. for (let i2 = 0, len = fragments.length; i2 < len; i2++) {
  15310. adjustFragmentStart(fragments[i2], sliding);
  15311. }
  15312. if (details.fragmentHint) {
  15313. adjustFragmentStart(details.fragmentHint, sliding);
  15314. }
  15315. details.alignedSliding = true;
  15316. }
  15317. function alignStream(switchDetails, details) {
  15318. if (!switchDetails) {
  15319. return;
  15320. }
  15321. alignDiscontinuities(details, switchDetails);
  15322. if (!details.alignedSliding && switchDetails) {
  15323. alignMediaPlaylistByPDT(details, switchDetails);
  15324. }
  15325. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  15326. adjustSliding(switchDetails, details, false);
  15327. }
  15328. }
  15329. function alignDiscontinuities(details, refDetails) {
  15330. if (!shouldAlignOnDiscontinuities(refDetails, details)) {
  15331. return;
  15332. }
  15333. const targetCC = Math.min(refDetails.endCC, details.endCC);
  15334. const refFrag = findFirstFragWithCC(refDetails.fragments, targetCC);
  15335. const frag = findFirstFragWithCC(details.fragments, targetCC);
  15336. if (!refFrag || !frag) {
  15337. return;
  15338. }
  15339. logger.log(`Aligning playlist at start of dicontinuity sequence ${targetCC}`);
  15340. const delta = refFrag.start - frag.start;
  15341. adjustSlidingStart(delta, details);
  15342. }
  15343. function alignMediaPlaylistByPDT(details, refDetails) {
  15344. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  15345. return;
  15346. }
  15347. const fragments = details.fragments;
  15348. const refFragments = refDetails.fragments;
  15349. if (!fragments.length || !refFragments.length) {
  15350. return;
  15351. }
  15352. let refFrag;
  15353. let frag;
  15354. const targetCC = Math.min(refDetails.endCC, details.endCC);
  15355. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  15356. refFrag = findFirstFragWithCC(refFragments, targetCC);
  15357. frag = findFirstFragWithCC(fragments, targetCC);
  15358. }
  15359. if (!refFrag || !frag) {
  15360. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  15361. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  15362. }
  15363. const refPDT = refFrag.programDateTime;
  15364. const targetPDT = frag.programDateTime;
  15365. if (!refPDT || !targetPDT) {
  15366. return;
  15367. }
  15368. const delta = (targetPDT - refPDT) / 1e3 - (frag.start - refFrag.start);
  15369. adjustSlidingStart(delta, details);
  15370. }
  15371. const TimeRanges = {
  15372. toString: function(r2) {
  15373. let log = "";
  15374. const len = r2.length;
  15375. for (let i2 = 0; i2 < len; i2++) {
  15376. log += `[${r2.start(i2).toFixed(3)}-${r2.end(i2).toFixed(3)}]`;
  15377. }
  15378. return log;
  15379. }
  15380. };
  15381. const State = {
  15382. STOPPED: "STOPPED",
  15383. IDLE: "IDLE",
  15384. KEY_LOADING: "KEY_LOADING",
  15385. FRAG_LOADING: "FRAG_LOADING",
  15386. FRAG_LOADING_WAITING_RETRY: "FRAG_LOADING_WAITING_RETRY",
  15387. WAITING_TRACK: "WAITING_TRACK",
  15388. PARSING: "PARSING",
  15389. PARSED: "PARSED",
  15390. ENDED: "ENDED",
  15391. ERROR: "ERROR",
  15392. WAITING_INIT_PTS: "WAITING_INIT_PTS",
  15393. WAITING_LEVEL: "WAITING_LEVEL"
  15394. };
  15395. class BaseStreamController extends TaskLoop {
  15396. constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  15397. super(logPrefix, hls.logger);
  15398. this.hls = void 0;
  15399. this.fragPrevious = null;
  15400. this.fragCurrent = null;
  15401. this.fragmentTracker = void 0;
  15402. this.transmuxer = null;
  15403. this._state = State.STOPPED;
  15404. this.playlistType = void 0;
  15405. this.media = null;
  15406. this.mediaBuffer = null;
  15407. this.config = void 0;
  15408. this.bitrateTest = false;
  15409. this.lastCurrentTime = 0;
  15410. this.nextLoadPosition = 0;
  15411. this.startPosition = 0;
  15412. this.startTimeOffset = null;
  15413. this.retryDate = 0;
  15414. this.levels = null;
  15415. this.fragmentLoader = void 0;
  15416. this.keyLoader = void 0;
  15417. this.levelLastLoaded = null;
  15418. this.startFragRequested = false;
  15419. this.decrypter = void 0;
  15420. this.initPTS = [];
  15421. this.buffering = true;
  15422. this.loadingParts = false;
  15423. this.loopSn = void 0;
  15424. this.onMediaSeeking = () => {
  15425. const {
  15426. config,
  15427. fragCurrent,
  15428. media,
  15429. mediaBuffer,
  15430. state
  15431. } = this;
  15432. const currentTime = media ? media.currentTime : 0;
  15433. const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  15434. const noFowardBuffer = !bufferInfo.len;
  15435. this.log(`Media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}, ${noFowardBuffer ? "out of" : "in"} buffer`);
  15436. if (this.state === State.ENDED) {
  15437. this.resetLoadingState();
  15438. } else if (fragCurrent) {
  15439. const tolerance = config.maxFragLookUpTolerance;
  15440. const fragStartOffset = fragCurrent.start - tolerance;
  15441. const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  15442. if (noFowardBuffer || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  15443. const pastFragment = currentTime > fragEndOffset;
  15444. if (currentTime < fragStartOffset || pastFragment) {
  15445. if (pastFragment && fragCurrent.loader) {
  15446. this.log(`Cancelling fragment load for seek (sn: ${fragCurrent.sn})`);
  15447. fragCurrent.abortRequests();
  15448. this.resetLoadingState();
  15449. }
  15450. this.fragPrevious = null;
  15451. }
  15452. }
  15453. }
  15454. if (media) {
  15455. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  15456. const lastCurrentTime = this.lastCurrentTime;
  15457. if (currentTime > lastCurrentTime) {
  15458. this.lastCurrentTime = currentTime;
  15459. }
  15460. if (!this.loadingParts) {
  15461. const bufferEnd = Math.max(bufferInfo.end, currentTime);
  15462. const shouldLoadParts = this.shouldLoadParts(this.getLevelDetails(), bufferEnd);
  15463. if (shouldLoadParts) {
  15464. this.log(`LL-Part loading ON after seeking to ${currentTime.toFixed(2)} with buffer @${bufferEnd.toFixed(2)}`);
  15465. this.loadingParts = shouldLoadParts;
  15466. }
  15467. }
  15468. }
  15469. if (!this.hls.hasEnoughToStart) {
  15470. this.log(`Setting ${noFowardBuffer ? "startPosition" : "nextLoadPosition"} to ${currentTime} for seek without enough to start`);
  15471. this.nextLoadPosition = currentTime;
  15472. if (noFowardBuffer) {
  15473. this.startPosition = currentTime;
  15474. }
  15475. }
  15476. this.tickImmediate();
  15477. };
  15478. this.onMediaEnded = () => {
  15479. this.log(`setting startPosition to 0 because media ended`);
  15480. this.startPosition = this.lastCurrentTime = 0;
  15481. };
  15482. this.playlistType = playlistType;
  15483. this.hls = hls;
  15484. this.fragmentLoader = new FragmentLoader(hls.config);
  15485. this.keyLoader = keyLoader;
  15486. this.fragmentTracker = fragmentTracker;
  15487. this.config = hls.config;
  15488. this.decrypter = new Decrypter(hls.config);
  15489. }
  15490. registerListeners() {
  15491. const {
  15492. hls
  15493. } = this;
  15494. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  15495. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  15496. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15497. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  15498. hls.on(Events.ERROR, this.onError, this);
  15499. }
  15500. unregisterListeners() {
  15501. const {
  15502. hls
  15503. } = this;
  15504. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  15505. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  15506. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15507. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  15508. hls.off(Events.ERROR, this.onError, this);
  15509. }
  15510. doTick() {
  15511. this.onTickEnd();
  15512. }
  15513. onTickEnd() {
  15514. }
  15515. startLoad(startPosition) {
  15516. }
  15517. stopLoad() {
  15518. if (this.state === State.STOPPED) {
  15519. return;
  15520. }
  15521. this.fragmentLoader.abort();
  15522. this.keyLoader.abort(this.playlistType);
  15523. const frag = this.fragCurrent;
  15524. if (frag != null && frag.loader) {
  15525. frag.abortRequests();
  15526. this.fragmentTracker.removeFragment(frag);
  15527. }
  15528. this.resetTransmuxer();
  15529. this.fragCurrent = null;
  15530. this.fragPrevious = null;
  15531. this.clearInterval();
  15532. this.clearNextTick();
  15533. this.state = State.STOPPED;
  15534. }
  15535. get startPositionValue() {
  15536. const {
  15537. nextLoadPosition,
  15538. startPosition
  15539. } = this;
  15540. if (startPosition === -1 && nextLoadPosition) {
  15541. return nextLoadPosition;
  15542. }
  15543. return startPosition;
  15544. }
  15545. get bufferingEnabled() {
  15546. return this.buffering;
  15547. }
  15548. pauseBuffering() {
  15549. this.buffering = false;
  15550. }
  15551. resumeBuffering() {
  15552. this.buffering = true;
  15553. }
  15554. get inFlightFrag() {
  15555. return {
  15556. frag: this.fragCurrent,
  15557. state: this.state
  15558. };
  15559. }
  15560. _streamEnded(bufferInfo, levelDetails) {
  15561. if (levelDetails.live || !this.media) {
  15562. return false;
  15563. }
  15564. const bufferEnd = bufferInfo.end || 0;
  15565. const timelineStart = this.config.timelineOffset || 0;
  15566. if (bufferEnd <= timelineStart) {
  15567. return false;
  15568. }
  15569. const bufferedRanges = bufferInfo.buffered;
  15570. if (this.config.maxBufferHole && bufferedRanges && bufferedRanges.length > 1) {
  15571. bufferInfo = BufferHelper.bufferedInfo(bufferedRanges, bufferInfo.start, 0);
  15572. }
  15573. const nextStart = bufferInfo.nextStart;
  15574. const hasSecondBufferedRange = nextStart && nextStart > timelineStart && nextStart < levelDetails.edge;
  15575. if (hasSecondBufferedRange) {
  15576. return false;
  15577. }
  15578. if (this.media.currentTime < bufferInfo.start) {
  15579. return false;
  15580. }
  15581. const partList = levelDetails.partList;
  15582. if (partList != null && partList.length) {
  15583. const lastPart = partList[partList.length - 1];
  15584. const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  15585. return lastPartBuffered;
  15586. }
  15587. const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  15588. return this.fragmentTracker.isEndListAppended(playlistType);
  15589. }
  15590. getLevelDetails() {
  15591. if (this.levels && this.levelLastLoaded !== null) {
  15592. var _this$levelLastLoaded;
  15593. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  15594. }
  15595. }
  15596. get timelineOffset() {
  15597. const configuredTimelineOffset = this.config.timelineOffset;
  15598. if (configuredTimelineOffset) {
  15599. var _this$getLevelDetails;
  15600. return ((_this$getLevelDetails = this.getLevelDetails()) == null ? void 0 : _this$getLevelDetails.appliedTimelineOffset) || configuredTimelineOffset;
  15601. }
  15602. return 0;
  15603. }
  15604. onMediaAttached(event, data) {
  15605. const media = this.media = this.mediaBuffer = data.media;
  15606. media.removeEventListener("seeking", this.onMediaSeeking);
  15607. media.removeEventListener("ended", this.onMediaEnded);
  15608. media.addEventListener("seeking", this.onMediaSeeking);
  15609. media.addEventListener("ended", this.onMediaEnded);
  15610. const config = this.config;
  15611. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  15612. this.startLoad(config.startPosition);
  15613. }
  15614. }
  15615. onMediaDetaching(event, data) {
  15616. const transferringMedia = !!data.transferMedia;
  15617. const media = this.media;
  15618. if (media === null) {
  15619. return;
  15620. }
  15621. if (media.ended) {
  15622. this.log("MSE detaching and video ended, reset startPosition");
  15623. this.startPosition = this.lastCurrentTime = 0;
  15624. }
  15625. media.removeEventListener("seeking", this.onMediaSeeking);
  15626. media.removeEventListener("ended", this.onMediaEnded);
  15627. if (this.keyLoader && !transferringMedia) {
  15628. this.keyLoader.detach();
  15629. }
  15630. this.media = this.mediaBuffer = null;
  15631. this.loopSn = void 0;
  15632. if (transferringMedia) {
  15633. this.resetLoadingState();
  15634. this.resetTransmuxer();
  15635. return;
  15636. }
  15637. this.loadingParts = false;
  15638. this.fragmentTracker.removeAllFragments();
  15639. this.stopLoad();
  15640. }
  15641. onManifestLoading() {
  15642. this.initPTS = [];
  15643. this.levels = this.levelLastLoaded = this.fragCurrent = null;
  15644. this.lastCurrentTime = this.startPosition = 0;
  15645. this.startFragRequested = false;
  15646. }
  15647. onError(event, data) {
  15648. }
  15649. onManifestLoaded(event, data) {
  15650. this.startTimeOffset = data.startTimeOffset;
  15651. }
  15652. onHandlerDestroying() {
  15653. this.stopLoad();
  15654. if (this.transmuxer) {
  15655. this.transmuxer.destroy();
  15656. this.transmuxer = null;
  15657. }
  15658. super.onHandlerDestroying();
  15659. this.hls = this.onMediaSeeking = this.onMediaEnded = null;
  15660. }
  15661. onHandlerDestroyed() {
  15662. this.state = State.STOPPED;
  15663. if (this.fragmentLoader) {
  15664. this.fragmentLoader.destroy();
  15665. }
  15666. if (this.keyLoader) {
  15667. this.keyLoader.destroy();
  15668. }
  15669. if (this.decrypter) {
  15670. this.decrypter.destroy();
  15671. }
  15672. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  15673. super.onHandlerDestroyed();
  15674. }
  15675. loadFragment(frag, level, targetBufferTime) {
  15676. this.startFragRequested = true;
  15677. this._loadFragForPlayback(frag, level, targetBufferTime);
  15678. }
  15679. _loadFragForPlayback(fragment, level, targetBufferTime) {
  15680. const progressCallback = (data) => {
  15681. const frag = data.frag;
  15682. if (this.fragContextChanged(frag)) {
  15683. this.warn(`${frag.type} sn: ${frag.sn}${data.part ? " part: " + data.part.index : ""} of ${this.fragInfo(frag, false, data.part)}) was dropped during download.`);
  15684. this.fragmentTracker.removeFragment(frag);
  15685. return;
  15686. }
  15687. frag.stats.chunkCount++;
  15688. this._handleFragmentLoadProgress(data);
  15689. };
  15690. this._doFragLoad(fragment, level, targetBufferTime, progressCallback).then((data) => {
  15691. if (!data) {
  15692. return;
  15693. }
  15694. const state = this.state;
  15695. const frag = data.frag;
  15696. if (this.fragContextChanged(frag)) {
  15697. if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {
  15698. this.fragmentTracker.removeFragment(frag);
  15699. this.state = State.IDLE;
  15700. }
  15701. return;
  15702. }
  15703. if ("payload" in data) {
  15704. this.log(`Loaded ${frag.type} sn: ${frag.sn} of ${this.playlistLabel()} ${frag.level}`);
  15705. this.hls.trigger(Events.FRAG_LOADED, data);
  15706. }
  15707. this._handleFragmentLoadComplete(data);
  15708. }).catch((reason) => {
  15709. if (this.state === State.STOPPED || this.state === State.ERROR) {
  15710. return;
  15711. }
  15712. this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);
  15713. this.resetFragmentLoading(fragment);
  15714. });
  15715. }
  15716. clearTrackerIfNeeded(frag) {
  15717. var _this$mediaBuffer;
  15718. const {
  15719. fragmentTracker
  15720. } = this;
  15721. const fragState = fragmentTracker.getState(frag);
  15722. if (fragState === FragmentState.APPENDING) {
  15723. const playlistType = frag.type;
  15724. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  15725. const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  15726. const backtrackFragment = this.backtrackFragment;
  15727. const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  15728. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  15729. fragmentTracker.removeFragment(frag);
  15730. }
  15731. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  15732. fragmentTracker.removeAllFragments();
  15733. } else if (fragmentTracker.hasParts(frag.type)) {
  15734. fragmentTracker.detectPartialFragments({
  15735. frag,
  15736. part: null,
  15737. stats: frag.stats,
  15738. id: frag.type
  15739. });
  15740. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  15741. fragmentTracker.removeFragment(frag);
  15742. }
  15743. }
  15744. }
  15745. checkLiveUpdate(details) {
  15746. if (details.updated && !details.live) {
  15747. const lastFragment = details.fragments[details.fragments.length - 1];
  15748. this.fragmentTracker.detectPartialFragments({
  15749. frag: lastFragment,
  15750. part: null,
  15751. stats: lastFragment.stats,
  15752. id: lastFragment.type
  15753. });
  15754. }
  15755. if (!details.fragments[0]) {
  15756. details.deltaUpdateFailed = true;
  15757. }
  15758. }
  15759. waitForLive(levelInfo) {
  15760. const details = levelInfo.details;
  15761. return (details == null ? void 0 : details.live) && details.type !== "EVENT" && (this.levelLastLoaded !== levelInfo || details.expired);
  15762. }
  15763. flushMainBuffer(startOffset, endOffset, type = null) {
  15764. if (!(startOffset - endOffset)) {
  15765. return;
  15766. }
  15767. const flushScope = {
  15768. startOffset,
  15769. endOffset,
  15770. type
  15771. };
  15772. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  15773. }
  15774. _loadInitSegment(fragment, level) {
  15775. this._doFragLoad(fragment, level).then((data) => {
  15776. const frag = data == null ? void 0 : data.frag;
  15777. if (!frag || this.fragContextChanged(frag) || !this.levels) {
  15778. throw new Error("init load aborted");
  15779. }
  15780. return data;
  15781. }).then((data) => {
  15782. const {
  15783. hls
  15784. } = this;
  15785. const {
  15786. frag,
  15787. payload
  15788. } = data;
  15789. const decryptData = frag.decryptdata;
  15790. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  15791. const startTime = self.performance.now();
  15792. return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
  15793. hls.trigger(Events.ERROR, {
  15794. type: ErrorTypes.MEDIA_ERROR,
  15795. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  15796. fatal: false,
  15797. error: err,
  15798. reason: err.message,
  15799. frag
  15800. });
  15801. throw err;
  15802. }).then((decryptedData) => {
  15803. const endTime = self.performance.now();
  15804. hls.trigger(Events.FRAG_DECRYPTED, {
  15805. frag,
  15806. payload: decryptedData,
  15807. stats: {
  15808. tstart: startTime,
  15809. tdecrypt: endTime
  15810. }
  15811. });
  15812. data.payload = decryptedData;
  15813. return this.completeInitSegmentLoad(data);
  15814. });
  15815. }
  15816. return this.completeInitSegmentLoad(data);
  15817. }).catch((reason) => {
  15818. if (this.state === State.STOPPED || this.state === State.ERROR) {
  15819. return;
  15820. }
  15821. this.warn(reason);
  15822. this.resetFragmentLoading(fragment);
  15823. });
  15824. }
  15825. completeInitSegmentLoad(data) {
  15826. const {
  15827. levels
  15828. } = this;
  15829. if (!levels) {
  15830. throw new Error("init load aborted, missing levels");
  15831. }
  15832. const stats = data.frag.stats;
  15833. if (this.state !== State.STOPPED) {
  15834. this.state = State.IDLE;
  15835. }
  15836. data.frag.data = new Uint8Array(data.payload);
  15837. stats.parsing.start = stats.buffering.start = self.performance.now();
  15838. stats.parsing.end = stats.buffering.end = self.performance.now();
  15839. this.tick();
  15840. }
  15841. fragContextChanged(frag) {
  15842. const {
  15843. fragCurrent
  15844. } = this;
  15845. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  15846. }
  15847. fragBufferedComplete(frag, part) {
  15848. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  15849. this.log(`Buffered ${frag.type} sn: ${frag.sn}${part ? " part: " + part.index : ""} of ${this.fragInfo(frag, false, part)} > buffer:${media ? TimeRanges.toString(BufferHelper.getBuffered(media)) : "(detached)"})`);
  15850. if (isMediaFragment(frag)) {
  15851. var _this$levels;
  15852. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  15853. const el = frag.elementaryStreams;
  15854. if (!Object.keys(el).some((type) => !!el[type])) {
  15855. this.state = State.IDLE;
  15856. return;
  15857. }
  15858. }
  15859. const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  15860. if (level != null && level.fragmentError) {
  15861. this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);
  15862. level.fragmentError = 0;
  15863. }
  15864. }
  15865. this.state = State.IDLE;
  15866. }
  15867. _handleFragmentLoadComplete(fragLoadedEndData) {
  15868. const {
  15869. transmuxer
  15870. } = this;
  15871. if (!transmuxer) {
  15872. return;
  15873. }
  15874. const {
  15875. frag,
  15876. part,
  15877. partsLoaded
  15878. } = fragLoadedEndData;
  15879. const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some((fragLoaded) => !fragLoaded);
  15880. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  15881. transmuxer.flush(chunkMeta);
  15882. }
  15883. _handleFragmentLoadProgress(frag) {
  15884. }
  15885. _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {
  15886. var _frag$decryptdata;
  15887. this.fragCurrent = frag;
  15888. const details = level == null ? void 0 : level.details;
  15889. if (!this.levels || !details) {
  15890. throw new Error(`frag load aborted, missing level${details ? "" : " detail"}s`);
  15891. }
  15892. let keyLoadingPromise = null;
  15893. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  15894. this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.playlistLabel()} ${frag.level}`);
  15895. this.state = State.KEY_LOADING;
  15896. this.fragCurrent = frag;
  15897. keyLoadingPromise = this.keyLoader.load(frag).then((keyLoadedData) => {
  15898. if (!this.fragContextChanged(keyLoadedData.frag)) {
  15899. this.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  15900. if (this.state === State.KEY_LOADING) {
  15901. this.state = State.IDLE;
  15902. }
  15903. return keyLoadedData;
  15904. }
  15905. });
  15906. this.hls.trigger(Events.KEY_LOADING, {
  15907. frag
  15908. });
  15909. if (this.fragCurrent === null) {
  15910. keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`));
  15911. }
  15912. } else if (!frag.encrypted) {
  15913. keyLoadingPromise = this.keyLoader.loadClear(frag, details.encryptedFragments, this.startFragRequested);
  15914. if (keyLoadingPromise) {
  15915. this.log(`[eme] blocking frag load until media-keys acquired`);
  15916. }
  15917. }
  15918. const fragPrevious = this.fragPrevious;
  15919. if (isMediaFragment(frag) && (!fragPrevious || frag.sn !== fragPrevious.sn)) {
  15920. const shouldLoadParts = this.shouldLoadParts(level.details, frag.end);
  15921. if (shouldLoadParts !== this.loadingParts) {
  15922. this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} loading sn ${fragPrevious == null ? void 0 : fragPrevious.sn}->${frag.sn}`);
  15923. this.loadingParts = shouldLoadParts;
  15924. }
  15925. }
  15926. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  15927. if (this.loadingParts && isMediaFragment(frag)) {
  15928. const partList = details.partList;
  15929. if (partList && progressCallback) {
  15930. if (targetBufferTime > frag.end && details.fragmentHint) {
  15931. frag = details.fragmentHint;
  15932. }
  15933. const partIndex = this.getNextPart(partList, frag, targetBufferTime);
  15934. if (partIndex > -1) {
  15935. const part = partList[partIndex];
  15936. frag = this.fragCurrent = part.fragment;
  15937. this.log(`Loading ${frag.type} sn: ${frag.sn} part: ${part.index} (${partIndex}/${partList.length - 1}) of ${this.fragInfo(frag, false, part)}) cc: ${frag.cc} [${details.startSN}-${details.endSN}], target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  15938. this.nextLoadPosition = part.start + part.duration;
  15939. this.state = State.FRAG_LOADING;
  15940. let _result;
  15941. if (keyLoadingPromise) {
  15942. _result = keyLoadingPromise.then((keyLoadedData) => {
  15943. if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
  15944. return null;
  15945. }
  15946. return this.doFragPartsLoad(frag, part, level, progressCallback);
  15947. }).catch((error) => this.handleFragLoadError(error));
  15948. } else {
  15949. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch((error) => this.handleFragLoadError(error));
  15950. }
  15951. this.hls.trigger(Events.FRAG_LOADING, {
  15952. frag,
  15953. part,
  15954. targetBufferTime
  15955. });
  15956. if (this.fragCurrent === null) {
  15957. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));
  15958. }
  15959. return _result;
  15960. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  15961. return Promise.resolve(null);
  15962. }
  15963. }
  15964. }
  15965. if (isMediaFragment(frag) && this.loadingParts) {
  15966. this.log(`LL-Part loading OFF after next part miss @${targetBufferTime.toFixed(2)}`);
  15967. this.loadingParts = false;
  15968. } else if (!frag.url) {
  15969. return Promise.resolve(null);
  15970. }
  15971. this.log(`Loading ${frag.type} sn: ${frag.sn} of ${this.fragInfo(frag, false)}) cc: ${frag.cc} ${details ? "[" + details.startSN + "-" + details.endSN + "]" : ""}, target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  15972. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  15973. this.nextLoadPosition = frag.start + frag.duration;
  15974. }
  15975. this.state = State.FRAG_LOADING;
  15976. const dataOnProgress = this.config.progressive;
  15977. let result;
  15978. if (dataOnProgress && keyLoadingPromise) {
  15979. result = keyLoadingPromise.then((keyLoadedData) => {
  15980. if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  15981. return null;
  15982. }
  15983. return this.fragmentLoader.load(frag, progressCallback);
  15984. }).catch((error) => this.handleFragLoadError(error));
  15985. } else {
  15986. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : void 0), keyLoadingPromise]).then(([fragLoadedData]) => {
  15987. if (!dataOnProgress && fragLoadedData && progressCallback) {
  15988. progressCallback(fragLoadedData);
  15989. }
  15990. return fragLoadedData;
  15991. }).catch((error) => this.handleFragLoadError(error));
  15992. }
  15993. this.hls.trigger(Events.FRAG_LOADING, {
  15994. frag,
  15995. targetBufferTime
  15996. });
  15997. if (this.fragCurrent === null) {
  15998. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));
  15999. }
  16000. return result;
  16001. }
  16002. doFragPartsLoad(frag, fromPart, level, progressCallback) {
  16003. return new Promise((resolve2, reject) => {
  16004. var _level$details;
  16005. const partsLoaded = [];
  16006. const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  16007. const loadPart = (part) => {
  16008. this.fragmentLoader.loadPart(frag, part, progressCallback).then((partLoadedData) => {
  16009. partsLoaded[part.index] = partLoadedData;
  16010. const loadedPart = partLoadedData.part;
  16011. this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  16012. const nextPart = getPartWith(level.details, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  16013. if (nextPart) {
  16014. loadPart(nextPart);
  16015. } else {
  16016. return resolve2({
  16017. frag,
  16018. part: loadedPart,
  16019. partsLoaded
  16020. });
  16021. }
  16022. }).catch(reject);
  16023. };
  16024. loadPart(fromPart);
  16025. });
  16026. }
  16027. handleFragLoadError(error) {
  16028. if ("data" in error) {
  16029. const data = error.data;
  16030. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  16031. this.handleFragLoadAborted(data.frag, data.part);
  16032. } else {
  16033. this.hls.trigger(Events.ERROR, data);
  16034. }
  16035. } else {
  16036. this.hls.trigger(Events.ERROR, {
  16037. type: ErrorTypes.OTHER_ERROR,
  16038. details: ErrorDetails.INTERNAL_EXCEPTION,
  16039. err: error,
  16040. error,
  16041. fatal: true
  16042. });
  16043. }
  16044. return null;
  16045. }
  16046. _handleTransmuxerFlush(chunkMeta) {
  16047. const context = this.getCurrentContext(chunkMeta);
  16048. if (!context || this.state !== State.PARSING) {
  16049. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  16050. this.state = State.IDLE;
  16051. }
  16052. return;
  16053. }
  16054. const {
  16055. frag,
  16056. part,
  16057. level
  16058. } = context;
  16059. const now2 = self.performance.now();
  16060. frag.stats.parsing.end = now2;
  16061. if (part) {
  16062. part.stats.parsing.end = now2;
  16063. }
  16064. const levelDetails = this.getLevelDetails();
  16065. const loadingPartsAtEdge = levelDetails && frag.sn > levelDetails.endSN;
  16066. const shouldLoadParts = loadingPartsAtEdge || this.shouldLoadParts(levelDetails, frag.end);
  16067. if (shouldLoadParts !== this.loadingParts) {
  16068. this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} after parsing segment ending @${frag.end.toFixed(2)}`);
  16069. this.loadingParts = shouldLoadParts;
  16070. }
  16071. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  16072. }
  16073. shouldLoadParts(details, bufferEnd) {
  16074. if (this.config.lowLatencyMode) {
  16075. if (!details) {
  16076. return this.loadingParts;
  16077. }
  16078. if (details != null && details.partList) {
  16079. var _details$fragmentHint;
  16080. const firstPart = details.partList[0];
  16081. const safePartStart = firstPart.end + (((_details$fragmentHint = details.fragmentHint) == null ? void 0 : _details$fragmentHint.duration) || 0);
  16082. if (bufferEnd >= safePartStart) {
  16083. var _this$media;
  16084. const playhead = this.hls.hasEnoughToStart ? ((_this$media = this.media) == null ? void 0 : _this$media.currentTime) || this.lastCurrentTime : this.getLoadPosition();
  16085. if (playhead > firstPart.start - firstPart.fragment.duration) {
  16086. return true;
  16087. }
  16088. }
  16089. }
  16090. }
  16091. return false;
  16092. }
  16093. getCurrentContext(chunkMeta) {
  16094. const {
  16095. levels,
  16096. fragCurrent
  16097. } = this;
  16098. const {
  16099. level: levelIndex,
  16100. sn: sn2,
  16101. part: partIndex
  16102. } = chunkMeta;
  16103. if (!(levels != null && levels[levelIndex])) {
  16104. this.warn(`Levels object was unset while buffering fragment ${sn2} of ${this.playlistLabel()} ${levelIndex}. The current chunk will not be buffered.`);
  16105. return null;
  16106. }
  16107. const level = levels[levelIndex];
  16108. const levelDetails = level.details;
  16109. const part = partIndex > -1 ? getPartWith(levelDetails, sn2, partIndex) : null;
  16110. const frag = part ? part.fragment : getFragmentWithSN(levelDetails, sn2, fragCurrent);
  16111. if (!frag) {
  16112. return null;
  16113. }
  16114. if (fragCurrent && fragCurrent !== frag) {
  16115. frag.stats = fragCurrent.stats;
  16116. }
  16117. return {
  16118. frag,
  16119. part,
  16120. level
  16121. };
  16122. }
  16123. bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  16124. var _buffer;
  16125. if (!data || this.state !== State.PARSING) {
  16126. return;
  16127. }
  16128. const {
  16129. data1,
  16130. data2
  16131. } = data;
  16132. let buffer2 = data1;
  16133. if (data1 && data2) {
  16134. buffer2 = appendUint8Array(data1, data2);
  16135. }
  16136. if (!((_buffer = buffer2) != null && _buffer.length)) {
  16137. return;
  16138. }
  16139. const offsetTimestamp = this.initPTS[frag.cc];
  16140. const offset = offsetTimestamp ? -offsetTimestamp.baseTime / offsetTimestamp.timescale : void 0;
  16141. const segment = {
  16142. type: data.type,
  16143. frag,
  16144. part,
  16145. chunkMeta,
  16146. offset,
  16147. parent: frag.type,
  16148. data: buffer2
  16149. };
  16150. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  16151. if (data.dropped && data.independent && !part) {
  16152. if (noBacktracking) {
  16153. return;
  16154. }
  16155. this.flushBufferGap(frag);
  16156. }
  16157. }
  16158. flushBufferGap(frag) {
  16159. const media = this.media;
  16160. if (!media) {
  16161. return;
  16162. }
  16163. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  16164. this.flushMainBuffer(0, frag.start);
  16165. return;
  16166. }
  16167. const currentTime = media.currentTime;
  16168. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  16169. const fragDuration = frag.duration;
  16170. const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  16171. const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  16172. if (frag.start - start > segmentFraction) {
  16173. this.flushMainBuffer(start, frag.start);
  16174. }
  16175. }
  16176. getFwdBufferInfo(bufferable, type) {
  16177. var _this$media2;
  16178. const pos = this.getLoadPosition();
  16179. if (!isFiniteNumber(pos)) {
  16180. return null;
  16181. }
  16182. const backwardSeek = this.lastCurrentTime > pos;
  16183. const maxBufferHole = backwardSeek || (_this$media2 = this.media) != null && _this$media2.paused ? 0 : this.config.maxBufferHole;
  16184. return this.getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole);
  16185. }
  16186. getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole) {
  16187. const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  16188. if (bufferInfo.len === 0 && bufferInfo.nextStart !== void 0) {
  16189. const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  16190. if (bufferedFragAtPos && (bufferInfo.nextStart <= bufferedFragAtPos.end || bufferedFragAtPos.gap)) {
  16191. const gapDuration = Math.max(Math.min(bufferInfo.nextStart, bufferedFragAtPos.end) - pos, maxBufferHole);
  16192. return BufferHelper.bufferInfo(bufferable, pos, gapDuration);
  16193. }
  16194. }
  16195. return bufferInfo;
  16196. }
  16197. getMaxBufferLength(levelBitrate) {
  16198. const {
  16199. config
  16200. } = this;
  16201. let maxBufLen;
  16202. if (levelBitrate) {
  16203. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  16204. } else {
  16205. maxBufLen = config.maxBufferLength;
  16206. }
  16207. return Math.min(maxBufLen, config.maxMaxBufferLength);
  16208. }
  16209. reduceMaxBufferLength(threshold, fragDuration) {
  16210. const config = this.config;
  16211. const minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
  16212. const reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
  16213. if (reducedLength >= minLength) {
  16214. config.maxMaxBufferLength = reducedLength;
  16215. this.warn(`Reduce max buffer length to ${reducedLength}s`);
  16216. return true;
  16217. }
  16218. return false;
  16219. }
  16220. getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {
  16221. var _this$fragmentTracker;
  16222. const fragOrPart = (_this$fragmentTracker = this.fragmentTracker) == null ? void 0 : _this$fragmentTracker.getAppendedFrag(position, playlistType);
  16223. if (fragOrPart && "fragment" in fragOrPart) {
  16224. return fragOrPart.fragment;
  16225. }
  16226. return fragOrPart;
  16227. }
  16228. getNextFragment(pos, levelDetails) {
  16229. const fragments = levelDetails.fragments;
  16230. const fragLen = fragments.length;
  16231. if (!fragLen) {
  16232. return null;
  16233. }
  16234. const {
  16235. config
  16236. } = this;
  16237. const start = fragments[0].start;
  16238. const canLoadParts = config.lowLatencyMode && !!levelDetails.partList;
  16239. let frag = null;
  16240. if (levelDetails.live) {
  16241. const initialLiveManifestSize = config.initialLiveManifestSize;
  16242. if (fragLen < initialLiveManifestSize) {
  16243. this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);
  16244. return null;
  16245. }
  16246. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  16247. var _frag;
  16248. if (canLoadParts && !this.loadingParts) {
  16249. this.log(`LL-Part loading ON for initial live fragment`);
  16250. this.loadingParts = true;
  16251. }
  16252. frag = this.getInitialLiveFragment(levelDetails);
  16253. const mainStart = this.hls.startPosition;
  16254. const liveSyncPosition = this.hls.liveSyncPosition;
  16255. const startPosition = frag ? (mainStart !== -1 && mainStart >= start ? mainStart : liveSyncPosition) || frag.start : pos;
  16256. this.log(`Setting startPosition to ${startPosition} to match start frag at live edge. mainStart: ${mainStart} liveSyncPosition: ${liveSyncPosition} frag.start: ${(_frag = frag) == null ? void 0 : _frag.start}`);
  16257. this.startPosition = this.nextLoadPosition = startPosition;
  16258. }
  16259. } else if (pos <= start) {
  16260. frag = fragments[0];
  16261. }
  16262. if (!frag) {
  16263. const end = this.loadingParts ? levelDetails.partEnd : levelDetails.fragmentEnd;
  16264. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  16265. }
  16266. let programFrag = this.filterReplacedPrimary(frag, levelDetails);
  16267. if (!programFrag && frag) {
  16268. const curSNIdx = frag.sn - levelDetails.startSN;
  16269. programFrag = this.filterReplacedPrimary(fragments[curSNIdx + 1] || null, levelDetails);
  16270. }
  16271. return this.mapToInitFragWhenRequired(programFrag);
  16272. }
  16273. isLoopLoading(frag, targetBufferTime) {
  16274. const trackerState = this.fragmentTracker.getState(frag);
  16275. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  16276. }
  16277. getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  16278. let nextFragment = null;
  16279. if (frag.gap) {
  16280. nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  16281. if (nextFragment && !nextFragment.gap && bufferInfo.nextStart) {
  16282. const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType, 0);
  16283. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  16284. const sn2 = nextFragment.sn;
  16285. if (this.loopSn !== sn2) {
  16286. this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${sn2}`);
  16287. this.loopSn = sn2;
  16288. }
  16289. return null;
  16290. }
  16291. }
  16292. }
  16293. this.loopSn = void 0;
  16294. return nextFragment;
  16295. }
  16296. get primaryPrefetch() {
  16297. if (interstitialsEnabled(this.hls.config)) {
  16298. var _this$hls$interstitia, _this$hls$interstitia2;
  16299. const playingInterstitial = (_this$hls$interstitia = this.hls.interstitialsManager) == null ? void 0 : (_this$hls$interstitia2 = _this$hls$interstitia.playingItem) == null ? void 0 : _this$hls$interstitia2.event;
  16300. if (playingInterstitial) {
  16301. return true;
  16302. }
  16303. }
  16304. return false;
  16305. }
  16306. filterReplacedPrimary(frag, details) {
  16307. if (!frag) {
  16308. return frag;
  16309. }
  16310. if (interstitialsEnabled(this.hls.config) && frag.type !== PlaylistLevelType.SUBTITLE) {
  16311. const interstitials = this.hls.interstitialsManager;
  16312. const bufferingItem = interstitials == null ? void 0 : interstitials.bufferingItem;
  16313. if (bufferingItem) {
  16314. const bufferingInterstitial = bufferingItem.event;
  16315. if (bufferingInterstitial) {
  16316. if (bufferingInterstitial.appendInPlace || Math.abs(frag.start - bufferingItem.start) > 1 || bufferingItem.start === 0) {
  16317. return null;
  16318. }
  16319. } else {
  16320. if (frag.end <= bufferingItem.start && (details == null ? void 0 : details.live) === false) {
  16321. return null;
  16322. }
  16323. if (frag.start > bufferingItem.end && bufferingItem.nextEvent) {
  16324. if (bufferingItem.nextEvent.appendInPlace || frag.start - bufferingItem.end > 1) {
  16325. return null;
  16326. }
  16327. }
  16328. }
  16329. }
  16330. const playerQueue = interstitials == null ? void 0 : interstitials.playerQueue;
  16331. if (playerQueue) {
  16332. for (let i2 = playerQueue.length; i2--; ) {
  16333. const interstitial = playerQueue[i2].interstitial;
  16334. if (interstitial.appendInPlace && frag.start >= interstitial.startTime && frag.end <= interstitial.resumeTime) {
  16335. return null;
  16336. }
  16337. }
  16338. }
  16339. }
  16340. return frag;
  16341. }
  16342. mapToInitFragWhenRequired(frag) {
  16343. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  16344. return frag.initSegment;
  16345. }
  16346. return frag;
  16347. }
  16348. getNextPart(partList, frag, targetBufferTime) {
  16349. let nextPart = -1;
  16350. let contiguous = false;
  16351. let independentAttrOmitted = true;
  16352. for (let i2 = 0, len = partList.length; i2 < len; i2++) {
  16353. const part = partList[i2];
  16354. independentAttrOmitted = independentAttrOmitted && !part.independent;
  16355. if (nextPart > -1 && targetBufferTime < part.start) {
  16356. break;
  16357. }
  16358. const loaded = part.loaded;
  16359. if (loaded) {
  16360. nextPart = -1;
  16361. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  16362. nextPart = i2;
  16363. }
  16364. contiguous = loaded;
  16365. }
  16366. return nextPart;
  16367. }
  16368. loadedEndOfParts(partList, targetBufferTime) {
  16369. const lastPart = partList[partList.length - 1];
  16370. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  16371. }
  16372. /*
  16373. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  16374. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  16375. start and end times for each fragment in the playlist (after which this method will not need to be called).
  16376. */
  16377. getInitialLiveFragment(levelDetails) {
  16378. const fragments = levelDetails.fragments;
  16379. const fragPrevious = this.fragPrevious;
  16380. let frag = null;
  16381. if (fragPrevious) {
  16382. if (levelDetails.hasProgramDateTime) {
  16383. this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
  16384. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  16385. }
  16386. if (!frag) {
  16387. const targetSN = fragPrevious.sn + 1;
  16388. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  16389. const fragNext = fragments[targetSN - levelDetails.startSN];
  16390. if (fragPrevious.cc === fragNext.cc) {
  16391. frag = fragNext;
  16392. this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
  16393. }
  16394. }
  16395. if (!frag) {
  16396. frag = findNearestWithCC(levelDetails, fragPrevious.cc, fragPrevious.end);
  16397. if (frag) {
  16398. this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
  16399. }
  16400. }
  16401. }
  16402. } else {
  16403. const liveStart = this.hls.liveSyncPosition;
  16404. if (liveStart !== null) {
  16405. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  16406. }
  16407. }
  16408. return frag;
  16409. }
  16410. /*
  16411. This method finds the best matching fragment given the provided position.
  16412. */
  16413. getFragmentAtPosition(bufferEnd, end, levelDetails) {
  16414. const {
  16415. config
  16416. } = this;
  16417. let {
  16418. fragPrevious
  16419. } = this;
  16420. let {
  16421. fragments,
  16422. endSN
  16423. } = levelDetails;
  16424. const {
  16425. fragmentHint
  16426. } = levelDetails;
  16427. const {
  16428. maxFragLookUpTolerance
  16429. } = config;
  16430. const partList = levelDetails.partList;
  16431. const loadingParts = !!(this.loadingParts && partList != null && partList.length && fragmentHint);
  16432. if (loadingParts && fragmentHint && !this.bitrateTest && partList[partList.length - 1].fragment.sn === fragmentHint.sn) {
  16433. fragments = fragments.concat(fragmentHint);
  16434. endSN = fragmentHint.sn;
  16435. }
  16436. let frag;
  16437. if (bufferEnd < end) {
  16438. var _this$media3;
  16439. const backwardSeek = bufferEnd < this.lastCurrentTime;
  16440. const lookupTolerance = backwardSeek || bufferEnd > end - maxFragLookUpTolerance || (_this$media3 = this.media) != null && _this$media3.paused || !this.startFragRequested ? 0 : maxFragLookUpTolerance;
  16441. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  16442. } else {
  16443. frag = fragments[fragments.length - 1];
  16444. }
  16445. if (frag) {
  16446. const curSNIdx = frag.sn - levelDetails.startSN;
  16447. const fragState = this.fragmentTracker.getState(frag);
  16448. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  16449. fragPrevious = frag;
  16450. }
  16451. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn || !levelDetails.live && !loadingParts)) {
  16452. const sameLevel = fragPrevious && frag.level === fragPrevious.level;
  16453. if (sameLevel) {
  16454. const nextFrag = fragments[curSNIdx + 1];
  16455. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  16456. frag = nextFrag;
  16457. } else {
  16458. frag = null;
  16459. }
  16460. }
  16461. }
  16462. }
  16463. return frag;
  16464. }
  16465. alignPlaylists(details, previousDetails, switchDetails) {
  16466. const length = details.fragments.length;
  16467. if (!length) {
  16468. this.warn(`No fragments in live playlist`);
  16469. return 0;
  16470. }
  16471. const slidingStart = details.fragmentStart;
  16472. const firstLevelLoad = !previousDetails;
  16473. const aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  16474. if (firstLevelLoad || !aligned && !slidingStart) {
  16475. alignStream(switchDetails, details);
  16476. const alignedSlidingStart = details.fragmentStart;
  16477. this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : "na"}->${details.startSN} fragments: ${length}`);
  16478. return alignedSlidingStart;
  16479. }
  16480. return slidingStart;
  16481. }
  16482. waitForCdnTuneIn(details) {
  16483. const advancePartLimit = 3;
  16484. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  16485. }
  16486. setStartPosition(details, sliding) {
  16487. let startPosition = this.startPosition;
  16488. if (startPosition < sliding) {
  16489. startPosition = -1;
  16490. }
  16491. const timelineOffset = this.timelineOffset;
  16492. if (startPosition === -1) {
  16493. const offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  16494. const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  16495. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  16496. startPosition = sliding + startTimeOffset;
  16497. if (startTimeOffset < 0) {
  16498. startPosition += details.edge;
  16499. }
  16500. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  16501. this.log(`Setting startPosition to ${startPosition} for start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? "multivariant" : "media"} playlist`);
  16502. this.startPosition = startPosition;
  16503. } else if (details.live) {
  16504. startPosition = this.hls.liveSyncPosition || sliding;
  16505. this.log(`Setting startPosition to -1 to start at live edge ${startPosition}`);
  16506. this.startPosition = -1;
  16507. } else {
  16508. this.log(`setting startPosition to 0 by default`);
  16509. this.startPosition = startPosition = 0;
  16510. }
  16511. this.lastCurrentTime = startPosition + timelineOffset;
  16512. }
  16513. this.nextLoadPosition = startPosition + timelineOffset;
  16514. }
  16515. getLoadPosition() {
  16516. var _this$hls;
  16517. const {
  16518. media
  16519. } = this;
  16520. let pos = 0;
  16521. if ((_this$hls = this.hls) != null && _this$hls.hasEnoughToStart && media) {
  16522. pos = media.currentTime;
  16523. } else if (this.nextLoadPosition >= 0) {
  16524. pos = this.nextLoadPosition;
  16525. }
  16526. return pos;
  16527. }
  16528. handleFragLoadAborted(frag, part) {
  16529. if (this.transmuxer && frag.type === this.playlistType && isMediaFragment(frag) && frag.stats.aborted) {
  16530. this.log(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of ${this.playlistLabel()} ${frag.level} was aborted`);
  16531. this.resetFragmentLoading(frag);
  16532. }
  16533. }
  16534. resetFragmentLoading(frag) {
  16535. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  16536. this.state = State.IDLE;
  16537. }
  16538. }
  16539. onFragmentOrKeyLoadError(filterType, data) {
  16540. if (data.chunkMeta && !data.frag) {
  16541. const context = this.getCurrentContext(data.chunkMeta);
  16542. if (context) {
  16543. data.frag = context.frag;
  16544. }
  16545. }
  16546. const frag = data.frag;
  16547. if (!frag || frag.type !== filterType || !this.levels) {
  16548. return;
  16549. }
  16550. if (this.fragContextChanged(frag)) {
  16551. var _this$fragCurrent;
  16552. this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.url}`);
  16553. return;
  16554. }
  16555. const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  16556. if (gapTagEncountered) {
  16557. this.fragmentTracker.fragBuffered(frag, true);
  16558. }
  16559. const errorAction = data.errorAction;
  16560. const {
  16561. action,
  16562. flags,
  16563. retryCount = 0,
  16564. retryConfig
  16565. } = errorAction || {};
  16566. const couldRetry = !!errorAction && !!retryConfig;
  16567. const retry = couldRetry && action === NetworkErrorAction.RetryRequest;
  16568. const noAlternate = couldRetry && !errorAction.resolved && flags === ErrorActionFlags.MoveAllAlternatesMatchingHost;
  16569. if (!retry && noAlternate && isMediaFragment(frag) && !frag.endList) {
  16570. this.resetFragmentErrors(filterType);
  16571. this.treatAsGap(frag);
  16572. errorAction.resolved = true;
  16573. } else if ((retry || noAlternate) && retryCount < retryConfig.maxNumRetry) {
  16574. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  16575. const delay = getRetryDelay(retryConfig, retryCount);
  16576. this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);
  16577. errorAction.resolved = true;
  16578. this.retryDate = self.performance.now() + delay;
  16579. this.state = State.FRAG_LOADING_WAITING_RETRY;
  16580. } else if (retryConfig && errorAction) {
  16581. this.resetFragmentErrors(filterType);
  16582. if (retryCount < retryConfig.maxNumRetry) {
  16583. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  16584. errorAction.resolved = true;
  16585. }
  16586. } else {
  16587. this.warn(`${data.details} reached or exceeded max retry (${retryCount})`);
  16588. return;
  16589. }
  16590. } else if (action === NetworkErrorAction.SendAlternateToPenaltyBox) {
  16591. this.state = State.WAITING_LEVEL;
  16592. } else {
  16593. this.state = State.ERROR;
  16594. }
  16595. this.tickImmediate();
  16596. }
  16597. reduceLengthAndFlushBuffer(data) {
  16598. if (this.state === State.PARSING || this.state === State.PARSED) {
  16599. const frag = data.frag;
  16600. const playlistType = data.parent;
  16601. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  16602. const buffered = bufferedInfo && bufferedInfo.len > 0.5;
  16603. if (buffered) {
  16604. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  16605. }
  16606. const flushBuffer = !buffered;
  16607. if (flushBuffer) {
  16608. this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`);
  16609. }
  16610. if (frag) {
  16611. this.fragmentTracker.removeFragment(frag);
  16612. this.nextLoadPosition = frag.start;
  16613. }
  16614. this.resetLoadingState();
  16615. return flushBuffer;
  16616. }
  16617. return false;
  16618. }
  16619. resetFragmentErrors(filterType) {
  16620. if (filterType === PlaylistLevelType.AUDIO) {
  16621. this.fragCurrent = null;
  16622. }
  16623. if (!this.hls.hasEnoughToStart) {
  16624. this.startFragRequested = false;
  16625. }
  16626. if (this.state !== State.STOPPED) {
  16627. this.state = State.IDLE;
  16628. }
  16629. }
  16630. afterBufferFlushed(media, bufferType, playlistType) {
  16631. if (!media) {
  16632. return;
  16633. }
  16634. const bufferedTimeRanges = BufferHelper.getBuffered(media);
  16635. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  16636. if (this.state === State.ENDED) {
  16637. this.resetLoadingState();
  16638. }
  16639. }
  16640. resetLoadingState() {
  16641. this.log("Reset loading state");
  16642. this.fragCurrent = null;
  16643. this.fragPrevious = null;
  16644. if (this.state !== State.STOPPED) {
  16645. this.state = State.IDLE;
  16646. }
  16647. }
  16648. resetStartWhenNotLoaded(level) {
  16649. if (!this.hls.hasEnoughToStart) {
  16650. this.startFragRequested = false;
  16651. const details = level ? level.details : null;
  16652. if (details != null && details.live) {
  16653. this.log(`resetting startPosition for live start`);
  16654. this.startPosition = -1;
  16655. this.setStartPosition(details, details.fragmentStart);
  16656. this.resetLoadingState();
  16657. } else {
  16658. this.nextLoadPosition = this.startPosition;
  16659. }
  16660. }
  16661. }
  16662. resetWhenMissingContext(chunkMeta) {
  16663. this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of ${this.playlistLabel()} ${chunkMeta.level}. This chunk will not be buffered.`);
  16664. this.removeUnbufferedFrags();
  16665. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  16666. this.resetLoadingState();
  16667. }
  16668. removeUnbufferedFrags(start = 0) {
  16669. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  16670. }
  16671. updateLevelTiming(frag, part, level, partial2) {
  16672. const details = level.details;
  16673. if (!details) {
  16674. this.warn("level.details undefined");
  16675. return;
  16676. }
  16677. const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => {
  16678. const info = frag.elementaryStreams[type];
  16679. if (info) {
  16680. const parsedDuration = info.endPTS - info.startPTS;
  16681. if (parsedDuration <= 0) {
  16682. this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`);
  16683. return result || false;
  16684. }
  16685. const drift = partial2 ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  16686. this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  16687. details,
  16688. level,
  16689. drift,
  16690. type,
  16691. frag,
  16692. start: info.startPTS,
  16693. end: info.endPTS
  16694. });
  16695. return true;
  16696. }
  16697. return result;
  16698. }, false);
  16699. if (!parsed) {
  16700. var _this$transmuxer;
  16701. if (level.fragmentError === 0) {
  16702. this.treatAsGap(frag, level);
  16703. }
  16704. if (((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  16705. const error = new Error(`Found no media in fragment ${frag.sn} of ${this.playlistLabel()} ${frag.level} resetting transmuxer to fallback to playlist timing`);
  16706. this.warn(error.message);
  16707. this.hls.trigger(Events.ERROR, {
  16708. type: ErrorTypes.MEDIA_ERROR,
  16709. details: ErrorDetails.FRAG_PARSING_ERROR,
  16710. fatal: false,
  16711. error,
  16712. frag,
  16713. reason: `Found no media in msn ${frag.sn} of ${this.playlistLabel()} "${level.url}"`
  16714. });
  16715. if (!this.hls) {
  16716. return;
  16717. }
  16718. this.resetTransmuxer();
  16719. }
  16720. }
  16721. this.state = State.PARSED;
  16722. this.log(`Parsed ${frag.type} sn: ${frag.sn}${part ? " part: " + part.index : ""} of ${this.fragInfo(frag, false, part)})`);
  16723. this.hls.trigger(Events.FRAG_PARSED, {
  16724. frag,
  16725. part
  16726. });
  16727. }
  16728. playlistLabel() {
  16729. return this.playlistType === PlaylistLevelType.MAIN ? "level" : "track";
  16730. }
  16731. fragInfo(frag, pts = true, part) {
  16732. var _ref, _ref2;
  16733. return `${this.playlistLabel()} ${frag.level} (${part ? "part" : "frag"}:[${((_ref = pts && !part ? frag.startPTS : (part || frag).start) != null ? _ref : NaN).toFixed(3)}-${((_ref2 = pts && !part ? frag.endPTS : (part || frag).end) != null ? _ref2 : NaN).toFixed(3)}]${part && frag.type === "main" ? "INDEPENDENT=" + (part.independent ? "YES" : "NO") : ""}`;
  16734. }
  16735. treatAsGap(frag, level) {
  16736. if (level) {
  16737. level.fragmentError++;
  16738. }
  16739. frag.gap = true;
  16740. this.fragmentTracker.removeFragment(frag);
  16741. this.fragmentTracker.fragBuffered(frag, true);
  16742. }
  16743. resetTransmuxer() {
  16744. var _this$transmuxer2;
  16745. (_this$transmuxer2 = this.transmuxer) == null ? void 0 : _this$transmuxer2.reset();
  16746. }
  16747. recoverWorkerError(data) {
  16748. if (data.event === "demuxerWorker") {
  16749. this.fragmentTracker.removeAllFragments();
  16750. if (this.transmuxer) {
  16751. this.transmuxer.destroy();
  16752. this.transmuxer = null;
  16753. }
  16754. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  16755. this.resetLoadingState();
  16756. }
  16757. }
  16758. set state(nextState) {
  16759. const previousState = this._state;
  16760. if (previousState !== nextState) {
  16761. this._state = nextState;
  16762. this.log(`${previousState}->${nextState}`);
  16763. }
  16764. }
  16765. get state() {
  16766. return this._state;
  16767. }
  16768. }
  16769. function interstitialsEnabled(config) {
  16770. return !!config.interstitialsController && config.enableInterstitialPlayback !== false;
  16771. }
  16772. class ChunkCache {
  16773. constructor() {
  16774. this.chunks = [];
  16775. this.dataLength = 0;
  16776. }
  16777. push(chunk) {
  16778. this.chunks.push(chunk);
  16779. this.dataLength += chunk.length;
  16780. }
  16781. flush() {
  16782. const {
  16783. chunks,
  16784. dataLength
  16785. } = this;
  16786. let result;
  16787. if (!chunks.length) {
  16788. return new Uint8Array(0);
  16789. } else if (chunks.length === 1) {
  16790. result = chunks[0];
  16791. } else {
  16792. result = concatUint8Arrays(chunks, dataLength);
  16793. }
  16794. this.reset();
  16795. return result;
  16796. }
  16797. reset() {
  16798. this.chunks.length = 0;
  16799. this.dataLength = 0;
  16800. }
  16801. }
  16802. function concatUint8Arrays(chunks, dataLength) {
  16803. const result = new Uint8Array(dataLength);
  16804. let offset = 0;
  16805. for (let i2 = 0; i2 < chunks.length; i2++) {
  16806. const chunk = chunks[i2];
  16807. result.set(chunk, offset);
  16808. offset += chunk.length;
  16809. }
  16810. return result;
  16811. }
  16812. var eventemitter3 = { exports: {} };
  16813. var hasRequiredEventemitter3;
  16814. function requireEventemitter3() {
  16815. if (hasRequiredEventemitter3)
  16816. return eventemitter3.exports;
  16817. hasRequiredEventemitter3 = 1;
  16818. (function(module2) {
  16819. var has2 = Object.prototype.hasOwnProperty, prefix = "~";
  16820. function Events2() {
  16821. }
  16822. if (Object.create) {
  16823. Events2.prototype = /* @__PURE__ */ Object.create(null);
  16824. if (!new Events2().__proto__)
  16825. prefix = false;
  16826. }
  16827. function EE(fn2, context, once2) {
  16828. this.fn = fn2;
  16829. this.context = context;
  16830. this.once = once2 || false;
  16831. }
  16832. function addListener(emitter, event, fn2, context, once2) {
  16833. if (typeof fn2 !== "function") {
  16834. throw new TypeError("The listener must be a function");
  16835. }
  16836. var listener = new EE(fn2, context || emitter, once2), evt = prefix ? prefix + event : event;
  16837. if (!emitter._events[evt])
  16838. emitter._events[evt] = listener, emitter._eventsCount++;
  16839. else if (!emitter._events[evt].fn)
  16840. emitter._events[evt].push(listener);
  16841. else
  16842. emitter._events[evt] = [emitter._events[evt], listener];
  16843. return emitter;
  16844. }
  16845. function clearEvent(emitter, evt) {
  16846. if (--emitter._eventsCount === 0)
  16847. emitter._events = new Events2();
  16848. else
  16849. delete emitter._events[evt];
  16850. }
  16851. function EventEmitter2() {
  16852. this._events = new Events2();
  16853. this._eventsCount = 0;
  16854. }
  16855. EventEmitter2.prototype.eventNames = function eventNames() {
  16856. var names = [], events, name;
  16857. if (this._eventsCount === 0)
  16858. return names;
  16859. for (name in events = this._events) {
  16860. if (has2.call(events, name))
  16861. names.push(prefix ? name.slice(1) : name);
  16862. }
  16863. if (Object.getOwnPropertySymbols) {
  16864. return names.concat(Object.getOwnPropertySymbols(events));
  16865. }
  16866. return names;
  16867. };
  16868. EventEmitter2.prototype.listeners = function listeners(event) {
  16869. var evt = prefix ? prefix + event : event, handlers = this._events[evt];
  16870. if (!handlers)
  16871. return [];
  16872. if (handlers.fn)
  16873. return [handlers.fn];
  16874. for (var i2 = 0, l2 = handlers.length, ee2 = new Array(l2); i2 < l2; i2++) {
  16875. ee2[i2] = handlers[i2].fn;
  16876. }
  16877. return ee2;
  16878. };
  16879. EventEmitter2.prototype.listenerCount = function listenerCount(event) {
  16880. var evt = prefix ? prefix + event : event, listeners = this._events[evt];
  16881. if (!listeners)
  16882. return 0;
  16883. if (listeners.fn)
  16884. return 1;
  16885. return listeners.length;
  16886. };
  16887. EventEmitter2.prototype.emit = function emit2(event, a1, a2, a3, a4, a5) {
  16888. var evt = prefix ? prefix + event : event;
  16889. if (!this._events[evt])
  16890. return false;
  16891. var listeners = this._events[evt], len = arguments.length, args, i2;
  16892. if (listeners.fn) {
  16893. if (listeners.once)
  16894. this.removeListener(event, listeners.fn, void 0, true);
  16895. switch (len) {
  16896. case 1:
  16897. return listeners.fn.call(listeners.context), true;
  16898. case 2:
  16899. return listeners.fn.call(listeners.context, a1), true;
  16900. case 3:
  16901. return listeners.fn.call(listeners.context, a1, a2), true;
  16902. case 4:
  16903. return listeners.fn.call(listeners.context, a1, a2, a3), true;
  16904. case 5:
  16905. return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  16906. case 6:
  16907. return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  16908. }
  16909. for (i2 = 1, args = new Array(len - 1); i2 < len; i2++) {
  16910. args[i2 - 1] = arguments[i2];
  16911. }
  16912. listeners.fn.apply(listeners.context, args);
  16913. } else {
  16914. var length = listeners.length, j2;
  16915. for (i2 = 0; i2 < length; i2++) {
  16916. if (listeners[i2].once)
  16917. this.removeListener(event, listeners[i2].fn, void 0, true);
  16918. switch (len) {
  16919. case 1:
  16920. listeners[i2].fn.call(listeners[i2].context);
  16921. break;
  16922. case 2:
  16923. listeners[i2].fn.call(listeners[i2].context, a1);
  16924. break;
  16925. case 3:
  16926. listeners[i2].fn.call(listeners[i2].context, a1, a2);
  16927. break;
  16928. case 4:
  16929. listeners[i2].fn.call(listeners[i2].context, a1, a2, a3);
  16930. break;
  16931. default:
  16932. if (!args)
  16933. for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) {
  16934. args[j2 - 1] = arguments[j2];
  16935. }
  16936. listeners[i2].fn.apply(listeners[i2].context, args);
  16937. }
  16938. }
  16939. }
  16940. return true;
  16941. };
  16942. EventEmitter2.prototype.on = function on2(event, fn2, context) {
  16943. return addListener(this, event, fn2, context, false);
  16944. };
  16945. EventEmitter2.prototype.once = function once2(event, fn2, context) {
  16946. return addListener(this, event, fn2, context, true);
  16947. };
  16948. EventEmitter2.prototype.removeListener = function removeListener(event, fn2, context, once2) {
  16949. var evt = prefix ? prefix + event : event;
  16950. if (!this._events[evt])
  16951. return this;
  16952. if (!fn2) {
  16953. clearEvent(this, evt);
  16954. return this;
  16955. }
  16956. var listeners = this._events[evt];
  16957. if (listeners.fn) {
  16958. if (listeners.fn === fn2 && (!once2 || listeners.once) && (!context || listeners.context === context)) {
  16959. clearEvent(this, evt);
  16960. }
  16961. } else {
  16962. for (var i2 = 0, events = [], length = listeners.length; i2 < length; i2++) {
  16963. if (listeners[i2].fn !== fn2 || once2 && !listeners[i2].once || context && listeners[i2].context !== context) {
  16964. events.push(listeners[i2]);
  16965. }
  16966. }
  16967. if (events.length)
  16968. this._events[evt] = events.length === 1 ? events[0] : events;
  16969. else
  16970. clearEvent(this, evt);
  16971. }
  16972. return this;
  16973. };
  16974. EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
  16975. var evt;
  16976. if (event) {
  16977. evt = prefix ? prefix + event : event;
  16978. if (this._events[evt])
  16979. clearEvent(this, evt);
  16980. } else {
  16981. this._events = new Events2();
  16982. this._eventsCount = 0;
  16983. }
  16984. return this;
  16985. };
  16986. EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
  16987. EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
  16988. EventEmitter2.prefixed = prefix;
  16989. EventEmitter2.EventEmitter = EventEmitter2;
  16990. {
  16991. module2.exports = EventEmitter2;
  16992. }
  16993. })(eventemitter3);
  16994. return eventemitter3.exports;
  16995. }
  16996. var eventemitter3Exports = requireEventemitter3();
  16997. var EventEmitter = /* @__PURE__ */ getDefaultExportFromCjs$1(eventemitter3Exports);
  16998. const version = "1.6.7";
  16999. const workerStore = {};
  17000. function hasUMDWorker() {
  17001. return typeof __HLS_WORKER_BUNDLE__ === "function";
  17002. }
  17003. function injectWorker() {
  17004. const workerContext = workerStore[version];
  17005. if (workerContext) {
  17006. workerContext.clientCount++;
  17007. return workerContext;
  17008. }
  17009. const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
  17010. type: "text/javascript"
  17011. });
  17012. const objectURL = self.URL.createObjectURL(blob);
  17013. const worker = new self.Worker(objectURL);
  17014. const result = {
  17015. worker,
  17016. objectURL,
  17017. clientCount: 1
  17018. };
  17019. workerStore[version] = result;
  17020. return result;
  17021. }
  17022. function loadWorker(path) {
  17023. const workerContext = workerStore[path];
  17024. if (workerContext) {
  17025. workerContext.clientCount++;
  17026. return workerContext;
  17027. }
  17028. const scriptURL = new self.URL(path, self.location.href).href;
  17029. const worker = new self.Worker(scriptURL);
  17030. const result = {
  17031. worker,
  17032. scriptURL,
  17033. clientCount: 1
  17034. };
  17035. workerStore[path] = result;
  17036. return result;
  17037. }
  17038. function removeWorkerFromStore(path) {
  17039. const workerContext = workerStore[path || version];
  17040. if (workerContext) {
  17041. const clientCount = workerContext.clientCount--;
  17042. if (clientCount === 1) {
  17043. const {
  17044. worker,
  17045. objectURL
  17046. } = workerContext;
  17047. delete workerStore[path || version];
  17048. if (objectURL) {
  17049. self.URL.revokeObjectURL(objectURL);
  17050. }
  17051. worker.terminate();
  17052. }
  17053. }
  17054. }
  17055. function isId3Footer(data, offset) {
  17056. if (offset + 10 <= data.length) {
  17057. if (data[offset] === 51 && data[offset + 1] === 68 && data[offset + 2] === 73) {
  17058. if (data[offset + 3] < 255 && data[offset + 4] < 255) {
  17059. if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
  17060. return true;
  17061. }
  17062. }
  17063. }
  17064. }
  17065. return false;
  17066. }
  17067. function isId3Header(data, offset) {
  17068. if (offset + 10 <= data.length) {
  17069. if (data[offset] === 73 && data[offset + 1] === 68 && data[offset + 2] === 51) {
  17070. if (data[offset + 3] < 255 && data[offset + 4] < 255) {
  17071. if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
  17072. return true;
  17073. }
  17074. }
  17075. }
  17076. }
  17077. return false;
  17078. }
  17079. function readId3Size(data, offset) {
  17080. let size2 = 0;
  17081. size2 = (data[offset] & 127) << 21;
  17082. size2 |= (data[offset + 1] & 127) << 14;
  17083. size2 |= (data[offset + 2] & 127) << 7;
  17084. size2 |= data[offset + 3] & 127;
  17085. return size2;
  17086. }
  17087. function getId3Data(data, offset) {
  17088. const front = offset;
  17089. let length = 0;
  17090. while (isId3Header(data, offset)) {
  17091. length += 10;
  17092. const size2 = readId3Size(data, offset + 6);
  17093. length += size2;
  17094. if (isId3Footer(data, offset + 10)) {
  17095. length += 10;
  17096. }
  17097. offset += length;
  17098. }
  17099. if (length > 0) {
  17100. return data.subarray(front, front + length);
  17101. }
  17102. return void 0;
  17103. }
  17104. function getAudioConfig(observer, data, offset, manifestCodec) {
  17105. const adtsSamplingRates = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
  17106. const byte2 = data[offset + 2];
  17107. const adtsSamplingIndex = byte2 >> 2 & 15;
  17108. if (adtsSamplingIndex > 12) {
  17109. const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);
  17110. observer.emit(Events.ERROR, Events.ERROR, {
  17111. type: ErrorTypes.MEDIA_ERROR,
  17112. details: ErrorDetails.FRAG_PARSING_ERROR,
  17113. fatal: true,
  17114. error,
  17115. reason: error.message
  17116. });
  17117. return;
  17118. }
  17119. const adtsObjectType = (byte2 >> 6 & 3) + 1;
  17120. const channelCount = data[offset + 3] >> 6 & 3 | (byte2 & 1) << 2;
  17121. const codec = "mp4a.40." + adtsObjectType;
  17122. const samplerate = adtsSamplingRates[adtsSamplingIndex];
  17123. let aacSampleIndex = adtsSamplingIndex;
  17124. if (adtsObjectType === 5 || adtsObjectType === 29) {
  17125. aacSampleIndex -= 3;
  17126. }
  17127. const config = [adtsObjectType << 3 | (aacSampleIndex & 14) >> 1, (aacSampleIndex & 1) << 7 | channelCount << 3];
  17128. logger.log(`manifest codec:${manifestCodec}, parsed codec:${codec}, channels:${channelCount}, rate:${samplerate} (ADTS object type:${adtsObjectType} sampling index:${adtsSamplingIndex})`);
  17129. return {
  17130. config,
  17131. samplerate,
  17132. channelCount,
  17133. codec,
  17134. parsedCodec: codec,
  17135. manifestCodec
  17136. };
  17137. }
  17138. function isHeaderPattern$1(data, offset) {
  17139. return data[offset] === 255 && (data[offset + 1] & 246) === 240;
  17140. }
  17141. function getHeaderLength(data, offset) {
  17142. return data[offset + 1] & 1 ? 7 : 9;
  17143. }
  17144. function getFullFrameLength(data, offset) {
  17145. return (data[offset + 3] & 3) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 224) >>> 5;
  17146. }
  17147. function canGetFrameLength(data, offset) {
  17148. return offset + 5 < data.length;
  17149. }
  17150. function isHeader$1(data, offset) {
  17151. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  17152. }
  17153. function canParse$1(data, offset) {
  17154. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  17155. }
  17156. function probe$1(data, offset) {
  17157. if (isHeader$1(data, offset)) {
  17158. const headerLength = getHeaderLength(data, offset);
  17159. if (offset + headerLength >= data.length) {
  17160. return false;
  17161. }
  17162. const frameLength = getFullFrameLength(data, offset);
  17163. if (frameLength <= headerLength) {
  17164. return false;
  17165. }
  17166. const newOffset = offset + frameLength;
  17167. return newOffset === data.length || isHeader$1(data, newOffset);
  17168. }
  17169. return false;
  17170. }
  17171. function initTrackConfig(track2, observer, data, offset, audioCodec) {
  17172. if (!track2.samplerate) {
  17173. const config = getAudioConfig(observer, data, offset, audioCodec);
  17174. if (!config) {
  17175. return;
  17176. }
  17177. _extends(track2, config);
  17178. }
  17179. }
  17180. function getFrameDuration(samplerate) {
  17181. return 1024 * 9e4 / samplerate;
  17182. }
  17183. function parseFrameHeader(data, offset) {
  17184. const headerLength = getHeaderLength(data, offset);
  17185. if (offset + headerLength <= data.length) {
  17186. const frameLength = getFullFrameLength(data, offset) - headerLength;
  17187. if (frameLength > 0) {
  17188. return {
  17189. headerLength,
  17190. frameLength
  17191. };
  17192. }
  17193. }
  17194. }
  17195. function appendFrame$2(track2, data, offset, pts, frameIndex) {
  17196. const frameDuration = getFrameDuration(track2.samplerate);
  17197. const stamp = pts + frameIndex * frameDuration;
  17198. const header = parseFrameHeader(data, offset);
  17199. let unit;
  17200. if (header) {
  17201. const {
  17202. frameLength,
  17203. headerLength
  17204. } = header;
  17205. const _length = headerLength + frameLength;
  17206. const missing = Math.max(0, offset + _length - data.length);
  17207. if (missing) {
  17208. unit = new Uint8Array(_length - headerLength);
  17209. unit.set(data.subarray(offset + headerLength, data.length), 0);
  17210. } else {
  17211. unit = data.subarray(offset + headerLength, offset + _length);
  17212. }
  17213. const _sample = {
  17214. unit,
  17215. pts: stamp
  17216. };
  17217. if (!missing) {
  17218. track2.samples.push(_sample);
  17219. }
  17220. return {
  17221. sample: _sample,
  17222. length: _length,
  17223. missing
  17224. };
  17225. }
  17226. const length = data.length - offset;
  17227. unit = new Uint8Array(length);
  17228. unit.set(data.subarray(offset, data.length), 0);
  17229. const sample = {
  17230. unit,
  17231. pts: stamp
  17232. };
  17233. return {
  17234. sample,
  17235. length,
  17236. missing: -1
  17237. };
  17238. }
  17239. function canParseId3(data, offset) {
  17240. return isId3Header(data, offset) && readId3Size(data, offset + 6) + 10 <= data.length - offset;
  17241. }
  17242. function toArrayBuffer(view2) {
  17243. if (view2 instanceof ArrayBuffer) {
  17244. return view2;
  17245. } else {
  17246. if (view2.byteOffset == 0 && view2.byteLength == view2.buffer.byteLength) {
  17247. return view2.buffer;
  17248. }
  17249. return new Uint8Array(view2).buffer;
  17250. }
  17251. }
  17252. function toUint8(data, offset = 0, length = Infinity) {
  17253. return view(data, offset, length, Uint8Array);
  17254. }
  17255. function view(data, offset, length, Type) {
  17256. const buffer2 = unsafeGetArrayBuffer(data);
  17257. let bytesPerElement = 1;
  17258. if ("BYTES_PER_ELEMENT" in Type) {
  17259. bytesPerElement = Type.BYTES_PER_ELEMENT;
  17260. }
  17261. const dataOffset = isArrayBufferView(data) ? data.byteOffset : 0;
  17262. const dataEnd = (dataOffset + data.byteLength) / bytesPerElement;
  17263. const rawStart = (dataOffset + offset) / bytesPerElement;
  17264. const start = Math.floor(Math.max(0, Math.min(rawStart, dataEnd)));
  17265. const end = Math.floor(Math.min(start + Math.max(length, 0), dataEnd));
  17266. return new Type(buffer2, start, end - start);
  17267. }
  17268. function unsafeGetArrayBuffer(view2) {
  17269. if (view2 instanceof ArrayBuffer) {
  17270. return view2;
  17271. } else {
  17272. return view2.buffer;
  17273. }
  17274. }
  17275. function isArrayBufferView(obj) {
  17276. return obj && obj.buffer instanceof ArrayBuffer && obj.byteLength !== void 0 && obj.byteOffset !== void 0;
  17277. }
  17278. function decodeId3ImageFrame(frame) {
  17279. const metadataFrame = {
  17280. key: frame.type,
  17281. description: "",
  17282. data: "",
  17283. mimeType: null,
  17284. pictureType: null
  17285. };
  17286. const utf8Encoding = 3;
  17287. if (frame.size < 2) {
  17288. return void 0;
  17289. }
  17290. if (frame.data[0] !== utf8Encoding) {
  17291. console.log("Ignore frame with unrecognized character encoding");
  17292. return void 0;
  17293. }
  17294. const mimeTypeEndIndex = frame.data.subarray(1).indexOf(0);
  17295. if (mimeTypeEndIndex === -1) {
  17296. return void 0;
  17297. }
  17298. const mimeType = utf8ArrayToStr(toUint8(frame.data, 1, mimeTypeEndIndex));
  17299. const pictureType = frame.data[2 + mimeTypeEndIndex];
  17300. const descriptionEndIndex = frame.data.subarray(3 + mimeTypeEndIndex).indexOf(0);
  17301. if (descriptionEndIndex === -1) {
  17302. return void 0;
  17303. }
  17304. const description = utf8ArrayToStr(toUint8(frame.data, 3 + mimeTypeEndIndex, descriptionEndIndex));
  17305. let data;
  17306. if (mimeType === "-->") {
  17307. data = utf8ArrayToStr(toUint8(frame.data, 4 + mimeTypeEndIndex + descriptionEndIndex));
  17308. } else {
  17309. data = toArrayBuffer(frame.data.subarray(4 + mimeTypeEndIndex + descriptionEndIndex));
  17310. }
  17311. metadataFrame.mimeType = mimeType;
  17312. metadataFrame.pictureType = pictureType;
  17313. metadataFrame.description = description;
  17314. metadataFrame.data = data;
  17315. return metadataFrame;
  17316. }
  17317. function decodeId3PrivFrame(frame) {
  17318. if (frame.size < 2) {
  17319. return void 0;
  17320. }
  17321. const owner = utf8ArrayToStr(frame.data, true);
  17322. const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  17323. return {
  17324. key: frame.type,
  17325. info: owner,
  17326. data: privateData.buffer
  17327. };
  17328. }
  17329. function decodeId3TextFrame(frame) {
  17330. if (frame.size < 2) {
  17331. return void 0;
  17332. }
  17333. if (frame.type === "TXXX") {
  17334. let index2 = 1;
  17335. const description = utf8ArrayToStr(frame.data.subarray(index2), true);
  17336. index2 += description.length + 1;
  17337. const value = utf8ArrayToStr(frame.data.subarray(index2));
  17338. return {
  17339. key: frame.type,
  17340. info: description,
  17341. data: value
  17342. };
  17343. }
  17344. const text = utf8ArrayToStr(frame.data.subarray(1));
  17345. return {
  17346. key: frame.type,
  17347. info: "",
  17348. data: text
  17349. };
  17350. }
  17351. function decodeId3UrlFrame(frame) {
  17352. if (frame.type === "WXXX") {
  17353. if (frame.size < 2) {
  17354. return void 0;
  17355. }
  17356. let index2 = 1;
  17357. const description = utf8ArrayToStr(frame.data.subarray(index2), true);
  17358. index2 += description.length + 1;
  17359. const value = utf8ArrayToStr(frame.data.subarray(index2));
  17360. return {
  17361. key: frame.type,
  17362. info: description,
  17363. data: value
  17364. };
  17365. }
  17366. const url = utf8ArrayToStr(frame.data);
  17367. return {
  17368. key: frame.type,
  17369. info: "",
  17370. data: url
  17371. };
  17372. }
  17373. function decodeId3Frame(frame) {
  17374. if (frame.type === "PRIV") {
  17375. return decodeId3PrivFrame(frame);
  17376. } else if (frame.type[0] === "W") {
  17377. return decodeId3UrlFrame(frame);
  17378. } else if (frame.type === "APIC") {
  17379. return decodeId3ImageFrame(frame);
  17380. }
  17381. return decodeId3TextFrame(frame);
  17382. }
  17383. function getId3FrameData(data) {
  17384. const type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  17385. const size2 = readId3Size(data, 4);
  17386. const offset = 10;
  17387. return {
  17388. type,
  17389. size: size2,
  17390. data: data.subarray(offset, offset + size2)
  17391. };
  17392. }
  17393. const HEADER_FOOTER_SIZE = 10;
  17394. const FRAME_SIZE = 10;
  17395. function getId3Frames(id3Data) {
  17396. let offset = 0;
  17397. const frames = [];
  17398. while (isId3Header(id3Data, offset)) {
  17399. const size2 = readId3Size(id3Data, offset + 6);
  17400. if (id3Data[offset + 5] >> 6 & 1) {
  17401. offset += HEADER_FOOTER_SIZE;
  17402. }
  17403. offset += HEADER_FOOTER_SIZE;
  17404. const end = offset + size2;
  17405. while (offset + FRAME_SIZE < end) {
  17406. const frameData = getId3FrameData(id3Data.subarray(offset));
  17407. const frame = decodeId3Frame(frameData);
  17408. if (frame) {
  17409. frames.push(frame);
  17410. }
  17411. offset += frameData.size + HEADER_FOOTER_SIZE;
  17412. }
  17413. if (isId3Footer(id3Data, offset)) {
  17414. offset += HEADER_FOOTER_SIZE;
  17415. }
  17416. }
  17417. return frames;
  17418. }
  17419. function isId3TimestampFrame(frame) {
  17420. return frame && frame.key === "PRIV" && frame.info === "com.apple.streaming.transportStreamTimestamp";
  17421. }
  17422. function readId3Timestamp(timeStampFrame) {
  17423. if (timeStampFrame.data.byteLength === 8) {
  17424. const data = new Uint8Array(timeStampFrame.data);
  17425. const pts33Bit = data[3] & 1;
  17426. let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  17427. timestamp /= 45;
  17428. if (pts33Bit) {
  17429. timestamp += 4772185884e-2;
  17430. }
  17431. return Math.round(timestamp);
  17432. }
  17433. return void 0;
  17434. }
  17435. function getId3Timestamp(data) {
  17436. const frames = getId3Frames(data);
  17437. for (let i2 = 0; i2 < frames.length; i2++) {
  17438. const frame = frames[i2];
  17439. if (isId3TimestampFrame(frame)) {
  17440. return readId3Timestamp(frame);
  17441. }
  17442. }
  17443. return void 0;
  17444. }
  17445. let MetadataSchema = /* @__PURE__ */ function(MetadataSchema2) {
  17446. MetadataSchema2["audioId3"] = "org.id3";
  17447. MetadataSchema2["dateRange"] = "com.apple.quicktime.HLS";
  17448. MetadataSchema2["emsg"] = "https://aomedia.org/emsg/ID3";
  17449. MetadataSchema2["misbklv"] = "urn:misb:KLV:bin:1910.1";
  17450. return MetadataSchema2;
  17451. }({});
  17452. function dummyTrack(type = "", inputTimeScale = 9e4) {
  17453. return {
  17454. type,
  17455. id: -1,
  17456. pid: -1,
  17457. inputTimeScale,
  17458. sequenceNumber: -1,
  17459. samples: [],
  17460. dropped: 0
  17461. };
  17462. }
  17463. class BaseAudioDemuxer {
  17464. constructor() {
  17465. this._audioTrack = void 0;
  17466. this._id3Track = void 0;
  17467. this.frameIndex = 0;
  17468. this.cachedData = null;
  17469. this.basePTS = null;
  17470. this.initPTS = null;
  17471. this.lastPTS = null;
  17472. }
  17473. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  17474. this._id3Track = {
  17475. type: "id3",
  17476. id: 3,
  17477. pid: -1,
  17478. inputTimeScale: 9e4,
  17479. sequenceNumber: 0,
  17480. samples: [],
  17481. dropped: 0
  17482. };
  17483. }
  17484. resetTimeStamp(deaultTimestamp) {
  17485. this.initPTS = deaultTimestamp;
  17486. this.resetContiguity();
  17487. }
  17488. resetContiguity() {
  17489. this.basePTS = null;
  17490. this.lastPTS = null;
  17491. this.frameIndex = 0;
  17492. }
  17493. canParse(data, offset) {
  17494. return false;
  17495. }
  17496. appendFrame(track2, data, offset) {
  17497. }
  17498. // feed incoming data to the front of the parsing pipeline
  17499. demux(data, timeOffset) {
  17500. if (this.cachedData) {
  17501. data = appendUint8Array(this.cachedData, data);
  17502. this.cachedData = null;
  17503. }
  17504. let id3Data = getId3Data(data, 0);
  17505. let offset = id3Data ? id3Data.length : 0;
  17506. let lastDataIndex;
  17507. const track2 = this._audioTrack;
  17508. const id3Track = this._id3Track;
  17509. const timestamp = id3Data ? getId3Timestamp(id3Data) : void 0;
  17510. const length = data.length;
  17511. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  17512. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  17513. this.lastPTS = this.basePTS;
  17514. }
  17515. if (this.lastPTS === null) {
  17516. this.lastPTS = this.basePTS;
  17517. }
  17518. if (id3Data && id3Data.length > 0) {
  17519. id3Track.samples.push({
  17520. pts: this.lastPTS,
  17521. dts: this.lastPTS,
  17522. data: id3Data,
  17523. type: MetadataSchema.audioId3,
  17524. duration: Number.POSITIVE_INFINITY
  17525. });
  17526. }
  17527. while (offset < length) {
  17528. if (this.canParse(data, offset)) {
  17529. const frame = this.appendFrame(track2, data, offset);
  17530. if (frame) {
  17531. this.frameIndex++;
  17532. this.lastPTS = frame.sample.pts;
  17533. offset += frame.length;
  17534. lastDataIndex = offset;
  17535. } else {
  17536. offset = length;
  17537. }
  17538. } else if (canParseId3(data, offset)) {
  17539. id3Data = getId3Data(data, offset);
  17540. id3Track.samples.push({
  17541. pts: this.lastPTS,
  17542. dts: this.lastPTS,
  17543. data: id3Data,
  17544. type: MetadataSchema.audioId3,
  17545. duration: Number.POSITIVE_INFINITY
  17546. });
  17547. offset += id3Data.length;
  17548. lastDataIndex = offset;
  17549. } else {
  17550. offset++;
  17551. }
  17552. if (offset === length && lastDataIndex !== length) {
  17553. const partialData = data.slice(lastDataIndex);
  17554. if (this.cachedData) {
  17555. this.cachedData = appendUint8Array(this.cachedData, partialData);
  17556. } else {
  17557. this.cachedData = partialData;
  17558. }
  17559. }
  17560. }
  17561. return {
  17562. audioTrack: track2,
  17563. videoTrack: dummyTrack(),
  17564. id3Track,
  17565. textTrack: dummyTrack()
  17566. };
  17567. }
  17568. demuxSampleAes(data, keyData, timeOffset) {
  17569. return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  17570. }
  17571. flush(timeOffset) {
  17572. const cachedData = this.cachedData;
  17573. if (cachedData) {
  17574. this.cachedData = null;
  17575. this.demux(cachedData, 0);
  17576. }
  17577. return {
  17578. audioTrack: this._audioTrack,
  17579. videoTrack: dummyTrack(),
  17580. id3Track: this._id3Track,
  17581. textTrack: dummyTrack()
  17582. };
  17583. }
  17584. destroy() {
  17585. this.cachedData = null;
  17586. this._audioTrack = this._id3Track = void 0;
  17587. }
  17588. }
  17589. const initPTSFn = (timestamp, timeOffset, initPTS) => {
  17590. if (isFiniteNumber(timestamp)) {
  17591. return timestamp * 90;
  17592. }
  17593. const init90kHz = initPTS ? initPTS.baseTime * 9e4 / initPTS.timescale : 0;
  17594. return timeOffset * 9e4 + init90kHz;
  17595. };
  17596. let chromeVersion$1 = null;
  17597. const 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];
  17598. const SamplingRateMap = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3];
  17599. const SamplesCoefficients = [
  17600. // MPEG 2.5
  17601. [
  17602. 0,
  17603. // Reserved
  17604. 72,
  17605. // Layer3
  17606. 144,
  17607. // Layer2
  17608. 12
  17609. // Layer1
  17610. ],
  17611. // Reserved
  17612. [
  17613. 0,
  17614. // Reserved
  17615. 0,
  17616. // Layer3
  17617. 0,
  17618. // Layer2
  17619. 0
  17620. // Layer1
  17621. ],
  17622. // MPEG 2
  17623. [
  17624. 0,
  17625. // Reserved
  17626. 72,
  17627. // Layer3
  17628. 144,
  17629. // Layer2
  17630. 12
  17631. // Layer1
  17632. ],
  17633. // MPEG 1
  17634. [
  17635. 0,
  17636. // Reserved
  17637. 144,
  17638. // Layer3
  17639. 144,
  17640. // Layer2
  17641. 12
  17642. // Layer1
  17643. ]
  17644. ];
  17645. const BytesInSlot = [
  17646. 0,
  17647. // Reserved
  17648. 1,
  17649. // Layer3
  17650. 1,
  17651. // Layer2
  17652. 4
  17653. // Layer1
  17654. ];
  17655. function appendFrame$1(track2, data, offset, pts, frameIndex) {
  17656. if (offset + 24 > data.length) {
  17657. return;
  17658. }
  17659. const header = parseHeader(data, offset);
  17660. if (header && offset + header.frameLength <= data.length) {
  17661. const frameDuration = header.samplesPerFrame * 9e4 / header.sampleRate;
  17662. const stamp = pts + frameIndex * frameDuration;
  17663. const sample = {
  17664. unit: data.subarray(offset, offset + header.frameLength),
  17665. pts: stamp,
  17666. dts: stamp
  17667. };
  17668. track2.config = [];
  17669. track2.channelCount = header.channelCount;
  17670. track2.samplerate = header.sampleRate;
  17671. track2.samples.push(sample);
  17672. return {
  17673. sample,
  17674. length: header.frameLength,
  17675. missing: 0
  17676. };
  17677. }
  17678. }
  17679. function parseHeader(data, offset) {
  17680. const mpegVersion = data[offset + 1] >> 3 & 3;
  17681. const mpegLayer = data[offset + 1] >> 1 & 3;
  17682. const bitRateIndex = data[offset + 2] >> 4 & 15;
  17683. const sampleRateIndex = data[offset + 2] >> 2 & 3;
  17684. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  17685. const paddingBit = data[offset + 2] >> 1 & 1;
  17686. const channelMode = data[offset + 3] >> 6;
  17687. const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  17688. const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1e3;
  17689. const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  17690. const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  17691. const channelCount = channelMode === 3 ? 1 : 2;
  17692. const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  17693. const bytesInSlot = BytesInSlot[mpegLayer];
  17694. const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  17695. const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  17696. if (chromeVersion$1 === null) {
  17697. const userAgent = navigator.userAgent || "";
  17698. const result = userAgent.match(/Chrome\/(\d+)/i);
  17699. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  17700. }
  17701. const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  17702. if (needChromeFix && mpegLayer === 2 && bitRate >= 224e3 && channelMode === 0) {
  17703. data[offset + 3] = data[offset + 3] | 128;
  17704. }
  17705. return {
  17706. sampleRate,
  17707. channelCount,
  17708. frameLength,
  17709. samplesPerFrame
  17710. };
  17711. }
  17712. }
  17713. function isHeaderPattern(data, offset) {
  17714. return data[offset] === 255 && (data[offset + 1] & 224) === 224 && (data[offset + 1] & 6) !== 0;
  17715. }
  17716. function isHeader(data, offset) {
  17717. return offset + 1 < data.length && isHeaderPattern(data, offset);
  17718. }
  17719. function canParse(data, offset) {
  17720. const headerSize = 4;
  17721. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  17722. }
  17723. function probe(data, offset) {
  17724. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  17725. const headerLength = 4;
  17726. const header = parseHeader(data, offset);
  17727. let frameLength = headerLength;
  17728. if (header != null && header.frameLength) {
  17729. frameLength = header.frameLength;
  17730. }
  17731. const newOffset = offset + frameLength;
  17732. return newOffset === data.length || isHeader(data, newOffset);
  17733. }
  17734. return false;
  17735. }
  17736. class AACDemuxer extends BaseAudioDemuxer {
  17737. constructor(observer, config) {
  17738. super();
  17739. this.observer = void 0;
  17740. this.config = void 0;
  17741. this.observer = observer;
  17742. this.config = config;
  17743. }
  17744. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  17745. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  17746. this._audioTrack = {
  17747. container: "audio/adts",
  17748. type: "audio",
  17749. id: 2,
  17750. pid: -1,
  17751. sequenceNumber: 0,
  17752. segmentCodec: "aac",
  17753. samples: [],
  17754. manifestCodec: audioCodec,
  17755. duration: trackDuration,
  17756. inputTimeScale: 9e4,
  17757. dropped: 0
  17758. };
  17759. }
  17760. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  17761. static probe(data, logger2) {
  17762. if (!data) {
  17763. return false;
  17764. }
  17765. const id3Data = getId3Data(data, 0);
  17766. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  17767. if (probe(data, offset)) {
  17768. return false;
  17769. }
  17770. for (let length = data.length; offset < length; offset++) {
  17771. if (probe$1(data, offset)) {
  17772. logger2.log("ADTS sync word found !");
  17773. return true;
  17774. }
  17775. }
  17776. return false;
  17777. }
  17778. canParse(data, offset) {
  17779. return canParse$1(data, offset);
  17780. }
  17781. appendFrame(track2, data, offset) {
  17782. initTrackConfig(track2, this.observer, data, offset, track2.manifestCodec);
  17783. const frame = appendFrame$2(track2, data, offset, this.basePTS, this.frameIndex);
  17784. if (frame && frame.missing === 0) {
  17785. return frame;
  17786. }
  17787. }
  17788. }
  17789. const getAudioBSID = (data, offset) => {
  17790. let bsid = 0;
  17791. let numBits = 5;
  17792. offset += numBits;
  17793. const temp = new Uint32Array(1);
  17794. const mask = new Uint32Array(1);
  17795. const byte = new Uint8Array(1);
  17796. while (numBits > 0) {
  17797. byte[0] = data[offset];
  17798. const bits = Math.min(numBits, 8);
  17799. const shift = 8 - bits;
  17800. mask[0] = 4278190080 >>> 24 + shift << shift;
  17801. temp[0] = (byte[0] & mask[0]) >> shift;
  17802. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  17803. offset += 1;
  17804. numBits -= bits;
  17805. }
  17806. return bsid;
  17807. };
  17808. class AC3Demuxer extends BaseAudioDemuxer {
  17809. constructor(observer) {
  17810. super();
  17811. this.observer = void 0;
  17812. this.observer = observer;
  17813. }
  17814. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  17815. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  17816. this._audioTrack = {
  17817. container: "audio/ac-3",
  17818. type: "audio",
  17819. id: 2,
  17820. pid: -1,
  17821. sequenceNumber: 0,
  17822. segmentCodec: "ac3",
  17823. samples: [],
  17824. manifestCodec: audioCodec,
  17825. duration: trackDuration,
  17826. inputTimeScale: 9e4,
  17827. dropped: 0
  17828. };
  17829. }
  17830. canParse(data, offset) {
  17831. return offset + 64 < data.length;
  17832. }
  17833. appendFrame(track2, data, offset) {
  17834. const frameLength = appendFrame(track2, data, offset, this.basePTS, this.frameIndex);
  17835. if (frameLength !== -1) {
  17836. const sample = track2.samples[track2.samples.length - 1];
  17837. return {
  17838. sample,
  17839. length: frameLength,
  17840. missing: 0
  17841. };
  17842. }
  17843. }
  17844. static probe(data) {
  17845. if (!data) {
  17846. return false;
  17847. }
  17848. const id3Data = getId3Data(data, 0);
  17849. if (!id3Data) {
  17850. return false;
  17851. }
  17852. const offset = id3Data.length;
  17853. if (data[offset] === 11 && data[offset + 1] === 119 && getId3Timestamp(id3Data) !== void 0 && // check the bsid to confirm ac-3
  17854. getAudioBSID(data, offset) < 16) {
  17855. return true;
  17856. }
  17857. return false;
  17858. }
  17859. }
  17860. function appendFrame(track2, data, start, pts, frameIndex) {
  17861. if (start + 8 > data.length) {
  17862. return -1;
  17863. }
  17864. if (data[start] !== 11 || data[start + 1] !== 119) {
  17865. return -1;
  17866. }
  17867. const samplingRateCode = data[start + 4] >> 6;
  17868. if (samplingRateCode >= 3) {
  17869. return -1;
  17870. }
  17871. const samplingRateMap = [48e3, 44100, 32e3];
  17872. const sampleRate = samplingRateMap[samplingRateCode];
  17873. const frameSizeCode = data[start + 4] & 63;
  17874. const frameSizeMap = [64, 69, 96, 64, 70, 96, 80, 87, 120, 80, 88, 120, 96, 104, 144, 96, 105, 144, 112, 121, 168, 112, 122, 168, 128, 139, 192, 128, 140, 192, 160, 174, 240, 160, 175, 240, 192, 208, 288, 192, 209, 288, 224, 243, 336, 224, 244, 336, 256, 278, 384, 256, 279, 384, 320, 348, 480, 320, 349, 480, 384, 417, 576, 384, 418, 576, 448, 487, 672, 448, 488, 672, 512, 557, 768, 512, 558, 768, 640, 696, 960, 640, 697, 960, 768, 835, 1152, 768, 836, 1152, 896, 975, 1344, 896, 976, 1344, 1024, 1114, 1536, 1024, 1115, 1536, 1152, 1253, 1728, 1152, 1254, 1728, 1280, 1393, 1920, 1280, 1394, 1920];
  17875. const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;
  17876. if (start + frameLength > data.length) {
  17877. return -1;
  17878. }
  17879. const channelMode = data[start + 6] >> 5;
  17880. let skipCount = 0;
  17881. if (channelMode === 2) {
  17882. skipCount += 2;
  17883. } else {
  17884. if (channelMode & 1 && channelMode !== 1) {
  17885. skipCount += 2;
  17886. }
  17887. if (channelMode & 4) {
  17888. skipCount += 2;
  17889. }
  17890. }
  17891. const lfeon = (data[start + 6] << 8 | data[start + 7]) >> 12 - skipCount & 1;
  17892. const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];
  17893. const channelCount = channelsMap[channelMode] + lfeon;
  17894. const bsid = data[start + 5] >> 3;
  17895. const bsmod = data[start + 5] & 7;
  17896. const config = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 224]);
  17897. const frameDuration = 1536 / sampleRate * 9e4;
  17898. const stamp = pts + frameIndex * frameDuration;
  17899. const unit = data.subarray(start, start + frameLength);
  17900. track2.config = config;
  17901. track2.channelCount = channelCount;
  17902. track2.samplerate = sampleRate;
  17903. track2.samples.push({
  17904. unit,
  17905. pts: stamp
  17906. });
  17907. return frameLength;
  17908. }
  17909. class MP3Demuxer extends BaseAudioDemuxer {
  17910. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  17911. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  17912. this._audioTrack = {
  17913. container: "audio/mpeg",
  17914. type: "audio",
  17915. id: 2,
  17916. pid: -1,
  17917. sequenceNumber: 0,
  17918. segmentCodec: "mp3",
  17919. samples: [],
  17920. manifestCodec: audioCodec,
  17921. duration: trackDuration,
  17922. inputTimeScale: 9e4,
  17923. dropped: 0
  17924. };
  17925. }
  17926. static probe(data) {
  17927. if (!data) {
  17928. return false;
  17929. }
  17930. const id3Data = getId3Data(data, 0);
  17931. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  17932. if (id3Data && data[offset] === 11 && data[offset + 1] === 119 && getId3Timestamp(id3Data) !== void 0 && // check the bsid to confirm ac-3 or ec-3 (not mp3)
  17933. getAudioBSID(data, offset) <= 16) {
  17934. return false;
  17935. }
  17936. for (let length = data.length; offset < length; offset++) {
  17937. if (probe(data, offset)) {
  17938. logger.log("MPEG Audio sync word found !");
  17939. return true;
  17940. }
  17941. }
  17942. return false;
  17943. }
  17944. canParse(data, offset) {
  17945. return canParse(data, offset);
  17946. }
  17947. appendFrame(track2, data, offset) {
  17948. if (this.basePTS === null) {
  17949. return;
  17950. }
  17951. return appendFrame$1(track2, data, offset, this.basePTS, this.frameIndex);
  17952. }
  17953. }
  17954. const emsgSchemePattern = /\/emsg[-/]ID3/i;
  17955. class MP4Demuxer {
  17956. constructor(observer, config) {
  17957. this.remainderData = null;
  17958. this.timeOffset = 0;
  17959. this.config = void 0;
  17960. this.videoTrack = void 0;
  17961. this.audioTrack = void 0;
  17962. this.id3Track = void 0;
  17963. this.txtTrack = void 0;
  17964. this.config = config;
  17965. }
  17966. resetTimeStamp() {
  17967. }
  17968. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  17969. const videoTrack = this.videoTrack = dummyTrack("video", 1);
  17970. const audioTrack = this.audioTrack = dummyTrack("audio", 1);
  17971. const captionTrack = this.txtTrack = dummyTrack("text", 1);
  17972. this.id3Track = dummyTrack("id3", 1);
  17973. this.timeOffset = 0;
  17974. if (!(initSegment != null && initSegment.byteLength)) {
  17975. return;
  17976. }
  17977. const initData2 = parseInitSegment(initSegment);
  17978. if (initData2.video) {
  17979. const {
  17980. id,
  17981. timescale,
  17982. codec,
  17983. supplemental
  17984. } = initData2.video;
  17985. videoTrack.id = id;
  17986. videoTrack.timescale = captionTrack.timescale = timescale;
  17987. videoTrack.codec = codec;
  17988. videoTrack.supplemental = supplemental;
  17989. }
  17990. if (initData2.audio) {
  17991. const {
  17992. id,
  17993. timescale,
  17994. codec
  17995. } = initData2.audio;
  17996. audioTrack.id = id;
  17997. audioTrack.timescale = timescale;
  17998. audioTrack.codec = codec;
  17999. }
  18000. captionTrack.id = RemuxerTrackIdConfig.text;
  18001. videoTrack.sampleDuration = 0;
  18002. videoTrack.duration = audioTrack.duration = trackDuration;
  18003. }
  18004. resetContiguity() {
  18005. this.remainderData = null;
  18006. }
  18007. static probe(data) {
  18008. return hasMoofData(data);
  18009. }
  18010. demux(data, timeOffset) {
  18011. this.timeOffset = timeOffset;
  18012. let videoSamples = data;
  18013. const videoTrack = this.videoTrack;
  18014. const textTrack = this.txtTrack;
  18015. if (this.config.progressive) {
  18016. if (this.remainderData) {
  18017. videoSamples = appendUint8Array(this.remainderData, data);
  18018. }
  18019. const segmentedData = segmentValidRange(videoSamples);
  18020. this.remainderData = segmentedData.remainder;
  18021. videoTrack.samples = segmentedData.valid || new Uint8Array();
  18022. } else {
  18023. videoTrack.samples = videoSamples;
  18024. }
  18025. const id3Track = this.extractID3Track(videoTrack, timeOffset);
  18026. textTrack.samples = parseSamples(timeOffset, videoTrack);
  18027. return {
  18028. videoTrack,
  18029. audioTrack: this.audioTrack,
  18030. id3Track,
  18031. textTrack: this.txtTrack
  18032. };
  18033. }
  18034. flush() {
  18035. const timeOffset = this.timeOffset;
  18036. const videoTrack = this.videoTrack;
  18037. const textTrack = this.txtTrack;
  18038. videoTrack.samples = this.remainderData || new Uint8Array();
  18039. this.remainderData = null;
  18040. const id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  18041. textTrack.samples = parseSamples(timeOffset, videoTrack);
  18042. return {
  18043. videoTrack,
  18044. audioTrack: dummyTrack(),
  18045. id3Track,
  18046. textTrack: dummyTrack()
  18047. };
  18048. }
  18049. extractID3Track(videoTrack, timeOffset) {
  18050. const id3Track = this.id3Track;
  18051. if (videoTrack.samples.length) {
  18052. const emsgs = findBox(videoTrack.samples, ["emsg"]);
  18053. if (emsgs) {
  18054. emsgs.forEach((data) => {
  18055. const emsgInfo = parseEmsg(data);
  18056. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  18057. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  18058. let duration = emsgInfo.eventDuration === 4294967295 ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  18059. if (duration <= 1e-3) {
  18060. duration = Number.POSITIVE_INFINITY;
  18061. }
  18062. const payload = emsgInfo.payload;
  18063. id3Track.samples.push({
  18064. data: payload,
  18065. len: payload.byteLength,
  18066. dts: pts,
  18067. pts,
  18068. type: MetadataSchema.emsg,
  18069. duration
  18070. });
  18071. } else if (this.config.enableEmsgKLVMetadata && emsgInfo.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")) {
  18072. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  18073. id3Track.samples.push({
  18074. data: emsgInfo.payload,
  18075. len: emsgInfo.payload.byteLength,
  18076. dts: pts,
  18077. pts,
  18078. type: MetadataSchema.misbklv,
  18079. duration: Number.POSITIVE_INFINITY
  18080. });
  18081. }
  18082. });
  18083. }
  18084. }
  18085. return id3Track;
  18086. }
  18087. demuxSampleAes(data, keyData, timeOffset) {
  18088. return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"));
  18089. }
  18090. destroy() {
  18091. this.config = null;
  18092. this.remainderData = null;
  18093. this.videoTrack = this.audioTrack = this.id3Track = this.txtTrack = void 0;
  18094. }
  18095. }
  18096. function getEmsgStartTime(emsgInfo, timeOffset) {
  18097. return isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  18098. }
  18099. class SampleAesDecrypter {
  18100. constructor(observer, config, keyData) {
  18101. this.keyData = void 0;
  18102. this.decrypter = void 0;
  18103. this.keyData = keyData;
  18104. this.decrypter = new Decrypter(config, {
  18105. removePKCS7Padding: false
  18106. });
  18107. }
  18108. decryptBuffer(encryptedData) {
  18109. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, DecrypterAesMode.cbc);
  18110. }
  18111. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  18112. decryptAacSample(samples, sampleIndex, callback) {
  18113. const curUnit = samples[sampleIndex].unit;
  18114. if (curUnit.length <= 16) {
  18115. return;
  18116. }
  18117. const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  18118. const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  18119. this.decryptBuffer(encryptedBuffer).then((decryptedBuffer) => {
  18120. const decryptedData = new Uint8Array(decryptedBuffer);
  18121. curUnit.set(decryptedData, 16);
  18122. if (!this.decrypter.isSync()) {
  18123. this.decryptAacSamples(samples, sampleIndex + 1, callback);
  18124. }
  18125. });
  18126. }
  18127. decryptAacSamples(samples, sampleIndex, callback) {
  18128. for (; ; sampleIndex++) {
  18129. if (sampleIndex >= samples.length) {
  18130. callback();
  18131. return;
  18132. }
  18133. if (samples[sampleIndex].unit.length < 32) {
  18134. continue;
  18135. }
  18136. this.decryptAacSample(samples, sampleIndex, callback);
  18137. if (!this.decrypter.isSync()) {
  18138. return;
  18139. }
  18140. }
  18141. }
  18142. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  18143. getAvcEncryptedData(decodedData) {
  18144. const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  18145. const encryptedData = new Int8Array(encryptedDataLen);
  18146. let outputPos = 0;
  18147. for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  18148. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  18149. }
  18150. return encryptedData;
  18151. }
  18152. getAvcDecryptedUnit(decodedData, decryptedData) {
  18153. const uint8DecryptedData = new Uint8Array(decryptedData);
  18154. let inputPos = 0;
  18155. for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  18156. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  18157. }
  18158. return decodedData;
  18159. }
  18160. decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  18161. const decodedData = discardEPB(curUnit.data);
  18162. const encryptedData = this.getAvcEncryptedData(decodedData);
  18163. this.decryptBuffer(encryptedData.buffer).then((decryptedBuffer) => {
  18164. curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  18165. if (!this.decrypter.isSync()) {
  18166. this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  18167. }
  18168. });
  18169. }
  18170. decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  18171. if (samples instanceof Uint8Array) {
  18172. throw new Error("Cannot decrypt samples of type Uint8Array");
  18173. }
  18174. for (; ; sampleIndex++, unitIndex = 0) {
  18175. if (sampleIndex >= samples.length) {
  18176. callback();
  18177. return;
  18178. }
  18179. const curUnits = samples[sampleIndex].units;
  18180. for (; ; unitIndex++) {
  18181. if (unitIndex >= curUnits.length) {
  18182. break;
  18183. }
  18184. const curUnit = curUnits[unitIndex];
  18185. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  18186. continue;
  18187. }
  18188. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  18189. if (!this.decrypter.isSync()) {
  18190. return;
  18191. }
  18192. }
  18193. }
  18194. }
  18195. }
  18196. class BaseVideoParser {
  18197. constructor() {
  18198. this.VideoSample = null;
  18199. }
  18200. createVideoSample(key, pts, dts) {
  18201. return {
  18202. key,
  18203. frame: false,
  18204. pts,
  18205. dts,
  18206. units: [],
  18207. length: 0
  18208. };
  18209. }
  18210. getLastNalUnit(samples) {
  18211. var _VideoSample;
  18212. let VideoSample = this.VideoSample;
  18213. let lastUnit;
  18214. if (!VideoSample || VideoSample.units.length === 0) {
  18215. VideoSample = samples[samples.length - 1];
  18216. }
  18217. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  18218. const units = VideoSample.units;
  18219. lastUnit = units[units.length - 1];
  18220. }
  18221. return lastUnit;
  18222. }
  18223. pushAccessUnit(VideoSample, videoTrack) {
  18224. if (VideoSample.units.length && VideoSample.frame) {
  18225. if (VideoSample.pts === void 0) {
  18226. const samples = videoTrack.samples;
  18227. const nbSamples = samples.length;
  18228. if (nbSamples) {
  18229. const lastSample = samples[nbSamples - 1];
  18230. VideoSample.pts = lastSample.pts;
  18231. VideoSample.dts = lastSample.dts;
  18232. } else {
  18233. videoTrack.dropped++;
  18234. return;
  18235. }
  18236. }
  18237. videoTrack.samples.push(VideoSample);
  18238. }
  18239. }
  18240. parseNALu(track2, array, endOfSegment) {
  18241. const len = array.byteLength;
  18242. let state = track2.naluState || 0;
  18243. const lastState = state;
  18244. const units = [];
  18245. let i2 = 0;
  18246. let value;
  18247. let overflow;
  18248. let unitType;
  18249. let lastUnitStart = -1;
  18250. let lastUnitType = 0;
  18251. if (state === -1) {
  18252. lastUnitStart = 0;
  18253. lastUnitType = this.getNALuType(array, 0);
  18254. state = 0;
  18255. i2 = 1;
  18256. }
  18257. while (i2 < len) {
  18258. value = array[i2++];
  18259. if (!state) {
  18260. state = value ? 0 : 1;
  18261. continue;
  18262. }
  18263. if (state === 1) {
  18264. state = value ? 0 : 2;
  18265. continue;
  18266. }
  18267. if (!value) {
  18268. state = 3;
  18269. } else if (value === 1) {
  18270. overflow = i2 - state - 1;
  18271. if (lastUnitStart >= 0) {
  18272. const unit = {
  18273. data: array.subarray(lastUnitStart, overflow),
  18274. type: lastUnitType
  18275. };
  18276. units.push(unit);
  18277. } else {
  18278. const lastUnit = this.getLastNalUnit(track2.samples);
  18279. if (lastUnit) {
  18280. if (lastState && i2 <= 4 - lastState) {
  18281. if (lastUnit.state) {
  18282. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  18283. }
  18284. }
  18285. if (overflow > 0) {
  18286. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  18287. lastUnit.state = 0;
  18288. }
  18289. }
  18290. }
  18291. if (i2 < len) {
  18292. unitType = this.getNALuType(array, i2);
  18293. lastUnitStart = i2;
  18294. lastUnitType = unitType;
  18295. state = 0;
  18296. } else {
  18297. state = -1;
  18298. }
  18299. } else {
  18300. state = 0;
  18301. }
  18302. }
  18303. if (lastUnitStart >= 0 && state >= 0) {
  18304. const unit = {
  18305. data: array.subarray(lastUnitStart, len),
  18306. type: lastUnitType,
  18307. state
  18308. };
  18309. units.push(unit);
  18310. }
  18311. if (units.length === 0) {
  18312. const lastUnit = this.getLastNalUnit(track2.samples);
  18313. if (lastUnit) {
  18314. lastUnit.data = appendUint8Array(lastUnit.data, array);
  18315. }
  18316. }
  18317. track2.naluState = state;
  18318. return units;
  18319. }
  18320. }
  18321. class ExpGolomb {
  18322. constructor(data) {
  18323. this.data = void 0;
  18324. this.bytesAvailable = void 0;
  18325. this.word = void 0;
  18326. this.bitsAvailable = void 0;
  18327. this.data = data;
  18328. this.bytesAvailable = data.byteLength;
  18329. this.word = 0;
  18330. this.bitsAvailable = 0;
  18331. }
  18332. // ():void
  18333. loadWord() {
  18334. const data = this.data;
  18335. const bytesAvailable = this.bytesAvailable;
  18336. const position = data.byteLength - bytesAvailable;
  18337. const workingBytes = new Uint8Array(4);
  18338. const availableBytes = Math.min(4, bytesAvailable);
  18339. if (availableBytes === 0) {
  18340. throw new Error("no bytes available");
  18341. }
  18342. workingBytes.set(data.subarray(position, position + availableBytes));
  18343. this.word = new DataView(workingBytes.buffer).getUint32(0);
  18344. this.bitsAvailable = availableBytes * 8;
  18345. this.bytesAvailable -= availableBytes;
  18346. }
  18347. // (count:int):void
  18348. skipBits(count) {
  18349. let skipBytes;
  18350. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  18351. if (this.bitsAvailable > count) {
  18352. this.word <<= count;
  18353. this.bitsAvailable -= count;
  18354. } else {
  18355. count -= this.bitsAvailable;
  18356. skipBytes = count >> 3;
  18357. count -= skipBytes << 3;
  18358. this.bytesAvailable -= skipBytes;
  18359. this.loadWord();
  18360. this.word <<= count;
  18361. this.bitsAvailable -= count;
  18362. }
  18363. }
  18364. // (size:int):uint
  18365. readBits(size2) {
  18366. let bits = Math.min(this.bitsAvailable, size2);
  18367. const valu = this.word >>> 32 - bits;
  18368. if (size2 > 32) {
  18369. logger.error("Cannot read more than 32 bits at a time");
  18370. }
  18371. this.bitsAvailable -= bits;
  18372. if (this.bitsAvailable > 0) {
  18373. this.word <<= bits;
  18374. } else if (this.bytesAvailable > 0) {
  18375. this.loadWord();
  18376. } else {
  18377. throw new Error("no bits available");
  18378. }
  18379. bits = size2 - bits;
  18380. if (bits > 0 && this.bitsAvailable) {
  18381. return valu << bits | this.readBits(bits);
  18382. } else {
  18383. return valu;
  18384. }
  18385. }
  18386. // ():uint
  18387. skipLZ() {
  18388. let leadingZeroCount;
  18389. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  18390. if ((this.word & 2147483648 >>> leadingZeroCount) !== 0) {
  18391. this.word <<= leadingZeroCount;
  18392. this.bitsAvailable -= leadingZeroCount;
  18393. return leadingZeroCount;
  18394. }
  18395. }
  18396. this.loadWord();
  18397. return leadingZeroCount + this.skipLZ();
  18398. }
  18399. // ():void
  18400. skipUEG() {
  18401. this.skipBits(1 + this.skipLZ());
  18402. }
  18403. // ():void
  18404. skipEG() {
  18405. this.skipBits(1 + this.skipLZ());
  18406. }
  18407. // ():uint
  18408. readUEG() {
  18409. const clz = this.skipLZ();
  18410. return this.readBits(clz + 1) - 1;
  18411. }
  18412. // ():int
  18413. readEG() {
  18414. const valu = this.readUEG();
  18415. if (1 & valu) {
  18416. return 1 + valu >>> 1;
  18417. } else {
  18418. return -1 * (valu >>> 1);
  18419. }
  18420. }
  18421. // Some convenience functions
  18422. // :Boolean
  18423. readBoolean() {
  18424. return this.readBits(1) === 1;
  18425. }
  18426. // ():int
  18427. readUByte() {
  18428. return this.readBits(8);
  18429. }
  18430. // ():int
  18431. readUShort() {
  18432. return this.readBits(16);
  18433. }
  18434. // ():int
  18435. readUInt() {
  18436. return this.readBits(32);
  18437. }
  18438. }
  18439. class AvcVideoParser extends BaseVideoParser {
  18440. parsePES(track2, textTrack, pes, endOfSegment) {
  18441. const units = this.parseNALu(track2, pes.data, endOfSegment);
  18442. let VideoSample = this.VideoSample;
  18443. let push2;
  18444. let spsfound = false;
  18445. pes.data = null;
  18446. if (VideoSample && units.length && !track2.audFound) {
  18447. this.pushAccessUnit(VideoSample, track2);
  18448. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  18449. }
  18450. units.forEach((unit) => {
  18451. var _VideoSample2, _VideoSample3;
  18452. switch (unit.type) {
  18453. case 1: {
  18454. let iskey = false;
  18455. push2 = true;
  18456. const data = unit.data;
  18457. if (spsfound && data.length > 4) {
  18458. const sliceType = this.readSliceType(data);
  18459. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  18460. iskey = true;
  18461. }
  18462. }
  18463. if (iskey) {
  18464. var _VideoSample;
  18465. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  18466. this.pushAccessUnit(VideoSample, track2);
  18467. VideoSample = this.VideoSample = null;
  18468. }
  18469. }
  18470. if (!VideoSample) {
  18471. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  18472. }
  18473. VideoSample.frame = true;
  18474. VideoSample.key = iskey;
  18475. break;
  18476. }
  18477. case 5:
  18478. push2 = true;
  18479. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  18480. this.pushAccessUnit(VideoSample, track2);
  18481. VideoSample = this.VideoSample = null;
  18482. }
  18483. if (!VideoSample) {
  18484. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  18485. }
  18486. VideoSample.key = true;
  18487. VideoSample.frame = true;
  18488. break;
  18489. case 6: {
  18490. push2 = true;
  18491. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  18492. break;
  18493. }
  18494. case 7: {
  18495. var _track$pixelRatio, _track$pixelRatio2;
  18496. push2 = true;
  18497. spsfound = true;
  18498. const sps = unit.data;
  18499. const config = this.readSPS(sps);
  18500. if (!track2.sps || track2.width !== config.width || track2.height !== config.height || ((_track$pixelRatio = track2.pixelRatio) == null ? void 0 : _track$pixelRatio[0]) !== config.pixelRatio[0] || ((_track$pixelRatio2 = track2.pixelRatio) == null ? void 0 : _track$pixelRatio2[1]) !== config.pixelRatio[1]) {
  18501. track2.width = config.width;
  18502. track2.height = config.height;
  18503. track2.pixelRatio = config.pixelRatio;
  18504. track2.sps = [sps];
  18505. const codecarray = sps.subarray(1, 4);
  18506. let codecstring = "avc1.";
  18507. for (let i2 = 0; i2 < 3; i2++) {
  18508. let h2 = codecarray[i2].toString(16);
  18509. if (h2.length < 2) {
  18510. h2 = "0" + h2;
  18511. }
  18512. codecstring += h2;
  18513. }
  18514. track2.codec = codecstring;
  18515. }
  18516. break;
  18517. }
  18518. case 8:
  18519. push2 = true;
  18520. track2.pps = [unit.data];
  18521. break;
  18522. case 9:
  18523. push2 = true;
  18524. track2.audFound = true;
  18525. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  18526. this.pushAccessUnit(VideoSample, track2);
  18527. VideoSample = null;
  18528. }
  18529. if (!VideoSample) {
  18530. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  18531. }
  18532. break;
  18533. case 12:
  18534. push2 = true;
  18535. break;
  18536. default:
  18537. push2 = false;
  18538. break;
  18539. }
  18540. if (VideoSample && push2) {
  18541. const units2 = VideoSample.units;
  18542. units2.push(unit);
  18543. }
  18544. });
  18545. if (endOfSegment && VideoSample) {
  18546. this.pushAccessUnit(VideoSample, track2);
  18547. this.VideoSample = null;
  18548. }
  18549. }
  18550. getNALuType(data, offset) {
  18551. return data[offset] & 31;
  18552. }
  18553. readSliceType(data) {
  18554. const eg = new ExpGolomb(data);
  18555. eg.readUByte();
  18556. eg.readUEG();
  18557. return eg.readUEG();
  18558. }
  18559. /**
  18560. * The scaling list is optionally transmitted as part of a sequence parameter
  18561. * set and is not relevant to transmuxing.
  18562. * @param count the number of entries in this scaling list
  18563. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  18564. */
  18565. skipScalingList(count, reader) {
  18566. let lastScale = 8;
  18567. let nextScale = 8;
  18568. let deltaScale;
  18569. for (let j2 = 0; j2 < count; j2++) {
  18570. if (nextScale !== 0) {
  18571. deltaScale = reader.readEG();
  18572. nextScale = (lastScale + deltaScale + 256) % 256;
  18573. }
  18574. lastScale = nextScale === 0 ? lastScale : nextScale;
  18575. }
  18576. }
  18577. /**
  18578. * Read a sequence parameter set and return some interesting video
  18579. * properties. A sequence parameter set is the H264 metadata that
  18580. * describes the properties of upcoming video frames.
  18581. * @returns an object with configuration parsed from the
  18582. * sequence parameter set, including the dimensions of the
  18583. * associated video frames.
  18584. */
  18585. readSPS(sps) {
  18586. const eg = new ExpGolomb(sps);
  18587. let frameCropLeftOffset = 0;
  18588. let frameCropRightOffset = 0;
  18589. let frameCropTopOffset = 0;
  18590. let frameCropBottomOffset = 0;
  18591. let numRefFramesInPicOrderCntCycle;
  18592. let scalingListCount;
  18593. let i2;
  18594. const readUByte = eg.readUByte.bind(eg);
  18595. const readBits = eg.readBits.bind(eg);
  18596. const readUEG = eg.readUEG.bind(eg);
  18597. const readBoolean = eg.readBoolean.bind(eg);
  18598. const skipBits = eg.skipBits.bind(eg);
  18599. const skipEG = eg.skipEG.bind(eg);
  18600. const skipUEG = eg.skipUEG.bind(eg);
  18601. const skipScalingList = this.skipScalingList.bind(this);
  18602. readUByte();
  18603. const profileIdc = readUByte();
  18604. readBits(5);
  18605. skipBits(3);
  18606. readUByte();
  18607. skipUEG();
  18608. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  18609. const chromaFormatIdc = readUEG();
  18610. if (chromaFormatIdc === 3) {
  18611. skipBits(1);
  18612. }
  18613. skipUEG();
  18614. skipUEG();
  18615. skipBits(1);
  18616. if (readBoolean()) {
  18617. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  18618. for (i2 = 0; i2 < scalingListCount; i2++) {
  18619. if (readBoolean()) {
  18620. if (i2 < 6) {
  18621. skipScalingList(16, eg);
  18622. } else {
  18623. skipScalingList(64, eg);
  18624. }
  18625. }
  18626. }
  18627. }
  18628. }
  18629. skipUEG();
  18630. const picOrderCntType = readUEG();
  18631. if (picOrderCntType === 0) {
  18632. readUEG();
  18633. } else if (picOrderCntType === 1) {
  18634. skipBits(1);
  18635. skipEG();
  18636. skipEG();
  18637. numRefFramesInPicOrderCntCycle = readUEG();
  18638. for (i2 = 0; i2 < numRefFramesInPicOrderCntCycle; i2++) {
  18639. skipEG();
  18640. }
  18641. }
  18642. skipUEG();
  18643. skipBits(1);
  18644. const picWidthInMbsMinus1 = readUEG();
  18645. const picHeightInMapUnitsMinus1 = readUEG();
  18646. const frameMbsOnlyFlag = readBits(1);
  18647. if (frameMbsOnlyFlag === 0) {
  18648. skipBits(1);
  18649. }
  18650. skipBits(1);
  18651. if (readBoolean()) {
  18652. frameCropLeftOffset = readUEG();
  18653. frameCropRightOffset = readUEG();
  18654. frameCropTopOffset = readUEG();
  18655. frameCropBottomOffset = readUEG();
  18656. }
  18657. let pixelRatio = [1, 1];
  18658. if (readBoolean()) {
  18659. if (readBoolean()) {
  18660. const aspectRatioIdc = readUByte();
  18661. switch (aspectRatioIdc) {
  18662. case 1:
  18663. pixelRatio = [1, 1];
  18664. break;
  18665. case 2:
  18666. pixelRatio = [12, 11];
  18667. break;
  18668. case 3:
  18669. pixelRatio = [10, 11];
  18670. break;
  18671. case 4:
  18672. pixelRatio = [16, 11];
  18673. break;
  18674. case 5:
  18675. pixelRatio = [40, 33];
  18676. break;
  18677. case 6:
  18678. pixelRatio = [24, 11];
  18679. break;
  18680. case 7:
  18681. pixelRatio = [20, 11];
  18682. break;
  18683. case 8:
  18684. pixelRatio = [32, 11];
  18685. break;
  18686. case 9:
  18687. pixelRatio = [80, 33];
  18688. break;
  18689. case 10:
  18690. pixelRatio = [18, 11];
  18691. break;
  18692. case 11:
  18693. pixelRatio = [15, 11];
  18694. break;
  18695. case 12:
  18696. pixelRatio = [64, 33];
  18697. break;
  18698. case 13:
  18699. pixelRatio = [160, 99];
  18700. break;
  18701. case 14:
  18702. pixelRatio = [4, 3];
  18703. break;
  18704. case 15:
  18705. pixelRatio = [3, 2];
  18706. break;
  18707. case 16:
  18708. pixelRatio = [2, 1];
  18709. break;
  18710. case 255: {
  18711. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  18712. break;
  18713. }
  18714. }
  18715. }
  18716. }
  18717. return {
  18718. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  18719. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  18720. pixelRatio
  18721. };
  18722. }
  18723. }
  18724. class HevcVideoParser extends BaseVideoParser {
  18725. constructor(...args) {
  18726. super(...args);
  18727. this.initVPS = null;
  18728. }
  18729. parsePES(track2, textTrack, pes, endOfSegment) {
  18730. const units = this.parseNALu(track2, pes.data, endOfSegment);
  18731. let VideoSample = this.VideoSample;
  18732. let push2;
  18733. let spsfound = false;
  18734. pes.data = null;
  18735. if (VideoSample && units.length && !track2.audFound) {
  18736. this.pushAccessUnit(VideoSample, track2);
  18737. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  18738. }
  18739. units.forEach((unit) => {
  18740. var _VideoSample2, _VideoSample3;
  18741. switch (unit.type) {
  18742. case 0:
  18743. case 1:
  18744. case 2:
  18745. case 3:
  18746. case 4:
  18747. case 5:
  18748. case 6:
  18749. case 7:
  18750. case 8:
  18751. case 9:
  18752. if (!VideoSample) {
  18753. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  18754. }
  18755. VideoSample.frame = true;
  18756. push2 = true;
  18757. break;
  18758. case 16:
  18759. case 17:
  18760. case 18:
  18761. case 21:
  18762. push2 = true;
  18763. if (spsfound) {
  18764. var _VideoSample;
  18765. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  18766. this.pushAccessUnit(VideoSample, track2);
  18767. VideoSample = this.VideoSample = null;
  18768. }
  18769. }
  18770. if (!VideoSample) {
  18771. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  18772. }
  18773. VideoSample.key = true;
  18774. VideoSample.frame = true;
  18775. break;
  18776. case 19:
  18777. case 20:
  18778. push2 = true;
  18779. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  18780. this.pushAccessUnit(VideoSample, track2);
  18781. VideoSample = this.VideoSample = null;
  18782. }
  18783. if (!VideoSample) {
  18784. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  18785. }
  18786. VideoSample.key = true;
  18787. VideoSample.frame = true;
  18788. break;
  18789. case 39:
  18790. push2 = true;
  18791. parseSEIMessageFromNALu(
  18792. unit.data,
  18793. 2,
  18794. // NALu header size
  18795. pes.pts,
  18796. textTrack.samples
  18797. );
  18798. break;
  18799. case 32:
  18800. push2 = true;
  18801. if (!track2.vps) {
  18802. if (typeof track2.params !== "object") {
  18803. track2.params = {};
  18804. }
  18805. track2.params = _extends(track2.params, this.readVPS(unit.data));
  18806. this.initVPS = unit.data;
  18807. }
  18808. track2.vps = [unit.data];
  18809. break;
  18810. case 33:
  18811. push2 = true;
  18812. spsfound = true;
  18813. if (track2.vps !== void 0 && track2.vps[0] !== this.initVPS && track2.sps !== void 0 && !this.matchSPS(track2.sps[0], unit.data)) {
  18814. this.initVPS = track2.vps[0];
  18815. track2.sps = track2.pps = void 0;
  18816. }
  18817. if (!track2.sps) {
  18818. const config = this.readSPS(unit.data);
  18819. track2.width = config.width;
  18820. track2.height = config.height;
  18821. track2.pixelRatio = config.pixelRatio;
  18822. track2.codec = config.codecString;
  18823. track2.sps = [];
  18824. if (typeof track2.params !== "object") {
  18825. track2.params = {};
  18826. }
  18827. for (const prop in config.params) {
  18828. track2.params[prop] = config.params[prop];
  18829. }
  18830. }
  18831. this.pushParameterSet(track2.sps, unit.data, track2.vps);
  18832. if (!VideoSample) {
  18833. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  18834. }
  18835. VideoSample.key = true;
  18836. break;
  18837. case 34:
  18838. push2 = true;
  18839. if (typeof track2.params === "object") {
  18840. if (!track2.pps) {
  18841. track2.pps = [];
  18842. const config = this.readPPS(unit.data);
  18843. for (const prop in config) {
  18844. track2.params[prop] = config[prop];
  18845. }
  18846. }
  18847. this.pushParameterSet(track2.pps, unit.data, track2.vps);
  18848. }
  18849. break;
  18850. case 35:
  18851. push2 = true;
  18852. track2.audFound = true;
  18853. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  18854. this.pushAccessUnit(VideoSample, track2);
  18855. VideoSample = null;
  18856. }
  18857. if (!VideoSample) {
  18858. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  18859. }
  18860. break;
  18861. default:
  18862. push2 = false;
  18863. break;
  18864. }
  18865. if (VideoSample && push2) {
  18866. const units2 = VideoSample.units;
  18867. units2.push(unit);
  18868. }
  18869. });
  18870. if (endOfSegment && VideoSample) {
  18871. this.pushAccessUnit(VideoSample, track2);
  18872. this.VideoSample = null;
  18873. }
  18874. }
  18875. pushParameterSet(parameterSets, data, vps) {
  18876. if (vps && vps[0] === this.initVPS || !vps && !parameterSets.length) {
  18877. parameterSets.push(data);
  18878. }
  18879. }
  18880. getNALuType(data, offset) {
  18881. return (data[offset] & 126) >>> 1;
  18882. }
  18883. ebsp2rbsp(arr) {
  18884. const dst = new Uint8Array(arr.byteLength);
  18885. let dstIdx = 0;
  18886. for (let i2 = 0; i2 < arr.byteLength; i2++) {
  18887. if (i2 >= 2) {
  18888. if (arr[i2] === 3 && arr[i2 - 1] === 0 && arr[i2 - 2] === 0) {
  18889. continue;
  18890. }
  18891. }
  18892. dst[dstIdx] = arr[i2];
  18893. dstIdx++;
  18894. }
  18895. return new Uint8Array(dst.buffer, 0, dstIdx);
  18896. }
  18897. pushAccessUnit(VideoSample, videoTrack) {
  18898. super.pushAccessUnit(VideoSample, videoTrack);
  18899. if (this.initVPS) {
  18900. this.initVPS = null;
  18901. }
  18902. }
  18903. readVPS(vps) {
  18904. const eg = new ExpGolomb(vps);
  18905. eg.readUByte();
  18906. eg.readUByte();
  18907. eg.readBits(4);
  18908. eg.skipBits(2);
  18909. eg.readBits(6);
  18910. const max_sub_layers_minus1 = eg.readBits(3);
  18911. const temporal_id_nesting_flag = eg.readBoolean();
  18912. return {
  18913. numTemporalLayers: max_sub_layers_minus1 + 1,
  18914. temporalIdNested: temporal_id_nesting_flag
  18915. };
  18916. }
  18917. readSPS(sps) {
  18918. const eg = new ExpGolomb(this.ebsp2rbsp(sps));
  18919. eg.readUByte();
  18920. eg.readUByte();
  18921. eg.readBits(4);
  18922. const max_sub_layers_minus1 = eg.readBits(3);
  18923. eg.readBoolean();
  18924. const general_profile_space = eg.readBits(2);
  18925. const general_tier_flag = eg.readBoolean();
  18926. const general_profile_idc = eg.readBits(5);
  18927. const general_profile_compatibility_flags_1 = eg.readUByte();
  18928. const general_profile_compatibility_flags_2 = eg.readUByte();
  18929. const general_profile_compatibility_flags_3 = eg.readUByte();
  18930. const general_profile_compatibility_flags_4 = eg.readUByte();
  18931. const general_constraint_indicator_flags_1 = eg.readUByte();
  18932. const general_constraint_indicator_flags_2 = eg.readUByte();
  18933. const general_constraint_indicator_flags_3 = eg.readUByte();
  18934. const general_constraint_indicator_flags_4 = eg.readUByte();
  18935. const general_constraint_indicator_flags_5 = eg.readUByte();
  18936. const general_constraint_indicator_flags_6 = eg.readUByte();
  18937. const general_level_idc = eg.readUByte();
  18938. const sub_layer_profile_present_flags = [];
  18939. const sub_layer_level_present_flags = [];
  18940. for (let i2 = 0; i2 < max_sub_layers_minus1; i2++) {
  18941. sub_layer_profile_present_flags.push(eg.readBoolean());
  18942. sub_layer_level_present_flags.push(eg.readBoolean());
  18943. }
  18944. if (max_sub_layers_minus1 > 0) {
  18945. for (let i2 = max_sub_layers_minus1; i2 < 8; i2++) {
  18946. eg.readBits(2);
  18947. }
  18948. }
  18949. for (let i2 = 0; i2 < max_sub_layers_minus1; i2++) {
  18950. if (sub_layer_profile_present_flags[i2]) {
  18951. eg.readUByte();
  18952. eg.readUByte();
  18953. eg.readUByte();
  18954. eg.readUByte();
  18955. eg.readUByte();
  18956. eg.readUByte();
  18957. eg.readUByte();
  18958. eg.readUByte();
  18959. eg.readUByte();
  18960. eg.readUByte();
  18961. eg.readUByte();
  18962. }
  18963. if (sub_layer_level_present_flags[i2]) {
  18964. eg.readUByte();
  18965. }
  18966. }
  18967. eg.readUEG();
  18968. const chroma_format_idc = eg.readUEG();
  18969. if (chroma_format_idc == 3) {
  18970. eg.skipBits(1);
  18971. }
  18972. const pic_width_in_luma_samples = eg.readUEG();
  18973. const pic_height_in_luma_samples = eg.readUEG();
  18974. const conformance_window_flag = eg.readBoolean();
  18975. let pic_left_offset = 0, pic_right_offset = 0, pic_top_offset = 0, pic_bottom_offset = 0;
  18976. if (conformance_window_flag) {
  18977. pic_left_offset += eg.readUEG();
  18978. pic_right_offset += eg.readUEG();
  18979. pic_top_offset += eg.readUEG();
  18980. pic_bottom_offset += eg.readUEG();
  18981. }
  18982. const bit_depth_luma_minus8 = eg.readUEG();
  18983. const bit_depth_chroma_minus8 = eg.readUEG();
  18984. const log2_max_pic_order_cnt_lsb_minus4 = eg.readUEG();
  18985. const sub_layer_ordering_info_present_flag = eg.readBoolean();
  18986. for (let i2 = sub_layer_ordering_info_present_flag ? 0 : max_sub_layers_minus1; i2 <= max_sub_layers_minus1; i2++) {
  18987. eg.skipUEG();
  18988. eg.skipUEG();
  18989. eg.skipUEG();
  18990. }
  18991. eg.skipUEG();
  18992. eg.skipUEG();
  18993. eg.skipUEG();
  18994. eg.skipUEG();
  18995. eg.skipUEG();
  18996. eg.skipUEG();
  18997. const scaling_list_enabled_flag = eg.readBoolean();
  18998. if (scaling_list_enabled_flag) {
  18999. const sps_scaling_list_data_present_flag = eg.readBoolean();
  19000. if (sps_scaling_list_data_present_flag) {
  19001. for (let sizeId = 0; sizeId < 4; sizeId++) {
  19002. for (let matrixId = 0; matrixId < (sizeId === 3 ? 2 : 6); matrixId++) {
  19003. const scaling_list_pred_mode_flag = eg.readBoolean();
  19004. if (!scaling_list_pred_mode_flag) {
  19005. eg.readUEG();
  19006. } else {
  19007. const coefNum = Math.min(64, 1 << 4 + (sizeId << 1));
  19008. if (sizeId > 1) {
  19009. eg.readEG();
  19010. }
  19011. for (let i2 = 0; i2 < coefNum; i2++) {
  19012. eg.readEG();
  19013. }
  19014. }
  19015. }
  19016. }
  19017. }
  19018. }
  19019. eg.readBoolean();
  19020. eg.readBoolean();
  19021. const pcm_enabled_flag = eg.readBoolean();
  19022. if (pcm_enabled_flag) {
  19023. eg.readUByte();
  19024. eg.skipUEG();
  19025. eg.skipUEG();
  19026. eg.readBoolean();
  19027. }
  19028. const num_short_term_ref_pic_sets = eg.readUEG();
  19029. let num_delta_pocs = 0;
  19030. for (let i2 = 0; i2 < num_short_term_ref_pic_sets; i2++) {
  19031. let inter_ref_pic_set_prediction_flag = false;
  19032. if (i2 !== 0) {
  19033. inter_ref_pic_set_prediction_flag = eg.readBoolean();
  19034. }
  19035. if (inter_ref_pic_set_prediction_flag) {
  19036. if (i2 === num_short_term_ref_pic_sets) {
  19037. eg.readUEG();
  19038. }
  19039. eg.readBoolean();
  19040. eg.readUEG();
  19041. let next_num_delta_pocs = 0;
  19042. for (let j2 = 0; j2 <= num_delta_pocs; j2++) {
  19043. const used_by_curr_pic_flag = eg.readBoolean();
  19044. let use_delta_flag = false;
  19045. if (!used_by_curr_pic_flag) {
  19046. use_delta_flag = eg.readBoolean();
  19047. }
  19048. if (used_by_curr_pic_flag || use_delta_flag) {
  19049. next_num_delta_pocs++;
  19050. }
  19051. }
  19052. num_delta_pocs = next_num_delta_pocs;
  19053. } else {
  19054. const num_negative_pics = eg.readUEG();
  19055. const num_positive_pics = eg.readUEG();
  19056. num_delta_pocs = num_negative_pics + num_positive_pics;
  19057. for (let j2 = 0; j2 < num_negative_pics; j2++) {
  19058. eg.readUEG();
  19059. eg.readBoolean();
  19060. }
  19061. for (let j2 = 0; j2 < num_positive_pics; j2++) {
  19062. eg.readUEG();
  19063. eg.readBoolean();
  19064. }
  19065. }
  19066. }
  19067. const long_term_ref_pics_present_flag = eg.readBoolean();
  19068. if (long_term_ref_pics_present_flag) {
  19069. const num_long_term_ref_pics_sps = eg.readUEG();
  19070. for (let i2 = 0; i2 < num_long_term_ref_pics_sps; i2++) {
  19071. for (let j2 = 0; j2 < log2_max_pic_order_cnt_lsb_minus4 + 4; j2++) {
  19072. eg.readBits(1);
  19073. }
  19074. eg.readBits(1);
  19075. }
  19076. }
  19077. let min_spatial_segmentation_idc = 0;
  19078. let sar_width = 1, sar_height = 1;
  19079. let fps_fixed = true, fps_den = 1, fps_num = 0;
  19080. eg.readBoolean();
  19081. eg.readBoolean();
  19082. let default_display_window_flag = false;
  19083. const vui_parameters_present_flag = eg.readBoolean();
  19084. if (vui_parameters_present_flag) {
  19085. const aspect_ratio_info_present_flag = eg.readBoolean();
  19086. if (aspect_ratio_info_present_flag) {
  19087. const aspect_ratio_idc = eg.readUByte();
  19088. const sar_width_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  19089. const sar_height_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  19090. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  19091. sar_width = sar_width_table[aspect_ratio_idc - 1];
  19092. sar_height = sar_height_table[aspect_ratio_idc - 1];
  19093. } else if (aspect_ratio_idc === 255) {
  19094. sar_width = eg.readBits(16);
  19095. sar_height = eg.readBits(16);
  19096. }
  19097. }
  19098. const overscan_info_present_flag = eg.readBoolean();
  19099. if (overscan_info_present_flag) {
  19100. eg.readBoolean();
  19101. }
  19102. const video_signal_type_present_flag = eg.readBoolean();
  19103. if (video_signal_type_present_flag) {
  19104. eg.readBits(3);
  19105. eg.readBoolean();
  19106. const colour_description_present_flag = eg.readBoolean();
  19107. if (colour_description_present_flag) {
  19108. eg.readUByte();
  19109. eg.readUByte();
  19110. eg.readUByte();
  19111. }
  19112. }
  19113. const chroma_loc_info_present_flag = eg.readBoolean();
  19114. if (chroma_loc_info_present_flag) {
  19115. eg.readUEG();
  19116. eg.readUEG();
  19117. }
  19118. eg.readBoolean();
  19119. eg.readBoolean();
  19120. eg.readBoolean();
  19121. default_display_window_flag = eg.readBoolean();
  19122. if (default_display_window_flag) {
  19123. pic_left_offset += eg.readUEG();
  19124. pic_right_offset += eg.readUEG();
  19125. pic_top_offset += eg.readUEG();
  19126. pic_bottom_offset += eg.readUEG();
  19127. }
  19128. const vui_timing_info_present_flag = eg.readBoolean();
  19129. if (vui_timing_info_present_flag) {
  19130. fps_den = eg.readBits(32);
  19131. fps_num = eg.readBits(32);
  19132. const vui_poc_proportional_to_timing_flag = eg.readBoolean();
  19133. if (vui_poc_proportional_to_timing_flag) {
  19134. eg.readUEG();
  19135. }
  19136. const vui_hrd_parameters_present_flag = eg.readBoolean();
  19137. if (vui_hrd_parameters_present_flag) {
  19138. const nal_hrd_parameters_present_flag = eg.readBoolean();
  19139. const vcl_hrd_parameters_present_flag = eg.readBoolean();
  19140. let sub_pic_hrd_params_present_flag = false;
  19141. if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
  19142. sub_pic_hrd_params_present_flag = eg.readBoolean();
  19143. if (sub_pic_hrd_params_present_flag) {
  19144. eg.readUByte();
  19145. eg.readBits(5);
  19146. eg.readBoolean();
  19147. eg.readBits(5);
  19148. }
  19149. eg.readBits(4);
  19150. eg.readBits(4);
  19151. if (sub_pic_hrd_params_present_flag) {
  19152. eg.readBits(4);
  19153. }
  19154. eg.readBits(5);
  19155. eg.readBits(5);
  19156. eg.readBits(5);
  19157. }
  19158. for (let i2 = 0; i2 <= max_sub_layers_minus1; i2++) {
  19159. fps_fixed = eg.readBoolean();
  19160. const fixed_pic_rate_within_cvs_flag = fps_fixed || eg.readBoolean();
  19161. let low_delay_hrd_flag = false;
  19162. if (fixed_pic_rate_within_cvs_flag) {
  19163. eg.readEG();
  19164. } else {
  19165. low_delay_hrd_flag = eg.readBoolean();
  19166. }
  19167. const cpb_cnt = low_delay_hrd_flag ? 1 : eg.readUEG() + 1;
  19168. if (nal_hrd_parameters_present_flag) {
  19169. for (let j2 = 0; j2 < cpb_cnt; j2++) {
  19170. eg.readUEG();
  19171. eg.readUEG();
  19172. if (sub_pic_hrd_params_present_flag) {
  19173. eg.readUEG();
  19174. eg.readUEG();
  19175. }
  19176. eg.skipBits(1);
  19177. }
  19178. }
  19179. if (vcl_hrd_parameters_present_flag) {
  19180. for (let j2 = 0; j2 < cpb_cnt; j2++) {
  19181. eg.readUEG();
  19182. eg.readUEG();
  19183. if (sub_pic_hrd_params_present_flag) {
  19184. eg.readUEG();
  19185. eg.readUEG();
  19186. }
  19187. eg.skipBits(1);
  19188. }
  19189. }
  19190. }
  19191. }
  19192. }
  19193. const bitstream_restriction_flag = eg.readBoolean();
  19194. if (bitstream_restriction_flag) {
  19195. eg.readBoolean();
  19196. eg.readBoolean();
  19197. eg.readBoolean();
  19198. min_spatial_segmentation_idc = eg.readUEG();
  19199. }
  19200. }
  19201. let width = pic_width_in_luma_samples, height = pic_height_in_luma_samples;
  19202. if (conformance_window_flag || default_display_window_flag) {
  19203. let chroma_scale_w = 1, chroma_scale_h = 1;
  19204. if (chroma_format_idc === 1) {
  19205. chroma_scale_w = chroma_scale_h = 2;
  19206. } else if (chroma_format_idc == 2) {
  19207. chroma_scale_w = 2;
  19208. }
  19209. width = pic_width_in_luma_samples - chroma_scale_w * pic_right_offset - chroma_scale_w * pic_left_offset;
  19210. height = pic_height_in_luma_samples - chroma_scale_h * pic_bottom_offset - chroma_scale_h * pic_top_offset;
  19211. }
  19212. const profile_space_string = general_profile_space ? ["A", "B", "C"][general_profile_space] : "";
  19213. const profile_compatibility_buf = general_profile_compatibility_flags_1 << 24 | general_profile_compatibility_flags_2 << 16 | general_profile_compatibility_flags_3 << 8 | general_profile_compatibility_flags_4;
  19214. let profile_compatibility_rev = 0;
  19215. for (let i2 = 0; i2 < 32; i2++) {
  19216. profile_compatibility_rev = (profile_compatibility_rev | (profile_compatibility_buf >> i2 & 1) << 31 - i2) >>> 0;
  19217. }
  19218. let profile_compatibility_flags_string = profile_compatibility_rev.toString(16);
  19219. if (general_profile_idc === 1 && profile_compatibility_flags_string === "2") {
  19220. profile_compatibility_flags_string = "6";
  19221. }
  19222. const tier_flag_string = general_tier_flag ? "H" : "L";
  19223. return {
  19224. codecString: `hvc1.${profile_space_string}${general_profile_idc}.${profile_compatibility_flags_string}.${tier_flag_string}${general_level_idc}.B0`,
  19225. params: {
  19226. general_tier_flag,
  19227. general_profile_idc,
  19228. general_profile_space,
  19229. general_profile_compatibility_flags: [general_profile_compatibility_flags_1, general_profile_compatibility_flags_2, general_profile_compatibility_flags_3, general_profile_compatibility_flags_4],
  19230. general_constraint_indicator_flags: [general_constraint_indicator_flags_1, general_constraint_indicator_flags_2, general_constraint_indicator_flags_3, general_constraint_indicator_flags_4, general_constraint_indicator_flags_5, general_constraint_indicator_flags_6],
  19231. general_level_idc,
  19232. bit_depth: bit_depth_luma_minus8 + 8,
  19233. bit_depth_luma_minus8,
  19234. bit_depth_chroma_minus8,
  19235. min_spatial_segmentation_idc,
  19236. chroma_format_idc,
  19237. frame_rate: {
  19238. fixed: fps_fixed,
  19239. fps: fps_num / fps_den
  19240. }
  19241. },
  19242. width,
  19243. height,
  19244. pixelRatio: [sar_width, sar_height]
  19245. };
  19246. }
  19247. readPPS(pps) {
  19248. const eg = new ExpGolomb(this.ebsp2rbsp(pps));
  19249. eg.readUByte();
  19250. eg.readUByte();
  19251. eg.skipUEG();
  19252. eg.skipUEG();
  19253. eg.skipBits(2);
  19254. eg.skipBits(3);
  19255. eg.skipBits(2);
  19256. eg.skipUEG();
  19257. eg.skipUEG();
  19258. eg.skipEG();
  19259. eg.skipBits(2);
  19260. const cu_qp_delta_enabled_flag = eg.readBoolean();
  19261. if (cu_qp_delta_enabled_flag) {
  19262. eg.skipUEG();
  19263. }
  19264. eg.skipEG();
  19265. eg.skipEG();
  19266. eg.skipBits(4);
  19267. const tiles_enabled_flag = eg.readBoolean();
  19268. const entropy_coding_sync_enabled_flag = eg.readBoolean();
  19269. let parallelismType = 1;
  19270. if (entropy_coding_sync_enabled_flag && tiles_enabled_flag) {
  19271. parallelismType = 0;
  19272. } else if (entropy_coding_sync_enabled_flag) {
  19273. parallelismType = 3;
  19274. } else if (tiles_enabled_flag) {
  19275. parallelismType = 2;
  19276. }
  19277. return {
  19278. parallelismType
  19279. };
  19280. }
  19281. matchSPS(sps1, sps2) {
  19282. return String.fromCharCode.apply(null, sps1).substr(3) === String.fromCharCode.apply(null, sps2).substr(3);
  19283. }
  19284. }
  19285. const PACKET_LENGTH = 188;
  19286. class TSDemuxer {
  19287. constructor(observer, config, typeSupported, logger2) {
  19288. this.logger = void 0;
  19289. this.observer = void 0;
  19290. this.config = void 0;
  19291. this.typeSupported = void 0;
  19292. this.sampleAes = null;
  19293. this.pmtParsed = false;
  19294. this.audioCodec = void 0;
  19295. this.videoCodec = void 0;
  19296. this._pmtId = -1;
  19297. this._videoTrack = void 0;
  19298. this._audioTrack = void 0;
  19299. this._id3Track = void 0;
  19300. this._txtTrack = void 0;
  19301. this.aacOverFlow = null;
  19302. this.remainderData = null;
  19303. this.videoParser = void 0;
  19304. this.observer = observer;
  19305. this.config = config;
  19306. this.typeSupported = typeSupported;
  19307. this.logger = logger2;
  19308. this.videoParser = null;
  19309. }
  19310. static probe(data, logger2) {
  19311. const syncOffset = TSDemuxer.syncOffset(data);
  19312. if (syncOffset > 0) {
  19313. logger2.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);
  19314. }
  19315. return syncOffset !== -1;
  19316. }
  19317. static syncOffset(data) {
  19318. const length = data.length;
  19319. let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  19320. let i2 = 0;
  19321. while (i2 < scanwindow) {
  19322. let foundPat = false;
  19323. let packetStart = -1;
  19324. let tsPackets = 0;
  19325. for (let j2 = i2; j2 < length; j2 += PACKET_LENGTH) {
  19326. if (data[j2] === 71 && (length - j2 === PACKET_LENGTH || data[j2 + PACKET_LENGTH] === 71)) {
  19327. tsPackets++;
  19328. if (packetStart === -1) {
  19329. packetStart = j2;
  19330. if (packetStart !== 0) {
  19331. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  19332. }
  19333. }
  19334. if (!foundPat) {
  19335. foundPat = parsePID(data, j2) === 0;
  19336. }
  19337. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j2 + PACKET_LENGTH > scanwindow)) {
  19338. return packetStart;
  19339. }
  19340. } else if (tsPackets) {
  19341. return -1;
  19342. } else {
  19343. break;
  19344. }
  19345. }
  19346. i2++;
  19347. }
  19348. return -1;
  19349. }
  19350. /**
  19351. * Creates a track model internal to demuxer used to drive remuxing input
  19352. */
  19353. static createTrack(type, duration) {
  19354. return {
  19355. container: type === "video" || type === "audio" ? "video/mp2t" : void 0,
  19356. type,
  19357. id: RemuxerTrackIdConfig[type],
  19358. pid: -1,
  19359. inputTimeScale: 9e4,
  19360. sequenceNumber: 0,
  19361. samples: [],
  19362. dropped: 0,
  19363. duration: type === "audio" ? duration : void 0
  19364. };
  19365. }
  19366. /**
  19367. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  19368. * Resets all internal track instances of the demuxer.
  19369. */
  19370. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  19371. this.pmtParsed = false;
  19372. this._pmtId = -1;
  19373. this._videoTrack = TSDemuxer.createTrack("video");
  19374. this._videoTrack.duration = trackDuration;
  19375. this._audioTrack = TSDemuxer.createTrack("audio", trackDuration);
  19376. this._id3Track = TSDemuxer.createTrack("id3");
  19377. this._txtTrack = TSDemuxer.createTrack("text");
  19378. this._audioTrack.segmentCodec = "aac";
  19379. this.aacOverFlow = null;
  19380. this.remainderData = null;
  19381. this.audioCodec = audioCodec;
  19382. this.videoCodec = videoCodec;
  19383. }
  19384. resetTimeStamp() {
  19385. }
  19386. resetContiguity() {
  19387. const {
  19388. _audioTrack,
  19389. _videoTrack,
  19390. _id3Track
  19391. } = this;
  19392. if (_audioTrack) {
  19393. _audioTrack.pesData = null;
  19394. }
  19395. if (_videoTrack) {
  19396. _videoTrack.pesData = null;
  19397. }
  19398. if (_id3Track) {
  19399. _id3Track.pesData = null;
  19400. }
  19401. this.aacOverFlow = null;
  19402. this.remainderData = null;
  19403. }
  19404. demux(data, timeOffset, isSampleAes = false, flush = false) {
  19405. if (!isSampleAes) {
  19406. this.sampleAes = null;
  19407. }
  19408. let pes;
  19409. const videoTrack = this._videoTrack;
  19410. const audioTrack = this._audioTrack;
  19411. const id3Track = this._id3Track;
  19412. const textTrack = this._txtTrack;
  19413. let videoPid = videoTrack.pid;
  19414. let videoData = videoTrack.pesData;
  19415. let audioPid = audioTrack.pid;
  19416. let id3Pid = id3Track.pid;
  19417. let audioData = audioTrack.pesData;
  19418. let id3Data = id3Track.pesData;
  19419. let unknownPID = null;
  19420. let pmtParsed = this.pmtParsed;
  19421. let pmtId = this._pmtId;
  19422. let len = data.length;
  19423. if (this.remainderData) {
  19424. data = appendUint8Array(this.remainderData, data);
  19425. len = data.length;
  19426. this.remainderData = null;
  19427. }
  19428. if (len < PACKET_LENGTH && !flush) {
  19429. this.remainderData = data;
  19430. return {
  19431. audioTrack,
  19432. videoTrack,
  19433. id3Track,
  19434. textTrack
  19435. };
  19436. }
  19437. const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  19438. len -= (len - syncOffset) % PACKET_LENGTH;
  19439. if (len < data.byteLength && !flush) {
  19440. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  19441. }
  19442. let tsPacketErrors = 0;
  19443. for (let start = syncOffset; start < len; start += PACKET_LENGTH) {
  19444. if (data[start] === 71) {
  19445. const stt = !!(data[start + 1] & 64);
  19446. const pid = parsePID(data, start);
  19447. const atf = (data[start + 3] & 48) >> 4;
  19448. let offset;
  19449. if (atf > 1) {
  19450. offset = start + 5 + data[start + 4];
  19451. if (offset === start + PACKET_LENGTH) {
  19452. continue;
  19453. }
  19454. } else {
  19455. offset = start + 4;
  19456. }
  19457. switch (pid) {
  19458. case videoPid:
  19459. if (stt) {
  19460. if (videoData && (pes = parsePES(videoData, this.logger))) {
  19461. if (this.videoParser === null) {
  19462. switch (videoTrack.segmentCodec) {
  19463. case "avc":
  19464. this.videoParser = new AvcVideoParser();
  19465. break;
  19466. case "hevc":
  19467. {
  19468. this.videoParser = new HevcVideoParser();
  19469. }
  19470. break;
  19471. }
  19472. }
  19473. if (this.videoParser !== null) {
  19474. this.videoParser.parsePES(videoTrack, textTrack, pes, false);
  19475. }
  19476. }
  19477. videoData = {
  19478. data: [],
  19479. size: 0
  19480. };
  19481. }
  19482. if (videoData) {
  19483. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  19484. videoData.size += start + PACKET_LENGTH - offset;
  19485. }
  19486. break;
  19487. case audioPid:
  19488. if (stt) {
  19489. if (audioData && (pes = parsePES(audioData, this.logger))) {
  19490. switch (audioTrack.segmentCodec) {
  19491. case "aac":
  19492. this.parseAACPES(audioTrack, pes);
  19493. break;
  19494. case "mp3":
  19495. this.parseMPEGPES(audioTrack, pes);
  19496. break;
  19497. case "ac3":
  19498. {
  19499. this.parseAC3PES(audioTrack, pes);
  19500. }
  19501. break;
  19502. }
  19503. }
  19504. audioData = {
  19505. data: [],
  19506. size: 0
  19507. };
  19508. }
  19509. if (audioData) {
  19510. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  19511. audioData.size += start + PACKET_LENGTH - offset;
  19512. }
  19513. break;
  19514. case id3Pid:
  19515. if (stt) {
  19516. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  19517. this.parseID3PES(id3Track, pes);
  19518. }
  19519. id3Data = {
  19520. data: [],
  19521. size: 0
  19522. };
  19523. }
  19524. if (id3Data) {
  19525. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  19526. id3Data.size += start + PACKET_LENGTH - offset;
  19527. }
  19528. break;
  19529. case 0:
  19530. if (stt) {
  19531. offset += data[offset] + 1;
  19532. }
  19533. pmtId = this._pmtId = parsePAT(data, offset);
  19534. break;
  19535. case pmtId: {
  19536. if (stt) {
  19537. offset += data[offset] + 1;
  19538. }
  19539. const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer, this.logger);
  19540. videoPid = parsedPIDs.videoPid;
  19541. if (videoPid > 0) {
  19542. videoTrack.pid = videoPid;
  19543. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  19544. }
  19545. audioPid = parsedPIDs.audioPid;
  19546. if (audioPid > 0) {
  19547. audioTrack.pid = audioPid;
  19548. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  19549. }
  19550. id3Pid = parsedPIDs.id3Pid;
  19551. if (id3Pid > 0) {
  19552. id3Track.pid = id3Pid;
  19553. }
  19554. if (unknownPID !== null && !pmtParsed) {
  19555. this.logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);
  19556. unknownPID = null;
  19557. start = syncOffset - 188;
  19558. }
  19559. pmtParsed = this.pmtParsed = true;
  19560. break;
  19561. }
  19562. case 17:
  19563. case 8191:
  19564. break;
  19565. default:
  19566. unknownPID = pid;
  19567. break;
  19568. }
  19569. } else {
  19570. tsPacketErrors++;
  19571. }
  19572. }
  19573. if (tsPacketErrors > 0) {
  19574. emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`), void 0, this.logger);
  19575. }
  19576. videoTrack.pesData = videoData;
  19577. audioTrack.pesData = audioData;
  19578. id3Track.pesData = id3Data;
  19579. const demuxResult = {
  19580. audioTrack,
  19581. videoTrack,
  19582. id3Track,
  19583. textTrack
  19584. };
  19585. if (flush) {
  19586. this.extractRemainingSamples(demuxResult);
  19587. }
  19588. return demuxResult;
  19589. }
  19590. flush() {
  19591. const {
  19592. remainderData
  19593. } = this;
  19594. this.remainderData = null;
  19595. let result;
  19596. if (remainderData) {
  19597. result = this.demux(remainderData, -1, false, true);
  19598. } else {
  19599. result = {
  19600. videoTrack: this._videoTrack,
  19601. audioTrack: this._audioTrack,
  19602. id3Track: this._id3Track,
  19603. textTrack: this._txtTrack
  19604. };
  19605. }
  19606. this.extractRemainingSamples(result);
  19607. if (this.sampleAes) {
  19608. return this.decrypt(result, this.sampleAes);
  19609. }
  19610. return result;
  19611. }
  19612. extractRemainingSamples(demuxResult) {
  19613. const {
  19614. audioTrack,
  19615. videoTrack,
  19616. id3Track,
  19617. textTrack
  19618. } = demuxResult;
  19619. const videoData = videoTrack.pesData;
  19620. const audioData = audioTrack.pesData;
  19621. const id3Data = id3Track.pesData;
  19622. let pes;
  19623. if (videoData && (pes = parsePES(videoData, this.logger))) {
  19624. if (this.videoParser === null) {
  19625. switch (videoTrack.segmentCodec) {
  19626. case "avc":
  19627. this.videoParser = new AvcVideoParser();
  19628. break;
  19629. case "hevc":
  19630. {
  19631. this.videoParser = new HevcVideoParser();
  19632. }
  19633. break;
  19634. }
  19635. }
  19636. if (this.videoParser !== null) {
  19637. this.videoParser.parsePES(videoTrack, textTrack, pes, true);
  19638. videoTrack.pesData = null;
  19639. }
  19640. } else {
  19641. videoTrack.pesData = videoData;
  19642. }
  19643. if (audioData && (pes = parsePES(audioData, this.logger))) {
  19644. switch (audioTrack.segmentCodec) {
  19645. case "aac":
  19646. this.parseAACPES(audioTrack, pes);
  19647. break;
  19648. case "mp3":
  19649. this.parseMPEGPES(audioTrack, pes);
  19650. break;
  19651. case "ac3":
  19652. {
  19653. this.parseAC3PES(audioTrack, pes);
  19654. }
  19655. break;
  19656. }
  19657. audioTrack.pesData = null;
  19658. } else {
  19659. if (audioData != null && audioData.size) {
  19660. this.logger.log("last AAC PES packet truncated,might overlap between fragments");
  19661. }
  19662. audioTrack.pesData = audioData;
  19663. }
  19664. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  19665. this.parseID3PES(id3Track, pes);
  19666. id3Track.pesData = null;
  19667. } else {
  19668. id3Track.pesData = id3Data;
  19669. }
  19670. }
  19671. demuxSampleAes(data, keyData, timeOffset) {
  19672. const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  19673. const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  19674. return this.decrypt(demuxResult, sampleAes);
  19675. }
  19676. decrypt(demuxResult, sampleAes) {
  19677. return new Promise((resolve2) => {
  19678. const {
  19679. audioTrack,
  19680. videoTrack
  19681. } = demuxResult;
  19682. if (audioTrack.samples && audioTrack.segmentCodec === "aac") {
  19683. sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {
  19684. if (videoTrack.samples) {
  19685. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  19686. resolve2(demuxResult);
  19687. });
  19688. } else {
  19689. resolve2(demuxResult);
  19690. }
  19691. });
  19692. } else if (videoTrack.samples) {
  19693. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  19694. resolve2(demuxResult);
  19695. });
  19696. }
  19697. });
  19698. }
  19699. destroy() {
  19700. if (this.observer) {
  19701. this.observer.removeAllListeners();
  19702. }
  19703. this.config = this.logger = this.observer = null;
  19704. this.aacOverFlow = this.videoParser = this.remainderData = this.sampleAes = null;
  19705. this._videoTrack = this._audioTrack = this._id3Track = this._txtTrack = void 0;
  19706. }
  19707. parseAACPES(track2, pes) {
  19708. let startOffset = 0;
  19709. const aacOverFlow = this.aacOverFlow;
  19710. let data = pes.data;
  19711. if (aacOverFlow) {
  19712. this.aacOverFlow = null;
  19713. const frameMissingBytes = aacOverFlow.missing;
  19714. const sampleLength = aacOverFlow.sample.unit.byteLength;
  19715. if (frameMissingBytes === -1) {
  19716. data = appendUint8Array(aacOverFlow.sample.unit, data);
  19717. } else {
  19718. const frameOverflowBytes = sampleLength - frameMissingBytes;
  19719. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  19720. track2.samples.push(aacOverFlow.sample);
  19721. startOffset = aacOverFlow.missing;
  19722. }
  19723. }
  19724. let offset;
  19725. let len;
  19726. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  19727. if (isHeader$1(data, offset)) {
  19728. break;
  19729. }
  19730. }
  19731. if (offset !== startOffset) {
  19732. let reason;
  19733. const recoverable = offset < len - 1;
  19734. if (recoverable) {
  19735. reason = `AAC PES did not start with ADTS header,offset:${offset}`;
  19736. } else {
  19737. reason = "No ADTS header found in AAC PES";
  19738. }
  19739. emitParsingError(this.observer, new Error(reason), recoverable, this.logger);
  19740. if (!recoverable) {
  19741. return;
  19742. }
  19743. }
  19744. initTrackConfig(track2, this.observer, data, offset, this.audioCodec);
  19745. let pts;
  19746. if (pes.pts !== void 0) {
  19747. pts = pes.pts;
  19748. } else if (aacOverFlow) {
  19749. const frameDuration = getFrameDuration(track2.samplerate);
  19750. pts = aacOverFlow.sample.pts + frameDuration;
  19751. } else {
  19752. this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");
  19753. return;
  19754. }
  19755. let frameIndex = 0;
  19756. let frame;
  19757. while (offset < len) {
  19758. frame = appendFrame$2(track2, data, offset, pts, frameIndex);
  19759. offset += frame.length;
  19760. if (!frame.missing) {
  19761. frameIndex++;
  19762. for (; offset < len - 1; offset++) {
  19763. if (isHeader$1(data, offset)) {
  19764. break;
  19765. }
  19766. }
  19767. } else {
  19768. this.aacOverFlow = frame;
  19769. break;
  19770. }
  19771. }
  19772. }
  19773. parseMPEGPES(track2, pes) {
  19774. const data = pes.data;
  19775. const length = data.length;
  19776. let frameIndex = 0;
  19777. let offset = 0;
  19778. const pts = pes.pts;
  19779. if (pts === void 0) {
  19780. this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");
  19781. return;
  19782. }
  19783. while (offset < length) {
  19784. if (isHeader(data, offset)) {
  19785. const frame = appendFrame$1(track2, data, offset, pts, frameIndex);
  19786. if (frame) {
  19787. offset += frame.length;
  19788. frameIndex++;
  19789. } else {
  19790. break;
  19791. }
  19792. } else {
  19793. offset++;
  19794. }
  19795. }
  19796. }
  19797. parseAC3PES(track2, pes) {
  19798. {
  19799. const data = pes.data;
  19800. const pts = pes.pts;
  19801. if (pts === void 0) {
  19802. this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");
  19803. return;
  19804. }
  19805. const length = data.length;
  19806. let frameIndex = 0;
  19807. let offset = 0;
  19808. let parsed;
  19809. while (offset < length && (parsed = appendFrame(track2, data, offset, pts, frameIndex++)) > 0) {
  19810. offset += parsed;
  19811. }
  19812. }
  19813. }
  19814. parseID3PES(id3Track, pes) {
  19815. if (pes.pts === void 0) {
  19816. this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");
  19817. return;
  19818. }
  19819. const id3Sample = _extends({}, pes, {
  19820. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  19821. duration: Number.POSITIVE_INFINITY
  19822. });
  19823. id3Track.samples.push(id3Sample);
  19824. }
  19825. }
  19826. function parsePID(data, offset) {
  19827. return ((data[offset + 1] & 31) << 8) + data[offset + 2];
  19828. }
  19829. function parsePAT(data, offset) {
  19830. return (data[offset + 10] & 31) << 8 | data[offset + 11];
  19831. }
  19832. function parsePMT(data, offset, typeSupported, isSampleAes, observer, logger2) {
  19833. const result = {
  19834. audioPid: -1,
  19835. videoPid: -1,
  19836. id3Pid: -1,
  19837. segmentVideoCodec: "avc",
  19838. segmentAudioCodec: "aac"
  19839. };
  19840. const sectionLength = (data[offset + 1] & 15) << 8 | data[offset + 2];
  19841. const tableEnd = offset + 3 + sectionLength - 4;
  19842. const programInfoLength = (data[offset + 10] & 15) << 8 | data[offset + 11];
  19843. offset += 12 + programInfoLength;
  19844. while (offset < tableEnd) {
  19845. const pid = parsePID(data, offset);
  19846. const esInfoLength = (data[offset + 3] & 15) << 8 | data[offset + 4];
  19847. switch (data[offset]) {
  19848. case 207:
  19849. if (!isSampleAes) {
  19850. logEncryptedSamplesFoundInUnencryptedStream("ADTS AAC", logger2);
  19851. break;
  19852. }
  19853. case 15:
  19854. if (result.audioPid === -1) {
  19855. result.audioPid = pid;
  19856. }
  19857. break;
  19858. case 21:
  19859. if (result.id3Pid === -1) {
  19860. result.id3Pid = pid;
  19861. }
  19862. break;
  19863. case 219:
  19864. if (!isSampleAes) {
  19865. logEncryptedSamplesFoundInUnencryptedStream("H.264", logger2);
  19866. break;
  19867. }
  19868. case 27:
  19869. if (result.videoPid === -1) {
  19870. result.videoPid = pid;
  19871. }
  19872. break;
  19873. case 3:
  19874. case 4:
  19875. if (!typeSupported.mpeg && !typeSupported.mp3) {
  19876. logger2.log("MPEG audio found, not supported in this browser");
  19877. } else if (result.audioPid === -1) {
  19878. result.audioPid = pid;
  19879. result.segmentAudioCodec = "mp3";
  19880. }
  19881. break;
  19882. case 193:
  19883. if (!isSampleAes) {
  19884. logEncryptedSamplesFoundInUnencryptedStream("AC-3", logger2);
  19885. break;
  19886. }
  19887. case 129:
  19888. {
  19889. if (!typeSupported.ac3) {
  19890. logger2.log("AC-3 audio found, not supported in this browser");
  19891. } else if (result.audioPid === -1) {
  19892. result.audioPid = pid;
  19893. result.segmentAudioCodec = "ac3";
  19894. }
  19895. }
  19896. break;
  19897. case 6:
  19898. if (result.audioPid === -1 && esInfoLength > 0) {
  19899. let parsePos = offset + 5;
  19900. let remaining = esInfoLength;
  19901. while (remaining > 2) {
  19902. const descriptorId = data[parsePos];
  19903. switch (descriptorId) {
  19904. case 106:
  19905. {
  19906. if (typeSupported.ac3 !== true) {
  19907. logger2.log("AC-3 audio found, not supported in this browser for now");
  19908. } else {
  19909. result.audioPid = pid;
  19910. result.segmentAudioCodec = "ac3";
  19911. }
  19912. }
  19913. break;
  19914. }
  19915. const descriptorLen = data[parsePos + 1] + 2;
  19916. parsePos += descriptorLen;
  19917. remaining -= descriptorLen;
  19918. }
  19919. }
  19920. break;
  19921. case 194:
  19922. case 135:
  19923. emitParsingError(observer, new Error("Unsupported EC-3 in M2TS found"), void 0, logger2);
  19924. return result;
  19925. case 36:
  19926. {
  19927. if (result.videoPid === -1) {
  19928. result.videoPid = pid;
  19929. result.segmentVideoCodec = "hevc";
  19930. logger2.log("HEVC in M2TS found");
  19931. }
  19932. }
  19933. break;
  19934. }
  19935. offset += esInfoLength + 5;
  19936. }
  19937. return result;
  19938. }
  19939. function emitParsingError(observer, error, levelRetry, logger2) {
  19940. logger2.warn(`parsing error: ${error.message}`);
  19941. observer.emit(Events.ERROR, Events.ERROR, {
  19942. type: ErrorTypes.MEDIA_ERROR,
  19943. details: ErrorDetails.FRAG_PARSING_ERROR,
  19944. fatal: false,
  19945. levelRetry,
  19946. error,
  19947. reason: error.message
  19948. });
  19949. }
  19950. function logEncryptedSamplesFoundInUnencryptedStream(type, logger2) {
  19951. logger2.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);
  19952. }
  19953. function parsePES(stream, logger2) {
  19954. let i2 = 0;
  19955. let frag;
  19956. let pesLen;
  19957. let pesHdrLen;
  19958. let pesPts;
  19959. let pesDts;
  19960. const data = stream.data;
  19961. if (!stream || stream.size === 0) {
  19962. return null;
  19963. }
  19964. while (data[0].length < 19 && data.length > 1) {
  19965. data[0] = appendUint8Array(data[0], data[1]);
  19966. data.splice(1, 1);
  19967. }
  19968. frag = data[0];
  19969. const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  19970. if (pesPrefix === 1) {
  19971. pesLen = (frag[4] << 8) + frag[5];
  19972. if (pesLen && pesLen > stream.size - 6) {
  19973. return null;
  19974. }
  19975. const pesFlags = frag[7];
  19976. if (pesFlags & 192) {
  19977. pesPts = (frag[9] & 14) * 536870912 + // 1 << 29
  19978. (frag[10] & 255) * 4194304 + // 1 << 22
  19979. (frag[11] & 254) * 16384 + // 1 << 14
  19980. (frag[12] & 255) * 128 + // 1 << 7
  19981. (frag[13] & 254) / 2;
  19982. if (pesFlags & 64) {
  19983. pesDts = (frag[14] & 14) * 536870912 + // 1 << 29
  19984. (frag[15] & 255) * 4194304 + // 1 << 22
  19985. (frag[16] & 254) * 16384 + // 1 << 14
  19986. (frag[17] & 255) * 128 + // 1 << 7
  19987. (frag[18] & 254) / 2;
  19988. if (pesPts - pesDts > 60 * 9e4) {
  19989. logger2.warn(`${Math.round((pesPts - pesDts) / 9e4)}s delta between PTS and DTS, align them`);
  19990. pesPts = pesDts;
  19991. }
  19992. } else {
  19993. pesDts = pesPts;
  19994. }
  19995. }
  19996. pesHdrLen = frag[8];
  19997. let payloadStartOffset = pesHdrLen + 9;
  19998. if (stream.size <= payloadStartOffset) {
  19999. return null;
  20000. }
  20001. stream.size -= payloadStartOffset;
  20002. const pesData = new Uint8Array(stream.size);
  20003. for (let j2 = 0, dataLen = data.length; j2 < dataLen; j2++) {
  20004. frag = data[j2];
  20005. let len = frag.byteLength;
  20006. if (payloadStartOffset) {
  20007. if (payloadStartOffset > len) {
  20008. payloadStartOffset -= len;
  20009. continue;
  20010. } else {
  20011. frag = frag.subarray(payloadStartOffset);
  20012. len -= payloadStartOffset;
  20013. payloadStartOffset = 0;
  20014. }
  20015. }
  20016. pesData.set(frag, i2);
  20017. i2 += len;
  20018. }
  20019. if (pesLen) {
  20020. pesLen -= pesHdrLen + 3;
  20021. }
  20022. return {
  20023. data: pesData,
  20024. pts: pesPts,
  20025. dts: pesDts,
  20026. len: pesLen
  20027. };
  20028. }
  20029. return null;
  20030. }
  20031. class AAC {
  20032. static getSilentFrame(codec, channelCount) {
  20033. switch (codec) {
  20034. case "mp4a.40.2":
  20035. if (channelCount === 1) {
  20036. return new Uint8Array([0, 200, 0, 128, 35, 128]);
  20037. } else if (channelCount === 2) {
  20038. return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);
  20039. } else if (channelCount === 3) {
  20040. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);
  20041. } else if (channelCount === 4) {
  20042. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);
  20043. } else if (channelCount === 5) {
  20044. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 56]);
  20045. } else if (channelCount === 6) {
  20046. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 0, 178, 0, 32, 8, 224]);
  20047. }
  20048. break;
  20049. default:
  20050. if (channelCount === 1) {
  20051. return new Uint8Array([1, 64, 34, 128, 163, 78, 230, 128, 186, 8, 0, 0, 0, 28, 6, 241, 193, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);
  20052. } else if (channelCount === 2) {
  20053. return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);
  20054. } else if (channelCount === 3) {
  20055. return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);
  20056. }
  20057. break;
  20058. }
  20059. return void 0;
  20060. }
  20061. }
  20062. const UINT32_MAX = Math.pow(2, 32) - 1;
  20063. class MP4 {
  20064. static init() {
  20065. MP4.types = {
  20066. avc1: [],
  20067. // codingname
  20068. avcC: [],
  20069. hvc1: [],
  20070. hvcC: [],
  20071. btrt: [],
  20072. dinf: [],
  20073. dref: [],
  20074. esds: [],
  20075. ftyp: [],
  20076. hdlr: [],
  20077. mdat: [],
  20078. mdhd: [],
  20079. mdia: [],
  20080. mfhd: [],
  20081. minf: [],
  20082. moof: [],
  20083. moov: [],
  20084. mp4a: [],
  20085. ".mp3": [],
  20086. dac3: [],
  20087. "ac-3": [],
  20088. mvex: [],
  20089. mvhd: [],
  20090. pasp: [],
  20091. sdtp: [],
  20092. stbl: [],
  20093. stco: [],
  20094. stsc: [],
  20095. stsd: [],
  20096. stsz: [],
  20097. stts: [],
  20098. tfdt: [],
  20099. tfhd: [],
  20100. traf: [],
  20101. trak: [],
  20102. trun: [],
  20103. trex: [],
  20104. tkhd: [],
  20105. vmhd: [],
  20106. smhd: []
  20107. };
  20108. let i2;
  20109. for (i2 in MP4.types) {
  20110. if (MP4.types.hasOwnProperty(i2)) {
  20111. MP4.types[i2] = [i2.charCodeAt(0), i2.charCodeAt(1), i2.charCodeAt(2), i2.charCodeAt(3)];
  20112. }
  20113. }
  20114. const videoHdlr = new Uint8Array([
  20115. 0,
  20116. // version 0
  20117. 0,
  20118. 0,
  20119. 0,
  20120. // flags
  20121. 0,
  20122. 0,
  20123. 0,
  20124. 0,
  20125. // pre_defined
  20126. 118,
  20127. 105,
  20128. 100,
  20129. 101,
  20130. // handler_type: 'vide'
  20131. 0,
  20132. 0,
  20133. 0,
  20134. 0,
  20135. // reserved
  20136. 0,
  20137. 0,
  20138. 0,
  20139. 0,
  20140. // reserved
  20141. 0,
  20142. 0,
  20143. 0,
  20144. 0,
  20145. // reserved
  20146. 86,
  20147. 105,
  20148. 100,
  20149. 101,
  20150. 111,
  20151. 72,
  20152. 97,
  20153. 110,
  20154. 100,
  20155. 108,
  20156. 101,
  20157. 114,
  20158. 0
  20159. // name: 'VideoHandler'
  20160. ]);
  20161. const audioHdlr = new Uint8Array([
  20162. 0,
  20163. // version 0
  20164. 0,
  20165. 0,
  20166. 0,
  20167. // flags
  20168. 0,
  20169. 0,
  20170. 0,
  20171. 0,
  20172. // pre_defined
  20173. 115,
  20174. 111,
  20175. 117,
  20176. 110,
  20177. // handler_type: 'soun'
  20178. 0,
  20179. 0,
  20180. 0,
  20181. 0,
  20182. // reserved
  20183. 0,
  20184. 0,
  20185. 0,
  20186. 0,
  20187. // reserved
  20188. 0,
  20189. 0,
  20190. 0,
  20191. 0,
  20192. // reserved
  20193. 83,
  20194. 111,
  20195. 117,
  20196. 110,
  20197. 100,
  20198. 72,
  20199. 97,
  20200. 110,
  20201. 100,
  20202. 108,
  20203. 101,
  20204. 114,
  20205. 0
  20206. // name: 'SoundHandler'
  20207. ]);
  20208. MP4.HDLR_TYPES = {
  20209. video: videoHdlr,
  20210. audio: audioHdlr
  20211. };
  20212. const dref = new Uint8Array([
  20213. 0,
  20214. // version 0
  20215. 0,
  20216. 0,
  20217. 0,
  20218. // flags
  20219. 0,
  20220. 0,
  20221. 0,
  20222. 1,
  20223. // entry_count
  20224. 0,
  20225. 0,
  20226. 0,
  20227. 12,
  20228. // entry_size
  20229. 117,
  20230. 114,
  20231. 108,
  20232. 32,
  20233. // 'url' type
  20234. 0,
  20235. // version 0
  20236. 0,
  20237. 0,
  20238. 1
  20239. // entry_flags
  20240. ]);
  20241. const stco = new Uint8Array([
  20242. 0,
  20243. // version
  20244. 0,
  20245. 0,
  20246. 0,
  20247. // flags
  20248. 0,
  20249. 0,
  20250. 0,
  20251. 0
  20252. // entry_count
  20253. ]);
  20254. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  20255. MP4.STSZ = new Uint8Array([
  20256. 0,
  20257. // version
  20258. 0,
  20259. 0,
  20260. 0,
  20261. // flags
  20262. 0,
  20263. 0,
  20264. 0,
  20265. 0,
  20266. // sample_size
  20267. 0,
  20268. 0,
  20269. 0,
  20270. 0
  20271. // sample_count
  20272. ]);
  20273. MP4.VMHD = new Uint8Array([
  20274. 0,
  20275. // version
  20276. 0,
  20277. 0,
  20278. 1,
  20279. // flags
  20280. 0,
  20281. 0,
  20282. // graphicsmode
  20283. 0,
  20284. 0,
  20285. 0,
  20286. 0,
  20287. 0,
  20288. 0
  20289. // opcolor
  20290. ]);
  20291. MP4.SMHD = new Uint8Array([
  20292. 0,
  20293. // version
  20294. 0,
  20295. 0,
  20296. 0,
  20297. // flags
  20298. 0,
  20299. 0,
  20300. // balance
  20301. 0,
  20302. 0
  20303. // reserved
  20304. ]);
  20305. MP4.STSD = new Uint8Array([
  20306. 0,
  20307. // version 0
  20308. 0,
  20309. 0,
  20310. 0,
  20311. // flags
  20312. 0,
  20313. 0,
  20314. 0,
  20315. 1
  20316. ]);
  20317. const majorBrand = new Uint8Array([105, 115, 111, 109]);
  20318. const avc1Brand = new Uint8Array([97, 118, 99, 49]);
  20319. const minorVersion = new Uint8Array([0, 0, 0, 1]);
  20320. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  20321. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  20322. }
  20323. static box(type, ...payload) {
  20324. let size2 = 8;
  20325. let i2 = payload.length;
  20326. const len = i2;
  20327. while (i2--) {
  20328. size2 += payload[i2].byteLength;
  20329. }
  20330. const result = new Uint8Array(size2);
  20331. result[0] = size2 >> 24 & 255;
  20332. result[1] = size2 >> 16 & 255;
  20333. result[2] = size2 >> 8 & 255;
  20334. result[3] = size2 & 255;
  20335. result.set(type, 4);
  20336. for (i2 = 0, size2 = 8; i2 < len; i2++) {
  20337. result.set(payload[i2], size2);
  20338. size2 += payload[i2].byteLength;
  20339. }
  20340. return result;
  20341. }
  20342. static hdlr(type) {
  20343. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  20344. }
  20345. static mdat(data) {
  20346. return MP4.box(MP4.types.mdat, data);
  20347. }
  20348. static mdhd(timescale, duration) {
  20349. duration *= timescale;
  20350. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  20351. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  20352. return MP4.box(MP4.types.mdhd, new Uint8Array([
  20353. 1,
  20354. // version 1
  20355. 0,
  20356. 0,
  20357. 0,
  20358. // flags
  20359. 0,
  20360. 0,
  20361. 0,
  20362. 0,
  20363. 0,
  20364. 0,
  20365. 0,
  20366. 2,
  20367. // creation_time
  20368. 0,
  20369. 0,
  20370. 0,
  20371. 0,
  20372. 0,
  20373. 0,
  20374. 0,
  20375. 3,
  20376. // modification_time
  20377. timescale >> 24 & 255,
  20378. timescale >> 16 & 255,
  20379. timescale >> 8 & 255,
  20380. timescale & 255,
  20381. // timescale
  20382. upperWordDuration >> 24,
  20383. upperWordDuration >> 16 & 255,
  20384. upperWordDuration >> 8 & 255,
  20385. upperWordDuration & 255,
  20386. lowerWordDuration >> 24,
  20387. lowerWordDuration >> 16 & 255,
  20388. lowerWordDuration >> 8 & 255,
  20389. lowerWordDuration & 255,
  20390. 85,
  20391. 196,
  20392. // 'und' language (undetermined)
  20393. 0,
  20394. 0
  20395. ]));
  20396. }
  20397. static mdia(track2) {
  20398. return MP4.box(MP4.types.mdia, MP4.mdhd(track2.timescale || 0, track2.duration || 0), MP4.hdlr(track2.type), MP4.minf(track2));
  20399. }
  20400. static mfhd(sequenceNumber) {
  20401. return MP4.box(MP4.types.mfhd, new Uint8Array([
  20402. 0,
  20403. 0,
  20404. 0,
  20405. 0,
  20406. // flags
  20407. sequenceNumber >> 24,
  20408. sequenceNumber >> 16 & 255,
  20409. sequenceNumber >> 8 & 255,
  20410. sequenceNumber & 255
  20411. // sequence_number
  20412. ]));
  20413. }
  20414. static minf(track2) {
  20415. if (track2.type === "audio") {
  20416. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track2));
  20417. } else {
  20418. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track2));
  20419. }
  20420. }
  20421. static moof(sn2, baseMediaDecodeTime, track2) {
  20422. return MP4.box(MP4.types.moof, MP4.mfhd(sn2), MP4.traf(track2, baseMediaDecodeTime));
  20423. }
  20424. static moov(tracks) {
  20425. let i2 = tracks.length;
  20426. const boxes = [];
  20427. while (i2--) {
  20428. boxes[i2] = MP4.trak(tracks[i2]);
  20429. }
  20430. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale || 0, tracks[0].duration || 0)].concat(boxes).concat(MP4.mvex(tracks)));
  20431. }
  20432. static mvex(tracks) {
  20433. let i2 = tracks.length;
  20434. const boxes = [];
  20435. while (i2--) {
  20436. boxes[i2] = MP4.trex(tracks[i2]);
  20437. }
  20438. return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);
  20439. }
  20440. static mvhd(timescale, duration) {
  20441. duration *= timescale;
  20442. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  20443. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  20444. const bytes = new Uint8Array([
  20445. 1,
  20446. // version 1
  20447. 0,
  20448. 0,
  20449. 0,
  20450. // flags
  20451. 0,
  20452. 0,
  20453. 0,
  20454. 0,
  20455. 0,
  20456. 0,
  20457. 0,
  20458. 2,
  20459. // creation_time
  20460. 0,
  20461. 0,
  20462. 0,
  20463. 0,
  20464. 0,
  20465. 0,
  20466. 0,
  20467. 3,
  20468. // modification_time
  20469. timescale >> 24 & 255,
  20470. timescale >> 16 & 255,
  20471. timescale >> 8 & 255,
  20472. timescale & 255,
  20473. // timescale
  20474. upperWordDuration >> 24,
  20475. upperWordDuration >> 16 & 255,
  20476. upperWordDuration >> 8 & 255,
  20477. upperWordDuration & 255,
  20478. lowerWordDuration >> 24,
  20479. lowerWordDuration >> 16 & 255,
  20480. lowerWordDuration >> 8 & 255,
  20481. lowerWordDuration & 255,
  20482. 0,
  20483. 1,
  20484. 0,
  20485. 0,
  20486. // 1.0 rate
  20487. 1,
  20488. 0,
  20489. // 1.0 volume
  20490. 0,
  20491. 0,
  20492. // reserved
  20493. 0,
  20494. 0,
  20495. 0,
  20496. 0,
  20497. // reserved
  20498. 0,
  20499. 0,
  20500. 0,
  20501. 0,
  20502. // reserved
  20503. 0,
  20504. 1,
  20505. 0,
  20506. 0,
  20507. 0,
  20508. 0,
  20509. 0,
  20510. 0,
  20511. 0,
  20512. 0,
  20513. 0,
  20514. 0,
  20515. 0,
  20516. 0,
  20517. 0,
  20518. 0,
  20519. 0,
  20520. 1,
  20521. 0,
  20522. 0,
  20523. 0,
  20524. 0,
  20525. 0,
  20526. 0,
  20527. 0,
  20528. 0,
  20529. 0,
  20530. 0,
  20531. 0,
  20532. 0,
  20533. 0,
  20534. 0,
  20535. 64,
  20536. 0,
  20537. 0,
  20538. 0,
  20539. // transformation: unity matrix
  20540. 0,
  20541. 0,
  20542. 0,
  20543. 0,
  20544. 0,
  20545. 0,
  20546. 0,
  20547. 0,
  20548. 0,
  20549. 0,
  20550. 0,
  20551. 0,
  20552. 0,
  20553. 0,
  20554. 0,
  20555. 0,
  20556. 0,
  20557. 0,
  20558. 0,
  20559. 0,
  20560. 0,
  20561. 0,
  20562. 0,
  20563. 0,
  20564. // pre_defined
  20565. 255,
  20566. 255,
  20567. 255,
  20568. 255
  20569. // next_track_ID
  20570. ]);
  20571. return MP4.box(MP4.types.mvhd, bytes);
  20572. }
  20573. static sdtp(track2) {
  20574. const samples = track2.samples || [];
  20575. const bytes = new Uint8Array(4 + samples.length);
  20576. let i2;
  20577. let flags;
  20578. for (i2 = 0; i2 < samples.length; i2++) {
  20579. flags = samples[i2].flags;
  20580. bytes[i2 + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  20581. }
  20582. return MP4.box(MP4.types.sdtp, bytes);
  20583. }
  20584. static stbl(track2) {
  20585. return MP4.box(MP4.types.stbl, MP4.stsd(track2), 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));
  20586. }
  20587. static avc1(track2) {
  20588. let sps = [];
  20589. let pps = [];
  20590. let i2;
  20591. let data;
  20592. let len;
  20593. for (i2 = 0; i2 < track2.sps.length; i2++) {
  20594. data = track2.sps[i2];
  20595. len = data.byteLength;
  20596. sps.push(len >>> 8 & 255);
  20597. sps.push(len & 255);
  20598. sps = sps.concat(Array.prototype.slice.call(data));
  20599. }
  20600. for (i2 = 0; i2 < track2.pps.length; i2++) {
  20601. data = track2.pps[i2];
  20602. len = data.byteLength;
  20603. pps.push(len >>> 8 & 255);
  20604. pps.push(len & 255);
  20605. pps = pps.concat(Array.prototype.slice.call(data));
  20606. }
  20607. const avcc = MP4.box(MP4.types.avcC, new Uint8Array([
  20608. 1,
  20609. // version
  20610. sps[3],
  20611. // profile
  20612. sps[4],
  20613. // profile compat
  20614. sps[5],
  20615. // level
  20616. 252 | 3,
  20617. // lengthSizeMinusOne, hard-coded to 4 bytes
  20618. 224 | track2.sps.length
  20619. // 3bit reserved (111) + numOfSequenceParameterSets
  20620. ].concat(sps).concat([
  20621. track2.pps.length
  20622. // numOfPictureParameterSets
  20623. ]).concat(pps)));
  20624. const width = track2.width;
  20625. const height = track2.height;
  20626. const hSpacing = track2.pixelRatio[0];
  20627. const vSpacing = track2.pixelRatio[1];
  20628. return MP4.box(
  20629. MP4.types.avc1,
  20630. new Uint8Array([
  20631. 0,
  20632. 0,
  20633. 0,
  20634. // reserved
  20635. 0,
  20636. 0,
  20637. 0,
  20638. // reserved
  20639. 0,
  20640. 1,
  20641. // data_reference_index
  20642. 0,
  20643. 0,
  20644. // pre_defined
  20645. 0,
  20646. 0,
  20647. // reserved
  20648. 0,
  20649. 0,
  20650. 0,
  20651. 0,
  20652. 0,
  20653. 0,
  20654. 0,
  20655. 0,
  20656. 0,
  20657. 0,
  20658. 0,
  20659. 0,
  20660. // pre_defined
  20661. width >> 8 & 255,
  20662. width & 255,
  20663. // width
  20664. height >> 8 & 255,
  20665. height & 255,
  20666. // height
  20667. 0,
  20668. 72,
  20669. 0,
  20670. 0,
  20671. // horizresolution
  20672. 0,
  20673. 72,
  20674. 0,
  20675. 0,
  20676. // vertresolution
  20677. 0,
  20678. 0,
  20679. 0,
  20680. 0,
  20681. // reserved
  20682. 0,
  20683. 1,
  20684. // frame_count
  20685. 18,
  20686. 100,
  20687. 97,
  20688. 105,
  20689. 108,
  20690. // dailymotion/hls.js
  20691. 121,
  20692. 109,
  20693. 111,
  20694. 116,
  20695. 105,
  20696. 111,
  20697. 110,
  20698. 47,
  20699. 104,
  20700. 108,
  20701. 115,
  20702. 46,
  20703. 106,
  20704. 115,
  20705. 0,
  20706. 0,
  20707. 0,
  20708. 0,
  20709. 0,
  20710. 0,
  20711. 0,
  20712. 0,
  20713. 0,
  20714. 0,
  20715. 0,
  20716. 0,
  20717. 0,
  20718. // compressorname
  20719. 0,
  20720. 24,
  20721. // depth = 24
  20722. 17,
  20723. 17
  20724. ]),
  20725. // pre_defined = -1
  20726. avcc,
  20727. MP4.box(MP4.types.btrt, new Uint8Array([
  20728. 0,
  20729. 28,
  20730. 156,
  20731. 128,
  20732. // bufferSizeDB
  20733. 0,
  20734. 45,
  20735. 198,
  20736. 192,
  20737. // maxBitrate
  20738. 0,
  20739. 45,
  20740. 198,
  20741. 192
  20742. ])),
  20743. // avgBitrate
  20744. MP4.box(MP4.types.pasp, new Uint8Array([
  20745. hSpacing >> 24,
  20746. // hSpacing
  20747. hSpacing >> 16 & 255,
  20748. hSpacing >> 8 & 255,
  20749. hSpacing & 255,
  20750. vSpacing >> 24,
  20751. // vSpacing
  20752. vSpacing >> 16 & 255,
  20753. vSpacing >> 8 & 255,
  20754. vSpacing & 255
  20755. ]))
  20756. );
  20757. }
  20758. static esds(track2) {
  20759. const config = track2.config;
  20760. return new Uint8Array([
  20761. 0,
  20762. // version 0
  20763. 0,
  20764. 0,
  20765. 0,
  20766. // flags
  20767. 3,
  20768. // descriptor_type
  20769. 25,
  20770. // length
  20771. 0,
  20772. 1,
  20773. // es_id
  20774. 0,
  20775. // stream_priority
  20776. 4,
  20777. // descriptor_type
  20778. 17,
  20779. // length
  20780. 64,
  20781. // codec : mpeg4_audio
  20782. 21,
  20783. // stream_type
  20784. 0,
  20785. 0,
  20786. 0,
  20787. // buffer_size
  20788. 0,
  20789. 0,
  20790. 0,
  20791. 0,
  20792. // maxBitrate
  20793. 0,
  20794. 0,
  20795. 0,
  20796. 0,
  20797. // avgBitrate
  20798. 5,
  20799. // descriptor_type
  20800. 2,
  20801. // length
  20802. ...config,
  20803. 6,
  20804. 1,
  20805. 2
  20806. // GASpecificConfig)); // length + audio config descriptor
  20807. ]);
  20808. }
  20809. static audioStsd(track2) {
  20810. const samplerate = track2.samplerate || 0;
  20811. return new Uint8Array([
  20812. 0,
  20813. 0,
  20814. 0,
  20815. // reserved
  20816. 0,
  20817. 0,
  20818. 0,
  20819. // reserved
  20820. 0,
  20821. 1,
  20822. // data_reference_index
  20823. 0,
  20824. 0,
  20825. 0,
  20826. 0,
  20827. 0,
  20828. 0,
  20829. 0,
  20830. 0,
  20831. // reserved
  20832. 0,
  20833. track2.channelCount || 0,
  20834. // channelcount
  20835. 0,
  20836. 16,
  20837. // sampleSize:16bits
  20838. 0,
  20839. 0,
  20840. 0,
  20841. 0,
  20842. // reserved2
  20843. samplerate >> 8 & 255,
  20844. samplerate & 255,
  20845. //
  20846. 0,
  20847. 0
  20848. ]);
  20849. }
  20850. static mp4a(track2) {
  20851. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track2), MP4.box(MP4.types.esds, MP4.esds(track2)));
  20852. }
  20853. static mp3(track2) {
  20854. return MP4.box(MP4.types[".mp3"], MP4.audioStsd(track2));
  20855. }
  20856. static ac3(track2) {
  20857. return MP4.box(MP4.types["ac-3"], MP4.audioStsd(track2), MP4.box(MP4.types.dac3, track2.config));
  20858. }
  20859. static stsd(track2) {
  20860. const {
  20861. segmentCodec
  20862. } = track2;
  20863. if (track2.type === "audio") {
  20864. if (segmentCodec === "aac") {
  20865. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track2));
  20866. }
  20867. if (segmentCodec === "ac3" && track2.config) {
  20868. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track2));
  20869. }
  20870. if (segmentCodec === "mp3" && track2.codec === "mp3") {
  20871. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track2));
  20872. }
  20873. } else {
  20874. if (track2.pps && track2.sps) {
  20875. if (segmentCodec === "avc") {
  20876. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track2));
  20877. }
  20878. if (segmentCodec === "hevc" && track2.vps) {
  20879. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.hvc1(track2));
  20880. }
  20881. } else {
  20882. throw new Error(`video track missing pps or sps`);
  20883. }
  20884. }
  20885. throw new Error(`unsupported ${track2.type} segment codec (${segmentCodec}/${track2.codec})`);
  20886. }
  20887. static tkhd(track2) {
  20888. const id = track2.id;
  20889. const duration = (track2.duration || 0) * (track2.timescale || 0);
  20890. const width = track2.width || 0;
  20891. const height = track2.height || 0;
  20892. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  20893. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  20894. return MP4.box(MP4.types.tkhd, new Uint8Array([
  20895. 1,
  20896. // version 1
  20897. 0,
  20898. 0,
  20899. 7,
  20900. // flags
  20901. 0,
  20902. 0,
  20903. 0,
  20904. 0,
  20905. 0,
  20906. 0,
  20907. 0,
  20908. 2,
  20909. // creation_time
  20910. 0,
  20911. 0,
  20912. 0,
  20913. 0,
  20914. 0,
  20915. 0,
  20916. 0,
  20917. 3,
  20918. // modification_time
  20919. id >> 24 & 255,
  20920. id >> 16 & 255,
  20921. id >> 8 & 255,
  20922. id & 255,
  20923. // track_ID
  20924. 0,
  20925. 0,
  20926. 0,
  20927. 0,
  20928. // reserved
  20929. upperWordDuration >> 24,
  20930. upperWordDuration >> 16 & 255,
  20931. upperWordDuration >> 8 & 255,
  20932. upperWordDuration & 255,
  20933. lowerWordDuration >> 24,
  20934. lowerWordDuration >> 16 & 255,
  20935. lowerWordDuration >> 8 & 255,
  20936. lowerWordDuration & 255,
  20937. 0,
  20938. 0,
  20939. 0,
  20940. 0,
  20941. 0,
  20942. 0,
  20943. 0,
  20944. 0,
  20945. // reserved
  20946. 0,
  20947. 0,
  20948. // layer
  20949. 0,
  20950. 0,
  20951. // alternate_group
  20952. 0,
  20953. 0,
  20954. // non-audio track volume
  20955. 0,
  20956. 0,
  20957. // reserved
  20958. 0,
  20959. 1,
  20960. 0,
  20961. 0,
  20962. 0,
  20963. 0,
  20964. 0,
  20965. 0,
  20966. 0,
  20967. 0,
  20968. 0,
  20969. 0,
  20970. 0,
  20971. 0,
  20972. 0,
  20973. 0,
  20974. 0,
  20975. 1,
  20976. 0,
  20977. 0,
  20978. 0,
  20979. 0,
  20980. 0,
  20981. 0,
  20982. 0,
  20983. 0,
  20984. 0,
  20985. 0,
  20986. 0,
  20987. 0,
  20988. 0,
  20989. 0,
  20990. 64,
  20991. 0,
  20992. 0,
  20993. 0,
  20994. // transformation: unity matrix
  20995. width >> 8 & 255,
  20996. width & 255,
  20997. 0,
  20998. 0,
  20999. // width
  21000. height >> 8 & 255,
  21001. height & 255,
  21002. 0,
  21003. 0
  21004. // height
  21005. ]));
  21006. }
  21007. static traf(track2, baseMediaDecodeTime) {
  21008. const sampleDependencyTable = MP4.sdtp(track2);
  21009. const id = track2.id;
  21010. const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  21011. const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  21012. return MP4.box(
  21013. MP4.types.traf,
  21014. MP4.box(MP4.types.tfhd, new Uint8Array([
  21015. 0,
  21016. // version 0
  21017. 0,
  21018. 0,
  21019. 0,
  21020. // flags
  21021. id >> 24,
  21022. id >> 16 & 255,
  21023. id >> 8 & 255,
  21024. id & 255
  21025. // track_ID
  21026. ])),
  21027. MP4.box(MP4.types.tfdt, new Uint8Array([
  21028. 1,
  21029. // version 1
  21030. 0,
  21031. 0,
  21032. 0,
  21033. // flags
  21034. upperWordBaseMediaDecodeTime >> 24,
  21035. upperWordBaseMediaDecodeTime >> 16 & 255,
  21036. upperWordBaseMediaDecodeTime >> 8 & 255,
  21037. upperWordBaseMediaDecodeTime & 255,
  21038. lowerWordBaseMediaDecodeTime >> 24,
  21039. lowerWordBaseMediaDecodeTime >> 16 & 255,
  21040. lowerWordBaseMediaDecodeTime >> 8 & 255,
  21041. lowerWordBaseMediaDecodeTime & 255
  21042. ])),
  21043. MP4.trun(track2, sampleDependencyTable.length + 16 + // tfhd
  21044. 20 + // tfdt
  21045. 8 + // traf header
  21046. 16 + // mfhd
  21047. 8 + // moof header
  21048. 8),
  21049. // mdat header
  21050. sampleDependencyTable
  21051. );
  21052. }
  21053. /**
  21054. * Generate a track box.
  21055. * @param track a track definition
  21056. */
  21057. static trak(track2) {
  21058. track2.duration = track2.duration || 4294967295;
  21059. return MP4.box(MP4.types.trak, MP4.tkhd(track2), MP4.mdia(track2));
  21060. }
  21061. static trex(track2) {
  21062. const id = track2.id;
  21063. return MP4.box(MP4.types.trex, new Uint8Array([
  21064. 0,
  21065. // version 0
  21066. 0,
  21067. 0,
  21068. 0,
  21069. // flags
  21070. id >> 24,
  21071. id >> 16 & 255,
  21072. id >> 8 & 255,
  21073. id & 255,
  21074. // track_ID
  21075. 0,
  21076. 0,
  21077. 0,
  21078. 1,
  21079. // default_sample_description_index
  21080. 0,
  21081. 0,
  21082. 0,
  21083. 0,
  21084. // default_sample_duration
  21085. 0,
  21086. 0,
  21087. 0,
  21088. 0,
  21089. // default_sample_size
  21090. 0,
  21091. 1,
  21092. 0,
  21093. 1
  21094. // default_sample_flags
  21095. ]));
  21096. }
  21097. static trun(track2, offset) {
  21098. const samples = track2.samples || [];
  21099. const len = samples.length;
  21100. const arraylen = 12 + 16 * len;
  21101. const array = new Uint8Array(arraylen);
  21102. let i2;
  21103. let sample;
  21104. let duration;
  21105. let size2;
  21106. let flags;
  21107. let cts;
  21108. offset += 8 + arraylen;
  21109. array.set([
  21110. track2.type === "video" ? 1 : 0,
  21111. // version 1 for video with signed-int sample_composition_time_offset
  21112. 0,
  21113. 15,
  21114. 1,
  21115. // flags
  21116. len >>> 24 & 255,
  21117. len >>> 16 & 255,
  21118. len >>> 8 & 255,
  21119. len & 255,
  21120. // sample_count
  21121. offset >>> 24 & 255,
  21122. offset >>> 16 & 255,
  21123. offset >>> 8 & 255,
  21124. offset & 255
  21125. // data_offset
  21126. ], 0);
  21127. for (i2 = 0; i2 < len; i2++) {
  21128. sample = samples[i2];
  21129. duration = sample.duration;
  21130. size2 = sample.size;
  21131. flags = sample.flags;
  21132. cts = sample.cts;
  21133. array.set([
  21134. duration >>> 24 & 255,
  21135. duration >>> 16 & 255,
  21136. duration >>> 8 & 255,
  21137. duration & 255,
  21138. // sample_duration
  21139. size2 >>> 24 & 255,
  21140. size2 >>> 16 & 255,
  21141. size2 >>> 8 & 255,
  21142. size2 & 255,
  21143. // sample_size
  21144. flags.isLeading << 2 | flags.dependsOn,
  21145. flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync,
  21146. flags.degradPrio & 240 << 8,
  21147. flags.degradPrio & 15,
  21148. // sample_flags
  21149. cts >>> 24 & 255,
  21150. cts >>> 16 & 255,
  21151. cts >>> 8 & 255,
  21152. cts & 255
  21153. // sample_composition_time_offset
  21154. ], 12 + 16 * i2);
  21155. }
  21156. return MP4.box(MP4.types.trun, array);
  21157. }
  21158. static initSegment(tracks) {
  21159. if (!MP4.types) {
  21160. MP4.init();
  21161. }
  21162. const movie = MP4.moov(tracks);
  21163. const result = appendUint8Array(MP4.FTYP, movie);
  21164. return result;
  21165. }
  21166. static hvc1(track2) {
  21167. const ps2 = track2.params;
  21168. const units = [track2.vps, track2.sps, track2.pps];
  21169. const NALuLengthSize = 4;
  21170. const config = new Uint8Array([1, ps2.general_profile_space << 6 | (ps2.general_tier_flag ? 32 : 0) | ps2.general_profile_idc, ps2.general_profile_compatibility_flags[0], ps2.general_profile_compatibility_flags[1], ps2.general_profile_compatibility_flags[2], ps2.general_profile_compatibility_flags[3], ps2.general_constraint_indicator_flags[0], ps2.general_constraint_indicator_flags[1], ps2.general_constraint_indicator_flags[2], ps2.general_constraint_indicator_flags[3], ps2.general_constraint_indicator_flags[4], ps2.general_constraint_indicator_flags[5], ps2.general_level_idc, 240 | ps2.min_spatial_segmentation_idc >> 8, 255 & ps2.min_spatial_segmentation_idc, 252 | ps2.parallelismType, 252 | ps2.chroma_format_idc, 248 | ps2.bit_depth_luma_minus8, 248 | ps2.bit_depth_chroma_minus8, 0, parseInt(ps2.frame_rate.fps), NALuLengthSize - 1 | ps2.temporal_id_nested << 2 | ps2.num_temporal_layers << 3 | (ps2.frame_rate.fixed ? 64 : 0), units.length]);
  21171. let length = config.length;
  21172. for (let i2 = 0; i2 < units.length; i2 += 1) {
  21173. length += 3;
  21174. for (let j2 = 0; j2 < units[i2].length; j2 += 1) {
  21175. length += 2 + units[i2][j2].length;
  21176. }
  21177. }
  21178. const hvcC = new Uint8Array(length);
  21179. hvcC.set(config, 0);
  21180. length = config.length;
  21181. const iMax = units.length - 1;
  21182. for (let i2 = 0; i2 < units.length; i2 += 1) {
  21183. hvcC.set(new Uint8Array([32 + i2 | (i2 === iMax ? 128 : 0), 0, units[i2].length]), length);
  21184. length += 3;
  21185. for (let j2 = 0; j2 < units[i2].length; j2 += 1) {
  21186. hvcC.set(new Uint8Array([units[i2][j2].length >> 8, units[i2][j2].length & 255]), length);
  21187. length += 2;
  21188. hvcC.set(units[i2][j2], length);
  21189. length += units[i2][j2].length;
  21190. }
  21191. }
  21192. const hvcc = MP4.box(MP4.types.hvcC, hvcC);
  21193. const width = track2.width;
  21194. const height = track2.height;
  21195. const hSpacing = track2.pixelRatio[0];
  21196. const vSpacing = track2.pixelRatio[1];
  21197. return MP4.box(
  21198. MP4.types.hvc1,
  21199. new Uint8Array([
  21200. 0,
  21201. 0,
  21202. 0,
  21203. // reserved
  21204. 0,
  21205. 0,
  21206. 0,
  21207. // reserved
  21208. 0,
  21209. 1,
  21210. // data_reference_index
  21211. 0,
  21212. 0,
  21213. // pre_defined
  21214. 0,
  21215. 0,
  21216. // reserved
  21217. 0,
  21218. 0,
  21219. 0,
  21220. 0,
  21221. 0,
  21222. 0,
  21223. 0,
  21224. 0,
  21225. 0,
  21226. 0,
  21227. 0,
  21228. 0,
  21229. // pre_defined
  21230. width >> 8 & 255,
  21231. width & 255,
  21232. // width
  21233. height >> 8 & 255,
  21234. height & 255,
  21235. // height
  21236. 0,
  21237. 72,
  21238. 0,
  21239. 0,
  21240. // horizresolution
  21241. 0,
  21242. 72,
  21243. 0,
  21244. 0,
  21245. // vertresolution
  21246. 0,
  21247. 0,
  21248. 0,
  21249. 0,
  21250. // reserved
  21251. 0,
  21252. 1,
  21253. // frame_count
  21254. 18,
  21255. 100,
  21256. 97,
  21257. 105,
  21258. 108,
  21259. // dailymotion/hls.js
  21260. 121,
  21261. 109,
  21262. 111,
  21263. 116,
  21264. 105,
  21265. 111,
  21266. 110,
  21267. 47,
  21268. 104,
  21269. 108,
  21270. 115,
  21271. 46,
  21272. 106,
  21273. 115,
  21274. 0,
  21275. 0,
  21276. 0,
  21277. 0,
  21278. 0,
  21279. 0,
  21280. 0,
  21281. 0,
  21282. 0,
  21283. 0,
  21284. 0,
  21285. 0,
  21286. 0,
  21287. // compressorname
  21288. 0,
  21289. 24,
  21290. // depth = 24
  21291. 17,
  21292. 17
  21293. ]),
  21294. // pre_defined = -1
  21295. hvcc,
  21296. MP4.box(MP4.types.btrt, new Uint8Array([
  21297. 0,
  21298. 28,
  21299. 156,
  21300. 128,
  21301. // bufferSizeDB
  21302. 0,
  21303. 45,
  21304. 198,
  21305. 192,
  21306. // maxBitrate
  21307. 0,
  21308. 45,
  21309. 198,
  21310. 192
  21311. ])),
  21312. // avgBitrate
  21313. MP4.box(MP4.types.pasp, new Uint8Array([
  21314. hSpacing >> 24,
  21315. // hSpacing
  21316. hSpacing >> 16 & 255,
  21317. hSpacing >> 8 & 255,
  21318. hSpacing & 255,
  21319. vSpacing >> 24,
  21320. // vSpacing
  21321. vSpacing >> 16 & 255,
  21322. vSpacing >> 8 & 255,
  21323. vSpacing & 255
  21324. ]))
  21325. );
  21326. }
  21327. }
  21328. MP4.types = void 0;
  21329. MP4.HDLR_TYPES = void 0;
  21330. MP4.STTS = void 0;
  21331. MP4.STSC = void 0;
  21332. MP4.STCO = void 0;
  21333. MP4.STSZ = void 0;
  21334. MP4.VMHD = void 0;
  21335. MP4.SMHD = void 0;
  21336. MP4.STSD = void 0;
  21337. MP4.FTYP = void 0;
  21338. MP4.DINF = void 0;
  21339. const MPEG_TS_CLOCK_FREQ_HZ = 9e4;
  21340. function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) {
  21341. const result = baseTime * destScale * srcBase;
  21342. return round ? Math.round(result) : result;
  21343. }
  21344. function toTimescaleFromScale(baseTime, destScale, srcScale = 1, round = false) {
  21345. return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);
  21346. }
  21347. function toMsFromMpegTsClock(baseTime, round = false) {
  21348. return toTimescaleFromBase(baseTime, 1e3, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  21349. }
  21350. function toMpegTsClockFromTimescale(baseTime, srcScale = 1) {
  21351. return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
  21352. }
  21353. const MAX_SILENT_FRAME_DURATION = 10 * 1e3;
  21354. const AAC_SAMPLES_PER_FRAME = 1024;
  21355. const MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  21356. const AC3_SAMPLES_PER_FRAME = 1536;
  21357. let chromeVersion = null;
  21358. let safariWebkitVersion = null;
  21359. function createMp4Sample(isKeyframe, duration, size2, cts) {
  21360. return {
  21361. duration,
  21362. size: size2,
  21363. cts,
  21364. flags: {
  21365. isLeading: 0,
  21366. isDependedOn: 0,
  21367. hasRedundancy: 0,
  21368. degradPrio: 0,
  21369. dependsOn: isKeyframe ? 2 : 1,
  21370. isNonSync: isKeyframe ? 0 : 1
  21371. }
  21372. };
  21373. }
  21374. class MP4Remuxer extends Logger {
  21375. constructor(observer, config, typeSupported, logger2) {
  21376. super("mp4-remuxer", logger2);
  21377. this.observer = void 0;
  21378. this.config = void 0;
  21379. this.typeSupported = void 0;
  21380. this.ISGenerated = false;
  21381. this._initPTS = null;
  21382. this._initDTS = null;
  21383. this.nextVideoTs = null;
  21384. this.nextAudioTs = null;
  21385. this.videoSampleDuration = null;
  21386. this.isAudioContiguous = false;
  21387. this.isVideoContiguous = false;
  21388. this.videoTrackConfig = void 0;
  21389. this.observer = observer;
  21390. this.config = config;
  21391. this.typeSupported = typeSupported;
  21392. this.ISGenerated = false;
  21393. if (chromeVersion === null) {
  21394. const userAgent = navigator.userAgent || "";
  21395. const result = userAgent.match(/Chrome\/(\d+)/i);
  21396. chromeVersion = result ? parseInt(result[1]) : 0;
  21397. }
  21398. if (safariWebkitVersion === null) {
  21399. const result = navigator.userAgent.match(/Safari\/(\d+)/i);
  21400. safariWebkitVersion = result ? parseInt(result[1]) : 0;
  21401. }
  21402. }
  21403. destroy() {
  21404. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  21405. }
  21406. resetTimeStamp(defaultTimeStamp) {
  21407. this.log("initPTS & initDTS reset");
  21408. this._initPTS = this._initDTS = defaultTimeStamp;
  21409. }
  21410. resetNextTimestamp() {
  21411. this.log("reset next timestamp");
  21412. this.isVideoContiguous = false;
  21413. this.isAudioContiguous = false;
  21414. }
  21415. resetInitSegment() {
  21416. this.log("ISGenerated flag reset");
  21417. this.ISGenerated = false;
  21418. this.videoTrackConfig = void 0;
  21419. }
  21420. getVideoStartPts(videoSamples) {
  21421. let rolloverDetected = false;
  21422. const firstPts = videoSamples[0].pts;
  21423. const startPTS = videoSamples.reduce((minPTS, sample) => {
  21424. let pts = sample.pts;
  21425. let delta = pts - minPTS;
  21426. if (delta < -4294967296) {
  21427. rolloverDetected = true;
  21428. pts = normalizePts(pts, firstPts);
  21429. delta = pts - minPTS;
  21430. }
  21431. if (delta > 0) {
  21432. return minPTS;
  21433. }
  21434. return pts;
  21435. }, firstPts);
  21436. if (rolloverDetected) {
  21437. this.debug("PTS rollover detected");
  21438. }
  21439. return startPTS;
  21440. }
  21441. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  21442. let video;
  21443. let audio;
  21444. let initSegment;
  21445. let text;
  21446. let id3;
  21447. let independent;
  21448. let audioTimeOffset = timeOffset;
  21449. let videoTimeOffset = timeOffset;
  21450. const hasAudio = audioTrack.pid > -1;
  21451. const hasVideo = videoTrack.pid > -1;
  21452. const length = videoTrack.samples.length;
  21453. const enoughAudioSamples = audioTrack.samples.length > 0;
  21454. const enoughVideoSamples = flush && length > 0 || length > 1;
  21455. const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  21456. if (canRemuxAvc) {
  21457. if (this.ISGenerated) {
  21458. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  21459. const config = this.videoTrackConfig;
  21460. if (config && (videoTrack.width !== config.width || videoTrack.height !== config.height || ((_videoTrack$pixelRati = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati[0]) !== ((_config$pixelRatio = config.pixelRatio) == null ? void 0 : _config$pixelRatio[0]) || ((_videoTrack$pixelRati2 = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati2[1]) !== ((_config$pixelRatio2 = config.pixelRatio) == null ? void 0 : _config$pixelRatio2[1])) || !config && enoughVideoSamples || this.nextAudioTs === null && enoughAudioSamples) {
  21461. this.resetInitSegment();
  21462. }
  21463. }
  21464. if (!this.ISGenerated) {
  21465. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  21466. }
  21467. const isVideoContiguous = this.isVideoContiguous;
  21468. let firstKeyFrameIndex = -1;
  21469. let firstKeyFramePTS;
  21470. if (enoughVideoSamples) {
  21471. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  21472. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  21473. independent = true;
  21474. if (firstKeyFrameIndex > 0) {
  21475. this.warn(`Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);
  21476. const startPTS = this.getVideoStartPts(videoTrack.samples);
  21477. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  21478. videoTrack.dropped += firstKeyFrameIndex;
  21479. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  21480. firstKeyFramePTS = videoTimeOffset;
  21481. } else if (firstKeyFrameIndex === -1) {
  21482. this.warn(`No keyframe found out of ${length} video samples`);
  21483. independent = false;
  21484. }
  21485. }
  21486. }
  21487. if (this.ISGenerated) {
  21488. if (enoughAudioSamples && enoughVideoSamples) {
  21489. const startPTS = this.getVideoStartPts(videoTrack.samples);
  21490. const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;
  21491. const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  21492. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  21493. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  21494. }
  21495. if (enoughAudioSamples) {
  21496. if (!audioTrack.samplerate) {
  21497. this.warn("regenerate InitSegment as audio detected");
  21498. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  21499. }
  21500. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : void 0);
  21501. if (enoughVideoSamples) {
  21502. const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  21503. if (!videoTrack.inputTimeScale) {
  21504. this.warn("regenerate InitSegment as video detected");
  21505. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  21506. }
  21507. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  21508. }
  21509. } else if (enoughVideoSamples) {
  21510. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  21511. }
  21512. if (video) {
  21513. video.firstKeyFrame = firstKeyFrameIndex;
  21514. video.independent = firstKeyFrameIndex !== -1;
  21515. video.firstKeyFramePTS = firstKeyFramePTS;
  21516. }
  21517. }
  21518. }
  21519. if (this.ISGenerated && this._initPTS && this._initDTS) {
  21520. if (id3Track.samples.length) {
  21521. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  21522. }
  21523. if (textTrack.samples.length) {
  21524. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  21525. }
  21526. }
  21527. return {
  21528. audio,
  21529. video,
  21530. initSegment,
  21531. independent,
  21532. text,
  21533. id3
  21534. };
  21535. }
  21536. generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  21537. const audioSamples = audioTrack.samples;
  21538. const videoSamples = videoTrack.samples;
  21539. const typeSupported = this.typeSupported;
  21540. const tracks = {};
  21541. const _initPTS = this._initPTS;
  21542. let computePTSDTS = !_initPTS || accurateTimeOffset;
  21543. let container = "audio/mp4";
  21544. let initPTS;
  21545. let initDTS;
  21546. let timescale;
  21547. let trackId;
  21548. if (computePTSDTS) {
  21549. initPTS = initDTS = Infinity;
  21550. }
  21551. if (audioTrack.config && audioSamples.length) {
  21552. audioTrack.timescale = audioTrack.samplerate;
  21553. switch (audioTrack.segmentCodec) {
  21554. case "mp3":
  21555. if (typeSupported.mpeg) {
  21556. container = "audio/mpeg";
  21557. audioTrack.codec = "";
  21558. } else if (typeSupported.mp3) {
  21559. audioTrack.codec = "mp3";
  21560. }
  21561. break;
  21562. case "ac3":
  21563. audioTrack.codec = "ac-3";
  21564. break;
  21565. }
  21566. tracks.audio = {
  21567. id: "audio",
  21568. container,
  21569. codec: audioTrack.codec,
  21570. initSegment: audioTrack.segmentCodec === "mp3" && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  21571. metadata: {
  21572. channelCount: audioTrack.channelCount
  21573. }
  21574. };
  21575. if (computePTSDTS) {
  21576. trackId = audioTrack.id;
  21577. timescale = audioTrack.inputTimeScale;
  21578. if (!_initPTS || timescale !== _initPTS.timescale) {
  21579. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  21580. } else {
  21581. computePTSDTS = false;
  21582. }
  21583. }
  21584. }
  21585. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  21586. videoTrack.timescale = videoTrack.inputTimeScale;
  21587. tracks.video = {
  21588. id: "main",
  21589. container: "video/mp4",
  21590. codec: videoTrack.codec,
  21591. initSegment: MP4.initSegment([videoTrack]),
  21592. metadata: {
  21593. width: videoTrack.width,
  21594. height: videoTrack.height
  21595. }
  21596. };
  21597. if (computePTSDTS) {
  21598. trackId = videoTrack.id;
  21599. timescale = videoTrack.inputTimeScale;
  21600. if (!_initPTS || timescale !== _initPTS.timescale) {
  21601. const startPTS = this.getVideoStartPts(videoSamples);
  21602. const startOffset = Math.round(timescale * timeOffset);
  21603. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  21604. initPTS = Math.min(initPTS, startPTS - startOffset);
  21605. } else {
  21606. computePTSDTS = false;
  21607. }
  21608. }
  21609. this.videoTrackConfig = {
  21610. width: videoTrack.width,
  21611. height: videoTrack.height,
  21612. pixelRatio: videoTrack.pixelRatio
  21613. };
  21614. }
  21615. if (Object.keys(tracks).length) {
  21616. this.ISGenerated = true;
  21617. if (computePTSDTS) {
  21618. this._initPTS = {
  21619. baseTime: initPTS,
  21620. timescale
  21621. };
  21622. this._initDTS = {
  21623. baseTime: initDTS,
  21624. timescale
  21625. };
  21626. } else {
  21627. initPTS = timescale = void 0;
  21628. }
  21629. return {
  21630. tracks,
  21631. initPTS,
  21632. timescale,
  21633. trackId
  21634. };
  21635. }
  21636. }
  21637. remuxVideo(track2, timeOffset, contiguous, audioTrackLength) {
  21638. const timeScale = track2.inputTimeScale;
  21639. const inputSamples = track2.samples;
  21640. const outputSamples = [];
  21641. const nbSamples = inputSamples.length;
  21642. const initPTS = this._initPTS;
  21643. const initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  21644. let nextVideoTs = this.nextVideoTs;
  21645. let offset = 8;
  21646. let mp4SampleDuration = this.videoSampleDuration;
  21647. let firstDTS;
  21648. let lastDTS;
  21649. let minPTS = Number.POSITIVE_INFINITY;
  21650. let maxPTS = Number.NEGATIVE_INFINITY;
  21651. let sortSamples = false;
  21652. if (!contiguous || nextVideoTs === null) {
  21653. const pts = initTime + timeOffset * timeScale;
  21654. const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  21655. if (chromeVersion && nextVideoTs !== null && Math.abs(pts - cts - (nextVideoTs + initTime)) < 15e3) {
  21656. contiguous = true;
  21657. } else {
  21658. nextVideoTs = pts - cts - initTime;
  21659. }
  21660. }
  21661. const nextVideoPts = nextVideoTs + initTime;
  21662. for (let i2 = 0; i2 < nbSamples; i2++) {
  21663. const sample = inputSamples[i2];
  21664. sample.pts = normalizePts(sample.pts, nextVideoPts);
  21665. sample.dts = normalizePts(sample.dts, nextVideoPts);
  21666. if (sample.dts < inputSamples[i2 > 0 ? i2 - 1 : i2].dts) {
  21667. sortSamples = true;
  21668. }
  21669. }
  21670. if (sortSamples) {
  21671. inputSamples.sort(function(a2, b2) {
  21672. const deltadts = a2.dts - b2.dts;
  21673. const deltapts = a2.pts - b2.pts;
  21674. return deltadts || deltapts;
  21675. });
  21676. }
  21677. firstDTS = inputSamples[0].dts;
  21678. lastDTS = inputSamples[inputSamples.length - 1].dts;
  21679. const inputDuration = lastDTS - firstDTS;
  21680. const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track2.inputTimeScale / 30;
  21681. if (contiguous) {
  21682. const delta = firstDTS - nextVideoPts;
  21683. const foundHole = delta > averageSampleDuration;
  21684. const foundOverlap = delta < -1;
  21685. if (foundHole || foundOverlap) {
  21686. if (foundHole) {
  21687. this.warn(`${(track2.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);
  21688. } else {
  21689. this.warn(`${(track2.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);
  21690. }
  21691. if (!foundOverlap || nextVideoPts >= inputSamples[0].pts || chromeVersion) {
  21692. firstDTS = nextVideoPts;
  21693. const firstPTS = inputSamples[0].pts - delta;
  21694. if (foundHole) {
  21695. inputSamples[0].dts = firstDTS;
  21696. inputSamples[0].pts = firstPTS;
  21697. } else {
  21698. let isPTSOrderRetained = true;
  21699. for (let i2 = 0; i2 < inputSamples.length; i2++) {
  21700. if (inputSamples[i2].dts > firstPTS && isPTSOrderRetained) {
  21701. break;
  21702. }
  21703. const prevPTS = inputSamples[i2].pts;
  21704. inputSamples[i2].dts -= delta;
  21705. inputSamples[i2].pts -= delta;
  21706. if (i2 < inputSamples.length - 1) {
  21707. const nextSamplePTS = inputSamples[i2 + 1].pts;
  21708. const currentSamplePTS = inputSamples[i2].pts;
  21709. const currentOrder = nextSamplePTS <= currentSamplePTS;
  21710. const prevOrder = nextSamplePTS <= prevPTS;
  21711. isPTSOrderRetained = currentOrder == prevOrder;
  21712. }
  21713. }
  21714. }
  21715. this.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);
  21716. }
  21717. }
  21718. }
  21719. firstDTS = Math.max(0, firstDTS);
  21720. let nbNalu = 0;
  21721. let naluLen = 0;
  21722. let dtsStep = firstDTS;
  21723. for (let i2 = 0; i2 < nbSamples; i2++) {
  21724. const sample = inputSamples[i2];
  21725. const units = sample.units;
  21726. const nbUnits = units.length;
  21727. let sampleLen = 0;
  21728. for (let j2 = 0; j2 < nbUnits; j2++) {
  21729. sampleLen += units[j2].data.length;
  21730. }
  21731. naluLen += sampleLen;
  21732. nbNalu += nbUnits;
  21733. sample.length = sampleLen;
  21734. if (sample.dts < dtsStep) {
  21735. sample.dts = dtsStep;
  21736. dtsStep += averageSampleDuration / 4 | 0 || 1;
  21737. } else {
  21738. dtsStep = sample.dts;
  21739. }
  21740. minPTS = Math.min(sample.pts, minPTS);
  21741. maxPTS = Math.max(sample.pts, maxPTS);
  21742. }
  21743. lastDTS = inputSamples[nbSamples - 1].dts;
  21744. const mdatSize = naluLen + 4 * nbNalu + 8;
  21745. let mdat;
  21746. try {
  21747. mdat = new Uint8Array(mdatSize);
  21748. } catch (err) {
  21749. this.observer.emit(Events.ERROR, Events.ERROR, {
  21750. type: ErrorTypes.MUX_ERROR,
  21751. details: ErrorDetails.REMUX_ALLOC_ERROR,
  21752. fatal: false,
  21753. error: err,
  21754. bytes: mdatSize,
  21755. reason: `fail allocating video mdat ${mdatSize}`
  21756. });
  21757. return;
  21758. }
  21759. const view2 = new DataView(mdat.buffer);
  21760. view2.setUint32(0, mdatSize);
  21761. mdat.set(MP4.types.mdat, 4);
  21762. let stretchedLastFrame = false;
  21763. let minDtsDelta = Number.POSITIVE_INFINITY;
  21764. let minPtsDelta = Number.POSITIVE_INFINITY;
  21765. let maxDtsDelta = Number.NEGATIVE_INFINITY;
  21766. let maxPtsDelta = Number.NEGATIVE_INFINITY;
  21767. for (let i2 = 0; i2 < nbSamples; i2++) {
  21768. const VideoSample = inputSamples[i2];
  21769. const VideoSampleUnits = VideoSample.units;
  21770. let mp4SampleLength = 0;
  21771. for (let j2 = 0, nbUnits = VideoSampleUnits.length; j2 < nbUnits; j2++) {
  21772. const unit = VideoSampleUnits[j2];
  21773. const unitData = unit.data;
  21774. const unitDataLen = unit.data.byteLength;
  21775. view2.setUint32(offset, unitDataLen);
  21776. offset += 4;
  21777. mdat.set(unitData, offset);
  21778. offset += unitDataLen;
  21779. mp4SampleLength += 4 + unitDataLen;
  21780. }
  21781. let ptsDelta;
  21782. if (i2 < nbSamples - 1) {
  21783. mp4SampleDuration = inputSamples[i2 + 1].dts - VideoSample.dts;
  21784. ptsDelta = inputSamples[i2 + 1].pts - VideoSample.pts;
  21785. } else {
  21786. const config = this.config;
  21787. const lastFrameDuration = i2 > 0 ? VideoSample.dts - inputSamples[i2 - 1].dts : averageSampleDuration;
  21788. ptsDelta = i2 > 0 ? VideoSample.pts - inputSamples[i2 - 1].pts : averageSampleDuration;
  21789. if (config.stretchShortVideoTrack && this.nextAudioTs !== null) {
  21790. const gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  21791. const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioTs + initTime) - VideoSample.pts;
  21792. if (deltaToFrameEnd > gapTolerance) {
  21793. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  21794. if (mp4SampleDuration < 0) {
  21795. mp4SampleDuration = lastFrameDuration;
  21796. } else {
  21797. stretchedLastFrame = true;
  21798. }
  21799. this.log(`It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);
  21800. } else {
  21801. mp4SampleDuration = lastFrameDuration;
  21802. }
  21803. } else {
  21804. mp4SampleDuration = lastFrameDuration;
  21805. }
  21806. }
  21807. const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  21808. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  21809. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  21810. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  21811. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  21812. outputSamples.push(createMp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  21813. }
  21814. if (outputSamples.length) {
  21815. if (chromeVersion) {
  21816. if (chromeVersion < 70) {
  21817. const flags = outputSamples[0].flags;
  21818. flags.dependsOn = 2;
  21819. flags.isNonSync = 0;
  21820. }
  21821. } else if (safariWebkitVersion) {
  21822. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  21823. this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");
  21824. let dts = firstDTS;
  21825. for (let i2 = 0, len = outputSamples.length; i2 < len; i2++) {
  21826. const nextDts = dts + outputSamples[i2].duration;
  21827. const pts = dts + outputSamples[i2].cts;
  21828. if (i2 < len - 1) {
  21829. const nextPts = nextDts + outputSamples[i2 + 1].cts;
  21830. outputSamples[i2].duration = nextPts - pts;
  21831. } else {
  21832. outputSamples[i2].duration = i2 ? outputSamples[i2 - 1].duration : averageSampleDuration;
  21833. }
  21834. outputSamples[i2].cts = 0;
  21835. dts = nextDts;
  21836. }
  21837. }
  21838. }
  21839. }
  21840. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  21841. const endDTS = lastDTS + mp4SampleDuration;
  21842. this.nextVideoTs = nextVideoTs = endDTS - initTime;
  21843. this.videoSampleDuration = mp4SampleDuration;
  21844. this.isVideoContiguous = true;
  21845. const moof = MP4.moof(track2.sequenceNumber++, firstDTS, _extends(track2, {
  21846. samples: outputSamples
  21847. }));
  21848. const type = "video";
  21849. const data = {
  21850. data1: moof,
  21851. data2: mdat,
  21852. startPTS: (minPTS - initTime) / timeScale,
  21853. endPTS: (maxPTS + mp4SampleDuration - initTime) / timeScale,
  21854. startDTS: (firstDTS - initTime) / timeScale,
  21855. endDTS: nextVideoTs / timeScale,
  21856. type,
  21857. hasAudio: false,
  21858. hasVideo: true,
  21859. nb: outputSamples.length,
  21860. dropped: track2.dropped
  21861. };
  21862. track2.samples = [];
  21863. track2.dropped = 0;
  21864. return data;
  21865. }
  21866. getSamplesPerFrame(track2) {
  21867. switch (track2.segmentCodec) {
  21868. case "mp3":
  21869. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  21870. case "ac3":
  21871. return AC3_SAMPLES_PER_FRAME;
  21872. default:
  21873. return AAC_SAMPLES_PER_FRAME;
  21874. }
  21875. }
  21876. remuxAudio(track2, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  21877. const inputTimeScale = track2.inputTimeScale;
  21878. const mp4timeScale = track2.samplerate ? track2.samplerate : inputTimeScale;
  21879. const scaleFactor = inputTimeScale / mp4timeScale;
  21880. const mp4SampleDuration = this.getSamplesPerFrame(track2);
  21881. const inputSampleDuration = mp4SampleDuration * scaleFactor;
  21882. const initPTS = this._initPTS;
  21883. const rawMPEG = track2.segmentCodec === "mp3" && this.typeSupported.mpeg;
  21884. const outputSamples = [];
  21885. const alignedWithVideo = videoTimeOffset !== void 0;
  21886. let inputSamples = track2.samples;
  21887. let offset = rawMPEG ? 0 : 8;
  21888. let nextAudioTs = this.nextAudioTs || -1;
  21889. const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  21890. const timeOffsetMpegTS = initTime + timeOffset * inputTimeScale;
  21891. this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioTs > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - (nextAudioTs + initTime)) < 9e3 || Math.abs(normalizePts(inputSamples[0].pts, timeOffsetMpegTS) - (nextAudioTs + initTime)) < 20 * inputSampleDuration);
  21892. inputSamples.forEach(function(sample) {
  21893. sample.pts = normalizePts(sample.pts, timeOffsetMpegTS);
  21894. });
  21895. if (!contiguous || nextAudioTs < 0) {
  21896. inputSamples = inputSamples.filter((sample) => sample.pts >= 0);
  21897. if (!inputSamples.length) {
  21898. return;
  21899. }
  21900. if (videoTimeOffset === 0) {
  21901. nextAudioTs = 0;
  21902. } else if (accurateTimeOffset && !alignedWithVideo) {
  21903. nextAudioTs = Math.max(0, timeOffsetMpegTS - initTime);
  21904. } else {
  21905. nextAudioTs = inputSamples[0].pts - initTime;
  21906. }
  21907. }
  21908. if (track2.segmentCodec === "aac") {
  21909. const maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  21910. for (let i2 = 0, nextPts = nextAudioTs + initTime; i2 < inputSamples.length; i2++) {
  21911. const sample = inputSamples[i2];
  21912. const pts = sample.pts;
  21913. const delta = pts - nextPts;
  21914. const duration = Math.abs(1e3 * delta / inputTimeScale);
  21915. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  21916. if (i2 === 0) {
  21917. this.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps marker by ${Math.round(1e3 * delta / inputTimeScale)} ms.`);
  21918. this.nextAudioTs = nextAudioTs = pts - initTime;
  21919. nextPts = pts;
  21920. }
  21921. } else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  21922. let missing = Math.round(delta / inputSampleDuration);
  21923. nextPts = pts - missing * inputSampleDuration;
  21924. while (nextPts < 0 && missing && inputSampleDuration) {
  21925. missing--;
  21926. nextPts += inputSampleDuration;
  21927. }
  21928. if (i2 === 0) {
  21929. this.nextAudioTs = nextAudioTs = nextPts - initTime;
  21930. }
  21931. this.warn(`Injecting ${missing} audio frames @ ${((nextPts - initTime) / inputTimeScale).toFixed(3)}s due to ${Math.round(1e3 * delta / inputTimeScale)} ms gap.`);
  21932. for (let j2 = 0; j2 < missing; j2++) {
  21933. let fillFrame = AAC.getSilentFrame(track2.parsedCodec || track2.manifestCodec || track2.codec, track2.channelCount);
  21934. if (!fillFrame) {
  21935. this.log("Unable to get silent frame for given audio codec; duplicating last frame instead.");
  21936. fillFrame = sample.unit.subarray();
  21937. }
  21938. inputSamples.splice(i2, 0, {
  21939. unit: fillFrame,
  21940. pts: nextPts
  21941. });
  21942. nextPts += inputSampleDuration;
  21943. i2++;
  21944. }
  21945. }
  21946. sample.pts = nextPts;
  21947. nextPts += inputSampleDuration;
  21948. }
  21949. }
  21950. let firstPTS = null;
  21951. let lastPTS = null;
  21952. let mdat;
  21953. let mdatSize = 0;
  21954. let sampleLength = inputSamples.length;
  21955. while (sampleLength--) {
  21956. mdatSize += inputSamples[sampleLength].unit.byteLength;
  21957. }
  21958. for (let j2 = 0, _nbSamples = inputSamples.length; j2 < _nbSamples; j2++) {
  21959. const audioSample = inputSamples[j2];
  21960. const unit = audioSample.unit;
  21961. let pts = audioSample.pts;
  21962. if (lastPTS !== null) {
  21963. const prevSample = outputSamples[j2 - 1];
  21964. prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);
  21965. } else {
  21966. if (contiguous && track2.segmentCodec === "aac") {
  21967. pts = nextAudioTs + initTime;
  21968. }
  21969. firstPTS = pts;
  21970. if (mdatSize > 0) {
  21971. mdatSize += offset;
  21972. try {
  21973. mdat = new Uint8Array(mdatSize);
  21974. } catch (err) {
  21975. this.observer.emit(Events.ERROR, Events.ERROR, {
  21976. type: ErrorTypes.MUX_ERROR,
  21977. details: ErrorDetails.REMUX_ALLOC_ERROR,
  21978. fatal: false,
  21979. error: err,
  21980. bytes: mdatSize,
  21981. reason: `fail allocating audio mdat ${mdatSize}`
  21982. });
  21983. return;
  21984. }
  21985. if (!rawMPEG) {
  21986. const view2 = new DataView(mdat.buffer);
  21987. view2.setUint32(0, mdatSize);
  21988. mdat.set(MP4.types.mdat, 4);
  21989. }
  21990. } else {
  21991. return;
  21992. }
  21993. }
  21994. mdat.set(unit, offset);
  21995. const unitLen = unit.byteLength;
  21996. offset += unitLen;
  21997. outputSamples.push(createMp4Sample(true, mp4SampleDuration, unitLen, 0));
  21998. lastPTS = pts;
  21999. }
  22000. const nbSamples = outputSamples.length;
  22001. if (!nbSamples) {
  22002. return;
  22003. }
  22004. const lastSample = outputSamples[outputSamples.length - 1];
  22005. nextAudioTs = lastPTS - initTime;
  22006. this.nextAudioTs = nextAudioTs + scaleFactor * lastSample.duration;
  22007. const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track2.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track2, {
  22008. samples: outputSamples
  22009. }));
  22010. track2.samples = [];
  22011. const start = (firstPTS - initTime) / inputTimeScale;
  22012. const end = nextAudioTs / inputTimeScale;
  22013. const type = "audio";
  22014. const audioData = {
  22015. data1: moof,
  22016. data2: mdat,
  22017. startPTS: start,
  22018. endPTS: end,
  22019. startDTS: start,
  22020. endDTS: end,
  22021. type,
  22022. hasAudio: true,
  22023. hasVideo: false,
  22024. nb: nbSamples
  22025. };
  22026. this.isAudioContiguous = true;
  22027. return audioData;
  22028. }
  22029. }
  22030. function normalizePts(value, reference) {
  22031. let offset;
  22032. if (reference === null) {
  22033. return value;
  22034. }
  22035. if (reference < value) {
  22036. offset = -8589934592;
  22037. } else {
  22038. offset = 8589934592;
  22039. }
  22040. while (Math.abs(value - reference) > 4294967296) {
  22041. value += offset;
  22042. }
  22043. return value;
  22044. }
  22045. function findKeyframeIndex(samples) {
  22046. for (let i2 = 0; i2 < samples.length; i2++) {
  22047. if (samples[i2].key) {
  22048. return i2;
  22049. }
  22050. }
  22051. return -1;
  22052. }
  22053. function flushTextTrackMetadataCueSamples(track2, timeOffset, initPTS, initDTS) {
  22054. const length = track2.samples.length;
  22055. if (!length) {
  22056. return;
  22057. }
  22058. const inputTimeScale = track2.inputTimeScale;
  22059. for (let index2 = 0; index2 < length; index2++) {
  22060. const sample = track2.samples[index2];
  22061. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  22062. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  22063. }
  22064. const samples = track2.samples;
  22065. track2.samples = [];
  22066. return {
  22067. samples
  22068. };
  22069. }
  22070. function flushTextTrackUserdataCueSamples(track2, timeOffset, initPTS) {
  22071. const length = track2.samples.length;
  22072. if (!length) {
  22073. return;
  22074. }
  22075. const inputTimeScale = track2.inputTimeScale;
  22076. for (let index2 = 0; index2 < length; index2++) {
  22077. const sample = track2.samples[index2];
  22078. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  22079. }
  22080. track2.samples.sort((a2, b2) => a2.pts - b2.pts);
  22081. const samples = track2.samples;
  22082. track2.samples = [];
  22083. return {
  22084. samples
  22085. };
  22086. }
  22087. class PassThroughRemuxer extends Logger {
  22088. constructor(observer, config, typeSupported, logger2) {
  22089. super("passthrough-remuxer", logger2);
  22090. this.emitInitSegment = false;
  22091. this.audioCodec = void 0;
  22092. this.videoCodec = void 0;
  22093. this.initData = void 0;
  22094. this.initPTS = null;
  22095. this.initTracks = void 0;
  22096. this.lastEndTime = null;
  22097. this.isVideoContiguous = false;
  22098. }
  22099. destroy() {
  22100. }
  22101. resetTimeStamp(defaultInitPTS) {
  22102. this.lastEndTime = null;
  22103. const initPTS = this.initPTS;
  22104. if (initPTS && defaultInitPTS) {
  22105. if (initPTS.baseTime === defaultInitPTS.baseTime && initPTS.timescale === defaultInitPTS.timescale) {
  22106. return;
  22107. }
  22108. }
  22109. this.initPTS = defaultInitPTS;
  22110. }
  22111. resetNextTimestamp() {
  22112. this.isVideoContiguous = false;
  22113. this.lastEndTime = null;
  22114. }
  22115. resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  22116. this.audioCodec = audioCodec;
  22117. this.videoCodec = videoCodec;
  22118. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  22119. this.emitInitSegment = true;
  22120. }
  22121. generateInitSegment(initSegment) {
  22122. let {
  22123. audioCodec,
  22124. videoCodec
  22125. } = this;
  22126. if (!(initSegment != null && initSegment.byteLength)) {
  22127. this.initTracks = void 0;
  22128. this.initData = void 0;
  22129. return;
  22130. }
  22131. const initData2 = this.initData = parseInitSegment(initSegment);
  22132. if (initData2.audio) {
  22133. audioCodec = getParsedTrackCodec(initData2.audio, ElementaryStreamTypes.AUDIO, this);
  22134. }
  22135. if (initData2.video) {
  22136. videoCodec = getParsedTrackCodec(initData2.video, ElementaryStreamTypes.VIDEO, this);
  22137. }
  22138. const tracks = {};
  22139. if (initData2.audio && initData2.video) {
  22140. tracks.audiovideo = {
  22141. container: "video/mp4",
  22142. codec: audioCodec + "," + videoCodec,
  22143. supplemental: initData2.video.supplemental,
  22144. initSegment,
  22145. id: "main"
  22146. };
  22147. } else if (initData2.audio) {
  22148. tracks.audio = {
  22149. container: "audio/mp4",
  22150. codec: audioCodec,
  22151. initSegment,
  22152. id: "audio"
  22153. };
  22154. } else if (initData2.video) {
  22155. tracks.video = {
  22156. container: "video/mp4",
  22157. codec: videoCodec,
  22158. supplemental: initData2.video.supplemental,
  22159. initSegment,
  22160. id: "main"
  22161. };
  22162. } else {
  22163. this.warn("initSegment does not contain moov or trak boxes.");
  22164. }
  22165. this.initTracks = tracks;
  22166. }
  22167. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  22168. var _initData, _initData2;
  22169. let {
  22170. initPTS,
  22171. lastEndTime
  22172. } = this;
  22173. const result = {
  22174. audio: void 0,
  22175. video: void 0,
  22176. text: textTrack,
  22177. id3: id3Track,
  22178. initSegment: void 0
  22179. };
  22180. if (!isFiniteNumber(lastEndTime)) {
  22181. lastEndTime = this.lastEndTime = timeOffset || 0;
  22182. }
  22183. const data = videoTrack.samples;
  22184. if (!(data != null && data.length)) {
  22185. return result;
  22186. }
  22187. const initSegment = {
  22188. initPTS: void 0,
  22189. timescale: void 0,
  22190. trackId: void 0
  22191. };
  22192. let initData2 = this.initData;
  22193. if (!((_initData = initData2) != null && _initData.length)) {
  22194. this.generateInitSegment(data);
  22195. initData2 = this.initData;
  22196. }
  22197. if (!((_initData2 = initData2) != null && _initData2.length)) {
  22198. this.warn("Failed to generate initSegment.");
  22199. return result;
  22200. }
  22201. if (this.emitInitSegment) {
  22202. initSegment.tracks = this.initTracks;
  22203. this.emitInitSegment = false;
  22204. }
  22205. const trackSampleData = getSampleData(data, initData2, this);
  22206. const audioSampleTimestamps = initData2.audio ? trackSampleData[initData2.audio.id] : null;
  22207. const videoSampleTimestamps = initData2.video ? trackSampleData[initData2.video.id] : null;
  22208. const videoStartTime = toStartEndOrDefault(videoSampleTimestamps, Infinity);
  22209. const audioStartTime = toStartEndOrDefault(audioSampleTimestamps, Infinity);
  22210. const videoEndTime = toStartEndOrDefault(videoSampleTimestamps, 0, true);
  22211. const audioEndTime = toStartEndOrDefault(audioSampleTimestamps, 0, true);
  22212. let baseOffsetSamples;
  22213. let decodeTime = timeOffset;
  22214. let duration = 0;
  22215. if (audioSampleTimestamps && (!videoSampleTimestamps || !initPTS && audioStartTime < videoStartTime || initPTS && initPTS.trackId === initData2.audio.id)) {
  22216. initSegment.trackId = initData2.audio.id;
  22217. baseOffsetSamples = audioSampleTimestamps;
  22218. duration = audioEndTime - audioStartTime;
  22219. } else if (videoSampleTimestamps) {
  22220. initSegment.trackId = initData2.video.id;
  22221. baseOffsetSamples = videoSampleTimestamps;
  22222. duration = videoEndTime - videoStartTime;
  22223. }
  22224. if (baseOffsetSamples) {
  22225. const timescale = baseOffsetSamples.timescale;
  22226. decodeTime = baseOffsetSamples.start / timescale;
  22227. initSegment.initPTS = baseOffsetSamples.start - timeOffset * timescale;
  22228. initSegment.timescale = timescale;
  22229. if (!initPTS) {
  22230. this.initPTS = initPTS = {
  22231. baseTime: initSegment.initPTS,
  22232. timescale,
  22233. trackId: initSegment.trackId
  22234. };
  22235. }
  22236. }
  22237. if ((accurateTimeOffset || !initPTS) && (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale)) {
  22238. initSegment.initPTS = decodeTime - timeOffset;
  22239. initSegment.timescale = 1;
  22240. if (initPTS && initPTS.timescale === 1) {
  22241. this.warn(`Adjusting initPTS @${timeOffset} from ${initPTS.baseTime / initPTS.timescale} to ${initSegment.initPTS}`);
  22242. }
  22243. this.initPTS = initPTS = {
  22244. baseTime: initSegment.initPTS,
  22245. timescale: 1
  22246. };
  22247. }
  22248. const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  22249. const endTime = startTime + duration;
  22250. if (duration > 0) {
  22251. this.lastEndTime = endTime;
  22252. } else {
  22253. this.warn("Duration parsed from mp4 should be greater than zero");
  22254. this.resetNextTimestamp();
  22255. }
  22256. const hasAudio = !!initData2.audio;
  22257. const hasVideo = !!initData2.video;
  22258. let type = "";
  22259. if (hasAudio) {
  22260. type += "audio";
  22261. }
  22262. if (hasVideo) {
  22263. type += "video";
  22264. }
  22265. const track2 = {
  22266. data1: data,
  22267. startPTS: startTime,
  22268. startDTS: startTime,
  22269. endPTS: endTime,
  22270. endDTS: endTime,
  22271. type,
  22272. hasAudio,
  22273. hasVideo,
  22274. nb: 1,
  22275. dropped: 0
  22276. };
  22277. result.audio = hasAudio && !hasVideo ? track2 : void 0;
  22278. result.video = hasVideo ? track2 : void 0;
  22279. const videoSampleCount = videoSampleTimestamps == null ? void 0 : videoSampleTimestamps.sampleCount;
  22280. if (videoSampleCount) {
  22281. const firstKeyFrame = videoSampleTimestamps.keyFrameIndex;
  22282. const independent = firstKeyFrame !== -1;
  22283. track2.nb = videoSampleCount;
  22284. track2.dropped = firstKeyFrame === 0 || this.isVideoContiguous ? 0 : independent ? firstKeyFrame : videoSampleCount;
  22285. track2.independent = independent;
  22286. track2.firstKeyFrame = firstKeyFrame;
  22287. if (independent && videoSampleTimestamps.keyFrameStart) {
  22288. track2.firstKeyFramePTS = (videoSampleTimestamps.keyFrameStart - initPTS.baseTime) / initPTS.timescale;
  22289. }
  22290. if (!this.isVideoContiguous) {
  22291. result.independent = independent;
  22292. }
  22293. this.isVideoContiguous || (this.isVideoContiguous = independent);
  22294. if (track2.dropped) {
  22295. this.warn(`fmp4 does not start with IDR: firstIDR ${firstKeyFrame}/${videoSampleCount} dropped: ${track2.dropped} start: ${track2.firstKeyFramePTS || "NA"}`);
  22296. }
  22297. }
  22298. result.initSegment = initSegment;
  22299. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  22300. if (textTrack.samples.length) {
  22301. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  22302. }
  22303. return result;
  22304. }
  22305. }
  22306. function toStartEndOrDefault(trackTimes, defaultValue, end = false) {
  22307. return (trackTimes == null ? void 0 : trackTimes.start) !== void 0 ? (trackTimes.start + (end ? trackTimes.duration : 0)) / trackTimes.timescale : defaultValue;
  22308. }
  22309. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  22310. if (initPTS === null) {
  22311. return true;
  22312. }
  22313. const minDuration = Math.max(duration, 1);
  22314. const startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  22315. return Math.abs(startTime - timeOffset) > minDuration;
  22316. }
  22317. function getParsedTrackCodec(track2, type, logger2) {
  22318. const parsedCodec = track2 == null ? void 0 : track2.codec;
  22319. if (parsedCodec && parsedCodec.length > 4) {
  22320. return parsedCodec;
  22321. }
  22322. if (type === ElementaryStreamTypes.AUDIO) {
  22323. if (parsedCodec === "ec-3" || parsedCodec === "ac-3" || parsedCodec === "alac") {
  22324. return parsedCodec;
  22325. }
  22326. if (parsedCodec === "fLaC" || parsedCodec === "Opus") {
  22327. const preferManagedMediaSource = false;
  22328. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  22329. }
  22330. logger2.warn(`Unhandled audio codec "${parsedCodec}" in mp4 MAP`);
  22331. return parsedCodec || "mp4a";
  22332. }
  22333. logger2.warn(`Unhandled video codec "${parsedCodec}" in mp4 MAP`);
  22334. return parsedCodec || "avc1";
  22335. }
  22336. let now;
  22337. try {
  22338. now = self.performance.now.bind(self.performance);
  22339. } catch (err) {
  22340. now = Date.now;
  22341. }
  22342. const muxConfig = [{
  22343. demux: MP4Demuxer,
  22344. remux: PassThroughRemuxer
  22345. }, {
  22346. demux: TSDemuxer,
  22347. remux: MP4Remuxer
  22348. }, {
  22349. demux: AACDemuxer,
  22350. remux: MP4Remuxer
  22351. }, {
  22352. demux: MP3Demuxer,
  22353. remux: MP4Remuxer
  22354. }];
  22355. {
  22356. muxConfig.splice(2, 0, {
  22357. demux: AC3Demuxer,
  22358. remux: MP4Remuxer
  22359. });
  22360. }
  22361. class Transmuxer {
  22362. constructor(observer, typeSupported, config, vendor, id, logger2) {
  22363. this.asyncResult = false;
  22364. this.logger = void 0;
  22365. this.observer = void 0;
  22366. this.typeSupported = void 0;
  22367. this.config = void 0;
  22368. this.id = void 0;
  22369. this.demuxer = void 0;
  22370. this.remuxer = void 0;
  22371. this.decrypter = void 0;
  22372. this.probe = void 0;
  22373. this.decryptionPromise = null;
  22374. this.transmuxConfig = void 0;
  22375. this.currentTransmuxState = void 0;
  22376. this.observer = observer;
  22377. this.typeSupported = typeSupported;
  22378. this.config = config;
  22379. this.id = id;
  22380. this.logger = logger2;
  22381. }
  22382. configure(transmuxConfig) {
  22383. this.transmuxConfig = transmuxConfig;
  22384. if (this.decrypter) {
  22385. this.decrypter.reset();
  22386. }
  22387. }
  22388. push(data, decryptdata, chunkMeta, state) {
  22389. const stats = chunkMeta.transmuxing;
  22390. stats.executeStart = now();
  22391. let uintData = new Uint8Array(data);
  22392. const {
  22393. currentTransmuxState,
  22394. transmuxConfig
  22395. } = this;
  22396. if (state) {
  22397. this.currentTransmuxState = state;
  22398. }
  22399. const {
  22400. contiguous,
  22401. discontinuity,
  22402. trackSwitch,
  22403. accurateTimeOffset,
  22404. timeOffset,
  22405. initSegmentChange
  22406. } = state || currentTransmuxState;
  22407. const {
  22408. audioCodec,
  22409. videoCodec,
  22410. defaultInitPts,
  22411. duration,
  22412. initSegmentData
  22413. } = transmuxConfig;
  22414. const keyData = getEncryptionType(uintData, decryptdata);
  22415. if (keyData && isFullSegmentEncryption(keyData.method)) {
  22416. const decrypter = this.getDecrypter();
  22417. const aesMode = getAesModeFromFullSegmentMethod(keyData.method);
  22418. if (decrypter.isSync()) {
  22419. let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode);
  22420. const loadingParts = chunkMeta.part > -1;
  22421. if (loadingParts) {
  22422. const _data = decrypter.flush();
  22423. decryptedData = _data ? _data.buffer : _data;
  22424. }
  22425. if (!decryptedData) {
  22426. stats.executeEnd = now();
  22427. return emptyResult(chunkMeta);
  22428. }
  22429. uintData = new Uint8Array(decryptedData);
  22430. } else {
  22431. this.asyncResult = true;
  22432. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode).then((decryptedData) => {
  22433. const result2 = this.push(decryptedData, null, chunkMeta);
  22434. this.decryptionPromise = null;
  22435. return result2;
  22436. });
  22437. return this.decryptionPromise;
  22438. }
  22439. }
  22440. const resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  22441. if (resetMuxers) {
  22442. const error = this.configureTransmuxer(uintData);
  22443. if (error) {
  22444. this.logger.warn(`[transmuxer] ${error.message}`);
  22445. this.observer.emit(Events.ERROR, Events.ERROR, {
  22446. type: ErrorTypes.MEDIA_ERROR,
  22447. details: ErrorDetails.FRAG_PARSING_ERROR,
  22448. fatal: false,
  22449. error,
  22450. reason: error.message
  22451. });
  22452. stats.executeEnd = now();
  22453. return emptyResult(chunkMeta);
  22454. }
  22455. }
  22456. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  22457. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  22458. }
  22459. if (discontinuity || initSegmentChange || resetMuxers) {
  22460. this.resetInitialTimestamp(defaultInitPts);
  22461. }
  22462. if (!contiguous) {
  22463. this.resetContiguity();
  22464. }
  22465. const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  22466. this.asyncResult = isPromise(result);
  22467. const currentState = this.currentTransmuxState;
  22468. currentState.contiguous = true;
  22469. currentState.discontinuity = false;
  22470. currentState.trackSwitch = false;
  22471. stats.executeEnd = now();
  22472. return result;
  22473. }
  22474. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  22475. flush(chunkMeta) {
  22476. const stats = chunkMeta.transmuxing;
  22477. stats.executeStart = now();
  22478. const {
  22479. decrypter,
  22480. currentTransmuxState,
  22481. decryptionPromise
  22482. } = this;
  22483. if (decryptionPromise) {
  22484. this.asyncResult = true;
  22485. return decryptionPromise.then(() => {
  22486. return this.flush(chunkMeta);
  22487. });
  22488. }
  22489. const transmuxResults = [];
  22490. const {
  22491. timeOffset
  22492. } = currentTransmuxState;
  22493. if (decrypter) {
  22494. const decryptedData = decrypter.flush();
  22495. if (decryptedData) {
  22496. transmuxResults.push(this.push(decryptedData.buffer, null, chunkMeta));
  22497. }
  22498. }
  22499. const {
  22500. demuxer,
  22501. remuxer
  22502. } = this;
  22503. if (!demuxer || !remuxer) {
  22504. stats.executeEnd = now();
  22505. const emptyResults = [emptyResult(chunkMeta)];
  22506. if (this.asyncResult) {
  22507. return Promise.resolve(emptyResults);
  22508. }
  22509. return emptyResults;
  22510. }
  22511. const demuxResultOrPromise = demuxer.flush(timeOffset);
  22512. if (isPromise(demuxResultOrPromise)) {
  22513. this.asyncResult = true;
  22514. return demuxResultOrPromise.then((demuxResult) => {
  22515. this.flushRemux(transmuxResults, demuxResult, chunkMeta);
  22516. return transmuxResults;
  22517. });
  22518. }
  22519. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  22520. if (this.asyncResult) {
  22521. return Promise.resolve(transmuxResults);
  22522. }
  22523. return transmuxResults;
  22524. }
  22525. flushRemux(transmuxResults, demuxResult, chunkMeta) {
  22526. const {
  22527. audioTrack,
  22528. videoTrack,
  22529. id3Track,
  22530. textTrack
  22531. } = demuxResult;
  22532. const {
  22533. accurateTimeOffset,
  22534. timeOffset
  22535. } = this.currentTransmuxState;
  22536. this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${chunkMeta.sn}${chunkMeta.part > -1 ? " part: " + chunkMeta.part : ""} of ${this.id === PlaylistLevelType.MAIN ? "level" : "track"} ${chunkMeta.level}`);
  22537. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  22538. transmuxResults.push({
  22539. remuxResult,
  22540. chunkMeta
  22541. });
  22542. chunkMeta.transmuxing.executeEnd = now();
  22543. }
  22544. resetInitialTimestamp(defaultInitPts) {
  22545. const {
  22546. demuxer,
  22547. remuxer
  22548. } = this;
  22549. if (!demuxer || !remuxer) {
  22550. return;
  22551. }
  22552. demuxer.resetTimeStamp(defaultInitPts);
  22553. remuxer.resetTimeStamp(defaultInitPts);
  22554. }
  22555. resetContiguity() {
  22556. const {
  22557. demuxer,
  22558. remuxer
  22559. } = this;
  22560. if (!demuxer || !remuxer) {
  22561. return;
  22562. }
  22563. demuxer.resetContiguity();
  22564. remuxer.resetNextTimestamp();
  22565. }
  22566. resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  22567. const {
  22568. demuxer,
  22569. remuxer
  22570. } = this;
  22571. if (!demuxer || !remuxer) {
  22572. return;
  22573. }
  22574. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  22575. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  22576. }
  22577. destroy() {
  22578. if (this.demuxer) {
  22579. this.demuxer.destroy();
  22580. this.demuxer = void 0;
  22581. }
  22582. if (this.remuxer) {
  22583. this.remuxer.destroy();
  22584. this.remuxer = void 0;
  22585. }
  22586. }
  22587. transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  22588. let result;
  22589. if (keyData && keyData.method === "SAMPLE-AES") {
  22590. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  22591. } else {
  22592. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  22593. }
  22594. return result;
  22595. }
  22596. transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  22597. const {
  22598. audioTrack,
  22599. videoTrack,
  22600. id3Track,
  22601. textTrack
  22602. } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);
  22603. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  22604. return {
  22605. remuxResult,
  22606. chunkMeta
  22607. };
  22608. }
  22609. transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  22610. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then((demuxResult) => {
  22611. const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);
  22612. return {
  22613. remuxResult,
  22614. chunkMeta
  22615. };
  22616. });
  22617. }
  22618. configureTransmuxer(data) {
  22619. const {
  22620. config,
  22621. observer,
  22622. typeSupported
  22623. } = this;
  22624. let mux;
  22625. for (let i2 = 0, len = muxConfig.length; i2 < len; i2++) {
  22626. var _muxConfig$i$demux;
  22627. if ((_muxConfig$i$demux = muxConfig[i2].demux) != null && _muxConfig$i$demux.probe(data, this.logger)) {
  22628. mux = muxConfig[i2];
  22629. break;
  22630. }
  22631. }
  22632. if (!mux) {
  22633. return new Error("Failed to find demuxer by probing fragment data");
  22634. }
  22635. const demuxer = this.demuxer;
  22636. const remuxer = this.remuxer;
  22637. const Remuxer = mux.remux;
  22638. const Demuxer = mux.demux;
  22639. if (!remuxer || !(remuxer instanceof Remuxer)) {
  22640. this.remuxer = new Remuxer(observer, config, typeSupported, this.logger);
  22641. }
  22642. if (!demuxer || !(demuxer instanceof Demuxer)) {
  22643. this.demuxer = new Demuxer(observer, config, typeSupported, this.logger);
  22644. this.probe = Demuxer.probe;
  22645. }
  22646. }
  22647. needsProbing(discontinuity, trackSwitch) {
  22648. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  22649. }
  22650. getDecrypter() {
  22651. let decrypter = this.decrypter;
  22652. if (!decrypter) {
  22653. decrypter = this.decrypter = new Decrypter(this.config);
  22654. }
  22655. return decrypter;
  22656. }
  22657. }
  22658. function getEncryptionType(data, decryptData) {
  22659. let encryptionType = null;
  22660. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  22661. encryptionType = decryptData;
  22662. }
  22663. return encryptionType;
  22664. }
  22665. const emptyResult = (chunkMeta) => ({
  22666. remuxResult: {},
  22667. chunkMeta
  22668. });
  22669. function isPromise(p2) {
  22670. return "then" in p2 && p2.then instanceof Function;
  22671. }
  22672. class TransmuxConfig {
  22673. constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  22674. this.audioCodec = void 0;
  22675. this.videoCodec = void 0;
  22676. this.initSegmentData = void 0;
  22677. this.duration = void 0;
  22678. this.defaultInitPts = void 0;
  22679. this.audioCodec = audioCodec;
  22680. this.videoCodec = videoCodec;
  22681. this.initSegmentData = initSegmentData;
  22682. this.duration = duration;
  22683. this.defaultInitPts = defaultInitPts || null;
  22684. }
  22685. }
  22686. class TransmuxState {
  22687. constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  22688. this.discontinuity = void 0;
  22689. this.contiguous = void 0;
  22690. this.accurateTimeOffset = void 0;
  22691. this.trackSwitch = void 0;
  22692. this.timeOffset = void 0;
  22693. this.initSegmentChange = void 0;
  22694. this.discontinuity = discontinuity;
  22695. this.contiguous = contiguous;
  22696. this.accurateTimeOffset = accurateTimeOffset;
  22697. this.trackSwitch = trackSwitch;
  22698. this.timeOffset = timeOffset;
  22699. this.initSegmentChange = initSegmentChange;
  22700. }
  22701. }
  22702. let transmuxerInstanceCount = 0;
  22703. class TransmuxerInterface {
  22704. constructor(_hls, id, onTransmuxComplete, onFlush) {
  22705. this.error = null;
  22706. this.hls = void 0;
  22707. this.id = void 0;
  22708. this.instanceNo = transmuxerInstanceCount++;
  22709. this.observer = void 0;
  22710. this.frag = null;
  22711. this.part = null;
  22712. this.useWorker = void 0;
  22713. this.workerContext = null;
  22714. this.transmuxer = null;
  22715. this.onTransmuxComplete = void 0;
  22716. this.onFlush = void 0;
  22717. this.onWorkerMessage = (event) => {
  22718. const data = event.data;
  22719. const hls = this.hls;
  22720. if (!hls || !(data != null && data.event) || data.instanceNo !== this.instanceNo) {
  22721. return;
  22722. }
  22723. switch (data.event) {
  22724. case "init": {
  22725. var _this$workerContext;
  22726. const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  22727. if (objectURL) {
  22728. self.URL.revokeObjectURL(objectURL);
  22729. }
  22730. break;
  22731. }
  22732. case "transmuxComplete": {
  22733. this.handleTransmuxComplete(data.data);
  22734. break;
  22735. }
  22736. case "flush": {
  22737. this.onFlush(data.data);
  22738. break;
  22739. }
  22740. case "workerLog": {
  22741. if (hls.logger[data.data.logType]) {
  22742. hls.logger[data.data.logType](data.data.message);
  22743. }
  22744. break;
  22745. }
  22746. default: {
  22747. data.data = data.data || {};
  22748. data.data.frag = this.frag;
  22749. data.data.part = this.part;
  22750. data.data.id = this.id;
  22751. hls.trigger(data.event, data.data);
  22752. break;
  22753. }
  22754. }
  22755. };
  22756. this.onWorkerError = (event) => {
  22757. if (!this.hls) {
  22758. return;
  22759. }
  22760. const error = new Error(`${event.message} (${event.filename}:${event.lineno})`);
  22761. this.hls.config.enableWorker = false;
  22762. this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`);
  22763. this.hls.trigger(Events.ERROR, {
  22764. type: ErrorTypes.OTHER_ERROR,
  22765. details: ErrorDetails.INTERNAL_EXCEPTION,
  22766. fatal: false,
  22767. event: "demuxerWorker",
  22768. error
  22769. });
  22770. };
  22771. const config = _hls.config;
  22772. this.hls = _hls;
  22773. this.id = id;
  22774. this.useWorker = !!config.enableWorker;
  22775. this.onTransmuxComplete = onTransmuxComplete;
  22776. this.onFlush = onFlush;
  22777. const forwardMessage = (ev, data) => {
  22778. data = data || {};
  22779. data.frag = this.frag || void 0;
  22780. if (ev === Events.ERROR) {
  22781. data = data;
  22782. data.parent = this.id;
  22783. data.part = this.part;
  22784. this.error = data.error;
  22785. }
  22786. this.hls.trigger(ev, data);
  22787. };
  22788. this.observer = new EventEmitter();
  22789. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  22790. this.observer.on(Events.ERROR, forwardMessage);
  22791. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  22792. if (this.useWorker && typeof Worker !== "undefined") {
  22793. const logger2 = this.hls.logger;
  22794. const canCreateWorker = config.workerPath || hasUMDWorker();
  22795. if (canCreateWorker) {
  22796. try {
  22797. if (config.workerPath) {
  22798. logger2.log(`loading Web Worker ${config.workerPath} for "${id}"`);
  22799. this.workerContext = loadWorker(config.workerPath);
  22800. } else {
  22801. logger2.log(`injecting Web Worker for "${id}"`);
  22802. this.workerContext = injectWorker();
  22803. }
  22804. const {
  22805. worker
  22806. } = this.workerContext;
  22807. worker.addEventListener("message", this.onWorkerMessage);
  22808. worker.addEventListener("error", this.onWorkerError);
  22809. worker.postMessage({
  22810. instanceNo: this.instanceNo,
  22811. cmd: "init",
  22812. typeSupported: m2tsTypeSupported,
  22813. id,
  22814. config: stringify(config)
  22815. });
  22816. } catch (err) {
  22817. logger2.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err);
  22818. this.terminateWorker();
  22819. this.error = null;
  22820. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id, _hls.logger);
  22821. }
  22822. return;
  22823. }
  22824. }
  22825. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id, _hls.logger);
  22826. }
  22827. reset() {
  22828. this.frag = null;
  22829. this.part = null;
  22830. if (this.workerContext) {
  22831. const instanceNo = this.instanceNo;
  22832. this.instanceNo = transmuxerInstanceCount++;
  22833. const config = this.hls.config;
  22834. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  22835. this.workerContext.worker.postMessage({
  22836. instanceNo: this.instanceNo,
  22837. cmd: "reset",
  22838. resetNo: instanceNo,
  22839. typeSupported: m2tsTypeSupported,
  22840. id: this.id,
  22841. config: stringify(config)
  22842. });
  22843. }
  22844. }
  22845. terminateWorker() {
  22846. if (this.workerContext) {
  22847. const {
  22848. worker
  22849. } = this.workerContext;
  22850. this.workerContext = null;
  22851. worker.removeEventListener("message", this.onWorkerMessage);
  22852. worker.removeEventListener("error", this.onWorkerError);
  22853. removeWorkerFromStore(this.hls.config.workerPath);
  22854. }
  22855. }
  22856. destroy() {
  22857. if (this.workerContext) {
  22858. this.terminateWorker();
  22859. this.onWorkerMessage = this.onWorkerError = null;
  22860. } else {
  22861. const transmuxer = this.transmuxer;
  22862. if (transmuxer) {
  22863. transmuxer.destroy();
  22864. this.transmuxer = null;
  22865. }
  22866. }
  22867. const observer = this.observer;
  22868. if (observer) {
  22869. observer.removeAllListeners();
  22870. }
  22871. this.frag = null;
  22872. this.part = null;
  22873. this.observer = null;
  22874. this.hls = null;
  22875. }
  22876. push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  22877. var _frag$initSegment, _lastFrag$initSegment;
  22878. chunkMeta.transmuxing.start = self.performance.now();
  22879. const {
  22880. instanceNo,
  22881. transmuxer
  22882. } = this;
  22883. const timeOffset = part ? part.start : frag.start;
  22884. const decryptdata = frag.decryptdata;
  22885. const lastFrag = this.frag;
  22886. const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  22887. const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  22888. const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  22889. const partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  22890. const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  22891. const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  22892. const now2 = self.performance.now();
  22893. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  22894. frag.stats.parsing.start = now2;
  22895. }
  22896. if (part && (partDiff || !contiguous)) {
  22897. part.stats.parsing.start = now2;
  22898. }
  22899. const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  22900. const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  22901. if (!contiguous || discontinuity || initSegmentChange) {
  22902. this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${frag.type} sn: ${chunkMeta.sn}${chunkMeta.part > -1 ? " part: " + chunkMeta.part : ""} ${this.id === PlaylistLevelType.MAIN ? "level" : "track"}: ${chunkMeta.level} id: ${chunkMeta.id}
  22903. discontinuity: ${discontinuity}
  22904. trackSwitch: ${trackSwitch}
  22905. contiguous: ${contiguous}
  22906. accurateTimeOffset: ${accurateTimeOffset}
  22907. timeOffset: ${timeOffset}
  22908. initSegmentChange: ${initSegmentChange}`);
  22909. const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  22910. this.configureTransmuxer(config);
  22911. }
  22912. this.frag = frag;
  22913. this.part = part;
  22914. if (this.workerContext) {
  22915. this.workerContext.worker.postMessage({
  22916. instanceNo,
  22917. cmd: "demux",
  22918. data,
  22919. decryptdata,
  22920. chunkMeta,
  22921. state
  22922. }, data instanceof ArrayBuffer ? [data] : []);
  22923. } else if (transmuxer) {
  22924. const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  22925. if (isPromise(transmuxResult)) {
  22926. transmuxResult.then((data2) => {
  22927. this.handleTransmuxComplete(data2);
  22928. }).catch((error) => {
  22929. this.transmuxerError(error, chunkMeta, "transmuxer-interface push error");
  22930. });
  22931. } else {
  22932. this.handleTransmuxComplete(transmuxResult);
  22933. }
  22934. }
  22935. }
  22936. flush(chunkMeta) {
  22937. chunkMeta.transmuxing.start = self.performance.now();
  22938. const {
  22939. instanceNo,
  22940. transmuxer
  22941. } = this;
  22942. if (this.workerContext) {
  22943. this.workerContext.worker.postMessage({
  22944. instanceNo,
  22945. cmd: "flush",
  22946. chunkMeta
  22947. });
  22948. } else if (transmuxer) {
  22949. const transmuxResult = transmuxer.flush(chunkMeta);
  22950. if (isPromise(transmuxResult)) {
  22951. transmuxResult.then((data) => {
  22952. this.handleFlushResult(data, chunkMeta);
  22953. }).catch((error) => {
  22954. this.transmuxerError(error, chunkMeta, "transmuxer-interface flush error");
  22955. });
  22956. } else {
  22957. this.handleFlushResult(transmuxResult, chunkMeta);
  22958. }
  22959. }
  22960. }
  22961. transmuxerError(error, chunkMeta, reason) {
  22962. if (!this.hls) {
  22963. return;
  22964. }
  22965. this.error = error;
  22966. this.hls.trigger(Events.ERROR, {
  22967. type: ErrorTypes.MEDIA_ERROR,
  22968. details: ErrorDetails.FRAG_PARSING_ERROR,
  22969. chunkMeta,
  22970. frag: this.frag || void 0,
  22971. part: this.part || void 0,
  22972. fatal: false,
  22973. error,
  22974. err: error,
  22975. reason
  22976. });
  22977. }
  22978. handleFlushResult(results, chunkMeta) {
  22979. results.forEach((result) => {
  22980. this.handleTransmuxComplete(result);
  22981. });
  22982. this.onFlush(chunkMeta);
  22983. }
  22984. configureTransmuxer(config) {
  22985. const {
  22986. instanceNo,
  22987. transmuxer
  22988. } = this;
  22989. if (this.workerContext) {
  22990. this.workerContext.worker.postMessage({
  22991. instanceNo,
  22992. cmd: "configure",
  22993. config
  22994. });
  22995. } else if (transmuxer) {
  22996. transmuxer.configure(config);
  22997. }
  22998. }
  22999. handleTransmuxComplete(result) {
  23000. result.chunkMeta.transmuxing.end = self.performance.now();
  23001. this.onTransmuxComplete(result);
  23002. }
  23003. }
  23004. const TICK_INTERVAL$3 = 100;
  23005. class AudioStreamController extends BaseStreamController {
  23006. constructor(hls, fragmentTracker, keyLoader) {
  23007. super(hls, fragmentTracker, keyLoader, "audio-stream-controller", PlaylistLevelType.AUDIO);
  23008. this.mainAnchor = null;
  23009. this.mainFragLoading = null;
  23010. this.audioOnly = false;
  23011. this.bufferedTrack = null;
  23012. this.switchingTrack = null;
  23013. this.trackId = -1;
  23014. this.waitingData = null;
  23015. this.mainDetails = null;
  23016. this.flushing = false;
  23017. this.bufferFlushed = false;
  23018. this.cachedTrackLoadedData = null;
  23019. this.registerListeners();
  23020. }
  23021. onHandlerDestroying() {
  23022. this.unregisterListeners();
  23023. super.onHandlerDestroying();
  23024. this.resetItem();
  23025. }
  23026. resetItem() {
  23027. this.mainDetails = this.mainAnchor = this.mainFragLoading = this.bufferedTrack = this.switchingTrack = this.waitingData = this.cachedTrackLoadedData = null;
  23028. }
  23029. registerListeners() {
  23030. super.registerListeners();
  23031. const {
  23032. hls
  23033. } = this;
  23034. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  23035. hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  23036. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  23037. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  23038. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  23039. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  23040. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  23041. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  23042. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  23043. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  23044. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  23045. }
  23046. unregisterListeners() {
  23047. const {
  23048. hls
  23049. } = this;
  23050. if (!hls) {
  23051. return;
  23052. }
  23053. super.unregisterListeners();
  23054. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  23055. hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  23056. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  23057. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  23058. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  23059. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  23060. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  23061. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  23062. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  23063. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  23064. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  23065. }
  23066. // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
  23067. onInitPtsFound(event, {
  23068. frag,
  23069. id,
  23070. initPTS,
  23071. timescale
  23072. }) {
  23073. if (id === PlaylistLevelType.MAIN) {
  23074. const cc = frag.cc;
  23075. const inFlightFrag = this.fragCurrent;
  23076. this.initPTS[cc] = {
  23077. baseTime: initPTS,
  23078. timescale
  23079. };
  23080. this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}/${timescale}`);
  23081. this.mainAnchor = frag;
  23082. if (this.state === State.WAITING_INIT_PTS) {
  23083. const waitingData = this.waitingData;
  23084. if (!waitingData && !this.loadingParts || waitingData && waitingData.frag.cc !== cc) {
  23085. this.syncWithAnchor(frag, waitingData == null ? void 0 : waitingData.frag);
  23086. }
  23087. } else if (!this.hls.hasEnoughToStart && inFlightFrag && inFlightFrag.cc !== cc) {
  23088. inFlightFrag.abortRequests();
  23089. this.syncWithAnchor(frag, inFlightFrag);
  23090. } else if (this.state === State.IDLE) {
  23091. this.tick();
  23092. }
  23093. }
  23094. }
  23095. getLoadPosition() {
  23096. if (!this.startFragRequested && this.nextLoadPosition >= 0) {
  23097. return this.nextLoadPosition;
  23098. }
  23099. return super.getLoadPosition();
  23100. }
  23101. syncWithAnchor(mainAnchor, waitingToAppend) {
  23102. var _this$mainFragLoading;
  23103. const mainFragLoading = ((_this$mainFragLoading = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading.frag) || null;
  23104. if (waitingToAppend) {
  23105. if ((mainFragLoading == null ? void 0 : mainFragLoading.cc) === waitingToAppend.cc) {
  23106. return;
  23107. }
  23108. }
  23109. const targetDiscontinuity = (mainFragLoading || mainAnchor).cc;
  23110. const trackDetails = this.getLevelDetails();
  23111. const pos = this.getLoadPosition();
  23112. const syncFrag = findNearestWithCC(trackDetails, targetDiscontinuity, pos);
  23113. if (syncFrag) {
  23114. this.log(`Syncing with main frag at ${syncFrag.start} cc ${syncFrag.cc}`);
  23115. this.startFragRequested = false;
  23116. this.nextLoadPosition = syncFrag.start;
  23117. this.resetLoadingState();
  23118. if (this.state === State.IDLE) {
  23119. this.doTickIdle();
  23120. }
  23121. }
  23122. }
  23123. startLoad(startPosition, skipSeekToStartPosition) {
  23124. if (!this.levels) {
  23125. this.startPosition = startPosition;
  23126. this.state = State.STOPPED;
  23127. return;
  23128. }
  23129. const lastCurrentTime = this.lastCurrentTime;
  23130. this.stopLoad();
  23131. this.setInterval(TICK_INTERVAL$3);
  23132. if (lastCurrentTime > 0 && startPosition === -1) {
  23133. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  23134. startPosition = lastCurrentTime;
  23135. this.state = State.IDLE;
  23136. } else {
  23137. this.state = State.WAITING_TRACK;
  23138. }
  23139. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  23140. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  23141. this.tick();
  23142. }
  23143. doTick() {
  23144. switch (this.state) {
  23145. case State.IDLE:
  23146. this.doTickIdle();
  23147. break;
  23148. case State.WAITING_TRACK: {
  23149. const {
  23150. levels,
  23151. trackId
  23152. } = this;
  23153. const currenTrack = levels == null ? void 0 : levels[trackId];
  23154. const details = currenTrack == null ? void 0 : currenTrack.details;
  23155. if (details && !this.waitForLive(currenTrack)) {
  23156. if (this.waitForCdnTuneIn(details)) {
  23157. break;
  23158. }
  23159. this.state = State.WAITING_INIT_PTS;
  23160. }
  23161. break;
  23162. }
  23163. case State.FRAG_LOADING_WAITING_RETRY: {
  23164. var _this$media;
  23165. const now2 = performance.now();
  23166. const retryDate = this.retryDate;
  23167. if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  23168. const {
  23169. levels,
  23170. trackId
  23171. } = this;
  23172. this.log("RetryDate reached, switch back to IDLE state");
  23173. this.resetStartWhenNotLoaded((levels == null ? void 0 : levels[trackId]) || null);
  23174. this.state = State.IDLE;
  23175. }
  23176. break;
  23177. }
  23178. case State.WAITING_INIT_PTS: {
  23179. const waitingData = this.waitingData;
  23180. if (waitingData) {
  23181. const {
  23182. frag,
  23183. part,
  23184. cache,
  23185. complete
  23186. } = waitingData;
  23187. const mainAnchor = this.mainAnchor;
  23188. if (this.initPTS[frag.cc] !== void 0) {
  23189. this.waitingData = null;
  23190. this.state = State.FRAG_LOADING;
  23191. const payload = cache.flush().buffer;
  23192. const data = {
  23193. frag,
  23194. part,
  23195. payload,
  23196. networkDetails: null
  23197. };
  23198. this._handleFragmentLoadProgress(data);
  23199. if (complete) {
  23200. super._handleFragmentLoadComplete(data);
  23201. }
  23202. } else if (mainAnchor && mainAnchor.cc !== waitingData.frag.cc) {
  23203. this.syncWithAnchor(mainAnchor, waitingData.frag);
  23204. }
  23205. } else {
  23206. this.state = State.IDLE;
  23207. }
  23208. }
  23209. }
  23210. this.onTickEnd();
  23211. }
  23212. resetLoadingState() {
  23213. const waitingData = this.waitingData;
  23214. if (waitingData) {
  23215. this.fragmentTracker.removeFragment(waitingData.frag);
  23216. this.waitingData = null;
  23217. }
  23218. super.resetLoadingState();
  23219. }
  23220. onTickEnd() {
  23221. const {
  23222. media
  23223. } = this;
  23224. if (!(media != null && media.readyState)) {
  23225. return;
  23226. }
  23227. this.lastCurrentTime = media.currentTime;
  23228. }
  23229. doTickIdle() {
  23230. var _this$mainFragLoading2;
  23231. const {
  23232. hls,
  23233. levels,
  23234. media,
  23235. trackId
  23236. } = this;
  23237. const config = hls.config;
  23238. if (!this.buffering || !media && !this.primaryPrefetch && (this.startFragRequested || !config.startFragPrefetch) || !(levels != null && levels[trackId])) {
  23239. return;
  23240. }
  23241. const levelInfo = levels[trackId];
  23242. const trackDetails = levelInfo.details;
  23243. if (!trackDetails || this.waitForLive(levelInfo) || this.waitForCdnTuneIn(trackDetails)) {
  23244. this.state = State.WAITING_TRACK;
  23245. this.startFragRequested = false;
  23246. return;
  23247. }
  23248. const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;
  23249. if (this.bufferFlushed && bufferable) {
  23250. this.bufferFlushed = false;
  23251. this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO);
  23252. }
  23253. const bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO);
  23254. if (bufferInfo === null) {
  23255. return;
  23256. }
  23257. if (!this.switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {
  23258. hls.trigger(Events.BUFFER_EOS, {
  23259. type: "audio"
  23260. });
  23261. this.state = State.ENDED;
  23262. return;
  23263. }
  23264. const bufferLen = bufferInfo.len;
  23265. const maxBufLen = hls.maxBufferLength;
  23266. const fragments = trackDetails.fragments;
  23267. const start = fragments[0].start;
  23268. const loadPosition = this.getLoadPosition();
  23269. const targetBufferTime = this.flushing ? loadPosition : bufferInfo.end;
  23270. if (this.switchingTrack && media) {
  23271. const pos = loadPosition;
  23272. if (trackDetails.PTSKnown && pos < start) {
  23273. if (bufferInfo.end > start || bufferInfo.nextStart) {
  23274. this.log("Alt audio track ahead of main track, seek to start of alt audio track");
  23275. media.currentTime = start + 0.05;
  23276. }
  23277. }
  23278. }
  23279. if (bufferLen >= maxBufLen && !this.switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) {
  23280. return;
  23281. }
  23282. let frag = this.getNextFragment(targetBufferTime, trackDetails);
  23283. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  23284. frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  23285. }
  23286. if (!frag) {
  23287. this.bufferFlushed = true;
  23288. return;
  23289. }
  23290. let mainFragLoading = ((_this$mainFragLoading2 = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading2.frag) || null;
  23291. if (!this.audioOnly && this.startFragRequested && mainFragLoading && isMediaFragment(frag) && !frag.endList && (!trackDetails.live || !this.loadingParts && targetBufferTime < this.hls.liveSyncPosition)) {
  23292. if (this.fragmentTracker.getState(mainFragLoading) === FragmentState.OK) {
  23293. this.mainFragLoading = mainFragLoading = null;
  23294. }
  23295. if (mainFragLoading && isMediaFragment(mainFragLoading)) {
  23296. if (frag.start > mainFragLoading.end) {
  23297. const mainFragAtPos = this.fragmentTracker.getFragAtPos(targetBufferTime, PlaylistLevelType.MAIN);
  23298. if (mainFragAtPos && mainFragAtPos.end > mainFragLoading.end) {
  23299. mainFragLoading = mainFragAtPos;
  23300. this.mainFragLoading = {
  23301. frag: mainFragAtPos,
  23302. targetBufferTime: null
  23303. };
  23304. }
  23305. }
  23306. const atBufferSyncLimit = frag.start > mainFragLoading.end;
  23307. if (atBufferSyncLimit) {
  23308. return;
  23309. }
  23310. }
  23311. }
  23312. this.loadFragment(frag, levelInfo, targetBufferTime);
  23313. }
  23314. onMediaDetaching(event, data) {
  23315. this.bufferFlushed = this.flushing = false;
  23316. super.onMediaDetaching(event, data);
  23317. }
  23318. onAudioTracksUpdated(event, {
  23319. audioTracks
  23320. }) {
  23321. this.resetTransmuxer();
  23322. this.levels = audioTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
  23323. }
  23324. onAudioTrackSwitching(event, data) {
  23325. const altAudio = !!data.url;
  23326. this.trackId = data.id;
  23327. const {
  23328. fragCurrent
  23329. } = this;
  23330. if (fragCurrent) {
  23331. fragCurrent.abortRequests();
  23332. this.removeUnbufferedFrags(fragCurrent.start);
  23333. }
  23334. this.resetLoadingState();
  23335. if (altAudio) {
  23336. this.switchingTrack = data;
  23337. this.flushAudioIfNeeded(data);
  23338. if (this.state !== State.STOPPED) {
  23339. this.setInterval(TICK_INTERVAL$3);
  23340. this.state = State.IDLE;
  23341. this.tick();
  23342. }
  23343. } else {
  23344. this.resetTransmuxer();
  23345. this.switchingTrack = null;
  23346. this.bufferedTrack = data;
  23347. this.clearInterval();
  23348. }
  23349. }
  23350. onManifestLoading() {
  23351. super.onManifestLoading();
  23352. this.bufferFlushed = this.flushing = this.audioOnly = false;
  23353. this.resetItem();
  23354. this.trackId = -1;
  23355. }
  23356. onLevelLoaded(event, data) {
  23357. this.mainDetails = data.details;
  23358. const cachedTrackLoadedData = this.cachedTrackLoadedData;
  23359. if (cachedTrackLoadedData) {
  23360. this.cachedTrackLoadedData = null;
  23361. this.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED, cachedTrackLoadedData);
  23362. }
  23363. }
  23364. onAudioTrackLoaded(event, data) {
  23365. var _trackLevel$details;
  23366. const {
  23367. levels
  23368. } = this;
  23369. const {
  23370. details: newDetails,
  23371. id: trackId,
  23372. groupId,
  23373. track: track2
  23374. } = data;
  23375. if (!levels) {
  23376. this.warn(`Audio tracks reset while loading track ${trackId} "${track2.name}" of "${groupId}"`);
  23377. return;
  23378. }
  23379. const mainDetails = this.mainDetails;
  23380. if (!mainDetails || newDetails.endCC > mainDetails.endCC || mainDetails.expired) {
  23381. this.cachedTrackLoadedData = data;
  23382. if (this.state !== State.STOPPED) {
  23383. this.state = State.WAITING_TRACK;
  23384. }
  23385. return;
  23386. }
  23387. this.cachedTrackLoadedData = null;
  23388. this.log(`Audio track ${trackId} "${track2.name}" of "${groupId}" loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
  23389. const trackLevel = levels[trackId];
  23390. let sliding = 0;
  23391. if (newDetails.live || (_trackLevel$details = trackLevel.details) != null && _trackLevel$details.live) {
  23392. this.checkLiveUpdate(newDetails);
  23393. if (newDetails.deltaUpdateFailed) {
  23394. return;
  23395. }
  23396. if (trackLevel.details) {
  23397. var _this$levelLastLoaded;
  23398. sliding = this.alignPlaylists(newDetails, trackLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  23399. }
  23400. if (!newDetails.alignedSliding) {
  23401. alignDiscontinuities(newDetails, mainDetails);
  23402. if (!newDetails.alignedSliding) {
  23403. alignMediaPlaylistByPDT(newDetails, mainDetails);
  23404. }
  23405. sliding = newDetails.fragmentStart;
  23406. }
  23407. }
  23408. trackLevel.details = newDetails;
  23409. this.levelLastLoaded = trackLevel;
  23410. if (!this.startFragRequested) {
  23411. this.setStartPosition(mainDetails, sliding);
  23412. }
  23413. this.hls.trigger(Events.AUDIO_TRACK_UPDATED, {
  23414. details: newDetails,
  23415. id: trackId,
  23416. groupId: data.groupId
  23417. });
  23418. if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
  23419. this.state = State.IDLE;
  23420. }
  23421. this.tick();
  23422. }
  23423. _handleFragmentLoadProgress(data) {
  23424. var _frag$initSegment;
  23425. const frag = data.frag;
  23426. const {
  23427. part,
  23428. payload
  23429. } = data;
  23430. const {
  23431. config,
  23432. trackId,
  23433. levels
  23434. } = this;
  23435. if (!levels) {
  23436. this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  23437. return;
  23438. }
  23439. const track2 = levels[trackId];
  23440. if (!track2) {
  23441. this.warn("Audio track is undefined on fragment load progress");
  23442. return;
  23443. }
  23444. const details = track2.details;
  23445. if (!details) {
  23446. this.warn("Audio track details undefined on fragment load progress");
  23447. this.removeUnbufferedFrags(frag.start);
  23448. return;
  23449. }
  23450. const audioCodec = config.defaultAudioCodec || track2.audioCodec || "mp4a.40.2";
  23451. let transmuxer = this.transmuxer;
  23452. if (!transmuxer) {
  23453. transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  23454. }
  23455. const initPTS = this.initPTS[frag.cc];
  23456. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  23457. if (initPTS !== void 0) {
  23458. const accurateTimeOffset = false;
  23459. const partIndex = part ? part.index : -1;
  23460. const partial2 = partIndex !== -1;
  23461. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial2);
  23462. transmuxer.push(payload, initSegmentData, audioCodec, "", frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  23463. } else {
  23464. this.log(`Unknown video PTS for cc ${frag.cc}, waiting for video PTS before demuxing audio frag ${frag.sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
  23465. const {
  23466. cache
  23467. } = this.waitingData = this.waitingData || {
  23468. frag,
  23469. part,
  23470. cache: new ChunkCache(),
  23471. complete: false
  23472. };
  23473. cache.push(new Uint8Array(payload));
  23474. if (this.state !== State.STOPPED) {
  23475. this.state = State.WAITING_INIT_PTS;
  23476. }
  23477. }
  23478. }
  23479. _handleFragmentLoadComplete(fragLoadedData) {
  23480. if (this.waitingData) {
  23481. this.waitingData.complete = true;
  23482. return;
  23483. }
  23484. super._handleFragmentLoadComplete(fragLoadedData);
  23485. }
  23486. onBufferReset() {
  23487. this.mediaBuffer = null;
  23488. }
  23489. onBufferCreated(event, data) {
  23490. this.bufferFlushed = this.flushing = false;
  23491. const audioTrack = data.tracks.audio;
  23492. if (audioTrack) {
  23493. this.mediaBuffer = audioTrack.buffer || null;
  23494. }
  23495. }
  23496. onFragLoading(event, data) {
  23497. if (!this.audioOnly && data.frag.type === PlaylistLevelType.MAIN && isMediaFragment(data.frag)) {
  23498. this.mainFragLoading = data;
  23499. if (this.state === State.IDLE) {
  23500. this.tick();
  23501. }
  23502. }
  23503. }
  23504. onFragBuffered(event, data) {
  23505. const {
  23506. frag,
  23507. part
  23508. } = data;
  23509. if (frag.type !== PlaylistLevelType.AUDIO) {
  23510. if (!this.audioOnly && frag.type === PlaylistLevelType.MAIN && !frag.elementaryStreams.video && !frag.elementaryStreams.audiovideo) {
  23511. this.audioOnly = true;
  23512. this.mainFragLoading = null;
  23513. }
  23514. return;
  23515. }
  23516. if (this.fragContextChanged(frag)) {
  23517. this.warn(`Fragment ${frag.sn}${part ? " p: " + part.index : ""} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack ? this.switchingTrack.name : "false"}`);
  23518. return;
  23519. }
  23520. if (isMediaFragment(frag)) {
  23521. this.fragPrevious = frag;
  23522. const track2 = this.switchingTrack;
  23523. if (track2) {
  23524. this.bufferedTrack = track2;
  23525. this.switchingTrack = null;
  23526. this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, track2));
  23527. }
  23528. }
  23529. this.fragBufferedComplete(frag, part);
  23530. if (this.media) {
  23531. this.tick();
  23532. }
  23533. }
  23534. onError(event, data) {
  23535. var _data$context;
  23536. if (data.fatal) {
  23537. this.state = State.ERROR;
  23538. return;
  23539. }
  23540. switch (data.details) {
  23541. case ErrorDetails.FRAG_GAP:
  23542. case ErrorDetails.FRAG_PARSING_ERROR:
  23543. case ErrorDetails.FRAG_DECRYPT_ERROR:
  23544. case ErrorDetails.FRAG_LOAD_ERROR:
  23545. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  23546. case ErrorDetails.KEY_LOAD_ERROR:
  23547. case ErrorDetails.KEY_LOAD_TIMEOUT:
  23548. this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);
  23549. break;
  23550. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  23551. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  23552. case ErrorDetails.LEVEL_PARSING_ERROR:
  23553. if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) {
  23554. this.state = State.IDLE;
  23555. }
  23556. break;
  23557. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  23558. case ErrorDetails.BUFFER_APPEND_ERROR:
  23559. if (data.parent !== "audio") {
  23560. return;
  23561. }
  23562. if (!this.reduceLengthAndFlushBuffer(data)) {
  23563. this.resetLoadingState();
  23564. }
  23565. break;
  23566. case ErrorDetails.BUFFER_FULL_ERROR:
  23567. if (data.parent !== "audio") {
  23568. return;
  23569. }
  23570. if (this.reduceLengthAndFlushBuffer(data)) {
  23571. this.bufferedTrack = null;
  23572. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
  23573. }
  23574. break;
  23575. case ErrorDetails.INTERNAL_EXCEPTION:
  23576. this.recoverWorkerError(data);
  23577. break;
  23578. }
  23579. }
  23580. onBufferFlushing(event, {
  23581. type
  23582. }) {
  23583. if (type !== ElementaryStreamTypes.VIDEO) {
  23584. this.flushing = true;
  23585. }
  23586. }
  23587. onBufferFlushed(event, {
  23588. type
  23589. }) {
  23590. if (type !== ElementaryStreamTypes.VIDEO) {
  23591. this.flushing = false;
  23592. this.bufferFlushed = true;
  23593. if (this.state === State.ENDED) {
  23594. this.state = State.IDLE;
  23595. }
  23596. const mediaBuffer = this.mediaBuffer || this.media;
  23597. if (mediaBuffer) {
  23598. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO);
  23599. this.tick();
  23600. }
  23601. }
  23602. }
  23603. _handleTransmuxComplete(transmuxResult) {
  23604. var _id3$samples;
  23605. const id = "audio";
  23606. const {
  23607. hls
  23608. } = this;
  23609. const {
  23610. remuxResult,
  23611. chunkMeta
  23612. } = transmuxResult;
  23613. const context = this.getCurrentContext(chunkMeta);
  23614. if (!context) {
  23615. this.resetWhenMissingContext(chunkMeta);
  23616. return;
  23617. }
  23618. const {
  23619. frag,
  23620. part,
  23621. level
  23622. } = context;
  23623. const {
  23624. details
  23625. } = level;
  23626. const {
  23627. audio,
  23628. text,
  23629. id3,
  23630. initSegment
  23631. } = remuxResult;
  23632. if (this.fragContextChanged(frag) || !details) {
  23633. this.fragmentTracker.removeFragment(frag);
  23634. return;
  23635. }
  23636. this.state = State.PARSING;
  23637. if (this.switchingTrack && audio) {
  23638. this.completeAudioSwitch(this.switchingTrack);
  23639. }
  23640. if (initSegment != null && initSegment.tracks) {
  23641. const mapFragment = frag.initSegment || frag;
  23642. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  23643. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  23644. frag: mapFragment,
  23645. id,
  23646. tracks: initSegment.tracks
  23647. });
  23648. }
  23649. if (audio) {
  23650. const {
  23651. startPTS,
  23652. endPTS,
  23653. startDTS,
  23654. endDTS
  23655. } = audio;
  23656. if (part) {
  23657. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  23658. startPTS,
  23659. endPTS,
  23660. startDTS,
  23661. endDTS
  23662. };
  23663. }
  23664. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  23665. this.bufferFragmentData(audio, frag, part, chunkMeta);
  23666. }
  23667. if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  23668. const emittedID3 = _extends({
  23669. id,
  23670. frag,
  23671. details
  23672. }, id3);
  23673. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  23674. }
  23675. if (text) {
  23676. const emittedText = _extends({
  23677. id,
  23678. frag,
  23679. details
  23680. }, text);
  23681. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  23682. }
  23683. }
  23684. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  23685. if (this.state !== State.PARSING) {
  23686. return;
  23687. }
  23688. if (tracks.video) {
  23689. delete tracks.video;
  23690. }
  23691. if (tracks.audiovideo) {
  23692. delete tracks.audiovideo;
  23693. }
  23694. if (!tracks.audio) {
  23695. return;
  23696. }
  23697. const track2 = tracks.audio;
  23698. track2.id = PlaylistLevelType.AUDIO;
  23699. const variantAudioCodecs = currentLevel.audioCodec;
  23700. this.log(`Init audio buffer, container:${track2.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track2.codec}]`);
  23701. if (variantAudioCodecs && variantAudioCodecs.split(",").length === 1) {
  23702. track2.levelCodec = variantAudioCodecs;
  23703. }
  23704. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  23705. const initSegment = track2.initSegment;
  23706. if (initSegment != null && initSegment.byteLength) {
  23707. const segment = {
  23708. type: "audio",
  23709. frag,
  23710. part: null,
  23711. chunkMeta,
  23712. parent: frag.type,
  23713. data: initSegment
  23714. };
  23715. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  23716. }
  23717. this.tickImmediate();
  23718. }
  23719. loadFragment(frag, track2, targetBufferTime) {
  23720. const fragState = this.fragmentTracker.getState(frag);
  23721. if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  23722. var _track$details;
  23723. if (!isMediaFragment(frag)) {
  23724. this._loadInitSegment(frag, track2);
  23725. } else if ((_track$details = track2.details) != null && _track$details.live && !this.initPTS[frag.cc]) {
  23726. this.log(`Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`);
  23727. this.state = State.WAITING_INIT_PTS;
  23728. const mainDetails = this.mainDetails;
  23729. if (mainDetails && mainDetails.fragmentStart !== track2.details.fragmentStart) {
  23730. alignMediaPlaylistByPDT(track2.details, mainDetails);
  23731. }
  23732. } else {
  23733. super.loadFragment(frag, track2, targetBufferTime);
  23734. }
  23735. } else {
  23736. this.clearTrackerIfNeeded(frag);
  23737. }
  23738. }
  23739. flushAudioIfNeeded(switchingTrack) {
  23740. if (this.media && this.bufferedTrack) {
  23741. const {
  23742. name,
  23743. lang,
  23744. assocLang,
  23745. characteristics,
  23746. audioCodec,
  23747. channels
  23748. } = this.bufferedTrack;
  23749. if (!matchesOption({
  23750. name,
  23751. lang,
  23752. assocLang,
  23753. characteristics,
  23754. audioCodec,
  23755. channels
  23756. }, switchingTrack, audioMatchPredicate)) {
  23757. if (useAlternateAudio(switchingTrack.url, this.hls)) {
  23758. this.log("Switching audio track : flushing all audio");
  23759. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
  23760. this.bufferedTrack = null;
  23761. } else {
  23762. this.bufferedTrack = switchingTrack;
  23763. }
  23764. }
  23765. }
  23766. }
  23767. completeAudioSwitch(switchingTrack) {
  23768. const {
  23769. hls
  23770. } = this;
  23771. this.flushAudioIfNeeded(switchingTrack);
  23772. this.bufferedTrack = switchingTrack;
  23773. this.switchingTrack = null;
  23774. hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, switchingTrack));
  23775. }
  23776. }
  23777. class BasePlaylistController extends Logger {
  23778. constructor(hls, logPrefix) {
  23779. super(logPrefix, hls.logger);
  23780. this.hls = void 0;
  23781. this.canLoad = false;
  23782. this.timer = -1;
  23783. this.hls = hls;
  23784. }
  23785. destroy() {
  23786. this.clearTimer();
  23787. this.hls = this.log = this.warn = null;
  23788. }
  23789. clearTimer() {
  23790. if (this.timer !== -1) {
  23791. self.clearTimeout(this.timer);
  23792. this.timer = -1;
  23793. }
  23794. }
  23795. startLoad() {
  23796. this.canLoad = true;
  23797. this.loadPlaylist();
  23798. }
  23799. stopLoad() {
  23800. this.canLoad = false;
  23801. this.clearTimer();
  23802. }
  23803. switchParams(playlistUri, previous, current) {
  23804. const renditionReports = previous == null ? void 0 : previous.renditionReports;
  23805. if (renditionReports) {
  23806. let foundIndex = -1;
  23807. for (let i2 = 0; i2 < renditionReports.length; i2++) {
  23808. const attr = renditionReports[i2];
  23809. let uri;
  23810. try {
  23811. uri = new self.URL(attr.URI, previous.url).href;
  23812. } catch (error) {
  23813. this.warn(`Could not construct new URL for Rendition Report: ${error}`);
  23814. uri = attr.URI || "";
  23815. }
  23816. if (uri === playlistUri) {
  23817. foundIndex = i2;
  23818. break;
  23819. } else if (uri === playlistUri.substring(0, uri.length)) {
  23820. foundIndex = i2;
  23821. }
  23822. }
  23823. if (foundIndex !== -1) {
  23824. const attr = renditionReports[foundIndex];
  23825. const msn = parseInt(attr["LAST-MSN"]) || (previous == null ? void 0 : previous.lastPartSn);
  23826. let part = parseInt(attr["LAST-PART"]) || (previous == null ? void 0 : previous.lastPartIndex);
  23827. if (this.hls.config.lowLatencyMode) {
  23828. const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  23829. if (part >= 0 && currentGoal > previous.partTarget) {
  23830. part += 1;
  23831. }
  23832. }
  23833. const skip = current && getSkipValue(current);
  23834. return new HlsUrlParameters(msn, part >= 0 ? part : void 0, skip);
  23835. }
  23836. }
  23837. }
  23838. loadPlaylist(hlsUrlParameters) {
  23839. this.clearTimer();
  23840. }
  23841. loadingPlaylist(playlist, hlsUrlParameters) {
  23842. this.clearTimer();
  23843. }
  23844. shouldLoadPlaylist(playlist) {
  23845. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  23846. }
  23847. getUrlWithDirectives(uri, hlsUrlParameters) {
  23848. if (hlsUrlParameters) {
  23849. try {
  23850. return hlsUrlParameters.addDirectives(uri);
  23851. } catch (error) {
  23852. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  23853. }
  23854. }
  23855. return uri;
  23856. }
  23857. playlistLoaded(index2, data, previousDetails) {
  23858. const {
  23859. details,
  23860. stats
  23861. } = data;
  23862. const now2 = self.performance.now();
  23863. const elapsed = stats.loading.first ? Math.max(0, now2 - stats.loading.first) : 0;
  23864. details.advancedDateTime = Date.now() - elapsed;
  23865. const timelineOffset = this.hls.config.timelineOffset;
  23866. if (timelineOffset !== details.appliedTimelineOffset) {
  23867. const offset = Math.max(timelineOffset || 0, 0);
  23868. details.appliedTimelineOffset = offset;
  23869. details.fragments.forEach((frag) => {
  23870. frag.start = frag.playlistOffset + offset;
  23871. });
  23872. }
  23873. if (details.live || previousDetails != null && previousDetails.live) {
  23874. const levelOrTrack = "levelInfo" in data ? data.levelInfo : data.track;
  23875. details.reloaded(previousDetails);
  23876. if (previousDetails && details.fragments.length > 0) {
  23877. mergeDetails(previousDetails, details);
  23878. const error = details.playlistParsingError;
  23879. if (error) {
  23880. this.warn(error);
  23881. const hls = this.hls;
  23882. if (!hls.config.ignorePlaylistParsingErrors) {
  23883. var _details$fragments$;
  23884. const {
  23885. networkDetails
  23886. } = data;
  23887. hls.trigger(Events.ERROR, {
  23888. type: ErrorTypes.NETWORK_ERROR,
  23889. details: ErrorDetails.LEVEL_PARSING_ERROR,
  23890. fatal: false,
  23891. url: details.url,
  23892. error,
  23893. reason: error.message,
  23894. level: data.level || void 0,
  23895. parent: (_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.type,
  23896. networkDetails,
  23897. stats
  23898. });
  23899. return;
  23900. }
  23901. details.playlistParsingError = null;
  23902. }
  23903. }
  23904. if (details.requestScheduled === -1) {
  23905. details.requestScheduled = stats.loading.start;
  23906. }
  23907. const bufferInfo = this.hls.mainForwardBufferInfo;
  23908. const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  23909. const distanceToLiveEdgeMs = (details.edge - position) * 1e3;
  23910. const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  23911. if (details.requestScheduled + reloadInterval < now2) {
  23912. details.requestScheduled = now2;
  23913. } else {
  23914. details.requestScheduled += reloadInterval;
  23915. }
  23916. this.log(`live playlist ${index2} ${details.advanced ? "REFRESHED " + details.lastPartSn + "-" + details.lastPartIndex : details.updated ? "UPDATED" : "MISSED"}`);
  23917. if (!this.canLoad || !details.live) {
  23918. return;
  23919. }
  23920. let deliveryDirectives;
  23921. let msn = void 0;
  23922. let part = void 0;
  23923. if (details.canBlockReload && details.endSN && details.advanced) {
  23924. const lowLatencyMode = this.hls.config.lowLatencyMode;
  23925. const lastPartSn = details.lastPartSn;
  23926. const endSn = details.endSN;
  23927. const lastPartIndex = details.lastPartIndex;
  23928. const hasParts = lastPartIndex !== -1;
  23929. const atLastPartOfSegment = lastPartSn === endSn;
  23930. if (hasParts) {
  23931. if (atLastPartOfSegment) {
  23932. msn = endSn + 1;
  23933. part = lowLatencyMode ? 0 : lastPartIndex;
  23934. } else {
  23935. msn = lastPartSn;
  23936. part = lowLatencyMode ? lastPartIndex + 1 : details.maxPartIndex;
  23937. }
  23938. } else {
  23939. msn = endSn + 1;
  23940. }
  23941. const lastAdvanced = details.age;
  23942. const cdnAge = lastAdvanced + details.ageHeader;
  23943. let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  23944. if (currentGoal > 0) {
  23945. if (cdnAge > details.targetduration * 3) {
  23946. this.log(`Playlist last advanced ${lastAdvanced.toFixed(2)}s ago. Omitting segment and part directives.`);
  23947. msn = void 0;
  23948. part = void 0;
  23949. } else if (previousDetails != null && previousDetails.tuneInGoal && cdnAge - details.partTarget > previousDetails.tuneInGoal) {
  23950. this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);
  23951. currentGoal = 0;
  23952. } else {
  23953. const segments = Math.floor(currentGoal / details.targetduration);
  23954. msn += segments;
  23955. if (part !== void 0) {
  23956. const parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  23957. part += parts;
  23958. }
  23959. this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);
  23960. }
  23961. details.tuneInGoal = currentGoal;
  23962. }
  23963. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  23964. if (lowLatencyMode || !atLastPartOfSegment) {
  23965. details.requestScheduled = now2;
  23966. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  23967. return;
  23968. }
  23969. } else if (details.canBlockReload || details.canSkipUntil) {
  23970. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  23971. }
  23972. if (deliveryDirectives && msn !== void 0 && details.canBlockReload) {
  23973. details.requestScheduled = stats.loading.first + Math.max(reloadInterval - elapsed * 2, reloadInterval / 2);
  23974. }
  23975. this.scheduleLoading(levelOrTrack, deliveryDirectives, details);
  23976. } else {
  23977. this.clearTimer();
  23978. }
  23979. }
  23980. scheduleLoading(levelOrTrack, deliveryDirectives, updatedDetails) {
  23981. const details = updatedDetails || levelOrTrack.details;
  23982. if (!details) {
  23983. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  23984. return;
  23985. }
  23986. const now2 = self.performance.now();
  23987. const requestScheduled = details.requestScheduled;
  23988. if (now2 >= requestScheduled) {
  23989. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  23990. return;
  23991. }
  23992. const estimatedTimeUntilUpdate = requestScheduled - now2;
  23993. this.log(`reload live playlist ${levelOrTrack.name || levelOrTrack.bitrate + "bps"} in ${Math.round(estimatedTimeUntilUpdate)} ms`);
  23994. this.clearTimer();
  23995. this.timer = self.setTimeout(() => this.loadingPlaylist(levelOrTrack, deliveryDirectives), estimatedTimeUntilUpdate);
  23996. }
  23997. getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  23998. let skip = getSkipValue(details);
  23999. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  24000. msn = previousDeliveryDirectives.msn;
  24001. part = previousDeliveryDirectives.part;
  24002. skip = HlsSkip.No;
  24003. }
  24004. return new HlsUrlParameters(msn, part, skip);
  24005. }
  24006. checkRetry(errorEvent) {
  24007. const errorDetails = errorEvent.details;
  24008. const isTimeout = isTimeoutError(errorEvent);
  24009. const errorAction = errorEvent.errorAction;
  24010. const {
  24011. action,
  24012. retryCount = 0,
  24013. retryConfig
  24014. } = errorAction || {};
  24015. const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  24016. if (retry) {
  24017. var _errorEvent$context;
  24018. if (retryCount >= retryConfig.maxNumRetry) {
  24019. return false;
  24020. }
  24021. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  24022. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`);
  24023. this.loadPlaylist();
  24024. } else {
  24025. const delay = getRetryDelay(retryConfig, retryCount);
  24026. this.clearTimer();
  24027. this.timer = self.setTimeout(() => this.loadPlaylist(), delay);
  24028. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay}ms`);
  24029. }
  24030. errorEvent.levelRetry = true;
  24031. errorAction.resolved = true;
  24032. }
  24033. return retry;
  24034. }
  24035. }
  24036. function subtitleOptionsIdentical(trackList1, trackList2) {
  24037. if (trackList1.length !== trackList2.length) {
  24038. return false;
  24039. }
  24040. for (let i2 = 0; i2 < trackList1.length; i2++) {
  24041. if (!mediaAttributesIdentical(trackList1[i2].attrs, trackList2[i2].attrs)) {
  24042. return false;
  24043. }
  24044. }
  24045. return true;
  24046. }
  24047. function mediaAttributesIdentical(attrs1, attrs2, customAttributes) {
  24048. const stableRenditionId = attrs1["STABLE-RENDITION-ID"];
  24049. if (stableRenditionId && !customAttributes) {
  24050. return stableRenditionId === attrs2["STABLE-RENDITION-ID"];
  24051. }
  24052. return !(customAttributes || ["LANGUAGE", "NAME", "CHARACTERISTICS", "AUTOSELECT", "DEFAULT", "FORCED", "ASSOC-LANGUAGE"]).some((subtitleAttribute) => attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]);
  24053. }
  24054. function subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) {
  24055. return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || "").toLowerCase());
  24056. }
  24057. class AudioTrackController extends BasePlaylistController {
  24058. constructor(hls) {
  24059. super(hls, "audio-track-controller");
  24060. this.tracks = [];
  24061. this.groupIds = null;
  24062. this.tracksInGroup = [];
  24063. this.trackId = -1;
  24064. this.currentTrack = null;
  24065. this.selectDefaultTrack = true;
  24066. this.registerListeners();
  24067. }
  24068. registerListeners() {
  24069. const {
  24070. hls
  24071. } = this;
  24072. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24073. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  24074. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  24075. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  24076. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  24077. hls.on(Events.ERROR, this.onError, this);
  24078. }
  24079. unregisterListeners() {
  24080. const {
  24081. hls
  24082. } = this;
  24083. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24084. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  24085. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  24086. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  24087. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  24088. hls.off(Events.ERROR, this.onError, this);
  24089. }
  24090. destroy() {
  24091. this.unregisterListeners();
  24092. this.tracks.length = 0;
  24093. this.tracksInGroup.length = 0;
  24094. this.currentTrack = null;
  24095. super.destroy();
  24096. }
  24097. onManifestLoading() {
  24098. this.tracks = [];
  24099. this.tracksInGroup = [];
  24100. this.groupIds = null;
  24101. this.currentTrack = null;
  24102. this.trackId = -1;
  24103. this.selectDefaultTrack = true;
  24104. }
  24105. onManifestParsed(event, data) {
  24106. this.tracks = data.audioTracks || [];
  24107. }
  24108. onAudioTrackLoaded(event, data) {
  24109. const {
  24110. id,
  24111. groupId,
  24112. details
  24113. } = data;
  24114. const trackInActiveGroup = this.tracksInGroup[id];
  24115. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  24116. this.warn(`Audio track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  24117. return;
  24118. }
  24119. const curDetails = trackInActiveGroup.details;
  24120. trackInActiveGroup.details = data.details;
  24121. this.log(`Audio track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  24122. if (id === this.trackId) {
  24123. this.playlistLoaded(id, data, curDetails);
  24124. }
  24125. }
  24126. onLevelLoading(event, data) {
  24127. this.switchLevel(data.level);
  24128. }
  24129. onLevelSwitching(event, data) {
  24130. this.switchLevel(data.level);
  24131. }
  24132. switchLevel(levelIndex) {
  24133. const levelInfo = this.hls.levels[levelIndex];
  24134. if (!levelInfo) {
  24135. return;
  24136. }
  24137. const audioGroups = levelInfo.audioGroups || null;
  24138. const currentGroups = this.groupIds;
  24139. let currentTrack = this.currentTrack;
  24140. if (!audioGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (audioGroups == null ? void 0 : audioGroups.length) || audioGroups != null && audioGroups.some((groupId) => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) {
  24141. this.groupIds = audioGroups;
  24142. this.trackId = -1;
  24143. this.currentTrack = null;
  24144. const audioTracks = this.tracks.filter((track2) => !audioGroups || audioGroups.indexOf(track2.groupId) !== -1);
  24145. if (audioTracks.length) {
  24146. if (this.selectDefaultTrack && !audioTracks.some((track2) => track2.default)) {
  24147. this.selectDefaultTrack = false;
  24148. }
  24149. audioTracks.forEach((track2, i2) => {
  24150. track2.id = i2;
  24151. });
  24152. } else if (!currentTrack && !this.tracksInGroup.length) {
  24153. return;
  24154. }
  24155. this.tracksInGroup = audioTracks;
  24156. const audioPreference = this.hls.config.audioPreference;
  24157. if (!currentTrack && audioPreference) {
  24158. const groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate);
  24159. if (groupIndex > -1) {
  24160. currentTrack = audioTracks[groupIndex];
  24161. } else {
  24162. const allIndex = findMatchingOption(audioPreference, this.tracks);
  24163. currentTrack = this.tracks[allIndex];
  24164. }
  24165. }
  24166. let trackId = this.findTrackId(currentTrack);
  24167. if (trackId === -1 && currentTrack) {
  24168. trackId = this.findTrackId(null);
  24169. }
  24170. const audioTracksUpdated = {
  24171. audioTracks
  24172. };
  24173. this.log(`Updating audio tracks, ${audioTracks.length} track(s) found in group(s): ${audioGroups == null ? void 0 : audioGroups.join(",")}`);
  24174. this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);
  24175. const selectedTrackId = this.trackId;
  24176. if (trackId !== -1 && selectedTrackId === -1) {
  24177. this.setAudioTrack(trackId);
  24178. } else if (audioTracks.length && selectedTrackId === -1) {
  24179. var _this$groupIds;
  24180. const error = new Error(`No audio track selected for current audio group-ID(s): ${(_this$groupIds = this.groupIds) == null ? void 0 : _this$groupIds.join(",")} track count: ${audioTracks.length}`);
  24181. this.warn(error.message);
  24182. this.hls.trigger(Events.ERROR, {
  24183. type: ErrorTypes.MEDIA_ERROR,
  24184. details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  24185. fatal: true,
  24186. error
  24187. });
  24188. }
  24189. }
  24190. }
  24191. onError(event, data) {
  24192. if (data.fatal || !data.context) {
  24193. return;
  24194. }
  24195. if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  24196. this.checkRetry(data);
  24197. }
  24198. }
  24199. get allAudioTracks() {
  24200. return this.tracks;
  24201. }
  24202. get audioTracks() {
  24203. return this.tracksInGroup;
  24204. }
  24205. get audioTrack() {
  24206. return this.trackId;
  24207. }
  24208. set audioTrack(newId) {
  24209. this.selectDefaultTrack = false;
  24210. this.setAudioTrack(newId);
  24211. }
  24212. setAudioOption(audioOption) {
  24213. const hls = this.hls;
  24214. hls.config.audioPreference = audioOption;
  24215. if (audioOption) {
  24216. const allAudioTracks = this.allAudioTracks;
  24217. this.selectDefaultTrack = false;
  24218. if (allAudioTracks.length) {
  24219. const currentTrack = this.currentTrack;
  24220. if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) {
  24221. return currentTrack;
  24222. }
  24223. const groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate);
  24224. if (groupIndex > -1) {
  24225. const track2 = this.tracksInGroup[groupIndex];
  24226. this.setAudioTrack(groupIndex);
  24227. return track2;
  24228. } else if (currentTrack) {
  24229. let searchIndex = hls.loadLevel;
  24230. if (searchIndex === -1) {
  24231. searchIndex = hls.firstAutoLevel;
  24232. }
  24233. const switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate);
  24234. if (switchIndex === -1) {
  24235. return null;
  24236. }
  24237. hls.nextLoadLevel = switchIndex;
  24238. }
  24239. if (audioOption.channels || audioOption.audioCodec) {
  24240. const withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks);
  24241. if (withoutCodecAndChannelsMatch > -1) {
  24242. return allAudioTracks[withoutCodecAndChannelsMatch];
  24243. }
  24244. }
  24245. }
  24246. }
  24247. return null;
  24248. }
  24249. setAudioTrack(newId) {
  24250. const tracks = this.tracksInGroup;
  24251. if (newId < 0 || newId >= tracks.length) {
  24252. this.warn(`Invalid audio track id: ${newId}`);
  24253. return;
  24254. }
  24255. this.selectDefaultTrack = false;
  24256. const lastTrack = this.currentTrack;
  24257. const track2 = tracks[newId];
  24258. const trackLoaded = track2.details && !track2.details.live;
  24259. if (newId === this.trackId && track2 === lastTrack && trackLoaded) {
  24260. return;
  24261. }
  24262. this.log(`Switching to audio-track ${newId} "${track2.name}" lang:${track2.lang} group:${track2.groupId} channels:${track2.channels}`);
  24263. this.trackId = newId;
  24264. this.currentTrack = track2;
  24265. this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread2({}, track2));
  24266. if (trackLoaded) {
  24267. return;
  24268. }
  24269. const hlsUrlParameters = this.switchParams(track2.url, lastTrack == null ? void 0 : lastTrack.details, track2.details);
  24270. this.loadPlaylist(hlsUrlParameters);
  24271. }
  24272. findTrackId(currentTrack) {
  24273. const audioTracks = this.tracksInGroup;
  24274. for (let i2 = 0; i2 < audioTracks.length; i2++) {
  24275. const track2 = audioTracks[i2];
  24276. if (this.selectDefaultTrack && !track2.default) {
  24277. continue;
  24278. }
  24279. if (!currentTrack || matchesOption(currentTrack, track2, audioMatchPredicate)) {
  24280. return i2;
  24281. }
  24282. }
  24283. if (currentTrack) {
  24284. const {
  24285. name,
  24286. lang,
  24287. assocLang,
  24288. characteristics,
  24289. audioCodec,
  24290. channels
  24291. } = currentTrack;
  24292. for (let i2 = 0; i2 < audioTracks.length; i2++) {
  24293. const track2 = audioTracks[i2];
  24294. if (matchesOption({
  24295. name,
  24296. lang,
  24297. assocLang,
  24298. characteristics,
  24299. audioCodec,
  24300. channels
  24301. }, track2, audioMatchPredicate)) {
  24302. return i2;
  24303. }
  24304. }
  24305. for (let i2 = 0; i2 < audioTracks.length; i2++) {
  24306. const track2 = audioTracks[i2];
  24307. if (mediaAttributesIdentical(currentTrack.attrs, track2.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
  24308. return i2;
  24309. }
  24310. }
  24311. for (let i2 = 0; i2 < audioTracks.length; i2++) {
  24312. const track2 = audioTracks[i2];
  24313. if (mediaAttributesIdentical(currentTrack.attrs, track2.attrs, ["LANGUAGE"])) {
  24314. return i2;
  24315. }
  24316. }
  24317. }
  24318. return -1;
  24319. }
  24320. loadPlaylist(hlsUrlParameters) {
  24321. super.loadPlaylist();
  24322. const audioTrack = this.currentTrack;
  24323. if (!this.shouldLoadPlaylist(audioTrack)) {
  24324. return;
  24325. }
  24326. if (useAlternateAudio(audioTrack.url, this.hls)) {
  24327. this.scheduleLoading(audioTrack, hlsUrlParameters);
  24328. }
  24329. }
  24330. loadingPlaylist(audioTrack, hlsUrlParameters) {
  24331. super.loadingPlaylist(audioTrack, hlsUrlParameters);
  24332. const id = audioTrack.id;
  24333. const groupId = audioTrack.groupId;
  24334. const url = this.getUrlWithDirectives(audioTrack.url, hlsUrlParameters);
  24335. const details = audioTrack.details;
  24336. const age = details == null ? void 0 : details.age;
  24337. this.log(`Loading audio-track ${id} "${audioTrack.name}" lang:${audioTrack.lang} group:${groupId}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== void 0 ? " at sn " + hlsUrlParameters.msn + " part " + hlsUrlParameters.part : ""}${age && details.live ? " age " + age.toFixed(1) + (details.type ? " " + details.type || "" : "") : ""} ${url}`);
  24338. this.hls.trigger(Events.AUDIO_TRACK_LOADING, {
  24339. url,
  24340. id,
  24341. groupId,
  24342. deliveryDirectives: hlsUrlParameters || null,
  24343. track: audioTrack
  24344. });
  24345. }
  24346. }
  24347. class BufferOperationQueue {
  24348. constructor(sourceBufferReference) {
  24349. this.tracks = void 0;
  24350. this.queues = {
  24351. video: [],
  24352. audio: [],
  24353. audiovideo: []
  24354. };
  24355. this.tracks = sourceBufferReference;
  24356. }
  24357. destroy() {
  24358. this.tracks = this.queues = null;
  24359. }
  24360. append(operation, type, pending) {
  24361. if (this.queues === null || this.tracks === null) {
  24362. return;
  24363. }
  24364. const queue2 = this.queues[type];
  24365. queue2.push(operation);
  24366. if (queue2.length === 1 && !pending) {
  24367. this.executeNext(type);
  24368. }
  24369. }
  24370. appendBlocker(type) {
  24371. return new Promise((resolve2) => {
  24372. const operation = {
  24373. label: "async-blocker",
  24374. execute: resolve2,
  24375. onStart: () => {
  24376. },
  24377. onComplete: () => {
  24378. },
  24379. onError: () => {
  24380. }
  24381. };
  24382. this.append(operation, type);
  24383. });
  24384. }
  24385. prependBlocker(type) {
  24386. return new Promise((resolve2) => {
  24387. if (this.queues) {
  24388. const operation = {
  24389. label: "async-blocker-prepend",
  24390. execute: resolve2,
  24391. onStart: () => {
  24392. },
  24393. onComplete: () => {
  24394. },
  24395. onError: () => {
  24396. }
  24397. };
  24398. this.queues[type].unshift(operation);
  24399. }
  24400. });
  24401. }
  24402. removeBlockers() {
  24403. if (this.queues === null) {
  24404. return;
  24405. }
  24406. [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach((queue2) => {
  24407. var _queue$;
  24408. const label = (_queue$ = queue2[0]) == null ? void 0 : _queue$.label;
  24409. if (label === "async-blocker" || label === "async-blocker-prepend") {
  24410. queue2[0].execute();
  24411. queue2.splice(0, 1);
  24412. }
  24413. });
  24414. }
  24415. unblockAudio(op) {
  24416. if (this.queues === null) {
  24417. return;
  24418. }
  24419. const queue2 = this.queues.audio;
  24420. if (queue2[0] === op) {
  24421. this.shiftAndExecuteNext("audio");
  24422. }
  24423. }
  24424. executeNext(type) {
  24425. if (this.queues === null || this.tracks === null) {
  24426. return;
  24427. }
  24428. const queue2 = this.queues[type];
  24429. if (queue2.length) {
  24430. const operation = queue2[0];
  24431. try {
  24432. operation.execute();
  24433. } catch (error) {
  24434. var _this$tracks$type;
  24435. operation.onError(error);
  24436. if (this.queues === null || this.tracks === null) {
  24437. return;
  24438. }
  24439. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  24440. if (!(sb != null && sb.updating)) {
  24441. this.shiftAndExecuteNext(type);
  24442. }
  24443. }
  24444. }
  24445. }
  24446. shiftAndExecuteNext(type) {
  24447. if (this.queues === null) {
  24448. return;
  24449. }
  24450. this.queues[type].shift();
  24451. this.executeNext(type);
  24452. }
  24453. current(type) {
  24454. var _this$queues;
  24455. return ((_this$queues = this.queues) == null ? void 0 : _this$queues[type][0]) || null;
  24456. }
  24457. toString() {
  24458. const {
  24459. queues,
  24460. tracks
  24461. } = this;
  24462. if (queues === null || tracks === null) {
  24463. return `<destroyed>`;
  24464. }
  24465. return `
  24466. ${this.list("video")}
  24467. ${this.list("audio")}
  24468. ${this.list("audiovideo")}}`;
  24469. }
  24470. list(type) {
  24471. var _this$queues2, _this$tracks;
  24472. return (_this$queues2 = this.queues) != null && _this$queues2[type] || (_this$tracks = this.tracks) != null && _this$tracks[type] ? `${type}: (${this.listSbInfo(type)}) ${this.listOps(type)}` : "";
  24473. }
  24474. listSbInfo(type) {
  24475. var _this$tracks2;
  24476. const track2 = (_this$tracks2 = this.tracks) == null ? void 0 : _this$tracks2[type];
  24477. const sb = track2 == null ? void 0 : track2.buffer;
  24478. if (!sb) {
  24479. return "none";
  24480. }
  24481. return `SourceBuffer${sb.updating ? " updating" : ""}${track2.ended ? " ended" : ""}${track2.ending ? " ending" : ""}`;
  24482. }
  24483. listOps(type) {
  24484. var _this$queues3;
  24485. return ((_this$queues3 = this.queues) == null ? void 0 : _this$queues3[type].map((op) => op.label).join(", ")) || "";
  24486. }
  24487. }
  24488. const VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  24489. const TRACK_REMOVED_ERROR_NAME = "HlsJsTrackRemovedError";
  24490. class HlsJsTrackRemovedError extends Error {
  24491. constructor(message) {
  24492. super(message);
  24493. this.name = TRACK_REMOVED_ERROR_NAME;
  24494. }
  24495. }
  24496. class BufferController extends Logger {
  24497. constructor(hls, fragmentTracker) {
  24498. super("buffer-controller", hls.logger);
  24499. this.hls = void 0;
  24500. this.fragmentTracker = void 0;
  24501. this.details = null;
  24502. this._objectUrl = null;
  24503. this.operationQueue = null;
  24504. this.bufferCodecEventsTotal = 0;
  24505. this.media = null;
  24506. this.mediaSource = null;
  24507. this.lastMpegAudioChunk = null;
  24508. this.blockedAudioAppend = null;
  24509. this.lastVideoAppendEnd = 0;
  24510. this.appendSource = void 0;
  24511. this.transferData = void 0;
  24512. this.overrides = void 0;
  24513. this.appendErrors = {
  24514. audio: 0,
  24515. video: 0,
  24516. audiovideo: 0
  24517. };
  24518. this.tracks = {};
  24519. this.sourceBuffers = [[null, null], [null, null]];
  24520. this._onEndStreaming = (event) => {
  24521. var _this$mediaSource;
  24522. if (!this.hls) {
  24523. return;
  24524. }
  24525. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) !== "open") {
  24526. return;
  24527. }
  24528. this.hls.pauseBuffering();
  24529. };
  24530. this._onStartStreaming = (event) => {
  24531. if (!this.hls) {
  24532. return;
  24533. }
  24534. this.hls.resumeBuffering();
  24535. };
  24536. this._onMediaSourceOpen = (e2) => {
  24537. const {
  24538. media,
  24539. mediaSource
  24540. } = this;
  24541. if (e2) {
  24542. this.log("Media source opened");
  24543. }
  24544. if (!media || !mediaSource) {
  24545. return;
  24546. }
  24547. mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
  24548. media.removeEventListener("emptied", this._onMediaEmptied);
  24549. this.updateDuration();
  24550. this.hls.trigger(Events.MEDIA_ATTACHED, {
  24551. media,
  24552. mediaSource
  24553. });
  24554. if (this.mediaSource !== null) {
  24555. this.checkPendingTracks();
  24556. }
  24557. };
  24558. this._onMediaSourceClose = () => {
  24559. this.log("Media source closed");
  24560. };
  24561. this._onMediaSourceEnded = () => {
  24562. this.log("Media source ended");
  24563. };
  24564. this._onMediaEmptied = () => {
  24565. const {
  24566. mediaSrc,
  24567. _objectUrl
  24568. } = this;
  24569. if (mediaSrc !== _objectUrl) {
  24570. this.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);
  24571. }
  24572. };
  24573. this.hls = hls;
  24574. this.fragmentTracker = fragmentTracker;
  24575. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  24576. this.initTracks();
  24577. this.registerListeners();
  24578. }
  24579. hasSourceTypes() {
  24580. return Object.keys(this.tracks).length > 0;
  24581. }
  24582. destroy() {
  24583. this.unregisterListeners();
  24584. this.details = null;
  24585. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  24586. this.transferData = this.overrides = void 0;
  24587. if (this.operationQueue) {
  24588. this.operationQueue.destroy();
  24589. this.operationQueue = null;
  24590. }
  24591. this.hls = this.fragmentTracker = null;
  24592. this._onMediaSourceOpen = this._onMediaSourceClose = null;
  24593. this._onMediaSourceEnded = null;
  24594. this._onStartStreaming = this._onEndStreaming = null;
  24595. }
  24596. registerListeners() {
  24597. const {
  24598. hls
  24599. } = this;
  24600. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  24601. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  24602. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24603. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  24604. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  24605. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  24606. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  24607. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  24608. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  24609. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  24610. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  24611. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  24612. hls.on(Events.ERROR, this.onError, this);
  24613. }
  24614. unregisterListeners() {
  24615. const {
  24616. hls
  24617. } = this;
  24618. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  24619. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  24620. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24621. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  24622. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  24623. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  24624. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  24625. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  24626. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  24627. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  24628. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  24629. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  24630. hls.off(Events.ERROR, this.onError, this);
  24631. }
  24632. transferMedia() {
  24633. const {
  24634. media,
  24635. mediaSource
  24636. } = this;
  24637. if (!media) {
  24638. return null;
  24639. }
  24640. const tracks = {};
  24641. if (this.operationQueue) {
  24642. const updating = this.isUpdating();
  24643. if (!updating) {
  24644. this.operationQueue.removeBlockers();
  24645. }
  24646. const queued = this.isQueued();
  24647. if (updating || queued) {
  24648. this.warn(`Transfering MediaSource with${queued ? " operations in queue" : ""}${updating ? " updating SourceBuffer(s)" : ""} ${this.operationQueue}`);
  24649. }
  24650. this.operationQueue.destroy();
  24651. }
  24652. const transferData = this.transferData;
  24653. if (!this.sourceBufferCount && transferData && transferData.mediaSource === mediaSource) {
  24654. _extends(tracks, transferData.tracks);
  24655. } else {
  24656. this.sourceBuffers.forEach((tuple) => {
  24657. const [type] = tuple;
  24658. if (type) {
  24659. tracks[type] = _extends({}, this.tracks[type]);
  24660. this.removeBuffer(type);
  24661. }
  24662. tuple[0] = tuple[1] = null;
  24663. });
  24664. }
  24665. return {
  24666. media,
  24667. mediaSource,
  24668. tracks
  24669. };
  24670. }
  24671. initTracks() {
  24672. const tracks = {};
  24673. this.sourceBuffers = [[null, null], [null, null]];
  24674. this.tracks = tracks;
  24675. this.resetQueue();
  24676. this.resetAppendErrors();
  24677. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  24678. this.lastVideoAppendEnd = 0;
  24679. }
  24680. onManifestLoading() {
  24681. this.bufferCodecEventsTotal = 0;
  24682. this.details = null;
  24683. }
  24684. onManifestParsed(event, data) {
  24685. var _this$transferData;
  24686. let codecEvents = 2;
  24687. if (data.audio && !data.video || !data.altAudio) {
  24688. codecEvents = 1;
  24689. }
  24690. this.bufferCodecEventsTotal = codecEvents;
  24691. this.log(`${codecEvents} bufferCodec event(s) expected.`);
  24692. if ((_this$transferData = this.transferData) != null && _this$transferData.mediaSource && this.sourceBufferCount && codecEvents) {
  24693. this.bufferCreated();
  24694. }
  24695. }
  24696. onMediaAttaching(event, data) {
  24697. const media = this.media = data.media;
  24698. const MediaSource = getMediaSource(this.appendSource);
  24699. this.transferData = this.overrides = void 0;
  24700. if (media && MediaSource) {
  24701. const transferringMedia = !!data.mediaSource;
  24702. if (transferringMedia || data.overrides) {
  24703. this.transferData = data;
  24704. this.overrides = data.overrides;
  24705. }
  24706. const ms2 = this.mediaSource = data.mediaSource || new MediaSource();
  24707. this.assignMediaSource(ms2);
  24708. if (transferringMedia) {
  24709. this._objectUrl = media.src;
  24710. this.attachTransferred();
  24711. } else {
  24712. const objectUrl = this._objectUrl = self.URL.createObjectURL(ms2);
  24713. if (this.appendSource) {
  24714. try {
  24715. media.removeAttribute("src");
  24716. const MMS = self.ManagedMediaSource;
  24717. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms2 instanceof MMS;
  24718. removeSourceChildren(media);
  24719. addSource(media, objectUrl);
  24720. media.load();
  24721. } catch (error) {
  24722. media.src = objectUrl;
  24723. }
  24724. } else {
  24725. media.src = objectUrl;
  24726. }
  24727. }
  24728. media.addEventListener("emptied", this._onMediaEmptied);
  24729. }
  24730. }
  24731. assignMediaSource(ms2) {
  24732. var _this$transferData2, _ms$constructor;
  24733. this.log(`${((_this$transferData2 = this.transferData) == null ? void 0 : _this$transferData2.mediaSource) === ms2 ? "transferred" : "created"} media source: ${(_ms$constructor = ms2.constructor) == null ? void 0 : _ms$constructor.name}`);
  24734. ms2.addEventListener("sourceopen", this._onMediaSourceOpen);
  24735. ms2.addEventListener("sourceended", this._onMediaSourceEnded);
  24736. ms2.addEventListener("sourceclose", this._onMediaSourceClose);
  24737. if (this.appendSource) {
  24738. ms2.addEventListener("startstreaming", this._onStartStreaming);
  24739. ms2.addEventListener("endstreaming", this._onEndStreaming);
  24740. }
  24741. }
  24742. attachTransferred() {
  24743. const media = this.media;
  24744. const data = this.transferData;
  24745. if (!data || !media) {
  24746. return;
  24747. }
  24748. const requiredTracks = this.tracks;
  24749. const transferredTracks = data.tracks;
  24750. const trackNames = transferredTracks ? Object.keys(transferredTracks) : null;
  24751. const trackCount = trackNames ? trackNames.length : 0;
  24752. const mediaSourceOpenCallback = () => {
  24753. if (this.media && this.mediaSourceOpenOrEnded) {
  24754. this._onMediaSourceOpen();
  24755. }
  24756. };
  24757. if (transferredTracks && trackNames && trackCount) {
  24758. if (!this.tracksReady) {
  24759. this.hls.config.startFragPrefetch = true;
  24760. this.log(`attachTransferred: waiting for SourceBuffer track info`);
  24761. return;
  24762. }
  24763. this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
  24764. required tracks: ${stringify(requiredTracks, (key, value) => key === "initSegment" ? void 0 : value)};
  24765. transfer tracks: ${stringify(transferredTracks, (key, value) => key === "initSegment" ? void 0 : value)}}`);
  24766. if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {
  24767. data.mediaSource = null;
  24768. data.tracks = void 0;
  24769. const currentTime = media.currentTime;
  24770. const details = this.details;
  24771. const startTime = Math.max(currentTime, (details == null ? void 0 : details.fragments[0].start) || 0);
  24772. if (startTime - currentTime > 1) {
  24773. this.log(`attachTransferred: waiting for playback to reach new tracks start time ${currentTime} -> ${startTime}`);
  24774. return;
  24775. }
  24776. this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(transferredTracks)}"->"${Object.keys(requiredTracks)}") start time: ${startTime} currentTime: ${currentTime}`);
  24777. this.onMediaDetaching(Events.MEDIA_DETACHING, {});
  24778. this.onMediaAttaching(Events.MEDIA_ATTACHING, data);
  24779. media.currentTime = startTime;
  24780. return;
  24781. }
  24782. this.transferData = void 0;
  24783. trackNames.forEach((trackName) => {
  24784. const type = trackName;
  24785. const track2 = transferredTracks[type];
  24786. if (track2) {
  24787. const sb = track2.buffer;
  24788. if (sb) {
  24789. const fragmentTracker = this.fragmentTracker;
  24790. const playlistType = track2.id;
  24791. if (fragmentTracker.hasFragments(playlistType) || fragmentTracker.hasParts(playlistType)) {
  24792. const bufferedTimeRanges = BufferHelper.getBuffered(sb);
  24793. fragmentTracker.detectEvictedFragments(type, bufferedTimeRanges, playlistType, null, true);
  24794. }
  24795. const sbIndex = sourceBufferNameToIndex(type);
  24796. const sbTuple = [type, sb];
  24797. this.sourceBuffers[sbIndex] = sbTuple;
  24798. if (sb.updating && this.operationQueue) {
  24799. this.operationQueue.prependBlocker(type);
  24800. }
  24801. this.trackSourceBuffer(type, track2);
  24802. }
  24803. }
  24804. });
  24805. mediaSourceOpenCallback();
  24806. this.bufferCreated();
  24807. } else {
  24808. this.log(`attachTransferred: MediaSource w/o SourceBuffers`);
  24809. mediaSourceOpenCallback();
  24810. }
  24811. }
  24812. get mediaSourceOpenOrEnded() {
  24813. var _this$mediaSource2;
  24814. const readyState = (_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState;
  24815. return readyState === "open" || readyState === "ended";
  24816. }
  24817. onMediaDetaching(event, data) {
  24818. const transferringMedia = !!data.transferMedia;
  24819. this.transferData = this.overrides = void 0;
  24820. const {
  24821. media,
  24822. mediaSource,
  24823. _objectUrl
  24824. } = this;
  24825. if (mediaSource) {
  24826. this.log(`media source ${transferringMedia ? "transferring" : "detaching"}`);
  24827. if (transferringMedia) {
  24828. this.sourceBuffers.forEach(([type]) => {
  24829. if (type) {
  24830. this.removeBuffer(type);
  24831. }
  24832. });
  24833. this.resetQueue();
  24834. } else {
  24835. if (this.mediaSourceOpenOrEnded) {
  24836. const open = mediaSource.readyState === "open";
  24837. try {
  24838. const sourceBuffers = mediaSource.sourceBuffers;
  24839. for (let i2 = sourceBuffers.length; i2--; ) {
  24840. if (open) {
  24841. sourceBuffers[i2].abort();
  24842. }
  24843. mediaSource.removeSourceBuffer(sourceBuffers[i2]);
  24844. }
  24845. if (open) {
  24846. mediaSource.endOfStream();
  24847. }
  24848. } catch (err) {
  24849. this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);
  24850. }
  24851. }
  24852. if (this.sourceBufferCount) {
  24853. this.onBufferReset();
  24854. }
  24855. }
  24856. mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
  24857. mediaSource.removeEventListener("sourceended", this._onMediaSourceEnded);
  24858. mediaSource.removeEventListener("sourceclose", this._onMediaSourceClose);
  24859. if (this.appendSource) {
  24860. mediaSource.removeEventListener("startstreaming", this._onStartStreaming);
  24861. mediaSource.removeEventListener("endstreaming", this._onEndStreaming);
  24862. }
  24863. this.mediaSource = null;
  24864. this._objectUrl = null;
  24865. }
  24866. if (media) {
  24867. media.removeEventListener("emptied", this._onMediaEmptied);
  24868. if (!transferringMedia) {
  24869. if (_objectUrl) {
  24870. self.URL.revokeObjectURL(_objectUrl);
  24871. }
  24872. if (this.mediaSrc === _objectUrl) {
  24873. media.removeAttribute("src");
  24874. if (this.appendSource) {
  24875. removeSourceChildren(media);
  24876. }
  24877. media.load();
  24878. } else {
  24879. this.warn("media|source.src was changed by a third party - skip cleanup");
  24880. }
  24881. }
  24882. this.media = null;
  24883. }
  24884. this.hls.trigger(Events.MEDIA_DETACHED, data);
  24885. }
  24886. onBufferReset() {
  24887. this.sourceBuffers.forEach(([type]) => {
  24888. if (type) {
  24889. this.resetBuffer(type);
  24890. }
  24891. });
  24892. this.initTracks();
  24893. }
  24894. resetBuffer(type) {
  24895. var _this$tracks$type;
  24896. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  24897. this.removeBuffer(type);
  24898. if (sb) {
  24899. try {
  24900. var _this$mediaSource3;
  24901. if ((_this$mediaSource3 = this.mediaSource) != null && _this$mediaSource3.sourceBuffers.length) {
  24902. this.mediaSource.removeSourceBuffer(sb);
  24903. }
  24904. } catch (err) {
  24905. this.warn(`onBufferReset ${type}`, err);
  24906. }
  24907. }
  24908. delete this.tracks[type];
  24909. }
  24910. removeBuffer(type) {
  24911. this.removeBufferListeners(type);
  24912. this.sourceBuffers[sourceBufferNameToIndex(type)] = [null, null];
  24913. const track2 = this.tracks[type];
  24914. if (track2) {
  24915. track2.buffer = void 0;
  24916. }
  24917. }
  24918. resetQueue() {
  24919. if (this.operationQueue) {
  24920. this.operationQueue.destroy();
  24921. }
  24922. this.operationQueue = new BufferOperationQueue(this.tracks);
  24923. }
  24924. onBufferCodecs(event, data) {
  24925. const tracks = this.tracks;
  24926. const trackNames = Object.keys(data);
  24927. this.log(`BUFFER_CODECS: "${trackNames}" (current SB count ${this.sourceBufferCount})`);
  24928. const unmuxedToMuxed = "audiovideo" in data && (tracks.audio || tracks.video) || tracks.audiovideo && ("audio" in data || "video" in data);
  24929. const muxedToUnmuxed = !unmuxedToMuxed && this.sourceBufferCount && this.media && trackNames.some((sbName) => !tracks[sbName]);
  24930. if (unmuxedToMuxed || muxedToUnmuxed) {
  24931. this.warn(`Unsupported transition between "${Object.keys(tracks)}" and "${trackNames}" SourceBuffers`);
  24932. return;
  24933. }
  24934. trackNames.forEach((trackName) => {
  24935. var _this$transferData3, _this$transferData3$t, _trackCodec;
  24936. const parsedTrack = data[trackName];
  24937. const {
  24938. id,
  24939. codec,
  24940. levelCodec,
  24941. container,
  24942. metadata,
  24943. supplemental
  24944. } = parsedTrack;
  24945. let track2 = tracks[trackName];
  24946. const transferredTrack = (_this$transferData3 = this.transferData) == null ? void 0 : (_this$transferData3$t = _this$transferData3.tracks) == null ? void 0 : _this$transferData3$t[trackName];
  24947. const sbTrack = transferredTrack != null && transferredTrack.buffer ? transferredTrack : track2;
  24948. const sbCodec = (sbTrack == null ? void 0 : sbTrack.pendingCodec) || (sbTrack == null ? void 0 : sbTrack.codec);
  24949. const trackLevelCodec = sbTrack == null ? void 0 : sbTrack.levelCodec;
  24950. if (!track2) {
  24951. track2 = tracks[trackName] = {
  24952. buffer: void 0,
  24953. listeners: [],
  24954. codec,
  24955. supplemental,
  24956. container,
  24957. levelCodec,
  24958. metadata,
  24959. id
  24960. };
  24961. }
  24962. const currentCodecFull = pickMostCompleteCodecName(sbCodec, trackLevelCodec);
  24963. const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
  24964. let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  24965. const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
  24966. if (trackCodec && currentCodecFull && currentCodec !== nextCodec) {
  24967. if (trackName.slice(0, 5) === "audio") {
  24968. trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
  24969. }
  24970. this.log(`switching codec ${sbCodec} to ${trackCodec}`);
  24971. if (trackCodec !== (track2.pendingCodec || track2.codec)) {
  24972. track2.pendingCodec = trackCodec;
  24973. }
  24974. track2.container = container;
  24975. this.appendChangeType(trackName, container, trackCodec);
  24976. }
  24977. });
  24978. if (this.tracksReady || this.sourceBufferCount) {
  24979. data.tracks = this.sourceBufferTracks;
  24980. }
  24981. if (this.sourceBufferCount) {
  24982. return;
  24983. }
  24984. if (this.mediaSourceOpenOrEnded) {
  24985. this.checkPendingTracks();
  24986. }
  24987. }
  24988. get sourceBufferTracks() {
  24989. return Object.keys(this.tracks).reduce((baseTracks, type) => {
  24990. const track2 = this.tracks[type];
  24991. baseTracks[type] = {
  24992. id: track2.id,
  24993. container: track2.container,
  24994. codec: track2.codec,
  24995. levelCodec: track2.levelCodec
  24996. };
  24997. return baseTracks;
  24998. }, {});
  24999. }
  25000. appendChangeType(type, container, codec) {
  25001. const mimeType = `${container};codecs=${codec}`;
  25002. const operation = {
  25003. label: `change-type=${mimeType}`,
  25004. execute: () => {
  25005. const track2 = this.tracks[type];
  25006. if (track2) {
  25007. const sb = track2.buffer;
  25008. if (sb != null && sb.changeType) {
  25009. this.log(`changing ${type} sourceBuffer type to ${mimeType}`);
  25010. sb.changeType(mimeType);
  25011. track2.codec = codec;
  25012. track2.container = container;
  25013. }
  25014. }
  25015. this.shiftAndExecuteNext(type);
  25016. },
  25017. onStart: () => {
  25018. },
  25019. onComplete: () => {
  25020. },
  25021. onError: (error) => {
  25022. this.warn(`Failed to change ${type} SourceBuffer type`, error);
  25023. }
  25024. };
  25025. this.append(operation, type, this.isPending(this.tracks[type]));
  25026. }
  25027. blockAudio(partOrFrag) {
  25028. var _this$fragmentTracker;
  25029. const pStart = partOrFrag.start;
  25030. const pTime = pStart + partOrFrag.duration * 0.05;
  25031. const atGap = ((_this$fragmentTracker = this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker.gap) === true;
  25032. if (atGap) {
  25033. return;
  25034. }
  25035. const op = {
  25036. label: "block-audio",
  25037. execute: () => {
  25038. var _this$fragmentTracker2;
  25039. const videoTrack = this.tracks.video;
  25040. if (this.lastVideoAppendEnd > pTime || videoTrack != null && videoTrack.buffer && BufferHelper.isBuffered(videoTrack.buffer, pTime) || ((_this$fragmentTracker2 = this.fragmentTracker.getAppendedFrag(pTime, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker2.gap) === true) {
  25041. this.blockedAudioAppend = null;
  25042. this.shiftAndExecuteNext("audio");
  25043. }
  25044. },
  25045. onStart: () => {
  25046. },
  25047. onComplete: () => {
  25048. },
  25049. onError: (error) => {
  25050. this.warn("Error executing block-audio operation", error);
  25051. }
  25052. };
  25053. this.blockedAudioAppend = {
  25054. op,
  25055. frag: partOrFrag
  25056. };
  25057. this.append(op, "audio", true);
  25058. }
  25059. unblockAudio() {
  25060. const {
  25061. blockedAudioAppend,
  25062. operationQueue
  25063. } = this;
  25064. if (blockedAudioAppend && operationQueue) {
  25065. this.blockedAudioAppend = null;
  25066. operationQueue.unblockAudio(blockedAudioAppend.op);
  25067. }
  25068. }
  25069. onBufferAppending(event, eventData) {
  25070. const {
  25071. tracks
  25072. } = this;
  25073. const {
  25074. data,
  25075. type,
  25076. parent,
  25077. frag,
  25078. part,
  25079. chunkMeta,
  25080. offset
  25081. } = eventData;
  25082. const chunkStats = chunkMeta.buffering[type];
  25083. const {
  25084. sn: sn2,
  25085. cc
  25086. } = frag;
  25087. const bufferAppendingStart = self.performance.now();
  25088. chunkStats.start = bufferAppendingStart;
  25089. const fragBuffering = frag.stats.buffering;
  25090. const partBuffering = part ? part.stats.buffering : null;
  25091. if (fragBuffering.start === 0) {
  25092. fragBuffering.start = bufferAppendingStart;
  25093. }
  25094. if (partBuffering && partBuffering.start === 0) {
  25095. partBuffering.start = bufferAppendingStart;
  25096. }
  25097. const audioTrack = tracks.audio;
  25098. let checkTimestampOffset = false;
  25099. if (type === "audio" && (audioTrack == null ? void 0 : audioTrack.container) === "audio/mpeg") {
  25100. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  25101. this.lastMpegAudioChunk = chunkMeta;
  25102. }
  25103. const videoTrack = tracks.video;
  25104. const videoSb = videoTrack == null ? void 0 : videoTrack.buffer;
  25105. if (videoSb && sn2 !== "initSegment") {
  25106. const partOrFrag = part || frag;
  25107. const blockedAudioAppend = this.blockedAudioAppend;
  25108. if (type === "audio" && parent !== "main" && !this.blockedAudioAppend) {
  25109. const pStart = partOrFrag.start;
  25110. const pTime = pStart + partOrFrag.duration * 0.05;
  25111. const vbuffered = videoSb.buffered;
  25112. const vappending = this.currentOp("video");
  25113. if (!vbuffered.length && !vappending) {
  25114. this.blockAudio(partOrFrag);
  25115. } else if (!vappending && !BufferHelper.isBuffered(videoSb, pTime) && this.lastVideoAppendEnd < pTime) {
  25116. this.blockAudio(partOrFrag);
  25117. }
  25118. } else if (type === "video") {
  25119. const videoAppendEnd = partOrFrag.end;
  25120. if (blockedAudioAppend) {
  25121. const audioStart = blockedAudioAppend.frag.start;
  25122. if (videoAppendEnd > audioStart || videoAppendEnd < this.lastVideoAppendEnd || BufferHelper.isBuffered(videoSb, audioStart)) {
  25123. this.unblockAudio();
  25124. }
  25125. }
  25126. this.lastVideoAppendEnd = videoAppendEnd;
  25127. }
  25128. }
  25129. const fragStart = (part || frag).start;
  25130. const operation = {
  25131. label: `append-${type}`,
  25132. execute: () => {
  25133. var _this$tracks$type2;
  25134. chunkStats.executeStart = self.performance.now();
  25135. const sb = (_this$tracks$type2 = this.tracks[type]) == null ? void 0 : _this$tracks$type2.buffer;
  25136. if (sb) {
  25137. if (checkTimestampOffset) {
  25138. this.updateTimestampOffset(sb, fragStart, 0.1, type, sn2, cc);
  25139. } else if (offset !== void 0 && isFiniteNumber(offset)) {
  25140. this.updateTimestampOffset(sb, offset, 1e-6, type, sn2, cc);
  25141. }
  25142. }
  25143. this.appendExecutor(data, type);
  25144. },
  25145. onStart: () => {
  25146. },
  25147. onComplete: () => {
  25148. const end = self.performance.now();
  25149. chunkStats.executeEnd = chunkStats.end = end;
  25150. if (fragBuffering.first === 0) {
  25151. fragBuffering.first = end;
  25152. }
  25153. if (partBuffering && partBuffering.first === 0) {
  25154. partBuffering.first = end;
  25155. }
  25156. const timeRanges = {};
  25157. this.sourceBuffers.forEach(([type2, sb]) => {
  25158. if (type2) {
  25159. timeRanges[type2] = BufferHelper.getBuffered(sb);
  25160. }
  25161. });
  25162. this.appendErrors[type] = 0;
  25163. if (type === "audio" || type === "video") {
  25164. this.appendErrors.audiovideo = 0;
  25165. } else {
  25166. this.appendErrors.audio = 0;
  25167. this.appendErrors.video = 0;
  25168. }
  25169. this.hls.trigger(Events.BUFFER_APPENDED, {
  25170. type,
  25171. frag,
  25172. part,
  25173. chunkMeta,
  25174. parent: frag.type,
  25175. timeRanges
  25176. });
  25177. },
  25178. onError: (error) => {
  25179. var _this$media;
  25180. const event2 = {
  25181. type: ErrorTypes.MEDIA_ERROR,
  25182. parent: frag.type,
  25183. details: ErrorDetails.BUFFER_APPEND_ERROR,
  25184. sourceBufferName: type,
  25185. frag,
  25186. part,
  25187. chunkMeta,
  25188. error,
  25189. err: error,
  25190. fatal: false
  25191. };
  25192. const mediaError = (_this$media = this.media) == null ? void 0 : _this$media.error;
  25193. if (error.code === DOMException.QUOTA_EXCEEDED_ERR || error.name == "QuotaExceededError" || `quota` in error) {
  25194. event2.details = ErrorDetails.BUFFER_FULL_ERROR;
  25195. } else if (error.code === DOMException.INVALID_STATE_ERR && this.mediaSourceOpenOrEnded && !mediaError) {
  25196. event2.errorAction = createDoNothingErrorAction(true);
  25197. } else if (error.name === TRACK_REMOVED_ERROR_NAME && this.sourceBufferCount === 0) {
  25198. event2.errorAction = createDoNothingErrorAction(true);
  25199. } else {
  25200. const appendErrorCount = ++this.appendErrors[type];
  25201. this.warn(`Failed ${appendErrorCount}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer (${mediaError ? mediaError : "no media error"})`);
  25202. if (appendErrorCount >= this.hls.config.appendErrorMaxRetry || !!mediaError) {
  25203. event2.fatal = true;
  25204. }
  25205. }
  25206. this.hls.trigger(Events.ERROR, event2);
  25207. }
  25208. };
  25209. this.append(operation, type, this.isPending(this.tracks[type]));
  25210. }
  25211. getFlushOp(type, start, end) {
  25212. this.log(`queuing "${type}" remove ${start}-${end}`);
  25213. return {
  25214. label: "remove",
  25215. execute: () => {
  25216. this.removeExecutor(type, start, end);
  25217. },
  25218. onStart: () => {
  25219. },
  25220. onComplete: () => {
  25221. this.hls.trigger(Events.BUFFER_FLUSHED, {
  25222. type
  25223. });
  25224. },
  25225. onError: (error) => {
  25226. this.warn(`Failed to remove ${start}-${end} from "${type}" SourceBuffer`, error);
  25227. }
  25228. };
  25229. }
  25230. onBufferFlushing(event, data) {
  25231. const {
  25232. type,
  25233. startOffset,
  25234. endOffset
  25235. } = data;
  25236. if (type) {
  25237. this.append(this.getFlushOp(type, startOffset, endOffset), type);
  25238. } else {
  25239. this.sourceBuffers.forEach(([type2]) => {
  25240. if (type2) {
  25241. this.append(this.getFlushOp(type2, startOffset, endOffset), type2);
  25242. }
  25243. });
  25244. }
  25245. }
  25246. onFragParsed(event, data) {
  25247. const {
  25248. frag,
  25249. part
  25250. } = data;
  25251. const buffersAppendedTo = [];
  25252. const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  25253. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  25254. buffersAppendedTo.push("audiovideo");
  25255. } else {
  25256. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  25257. buffersAppendedTo.push("audio");
  25258. }
  25259. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  25260. buffersAppendedTo.push("video");
  25261. }
  25262. }
  25263. const onUnblocked = () => {
  25264. const now2 = self.performance.now();
  25265. frag.stats.buffering.end = now2;
  25266. if (part) {
  25267. part.stats.buffering.end = now2;
  25268. }
  25269. const stats = part ? part.stats : frag.stats;
  25270. this.hls.trigger(Events.FRAG_BUFFERED, {
  25271. frag,
  25272. part,
  25273. stats,
  25274. id: frag.type
  25275. });
  25276. };
  25277. if (buffersAppendedTo.length === 0) {
  25278. this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);
  25279. }
  25280. this.blockBuffers(onUnblocked, buffersAppendedTo).catch((error) => {
  25281. this.warn(`Fragment buffered callback ${error}`);
  25282. this.stepOperationQueue(this.sourceBufferTypes);
  25283. });
  25284. }
  25285. onFragChanged(event, data) {
  25286. this.trimBuffers();
  25287. }
  25288. get bufferedToEnd() {
  25289. return this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  25290. var _this$tracks$type3, _this$tracks$type4;
  25291. return type && (!((_this$tracks$type3 = this.tracks[type]) != null && _this$tracks$type3.ended) || ((_this$tracks$type4 = this.tracks[type]) == null ? void 0 : _this$tracks$type4.ending));
  25292. });
  25293. }
  25294. // on BUFFER_EOS mark matching sourcebuffer(s) as "ending" and "ended" and queue endOfStream after remaining operations(s)
  25295. // an undefined data.type will mark all buffers as EOS.
  25296. onBufferEos(event, data) {
  25297. var _this$overrides;
  25298. this.sourceBuffers.forEach(([type]) => {
  25299. if (type) {
  25300. const track2 = this.tracks[type];
  25301. if (!data.type || data.type === type) {
  25302. track2.ending = true;
  25303. if (!track2.ended) {
  25304. track2.ended = true;
  25305. this.log(`${type} buffer reached EOS`);
  25306. }
  25307. }
  25308. }
  25309. });
  25310. const allowEndOfStream = ((_this$overrides = this.overrides) == null ? void 0 : _this$overrides.endOfStream) !== false;
  25311. const allTracksEnding = this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  25312. var _this$tracks$type5;
  25313. return type && !((_this$tracks$type5 = this.tracks[type]) != null && _this$tracks$type5.ended);
  25314. });
  25315. if (allTracksEnding) {
  25316. if (allowEndOfStream) {
  25317. this.log(`Queueing EOS`);
  25318. this.blockUntilOpen(() => {
  25319. this.tracksEnded();
  25320. const {
  25321. mediaSource
  25322. } = this;
  25323. if (!mediaSource || mediaSource.readyState !== "open") {
  25324. if (mediaSource) {
  25325. this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);
  25326. }
  25327. return;
  25328. }
  25329. this.log(`Calling mediaSource.endOfStream()`);
  25330. mediaSource.endOfStream();
  25331. this.hls.trigger(Events.BUFFERED_TO_END, void 0);
  25332. });
  25333. } else {
  25334. this.tracksEnded();
  25335. this.hls.trigger(Events.BUFFERED_TO_END, void 0);
  25336. }
  25337. }
  25338. }
  25339. tracksEnded() {
  25340. this.sourceBuffers.forEach(([type]) => {
  25341. if (type !== null) {
  25342. const track2 = this.tracks[type];
  25343. if (track2) {
  25344. track2.ending = false;
  25345. }
  25346. }
  25347. });
  25348. }
  25349. onLevelUpdated(event, {
  25350. details
  25351. }) {
  25352. if (!details.fragments.length) {
  25353. return;
  25354. }
  25355. this.details = details;
  25356. this.updateDuration();
  25357. }
  25358. updateDuration() {
  25359. this.blockUntilOpen(() => {
  25360. const durationAndRange = this.getDurationAndRange();
  25361. if (!durationAndRange) {
  25362. return;
  25363. }
  25364. this.updateMediaSource(durationAndRange);
  25365. });
  25366. }
  25367. onError(event, data) {
  25368. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && data.frag) {
  25369. var _data$errorAction;
  25370. const nextAutoLevel = (_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.nextAutoLevel;
  25371. if (isFiniteNumber(nextAutoLevel) && nextAutoLevel !== data.frag.level) {
  25372. this.resetAppendErrors();
  25373. }
  25374. }
  25375. }
  25376. resetAppendErrors() {
  25377. this.appendErrors = {
  25378. audio: 0,
  25379. video: 0,
  25380. audiovideo: 0
  25381. };
  25382. }
  25383. trimBuffers() {
  25384. const {
  25385. hls,
  25386. details,
  25387. media
  25388. } = this;
  25389. if (!media || details === null) {
  25390. return;
  25391. }
  25392. if (!this.sourceBufferCount) {
  25393. return;
  25394. }
  25395. const config = hls.config;
  25396. const currentTime = media.currentTime;
  25397. const targetDuration = details.levelTargetDuration;
  25398. const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  25399. if (isFiniteNumber(backBufferLength) && backBufferLength >= 0) {
  25400. const maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  25401. const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  25402. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  25403. }
  25404. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  25405. const frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  25406. const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  25407. const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  25408. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  25409. }
  25410. }
  25411. flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  25412. this.sourceBuffers.forEach(([type, sb]) => {
  25413. if (sb) {
  25414. const buffered = BufferHelper.getBuffered(sb);
  25415. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  25416. var _this$details;
  25417. this.hls.trigger(Events.BACK_BUFFER_REACHED, {
  25418. bufferEnd: targetBackBufferPosition
  25419. });
  25420. const track2 = this.tracks[type];
  25421. if ((_this$details = this.details) != null && _this$details.live) {
  25422. this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  25423. bufferEnd: targetBackBufferPosition
  25424. });
  25425. } else if (track2 != null && track2.ended) {
  25426. this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`);
  25427. return;
  25428. }
  25429. this.hls.trigger(Events.BUFFER_FLUSHING, {
  25430. startOffset: 0,
  25431. endOffset: targetBackBufferPosition,
  25432. type
  25433. });
  25434. }
  25435. }
  25436. });
  25437. }
  25438. flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  25439. this.sourceBuffers.forEach(([type, sb]) => {
  25440. if (sb) {
  25441. const buffered = BufferHelper.getBuffered(sb);
  25442. const numBufferedRanges = buffered.length;
  25443. if (numBufferedRanges < 2) {
  25444. return;
  25445. }
  25446. const bufferStart = buffered.start(numBufferedRanges - 1);
  25447. const bufferEnd = buffered.end(numBufferedRanges - 1);
  25448. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  25449. return;
  25450. }
  25451. this.hls.trigger(Events.BUFFER_FLUSHING, {
  25452. startOffset: bufferStart,
  25453. endOffset: Infinity,
  25454. type
  25455. });
  25456. }
  25457. });
  25458. }
  25459. /**
  25460. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  25461. * 'liveDurationInfinity` is set to `true`
  25462. * More details: https://github.com/video-dev/hls.js/issues/355
  25463. */
  25464. getDurationAndRange() {
  25465. var _this$overrides2;
  25466. const {
  25467. details,
  25468. mediaSource
  25469. } = this;
  25470. if (!details || !this.media || (mediaSource == null ? void 0 : mediaSource.readyState) !== "open") {
  25471. return null;
  25472. }
  25473. const playlistEnd = details.edge;
  25474. if (details.live && this.hls.config.liveDurationInfinity) {
  25475. const len = details.fragments.length;
  25476. if (len && details.live && !!mediaSource.setLiveSeekableRange) {
  25477. const start = Math.max(0, details.fragmentStart);
  25478. const end = Math.max(start, playlistEnd);
  25479. return {
  25480. duration: Infinity,
  25481. start,
  25482. end
  25483. };
  25484. }
  25485. return {
  25486. duration: Infinity
  25487. };
  25488. }
  25489. const overrideDuration = (_this$overrides2 = this.overrides) == null ? void 0 : _this$overrides2.duration;
  25490. if (overrideDuration) {
  25491. if (!isFiniteNumber(overrideDuration)) {
  25492. return null;
  25493. }
  25494. return {
  25495. duration: overrideDuration
  25496. };
  25497. }
  25498. const mediaDuration = this.media.duration;
  25499. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  25500. if (playlistEnd > msDuration && playlistEnd > mediaDuration || !isFiniteNumber(mediaDuration)) {
  25501. return {
  25502. duration: playlistEnd
  25503. };
  25504. }
  25505. return null;
  25506. }
  25507. updateMediaSource({
  25508. duration,
  25509. start,
  25510. end
  25511. }) {
  25512. const mediaSource = this.mediaSource;
  25513. if (!this.media || !mediaSource || mediaSource.readyState !== "open") {
  25514. return;
  25515. }
  25516. if (mediaSource.duration !== duration) {
  25517. if (isFiniteNumber(duration)) {
  25518. this.log(`Updating MediaSource duration to ${duration.toFixed(3)}`);
  25519. }
  25520. mediaSource.duration = duration;
  25521. }
  25522. if (start !== void 0 && end !== void 0) {
  25523. this.log(`MediaSource duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`);
  25524. mediaSource.setLiveSeekableRange(start, end);
  25525. }
  25526. }
  25527. get tracksReady() {
  25528. const pendingTrackCount = this.pendingTrackCount;
  25529. return pendingTrackCount > 0 && (pendingTrackCount >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  25530. }
  25531. checkPendingTracks() {
  25532. const {
  25533. bufferCodecEventsTotal,
  25534. pendingTrackCount,
  25535. tracks
  25536. } = this;
  25537. this.log(`checkPendingTracks (pending: ${pendingTrackCount} codec events expected: ${bufferCodecEventsTotal}) ${stringify(tracks)}`);
  25538. if (this.tracksReady) {
  25539. var _this$transferData4;
  25540. const transferredTracks = (_this$transferData4 = this.transferData) == null ? void 0 : _this$transferData4.tracks;
  25541. if (transferredTracks && Object.keys(transferredTracks).length) {
  25542. this.attachTransferred();
  25543. } else {
  25544. this.createSourceBuffers();
  25545. }
  25546. }
  25547. }
  25548. bufferCreated() {
  25549. if (this.sourceBufferCount) {
  25550. const tracks = {};
  25551. this.sourceBuffers.forEach(([type, buffer2]) => {
  25552. if (type) {
  25553. const track2 = this.tracks[type];
  25554. tracks[type] = {
  25555. buffer: buffer2,
  25556. container: track2.container,
  25557. codec: track2.codec,
  25558. supplemental: track2.supplemental,
  25559. levelCodec: track2.levelCodec,
  25560. id: track2.id,
  25561. metadata: track2.metadata
  25562. };
  25563. }
  25564. });
  25565. this.hls.trigger(Events.BUFFER_CREATED, {
  25566. tracks
  25567. });
  25568. this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`);
  25569. this.sourceBuffers.forEach(([type]) => {
  25570. this.executeNext(type);
  25571. });
  25572. } else {
  25573. const error = new Error("could not create source buffer for media codec(s)");
  25574. this.hls.trigger(Events.ERROR, {
  25575. type: ErrorTypes.MEDIA_ERROR,
  25576. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  25577. fatal: true,
  25578. error,
  25579. reason: error.message
  25580. });
  25581. }
  25582. }
  25583. createSourceBuffers() {
  25584. const {
  25585. tracks,
  25586. sourceBuffers,
  25587. mediaSource
  25588. } = this;
  25589. if (!mediaSource) {
  25590. throw new Error("createSourceBuffers called when mediaSource was null");
  25591. }
  25592. for (const trackName in tracks) {
  25593. const type = trackName;
  25594. const track2 = tracks[type];
  25595. if (this.isPending(track2)) {
  25596. const codec = this.getTrackCodec(track2, type);
  25597. const mimeType = `${track2.container};codecs=${codec}`;
  25598. track2.codec = codec;
  25599. this.log(`creating sourceBuffer(${mimeType})${this.currentOp(type) ? " Queued" : ""} ${stringify(track2)}`);
  25600. try {
  25601. const sb = mediaSource.addSourceBuffer(mimeType);
  25602. const sbIndex = sourceBufferNameToIndex(type);
  25603. const sbTuple = [type, sb];
  25604. sourceBuffers[sbIndex] = sbTuple;
  25605. track2.buffer = sb;
  25606. } catch (error) {
  25607. var _this$operationQueue;
  25608. this.error(`error while trying to add sourceBuffer: ${error.message}`);
  25609. this.shiftAndExecuteNext(type);
  25610. (_this$operationQueue = this.operationQueue) == null ? void 0 : _this$operationQueue.removeBlockers();
  25611. delete this.tracks[type];
  25612. this.hls.trigger(Events.ERROR, {
  25613. type: ErrorTypes.MEDIA_ERROR,
  25614. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  25615. fatal: false,
  25616. error,
  25617. sourceBufferName: type,
  25618. mimeType,
  25619. parent: track2.id
  25620. });
  25621. return;
  25622. }
  25623. this.trackSourceBuffer(type, track2);
  25624. }
  25625. }
  25626. this.bufferCreated();
  25627. }
  25628. getTrackCodec(track2, trackName) {
  25629. const supplementalCodec = track2.supplemental;
  25630. let trackCodec = track2.codec;
  25631. if (supplementalCodec && (trackName === "video" || trackName === "audiovideo") && areCodecsMediaSourceSupported(supplementalCodec, "video")) {
  25632. trackCodec = replaceVideoCodec(trackCodec, supplementalCodec);
  25633. }
  25634. const codec = pickMostCompleteCodecName(trackCodec, track2.levelCodec);
  25635. if (codec) {
  25636. if (trackName.slice(0, 5) === "audio") {
  25637. return getCodecCompatibleName(codec, this.appendSource);
  25638. }
  25639. return codec;
  25640. }
  25641. return "";
  25642. }
  25643. trackSourceBuffer(type, track2) {
  25644. const buffer2 = track2.buffer;
  25645. if (!buffer2) {
  25646. return;
  25647. }
  25648. const codec = this.getTrackCodec(track2, type);
  25649. this.tracks[type] = {
  25650. buffer: buffer2,
  25651. codec,
  25652. container: track2.container,
  25653. levelCodec: track2.levelCodec,
  25654. supplemental: track2.supplemental,
  25655. metadata: track2.metadata,
  25656. id: track2.id,
  25657. listeners: []
  25658. };
  25659. this.removeBufferListeners(type);
  25660. this.addBufferListener(type, "updatestart", this.onSBUpdateStart);
  25661. this.addBufferListener(type, "updateend", this.onSBUpdateEnd);
  25662. this.addBufferListener(type, "error", this.onSBUpdateError);
  25663. if (this.appendSource) {
  25664. this.addBufferListener(type, "bufferedchange", (type2, event) => {
  25665. const removedRanges = event.removedRanges;
  25666. if (removedRanges != null && removedRanges.length) {
  25667. this.hls.trigger(Events.BUFFER_FLUSHED, {
  25668. type: type2
  25669. });
  25670. }
  25671. });
  25672. }
  25673. }
  25674. get mediaSrc() {
  25675. var _this$media2, _this$media2$querySel;
  25676. const media = ((_this$media2 = this.media) == null ? void 0 : (_this$media2$querySel = _this$media2.querySelector) == null ? void 0 : _this$media2$querySel.call(_this$media2, "source")) || this.media;
  25677. return media == null ? void 0 : media.src;
  25678. }
  25679. onSBUpdateStart(type) {
  25680. const operation = this.currentOp(type);
  25681. if (!operation) {
  25682. return;
  25683. }
  25684. operation.onStart();
  25685. }
  25686. onSBUpdateEnd(type) {
  25687. var _this$mediaSource4;
  25688. if (((_this$mediaSource4 = this.mediaSource) == null ? void 0 : _this$mediaSource4.readyState) === "closed") {
  25689. this.resetBuffer(type);
  25690. return;
  25691. }
  25692. const operation = this.currentOp(type);
  25693. if (!operation) {
  25694. return;
  25695. }
  25696. operation.onComplete();
  25697. this.shiftAndExecuteNext(type);
  25698. }
  25699. onSBUpdateError(type, event) {
  25700. var _this$mediaSource5;
  25701. const error = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource5 = this.mediaSource) == null ? void 0 : _this$mediaSource5.readyState}`);
  25702. this.error(`${error}`, event);
  25703. this.hls.trigger(Events.ERROR, {
  25704. type: ErrorTypes.MEDIA_ERROR,
  25705. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  25706. sourceBufferName: type,
  25707. error,
  25708. fatal: false
  25709. });
  25710. const operation = this.currentOp(type);
  25711. if (operation) {
  25712. operation.onError(error);
  25713. }
  25714. }
  25715. updateTimestampOffset(sb, timestampOffset, tolerance, type, sn2, cc) {
  25716. const delta = timestampOffset - sb.timestampOffset;
  25717. if (Math.abs(delta) >= tolerance) {
  25718. this.log(`Updating ${type} SourceBuffer timestampOffset to ${timestampOffset} (sn: ${sn2} cc: ${cc})`);
  25719. sb.timestampOffset = timestampOffset;
  25720. }
  25721. }
  25722. // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually
  25723. removeExecutor(type, startOffset, endOffset) {
  25724. const {
  25725. media,
  25726. mediaSource
  25727. } = this;
  25728. const track2 = this.tracks[type];
  25729. const sb = track2 == null ? void 0 : track2.buffer;
  25730. if (!media || !mediaSource || !sb) {
  25731. this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`);
  25732. this.shiftAndExecuteNext(type);
  25733. return;
  25734. }
  25735. const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  25736. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  25737. const removeStart = Math.max(0, startOffset);
  25738. const removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  25739. if (removeEnd > removeStart && (!track2.ending || track2.ended)) {
  25740. track2.ended = false;
  25741. this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`);
  25742. sb.remove(removeStart, removeEnd);
  25743. } else {
  25744. this.shiftAndExecuteNext(type);
  25745. }
  25746. }
  25747. // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually
  25748. appendExecutor(data, type) {
  25749. const track2 = this.tracks[type];
  25750. const sb = track2 == null ? void 0 : track2.buffer;
  25751. if (!sb) {
  25752. throw new HlsJsTrackRemovedError(`Attempting to append to the ${type} SourceBuffer, but it does not exist`);
  25753. }
  25754. track2.ending = false;
  25755. track2.ended = false;
  25756. sb.appendBuffer(data);
  25757. }
  25758. blockUntilOpen(callback) {
  25759. if (this.isUpdating() || this.isQueued()) {
  25760. this.blockBuffers(callback).catch((error) => {
  25761. this.warn(`SourceBuffer blocked callback ${error}`);
  25762. this.stepOperationQueue(this.sourceBufferTypes);
  25763. });
  25764. } else {
  25765. try {
  25766. callback();
  25767. } catch (error) {
  25768. this.warn(`Callback run without blocking ${this.operationQueue} ${error}`);
  25769. }
  25770. }
  25771. }
  25772. isUpdating() {
  25773. return this.sourceBuffers.some(([type, sb]) => type && sb.updating);
  25774. }
  25775. isQueued() {
  25776. return this.sourceBuffers.some(([type]) => type && !!this.currentOp(type));
  25777. }
  25778. isPending(track2) {
  25779. return !!track2 && !track2.buffer;
  25780. }
  25781. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  25782. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  25783. // upon completion, since we already do it here
  25784. blockBuffers(onUnblocked, bufferNames = this.sourceBufferTypes) {
  25785. if (!bufferNames.length) {
  25786. this.log("Blocking operation requested, but no SourceBuffers exist");
  25787. return Promise.resolve().then(onUnblocked);
  25788. }
  25789. const {
  25790. operationQueue
  25791. } = this;
  25792. const blockingOperations = bufferNames.map((type) => this.appendBlocker(type));
  25793. const audioBlocked = bufferNames.length > 1 && !!this.blockedAudioAppend;
  25794. if (audioBlocked) {
  25795. this.unblockAudio();
  25796. }
  25797. return Promise.all(blockingOperations).then((result) => {
  25798. if (operationQueue !== this.operationQueue) {
  25799. return;
  25800. }
  25801. onUnblocked();
  25802. this.stepOperationQueue(this.sourceBufferTypes);
  25803. });
  25804. }
  25805. stepOperationQueue(bufferNames) {
  25806. bufferNames.forEach((type) => {
  25807. var _this$tracks$type6;
  25808. const sb = (_this$tracks$type6 = this.tracks[type]) == null ? void 0 : _this$tracks$type6.buffer;
  25809. if (!sb || sb.updating) {
  25810. return;
  25811. }
  25812. this.shiftAndExecuteNext(type);
  25813. });
  25814. }
  25815. append(operation, type, pending) {
  25816. if (this.operationQueue) {
  25817. this.operationQueue.append(operation, type, pending);
  25818. }
  25819. }
  25820. appendBlocker(type) {
  25821. if (this.operationQueue) {
  25822. return this.operationQueue.appendBlocker(type);
  25823. }
  25824. }
  25825. currentOp(type) {
  25826. if (this.operationQueue) {
  25827. return this.operationQueue.current(type);
  25828. }
  25829. return null;
  25830. }
  25831. executeNext(type) {
  25832. if (type && this.operationQueue) {
  25833. this.operationQueue.executeNext(type);
  25834. }
  25835. }
  25836. shiftAndExecuteNext(type) {
  25837. if (this.operationQueue) {
  25838. this.operationQueue.shiftAndExecuteNext(type);
  25839. }
  25840. }
  25841. get pendingTrackCount() {
  25842. return Object.keys(this.tracks).reduce((acc, type) => acc + (this.isPending(this.tracks[type]) ? 1 : 0), 0);
  25843. }
  25844. get sourceBufferCount() {
  25845. return this.sourceBuffers.reduce((acc, [type]) => acc + (type ? 1 : 0), 0);
  25846. }
  25847. get sourceBufferTypes() {
  25848. return this.sourceBuffers.map(([type]) => type).filter((type) => !!type);
  25849. }
  25850. addBufferListener(type, event, fn2) {
  25851. const track2 = this.tracks[type];
  25852. if (!track2) {
  25853. return;
  25854. }
  25855. const buffer2 = track2.buffer;
  25856. if (!buffer2) {
  25857. return;
  25858. }
  25859. const listener = fn2.bind(this, type);
  25860. track2.listeners.push({
  25861. event,
  25862. listener
  25863. });
  25864. buffer2.addEventListener(event, listener);
  25865. }
  25866. removeBufferListeners(type) {
  25867. const track2 = this.tracks[type];
  25868. if (!track2) {
  25869. return;
  25870. }
  25871. const buffer2 = track2.buffer;
  25872. if (!buffer2) {
  25873. return;
  25874. }
  25875. track2.listeners.forEach((l2) => {
  25876. buffer2.removeEventListener(l2.event, l2.listener);
  25877. });
  25878. track2.listeners.length = 0;
  25879. }
  25880. }
  25881. function removeSourceChildren(node) {
  25882. const sourceChildren = node.querySelectorAll("source");
  25883. [].slice.call(sourceChildren).forEach((source) => {
  25884. node.removeChild(source);
  25885. });
  25886. }
  25887. function addSource(media, url) {
  25888. const source = self.document.createElement("source");
  25889. source.type = "video/mp4";
  25890. source.src = url;
  25891. media.appendChild(source);
  25892. }
  25893. function sourceBufferNameToIndex(type) {
  25894. return type === "audio" ? 1 : 0;
  25895. }
  25896. class CapLevelController {
  25897. constructor(hls) {
  25898. this.hls = void 0;
  25899. this.autoLevelCapping = void 0;
  25900. this.firstLevel = void 0;
  25901. this.media = void 0;
  25902. this.restrictedLevels = void 0;
  25903. this.timer = void 0;
  25904. this.clientRect = void 0;
  25905. this.streamController = void 0;
  25906. this.hls = hls;
  25907. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  25908. this.firstLevel = -1;
  25909. this.media = null;
  25910. this.restrictedLevels = [];
  25911. this.timer = void 0;
  25912. this.clientRect = null;
  25913. this.registerListeners();
  25914. }
  25915. setStreamController(streamController) {
  25916. this.streamController = streamController;
  25917. }
  25918. destroy() {
  25919. if (this.hls) {
  25920. this.unregisterListener();
  25921. }
  25922. if (this.timer) {
  25923. this.stopCapping();
  25924. }
  25925. this.media = null;
  25926. this.clientRect = null;
  25927. this.hls = this.streamController = null;
  25928. }
  25929. registerListeners() {
  25930. const {
  25931. hls
  25932. } = this;
  25933. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  25934. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  25935. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  25936. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  25937. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  25938. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25939. }
  25940. unregisterListener() {
  25941. const {
  25942. hls
  25943. } = this;
  25944. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  25945. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  25946. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  25947. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  25948. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  25949. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25950. }
  25951. onFpsDropLevelCapping(event, data) {
  25952. const level = this.hls.levels[data.droppedLevel];
  25953. if (this.isLevelAllowed(level)) {
  25954. this.restrictedLevels.push({
  25955. bitrate: level.bitrate,
  25956. height: level.height,
  25957. width: level.width
  25958. });
  25959. }
  25960. }
  25961. onMediaAttaching(event, data) {
  25962. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  25963. this.clientRect = null;
  25964. if (this.timer && this.hls.levels.length) {
  25965. this.detectPlayerSize();
  25966. }
  25967. }
  25968. onManifestParsed(event, data) {
  25969. const hls = this.hls;
  25970. this.restrictedLevels = [];
  25971. this.firstLevel = data.firstLevel;
  25972. if (hls.config.capLevelToPlayerSize && data.video) {
  25973. this.startCapping();
  25974. }
  25975. }
  25976. onLevelsUpdated(event, data) {
  25977. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  25978. this.detectPlayerSize();
  25979. }
  25980. }
  25981. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  25982. // to the first level
  25983. onBufferCodecs(event, data) {
  25984. const hls = this.hls;
  25985. if (hls.config.capLevelToPlayerSize && data.video) {
  25986. this.startCapping();
  25987. }
  25988. }
  25989. onMediaDetaching() {
  25990. this.stopCapping();
  25991. this.media = null;
  25992. }
  25993. detectPlayerSize() {
  25994. if (this.media) {
  25995. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  25996. this.clientRect = null;
  25997. return;
  25998. }
  25999. const levels = this.hls.levels;
  26000. if (levels.length) {
  26001. const hls = this.hls;
  26002. const maxLevel = this.getMaxLevel(levels.length - 1);
  26003. if (maxLevel !== this.autoLevelCapping) {
  26004. hls.logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);
  26005. }
  26006. hls.autoLevelCapping = maxLevel;
  26007. if (hls.autoLevelEnabled && hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  26008. this.streamController.nextLevelSwitch();
  26009. }
  26010. this.autoLevelCapping = hls.autoLevelCapping;
  26011. }
  26012. }
  26013. }
  26014. /*
  26015. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  26016. */
  26017. getMaxLevel(capLevelIndex) {
  26018. const levels = this.hls.levels;
  26019. if (!levels.length) {
  26020. return -1;
  26021. }
  26022. const validLevels = levels.filter((level, index2) => this.isLevelAllowed(level) && index2 <= capLevelIndex);
  26023. this.clientRect = null;
  26024. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  26025. }
  26026. startCapping() {
  26027. if (this.timer) {
  26028. return;
  26029. }
  26030. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  26031. self.clearInterval(this.timer);
  26032. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1e3);
  26033. this.detectPlayerSize();
  26034. }
  26035. stopCapping() {
  26036. this.restrictedLevels = [];
  26037. this.firstLevel = -1;
  26038. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  26039. if (this.timer) {
  26040. self.clearInterval(this.timer);
  26041. this.timer = void 0;
  26042. }
  26043. }
  26044. getDimensions() {
  26045. if (this.clientRect) {
  26046. return this.clientRect;
  26047. }
  26048. const media = this.media;
  26049. const boundsRect = {
  26050. width: 0,
  26051. height: 0
  26052. };
  26053. if (media) {
  26054. const clientRect = media.getBoundingClientRect();
  26055. boundsRect.width = clientRect.width;
  26056. boundsRect.height = clientRect.height;
  26057. if (!boundsRect.width && !boundsRect.height) {
  26058. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  26059. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  26060. }
  26061. }
  26062. this.clientRect = boundsRect;
  26063. return boundsRect;
  26064. }
  26065. get mediaWidth() {
  26066. return this.getDimensions().width * this.contentScaleFactor;
  26067. }
  26068. get mediaHeight() {
  26069. return this.getDimensions().height * this.contentScaleFactor;
  26070. }
  26071. get contentScaleFactor() {
  26072. let pixelRatio = 1;
  26073. if (!this.hls.config.ignoreDevicePixelRatio) {
  26074. try {
  26075. pixelRatio = self.devicePixelRatio;
  26076. } catch (e2) {
  26077. }
  26078. }
  26079. return Math.min(pixelRatio, this.hls.config.maxDevicePixelRatio);
  26080. }
  26081. isLevelAllowed(level) {
  26082. const restrictedLevels = this.restrictedLevels;
  26083. return !restrictedLevels.some((restrictedLevel) => {
  26084. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  26085. });
  26086. }
  26087. static getMaxLevelByMediaSize(levels, width, height) {
  26088. if (!(levels != null && levels.length)) {
  26089. return -1;
  26090. }
  26091. const atGreatestBandwidth = (curLevel, nextLevel) => {
  26092. if (!nextLevel) {
  26093. return true;
  26094. }
  26095. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  26096. };
  26097. let maxLevelIndex = levels.length - 1;
  26098. const squareSize = Math.max(width, height);
  26099. for (let i2 = 0; i2 < levels.length; i2 += 1) {
  26100. const level = levels[i2];
  26101. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i2 + 1])) {
  26102. maxLevelIndex = i2;
  26103. break;
  26104. }
  26105. }
  26106. return maxLevelIndex;
  26107. }
  26108. }
  26109. const CmObjectType = {
  26110. /**
  26111. * text file, such as a manifest or playlist
  26112. */
  26113. MANIFEST: "m",
  26114. /**
  26115. * audio only
  26116. */
  26117. AUDIO: "a",
  26118. /**
  26119. * video only
  26120. */
  26121. VIDEO: "v",
  26122. /**
  26123. * muxed audio and video
  26124. */
  26125. MUXED: "av",
  26126. /**
  26127. * init segment
  26128. */
  26129. INIT: "i",
  26130. /**
  26131. * caption or subtitle
  26132. */
  26133. CAPTION: "c",
  26134. /**
  26135. * ISOBMFF timed text track
  26136. */
  26137. TIMED_TEXT: "tt",
  26138. /**
  26139. * cryptographic key, license or certificate.
  26140. */
  26141. KEY: "k",
  26142. /**
  26143. * other
  26144. */
  26145. OTHER: "o"
  26146. };
  26147. const CmcdObjectType = CmObjectType;
  26148. const CmStreamingFormat = {
  26149. /**
  26150. * HTTP Live Streaming (HLS)
  26151. */
  26152. HLS: "h"
  26153. };
  26154. const CmcdStreamingFormat = CmStreamingFormat;
  26155. const CMCD_OBJECT = "CMCD-Object";
  26156. const CMCD_REQUEST = "CMCD-Request";
  26157. const CMCD_SESSION = "CMCD-Session";
  26158. const CMCD_STATUS = "CMCD-Status";
  26159. const CmcdHeaderField = {
  26160. /**
  26161. * keys whose values vary with the object being requested.
  26162. */
  26163. OBJECT: CMCD_OBJECT,
  26164. /**
  26165. * keys whose values vary with each request.
  26166. */
  26167. REQUEST: CMCD_REQUEST,
  26168. /**
  26169. * keys whose values are expected to be invariant over the life of the session.
  26170. */
  26171. SESSION: CMCD_SESSION,
  26172. /**
  26173. * keys whose values do not vary with every request or object.
  26174. */
  26175. STATUS: CMCD_STATUS
  26176. };
  26177. const CmcdHeaderMap = {
  26178. [CmcdHeaderField.OBJECT]: ["br", "ab", "d", "ot", "tb", "tpb", "lb", "tab", "lab", "url"],
  26179. [CmcdHeaderField.REQUEST]: ["pb", "bl", "tbl", "dl", "ltc", "mtp", "nor", "nrr", "rc", "sn", "sta", "su", "ttfb", "ttfbb", "ttlb", "cmsdd", "cmsds", "smrt", "df", "cs"],
  26180. [CmcdHeaderField.SESSION]: ["cid", "pr", "sf", "sid", "st", "v", "msd"],
  26181. [CmcdHeaderField.STATUS]: ["bs", "bsd", "cdn", "rtp", "bg", "pt", "ec", "e"]
  26182. };
  26183. class SfItem {
  26184. constructor(value, params) {
  26185. if (Array.isArray(value)) {
  26186. value = value.map((v2) => v2 instanceof SfItem ? v2 : new SfItem(v2));
  26187. }
  26188. this.value = value;
  26189. this.params = params;
  26190. }
  26191. }
  26192. const DICT = "Dict";
  26193. function format(value) {
  26194. if (Array.isArray(value)) {
  26195. return JSON.stringify(value);
  26196. }
  26197. if (value instanceof Map) {
  26198. return "Map{}";
  26199. }
  26200. if (value instanceof Set) {
  26201. return "Set{}";
  26202. }
  26203. if (typeof value === "object") {
  26204. return JSON.stringify(value);
  26205. }
  26206. return String(value);
  26207. }
  26208. function throwError(action, src, type, cause) {
  26209. return new Error(`failed to ${action} "${format(src)}" as ${type}`, {
  26210. cause
  26211. });
  26212. }
  26213. function serializeError(src, type, cause) {
  26214. return throwError("serialize", src, type, cause);
  26215. }
  26216. class SfToken {
  26217. constructor(description) {
  26218. this.description = description;
  26219. }
  26220. }
  26221. const BARE_ITEM = "Bare Item";
  26222. const BOOLEAN = "Boolean";
  26223. function serializeBoolean(value) {
  26224. if (typeof value !== "boolean") {
  26225. throw serializeError(value, BOOLEAN);
  26226. }
  26227. return value ? "?1" : "?0";
  26228. }
  26229. function encodeBase64(binary) {
  26230. return btoa(String.fromCharCode(...binary));
  26231. }
  26232. const BYTES = "Byte Sequence";
  26233. function serializeByteSequence(value) {
  26234. if (ArrayBuffer.isView(value) === false) {
  26235. throw serializeError(value, BYTES);
  26236. }
  26237. return `:${encodeBase64(value)}:`;
  26238. }
  26239. const INTEGER = "Integer";
  26240. function isInvalidInt(value) {
  26241. return value < -999999999999999 || 999999999999999 < value;
  26242. }
  26243. function serializeInteger(value) {
  26244. if (isInvalidInt(value)) {
  26245. throw serializeError(value, INTEGER);
  26246. }
  26247. return value.toString();
  26248. }
  26249. function serializeDate(value) {
  26250. return `@${serializeInteger(value.getTime() / 1e3)}`;
  26251. }
  26252. function roundToEven(value, precision) {
  26253. if (value < 0) {
  26254. return -roundToEven(-value, precision);
  26255. }
  26256. const decimalShift = Math.pow(10, precision);
  26257. const isEquidistant = Math.abs(value * decimalShift % 1 - 0.5) < Number.EPSILON;
  26258. if (isEquidistant) {
  26259. const flooredValue = Math.floor(value * decimalShift);
  26260. return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;
  26261. } else {
  26262. return Math.round(value * decimalShift) / decimalShift;
  26263. }
  26264. }
  26265. const DECIMAL = "Decimal";
  26266. function serializeDecimal(value) {
  26267. const roundedValue = roundToEven(value, 3);
  26268. if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {
  26269. throw serializeError(value, DECIMAL);
  26270. }
  26271. const stringValue = roundedValue.toString();
  26272. return stringValue.includes(".") ? stringValue : `${stringValue}.0`;
  26273. }
  26274. const STRING = "String";
  26275. const STRING_REGEX = /[\x00-\x1f\x7f]+/;
  26276. function serializeString(value) {
  26277. if (STRING_REGEX.test(value)) {
  26278. throw serializeError(value, STRING);
  26279. }
  26280. return `"${value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`)}"`;
  26281. }
  26282. function symbolToStr(symbol) {
  26283. return symbol.description || symbol.toString().slice(7, -1);
  26284. }
  26285. const TOKEN = "Token";
  26286. function serializeToken(token) {
  26287. const value = symbolToStr(token);
  26288. if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value) === false) {
  26289. throw serializeError(value, TOKEN);
  26290. }
  26291. return value;
  26292. }
  26293. function serializeBareItem(value) {
  26294. switch (typeof value) {
  26295. case "number":
  26296. if (!isFiniteNumber(value)) {
  26297. throw serializeError(value, BARE_ITEM);
  26298. }
  26299. if (Number.isInteger(value)) {
  26300. return serializeInteger(value);
  26301. }
  26302. return serializeDecimal(value);
  26303. case "string":
  26304. return serializeString(value);
  26305. case "symbol":
  26306. return serializeToken(value);
  26307. case "boolean":
  26308. return serializeBoolean(value);
  26309. case "object":
  26310. if (value instanceof Date) {
  26311. return serializeDate(value);
  26312. }
  26313. if (value instanceof Uint8Array) {
  26314. return serializeByteSequence(value);
  26315. }
  26316. if (value instanceof SfToken) {
  26317. return serializeToken(value);
  26318. }
  26319. default:
  26320. throw serializeError(value, BARE_ITEM);
  26321. }
  26322. }
  26323. const KEY = "Key";
  26324. function serializeKey(value) {
  26325. if (/^[a-z*][a-z0-9\-_.*]*$/.test(value) === false) {
  26326. throw serializeError(value, KEY);
  26327. }
  26328. return value;
  26329. }
  26330. function serializeParams(params) {
  26331. if (params == null) {
  26332. return "";
  26333. }
  26334. return Object.entries(params).map(([key, value]) => {
  26335. if (value === true) {
  26336. return `;${serializeKey(key)}`;
  26337. }
  26338. return `;${serializeKey(key)}=${serializeBareItem(value)}`;
  26339. }).join("");
  26340. }
  26341. function serializeItem(value) {
  26342. if (value instanceof SfItem) {
  26343. return `${serializeBareItem(value.value)}${serializeParams(value.params)}`;
  26344. } else {
  26345. return serializeBareItem(value);
  26346. }
  26347. }
  26348. function serializeInnerList(value) {
  26349. return `(${value.value.map(serializeItem).join(" ")})${serializeParams(value.params)}`;
  26350. }
  26351. function serializeDict(dict, options = {
  26352. whitespace: true
  26353. }) {
  26354. if (typeof dict !== "object") {
  26355. throw serializeError(dict, DICT);
  26356. }
  26357. const entries = dict instanceof Map ? dict.entries() : Object.entries(dict);
  26358. const optionalWhiteSpace = (options === null || options === void 0 ? void 0 : options.whitespace) ? " " : "";
  26359. return Array.from(entries).map(([key, item]) => {
  26360. if (item instanceof SfItem === false) {
  26361. item = new SfItem(item);
  26362. }
  26363. let output = serializeKey(key);
  26364. if (item.value === true) {
  26365. output += serializeParams(item.params);
  26366. } else {
  26367. output += "=";
  26368. if (Array.isArray(item.value)) {
  26369. output += serializeInnerList(item);
  26370. } else {
  26371. output += serializeItem(item);
  26372. }
  26373. }
  26374. return output;
  26375. }).join(`,${optionalWhiteSpace}`);
  26376. }
  26377. function encodeSfDict(value, options) {
  26378. return serializeDict(value, options);
  26379. }
  26380. function isTokenField(key) {
  26381. return ["ot", "sf", "st", "e", "sta"].includes(key);
  26382. }
  26383. function isValid(value) {
  26384. if (typeof value === "number") {
  26385. return isFiniteNumber(value);
  26386. }
  26387. return value != null && value !== "" && value !== false;
  26388. }
  26389. function urlToRelativePath(url, base) {
  26390. const to = new URL(url);
  26391. const from = new URL(base);
  26392. if (to.origin !== from.origin) {
  26393. return url;
  26394. }
  26395. const toPath = to.pathname.split("/").slice(1);
  26396. const fromPath = from.pathname.split("/").slice(1, -1);
  26397. while (toPath[0] === fromPath[0]) {
  26398. toPath.shift();
  26399. fromPath.shift();
  26400. }
  26401. while (fromPath.length) {
  26402. fromPath.shift();
  26403. toPath.unshift("..");
  26404. }
  26405. return toPath.join("/");
  26406. }
  26407. const toRounded = (value) => Math.round(value);
  26408. const toUrlSafe = (value, options) => {
  26409. if (options === null || options === void 0 ? void 0 : options.baseUrl) {
  26410. value = urlToRelativePath(value, options.baseUrl);
  26411. }
  26412. return encodeURIComponent(value);
  26413. };
  26414. const toHundred = (value) => toRounded(value / 100) * 100;
  26415. const CmcdFormatters = {
  26416. /**
  26417. * Bitrate (kbps) rounded integer
  26418. */
  26419. br: toRounded,
  26420. /**
  26421. * Duration (milliseconds) rounded integer
  26422. */
  26423. d: toRounded,
  26424. /**
  26425. * Buffer Length (milliseconds) rounded nearest 100ms
  26426. */
  26427. bl: toHundred,
  26428. /**
  26429. * Deadline (milliseconds) rounded nearest 100ms
  26430. */
  26431. dl: toHundred,
  26432. /**
  26433. * Measured Throughput (kbps) rounded nearest 100kbps
  26434. */
  26435. mtp: toHundred,
  26436. /**
  26437. * Next Object Request URL encoded
  26438. */
  26439. nor: toUrlSafe,
  26440. /**
  26441. * Requested maximum throughput (kbps) rounded nearest 100kbps
  26442. */
  26443. rtp: toHundred,
  26444. /**
  26445. * Top Bitrate (kbps) rounded integer
  26446. */
  26447. tb: toRounded
  26448. };
  26449. function processCmcd(obj, options) {
  26450. const results = {};
  26451. if (obj == null || typeof obj !== "object") {
  26452. return results;
  26453. }
  26454. const keys = Object.keys(obj).sort();
  26455. const formatters = _extends({}, CmcdFormatters, options === null || options === void 0 ? void 0 : options.formatters);
  26456. const filter = options === null || options === void 0 ? void 0 : options.filter;
  26457. keys.forEach((key) => {
  26458. if ((filter === null || filter === void 0 ? void 0 : filter(key)) === false) {
  26459. return;
  26460. }
  26461. let value = obj[key];
  26462. const formatter = formatters[key];
  26463. if (formatter) {
  26464. value = formatter(value, options);
  26465. }
  26466. if (key === "v" && value === 1) {
  26467. return;
  26468. }
  26469. if (key == "pr" && value === 1) {
  26470. return;
  26471. }
  26472. if (!isValid(value)) {
  26473. return;
  26474. }
  26475. if (isTokenField(key) && typeof value === "string") {
  26476. value = new SfToken(value);
  26477. }
  26478. results[key] = value;
  26479. });
  26480. return results;
  26481. }
  26482. function encodeCmcd(cmcd, options = {}) {
  26483. if (!cmcd) {
  26484. return "";
  26485. }
  26486. return encodeSfDict(processCmcd(cmcd, options), _extends({
  26487. whitespace: false
  26488. }, options));
  26489. }
  26490. function toCmcdHeaders(cmcd, options = {}) {
  26491. const result = {};
  26492. if (!cmcd) {
  26493. return result;
  26494. }
  26495. const entries = Object.entries(cmcd);
  26496. const headerMap = Object.entries(CmcdHeaderMap).concat(Object.entries((options === null || options === void 0 ? void 0 : options.customHeaderMap) || {}));
  26497. const shards = entries.reduce((acc, entry) => {
  26498. var _a, _b;
  26499. const [key, value] = entry;
  26500. const field = ((_a = headerMap.find((entry2) => entry2[1].includes(key))) === null || _a === void 0 ? void 0 : _a[0]) || CmcdHeaderField.REQUEST;
  26501. (_b = acc[field]) !== null && _b !== void 0 ? _b : acc[field] = {};
  26502. acc[field][key] = value;
  26503. return acc;
  26504. }, {});
  26505. return Object.entries(shards).reduce((acc, [field, value]) => {
  26506. acc[field] = encodeCmcd(value, options);
  26507. return acc;
  26508. }, result);
  26509. }
  26510. function appendCmcdHeaders(headers, cmcd, options) {
  26511. return _extends(headers, toCmcdHeaders(cmcd, options));
  26512. }
  26513. const CMCD_PARAM = "CMCD";
  26514. function toCmcdQuery(cmcd, options = {}) {
  26515. if (!cmcd) {
  26516. return "";
  26517. }
  26518. const params = encodeCmcd(cmcd, options);
  26519. return `${CMCD_PARAM}=${encodeURIComponent(params)}`;
  26520. }
  26521. const REGEX = /CMCD=[^&#]+/;
  26522. function appendCmcdQuery(url, cmcd, options) {
  26523. const query = toCmcdQuery(cmcd, options);
  26524. if (!query) {
  26525. return url;
  26526. }
  26527. if (REGEX.test(url)) {
  26528. return url.replace(REGEX, query);
  26529. }
  26530. const separator = url.includes("?") ? "&" : "?";
  26531. return `${url}${separator}${query}`;
  26532. }
  26533. class CMCDController {
  26534. constructor(hls) {
  26535. this.hls = void 0;
  26536. this.config = void 0;
  26537. this.media = void 0;
  26538. this.sid = void 0;
  26539. this.cid = void 0;
  26540. this.useHeaders = false;
  26541. this.includeKeys = void 0;
  26542. this.initialized = false;
  26543. this.starved = false;
  26544. this.buffering = true;
  26545. this.audioBuffer = void 0;
  26546. this.videoBuffer = void 0;
  26547. this.onWaiting = () => {
  26548. if (this.initialized) {
  26549. this.starved = true;
  26550. }
  26551. this.buffering = true;
  26552. };
  26553. this.onPlaying = () => {
  26554. if (!this.initialized) {
  26555. this.initialized = true;
  26556. }
  26557. this.buffering = false;
  26558. };
  26559. this.applyPlaylistData = (context) => {
  26560. try {
  26561. this.apply(context, {
  26562. ot: CmcdObjectType.MANIFEST,
  26563. su: !this.initialized
  26564. });
  26565. } catch (error) {
  26566. this.hls.logger.warn("Could not generate manifest CMCD data.", error);
  26567. }
  26568. };
  26569. this.applyFragmentData = (context) => {
  26570. try {
  26571. const {
  26572. frag,
  26573. part
  26574. } = context;
  26575. const level = this.hls.levels[frag.level];
  26576. const ot2 = this.getObjectType(frag);
  26577. const data = {
  26578. d: (part || frag).duration * 1e3,
  26579. ot: ot2
  26580. };
  26581. if (ot2 === CmcdObjectType.VIDEO || ot2 === CmcdObjectType.AUDIO || ot2 == CmcdObjectType.MUXED) {
  26582. data.br = level.bitrate / 1e3;
  26583. data.tb = this.getTopBandwidth(ot2) / 1e3;
  26584. data.bl = this.getBufferLength(ot2);
  26585. }
  26586. const next = part ? this.getNextPart(part) : this.getNextFrag(frag);
  26587. if (next != null && next.url && next.url !== frag.url) {
  26588. data.nor = next.url;
  26589. }
  26590. this.apply(context, data);
  26591. } catch (error) {
  26592. this.hls.logger.warn("Could not generate segment CMCD data.", error);
  26593. }
  26594. };
  26595. this.hls = hls;
  26596. const config = this.config = hls.config;
  26597. const {
  26598. cmcd
  26599. } = config;
  26600. if (cmcd != null) {
  26601. config.pLoader = this.createPlaylistLoader();
  26602. config.fLoader = this.createFragmentLoader();
  26603. this.sid = cmcd.sessionId || hls.sessionId;
  26604. this.cid = cmcd.contentId;
  26605. this.useHeaders = cmcd.useHeaders === true;
  26606. this.includeKeys = cmcd.includeKeys;
  26607. this.registerListeners();
  26608. }
  26609. }
  26610. registerListeners() {
  26611. const hls = this.hls;
  26612. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  26613. hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  26614. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  26615. }
  26616. unregisterListeners() {
  26617. const hls = this.hls;
  26618. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  26619. hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  26620. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  26621. }
  26622. destroy() {
  26623. this.unregisterListeners();
  26624. this.onMediaDetached();
  26625. this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
  26626. this.onWaiting = this.onPlaying = this.media = null;
  26627. }
  26628. onMediaAttached(event, data) {
  26629. this.media = data.media;
  26630. this.media.addEventListener("waiting", this.onWaiting);
  26631. this.media.addEventListener("playing", this.onPlaying);
  26632. }
  26633. onMediaDetached() {
  26634. if (!this.media) {
  26635. return;
  26636. }
  26637. this.media.removeEventListener("waiting", this.onWaiting);
  26638. this.media.removeEventListener("playing", this.onPlaying);
  26639. this.media = null;
  26640. }
  26641. onBufferCreated(event, data) {
  26642. var _data$tracks$audio, _data$tracks$video;
  26643. this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer;
  26644. this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer;
  26645. }
  26646. /**
  26647. * Create baseline CMCD data
  26648. */
  26649. createData() {
  26650. var _this$media;
  26651. return {
  26652. v: 1,
  26653. sf: CmcdStreamingFormat.HLS,
  26654. sid: this.sid,
  26655. cid: this.cid,
  26656. pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate,
  26657. mtp: this.hls.bandwidthEstimate / 1e3
  26658. };
  26659. }
  26660. /**
  26661. * Apply CMCD data to a request.
  26662. */
  26663. apply(context, data = {}) {
  26664. _extends(data, this.createData());
  26665. const isVideo = data.ot === CmcdObjectType.INIT || data.ot === CmcdObjectType.VIDEO || data.ot === CmcdObjectType.MUXED;
  26666. if (this.starved && isVideo) {
  26667. data.bs = true;
  26668. data.su = true;
  26669. this.starved = false;
  26670. }
  26671. if (data.su == null) {
  26672. data.su = this.buffering;
  26673. }
  26674. const {
  26675. includeKeys
  26676. } = this;
  26677. if (includeKeys) {
  26678. data = Object.keys(data).reduce((acc, key) => {
  26679. includeKeys.includes(key) && (acc[key] = data[key]);
  26680. return acc;
  26681. }, {});
  26682. }
  26683. const options = {
  26684. baseUrl: context.url
  26685. };
  26686. if (this.useHeaders) {
  26687. if (!context.headers) {
  26688. context.headers = {};
  26689. }
  26690. appendCmcdHeaders(context.headers, data, options);
  26691. } else {
  26692. context.url = appendCmcdQuery(context.url, data, options);
  26693. }
  26694. }
  26695. getNextFrag(fragment) {
  26696. var _this$hls$levels$frag;
  26697. const levelDetails = (_this$hls$levels$frag = this.hls.levels[fragment.level]) == null ? void 0 : _this$hls$levels$frag.details;
  26698. if (levelDetails) {
  26699. const index2 = fragment.sn - levelDetails.startSN;
  26700. return levelDetails.fragments[index2 + 1];
  26701. }
  26702. return void 0;
  26703. }
  26704. getNextPart(part) {
  26705. var _this$hls$levels$frag2, _this$hls$levels$frag3;
  26706. const {
  26707. index: index2,
  26708. fragment
  26709. } = part;
  26710. const partList = (_this$hls$levels$frag2 = this.hls.levels[fragment.level]) == null ? void 0 : (_this$hls$levels$frag3 = _this$hls$levels$frag2.details) == null ? void 0 : _this$hls$levels$frag3.partList;
  26711. if (partList) {
  26712. const {
  26713. sn: sn2
  26714. } = fragment;
  26715. for (let i2 = partList.length - 1; i2 >= 0; i2--) {
  26716. const p2 = partList[i2];
  26717. if (p2.index === index2 && p2.fragment.sn === sn2) {
  26718. return partList[i2 + 1];
  26719. }
  26720. }
  26721. }
  26722. return void 0;
  26723. }
  26724. /**
  26725. * The CMCD object type.
  26726. */
  26727. getObjectType(fragment) {
  26728. const {
  26729. type
  26730. } = fragment;
  26731. if (type === "subtitle") {
  26732. return CmcdObjectType.TIMED_TEXT;
  26733. }
  26734. if (fragment.sn === "initSegment") {
  26735. return CmcdObjectType.INIT;
  26736. }
  26737. if (type === "audio") {
  26738. return CmcdObjectType.AUDIO;
  26739. }
  26740. if (type === "main") {
  26741. if (!this.hls.audioTracks.length) {
  26742. return CmcdObjectType.MUXED;
  26743. }
  26744. return CmcdObjectType.VIDEO;
  26745. }
  26746. return void 0;
  26747. }
  26748. /**
  26749. * Get the highest bitrate.
  26750. */
  26751. getTopBandwidth(type) {
  26752. let bitrate = 0;
  26753. let levels;
  26754. const hls = this.hls;
  26755. if (type === CmcdObjectType.AUDIO) {
  26756. levels = hls.audioTracks;
  26757. } else {
  26758. const max = hls.maxAutoLevel;
  26759. const len = max > -1 ? max + 1 : hls.levels.length;
  26760. levels = hls.levels.slice(0, len);
  26761. }
  26762. levels.forEach((level) => {
  26763. if (level.bitrate > bitrate) {
  26764. bitrate = level.bitrate;
  26765. }
  26766. });
  26767. return bitrate > 0 ? bitrate : NaN;
  26768. }
  26769. /**
  26770. * Get the buffer length for a media type in milliseconds
  26771. */
  26772. getBufferLength(type) {
  26773. const media = this.media;
  26774. const buffer2 = type === CmcdObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;
  26775. if (!buffer2 || !media) {
  26776. return NaN;
  26777. }
  26778. const info = BufferHelper.bufferInfo(buffer2, media.currentTime, this.config.maxBufferHole);
  26779. return info.len * 1e3;
  26780. }
  26781. /**
  26782. * Create a playlist loader
  26783. */
  26784. createPlaylistLoader() {
  26785. const {
  26786. pLoader
  26787. } = this.config;
  26788. const apply = this.applyPlaylistData;
  26789. const Ctor = pLoader || this.config.loader;
  26790. return class CmcdPlaylistLoader {
  26791. constructor(config) {
  26792. this.loader = void 0;
  26793. this.loader = new Ctor(config);
  26794. }
  26795. get stats() {
  26796. return this.loader.stats;
  26797. }
  26798. get context() {
  26799. return this.loader.context;
  26800. }
  26801. destroy() {
  26802. this.loader.destroy();
  26803. }
  26804. abort() {
  26805. this.loader.abort();
  26806. }
  26807. load(context, config, callbacks) {
  26808. apply(context);
  26809. this.loader.load(context, config, callbacks);
  26810. }
  26811. };
  26812. }
  26813. /**
  26814. * Create a playlist loader
  26815. */
  26816. createFragmentLoader() {
  26817. const {
  26818. fLoader
  26819. } = this.config;
  26820. const apply = this.applyFragmentData;
  26821. const Ctor = fLoader || this.config.loader;
  26822. return class CmcdFragmentLoader {
  26823. constructor(config) {
  26824. this.loader = void 0;
  26825. this.loader = new Ctor(config);
  26826. }
  26827. get stats() {
  26828. return this.loader.stats;
  26829. }
  26830. get context() {
  26831. return this.loader.context;
  26832. }
  26833. destroy() {
  26834. this.loader.destroy();
  26835. }
  26836. abort() {
  26837. this.loader.abort();
  26838. }
  26839. load(context, config, callbacks) {
  26840. apply(context);
  26841. this.loader.load(context, config, callbacks);
  26842. }
  26843. };
  26844. }
  26845. }
  26846. const PATHWAY_PENALTY_DURATION_MS = 3e5;
  26847. class ContentSteeringController extends Logger {
  26848. constructor(hls) {
  26849. super("content-steering", hls.logger);
  26850. this.hls = void 0;
  26851. this.loader = null;
  26852. this.uri = null;
  26853. this.pathwayId = ".";
  26854. this._pathwayPriority = null;
  26855. this.timeToLoad = 300;
  26856. this.reloadTimer = -1;
  26857. this.updated = 0;
  26858. this.started = false;
  26859. this.enabled = true;
  26860. this.levels = null;
  26861. this.audioTracks = null;
  26862. this.subtitleTracks = null;
  26863. this.penalizedPathways = {};
  26864. this.hls = hls;
  26865. this.registerListeners();
  26866. }
  26867. registerListeners() {
  26868. const hls = this.hls;
  26869. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  26870. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  26871. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  26872. hls.on(Events.ERROR, this.onError, this);
  26873. }
  26874. unregisterListeners() {
  26875. const hls = this.hls;
  26876. if (!hls) {
  26877. return;
  26878. }
  26879. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  26880. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  26881. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  26882. hls.off(Events.ERROR, this.onError, this);
  26883. }
  26884. pathways() {
  26885. return (this.levels || []).reduce((pathways, level) => {
  26886. if (pathways.indexOf(level.pathwayId) === -1) {
  26887. pathways.push(level.pathwayId);
  26888. }
  26889. return pathways;
  26890. }, []);
  26891. }
  26892. get pathwayPriority() {
  26893. return this._pathwayPriority;
  26894. }
  26895. set pathwayPriority(pathwayPriority) {
  26896. this.updatePathwayPriority(pathwayPriority);
  26897. }
  26898. startLoad() {
  26899. this.started = true;
  26900. this.clearTimeout();
  26901. if (this.enabled && this.uri) {
  26902. if (this.updated) {
  26903. const ttl = this.timeToLoad * 1e3 - (performance.now() - this.updated);
  26904. if (ttl > 0) {
  26905. this.scheduleRefresh(this.uri, ttl);
  26906. return;
  26907. }
  26908. }
  26909. this.loadSteeringManifest(this.uri);
  26910. }
  26911. }
  26912. stopLoad() {
  26913. this.started = false;
  26914. if (this.loader) {
  26915. this.loader.destroy();
  26916. this.loader = null;
  26917. }
  26918. this.clearTimeout();
  26919. }
  26920. clearTimeout() {
  26921. if (this.reloadTimer !== -1) {
  26922. self.clearTimeout(this.reloadTimer);
  26923. this.reloadTimer = -1;
  26924. }
  26925. }
  26926. destroy() {
  26927. this.unregisterListeners();
  26928. this.stopLoad();
  26929. this.hls = null;
  26930. this.levels = this.audioTracks = this.subtitleTracks = null;
  26931. }
  26932. removeLevel(levelToRemove) {
  26933. const levels = this.levels;
  26934. if (levels) {
  26935. this.levels = levels.filter((level) => level !== levelToRemove);
  26936. }
  26937. }
  26938. onManifestLoading() {
  26939. this.stopLoad();
  26940. this.enabled = true;
  26941. this.timeToLoad = 300;
  26942. this.updated = 0;
  26943. this.uri = null;
  26944. this.pathwayId = ".";
  26945. this.levels = this.audioTracks = this.subtitleTracks = null;
  26946. }
  26947. onManifestLoaded(event, data) {
  26948. const {
  26949. contentSteering
  26950. } = data;
  26951. if (contentSteering === null) {
  26952. return;
  26953. }
  26954. this.pathwayId = contentSteering.pathwayId;
  26955. this.uri = contentSteering.uri;
  26956. if (this.started) {
  26957. this.startLoad();
  26958. }
  26959. }
  26960. onManifestParsed(event, data) {
  26961. this.audioTracks = data.audioTracks;
  26962. this.subtitleTracks = data.subtitleTracks;
  26963. }
  26964. onError(event, data) {
  26965. const {
  26966. errorAction
  26967. } = data;
  26968. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  26969. const levels = this.levels;
  26970. let pathwayPriority = this._pathwayPriority;
  26971. let errorPathway = this.pathwayId;
  26972. if (data.context) {
  26973. const {
  26974. groupId,
  26975. pathwayId,
  26976. type
  26977. } = data.context;
  26978. if (groupId && levels) {
  26979. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  26980. } else if (pathwayId) {
  26981. errorPathway = pathwayId;
  26982. }
  26983. }
  26984. if (!(errorPathway in this.penalizedPathways)) {
  26985. this.penalizedPathways[errorPathway] = performance.now();
  26986. }
  26987. if (!pathwayPriority && levels) {
  26988. pathwayPriority = this.pathways();
  26989. }
  26990. if (pathwayPriority && pathwayPriority.length > 1) {
  26991. this.updatePathwayPriority(pathwayPriority);
  26992. errorAction.resolved = this.pathwayId !== errorPathway;
  26993. }
  26994. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && !data.fatal) {
  26995. errorAction.resolved = true;
  26996. } else if (!errorAction.resolved) {
  26997. this.warn(`Could not resolve ${data.details} ("${data.error.message}") with content-steering for Pathway: ${errorPathway} levels: ${levels ? levels.length : levels} priorities: ${stringify(pathwayPriority)} penalized: ${stringify(this.penalizedPathways)}`);
  26998. }
  26999. }
  27000. }
  27001. filterParsedLevels(levels) {
  27002. this.levels = levels;
  27003. let pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  27004. if (pathwayLevels.length === 0) {
  27005. const pathwayId = levels[0].pathwayId;
  27006. this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`);
  27007. pathwayLevels = this.getLevelsForPathway(pathwayId);
  27008. this.pathwayId = pathwayId;
  27009. }
  27010. if (pathwayLevels.length !== levels.length) {
  27011. this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`);
  27012. }
  27013. return pathwayLevels;
  27014. }
  27015. getLevelsForPathway(pathwayId) {
  27016. if (this.levels === null) {
  27017. return [];
  27018. }
  27019. return this.levels.filter((level) => pathwayId === level.pathwayId);
  27020. }
  27021. updatePathwayPriority(pathwayPriority) {
  27022. this._pathwayPriority = pathwayPriority;
  27023. let levels;
  27024. const penalizedPathways = this.penalizedPathways;
  27025. const now2 = performance.now();
  27026. Object.keys(penalizedPathways).forEach((pathwayId) => {
  27027. if (now2 - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  27028. delete penalizedPathways[pathwayId];
  27029. }
  27030. });
  27031. for (let i2 = 0; i2 < pathwayPriority.length; i2++) {
  27032. const pathwayId = pathwayPriority[i2];
  27033. if (pathwayId in penalizedPathways) {
  27034. continue;
  27035. }
  27036. if (pathwayId === this.pathwayId) {
  27037. return;
  27038. }
  27039. const selectedIndex = this.hls.nextLoadLevel;
  27040. const selectedLevel = this.hls.levels[selectedIndex];
  27041. levels = this.getLevelsForPathway(pathwayId);
  27042. if (levels.length > 0) {
  27043. this.log(`Setting Pathway to "${pathwayId}"`);
  27044. this.pathwayId = pathwayId;
  27045. reassignFragmentLevelIndexes(levels);
  27046. this.hls.trigger(Events.LEVELS_UPDATED, {
  27047. levels
  27048. });
  27049. const levelAfterChange = this.hls.levels[selectedIndex];
  27050. if (selectedLevel && levelAfterChange && this.levels) {
  27051. if (levelAfterChange.attrs["STABLE-VARIANT-ID"] !== selectedLevel.attrs["STABLE-VARIANT-ID"] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  27052. this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);
  27053. }
  27054. this.hls.nextLoadLevel = selectedIndex;
  27055. }
  27056. break;
  27057. }
  27058. }
  27059. }
  27060. getPathwayForGroupId(groupId, type, defaultPathway) {
  27061. const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  27062. for (let i2 = 0; i2 < levels.length; i2++) {
  27063. if (type === PlaylistContextType.AUDIO_TRACK && levels[i2].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i2].hasSubtitleGroup(groupId)) {
  27064. return levels[i2].pathwayId;
  27065. }
  27066. }
  27067. return defaultPathway;
  27068. }
  27069. clonePathways(pathwayClones) {
  27070. const levels = this.levels;
  27071. if (!levels) {
  27072. return;
  27073. }
  27074. const audioGroupCloneMap = {};
  27075. const subtitleGroupCloneMap = {};
  27076. pathwayClones.forEach((pathwayClone) => {
  27077. const {
  27078. ID: cloneId,
  27079. "BASE-ID": baseId,
  27080. "URI-REPLACEMENT": uriReplacement
  27081. } = pathwayClone;
  27082. if (levels.some((level) => level.pathwayId === cloneId)) {
  27083. return;
  27084. }
  27085. const clonedVariants = this.getLevelsForPathway(baseId).map((baseLevel) => {
  27086. const attributes = new AttrList(baseLevel.attrs);
  27087. attributes["PATHWAY-ID"] = cloneId;
  27088. const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;
  27089. const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;
  27090. if (clonedAudioGroupId) {
  27091. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  27092. attributes.AUDIO = clonedAudioGroupId;
  27093. }
  27094. if (clonedSubtitleGroupId) {
  27095. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  27096. attributes.SUBTITLES = clonedSubtitleGroupId;
  27097. }
  27098. const url = performUriReplacement(baseLevel.uri, attributes["STABLE-VARIANT-ID"], "PER-VARIANT-URIS", uriReplacement);
  27099. const clonedLevel = new Level({
  27100. attrs: attributes,
  27101. audioCodec: baseLevel.audioCodec,
  27102. bitrate: baseLevel.bitrate,
  27103. height: baseLevel.height,
  27104. name: baseLevel.name,
  27105. url,
  27106. videoCodec: baseLevel.videoCodec,
  27107. width: baseLevel.width
  27108. });
  27109. if (baseLevel.audioGroups) {
  27110. for (let i2 = 1; i2 < baseLevel.audioGroups.length; i2++) {
  27111. clonedLevel.addGroupId("audio", `${baseLevel.audioGroups[i2]}_clone_${cloneId}`);
  27112. }
  27113. }
  27114. if (baseLevel.subtitleGroups) {
  27115. for (let i2 = 1; i2 < baseLevel.subtitleGroups.length; i2++) {
  27116. clonedLevel.addGroupId("text", `${baseLevel.subtitleGroups[i2]}_clone_${cloneId}`);
  27117. }
  27118. }
  27119. return clonedLevel;
  27120. });
  27121. levels.push(...clonedVariants);
  27122. cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  27123. cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  27124. });
  27125. }
  27126. loadSteeringManifest(uri) {
  27127. const config = this.hls.config;
  27128. const Loader = config.loader;
  27129. if (this.loader) {
  27130. this.loader.destroy();
  27131. }
  27132. this.loader = new Loader(config);
  27133. let url;
  27134. try {
  27135. url = new self.URL(uri);
  27136. } catch (error) {
  27137. this.enabled = false;
  27138. this.log(`Failed to parse Steering Manifest URI: ${uri}`);
  27139. return;
  27140. }
  27141. if (url.protocol !== "data:") {
  27142. const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  27143. url.searchParams.set("_HLS_pathway", this.pathwayId);
  27144. url.searchParams.set("_HLS_throughput", "" + throughput);
  27145. }
  27146. const context = {
  27147. responseType: "json",
  27148. url: url.href
  27149. };
  27150. const loadPolicy = config.steeringManifestLoadPolicy.default;
  27151. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  27152. const loaderConfig = {
  27153. loadPolicy,
  27154. timeout: loadPolicy.maxLoadTimeMs,
  27155. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  27156. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  27157. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  27158. };
  27159. const callbacks = {
  27160. onSuccess: (response, stats, context2, networkDetails) => {
  27161. this.log(`Loaded steering manifest: "${url}"`);
  27162. const steeringData = response.data;
  27163. if ((steeringData == null ? void 0 : steeringData.VERSION) !== 1) {
  27164. this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);
  27165. return;
  27166. }
  27167. this.updated = performance.now();
  27168. this.timeToLoad = steeringData.TTL;
  27169. const {
  27170. "RELOAD-URI": reloadUri,
  27171. "PATHWAY-CLONES": pathwayClones,
  27172. "PATHWAY-PRIORITY": pathwayPriority
  27173. } = steeringData;
  27174. if (reloadUri) {
  27175. try {
  27176. this.uri = new self.URL(reloadUri, url).href;
  27177. } catch (error) {
  27178. this.enabled = false;
  27179. this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);
  27180. return;
  27181. }
  27182. }
  27183. this.scheduleRefresh(this.uri || context2.url);
  27184. if (pathwayClones) {
  27185. this.clonePathways(pathwayClones);
  27186. }
  27187. const loadedSteeringData = {
  27188. steeringManifest: steeringData,
  27189. url: url.toString()
  27190. };
  27191. this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  27192. if (pathwayPriority) {
  27193. this.updatePathwayPriority(pathwayPriority);
  27194. }
  27195. },
  27196. onError: (error, context2, networkDetails, stats) => {
  27197. this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context2.url})`);
  27198. this.stopLoad();
  27199. if (error.code === 410) {
  27200. this.enabled = false;
  27201. this.log(`Steering manifest ${context2.url} no longer available`);
  27202. return;
  27203. }
  27204. let ttl = this.timeToLoad * 1e3;
  27205. if (error.code === 429) {
  27206. const loader = this.loader;
  27207. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === "function") {
  27208. const retryAfter = loader.getResponseHeader("Retry-After");
  27209. if (retryAfter) {
  27210. ttl = parseFloat(retryAfter) * 1e3;
  27211. }
  27212. }
  27213. this.log(`Steering manifest ${context2.url} rate limited`);
  27214. return;
  27215. }
  27216. this.scheduleRefresh(this.uri || context2.url, ttl);
  27217. },
  27218. onTimeout: (stats, context2, networkDetails) => {
  27219. this.log(`Timeout loading steering manifest (${context2.url})`);
  27220. this.scheduleRefresh(this.uri || context2.url);
  27221. }
  27222. };
  27223. this.log(`Requesting steering manifest: ${url}`);
  27224. this.loader.load(context, loaderConfig, callbacks);
  27225. }
  27226. scheduleRefresh(uri, ttlMs = this.timeToLoad * 1e3) {
  27227. this.clearTimeout();
  27228. this.reloadTimer = self.setTimeout(() => {
  27229. var _this$hls;
  27230. const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;
  27231. if (media && !media.ended) {
  27232. this.loadSteeringManifest(uri);
  27233. return;
  27234. }
  27235. this.scheduleRefresh(uri, this.timeToLoad * 1e3);
  27236. }, ttlMs);
  27237. }
  27238. }
  27239. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  27240. if (!tracks) {
  27241. return;
  27242. }
  27243. Object.keys(groupCloneMap).forEach((audioGroupId) => {
  27244. const clonedTracks = tracks.filter((track2) => track2.groupId === audioGroupId).map((track2) => {
  27245. const clonedTrack = _extends({}, track2);
  27246. clonedTrack.details = void 0;
  27247. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  27248. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track2.url, track2.attrs["STABLE-RENDITION-ID"], "PER-RENDITION-URIS", uriReplacement);
  27249. clonedTrack.groupId = clonedTrack.attrs["GROUP-ID"] = groupCloneMap[audioGroupId];
  27250. clonedTrack.attrs["PATHWAY-ID"] = cloneId;
  27251. return clonedTrack;
  27252. });
  27253. tracks.push(...clonedTracks);
  27254. });
  27255. }
  27256. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  27257. const {
  27258. HOST: host2,
  27259. PARAMS: params,
  27260. [perOptionKey]: perOptionUris
  27261. } = uriReplacement;
  27262. let perVariantUri;
  27263. if (stableId) {
  27264. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  27265. if (perVariantUri) {
  27266. uri = perVariantUri;
  27267. }
  27268. }
  27269. const url = new self.URL(uri);
  27270. if (host2 && !perVariantUri) {
  27271. url.host = host2;
  27272. }
  27273. if (params) {
  27274. Object.keys(params).sort().forEach((key) => {
  27275. if (key) {
  27276. url.searchParams.set(key, params[key]);
  27277. }
  27278. });
  27279. }
  27280. return url.href;
  27281. }
  27282. function addEventListener(el, type, listener) {
  27283. removeEventListener(el, type, listener);
  27284. el.addEventListener(type, listener);
  27285. }
  27286. function removeEventListener(el, type, listener) {
  27287. el.removeEventListener(type, listener);
  27288. }
  27289. class EMEController extends Logger {
  27290. constructor(hls) {
  27291. super("eme", hls.logger);
  27292. this.hls = void 0;
  27293. this.config = void 0;
  27294. this.media = null;
  27295. this.keyFormatPromise = null;
  27296. this.keySystemAccessPromises = {};
  27297. this._requestLicenseFailureCount = 0;
  27298. this.mediaKeySessions = [];
  27299. this.keyIdToKeySessionPromise = {};
  27300. this.mediaKeys = null;
  27301. this.setMediaKeysQueue = EMEController.CDMCleanupPromise ? [EMEController.CDMCleanupPromise] : [];
  27302. this.onWaitingForKey = (event) => {
  27303. this.log(`"${event.type}" event`);
  27304. };
  27305. this.hls = hls;
  27306. this.config = hls.config;
  27307. this.registerListeners();
  27308. }
  27309. destroy() {
  27310. this.onDestroying();
  27311. this.onMediaDetached();
  27312. const config = this.config;
  27313. config.requestMediaKeySystemAccessFunc = null;
  27314. config.licenseXhrSetup = config.licenseResponseCallback = void 0;
  27315. config.drmSystems = config.drmSystemOptions = {};
  27316. this.hls = this.config = this.keyIdToKeySessionPromise = null;
  27317. this.onWaitingForKey = null;
  27318. }
  27319. registerListeners() {
  27320. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  27321. this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  27322. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  27323. this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  27324. this.hls.on(Events.DESTROYING, this.onDestroying, this);
  27325. }
  27326. unregisterListeners() {
  27327. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  27328. this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  27329. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  27330. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  27331. this.hls.off(Events.DESTROYING, this.onDestroying, this);
  27332. }
  27333. getLicenseServerUrl(keySystem) {
  27334. const {
  27335. drmSystems,
  27336. widevineLicenseUrl
  27337. } = this.config;
  27338. const keySystemConfiguration = drmSystems[keySystem];
  27339. if (keySystemConfiguration) {
  27340. return keySystemConfiguration.licenseUrl;
  27341. }
  27342. if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {
  27343. return widevineLicenseUrl;
  27344. }
  27345. }
  27346. getLicenseServerUrlOrThrow(keySystem) {
  27347. const url = this.getLicenseServerUrl(keySystem);
  27348. if (url === void 0) {
  27349. throw new Error(`no license server URL configured for key-system "${keySystem}"`);
  27350. }
  27351. return url;
  27352. }
  27353. getServerCertificateUrl(keySystem) {
  27354. const {
  27355. drmSystems
  27356. } = this.config;
  27357. const keySystemConfiguration = drmSystems[keySystem];
  27358. if (keySystemConfiguration) {
  27359. return keySystemConfiguration.serverCertificateUrl;
  27360. } else {
  27361. this.log(`No Server Certificate in config.drmSystems["${keySystem}"]`);
  27362. }
  27363. }
  27364. attemptKeySystemAccess(keySystemsToAttempt) {
  27365. const levels = this.hls.levels;
  27366. const uniqueCodec = (value, i2, a2) => !!value && a2.indexOf(value) === i2;
  27367. const audioCodecs = levels.map((level) => level.audioCodec).filter(uniqueCodec);
  27368. const videoCodecs = levels.map((level) => level.videoCodec).filter(uniqueCodec);
  27369. if (audioCodecs.length + videoCodecs.length === 0) {
  27370. videoCodecs.push("avc1.42e01e");
  27371. }
  27372. return new Promise((resolve2, reject) => {
  27373. const attempt = (keySystems) => {
  27374. const keySystem = keySystems.shift();
  27375. this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then((mediaKeys) => resolve2({
  27376. keySystem,
  27377. mediaKeys
  27378. })).catch((error) => {
  27379. if (keySystems.length) {
  27380. attempt(keySystems);
  27381. } else if (error instanceof EMEKeyError) {
  27382. reject(error);
  27383. } else {
  27384. reject(new EMEKeyError({
  27385. type: ErrorTypes.KEY_SYSTEM_ERROR,
  27386. details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  27387. error,
  27388. fatal: true
  27389. }, error.message));
  27390. }
  27391. });
  27392. };
  27393. attempt(keySystemsToAttempt);
  27394. });
  27395. }
  27396. requestMediaKeySystemAccess(keySystem, supportedConfigurations) {
  27397. const {
  27398. requestMediaKeySystemAccessFunc
  27399. } = this.config;
  27400. if (!(typeof requestMediaKeySystemAccessFunc === "function")) {
  27401. let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;
  27402. if (requestMediaKeySystemAccess === null && self.location.protocol === "http:") {
  27403. errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;
  27404. }
  27405. return Promise.reject(new Error(errMessage));
  27406. }
  27407. return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);
  27408. }
  27409. getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) {
  27410. const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions);
  27411. const keySystemAccessPromises = this.keySystemAccessPromises[keySystem];
  27412. let keySystemAccess = keySystemAccessPromises == null ? void 0 : keySystemAccessPromises.keySystemAccess;
  27413. if (!keySystemAccess) {
  27414. this.log(`Requesting encrypted media "${keySystem}" key-system access with config: ${stringify(mediaKeySystemConfigs)}`);
  27415. keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
  27416. const _keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = {
  27417. keySystemAccess
  27418. };
  27419. keySystemAccess.catch((error) => {
  27420. this.log(`Failed to obtain access to key-system "${keySystem}": ${error}`);
  27421. });
  27422. return keySystemAccess.then((mediaKeySystemAccess) => {
  27423. this.log(`Access for key-system "${mediaKeySystemAccess.keySystem}" obtained`);
  27424. const certificateRequest = this.fetchServerCertificate(keySystem);
  27425. this.log(`Create media-keys for "${keySystem}"`);
  27426. _keySystemAccessPromises.mediaKeys = mediaKeySystemAccess.createMediaKeys().then((mediaKeys) => {
  27427. this.log(`Media-keys created for "${keySystem}"`);
  27428. _keySystemAccessPromises.hasMediaKeys = true;
  27429. return certificateRequest.then((certificate) => {
  27430. if (certificate) {
  27431. return this.setMediaKeysServerCertificate(mediaKeys, keySystem, certificate);
  27432. }
  27433. return mediaKeys;
  27434. });
  27435. });
  27436. _keySystemAccessPromises.mediaKeys.catch((error) => {
  27437. this.error(`Failed to create media-keys for "${keySystem}"}: ${error}`);
  27438. });
  27439. return _keySystemAccessPromises.mediaKeys;
  27440. });
  27441. }
  27442. return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys);
  27443. }
  27444. createMediaKeySessionContext({
  27445. decryptdata,
  27446. keySystem,
  27447. mediaKeys
  27448. }) {
  27449. this.log(`Creating key-system session "${keySystem}" keyId: ${Hex.hexDump(decryptdata.keyId || [])}`);
  27450. const mediaKeysSession = mediaKeys.createSession();
  27451. const mediaKeySessionContext = {
  27452. decryptdata,
  27453. keySystem,
  27454. mediaKeys,
  27455. mediaKeysSession,
  27456. keyStatus: "status-pending"
  27457. };
  27458. this.mediaKeySessions.push(mediaKeySessionContext);
  27459. return mediaKeySessionContext;
  27460. }
  27461. renewKeySession(mediaKeySessionContext) {
  27462. const decryptdata = mediaKeySessionContext.decryptdata;
  27463. if (decryptdata.pssh) {
  27464. const keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext);
  27465. const keyId = this.getKeyIdString(decryptdata);
  27466. const scheme = "cenc";
  27467. this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh.buffer, "expired");
  27468. } else {
  27469. this.warn(`Could not renew expired session. Missing pssh initData.`);
  27470. }
  27471. this.removeSession(mediaKeySessionContext);
  27472. }
  27473. getKeyIdString(decryptdata) {
  27474. if (!decryptdata) {
  27475. throw new Error("Could not read keyId of undefined decryptdata");
  27476. }
  27477. if (decryptdata.keyId === null) {
  27478. throw new Error("keyId is null");
  27479. }
  27480. return Hex.hexDump(decryptdata.keyId);
  27481. }
  27482. updateKeySession(mediaKeySessionContext, data) {
  27483. var _mediaKeySessionConte;
  27484. const keySession = mediaKeySessionContext.mediaKeysSession;
  27485. this.log(`Updating key-session "${keySession.sessionId}" for keyID ${Hex.hexDump(((_mediaKeySessionConte = mediaKeySessionContext.decryptdata) == null ? void 0 : _mediaKeySessionConte.keyId) || [])}
  27486. } (data length: ${data ? data.byteLength : data})`);
  27487. return keySession.update(data);
  27488. }
  27489. getSelectedKeySystemFormats() {
  27490. return Object.keys(this.keySystemAccessPromises).map((keySystem) => ({
  27491. keySystem,
  27492. hasMediaKeys: this.keySystemAccessPromises[keySystem].hasMediaKeys
  27493. })).filter(({
  27494. hasMediaKeys
  27495. }) => !!hasMediaKeys).map(({
  27496. keySystem
  27497. }) => keySystemDomainToKeySystemFormat(keySystem)).filter((keySystem) => !!keySystem);
  27498. }
  27499. getKeySystemAccess(keySystemsToAttempt) {
  27500. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  27501. keySystem,
  27502. mediaKeys
  27503. }) => {
  27504. return this.attemptSetMediaKeys(keySystem, mediaKeys);
  27505. });
  27506. }
  27507. selectKeySystem(keySystemsToAttempt) {
  27508. return new Promise((resolve2, reject) => {
  27509. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  27510. keySystem
  27511. }) => {
  27512. const keySystemFormat = keySystemDomainToKeySystemFormat(keySystem);
  27513. if (keySystemFormat) {
  27514. resolve2(keySystemFormat);
  27515. } else {
  27516. reject(new Error(`Unable to find format for key-system "${keySystem}"`));
  27517. }
  27518. }).catch(reject);
  27519. });
  27520. }
  27521. selectKeySystemFormat(frag) {
  27522. const keyFormats = Object.keys(frag.levelkeys || {});
  27523. if (!this.keyFormatPromise) {
  27524. this.log(`Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${frag.level}) key formats ${keyFormats.join(", ")}`);
  27525. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  27526. }
  27527. return this.keyFormatPromise;
  27528. }
  27529. getKeyFormatPromise(keyFormats) {
  27530. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  27531. const keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter((value) => !!value && keySystemsInConfig.indexOf(value) !== -1);
  27532. return this.selectKeySystem(keySystemsToAttempt);
  27533. }
  27534. loadKey(data) {
  27535. const decryptdata = data.keyInfo.decryptdata;
  27536. const keyId = this.getKeyIdString(decryptdata);
  27537. const keyDetails = `(keyId: ${keyId} format: "${decryptdata.keyFormat}" method: ${decryptdata.method} uri: ${decryptdata.uri})`;
  27538. this.log(`Starting session for key ${keyDetails}`);
  27539. let keyContextPromise = this.keyIdToKeySessionPromise[keyId];
  27540. if (!keyContextPromise) {
  27541. keyContextPromise = this.getKeySystemForKeyPromise(decryptdata).then(({
  27542. keySystem,
  27543. mediaKeys
  27544. }) => {
  27545. this.throwIfDestroyed();
  27546. this.log(`Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`);
  27547. return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {
  27548. this.throwIfDestroyed();
  27549. return this.createMediaKeySessionContext({
  27550. keySystem,
  27551. mediaKeys,
  27552. decryptdata
  27553. });
  27554. });
  27555. });
  27556. const keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] = keyContextPromise.then((keySessionContext) => {
  27557. const scheme = "cenc";
  27558. const initData2 = decryptdata.pssh ? decryptdata.pssh.buffer : null;
  27559. return this.generateRequestWithPreferredKeySession(keySessionContext, scheme, initData2, "playlist-key");
  27560. });
  27561. keySessionContextPromise.catch((error) => this.handleError(error));
  27562. }
  27563. return keyContextPromise;
  27564. }
  27565. throwIfDestroyed(message = "Invalid state") {
  27566. if (!this.hls) {
  27567. throw new Error("invalid state");
  27568. }
  27569. }
  27570. handleError(error) {
  27571. if (!this.hls) {
  27572. return;
  27573. }
  27574. this.error(error.message);
  27575. if (error instanceof EMEKeyError) {
  27576. this.hls.trigger(Events.ERROR, error.data);
  27577. } else {
  27578. this.hls.trigger(Events.ERROR, {
  27579. type: ErrorTypes.KEY_SYSTEM_ERROR,
  27580. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  27581. error,
  27582. fatal: true
  27583. });
  27584. }
  27585. }
  27586. getKeySystemForKeyPromise(decryptdata) {
  27587. const keyId = this.getKeyIdString(decryptdata);
  27588. const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];
  27589. if (!mediaKeySessionContext) {
  27590. const keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat);
  27591. const keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config);
  27592. return this.attemptKeySystemAccess(keySystemsToAttempt);
  27593. }
  27594. return mediaKeySessionContext;
  27595. }
  27596. getKeySystemSelectionPromise(keySystemsToAttempt) {
  27597. if (!keySystemsToAttempt.length) {
  27598. keySystemsToAttempt = getKeySystemsForConfig(this.config);
  27599. }
  27600. if (keySystemsToAttempt.length === 0) {
  27601. throw new EMEKeyError({
  27602. type: ErrorTypes.KEY_SYSTEM_ERROR,
  27603. details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,
  27604. fatal: true
  27605. }, `Missing key-system license configuration options ${stringify({
  27606. drmSystems: this.config.drmSystems
  27607. })}`);
  27608. }
  27609. return this.attemptKeySystemAccess(keySystemsToAttempt);
  27610. }
  27611. attemptSetMediaKeys(keySystem, mediaKeys) {
  27612. if (this.mediaKeys === mediaKeys) {
  27613. return Promise.resolve();
  27614. }
  27615. const queue2 = this.setMediaKeysQueue.slice();
  27616. this.log(`Setting media-keys for "${keySystem}"`);
  27617. const setMediaKeysPromise = Promise.all(queue2).then(() => {
  27618. if (!this.media) {
  27619. this.mediaKeys = null;
  27620. throw new Error("Attempted to set mediaKeys without media element attached");
  27621. }
  27622. return this.media.setMediaKeys(mediaKeys);
  27623. });
  27624. this.mediaKeys = mediaKeys;
  27625. this.setMediaKeysQueue.push(setMediaKeysPromise);
  27626. return setMediaKeysPromise.then(() => {
  27627. this.log(`Media-keys set for "${keySystem}"`);
  27628. queue2.push(setMediaKeysPromise);
  27629. this.setMediaKeysQueue = this.setMediaKeysQueue.filter((p2) => queue2.indexOf(p2) === -1);
  27630. });
  27631. }
  27632. generateRequestWithPreferredKeySession(context, initDataType, initData2, reason) {
  27633. var _this$config$drmSyste, _this$config$drmSyste2;
  27634. const generateRequestFilter = (_this$config$drmSyste = this.config.drmSystems) == null ? void 0 : (_this$config$drmSyste2 = _this$config$drmSyste[context.keySystem]) == null ? void 0 : _this$config$drmSyste2.generateRequest;
  27635. if (generateRequestFilter) {
  27636. try {
  27637. const mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData2, context);
  27638. if (!mappedInitData) {
  27639. throw new Error("Invalid response from configured generateRequest filter");
  27640. }
  27641. initDataType = mappedInitData.initDataType;
  27642. initData2 = mappedInitData.initData ? mappedInitData.initData : null;
  27643. context.decryptdata.pssh = initData2 ? new Uint8Array(initData2) : null;
  27644. } catch (error) {
  27645. var _this$hls;
  27646. this.warn(error.message);
  27647. if ((_this$hls = this.hls) != null && _this$hls.config.debug) {
  27648. throw error;
  27649. }
  27650. }
  27651. }
  27652. if (initData2 === null) {
  27653. this.log(`Skipping key-session request for "${reason}" (no initData)`);
  27654. return Promise.resolve(context);
  27655. }
  27656. const keyId = this.getKeyIdString(context.decryptdata);
  27657. this.log(`Generating key-session request for "${reason}": ${keyId} (init data type: ${initDataType} length: ${initData2 ? initData2.byteLength : null})`);
  27658. const licenseStatus = new EventEmitter();
  27659. const onmessage = context._onmessage = (event) => {
  27660. const keySession = context.mediaKeysSession;
  27661. if (!keySession) {
  27662. licenseStatus.emit("error", new Error("invalid state"));
  27663. return;
  27664. }
  27665. const {
  27666. messageType,
  27667. message
  27668. } = event;
  27669. this.log(`"${messageType}" message event for session "${keySession.sessionId}" message size: ${message.byteLength}`);
  27670. if (messageType === "license-request" || messageType === "license-renewal") {
  27671. this.renewLicense(context, message).catch((error) => {
  27672. if (licenseStatus.eventNames().length) {
  27673. licenseStatus.emit("error", error);
  27674. } else {
  27675. this.handleError(error);
  27676. }
  27677. });
  27678. } else if (messageType === "license-release") {
  27679. if (context.keySystem === KeySystems.FAIRPLAY) {
  27680. this.updateKeySession(context, strToUtf8array("acknowledged"));
  27681. this.removeSession(context);
  27682. }
  27683. } else {
  27684. this.warn(`unhandled media key message type "${messageType}"`);
  27685. }
  27686. };
  27687. const onkeystatuseschange = context._onkeystatuseschange = (event) => {
  27688. const keySession = context.mediaKeysSession;
  27689. if (!keySession) {
  27690. licenseStatus.emit("error", new Error("invalid state"));
  27691. return;
  27692. }
  27693. this.onKeyStatusChange(context);
  27694. const keyStatus = context.keyStatus;
  27695. licenseStatus.emit("keyStatus", keyStatus);
  27696. if (keyStatus === "expired") {
  27697. this.warn(`${context.keySystem} expired for key ${keyId}`);
  27698. this.renewKeySession(context);
  27699. }
  27700. };
  27701. addEventListener(context.mediaKeysSession, "message", onmessage);
  27702. addEventListener(context.mediaKeysSession, "keystatuseschange", onkeystatuseschange);
  27703. const keyUsablePromise = new Promise((resolve2, reject) => {
  27704. licenseStatus.on("error", reject);
  27705. licenseStatus.on("keyStatus", (keyStatus) => {
  27706. if (keyStatus.startsWith("usable")) {
  27707. resolve2();
  27708. } else if (keyStatus === "output-restricted") {
  27709. reject(new EMEKeyError({
  27710. type: ErrorTypes.KEY_SYSTEM_ERROR,
  27711. details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,
  27712. fatal: false
  27713. }, "HDCP level output restricted"));
  27714. } else if (keyStatus === "internal-error") {
  27715. reject(new EMEKeyError({
  27716. type: ErrorTypes.KEY_SYSTEM_ERROR,
  27717. details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,
  27718. fatal: true
  27719. }, `key status changed to "${keyStatus}"`));
  27720. } else if (keyStatus === "expired") {
  27721. reject(new Error("key expired while generating request"));
  27722. } else {
  27723. this.warn(`unhandled key status change "${keyStatus}"`);
  27724. }
  27725. });
  27726. });
  27727. return context.mediaKeysSession.generateRequest(initDataType, initData2).then(() => {
  27728. var _context$mediaKeysSes;
  27729. this.log(`Request generated for key-session "${(_context$mediaKeysSes = context.mediaKeysSession) == null ? void 0 : _context$mediaKeysSes.sessionId}" keyId: ${keyId}`);
  27730. }).catch((error) => {
  27731. throw new EMEKeyError({
  27732. type: ErrorTypes.KEY_SYSTEM_ERROR,
  27733. details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
  27734. error,
  27735. fatal: false
  27736. }, `Error generating key-session request: ${error}`);
  27737. }).then(() => keyUsablePromise).catch((error) => {
  27738. licenseStatus.removeAllListeners();
  27739. this.removeSession(context);
  27740. throw error;
  27741. }).then(() => {
  27742. licenseStatus.removeAllListeners();
  27743. return context;
  27744. });
  27745. }
  27746. onKeyStatusChange(mediaKeySessionContext) {
  27747. mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach((status2, keyId) => {
  27748. if (typeof keyId === "string" && typeof status2 === "object") {
  27749. const temp = keyId;
  27750. keyId = status2;
  27751. status2 = temp;
  27752. }
  27753. this.log(`key status change "${status2}" for keyStatuses keyId: ${Hex.hexDump("buffer" in keyId ? new Uint8Array(keyId.buffer, keyId.byteOffset, keyId.byteLength) : new Uint8Array(keyId))} session keyId: ${Hex.hexDump(new Uint8Array(mediaKeySessionContext.decryptdata.keyId || []))} uri: ${mediaKeySessionContext.decryptdata.uri}`);
  27754. mediaKeySessionContext.keyStatus = status2;
  27755. });
  27756. }
  27757. fetchServerCertificate(keySystem) {
  27758. const config = this.config;
  27759. const Loader = config.loader;
  27760. const certLoader = new Loader(config);
  27761. const url = this.getServerCertificateUrl(keySystem);
  27762. if (!url) {
  27763. return Promise.resolve();
  27764. }
  27765. this.log(`Fetching server certificate for "${keySystem}"`);
  27766. return new Promise((resolve2, reject) => {
  27767. const loaderContext = {
  27768. responseType: "arraybuffer",
  27769. url
  27770. };
  27771. const loadPolicy = config.certLoadPolicy.default;
  27772. const loaderConfig = {
  27773. loadPolicy,
  27774. timeout: loadPolicy.maxLoadTimeMs,
  27775. maxRetry: 0,
  27776. retryDelay: 0,
  27777. maxRetryDelay: 0
  27778. };
  27779. const loaderCallbacks = {
  27780. onSuccess: (response, stats, context, networkDetails) => {
  27781. resolve2(response.data);
  27782. },
  27783. onError: (response, contex, networkDetails, stats) => {
  27784. reject(new EMEKeyError({
  27785. type: ErrorTypes.KEY_SYSTEM_ERROR,
  27786. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  27787. fatal: true,
  27788. networkDetails,
  27789. response: _objectSpread2({
  27790. url: loaderContext.url,
  27791. data: void 0
  27792. }, response)
  27793. }, `"${keySystem}" certificate request failed (${url}). Status: ${response.code} (${response.text})`));
  27794. },
  27795. onTimeout: (stats, context, networkDetails) => {
  27796. reject(new EMEKeyError({
  27797. type: ErrorTypes.KEY_SYSTEM_ERROR,
  27798. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  27799. fatal: true,
  27800. networkDetails,
  27801. response: {
  27802. url: loaderContext.url,
  27803. data: void 0
  27804. }
  27805. }, `"${keySystem}" certificate request timed out (${url})`));
  27806. },
  27807. onAbort: (stats, context, networkDetails) => {
  27808. reject(new Error("aborted"));
  27809. }
  27810. };
  27811. certLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  27812. });
  27813. }
  27814. setMediaKeysServerCertificate(mediaKeys, keySystem, cert) {
  27815. return new Promise((resolve2, reject) => {
  27816. mediaKeys.setServerCertificate(cert).then((success) => {
  27817. this.log(`setServerCertificate ${success ? "success" : "not supported by CDM"} (${cert == null ? void 0 : cert.byteLength}) on "${keySystem}"`);
  27818. resolve2(mediaKeys);
  27819. }).catch((error) => {
  27820. reject(new EMEKeyError({
  27821. type: ErrorTypes.KEY_SYSTEM_ERROR,
  27822. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,
  27823. error,
  27824. fatal: true
  27825. }, error.message));
  27826. });
  27827. });
  27828. }
  27829. renewLicense(context, keyMessage) {
  27830. return this.requestLicense(context, new Uint8Array(keyMessage)).then((data) => {
  27831. return this.updateKeySession(context, new Uint8Array(data)).catch((error) => {
  27832. throw new EMEKeyError({
  27833. type: ErrorTypes.KEY_SYSTEM_ERROR,
  27834. details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,
  27835. error,
  27836. fatal: true
  27837. }, error.message);
  27838. });
  27839. });
  27840. }
  27841. unpackPlayReadyKeyMessage(xhr, licenseChallenge) {
  27842. const xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer));
  27843. if (!xmlString.includes("PlayReadyKeyMessage")) {
  27844. xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  27845. return licenseChallenge;
  27846. }
  27847. const keyMessageXml = new DOMParser().parseFromString(xmlString, "application/xml");
  27848. const headers = keyMessageXml.querySelectorAll("HttpHeader");
  27849. if (headers.length > 0) {
  27850. let header;
  27851. for (let i2 = 0, len = headers.length; i2 < len; i2++) {
  27852. var _header$querySelector, _header$querySelector2;
  27853. header = headers[i2];
  27854. const name = (_header$querySelector = header.querySelector("name")) == null ? void 0 : _header$querySelector.textContent;
  27855. const value = (_header$querySelector2 = header.querySelector("value")) == null ? void 0 : _header$querySelector2.textContent;
  27856. if (name && value) {
  27857. xhr.setRequestHeader(name, value);
  27858. }
  27859. }
  27860. }
  27861. const challengeElement = keyMessageXml.querySelector("Challenge");
  27862. const challengeText = challengeElement == null ? void 0 : challengeElement.textContent;
  27863. if (!challengeText) {
  27864. throw new Error(`Cannot find <Challenge> in key message`);
  27865. }
  27866. return strToUtf8array(atob(challengeText));
  27867. }
  27868. setupLicenseXHR(xhr, url, keysListItem, licenseChallenge) {
  27869. const licenseXhrSetup = this.config.licenseXhrSetup;
  27870. if (!licenseXhrSetup) {
  27871. xhr.open("POST", url, true);
  27872. return Promise.resolve({
  27873. xhr,
  27874. licenseChallenge
  27875. });
  27876. }
  27877. return Promise.resolve().then(() => {
  27878. if (!keysListItem.decryptdata) {
  27879. throw new Error("Key removed");
  27880. }
  27881. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  27882. }).catch((error) => {
  27883. if (!keysListItem.decryptdata) {
  27884. throw error;
  27885. }
  27886. xhr.open("POST", url, true);
  27887. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  27888. }).then((licenseXhrSetupResult) => {
  27889. if (!xhr.readyState) {
  27890. xhr.open("POST", url, true);
  27891. }
  27892. const finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge;
  27893. return {
  27894. xhr,
  27895. licenseChallenge: finalLicenseChallenge
  27896. };
  27897. });
  27898. }
  27899. requestLicense(keySessionContext, licenseChallenge) {
  27900. const keyLoadPolicy = this.config.keyLoadPolicy.default;
  27901. return new Promise((resolve2, reject) => {
  27902. const url = this.getLicenseServerUrlOrThrow(keySessionContext.keySystem);
  27903. this.log(`Sending license request to URL: ${url}`);
  27904. const xhr = new XMLHttpRequest();
  27905. xhr.responseType = "arraybuffer";
  27906. xhr.onreadystatechange = () => {
  27907. if (!this.hls || !keySessionContext.mediaKeysSession) {
  27908. return reject(new Error("invalid state"));
  27909. }
  27910. if (xhr.readyState === 4) {
  27911. if (xhr.status === 200) {
  27912. this._requestLicenseFailureCount = 0;
  27913. let data = xhr.response;
  27914. this.log(`License received ${data instanceof ArrayBuffer ? data.byteLength : data}`);
  27915. const licenseResponseCallback = this.config.licenseResponseCallback;
  27916. if (licenseResponseCallback) {
  27917. try {
  27918. data = licenseResponseCallback.call(this.hls, xhr, url, keySessionContext);
  27919. } catch (error) {
  27920. this.error(error);
  27921. }
  27922. }
  27923. resolve2(data);
  27924. } else {
  27925. const retryConfig = keyLoadPolicy.errorRetry;
  27926. const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;
  27927. this._requestLicenseFailureCount++;
  27928. if (this._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) {
  27929. reject(new EMEKeyError({
  27930. type: ErrorTypes.KEY_SYSTEM_ERROR,
  27931. details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  27932. fatal: true,
  27933. networkDetails: xhr,
  27934. response: {
  27935. url,
  27936. data: void 0,
  27937. code: xhr.status,
  27938. text: xhr.statusText
  27939. }
  27940. }, `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`));
  27941. } else {
  27942. const attemptsLeft = maxNumRetry - this._requestLicenseFailureCount + 1;
  27943. this.warn(`Retrying license request, ${attemptsLeft} attempts left`);
  27944. this.requestLicense(keySessionContext, licenseChallenge).then(resolve2, reject);
  27945. }
  27946. }
  27947. }
  27948. };
  27949. if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) {
  27950. keySessionContext.licenseXhr.abort();
  27951. }
  27952. keySessionContext.licenseXhr = xhr;
  27953. this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(({
  27954. xhr: xhr2,
  27955. licenseChallenge: licenseChallenge2
  27956. }) => {
  27957. if (keySessionContext.keySystem == KeySystems.PLAYREADY) {
  27958. licenseChallenge2 = this.unpackPlayReadyKeyMessage(xhr2, licenseChallenge2);
  27959. }
  27960. xhr2.send(licenseChallenge2);
  27961. });
  27962. });
  27963. }
  27964. onDestroying() {
  27965. this.unregisterListeners();
  27966. this._clear();
  27967. }
  27968. onMediaAttached(event, data) {
  27969. if (!this.config.emeEnabled) {
  27970. return;
  27971. }
  27972. const media = data.media;
  27973. this.media = media;
  27974. addEventListener(media, "waitingforkey", this.onWaitingForKey);
  27975. }
  27976. onMediaDetached() {
  27977. const media = this.media;
  27978. if (media) {
  27979. removeEventListener(media, "waitingforkey", this.onWaitingForKey);
  27980. this.media = null;
  27981. this.mediaKeys = null;
  27982. }
  27983. }
  27984. _clear() {
  27985. var _media$setMediaKeys;
  27986. this._requestLicenseFailureCount = 0;
  27987. this.keyIdToKeySessionPromise = {};
  27988. if (!this.mediaKeys && !this.mediaKeySessions.length) {
  27989. return;
  27990. }
  27991. const media = this.media;
  27992. const mediaKeysList = this.mediaKeySessions.slice();
  27993. this.mediaKeySessions = [];
  27994. this.mediaKeys = null;
  27995. LevelKey.clearKeyUriToKeyIdMap();
  27996. const keySessionCount = mediaKeysList.length;
  27997. EMEController.CDMCleanupPromise = Promise.all(mediaKeysList.map((mediaKeySessionContext) => this.removeSession(mediaKeySessionContext)).concat(media == null ? void 0 : (_media$setMediaKeys = media.setMediaKeys(null)) == null ? void 0 : _media$setMediaKeys.catch((error) => {
  27998. var _this$hls2;
  27999. this.log(`Could not clear media keys: ${error}`);
  28000. (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.trigger(Events.ERROR, {
  28001. type: ErrorTypes.OTHER_ERROR,
  28002. details: ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,
  28003. fatal: false,
  28004. error: new Error(`Could not clear media keys: ${error}`)
  28005. });
  28006. }))).catch((error) => {
  28007. var _this$hls3;
  28008. this.log(`Could not close sessions and clear media keys: ${error}`);
  28009. (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.trigger(Events.ERROR, {
  28010. type: ErrorTypes.OTHER_ERROR,
  28011. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  28012. fatal: false,
  28013. error: new Error(`Could not close sessions and clear media keys: ${error}`)
  28014. });
  28015. }).then(() => {
  28016. if (keySessionCount) {
  28017. this.log("finished closing key sessions and clearing media keys");
  28018. }
  28019. });
  28020. }
  28021. onManifestLoading() {
  28022. this.keyFormatPromise = null;
  28023. }
  28024. onManifestLoaded(event, {
  28025. sessionKeys
  28026. }) {
  28027. if (!sessionKeys || !this.config.emeEnabled) {
  28028. return;
  28029. }
  28030. if (!this.keyFormatPromise) {
  28031. const keyFormats = sessionKeys.reduce((formats, sessionKey) => {
  28032. if (formats.indexOf(sessionKey.keyFormat) === -1) {
  28033. formats.push(sessionKey.keyFormat);
  28034. }
  28035. return formats;
  28036. }, []);
  28037. this.log(`Selecting key-system from session-keys ${keyFormats.join(", ")}`);
  28038. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  28039. }
  28040. }
  28041. removeSession(mediaKeySessionContext) {
  28042. const {
  28043. mediaKeysSession,
  28044. licenseXhr
  28045. } = mediaKeySessionContext;
  28046. if (mediaKeysSession) {
  28047. this.log(`Remove licenses and keys and close session ${mediaKeysSession.sessionId}`);
  28048. if (mediaKeySessionContext._onmessage) {
  28049. mediaKeysSession.removeEventListener("message", mediaKeySessionContext._onmessage);
  28050. mediaKeySessionContext._onmessage = void 0;
  28051. }
  28052. if (mediaKeySessionContext._onkeystatuseschange) {
  28053. mediaKeysSession.removeEventListener("keystatuseschange", mediaKeySessionContext._onkeystatuseschange);
  28054. mediaKeySessionContext._onkeystatuseschange = void 0;
  28055. }
  28056. if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {
  28057. licenseXhr.abort();
  28058. }
  28059. mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = void 0;
  28060. const index2 = this.mediaKeySessions.indexOf(mediaKeySessionContext);
  28061. if (index2 > -1) {
  28062. this.mediaKeySessions.splice(index2, 1);
  28063. }
  28064. const {
  28065. drmSystemOptions
  28066. } = this.config;
  28067. const removePromise = isPersistentSessionType(drmSystemOptions) ? new Promise((resolve2, reject) => {
  28068. self.setTimeout(() => reject(new Error(`MediaKeySession.remove() timeout`)), 8e3);
  28069. mediaKeysSession.remove().then(resolve2);
  28070. }) : Promise.resolve();
  28071. return removePromise.catch((error) => {
  28072. var _this$hls4;
  28073. this.log(`Could not remove session: ${error}`);
  28074. (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.trigger(Events.ERROR, {
  28075. type: ErrorTypes.OTHER_ERROR,
  28076. details: ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,
  28077. fatal: false,
  28078. error: new Error(`Could not remove session: ${error}`)
  28079. });
  28080. }).then(() => {
  28081. return mediaKeysSession.close();
  28082. }).catch((error) => {
  28083. var _this$hls5;
  28084. this.log(`Could not close session: ${error}`);
  28085. (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.trigger(Events.ERROR, {
  28086. type: ErrorTypes.OTHER_ERROR,
  28087. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  28088. fatal: false,
  28089. error: new Error(`Could not close session: ${error}`)
  28090. });
  28091. });
  28092. }
  28093. }
  28094. }
  28095. EMEController.CDMCleanupPromise = void 0;
  28096. class EMEKeyError extends Error {
  28097. constructor(data, message) {
  28098. super(message);
  28099. this.data = void 0;
  28100. data.error || (data.error = new Error(message));
  28101. this.data = data;
  28102. data.err = data.error;
  28103. }
  28104. }
  28105. class FPSController {
  28106. constructor(hls) {
  28107. this.hls = void 0;
  28108. this.isVideoPlaybackQualityAvailable = false;
  28109. this.timer = void 0;
  28110. this.media = null;
  28111. this.lastTime = void 0;
  28112. this.lastDroppedFrames = 0;
  28113. this.lastDecodedFrames = 0;
  28114. this.streamController = void 0;
  28115. this.hls = hls;
  28116. this.registerListeners();
  28117. }
  28118. setStreamController(streamController) {
  28119. this.streamController = streamController;
  28120. }
  28121. registerListeners() {
  28122. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  28123. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28124. }
  28125. unregisterListeners() {
  28126. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  28127. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28128. }
  28129. destroy() {
  28130. if (this.timer) {
  28131. clearInterval(this.timer);
  28132. }
  28133. this.unregisterListeners();
  28134. this.isVideoPlaybackQualityAvailable = false;
  28135. this.media = null;
  28136. }
  28137. onMediaAttaching(event, data) {
  28138. const config = this.hls.config;
  28139. if (config.capLevelOnFPSDrop) {
  28140. const media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  28141. this.media = media;
  28142. if (media && typeof media.getVideoPlaybackQuality === "function") {
  28143. this.isVideoPlaybackQualityAvailable = true;
  28144. }
  28145. self.clearInterval(this.timer);
  28146. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  28147. }
  28148. }
  28149. onMediaDetaching() {
  28150. this.media = null;
  28151. }
  28152. checkFPS(video, decodedFrames, droppedFrames) {
  28153. const currentTime = performance.now();
  28154. if (decodedFrames) {
  28155. if (this.lastTime) {
  28156. const currentPeriod = currentTime - this.lastTime;
  28157. const currentDropped = droppedFrames - this.lastDroppedFrames;
  28158. const currentDecoded = decodedFrames - this.lastDecodedFrames;
  28159. const droppedFPS = 1e3 * currentDropped / currentPeriod;
  28160. const hls = this.hls;
  28161. hls.trigger(Events.FPS_DROP, {
  28162. currentDropped,
  28163. currentDecoded,
  28164. totalDroppedFrames: droppedFrames
  28165. });
  28166. if (droppedFPS > 0) {
  28167. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  28168. let currentLevel = hls.currentLevel;
  28169. hls.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: " + currentLevel);
  28170. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  28171. currentLevel = currentLevel - 1;
  28172. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  28173. level: currentLevel,
  28174. droppedLevel: hls.currentLevel
  28175. });
  28176. hls.autoLevelCapping = currentLevel;
  28177. this.streamController.nextLevelSwitch();
  28178. }
  28179. }
  28180. }
  28181. }
  28182. this.lastTime = currentTime;
  28183. this.lastDroppedFrames = droppedFrames;
  28184. this.lastDecodedFrames = decodedFrames;
  28185. }
  28186. }
  28187. checkFPSInterval() {
  28188. const video = this.media;
  28189. if (video) {
  28190. if (this.isVideoPlaybackQualityAvailable) {
  28191. const videoPlaybackQuality = video.getVideoPlaybackQuality();
  28192. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  28193. } else {
  28194. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  28195. }
  28196. }
  28197. }
  28198. }
  28199. function sendAddTrackEvent(track2, videoEl) {
  28200. let event;
  28201. try {
  28202. event = new Event("addtrack");
  28203. } catch (err) {
  28204. event = document.createEvent("Event");
  28205. event.initEvent("addtrack", false, false);
  28206. }
  28207. event.track = track2;
  28208. videoEl.dispatchEvent(event);
  28209. }
  28210. function addCueToTrack(track2, cue) {
  28211. const mode = track2.mode;
  28212. if (mode === "disabled") {
  28213. track2.mode = "hidden";
  28214. }
  28215. if (track2.cues && !track2.cues.getCueById(cue.id)) {
  28216. try {
  28217. track2.addCue(cue);
  28218. if (!track2.cues.getCueById(cue.id)) {
  28219. throw new Error(`addCue is failed for: ${cue}`);
  28220. }
  28221. } catch (err) {
  28222. logger.debug(`[texttrack-utils]: ${err}`);
  28223. try {
  28224. const textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  28225. textTrackCue.id = cue.id;
  28226. track2.addCue(textTrackCue);
  28227. } catch (err2) {
  28228. logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`);
  28229. }
  28230. }
  28231. }
  28232. if (mode === "disabled") {
  28233. track2.mode = mode;
  28234. }
  28235. }
  28236. function clearCurrentCues(track2, enterHandler) {
  28237. const mode = track2.mode;
  28238. if (mode === "disabled") {
  28239. track2.mode = "hidden";
  28240. }
  28241. if (track2.cues) {
  28242. for (let i2 = track2.cues.length; i2--; ) {
  28243. if (enterHandler) {
  28244. track2.cues[i2].removeEventListener("enter", enterHandler);
  28245. }
  28246. track2.removeCue(track2.cues[i2]);
  28247. }
  28248. }
  28249. if (mode === "disabled") {
  28250. track2.mode = mode;
  28251. }
  28252. }
  28253. function removeCuesInRange(track2, start, end, predicate) {
  28254. const mode = track2.mode;
  28255. if (mode === "disabled") {
  28256. track2.mode = "hidden";
  28257. }
  28258. if (track2.cues && track2.cues.length > 0) {
  28259. const cues = getCuesInRange(track2.cues, start, end);
  28260. for (let i2 = 0; i2 < cues.length; i2++) {
  28261. if (!predicate || predicate(cues[i2])) {
  28262. track2.removeCue(cues[i2]);
  28263. }
  28264. }
  28265. }
  28266. if (mode === "disabled") {
  28267. track2.mode = mode;
  28268. }
  28269. }
  28270. function getFirstCueIndexFromTime(cues, time) {
  28271. if (time <= cues[0].startTime) {
  28272. return 0;
  28273. }
  28274. const len = cues.length - 1;
  28275. if (time > cues[len].endTime) {
  28276. return -1;
  28277. }
  28278. let left = 0;
  28279. let right = len;
  28280. let mid;
  28281. while (left <= right) {
  28282. mid = Math.floor((right + left) / 2);
  28283. if (time < cues[mid].startTime) {
  28284. right = mid - 1;
  28285. } else if (time > cues[mid].startTime && left < len) {
  28286. left = mid + 1;
  28287. } else {
  28288. return mid;
  28289. }
  28290. }
  28291. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  28292. }
  28293. function getCuesInRange(cues, start, end) {
  28294. const cuesFound = [];
  28295. const firstCueInRange = getFirstCueIndexFromTime(cues, start);
  28296. if (firstCueInRange > -1) {
  28297. for (let i2 = firstCueInRange, len = cues.length; i2 < len; i2++) {
  28298. const cue = cues[i2];
  28299. if (cue.startTime >= start && cue.endTime <= end) {
  28300. cuesFound.push(cue);
  28301. } else if (cue.startTime > end) {
  28302. return cuesFound;
  28303. }
  28304. }
  28305. }
  28306. return cuesFound;
  28307. }
  28308. function filterSubtitleTracks(textTrackList) {
  28309. const tracks = [];
  28310. for (let i2 = 0; i2 < textTrackList.length; i2++) {
  28311. const track2 = textTrackList[i2];
  28312. if ((track2.kind === "subtitles" || track2.kind === "captions") && track2.label) {
  28313. tracks.push(textTrackList[i2]);
  28314. }
  28315. }
  28316. return tracks;
  28317. }
  28318. class SubtitleTrackController extends BasePlaylistController {
  28319. constructor(hls) {
  28320. super(hls, "subtitle-track-controller");
  28321. this.media = null;
  28322. this.tracks = [];
  28323. this.groupIds = null;
  28324. this.tracksInGroup = [];
  28325. this.trackId = -1;
  28326. this.currentTrack = null;
  28327. this.selectDefaultTrack = true;
  28328. this.queuedDefaultTrack = -1;
  28329. this.useTextTrackPolling = false;
  28330. this.subtitlePollingInterval = -1;
  28331. this._subtitleDisplay = true;
  28332. this.asyncPollTrackChange = () => this.pollTrackChange(0);
  28333. this.onTextTracksChanged = () => {
  28334. if (!this.useTextTrackPolling) {
  28335. self.clearInterval(this.subtitlePollingInterval);
  28336. }
  28337. if (!this.media || !this.hls.config.renderTextTracksNatively) {
  28338. return;
  28339. }
  28340. let textTrack = null;
  28341. const tracks = filterSubtitleTracks(this.media.textTracks);
  28342. for (let i2 = 0; i2 < tracks.length; i2++) {
  28343. if (tracks[i2].mode === "hidden") {
  28344. textTrack = tracks[i2];
  28345. } else if (tracks[i2].mode === "showing") {
  28346. textTrack = tracks[i2];
  28347. break;
  28348. }
  28349. }
  28350. const trackId = this.findTrackForTextTrack(textTrack);
  28351. if (this.subtitleTrack !== trackId) {
  28352. this.setSubtitleTrack(trackId);
  28353. }
  28354. };
  28355. this.registerListeners();
  28356. }
  28357. destroy() {
  28358. this.unregisterListeners();
  28359. this.tracks.length = 0;
  28360. this.tracksInGroup.length = 0;
  28361. this.currentTrack = null;
  28362. this.onTextTracksChanged = this.asyncPollTrackChange = null;
  28363. super.destroy();
  28364. }
  28365. get subtitleDisplay() {
  28366. return this._subtitleDisplay;
  28367. }
  28368. set subtitleDisplay(value) {
  28369. this._subtitleDisplay = value;
  28370. if (this.trackId > -1) {
  28371. this.toggleTrackModes();
  28372. }
  28373. }
  28374. registerListeners() {
  28375. const {
  28376. hls
  28377. } = this;
  28378. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  28379. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28380. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  28381. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  28382. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  28383. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  28384. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  28385. hls.on(Events.ERROR, this.onError, this);
  28386. }
  28387. unregisterListeners() {
  28388. const {
  28389. hls
  28390. } = this;
  28391. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  28392. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28393. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  28394. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  28395. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  28396. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  28397. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  28398. hls.off(Events.ERROR, this.onError, this);
  28399. }
  28400. // Listen for subtitle track change, then extract the current track ID.
  28401. onMediaAttached(event, data) {
  28402. this.media = data.media;
  28403. if (!this.media) {
  28404. return;
  28405. }
  28406. if (this.queuedDefaultTrack > -1) {
  28407. this.subtitleTrack = this.queuedDefaultTrack;
  28408. this.queuedDefaultTrack = -1;
  28409. }
  28410. this.useTextTrackPolling = !(this.media.textTracks && "onchange" in this.media.textTracks);
  28411. if (this.useTextTrackPolling) {
  28412. this.pollTrackChange(500);
  28413. } else {
  28414. this.media.textTracks.addEventListener("change", this.asyncPollTrackChange);
  28415. }
  28416. }
  28417. pollTrackChange(timeout) {
  28418. self.clearInterval(this.subtitlePollingInterval);
  28419. this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout);
  28420. }
  28421. onMediaDetaching(event, data) {
  28422. const media = this.media;
  28423. if (!media) {
  28424. return;
  28425. }
  28426. const transferringMedia = !!data.transferMedia;
  28427. self.clearInterval(this.subtitlePollingInterval);
  28428. if (!this.useTextTrackPolling) {
  28429. media.textTracks.removeEventListener("change", this.asyncPollTrackChange);
  28430. }
  28431. if (this.trackId > -1) {
  28432. this.queuedDefaultTrack = this.trackId;
  28433. }
  28434. this.subtitleTrack = -1;
  28435. this.media = null;
  28436. if (transferringMedia) {
  28437. return;
  28438. }
  28439. const textTracks = filterSubtitleTracks(media.textTracks);
  28440. textTracks.forEach((track2) => {
  28441. clearCurrentCues(track2);
  28442. });
  28443. }
  28444. onManifestLoading() {
  28445. this.tracks = [];
  28446. this.groupIds = null;
  28447. this.tracksInGroup = [];
  28448. this.trackId = -1;
  28449. this.currentTrack = null;
  28450. this.selectDefaultTrack = true;
  28451. }
  28452. // Fired whenever a new manifest is loaded.
  28453. onManifestParsed(event, data) {
  28454. this.tracks = data.subtitleTracks;
  28455. }
  28456. onSubtitleTrackLoaded(event, data) {
  28457. const {
  28458. id,
  28459. groupId,
  28460. details
  28461. } = data;
  28462. const trackInActiveGroup = this.tracksInGroup[id];
  28463. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  28464. this.warn(`Subtitle track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  28465. return;
  28466. }
  28467. const curDetails = trackInActiveGroup.details;
  28468. trackInActiveGroup.details = data.details;
  28469. this.log(`Subtitle track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  28470. if (id === this.trackId) {
  28471. this.playlistLoaded(id, data, curDetails);
  28472. }
  28473. }
  28474. onLevelLoading(event, data) {
  28475. this.switchLevel(data.level);
  28476. }
  28477. onLevelSwitching(event, data) {
  28478. this.switchLevel(data.level);
  28479. }
  28480. switchLevel(levelIndex) {
  28481. const levelInfo = this.hls.levels[levelIndex];
  28482. if (!levelInfo) {
  28483. return;
  28484. }
  28485. const subtitleGroups = levelInfo.subtitleGroups || null;
  28486. const currentGroups = this.groupIds;
  28487. let currentTrack = this.currentTrack;
  28488. if (!subtitleGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (subtitleGroups == null ? void 0 : subtitleGroups.length) || subtitleGroups != null && subtitleGroups.some((groupId) => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) {
  28489. this.groupIds = subtitleGroups;
  28490. this.trackId = -1;
  28491. this.currentTrack = null;
  28492. const subtitleTracks = this.tracks.filter((track2) => !subtitleGroups || subtitleGroups.indexOf(track2.groupId) !== -1);
  28493. if (subtitleTracks.length) {
  28494. if (this.selectDefaultTrack && !subtitleTracks.some((track2) => track2.default)) {
  28495. this.selectDefaultTrack = false;
  28496. }
  28497. subtitleTracks.forEach((track2, i2) => {
  28498. track2.id = i2;
  28499. });
  28500. } else if (!currentTrack && !this.tracksInGroup.length) {
  28501. return;
  28502. }
  28503. this.tracksInGroup = subtitleTracks;
  28504. const subtitlePreference = this.hls.config.subtitlePreference;
  28505. if (!currentTrack && subtitlePreference) {
  28506. this.selectDefaultTrack = false;
  28507. const groupIndex = findMatchingOption(subtitlePreference, subtitleTracks);
  28508. if (groupIndex > -1) {
  28509. currentTrack = subtitleTracks[groupIndex];
  28510. } else {
  28511. const allIndex = findMatchingOption(subtitlePreference, this.tracks);
  28512. currentTrack = this.tracks[allIndex];
  28513. }
  28514. }
  28515. let trackId = this.findTrackId(currentTrack);
  28516. if (trackId === -1 && currentTrack) {
  28517. trackId = this.findTrackId(null);
  28518. }
  28519. const subtitleTracksUpdated = {
  28520. subtitleTracks
  28521. };
  28522. this.log(`Updating subtitle tracks, ${subtitleTracks.length} track(s) found in "${subtitleGroups == null ? void 0 : subtitleGroups.join(",")}" group-id`);
  28523. this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
  28524. if (trackId !== -1 && this.trackId === -1) {
  28525. this.setSubtitleTrack(trackId);
  28526. }
  28527. }
  28528. }
  28529. findTrackId(currentTrack) {
  28530. const tracks = this.tracksInGroup;
  28531. const selectDefault = this.selectDefaultTrack;
  28532. for (let i2 = 0; i2 < tracks.length; i2++) {
  28533. const track2 = tracks[i2];
  28534. if (selectDefault && !track2.default || !selectDefault && !currentTrack) {
  28535. continue;
  28536. }
  28537. if (!currentTrack || matchesOption(track2, currentTrack)) {
  28538. return i2;
  28539. }
  28540. }
  28541. if (currentTrack) {
  28542. for (let i2 = 0; i2 < tracks.length; i2++) {
  28543. const track2 = tracks[i2];
  28544. if (mediaAttributesIdentical(currentTrack.attrs, track2.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
  28545. return i2;
  28546. }
  28547. }
  28548. for (let i2 = 0; i2 < tracks.length; i2++) {
  28549. const track2 = tracks[i2];
  28550. if (mediaAttributesIdentical(currentTrack.attrs, track2.attrs, ["LANGUAGE"])) {
  28551. return i2;
  28552. }
  28553. }
  28554. }
  28555. return -1;
  28556. }
  28557. findTrackForTextTrack(textTrack) {
  28558. if (textTrack) {
  28559. const tracks = this.tracksInGroup;
  28560. for (let i2 = 0; i2 < tracks.length; i2++) {
  28561. const track2 = tracks[i2];
  28562. if (subtitleTrackMatchesTextTrack(track2, textTrack)) {
  28563. return i2;
  28564. }
  28565. }
  28566. }
  28567. return -1;
  28568. }
  28569. onError(event, data) {
  28570. if (data.fatal || !data.context) {
  28571. return;
  28572. }
  28573. if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  28574. this.checkRetry(data);
  28575. }
  28576. }
  28577. get allSubtitleTracks() {
  28578. return this.tracks;
  28579. }
  28580. /** get alternate subtitle tracks list from playlist **/
  28581. get subtitleTracks() {
  28582. return this.tracksInGroup;
  28583. }
  28584. /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
  28585. get subtitleTrack() {
  28586. return this.trackId;
  28587. }
  28588. set subtitleTrack(newId) {
  28589. this.selectDefaultTrack = false;
  28590. this.setSubtitleTrack(newId);
  28591. }
  28592. setSubtitleOption(subtitleOption) {
  28593. this.hls.config.subtitlePreference = subtitleOption;
  28594. if (subtitleOption) {
  28595. if (subtitleOption.id === -1) {
  28596. this.setSubtitleTrack(-1);
  28597. return null;
  28598. }
  28599. const allSubtitleTracks = this.allSubtitleTracks;
  28600. this.selectDefaultTrack = false;
  28601. if (allSubtitleTracks.length) {
  28602. const currentTrack = this.currentTrack;
  28603. if (currentTrack && matchesOption(subtitleOption, currentTrack)) {
  28604. return currentTrack;
  28605. }
  28606. const groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup);
  28607. if (groupIndex > -1) {
  28608. const track2 = this.tracksInGroup[groupIndex];
  28609. this.setSubtitleTrack(groupIndex);
  28610. return track2;
  28611. } else if (currentTrack) {
  28612. return null;
  28613. } else {
  28614. const allIndex = findMatchingOption(subtitleOption, allSubtitleTracks);
  28615. if (allIndex > -1) {
  28616. return allSubtitleTracks[allIndex];
  28617. }
  28618. }
  28619. }
  28620. }
  28621. return null;
  28622. }
  28623. loadPlaylist(hlsUrlParameters) {
  28624. super.loadPlaylist();
  28625. if (this.shouldLoadPlaylist(this.currentTrack)) {
  28626. this.scheduleLoading(this.currentTrack, hlsUrlParameters);
  28627. }
  28628. }
  28629. loadingPlaylist(currentTrack, hlsUrlParameters) {
  28630. super.loadingPlaylist(currentTrack, hlsUrlParameters);
  28631. const id = currentTrack.id;
  28632. const groupId = currentTrack.groupId;
  28633. const url = this.getUrlWithDirectives(currentTrack.url, hlsUrlParameters);
  28634. const details = currentTrack.details;
  28635. const age = details == null ? void 0 : details.age;
  28636. this.log(`Loading subtitle ${id} "${currentTrack.name}" lang:${currentTrack.lang} group:${groupId}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== void 0 ? " at sn " + hlsUrlParameters.msn + " part " + hlsUrlParameters.part : ""}${age && details.live ? " age " + age.toFixed(1) + (details.type ? " " + details.type || "" : "") : ""} ${url}`);
  28637. this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {
  28638. url,
  28639. id,
  28640. groupId,
  28641. deliveryDirectives: hlsUrlParameters || null,
  28642. track: currentTrack
  28643. });
  28644. }
  28645. /**
  28646. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  28647. * This operates on the DOM textTracks.
  28648. * A value of -1 will disable all subtitle tracks.
  28649. */
  28650. toggleTrackModes() {
  28651. const {
  28652. media
  28653. } = this;
  28654. if (!media) {
  28655. return;
  28656. }
  28657. const textTracks = filterSubtitleTracks(media.textTracks);
  28658. const currentTrack = this.currentTrack;
  28659. let nextTrack;
  28660. if (currentTrack) {
  28661. nextTrack = textTracks.filter((textTrack) => subtitleTrackMatchesTextTrack(currentTrack, textTrack))[0];
  28662. if (!nextTrack) {
  28663. this.warn(`Unable to find subtitle TextTrack with name "${currentTrack.name}" and language "${currentTrack.lang}"`);
  28664. }
  28665. }
  28666. [].slice.call(textTracks).forEach((track2) => {
  28667. if (track2.mode !== "disabled" && track2 !== nextTrack) {
  28668. track2.mode = "disabled";
  28669. }
  28670. });
  28671. if (nextTrack) {
  28672. const mode = this.subtitleDisplay ? "showing" : "hidden";
  28673. if (nextTrack.mode !== mode) {
  28674. nextTrack.mode = mode;
  28675. }
  28676. }
  28677. }
  28678. /**
  28679. * This method is responsible for validating the subtitle index and periodically reloading if live.
  28680. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  28681. */
  28682. setSubtitleTrack(newId) {
  28683. const tracks = this.tracksInGroup;
  28684. if (!this.media) {
  28685. this.queuedDefaultTrack = newId;
  28686. return;
  28687. }
  28688. if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) {
  28689. this.warn(`Invalid subtitle track id: ${newId}`);
  28690. return;
  28691. }
  28692. this.selectDefaultTrack = false;
  28693. const lastTrack = this.currentTrack;
  28694. const track2 = tracks[newId] || null;
  28695. this.trackId = newId;
  28696. this.currentTrack = track2;
  28697. this.toggleTrackModes();
  28698. if (!track2) {
  28699. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  28700. id: newId
  28701. });
  28702. return;
  28703. }
  28704. const trackLoaded = !!track2.details && !track2.details.live;
  28705. if (newId === this.trackId && track2 === lastTrack && trackLoaded) {
  28706. return;
  28707. }
  28708. this.log(`Switching to subtitle-track ${newId}` + (track2 ? ` "${track2.name}" lang:${track2.lang} group:${track2.groupId}` : ""));
  28709. const {
  28710. id,
  28711. groupId = "",
  28712. name,
  28713. type,
  28714. url
  28715. } = track2;
  28716. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  28717. id,
  28718. groupId,
  28719. name,
  28720. type,
  28721. url
  28722. });
  28723. const hlsUrlParameters = this.switchParams(track2.url, lastTrack == null ? void 0 : lastTrack.details, track2.details);
  28724. this.loadPlaylist(hlsUrlParameters);
  28725. }
  28726. }
  28727. function uuid() {
  28728. try {
  28729. return crypto.randomUUID();
  28730. } catch (error) {
  28731. try {
  28732. const url = URL.createObjectURL(new Blob());
  28733. const uuid2 = url.toString();
  28734. URL.revokeObjectURL(url);
  28735. return uuid2.slice(uuid2.lastIndexOf("/") + 1);
  28736. } catch (error2) {
  28737. let dt2 = (/* @__PURE__ */ new Date()).getTime();
  28738. const uuid2 = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c2) => {
  28739. const r2 = (dt2 + Math.random() * 16) % 16 | 0;
  28740. dt2 = Math.floor(dt2 / 16);
  28741. return (c2 == "x" ? r2 : r2 & 3 | 8).toString(16);
  28742. });
  28743. return uuid2;
  28744. }
  28745. }
  28746. }
  28747. function hash(text) {
  28748. let hash2 = 5381;
  28749. let i2 = text.length;
  28750. while (i2) {
  28751. hash2 = hash2 * 33 ^ text.charCodeAt(--i2);
  28752. }
  28753. return (hash2 >>> 0).toString();
  28754. }
  28755. const ALIGNED_END_THRESHOLD_SECONDS = 0.025;
  28756. let TimelineOccupancy = /* @__PURE__ */ function(TimelineOccupancy2) {
  28757. TimelineOccupancy2[TimelineOccupancy2["Point"] = 0] = "Point";
  28758. TimelineOccupancy2[TimelineOccupancy2["Range"] = 1] = "Range";
  28759. return TimelineOccupancy2;
  28760. }({});
  28761. function generateAssetIdentifier(interstitial, uri, assetListIndex) {
  28762. return `${interstitial.identifier}-${assetListIndex + 1}-${hash(uri)}`;
  28763. }
  28764. class InterstitialEvent {
  28765. constructor(dateRange, base) {
  28766. this.base = void 0;
  28767. this._duration = null;
  28768. this._timelineStart = null;
  28769. this.appendInPlaceDisabled = void 0;
  28770. this.appendInPlaceStarted = void 0;
  28771. this.dateRange = void 0;
  28772. this.hasPlayed = false;
  28773. this.cumulativeDuration = 0;
  28774. this.resumeOffset = NaN;
  28775. this.playoutLimit = NaN;
  28776. this.restrictions = {
  28777. skip: false,
  28778. jump: false
  28779. };
  28780. this.snapOptions = {
  28781. out: false,
  28782. in: false
  28783. };
  28784. this.assetList = [];
  28785. this.assetListLoader = void 0;
  28786. this.assetListResponse = null;
  28787. this.resumeAnchor = void 0;
  28788. this.error = void 0;
  28789. this.resetOnResume = void 0;
  28790. this.base = base;
  28791. this.dateRange = dateRange;
  28792. this.setDateRange(dateRange);
  28793. }
  28794. setDateRange(dateRange) {
  28795. this.dateRange = dateRange;
  28796. this.resumeOffset = dateRange.attr.optionalFloat("X-RESUME-OFFSET", this.resumeOffset);
  28797. this.playoutLimit = dateRange.attr.optionalFloat("X-PLAYOUT-LIMIT", this.playoutLimit);
  28798. this.restrictions = dateRange.attr.enumeratedStringList("X-RESTRICT", this.restrictions);
  28799. this.snapOptions = dateRange.attr.enumeratedStringList("X-SNAP", this.snapOptions);
  28800. }
  28801. reset() {
  28802. var _this$assetListLoader;
  28803. this.appendInPlaceStarted = false;
  28804. (_this$assetListLoader = this.assetListLoader) == null ? void 0 : _this$assetListLoader.destroy();
  28805. this.assetListLoader = void 0;
  28806. if (!this.supplementsPrimary) {
  28807. this.assetListResponse = null;
  28808. this.assetList = [];
  28809. this._duration = null;
  28810. }
  28811. }
  28812. isAssetPastPlayoutLimit(assetIndex) {
  28813. var _this$assetList$asset;
  28814. if (assetIndex > 0 && assetIndex >= this.assetList.length) {
  28815. return true;
  28816. }
  28817. const playoutLimit = this.playoutLimit;
  28818. if (assetIndex <= 0 || isNaN(playoutLimit)) {
  28819. return false;
  28820. }
  28821. if (playoutLimit === 0) {
  28822. return true;
  28823. }
  28824. const assetOffset = ((_this$assetList$asset = this.assetList[assetIndex]) == null ? void 0 : _this$assetList$asset.startOffset) || 0;
  28825. return assetOffset > playoutLimit;
  28826. }
  28827. findAssetIndex(asset) {
  28828. const index2 = this.assetList.indexOf(asset);
  28829. return index2;
  28830. }
  28831. get identifier() {
  28832. return this.dateRange.id;
  28833. }
  28834. get startDate() {
  28835. return this.dateRange.startDate;
  28836. }
  28837. get startTime() {
  28838. const startTime = this.dateRange.startTime;
  28839. if (this.snapOptions.out) {
  28840. const frag = this.dateRange.tagAnchor;
  28841. if (frag) {
  28842. return getSnapToFragmentTime(startTime, frag);
  28843. }
  28844. }
  28845. return startTime;
  28846. }
  28847. get startOffset() {
  28848. return this.cue.pre ? 0 : this.startTime;
  28849. }
  28850. get startIsAligned() {
  28851. if (this.startTime === 0 || this.snapOptions.out) {
  28852. return true;
  28853. }
  28854. const frag = this.dateRange.tagAnchor;
  28855. if (frag) {
  28856. const startTime = this.dateRange.startTime;
  28857. const snappedStart = getSnapToFragmentTime(startTime, frag);
  28858. return startTime - snappedStart < 0.1;
  28859. }
  28860. return false;
  28861. }
  28862. get resumptionOffset() {
  28863. const resumeOffset = this.resumeOffset;
  28864. const offset = isFiniteNumber(resumeOffset) ? resumeOffset : this.duration;
  28865. return this.cumulativeDuration + offset;
  28866. }
  28867. get resumeTime() {
  28868. const resumeTime = this.startOffset + this.resumptionOffset;
  28869. if (this.snapOptions.in) {
  28870. const frag = this.resumeAnchor;
  28871. if (frag) {
  28872. return getSnapToFragmentTime(resumeTime, frag);
  28873. }
  28874. }
  28875. return resumeTime;
  28876. }
  28877. get appendInPlace() {
  28878. if (this.appendInPlaceStarted) {
  28879. return true;
  28880. }
  28881. if (this.appendInPlaceDisabled) {
  28882. return false;
  28883. }
  28884. if (!this.cue.once && !this.cue.pre && // preroll starts at startPosition before startPosition is known (live)
  28885. this.startIsAligned && (isNaN(this.playoutLimit) && isNaN(this.resumeOffset) || this.resumeOffset && this.duration && Math.abs(this.resumeOffset - this.duration) < ALIGNED_END_THRESHOLD_SECONDS)) {
  28886. return true;
  28887. }
  28888. return false;
  28889. }
  28890. set appendInPlace(value) {
  28891. if (this.appendInPlaceStarted) {
  28892. this.resetOnResume = !value;
  28893. return;
  28894. }
  28895. this.appendInPlaceDisabled = !value;
  28896. }
  28897. // Extended timeline start time
  28898. get timelineStart() {
  28899. if (this._timelineStart !== null) {
  28900. return this._timelineStart;
  28901. }
  28902. return this.startTime;
  28903. }
  28904. set timelineStart(value) {
  28905. this._timelineStart = value;
  28906. }
  28907. get duration() {
  28908. const playoutLimit = this.playoutLimit;
  28909. let duration;
  28910. if (this._duration !== null) {
  28911. duration = this._duration;
  28912. } else if (this.dateRange.duration) {
  28913. duration = this.dateRange.duration;
  28914. } else {
  28915. duration = this.dateRange.plannedDuration || 0;
  28916. }
  28917. if (!isNaN(playoutLimit) && playoutLimit < duration) {
  28918. duration = playoutLimit;
  28919. }
  28920. return duration;
  28921. }
  28922. set duration(value) {
  28923. this._duration = value;
  28924. }
  28925. get cue() {
  28926. return this.dateRange.cue;
  28927. }
  28928. get timelineOccupancy() {
  28929. if (this.dateRange.attr["X-TIMELINE-OCCUPIES"] === "RANGE") {
  28930. return TimelineOccupancy.Range;
  28931. }
  28932. return TimelineOccupancy.Point;
  28933. }
  28934. get supplementsPrimary() {
  28935. return this.dateRange.attr["X-TIMELINE-STYLE"] === "PRIMARY";
  28936. }
  28937. get contentMayVary() {
  28938. return this.dateRange.attr["X-CONTENT-MAY-VARY"] !== "NO";
  28939. }
  28940. get assetUrl() {
  28941. return this.dateRange.attr["X-ASSET-URI"];
  28942. }
  28943. get assetListUrl() {
  28944. return this.dateRange.attr["X-ASSET-LIST"];
  28945. }
  28946. get baseUrl() {
  28947. return this.base.url;
  28948. }
  28949. get assetListLoaded() {
  28950. return this.assetList.length > 0 || this.assetListResponse !== null;
  28951. }
  28952. toString() {
  28953. return eventToString(this);
  28954. }
  28955. }
  28956. function getSnapToFragmentTime(time, frag) {
  28957. return time - frag.start < frag.duration / 2 && !(Math.abs(time - (frag.start + frag.duration)) < ALIGNED_END_THRESHOLD_SECONDS) ? frag.start : frag.start + frag.duration;
  28958. }
  28959. function getInterstitialUrl(uri, sessionId, baseUrl) {
  28960. const url = new self.URL(uri, baseUrl);
  28961. if (url.protocol !== "data:") {
  28962. url.searchParams.set("_HLS_primary_id", sessionId);
  28963. }
  28964. return url;
  28965. }
  28966. function getNextAssetIndex(interstitial, assetListIndex) {
  28967. while ((_interstitial$assetLi = interstitial.assetList[++assetListIndex]) != null && _interstitial$assetLi.error) {
  28968. var _interstitial$assetLi;
  28969. }
  28970. return assetListIndex;
  28971. }
  28972. function eventToString(interstitial) {
  28973. return `["${interstitial.identifier}" ${interstitial.cue.pre ? "<pre>" : interstitial.cue.post ? "<post>" : ""}${interstitial.timelineStart.toFixed(2)}-${interstitial.resumeTime.toFixed(2)}]`;
  28974. }
  28975. function eventAssetToString(asset) {
  28976. const start = asset.timelineStart;
  28977. const duration = asset.duration || 0;
  28978. return `["${asset.identifier}" ${start.toFixed(2)}-${(start + duration).toFixed(2)}]`;
  28979. }
  28980. class HlsAssetPlayer {
  28981. constructor(HlsPlayerClass, userConfig, interstitial, assetItem) {
  28982. this.hls = void 0;
  28983. this.interstitial = void 0;
  28984. this.assetItem = void 0;
  28985. this.tracks = null;
  28986. this.hasDetails = false;
  28987. this.mediaAttached = null;
  28988. this._currentTime = void 0;
  28989. this._bufferedEosTime = void 0;
  28990. this.checkPlayout = () => {
  28991. if (this.reachedPlayout(this.currentTime)) {
  28992. this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED, {});
  28993. }
  28994. };
  28995. const hls = this.hls = new HlsPlayerClass(userConfig);
  28996. this.interstitial = interstitial;
  28997. this.assetItem = assetItem;
  28998. let uri = assetItem.uri;
  28999. try {
  29000. uri = getInterstitialUrl(uri, userConfig.primarySessionId).href;
  29001. } catch (error) {
  29002. }
  29003. hls.loadSource(uri);
  29004. const detailsLoaded = () => {
  29005. this.hasDetails = true;
  29006. };
  29007. hls.once(Events.LEVEL_LOADED, detailsLoaded);
  29008. hls.once(Events.AUDIO_TRACK_LOADED, detailsLoaded);
  29009. hls.once(Events.SUBTITLE_TRACK_LOADED, detailsLoaded);
  29010. hls.on(Events.MEDIA_ATTACHING, (name, {
  29011. media
  29012. }) => {
  29013. this.removeMediaListeners();
  29014. this.mediaAttached = media;
  29015. const event = this.interstitial;
  29016. if (event.playoutLimit) {
  29017. media.addEventListener("timeupdate", this.checkPlayout);
  29018. if (this.appendInPlace) {
  29019. hls.on(Events.BUFFER_APPENDED, () => {
  29020. const bufferedEnd = this.bufferedEnd;
  29021. if (this.reachedPlayout(bufferedEnd)) {
  29022. this._bufferedEosTime = bufferedEnd;
  29023. hls.trigger(Events.BUFFERED_TO_END, void 0);
  29024. }
  29025. });
  29026. }
  29027. }
  29028. });
  29029. }
  29030. get appendInPlace() {
  29031. var _this$interstitial;
  29032. return ((_this$interstitial = this.interstitial) == null ? void 0 : _this$interstitial.appendInPlace) || false;
  29033. }
  29034. bufferedInPlaceToEnd(media) {
  29035. var _this$hls;
  29036. if (!this.appendInPlace) {
  29037. return false;
  29038. }
  29039. if ((_this$hls = this.hls) != null && _this$hls.bufferedToEnd) {
  29040. return true;
  29041. }
  29042. if (!media || !this._bufferedEosTime) {
  29043. return false;
  29044. }
  29045. const start = this.timelineOffset;
  29046. const bufferInfo = BufferHelper.bufferInfo(media, start, 0);
  29047. const bufferedEnd = this.getAssetTime(bufferInfo.end);
  29048. return bufferedEnd >= this._bufferedEosTime - 0.02;
  29049. }
  29050. reachedPlayout(time) {
  29051. const interstitial = this.interstitial;
  29052. const playoutLimit = interstitial.playoutLimit;
  29053. return this.startOffset + time >= playoutLimit;
  29054. }
  29055. get destroyed() {
  29056. var _this$hls2;
  29057. return !((_this$hls2 = this.hls) != null && _this$hls2.userConfig);
  29058. }
  29059. get assetId() {
  29060. return this.assetItem.identifier;
  29061. }
  29062. get interstitialId() {
  29063. return this.assetItem.parentIdentifier;
  29064. }
  29065. get media() {
  29066. var _this$hls3;
  29067. return ((_this$hls3 = this.hls) == null ? void 0 : _this$hls3.media) || null;
  29068. }
  29069. get bufferedEnd() {
  29070. const media = this.media || this.mediaAttached;
  29071. if (!media) {
  29072. if (this._bufferedEosTime) {
  29073. return this._bufferedEosTime;
  29074. }
  29075. return this.currentTime;
  29076. }
  29077. const bufferInfo = BufferHelper.bufferInfo(media, media.currentTime, 1e-3);
  29078. return this.getAssetTime(bufferInfo.end);
  29079. }
  29080. get currentTime() {
  29081. const media = this.media || this.mediaAttached;
  29082. if (!media) {
  29083. return this._currentTime || 0;
  29084. }
  29085. return this.getAssetTime(media.currentTime);
  29086. }
  29087. get duration() {
  29088. const duration = this.assetItem.duration;
  29089. if (!duration) {
  29090. return 0;
  29091. }
  29092. return duration;
  29093. }
  29094. get remaining() {
  29095. const duration = this.duration;
  29096. if (!duration) {
  29097. return 0;
  29098. }
  29099. return Math.max(0, duration - this.currentTime);
  29100. }
  29101. get startOffset() {
  29102. return this.assetItem.startOffset;
  29103. }
  29104. get timelineOffset() {
  29105. var _this$hls4;
  29106. return ((_this$hls4 = this.hls) == null ? void 0 : _this$hls4.config.timelineOffset) || 0;
  29107. }
  29108. set timelineOffset(value) {
  29109. const timelineOffset = this.timelineOffset;
  29110. if (value !== timelineOffset) {
  29111. const diff2 = value - timelineOffset;
  29112. if (Math.abs(diff2) > 1 / 9e4) {
  29113. if (this.hasDetails) {
  29114. throw new Error(`Cannot set timelineOffset after playlists are loaded`);
  29115. }
  29116. this.hls.config.timelineOffset = value;
  29117. }
  29118. }
  29119. }
  29120. getAssetTime(time) {
  29121. const timelineOffset = this.timelineOffset;
  29122. const duration = this.duration;
  29123. return Math.min(Math.max(0, time - timelineOffset), duration);
  29124. }
  29125. removeMediaListeners() {
  29126. const media = this.mediaAttached;
  29127. if (media) {
  29128. this._currentTime = media.currentTime;
  29129. this.bufferSnapShot();
  29130. media.removeEventListener("timeupdate", this.checkPlayout);
  29131. }
  29132. }
  29133. bufferSnapShot() {
  29134. if (this.mediaAttached) {
  29135. var _this$hls5;
  29136. if ((_this$hls5 = this.hls) != null && _this$hls5.bufferedToEnd) {
  29137. this._bufferedEosTime = this.bufferedEnd;
  29138. }
  29139. }
  29140. }
  29141. destroy() {
  29142. this.removeMediaListeners();
  29143. this.hls.destroy();
  29144. this.hls = this.interstitial = null;
  29145. this.tracks = this.mediaAttached = this.checkPlayout = null;
  29146. }
  29147. attachMedia(data) {
  29148. this.hls.attachMedia(data);
  29149. }
  29150. detachMedia() {
  29151. this.removeMediaListeners();
  29152. this.mediaAttached = null;
  29153. this.hls.detachMedia();
  29154. }
  29155. resumeBuffering() {
  29156. this.hls.resumeBuffering();
  29157. }
  29158. pauseBuffering() {
  29159. this.hls.pauseBuffering();
  29160. }
  29161. transferMedia() {
  29162. this.bufferSnapShot();
  29163. return this.hls.transferMedia();
  29164. }
  29165. resetDetails() {
  29166. const hls = this.hls;
  29167. if (this.hasDetails) {
  29168. hls.stopLoad();
  29169. const deleteDetails = (obj) => delete obj.details;
  29170. hls.levels.forEach(deleteDetails);
  29171. hls.allAudioTracks.forEach(deleteDetails);
  29172. hls.allSubtitleTracks.forEach(deleteDetails);
  29173. this.hasDetails = false;
  29174. }
  29175. }
  29176. on(event, listener, context) {
  29177. this.hls.on(event, listener);
  29178. }
  29179. once(event, listener, context) {
  29180. this.hls.once(event, listener);
  29181. }
  29182. off(event, listener, context) {
  29183. this.hls.off(event, listener);
  29184. }
  29185. toString() {
  29186. var _this$hls6;
  29187. return `HlsAssetPlayer: ${eventAssetToString(this.assetItem)} ${(_this$hls6 = this.hls) == null ? void 0 : _this$hls6.sessionId} ${this.appendInPlace ? "append-in-place" : ""}`;
  29188. }
  29189. }
  29190. const ABUTTING_THRESHOLD_SECONDS = 0.033;
  29191. class InterstitialsSchedule extends Logger {
  29192. constructor(onScheduleUpdate, logger2) {
  29193. super("interstitials-sched", logger2);
  29194. this.onScheduleUpdate = void 0;
  29195. this.eventMap = {};
  29196. this.events = null;
  29197. this.items = null;
  29198. this.durations = {
  29199. primary: 0,
  29200. playout: 0,
  29201. integrated: 0
  29202. };
  29203. this.onScheduleUpdate = onScheduleUpdate;
  29204. }
  29205. destroy() {
  29206. this.reset();
  29207. this.onScheduleUpdate = null;
  29208. }
  29209. reset() {
  29210. this.eventMap = {};
  29211. this.setDurations(0, 0, 0);
  29212. if (this.events) {
  29213. this.events.forEach((interstitial) => interstitial.reset());
  29214. }
  29215. this.events = this.items = null;
  29216. }
  29217. resetErrorsInRange(start, end) {
  29218. if (this.events) {
  29219. return this.events.reduce((count, interstitial) => {
  29220. if (start <= interstitial.startOffset && end > interstitial.startOffset) {
  29221. delete interstitial.error;
  29222. return count + 1;
  29223. }
  29224. return count;
  29225. }, 0);
  29226. }
  29227. return 0;
  29228. }
  29229. get duration() {
  29230. const items = this.items;
  29231. return items ? items[items.length - 1].end : 0;
  29232. }
  29233. get length() {
  29234. return this.items ? this.items.length : 0;
  29235. }
  29236. getEvent(identifier) {
  29237. return identifier ? this.eventMap[identifier] || null : null;
  29238. }
  29239. hasEvent(identifier) {
  29240. return identifier in this.eventMap;
  29241. }
  29242. findItemIndex(item, time) {
  29243. if (item.event) {
  29244. return this.findEventIndex(item.event.identifier);
  29245. }
  29246. let index2 = -1;
  29247. if (item.nextEvent) {
  29248. index2 = this.findEventIndex(item.nextEvent.identifier) - 1;
  29249. } else if (item.previousEvent) {
  29250. index2 = this.findEventIndex(item.previousEvent.identifier) + 1;
  29251. }
  29252. const items = this.items;
  29253. if (items) {
  29254. if (!items[index2]) {
  29255. if (time === void 0) {
  29256. time = item.start;
  29257. }
  29258. index2 = this.findItemIndexAtTime(time);
  29259. }
  29260. while (index2 >= 0 && (_items$index = items[index2]) != null && _items$index.event) {
  29261. var _items$index;
  29262. index2--;
  29263. }
  29264. }
  29265. return index2;
  29266. }
  29267. findItemIndexAtTime(timelinePos, timelineType) {
  29268. const items = this.items;
  29269. if (items) {
  29270. for (let i2 = 0; i2 < items.length; i2++) {
  29271. let timeRange = items[i2];
  29272. if (timelineType && timelineType !== "primary") {
  29273. timeRange = timeRange[timelineType];
  29274. }
  29275. if (timelinePos === timeRange.start || timelinePos > timeRange.start && timelinePos < timeRange.end) {
  29276. return i2;
  29277. }
  29278. }
  29279. }
  29280. return -1;
  29281. }
  29282. findJumpRestrictedIndex(startIndex, endIndex) {
  29283. const items = this.items;
  29284. if (items) {
  29285. for (let i2 = startIndex; i2 <= endIndex; i2++) {
  29286. if (!items[i2]) {
  29287. break;
  29288. }
  29289. const event = items[i2].event;
  29290. if (event != null && event.restrictions.jump && !event.appendInPlace) {
  29291. return i2;
  29292. }
  29293. }
  29294. }
  29295. return -1;
  29296. }
  29297. findEventIndex(identifier) {
  29298. const items = this.items;
  29299. if (items) {
  29300. for (let i2 = items.length; i2--; ) {
  29301. var _items$i$event;
  29302. if (((_items$i$event = items[i2].event) == null ? void 0 : _items$i$event.identifier) === identifier) {
  29303. return i2;
  29304. }
  29305. }
  29306. }
  29307. return -1;
  29308. }
  29309. findAssetIndex(event, timelinePos) {
  29310. const assetList = event.assetList;
  29311. const length = assetList.length;
  29312. if (length > 1) {
  29313. for (let i2 = 0; i2 < length; i2++) {
  29314. const asset = assetList[i2];
  29315. if (!asset.error) {
  29316. const timelineStart = asset.timelineStart;
  29317. if (timelinePos === timelineStart || timelinePos > timelineStart && timelinePos < timelineStart + (asset.duration || 0)) {
  29318. return i2;
  29319. }
  29320. }
  29321. }
  29322. }
  29323. return 0;
  29324. }
  29325. get assetIdAtEnd() {
  29326. var _this$items, _this$items2;
  29327. const interstitialAtEnd = (_this$items = this.items) == null ? void 0 : (_this$items2 = _this$items[this.length - 1]) == null ? void 0 : _this$items2.event;
  29328. if (interstitialAtEnd) {
  29329. const assetList = interstitialAtEnd.assetList;
  29330. const assetAtEnd = assetList[assetList.length - 1];
  29331. if (assetAtEnd) {
  29332. return assetAtEnd.identifier;
  29333. }
  29334. }
  29335. return null;
  29336. }
  29337. parseInterstitialDateRanges(mediaSelection, enableAppendInPlace) {
  29338. const details = mediaSelection.main.details;
  29339. const {
  29340. dateRanges
  29341. } = details;
  29342. const previousInterstitialEvents = this.events;
  29343. const interstitialEvents = this.parseDateRanges(dateRanges, {
  29344. url: details.url
  29345. }, enableAppendInPlace);
  29346. const ids = Object.keys(dateRanges);
  29347. const removedInterstitials = previousInterstitialEvents ? previousInterstitialEvents.filter((event) => !ids.includes(event.identifier)) : [];
  29348. if (interstitialEvents.length) {
  29349. interstitialEvents.sort((a2, b2) => {
  29350. const aPre = a2.cue.pre;
  29351. const aPost = a2.cue.post;
  29352. const bPre = b2.cue.pre;
  29353. const bPost = b2.cue.post;
  29354. if (aPre && !bPre) {
  29355. return -1;
  29356. }
  29357. if (bPre && !aPre) {
  29358. return 1;
  29359. }
  29360. if (aPost && !bPost) {
  29361. return 1;
  29362. }
  29363. if (bPost && !aPost) {
  29364. return -1;
  29365. }
  29366. if (!aPre && !bPre && !aPost && !bPost) {
  29367. const startA = a2.startTime;
  29368. const startB = b2.startTime;
  29369. if (startA !== startB) {
  29370. return startA - startB;
  29371. }
  29372. }
  29373. return a2.dateRange.tagOrder - b2.dateRange.tagOrder;
  29374. });
  29375. }
  29376. this.events = interstitialEvents;
  29377. removedInterstitials.forEach((interstitial) => {
  29378. this.removeEvent(interstitial);
  29379. });
  29380. this.updateSchedule(mediaSelection, removedInterstitials);
  29381. }
  29382. updateSchedule(mediaSelection, removedInterstitials = []) {
  29383. const events = this.events || [];
  29384. if (events.length || removedInterstitials.length || this.length < 2) {
  29385. const currentItems = this.items;
  29386. const updatedItems = this.parseSchedule(events, mediaSelection);
  29387. const updated = removedInterstitials.length || (currentItems == null ? void 0 : currentItems.length) !== updatedItems.length || updatedItems.some((item, i2) => {
  29388. return Math.abs(item.playout.start - currentItems[i2].playout.start) > 5e-3 || Math.abs(item.playout.end - currentItems[i2].playout.end) > 5e-3;
  29389. });
  29390. if (updated) {
  29391. this.items = updatedItems;
  29392. this.onScheduleUpdate(removedInterstitials, currentItems);
  29393. }
  29394. }
  29395. }
  29396. parseDateRanges(dateRanges, baseData, enableAppendInPlace) {
  29397. const interstitialEvents = [];
  29398. const ids = Object.keys(dateRanges);
  29399. for (let i2 = 0; i2 < ids.length; i2++) {
  29400. const id = ids[i2];
  29401. const dateRange = dateRanges[id];
  29402. if (dateRange.isInterstitial) {
  29403. let interstitial = this.eventMap[id];
  29404. if (interstitial) {
  29405. interstitial.setDateRange(dateRange);
  29406. } else {
  29407. interstitial = new InterstitialEvent(dateRange, baseData);
  29408. this.eventMap[id] = interstitial;
  29409. if (enableAppendInPlace === false) {
  29410. interstitial.appendInPlace = enableAppendInPlace;
  29411. }
  29412. }
  29413. interstitialEvents.push(interstitial);
  29414. }
  29415. }
  29416. return interstitialEvents;
  29417. }
  29418. parseSchedule(interstitialEvents, mediaSelection) {
  29419. const schedule = [];
  29420. const details = mediaSelection.main.details;
  29421. const primaryDuration = details.live ? Infinity : details.edge;
  29422. let playoutDuration = 0;
  29423. interstitialEvents = interstitialEvents.filter((event) => !event.error && !(event.cue.once && event.hasPlayed));
  29424. if (interstitialEvents.length) {
  29425. this.resolveOffsets(interstitialEvents, mediaSelection);
  29426. let primaryPosition = 0;
  29427. let integratedTime = 0;
  29428. interstitialEvents.forEach((interstitial, i2) => {
  29429. const preroll = interstitial.cue.pre;
  29430. const postroll = interstitial.cue.post;
  29431. const previousEvent = interstitialEvents[i2 - 1] || null;
  29432. const appendInPlace = interstitial.appendInPlace;
  29433. const eventStart = postroll ? primaryDuration : interstitial.startOffset;
  29434. const interstitialDuration = interstitial.duration;
  29435. const timelineDuration = interstitial.timelineOccupancy === TimelineOccupancy.Range ? interstitialDuration : 0;
  29436. const resumptionOffset = interstitial.resumptionOffset;
  29437. const inSameStartTimeSequence = (previousEvent == null ? void 0 : previousEvent.startTime) === eventStart;
  29438. const start = eventStart + interstitial.cumulativeDuration;
  29439. let end = appendInPlace ? start + interstitialDuration : eventStart + resumptionOffset;
  29440. if (preroll || !postroll && eventStart <= 0) {
  29441. const integratedStart = integratedTime;
  29442. integratedTime += timelineDuration;
  29443. interstitial.timelineStart = start;
  29444. const playoutStart = playoutDuration;
  29445. playoutDuration += interstitialDuration;
  29446. schedule.push({
  29447. event: interstitial,
  29448. start,
  29449. end,
  29450. playout: {
  29451. start: playoutStart,
  29452. end: playoutDuration
  29453. },
  29454. integrated: {
  29455. start: integratedStart,
  29456. end: integratedTime
  29457. }
  29458. });
  29459. } else if (eventStart <= primaryDuration) {
  29460. if (!inSameStartTimeSequence) {
  29461. const segmentDuration = eventStart - primaryPosition;
  29462. if (segmentDuration > ABUTTING_THRESHOLD_SECONDS) {
  29463. const timelineStart = primaryPosition;
  29464. const _integratedStart = integratedTime;
  29465. integratedTime += segmentDuration;
  29466. const _playoutStart = playoutDuration;
  29467. playoutDuration += segmentDuration;
  29468. const primarySegment = {
  29469. previousEvent: interstitialEvents[i2 - 1] || null,
  29470. nextEvent: interstitial,
  29471. start: timelineStart,
  29472. end: timelineStart + segmentDuration,
  29473. playout: {
  29474. start: _playoutStart,
  29475. end: playoutDuration
  29476. },
  29477. integrated: {
  29478. start: _integratedStart,
  29479. end: integratedTime
  29480. }
  29481. };
  29482. schedule.push(primarySegment);
  29483. } else if (segmentDuration > 0 && previousEvent) {
  29484. previousEvent.cumulativeDuration += segmentDuration;
  29485. schedule[schedule.length - 1].end = eventStart;
  29486. }
  29487. }
  29488. if (postroll) {
  29489. end = start;
  29490. }
  29491. interstitial.timelineStart = start;
  29492. const integratedStart = integratedTime;
  29493. integratedTime += timelineDuration;
  29494. const playoutStart = playoutDuration;
  29495. playoutDuration += interstitialDuration;
  29496. schedule.push({
  29497. event: interstitial,
  29498. start,
  29499. end,
  29500. playout: {
  29501. start: playoutStart,
  29502. end: playoutDuration
  29503. },
  29504. integrated: {
  29505. start: integratedStart,
  29506. end: integratedTime
  29507. }
  29508. });
  29509. } else {
  29510. return;
  29511. }
  29512. const resumeTime = interstitial.resumeTime;
  29513. if (postroll || resumeTime > primaryDuration) {
  29514. primaryPosition = primaryDuration;
  29515. } else {
  29516. primaryPosition = resumeTime;
  29517. }
  29518. });
  29519. if (primaryPosition < primaryDuration) {
  29520. var _schedule;
  29521. const timelineStart = primaryPosition;
  29522. const integratedStart = integratedTime;
  29523. const segmentDuration = primaryDuration - primaryPosition;
  29524. integratedTime += segmentDuration;
  29525. const playoutStart = playoutDuration;
  29526. playoutDuration += segmentDuration;
  29527. schedule.push({
  29528. previousEvent: ((_schedule = schedule[schedule.length - 1]) == null ? void 0 : _schedule.event) || null,
  29529. nextEvent: null,
  29530. start: primaryPosition,
  29531. end: timelineStart + segmentDuration,
  29532. playout: {
  29533. start: playoutStart,
  29534. end: playoutDuration
  29535. },
  29536. integrated: {
  29537. start: integratedStart,
  29538. end: integratedTime
  29539. }
  29540. });
  29541. }
  29542. this.setDurations(primaryDuration, playoutDuration, integratedTime);
  29543. } else {
  29544. const start = 0;
  29545. schedule.push({
  29546. previousEvent: null,
  29547. nextEvent: null,
  29548. start,
  29549. end: primaryDuration,
  29550. playout: {
  29551. start,
  29552. end: primaryDuration
  29553. },
  29554. integrated: {
  29555. start,
  29556. end: primaryDuration
  29557. }
  29558. });
  29559. this.setDurations(primaryDuration, primaryDuration, primaryDuration);
  29560. }
  29561. return schedule;
  29562. }
  29563. setDurations(primary, playout, integrated) {
  29564. this.durations = {
  29565. primary,
  29566. playout,
  29567. integrated
  29568. };
  29569. }
  29570. resolveOffsets(interstitialEvents, mediaSelection) {
  29571. const details = mediaSelection.main.details;
  29572. const primaryDuration = details.live ? Infinity : details.edge;
  29573. let cumulativeDuration = 0;
  29574. let lastScheduledStart = -1;
  29575. interstitialEvents.forEach((interstitial, i2) => {
  29576. const preroll = interstitial.cue.pre;
  29577. const postroll = interstitial.cue.post;
  29578. const eventStart = preroll ? 0 : postroll ? primaryDuration : interstitial.startTime;
  29579. this.updateAssetDurations(interstitial);
  29580. const inSameStartTimeSequence = lastScheduledStart === eventStart;
  29581. if (inSameStartTimeSequence) {
  29582. interstitial.cumulativeDuration = cumulativeDuration;
  29583. } else {
  29584. cumulativeDuration = 0;
  29585. lastScheduledStart = eventStart;
  29586. }
  29587. if (!postroll && interstitial.snapOptions.in) {
  29588. interstitial.resumeAnchor = findFragmentByPTS(null, details.fragments, interstitial.startOffset + interstitial.resumptionOffset, 0, 0) || void 0;
  29589. }
  29590. if (interstitial.appendInPlace && !interstitial.appendInPlaceStarted) {
  29591. const alignedSegmentStart = this.primaryCanResumeInPlaceAt(interstitial, mediaSelection);
  29592. if (!alignedSegmentStart) {
  29593. interstitial.appendInPlace = false;
  29594. }
  29595. }
  29596. if (!interstitial.appendInPlace && i2 + 1 < interstitialEvents.length) {
  29597. const timeBetween = interstitialEvents[i2 + 1].startTime - interstitialEvents[i2].resumeTime;
  29598. if (timeBetween < ABUTTING_THRESHOLD_SECONDS) {
  29599. interstitialEvents[i2 + 1].appendInPlace = false;
  29600. if (interstitialEvents[i2 + 1].appendInPlace) {
  29601. this.warn(`Could not change append strategy for abutting event ${interstitial}`);
  29602. }
  29603. }
  29604. }
  29605. const resumeOffset = isFiniteNumber(interstitial.resumeOffset) ? interstitial.resumeOffset : interstitial.duration;
  29606. cumulativeDuration += resumeOffset;
  29607. });
  29608. }
  29609. primaryCanResumeInPlaceAt(interstitial, mediaSelection) {
  29610. const resumeTime = interstitial.resumeTime;
  29611. const resumesInPlaceAt = interstitial.startTime + interstitial.resumptionOffset;
  29612. if (Math.abs(resumeTime - resumesInPlaceAt) > ALIGNED_END_THRESHOLD_SECONDS) {
  29613. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with estimated timeline end ${resumesInPlaceAt}`);
  29614. return false;
  29615. }
  29616. if (!mediaSelection) {
  29617. this.log(`"${interstitial.identifier}" resumption ${resumeTime} can not be aligned with media (none selected)`);
  29618. return false;
  29619. }
  29620. const playlists = Object.keys(mediaSelection);
  29621. return !playlists.some((playlistType) => {
  29622. const details = mediaSelection[playlistType].details;
  29623. const playlistEnd = details.edge;
  29624. if (resumeTime >= playlistEnd) {
  29625. this.log(`"${interstitial.identifier}" resumption ${resumeTime} past ${playlistType} playlist end ${playlistEnd}`);
  29626. return false;
  29627. }
  29628. const startFragment = findFragmentByPTS(null, details.fragments, resumeTime);
  29629. if (!startFragment) {
  29630. this.log(`"${interstitial.identifier}" resumption ${resumeTime} does not align with any fragments in ${playlistType} playlist (${details.fragStart}-${details.fragmentEnd})`);
  29631. return true;
  29632. }
  29633. const allowance = playlistType === "audio" ? 0.175 : 0;
  29634. const alignedWithSegment = Math.abs(startFragment.start - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance || Math.abs(startFragment.end - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance;
  29635. if (!alignedWithSegment) {
  29636. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with ${playlistType} fragment bounds (${startFragment.start}-${startFragment.end} sn: ${startFragment.sn} cc: ${startFragment.cc})`);
  29637. return true;
  29638. }
  29639. return false;
  29640. });
  29641. }
  29642. updateAssetDurations(interstitial) {
  29643. if (!interstitial.assetListLoaded) {
  29644. return;
  29645. }
  29646. const eventStart = interstitial.timelineStart;
  29647. let sumDuration = 0;
  29648. let hasUnknownDuration = false;
  29649. let hasErrors = false;
  29650. interstitial.assetList.forEach((asset, i2) => {
  29651. const timelineStart = eventStart + sumDuration;
  29652. asset.startOffset = sumDuration;
  29653. asset.timelineStart = timelineStart;
  29654. hasUnknownDuration || (hasUnknownDuration = asset.duration === null);
  29655. hasErrors || (hasErrors = !!asset.error);
  29656. const duration = asset.error ? 0 : asset.duration || 0;
  29657. sumDuration += duration;
  29658. });
  29659. if (hasUnknownDuration && !hasErrors) {
  29660. interstitial.duration = Math.max(sumDuration, interstitial.duration);
  29661. } else {
  29662. interstitial.duration = sumDuration;
  29663. }
  29664. }
  29665. removeEvent(interstitial) {
  29666. interstitial.reset();
  29667. delete this.eventMap[interstitial.identifier];
  29668. }
  29669. }
  29670. function segmentToString(segment) {
  29671. return `[${segment.event ? '"' + segment.event.identifier + '"' : "primary"}: ${segment.start.toFixed(2)}-${segment.end.toFixed(2)}]`;
  29672. }
  29673. class AssetListLoader {
  29674. constructor(hls) {
  29675. this.hls = void 0;
  29676. this.hls = hls;
  29677. }
  29678. destroy() {
  29679. this.hls = null;
  29680. }
  29681. loadAssetList(interstitial, hlsStartOffset) {
  29682. const assetListUrl = interstitial.assetListUrl;
  29683. let url;
  29684. try {
  29685. url = getInterstitialUrl(assetListUrl, this.hls.sessionId, interstitial.baseUrl);
  29686. } catch (error) {
  29687. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, error, assetListUrl);
  29688. this.hls.trigger(Events.ERROR, errorData);
  29689. return;
  29690. }
  29691. if (hlsStartOffset && url.protocol !== "data:") {
  29692. url.searchParams.set("_HLS_start_offset", "" + hlsStartOffset);
  29693. }
  29694. const config = this.hls.config;
  29695. const Loader = config.loader;
  29696. const loader = new Loader(config);
  29697. const context = {
  29698. responseType: "json",
  29699. url: url.href
  29700. };
  29701. const loadPolicy = config.interstitialAssetListLoadPolicy.default;
  29702. const loaderConfig = {
  29703. loadPolicy,
  29704. timeout: loadPolicy.maxLoadTimeMs,
  29705. maxRetry: 0,
  29706. retryDelay: 0,
  29707. maxRetryDelay: 0
  29708. };
  29709. const callbacks = {
  29710. onSuccess: (response, stats, context2, networkDetails) => {
  29711. const assetListResponse = response.data;
  29712. const assets = assetListResponse == null ? void 0 : assetListResponse.ASSETS;
  29713. if (!Array.isArray(assets)) {
  29714. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_PARSING_ERROR, new Error(`Invalid interstitial asset list`), context2.url, stats, networkDetails);
  29715. this.hls.trigger(Events.ERROR, errorData);
  29716. return;
  29717. }
  29718. interstitial.assetListResponse = assetListResponse;
  29719. this.hls.trigger(Events.ASSET_LIST_LOADED, {
  29720. event: interstitial,
  29721. assetListResponse,
  29722. networkDetails
  29723. });
  29724. },
  29725. onError: (error, context2, networkDetails, stats) => {
  29726. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, new Error(`Error loading X-ASSET-LIST: HTTP status ${error.code} ${error.text} (${context2.url})`), context2.url, stats, networkDetails);
  29727. this.hls.trigger(Events.ERROR, errorData);
  29728. },
  29729. onTimeout: (stats, context2, networkDetails) => {
  29730. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_TIMEOUT, new Error(`Timeout loading X-ASSET-LIST (${context2.url})`), context2.url, stats, networkDetails);
  29731. this.hls.trigger(Events.ERROR, errorData);
  29732. }
  29733. };
  29734. loader.load(context, loaderConfig, callbacks);
  29735. this.hls.trigger(Events.ASSET_LIST_LOADING, {
  29736. event: interstitial
  29737. });
  29738. return loader;
  29739. }
  29740. assignAssetListError(interstitial, details, error, url, stats, networkDetails) {
  29741. interstitial.error = error;
  29742. return {
  29743. type: ErrorTypes.NETWORK_ERROR,
  29744. details,
  29745. fatal: false,
  29746. interstitial,
  29747. url,
  29748. error,
  29749. networkDetails,
  29750. stats
  29751. };
  29752. }
  29753. }
  29754. function playWithCatch(media) {
  29755. media == null ? void 0 : media.play().catch(() => {
  29756. });
  29757. }
  29758. class InterstitialsController extends Logger {
  29759. constructor(hls, HlsPlayerClass) {
  29760. super("interstitials", hls.logger);
  29761. this.HlsPlayerClass = void 0;
  29762. this.hls = void 0;
  29763. this.assetListLoader = void 0;
  29764. this.mediaSelection = null;
  29765. this.altSelection = null;
  29766. this.media = null;
  29767. this.detachedData = null;
  29768. this.requiredTracks = null;
  29769. this.manager = null;
  29770. this.playerQueue = [];
  29771. this.bufferedPos = -1;
  29772. this.timelinePos = -1;
  29773. this.schedule = void 0;
  29774. this.playingItem = null;
  29775. this.bufferingItem = null;
  29776. this.waitingItem = null;
  29777. this.endedItem = null;
  29778. this.playingAsset = null;
  29779. this.endedAsset = null;
  29780. this.bufferingAsset = null;
  29781. this.shouldPlay = false;
  29782. this.onPlay = () => {
  29783. this.shouldPlay = true;
  29784. };
  29785. this.onPause = () => {
  29786. this.shouldPlay = false;
  29787. };
  29788. this.onSeeking = () => {
  29789. const currentTime = this.currentTime;
  29790. if (currentTime === void 0 || this.playbackDisabled) {
  29791. return;
  29792. }
  29793. const diff2 = currentTime - this.timelinePos;
  29794. const roundingError = Math.abs(diff2) < 1 / 7056e5;
  29795. if (roundingError) {
  29796. return;
  29797. }
  29798. const backwardSeek = diff2 <= -0.01;
  29799. this.timelinePos = currentTime;
  29800. this.bufferedPos = currentTime;
  29801. const playingItem = this.playingItem;
  29802. if (!playingItem) {
  29803. this.checkBuffer();
  29804. return;
  29805. }
  29806. if (backwardSeek) {
  29807. const resetCount = this.schedule.resetErrorsInRange(currentTime, currentTime - diff2);
  29808. if (resetCount) {
  29809. this.updateSchedule();
  29810. }
  29811. }
  29812. this.checkBuffer();
  29813. if (backwardSeek && currentTime < playingItem.start || currentTime >= playingItem.end) {
  29814. var _this$media;
  29815. const scheduleIndex = this.schedule.findItemIndexAtTime(this.timelinePos);
  29816. if (!this.isInterstitial(playingItem) && (_this$media = this.media) != null && _this$media.paused) {
  29817. this.shouldPlay = false;
  29818. }
  29819. if (!backwardSeek) {
  29820. const playingIndex = this.findItemIndex(playingItem);
  29821. if (scheduleIndex > playingIndex) {
  29822. const jumpIndex = this.schedule.findJumpRestrictedIndex(playingIndex + 1, scheduleIndex);
  29823. if (jumpIndex > playingIndex) {
  29824. this.setSchedulePosition(jumpIndex);
  29825. return;
  29826. }
  29827. }
  29828. }
  29829. this.setSchedulePosition(scheduleIndex);
  29830. return;
  29831. }
  29832. const playingAsset = this.playingAsset;
  29833. if (!playingAsset) {
  29834. if (this.playingLastItem && this.isInterstitial(playingItem)) {
  29835. const restartAsset = playingItem.event.assetList[0];
  29836. if (restartAsset) {
  29837. this.endedItem = this.playingItem;
  29838. this.playingItem = null;
  29839. this.setScheduleToAssetAtTime(currentTime, restartAsset);
  29840. }
  29841. }
  29842. return;
  29843. }
  29844. const start = playingAsset.timelineStart;
  29845. const duration = playingAsset.duration || 0;
  29846. if (backwardSeek && currentTime < start || currentTime >= start + duration) {
  29847. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  29848. }
  29849. };
  29850. this.onTimeupdate = () => {
  29851. const currentTime = this.currentTime;
  29852. if (currentTime === void 0 || this.playbackDisabled) {
  29853. return;
  29854. }
  29855. if (currentTime > this.timelinePos) {
  29856. this.timelinePos = currentTime;
  29857. if (currentTime > this.bufferedPos) {
  29858. this.checkBuffer();
  29859. }
  29860. } else {
  29861. return;
  29862. }
  29863. const playingItem = this.playingItem;
  29864. if (!playingItem || this.playingLastItem) {
  29865. return;
  29866. }
  29867. if (currentTime >= playingItem.end) {
  29868. this.timelinePos = playingItem.end;
  29869. const playingIndex = this.findItemIndex(playingItem);
  29870. this.setSchedulePosition(playingIndex + 1);
  29871. }
  29872. const playingAsset = this.playingAsset;
  29873. if (!playingAsset) {
  29874. return;
  29875. }
  29876. const end = playingAsset.timelineStart + (playingAsset.duration || 0);
  29877. if (currentTime >= end) {
  29878. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  29879. }
  29880. };
  29881. this.onScheduleUpdate = (removedInterstitials, previousItems) => {
  29882. const schedule = this.schedule;
  29883. const playingItem = this.playingItem;
  29884. const interstitialEvents = schedule.events || [];
  29885. const scheduleItems = schedule.items || [];
  29886. const durations = schedule.durations;
  29887. const removedIds = removedInterstitials.map((interstitial) => interstitial.identifier);
  29888. const interstitialsUpdated = !!(interstitialEvents.length || removedIds.length);
  29889. if (interstitialsUpdated || previousItems) {
  29890. this.log(`INTERSTITIALS_UPDATED (${interstitialEvents.length}): ${interstitialEvents}
  29891. Schedule: ${scheduleItems.map((seg) => segmentToString(seg))} pos: ${this.timelinePos}`);
  29892. }
  29893. if (removedIds.length) {
  29894. this.log(`Removed events ${removedIds}`);
  29895. }
  29896. this.playerQueue.forEach((player) => {
  29897. if (player.interstitial.appendInPlace) {
  29898. const timelineStart = player.assetItem.timelineStart;
  29899. const diff2 = player.timelineOffset - timelineStart;
  29900. if (diff2) {
  29901. try {
  29902. player.timelineOffset = timelineStart;
  29903. } catch (e2) {
  29904. if (Math.abs(diff2) > ALIGNED_END_THRESHOLD_SECONDS) {
  29905. this.warn(`${e2} ("${player.assetId}" ${player.timelineOffset}->${timelineStart})`);
  29906. }
  29907. }
  29908. }
  29909. }
  29910. });
  29911. let trimInPlaceForPlayout = null;
  29912. if (playingItem) {
  29913. const updatedPlayingItem = this.updateItem(playingItem, this.timelinePos);
  29914. if (this.itemsMatch(playingItem, updatedPlayingItem)) {
  29915. this.playingItem = updatedPlayingItem;
  29916. this.waitingItem = this.endedItem = null;
  29917. trimInPlaceForPlayout = () => this.trimInPlace(updatedPlayingItem, playingItem);
  29918. }
  29919. } else {
  29920. this.waitingItem = this.updateItem(this.waitingItem);
  29921. this.endedItem = this.updateItem(this.endedItem);
  29922. }
  29923. const bufferingItem = this.bufferingItem;
  29924. if (bufferingItem) {
  29925. const updatedBufferingItem = this.updateItem(bufferingItem, this.bufferedPos);
  29926. if (this.itemsMatch(bufferingItem, updatedBufferingItem)) {
  29927. this.bufferingItem = updatedBufferingItem;
  29928. trimInPlaceForPlayout || (trimInPlaceForPlayout = () => this.trimInPlace(updatedBufferingItem, bufferingItem));
  29929. } else if (bufferingItem.event) {
  29930. this.bufferingItem = this.playingItem;
  29931. this.clearInterstitial(bufferingItem.event, null);
  29932. }
  29933. }
  29934. removedInterstitials.forEach((interstitial) => {
  29935. interstitial.assetList.forEach((asset) => {
  29936. this.clearAssetPlayer(asset.identifier, null);
  29937. });
  29938. });
  29939. if (interstitialsUpdated || previousItems) {
  29940. this.hls.trigger(Events.INTERSTITIALS_UPDATED, {
  29941. events: interstitialEvents.slice(0),
  29942. schedule: scheduleItems.slice(0),
  29943. durations,
  29944. removedIds
  29945. });
  29946. if (this.isInterstitial(playingItem) && removedIds.includes(playingItem.event.identifier)) {
  29947. this.warn(`Interstitial "${playingItem.event.identifier}" removed while playing`);
  29948. this.primaryFallback(playingItem.event);
  29949. return;
  29950. }
  29951. if (trimInPlaceForPlayout) {
  29952. trimInPlaceForPlayout();
  29953. }
  29954. this.checkBuffer();
  29955. }
  29956. };
  29957. this.hls = hls;
  29958. this.HlsPlayerClass = HlsPlayerClass;
  29959. this.assetListLoader = new AssetListLoader(hls);
  29960. this.schedule = new InterstitialsSchedule(this.onScheduleUpdate, hls.logger);
  29961. this.registerListeners();
  29962. }
  29963. registerListeners() {
  29964. const hls = this.hls;
  29965. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  29966. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  29967. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  29968. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  29969. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  29970. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  29971. hls.on(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  29972. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  29973. hls.on(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  29974. hls.on(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  29975. hls.on(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  29976. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  29977. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  29978. hls.on(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  29979. hls.on(Events.MEDIA_ENDED, this.onMediaEnded, this);
  29980. hls.on(Events.ERROR, this.onError, this);
  29981. hls.on(Events.DESTROYING, this.onDestroying, this);
  29982. }
  29983. unregisterListeners() {
  29984. const hls = this.hls;
  29985. if (!hls) {
  29986. return;
  29987. }
  29988. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  29989. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  29990. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  29991. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  29992. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  29993. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  29994. hls.off(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  29995. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  29996. hls.off(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  29997. hls.off(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  29998. hls.off(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  29999. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  30000. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  30001. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  30002. hls.off(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  30003. hls.off(Events.MEDIA_ENDED, this.onMediaEnded, this);
  30004. hls.off(Events.ERROR, this.onError, this);
  30005. hls.off(Events.DESTROYING, this.onDestroying, this);
  30006. }
  30007. startLoad() {
  30008. this.resumeBuffering();
  30009. }
  30010. stopLoad() {
  30011. this.pauseBuffering();
  30012. }
  30013. resumeBuffering() {
  30014. var _this$getBufferingPla;
  30015. (_this$getBufferingPla = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla.resumeBuffering();
  30016. }
  30017. pauseBuffering() {
  30018. var _this$getBufferingPla2;
  30019. (_this$getBufferingPla2 = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla2.pauseBuffering();
  30020. }
  30021. destroy() {
  30022. this.unregisterListeners();
  30023. this.stopLoad();
  30024. if (this.assetListLoader) {
  30025. this.assetListLoader.destroy();
  30026. }
  30027. this.emptyPlayerQueue();
  30028. this.clearScheduleState();
  30029. if (this.schedule) {
  30030. this.schedule.destroy();
  30031. }
  30032. this.media = this.detachedData = this.mediaSelection = this.requiredTracks = this.altSelection = this.manager = null;
  30033. this.hls = this.HlsPlayerClass = this.schedule = this.log = null;
  30034. this.assetListLoader = null;
  30035. this.onPlay = this.onPause = this.onSeeking = this.onTimeupdate = null;
  30036. this.onScheduleUpdate = null;
  30037. }
  30038. onDestroying() {
  30039. const media = this.primaryMedia || this.media;
  30040. if (media) {
  30041. this.removeMediaListeners(media);
  30042. }
  30043. }
  30044. removeMediaListeners(media) {
  30045. removeEventListener(media, "play", this.onPlay);
  30046. removeEventListener(media, "pause", this.onPause);
  30047. removeEventListener(media, "seeking", this.onSeeking);
  30048. removeEventListener(media, "timeupdate", this.onTimeupdate);
  30049. }
  30050. onMediaAttaching(event, data) {
  30051. const media = this.media = data.media;
  30052. addEventListener(media, "seeking", this.onSeeking);
  30053. addEventListener(media, "timeupdate", this.onTimeupdate);
  30054. addEventListener(media, "play", this.onPlay);
  30055. addEventListener(media, "pause", this.onPause);
  30056. }
  30057. onMediaAttached(event, data) {
  30058. const playingItem = this.effectivePlayingItem;
  30059. const detachedMedia = this.detachedData;
  30060. this.detachedData = null;
  30061. if (playingItem === null) {
  30062. this.checkStart();
  30063. } else if (!detachedMedia) {
  30064. this.clearScheduleState();
  30065. const playingIndex = this.findItemIndex(playingItem);
  30066. this.setSchedulePosition(playingIndex);
  30067. }
  30068. }
  30069. clearScheduleState() {
  30070. this.playingItem = this.bufferingItem = this.waitingItem = this.endedItem = this.playingAsset = this.endedAsset = this.bufferingAsset = null;
  30071. }
  30072. onMediaDetaching(event, data) {
  30073. const transferringMedia = !!data.transferMedia;
  30074. const media = this.media;
  30075. this.media = null;
  30076. if (transferringMedia) {
  30077. return;
  30078. }
  30079. if (media) {
  30080. this.removeMediaListeners(media);
  30081. }
  30082. if (this.detachedData) {
  30083. const player = this.getBufferingPlayer();
  30084. if (player) {
  30085. this.playingAsset = this.endedAsset = this.bufferingAsset = this.bufferingItem = this.waitingItem = this.detachedData = null;
  30086. player.detachMedia();
  30087. }
  30088. this.shouldPlay = false;
  30089. }
  30090. }
  30091. get interstitialsManager() {
  30092. if (!this.manager) {
  30093. if (!this.hls) {
  30094. return null;
  30095. }
  30096. const c2 = this;
  30097. const effectiveBufferingItem = () => c2.bufferingItem || c2.waitingItem;
  30098. const getAssetPlayer = (asset) => asset ? c2.getAssetPlayer(asset.identifier) : asset;
  30099. const getMappedTime = (item, timelineType, asset, controllerField, assetPlayerField) => {
  30100. if (item) {
  30101. let time = item[timelineType].start;
  30102. const interstitial = item.event;
  30103. if (interstitial) {
  30104. if (timelineType === "playout" || interstitial.timelineOccupancy !== TimelineOccupancy.Point) {
  30105. const assetPlayer = getAssetPlayer(asset);
  30106. if ((assetPlayer == null ? void 0 : assetPlayer.interstitial) === interstitial) {
  30107. time += assetPlayer.assetItem.startOffset + assetPlayer[assetPlayerField];
  30108. }
  30109. }
  30110. } else {
  30111. const value = controllerField === "bufferedPos" ? getBufferedEnd() : c2[controllerField];
  30112. time += value - item.start;
  30113. }
  30114. return time;
  30115. }
  30116. return 0;
  30117. };
  30118. const findMappedTime = (primaryTime, timelineType) => {
  30119. if (primaryTime !== 0 && timelineType !== "primary" && c2.schedule.length) {
  30120. var _c$schedule$items;
  30121. const index2 = c2.schedule.findItemIndexAtTime(primaryTime);
  30122. const item = (_c$schedule$items = c2.schedule.items) == null ? void 0 : _c$schedule$items[index2];
  30123. if (item) {
  30124. const diff2 = item[timelineType].start - item.start;
  30125. return primaryTime + diff2;
  30126. }
  30127. }
  30128. return primaryTime;
  30129. };
  30130. const getBufferedEnd = () => {
  30131. const value = c2.bufferedPos;
  30132. if (value === Number.MAX_VALUE) {
  30133. return getMappedDuration("primary");
  30134. }
  30135. return Math.max(value, 0);
  30136. };
  30137. const getMappedDuration = (timelineType) => {
  30138. var _c$primaryDetails;
  30139. if ((_c$primaryDetails = c2.primaryDetails) != null && _c$primaryDetails.live) {
  30140. return c2.primaryDetails.edge;
  30141. }
  30142. return c2.schedule.durations[timelineType];
  30143. };
  30144. const seekTo = (time, timelineType) => {
  30145. var _item$event, _c$schedule$items2;
  30146. const item = c2.effectivePlayingItem;
  30147. if (item != null && (_item$event = item.event) != null && _item$event.restrictions.skip) {
  30148. return;
  30149. }
  30150. c2.log(`seek to ${time} "${timelineType}"`);
  30151. const playingItem = c2.effectivePlayingItem;
  30152. const targetIndex = c2.schedule.findItemIndexAtTime(time, timelineType);
  30153. const targetItem = (_c$schedule$items2 = c2.schedule.items) == null ? void 0 : _c$schedule$items2[targetIndex];
  30154. const bufferingPlayer = c2.getBufferingPlayer();
  30155. const bufferingInterstitial = bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial;
  30156. const appendInPlace = bufferingInterstitial == null ? void 0 : bufferingInterstitial.appendInPlace;
  30157. const seekInItem = playingItem && c2.itemsMatch(playingItem, targetItem);
  30158. if (playingItem && (appendInPlace || seekInItem)) {
  30159. const assetPlayer = getAssetPlayer(c2.playingAsset);
  30160. const media = (assetPlayer == null ? void 0 : assetPlayer.media) || c2.primaryMedia;
  30161. if (media) {
  30162. const currentTime = timelineType === "primary" ? media.currentTime : getMappedTime(playingItem, timelineType, c2.playingAsset, "timelinePos", "currentTime");
  30163. const diff2 = time - currentTime;
  30164. const seekToTime = (appendInPlace ? currentTime : media.currentTime) + diff2;
  30165. if (seekToTime >= 0 && (!assetPlayer || appendInPlace || seekToTime <= assetPlayer.duration)) {
  30166. media.currentTime = seekToTime;
  30167. return;
  30168. }
  30169. }
  30170. }
  30171. if (targetItem) {
  30172. let seekToTime = time;
  30173. if (timelineType !== "primary") {
  30174. const primarySegmentStart = targetItem[timelineType].start;
  30175. const diff2 = time - primarySegmentStart;
  30176. seekToTime = targetItem.start + diff2;
  30177. }
  30178. const targetIsPrimary = !c2.isInterstitial(targetItem);
  30179. if ((!c2.isInterstitial(playingItem) || playingItem.event.appendInPlace) && (targetIsPrimary || targetItem.event.appendInPlace)) {
  30180. const media = c2.media || (appendInPlace ? bufferingPlayer == null ? void 0 : bufferingPlayer.media : null);
  30181. if (media) {
  30182. media.currentTime = seekToTime;
  30183. }
  30184. } else if (playingItem) {
  30185. const playingIndex = c2.findItemIndex(playingItem);
  30186. if (targetIndex > playingIndex) {
  30187. const jumpIndex = c2.schedule.findJumpRestrictedIndex(playingIndex + 1, targetIndex);
  30188. if (jumpIndex > playingIndex) {
  30189. c2.setSchedulePosition(jumpIndex);
  30190. return;
  30191. }
  30192. }
  30193. let assetIndex = 0;
  30194. if (targetIsPrimary) {
  30195. c2.timelinePos = seekToTime;
  30196. c2.checkBuffer();
  30197. } else {
  30198. var _targetItem$event;
  30199. const assetList = targetItem == null ? void 0 : (_targetItem$event = targetItem.event) == null ? void 0 : _targetItem$event.assetList;
  30200. if (assetList) {
  30201. const eventTime = time - (targetItem[timelineType] || targetItem).start;
  30202. for (let i2 = assetList.length; i2--; ) {
  30203. const asset = assetList[i2];
  30204. if (asset.duration && eventTime >= asset.startOffset && eventTime < asset.startOffset + asset.duration) {
  30205. assetIndex = i2;
  30206. break;
  30207. }
  30208. }
  30209. }
  30210. }
  30211. c2.setSchedulePosition(targetIndex, assetIndex);
  30212. }
  30213. }
  30214. };
  30215. const getActiveInterstitial = () => {
  30216. const playingItem = c2.effectivePlayingItem;
  30217. if (c2.isInterstitial(playingItem)) {
  30218. return playingItem;
  30219. }
  30220. const bufferingItem = effectiveBufferingItem();
  30221. if (c2.isInterstitial(bufferingItem)) {
  30222. return bufferingItem;
  30223. }
  30224. return null;
  30225. };
  30226. const interstitialPlayer = {
  30227. get currentTime() {
  30228. const interstitialItem = getActiveInterstitial();
  30229. const playingItem = c2.effectivePlayingItem;
  30230. if (playingItem && playingItem === interstitialItem) {
  30231. return getMappedTime(playingItem, "playout", c2.effectivePlayingAsset, "timelinePos", "currentTime") - playingItem.playout.start;
  30232. }
  30233. return 0;
  30234. },
  30235. set currentTime(time) {
  30236. const interstitialItem = getActiveInterstitial();
  30237. const playingItem = c2.effectivePlayingItem;
  30238. if (playingItem && playingItem === interstitialItem) {
  30239. seekTo(time + playingItem.playout.start, "playout");
  30240. }
  30241. },
  30242. get duration() {
  30243. const interstitialItem = getActiveInterstitial();
  30244. if (interstitialItem) {
  30245. return interstitialItem.playout.end - interstitialItem.playout.start;
  30246. }
  30247. return 0;
  30248. },
  30249. get assetPlayers() {
  30250. var _getActiveInterstitia;
  30251. const assetList = (_getActiveInterstitia = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia.event.assetList;
  30252. if (assetList) {
  30253. return assetList.map((asset) => c2.getAssetPlayer(asset.identifier));
  30254. }
  30255. return [];
  30256. },
  30257. get playingIndex() {
  30258. var _getActiveInterstitia2;
  30259. const interstitial = (_getActiveInterstitia2 = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia2.event;
  30260. if (interstitial && c2.effectivePlayingAsset) {
  30261. return interstitial.findAssetIndex(c2.effectivePlayingAsset);
  30262. }
  30263. return -1;
  30264. },
  30265. get scheduleItem() {
  30266. return getActiveInterstitial();
  30267. }
  30268. };
  30269. this.manager = {
  30270. get events() {
  30271. var _c$schedule, _c$schedule$events;
  30272. return ((_c$schedule = c2.schedule) == null ? void 0 : (_c$schedule$events = _c$schedule.events) == null ? void 0 : _c$schedule$events.slice(0)) || [];
  30273. },
  30274. get schedule() {
  30275. var _c$schedule2, _c$schedule2$items;
  30276. return ((_c$schedule2 = c2.schedule) == null ? void 0 : (_c$schedule2$items = _c$schedule2.items) == null ? void 0 : _c$schedule2$items.slice(0)) || [];
  30277. },
  30278. get interstitialPlayer() {
  30279. if (getActiveInterstitial()) {
  30280. return interstitialPlayer;
  30281. }
  30282. return null;
  30283. },
  30284. get playerQueue() {
  30285. return c2.playerQueue.slice(0);
  30286. },
  30287. get bufferingAsset() {
  30288. return c2.bufferingAsset;
  30289. },
  30290. get bufferingItem() {
  30291. return effectiveBufferingItem();
  30292. },
  30293. get bufferingIndex() {
  30294. const item = effectiveBufferingItem();
  30295. return c2.findItemIndex(item);
  30296. },
  30297. get playingAsset() {
  30298. return c2.effectivePlayingAsset;
  30299. },
  30300. get playingItem() {
  30301. return c2.effectivePlayingItem;
  30302. },
  30303. get playingIndex() {
  30304. const item = c2.effectivePlayingItem;
  30305. return c2.findItemIndex(item);
  30306. },
  30307. primary: {
  30308. get bufferedEnd() {
  30309. return getBufferedEnd();
  30310. },
  30311. get currentTime() {
  30312. const timelinePos = c2.timelinePos;
  30313. return timelinePos > 0 ? timelinePos : 0;
  30314. },
  30315. set currentTime(time) {
  30316. seekTo(time, "primary");
  30317. },
  30318. get duration() {
  30319. return getMappedDuration("primary");
  30320. },
  30321. get seekableStart() {
  30322. var _c$primaryDetails2;
  30323. return ((_c$primaryDetails2 = c2.primaryDetails) == null ? void 0 : _c$primaryDetails2.fragmentStart) || 0;
  30324. }
  30325. },
  30326. integrated: {
  30327. get bufferedEnd() {
  30328. return getMappedTime(effectiveBufferingItem(), "integrated", c2.bufferingAsset, "bufferedPos", "bufferedEnd");
  30329. },
  30330. get currentTime() {
  30331. return getMappedTime(c2.effectivePlayingItem, "integrated", c2.effectivePlayingAsset, "timelinePos", "currentTime");
  30332. },
  30333. set currentTime(time) {
  30334. seekTo(time, "integrated");
  30335. },
  30336. get duration() {
  30337. return getMappedDuration("integrated");
  30338. },
  30339. get seekableStart() {
  30340. var _c$primaryDetails3;
  30341. return findMappedTime(((_c$primaryDetails3 = c2.primaryDetails) == null ? void 0 : _c$primaryDetails3.fragmentStart) || 0, "integrated");
  30342. }
  30343. },
  30344. skip: () => {
  30345. const item = c2.effectivePlayingItem;
  30346. const event = item == null ? void 0 : item.event;
  30347. if (event && !event.restrictions.skip) {
  30348. const index2 = c2.findItemIndex(item);
  30349. if (event.appendInPlace) {
  30350. const time = item.playout.start + item.event.duration;
  30351. seekTo(time + 1e-3, "playout");
  30352. } else {
  30353. c2.advanceAfterAssetEnded(event, index2, Infinity);
  30354. }
  30355. }
  30356. }
  30357. };
  30358. }
  30359. return this.manager;
  30360. }
  30361. // Schedule getters
  30362. get effectivePlayingItem() {
  30363. return this.waitingItem || this.playingItem || this.endedItem;
  30364. }
  30365. get effectivePlayingAsset() {
  30366. return this.playingAsset || this.endedAsset;
  30367. }
  30368. get playingLastItem() {
  30369. var _this$schedule;
  30370. const playingItem = this.playingItem;
  30371. const items = (_this$schedule = this.schedule) == null ? void 0 : _this$schedule.items;
  30372. if (!this.playbackStarted || !playingItem || !items) {
  30373. return false;
  30374. }
  30375. return this.findItemIndex(playingItem) === items.length - 1;
  30376. }
  30377. get playbackStarted() {
  30378. return this.effectivePlayingItem !== null;
  30379. }
  30380. // Media getters and event callbacks
  30381. get currentTime() {
  30382. var _this$bufferingItem, _this$bufferingItem$e, _media;
  30383. if (this.mediaSelection === null) {
  30384. return void 0;
  30385. }
  30386. const queuedForPlayback = this.waitingItem || this.playingItem;
  30387. if (this.isInterstitial(queuedForPlayback) && !queuedForPlayback.event.appendInPlace) {
  30388. return void 0;
  30389. }
  30390. let media = this.media;
  30391. if (!media && (_this$bufferingItem = this.bufferingItem) != null && (_this$bufferingItem$e = _this$bufferingItem.event) != null && _this$bufferingItem$e.appendInPlace) {
  30392. media = this.primaryMedia;
  30393. }
  30394. const currentTime = (_media = media) == null ? void 0 : _media.currentTime;
  30395. if (currentTime === void 0 || !isFiniteNumber(currentTime)) {
  30396. return void 0;
  30397. }
  30398. return currentTime;
  30399. }
  30400. get primaryMedia() {
  30401. var _this$detachedData;
  30402. return this.media || ((_this$detachedData = this.detachedData) == null ? void 0 : _this$detachedData.media) || null;
  30403. }
  30404. isInterstitial(item) {
  30405. return !!(item != null && item.event);
  30406. }
  30407. retreiveMediaSource(assetId, toSegment) {
  30408. const player = this.getAssetPlayer(assetId);
  30409. if (player) {
  30410. this.transferMediaFromPlayer(player, toSegment);
  30411. }
  30412. }
  30413. transferMediaFromPlayer(player, toSegment) {
  30414. const appendInPlace = player.interstitial.appendInPlace;
  30415. const playerMedia = player.media;
  30416. if (appendInPlace && playerMedia === this.primaryMedia) {
  30417. this.bufferingAsset = null;
  30418. if (!toSegment || this.isInterstitial(toSegment) && !toSegment.event.appendInPlace) {
  30419. if (toSegment && playerMedia) {
  30420. this.detachedData = {
  30421. media: playerMedia
  30422. };
  30423. return;
  30424. }
  30425. }
  30426. const attachMediaSourceData = player.transferMedia();
  30427. this.log(`transfer MediaSource from ${player} ${stringify(attachMediaSourceData)}`);
  30428. this.detachedData = attachMediaSourceData;
  30429. } else if (toSegment && playerMedia) {
  30430. this.shouldPlay || (this.shouldPlay = !playerMedia.paused);
  30431. }
  30432. }
  30433. transferMediaTo(player, media) {
  30434. var _this$detachedData2, _attachMediaSourceDat;
  30435. if (player.media === media) {
  30436. return;
  30437. }
  30438. let attachMediaSourceData = null;
  30439. const primaryPlayer = this.hls;
  30440. const isAssetPlayer = player !== primaryPlayer;
  30441. const appendInPlace = isAssetPlayer && player.interstitial.appendInPlace;
  30442. const detachedMediaSource = (_this$detachedData2 = this.detachedData) == null ? void 0 : _this$detachedData2.mediaSource;
  30443. let logFromSource;
  30444. if (primaryPlayer.media) {
  30445. if (appendInPlace) {
  30446. attachMediaSourceData = primaryPlayer.transferMedia();
  30447. this.detachedData = attachMediaSourceData;
  30448. }
  30449. logFromSource = `Primary`;
  30450. } else if (detachedMediaSource) {
  30451. const bufferingPlayer = this.getBufferingPlayer();
  30452. if (bufferingPlayer) {
  30453. attachMediaSourceData = bufferingPlayer.transferMedia();
  30454. logFromSource = `${bufferingPlayer}`;
  30455. } else {
  30456. logFromSource = `detached MediaSource`;
  30457. }
  30458. } else {
  30459. logFromSource = `detached media`;
  30460. }
  30461. if (!attachMediaSourceData) {
  30462. if (detachedMediaSource) {
  30463. attachMediaSourceData = this.detachedData;
  30464. this.log(`using detachedData: MediaSource ${stringify(attachMediaSourceData)}`);
  30465. } else if (!this.detachedData || primaryPlayer.media === media) {
  30466. const playerQueue = this.playerQueue;
  30467. if (playerQueue.length > 1) {
  30468. playerQueue.forEach((queuedPlayer) => {
  30469. if (isAssetPlayer && queuedPlayer.interstitial.appendInPlace !== appendInPlace) {
  30470. const interstitial = queuedPlayer.interstitial;
  30471. this.clearInterstitial(queuedPlayer.interstitial, null);
  30472. interstitial.appendInPlace = false;
  30473. if (interstitial.appendInPlace) {
  30474. this.warn(`Could not change append strategy for queued assets ${interstitial}`);
  30475. }
  30476. }
  30477. });
  30478. }
  30479. this.hls.detachMedia();
  30480. this.detachedData = {
  30481. media
  30482. };
  30483. }
  30484. }
  30485. const transferring = attachMediaSourceData && "mediaSource" in attachMediaSourceData && ((_attachMediaSourceDat = attachMediaSourceData.mediaSource) == null ? void 0 : _attachMediaSourceDat.readyState) !== "closed";
  30486. const dataToAttach = transferring && attachMediaSourceData ? attachMediaSourceData : media;
  30487. this.log(`${transferring ? "transfering MediaSource" : "attaching media"} to ${isAssetPlayer ? player : "Primary"} from ${logFromSource}`);
  30488. if (dataToAttach === attachMediaSourceData) {
  30489. const isAssetAtEndOfSchedule = isAssetPlayer && player.assetId === this.schedule.assetIdAtEnd;
  30490. dataToAttach.overrides = {
  30491. duration: this.schedule.duration,
  30492. endOfStream: !isAssetPlayer || isAssetAtEndOfSchedule,
  30493. cueRemoval: !isAssetPlayer
  30494. };
  30495. }
  30496. player.attachMedia(dataToAttach);
  30497. }
  30498. onInterstitialCueEnter() {
  30499. this.onTimeupdate();
  30500. }
  30501. // Scheduling methods
  30502. checkStart() {
  30503. const schedule = this.schedule;
  30504. const interstitialEvents = schedule.events;
  30505. if (!interstitialEvents || this.playbackDisabled || !this.media) {
  30506. return;
  30507. }
  30508. if (this.bufferedPos === -1) {
  30509. this.bufferedPos = 0;
  30510. }
  30511. const timelinePos = this.timelinePos;
  30512. const effectivePlayingItem = this.effectivePlayingItem;
  30513. if (timelinePos === -1) {
  30514. const startPosition = this.hls.startPosition;
  30515. this.timelinePos = startPosition;
  30516. if (interstitialEvents.length && interstitialEvents[0].cue.pre) {
  30517. const index2 = schedule.findEventIndex(interstitialEvents[0].identifier);
  30518. this.setSchedulePosition(index2);
  30519. } else if (startPosition >= 0 || !this.primaryLive) {
  30520. const start = this.timelinePos = startPosition > 0 ? startPosition : 0;
  30521. const index2 = schedule.findItemIndexAtTime(start);
  30522. this.setSchedulePosition(index2);
  30523. }
  30524. } else if (effectivePlayingItem && !this.playingItem) {
  30525. const index2 = schedule.findItemIndex(effectivePlayingItem);
  30526. this.setSchedulePosition(index2);
  30527. }
  30528. }
  30529. advanceAfterAssetEnded(interstitial, index2, assetListIndex) {
  30530. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex);
  30531. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  30532. this.setSchedulePosition(index2, nextAssetIndex);
  30533. } else {
  30534. const scheduleItems = this.schedule.items;
  30535. if (scheduleItems) {
  30536. const nextIndex = index2 + 1;
  30537. const scheduleLength = scheduleItems.length;
  30538. if (nextIndex >= scheduleLength) {
  30539. this.setSchedulePosition(-1);
  30540. return;
  30541. }
  30542. const resumptionTime = interstitial.resumeTime;
  30543. if (this.timelinePos < resumptionTime) {
  30544. this.timelinePos = resumptionTime;
  30545. this.checkBuffer();
  30546. }
  30547. this.setSchedulePosition(nextIndex);
  30548. }
  30549. }
  30550. }
  30551. setScheduleToAssetAtTime(time, playingAsset) {
  30552. const schedule = this.schedule;
  30553. const parentIdentifier = playingAsset.parentIdentifier;
  30554. const interstitial = schedule.getEvent(parentIdentifier);
  30555. if (interstitial) {
  30556. const itemIndex = schedule.findEventIndex(parentIdentifier);
  30557. const assetListIndex = schedule.findAssetIndex(interstitial, time);
  30558. this.advanceAfterAssetEnded(interstitial, itemIndex, assetListIndex - 1);
  30559. }
  30560. }
  30561. setSchedulePosition(index2, assetListIndex) {
  30562. const scheduleItems = this.schedule.items;
  30563. if (!scheduleItems || this.playbackDisabled) {
  30564. return;
  30565. }
  30566. this.log(`setSchedulePosition ${index2}, ${assetListIndex}`);
  30567. const scheduledItem = index2 >= 0 ? scheduleItems[index2] : null;
  30568. const currentItem = this.playingItem;
  30569. const playingLastItem = this.playingLastItem;
  30570. if (this.isInterstitial(currentItem)) {
  30571. var _interstitial$assetLi;
  30572. const interstitial = currentItem.event;
  30573. const playingAsset = this.playingAsset;
  30574. const assetId = playingAsset == null ? void 0 : playingAsset.identifier;
  30575. const player = assetId ? this.getAssetPlayer(assetId) : null;
  30576. if (player && assetId && (!this.eventItemsMatch(currentItem, scheduledItem) || assetListIndex !== void 0 && assetId !== ((_interstitial$assetLi = interstitial.assetList) == null ? void 0 : _interstitial$assetLi[assetListIndex].identifier))) {
  30577. var _this$detachedData3;
  30578. const playingAssetListIndex = interstitial.findAssetIndex(playingAsset);
  30579. this.log(`INTERSTITIAL_ASSET_ENDED ${playingAssetListIndex + 1}/${interstitial.assetList.length} ${eventAssetToString(playingAsset)}`);
  30580. this.endedAsset = playingAsset;
  30581. this.playingAsset = null;
  30582. this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED, {
  30583. asset: playingAsset,
  30584. assetListIndex: playingAssetListIndex,
  30585. event: interstitial,
  30586. schedule: scheduleItems.slice(0),
  30587. scheduleIndex: index2,
  30588. player
  30589. });
  30590. if (currentItem !== this.playingItem) {
  30591. if (this.itemsMatch(currentItem, this.playingItem) && !this.playingAsset) {
  30592. this.advanceAfterAssetEnded(interstitial, this.findItemIndex(this.playingItem), playingAssetListIndex);
  30593. }
  30594. return;
  30595. }
  30596. this.retreiveMediaSource(assetId, scheduledItem);
  30597. if (player.media && !((_this$detachedData3 = this.detachedData) != null && _this$detachedData3.mediaSource)) {
  30598. player.detachMedia();
  30599. }
  30600. }
  30601. if (!this.eventItemsMatch(currentItem, scheduledItem)) {
  30602. this.endedItem = currentItem;
  30603. this.playingItem = null;
  30604. this.log(`INTERSTITIAL_ENDED ${interstitial} ${segmentToString(currentItem)}`);
  30605. interstitial.hasPlayed = true;
  30606. this.hls.trigger(Events.INTERSTITIAL_ENDED, {
  30607. event: interstitial,
  30608. schedule: scheduleItems.slice(0),
  30609. scheduleIndex: index2
  30610. });
  30611. if (interstitial.cue.once) {
  30612. this.updateSchedule();
  30613. const items = this.schedule.items;
  30614. if (scheduledItem && items) {
  30615. const updatedIndex = this.findItemIndex(scheduledItem);
  30616. this.advanceSchedule(updatedIndex, items, assetListIndex, currentItem, playingLastItem);
  30617. }
  30618. return;
  30619. }
  30620. }
  30621. }
  30622. this.advanceSchedule(index2, scheduleItems, assetListIndex, currentItem, playingLastItem);
  30623. }
  30624. advanceSchedule(index2, scheduleItems, assetListIndex, currentItem, playedLastItem) {
  30625. const scheduledItem = index2 >= 0 ? scheduleItems[index2] : null;
  30626. const media = this.primaryMedia;
  30627. const playerQueue = this.playerQueue;
  30628. if (playerQueue.length) {
  30629. playerQueue.forEach((player) => {
  30630. const interstitial = player.interstitial;
  30631. const queuedIndex = this.schedule.findEventIndex(interstitial.identifier);
  30632. if (queuedIndex < index2 || queuedIndex > index2 + 1) {
  30633. this.clearInterstitial(interstitial, scheduledItem);
  30634. }
  30635. });
  30636. }
  30637. if (this.isInterstitial(scheduledItem)) {
  30638. this.timelinePos = Math.min(Math.max(this.timelinePos, scheduledItem.start), scheduledItem.end);
  30639. const interstitial = scheduledItem.event;
  30640. if (assetListIndex === void 0) {
  30641. assetListIndex = this.schedule.findAssetIndex(interstitial, this.timelinePos);
  30642. const assetIndexCandidate = getNextAssetIndex(interstitial, assetListIndex - 1);
  30643. if (interstitial.isAssetPastPlayoutLimit(assetIndexCandidate)) {
  30644. this.advanceAfterAssetEnded(interstitial, index2, assetListIndex);
  30645. return;
  30646. }
  30647. assetListIndex = assetIndexCandidate;
  30648. }
  30649. const waitingItem = this.waitingItem;
  30650. if (!this.assetsBuffered(scheduledItem, media)) {
  30651. this.setBufferingItem(scheduledItem);
  30652. }
  30653. let player = this.preloadAssets(interstitial, assetListIndex);
  30654. if (!this.eventItemsMatch(scheduledItem, waitingItem || currentItem)) {
  30655. this.waitingItem = scheduledItem;
  30656. this.log(`INTERSTITIAL_STARTED ${segmentToString(scheduledItem)} ${interstitial.appendInPlace ? "append in place" : ""}`);
  30657. this.hls.trigger(Events.INTERSTITIAL_STARTED, {
  30658. event: interstitial,
  30659. schedule: scheduleItems.slice(0),
  30660. scheduleIndex: index2
  30661. });
  30662. }
  30663. if (!interstitial.assetListLoaded) {
  30664. this.log(`Waiting for ASSET-LIST to complete loading ${interstitial}`);
  30665. return;
  30666. }
  30667. if (interstitial.assetListLoader) {
  30668. interstitial.assetListLoader.destroy();
  30669. interstitial.assetListLoader = void 0;
  30670. }
  30671. if (!media) {
  30672. this.log(`Waiting for attachMedia to start Interstitial ${interstitial}`);
  30673. return;
  30674. }
  30675. this.waitingItem = this.endedItem = null;
  30676. this.playingItem = scheduledItem;
  30677. const assetItem = interstitial.assetList[assetListIndex];
  30678. if (!assetItem) {
  30679. const nextItem = scheduleItems[index2 + 1];
  30680. const _media2 = this.media;
  30681. if (nextItem && _media2 && !this.isInterstitial(nextItem) && _media2.currentTime < nextItem.start) {
  30682. _media2.currentTime = this.timelinePos = nextItem.start;
  30683. }
  30684. this.advanceAfterAssetEnded(interstitial, index2, assetListIndex || 0);
  30685. return;
  30686. }
  30687. if (!player) {
  30688. player = this.getAssetPlayer(assetItem.identifier);
  30689. }
  30690. if (player === null || player.destroyed) {
  30691. const assetListLength = interstitial.assetList.length;
  30692. this.warn(`asset ${assetListIndex + 1}/${assetListLength} player destroyed ${interstitial}`);
  30693. player = this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  30694. }
  30695. if (!this.eventItemsMatch(scheduledItem, this.bufferingItem)) {
  30696. if (interstitial.appendInPlace && this.isAssetBuffered(assetItem)) {
  30697. return;
  30698. }
  30699. }
  30700. this.startAssetPlayer(player, assetListIndex, scheduleItems, index2, media);
  30701. if (this.shouldPlay) {
  30702. playWithCatch(player.media);
  30703. }
  30704. } else if (scheduledItem !== null) {
  30705. this.resumePrimary(scheduledItem, index2, currentItem);
  30706. if (this.shouldPlay) {
  30707. playWithCatch(this.hls.media);
  30708. }
  30709. } else if (playedLastItem && this.isInterstitial(currentItem)) {
  30710. this.endedItem = null;
  30711. this.playingItem = currentItem;
  30712. if (!currentItem.event.appendInPlace) {
  30713. this.attachPrimary(this.schedule.durations.primary, null);
  30714. }
  30715. }
  30716. }
  30717. get playbackDisabled() {
  30718. return this.hls.config.enableInterstitialPlayback === false;
  30719. }
  30720. get primaryDetails() {
  30721. var _this$mediaSelection, _this$mediaSelection$;
  30722. return (_this$mediaSelection = this.mediaSelection) == null ? void 0 : (_this$mediaSelection$ = _this$mediaSelection.main) == null ? void 0 : _this$mediaSelection$.details;
  30723. }
  30724. get primaryLive() {
  30725. var _this$primaryDetails;
  30726. return !!((_this$primaryDetails = this.primaryDetails) != null && _this$primaryDetails.live);
  30727. }
  30728. resumePrimary(scheduledItem, index2, fromItem) {
  30729. var _this$detachedData4;
  30730. this.playingItem = scheduledItem;
  30731. this.playingAsset = this.endedAsset = null;
  30732. this.waitingItem = this.endedItem = null;
  30733. this.bufferedToItem(scheduledItem);
  30734. this.log(`resuming ${segmentToString(scheduledItem)}`);
  30735. if (!((_this$detachedData4 = this.detachedData) != null && _this$detachedData4.mediaSource)) {
  30736. let timelinePos = this.timelinePos;
  30737. if (timelinePos < scheduledItem.start || timelinePos >= scheduledItem.end) {
  30738. timelinePos = this.getPrimaryResumption(scheduledItem, index2);
  30739. this.timelinePos = timelinePos;
  30740. }
  30741. this.attachPrimary(timelinePos, scheduledItem);
  30742. }
  30743. if (!fromItem) {
  30744. return;
  30745. }
  30746. const scheduleItems = this.schedule.items;
  30747. if (!scheduleItems) {
  30748. return;
  30749. }
  30750. this.log(`INTERSTITIALS_PRIMARY_RESUMED ${segmentToString(scheduledItem)}`);
  30751. this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED, {
  30752. schedule: scheduleItems.slice(0),
  30753. scheduleIndex: index2
  30754. });
  30755. this.checkBuffer();
  30756. }
  30757. getPrimaryResumption(scheduledItem, index2) {
  30758. const itemStart = scheduledItem.start;
  30759. if (this.primaryLive) {
  30760. const details = this.primaryDetails;
  30761. if (index2 === 0) {
  30762. return this.hls.startPosition;
  30763. } else if (details && (itemStart < details.fragmentStart || itemStart > details.edge)) {
  30764. return this.hls.liveSyncPosition || -1;
  30765. }
  30766. }
  30767. return itemStart;
  30768. }
  30769. isAssetBuffered(asset) {
  30770. const player = this.getAssetPlayer(asset.identifier);
  30771. if (player != null && player.hls) {
  30772. return player.hls.bufferedToEnd;
  30773. }
  30774. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  30775. return bufferInfo.end + 1 >= asset.timelineStart + (asset.duration || 0);
  30776. }
  30777. attachPrimary(timelinePos, item, skipSeekToStartPosition) {
  30778. if (item) {
  30779. this.setBufferingItem(item);
  30780. } else {
  30781. this.bufferingItem = this.playingItem;
  30782. }
  30783. this.bufferingAsset = null;
  30784. const media = this.primaryMedia;
  30785. if (!media) {
  30786. return;
  30787. }
  30788. const hls = this.hls;
  30789. if (hls.media) {
  30790. this.checkBuffer();
  30791. } else {
  30792. this.transferMediaTo(hls, media);
  30793. if (skipSeekToStartPosition) {
  30794. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  30795. }
  30796. }
  30797. if (!skipSeekToStartPosition) {
  30798. this.timelinePos = timelinePos;
  30799. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  30800. }
  30801. }
  30802. startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition) {
  30803. var _hls$mainForwardBuffe;
  30804. const hls = this.hls;
  30805. if (!hls.loadingEnabled || !hls.media || Math.abs((((_hls$mainForwardBuffe = hls.mainForwardBufferInfo) == null ? void 0 : _hls$mainForwardBuffe.start) || hls.media.currentTime) - timelinePos) > 0.5) {
  30806. hls.startLoad(timelinePos, skipSeekToStartPosition);
  30807. } else if (!hls.bufferingEnabled) {
  30808. hls.resumeBuffering();
  30809. }
  30810. }
  30811. // HLS.js event callbacks
  30812. onManifestLoading() {
  30813. this.stopLoad();
  30814. this.schedule.reset();
  30815. this.emptyPlayerQueue();
  30816. this.clearScheduleState();
  30817. this.shouldPlay = false;
  30818. this.bufferedPos = this.timelinePos = -1;
  30819. this.mediaSelection = this.altSelection = this.manager = this.requiredTracks = null;
  30820. this.hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  30821. this.hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  30822. }
  30823. onLevelUpdated(event, data) {
  30824. if (data.level === -1) {
  30825. return;
  30826. }
  30827. const main = this.hls.levels[data.level];
  30828. const currentSelection = _objectSpread2(_objectSpread2({}, this.mediaSelection || this.altSelection), {}, {
  30829. main
  30830. });
  30831. this.mediaSelection = currentSelection;
  30832. this.schedule.parseInterstitialDateRanges(currentSelection, this.hls.config.interstitialAppendInPlace);
  30833. if (!this.effectivePlayingItem && this.schedule.items) {
  30834. this.checkStart();
  30835. }
  30836. }
  30837. onAudioTrackUpdated(event, data) {
  30838. const audio = this.hls.audioTracks[data.id];
  30839. const previousSelection = this.mediaSelection;
  30840. if (!previousSelection) {
  30841. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  30842. audio
  30843. });
  30844. return;
  30845. }
  30846. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  30847. audio
  30848. });
  30849. this.mediaSelection = currentSelection;
  30850. }
  30851. onSubtitleTrackUpdated(event, data) {
  30852. const subtitles = this.hls.subtitleTracks[data.id];
  30853. const previousSelection = this.mediaSelection;
  30854. if (!previousSelection) {
  30855. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  30856. subtitles
  30857. });
  30858. return;
  30859. }
  30860. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  30861. subtitles
  30862. });
  30863. this.mediaSelection = currentSelection;
  30864. }
  30865. onAudioTrackSwitching(event, data) {
  30866. const audioOption = getBasicSelectionOption(data);
  30867. this.playerQueue.forEach((player) => player.hls.setAudioOption(data) || player.hls.setAudioOption(audioOption));
  30868. }
  30869. onSubtitleTrackSwitch(event, data) {
  30870. const subtitleOption = getBasicSelectionOption(data);
  30871. this.playerQueue.forEach((player) => player.hls.setSubtitleOption(data) || data.id !== -1 && player.hls.setSubtitleOption(subtitleOption));
  30872. }
  30873. onBufferCodecs(event, data) {
  30874. const requiredTracks = data.tracks;
  30875. if (requiredTracks) {
  30876. this.requiredTracks = requiredTracks;
  30877. }
  30878. }
  30879. onBufferAppended(event, data) {
  30880. this.checkBuffer();
  30881. }
  30882. onBufferFlushed(event, data) {
  30883. const playingItem = this.playingItem;
  30884. if (playingItem && !this.itemsMatch(playingItem, this.bufferingItem) && !this.isInterstitial(playingItem)) {
  30885. const timelinePos = this.timelinePos;
  30886. this.bufferedPos = timelinePos;
  30887. this.checkBuffer();
  30888. }
  30889. }
  30890. onBufferedToEnd(event) {
  30891. const interstitialEvents = this.schedule.events;
  30892. if (this.bufferedPos < Number.MAX_VALUE && interstitialEvents) {
  30893. for (let i2 = 0; i2 < interstitialEvents.length; i2++) {
  30894. const interstitial = interstitialEvents[i2];
  30895. if (interstitial.cue.post) {
  30896. var _this$schedule$items;
  30897. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  30898. const item = (_this$schedule$items = this.schedule.items) == null ? void 0 : _this$schedule$items[scheduleIndex];
  30899. if (this.isInterstitial(item) && this.eventItemsMatch(item, this.bufferingItem)) {
  30900. this.bufferedToItem(item, 0);
  30901. }
  30902. break;
  30903. }
  30904. }
  30905. this.bufferedPos = Number.MAX_VALUE;
  30906. }
  30907. }
  30908. onMediaEnded(event) {
  30909. const playingItem = this.playingItem;
  30910. if (!this.playingLastItem && playingItem) {
  30911. const playingIndex = this.findItemIndex(playingItem);
  30912. this.setSchedulePosition(playingIndex + 1);
  30913. } else {
  30914. this.shouldPlay = false;
  30915. }
  30916. }
  30917. updateItem(previousItem, time) {
  30918. const items = this.schedule.items;
  30919. if (previousItem && items) {
  30920. const index2 = this.findItemIndex(previousItem, time);
  30921. return items[index2] || null;
  30922. }
  30923. return null;
  30924. }
  30925. trimInPlace(updatedItem, itemBeforeUpdate) {
  30926. if (this.isInterstitial(updatedItem) && updatedItem.event.appendInPlace && itemBeforeUpdate.end - updatedItem.end > 0.25) {
  30927. updatedItem.event.assetList.forEach((asset, index2) => {
  30928. if (updatedItem.event.isAssetPastPlayoutLimit(index2)) {
  30929. this.clearAssetPlayer(asset.identifier, null);
  30930. }
  30931. });
  30932. const flushStart = updatedItem.end + 0.25;
  30933. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, flushStart, 0);
  30934. if (bufferInfo.end > flushStart || (bufferInfo.nextStart || 0) > flushStart) {
  30935. this.attachPrimary(flushStart, null);
  30936. this.flushFrontBuffer(flushStart);
  30937. }
  30938. }
  30939. }
  30940. itemsMatch(a2, b2) {
  30941. return !!b2 && (a2 === b2 || a2.event && b2.event && this.eventItemsMatch(a2, b2) || !a2.event && !b2.event && this.findItemIndex(a2) === this.findItemIndex(b2));
  30942. }
  30943. eventItemsMatch(a2, b2) {
  30944. var _b$event;
  30945. return !!b2 && (a2 === b2 || a2.event.identifier === ((_b$event = b2.event) == null ? void 0 : _b$event.identifier));
  30946. }
  30947. findItemIndex(item, time) {
  30948. return item ? this.schedule.findItemIndex(item, time) : -1;
  30949. }
  30950. updateSchedule() {
  30951. const mediaSelection = this.mediaSelection;
  30952. if (!mediaSelection) {
  30953. return;
  30954. }
  30955. this.schedule.updateSchedule(mediaSelection, []);
  30956. }
  30957. // Schedule buffer control
  30958. checkBuffer(starved) {
  30959. const items = this.schedule.items;
  30960. if (!items) {
  30961. return;
  30962. }
  30963. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  30964. if (starved) {
  30965. this.bufferedPos = this.timelinePos;
  30966. }
  30967. starved || (starved = bufferInfo.len < 1);
  30968. this.updateBufferedPos(bufferInfo.end, items, starved);
  30969. }
  30970. updateBufferedPos(bufferEnd, items, bufferIsEmpty) {
  30971. const schedule = this.schedule;
  30972. const bufferingItem = this.bufferingItem;
  30973. if (this.bufferedPos > bufferEnd) {
  30974. return;
  30975. }
  30976. if (items.length === 1 && this.itemsMatch(items[0], bufferingItem)) {
  30977. this.bufferedPos = bufferEnd;
  30978. return;
  30979. }
  30980. const playingItem = this.playingItem;
  30981. const playingIndex = this.findItemIndex(playingItem);
  30982. let bufferEndIndex = schedule.findItemIndexAtTime(bufferEnd);
  30983. if (this.bufferedPos < bufferEnd) {
  30984. var _nextItemToBuffer$eve, _bufferingItem$event;
  30985. const bufferingIndex = this.findItemIndex(bufferingItem);
  30986. const nextToBufferIndex = Math.min(bufferingIndex + 1, items.length - 1);
  30987. const nextItemToBuffer = items[nextToBufferIndex];
  30988. if (bufferEndIndex === -1 && bufferingItem && bufferEnd >= bufferingItem.end || (_nextItemToBuffer$eve = nextItemToBuffer.event) != null && _nextItemToBuffer$eve.appendInPlace && bufferEnd + 0.01 >= nextItemToBuffer.start) {
  30989. bufferEndIndex = nextToBufferIndex;
  30990. }
  30991. if (nextToBufferIndex - playingIndex > 1 && (bufferingItem == null ? void 0 : (_bufferingItem$event = bufferingItem.event) == null ? void 0 : _bufferingItem$event.appendInPlace) === false) {
  30992. return;
  30993. }
  30994. this.bufferedPos = bufferEnd;
  30995. if (bufferEndIndex > bufferingIndex && bufferEndIndex > playingIndex) {
  30996. this.bufferedToItem(nextItemToBuffer);
  30997. } else {
  30998. const details = this.primaryDetails;
  30999. if (this.primaryLive && details && bufferEnd > details.edge - details.targetduration && nextItemToBuffer.start < details.edge + this.hls.config.interstitialLiveLookAhead && this.isInterstitial(nextItemToBuffer)) {
  31000. this.preloadAssets(nextItemToBuffer.event, 0);
  31001. }
  31002. }
  31003. } else if (bufferIsEmpty && playingItem && !this.itemsMatch(playingItem, bufferingItem)) {
  31004. if (bufferEndIndex === playingIndex) {
  31005. this.bufferedToItem(playingItem);
  31006. } else if (bufferEndIndex === playingIndex + 1) {
  31007. this.bufferedToItem(items[bufferEndIndex]);
  31008. }
  31009. }
  31010. }
  31011. assetsBuffered(item, media) {
  31012. const assetList = item.event.assetList;
  31013. if (assetList.length === 0) {
  31014. return false;
  31015. }
  31016. return !item.event.assetList.some((asset) => {
  31017. const player = this.getAssetPlayer(asset.identifier);
  31018. return !(player != null && player.bufferedInPlaceToEnd(media));
  31019. });
  31020. }
  31021. setBufferingItem(item) {
  31022. const bufferingLast = this.bufferingItem;
  31023. const schedule = this.schedule;
  31024. if (!this.itemsMatch(item, bufferingLast)) {
  31025. const {
  31026. items,
  31027. events
  31028. } = schedule;
  31029. if (!items || !events) {
  31030. return bufferingLast;
  31031. }
  31032. const isInterstitial = this.isInterstitial(item);
  31033. const bufferingPlayer = this.getBufferingPlayer();
  31034. this.bufferingItem = item;
  31035. this.bufferedPos = Math.max(item.start, Math.min(item.end, this.timelinePos));
  31036. const timeRemaining = bufferingPlayer ? bufferingPlayer.remaining : bufferingLast ? bufferingLast.end - this.timelinePos : 0;
  31037. this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${segmentToString(item)}` + (bufferingLast ? ` (${timeRemaining.toFixed(2)} remaining)` : ""));
  31038. if (!this.playbackDisabled) {
  31039. if (isInterstitial) {
  31040. item.event.assetList.forEach((asset) => {
  31041. const player = this.getAssetPlayer(asset.identifier);
  31042. if (player) {
  31043. player.resumeBuffering();
  31044. }
  31045. });
  31046. } else {
  31047. this.hls.resumeBuffering();
  31048. this.playerQueue.forEach((player) => player.pauseBuffering());
  31049. }
  31050. }
  31051. this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY, {
  31052. events: events.slice(0),
  31053. schedule: items.slice(0),
  31054. bufferingIndex: this.findItemIndex(item),
  31055. playingIndex: this.findItemIndex(this.playingItem)
  31056. });
  31057. } else if (this.bufferingItem !== item) {
  31058. this.bufferingItem = item;
  31059. }
  31060. return bufferingLast;
  31061. }
  31062. bufferedToItem(item, assetListIndex = 0) {
  31063. const bufferingLast = this.setBufferingItem(item);
  31064. if (this.playbackDisabled) {
  31065. return;
  31066. }
  31067. if (this.isInterstitial(item)) {
  31068. this.bufferedToEvent(item, assetListIndex);
  31069. } else if (bufferingLast !== null) {
  31070. this.bufferingAsset = null;
  31071. const detachedData = this.detachedData;
  31072. if (detachedData) {
  31073. if (detachedData.mediaSource) {
  31074. const skipSeekToStartPosition = true;
  31075. this.attachPrimary(item.start, item, skipSeekToStartPosition);
  31076. } else {
  31077. this.preloadPrimary(item);
  31078. }
  31079. } else {
  31080. this.preloadPrimary(item);
  31081. }
  31082. }
  31083. }
  31084. preloadPrimary(item) {
  31085. const index2 = this.findItemIndex(item);
  31086. const timelinePos = this.getPrimaryResumption(item, index2);
  31087. this.startLoadingPrimaryAt(timelinePos);
  31088. }
  31089. bufferedToEvent(item, assetListIndex) {
  31090. const interstitial = item.event;
  31091. const neverLoaded = interstitial.assetList.length === 0 && !interstitial.assetListLoader;
  31092. const playOnce = interstitial.cue.once;
  31093. if (neverLoaded || !playOnce) {
  31094. const player = this.preloadAssets(interstitial, assetListIndex);
  31095. if (player != null && player.interstitial.appendInPlace) {
  31096. const assetItem = interstitial.assetList[assetListIndex];
  31097. const media = this.primaryMedia;
  31098. if (assetItem && media) {
  31099. this.bufferAssetPlayer(player, media);
  31100. }
  31101. }
  31102. }
  31103. }
  31104. preloadAssets(interstitial, assetListIndex) {
  31105. const uri = interstitial.assetUrl;
  31106. const assetListLength = interstitial.assetList.length;
  31107. const neverLoaded = assetListLength === 0 && !interstitial.assetListLoader;
  31108. const playOnce = interstitial.cue.once;
  31109. if (neverLoaded) {
  31110. const timelineStart = interstitial.timelineStart;
  31111. if (interstitial.appendInPlace) {
  31112. var _playingItem$nextEven;
  31113. const playingItem = this.playingItem;
  31114. if (!this.isInterstitial(playingItem) && (playingItem == null ? void 0 : (_playingItem$nextEven = playingItem.nextEvent) == null ? void 0 : _playingItem$nextEven.identifier) === interstitial.identifier) {
  31115. this.flushFrontBuffer(timelineStart + 0.25);
  31116. }
  31117. }
  31118. let hlsStartOffset;
  31119. let liveStartPosition = 0;
  31120. if (!this.playingItem && this.primaryLive) {
  31121. liveStartPosition = this.hls.startPosition;
  31122. if (liveStartPosition === -1) {
  31123. liveStartPosition = this.hls.liveSyncPosition || 0;
  31124. }
  31125. }
  31126. if (liveStartPosition && !(interstitial.cue.pre || interstitial.cue.post)) {
  31127. const startOffset = liveStartPosition - timelineStart;
  31128. if (startOffset > 0) {
  31129. hlsStartOffset = Math.round(startOffset * 1e3) / 1e3;
  31130. }
  31131. }
  31132. this.log(`Load interstitial asset ${assetListIndex + 1}/${uri ? 1 : assetListLength} ${interstitial}${hlsStartOffset ? ` live-start: ${liveStartPosition} start-offset: ${hlsStartOffset}` : ""}`);
  31133. if (uri) {
  31134. return this.createAsset(interstitial, 0, 0, timelineStart, interstitial.duration, uri);
  31135. }
  31136. const assetListLoader = this.assetListLoader.loadAssetList(interstitial, hlsStartOffset);
  31137. if (assetListLoader) {
  31138. interstitial.assetListLoader = assetListLoader;
  31139. }
  31140. } else if (!playOnce && assetListLength) {
  31141. for (let i2 = assetListIndex; i2 < assetListLength; i2++) {
  31142. const asset = interstitial.assetList[i2];
  31143. const playerIndex = this.getAssetPlayerQueueIndex(asset.identifier);
  31144. if ((playerIndex === -1 || this.playerQueue[playerIndex].destroyed) && !asset.error) {
  31145. this.createAssetPlayer(interstitial, asset, i2);
  31146. }
  31147. }
  31148. return this.getAssetPlayer(interstitial.assetList[assetListIndex].identifier);
  31149. }
  31150. return null;
  31151. }
  31152. flushFrontBuffer(startOffset) {
  31153. const requiredTracks = this.requiredTracks;
  31154. if (!requiredTracks) {
  31155. return;
  31156. }
  31157. this.log(`Removing front buffer starting at ${startOffset}`);
  31158. const sourceBufferNames = Object.keys(requiredTracks);
  31159. sourceBufferNames.forEach((type) => {
  31160. this.hls.trigger(Events.BUFFER_FLUSHING, {
  31161. startOffset,
  31162. endOffset: Infinity,
  31163. type
  31164. });
  31165. });
  31166. }
  31167. // Interstitial Asset Player control
  31168. getAssetPlayerQueueIndex(assetId) {
  31169. const playerQueue = this.playerQueue;
  31170. for (let i2 = 0; i2 < playerQueue.length; i2++) {
  31171. if (assetId === playerQueue[i2].assetId) {
  31172. return i2;
  31173. }
  31174. }
  31175. return -1;
  31176. }
  31177. getAssetPlayer(assetId) {
  31178. const index2 = this.getAssetPlayerQueueIndex(assetId);
  31179. return this.playerQueue[index2] || null;
  31180. }
  31181. getBufferingPlayer() {
  31182. const {
  31183. playerQueue,
  31184. primaryMedia
  31185. } = this;
  31186. if (primaryMedia) {
  31187. for (let i2 = 0; i2 < playerQueue.length; i2++) {
  31188. if (playerQueue[i2].media === primaryMedia) {
  31189. return playerQueue[i2];
  31190. }
  31191. }
  31192. }
  31193. return null;
  31194. }
  31195. createAsset(interstitial, assetListIndex, startOffset, timelineStart, duration, uri) {
  31196. const assetItem = {
  31197. parentIdentifier: interstitial.identifier,
  31198. identifier: generateAssetIdentifier(interstitial, uri, assetListIndex),
  31199. duration,
  31200. startOffset,
  31201. timelineStart,
  31202. uri
  31203. };
  31204. return this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  31205. }
  31206. createAssetPlayer(interstitial, assetItem, assetListIndex) {
  31207. const primary = this.hls;
  31208. const userConfig = primary.userConfig;
  31209. let videoPreference = userConfig.videoPreference;
  31210. const currentLevel = primary.loadLevelObj || primary.levels[primary.currentLevel];
  31211. if (videoPreference || currentLevel) {
  31212. videoPreference = _extends({}, videoPreference);
  31213. if (currentLevel.videoCodec) {
  31214. videoPreference.videoCodec = currentLevel.videoCodec;
  31215. }
  31216. if (currentLevel.videoRange) {
  31217. videoPreference.allowedVideoRanges = [currentLevel.videoRange];
  31218. }
  31219. }
  31220. const selectedAudio = primary.audioTracks[primary.audioTrack];
  31221. const selectedSubtitle = primary.subtitleTracks[primary.subtitleTrack];
  31222. let startPosition = 0;
  31223. if (this.primaryLive || interstitial.appendInPlace) {
  31224. const timePastStart = this.timelinePos - assetItem.timelineStart;
  31225. if (timePastStart > 1) {
  31226. const duration = assetItem.duration;
  31227. if (duration && timePastStart < duration) {
  31228. startPosition = timePastStart;
  31229. }
  31230. }
  31231. }
  31232. const assetId = assetItem.identifier;
  31233. const playerConfig = _objectSpread2(_objectSpread2({}, userConfig), {}, {
  31234. autoStartLoad: true,
  31235. startFragPrefetch: true,
  31236. primarySessionId: primary.sessionId,
  31237. assetPlayerId: assetId,
  31238. abrEwmaDefaultEstimate: primary.bandwidthEstimate,
  31239. interstitialsController: void 0,
  31240. startPosition,
  31241. liveDurationInfinity: false,
  31242. testBandwidth: false,
  31243. videoPreference,
  31244. audioPreference: selectedAudio || userConfig.audioPreference,
  31245. subtitlePreference: selectedSubtitle || userConfig.subtitlePreference
  31246. });
  31247. if (interstitial.appendInPlace) {
  31248. interstitial.appendInPlaceStarted = true;
  31249. if (assetItem.timelineStart) {
  31250. playerConfig.timelineOffset = assetItem.timelineStart;
  31251. }
  31252. }
  31253. const cmcd = playerConfig.cmcd;
  31254. if (cmcd != null && cmcd.sessionId && cmcd.contentId) {
  31255. playerConfig.cmcd = _extends({}, cmcd, {
  31256. contentId: hash(assetItem.uri)
  31257. });
  31258. }
  31259. if (this.getAssetPlayer(assetId)) {
  31260. this.warn(`Duplicate date range identifier ${interstitial} and asset ${assetId}`);
  31261. }
  31262. const player = new HlsAssetPlayer(this.HlsPlayerClass, playerConfig, interstitial, assetItem);
  31263. this.playerQueue.push(player);
  31264. interstitial.assetList[assetListIndex] = assetItem;
  31265. const updateAssetPlayerDetails = (details) => {
  31266. if (details.live) {
  31267. const error = new Error(`Interstitials MUST be VOD assets ${interstitial}`);
  31268. const errorData = {
  31269. fatal: true,
  31270. type: ErrorTypes.OTHER_ERROR,
  31271. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  31272. error
  31273. };
  31274. this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
  31275. return;
  31276. }
  31277. const duration = details.edge - details.fragmentStart;
  31278. const currentAssetDuration = assetItem.duration;
  31279. if (currentAssetDuration === null || duration > currentAssetDuration) {
  31280. this.log(`Interstitial asset "${assetId}" duration change ${currentAssetDuration} > ${duration}`);
  31281. assetItem.duration = duration;
  31282. this.updateSchedule();
  31283. }
  31284. };
  31285. player.on(Events.LEVEL_UPDATED, (event, {
  31286. details
  31287. }) => updateAssetPlayerDetails(details));
  31288. player.on(Events.LEVEL_PTS_UPDATED, (event, {
  31289. details
  31290. }) => updateAssetPlayerDetails(details));
  31291. const onBufferCodecs = (event, data) => {
  31292. const inQueuPlayer = this.getAssetPlayer(assetId);
  31293. if (inQueuPlayer && data.tracks) {
  31294. inQueuPlayer.off(Events.BUFFER_CODECS, onBufferCodecs);
  31295. inQueuPlayer.tracks = data.tracks;
  31296. const media = this.primaryMedia;
  31297. if (this.bufferingAsset === inQueuPlayer.assetItem && media && !inQueuPlayer.media) {
  31298. this.bufferAssetPlayer(inQueuPlayer, media);
  31299. }
  31300. }
  31301. };
  31302. player.on(Events.BUFFER_CODECS, onBufferCodecs);
  31303. const bufferedToEnd = () => {
  31304. var _this$schedule$items2;
  31305. const inQueuPlayer = this.getAssetPlayer(assetId);
  31306. this.log(`buffered to end of asset ${inQueuPlayer}`);
  31307. if (!inQueuPlayer) {
  31308. return;
  31309. }
  31310. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  31311. const item = (_this$schedule$items2 = this.schedule.items) == null ? void 0 : _this$schedule$items2[scheduleIndex];
  31312. if (this.isInterstitial(item)) {
  31313. const assetListIndex2 = interstitial.findAssetIndex(assetItem);
  31314. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex2);
  31315. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  31316. this.bufferedToItem(item, nextAssetIndex);
  31317. } else {
  31318. var _this$schedule$items3;
  31319. const nextItem = (_this$schedule$items3 = this.schedule.items) == null ? void 0 : _this$schedule$items3[scheduleIndex + 1];
  31320. if (nextItem) {
  31321. this.bufferedToItem(nextItem);
  31322. }
  31323. }
  31324. }
  31325. };
  31326. player.on(Events.BUFFERED_TO_END, bufferedToEnd);
  31327. const endedWithAssetIndex = (assetIndex) => {
  31328. return () => {
  31329. const inQueuPlayer = this.getAssetPlayer(assetId);
  31330. if (!inQueuPlayer) {
  31331. return;
  31332. }
  31333. this.shouldPlay = true;
  31334. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  31335. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetIndex);
  31336. };
  31337. };
  31338. player.once(Events.MEDIA_ENDED, endedWithAssetIndex(assetListIndex));
  31339. player.once(Events.PLAYOUT_LIMIT_REACHED, endedWithAssetIndex(Infinity));
  31340. player.on(Events.ERROR, (event, data) => {
  31341. const inQueuPlayer = this.getAssetPlayer(assetId);
  31342. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  31343. if (inQueuPlayer != null && inQueuPlayer.media) {
  31344. const assetCurrentTime = inQueuPlayer.currentTime;
  31345. const distanceFromEnd = inQueuPlayer.duration - assetCurrentTime;
  31346. if (assetCurrentTime && interstitial.appendInPlace && distanceFromEnd / inQueuPlayer.media.playbackRate < 0.5) {
  31347. this.log(`Advancing buffer past end of asset ${assetId} ${interstitial} at ${inQueuPlayer.media.currentTime}`);
  31348. bufferedToEnd();
  31349. } else {
  31350. this.warn(`Stalled at ${assetCurrentTime} of ${assetCurrentTime + distanceFromEnd} in asset ${assetId} ${interstitial}`);
  31351. this.onTimeupdate();
  31352. this.checkBuffer(true);
  31353. }
  31354. }
  31355. return;
  31356. }
  31357. this.handleAssetItemError(data, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, `Asset player error ${data.error} ${interstitial}`);
  31358. });
  31359. player.on(Events.DESTROYING, () => {
  31360. const inQueuPlayer = this.getAssetPlayer(assetId);
  31361. if (!inQueuPlayer) {
  31362. return;
  31363. }
  31364. const error = new Error(`Asset player destroyed unexpectedly ${assetId}`);
  31365. const errorData = {
  31366. fatal: true,
  31367. type: ErrorTypes.OTHER_ERROR,
  31368. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  31369. error
  31370. };
  31371. this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
  31372. });
  31373. this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${eventAssetToString(assetItem)}`);
  31374. this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED, {
  31375. asset: assetItem,
  31376. assetListIndex,
  31377. event: interstitial,
  31378. player
  31379. });
  31380. return player;
  31381. }
  31382. clearInterstitial(interstitial, toSegment) {
  31383. interstitial.assetList.forEach((asset) => {
  31384. this.clearAssetPlayer(asset.identifier, toSegment);
  31385. });
  31386. interstitial.reset();
  31387. }
  31388. resetAssetPlayer(assetId) {
  31389. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  31390. if (playerIndex !== -1) {
  31391. this.log(`reset asset player "${assetId}" after error`);
  31392. const player = this.playerQueue[playerIndex];
  31393. this.transferMediaFromPlayer(player, null);
  31394. player.resetDetails();
  31395. }
  31396. }
  31397. clearAssetPlayer(assetId, toSegment) {
  31398. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  31399. if (playerIndex !== -1) {
  31400. this.log(`clear asset player "${assetId}" toSegment: ${toSegment ? segmentToString(toSegment) : toSegment}`);
  31401. const player = this.playerQueue[playerIndex];
  31402. this.transferMediaFromPlayer(player, toSegment);
  31403. this.playerQueue.splice(playerIndex, 1);
  31404. player.destroy();
  31405. }
  31406. }
  31407. emptyPlayerQueue() {
  31408. let player;
  31409. while (player = this.playerQueue.pop()) {
  31410. player.destroy();
  31411. }
  31412. this.playerQueue = [];
  31413. }
  31414. startAssetPlayer(player, assetListIndex, scheduleItems, scheduleIndex, media) {
  31415. const {
  31416. interstitial,
  31417. assetItem,
  31418. assetId
  31419. } = player;
  31420. const assetListLength = interstitial.assetList.length;
  31421. const playingAsset = this.playingAsset;
  31422. this.endedAsset = null;
  31423. this.playingAsset = assetItem;
  31424. if (!playingAsset || playingAsset.identifier !== assetId) {
  31425. if (playingAsset) {
  31426. this.clearAssetPlayer(playingAsset.identifier, scheduleItems[scheduleIndex]);
  31427. delete playingAsset.error;
  31428. }
  31429. this.log(`INTERSTITIAL_ASSET_STARTED ${assetListIndex + 1}/${assetListLength} ${eventAssetToString(assetItem)}`);
  31430. this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED, {
  31431. asset: assetItem,
  31432. assetListIndex,
  31433. event: interstitial,
  31434. schedule: scheduleItems.slice(0),
  31435. scheduleIndex,
  31436. player
  31437. });
  31438. }
  31439. this.bufferAssetPlayer(player, media);
  31440. }
  31441. bufferAssetPlayer(player, media) {
  31442. var _this$schedule$items4, _this$detachedData5;
  31443. const {
  31444. interstitial,
  31445. assetItem
  31446. } = player;
  31447. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  31448. const item = (_this$schedule$items4 = this.schedule.items) == null ? void 0 : _this$schedule$items4[scheduleIndex];
  31449. if (!item) {
  31450. return;
  31451. }
  31452. this.setBufferingItem(item);
  31453. this.bufferingAsset = assetItem;
  31454. const bufferingPlayer = this.getBufferingPlayer();
  31455. if (bufferingPlayer === player) {
  31456. return;
  31457. }
  31458. const appendInPlaceNext = interstitial.appendInPlace;
  31459. if (appendInPlaceNext && (bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial.appendInPlace) === false) {
  31460. return;
  31461. }
  31462. const activeTracks = (bufferingPlayer == null ? void 0 : bufferingPlayer.tracks) || ((_this$detachedData5 = this.detachedData) == null ? void 0 : _this$detachedData5.tracks) || this.requiredTracks;
  31463. if (appendInPlaceNext && assetItem !== this.playingAsset) {
  31464. if (!player.tracks) {
  31465. return;
  31466. }
  31467. if (activeTracks && !isCompatibleTrackChange(activeTracks, player.tracks)) {
  31468. const error = new Error(`Asset ${eventAssetToString(assetItem)} SourceBuffer tracks ('${Object.keys(player.tracks)}') are not compatible with primary content tracks ('${Object.keys(activeTracks)}')`);
  31469. const errorData = {
  31470. fatal: true,
  31471. type: ErrorTypes.OTHER_ERROR,
  31472. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  31473. error
  31474. };
  31475. const assetListIndex = interstitial.findAssetIndex(assetItem);
  31476. this.handleAssetItemError(errorData, interstitial, scheduleIndex, assetListIndex, error.message);
  31477. return;
  31478. }
  31479. }
  31480. this.transferMediaTo(player, media);
  31481. }
  31482. handleAssetItemError(data, interstitial, scheduleIndex, assetListIndex, errorMessage) {
  31483. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  31484. return;
  31485. }
  31486. const assetItem = interstitial.assetList[assetListIndex];
  31487. this.warn(`INTERSTITIAL_ASSET_ERROR ${assetItem ? eventAssetToString(assetItem) : assetItem} ${data.error}`);
  31488. const assetId = assetItem == null ? void 0 : assetItem.identifier;
  31489. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  31490. const player = this.playerQueue[playerIndex] || null;
  31491. const items = this.schedule.items;
  31492. const interstitialAssetError = _extends({}, data, {
  31493. fatal: false,
  31494. errorAction: createDoNothingErrorAction(true),
  31495. asset: assetItem,
  31496. assetListIndex,
  31497. event: interstitial,
  31498. schedule: items,
  31499. scheduleIndex,
  31500. player
  31501. });
  31502. this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR, interstitialAssetError);
  31503. if (!data.fatal) {
  31504. return;
  31505. }
  31506. const playingAsset = this.playingAsset;
  31507. const error = new Error(errorMessage);
  31508. if (assetItem) {
  31509. this.clearAssetPlayer(assetId, null);
  31510. assetItem.error = error;
  31511. }
  31512. if (!interstitial.assetList.some((asset) => !asset.error)) {
  31513. interstitial.error = error;
  31514. } else {
  31515. for (let i2 = assetListIndex; i2 < interstitial.assetList.length; i2++) {
  31516. this.resetAssetPlayer(interstitial.assetList[i2].identifier);
  31517. }
  31518. this.updateSchedule();
  31519. }
  31520. if (interstitial.error) {
  31521. this.primaryFallback(interstitial);
  31522. } else if (playingAsset && playingAsset.identifier === assetId) {
  31523. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetListIndex);
  31524. }
  31525. }
  31526. primaryFallback(interstitial) {
  31527. const flushStart = interstitial.timelineStart;
  31528. const playingItem = this.effectivePlayingItem;
  31529. this.updateSchedule();
  31530. if (playingItem) {
  31531. this.log(`Fallback to primary from event "${interstitial.identifier}" start: ${flushStart} pos: ${this.timelinePos} playing: ${playingItem ? segmentToString(playingItem) : "<none>"} error: ${interstitial.error}`);
  31532. let timelinePos = this.timelinePos;
  31533. if (timelinePos === -1) {
  31534. timelinePos = this.hls.startPosition;
  31535. }
  31536. const newPlayingItem = this.updateItem(playingItem, timelinePos);
  31537. if (this.itemsMatch(playingItem, newPlayingItem)) {
  31538. this.clearInterstitial(interstitial, null);
  31539. }
  31540. if (interstitial.appendInPlace) {
  31541. this.attachPrimary(flushStart, null);
  31542. this.flushFrontBuffer(flushStart);
  31543. }
  31544. const scheduleIndex = this.schedule.findItemIndexAtTime(timelinePos);
  31545. this.setSchedulePosition(scheduleIndex);
  31546. } else {
  31547. this.checkStart();
  31548. }
  31549. }
  31550. // Asset List loading
  31551. onAssetListLoaded(event, data) {
  31552. var _this$bufferingItem2;
  31553. const interstitial = data.event;
  31554. const interstitialId = interstitial.identifier;
  31555. const assets = data.assetListResponse.ASSETS;
  31556. if (!this.schedule.hasEvent(interstitialId)) {
  31557. return;
  31558. }
  31559. const eventStart = interstitial.timelineStart;
  31560. const previousDuration = interstitial.duration;
  31561. let sumDuration = 0;
  31562. assets.forEach((asset, assetListIndex) => {
  31563. const duration = parseFloat(asset.DURATION);
  31564. this.createAsset(interstitial, assetListIndex, sumDuration, eventStart + sumDuration, duration, asset.URI);
  31565. sumDuration += duration;
  31566. });
  31567. interstitial.duration = sumDuration;
  31568. this.log(`Loaded asset-list with duration: ${sumDuration} (was: ${previousDuration}) ${interstitial}`);
  31569. const waitingItem = this.waitingItem;
  31570. const waitingForItem = (waitingItem == null ? void 0 : waitingItem.event.identifier) === interstitialId;
  31571. this.updateSchedule();
  31572. const bufferingEvent = (_this$bufferingItem2 = this.bufferingItem) == null ? void 0 : _this$bufferingItem2.event;
  31573. if (waitingForItem) {
  31574. var _this$schedule$items5;
  31575. const scheduleIndex = this.schedule.findEventIndex(interstitialId);
  31576. const item = (_this$schedule$items5 = this.schedule.items) == null ? void 0 : _this$schedule$items5[scheduleIndex];
  31577. if (item) {
  31578. if (!this.playingItem && this.timelinePos > item.end) {
  31579. const index2 = this.schedule.findItemIndexAtTime(this.timelinePos);
  31580. if (index2 !== scheduleIndex) {
  31581. interstitial.error = new Error(`Interstitial no longer within playback range ${this.timelinePos} ${interstitial}`);
  31582. this.primaryFallback(interstitial);
  31583. return;
  31584. }
  31585. }
  31586. this.setBufferingItem(item);
  31587. }
  31588. this.setSchedulePosition(scheduleIndex);
  31589. } else if ((bufferingEvent == null ? void 0 : bufferingEvent.identifier) === interstitialId && bufferingEvent.appendInPlace) {
  31590. const assetItem = interstitial.assetList[0];
  31591. const player = this.getAssetPlayer(assetItem.identifier);
  31592. const media = this.primaryMedia;
  31593. if (assetItem && player && media) {
  31594. this.bufferAssetPlayer(player, media);
  31595. }
  31596. }
  31597. }
  31598. onError(event, data) {
  31599. switch (data.details) {
  31600. case ErrorDetails.ASSET_LIST_PARSING_ERROR:
  31601. case ErrorDetails.ASSET_LIST_LOAD_ERROR:
  31602. case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT: {
  31603. const interstitial = data.interstitial;
  31604. if (interstitial) {
  31605. this.primaryFallback(interstitial);
  31606. }
  31607. break;
  31608. }
  31609. case ErrorDetails.BUFFER_STALLED_ERROR: {
  31610. this.onTimeupdate();
  31611. this.checkBuffer(true);
  31612. break;
  31613. }
  31614. }
  31615. }
  31616. }
  31617. const TICK_INTERVAL$2 = 500;
  31618. class SubtitleStreamController extends BaseStreamController {
  31619. constructor(hls, fragmentTracker, keyLoader) {
  31620. super(hls, fragmentTracker, keyLoader, "subtitle-stream-controller", PlaylistLevelType.SUBTITLE);
  31621. this.currentTrackId = -1;
  31622. this.tracksBuffered = [];
  31623. this.mainDetails = null;
  31624. this.registerListeners();
  31625. }
  31626. onHandlerDestroying() {
  31627. this.unregisterListeners();
  31628. super.onHandlerDestroying();
  31629. this.mainDetails = null;
  31630. }
  31631. registerListeners() {
  31632. super.registerListeners();
  31633. const {
  31634. hls
  31635. } = this;
  31636. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  31637. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  31638. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  31639. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  31640. hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  31641. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  31642. }
  31643. unregisterListeners() {
  31644. super.unregisterListeners();
  31645. const {
  31646. hls
  31647. } = this;
  31648. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  31649. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  31650. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  31651. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  31652. hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  31653. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  31654. }
  31655. startLoad(startPosition, skipSeekToStartPosition) {
  31656. this.stopLoad();
  31657. this.state = State.IDLE;
  31658. this.setInterval(TICK_INTERVAL$2);
  31659. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  31660. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  31661. this.tick();
  31662. }
  31663. onManifestLoading() {
  31664. super.onManifestLoading();
  31665. this.mainDetails = null;
  31666. }
  31667. onMediaDetaching(event, data) {
  31668. this.tracksBuffered = [];
  31669. super.onMediaDetaching(event, data);
  31670. }
  31671. onLevelLoaded(event, data) {
  31672. this.mainDetails = data.details;
  31673. }
  31674. onSubtitleFragProcessed(event, data) {
  31675. const {
  31676. frag,
  31677. success
  31678. } = data;
  31679. if (!this.fragContextChanged(frag)) {
  31680. if (isMediaFragment(frag)) {
  31681. this.fragPrevious = frag;
  31682. }
  31683. this.state = State.IDLE;
  31684. }
  31685. if (!success) {
  31686. return;
  31687. }
  31688. const buffered = this.tracksBuffered[this.currentTrackId];
  31689. if (!buffered) {
  31690. return;
  31691. }
  31692. let timeRange;
  31693. const fragStart = frag.start;
  31694. for (let i2 = 0; i2 < buffered.length; i2++) {
  31695. if (fragStart >= buffered[i2].start && fragStart <= buffered[i2].end) {
  31696. timeRange = buffered[i2];
  31697. break;
  31698. }
  31699. }
  31700. const fragEnd = frag.start + frag.duration;
  31701. if (timeRange) {
  31702. timeRange.end = fragEnd;
  31703. } else {
  31704. timeRange = {
  31705. start: fragStart,
  31706. end: fragEnd
  31707. };
  31708. buffered.push(timeRange);
  31709. }
  31710. this.fragmentTracker.fragBuffered(frag);
  31711. this.fragBufferedComplete(frag, null);
  31712. if (this.media) {
  31713. this.tick();
  31714. }
  31715. }
  31716. onBufferFlushing(event, data) {
  31717. const {
  31718. startOffset,
  31719. endOffset
  31720. } = data;
  31721. if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
  31722. const endOffsetSubtitles = endOffset - 1;
  31723. if (endOffsetSubtitles <= 0) {
  31724. return;
  31725. }
  31726. data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
  31727. this.tracksBuffered.forEach((buffered) => {
  31728. for (let i2 = 0; i2 < buffered.length; ) {
  31729. if (buffered[i2].end <= endOffsetSubtitles) {
  31730. buffered.shift();
  31731. continue;
  31732. } else if (buffered[i2].start < endOffsetSubtitles) {
  31733. buffered[i2].start = endOffsetSubtitles;
  31734. } else {
  31735. break;
  31736. }
  31737. i2++;
  31738. }
  31739. });
  31740. this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE);
  31741. }
  31742. }
  31743. // If something goes wrong, proceed to next frag, if we were processing one.
  31744. onError(event, data) {
  31745. const frag = data.frag;
  31746. if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) {
  31747. if (data.details === ErrorDetails.FRAG_GAP) {
  31748. this.fragmentTracker.fragBuffered(frag, true);
  31749. }
  31750. if (this.fragCurrent) {
  31751. this.fragCurrent.abortRequests();
  31752. }
  31753. if (this.state !== State.STOPPED) {
  31754. this.state = State.IDLE;
  31755. }
  31756. }
  31757. }
  31758. // Got all new subtitle levels.
  31759. onSubtitleTracksUpdated(event, {
  31760. subtitleTracks
  31761. }) {
  31762. if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) {
  31763. this.levels = subtitleTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
  31764. return;
  31765. }
  31766. this.tracksBuffered = [];
  31767. this.levels = subtitleTracks.map((mediaPlaylist) => {
  31768. const level = new Level(mediaPlaylist);
  31769. this.tracksBuffered[level.id] = [];
  31770. return level;
  31771. });
  31772. this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE);
  31773. this.fragPrevious = null;
  31774. this.mediaBuffer = null;
  31775. }
  31776. onSubtitleTrackSwitch(event, data) {
  31777. var _this$levels;
  31778. this.currentTrackId = data.id;
  31779. if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) {
  31780. this.clearInterval();
  31781. return;
  31782. }
  31783. const currentTrack = this.levels[this.currentTrackId];
  31784. if (currentTrack != null && currentTrack.details) {
  31785. this.mediaBuffer = this.mediaBufferTimeRanges;
  31786. } else {
  31787. this.mediaBuffer = null;
  31788. }
  31789. if (currentTrack && this.state !== State.STOPPED) {
  31790. this.setInterval(TICK_INTERVAL$2);
  31791. }
  31792. }
  31793. // Got a new set of subtitle fragments.
  31794. onSubtitleTrackLoaded(event, data) {
  31795. var _track$details;
  31796. const {
  31797. currentTrackId,
  31798. levels
  31799. } = this;
  31800. const {
  31801. details: newDetails,
  31802. id: trackId
  31803. } = data;
  31804. if (!levels) {
  31805. this.warn(`Subtitle tracks were reset while loading level ${trackId}`);
  31806. return;
  31807. }
  31808. const track2 = levels[trackId];
  31809. if (trackId >= levels.length || !track2) {
  31810. return;
  31811. }
  31812. this.log(`Subtitle track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
  31813. this.mediaBuffer = this.mediaBufferTimeRanges;
  31814. let sliding = 0;
  31815. if (newDetails.live || (_track$details = track2.details) != null && _track$details.live) {
  31816. if (newDetails.deltaUpdateFailed) {
  31817. return;
  31818. }
  31819. const mainDetails = this.mainDetails;
  31820. if (!mainDetails) {
  31821. this.startFragRequested = false;
  31822. return;
  31823. }
  31824. const mainSlidingStartFragment = mainDetails.fragments[0];
  31825. if (!track2.details) {
  31826. if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
  31827. alignMediaPlaylistByPDT(newDetails, mainDetails);
  31828. sliding = newDetails.fragmentStart;
  31829. } else if (mainSlidingStartFragment) {
  31830. sliding = mainSlidingStartFragment.start;
  31831. addSliding(newDetails, sliding);
  31832. }
  31833. } else {
  31834. var _this$levelLastLoaded;
  31835. sliding = this.alignPlaylists(newDetails, track2.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  31836. if (sliding === 0 && mainSlidingStartFragment) {
  31837. sliding = mainSlidingStartFragment.start;
  31838. addSliding(newDetails, sliding);
  31839. }
  31840. }
  31841. if (mainDetails && !this.startFragRequested) {
  31842. this.setStartPosition(mainDetails, sliding);
  31843. }
  31844. }
  31845. track2.details = newDetails;
  31846. this.levelLastLoaded = track2;
  31847. if (trackId !== currentTrackId) {
  31848. return;
  31849. }
  31850. this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED, {
  31851. details: newDetails,
  31852. id: trackId,
  31853. groupId: data.groupId
  31854. });
  31855. this.tick();
  31856. if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) {
  31857. const foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0);
  31858. if (!foundFrag) {
  31859. this.warn("Subtitle playlist not aligned with playback");
  31860. track2.details = void 0;
  31861. }
  31862. }
  31863. }
  31864. _handleFragmentLoadComplete(fragLoadedData) {
  31865. const {
  31866. frag,
  31867. payload
  31868. } = fragLoadedData;
  31869. const decryptData = frag.decryptdata;
  31870. const hls = this.hls;
  31871. if (this.fragContextChanged(frag)) {
  31872. return;
  31873. }
  31874. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  31875. const startTime = performance.now();
  31876. this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
  31877. hls.trigger(Events.ERROR, {
  31878. type: ErrorTypes.MEDIA_ERROR,
  31879. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  31880. fatal: false,
  31881. error: err,
  31882. reason: err.message,
  31883. frag
  31884. });
  31885. throw err;
  31886. }).then((decryptedData) => {
  31887. const endTime = performance.now();
  31888. hls.trigger(Events.FRAG_DECRYPTED, {
  31889. frag,
  31890. payload: decryptedData,
  31891. stats: {
  31892. tstart: startTime,
  31893. tdecrypt: endTime
  31894. }
  31895. });
  31896. }).catch((err) => {
  31897. this.warn(`${err.name}: ${err.message}`);
  31898. this.state = State.IDLE;
  31899. });
  31900. }
  31901. }
  31902. doTick() {
  31903. if (!this.media) {
  31904. this.state = State.IDLE;
  31905. return;
  31906. }
  31907. if (this.state === State.IDLE) {
  31908. const {
  31909. currentTrackId,
  31910. levels
  31911. } = this;
  31912. const track2 = levels == null ? void 0 : levels[currentTrackId];
  31913. if (!track2 || !levels.length || !track2.details) {
  31914. return;
  31915. }
  31916. if (this.waitForLive(track2)) {
  31917. return;
  31918. }
  31919. const {
  31920. config
  31921. } = this;
  31922. const currentTime = this.getLoadPosition();
  31923. const bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config.maxBufferHole);
  31924. const {
  31925. end: targetBufferTime,
  31926. len: bufferLen
  31927. } = bufferedInfo;
  31928. const trackDetails = track2.details;
  31929. const maxBufLen = this.hls.maxBufferLength + trackDetails.levelTargetDuration;
  31930. if (bufferLen > maxBufLen) {
  31931. return;
  31932. }
  31933. const fragments = trackDetails.fragments;
  31934. const fragLen = fragments.length;
  31935. const end = trackDetails.edge;
  31936. let foundFrag = null;
  31937. const fragPrevious = this.fragPrevious;
  31938. if (targetBufferTime < end) {
  31939. const tolerance = config.maxFragLookUpTolerance;
  31940. const lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance;
  31941. foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance);
  31942. if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
  31943. foundFrag = fragments[0];
  31944. }
  31945. } else {
  31946. foundFrag = fragments[fragLen - 1];
  31947. }
  31948. foundFrag = this.filterReplacedPrimary(foundFrag, track2.details);
  31949. if (!foundFrag) {
  31950. return;
  31951. }
  31952. const curSNIdx = foundFrag.sn - trackDetails.startSN;
  31953. const prevFrag = fragments[curSNIdx - 1];
  31954. if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) {
  31955. foundFrag = prevFrag;
  31956. }
  31957. if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
  31958. const fragToLoad = this.mapToInitFragWhenRequired(foundFrag);
  31959. if (fragToLoad) {
  31960. this.loadFragment(fragToLoad, track2, targetBufferTime);
  31961. }
  31962. }
  31963. }
  31964. }
  31965. loadFragment(frag, level, targetBufferTime) {
  31966. if (!isMediaFragment(frag)) {
  31967. this._loadInitSegment(frag, level);
  31968. } else {
  31969. super.loadFragment(frag, level, targetBufferTime);
  31970. }
  31971. }
  31972. get mediaBufferTimeRanges() {
  31973. return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []);
  31974. }
  31975. }
  31976. class BufferableInstance {
  31977. constructor(timeranges) {
  31978. this.buffered = void 0;
  31979. const getRange = (name, index2, length) => {
  31980. index2 = index2 >>> 0;
  31981. if (index2 > length - 1) {
  31982. throw new DOMException(`Failed to execute '${name}' on 'TimeRanges': The index provided (${index2}) is greater than the maximum bound (${length})`);
  31983. }
  31984. return timeranges[index2][name];
  31985. };
  31986. this.buffered = {
  31987. get length() {
  31988. return timeranges.length;
  31989. },
  31990. end(index2) {
  31991. return getRange("end", index2, timeranges.length);
  31992. },
  31993. start(index2) {
  31994. return getRange("start", index2, timeranges.length);
  31995. }
  31996. };
  31997. }
  31998. }
  31999. const specialCea608CharsCodes = {
  32000. 42: 225,
  32001. // lowercase a, acute accent
  32002. 92: 233,
  32003. // lowercase e, acute accent
  32004. 94: 237,
  32005. // lowercase i, acute accent
  32006. 95: 243,
  32007. // lowercase o, acute accent
  32008. 96: 250,
  32009. // lowercase u, acute accent
  32010. 123: 231,
  32011. // lowercase c with cedilla
  32012. 124: 247,
  32013. // division symbol
  32014. 125: 209,
  32015. // uppercase N tilde
  32016. 126: 241,
  32017. // lowercase n tilde
  32018. 127: 9608,
  32019. // Full block
  32020. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  32021. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  32022. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  32023. 128: 174,
  32024. // Registered symbol (R)
  32025. 129: 176,
  32026. // degree sign
  32027. 130: 189,
  32028. // 1/2 symbol
  32029. 131: 191,
  32030. // Inverted (open) question mark
  32031. 132: 8482,
  32032. // Trademark symbol (TM)
  32033. 133: 162,
  32034. // Cents symbol
  32035. 134: 163,
  32036. // Pounds sterling
  32037. 135: 9834,
  32038. // Music 8'th note
  32039. 136: 224,
  32040. // lowercase a, grave accent
  32041. 137: 32,
  32042. // transparent space (regular)
  32043. 138: 232,
  32044. // lowercase e, grave accent
  32045. 139: 226,
  32046. // lowercase a, circumflex accent
  32047. 140: 234,
  32048. // lowercase e, circumflex accent
  32049. 141: 238,
  32050. // lowercase i, circumflex accent
  32051. 142: 244,
  32052. // lowercase o, circumflex accent
  32053. 143: 251,
  32054. // lowercase u, circumflex accent
  32055. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  32056. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  32057. 144: 193,
  32058. // capital letter A with acute
  32059. 145: 201,
  32060. // capital letter E with acute
  32061. 146: 211,
  32062. // capital letter O with acute
  32063. 147: 218,
  32064. // capital letter U with acute
  32065. 148: 220,
  32066. // capital letter U with diaresis
  32067. 149: 252,
  32068. // lowercase letter U with diaeresis
  32069. 150: 8216,
  32070. // opening single quote
  32071. 151: 161,
  32072. // inverted exclamation mark
  32073. 152: 42,
  32074. // asterisk
  32075. 153: 8217,
  32076. // closing single quote
  32077. 154: 9473,
  32078. // box drawings heavy horizontal
  32079. 155: 169,
  32080. // copyright sign
  32081. 156: 8480,
  32082. // Service mark
  32083. 157: 8226,
  32084. // (round) bullet
  32085. 158: 8220,
  32086. // Left double quotation mark
  32087. 159: 8221,
  32088. // Right double quotation mark
  32089. 160: 192,
  32090. // uppercase A, grave accent
  32091. 161: 194,
  32092. // uppercase A, circumflex
  32093. 162: 199,
  32094. // uppercase C with cedilla
  32095. 163: 200,
  32096. // uppercase E, grave accent
  32097. 164: 202,
  32098. // uppercase E, circumflex
  32099. 165: 203,
  32100. // capital letter E with diaresis
  32101. 166: 235,
  32102. // lowercase letter e with diaresis
  32103. 167: 206,
  32104. // uppercase I, circumflex
  32105. 168: 207,
  32106. // uppercase I, with diaresis
  32107. 169: 239,
  32108. // lowercase i, with diaresis
  32109. 170: 212,
  32110. // uppercase O, circumflex
  32111. 171: 217,
  32112. // uppercase U, grave accent
  32113. 172: 249,
  32114. // lowercase u, grave accent
  32115. 173: 219,
  32116. // uppercase U, circumflex
  32117. 174: 171,
  32118. // left-pointing double angle quotation mark
  32119. 175: 187,
  32120. // right-pointing double angle quotation mark
  32121. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  32122. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  32123. 176: 195,
  32124. // Uppercase A, tilde
  32125. 177: 227,
  32126. // Lowercase a, tilde
  32127. 178: 205,
  32128. // Uppercase I, acute accent
  32129. 179: 204,
  32130. // Uppercase I, grave accent
  32131. 180: 236,
  32132. // Lowercase i, grave accent
  32133. 181: 210,
  32134. // Uppercase O, grave accent
  32135. 182: 242,
  32136. // Lowercase o, grave accent
  32137. 183: 213,
  32138. // Uppercase O, tilde
  32139. 184: 245,
  32140. // Lowercase o, tilde
  32141. 185: 123,
  32142. // Open curly brace
  32143. 186: 125,
  32144. // Closing curly brace
  32145. 187: 92,
  32146. // Backslash
  32147. 188: 94,
  32148. // Caret
  32149. 189: 95,
  32150. // Underscore
  32151. 190: 124,
  32152. // Pipe (vertical line)
  32153. 191: 8764,
  32154. // Tilde operator
  32155. 192: 196,
  32156. // Uppercase A, umlaut
  32157. 193: 228,
  32158. // Lowercase A, umlaut
  32159. 194: 214,
  32160. // Uppercase O, umlaut
  32161. 195: 246,
  32162. // Lowercase o, umlaut
  32163. 196: 223,
  32164. // Esszett (sharp S)
  32165. 197: 165,
  32166. // Yen symbol
  32167. 198: 164,
  32168. // Generic currency sign
  32169. 199: 9475,
  32170. // Box drawings heavy vertical
  32171. 200: 197,
  32172. // Uppercase A, ring
  32173. 201: 229,
  32174. // Lowercase A, ring
  32175. 202: 216,
  32176. // Uppercase O, stroke
  32177. 203: 248,
  32178. // Lowercase o, strok
  32179. 204: 9487,
  32180. // Box drawings heavy down and right
  32181. 205: 9491,
  32182. // Box drawings heavy down and left
  32183. 206: 9495,
  32184. // Box drawings heavy up and right
  32185. 207: 9499
  32186. // Box drawings heavy up and left
  32187. };
  32188. const getCharForByte = (byte) => String.fromCharCode(specialCea608CharsCodes[byte] || byte);
  32189. const NR_ROWS = 15;
  32190. const NR_COLS = 100;
  32191. const rowsLowCh1 = {
  32192. 17: 1,
  32193. 18: 3,
  32194. 21: 5,
  32195. 22: 7,
  32196. 23: 9,
  32197. 16: 11,
  32198. 19: 12,
  32199. 20: 14
  32200. };
  32201. const rowsHighCh1 = {
  32202. 17: 2,
  32203. 18: 4,
  32204. 21: 6,
  32205. 22: 8,
  32206. 23: 10,
  32207. 19: 13,
  32208. 20: 15
  32209. };
  32210. const rowsLowCh2 = {
  32211. 25: 1,
  32212. 26: 3,
  32213. 29: 5,
  32214. 30: 7,
  32215. 31: 9,
  32216. 24: 11,
  32217. 27: 12,
  32218. 28: 14
  32219. };
  32220. const rowsHighCh2 = {
  32221. 25: 2,
  32222. 26: 4,
  32223. 29: 6,
  32224. 30: 8,
  32225. 31: 10,
  32226. 27: 13,
  32227. 28: 15
  32228. };
  32229. const backgroundColors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "black", "transparent"];
  32230. class CaptionsLogger {
  32231. constructor() {
  32232. this.time = null;
  32233. this.verboseLevel = 0;
  32234. }
  32235. log(severity, msg) {
  32236. if (this.verboseLevel >= severity) {
  32237. const m2 = typeof msg === "function" ? msg() : msg;
  32238. logger.log(`${this.time} [${severity}] ${m2}`);
  32239. }
  32240. }
  32241. }
  32242. const numArrayToHexArray = function numArrayToHexArray2(numArray) {
  32243. const hexArray = [];
  32244. for (let j2 = 0; j2 < numArray.length; j2++) {
  32245. hexArray.push(numArray[j2].toString(16));
  32246. }
  32247. return hexArray;
  32248. };
  32249. class PenState {
  32250. constructor() {
  32251. this.foreground = "white";
  32252. this.underline = false;
  32253. this.italics = false;
  32254. this.background = "black";
  32255. this.flash = false;
  32256. }
  32257. reset() {
  32258. this.foreground = "white";
  32259. this.underline = false;
  32260. this.italics = false;
  32261. this.background = "black";
  32262. this.flash = false;
  32263. }
  32264. setStyles(styles) {
  32265. const attribs = ["foreground", "underline", "italics", "background", "flash"];
  32266. for (let i2 = 0; i2 < attribs.length; i2++) {
  32267. const style = attribs[i2];
  32268. if (styles.hasOwnProperty(style)) {
  32269. this[style] = styles[style];
  32270. }
  32271. }
  32272. }
  32273. isDefault() {
  32274. return this.foreground === "white" && !this.underline && !this.italics && this.background === "black" && !this.flash;
  32275. }
  32276. equals(other) {
  32277. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  32278. }
  32279. copy(newPenState) {
  32280. this.foreground = newPenState.foreground;
  32281. this.underline = newPenState.underline;
  32282. this.italics = newPenState.italics;
  32283. this.background = newPenState.background;
  32284. this.flash = newPenState.flash;
  32285. }
  32286. toString() {
  32287. return "color=" + this.foreground + ", underline=" + this.underline + ", italics=" + this.italics + ", background=" + this.background + ", flash=" + this.flash;
  32288. }
  32289. }
  32290. class StyledUnicodeChar {
  32291. constructor() {
  32292. this.uchar = " ";
  32293. this.penState = new PenState();
  32294. }
  32295. reset() {
  32296. this.uchar = " ";
  32297. this.penState.reset();
  32298. }
  32299. setChar(uchar, newPenState) {
  32300. this.uchar = uchar;
  32301. this.penState.copy(newPenState);
  32302. }
  32303. setPenState(newPenState) {
  32304. this.penState.copy(newPenState);
  32305. }
  32306. equals(other) {
  32307. return this.uchar === other.uchar && this.penState.equals(other.penState);
  32308. }
  32309. copy(newChar) {
  32310. this.uchar = newChar.uchar;
  32311. this.penState.copy(newChar.penState);
  32312. }
  32313. isEmpty() {
  32314. return this.uchar === " " && this.penState.isDefault();
  32315. }
  32316. }
  32317. class Row {
  32318. constructor(logger2) {
  32319. this.chars = [];
  32320. this.pos = 0;
  32321. this.currPenState = new PenState();
  32322. this.cueStartTime = null;
  32323. this.logger = void 0;
  32324. for (let i2 = 0; i2 < NR_COLS; i2++) {
  32325. this.chars.push(new StyledUnicodeChar());
  32326. }
  32327. this.logger = logger2;
  32328. }
  32329. equals(other) {
  32330. for (let i2 = 0; i2 < NR_COLS; i2++) {
  32331. if (!this.chars[i2].equals(other.chars[i2])) {
  32332. return false;
  32333. }
  32334. }
  32335. return true;
  32336. }
  32337. copy(other) {
  32338. for (let i2 = 0; i2 < NR_COLS; i2++) {
  32339. this.chars[i2].copy(other.chars[i2]);
  32340. }
  32341. }
  32342. isEmpty() {
  32343. let empty = true;
  32344. for (let i2 = 0; i2 < NR_COLS; i2++) {
  32345. if (!this.chars[i2].isEmpty()) {
  32346. empty = false;
  32347. break;
  32348. }
  32349. }
  32350. return empty;
  32351. }
  32352. /**
  32353. * Set the cursor to a valid column.
  32354. */
  32355. setCursor(absPos) {
  32356. if (this.pos !== absPos) {
  32357. this.pos = absPos;
  32358. }
  32359. if (this.pos < 0) {
  32360. this.logger.log(3, "Negative cursor position " + this.pos);
  32361. this.pos = 0;
  32362. } else if (this.pos > NR_COLS) {
  32363. this.logger.log(3, "Too large cursor position " + this.pos);
  32364. this.pos = NR_COLS;
  32365. }
  32366. }
  32367. /**
  32368. * Move the cursor relative to current position.
  32369. */
  32370. moveCursor(relPos) {
  32371. const newPos = this.pos + relPos;
  32372. if (relPos > 1) {
  32373. for (let i2 = this.pos + 1; i2 < newPos + 1; i2++) {
  32374. this.chars[i2].setPenState(this.currPenState);
  32375. }
  32376. }
  32377. this.setCursor(newPos);
  32378. }
  32379. /**
  32380. * Backspace, move one step back and clear character.
  32381. */
  32382. backSpace() {
  32383. this.moveCursor(-1);
  32384. this.chars[this.pos].setChar(" ", this.currPenState);
  32385. }
  32386. insertChar(byte) {
  32387. if (byte >= 144) {
  32388. this.backSpace();
  32389. }
  32390. const char = getCharForByte(byte);
  32391. if (this.pos >= NR_COLS) {
  32392. this.logger.log(0, () => "Cannot insert " + byte.toString(16) + " (" + char + ") at position " + this.pos + ". Skipping it!");
  32393. return;
  32394. }
  32395. this.chars[this.pos].setChar(char, this.currPenState);
  32396. this.moveCursor(1);
  32397. }
  32398. clearFromPos(startPos) {
  32399. let i2;
  32400. for (i2 = startPos; i2 < NR_COLS; i2++) {
  32401. this.chars[i2].reset();
  32402. }
  32403. }
  32404. clear() {
  32405. this.clearFromPos(0);
  32406. this.pos = 0;
  32407. this.currPenState.reset();
  32408. }
  32409. clearToEndOfRow() {
  32410. this.clearFromPos(this.pos);
  32411. }
  32412. getTextString() {
  32413. const chars = [];
  32414. let empty = true;
  32415. for (let i2 = 0; i2 < NR_COLS; i2++) {
  32416. const char = this.chars[i2].uchar;
  32417. if (char !== " ") {
  32418. empty = false;
  32419. }
  32420. chars.push(char);
  32421. }
  32422. if (empty) {
  32423. return "";
  32424. } else {
  32425. return chars.join("");
  32426. }
  32427. }
  32428. setPenStyles(styles) {
  32429. this.currPenState.setStyles(styles);
  32430. const currChar = this.chars[this.pos];
  32431. currChar.setPenState(this.currPenState);
  32432. }
  32433. }
  32434. class CaptionScreen {
  32435. constructor(logger2) {
  32436. this.rows = [];
  32437. this.currRow = NR_ROWS - 1;
  32438. this.nrRollUpRows = null;
  32439. this.lastOutputScreen = null;
  32440. this.logger = void 0;
  32441. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  32442. this.rows.push(new Row(logger2));
  32443. }
  32444. this.logger = logger2;
  32445. }
  32446. reset() {
  32447. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  32448. this.rows[i2].clear();
  32449. }
  32450. this.currRow = NR_ROWS - 1;
  32451. }
  32452. equals(other) {
  32453. let equal = true;
  32454. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  32455. if (!this.rows[i2].equals(other.rows[i2])) {
  32456. equal = false;
  32457. break;
  32458. }
  32459. }
  32460. return equal;
  32461. }
  32462. copy(other) {
  32463. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  32464. this.rows[i2].copy(other.rows[i2]);
  32465. }
  32466. }
  32467. isEmpty() {
  32468. let empty = true;
  32469. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  32470. if (!this.rows[i2].isEmpty()) {
  32471. empty = false;
  32472. break;
  32473. }
  32474. }
  32475. return empty;
  32476. }
  32477. backSpace() {
  32478. const row = this.rows[this.currRow];
  32479. row.backSpace();
  32480. }
  32481. clearToEndOfRow() {
  32482. const row = this.rows[this.currRow];
  32483. row.clearToEndOfRow();
  32484. }
  32485. /**
  32486. * Insert a character (without styling) in the current row.
  32487. */
  32488. insertChar(char) {
  32489. const row = this.rows[this.currRow];
  32490. row.insertChar(char);
  32491. }
  32492. setPen(styles) {
  32493. const row = this.rows[this.currRow];
  32494. row.setPenStyles(styles);
  32495. }
  32496. moveCursor(relPos) {
  32497. const row = this.rows[this.currRow];
  32498. row.moveCursor(relPos);
  32499. }
  32500. setCursor(absPos) {
  32501. this.logger.log(2, "setCursor: " + absPos);
  32502. const row = this.rows[this.currRow];
  32503. row.setCursor(absPos);
  32504. }
  32505. setPAC(pacData) {
  32506. this.logger.log(2, () => "pacData = " + stringify(pacData));
  32507. let newRow = pacData.row - 1;
  32508. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  32509. newRow = this.nrRollUpRows - 1;
  32510. }
  32511. if (this.nrRollUpRows && this.currRow !== newRow) {
  32512. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  32513. this.rows[i2].clear();
  32514. }
  32515. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  32516. const lastOutputScreen = this.lastOutputScreen;
  32517. if (lastOutputScreen) {
  32518. const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  32519. const time = this.logger.time;
  32520. if (prevLineTime !== null && time !== null && prevLineTime < time) {
  32521. for (let i2 = 0; i2 < this.nrRollUpRows; i2++) {
  32522. this.rows[newRow - this.nrRollUpRows + i2 + 1].copy(lastOutputScreen.rows[topRowIndex + i2]);
  32523. }
  32524. }
  32525. }
  32526. }
  32527. this.currRow = newRow;
  32528. const row = this.rows[this.currRow];
  32529. if (pacData.indent !== null) {
  32530. const indent = pacData.indent;
  32531. const prevPos = Math.max(indent - 1, 0);
  32532. row.setCursor(pacData.indent);
  32533. pacData.color = row.chars[prevPos].penState.foreground;
  32534. }
  32535. const styles = {
  32536. foreground: pacData.color,
  32537. underline: pacData.underline,
  32538. italics: pacData.italics,
  32539. background: "black",
  32540. flash: false
  32541. };
  32542. this.setPen(styles);
  32543. }
  32544. /**
  32545. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  32546. */
  32547. setBkgData(bkgData) {
  32548. this.logger.log(2, () => "bkgData = " + stringify(bkgData));
  32549. this.backSpace();
  32550. this.setPen(bkgData);
  32551. this.insertChar(32);
  32552. }
  32553. setRollUpRows(nrRows) {
  32554. this.nrRollUpRows = nrRows;
  32555. }
  32556. rollUp() {
  32557. if (this.nrRollUpRows === null) {
  32558. this.logger.log(3, "roll_up but nrRollUpRows not set yet");
  32559. return;
  32560. }
  32561. this.logger.log(1, () => this.getDisplayText());
  32562. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  32563. const topRow = this.rows.splice(topRowIndex, 1)[0];
  32564. topRow.clear();
  32565. this.rows.splice(this.currRow, 0, topRow);
  32566. this.logger.log(2, "Rolling up");
  32567. }
  32568. /**
  32569. * Get all non-empty rows with as unicode text.
  32570. */
  32571. getDisplayText(asOneRow) {
  32572. asOneRow = asOneRow || false;
  32573. const displayText = [];
  32574. let text = "";
  32575. let rowNr = -1;
  32576. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  32577. const rowText = this.rows[i2].getTextString();
  32578. if (rowText) {
  32579. rowNr = i2 + 1;
  32580. if (asOneRow) {
  32581. displayText.push("Row " + rowNr + ": '" + rowText + "'");
  32582. } else {
  32583. displayText.push(rowText.trim());
  32584. }
  32585. }
  32586. }
  32587. if (displayText.length > 0) {
  32588. if (asOneRow) {
  32589. text = "[" + displayText.join(" | ") + "]";
  32590. } else {
  32591. text = displayText.join("\n");
  32592. }
  32593. }
  32594. return text;
  32595. }
  32596. getTextAndFormat() {
  32597. return this.rows;
  32598. }
  32599. }
  32600. class Cea608Channel {
  32601. constructor(channelNumber, outputFilter, logger2) {
  32602. this.chNr = void 0;
  32603. this.outputFilter = void 0;
  32604. this.mode = void 0;
  32605. this.verbose = void 0;
  32606. this.displayedMemory = void 0;
  32607. this.nonDisplayedMemory = void 0;
  32608. this.lastOutputScreen = void 0;
  32609. this.currRollUpRow = void 0;
  32610. this.writeScreen = void 0;
  32611. this.cueStartTime = void 0;
  32612. this.logger = void 0;
  32613. this.chNr = channelNumber;
  32614. this.outputFilter = outputFilter;
  32615. this.mode = null;
  32616. this.verbose = 0;
  32617. this.displayedMemory = new CaptionScreen(logger2);
  32618. this.nonDisplayedMemory = new CaptionScreen(logger2);
  32619. this.lastOutputScreen = new CaptionScreen(logger2);
  32620. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  32621. this.writeScreen = this.displayedMemory;
  32622. this.mode = null;
  32623. this.cueStartTime = null;
  32624. this.logger = logger2;
  32625. }
  32626. reset() {
  32627. this.mode = null;
  32628. this.displayedMemory.reset();
  32629. this.nonDisplayedMemory.reset();
  32630. this.lastOutputScreen.reset();
  32631. this.outputFilter.reset();
  32632. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  32633. this.writeScreen = this.displayedMemory;
  32634. this.mode = null;
  32635. this.cueStartTime = null;
  32636. }
  32637. getHandler() {
  32638. return this.outputFilter;
  32639. }
  32640. setHandler(newHandler) {
  32641. this.outputFilter = newHandler;
  32642. }
  32643. setPAC(pacData) {
  32644. this.writeScreen.setPAC(pacData);
  32645. }
  32646. setBkgData(bkgData) {
  32647. this.writeScreen.setBkgData(bkgData);
  32648. }
  32649. setMode(newMode) {
  32650. if (newMode === this.mode) {
  32651. return;
  32652. }
  32653. this.mode = newMode;
  32654. this.logger.log(2, () => "MODE=" + newMode);
  32655. if (this.mode === "MODE_POP-ON") {
  32656. this.writeScreen = this.nonDisplayedMemory;
  32657. } else {
  32658. this.writeScreen = this.displayedMemory;
  32659. this.writeScreen.reset();
  32660. }
  32661. if (this.mode !== "MODE_ROLL-UP") {
  32662. this.displayedMemory.nrRollUpRows = null;
  32663. this.nonDisplayedMemory.nrRollUpRows = null;
  32664. }
  32665. this.mode = newMode;
  32666. }
  32667. insertChars(chars) {
  32668. for (let i2 = 0; i2 < chars.length; i2++) {
  32669. this.writeScreen.insertChar(chars[i2]);
  32670. }
  32671. const screen = this.writeScreen === this.displayedMemory ? "DISP" : "NON_DISP";
  32672. this.logger.log(2, () => screen + ": " + this.writeScreen.getDisplayText(true));
  32673. if (this.mode === "MODE_PAINT-ON" || this.mode === "MODE_ROLL-UP") {
  32674. this.logger.log(1, () => "DISPLAYED: " + this.displayedMemory.getDisplayText(true));
  32675. this.outputDataUpdate();
  32676. }
  32677. }
  32678. ccRCL() {
  32679. this.logger.log(2, "RCL - Resume Caption Loading");
  32680. this.setMode("MODE_POP-ON");
  32681. }
  32682. ccBS() {
  32683. this.logger.log(2, "BS - BackSpace");
  32684. if (this.mode === "MODE_TEXT") {
  32685. return;
  32686. }
  32687. this.writeScreen.backSpace();
  32688. if (this.writeScreen === this.displayedMemory) {
  32689. this.outputDataUpdate();
  32690. }
  32691. }
  32692. ccAOF() {
  32693. }
  32694. ccAON() {
  32695. }
  32696. ccDER() {
  32697. this.logger.log(2, "DER- Delete to End of Row");
  32698. this.writeScreen.clearToEndOfRow();
  32699. this.outputDataUpdate();
  32700. }
  32701. ccRU(nrRows) {
  32702. this.logger.log(2, "RU(" + nrRows + ") - Roll Up");
  32703. this.writeScreen = this.displayedMemory;
  32704. this.setMode("MODE_ROLL-UP");
  32705. this.writeScreen.setRollUpRows(nrRows);
  32706. }
  32707. ccFON() {
  32708. this.logger.log(2, "FON - Flash On");
  32709. this.writeScreen.setPen({
  32710. flash: true
  32711. });
  32712. }
  32713. ccRDC() {
  32714. this.logger.log(2, "RDC - Resume Direct Captioning");
  32715. this.setMode("MODE_PAINT-ON");
  32716. }
  32717. ccTR() {
  32718. this.logger.log(2, "TR");
  32719. this.setMode("MODE_TEXT");
  32720. }
  32721. ccRTD() {
  32722. this.logger.log(2, "RTD");
  32723. this.setMode("MODE_TEXT");
  32724. }
  32725. ccEDM() {
  32726. this.logger.log(2, "EDM - Erase Displayed Memory");
  32727. this.displayedMemory.reset();
  32728. this.outputDataUpdate(true);
  32729. }
  32730. ccCR() {
  32731. this.logger.log(2, "CR - Carriage Return");
  32732. this.writeScreen.rollUp();
  32733. this.outputDataUpdate(true);
  32734. }
  32735. ccENM() {
  32736. this.logger.log(2, "ENM - Erase Non-displayed Memory");
  32737. this.nonDisplayedMemory.reset();
  32738. }
  32739. ccEOC() {
  32740. this.logger.log(2, "EOC - End Of Caption");
  32741. if (this.mode === "MODE_POP-ON") {
  32742. const tmp = this.displayedMemory;
  32743. this.displayedMemory = this.nonDisplayedMemory;
  32744. this.nonDisplayedMemory = tmp;
  32745. this.writeScreen = this.nonDisplayedMemory;
  32746. this.logger.log(1, () => "DISP: " + this.displayedMemory.getDisplayText());
  32747. }
  32748. this.outputDataUpdate(true);
  32749. }
  32750. ccTO(nrCols) {
  32751. this.logger.log(2, "TO(" + nrCols + ") - Tab Offset");
  32752. this.writeScreen.moveCursor(nrCols);
  32753. }
  32754. ccMIDROW(secondByte) {
  32755. const styles = {
  32756. flash: false
  32757. };
  32758. styles.underline = secondByte % 2 === 1;
  32759. styles.italics = secondByte >= 46;
  32760. if (!styles.italics) {
  32761. const colorIndex = Math.floor(secondByte / 2) - 16;
  32762. const colors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta"];
  32763. styles.foreground = colors[colorIndex];
  32764. } else {
  32765. styles.foreground = "white";
  32766. }
  32767. this.logger.log(2, "MIDROW: " + stringify(styles));
  32768. this.writeScreen.setPen(styles);
  32769. }
  32770. outputDataUpdate(dispatch2 = false) {
  32771. const time = this.logger.time;
  32772. if (time === null) {
  32773. return;
  32774. }
  32775. if (this.outputFilter) {
  32776. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  32777. this.cueStartTime = time;
  32778. } else {
  32779. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  32780. this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
  32781. if (dispatch2 && this.outputFilter.dispatchCue) {
  32782. this.outputFilter.dispatchCue();
  32783. }
  32784. this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
  32785. }
  32786. }
  32787. this.lastOutputScreen.copy(this.displayedMemory);
  32788. }
  32789. }
  32790. cueSplitAtTime(t2) {
  32791. if (this.outputFilter) {
  32792. if (!this.displayedMemory.isEmpty()) {
  32793. if (this.outputFilter.newCue) {
  32794. this.outputFilter.newCue(this.cueStartTime, t2, this.displayedMemory);
  32795. }
  32796. this.cueStartTime = t2;
  32797. }
  32798. }
  32799. }
  32800. }
  32801. class Cea608Parser {
  32802. constructor(field, out1, out2) {
  32803. this.channels = void 0;
  32804. this.currentChannel = 0;
  32805. this.cmdHistory = createCmdHistory();
  32806. this.logger = void 0;
  32807. const logger2 = this.logger = new CaptionsLogger();
  32808. this.channels = [null, new Cea608Channel(field, out1, logger2), new Cea608Channel(field + 1, out2, logger2)];
  32809. }
  32810. getHandler(channel) {
  32811. return this.channels[channel].getHandler();
  32812. }
  32813. setHandler(channel, newHandler) {
  32814. this.channels[channel].setHandler(newHandler);
  32815. }
  32816. /**
  32817. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  32818. */
  32819. addData(time, byteList) {
  32820. this.logger.time = time;
  32821. for (let i2 = 0; i2 < byteList.length; i2 += 2) {
  32822. const a2 = byteList[i2] & 127;
  32823. const b2 = byteList[i2 + 1] & 127;
  32824. let cmdFound = false;
  32825. let charsFound = null;
  32826. if (a2 === 0 && b2 === 0) {
  32827. continue;
  32828. } else {
  32829. this.logger.log(3, () => "[" + numArrayToHexArray([byteList[i2], byteList[i2 + 1]]) + "] -> (" + numArrayToHexArray([a2, b2]) + ")");
  32830. }
  32831. const cmdHistory = this.cmdHistory;
  32832. const isControlCode = a2 >= 16 && a2 <= 31;
  32833. if (isControlCode) {
  32834. if (hasCmdRepeated(a2, b2, cmdHistory)) {
  32835. setLastCmd(null, null, cmdHistory);
  32836. this.logger.log(3, () => "Repeated command (" + numArrayToHexArray([a2, b2]) + ") is dropped");
  32837. continue;
  32838. }
  32839. setLastCmd(a2, b2, this.cmdHistory);
  32840. cmdFound = this.parseCmd(a2, b2);
  32841. if (!cmdFound) {
  32842. cmdFound = this.parseMidrow(a2, b2);
  32843. }
  32844. if (!cmdFound) {
  32845. cmdFound = this.parsePAC(a2, b2);
  32846. }
  32847. if (!cmdFound) {
  32848. cmdFound = this.parseBackgroundAttributes(a2, b2);
  32849. }
  32850. } else {
  32851. setLastCmd(null, null, cmdHistory);
  32852. }
  32853. if (!cmdFound) {
  32854. charsFound = this.parseChars(a2, b2);
  32855. if (charsFound) {
  32856. const currChNr = this.currentChannel;
  32857. if (currChNr && currChNr > 0) {
  32858. const channel = this.channels[currChNr];
  32859. channel.insertChars(charsFound);
  32860. } else {
  32861. this.logger.log(2, "No channel found yet. TEXT-MODE?");
  32862. }
  32863. }
  32864. }
  32865. if (!cmdFound && !charsFound) {
  32866. this.logger.log(2, () => "Couldn't parse cleaned data " + numArrayToHexArray([a2, b2]) + " orig: " + numArrayToHexArray([byteList[i2], byteList[i2 + 1]]));
  32867. }
  32868. }
  32869. }
  32870. /**
  32871. * Parse Command.
  32872. * @returns True if a command was found
  32873. */
  32874. parseCmd(a2, b2) {
  32875. const cond1 = (a2 === 20 || a2 === 28 || a2 === 21 || a2 === 29) && b2 >= 32 && b2 <= 47;
  32876. const cond2 = (a2 === 23 || a2 === 31) && b2 >= 33 && b2 <= 35;
  32877. if (!(cond1 || cond2)) {
  32878. return false;
  32879. }
  32880. const chNr = a2 === 20 || a2 === 21 || a2 === 23 ? 1 : 2;
  32881. const channel = this.channels[chNr];
  32882. if (a2 === 20 || a2 === 21 || a2 === 28 || a2 === 29) {
  32883. if (b2 === 32) {
  32884. channel.ccRCL();
  32885. } else if (b2 === 33) {
  32886. channel.ccBS();
  32887. } else if (b2 === 34) {
  32888. channel.ccAOF();
  32889. } else if (b2 === 35) {
  32890. channel.ccAON();
  32891. } else if (b2 === 36) {
  32892. channel.ccDER();
  32893. } else if (b2 === 37) {
  32894. channel.ccRU(2);
  32895. } else if (b2 === 38) {
  32896. channel.ccRU(3);
  32897. } else if (b2 === 39) {
  32898. channel.ccRU(4);
  32899. } else if (b2 === 40) {
  32900. channel.ccFON();
  32901. } else if (b2 === 41) {
  32902. channel.ccRDC();
  32903. } else if (b2 === 42) {
  32904. channel.ccTR();
  32905. } else if (b2 === 43) {
  32906. channel.ccRTD();
  32907. } else if (b2 === 44) {
  32908. channel.ccEDM();
  32909. } else if (b2 === 45) {
  32910. channel.ccCR();
  32911. } else if (b2 === 46) {
  32912. channel.ccENM();
  32913. } else if (b2 === 47) {
  32914. channel.ccEOC();
  32915. }
  32916. } else {
  32917. channel.ccTO(b2 - 32);
  32918. }
  32919. this.currentChannel = chNr;
  32920. return true;
  32921. }
  32922. /**
  32923. * Parse midrow styling command
  32924. */
  32925. parseMidrow(a2, b2) {
  32926. let chNr = 0;
  32927. if ((a2 === 17 || a2 === 25) && b2 >= 32 && b2 <= 47) {
  32928. if (a2 === 17) {
  32929. chNr = 1;
  32930. } else {
  32931. chNr = 2;
  32932. }
  32933. if (chNr !== this.currentChannel) {
  32934. this.logger.log(0, "Mismatch channel in midrow parsing");
  32935. return false;
  32936. }
  32937. const channel = this.channels[chNr];
  32938. if (!channel) {
  32939. return false;
  32940. }
  32941. channel.ccMIDROW(b2);
  32942. this.logger.log(3, () => "MIDROW (" + numArrayToHexArray([a2, b2]) + ")");
  32943. return true;
  32944. }
  32945. return false;
  32946. }
  32947. /**
  32948. * Parse Preable Access Codes (Table 53).
  32949. * @returns {Boolean} Tells if PAC found
  32950. */
  32951. parsePAC(a2, b2) {
  32952. let row;
  32953. const case1 = (a2 >= 17 && a2 <= 23 || a2 >= 25 && a2 <= 31) && b2 >= 64 && b2 <= 127;
  32954. const case2 = (a2 === 16 || a2 === 24) && b2 >= 64 && b2 <= 95;
  32955. if (!(case1 || case2)) {
  32956. return false;
  32957. }
  32958. const chNr = a2 <= 23 ? 1 : 2;
  32959. if (b2 >= 64 && b2 <= 95) {
  32960. row = chNr === 1 ? rowsLowCh1[a2] : rowsLowCh2[a2];
  32961. } else {
  32962. row = chNr === 1 ? rowsHighCh1[a2] : rowsHighCh2[a2];
  32963. }
  32964. const channel = this.channels[chNr];
  32965. if (!channel) {
  32966. return false;
  32967. }
  32968. channel.setPAC(this.interpretPAC(row, b2));
  32969. this.currentChannel = chNr;
  32970. return true;
  32971. }
  32972. /**
  32973. * Interpret the second byte of the pac, and return the information.
  32974. * @returns pacData with style parameters
  32975. */
  32976. interpretPAC(row, byte) {
  32977. let pacIndex;
  32978. const pacData = {
  32979. color: null,
  32980. italics: false,
  32981. indent: null,
  32982. underline: false,
  32983. row
  32984. };
  32985. if (byte > 95) {
  32986. pacIndex = byte - 96;
  32987. } else {
  32988. pacIndex = byte - 64;
  32989. }
  32990. pacData.underline = (pacIndex & 1) === 1;
  32991. if (pacIndex <= 13) {
  32992. pacData.color = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "white"][Math.floor(pacIndex / 2)];
  32993. } else if (pacIndex <= 15) {
  32994. pacData.italics = true;
  32995. pacData.color = "white";
  32996. } else {
  32997. pacData.indent = Math.floor((pacIndex - 16) / 2) * 4;
  32998. }
  32999. return pacData;
  33000. }
  33001. /**
  33002. * Parse characters.
  33003. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  33004. */
  33005. parseChars(a2, b2) {
  33006. let channelNr;
  33007. let charCodes = null;
  33008. let charCode1 = null;
  33009. if (a2 >= 25) {
  33010. channelNr = 2;
  33011. charCode1 = a2 - 8;
  33012. } else {
  33013. channelNr = 1;
  33014. charCode1 = a2;
  33015. }
  33016. if (charCode1 >= 17 && charCode1 <= 19) {
  33017. let oneCode;
  33018. if (charCode1 === 17) {
  33019. oneCode = b2 + 80;
  33020. } else if (charCode1 === 18) {
  33021. oneCode = b2 + 112;
  33022. } else {
  33023. oneCode = b2 + 144;
  33024. }
  33025. this.logger.log(2, () => "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
  33026. charCodes = [oneCode];
  33027. } else if (a2 >= 32 && a2 <= 127) {
  33028. charCodes = b2 === 0 ? [a2] : [a2, b2];
  33029. }
  33030. if (charCodes) {
  33031. this.logger.log(3, () => "Char codes = " + numArrayToHexArray(charCodes).join(","));
  33032. }
  33033. return charCodes;
  33034. }
  33035. /**
  33036. * Parse extended background attributes as well as new foreground color black.
  33037. * @returns True if background attributes are found
  33038. */
  33039. parseBackgroundAttributes(a2, b2) {
  33040. const case1 = (a2 === 16 || a2 === 24) && b2 >= 32 && b2 <= 47;
  33041. const case2 = (a2 === 23 || a2 === 31) && b2 >= 45 && b2 <= 47;
  33042. if (!(case1 || case2)) {
  33043. return false;
  33044. }
  33045. let index2;
  33046. const bkgData = {};
  33047. if (a2 === 16 || a2 === 24) {
  33048. index2 = Math.floor((b2 - 32) / 2);
  33049. bkgData.background = backgroundColors[index2];
  33050. if (b2 % 2 === 1) {
  33051. bkgData.background = bkgData.background + "_semi";
  33052. }
  33053. } else if (b2 === 45) {
  33054. bkgData.background = "transparent";
  33055. } else {
  33056. bkgData.foreground = "black";
  33057. if (b2 === 47) {
  33058. bkgData.underline = true;
  33059. }
  33060. }
  33061. const chNr = a2 <= 23 ? 1 : 2;
  33062. const channel = this.channels[chNr];
  33063. channel.setBkgData(bkgData);
  33064. return true;
  33065. }
  33066. /**
  33067. * Reset state of parser and its channels.
  33068. */
  33069. reset() {
  33070. for (let i2 = 0; i2 < Object.keys(this.channels).length; i2++) {
  33071. const channel = this.channels[i2];
  33072. if (channel) {
  33073. channel.reset();
  33074. }
  33075. }
  33076. setLastCmd(null, null, this.cmdHistory);
  33077. }
  33078. /**
  33079. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  33080. */
  33081. cueSplitAtTime(t2) {
  33082. for (let i2 = 0; i2 < this.channels.length; i2++) {
  33083. const channel = this.channels[i2];
  33084. if (channel) {
  33085. channel.cueSplitAtTime(t2);
  33086. }
  33087. }
  33088. }
  33089. }
  33090. function setLastCmd(a2, b2, cmdHistory) {
  33091. cmdHistory.a = a2;
  33092. cmdHistory.b = b2;
  33093. }
  33094. function hasCmdRepeated(a2, b2, cmdHistory) {
  33095. return cmdHistory.a === a2 && cmdHistory.b === b2;
  33096. }
  33097. function createCmdHistory() {
  33098. return {
  33099. a: null,
  33100. b: null
  33101. };
  33102. }
  33103. var VTTCue = function() {
  33104. if (optionalSelf != null && optionalSelf.VTTCue) {
  33105. return self.VTTCue;
  33106. }
  33107. const AllowedDirections = ["", "lr", "rl"];
  33108. const AllowedAlignments = ["start", "middle", "end", "left", "right"];
  33109. function isAllowedValue(allowed, value) {
  33110. if (typeof value !== "string") {
  33111. return false;
  33112. }
  33113. if (!Array.isArray(allowed)) {
  33114. return false;
  33115. }
  33116. const lcValue = value.toLowerCase();
  33117. if (~allowed.indexOf(lcValue)) {
  33118. return lcValue;
  33119. }
  33120. return false;
  33121. }
  33122. function findDirectionSetting(value) {
  33123. return isAllowedValue(AllowedDirections, value);
  33124. }
  33125. function findAlignSetting(value) {
  33126. return isAllowedValue(AllowedAlignments, value);
  33127. }
  33128. function extend2(obj, ...rest) {
  33129. let i2 = 1;
  33130. for (; i2 < arguments.length; i2++) {
  33131. const cobj = arguments[i2];
  33132. for (const p2 in cobj) {
  33133. obj[p2] = cobj[p2];
  33134. }
  33135. }
  33136. return obj;
  33137. }
  33138. function VTTCue2(startTime, endTime, text) {
  33139. const cue = this;
  33140. const baseObj = {
  33141. enumerable: true
  33142. };
  33143. cue.hasBeenReset = false;
  33144. let _id = "";
  33145. let _pauseOnExit = false;
  33146. let _startTime = startTime;
  33147. let _endTime = endTime;
  33148. let _text = text;
  33149. let _region = null;
  33150. let _vertical = "";
  33151. let _snapToLines = true;
  33152. let _line = "auto";
  33153. let _lineAlign = "start";
  33154. let _position = 50;
  33155. let _positionAlign = "middle";
  33156. let _size = 50;
  33157. let _align = "middle";
  33158. Object.defineProperty(cue, "id", extend2({}, baseObj, {
  33159. get: function() {
  33160. return _id;
  33161. },
  33162. set: function(value) {
  33163. _id = "" + value;
  33164. }
  33165. }));
  33166. Object.defineProperty(cue, "pauseOnExit", extend2({}, baseObj, {
  33167. get: function() {
  33168. return _pauseOnExit;
  33169. },
  33170. set: function(value) {
  33171. _pauseOnExit = !!value;
  33172. }
  33173. }));
  33174. Object.defineProperty(cue, "startTime", extend2({}, baseObj, {
  33175. get: function() {
  33176. return _startTime;
  33177. },
  33178. set: function(value) {
  33179. if (typeof value !== "number") {
  33180. throw new TypeError("Start time must be set to a number.");
  33181. }
  33182. _startTime = value;
  33183. this.hasBeenReset = true;
  33184. }
  33185. }));
  33186. Object.defineProperty(cue, "endTime", extend2({}, baseObj, {
  33187. get: function() {
  33188. return _endTime;
  33189. },
  33190. set: function(value) {
  33191. if (typeof value !== "number") {
  33192. throw new TypeError("End time must be set to a number.");
  33193. }
  33194. _endTime = value;
  33195. this.hasBeenReset = true;
  33196. }
  33197. }));
  33198. Object.defineProperty(cue, "text", extend2({}, baseObj, {
  33199. get: function() {
  33200. return _text;
  33201. },
  33202. set: function(value) {
  33203. _text = "" + value;
  33204. this.hasBeenReset = true;
  33205. }
  33206. }));
  33207. Object.defineProperty(cue, "region", extend2({}, baseObj, {
  33208. get: function() {
  33209. return _region;
  33210. },
  33211. set: function(value) {
  33212. _region = value;
  33213. this.hasBeenReset = true;
  33214. }
  33215. }));
  33216. Object.defineProperty(cue, "vertical", extend2({}, baseObj, {
  33217. get: function() {
  33218. return _vertical;
  33219. },
  33220. set: function(value) {
  33221. const setting = findDirectionSetting(value);
  33222. if (setting === false) {
  33223. throw new SyntaxError("An invalid or illegal string was specified.");
  33224. }
  33225. _vertical = setting;
  33226. this.hasBeenReset = true;
  33227. }
  33228. }));
  33229. Object.defineProperty(cue, "snapToLines", extend2({}, baseObj, {
  33230. get: function() {
  33231. return _snapToLines;
  33232. },
  33233. set: function(value) {
  33234. _snapToLines = !!value;
  33235. this.hasBeenReset = true;
  33236. }
  33237. }));
  33238. Object.defineProperty(cue, "line", extend2({}, baseObj, {
  33239. get: function() {
  33240. return _line;
  33241. },
  33242. set: function(value) {
  33243. if (typeof value !== "number" && value !== "auto") {
  33244. throw new SyntaxError("An invalid number or illegal string was specified.");
  33245. }
  33246. _line = value;
  33247. this.hasBeenReset = true;
  33248. }
  33249. }));
  33250. Object.defineProperty(cue, "lineAlign", extend2({}, baseObj, {
  33251. get: function() {
  33252. return _lineAlign;
  33253. },
  33254. set: function(value) {
  33255. const setting = findAlignSetting(value);
  33256. if (!setting) {
  33257. throw new SyntaxError("An invalid or illegal string was specified.");
  33258. }
  33259. _lineAlign = setting;
  33260. this.hasBeenReset = true;
  33261. }
  33262. }));
  33263. Object.defineProperty(cue, "position", extend2({}, baseObj, {
  33264. get: function() {
  33265. return _position;
  33266. },
  33267. set: function(value) {
  33268. if (value < 0 || value > 100) {
  33269. throw new Error("Position must be between 0 and 100.");
  33270. }
  33271. _position = value;
  33272. this.hasBeenReset = true;
  33273. }
  33274. }));
  33275. Object.defineProperty(cue, "positionAlign", extend2({}, baseObj, {
  33276. get: function() {
  33277. return _positionAlign;
  33278. },
  33279. set: function(value) {
  33280. const setting = findAlignSetting(value);
  33281. if (!setting) {
  33282. throw new SyntaxError("An invalid or illegal string was specified.");
  33283. }
  33284. _positionAlign = setting;
  33285. this.hasBeenReset = true;
  33286. }
  33287. }));
  33288. Object.defineProperty(cue, "size", extend2({}, baseObj, {
  33289. get: function() {
  33290. return _size;
  33291. },
  33292. set: function(value) {
  33293. if (value < 0 || value > 100) {
  33294. throw new Error("Size must be between 0 and 100.");
  33295. }
  33296. _size = value;
  33297. this.hasBeenReset = true;
  33298. }
  33299. }));
  33300. Object.defineProperty(cue, "align", extend2({}, baseObj, {
  33301. get: function() {
  33302. return _align;
  33303. },
  33304. set: function(value) {
  33305. const setting = findAlignSetting(value);
  33306. if (!setting) {
  33307. throw new SyntaxError("An invalid or illegal string was specified.");
  33308. }
  33309. _align = setting;
  33310. this.hasBeenReset = true;
  33311. }
  33312. }));
  33313. cue.displayState = void 0;
  33314. }
  33315. VTTCue2.prototype.getCueAsHTML = function() {
  33316. const WebVTT = self.WebVTT;
  33317. return WebVTT.convertCueToDOMTree(self, this.text);
  33318. };
  33319. return VTTCue2;
  33320. }();
  33321. class StringDecoder {
  33322. decode(data, options) {
  33323. if (!data) {
  33324. return "";
  33325. }
  33326. if (typeof data !== "string") {
  33327. throw new Error("Error - expected string data.");
  33328. }
  33329. return decodeURIComponent(encodeURIComponent(data));
  33330. }
  33331. }
  33332. function parseTimeStamp(input) {
  33333. function computeSeconds(h2, m3, s2, f2) {
  33334. return (h2 | 0) * 3600 + (m3 | 0) * 60 + (s2 | 0) + parseFloat(f2 || 0);
  33335. }
  33336. const m2 = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
  33337. if (!m2) {
  33338. return null;
  33339. }
  33340. if (parseFloat(m2[2]) > 59) {
  33341. return computeSeconds(m2[2], m2[3], 0, m2[4]);
  33342. }
  33343. return computeSeconds(m2[1], m2[2], m2[3], m2[4]);
  33344. }
  33345. class Settings {
  33346. constructor() {
  33347. this.values = /* @__PURE__ */ Object.create(null);
  33348. }
  33349. // Only accept the first assignment to any key.
  33350. set(k, v2) {
  33351. if (!this.get(k) && v2 !== "") {
  33352. this.values[k] = v2;
  33353. }
  33354. }
  33355. // Return the value for a key, or a default value.
  33356. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  33357. // a number of possible default values as properties where 'defaultKey' is
  33358. // the key of the property that will be chosen; otherwise it's assumed to be
  33359. // a single value.
  33360. get(k, dflt, defaultKey) {
  33361. if (defaultKey) {
  33362. return this.has(k) ? this.values[k] : dflt[defaultKey];
  33363. }
  33364. return this.has(k) ? this.values[k] : dflt;
  33365. }
  33366. // Check whether we have a value for a key.
  33367. has(k) {
  33368. return k in this.values;
  33369. }
  33370. // Accept a setting if its one of the given alternatives.
  33371. alt(k, v2, a2) {
  33372. for (let n2 = 0; n2 < a2.length; ++n2) {
  33373. if (v2 === a2[n2]) {
  33374. this.set(k, v2);
  33375. break;
  33376. }
  33377. }
  33378. }
  33379. // Accept a setting if its a valid (signed) integer.
  33380. integer(k, v2) {
  33381. if (/^-?\d+$/.test(v2)) {
  33382. this.set(k, parseInt(v2, 10));
  33383. }
  33384. }
  33385. // Accept a setting if its a valid percentage.
  33386. percent(k, v2) {
  33387. if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v2)) {
  33388. const percent = parseFloat(v2);
  33389. if (percent >= 0 && percent <= 100) {
  33390. this.set(k, percent);
  33391. return true;
  33392. }
  33393. }
  33394. return false;
  33395. }
  33396. }
  33397. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  33398. const groups = groupDelim ? input.split(groupDelim) : [input];
  33399. for (const i2 in groups) {
  33400. if (typeof groups[i2] !== "string") {
  33401. continue;
  33402. }
  33403. const kv = groups[i2].split(keyValueDelim);
  33404. if (kv.length !== 2) {
  33405. continue;
  33406. }
  33407. const k = kv[0];
  33408. const v2 = kv[1];
  33409. callback(k, v2);
  33410. }
  33411. }
  33412. const defaults = new VTTCue(0, 0, "");
  33413. const center = defaults.align === "middle" ? "middle" : "center";
  33414. function parseCue(input, cue, regionList) {
  33415. const oInput = input;
  33416. function consumeTimeStamp() {
  33417. const ts2 = parseTimeStamp(input);
  33418. if (ts2 === null) {
  33419. throw new Error("Malformed timestamp: " + oInput);
  33420. }
  33421. input = input.replace(/^[^\sa-zA-Z-]+/, "");
  33422. return ts2;
  33423. }
  33424. function consumeCueSettings(input2, cue2) {
  33425. const settings = new Settings();
  33426. parseOptions(input2, function(k, v2) {
  33427. let vals;
  33428. switch (k) {
  33429. case "region":
  33430. for (let i2 = regionList.length - 1; i2 >= 0; i2--) {
  33431. if (regionList[i2].id === v2) {
  33432. settings.set(k, regionList[i2].region);
  33433. break;
  33434. }
  33435. }
  33436. break;
  33437. case "vertical":
  33438. settings.alt(k, v2, ["rl", "lr"]);
  33439. break;
  33440. case "line":
  33441. vals = v2.split(",");
  33442. settings.integer(k, vals[0]);
  33443. if (settings.percent(k, vals[0])) {
  33444. settings.set("snapToLines", false);
  33445. }
  33446. settings.alt(k, vals[0], ["auto"]);
  33447. if (vals.length === 2) {
  33448. settings.alt("lineAlign", vals[1], ["start", center, "end"]);
  33449. }
  33450. break;
  33451. case "position":
  33452. vals = v2.split(",");
  33453. settings.percent(k, vals[0]);
  33454. if (vals.length === 2) {
  33455. settings.alt("positionAlign", vals[1], ["start", center, "end", "line-left", "line-right", "auto"]);
  33456. }
  33457. break;
  33458. case "size":
  33459. settings.percent(k, v2);
  33460. break;
  33461. case "align":
  33462. settings.alt(k, v2, ["start", center, "end", "left", "right"]);
  33463. break;
  33464. }
  33465. }, /:/, /\s/);
  33466. cue2.region = settings.get("region", null);
  33467. cue2.vertical = settings.get("vertical", "");
  33468. let line = settings.get("line", "auto");
  33469. if (line === "auto" && defaults.line === -1) {
  33470. line = -1;
  33471. }
  33472. cue2.line = line;
  33473. cue2.lineAlign = settings.get("lineAlign", "start");
  33474. cue2.snapToLines = settings.get("snapToLines", true);
  33475. cue2.size = settings.get("size", 100);
  33476. cue2.align = settings.get("align", center);
  33477. let position = settings.get("position", "auto");
  33478. if (position === "auto" && defaults.position === 50) {
  33479. position = cue2.align === "start" || cue2.align === "left" ? 0 : cue2.align === "end" || cue2.align === "right" ? 100 : 50;
  33480. }
  33481. cue2.position = position;
  33482. }
  33483. function skipWhitespace() {
  33484. input = input.replace(/^\s+/, "");
  33485. }
  33486. skipWhitespace();
  33487. cue.startTime = consumeTimeStamp();
  33488. skipWhitespace();
  33489. if (input.slice(0, 3) !== "-->") {
  33490. throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  33491. }
  33492. input = input.slice(3);
  33493. skipWhitespace();
  33494. cue.endTime = consumeTimeStamp();
  33495. skipWhitespace();
  33496. consumeCueSettings(input, cue);
  33497. }
  33498. function fixLineBreaks(input) {
  33499. return input.replace(/<br(?: \/)?>/gi, "\n");
  33500. }
  33501. class VTTParser {
  33502. constructor() {
  33503. this.state = "INITIAL";
  33504. this.buffer = "";
  33505. this.decoder = new StringDecoder();
  33506. this.regionList = [];
  33507. this.cue = null;
  33508. this.oncue = void 0;
  33509. this.onparsingerror = void 0;
  33510. this.onflush = void 0;
  33511. }
  33512. parse(data) {
  33513. const _this = this;
  33514. if (data) {
  33515. _this.buffer += _this.decoder.decode(data, {
  33516. stream: true
  33517. });
  33518. }
  33519. function collectNextLine() {
  33520. let buffer2 = _this.buffer;
  33521. let pos = 0;
  33522. buffer2 = fixLineBreaks(buffer2);
  33523. while (pos < buffer2.length && buffer2[pos] !== "\r" && buffer2[pos] !== "\n") {
  33524. ++pos;
  33525. }
  33526. const line = buffer2.slice(0, pos);
  33527. if (buffer2[pos] === "\r") {
  33528. ++pos;
  33529. }
  33530. if (buffer2[pos] === "\n") {
  33531. ++pos;
  33532. }
  33533. _this.buffer = buffer2.slice(pos);
  33534. return line;
  33535. }
  33536. function parseHeader2(input) {
  33537. parseOptions(input, function(k, v2) {
  33538. }, /:/);
  33539. }
  33540. try {
  33541. let line = "";
  33542. if (_this.state === "INITIAL") {
  33543. if (!/\r\n|\n/.test(_this.buffer)) {
  33544. return this;
  33545. }
  33546. line = collectNextLine();
  33547. const m2 = line.match(/^()?WEBVTT([ \t].*)?$/);
  33548. if (!(m2 != null && m2[0])) {
  33549. throw new Error("Malformed WebVTT signature.");
  33550. }
  33551. _this.state = "HEADER";
  33552. }
  33553. let alreadyCollectedLine = false;
  33554. while (_this.buffer) {
  33555. if (!/\r\n|\n/.test(_this.buffer)) {
  33556. return this;
  33557. }
  33558. if (!alreadyCollectedLine) {
  33559. line = collectNextLine();
  33560. } else {
  33561. alreadyCollectedLine = false;
  33562. }
  33563. switch (_this.state) {
  33564. case "HEADER":
  33565. if (/:/.test(line)) {
  33566. parseHeader2(line);
  33567. } else if (!line) {
  33568. _this.state = "ID";
  33569. }
  33570. continue;
  33571. case "NOTE":
  33572. if (!line) {
  33573. _this.state = "ID";
  33574. }
  33575. continue;
  33576. case "ID":
  33577. if (/^NOTE($|[ \t])/.test(line)) {
  33578. _this.state = "NOTE";
  33579. break;
  33580. }
  33581. if (!line) {
  33582. continue;
  33583. }
  33584. _this.cue = new VTTCue(0, 0, "");
  33585. _this.state = "CUE";
  33586. if (line.indexOf("-->") === -1) {
  33587. _this.cue.id = line;
  33588. continue;
  33589. }
  33590. case "CUE":
  33591. if (!_this.cue) {
  33592. _this.state = "BADCUE";
  33593. continue;
  33594. }
  33595. try {
  33596. parseCue(line, _this.cue, _this.regionList);
  33597. } catch (e2) {
  33598. _this.cue = null;
  33599. _this.state = "BADCUE";
  33600. continue;
  33601. }
  33602. _this.state = "CUETEXT";
  33603. continue;
  33604. case "CUETEXT":
  33605. {
  33606. const hasSubstring = line.indexOf("-->") !== -1;
  33607. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  33608. if (_this.oncue && _this.cue) {
  33609. _this.oncue(_this.cue);
  33610. }
  33611. _this.cue = null;
  33612. _this.state = "ID";
  33613. continue;
  33614. }
  33615. if (_this.cue === null) {
  33616. continue;
  33617. }
  33618. if (_this.cue.text) {
  33619. _this.cue.text += "\n";
  33620. }
  33621. _this.cue.text += line;
  33622. }
  33623. continue;
  33624. case "BADCUE":
  33625. if (!line) {
  33626. _this.state = "ID";
  33627. }
  33628. }
  33629. }
  33630. } catch (e2) {
  33631. if (_this.state === "CUETEXT" && _this.cue && _this.oncue) {
  33632. _this.oncue(_this.cue);
  33633. }
  33634. _this.cue = null;
  33635. _this.state = _this.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  33636. }
  33637. return this;
  33638. }
  33639. flush() {
  33640. const _this = this;
  33641. try {
  33642. if (_this.cue || _this.state === "HEADER") {
  33643. _this.buffer += "\n\n";
  33644. _this.parse();
  33645. }
  33646. if (_this.state === "INITIAL" || _this.state === "BADWEBVTT") {
  33647. throw new Error("Malformed WebVTT signature.");
  33648. }
  33649. } catch (e2) {
  33650. if (_this.onparsingerror) {
  33651. _this.onparsingerror(e2);
  33652. }
  33653. }
  33654. if (_this.onflush) {
  33655. _this.onflush();
  33656. }
  33657. return this;
  33658. }
  33659. }
  33660. const LINEBREAKS = /\r\n|\n\r|\n|\r/g;
  33661. const startsWith = function startsWith2(inputString, searchString, position = 0) {
  33662. return inputString.slice(position, position + searchString.length) === searchString;
  33663. };
  33664. const cueString2millis = function cueString2millis2(timeString) {
  33665. let ts2 = parseInt(timeString.slice(-3));
  33666. const secs = parseInt(timeString.slice(-6, -4));
  33667. const mins = parseInt(timeString.slice(-9, -7));
  33668. const hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(":"))) : 0;
  33669. if (!isFiniteNumber(ts2) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {
  33670. throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);
  33671. }
  33672. ts2 += 1e3 * secs;
  33673. ts2 += 60 * 1e3 * mins;
  33674. ts2 += 60 * 60 * 1e3 * hours;
  33675. return ts2;
  33676. };
  33677. function generateCueId(startTime, endTime, text) {
  33678. return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
  33679. }
  33680. const calculateOffset = function calculateOffset2(vttCCs, cc, presentationTime) {
  33681. let currCC = vttCCs[cc];
  33682. let prevCC = vttCCs[currCC.prevCC];
  33683. if (!prevCC || !prevCC.new && currCC.new) {
  33684. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  33685. currCC.new = false;
  33686. return;
  33687. }
  33688. while ((_prevCC = prevCC) != null && _prevCC.new) {
  33689. var _prevCC;
  33690. vttCCs.ccOffset += currCC.start - prevCC.start;
  33691. currCC.new = false;
  33692. currCC = prevCC;
  33693. prevCC = vttCCs[currCC.prevCC];
  33694. }
  33695. vttCCs.presentationOffset = presentationTime;
  33696. };
  33697. function parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) {
  33698. const parser = new VTTParser();
  33699. const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, "\n").split("\n");
  33700. const cues = [];
  33701. const init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0;
  33702. let cueTime = "00:00.000";
  33703. let timestampMapMPEGTS = 0;
  33704. let timestampMapLOCAL = 0;
  33705. let parsingError;
  33706. let inHeader = true;
  33707. parser.oncue = function(cue) {
  33708. const currCC = vttCCs[cc];
  33709. let cueOffset = vttCCs.ccOffset;
  33710. const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 9e4;
  33711. if (currCC != null && currCC.new) {
  33712. if (timestampMapLOCAL !== void 0) {
  33713. cueOffset = vttCCs.ccOffset = currCC.start;
  33714. } else {
  33715. calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
  33716. }
  33717. }
  33718. if (webVttMpegTsMapOffset) {
  33719. if (!initPTS) {
  33720. parsingError = new Error("Missing initPTS for VTT MPEGTS");
  33721. return;
  33722. }
  33723. cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
  33724. }
  33725. const duration = cue.endTime - cue.startTime;
  33726. const startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 9e4, timeOffset * 9e4) / 9e4;
  33727. cue.startTime = Math.max(startTime, 0);
  33728. cue.endTime = Math.max(startTime + duration, 0);
  33729. const text = cue.text.trim();
  33730. cue.text = decodeURIComponent(encodeURIComponent(text));
  33731. if (!cue.id) {
  33732. cue.id = generateCueId(cue.startTime, cue.endTime, text);
  33733. }
  33734. if (cue.endTime > 0) {
  33735. cues.push(cue);
  33736. }
  33737. };
  33738. parser.onparsingerror = function(error) {
  33739. parsingError = error;
  33740. };
  33741. parser.onflush = function() {
  33742. if (parsingError) {
  33743. errorCallBack(parsingError);
  33744. return;
  33745. }
  33746. callBack(cues);
  33747. };
  33748. vttLines.forEach((line) => {
  33749. if (inHeader) {
  33750. if (startsWith(line, "X-TIMESTAMP-MAP=")) {
  33751. inHeader = false;
  33752. line.slice(16).split(",").forEach((timestamp) => {
  33753. if (startsWith(timestamp, "LOCAL:")) {
  33754. cueTime = timestamp.slice(6);
  33755. } else if (startsWith(timestamp, "MPEGTS:")) {
  33756. timestampMapMPEGTS = parseInt(timestamp.slice(7));
  33757. }
  33758. });
  33759. try {
  33760. timestampMapLOCAL = cueString2millis(cueTime) / 1e3;
  33761. } catch (error) {
  33762. parsingError = error;
  33763. }
  33764. return;
  33765. } else if (line === "") {
  33766. inHeader = false;
  33767. }
  33768. }
  33769. parser.parse(line + "\n");
  33770. });
  33771. parser.flush();
  33772. }
  33773. const IMSC1_CODEC = "stpp.ttml.im1t";
  33774. const HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;
  33775. const TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
  33776. const textAlignToLineAlign = {
  33777. left: "start",
  33778. center: "center",
  33779. right: "end",
  33780. start: "start",
  33781. end: "end"
  33782. };
  33783. function parseIMSC1(payload, initPTS, callBack, errorCallBack) {
  33784. const results = findBox(new Uint8Array(payload), ["mdat"]);
  33785. if (results.length === 0) {
  33786. errorCallBack(new Error("Could not parse IMSC1 mdat"));
  33787. return;
  33788. }
  33789. const ttmlList = results.map((mdat) => utf8ArrayToStr(mdat));
  33790. const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);
  33791. try {
  33792. ttmlList.forEach((ttml) => callBack(parseTTML(ttml, syncTime)));
  33793. } catch (error) {
  33794. errorCallBack(error);
  33795. }
  33796. }
  33797. function parseTTML(ttml, syncTime) {
  33798. const parser = new DOMParser();
  33799. const xmlDoc = parser.parseFromString(ttml, "text/xml");
  33800. const tt2 = xmlDoc.getElementsByTagName("tt")[0];
  33801. if (!tt2) {
  33802. throw new Error("Invalid ttml");
  33803. }
  33804. const defaultRateInfo = {
  33805. frameRate: 30,
  33806. subFrameRate: 1,
  33807. frameRateMultiplier: 0,
  33808. tickRate: 0
  33809. };
  33810. const rateInfo = Object.keys(defaultRateInfo).reduce((result, key) => {
  33811. result[key] = tt2.getAttribute(`ttp:${key}`) || defaultRateInfo[key];
  33812. return result;
  33813. }, {});
  33814. const trim = tt2.getAttribute("xml:space") !== "preserve";
  33815. const styleElements = collectionToDictionary(getElementCollection(tt2, "styling", "style"));
  33816. const regionElements = collectionToDictionary(getElementCollection(tt2, "layout", "region"));
  33817. const cueElements = getElementCollection(tt2, "body", "[begin]");
  33818. return [].map.call(cueElements, (cueElement) => {
  33819. const cueText = getTextContent(cueElement, trim);
  33820. if (!cueText || !cueElement.hasAttribute("begin")) {
  33821. return null;
  33822. }
  33823. const startTime = parseTtmlTime(cueElement.getAttribute("begin"), rateInfo);
  33824. const duration = parseTtmlTime(cueElement.getAttribute("dur"), rateInfo);
  33825. let endTime = parseTtmlTime(cueElement.getAttribute("end"), rateInfo);
  33826. if (startTime === null) {
  33827. throw timestampParsingError(cueElement);
  33828. }
  33829. if (endTime === null) {
  33830. if (duration === null) {
  33831. throw timestampParsingError(cueElement);
  33832. }
  33833. endTime = startTime + duration;
  33834. }
  33835. const cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);
  33836. cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);
  33837. const region = regionElements[cueElement.getAttribute("region")];
  33838. const style = styleElements[cueElement.getAttribute("style")];
  33839. const styles = getTtmlStyles(region, style, styleElements);
  33840. const {
  33841. textAlign
  33842. } = styles;
  33843. if (textAlign) {
  33844. const lineAlign = textAlignToLineAlign[textAlign];
  33845. if (lineAlign) {
  33846. cue.lineAlign = lineAlign;
  33847. }
  33848. cue.align = textAlign;
  33849. }
  33850. _extends(cue, styles);
  33851. return cue;
  33852. }).filter((cue) => cue !== null);
  33853. }
  33854. function getElementCollection(fromElement, parentName, childName) {
  33855. const parent = fromElement.getElementsByTagName(parentName)[0];
  33856. if (parent) {
  33857. return [].slice.call(parent.querySelectorAll(childName));
  33858. }
  33859. return [];
  33860. }
  33861. function collectionToDictionary(elementsWithId) {
  33862. return elementsWithId.reduce((dict, element) => {
  33863. const id = element.getAttribute("xml:id");
  33864. if (id) {
  33865. dict[id] = element;
  33866. }
  33867. return dict;
  33868. }, {});
  33869. }
  33870. function getTextContent(element, trim) {
  33871. return [].slice.call(element.childNodes).reduce((str, node, i2) => {
  33872. var _node$childNodes;
  33873. if (node.nodeName === "br" && i2) {
  33874. return str + "\n";
  33875. }
  33876. if ((_node$childNodes = node.childNodes) != null && _node$childNodes.length) {
  33877. return getTextContent(node, trim);
  33878. } else if (trim) {
  33879. return str + node.textContent.trim().replace(/\s+/g, " ");
  33880. }
  33881. return str + node.textContent;
  33882. }, "");
  33883. }
  33884. function getTtmlStyles(region, style, styleElements) {
  33885. const ttsNs = "http://www.w3.org/ns/ttml#styling";
  33886. let regionStyle = null;
  33887. const styleAttributes = [
  33888. "displayAlign",
  33889. "textAlign",
  33890. "color",
  33891. "backgroundColor",
  33892. "fontSize",
  33893. "fontFamily"
  33894. // 'fontWeight',
  33895. // 'lineHeight',
  33896. // 'wrapOption',
  33897. // 'fontStyle',
  33898. // 'direction',
  33899. // 'writingMode'
  33900. ];
  33901. const regionStyleName = region != null && region.hasAttribute("style") ? region.getAttribute("style") : null;
  33902. if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {
  33903. regionStyle = styleElements[regionStyleName];
  33904. }
  33905. return styleAttributes.reduce((styles, name) => {
  33906. const value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name);
  33907. if (value) {
  33908. styles[name] = value;
  33909. }
  33910. return styles;
  33911. }, {});
  33912. }
  33913. function getAttributeNS(element, ns2, name) {
  33914. if (!element) {
  33915. return null;
  33916. }
  33917. return element.hasAttributeNS(ns2, name) ? element.getAttributeNS(ns2, name) : null;
  33918. }
  33919. function timestampParsingError(node) {
  33920. return new Error(`Could not parse ttml timestamp ${node}`);
  33921. }
  33922. function parseTtmlTime(timeAttributeValue, rateInfo) {
  33923. if (!timeAttributeValue) {
  33924. return null;
  33925. }
  33926. let seconds = parseTimeStamp(timeAttributeValue);
  33927. if (seconds === null) {
  33928. if (HMSF_REGEX.test(timeAttributeValue)) {
  33929. seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
  33930. } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
  33931. seconds = parseTimeUnits(timeAttributeValue, rateInfo);
  33932. }
  33933. }
  33934. return seconds;
  33935. }
  33936. function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
  33937. const m2 = HMSF_REGEX.exec(timeAttributeValue);
  33938. const frames = (m2[4] | 0) + (m2[5] | 0) / rateInfo.subFrameRate;
  33939. return (m2[1] | 0) * 3600 + (m2[2] | 0) * 60 + (m2[3] | 0) + frames / rateInfo.frameRate;
  33940. }
  33941. function parseTimeUnits(timeAttributeValue, rateInfo) {
  33942. const m2 = TIME_UNIT_REGEX.exec(timeAttributeValue);
  33943. const value = Number(m2[1]);
  33944. const unit = m2[2];
  33945. switch (unit) {
  33946. case "h":
  33947. return value * 3600;
  33948. case "m":
  33949. return value * 60;
  33950. case "ms":
  33951. return value * 1e3;
  33952. case "f":
  33953. return value / rateInfo.frameRate;
  33954. case "t":
  33955. return value / rateInfo.tickRate;
  33956. }
  33957. return value;
  33958. }
  33959. class OutputFilter {
  33960. constructor(timelineController, trackName) {
  33961. this.timelineController = void 0;
  33962. this.cueRanges = [];
  33963. this.trackName = void 0;
  33964. this.startTime = null;
  33965. this.endTime = null;
  33966. this.screen = null;
  33967. this.timelineController = timelineController;
  33968. this.trackName = trackName;
  33969. }
  33970. dispatchCue() {
  33971. if (this.startTime === null) {
  33972. return;
  33973. }
  33974. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
  33975. this.startTime = null;
  33976. }
  33977. newCue(startTime, endTime, screen) {
  33978. if (this.startTime === null || this.startTime > startTime) {
  33979. this.startTime = startTime;
  33980. }
  33981. this.endTime = endTime;
  33982. this.screen = screen;
  33983. this.timelineController.createCaptionsTrack(this.trackName);
  33984. }
  33985. reset() {
  33986. this.cueRanges = [];
  33987. this.startTime = null;
  33988. }
  33989. }
  33990. class TimelineController {
  33991. constructor(hls) {
  33992. this.hls = void 0;
  33993. this.media = null;
  33994. this.config = void 0;
  33995. this.enabled = true;
  33996. this.Cues = void 0;
  33997. this.textTracks = [];
  33998. this.tracks = [];
  33999. this.initPTS = [];
  34000. this.unparsedVttFrags = [];
  34001. this.captionsTracks = {};
  34002. this.nonNativeCaptionsTracks = {};
  34003. this.cea608Parser1 = void 0;
  34004. this.cea608Parser2 = void 0;
  34005. this.lastCc = -1;
  34006. this.lastSn = -1;
  34007. this.lastPartIndex = -1;
  34008. this.prevCC = -1;
  34009. this.vttCCs = newVTTCCs();
  34010. this.captionsProperties = void 0;
  34011. this.hls = hls;
  34012. this.config = hls.config;
  34013. this.Cues = hls.config.cueHandler;
  34014. this.captionsProperties = {
  34015. textTrack1: {
  34016. label: this.config.captionsTextTrack1Label,
  34017. languageCode: this.config.captionsTextTrack1LanguageCode
  34018. },
  34019. textTrack2: {
  34020. label: this.config.captionsTextTrack2Label,
  34021. languageCode: this.config.captionsTextTrack2LanguageCode
  34022. },
  34023. textTrack3: {
  34024. label: this.config.captionsTextTrack3Label,
  34025. languageCode: this.config.captionsTextTrack3LanguageCode
  34026. },
  34027. textTrack4: {
  34028. label: this.config.captionsTextTrack4Label,
  34029. languageCode: this.config.captionsTextTrack4LanguageCode
  34030. }
  34031. };
  34032. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  34033. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  34034. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  34035. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  34036. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  34037. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  34038. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  34039. hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  34040. hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  34041. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  34042. hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  34043. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  34044. }
  34045. destroy() {
  34046. const {
  34047. hls
  34048. } = this;
  34049. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  34050. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  34051. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  34052. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  34053. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  34054. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  34055. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  34056. hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  34057. hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  34058. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  34059. hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  34060. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  34061. this.hls = this.config = this.media = null;
  34062. this.cea608Parser1 = this.cea608Parser2 = void 0;
  34063. }
  34064. initCea608Parsers() {
  34065. const channel1 = new OutputFilter(this, "textTrack1");
  34066. const channel2 = new OutputFilter(this, "textTrack2");
  34067. const channel3 = new OutputFilter(this, "textTrack3");
  34068. const channel4 = new OutputFilter(this, "textTrack4");
  34069. this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);
  34070. this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);
  34071. }
  34072. addCues(trackName, startTime, endTime, screen, cueRanges) {
  34073. let merged = false;
  34074. for (let i2 = cueRanges.length; i2--; ) {
  34075. const cueRange = cueRanges[i2];
  34076. const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  34077. if (overlap >= 0) {
  34078. cueRange[0] = Math.min(cueRange[0], startTime);
  34079. cueRange[1] = Math.max(cueRange[1], endTime);
  34080. merged = true;
  34081. if (overlap / (endTime - startTime) > 0.5) {
  34082. return;
  34083. }
  34084. }
  34085. }
  34086. if (!merged) {
  34087. cueRanges.push([startTime, endTime]);
  34088. }
  34089. if (this.config.renderTextTracksNatively) {
  34090. const track2 = this.captionsTracks[trackName];
  34091. this.Cues.newCue(track2, startTime, endTime, screen);
  34092. } else {
  34093. const cues = this.Cues.newCue(null, startTime, endTime, screen);
  34094. this.hls.trigger(Events.CUES_PARSED, {
  34095. type: "captions",
  34096. cues,
  34097. track: trackName
  34098. });
  34099. }
  34100. }
  34101. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  34102. onInitPtsFound(event, {
  34103. frag,
  34104. id,
  34105. initPTS,
  34106. timescale
  34107. }) {
  34108. const {
  34109. unparsedVttFrags
  34110. } = this;
  34111. if (id === PlaylistLevelType.MAIN) {
  34112. this.initPTS[frag.cc] = {
  34113. baseTime: initPTS,
  34114. timescale
  34115. };
  34116. }
  34117. if (unparsedVttFrags.length) {
  34118. this.unparsedVttFrags = [];
  34119. unparsedVttFrags.forEach((data) => {
  34120. if (this.initPTS[data.frag.cc]) {
  34121. this.onFragLoaded(Events.FRAG_LOADED, data);
  34122. } else {
  34123. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  34124. success: false,
  34125. frag: data.frag,
  34126. error: new Error("Subtitle discontinuity domain does not match main")
  34127. });
  34128. }
  34129. });
  34130. }
  34131. }
  34132. getExistingTrack(label, language) {
  34133. const {
  34134. media
  34135. } = this;
  34136. if (media) {
  34137. for (let i2 = 0; i2 < media.textTracks.length; i2++) {
  34138. const textTrack = media.textTracks[i2];
  34139. if (canReuseVttTextTrack(textTrack, {
  34140. name: label,
  34141. lang: language,
  34142. characteristics: "transcribes-spoken-dialog,describes-music-and-sound"
  34143. })) {
  34144. return textTrack;
  34145. }
  34146. }
  34147. }
  34148. return null;
  34149. }
  34150. createCaptionsTrack(trackName) {
  34151. if (this.config.renderTextTracksNatively) {
  34152. this.createNativeTrack(trackName);
  34153. } else {
  34154. this.createNonNativeTrack(trackName);
  34155. }
  34156. }
  34157. createNativeTrack(trackName) {
  34158. if (this.captionsTracks[trackName]) {
  34159. return;
  34160. }
  34161. const {
  34162. captionsProperties,
  34163. captionsTracks,
  34164. media
  34165. } = this;
  34166. const {
  34167. label,
  34168. languageCode
  34169. } = captionsProperties[trackName];
  34170. const existingTrack = this.getExistingTrack(label, languageCode);
  34171. if (!existingTrack) {
  34172. const textTrack = this.createTextTrack("captions", label, languageCode);
  34173. if (textTrack) {
  34174. textTrack[trackName] = true;
  34175. captionsTracks[trackName] = textTrack;
  34176. }
  34177. } else {
  34178. captionsTracks[trackName] = existingTrack;
  34179. clearCurrentCues(captionsTracks[trackName]);
  34180. sendAddTrackEvent(captionsTracks[trackName], media);
  34181. }
  34182. }
  34183. createNonNativeTrack(trackName) {
  34184. if (this.nonNativeCaptionsTracks[trackName]) {
  34185. return;
  34186. }
  34187. const trackProperties = this.captionsProperties[trackName];
  34188. if (!trackProperties) {
  34189. return;
  34190. }
  34191. const label = trackProperties.label;
  34192. const track2 = {
  34193. _id: trackName,
  34194. label,
  34195. kind: "captions",
  34196. default: trackProperties.media ? !!trackProperties.media.default : false,
  34197. closedCaptions: trackProperties.media
  34198. };
  34199. this.nonNativeCaptionsTracks[trackName] = track2;
  34200. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  34201. tracks: [track2]
  34202. });
  34203. }
  34204. createTextTrack(kind, label, lang) {
  34205. const media = this.media;
  34206. if (!media) {
  34207. return;
  34208. }
  34209. return media.addTextTrack(kind, label, lang);
  34210. }
  34211. onMediaAttaching(event, data) {
  34212. this.media = data.media;
  34213. if (!data.mediaSource) {
  34214. this._cleanTracks();
  34215. }
  34216. }
  34217. onMediaDetaching(event, data) {
  34218. const transferringMedia = !!data.transferMedia;
  34219. this.media = null;
  34220. if (transferringMedia) {
  34221. return;
  34222. }
  34223. const {
  34224. captionsTracks
  34225. } = this;
  34226. Object.keys(captionsTracks).forEach((trackName) => {
  34227. clearCurrentCues(captionsTracks[trackName]);
  34228. delete captionsTracks[trackName];
  34229. });
  34230. this.nonNativeCaptionsTracks = {};
  34231. }
  34232. onManifestLoading() {
  34233. this.lastCc = -1;
  34234. this.lastSn = -1;
  34235. this.lastPartIndex = -1;
  34236. this.prevCC = -1;
  34237. this.vttCCs = newVTTCCs();
  34238. this._cleanTracks();
  34239. this.tracks = [];
  34240. this.captionsTracks = {};
  34241. this.nonNativeCaptionsTracks = {};
  34242. this.textTracks = [];
  34243. this.unparsedVttFrags = [];
  34244. this.initPTS = [];
  34245. if (this.cea608Parser1 && this.cea608Parser2) {
  34246. this.cea608Parser1.reset();
  34247. this.cea608Parser2.reset();
  34248. }
  34249. }
  34250. _cleanTracks() {
  34251. const {
  34252. media
  34253. } = this;
  34254. if (!media) {
  34255. return;
  34256. }
  34257. const textTracks = media.textTracks;
  34258. if (textTracks) {
  34259. for (let i2 = 0; i2 < textTracks.length; i2++) {
  34260. clearCurrentCues(textTracks[i2]);
  34261. }
  34262. }
  34263. }
  34264. onSubtitleTracksUpdated(event, data) {
  34265. const tracks = data.subtitleTracks || [];
  34266. const hasIMSC1 = tracks.some((track2) => track2.textCodec === IMSC1_CODEC);
  34267. if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
  34268. const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);
  34269. if (listIsIdentical) {
  34270. this.tracks = tracks;
  34271. return;
  34272. }
  34273. this.textTracks = [];
  34274. this.tracks = tracks;
  34275. if (this.config.renderTextTracksNatively) {
  34276. const media = this.media;
  34277. const inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null;
  34278. this.tracks.forEach((track2, index2) => {
  34279. let textTrack;
  34280. if (inUseTracks) {
  34281. let inUseTrack = null;
  34282. for (let i2 = 0; i2 < inUseTracks.length; i2++) {
  34283. if (inUseTracks[i2] && canReuseVttTextTrack(inUseTracks[i2], track2)) {
  34284. inUseTrack = inUseTracks[i2];
  34285. inUseTracks[i2] = null;
  34286. break;
  34287. }
  34288. }
  34289. if (inUseTrack) {
  34290. textTrack = inUseTrack;
  34291. }
  34292. }
  34293. if (textTrack) {
  34294. clearCurrentCues(textTrack);
  34295. } else {
  34296. const textTrackKind = captionsOrSubtitlesFromCharacteristics(track2);
  34297. textTrack = this.createTextTrack(textTrackKind, track2.name, track2.lang);
  34298. if (textTrack) {
  34299. textTrack.mode = "disabled";
  34300. }
  34301. }
  34302. if (textTrack) {
  34303. this.textTracks.push(textTrack);
  34304. }
  34305. });
  34306. if (inUseTracks != null && inUseTracks.length) {
  34307. const unusedTextTracks = inUseTracks.filter((t2) => t2 !== null).map((t2) => t2.label);
  34308. if (unusedTextTracks.length) {
  34309. this.hls.logger.warn(`Media element contains unused subtitle tracks: ${unusedTextTracks.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);
  34310. }
  34311. }
  34312. } else if (this.tracks.length) {
  34313. const tracksList = this.tracks.map((track2) => {
  34314. return {
  34315. label: track2.name,
  34316. kind: track2.type.toLowerCase(),
  34317. default: track2.default,
  34318. subtitleTrack: track2
  34319. };
  34320. });
  34321. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  34322. tracks: tracksList
  34323. });
  34324. }
  34325. }
  34326. }
  34327. onManifestLoaded(event, data) {
  34328. if (this.config.enableCEA708Captions && data.captions) {
  34329. data.captions.forEach((captionsTrack) => {
  34330. const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
  34331. if (!instreamIdMatch) {
  34332. return;
  34333. }
  34334. const trackName = `textTrack${instreamIdMatch[1]}`;
  34335. const trackProperties = this.captionsProperties[trackName];
  34336. if (!trackProperties) {
  34337. return;
  34338. }
  34339. trackProperties.label = captionsTrack.name;
  34340. if (captionsTrack.lang) {
  34341. trackProperties.languageCode = captionsTrack.lang;
  34342. }
  34343. trackProperties.media = captionsTrack;
  34344. });
  34345. }
  34346. }
  34347. closedCaptionsForLevel(frag) {
  34348. const level = this.hls.levels[frag.level];
  34349. return level == null ? void 0 : level.attrs["CLOSED-CAPTIONS"];
  34350. }
  34351. onFragLoading(event, data) {
  34352. if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {
  34353. var _data$part$index, _data$part;
  34354. const {
  34355. cea608Parser1,
  34356. cea608Parser2,
  34357. lastSn
  34358. } = this;
  34359. const {
  34360. cc,
  34361. sn: sn2
  34362. } = data.frag;
  34363. const partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1;
  34364. if (cea608Parser1 && cea608Parser2) {
  34365. if (sn2 !== lastSn + 1 || sn2 === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) {
  34366. cea608Parser1.reset();
  34367. cea608Parser2.reset();
  34368. }
  34369. }
  34370. this.lastCc = cc;
  34371. this.lastSn = sn2;
  34372. this.lastPartIndex = partIndex;
  34373. }
  34374. }
  34375. onFragLoaded(event, data) {
  34376. const {
  34377. frag,
  34378. payload
  34379. } = data;
  34380. if (frag.type === PlaylistLevelType.SUBTITLE) {
  34381. if (payload.byteLength) {
  34382. const decryptData = frag.decryptdata;
  34383. const decrypted = "stats" in data;
  34384. if (decryptData == null || !decryptData.encrypted || decrypted) {
  34385. const trackPlaylistMedia = this.tracks[frag.level];
  34386. const vttCCs = this.vttCCs;
  34387. if (!vttCCs[frag.cc]) {
  34388. vttCCs[frag.cc] = {
  34389. start: frag.start,
  34390. prevCC: this.prevCC,
  34391. new: true
  34392. };
  34393. this.prevCC = frag.cc;
  34394. }
  34395. if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) {
  34396. this._parseIMSC1(frag, payload);
  34397. } else {
  34398. this._parseVTTs(data);
  34399. }
  34400. }
  34401. } else {
  34402. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  34403. success: false,
  34404. frag,
  34405. error: new Error("Empty subtitle payload")
  34406. });
  34407. }
  34408. }
  34409. }
  34410. _parseIMSC1(frag, payload) {
  34411. const hls = this.hls;
  34412. parseIMSC1(payload, this.initPTS[frag.cc], (cues) => {
  34413. this._appendCues(cues, frag.level);
  34414. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  34415. success: true,
  34416. frag
  34417. });
  34418. }, (error) => {
  34419. hls.logger.log(`Failed to parse IMSC1: ${error}`);
  34420. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  34421. success: false,
  34422. frag,
  34423. error
  34424. });
  34425. });
  34426. }
  34427. _parseVTTs(data) {
  34428. var _frag$initSegment;
  34429. const {
  34430. frag,
  34431. payload
  34432. } = data;
  34433. const {
  34434. initPTS,
  34435. unparsedVttFrags
  34436. } = this;
  34437. const maxAvCC = initPTS.length - 1;
  34438. if (!initPTS[frag.cc] && maxAvCC === -1) {
  34439. unparsedVttFrags.push(data);
  34440. return;
  34441. }
  34442. const hls = this.hls;
  34443. const payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)).buffer : payload;
  34444. parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, (cues) => {
  34445. this._appendCues(cues, frag.level);
  34446. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  34447. success: true,
  34448. frag
  34449. });
  34450. }, (error) => {
  34451. const missingInitPTS = error.message === "Missing initPTS for VTT MPEGTS";
  34452. if (missingInitPTS) {
  34453. unparsedVttFrags.push(data);
  34454. } else {
  34455. this._fallbackToIMSC1(frag, payload);
  34456. }
  34457. hls.logger.log(`Failed to parse VTT cue: ${error}`);
  34458. if (missingInitPTS && maxAvCC > frag.cc) {
  34459. return;
  34460. }
  34461. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  34462. success: false,
  34463. frag,
  34464. error
  34465. });
  34466. });
  34467. }
  34468. _fallbackToIMSC1(frag, payload) {
  34469. const trackPlaylistMedia = this.tracks[frag.level];
  34470. if (!trackPlaylistMedia.textCodec) {
  34471. parseIMSC1(payload, this.initPTS[frag.cc], () => {
  34472. trackPlaylistMedia.textCodec = IMSC1_CODEC;
  34473. this._parseIMSC1(frag, payload);
  34474. }, () => {
  34475. trackPlaylistMedia.textCodec = "wvtt";
  34476. });
  34477. }
  34478. }
  34479. _appendCues(cues, fragLevel) {
  34480. const hls = this.hls;
  34481. if (this.config.renderTextTracksNatively) {
  34482. const textTrack = this.textTracks[fragLevel];
  34483. if (!textTrack || textTrack.mode === "disabled") {
  34484. return;
  34485. }
  34486. cues.forEach((cue) => addCueToTrack(textTrack, cue));
  34487. } else {
  34488. const currentTrack = this.tracks[fragLevel];
  34489. if (!currentTrack) {
  34490. return;
  34491. }
  34492. const track2 = currentTrack.default ? "default" : "subtitles" + fragLevel;
  34493. hls.trigger(Events.CUES_PARSED, {
  34494. type: "subtitles",
  34495. cues,
  34496. track: track2
  34497. });
  34498. }
  34499. }
  34500. onFragDecrypted(event, data) {
  34501. const {
  34502. frag
  34503. } = data;
  34504. if (frag.type === PlaylistLevelType.SUBTITLE) {
  34505. this.onFragLoaded(Events.FRAG_LOADED, data);
  34506. }
  34507. }
  34508. onSubtitleTracksCleared() {
  34509. this.tracks = [];
  34510. this.captionsTracks = {};
  34511. }
  34512. onFragParsingUserdata(event, data) {
  34513. if (!this.enabled || !this.config.enableCEA708Captions) {
  34514. return;
  34515. }
  34516. const {
  34517. frag,
  34518. samples
  34519. } = data;
  34520. if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === "NONE") {
  34521. return;
  34522. }
  34523. for (let i2 = 0; i2 < samples.length; i2++) {
  34524. const ccBytes = samples[i2].bytes;
  34525. if (ccBytes) {
  34526. if (!this.cea608Parser1) {
  34527. this.initCea608Parsers();
  34528. }
  34529. const ccdatas = this.extractCea608Data(ccBytes);
  34530. this.cea608Parser1.addData(samples[i2].pts, ccdatas[0]);
  34531. this.cea608Parser2.addData(samples[i2].pts, ccdatas[1]);
  34532. }
  34533. }
  34534. }
  34535. onBufferFlushing(event, {
  34536. startOffset,
  34537. endOffset,
  34538. endOffsetSubtitles,
  34539. type
  34540. }) {
  34541. const {
  34542. media
  34543. } = this;
  34544. if (!media || media.currentTime < endOffset) {
  34545. return;
  34546. }
  34547. if (!type || type === "video") {
  34548. const {
  34549. captionsTracks
  34550. } = this;
  34551. Object.keys(captionsTracks).forEach((trackName) => removeCuesInRange(captionsTracks[trackName], startOffset, endOffset));
  34552. }
  34553. if (this.config.renderTextTracksNatively) {
  34554. if (startOffset === 0 && endOffsetSubtitles !== void 0) {
  34555. const {
  34556. textTracks
  34557. } = this;
  34558. Object.keys(textTracks).forEach((trackName) => removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles));
  34559. }
  34560. }
  34561. }
  34562. extractCea608Data(byteArray) {
  34563. const actualCCBytes = [[], []];
  34564. const count = byteArray[0] & 31;
  34565. let position = 2;
  34566. for (let j2 = 0; j2 < count; j2++) {
  34567. const tmpByte = byteArray[position++];
  34568. const ccbyte1 = 127 & byteArray[position++];
  34569. const ccbyte2 = 127 & byteArray[position++];
  34570. if (ccbyte1 === 0 && ccbyte2 === 0) {
  34571. continue;
  34572. }
  34573. const ccValid = (4 & tmpByte) !== 0;
  34574. if (ccValid) {
  34575. const ccType = 3 & tmpByte;
  34576. if (0 === ccType || 1 === ccType) {
  34577. actualCCBytes[ccType].push(ccbyte1);
  34578. actualCCBytes[ccType].push(ccbyte2);
  34579. }
  34580. }
  34581. }
  34582. return actualCCBytes;
  34583. }
  34584. }
  34585. function captionsOrSubtitlesFromCharacteristics(track2) {
  34586. if (track2.characteristics) {
  34587. if (/transcribes-spoken-dialog/gi.test(track2.characteristics) && /describes-music-and-sound/gi.test(track2.characteristics)) {
  34588. return "captions";
  34589. }
  34590. }
  34591. return "subtitles";
  34592. }
  34593. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  34594. return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack);
  34595. }
  34596. function intersection(x1, x2, y1, y2) {
  34597. return Math.min(x2, y2) - Math.max(x1, y1);
  34598. }
  34599. function newVTTCCs() {
  34600. return {
  34601. ccOffset: 0,
  34602. presentationOffset: 0,
  34603. 0: {
  34604. start: 0,
  34605. prevCC: -1,
  34606. new: true
  34607. }
  34608. };
  34609. }
  34610. const WHITESPACE_CHAR = /\s/;
  34611. const Cues = {
  34612. newCue(track2, startTime, endTime, captionScreen) {
  34613. const result = [];
  34614. let row;
  34615. let cue;
  34616. let indenting;
  34617. let indent;
  34618. let text;
  34619. const Cue = self.VTTCue || self.TextTrackCue;
  34620. for (let r2 = 0; r2 < captionScreen.rows.length; r2++) {
  34621. row = captionScreen.rows[r2];
  34622. indenting = true;
  34623. indent = 0;
  34624. text = "";
  34625. if (!row.isEmpty()) {
  34626. var _track$cues;
  34627. for (let c2 = 0; c2 < row.chars.length; c2++) {
  34628. if (WHITESPACE_CHAR.test(row.chars[c2].uchar) && indenting) {
  34629. indent++;
  34630. } else {
  34631. text += row.chars[c2].uchar;
  34632. indenting = false;
  34633. }
  34634. }
  34635. row.cueStartTime = startTime;
  34636. if (startTime === endTime) {
  34637. endTime += 1e-4;
  34638. }
  34639. if (indent >= 16) {
  34640. indent--;
  34641. } else {
  34642. indent++;
  34643. }
  34644. const cueText = fixLineBreaks(text.trim());
  34645. const id = generateCueId(startTime, endTime, cueText);
  34646. if (!(track2 != null && (_track$cues = track2.cues) != null && _track$cues.getCueById(id))) {
  34647. cue = new Cue(startTime, endTime, cueText);
  34648. cue.id = id;
  34649. cue.line = r2 + 1;
  34650. cue.align = "left";
  34651. cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
  34652. result.push(cue);
  34653. }
  34654. }
  34655. }
  34656. if (track2 && result.length) {
  34657. result.sort((cueA, cueB) => {
  34658. if (cueA.line === "auto" || cueB.line === "auto") {
  34659. return 0;
  34660. }
  34661. if (cueA.line > 8 && cueB.line > 8) {
  34662. return cueB.line - cueA.line;
  34663. }
  34664. return cueA.line - cueB.line;
  34665. });
  34666. result.forEach((cue2) => addCueToTrack(track2, cue2));
  34667. }
  34668. return result;
  34669. }
  34670. };
  34671. function fetchSupported() {
  34672. if (
  34673. // @ts-ignore
  34674. self.fetch && self.AbortController && self.ReadableStream && self.Request
  34675. ) {
  34676. try {
  34677. new self.ReadableStream({});
  34678. return true;
  34679. } catch (e2) {
  34680. }
  34681. }
  34682. return false;
  34683. }
  34684. const BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  34685. class FetchLoader {
  34686. constructor(config) {
  34687. this.fetchSetup = void 0;
  34688. this.requestTimeout = void 0;
  34689. this.request = null;
  34690. this.response = null;
  34691. this.controller = void 0;
  34692. this.context = null;
  34693. this.config = null;
  34694. this.callbacks = null;
  34695. this.stats = void 0;
  34696. this.loader = null;
  34697. this.fetchSetup = config.fetchSetup || getRequest;
  34698. this.controller = new self.AbortController();
  34699. this.stats = new LoadStats();
  34700. }
  34701. destroy() {
  34702. this.loader = this.callbacks = this.context = this.config = this.request = null;
  34703. this.abortInternal();
  34704. this.response = null;
  34705. this.fetchSetup = this.controller = this.stats = null;
  34706. }
  34707. abortInternal() {
  34708. if (this.controller && !this.stats.loading.end) {
  34709. this.stats.aborted = true;
  34710. this.controller.abort();
  34711. }
  34712. }
  34713. abort() {
  34714. var _this$callbacks;
  34715. this.abortInternal();
  34716. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  34717. this.callbacks.onAbort(this.stats, this.context, this.response);
  34718. }
  34719. }
  34720. load(context, config, callbacks) {
  34721. const stats = this.stats;
  34722. if (stats.loading.start) {
  34723. throw new Error("Loader can only be used once.");
  34724. }
  34725. stats.loading.start = self.performance.now();
  34726. const initParams = getRequestParameters(context, this.controller.signal);
  34727. const isArrayBuffer = context.responseType === "arraybuffer";
  34728. const LENGTH = isArrayBuffer ? "byteLength" : "length";
  34729. const {
  34730. maxTimeToFirstByteMs,
  34731. maxLoadTimeMs
  34732. } = config.loadPolicy;
  34733. this.context = context;
  34734. this.config = config;
  34735. this.callbacks = callbacks;
  34736. this.request = this.fetchSetup(context, initParams);
  34737. self.clearTimeout(this.requestTimeout);
  34738. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  34739. this.requestTimeout = self.setTimeout(() => {
  34740. if (this.callbacks) {
  34741. this.abortInternal();
  34742. this.callbacks.onTimeout(stats, context, this.response);
  34743. }
  34744. }, config.timeout);
  34745. const fetchPromise = isPromise(this.request) ? this.request.then(self.fetch) : self.fetch(this.request);
  34746. fetchPromise.then((response) => {
  34747. var _this$callbacks2;
  34748. this.response = this.loader = response;
  34749. const first = Math.max(self.performance.now(), stats.loading.start);
  34750. self.clearTimeout(this.requestTimeout);
  34751. config.timeout = maxLoadTimeMs;
  34752. this.requestTimeout = self.setTimeout(() => {
  34753. if (this.callbacks) {
  34754. this.abortInternal();
  34755. this.callbacks.onTimeout(stats, context, this.response);
  34756. }
  34757. }, maxLoadTimeMs - (first - stats.loading.start));
  34758. if (!response.ok) {
  34759. const {
  34760. status: status2,
  34761. statusText
  34762. } = response;
  34763. throw new FetchError(statusText || "fetch, bad network response", status2, response);
  34764. }
  34765. stats.loading.first = first;
  34766. stats.total = getContentLength(response.headers) || stats.total;
  34767. const onProgress = (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onProgress;
  34768. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  34769. return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  34770. }
  34771. if (isArrayBuffer) {
  34772. return response.arrayBuffer();
  34773. }
  34774. if (context.responseType === "json") {
  34775. return response.json();
  34776. }
  34777. return response.text();
  34778. }).then((responseData) => {
  34779. var _this$callbacks3, _this$callbacks4;
  34780. const response = this.response;
  34781. if (!response) {
  34782. throw new Error("loader destroyed");
  34783. }
  34784. self.clearTimeout(this.requestTimeout);
  34785. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  34786. const total = responseData[LENGTH];
  34787. if (total) {
  34788. stats.loaded = stats.total = total;
  34789. }
  34790. const loaderResponse = {
  34791. url: response.url,
  34792. data: responseData,
  34793. code: response.status
  34794. };
  34795. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  34796. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  34797. onProgress(stats, context, responseData, response);
  34798. }
  34799. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(loaderResponse, stats, context, response);
  34800. }).catch((error) => {
  34801. var _this$callbacks5;
  34802. self.clearTimeout(this.requestTimeout);
  34803. if (stats.aborted) {
  34804. return;
  34805. }
  34806. const code = !error ? 0 : error.code || 0;
  34807. const text = !error ? null : error.message;
  34808. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  34809. code,
  34810. text
  34811. }, context, error ? error.details : null, stats);
  34812. });
  34813. }
  34814. getCacheAge() {
  34815. let result = null;
  34816. if (this.response) {
  34817. const ageHeader = this.response.headers.get("age");
  34818. result = ageHeader ? parseFloat(ageHeader) : null;
  34819. }
  34820. return result;
  34821. }
  34822. getResponseHeader(name) {
  34823. return this.response ? this.response.headers.get(name) : null;
  34824. }
  34825. loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {
  34826. const chunkCache = new ChunkCache();
  34827. const reader = response.body.getReader();
  34828. const pump = () => {
  34829. return reader.read().then((data) => {
  34830. if (data.done) {
  34831. if (chunkCache.dataLength) {
  34832. onProgress(stats, context, chunkCache.flush().buffer, response);
  34833. }
  34834. return Promise.resolve(new ArrayBuffer(0));
  34835. }
  34836. const chunk = data.value;
  34837. const len = chunk.length;
  34838. stats.loaded += len;
  34839. if (len < highWaterMark || chunkCache.dataLength) {
  34840. chunkCache.push(chunk);
  34841. if (chunkCache.dataLength >= highWaterMark) {
  34842. onProgress(stats, context, chunkCache.flush().buffer, response);
  34843. }
  34844. } else {
  34845. onProgress(stats, context, chunk.buffer, response);
  34846. }
  34847. return pump();
  34848. }).catch(() => {
  34849. return Promise.reject();
  34850. });
  34851. };
  34852. return pump();
  34853. }
  34854. }
  34855. function getRequestParameters(context, signal) {
  34856. const initParams = {
  34857. method: "GET",
  34858. mode: "cors",
  34859. credentials: "same-origin",
  34860. signal,
  34861. headers: new self.Headers(_extends({}, context.headers))
  34862. };
  34863. if (context.rangeEnd) {
  34864. initParams.headers.set("Range", "bytes=" + context.rangeStart + "-" + String(context.rangeEnd - 1));
  34865. }
  34866. return initParams;
  34867. }
  34868. function getByteRangeLength(byteRangeHeader) {
  34869. const result = BYTERANGE.exec(byteRangeHeader);
  34870. if (result) {
  34871. return parseInt(result[2]) - parseInt(result[1]) + 1;
  34872. }
  34873. }
  34874. function getContentLength(headers) {
  34875. const contentRange = headers.get("Content-Range");
  34876. if (contentRange) {
  34877. const byteRangeLength = getByteRangeLength(contentRange);
  34878. if (isFiniteNumber(byteRangeLength)) {
  34879. return byteRangeLength;
  34880. }
  34881. }
  34882. const contentLength = headers.get("Content-Length");
  34883. if (contentLength) {
  34884. return parseInt(contentLength);
  34885. }
  34886. }
  34887. function getRequest(context, initParams) {
  34888. return new self.Request(context.url, initParams);
  34889. }
  34890. class FetchError extends Error {
  34891. constructor(message, code, details) {
  34892. super(message);
  34893. this.code = void 0;
  34894. this.details = void 0;
  34895. this.code = code;
  34896. this.details = details;
  34897. }
  34898. }
  34899. const AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  34900. class XhrLoader {
  34901. constructor(config) {
  34902. this.xhrSetup = void 0;
  34903. this.requestTimeout = void 0;
  34904. this.retryTimeout = void 0;
  34905. this.retryDelay = void 0;
  34906. this.config = null;
  34907. this.callbacks = null;
  34908. this.context = null;
  34909. this.loader = null;
  34910. this.stats = void 0;
  34911. this.xhrSetup = config ? config.xhrSetup || null : null;
  34912. this.stats = new LoadStats();
  34913. this.retryDelay = 0;
  34914. }
  34915. destroy() {
  34916. this.callbacks = null;
  34917. this.abortInternal();
  34918. this.loader = null;
  34919. this.config = null;
  34920. this.context = null;
  34921. this.xhrSetup = null;
  34922. }
  34923. abortInternal() {
  34924. const loader = this.loader;
  34925. self.clearTimeout(this.requestTimeout);
  34926. self.clearTimeout(this.retryTimeout);
  34927. if (loader) {
  34928. loader.onreadystatechange = null;
  34929. loader.onprogress = null;
  34930. if (loader.readyState !== 4) {
  34931. this.stats.aborted = true;
  34932. loader.abort();
  34933. }
  34934. }
  34935. }
  34936. abort() {
  34937. var _this$callbacks;
  34938. this.abortInternal();
  34939. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  34940. this.callbacks.onAbort(this.stats, this.context, this.loader);
  34941. }
  34942. }
  34943. load(context, config, callbacks) {
  34944. if (this.stats.loading.start) {
  34945. throw new Error("Loader can only be used once.");
  34946. }
  34947. this.stats.loading.start = self.performance.now();
  34948. this.context = context;
  34949. this.config = config;
  34950. this.callbacks = callbacks;
  34951. this.loadInternal();
  34952. }
  34953. loadInternal() {
  34954. const {
  34955. config,
  34956. context
  34957. } = this;
  34958. if (!config || !context) {
  34959. return;
  34960. }
  34961. const xhr = this.loader = new self.XMLHttpRequest();
  34962. const stats = this.stats;
  34963. stats.loading.first = 0;
  34964. stats.loaded = 0;
  34965. stats.aborted = false;
  34966. const xhrSetup = this.xhrSetup;
  34967. if (xhrSetup) {
  34968. Promise.resolve().then(() => {
  34969. if (this.loader !== xhr || this.stats.aborted)
  34970. return;
  34971. return xhrSetup(xhr, context.url);
  34972. }).catch((error) => {
  34973. if (this.loader !== xhr || this.stats.aborted)
  34974. return;
  34975. xhr.open("GET", context.url, true);
  34976. return xhrSetup(xhr, context.url);
  34977. }).then(() => {
  34978. if (this.loader !== xhr || this.stats.aborted)
  34979. return;
  34980. this.openAndSendXhr(xhr, context, config);
  34981. }).catch((error) => {
  34982. var _this$callbacks2;
  34983. (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onError({
  34984. code: xhr.status,
  34985. text: error.message
  34986. }, context, xhr, stats);
  34987. return;
  34988. });
  34989. } else {
  34990. this.openAndSendXhr(xhr, context, config);
  34991. }
  34992. }
  34993. openAndSendXhr(xhr, context, config) {
  34994. if (!xhr.readyState) {
  34995. xhr.open("GET", context.url, true);
  34996. }
  34997. const headers = context.headers;
  34998. const {
  34999. maxTimeToFirstByteMs,
  35000. maxLoadTimeMs
  35001. } = config.loadPolicy;
  35002. if (headers) {
  35003. for (const header in headers) {
  35004. xhr.setRequestHeader(header, headers[header]);
  35005. }
  35006. }
  35007. if (context.rangeEnd) {
  35008. xhr.setRequestHeader("Range", "bytes=" + context.rangeStart + "-" + (context.rangeEnd - 1));
  35009. }
  35010. xhr.onreadystatechange = this.readystatechange.bind(this);
  35011. xhr.onprogress = this.loadprogress.bind(this);
  35012. xhr.responseType = context.responseType;
  35013. self.clearTimeout(this.requestTimeout);
  35014. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  35015. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  35016. xhr.send();
  35017. }
  35018. readystatechange() {
  35019. const {
  35020. context,
  35021. loader: xhr,
  35022. stats
  35023. } = this;
  35024. if (!context || !xhr) {
  35025. return;
  35026. }
  35027. const readyState = xhr.readyState;
  35028. const config = this.config;
  35029. if (stats.aborted) {
  35030. return;
  35031. }
  35032. if (readyState >= 2) {
  35033. if (stats.loading.first === 0) {
  35034. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  35035. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  35036. self.clearTimeout(this.requestTimeout);
  35037. config.timeout = config.loadPolicy.maxLoadTimeMs;
  35038. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  35039. }
  35040. }
  35041. if (readyState === 4) {
  35042. self.clearTimeout(this.requestTimeout);
  35043. xhr.onreadystatechange = null;
  35044. xhr.onprogress = null;
  35045. const status2 = xhr.status;
  35046. const useResponseText = xhr.responseType === "text" ? xhr.responseText : null;
  35047. if (status2 >= 200 && status2 < 300) {
  35048. const data = useResponseText != null ? useResponseText : xhr.response;
  35049. if (data != null) {
  35050. var _this$callbacks3, _this$callbacks4;
  35051. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  35052. const len = xhr.responseType === "arraybuffer" ? data.byteLength : data.length;
  35053. stats.loaded = stats.total = len;
  35054. stats.bwEstimate = stats.total * 8e3 / (stats.loading.end - stats.loading.first);
  35055. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  35056. if (onProgress) {
  35057. onProgress(stats, context, data, xhr);
  35058. }
  35059. const _response = {
  35060. url: xhr.responseURL,
  35061. data,
  35062. code: status2
  35063. };
  35064. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(_response, stats, context, xhr);
  35065. return;
  35066. }
  35067. }
  35068. const retryConfig = config.loadPolicy.errorRetry;
  35069. const retryCount = stats.retry;
  35070. const response = {
  35071. url: context.url,
  35072. data: void 0,
  35073. code: status2
  35074. };
  35075. if (shouldRetry(retryConfig, retryCount, false, response)) {
  35076. this.retry(retryConfig);
  35077. } else {
  35078. var _this$callbacks5;
  35079. logger.error(`${status2} while loading ${context.url}`);
  35080. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  35081. code: status2,
  35082. text: xhr.statusText
  35083. }, context, xhr, stats);
  35084. }
  35085. }
  35086. }
  35087. }
  35088. loadtimeout() {
  35089. if (!this.config)
  35090. return;
  35091. const retryConfig = this.config.loadPolicy.timeoutRetry;
  35092. const retryCount = this.stats.retry;
  35093. if (shouldRetry(retryConfig, retryCount, true)) {
  35094. this.retry(retryConfig);
  35095. } else {
  35096. var _this$context;
  35097. logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);
  35098. const callbacks = this.callbacks;
  35099. if (callbacks) {
  35100. this.abortInternal();
  35101. callbacks.onTimeout(this.stats, this.context, this.loader);
  35102. }
  35103. }
  35104. }
  35105. retry(retryConfig) {
  35106. const {
  35107. context,
  35108. stats
  35109. } = this;
  35110. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  35111. stats.retry++;
  35112. logger.warn(`${status ? "HTTP Status " + status : "Timeout"} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`);
  35113. this.abortInternal();
  35114. this.loader = null;
  35115. self.clearTimeout(this.retryTimeout);
  35116. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  35117. }
  35118. loadprogress(event) {
  35119. const stats = this.stats;
  35120. stats.loaded = event.loaded;
  35121. if (event.lengthComputable) {
  35122. stats.total = event.total;
  35123. }
  35124. }
  35125. getCacheAge() {
  35126. let result = null;
  35127. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  35128. const ageHeader = this.loader.getResponseHeader("age");
  35129. result = ageHeader ? parseFloat(ageHeader) : null;
  35130. }
  35131. return result;
  35132. }
  35133. getResponseHeader(name) {
  35134. if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, "im").test(this.loader.getAllResponseHeaders())) {
  35135. return this.loader.getResponseHeader(name);
  35136. }
  35137. return null;
  35138. }
  35139. }
  35140. const defaultLoadPolicy = {
  35141. maxTimeToFirstByteMs: 8e3,
  35142. maxLoadTimeMs: 2e4,
  35143. timeoutRetry: null,
  35144. errorRetry: null
  35145. };
  35146. const hlsDefaultConfig = _objectSpread2(_objectSpread2({
  35147. autoStartLoad: true,
  35148. // used by stream-controller
  35149. startPosition: -1,
  35150. // used by stream-controller
  35151. defaultAudioCodec: void 0,
  35152. // used by stream-controller
  35153. debug: false,
  35154. // used by logger
  35155. capLevelOnFPSDrop: false,
  35156. // used by fps-controller
  35157. capLevelToPlayerSize: false,
  35158. // used by cap-level-controller
  35159. ignoreDevicePixelRatio: false,
  35160. // used by cap-level-controller
  35161. maxDevicePixelRatio: Number.POSITIVE_INFINITY,
  35162. // used by cap-level-controller
  35163. preferManagedMediaSource: true,
  35164. initialLiveManifestSize: 1,
  35165. // used by stream-controller
  35166. maxBufferLength: 30,
  35167. // used by stream-controller
  35168. backBufferLength: Infinity,
  35169. // used by buffer-controller
  35170. frontBufferFlushThreshold: Infinity,
  35171. startOnSegmentBoundary: false,
  35172. // used by stream-controller
  35173. maxBufferSize: 60 * 1e3 * 1e3,
  35174. // used by stream-controller
  35175. maxFragLookUpTolerance: 0.25,
  35176. // used by stream-controller
  35177. maxBufferHole: 0.1,
  35178. // used by stream-controller and gap-controller
  35179. detectStallWithCurrentTimeMs: 1250,
  35180. // used by gap-controller
  35181. highBufferWatchdogPeriod: 2,
  35182. // used by gap-controller
  35183. nudgeOffset: 0.1,
  35184. // used by gap-controller
  35185. nudgeMaxRetry: 3,
  35186. // used by gap-controller
  35187. nudgeOnVideoHole: true,
  35188. // used by gap-controller
  35189. liveSyncMode: "edge",
  35190. // used by stream-controller
  35191. liveSyncDurationCount: 3,
  35192. // used by latency-controller
  35193. liveSyncOnStallIncrease: 1,
  35194. // used by latency-controller
  35195. liveMaxLatencyDurationCount: Infinity,
  35196. // used by latency-controller
  35197. liveSyncDuration: void 0,
  35198. // used by latency-controller
  35199. liveMaxLatencyDuration: void 0,
  35200. // used by latency-controller
  35201. maxLiveSyncPlaybackRate: 1,
  35202. // used by latency-controller
  35203. liveDurationInfinity: false,
  35204. // used by buffer-controller
  35205. /**
  35206. * @deprecated use backBufferLength
  35207. */
  35208. liveBackBufferLength: null,
  35209. // used by buffer-controller
  35210. maxMaxBufferLength: 600,
  35211. // used by stream-controller
  35212. enableWorker: true,
  35213. // used by transmuxer
  35214. workerPath: null,
  35215. // used by transmuxer
  35216. enableSoftwareAES: true,
  35217. // used by decrypter
  35218. startLevel: void 0,
  35219. // used by level-controller
  35220. startFragPrefetch: false,
  35221. // used by stream-controller
  35222. fpsDroppedMonitoringPeriod: 5e3,
  35223. // used by fps-controller
  35224. fpsDroppedMonitoringThreshold: 0.2,
  35225. // used by fps-controller
  35226. appendErrorMaxRetry: 3,
  35227. // used by buffer-controller
  35228. ignorePlaylistParsingErrors: false,
  35229. loader: XhrLoader,
  35230. // loader: FetchLoader,
  35231. fLoader: void 0,
  35232. // used by fragment-loader
  35233. pLoader: void 0,
  35234. // used by playlist-loader
  35235. xhrSetup: void 0,
  35236. // used by xhr-loader
  35237. licenseXhrSetup: void 0,
  35238. // used by eme-controller
  35239. licenseResponseCallback: void 0,
  35240. // used by eme-controller
  35241. abrController: AbrController,
  35242. bufferController: BufferController,
  35243. capLevelController: CapLevelController,
  35244. errorController: ErrorController,
  35245. fpsController: FPSController,
  35246. stretchShortVideoTrack: false,
  35247. // used by mp4-remuxer
  35248. maxAudioFramesDrift: 1,
  35249. // used by mp4-remuxer
  35250. forceKeyFrameOnDiscontinuity: true,
  35251. // used by ts-demuxer
  35252. abrEwmaFastLive: 3,
  35253. // used by abr-controller
  35254. abrEwmaSlowLive: 9,
  35255. // used by abr-controller
  35256. abrEwmaFastVoD: 3,
  35257. // used by abr-controller
  35258. abrEwmaSlowVoD: 9,
  35259. // used by abr-controller
  35260. abrEwmaDefaultEstimate: 5e5,
  35261. // 500 kbps // used by abr-controller
  35262. abrEwmaDefaultEstimateMax: 5e6,
  35263. // 5 mbps
  35264. abrBandWidthFactor: 0.95,
  35265. // used by abr-controller
  35266. abrBandWidthUpFactor: 0.7,
  35267. // used by abr-controller
  35268. abrMaxWithRealBitrate: false,
  35269. // used by abr-controller
  35270. maxStarvationDelay: 4,
  35271. // used by abr-controller
  35272. maxLoadingDelay: 4,
  35273. // used by abr-controller
  35274. minAutoBitrate: 0,
  35275. // used by hls
  35276. emeEnabled: false,
  35277. // used by eme-controller
  35278. widevineLicenseUrl: void 0,
  35279. // used by eme-controller
  35280. drmSystems: {},
  35281. // used by eme-controller
  35282. drmSystemOptions: {},
  35283. // used by eme-controller
  35284. requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess,
  35285. // used by eme-controller
  35286. requireKeySystemAccessOnStart: false,
  35287. // used by eme-controller
  35288. testBandwidth: true,
  35289. progressive: false,
  35290. lowLatencyMode: true,
  35291. cmcd: void 0,
  35292. enableDateRangeMetadataCues: true,
  35293. enableEmsgMetadataCues: true,
  35294. enableEmsgKLVMetadata: false,
  35295. enableID3MetadataCues: true,
  35296. enableInterstitialPlayback: true,
  35297. interstitialAppendInPlace: true,
  35298. interstitialLiveLookAhead: 10,
  35299. useMediaCapabilities: true,
  35300. preserveManualLevelOnError: false,
  35301. certLoadPolicy: {
  35302. default: defaultLoadPolicy
  35303. },
  35304. keyLoadPolicy: {
  35305. default: {
  35306. maxTimeToFirstByteMs: 8e3,
  35307. maxLoadTimeMs: 2e4,
  35308. timeoutRetry: {
  35309. maxNumRetry: 1,
  35310. retryDelayMs: 1e3,
  35311. maxRetryDelayMs: 2e4,
  35312. backoff: "linear"
  35313. },
  35314. errorRetry: {
  35315. maxNumRetry: 8,
  35316. retryDelayMs: 1e3,
  35317. maxRetryDelayMs: 2e4,
  35318. backoff: "linear"
  35319. }
  35320. }
  35321. },
  35322. manifestLoadPolicy: {
  35323. default: {
  35324. maxTimeToFirstByteMs: Infinity,
  35325. maxLoadTimeMs: 2e4,
  35326. timeoutRetry: {
  35327. maxNumRetry: 2,
  35328. retryDelayMs: 0,
  35329. maxRetryDelayMs: 0
  35330. },
  35331. errorRetry: {
  35332. maxNumRetry: 1,
  35333. retryDelayMs: 1e3,
  35334. maxRetryDelayMs: 8e3
  35335. }
  35336. }
  35337. },
  35338. playlistLoadPolicy: {
  35339. default: {
  35340. maxTimeToFirstByteMs: 1e4,
  35341. maxLoadTimeMs: 2e4,
  35342. timeoutRetry: {
  35343. maxNumRetry: 2,
  35344. retryDelayMs: 0,
  35345. maxRetryDelayMs: 0
  35346. },
  35347. errorRetry: {
  35348. maxNumRetry: 2,
  35349. retryDelayMs: 1e3,
  35350. maxRetryDelayMs: 8e3
  35351. }
  35352. }
  35353. },
  35354. fragLoadPolicy: {
  35355. default: {
  35356. maxTimeToFirstByteMs: 1e4,
  35357. maxLoadTimeMs: 12e4,
  35358. timeoutRetry: {
  35359. maxNumRetry: 4,
  35360. retryDelayMs: 0,
  35361. maxRetryDelayMs: 0
  35362. },
  35363. errorRetry: {
  35364. maxNumRetry: 6,
  35365. retryDelayMs: 1e3,
  35366. maxRetryDelayMs: 8e3
  35367. }
  35368. }
  35369. },
  35370. steeringManifestLoadPolicy: {
  35371. default: {
  35372. maxTimeToFirstByteMs: 1e4,
  35373. maxLoadTimeMs: 2e4,
  35374. timeoutRetry: {
  35375. maxNumRetry: 2,
  35376. retryDelayMs: 0,
  35377. maxRetryDelayMs: 0
  35378. },
  35379. errorRetry: {
  35380. maxNumRetry: 1,
  35381. retryDelayMs: 1e3,
  35382. maxRetryDelayMs: 8e3
  35383. }
  35384. }
  35385. },
  35386. interstitialAssetListLoadPolicy: {
  35387. default: {
  35388. maxTimeToFirstByteMs: 1e4,
  35389. maxLoadTimeMs: 3e4,
  35390. timeoutRetry: {
  35391. maxNumRetry: 0,
  35392. retryDelayMs: 0,
  35393. maxRetryDelayMs: 0
  35394. },
  35395. errorRetry: {
  35396. maxNumRetry: 0,
  35397. retryDelayMs: 1e3,
  35398. maxRetryDelayMs: 8e3
  35399. }
  35400. }
  35401. },
  35402. // These default settings are deprecated in favor of the above policies
  35403. // and are maintained for backwards compatibility
  35404. manifestLoadingTimeOut: 1e4,
  35405. manifestLoadingMaxRetry: 1,
  35406. manifestLoadingRetryDelay: 1e3,
  35407. manifestLoadingMaxRetryTimeout: 64e3,
  35408. levelLoadingTimeOut: 1e4,
  35409. levelLoadingMaxRetry: 4,
  35410. levelLoadingRetryDelay: 1e3,
  35411. levelLoadingMaxRetryTimeout: 64e3,
  35412. fragLoadingTimeOut: 2e4,
  35413. fragLoadingMaxRetry: 6,
  35414. fragLoadingRetryDelay: 1e3,
  35415. fragLoadingMaxRetryTimeout: 64e3
  35416. }, timelineConfig()), {}, {
  35417. subtitleStreamController: SubtitleStreamController,
  35418. subtitleTrackController: SubtitleTrackController,
  35419. timelineController: TimelineController,
  35420. audioStreamController: AudioStreamController,
  35421. audioTrackController: AudioTrackController,
  35422. emeController: EMEController,
  35423. cmcdController: CMCDController,
  35424. contentSteeringController: ContentSteeringController,
  35425. interstitialsController: InterstitialsController
  35426. });
  35427. function timelineConfig() {
  35428. return {
  35429. cueHandler: Cues,
  35430. // used by timeline-controller
  35431. enableWebVTT: true,
  35432. // used by timeline-controller
  35433. enableIMSC1: true,
  35434. // used by timeline-controller
  35435. enableCEA708Captions: true,
  35436. // used by timeline-controller
  35437. captionsTextTrack1Label: "English",
  35438. // used by timeline-controller
  35439. captionsTextTrack1LanguageCode: "en",
  35440. // used by timeline-controller
  35441. captionsTextTrack2Label: "Spanish",
  35442. // used by timeline-controller
  35443. captionsTextTrack2LanguageCode: "es",
  35444. // used by timeline-controller
  35445. captionsTextTrack3Label: "Unknown CC",
  35446. // used by timeline-controller
  35447. captionsTextTrack3LanguageCode: "",
  35448. // used by timeline-controller
  35449. captionsTextTrack4Label: "Unknown CC",
  35450. // used by timeline-controller
  35451. captionsTextTrack4LanguageCode: "",
  35452. // used by timeline-controller
  35453. renderTextTracksNatively: true
  35454. };
  35455. }
  35456. function mergeConfig(defaultConfig, userConfig, logger2) {
  35457. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  35458. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  35459. }
  35460. if (userConfig.liveMaxLatencyDurationCount !== void 0 && (userConfig.liveSyncDurationCount === void 0 || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  35461. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  35462. }
  35463. if (userConfig.liveMaxLatencyDuration !== void 0 && (userConfig.liveSyncDuration === void 0 || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  35464. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  35465. }
  35466. const defaultsCopy = deepCpy(defaultConfig);
  35467. const deprecatedSettingTypes = ["manifest", "level", "frag"];
  35468. const deprecatedSettings = ["TimeOut", "MaxRetry", "RetryDelay", "MaxRetryTimeout"];
  35469. deprecatedSettingTypes.forEach((type) => {
  35470. const policyName = `${type === "level" ? "playlist" : type}LoadPolicy`;
  35471. const policyNotSet = userConfig[policyName] === void 0;
  35472. const report = [];
  35473. deprecatedSettings.forEach((setting) => {
  35474. const deprecatedSetting = `${type}Loading${setting}`;
  35475. const value = userConfig[deprecatedSetting];
  35476. if (value !== void 0 && policyNotSet) {
  35477. report.push(deprecatedSetting);
  35478. const settings = defaultsCopy[policyName].default;
  35479. userConfig[policyName] = {
  35480. default: settings
  35481. };
  35482. switch (setting) {
  35483. case "TimeOut":
  35484. settings.maxLoadTimeMs = value;
  35485. settings.maxTimeToFirstByteMs = value;
  35486. break;
  35487. case "MaxRetry":
  35488. settings.errorRetry.maxNumRetry = value;
  35489. settings.timeoutRetry.maxNumRetry = value;
  35490. break;
  35491. case "RetryDelay":
  35492. settings.errorRetry.retryDelayMs = value;
  35493. settings.timeoutRetry.retryDelayMs = value;
  35494. break;
  35495. case "MaxRetryTimeout":
  35496. settings.errorRetry.maxRetryDelayMs = value;
  35497. settings.timeoutRetry.maxRetryDelayMs = value;
  35498. break;
  35499. }
  35500. }
  35501. });
  35502. if (report.length) {
  35503. logger2.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${stringify(userConfig[policyName])}`);
  35504. }
  35505. });
  35506. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  35507. }
  35508. function deepCpy(obj) {
  35509. if (obj && typeof obj === "object") {
  35510. if (Array.isArray(obj)) {
  35511. return obj.map(deepCpy);
  35512. }
  35513. return Object.keys(obj).reduce((result, key) => {
  35514. result[key] = deepCpy(obj[key]);
  35515. return result;
  35516. }, {});
  35517. }
  35518. return obj;
  35519. }
  35520. function enableStreamingMode(config, logger2) {
  35521. const currentLoader = config.loader;
  35522. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  35523. logger2.log("[config]: Custom loader detected, cannot enable progressive streaming");
  35524. config.progressive = false;
  35525. } else {
  35526. const canStreamProgressively = fetchSupported();
  35527. if (canStreamProgressively) {
  35528. config.loader = FetchLoader;
  35529. config.progressive = true;
  35530. config.enableSoftwareAES = true;
  35531. logger2.log("[config]: Progressive streaming enabled, using FetchLoader");
  35532. }
  35533. }
  35534. }
  35535. const MAX_START_GAP_JUMP = 2;
  35536. const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  35537. const SKIP_BUFFER_RANGE_START = 0.05;
  35538. const TICK_INTERVAL$1 = 100;
  35539. class GapController extends TaskLoop {
  35540. constructor(hls, fragmentTracker) {
  35541. super("gap-controller", hls.logger);
  35542. this.hls = null;
  35543. this.fragmentTracker = null;
  35544. this.media = null;
  35545. this.mediaSource = void 0;
  35546. this.nudgeRetry = 0;
  35547. this.stallReported = false;
  35548. this.stalled = null;
  35549. this.moved = false;
  35550. this.seeking = false;
  35551. this.buffered = {};
  35552. this.lastCurrentTime = 0;
  35553. this.ended = 0;
  35554. this.waiting = 0;
  35555. this.onMediaPlaying = () => {
  35556. this.ended = 0;
  35557. this.waiting = 0;
  35558. };
  35559. this.onMediaWaiting = () => {
  35560. var _this$media;
  35561. if ((_this$media = this.media) != null && _this$media.seeking) {
  35562. return;
  35563. }
  35564. this.waiting = self.performance.now();
  35565. this.tick();
  35566. };
  35567. this.onMediaEnded = () => {
  35568. if (this.hls) {
  35569. var _this$media2;
  35570. this.ended = ((_this$media2 = this.media) == null ? void 0 : _this$media2.currentTime) || 1;
  35571. this.hls.trigger(Events.MEDIA_ENDED, {
  35572. stalled: false
  35573. });
  35574. }
  35575. };
  35576. this.hls = hls;
  35577. this.fragmentTracker = fragmentTracker;
  35578. this.registerListeners();
  35579. }
  35580. registerListeners() {
  35581. const {
  35582. hls
  35583. } = this;
  35584. if (hls) {
  35585. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  35586. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  35587. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  35588. }
  35589. }
  35590. unregisterListeners() {
  35591. const {
  35592. hls
  35593. } = this;
  35594. if (hls) {
  35595. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  35596. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  35597. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  35598. }
  35599. }
  35600. destroy() {
  35601. super.destroy();
  35602. this.unregisterListeners();
  35603. this.media = this.hls = this.fragmentTracker = null;
  35604. this.mediaSource = void 0;
  35605. }
  35606. onMediaAttached(event, data) {
  35607. this.setInterval(TICK_INTERVAL$1);
  35608. this.mediaSource = data.mediaSource;
  35609. const media = this.media = data.media;
  35610. addEventListener(media, "playing", this.onMediaPlaying);
  35611. addEventListener(media, "waiting", this.onMediaWaiting);
  35612. addEventListener(media, "ended", this.onMediaEnded);
  35613. }
  35614. onMediaDetaching(event, data) {
  35615. this.clearInterval();
  35616. const {
  35617. media
  35618. } = this;
  35619. if (media) {
  35620. removeEventListener(media, "playing", this.onMediaPlaying);
  35621. removeEventListener(media, "waiting", this.onMediaWaiting);
  35622. removeEventListener(media, "ended", this.onMediaEnded);
  35623. this.media = null;
  35624. }
  35625. this.mediaSource = void 0;
  35626. }
  35627. onBufferAppended(event, data) {
  35628. this.buffered = data.timeRanges;
  35629. }
  35630. get hasBuffered() {
  35631. return Object.keys(this.buffered).length > 0;
  35632. }
  35633. tick() {
  35634. var _this$media3;
  35635. if (!((_this$media3 = this.media) != null && _this$media3.readyState) || !this.hasBuffered) {
  35636. return;
  35637. }
  35638. const currentTime = this.media.currentTime;
  35639. this.poll(currentTime, this.lastCurrentTime);
  35640. this.lastCurrentTime = currentTime;
  35641. }
  35642. /**
  35643. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  35644. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  35645. *
  35646. * @param lastCurrentTime - Previously read playhead position
  35647. */
  35648. poll(currentTime, lastCurrentTime) {
  35649. var _this$hls, _this$hls2;
  35650. const config = (_this$hls = this.hls) == null ? void 0 : _this$hls.config;
  35651. if (!config) {
  35652. return;
  35653. }
  35654. const media = this.media;
  35655. if (!media) {
  35656. return;
  35657. }
  35658. const {
  35659. seeking
  35660. } = media;
  35661. const seeked = this.seeking && !seeking;
  35662. const beginSeek = !this.seeking && seeking;
  35663. const pausedEndedOrHalted = media.paused && !seeking || media.ended || media.playbackRate === 0;
  35664. this.seeking = seeking;
  35665. if (currentTime !== lastCurrentTime) {
  35666. if (lastCurrentTime) {
  35667. this.ended = 0;
  35668. }
  35669. this.moved = true;
  35670. if (!seeking) {
  35671. this.nudgeRetry = 0;
  35672. if (config.nudgeOnVideoHole && !pausedEndedOrHalted && currentTime > lastCurrentTime) {
  35673. this.nudgeOnVideoHole(currentTime, lastCurrentTime);
  35674. }
  35675. }
  35676. if (this.waiting === 0) {
  35677. this.stallResolved(currentTime);
  35678. }
  35679. return;
  35680. }
  35681. if (beginSeek || seeked) {
  35682. if (seeked) {
  35683. this.stallResolved(currentTime);
  35684. }
  35685. return;
  35686. }
  35687. if (pausedEndedOrHalted) {
  35688. this.nudgeRetry = 0;
  35689. this.stallResolved(currentTime);
  35690. if (!this.ended && media.ended && this.hls) {
  35691. this.ended = currentTime || 1;
  35692. this.hls.trigger(Events.MEDIA_ENDED, {
  35693. stalled: false
  35694. });
  35695. }
  35696. return;
  35697. }
  35698. if (!BufferHelper.getBuffered(media).length) {
  35699. this.nudgeRetry = 0;
  35700. return;
  35701. }
  35702. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  35703. const nextStart = bufferInfo.nextStart || 0;
  35704. const fragmentTracker = this.fragmentTracker;
  35705. if (seeking && fragmentTracker && this.hls) {
  35706. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, currentTime);
  35707. const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  35708. const noBufferHole = !nextStart || inFlightDependency || nextStart - currentTime > MAX_START_GAP_JUMP && !fragmentTracker.getPartialFragment(currentTime);
  35709. if (hasEnoughBuffer || noBufferHole) {
  35710. return;
  35711. }
  35712. this.moved = false;
  35713. }
  35714. const levelDetails = (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails;
  35715. if (!this.moved && this.stalled !== null && fragmentTracker) {
  35716. const isBuffered = bufferInfo.len > 0;
  35717. if (!isBuffered && !nextStart) {
  35718. return;
  35719. }
  35720. const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  35721. const isLive = !!(levelDetails != null && levelDetails.live);
  35722. const maxStartGapJump = isLive ? levelDetails.targetduration * 2 : MAX_START_GAP_JUMP;
  35723. const partialOrGap = fragmentTracker.getPartialFragment(currentTime);
  35724. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  35725. if (!media.paused) {
  35726. this._trySkipBufferHole(partialOrGap);
  35727. }
  35728. return;
  35729. }
  35730. }
  35731. const detectStallWithCurrentTimeMs = config.detectStallWithCurrentTimeMs;
  35732. const tnow = self.performance.now();
  35733. const tWaiting = this.waiting;
  35734. let stalled = this.stalled;
  35735. if (stalled === null) {
  35736. if (tWaiting > 0 && tnow - tWaiting < detectStallWithCurrentTimeMs) {
  35737. stalled = this.stalled = tWaiting;
  35738. } else {
  35739. this.stalled = tnow;
  35740. return;
  35741. }
  35742. }
  35743. const stalledDuration = tnow - stalled;
  35744. if (!seeking && (stalledDuration >= detectStallWithCurrentTimeMs || tWaiting) && this.hls) {
  35745. var _this$mediaSource;
  35746. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) === "ended" && !(levelDetails != null && levelDetails.live) && Math.abs(currentTime - ((levelDetails == null ? void 0 : levelDetails.edge) || 0)) < 1) {
  35747. if (this.ended) {
  35748. return;
  35749. }
  35750. this.ended = currentTime || 1;
  35751. this.hls.trigger(Events.MEDIA_ENDED, {
  35752. stalled: true
  35753. });
  35754. return;
  35755. }
  35756. this._reportStall(bufferInfo);
  35757. if (!this.media || !this.hls) {
  35758. return;
  35759. }
  35760. }
  35761. const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  35762. this._tryFixBufferStall(bufferedWithHoles, stalledDuration, currentTime);
  35763. }
  35764. stallResolved(currentTime) {
  35765. const stalled = this.stalled;
  35766. if (stalled && this.hls) {
  35767. this.stalled = null;
  35768. if (this.stallReported) {
  35769. const stalledDuration = self.performance.now() - stalled;
  35770. this.log(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);
  35771. this.stallReported = false;
  35772. this.waiting = 0;
  35773. this.hls.trigger(Events.STALL_RESOLVED, {});
  35774. }
  35775. }
  35776. }
  35777. nudgeOnVideoHole(currentTime, lastCurrentTime) {
  35778. var _this$buffered$audio;
  35779. const videoSourceBuffered = this.buffered.video;
  35780. if (this.hls && this.media && this.fragmentTracker && (_this$buffered$audio = this.buffered.audio) != null && _this$buffered$audio.length && videoSourceBuffered && videoSourceBuffered.length > 1 && currentTime > videoSourceBuffered.end(0)) {
  35781. const audioBufferInfo = BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio), currentTime, 0);
  35782. if (audioBufferInfo.len > 1 && lastCurrentTime >= audioBufferInfo.start) {
  35783. const videoTimes = BufferHelper.timeRangesToArray(videoSourceBuffered);
  35784. const lastBufferedIndex = BufferHelper.bufferedInfo(videoTimes, lastCurrentTime, 0).bufferedIndex;
  35785. if (lastBufferedIndex > -1 && lastBufferedIndex < videoTimes.length - 1) {
  35786. const bufferedIndex = BufferHelper.bufferedInfo(videoTimes, currentTime, 0).bufferedIndex;
  35787. const holeStart = videoTimes[lastBufferedIndex].end;
  35788. const holeEnd = videoTimes[lastBufferedIndex + 1].start;
  35789. if ((bufferedIndex === -1 || bufferedIndex > lastBufferedIndex) && holeEnd - holeStart < 1 && // `maxBufferHole` may be too small and setting it to 0 should not disable this feature
  35790. currentTime - holeStart < 2) {
  35791. const error = new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${currentTime} hole: ${holeStart} -> ${holeEnd} buffered index: ${bufferedIndex}`);
  35792. this.warn(error.message);
  35793. this.media.currentTime += 1e-6;
  35794. const frag = this.fragmentTracker.getPartialFragment(currentTime) || void 0;
  35795. const bufferInfo = BufferHelper.bufferInfo(this.media, currentTime, 0);
  35796. this.hls.trigger(Events.ERROR, {
  35797. type: ErrorTypes.MEDIA_ERROR,
  35798. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  35799. fatal: false,
  35800. error,
  35801. reason: error.message,
  35802. frag,
  35803. buffer: bufferInfo.len,
  35804. bufferInfo
  35805. });
  35806. }
  35807. }
  35808. }
  35809. }
  35810. }
  35811. /**
  35812. * Detects and attempts to fix known buffer stalling issues.
  35813. * @param bufferInfo - The properties of the current buffer.
  35814. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  35815. * @private
  35816. */
  35817. _tryFixBufferStall(bufferInfo, stalledDurationMs, currentTime) {
  35818. var _this$hls3, _this$hls4;
  35819. const {
  35820. fragmentTracker,
  35821. media
  35822. } = this;
  35823. const config = (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.config;
  35824. if (!media || !fragmentTracker || !config) {
  35825. return;
  35826. }
  35827. const levelDetails = (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.latestLevelDetails;
  35828. const partial2 = fragmentTracker.getPartialFragment(currentTime);
  35829. if (partial2 || levelDetails != null && levelDetails.live && currentTime < levelDetails.fragmentStart) {
  35830. const targetTime = this._trySkipBufferHole(partial2);
  35831. if (targetTime || !this.media) {
  35832. return;
  35833. }
  35834. }
  35835. const bufferedRanges = bufferInfo.buffered;
  35836. const adjacentTraversal = this.adjacentTraversal(bufferInfo, currentTime);
  35837. if ((bufferedRanges && bufferedRanges.length > 1 && bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && (bufferInfo.nextStart - currentTime < config.maxBufferHole || adjacentTraversal)) && (stalledDurationMs > config.highBufferWatchdogPeriod * 1e3 || this.waiting)) {
  35838. this.warn("Trying to nudge playhead over buffer-hole");
  35839. this._tryNudgeBuffer(bufferInfo);
  35840. }
  35841. }
  35842. adjacentTraversal(bufferInfo, currentTime) {
  35843. const fragmentTracker = this.fragmentTracker;
  35844. const nextStart = bufferInfo.nextStart;
  35845. if (fragmentTracker && nextStart) {
  35846. const current = fragmentTracker.getFragAtPos(currentTime, PlaylistLevelType.MAIN);
  35847. const next = fragmentTracker.getFragAtPos(nextStart, PlaylistLevelType.MAIN);
  35848. if (current && next) {
  35849. return next.sn - current.sn < 2;
  35850. }
  35851. }
  35852. return false;
  35853. }
  35854. /**
  35855. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  35856. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  35857. * @private
  35858. */
  35859. _reportStall(bufferInfo) {
  35860. const {
  35861. hls,
  35862. media,
  35863. stallReported,
  35864. stalled
  35865. } = this;
  35866. if (!stallReported && stalled !== null && media && hls) {
  35867. this.stallReported = true;
  35868. const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${stringify(bufferInfo)})`);
  35869. this.warn(error.message);
  35870. hls.trigger(Events.ERROR, {
  35871. type: ErrorTypes.MEDIA_ERROR,
  35872. details: ErrorDetails.BUFFER_STALLED_ERROR,
  35873. fatal: false,
  35874. error,
  35875. buffer: bufferInfo.len,
  35876. bufferInfo,
  35877. stalled: {
  35878. start: stalled
  35879. }
  35880. });
  35881. }
  35882. }
  35883. /**
  35884. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  35885. * @param partial - The partial fragment found at the current time (where playback is stalling).
  35886. * @private
  35887. */
  35888. _trySkipBufferHole(partial2) {
  35889. var _this$hls5;
  35890. const {
  35891. fragmentTracker,
  35892. media
  35893. } = this;
  35894. const config = (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.config;
  35895. if (!media || !fragmentTracker || !config) {
  35896. return 0;
  35897. }
  35898. const currentTime = media.currentTime;
  35899. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  35900. const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  35901. if (startTime && this.hls) {
  35902. const bufferStarved = bufferInfo.len <= config.maxBufferHole;
  35903. const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  35904. const gapLength = startTime - currentTime;
  35905. if (gapLength > 0 && (bufferStarved || waiting)) {
  35906. if (gapLength > config.maxBufferHole) {
  35907. let startGap = false;
  35908. if (currentTime === 0) {
  35909. const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  35910. if (startFrag && startTime < startFrag.end) {
  35911. startGap = true;
  35912. }
  35913. }
  35914. if (!startGap) {
  35915. const startProvisioned = partial2 || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  35916. if (startProvisioned) {
  35917. var _this$hls$loadLevelOb;
  35918. if (!((_this$hls$loadLevelOb = this.hls.loadLevelObj) != null && _this$hls$loadLevelOb.details)) {
  35919. return 0;
  35920. }
  35921. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, startTime);
  35922. if (inFlightDependency) {
  35923. return 0;
  35924. }
  35925. let moreToLoad = false;
  35926. let pos = startProvisioned.end;
  35927. while (pos < startTime) {
  35928. const provisioned = fragmentTracker.getAppendedFrag(pos, PlaylistLevelType.MAIN) || fragmentTracker.getPartialFragment(pos);
  35929. if (provisioned) {
  35930. pos += provisioned.duration;
  35931. } else {
  35932. moreToLoad = true;
  35933. break;
  35934. }
  35935. }
  35936. if (moreToLoad) {
  35937. return 0;
  35938. }
  35939. }
  35940. }
  35941. }
  35942. const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  35943. this.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);
  35944. this.moved = true;
  35945. media.currentTime = targetTime;
  35946. if (!(partial2 != null && partial2.gap)) {
  35947. const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);
  35948. this.hls.trigger(Events.ERROR, {
  35949. type: ErrorTypes.MEDIA_ERROR,
  35950. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  35951. fatal: false,
  35952. error,
  35953. reason: error.message,
  35954. frag: partial2 || void 0,
  35955. buffer: bufferInfo.len,
  35956. bufferInfo
  35957. });
  35958. }
  35959. return targetTime;
  35960. }
  35961. }
  35962. return 0;
  35963. }
  35964. /**
  35965. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  35966. * @private
  35967. */
  35968. _tryNudgeBuffer(bufferInfo) {
  35969. const {
  35970. hls,
  35971. media,
  35972. nudgeRetry
  35973. } = this;
  35974. const config = hls == null ? void 0 : hls.config;
  35975. if (!media || !config) {
  35976. return 0;
  35977. }
  35978. const currentTime = media.currentTime;
  35979. this.nudgeRetry++;
  35980. if (nudgeRetry < config.nudgeMaxRetry) {
  35981. const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  35982. const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);
  35983. this.warn(error.message);
  35984. media.currentTime = targetTime;
  35985. hls.trigger(Events.ERROR, {
  35986. type: ErrorTypes.MEDIA_ERROR,
  35987. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  35988. error,
  35989. fatal: false,
  35990. buffer: bufferInfo.len,
  35991. bufferInfo
  35992. });
  35993. } else {
  35994. const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);
  35995. this.error(error.message);
  35996. hls.trigger(Events.ERROR, {
  35997. type: ErrorTypes.MEDIA_ERROR,
  35998. details: ErrorDetails.BUFFER_STALLED_ERROR,
  35999. error,
  36000. fatal: true,
  36001. buffer: bufferInfo.len,
  36002. bufferInfo
  36003. });
  36004. }
  36005. }
  36006. }
  36007. function getInFlightDependency(inFlightFragments, currentTime) {
  36008. const main = inFlight(inFlightFragments.main);
  36009. if (main && main.start <= currentTime) {
  36010. return main;
  36011. }
  36012. const audio = inFlight(inFlightFragments.audio);
  36013. if (audio && audio.start <= currentTime) {
  36014. return audio;
  36015. }
  36016. return null;
  36017. }
  36018. function inFlight(inFlightData) {
  36019. if (!inFlightData) {
  36020. return null;
  36021. }
  36022. switch (inFlightData.state) {
  36023. case State.IDLE:
  36024. case State.STOPPED:
  36025. case State.ENDED:
  36026. case State.ERROR:
  36027. return null;
  36028. }
  36029. return inFlightData.frag;
  36030. }
  36031. const MIN_CUE_DURATION = 0.25;
  36032. function getCueClass() {
  36033. if (typeof self === "undefined")
  36034. return void 0;
  36035. return self.VTTCue || self.TextTrackCue;
  36036. }
  36037. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  36038. let cue = new Cue(startTime, endTime, "");
  36039. try {
  36040. cue.value = data;
  36041. if (type) {
  36042. cue.type = type;
  36043. }
  36044. } catch (e2) {
  36045. cue = new Cue(startTime, endTime, stringify(type ? _objectSpread2({
  36046. type
  36047. }, data) : data));
  36048. }
  36049. return cue;
  36050. }
  36051. const MAX_CUE_ENDTIME = (() => {
  36052. const Cue = getCueClass();
  36053. try {
  36054. Cue && new Cue(0, Number.POSITIVE_INFINITY, "");
  36055. } catch (e2) {
  36056. return Number.MAX_VALUE;
  36057. }
  36058. return Number.POSITIVE_INFINITY;
  36059. })();
  36060. class ID3TrackController {
  36061. constructor(hls) {
  36062. this.hls = void 0;
  36063. this.id3Track = null;
  36064. this.media = null;
  36065. this.dateRangeCuesAppended = {};
  36066. this.removeCues = true;
  36067. this.onEventCueEnter = () => {
  36068. if (!this.hls) {
  36069. return;
  36070. }
  36071. this.hls.trigger(Events.EVENT_CUE_ENTER, {});
  36072. };
  36073. this.hls = hls;
  36074. this._registerListeners();
  36075. }
  36076. destroy() {
  36077. this._unregisterListeners();
  36078. this.id3Track = null;
  36079. this.media = null;
  36080. this.dateRangeCuesAppended = {};
  36081. this.hls = this.onEventCueEnter = null;
  36082. }
  36083. _registerListeners() {
  36084. const {
  36085. hls
  36086. } = this;
  36087. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  36088. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  36089. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  36090. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  36091. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  36092. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  36093. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  36094. hls.on(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  36095. }
  36096. _unregisterListeners() {
  36097. const {
  36098. hls
  36099. } = this;
  36100. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  36101. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  36102. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  36103. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  36104. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  36105. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  36106. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  36107. hls.off(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  36108. }
  36109. // Add ID3 metatadata text track.
  36110. onMediaAttaching(event, data) {
  36111. var _data$overrides;
  36112. this.media = data.media;
  36113. if (((_data$overrides = data.overrides) == null ? void 0 : _data$overrides.cueRemoval) === false) {
  36114. this.removeCues = false;
  36115. }
  36116. }
  36117. onMediaAttached() {
  36118. const details = this.hls.latestLevelDetails;
  36119. if (details) {
  36120. this.updateDateRangeCues(details);
  36121. }
  36122. }
  36123. onMediaDetaching(event, data) {
  36124. this.media = null;
  36125. const transferringMedia = !!data.transferMedia;
  36126. if (transferringMedia) {
  36127. return;
  36128. }
  36129. if (this.id3Track) {
  36130. if (this.removeCues) {
  36131. clearCurrentCues(this.id3Track, this.onEventCueEnter);
  36132. }
  36133. this.id3Track = null;
  36134. }
  36135. this.dateRangeCuesAppended = {};
  36136. }
  36137. onManifestLoading() {
  36138. this.dateRangeCuesAppended = {};
  36139. }
  36140. createTrack(media) {
  36141. const track2 = this.getID3Track(media.textTracks);
  36142. track2.mode = "hidden";
  36143. return track2;
  36144. }
  36145. getID3Track(textTracks) {
  36146. if (!this.media) {
  36147. return;
  36148. }
  36149. for (let i2 = 0; i2 < textTracks.length; i2++) {
  36150. const textTrack = textTracks[i2];
  36151. if (textTrack.kind === "metadata" && textTrack.label === "id3") {
  36152. sendAddTrackEvent(textTrack, this.media);
  36153. return textTrack;
  36154. }
  36155. }
  36156. return this.media.addTextTrack("metadata", "id3");
  36157. }
  36158. onFragParsingMetadata(event, data) {
  36159. if (!this.media) {
  36160. return;
  36161. }
  36162. const {
  36163. hls: {
  36164. config: {
  36165. enableEmsgMetadataCues,
  36166. enableID3MetadataCues
  36167. }
  36168. }
  36169. } = this;
  36170. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  36171. return;
  36172. }
  36173. const {
  36174. samples
  36175. } = data;
  36176. if (!this.id3Track) {
  36177. this.id3Track = this.createTrack(this.media);
  36178. }
  36179. const Cue = getCueClass();
  36180. if (!Cue) {
  36181. return;
  36182. }
  36183. for (let i2 = 0; i2 < samples.length; i2++) {
  36184. const type = samples[i2].type;
  36185. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  36186. continue;
  36187. }
  36188. const frames = getId3Frames(samples[i2].data);
  36189. if (frames) {
  36190. const startTime = samples[i2].pts;
  36191. let endTime = startTime + samples[i2].duration;
  36192. if (endTime > MAX_CUE_ENDTIME) {
  36193. endTime = MAX_CUE_ENDTIME;
  36194. }
  36195. const timeDiff = endTime - startTime;
  36196. if (timeDiff <= 0) {
  36197. endTime = startTime + MIN_CUE_DURATION;
  36198. }
  36199. for (let j2 = 0; j2 < frames.length; j2++) {
  36200. const frame = frames[j2];
  36201. if (!isId3TimestampFrame(frame)) {
  36202. this.updateId3CueEnds(startTime, type);
  36203. const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  36204. if (cue) {
  36205. this.id3Track.addCue(cue);
  36206. }
  36207. }
  36208. }
  36209. }
  36210. }
  36211. }
  36212. updateId3CueEnds(startTime, type) {
  36213. var _this$id3Track;
  36214. const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  36215. if (cues) {
  36216. for (let i2 = cues.length; i2--; ) {
  36217. const cue = cues[i2];
  36218. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  36219. cue.endTime = startTime;
  36220. }
  36221. }
  36222. }
  36223. }
  36224. onBufferFlushing(event, {
  36225. startOffset,
  36226. endOffset,
  36227. type
  36228. }) {
  36229. const {
  36230. id3Track,
  36231. hls
  36232. } = this;
  36233. if (!hls) {
  36234. return;
  36235. }
  36236. const {
  36237. config: {
  36238. enableEmsgMetadataCues,
  36239. enableID3MetadataCues
  36240. }
  36241. } = hls;
  36242. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  36243. let predicate;
  36244. if (type === "audio") {
  36245. predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  36246. } else if (type === "video") {
  36247. predicate = (cue) => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  36248. } else {
  36249. predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  36250. }
  36251. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  36252. }
  36253. }
  36254. onLevelUpdated(event, {
  36255. details
  36256. }) {
  36257. this.updateDateRangeCues(details, true);
  36258. }
  36259. onLevelPtsUpdated(event, data) {
  36260. if (Math.abs(data.drift) > 0.01) {
  36261. this.updateDateRangeCues(data.details);
  36262. }
  36263. }
  36264. updateDateRangeCues(details, removeOldCues) {
  36265. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  36266. return;
  36267. }
  36268. const {
  36269. id3Track
  36270. } = this;
  36271. const {
  36272. dateRanges
  36273. } = details;
  36274. const ids = Object.keys(dateRanges);
  36275. let dateRangeCuesAppended = this.dateRangeCuesAppended;
  36276. if (id3Track && removeOldCues) {
  36277. var _id3Track$cues;
  36278. if ((_id3Track$cues = id3Track.cues) != null && _id3Track$cues.length) {
  36279. const idsToRemove = Object.keys(dateRangeCuesAppended).filter((id) => !ids.includes(id));
  36280. for (let i2 = idsToRemove.length; i2--; ) {
  36281. const id = idsToRemove[i2];
  36282. const cues = dateRangeCuesAppended[id].cues;
  36283. delete dateRangeCuesAppended[id];
  36284. Object.keys(cues).forEach((key) => {
  36285. try {
  36286. const cue = cues[key];
  36287. cue.removeEventListener("enter", this.onEventCueEnter);
  36288. id3Track.removeCue(cue);
  36289. } catch (e2) {
  36290. }
  36291. });
  36292. }
  36293. } else {
  36294. dateRangeCuesAppended = this.dateRangeCuesAppended = {};
  36295. }
  36296. }
  36297. const lastFragment = details.fragments[details.fragments.length - 1];
  36298. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  36299. return;
  36300. }
  36301. if (!this.id3Track) {
  36302. this.id3Track = this.createTrack(this.media);
  36303. }
  36304. const Cue = getCueClass();
  36305. for (let i2 = 0; i2 < ids.length; i2++) {
  36306. const id = ids[i2];
  36307. const dateRange = dateRanges[id];
  36308. const startTime = dateRange.startTime;
  36309. const appendedDateRangeCues = dateRangeCuesAppended[id];
  36310. const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  36311. let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  36312. let endTime = MAX_CUE_ENDTIME;
  36313. const {
  36314. duration,
  36315. endDate
  36316. } = dateRange;
  36317. if (endDate && duration !== null) {
  36318. endTime = startTime + duration;
  36319. durationKnown = true;
  36320. } else if (dateRange.endOnNext && !durationKnown) {
  36321. const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id2) => {
  36322. if (id2 !== dateRange.id) {
  36323. const otherDateRange = dateRanges[id2];
  36324. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  36325. return otherDateRange;
  36326. }
  36327. }
  36328. return candidateDateRange;
  36329. }, null);
  36330. if (nextDateRangeWithSameClass) {
  36331. endTime = nextDateRangeWithSameClass.startTime;
  36332. durationKnown = true;
  36333. }
  36334. }
  36335. const attributes = Object.keys(dateRange.attr);
  36336. for (let j2 = 0; j2 < attributes.length; j2++) {
  36337. const key = attributes[j2];
  36338. if (!isDateRangeCueAttribute(key)) {
  36339. continue;
  36340. }
  36341. const cue = cues[key];
  36342. if (cue) {
  36343. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  36344. cue.endTime = endTime;
  36345. } else if (Math.abs(cue.startTime - startTime) > 0.01) {
  36346. cue.startTime = startTime;
  36347. cue.endTime = endTime;
  36348. }
  36349. } else if (Cue) {
  36350. let data = dateRange.attr[key];
  36351. if (isSCTE35Attribute(key)) {
  36352. data = hexToArrayBuffer(data);
  36353. }
  36354. const payload = {
  36355. key,
  36356. data
  36357. };
  36358. const _cue = createCueWithDataFields(Cue, startTime, endTime, payload, MetadataSchema.dateRange);
  36359. if (_cue) {
  36360. _cue.id = id;
  36361. this.id3Track.addCue(_cue);
  36362. cues[key] = _cue;
  36363. if (this.hls.config.interstitialsController) {
  36364. if (key === "X-ASSET-LIST" || key === "X-ASSET-URL") {
  36365. _cue.addEventListener("enter", this.onEventCueEnter);
  36366. }
  36367. }
  36368. }
  36369. }
  36370. }
  36371. dateRangeCuesAppended[id] = {
  36372. cues,
  36373. dateRange,
  36374. durationKnown
  36375. };
  36376. }
  36377. }
  36378. }
  36379. class LatencyController {
  36380. constructor(hls) {
  36381. this.hls = void 0;
  36382. this.config = void 0;
  36383. this.media = null;
  36384. this.currentTime = 0;
  36385. this.stallCount = 0;
  36386. this._latency = null;
  36387. this._targetLatencyUpdated = false;
  36388. this.onTimeupdate = () => {
  36389. const {
  36390. media
  36391. } = this;
  36392. const levelDetails = this.levelDetails;
  36393. if (!media || !levelDetails) {
  36394. return;
  36395. }
  36396. this.currentTime = media.currentTime;
  36397. const latency = this.computeLatency();
  36398. if (latency === null) {
  36399. return;
  36400. }
  36401. this._latency = latency;
  36402. const {
  36403. lowLatencyMode,
  36404. maxLiveSyncPlaybackRate
  36405. } = this.config;
  36406. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  36407. return;
  36408. }
  36409. const targetLatency = this.targetLatency;
  36410. if (targetLatency === null) {
  36411. return;
  36412. }
  36413. const distanceFromTarget = latency - targetLatency;
  36414. const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  36415. const inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  36416. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  36417. const max = Math.min(2, Math.max(1, maxLiveSyncPlaybackRate));
  36418. const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  36419. const playbackRate = Math.min(max, Math.max(1, rate));
  36420. this.changeMediaPlaybackRate(media, playbackRate);
  36421. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  36422. this.changeMediaPlaybackRate(media, 1);
  36423. }
  36424. };
  36425. this.hls = hls;
  36426. this.config = hls.config;
  36427. this.registerListeners();
  36428. }
  36429. get levelDetails() {
  36430. var _this$hls;
  36431. return ((_this$hls = this.hls) == null ? void 0 : _this$hls.latestLevelDetails) || null;
  36432. }
  36433. get latency() {
  36434. return this._latency || 0;
  36435. }
  36436. get maxLatency() {
  36437. const {
  36438. config
  36439. } = this;
  36440. if (config.liveMaxLatencyDuration !== void 0) {
  36441. return config.liveMaxLatencyDuration;
  36442. }
  36443. const levelDetails = this.levelDetails;
  36444. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  36445. }
  36446. get targetLatency() {
  36447. const levelDetails = this.levelDetails;
  36448. if (levelDetails === null || this.hls === null) {
  36449. return null;
  36450. }
  36451. const {
  36452. holdBack,
  36453. partHoldBack,
  36454. targetduration
  36455. } = levelDetails;
  36456. const {
  36457. liveSyncDuration,
  36458. liveSyncDurationCount,
  36459. lowLatencyMode
  36460. } = this.config;
  36461. const userConfig = this.hls.userConfig;
  36462. let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  36463. if (this._targetLatencyUpdated || userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  36464. targetLatency = liveSyncDuration !== void 0 ? liveSyncDuration : liveSyncDurationCount * targetduration;
  36465. }
  36466. const maxLiveSyncOnStallIncrease = targetduration;
  36467. return targetLatency + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  36468. }
  36469. set targetLatency(latency) {
  36470. this.stallCount = 0;
  36471. this.config.liveSyncDuration = latency;
  36472. this._targetLatencyUpdated = true;
  36473. }
  36474. get liveSyncPosition() {
  36475. const liveEdge = this.estimateLiveEdge();
  36476. const targetLatency = this.targetLatency;
  36477. if (liveEdge === null || targetLatency === null) {
  36478. return null;
  36479. }
  36480. const levelDetails = this.levelDetails;
  36481. if (levelDetails === null) {
  36482. return null;
  36483. }
  36484. const edge = levelDetails.edge;
  36485. const syncPosition = liveEdge - targetLatency - this.edgeStalled;
  36486. const min = edge - levelDetails.totalduration;
  36487. const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  36488. return Math.min(Math.max(min, syncPosition), max);
  36489. }
  36490. get drift() {
  36491. const levelDetails = this.levelDetails;
  36492. if (levelDetails === null) {
  36493. return 1;
  36494. }
  36495. return levelDetails.drift;
  36496. }
  36497. get edgeStalled() {
  36498. const levelDetails = this.levelDetails;
  36499. if (levelDetails === null) {
  36500. return 0;
  36501. }
  36502. const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  36503. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  36504. }
  36505. get forwardBufferLength() {
  36506. const {
  36507. media
  36508. } = this;
  36509. const levelDetails = this.levelDetails;
  36510. if (!media || !levelDetails) {
  36511. return 0;
  36512. }
  36513. const bufferedRanges = media.buffered.length;
  36514. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  36515. }
  36516. destroy() {
  36517. this.unregisterListeners();
  36518. this.onMediaDetaching();
  36519. this.hls = null;
  36520. }
  36521. registerListeners() {
  36522. const {
  36523. hls
  36524. } = this;
  36525. if (!hls) {
  36526. return;
  36527. }
  36528. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  36529. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  36530. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  36531. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  36532. hls.on(Events.ERROR, this.onError, this);
  36533. }
  36534. unregisterListeners() {
  36535. const {
  36536. hls
  36537. } = this;
  36538. if (!hls) {
  36539. return;
  36540. }
  36541. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  36542. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  36543. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  36544. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  36545. hls.off(Events.ERROR, this.onError, this);
  36546. }
  36547. onMediaAttached(event, data) {
  36548. this.media = data.media;
  36549. this.media.addEventListener("timeupdate", this.onTimeupdate);
  36550. }
  36551. onMediaDetaching() {
  36552. if (this.media) {
  36553. this.media.removeEventListener("timeupdate", this.onTimeupdate);
  36554. this.media = null;
  36555. }
  36556. }
  36557. onManifestLoading() {
  36558. this._latency = null;
  36559. this.stallCount = 0;
  36560. }
  36561. onLevelUpdated(event, {
  36562. details
  36563. }) {
  36564. if (details.advanced) {
  36565. this.onTimeupdate();
  36566. }
  36567. if (!details.live && this.media) {
  36568. this.media.removeEventListener("timeupdate", this.onTimeupdate);
  36569. }
  36570. }
  36571. onError(event, data) {
  36572. var _this$levelDetails;
  36573. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  36574. return;
  36575. }
  36576. this.stallCount++;
  36577. if (this.hls && (_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  36578. this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency");
  36579. }
  36580. }
  36581. changeMediaPlaybackRate(media, playbackRate) {
  36582. var _this$hls2, _this$targetLatency;
  36583. if (media.playbackRate === playbackRate) {
  36584. return;
  36585. }
  36586. (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(_this$targetLatency = this.targetLatency) == null ? void 0 : _this$targetLatency.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${media.playbackRate} to ${playbackRate}`);
  36587. media.playbackRate = playbackRate;
  36588. }
  36589. estimateLiveEdge() {
  36590. const levelDetails = this.levelDetails;
  36591. if (levelDetails === null) {
  36592. return null;
  36593. }
  36594. return levelDetails.edge + levelDetails.age;
  36595. }
  36596. computeLatency() {
  36597. const liveEdge = this.estimateLiveEdge();
  36598. if (liveEdge === null) {
  36599. return null;
  36600. }
  36601. return liveEdge - this.currentTime;
  36602. }
  36603. }
  36604. class LevelController extends BasePlaylistController {
  36605. constructor(hls, contentSteeringController) {
  36606. super(hls, "level-controller");
  36607. this._levels = [];
  36608. this._firstLevel = -1;
  36609. this._maxAutoLevel = -1;
  36610. this._startLevel = void 0;
  36611. this.currentLevel = null;
  36612. this.currentLevelIndex = -1;
  36613. this.manualLevelIndex = -1;
  36614. this.steering = void 0;
  36615. this.onParsedComplete = void 0;
  36616. this.steering = contentSteeringController;
  36617. this._registerListeners();
  36618. }
  36619. _registerListeners() {
  36620. const {
  36621. hls
  36622. } = this;
  36623. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  36624. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  36625. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  36626. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  36627. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  36628. hls.on(Events.ERROR, this.onError, this);
  36629. }
  36630. _unregisterListeners() {
  36631. const {
  36632. hls
  36633. } = this;
  36634. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  36635. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  36636. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  36637. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  36638. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  36639. hls.off(Events.ERROR, this.onError, this);
  36640. }
  36641. destroy() {
  36642. this._unregisterListeners();
  36643. this.steering = null;
  36644. this.resetLevels();
  36645. super.destroy();
  36646. }
  36647. stopLoad() {
  36648. const levels = this._levels;
  36649. levels.forEach((level) => {
  36650. level.loadError = 0;
  36651. level.fragmentError = 0;
  36652. });
  36653. super.stopLoad();
  36654. }
  36655. resetLevels() {
  36656. this._startLevel = void 0;
  36657. this.manualLevelIndex = -1;
  36658. this.currentLevelIndex = -1;
  36659. this.currentLevel = null;
  36660. this._levels = [];
  36661. this._maxAutoLevel = -1;
  36662. }
  36663. onManifestLoading(event, data) {
  36664. this.resetLevels();
  36665. }
  36666. onManifestLoaded(event, data) {
  36667. const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  36668. const levels = [];
  36669. const redundantSet = {};
  36670. const generatePathwaySet = {};
  36671. let resolutionFound = false;
  36672. let videoCodecFound = false;
  36673. let audioCodecFound = false;
  36674. data.levels.forEach((levelParsed) => {
  36675. const attributes = levelParsed.attrs;
  36676. let {
  36677. audioCodec,
  36678. videoCodec
  36679. } = levelParsed;
  36680. if (audioCodec) {
  36681. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource) || void 0;
  36682. }
  36683. if (videoCodec) {
  36684. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  36685. }
  36686. const {
  36687. width,
  36688. height,
  36689. unknownCodecs
  36690. } = levelParsed;
  36691. let unknownUnsupportedCodecCount = unknownCodecs ? unknownCodecs.length : 0;
  36692. if (unknownCodecs) {
  36693. for (let i2 = unknownUnsupportedCodecCount; i2--; ) {
  36694. const unknownCodec = unknownCodecs[i2];
  36695. if (this.isAudioSupported(unknownCodec)) {
  36696. levelParsed.audioCodec = audioCodec = audioCodec ? `${audioCodec},${unknownCodec}` : unknownCodec;
  36697. unknownUnsupportedCodecCount--;
  36698. sampleEntryCodesISO.audio[audioCodec.substring(0, 4)] = 2;
  36699. } else if (this.isVideoSupported(unknownCodec)) {
  36700. levelParsed.videoCodec = videoCodec = videoCodec ? `${videoCodec},${unknownCodec}` : unknownCodec;
  36701. unknownUnsupportedCodecCount--;
  36702. sampleEntryCodesISO.video[videoCodec.substring(0, 4)] = 2;
  36703. }
  36704. }
  36705. }
  36706. resolutionFound || (resolutionFound = !!(width && height));
  36707. videoCodecFound || (videoCodecFound = !!videoCodec);
  36708. audioCodecFound || (audioCodecFound = !!audioCodec);
  36709. if (unknownUnsupportedCodecCount || audioCodec && !this.isAudioSupported(audioCodec) || videoCodec && !this.isVideoSupported(videoCodec)) {
  36710. this.log(`Some or all CODECS not supported "${attributes.CODECS}"`);
  36711. return;
  36712. }
  36713. const {
  36714. CODECS,
  36715. "FRAME-RATE": FRAMERATE,
  36716. "HDCP-LEVEL": HDCP,
  36717. "PATHWAY-ID": PATHWAY,
  36718. RESOLUTION,
  36719. "VIDEO-RANGE": VIDEO_RANGE
  36720. } = attributes;
  36721. const contentSteeringPrefix = `${PATHWAY || "."}-`;
  36722. const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;
  36723. if (!redundantSet[levelKey]) {
  36724. const level = this.createLevel(levelParsed);
  36725. redundantSet[levelKey] = level;
  36726. generatePathwaySet[levelKey] = 1;
  36727. levels.push(level);
  36728. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs["PATHWAY-ID"]) {
  36729. const pathwayCount = generatePathwaySet[levelKey] += 1;
  36730. levelParsed.attrs["PATHWAY-ID"] = new Array(pathwayCount + 1).join(".");
  36731. const level = this.createLevel(levelParsed);
  36732. redundantSet[levelKey] = level;
  36733. levels.push(level);
  36734. } else {
  36735. redundantSet[levelKey].addGroupId("audio", attributes.AUDIO);
  36736. redundantSet[levelKey].addGroupId("text", attributes.SUBTITLES);
  36737. }
  36738. });
  36739. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  36740. }
  36741. createLevel(levelParsed) {
  36742. const level = new Level(levelParsed);
  36743. const supplemental = levelParsed.supplemental;
  36744. if (supplemental != null && supplemental.videoCodec && !this.isVideoSupported(supplemental.videoCodec)) {
  36745. const error = new Error(`SUPPLEMENTAL-CODECS not supported "${supplemental.videoCodec}"`);
  36746. this.log(error.message);
  36747. level.supportedResult = getUnsupportedResult(error, []);
  36748. }
  36749. return level;
  36750. }
  36751. isAudioSupported(codec) {
  36752. return areCodecsMediaSourceSupported(codec, "audio", this.hls.config.preferManagedMediaSource);
  36753. }
  36754. isVideoSupported(codec) {
  36755. return areCodecsMediaSourceSupported(codec, "video", this.hls.config.preferManagedMediaSource);
  36756. }
  36757. filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  36758. let audioTracks = [];
  36759. let subtitleTracks = [];
  36760. let levels = filteredLevels;
  36761. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  36762. levels = levels.filter(({
  36763. videoCodec,
  36764. videoRange,
  36765. width,
  36766. height
  36767. }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange));
  36768. }
  36769. if (levels.length === 0) {
  36770. Promise.resolve().then(() => {
  36771. if (this.hls) {
  36772. let message = "no level with compatible codecs found in manifest";
  36773. let reason = message;
  36774. if (data.levels.length) {
  36775. reason = `one or more CODECS in variant not supported: ${stringify(data.levels.map((level) => level.attrs.CODECS).filter((value, index2, array) => array.indexOf(value) === index2))}`;
  36776. this.warn(reason);
  36777. message += ` (${reason})`;
  36778. }
  36779. const error = new Error(message);
  36780. this.hls.trigger(Events.ERROR, {
  36781. type: ErrorTypes.MEDIA_ERROR,
  36782. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  36783. fatal: true,
  36784. url: data.url,
  36785. error,
  36786. reason
  36787. });
  36788. }
  36789. });
  36790. return;
  36791. }
  36792. if (data.audioTracks) {
  36793. audioTracks = data.audioTracks.filter((track2) => !track2.audioCodec || this.isAudioSupported(track2.audioCodec));
  36794. assignTrackIdsByGroup(audioTracks);
  36795. }
  36796. if (data.subtitles) {
  36797. subtitleTracks = data.subtitles;
  36798. assignTrackIdsByGroup(subtitleTracks);
  36799. }
  36800. const unsortedLevels = levels.slice(0);
  36801. levels.sort((a2, b2) => {
  36802. if (a2.attrs["HDCP-LEVEL"] !== b2.attrs["HDCP-LEVEL"]) {
  36803. return (a2.attrs["HDCP-LEVEL"] || "") > (b2.attrs["HDCP-LEVEL"] || "") ? 1 : -1;
  36804. }
  36805. if (resolutionFound && a2.height !== b2.height) {
  36806. return a2.height - b2.height;
  36807. }
  36808. if (a2.frameRate !== b2.frameRate) {
  36809. return a2.frameRate - b2.frameRate;
  36810. }
  36811. if (a2.videoRange !== b2.videoRange) {
  36812. return VideoRangeValues.indexOf(a2.videoRange) - VideoRangeValues.indexOf(b2.videoRange);
  36813. }
  36814. if (a2.videoCodec !== b2.videoCodec) {
  36815. const valueA = videoCodecPreferenceValue(a2.videoCodec);
  36816. const valueB = videoCodecPreferenceValue(b2.videoCodec);
  36817. if (valueA !== valueB) {
  36818. return valueB - valueA;
  36819. }
  36820. }
  36821. if (a2.uri === b2.uri && a2.codecSet !== b2.codecSet) {
  36822. const valueA = codecsSetSelectionPreferenceValue(a2.codecSet);
  36823. const valueB = codecsSetSelectionPreferenceValue(b2.codecSet);
  36824. if (valueA !== valueB) {
  36825. return valueB - valueA;
  36826. }
  36827. }
  36828. if (a2.averageBitrate !== b2.averageBitrate) {
  36829. return a2.averageBitrate - b2.averageBitrate;
  36830. }
  36831. return 0;
  36832. });
  36833. let firstLevelInPlaylist = unsortedLevels[0];
  36834. if (this.steering) {
  36835. levels = this.steering.filterParsedLevels(levels);
  36836. if (levels.length !== unsortedLevels.length) {
  36837. for (let i2 = 0; i2 < unsortedLevels.length; i2++) {
  36838. if (unsortedLevels[i2].pathwayId === levels[0].pathwayId) {
  36839. firstLevelInPlaylist = unsortedLevels[i2];
  36840. break;
  36841. }
  36842. }
  36843. }
  36844. }
  36845. this._levels = levels;
  36846. for (let i2 = 0; i2 < levels.length; i2++) {
  36847. if (levels[i2] === firstLevelInPlaylist) {
  36848. var _this$hls$userConfig;
  36849. this._firstLevel = i2;
  36850. const firstLevelBitrate = firstLevelInPlaylist.bitrate;
  36851. const bandwidthEstimate = this.hls.bandwidthEstimate;
  36852. this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);
  36853. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === void 0) {
  36854. const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  36855. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === this.hls.abrEwmaDefaultEstimate) {
  36856. this.hls.bandwidthEstimate = startingBwEstimate;
  36857. }
  36858. }
  36859. break;
  36860. }
  36861. }
  36862. const audioOnly = audioCodecFound && !videoCodecFound;
  36863. const config = this.hls.config;
  36864. const altAudioEnabled = !!(config.audioStreamController && config.audioTrackController);
  36865. const edata = {
  36866. levels,
  36867. audioTracks,
  36868. subtitleTracks,
  36869. sessionData: data.sessionData,
  36870. sessionKeys: data.sessionKeys,
  36871. firstLevel: this._firstLevel,
  36872. stats: data.stats,
  36873. audio: audioCodecFound,
  36874. video: videoCodecFound,
  36875. altAudio: altAudioEnabled && !audioOnly && audioTracks.some((t2) => !!t2.url)
  36876. };
  36877. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  36878. }
  36879. get levels() {
  36880. if (this._levels.length === 0) {
  36881. return null;
  36882. }
  36883. return this._levels;
  36884. }
  36885. get loadLevelObj() {
  36886. return this.currentLevel;
  36887. }
  36888. get level() {
  36889. return this.currentLevelIndex;
  36890. }
  36891. set level(newLevel) {
  36892. const levels = this._levels;
  36893. if (levels.length === 0) {
  36894. return;
  36895. }
  36896. if (newLevel < 0 || newLevel >= levels.length) {
  36897. const error = new Error("invalid level idx");
  36898. const fatal = newLevel < 0;
  36899. this.hls.trigger(Events.ERROR, {
  36900. type: ErrorTypes.OTHER_ERROR,
  36901. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  36902. level: newLevel,
  36903. fatal,
  36904. error,
  36905. reason: error.message
  36906. });
  36907. if (fatal) {
  36908. return;
  36909. }
  36910. newLevel = Math.min(newLevel, levels.length - 1);
  36911. }
  36912. const lastLevelIndex = this.currentLevelIndex;
  36913. const lastLevel = this.currentLevel;
  36914. const lastPathwayId = lastLevel ? lastLevel.attrs["PATHWAY-ID"] : void 0;
  36915. const level = levels[newLevel];
  36916. const pathwayId = level.attrs["PATHWAY-ID"];
  36917. this.currentLevelIndex = newLevel;
  36918. this.currentLevel = level;
  36919. if (lastLevelIndex === newLevel && lastLevel && lastPathwayId === pathwayId) {
  36920. return;
  36921. }
  36922. 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 : ""}`);
  36923. const levelSwitchingData = {
  36924. level: newLevel,
  36925. attrs: level.attrs,
  36926. details: level.details,
  36927. bitrate: level.bitrate,
  36928. averageBitrate: level.averageBitrate,
  36929. maxBitrate: level.maxBitrate,
  36930. realBitrate: level.realBitrate,
  36931. width: level.width,
  36932. height: level.height,
  36933. codecSet: level.codecSet,
  36934. audioCodec: level.audioCodec,
  36935. videoCodec: level.videoCodec,
  36936. audioGroups: level.audioGroups,
  36937. subtitleGroups: level.subtitleGroups,
  36938. loaded: level.loaded,
  36939. loadError: level.loadError,
  36940. fragmentError: level.fragmentError,
  36941. name: level.name,
  36942. id: level.id,
  36943. uri: level.uri,
  36944. url: level.url,
  36945. urlId: 0,
  36946. audioGroupIds: level.audioGroupIds,
  36947. textGroupIds: level.textGroupIds
  36948. };
  36949. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  36950. const levelDetails = level.details;
  36951. if (!levelDetails || levelDetails.live) {
  36952. const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  36953. this.loadPlaylist(hlsUrlParameters);
  36954. }
  36955. }
  36956. get manualLevel() {
  36957. return this.manualLevelIndex;
  36958. }
  36959. set manualLevel(newLevel) {
  36960. this.manualLevelIndex = newLevel;
  36961. if (this._startLevel === void 0) {
  36962. this._startLevel = newLevel;
  36963. }
  36964. if (newLevel !== -1) {
  36965. this.level = newLevel;
  36966. }
  36967. }
  36968. get firstLevel() {
  36969. return this._firstLevel;
  36970. }
  36971. set firstLevel(newLevel) {
  36972. this._firstLevel = newLevel;
  36973. }
  36974. get startLevel() {
  36975. if (this._startLevel === void 0) {
  36976. const configStartLevel = this.hls.config.startLevel;
  36977. if (configStartLevel !== void 0) {
  36978. return configStartLevel;
  36979. }
  36980. return this.hls.firstAutoLevel;
  36981. }
  36982. return this._startLevel;
  36983. }
  36984. set startLevel(newLevel) {
  36985. this._startLevel = newLevel;
  36986. }
  36987. get pathways() {
  36988. if (this.steering) {
  36989. return this.steering.pathways();
  36990. }
  36991. return [];
  36992. }
  36993. get pathwayPriority() {
  36994. if (this.steering) {
  36995. return this.steering.pathwayPriority;
  36996. }
  36997. return null;
  36998. }
  36999. set pathwayPriority(pathwayPriority) {
  37000. if (this.steering) {
  37001. const pathwaysList = this.steering.pathways();
  37002. const filteredPathwayPriority = pathwayPriority.filter((pathwayId) => {
  37003. return pathwaysList.indexOf(pathwayId) !== -1;
  37004. });
  37005. if (pathwayPriority.length < 1) {
  37006. this.warn(`pathwayPriority ${pathwayPriority} should contain at least one pathway from list: ${pathwaysList}`);
  37007. return;
  37008. }
  37009. this.steering.pathwayPriority = filteredPathwayPriority;
  37010. }
  37011. }
  37012. onError(event, data) {
  37013. if (data.fatal || !data.context) {
  37014. return;
  37015. }
  37016. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  37017. this.checkRetry(data);
  37018. }
  37019. }
  37020. // reset errors on the successful load of a fragment
  37021. onFragBuffered(event, {
  37022. frag
  37023. }) {
  37024. if (frag !== void 0 && frag.type === PlaylistLevelType.MAIN) {
  37025. const el = frag.elementaryStreams;
  37026. if (!Object.keys(el).some((type) => !!el[type])) {
  37027. return;
  37028. }
  37029. const level = this._levels[frag.level];
  37030. if (level != null && level.loadError) {
  37031. this.log(`Resetting level error count of ${level.loadError} on frag buffered`);
  37032. level.loadError = 0;
  37033. }
  37034. }
  37035. }
  37036. onLevelLoaded(event, data) {
  37037. var _data$deliveryDirecti2;
  37038. const {
  37039. level,
  37040. details
  37041. } = data;
  37042. const curLevel = data.levelInfo;
  37043. if (!curLevel) {
  37044. var _data$deliveryDirecti;
  37045. this.warn(`Invalid level index ${level}`);
  37046. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  37047. details.deltaUpdateFailed = true;
  37048. }
  37049. return;
  37050. }
  37051. if (curLevel === this.currentLevel || data.withoutMultiVariant) {
  37052. if (curLevel.fragmentError === 0) {
  37053. curLevel.loadError = 0;
  37054. }
  37055. let previousDetails = curLevel.details;
  37056. if (previousDetails === data.details && previousDetails.advanced) {
  37057. previousDetails = void 0;
  37058. }
  37059. this.playlistLoaded(level, data, previousDetails);
  37060. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  37061. details.deltaUpdateFailed = true;
  37062. }
  37063. }
  37064. loadPlaylist(hlsUrlParameters) {
  37065. super.loadPlaylist();
  37066. if (this.shouldLoadPlaylist(this.currentLevel)) {
  37067. this.scheduleLoading(this.currentLevel, hlsUrlParameters);
  37068. }
  37069. }
  37070. loadingPlaylist(currentLevel, hlsUrlParameters) {
  37071. super.loadingPlaylist(currentLevel, hlsUrlParameters);
  37072. const url = this.getUrlWithDirectives(currentLevel.uri, hlsUrlParameters);
  37073. const currentLevelIndex = this.currentLevelIndex;
  37074. const pathwayId = currentLevel.attrs["PATHWAY-ID"];
  37075. const details = currentLevel.details;
  37076. const age = details == null ? void 0 : details.age;
  37077. this.log(`Loading level index ${currentLevelIndex}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== void 0 ? " at sn " + hlsUrlParameters.msn + " part " + hlsUrlParameters.part : ""}${pathwayId ? " Pathway " + pathwayId : ""}${age && details.live ? " age " + age.toFixed(1) + (details.type ? " " + details.type || "" : "") : ""} ${url}`);
  37078. this.hls.trigger(Events.LEVEL_LOADING, {
  37079. url,
  37080. level: currentLevelIndex,
  37081. levelInfo: currentLevel,
  37082. pathwayId: currentLevel.attrs["PATHWAY-ID"],
  37083. id: 0,
  37084. // Deprecated Level urlId
  37085. deliveryDirectives: hlsUrlParameters || null
  37086. });
  37087. }
  37088. get nextLoadLevel() {
  37089. if (this.manualLevelIndex !== -1) {
  37090. return this.manualLevelIndex;
  37091. } else {
  37092. return this.hls.nextAutoLevel;
  37093. }
  37094. }
  37095. set nextLoadLevel(nextLevel) {
  37096. this.level = nextLevel;
  37097. if (this.manualLevelIndex === -1) {
  37098. this.hls.nextAutoLevel = nextLevel;
  37099. }
  37100. }
  37101. removeLevel(levelIndex) {
  37102. var _this$currentLevel;
  37103. if (this._levels.length === 1) {
  37104. return;
  37105. }
  37106. const levels = this._levels.filter((level, index2) => {
  37107. if (index2 !== levelIndex) {
  37108. return true;
  37109. }
  37110. if (this.steering) {
  37111. this.steering.removeLevel(level);
  37112. }
  37113. if (level === this.currentLevel) {
  37114. this.currentLevel = null;
  37115. this.currentLevelIndex = -1;
  37116. if (level.details) {
  37117. level.details.fragments.forEach((f2) => f2.level = -1);
  37118. }
  37119. }
  37120. return false;
  37121. });
  37122. reassignFragmentLevelIndexes(levels);
  37123. this._levels = levels;
  37124. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  37125. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  37126. }
  37127. if (this.manualLevelIndex > -1) {
  37128. this.manualLevelIndex = this.currentLevelIndex;
  37129. }
  37130. const maxLevel = levels.length - 1;
  37131. this._firstLevel = Math.min(this._firstLevel, maxLevel);
  37132. if (this._startLevel) {
  37133. this._startLevel = Math.min(this._startLevel, maxLevel);
  37134. }
  37135. this.hls.trigger(Events.LEVELS_UPDATED, {
  37136. levels
  37137. });
  37138. }
  37139. onLevelsUpdated(event, {
  37140. levels
  37141. }) {
  37142. this._levels = levels;
  37143. }
  37144. checkMaxAutoUpdated() {
  37145. const {
  37146. autoLevelCapping,
  37147. maxAutoLevel,
  37148. maxHdcpLevel
  37149. } = this.hls;
  37150. if (this._maxAutoLevel !== maxAutoLevel) {
  37151. this._maxAutoLevel = maxAutoLevel;
  37152. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  37153. autoLevelCapping,
  37154. levels: this.levels,
  37155. maxAutoLevel,
  37156. minAutoLevel: this.hls.minAutoLevel,
  37157. maxHdcpLevel
  37158. });
  37159. }
  37160. }
  37161. }
  37162. function assignTrackIdsByGroup(tracks) {
  37163. const groups = {};
  37164. tracks.forEach((track2) => {
  37165. const groupId = track2.groupId || "";
  37166. track2.id = groups[groupId] = groups[groupId] || 0;
  37167. groups[groupId]++;
  37168. });
  37169. }
  37170. function getSourceBuffer() {
  37171. return self.SourceBuffer || self.WebKitSourceBuffer;
  37172. }
  37173. function isMSESupported() {
  37174. const mediaSource = getMediaSource();
  37175. if (!mediaSource) {
  37176. return false;
  37177. }
  37178. const sourceBuffer = getSourceBuffer();
  37179. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === "function" && typeof sourceBuffer.prototype.remove === "function";
  37180. }
  37181. function isSupported() {
  37182. if (!isMSESupported()) {
  37183. return false;
  37184. }
  37185. const mediaSource = getMediaSource();
  37186. return typeof (mediaSource == null ? void 0 : mediaSource.isTypeSupported) === "function" && (["avc1.42E01E,mp4a.40.2", "av01.0.01M.08", "vp09.00.50.08"].some((codecsForVideoContainer) => mediaSource.isTypeSupported(mimeTypeForCodec(codecsForVideoContainer, "video"))) || ["mp4a.40.2", "fLaC"].some((codecForAudioContainer) => mediaSource.isTypeSupported(mimeTypeForCodec(codecForAudioContainer, "audio"))));
  37187. }
  37188. function changeTypeSupported() {
  37189. var _sourceBuffer$prototy;
  37190. const sourceBuffer = getSourceBuffer();
  37191. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === "function";
  37192. }
  37193. const TICK_INTERVAL = 100;
  37194. class StreamController extends BaseStreamController {
  37195. constructor(hls, fragmentTracker, keyLoader) {
  37196. super(hls, fragmentTracker, keyLoader, "stream-controller", PlaylistLevelType.MAIN);
  37197. this.audioCodecSwap = false;
  37198. this.level = -1;
  37199. this._forceStartLoad = false;
  37200. this._hasEnoughToStart = false;
  37201. this.altAudio = 0;
  37202. this.audioOnly = false;
  37203. this.fragPlaying = null;
  37204. this.fragLastKbps = 0;
  37205. this.couldBacktrack = false;
  37206. this.backtrackFragment = null;
  37207. this.audioCodecSwitch = false;
  37208. this.videoBuffer = null;
  37209. this.onMediaPlaying = () => {
  37210. this.tick();
  37211. };
  37212. this.onMediaSeeked = () => {
  37213. const media = this.media;
  37214. const currentTime = media ? media.currentTime : null;
  37215. if (currentTime === null || !isFiniteNumber(currentTime)) {
  37216. return;
  37217. }
  37218. this.log(`Media seeked to ${currentTime.toFixed(3)}`);
  37219. if (!this.getBufferedFrag(currentTime)) {
  37220. return;
  37221. }
  37222. const bufferInfo = this.getFwdBufferInfoAtPos(media, currentTime, PlaylistLevelType.MAIN, 0);
  37223. if (bufferInfo === null || bufferInfo.len === 0) {
  37224. this.warn(`Main forward buffer length at ${currentTime} on "seeked" event ${bufferInfo ? bufferInfo.len : "empty"})`);
  37225. return;
  37226. }
  37227. this.tick();
  37228. };
  37229. this.registerListeners();
  37230. }
  37231. registerListeners() {
  37232. super.registerListeners();
  37233. const {
  37234. hls
  37235. } = this;
  37236. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  37237. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  37238. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  37239. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  37240. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  37241. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  37242. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  37243. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  37244. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  37245. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  37246. }
  37247. unregisterListeners() {
  37248. super.unregisterListeners();
  37249. const {
  37250. hls
  37251. } = this;
  37252. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  37253. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  37254. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  37255. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  37256. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  37257. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  37258. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  37259. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  37260. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  37261. }
  37262. onHandlerDestroying() {
  37263. this.onMediaPlaying = this.onMediaSeeked = null;
  37264. this.unregisterListeners();
  37265. super.onHandlerDestroying();
  37266. }
  37267. startLoad(startPosition, skipSeekToStartPosition) {
  37268. if (this.levels) {
  37269. const {
  37270. lastCurrentTime,
  37271. hls
  37272. } = this;
  37273. this.stopLoad();
  37274. this.setInterval(TICK_INTERVAL);
  37275. this.level = -1;
  37276. if (!this.startFragRequested) {
  37277. let startLevel = hls.startLevel;
  37278. if (startLevel === -1) {
  37279. if (hls.config.testBandwidth && this.levels.length > 1) {
  37280. startLevel = 0;
  37281. this.bitrateTest = true;
  37282. } else {
  37283. startLevel = hls.firstAutoLevel;
  37284. }
  37285. }
  37286. hls.nextLoadLevel = startLevel;
  37287. this.level = hls.loadLevel;
  37288. this._hasEnoughToStart = !!skipSeekToStartPosition;
  37289. }
  37290. if (lastCurrentTime > 0 && startPosition === -1 && !skipSeekToStartPosition) {
  37291. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  37292. startPosition = lastCurrentTime;
  37293. }
  37294. this.state = State.IDLE;
  37295. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  37296. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  37297. this.tick();
  37298. } else {
  37299. this._forceStartLoad = true;
  37300. this.state = State.STOPPED;
  37301. }
  37302. }
  37303. stopLoad() {
  37304. this._forceStartLoad = false;
  37305. super.stopLoad();
  37306. }
  37307. doTick() {
  37308. switch (this.state) {
  37309. case State.WAITING_LEVEL: {
  37310. const {
  37311. levels,
  37312. level
  37313. } = this;
  37314. const currentLevel = levels == null ? void 0 : levels[level];
  37315. const details = currentLevel == null ? void 0 : currentLevel.details;
  37316. if (details && (!details.live || this.levelLastLoaded === currentLevel && !this.waitForLive(currentLevel))) {
  37317. if (this.waitForCdnTuneIn(details)) {
  37318. break;
  37319. }
  37320. this.state = State.IDLE;
  37321. break;
  37322. } else if (this.hls.nextLoadLevel !== this.level) {
  37323. this.state = State.IDLE;
  37324. break;
  37325. }
  37326. break;
  37327. }
  37328. case State.FRAG_LOADING_WAITING_RETRY:
  37329. {
  37330. var _this$media;
  37331. const now2 = self.performance.now();
  37332. const retryDate = this.retryDate;
  37333. if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  37334. const {
  37335. levels,
  37336. level
  37337. } = this;
  37338. const currentLevel = levels == null ? void 0 : levels[level];
  37339. this.resetStartWhenNotLoaded(currentLevel || null);
  37340. this.state = State.IDLE;
  37341. }
  37342. }
  37343. break;
  37344. }
  37345. if (this.state === State.IDLE) {
  37346. this.doTickIdle();
  37347. }
  37348. this.onTickEnd();
  37349. }
  37350. onTickEnd() {
  37351. var _this$media2;
  37352. super.onTickEnd();
  37353. if ((_this$media2 = this.media) != null && _this$media2.readyState && this.media.seeking === false) {
  37354. this.lastCurrentTime = this.media.currentTime;
  37355. }
  37356. this.checkFragmentChanged();
  37357. }
  37358. doTickIdle() {
  37359. const {
  37360. hls,
  37361. levelLastLoaded,
  37362. levels,
  37363. media
  37364. } = this;
  37365. if (levelLastLoaded === null || !media && !this.primaryPrefetch && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  37366. return;
  37367. }
  37368. if (this.altAudio && this.audioOnly) {
  37369. return;
  37370. }
  37371. const level = this.buffering ? hls.nextLoadLevel : hls.loadLevel;
  37372. if (!(levels != null && levels[level])) {
  37373. return;
  37374. }
  37375. const levelInfo = levels[level];
  37376. const bufferInfo = this.getMainFwdBufferInfo();
  37377. if (bufferInfo === null) {
  37378. return;
  37379. }
  37380. const lastDetails = this.getLevelDetails();
  37381. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  37382. const data = {};
  37383. if (this.altAudio === 2) {
  37384. data.type = "video";
  37385. }
  37386. this.hls.trigger(Events.BUFFER_EOS, data);
  37387. this.state = State.ENDED;
  37388. return;
  37389. }
  37390. if (!this.buffering) {
  37391. return;
  37392. }
  37393. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  37394. this.log(`Adapting to level ${level} from level ${this.level}`);
  37395. }
  37396. this.level = hls.nextLoadLevel = level;
  37397. const levelDetails = levelInfo.details;
  37398. if (!levelDetails || this.state === State.WAITING_LEVEL || this.waitForLive(levelInfo)) {
  37399. this.level = level;
  37400. this.state = State.WAITING_LEVEL;
  37401. this.startFragRequested = false;
  37402. return;
  37403. }
  37404. const bufferLen = bufferInfo.len;
  37405. const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  37406. if (bufferLen >= maxBufLen) {
  37407. return;
  37408. }
  37409. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  37410. this.backtrackFragment = null;
  37411. }
  37412. const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  37413. let frag = this.getNextFragment(targetBufferTime, levelDetails);
  37414. if (this.couldBacktrack && !this.fragPrevious && frag && isMediaFragment(frag) && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  37415. var _this$backtrackFragme;
  37416. const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  37417. const fragIdx = backtrackSn - levelDetails.startSN;
  37418. const backtrackFrag = levelDetails.fragments[fragIdx - 1];
  37419. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  37420. frag = backtrackFrag;
  37421. this.fragmentTracker.removeFragment(backtrackFrag);
  37422. }
  37423. } else if (this.backtrackFragment && bufferInfo.len) {
  37424. this.backtrackFragment = null;
  37425. }
  37426. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  37427. const gapStart = frag.gap;
  37428. if (!gapStart) {
  37429. const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  37430. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  37431. if (mediaBuffer) {
  37432. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  37433. }
  37434. }
  37435. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  37436. }
  37437. if (!frag) {
  37438. return;
  37439. }
  37440. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  37441. frag = frag.initSegment;
  37442. }
  37443. this.loadFragment(frag, levelInfo, targetBufferTime);
  37444. }
  37445. loadFragment(frag, level, targetBufferTime) {
  37446. const fragState = this.fragmentTracker.getState(frag);
  37447. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  37448. if (!isMediaFragment(frag)) {
  37449. this._loadInitSegment(frag, level);
  37450. } else if (this.bitrateTest) {
  37451. this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);
  37452. this._loadBitrateTestFrag(frag, level);
  37453. } else {
  37454. super.loadFragment(frag, level, targetBufferTime);
  37455. }
  37456. } else {
  37457. this.clearTrackerIfNeeded(frag);
  37458. }
  37459. }
  37460. getBufferedFrag(position) {
  37461. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  37462. }
  37463. followingBufferedFrag(frag) {
  37464. if (frag) {
  37465. return this.getBufferedFrag(frag.end + 0.5);
  37466. }
  37467. return null;
  37468. }
  37469. /*
  37470. on immediate level switch :
  37471. - pause playback if playing
  37472. - cancel any pending load request
  37473. - and trigger a buffer flush
  37474. */
  37475. immediateLevelSwitch() {
  37476. this.abortCurrentFrag();
  37477. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  37478. }
  37479. /**
  37480. * try to switch ASAP without breaking video playback:
  37481. * in order to ensure smooth but quick level switching,
  37482. * we need to find the next flushable buffer range
  37483. * we should take into account new segment fetch time
  37484. */
  37485. nextLevelSwitch() {
  37486. const {
  37487. levels,
  37488. media
  37489. } = this;
  37490. if (media != null && media.readyState) {
  37491. let fetchdelay;
  37492. const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  37493. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  37494. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  37495. }
  37496. const levelDetails = this.getLevelDetails();
  37497. if (levelDetails != null && levelDetails.live) {
  37498. const bufferInfo = this.getMainFwdBufferInfo();
  37499. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  37500. return;
  37501. }
  37502. }
  37503. if (!media.paused && levels) {
  37504. const nextLevelId = this.hls.nextLoadLevel;
  37505. const nextLevel = levels[nextLevelId];
  37506. const fragLastKbps = this.fragLastKbps;
  37507. if (fragLastKbps && this.fragCurrent) {
  37508. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1e3 * fragLastKbps) + 1;
  37509. } else {
  37510. fetchdelay = 0;
  37511. }
  37512. } else {
  37513. fetchdelay = 0;
  37514. }
  37515. const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  37516. if (bufferedFrag) {
  37517. const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  37518. if (nextBufferedFrag) {
  37519. this.abortCurrentFrag();
  37520. const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  37521. const fragDuration = nextBufferedFrag.duration;
  37522. const 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)));
  37523. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  37524. }
  37525. }
  37526. }
  37527. }
  37528. abortCurrentFrag() {
  37529. const fragCurrent = this.fragCurrent;
  37530. this.fragCurrent = null;
  37531. this.backtrackFragment = null;
  37532. if (fragCurrent) {
  37533. fragCurrent.abortRequests();
  37534. this.fragmentTracker.removeFragment(fragCurrent);
  37535. }
  37536. switch (this.state) {
  37537. case State.KEY_LOADING:
  37538. case State.FRAG_LOADING:
  37539. case State.FRAG_LOADING_WAITING_RETRY:
  37540. case State.PARSING:
  37541. case State.PARSED:
  37542. this.state = State.IDLE;
  37543. break;
  37544. }
  37545. this.nextLoadPosition = this.getLoadPosition();
  37546. }
  37547. flushMainBuffer(startOffset, endOffset) {
  37548. super.flushMainBuffer(startOffset, endOffset, this.altAudio === 2 ? "video" : null);
  37549. }
  37550. onMediaAttached(event, data) {
  37551. super.onMediaAttached(event, data);
  37552. const media = data.media;
  37553. addEventListener(media, "playing", this.onMediaPlaying);
  37554. addEventListener(media, "seeked", this.onMediaSeeked);
  37555. }
  37556. onMediaDetaching(event, data) {
  37557. const {
  37558. media
  37559. } = this;
  37560. if (media) {
  37561. removeEventListener(media, "playing", this.onMediaPlaying);
  37562. removeEventListener(media, "seeked", this.onMediaSeeked);
  37563. }
  37564. this.videoBuffer = null;
  37565. this.fragPlaying = null;
  37566. super.onMediaDetaching(event, data);
  37567. const transferringMedia = !!data.transferMedia;
  37568. if (transferringMedia) {
  37569. return;
  37570. }
  37571. this._hasEnoughToStart = false;
  37572. }
  37573. onManifestLoading() {
  37574. super.onManifestLoading();
  37575. this.log("Trigger BUFFER_RESET");
  37576. this.hls.trigger(Events.BUFFER_RESET, void 0);
  37577. this.couldBacktrack = false;
  37578. this.fragLastKbps = 0;
  37579. this.fragPlaying = this.backtrackFragment = null;
  37580. this.altAudio = 0;
  37581. this.audioOnly = false;
  37582. }
  37583. onManifestParsed(event, data) {
  37584. let aac = false;
  37585. let heaac = false;
  37586. data.levels.forEach((level) => {
  37587. const codec = level.audioCodec;
  37588. if (codec) {
  37589. aac = aac || codec.indexOf("mp4a.40.2") !== -1;
  37590. heaac = heaac || codec.indexOf("mp4a.40.5") !== -1;
  37591. }
  37592. });
  37593. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  37594. if (this.audioCodecSwitch) {
  37595. this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC");
  37596. }
  37597. this.levels = data.levels;
  37598. this.startFragRequested = false;
  37599. }
  37600. onLevelLoading(event, data) {
  37601. const {
  37602. levels
  37603. } = this;
  37604. if (!levels || this.state !== State.IDLE) {
  37605. return;
  37606. }
  37607. const level = data.levelInfo;
  37608. if (!level.details || level.details.live && (this.levelLastLoaded !== level || level.details.expired) || this.waitForCdnTuneIn(level.details)) {
  37609. this.state = State.WAITING_LEVEL;
  37610. }
  37611. }
  37612. onLevelLoaded(event, data) {
  37613. var _curLevel$details;
  37614. const {
  37615. levels,
  37616. startFragRequested
  37617. } = this;
  37618. const newLevelId = data.level;
  37619. const newDetails = data.details;
  37620. const duration = newDetails.totalduration;
  37621. if (!levels) {
  37622. this.warn(`Levels were reset while loading level ${newLevelId}`);
  37623. return;
  37624. }
  37625. this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`);
  37626. const curLevel = data.levelInfo;
  37627. const fragCurrent = this.fragCurrent;
  37628. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  37629. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  37630. this.abortCurrentFrag();
  37631. }
  37632. }
  37633. let sliding = 0;
  37634. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  37635. var _this$levelLastLoaded;
  37636. this.checkLiveUpdate(newDetails);
  37637. if (newDetails.deltaUpdateFailed) {
  37638. return;
  37639. }
  37640. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  37641. }
  37642. curLevel.details = newDetails;
  37643. this.levelLastLoaded = curLevel;
  37644. if (!startFragRequested) {
  37645. this.setStartPosition(newDetails, sliding);
  37646. }
  37647. this.hls.trigger(Events.LEVEL_UPDATED, {
  37648. details: newDetails,
  37649. level: newLevelId
  37650. });
  37651. if (this.state === State.WAITING_LEVEL) {
  37652. if (this.waitForCdnTuneIn(newDetails)) {
  37653. return;
  37654. }
  37655. this.state = State.IDLE;
  37656. }
  37657. if (startFragRequested && newDetails.live) {
  37658. this.synchronizeToLiveEdge(newDetails);
  37659. }
  37660. this.tick();
  37661. }
  37662. synchronizeToLiveEdge(levelDetails) {
  37663. const {
  37664. config,
  37665. media
  37666. } = this;
  37667. if (!media) {
  37668. return;
  37669. }
  37670. const liveSyncPosition = this.hls.liveSyncPosition;
  37671. const currentTime = this.getLoadPosition();
  37672. const start = levelDetails.fragmentStart;
  37673. const end = levelDetails.edge;
  37674. const withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  37675. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  37676. const maxLatency = config.liveMaxLatencyDuration !== void 0 ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  37677. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  37678. if (!this._hasEnoughToStart) {
  37679. this.nextLoadPosition = liveSyncPosition;
  37680. }
  37681. if (media.readyState) {
  37682. this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
  37683. if (this.config.liveSyncMode === "buffered") {
  37684. var _bufferInfo$buffered;
  37685. const bufferInfo = BufferHelper.bufferInfo(media, liveSyncPosition, 0);
  37686. if (!(bufferInfo != null && (_bufferInfo$buffered = bufferInfo.buffered) != null && _bufferInfo$buffered.length)) {
  37687. media.currentTime = liveSyncPosition;
  37688. return;
  37689. }
  37690. const isLiveSyncInBuffer = bufferInfo.start <= currentTime;
  37691. if (isLiveSyncInBuffer) {
  37692. media.currentTime = liveSyncPosition;
  37693. return;
  37694. }
  37695. const {
  37696. nextStart
  37697. } = BufferHelper.bufferedInfo(bufferInfo.buffered, currentTime, 0);
  37698. if (nextStart) {
  37699. media.currentTime = nextStart;
  37700. }
  37701. } else {
  37702. media.currentTime = liveSyncPosition;
  37703. }
  37704. }
  37705. }
  37706. }
  37707. }
  37708. _handleFragmentLoadProgress(data) {
  37709. var _frag$initSegment;
  37710. const frag = data.frag;
  37711. const {
  37712. part,
  37713. payload
  37714. } = data;
  37715. const {
  37716. levels
  37717. } = this;
  37718. if (!levels) {
  37719. this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  37720. return;
  37721. }
  37722. const currentLevel = levels[frag.level];
  37723. if (!currentLevel) {
  37724. this.warn(`Level ${frag.level} not found on progress`);
  37725. return;
  37726. }
  37727. const details = currentLevel.details;
  37728. if (!details) {
  37729. this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);
  37730. this.fragmentTracker.removeFragment(frag);
  37731. return;
  37732. }
  37733. const videoCodec = currentLevel.videoCodec;
  37734. const accurateTimeOffset = details.PTSKnown || !details.live;
  37735. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  37736. const audioCodec = this._getAudioCodec(currentLevel);
  37737. const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  37738. const partIndex = part ? part.index : -1;
  37739. const partial2 = partIndex !== -1;
  37740. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial2);
  37741. const initPTS = this.initPTS[frag.cc];
  37742. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  37743. }
  37744. onAudioTrackSwitching(event, data) {
  37745. const hls = this.hls;
  37746. const fromAltAudio = this.altAudio === 2;
  37747. const altAudio = useAlternateAudio(data.url, hls);
  37748. if (!altAudio) {
  37749. if (this.mediaBuffer !== this.media) {
  37750. this.log("Switching on main audio, use media.buffered to schedule main fragment loading");
  37751. this.mediaBuffer = this.media;
  37752. const fragCurrent = this.fragCurrent;
  37753. if (fragCurrent) {
  37754. this.log("Switching to main audio track, cancel main fragment load");
  37755. fragCurrent.abortRequests();
  37756. this.fragmentTracker.removeFragment(fragCurrent);
  37757. }
  37758. this.resetTransmuxer();
  37759. this.resetLoadingState();
  37760. } else if (this.audioOnly) {
  37761. this.resetTransmuxer();
  37762. }
  37763. if (fromAltAudio) {
  37764. this.fragmentTracker.removeAllFragments();
  37765. hls.once(Events.BUFFER_FLUSHED, () => {
  37766. var _this$hls;
  37767. (_this$hls = this.hls) == null ? void 0 : _this$hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  37768. });
  37769. hls.trigger(Events.BUFFER_FLUSHING, {
  37770. startOffset: 0,
  37771. endOffset: Number.POSITIVE_INFINITY,
  37772. type: null
  37773. });
  37774. return;
  37775. }
  37776. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  37777. } else {
  37778. this.altAudio = 1;
  37779. }
  37780. }
  37781. onAudioTrackSwitched(event, data) {
  37782. const altAudio = useAlternateAudio(data.url, this.hls);
  37783. if (altAudio) {
  37784. const videoBuffer = this.videoBuffer;
  37785. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  37786. this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading");
  37787. this.mediaBuffer = videoBuffer;
  37788. }
  37789. }
  37790. this.altAudio = altAudio ? 2 : 0;
  37791. this.tick();
  37792. }
  37793. onBufferCreated(event, data) {
  37794. const tracks = data.tracks;
  37795. let mediaTrack;
  37796. let name;
  37797. let alternate = false;
  37798. for (const type in tracks) {
  37799. const track2 = tracks[type];
  37800. if (track2.id === "main") {
  37801. name = type;
  37802. mediaTrack = track2;
  37803. if (type === "video") {
  37804. const videoTrack = tracks[type];
  37805. if (videoTrack) {
  37806. this.videoBuffer = videoTrack.buffer;
  37807. }
  37808. }
  37809. } else {
  37810. alternate = true;
  37811. }
  37812. }
  37813. if (alternate && mediaTrack) {
  37814. this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);
  37815. this.mediaBuffer = mediaTrack.buffer;
  37816. } else {
  37817. this.mediaBuffer = this.media;
  37818. }
  37819. }
  37820. onFragBuffered(event, data) {
  37821. const {
  37822. frag,
  37823. part
  37824. } = data;
  37825. const bufferedMainFragment = frag.type === PlaylistLevelType.MAIN;
  37826. if (bufferedMainFragment) {
  37827. if (this.fragContextChanged(frag)) {
  37828. this.warn(`Fragment ${frag.sn}${part ? " p: " + part.index : ""} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);
  37829. if (this.state === State.PARSED) {
  37830. this.state = State.IDLE;
  37831. }
  37832. return;
  37833. }
  37834. const stats = part ? part.stats : frag.stats;
  37835. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  37836. if (isMediaFragment(frag)) {
  37837. this.fragPrevious = frag;
  37838. }
  37839. this.fragBufferedComplete(frag, part);
  37840. }
  37841. const media = this.media;
  37842. if (!media) {
  37843. return;
  37844. }
  37845. if (!this._hasEnoughToStart && BufferHelper.getBuffered(media).length) {
  37846. this._hasEnoughToStart = true;
  37847. this.seekToStartPos();
  37848. }
  37849. if (bufferedMainFragment) {
  37850. this.tick();
  37851. }
  37852. }
  37853. get hasEnoughToStart() {
  37854. return this._hasEnoughToStart;
  37855. }
  37856. onError(event, data) {
  37857. var _data$context;
  37858. if (data.fatal) {
  37859. this.state = State.ERROR;
  37860. return;
  37861. }
  37862. switch (data.details) {
  37863. case ErrorDetails.FRAG_GAP:
  37864. case ErrorDetails.FRAG_PARSING_ERROR:
  37865. case ErrorDetails.FRAG_DECRYPT_ERROR:
  37866. case ErrorDetails.FRAG_LOAD_ERROR:
  37867. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  37868. case ErrorDetails.KEY_LOAD_ERROR:
  37869. case ErrorDetails.KEY_LOAD_TIMEOUT:
  37870. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  37871. break;
  37872. case ErrorDetails.LEVEL_LOAD_ERROR:
  37873. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  37874. case ErrorDetails.LEVEL_PARSING_ERROR:
  37875. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  37876. this.state = State.IDLE;
  37877. }
  37878. break;
  37879. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  37880. case ErrorDetails.BUFFER_APPEND_ERROR:
  37881. if (data.parent !== "main") {
  37882. return;
  37883. }
  37884. if (this.reduceLengthAndFlushBuffer(data)) {
  37885. this.resetLoadingState();
  37886. }
  37887. break;
  37888. case ErrorDetails.BUFFER_FULL_ERROR:
  37889. if (data.parent !== "main") {
  37890. return;
  37891. }
  37892. if (this.reduceLengthAndFlushBuffer(data)) {
  37893. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  37894. }
  37895. break;
  37896. case ErrorDetails.INTERNAL_EXCEPTION:
  37897. this.recoverWorkerError(data);
  37898. break;
  37899. }
  37900. }
  37901. onFragLoadEmergencyAborted() {
  37902. this.state = State.IDLE;
  37903. if (!this._hasEnoughToStart) {
  37904. this.startFragRequested = false;
  37905. this.nextLoadPosition = this.lastCurrentTime;
  37906. }
  37907. this.tickImmediate();
  37908. }
  37909. onBufferFlushed(event, {
  37910. type
  37911. }) {
  37912. if (type !== ElementaryStreamTypes.AUDIO || !this.altAudio) {
  37913. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  37914. if (mediaBuffer) {
  37915. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  37916. this.tick();
  37917. }
  37918. }
  37919. }
  37920. onLevelsUpdated(event, data) {
  37921. if (this.level > -1 && this.fragCurrent) {
  37922. this.level = this.fragCurrent.level;
  37923. if (this.level === -1) {
  37924. this.resetWhenMissingContext(this.fragCurrent);
  37925. }
  37926. }
  37927. this.levels = data.levels;
  37928. }
  37929. swapAudioCodec() {
  37930. this.audioCodecSwap = !this.audioCodecSwap;
  37931. }
  37932. /**
  37933. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  37934. */
  37935. seekToStartPos() {
  37936. const {
  37937. media
  37938. } = this;
  37939. if (!media) {
  37940. return;
  37941. }
  37942. const currentTime = media.currentTime;
  37943. let startPosition = this.startPosition;
  37944. if (startPosition >= 0 && currentTime < startPosition) {
  37945. if (media.seeking) {
  37946. this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
  37947. return;
  37948. }
  37949. const timelineOffset = this.timelineOffset;
  37950. if (timelineOffset && startPosition) {
  37951. startPosition += timelineOffset;
  37952. }
  37953. const details = this.getLevelDetails();
  37954. const buffered = BufferHelper.getBuffered(media);
  37955. const bufferStart = buffered.length ? buffered.start(0) : 0;
  37956. const delta = bufferStart - startPosition;
  37957. const skipTolerance = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
  37958. if (this.config.startOnSegmentBoundary || delta > 0 && (delta < skipTolerance || this.loadingParts && delta < 2 * ((details == null ? void 0 : details.partTarget) || 0))) {
  37959. this.log(`adjusting start position by ${delta} to match buffer start`);
  37960. startPosition += delta;
  37961. this.startPosition = startPosition;
  37962. }
  37963. if (currentTime < startPosition) {
  37964. this.log(`seek to target start position ${startPosition} from current time ${currentTime} buffer start ${bufferStart}`);
  37965. media.currentTime = startPosition;
  37966. }
  37967. }
  37968. }
  37969. _getAudioCodec(currentLevel) {
  37970. let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  37971. if (this.audioCodecSwap && audioCodec) {
  37972. this.log("Swapping audio codec");
  37973. if (audioCodec.indexOf("mp4a.40.5") !== -1) {
  37974. audioCodec = "mp4a.40.2";
  37975. } else {
  37976. audioCodec = "mp4a.40.5";
  37977. }
  37978. }
  37979. return audioCodec;
  37980. }
  37981. _loadBitrateTestFrag(fragment, level) {
  37982. fragment.bitrateTest = true;
  37983. this._doFragLoad(fragment, level).then((data) => {
  37984. const {
  37985. hls
  37986. } = this;
  37987. const frag = data == null ? void 0 : data.frag;
  37988. if (!frag || this.fragContextChanged(frag)) {
  37989. return;
  37990. }
  37991. level.fragmentError = 0;
  37992. this.state = State.IDLE;
  37993. this.startFragRequested = false;
  37994. this.bitrateTest = false;
  37995. const stats = frag.stats;
  37996. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  37997. hls.trigger(Events.FRAG_LOADED, data);
  37998. frag.bitrateTest = false;
  37999. });
  38000. }
  38001. _handleTransmuxComplete(transmuxResult) {
  38002. var _id3$samples;
  38003. const id = this.playlistType;
  38004. const {
  38005. hls
  38006. } = this;
  38007. const {
  38008. remuxResult,
  38009. chunkMeta
  38010. } = transmuxResult;
  38011. const context = this.getCurrentContext(chunkMeta);
  38012. if (!context) {
  38013. this.resetWhenMissingContext(chunkMeta);
  38014. return;
  38015. }
  38016. const {
  38017. frag,
  38018. part,
  38019. level
  38020. } = context;
  38021. const {
  38022. video,
  38023. text,
  38024. id3,
  38025. initSegment
  38026. } = remuxResult;
  38027. const {
  38028. details
  38029. } = level;
  38030. const audio = this.altAudio ? void 0 : remuxResult.audio;
  38031. if (this.fragContextChanged(frag)) {
  38032. this.fragmentTracker.removeFragment(frag);
  38033. return;
  38034. }
  38035. this.state = State.PARSING;
  38036. if (initSegment) {
  38037. if (initSegment != null && initSegment.tracks) {
  38038. const mapFragment = frag.initSegment || frag;
  38039. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  38040. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  38041. frag: mapFragment,
  38042. id,
  38043. tracks: initSegment.tracks
  38044. });
  38045. }
  38046. const baseTime = initSegment.initPTS;
  38047. const timescale = initSegment.timescale;
  38048. const initPTS = this.initPTS[frag.cc];
  38049. if (isFiniteNumber(baseTime) && (!initPTS || initPTS.baseTime !== baseTime || initPTS.timescale !== timescale)) {
  38050. this.initPTS[frag.cc] = {
  38051. baseTime,
  38052. timescale
  38053. };
  38054. hls.trigger(Events.INIT_PTS_FOUND, {
  38055. frag,
  38056. id,
  38057. initPTS: baseTime,
  38058. timescale
  38059. });
  38060. }
  38061. }
  38062. if (video && details) {
  38063. if (audio && video.type === "audiovideo") {
  38064. this.logMuxedErr(frag);
  38065. }
  38066. const prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  38067. const isFirstFragment = frag.sn === details.startSN;
  38068. const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  38069. if (remuxResult.independent !== false) {
  38070. const {
  38071. startPTS,
  38072. endPTS,
  38073. startDTS,
  38074. endDTS
  38075. } = video;
  38076. if (part) {
  38077. part.elementaryStreams[video.type] = {
  38078. startPTS,
  38079. endPTS,
  38080. startDTS,
  38081. endDTS
  38082. };
  38083. } else {
  38084. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  38085. this.couldBacktrack = true;
  38086. }
  38087. if (video.dropped && video.independent) {
  38088. const bufferInfo = this.getMainFwdBufferInfo();
  38089. const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  38090. const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  38091. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  38092. this.backtrack(frag);
  38093. return;
  38094. } else if (isFirstInDiscontinuity) {
  38095. frag.gap = true;
  38096. }
  38097. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  38098. } else if (isFirstFragment && startPTS - (details.appliedTimelineOffset || 0) > MAX_START_GAP_JUMP) {
  38099. frag.gap = true;
  38100. }
  38101. }
  38102. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  38103. if (this.backtrackFragment) {
  38104. this.backtrackFragment = frag;
  38105. }
  38106. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  38107. } else if (isFirstFragment || isFirstInDiscontinuity) {
  38108. frag.gap = true;
  38109. } else {
  38110. this.backtrack(frag);
  38111. return;
  38112. }
  38113. }
  38114. if (audio) {
  38115. const {
  38116. startPTS,
  38117. endPTS,
  38118. startDTS,
  38119. endDTS
  38120. } = audio;
  38121. if (part) {
  38122. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  38123. startPTS,
  38124. endPTS,
  38125. startDTS,
  38126. endDTS
  38127. };
  38128. }
  38129. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  38130. this.bufferFragmentData(audio, frag, part, chunkMeta);
  38131. }
  38132. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  38133. const emittedID3 = {
  38134. id,
  38135. frag,
  38136. details,
  38137. samples: id3.samples
  38138. };
  38139. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  38140. }
  38141. if (details && text) {
  38142. const emittedText = {
  38143. id,
  38144. frag,
  38145. details,
  38146. samples: text.samples
  38147. };
  38148. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  38149. }
  38150. }
  38151. logMuxedErr(frag) {
  38152. this.warn(`${isMediaFragment(frag) ? "Media" : "Init"} segment with muxed audiovideo where only video expected: ${frag.url}`);
  38153. }
  38154. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  38155. if (this.state !== State.PARSING) {
  38156. return;
  38157. }
  38158. this.audioOnly = !!tracks.audio && !tracks.video;
  38159. if (this.altAudio && !this.audioOnly) {
  38160. delete tracks.audio;
  38161. if (tracks.audiovideo) {
  38162. this.logMuxedErr(frag);
  38163. }
  38164. }
  38165. const {
  38166. audio,
  38167. video,
  38168. audiovideo
  38169. } = tracks;
  38170. if (audio) {
  38171. const levelCodec = currentLevel.audioCodec;
  38172. let audioCodec = pickMostCompleteCodecName(audio.codec, levelCodec);
  38173. if (audioCodec === "mp4a") {
  38174. audioCodec = "mp4a.40.5";
  38175. }
  38176. const ua = navigator.userAgent.toLowerCase();
  38177. if (this.audioCodecSwitch) {
  38178. if (audioCodec) {
  38179. if (audioCodec.indexOf("mp4a.40.5") !== -1) {
  38180. audioCodec = "mp4a.40.2";
  38181. } else {
  38182. audioCodec = "mp4a.40.5";
  38183. }
  38184. }
  38185. const audioMetadata = audio.metadata;
  38186. if (audioMetadata && "channelCount" in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf("firefox") === -1) {
  38187. audioCodec = "mp4a.40.5";
  38188. }
  38189. }
  38190. if (audioCodec && audioCodec.indexOf("mp4a.40.5") !== -1 && ua.indexOf("android") !== -1 && audio.container !== "audio/mpeg") {
  38191. audioCodec = "mp4a.40.2";
  38192. this.log(`Android: force audio codec to ${audioCodec}`);
  38193. }
  38194. if (levelCodec && levelCodec !== audioCodec) {
  38195. this.log(`Swapping manifest audio codec "${levelCodec}" for "${audioCodec}"`);
  38196. }
  38197. audio.levelCodec = audioCodec;
  38198. audio.id = PlaylistLevelType.MAIN;
  38199. this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ""}/${levelCodec || ""}/${audio.codec}]`);
  38200. delete tracks.audiovideo;
  38201. }
  38202. if (video) {
  38203. video.levelCodec = currentLevel.videoCodec;
  38204. video.id = PlaylistLevelType.MAIN;
  38205. const parsedVideoCodec = video.codec;
  38206. if ((parsedVideoCodec == null ? void 0 : parsedVideoCodec.length) === 4) {
  38207. switch (parsedVideoCodec) {
  38208. case "hvc1":
  38209. case "hev1":
  38210. video.codec = "hvc1.1.6.L120.90";
  38211. break;
  38212. case "av01":
  38213. video.codec = "av01.0.04M.08";
  38214. break;
  38215. case "avc1":
  38216. video.codec = "avc1.42e01e";
  38217. break;
  38218. }
  38219. }
  38220. this.log(`Init video buffer, container:${video.container}, codecs[level/parsed]=[${currentLevel.videoCodec || ""}/${parsedVideoCodec}]${video.codec !== parsedVideoCodec ? " parsed-corrected=" + video.codec : ""}${video.supplemental ? " supplemental=" + video.supplemental : ""}`);
  38221. delete tracks.audiovideo;
  38222. }
  38223. if (audiovideo) {
  38224. this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);
  38225. delete tracks.video;
  38226. delete tracks.audio;
  38227. }
  38228. const trackTypes = Object.keys(tracks);
  38229. if (trackTypes.length) {
  38230. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  38231. if (!this.hls) {
  38232. return;
  38233. }
  38234. trackTypes.forEach((trackName) => {
  38235. const track2 = tracks[trackName];
  38236. const initSegment = track2.initSegment;
  38237. if (initSegment != null && initSegment.byteLength) {
  38238. this.hls.trigger(Events.BUFFER_APPENDING, {
  38239. type: trackName,
  38240. data: initSegment,
  38241. frag,
  38242. part: null,
  38243. chunkMeta,
  38244. parent: frag.type
  38245. });
  38246. }
  38247. });
  38248. }
  38249. this.tickImmediate();
  38250. }
  38251. getMainFwdBufferInfo() {
  38252. const bufferOutput = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
  38253. return this.getFwdBufferInfo(bufferOutput, PlaylistLevelType.MAIN);
  38254. }
  38255. get maxBufferLength() {
  38256. const {
  38257. levels,
  38258. level
  38259. } = this;
  38260. const levelInfo = levels == null ? void 0 : levels[level];
  38261. if (!levelInfo) {
  38262. return this.config.maxBufferLength;
  38263. }
  38264. return this.getMaxBufferLength(levelInfo.maxBitrate);
  38265. }
  38266. backtrack(frag) {
  38267. this.couldBacktrack = true;
  38268. this.backtrackFragment = frag;
  38269. this.resetTransmuxer();
  38270. this.flushBufferGap(frag);
  38271. this.fragmentTracker.removeFragment(frag);
  38272. this.fragPrevious = null;
  38273. this.nextLoadPosition = frag.start;
  38274. this.state = State.IDLE;
  38275. }
  38276. checkFragmentChanged() {
  38277. const video = this.media;
  38278. let fragPlayingCurrent = null;
  38279. if (video && video.readyState > 1 && video.seeking === false) {
  38280. const currentTime = video.currentTime;
  38281. if (BufferHelper.isBuffered(video, currentTime)) {
  38282. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  38283. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  38284. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  38285. }
  38286. if (fragPlayingCurrent) {
  38287. this.backtrackFragment = null;
  38288. const fragPlaying = this.fragPlaying;
  38289. const fragCurrentLevel = fragPlayingCurrent.level;
  38290. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  38291. this.fragPlaying = fragPlayingCurrent;
  38292. this.hls.trigger(Events.FRAG_CHANGED, {
  38293. frag: fragPlayingCurrent
  38294. });
  38295. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  38296. this.hls.trigger(Events.LEVEL_SWITCHED, {
  38297. level: fragCurrentLevel
  38298. });
  38299. }
  38300. }
  38301. }
  38302. }
  38303. }
  38304. get nextLevel() {
  38305. const frag = this.nextBufferedFrag;
  38306. if (frag) {
  38307. return frag.level;
  38308. }
  38309. return -1;
  38310. }
  38311. get currentFrag() {
  38312. var _this$media3;
  38313. if (this.fragPlaying) {
  38314. return this.fragPlaying;
  38315. }
  38316. const currentTime = ((_this$media3 = this.media) == null ? void 0 : _this$media3.currentTime) || this.lastCurrentTime;
  38317. if (isFiniteNumber(currentTime)) {
  38318. return this.getAppendedFrag(currentTime);
  38319. }
  38320. return null;
  38321. }
  38322. get currentProgramDateTime() {
  38323. var _this$media4;
  38324. const currentTime = ((_this$media4 = this.media) == null ? void 0 : _this$media4.currentTime) || this.lastCurrentTime;
  38325. if (isFiniteNumber(currentTime)) {
  38326. const details = this.getLevelDetails();
  38327. const frag = this.currentFrag || (details ? findFragmentByPTS(null, details.fragments, currentTime) : null);
  38328. if (frag) {
  38329. const programDateTime = frag.programDateTime;
  38330. if (programDateTime !== null) {
  38331. const epocMs = programDateTime + (currentTime - frag.start) * 1e3;
  38332. return new Date(epocMs);
  38333. }
  38334. }
  38335. }
  38336. return null;
  38337. }
  38338. get currentLevel() {
  38339. const frag = this.currentFrag;
  38340. if (frag) {
  38341. return frag.level;
  38342. }
  38343. return -1;
  38344. }
  38345. get nextBufferedFrag() {
  38346. const frag = this.currentFrag;
  38347. if (frag) {
  38348. return this.followingBufferedFrag(frag);
  38349. }
  38350. return null;
  38351. }
  38352. get forceStartLoad() {
  38353. return this._forceStartLoad;
  38354. }
  38355. }
  38356. class KeyLoader {
  38357. constructor(config) {
  38358. this.config = void 0;
  38359. this.keyUriToKeyInfo = {};
  38360. this.emeController = null;
  38361. this.config = config;
  38362. }
  38363. abort(type) {
  38364. for (const uri in this.keyUriToKeyInfo) {
  38365. const loader = this.keyUriToKeyInfo[uri].loader;
  38366. if (loader) {
  38367. var _loader$context;
  38368. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  38369. return;
  38370. }
  38371. loader.abort();
  38372. }
  38373. }
  38374. }
  38375. detach() {
  38376. for (const uri in this.keyUriToKeyInfo) {
  38377. const keyInfo = this.keyUriToKeyInfo[uri];
  38378. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  38379. delete this.keyUriToKeyInfo[uri];
  38380. }
  38381. }
  38382. }
  38383. destroy() {
  38384. this.detach();
  38385. for (const uri in this.keyUriToKeyInfo) {
  38386. const loader = this.keyUriToKeyInfo[uri].loader;
  38387. if (loader) {
  38388. loader.destroy();
  38389. }
  38390. }
  38391. this.keyUriToKeyInfo = {};
  38392. }
  38393. createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) {
  38394. return new LoadError({
  38395. type: ErrorTypes.NETWORK_ERROR,
  38396. details,
  38397. fatal: false,
  38398. frag,
  38399. response,
  38400. error,
  38401. networkDetails
  38402. });
  38403. }
  38404. loadClear(loadingFrag, encryptedFragments, startFragRequested) {
  38405. if (this.emeController && this.config.emeEnabled && !this.emeController.getSelectedKeySystemFormats().length) {
  38406. if (encryptedFragments.length) {
  38407. for (let i2 = 0, l2 = encryptedFragments.length; i2 < l2; i2++) {
  38408. const frag = encryptedFragments[i2];
  38409. if (loadingFrag.cc <= frag.cc && (!isMediaFragment(loadingFrag) || !isMediaFragment(frag) || loadingFrag.sn < frag.sn) || !startFragRequested && i2 == l2 - 1) {
  38410. return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
  38411. if (!this.emeController) {
  38412. return;
  38413. }
  38414. frag.setKeyFormat(keySystemFormat);
  38415. const keySystem = keySystemFormatToKeySystemDomain(keySystemFormat);
  38416. if (keySystem) {
  38417. return this.emeController.getKeySystemAccess([keySystem]);
  38418. }
  38419. });
  38420. }
  38421. }
  38422. }
  38423. if (this.config.requireKeySystemAccessOnStart) {
  38424. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  38425. if (keySystemsInConfig.length) {
  38426. return this.emeController.getKeySystemAccess(keySystemsInConfig);
  38427. }
  38428. }
  38429. }
  38430. return null;
  38431. }
  38432. load(frag) {
  38433. if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) {
  38434. return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
  38435. return this.loadInternal(frag, keySystemFormat);
  38436. });
  38437. }
  38438. return this.loadInternal(frag);
  38439. }
  38440. loadInternal(frag, keySystemFormat) {
  38441. var _keyInfo, _keyInfo2;
  38442. if (keySystemFormat) {
  38443. frag.setKeyFormat(keySystemFormat);
  38444. }
  38445. const decryptdata = frag.decryptdata;
  38446. if (!decryptdata) {
  38447. const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : "Missing decryption data on fragment in onKeyLoading");
  38448. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  38449. }
  38450. const uri = decryptdata.uri;
  38451. if (!uri) {
  38452. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`)));
  38453. }
  38454. let keyInfo = this.keyUriToKeyInfo[uri];
  38455. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  38456. decryptdata.key = keyInfo.decryptdata.key;
  38457. return Promise.resolve({
  38458. frag,
  38459. keyInfo
  38460. });
  38461. }
  38462. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  38463. var _keyInfo$mediaKeySess;
  38464. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  38465. case void 0:
  38466. case "status-pending":
  38467. case "usable":
  38468. case "usable-in-future":
  38469. return keyInfo.keyLoadPromise.then((keyLoadedData) => {
  38470. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  38471. return {
  38472. frag,
  38473. keyInfo
  38474. };
  38475. });
  38476. }
  38477. }
  38478. keyInfo = this.keyUriToKeyInfo[uri] = {
  38479. decryptdata,
  38480. keyLoadPromise: null,
  38481. loader: null,
  38482. mediaKeySessionContext: null
  38483. };
  38484. switch (decryptdata.method) {
  38485. case "ISO-23001-7":
  38486. case "SAMPLE-AES":
  38487. case "SAMPLE-AES-CENC":
  38488. case "SAMPLE-AES-CTR":
  38489. if (decryptdata.keyFormat === "identity") {
  38490. return this.loadKeyHTTP(keyInfo, frag);
  38491. }
  38492. return this.loadKeyEME(keyInfo, frag);
  38493. case "AES-128":
  38494. case "AES-256":
  38495. case "AES-256-CTR":
  38496. return this.loadKeyHTTP(keyInfo, frag);
  38497. default:
  38498. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`)));
  38499. }
  38500. }
  38501. loadKeyEME(keyInfo, frag) {
  38502. const keyLoadedData = {
  38503. frag,
  38504. keyInfo
  38505. };
  38506. if (this.emeController && this.config.emeEnabled) {
  38507. const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  38508. if (keySessionContextPromise) {
  38509. return (keyInfo.keyLoadPromise = keySessionContextPromise.then((keySessionContext) => {
  38510. keyInfo.mediaKeySessionContext = keySessionContext;
  38511. return keyLoadedData;
  38512. })).catch((error) => {
  38513. keyInfo.keyLoadPromise = null;
  38514. throw error;
  38515. });
  38516. }
  38517. }
  38518. return Promise.resolve(keyLoadedData);
  38519. }
  38520. loadKeyHTTP(keyInfo, frag) {
  38521. const config = this.config;
  38522. const Loader = config.loader;
  38523. const keyLoader = new Loader(config);
  38524. frag.keyLoader = keyInfo.loader = keyLoader;
  38525. return keyInfo.keyLoadPromise = new Promise((resolve2, reject) => {
  38526. const loaderContext = {
  38527. keyInfo,
  38528. frag,
  38529. responseType: "arraybuffer",
  38530. url: keyInfo.decryptdata.uri
  38531. };
  38532. const loadPolicy = config.keyLoadPolicy.default;
  38533. const loaderConfig = {
  38534. loadPolicy,
  38535. timeout: loadPolicy.maxLoadTimeMs,
  38536. maxRetry: 0,
  38537. retryDelay: 0,
  38538. maxRetryDelay: 0
  38539. };
  38540. const loaderCallbacks = {
  38541. onSuccess: (response, stats, context, networkDetails) => {
  38542. const {
  38543. frag: frag2,
  38544. keyInfo: keyInfo2,
  38545. url: uri
  38546. } = context;
  38547. if (!frag2.decryptdata || keyInfo2 !== this.keyUriToKeyInfo[uri]) {
  38548. return reject(this.createKeyLoadError(frag2, ErrorDetails.KEY_LOAD_ERROR, new Error("after key load, decryptdata unset or changed"), networkDetails));
  38549. }
  38550. keyInfo2.decryptdata.key = frag2.decryptdata.key = new Uint8Array(response.data);
  38551. frag2.keyLoader = null;
  38552. keyInfo2.loader = null;
  38553. resolve2({
  38554. frag: frag2,
  38555. keyInfo: keyInfo2
  38556. });
  38557. },
  38558. onError: (response, context, networkDetails, stats) => {
  38559. this.resetLoader(context);
  38560. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({
  38561. url: loaderContext.url,
  38562. data: void 0
  38563. }, response)));
  38564. },
  38565. onTimeout: (stats, context, networkDetails) => {
  38566. this.resetLoader(context);
  38567. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error("key loading timed out"), networkDetails));
  38568. },
  38569. onAbort: (stats, context, networkDetails) => {
  38570. this.resetLoader(context);
  38571. reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error("key loading aborted"), networkDetails));
  38572. }
  38573. };
  38574. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  38575. });
  38576. }
  38577. resetLoader(context) {
  38578. const {
  38579. frag,
  38580. keyInfo,
  38581. url: uri
  38582. } = context;
  38583. const loader = keyInfo.loader;
  38584. if (frag.keyLoader === loader) {
  38585. frag.keyLoader = null;
  38586. keyInfo.loader = null;
  38587. }
  38588. delete this.keyUriToKeyInfo[uri];
  38589. if (loader) {
  38590. loader.destroy();
  38591. }
  38592. }
  38593. }
  38594. function mapContextToLevelType(context) {
  38595. const {
  38596. type
  38597. } = context;
  38598. switch (type) {
  38599. case PlaylistContextType.AUDIO_TRACK:
  38600. return PlaylistLevelType.AUDIO;
  38601. case PlaylistContextType.SUBTITLE_TRACK:
  38602. return PlaylistLevelType.SUBTITLE;
  38603. default:
  38604. return PlaylistLevelType.MAIN;
  38605. }
  38606. }
  38607. function getResponseUrl(response, context) {
  38608. let url = response.url;
  38609. if (url === void 0 || url.indexOf("data:") === 0) {
  38610. url = context.url;
  38611. }
  38612. return url;
  38613. }
  38614. class PlaylistLoader {
  38615. constructor(hls) {
  38616. this.hls = void 0;
  38617. this.loaders = /* @__PURE__ */ Object.create(null);
  38618. this.variableList = null;
  38619. this.onManifestLoaded = this.checkAutostartLoad;
  38620. this.hls = hls;
  38621. this.registerListeners();
  38622. }
  38623. startLoad(startPosition) {
  38624. }
  38625. stopLoad() {
  38626. this.destroyInternalLoaders();
  38627. }
  38628. registerListeners() {
  38629. const {
  38630. hls
  38631. } = this;
  38632. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  38633. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  38634. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  38635. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  38636. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  38637. }
  38638. unregisterListeners() {
  38639. const {
  38640. hls
  38641. } = this;
  38642. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  38643. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  38644. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  38645. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  38646. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  38647. }
  38648. /**
  38649. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  38650. */
  38651. createInternalLoader(context) {
  38652. const config = this.hls.config;
  38653. const PLoader = config.pLoader;
  38654. const Loader = config.loader;
  38655. const InternalLoader = PLoader || Loader;
  38656. const loader = new InternalLoader(config);
  38657. this.loaders[context.type] = loader;
  38658. return loader;
  38659. }
  38660. getInternalLoader(context) {
  38661. return this.loaders[context.type];
  38662. }
  38663. resetInternalLoader(contextType) {
  38664. if (this.loaders[contextType]) {
  38665. delete this.loaders[contextType];
  38666. }
  38667. }
  38668. /**
  38669. * Call `destroy` on all internal loader instances mapped (one per context type)
  38670. */
  38671. destroyInternalLoaders() {
  38672. for (const contextType in this.loaders) {
  38673. const loader = this.loaders[contextType];
  38674. if (loader) {
  38675. loader.destroy();
  38676. }
  38677. this.resetInternalLoader(contextType);
  38678. }
  38679. }
  38680. destroy() {
  38681. this.variableList = null;
  38682. this.unregisterListeners();
  38683. this.destroyInternalLoaders();
  38684. }
  38685. onManifestLoading(event, data) {
  38686. const {
  38687. url
  38688. } = data;
  38689. this.variableList = null;
  38690. this.load({
  38691. id: null,
  38692. level: 0,
  38693. responseType: "text",
  38694. type: PlaylistContextType.MANIFEST,
  38695. url,
  38696. deliveryDirectives: null,
  38697. levelOrTrack: null
  38698. });
  38699. }
  38700. onLevelLoading(event, data) {
  38701. const {
  38702. id,
  38703. level,
  38704. pathwayId,
  38705. url,
  38706. deliveryDirectives,
  38707. levelInfo
  38708. } = data;
  38709. this.load({
  38710. id,
  38711. level,
  38712. pathwayId,
  38713. responseType: "text",
  38714. type: PlaylistContextType.LEVEL,
  38715. url,
  38716. deliveryDirectives,
  38717. levelOrTrack: levelInfo
  38718. });
  38719. }
  38720. onAudioTrackLoading(event, data) {
  38721. const {
  38722. id,
  38723. groupId,
  38724. url,
  38725. deliveryDirectives,
  38726. track: track2
  38727. } = data;
  38728. this.load({
  38729. id,
  38730. groupId,
  38731. level: null,
  38732. responseType: "text",
  38733. type: PlaylistContextType.AUDIO_TRACK,
  38734. url,
  38735. deliveryDirectives,
  38736. levelOrTrack: track2
  38737. });
  38738. }
  38739. onSubtitleTrackLoading(event, data) {
  38740. const {
  38741. id,
  38742. groupId,
  38743. url,
  38744. deliveryDirectives,
  38745. track: track2
  38746. } = data;
  38747. this.load({
  38748. id,
  38749. groupId,
  38750. level: null,
  38751. responseType: "text",
  38752. type: PlaylistContextType.SUBTITLE_TRACK,
  38753. url,
  38754. deliveryDirectives,
  38755. levelOrTrack: track2
  38756. });
  38757. }
  38758. onLevelsUpdated(event, data) {
  38759. const loader = this.loaders[PlaylistContextType.LEVEL];
  38760. if (loader) {
  38761. const context = loader.context;
  38762. if (context && !data.levels.some((lvl) => lvl === context.levelOrTrack)) {
  38763. loader.abort();
  38764. delete this.loaders[PlaylistContextType.LEVEL];
  38765. }
  38766. }
  38767. }
  38768. load(context) {
  38769. var _context$deliveryDire;
  38770. const config = this.hls.config;
  38771. let loader = this.getInternalLoader(context);
  38772. if (loader) {
  38773. const logger2 = this.hls.logger;
  38774. const loaderContext = loader.context;
  38775. if (loaderContext && loaderContext.levelOrTrack === context.levelOrTrack && (loaderContext.url === context.url || loaderContext.deliveryDirectives && !context.deliveryDirectives)) {
  38776. if (loaderContext.url === context.url) {
  38777. logger2.log(`[playlist-loader]: ignore ${context.url} ongoing request`);
  38778. } else {
  38779. logger2.log(`[playlist-loader]: ignore ${context.url} in favor of ${loaderContext.url}`);
  38780. }
  38781. return;
  38782. }
  38783. logger2.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);
  38784. loader.abort();
  38785. }
  38786. let loadPolicy;
  38787. if (context.type === PlaylistContextType.MANIFEST) {
  38788. loadPolicy = config.manifestLoadPolicy.default;
  38789. } else {
  38790. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  38791. timeoutRetry: null,
  38792. errorRetry: null
  38793. });
  38794. }
  38795. loader = this.createInternalLoader(context);
  38796. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  38797. let levelDetails;
  38798. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  38799. levelDetails = this.hls.levels[context.level].details;
  38800. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  38801. levelDetails = this.hls.audioTracks[context.id].details;
  38802. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  38803. levelDetails = this.hls.subtitleTracks[context.id].details;
  38804. }
  38805. if (levelDetails) {
  38806. const partTarget = levelDetails.partTarget;
  38807. const targetDuration = levelDetails.targetduration;
  38808. if (partTarget && targetDuration) {
  38809. const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1e3;
  38810. loadPolicy = _extends({}, loadPolicy, {
  38811. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  38812. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  38813. });
  38814. }
  38815. }
  38816. }
  38817. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  38818. const loaderConfig = {
  38819. loadPolicy,
  38820. timeout: loadPolicy.maxLoadTimeMs,
  38821. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  38822. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  38823. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  38824. };
  38825. const loaderCallbacks = {
  38826. onSuccess: (response, stats, context2, networkDetails) => {
  38827. const loader2 = this.getInternalLoader(context2);
  38828. this.resetInternalLoader(context2.type);
  38829. const string = response.data;
  38830. if (string.indexOf("#EXTM3U") !== 0) {
  38831. this.handleManifestParsingError(response, context2, new Error("no EXTM3U delimiter"), networkDetails || null, stats);
  38832. return;
  38833. }
  38834. stats.parsing.start = performance.now();
  38835. if (M3U8Parser.isMediaPlaylist(string) || context2.type !== PlaylistContextType.MANIFEST) {
  38836. this.handleTrackOrLevelPlaylist(response, stats, context2, networkDetails || null, loader2);
  38837. } else {
  38838. this.handleMasterPlaylist(response, stats, context2, networkDetails);
  38839. }
  38840. },
  38841. onError: (response, context2, networkDetails, stats) => {
  38842. this.handleNetworkError(context2, networkDetails, false, response, stats);
  38843. },
  38844. onTimeout: (stats, context2, networkDetails) => {
  38845. this.handleNetworkError(context2, networkDetails, true, void 0, stats);
  38846. }
  38847. };
  38848. loader.load(context, loaderConfig, loaderCallbacks);
  38849. }
  38850. checkAutostartLoad() {
  38851. if (!this.hls) {
  38852. return;
  38853. }
  38854. const {
  38855. config: {
  38856. autoStartLoad,
  38857. startPosition
  38858. },
  38859. forceStartLoad
  38860. } = this.hls;
  38861. if (autoStartLoad || forceStartLoad) {
  38862. this.hls.logger.log(`${autoStartLoad ? "auto" : "force"} startLoad with configured startPosition ${startPosition}`);
  38863. this.hls.startLoad(startPosition);
  38864. }
  38865. }
  38866. handleMasterPlaylist(response, stats, context, networkDetails) {
  38867. const hls = this.hls;
  38868. const string = response.data;
  38869. const url = getResponseUrl(response, context);
  38870. const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  38871. if (parsedResult.playlistParsingError) {
  38872. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  38873. return;
  38874. }
  38875. const {
  38876. contentSteering,
  38877. levels,
  38878. sessionData,
  38879. sessionKeys,
  38880. startTimeOffset,
  38881. variableList
  38882. } = parsedResult;
  38883. this.variableList = variableList;
  38884. const {
  38885. AUDIO: audioTracks = [],
  38886. SUBTITLES: subtitles,
  38887. "CLOSED-CAPTIONS": captions
  38888. } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);
  38889. if (audioTracks.length) {
  38890. const embeddedAudioFound = audioTracks.some((audioTrack) => !audioTrack.url);
  38891. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  38892. this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one");
  38893. audioTracks.unshift({
  38894. type: "main",
  38895. name: "main",
  38896. groupId: "main",
  38897. default: false,
  38898. autoselect: false,
  38899. forced: false,
  38900. id: -1,
  38901. attrs: new AttrList({}),
  38902. bitrate: 0,
  38903. url: ""
  38904. });
  38905. }
  38906. }
  38907. hls.trigger(Events.MANIFEST_LOADED, {
  38908. levels,
  38909. audioTracks,
  38910. subtitles,
  38911. captions,
  38912. contentSteering,
  38913. url,
  38914. stats,
  38915. networkDetails,
  38916. sessionData,
  38917. sessionKeys,
  38918. startTimeOffset,
  38919. variableList
  38920. });
  38921. }
  38922. handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  38923. const hls = this.hls;
  38924. const {
  38925. id,
  38926. level,
  38927. type
  38928. } = context;
  38929. const url = getResponseUrl(response, context);
  38930. const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  38931. const levelType = mapContextToLevelType(context);
  38932. const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, 0, this.variableList);
  38933. if (type === PlaylistContextType.MANIFEST) {
  38934. const singleLevel = {
  38935. attrs: new AttrList({}),
  38936. bitrate: 0,
  38937. details: levelDetails,
  38938. name: "",
  38939. url
  38940. };
  38941. levelDetails.requestScheduled = stats.loading.start + computeReloadInterval(levelDetails, 0);
  38942. hls.trigger(Events.MANIFEST_LOADED, {
  38943. levels: [singleLevel],
  38944. audioTracks: [],
  38945. url,
  38946. stats,
  38947. networkDetails,
  38948. sessionData: null,
  38949. sessionKeys: null,
  38950. contentSteering: null,
  38951. startTimeOffset: null,
  38952. variableList: null
  38953. });
  38954. }
  38955. stats.parsing.end = performance.now();
  38956. context.levelDetails = levelDetails;
  38957. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  38958. }
  38959. handleManifestParsingError(response, context, error, networkDetails, stats) {
  38960. this.hls.trigger(Events.ERROR, {
  38961. type: ErrorTypes.NETWORK_ERROR,
  38962. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  38963. fatal: context.type === PlaylistContextType.MANIFEST,
  38964. url: response.url,
  38965. err: error,
  38966. error,
  38967. reason: error.message,
  38968. response,
  38969. context,
  38970. networkDetails,
  38971. stats
  38972. });
  38973. }
  38974. handleNetworkError(context, networkDetails, timeout = false, response, stats) {
  38975. let message = `A network ${timeout ? "timeout" : "error" + (response ? " (status " + response.code + ")" : "")} occurred while loading ${context.type}`;
  38976. if (context.type === PlaylistContextType.LEVEL) {
  38977. message += `: ${context.level} id: ${context.id}`;
  38978. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  38979. message += ` id: ${context.id} group-id: "${context.groupId}"`;
  38980. }
  38981. const error = new Error(message);
  38982. this.hls.logger.warn(`[playlist-loader]: ${message}`);
  38983. let details = ErrorDetails.UNKNOWN;
  38984. let fatal = false;
  38985. const loader = this.getInternalLoader(context);
  38986. switch (context.type) {
  38987. case PlaylistContextType.MANIFEST:
  38988. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  38989. fatal = true;
  38990. break;
  38991. case PlaylistContextType.LEVEL:
  38992. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  38993. fatal = false;
  38994. break;
  38995. case PlaylistContextType.AUDIO_TRACK:
  38996. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  38997. fatal = false;
  38998. break;
  38999. case PlaylistContextType.SUBTITLE_TRACK:
  39000. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  39001. fatal = false;
  39002. break;
  39003. }
  39004. if (loader) {
  39005. this.resetInternalLoader(context.type);
  39006. }
  39007. const errorData = {
  39008. type: ErrorTypes.NETWORK_ERROR,
  39009. details,
  39010. fatal,
  39011. url: context.url,
  39012. loader,
  39013. context,
  39014. error,
  39015. networkDetails,
  39016. stats
  39017. };
  39018. if (response) {
  39019. const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  39020. errorData.response = _objectSpread2({
  39021. url,
  39022. data: void 0
  39023. }, response);
  39024. }
  39025. this.hls.trigger(Events.ERROR, errorData);
  39026. }
  39027. handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  39028. const hls = this.hls;
  39029. const {
  39030. type,
  39031. level,
  39032. id,
  39033. groupId,
  39034. deliveryDirectives
  39035. } = context;
  39036. const url = getResponseUrl(response, context);
  39037. const parent = mapContextToLevelType(context);
  39038. const levelIndex = typeof context.level === "number" && parent === PlaylistLevelType.MAIN ? level : void 0;
  39039. if (!levelDetails.fragments.length) {
  39040. const _error = levelDetails.playlistParsingError = new Error("No Segments found in Playlist");
  39041. hls.trigger(Events.ERROR, {
  39042. type: ErrorTypes.NETWORK_ERROR,
  39043. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  39044. fatal: false,
  39045. url,
  39046. error: _error,
  39047. reason: _error.message,
  39048. response,
  39049. context,
  39050. level: levelIndex,
  39051. parent,
  39052. networkDetails,
  39053. stats
  39054. });
  39055. return;
  39056. }
  39057. if (!levelDetails.targetduration) {
  39058. levelDetails.playlistParsingError = new Error("Missing Target Duration");
  39059. }
  39060. const error = levelDetails.playlistParsingError;
  39061. if (error) {
  39062. this.hls.logger.warn(error);
  39063. if (!hls.config.ignorePlaylistParsingErrors) {
  39064. hls.trigger(Events.ERROR, {
  39065. type: ErrorTypes.NETWORK_ERROR,
  39066. details: ErrorDetails.LEVEL_PARSING_ERROR,
  39067. fatal: false,
  39068. url,
  39069. error,
  39070. reason: error.message,
  39071. response,
  39072. context,
  39073. level: levelIndex,
  39074. parent,
  39075. networkDetails,
  39076. stats
  39077. });
  39078. return;
  39079. }
  39080. levelDetails.playlistParsingError = null;
  39081. }
  39082. if (levelDetails.live && loader) {
  39083. if (loader.getCacheAge) {
  39084. levelDetails.ageHeader = loader.getCacheAge() || 0;
  39085. }
  39086. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  39087. levelDetails.ageHeader = 0;
  39088. }
  39089. }
  39090. switch (type) {
  39091. case PlaylistContextType.MANIFEST:
  39092. case PlaylistContextType.LEVEL:
  39093. hls.trigger(Events.LEVEL_LOADED, {
  39094. details: levelDetails,
  39095. levelInfo: context.levelOrTrack || hls.levels[0],
  39096. level: levelIndex || 0,
  39097. id: id || 0,
  39098. stats,
  39099. networkDetails,
  39100. deliveryDirectives,
  39101. withoutMultiVariant: type === PlaylistContextType.MANIFEST
  39102. });
  39103. break;
  39104. case PlaylistContextType.AUDIO_TRACK:
  39105. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  39106. details: levelDetails,
  39107. track: context.levelOrTrack,
  39108. id: id || 0,
  39109. groupId: groupId || "",
  39110. stats,
  39111. networkDetails,
  39112. deliveryDirectives
  39113. });
  39114. break;
  39115. case PlaylistContextType.SUBTITLE_TRACK:
  39116. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  39117. details: levelDetails,
  39118. track: context.levelOrTrack,
  39119. id: id || 0,
  39120. groupId: groupId || "",
  39121. stats,
  39122. networkDetails,
  39123. deliveryDirectives
  39124. });
  39125. break;
  39126. }
  39127. }
  39128. }
  39129. class Hls {
  39130. /**
  39131. * Get the video-dev/hls.js package version.
  39132. */
  39133. static get version() {
  39134. return version;
  39135. }
  39136. /**
  39137. * Check if the required MediaSource Extensions are available.
  39138. */
  39139. static isMSESupported() {
  39140. return isMSESupported();
  39141. }
  39142. /**
  39143. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  39144. */
  39145. static isSupported() {
  39146. return isSupported();
  39147. }
  39148. /**
  39149. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  39150. */
  39151. static getMediaSource() {
  39152. return getMediaSource();
  39153. }
  39154. static get Events() {
  39155. return Events;
  39156. }
  39157. static get MetadataSchema() {
  39158. return MetadataSchema;
  39159. }
  39160. static get ErrorTypes() {
  39161. return ErrorTypes;
  39162. }
  39163. static get ErrorDetails() {
  39164. return ErrorDetails;
  39165. }
  39166. /**
  39167. * Get the default configuration applied to new instances.
  39168. */
  39169. static get DefaultConfig() {
  39170. if (!Hls.defaultConfig) {
  39171. return hlsDefaultConfig;
  39172. }
  39173. return Hls.defaultConfig;
  39174. }
  39175. /**
  39176. * Replace the default configuration applied to new instances.
  39177. */
  39178. static set DefaultConfig(defaultConfig) {
  39179. Hls.defaultConfig = defaultConfig;
  39180. }
  39181. /**
  39182. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  39183. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  39184. */
  39185. constructor(userConfig = {}) {
  39186. this.config = void 0;
  39187. this.userConfig = void 0;
  39188. this.logger = void 0;
  39189. this.coreComponents = void 0;
  39190. this.networkControllers = void 0;
  39191. this._emitter = new EventEmitter();
  39192. this._autoLevelCapping = -1;
  39193. this._maxHdcpLevel = null;
  39194. this.abrController = void 0;
  39195. this.bufferController = void 0;
  39196. this.capLevelController = void 0;
  39197. this.latencyController = void 0;
  39198. this.levelController = void 0;
  39199. this.streamController = void 0;
  39200. this.audioStreamController = void 0;
  39201. this.subtititleStreamController = void 0;
  39202. this.audioTrackController = void 0;
  39203. this.subtitleTrackController = void 0;
  39204. this.interstitialsController = void 0;
  39205. this.gapController = void 0;
  39206. this.emeController = void 0;
  39207. this.cmcdController = void 0;
  39208. this._media = null;
  39209. this._url = null;
  39210. this._sessionId = void 0;
  39211. this.triggeringException = void 0;
  39212. this.started = false;
  39213. const logger2 = this.logger = enableLogs(userConfig.debug || false, "Hls instance", userConfig.assetPlayerId);
  39214. const config = this.config = mergeConfig(Hls.DefaultConfig, userConfig, logger2);
  39215. this.userConfig = userConfig;
  39216. if (config.progressive) {
  39217. enableStreamingMode(config, logger2);
  39218. }
  39219. const {
  39220. abrController: _AbrController,
  39221. bufferController: _BufferController,
  39222. capLevelController: _CapLevelController,
  39223. errorController: _ErrorController,
  39224. fpsController: _FpsController
  39225. } = config;
  39226. const errorController = new _ErrorController(this);
  39227. const abrController = this.abrController = new _AbrController(this);
  39228. const fragmentTracker = new FragmentTracker(this);
  39229. const _InterstitialsController = config.interstitialsController;
  39230. const interstitialsController = _InterstitialsController ? this.interstitialsController = new _InterstitialsController(this, Hls) : null;
  39231. const bufferController = this.bufferController = new _BufferController(this, fragmentTracker);
  39232. const capLevelController = this.capLevelController = new _CapLevelController(this);
  39233. const fpsController = new _FpsController(this);
  39234. const playListLoader = new PlaylistLoader(this);
  39235. const _ContentSteeringController = config.contentSteeringController;
  39236. const contentSteering = _ContentSteeringController ? new _ContentSteeringController(this) : null;
  39237. const levelController = this.levelController = new LevelController(this, contentSteering);
  39238. const id3TrackController = new ID3TrackController(this);
  39239. const keyLoader = new KeyLoader(this.config);
  39240. const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  39241. const gapController = this.gapController = new GapController(this, fragmentTracker);
  39242. capLevelController.setStreamController(streamController);
  39243. fpsController.setStreamController(streamController);
  39244. const networkControllers = [playListLoader, levelController, streamController];
  39245. if (interstitialsController) {
  39246. networkControllers.splice(1, 0, interstitialsController);
  39247. }
  39248. if (contentSteering) {
  39249. networkControllers.splice(1, 0, contentSteering);
  39250. }
  39251. this.networkControllers = networkControllers;
  39252. const coreComponents = [abrController, bufferController, gapController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  39253. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  39254. const AudioStreamControllerClass = config.audioStreamController;
  39255. if (AudioStreamControllerClass) {
  39256. networkControllers.push(this.audioStreamController = new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  39257. }
  39258. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  39259. const SubtitleStreamControllerClass = config.subtitleStreamController;
  39260. if (SubtitleStreamControllerClass) {
  39261. networkControllers.push(this.subtititleStreamController = new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  39262. }
  39263. this.createController(config.timelineController, coreComponents);
  39264. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  39265. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  39266. this.latencyController = this.createController(LatencyController, coreComponents);
  39267. this.coreComponents = coreComponents;
  39268. networkControllers.push(errorController);
  39269. const onErrorOut = errorController.onErrorOut;
  39270. if (typeof onErrorOut === "function") {
  39271. this.on(Events.ERROR, onErrorOut, errorController);
  39272. }
  39273. this.on(Events.MANIFEST_LOADED, playListLoader.onManifestLoaded, playListLoader);
  39274. }
  39275. createController(ControllerClass, components) {
  39276. if (ControllerClass) {
  39277. const controllerInstance = new ControllerClass(this);
  39278. if (components) {
  39279. components.push(controllerInstance);
  39280. }
  39281. return controllerInstance;
  39282. }
  39283. return null;
  39284. }
  39285. // Delegate the EventEmitter through the public API of Hls.js
  39286. on(event, listener, context = this) {
  39287. this._emitter.on(event, listener, context);
  39288. }
  39289. once(event, listener, context = this) {
  39290. this._emitter.once(event, listener, context);
  39291. }
  39292. removeAllListeners(event) {
  39293. this._emitter.removeAllListeners(event);
  39294. }
  39295. off(event, listener, context = this, once2) {
  39296. this._emitter.off(event, listener, context, once2);
  39297. }
  39298. listeners(event) {
  39299. return this._emitter.listeners(event);
  39300. }
  39301. emit(event, name, eventObject) {
  39302. return this._emitter.emit(event, name, eventObject);
  39303. }
  39304. trigger(event, eventObject) {
  39305. if (this.config.debug) {
  39306. return this.emit(event, event, eventObject);
  39307. } else {
  39308. try {
  39309. return this.emit(event, event, eventObject);
  39310. } catch (error) {
  39311. this.logger.error("An internal error happened while handling event " + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  39312. if (!this.triggeringException) {
  39313. this.triggeringException = true;
  39314. const fatal = event === Events.ERROR;
  39315. this.trigger(Events.ERROR, {
  39316. type: ErrorTypes.OTHER_ERROR,
  39317. details: ErrorDetails.INTERNAL_EXCEPTION,
  39318. fatal,
  39319. event,
  39320. error
  39321. });
  39322. this.triggeringException = false;
  39323. }
  39324. }
  39325. }
  39326. return false;
  39327. }
  39328. listenerCount(event) {
  39329. return this._emitter.listenerCount(event);
  39330. }
  39331. /**
  39332. * Dispose of the instance
  39333. */
  39334. destroy() {
  39335. this.logger.log("destroy");
  39336. this.trigger(Events.DESTROYING, void 0);
  39337. this.detachMedia();
  39338. this.removeAllListeners();
  39339. this._autoLevelCapping = -1;
  39340. this._url = null;
  39341. this.networkControllers.forEach((component) => component.destroy());
  39342. this.networkControllers.length = 0;
  39343. this.coreComponents.forEach((component) => component.destroy());
  39344. this.coreComponents.length = 0;
  39345. const config = this.config;
  39346. config.xhrSetup = config.fetchSetup = void 0;
  39347. this.userConfig = null;
  39348. }
  39349. /**
  39350. * Attaches Hls.js to a media element
  39351. */
  39352. attachMedia(data) {
  39353. if (!data || "media" in data && !data.media) {
  39354. const error = new Error(`attachMedia failed: invalid argument (${data})`);
  39355. this.trigger(Events.ERROR, {
  39356. type: ErrorTypes.OTHER_ERROR,
  39357. details: ErrorDetails.ATTACH_MEDIA_ERROR,
  39358. fatal: true,
  39359. error
  39360. });
  39361. return;
  39362. }
  39363. this.logger.log(`attachMedia`);
  39364. if (this._media) {
  39365. this.logger.warn(`media must be detached before attaching`);
  39366. this.detachMedia();
  39367. }
  39368. const attachMediaSource = "media" in data;
  39369. const media = attachMediaSource ? data.media : data;
  39370. const attachingData = attachMediaSource ? data : {
  39371. media
  39372. };
  39373. this._media = media;
  39374. this.trigger(Events.MEDIA_ATTACHING, attachingData);
  39375. }
  39376. /**
  39377. * Detach Hls.js from the media
  39378. */
  39379. detachMedia() {
  39380. this.logger.log("detachMedia");
  39381. this.trigger(Events.MEDIA_DETACHING, {});
  39382. this._media = null;
  39383. }
  39384. /**
  39385. * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance
  39386. */
  39387. transferMedia() {
  39388. this._media = null;
  39389. const transferMedia = this.bufferController.transferMedia();
  39390. this.trigger(Events.MEDIA_DETACHING, {
  39391. transferMedia
  39392. });
  39393. return transferMedia;
  39394. }
  39395. /**
  39396. * Set the source URL. Can be relative or absolute.
  39397. */
  39398. loadSource(url) {
  39399. this.stopLoad();
  39400. const media = this.media;
  39401. const loadedSource = this._url;
  39402. const loadingSource = this._url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  39403. alwaysNormalize: true
  39404. });
  39405. this._autoLevelCapping = -1;
  39406. this._maxHdcpLevel = null;
  39407. this.logger.log(`loadSource:${loadingSource}`);
  39408. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  39409. this.detachMedia();
  39410. this.attachMedia(media);
  39411. }
  39412. this.trigger(Events.MANIFEST_LOADING, {
  39413. url
  39414. });
  39415. }
  39416. /**
  39417. * Gets the currently loaded URL
  39418. */
  39419. get url() {
  39420. return this._url;
  39421. }
  39422. /**
  39423. * Whether or not enough has been buffered to seek to start position or use `media.currentTime` to determine next load position
  39424. */
  39425. get hasEnoughToStart() {
  39426. return this.streamController.hasEnoughToStart;
  39427. }
  39428. /**
  39429. * Get the startPosition set on startLoad(position) or on autostart with config.startPosition
  39430. */
  39431. get startPosition() {
  39432. return this.streamController.startPositionValue;
  39433. }
  39434. /**
  39435. * Start loading data from the stream source.
  39436. * Depending on default config, client starts loading automatically when a source is set.
  39437. *
  39438. * @param startPosition - Set the start position to stream from.
  39439. * Defaults to -1 (None: starts from earliest point)
  39440. */
  39441. startLoad(startPosition = -1, skipSeekToStartPosition) {
  39442. this.logger.log(`startLoad(${startPosition + (skipSeekToStartPosition ? ", <skip seek to start>" : "")})`);
  39443. this.started = true;
  39444. this.resumeBuffering();
  39445. for (let i2 = 0; i2 < this.networkControllers.length; i2++) {
  39446. this.networkControllers[i2].startLoad(startPosition, skipSeekToStartPosition);
  39447. if (!this.started || !this.networkControllers) {
  39448. break;
  39449. }
  39450. }
  39451. }
  39452. /**
  39453. * Stop loading of any stream data.
  39454. */
  39455. stopLoad() {
  39456. this.logger.log("stopLoad");
  39457. this.started = false;
  39458. for (let i2 = 0; i2 < this.networkControllers.length; i2++) {
  39459. this.networkControllers[i2].stopLoad();
  39460. if (this.started || !this.networkControllers) {
  39461. break;
  39462. }
  39463. }
  39464. }
  39465. /**
  39466. * Returns whether loading, toggled with `startLoad()` and `stopLoad()`, is active or not`.
  39467. */
  39468. get loadingEnabled() {
  39469. return this.started;
  39470. }
  39471. /**
  39472. * Returns state of fragment loading toggled by calling `pauseBuffering()` and `resumeBuffering()`.
  39473. */
  39474. get bufferingEnabled() {
  39475. return this.streamController.bufferingEnabled;
  39476. }
  39477. /**
  39478. * Resumes stream controller segment loading after `pauseBuffering` has been called.
  39479. */
  39480. resumeBuffering() {
  39481. if (!this.bufferingEnabled) {
  39482. this.logger.log(`resume buffering`);
  39483. this.networkControllers.forEach((controller) => {
  39484. if (controller.resumeBuffering) {
  39485. controller.resumeBuffering();
  39486. }
  39487. });
  39488. }
  39489. }
  39490. /**
  39491. * Prevents stream controller from loading new segments until `resumeBuffering` is called.
  39492. * This allows for media buffering to be paused without interupting playlist loading.
  39493. */
  39494. pauseBuffering() {
  39495. if (this.bufferingEnabled) {
  39496. this.logger.log(`pause buffering`);
  39497. this.networkControllers.forEach((controller) => {
  39498. if (controller.pauseBuffering) {
  39499. controller.pauseBuffering();
  39500. }
  39501. });
  39502. }
  39503. }
  39504. get inFlightFragments() {
  39505. const inFlightData = {
  39506. [PlaylistLevelType.MAIN]: this.streamController.inFlightFrag
  39507. };
  39508. if (this.audioStreamController) {
  39509. inFlightData[PlaylistLevelType.AUDIO] = this.audioStreamController.inFlightFrag;
  39510. }
  39511. if (this.subtititleStreamController) {
  39512. inFlightData[PlaylistLevelType.SUBTITLE] = this.subtititleStreamController.inFlightFrag;
  39513. }
  39514. return inFlightData;
  39515. }
  39516. /**
  39517. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  39518. */
  39519. swapAudioCodec() {
  39520. this.logger.log("swapAudioCodec");
  39521. this.streamController.swapAudioCodec();
  39522. }
  39523. /**
  39524. * When the media-element fails, this allows to detach and then re-attach it
  39525. * as one call (convenience method).
  39526. *
  39527. * Automatic recovery of media-errors by this process is configurable.
  39528. */
  39529. recoverMediaError() {
  39530. this.logger.log("recoverMediaError");
  39531. const media = this._media;
  39532. const time = media == null ? void 0 : media.currentTime;
  39533. this.detachMedia();
  39534. if (media) {
  39535. this.attachMedia(media);
  39536. if (time) {
  39537. this.startLoad(time);
  39538. }
  39539. }
  39540. }
  39541. removeLevel(levelIndex) {
  39542. this.levelController.removeLevel(levelIndex);
  39543. }
  39544. /**
  39545. * @returns a UUID for this player instance
  39546. */
  39547. get sessionId() {
  39548. let _sessionId = this._sessionId;
  39549. if (!_sessionId) {
  39550. _sessionId = this._sessionId = uuid();
  39551. }
  39552. return _sessionId;
  39553. }
  39554. /**
  39555. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  39556. */
  39557. get levels() {
  39558. const levels = this.levelController.levels;
  39559. return levels ? levels : [];
  39560. }
  39561. /**
  39562. * @returns LevelDetails of last loaded level (variant) or `null` prior to loading a media playlist.
  39563. */
  39564. get latestLevelDetails() {
  39565. return this.streamController.getLevelDetails() || null;
  39566. }
  39567. /**
  39568. * @returns Level object of selected level (variant) or `null` prior to selecting a level or once the level is removed.
  39569. */
  39570. get loadLevelObj() {
  39571. return this.levelController.loadLevelObj;
  39572. }
  39573. /**
  39574. * Index of quality level (variant) currently played
  39575. */
  39576. get currentLevel() {
  39577. return this.streamController.currentLevel;
  39578. }
  39579. /**
  39580. * 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.
  39581. */
  39582. set currentLevel(newLevel) {
  39583. this.logger.log(`set currentLevel:${newLevel}`);
  39584. this.levelController.manualLevel = newLevel;
  39585. this.streamController.immediateLevelSwitch();
  39586. }
  39587. /**
  39588. * Index of next quality level loaded as scheduled by stream controller.
  39589. */
  39590. get nextLevel() {
  39591. return this.streamController.nextLevel;
  39592. }
  39593. /**
  39594. * Set quality level index for next loaded data.
  39595. * This will switch the video quality asap, without interrupting playback.
  39596. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  39597. * @param newLevel - Pass -1 for automatic level selection
  39598. */
  39599. set nextLevel(newLevel) {
  39600. this.logger.log(`set nextLevel:${newLevel}`);
  39601. this.levelController.manualLevel = newLevel;
  39602. this.streamController.nextLevelSwitch();
  39603. }
  39604. /**
  39605. * Return the quality level of the currently or last (of none is loaded currently) segment
  39606. */
  39607. get loadLevel() {
  39608. return this.levelController.level;
  39609. }
  39610. /**
  39611. * Set quality level index for next loaded data in a conservative way.
  39612. * This will switch the quality without flushing, but interrupt current loading.
  39613. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  39614. * @param newLevel - Pass -1 for automatic level selection
  39615. */
  39616. set loadLevel(newLevel) {
  39617. this.logger.log(`set loadLevel:${newLevel}`);
  39618. this.levelController.manualLevel = newLevel;
  39619. }
  39620. /**
  39621. * get next quality level loaded
  39622. */
  39623. get nextLoadLevel() {
  39624. return this.levelController.nextLoadLevel;
  39625. }
  39626. /**
  39627. * Set quality level of next loaded segment in a fully "non-destructive" way.
  39628. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  39629. */
  39630. set nextLoadLevel(level) {
  39631. this.levelController.nextLoadLevel = level;
  39632. }
  39633. /**
  39634. * Return "first level": like a default level, if not set,
  39635. * falls back to index of first level referenced in manifest
  39636. */
  39637. get firstLevel() {
  39638. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  39639. }
  39640. /**
  39641. * Sets "first-level", see getter.
  39642. */
  39643. set firstLevel(newLevel) {
  39644. this.logger.log(`set firstLevel:${newLevel}`);
  39645. this.levelController.firstLevel = newLevel;
  39646. }
  39647. /**
  39648. * Return the desired start level for the first fragment that will be loaded.
  39649. * The default value of -1 indicates automatic start level selection.
  39650. * Setting hls.nextAutoLevel without setting a startLevel will result in
  39651. * the nextAutoLevel value being used for one fragment load.
  39652. */
  39653. get startLevel() {
  39654. const startLevel = this.levelController.startLevel;
  39655. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  39656. return this.abrController.forcedAutoLevel;
  39657. }
  39658. return startLevel;
  39659. }
  39660. /**
  39661. * set start level (level of first fragment that will be played back)
  39662. * if not overrided by user, first level appearing in manifest will be used as start level
  39663. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  39664. * (determined from download of first segment)
  39665. */
  39666. set startLevel(newLevel) {
  39667. this.logger.log(`set startLevel:${newLevel}`);
  39668. if (newLevel !== -1) {
  39669. newLevel = Math.max(newLevel, this.minAutoLevel);
  39670. }
  39671. this.levelController.startLevel = newLevel;
  39672. }
  39673. /**
  39674. * Whether level capping is enabled.
  39675. * Default value is set via `config.capLevelToPlayerSize`.
  39676. */
  39677. get capLevelToPlayerSize() {
  39678. return this.config.capLevelToPlayerSize;
  39679. }
  39680. /**
  39681. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  39682. */
  39683. set capLevelToPlayerSize(shouldStartCapping) {
  39684. const newCapLevelToPlayerSize = !!shouldStartCapping;
  39685. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  39686. if (newCapLevelToPlayerSize) {
  39687. this.capLevelController.startCapping();
  39688. } else {
  39689. this.capLevelController.stopCapping();
  39690. this.autoLevelCapping = -1;
  39691. this.streamController.nextLevelSwitch();
  39692. }
  39693. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  39694. }
  39695. }
  39696. /**
  39697. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  39698. */
  39699. get autoLevelCapping() {
  39700. return this._autoLevelCapping;
  39701. }
  39702. /**
  39703. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  39704. */
  39705. get bandwidthEstimate() {
  39706. const {
  39707. bwEstimator
  39708. } = this.abrController;
  39709. if (!bwEstimator) {
  39710. return NaN;
  39711. }
  39712. return bwEstimator.getEstimate();
  39713. }
  39714. set bandwidthEstimate(abrEwmaDefaultEstimate) {
  39715. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  39716. }
  39717. get abrEwmaDefaultEstimate() {
  39718. const {
  39719. bwEstimator
  39720. } = this.abrController;
  39721. if (!bwEstimator) {
  39722. return NaN;
  39723. }
  39724. return bwEstimator.defaultEstimate;
  39725. }
  39726. /**
  39727. * get time to first byte estimate
  39728. * @type {number}
  39729. */
  39730. get ttfbEstimate() {
  39731. const {
  39732. bwEstimator
  39733. } = this.abrController;
  39734. if (!bwEstimator) {
  39735. return NaN;
  39736. }
  39737. return bwEstimator.getEstimateTTFB();
  39738. }
  39739. /**
  39740. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  39741. */
  39742. set autoLevelCapping(newLevel) {
  39743. if (this._autoLevelCapping !== newLevel) {
  39744. this.logger.log(`set autoLevelCapping:${newLevel}`);
  39745. this._autoLevelCapping = newLevel;
  39746. this.levelController.checkMaxAutoUpdated();
  39747. }
  39748. }
  39749. get maxHdcpLevel() {
  39750. return this._maxHdcpLevel;
  39751. }
  39752. set maxHdcpLevel(value) {
  39753. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  39754. this._maxHdcpLevel = value;
  39755. this.levelController.checkMaxAutoUpdated();
  39756. }
  39757. }
  39758. /**
  39759. * True when automatic level selection enabled
  39760. */
  39761. get autoLevelEnabled() {
  39762. return this.levelController.manualLevel === -1;
  39763. }
  39764. /**
  39765. * Level set manually (if any)
  39766. */
  39767. get manualLevel() {
  39768. return this.levelController.manualLevel;
  39769. }
  39770. /**
  39771. * min level selectable in auto mode according to config.minAutoBitrate
  39772. */
  39773. get minAutoLevel() {
  39774. const {
  39775. levels,
  39776. config: {
  39777. minAutoBitrate
  39778. }
  39779. } = this;
  39780. if (!levels)
  39781. return 0;
  39782. const len = levels.length;
  39783. for (let i2 = 0; i2 < len; i2++) {
  39784. if (levels[i2].maxBitrate >= minAutoBitrate) {
  39785. return i2;
  39786. }
  39787. }
  39788. return 0;
  39789. }
  39790. /**
  39791. * max level selectable in auto mode according to autoLevelCapping
  39792. */
  39793. get maxAutoLevel() {
  39794. const {
  39795. levels,
  39796. autoLevelCapping,
  39797. maxHdcpLevel
  39798. } = this;
  39799. let maxAutoLevel;
  39800. if (autoLevelCapping === -1 && levels != null && levels.length) {
  39801. maxAutoLevel = levels.length - 1;
  39802. } else {
  39803. maxAutoLevel = autoLevelCapping;
  39804. }
  39805. if (maxHdcpLevel) {
  39806. for (let i2 = maxAutoLevel; i2--; ) {
  39807. const hdcpLevel = levels[i2].attrs["HDCP-LEVEL"];
  39808. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  39809. return i2;
  39810. }
  39811. }
  39812. }
  39813. return maxAutoLevel;
  39814. }
  39815. get firstAutoLevel() {
  39816. return this.abrController.firstAutoLevel;
  39817. }
  39818. /**
  39819. * next automatically selected quality level
  39820. */
  39821. get nextAutoLevel() {
  39822. return this.abrController.nextAutoLevel;
  39823. }
  39824. /**
  39825. * this setter is used to force next auto level.
  39826. * this is useful to force a switch down in auto mode:
  39827. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  39828. * forced value is valid for one fragment. upon successful frag loading at forced level,
  39829. * this value will be resetted to -1 by ABR controller.
  39830. */
  39831. set nextAutoLevel(nextLevel) {
  39832. this.abrController.nextAutoLevel = nextLevel;
  39833. }
  39834. /**
  39835. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  39836. */
  39837. get playingDate() {
  39838. return this.streamController.currentProgramDateTime;
  39839. }
  39840. get mainForwardBufferInfo() {
  39841. return this.streamController.getMainFwdBufferInfo();
  39842. }
  39843. get maxBufferLength() {
  39844. return this.streamController.maxBufferLength;
  39845. }
  39846. /**
  39847. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  39848. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  39849. */
  39850. setAudioOption(audioOption) {
  39851. var _this$audioTrackContr;
  39852. return ((_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption)) || null;
  39853. }
  39854. /**
  39855. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  39856. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  39857. */
  39858. setSubtitleOption(subtitleOption) {
  39859. var _this$subtitleTrackCo;
  39860. return ((_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption)) || null;
  39861. }
  39862. /**
  39863. * Get the complete list of audio tracks across all media groups
  39864. */
  39865. get allAudioTracks() {
  39866. const audioTrackController = this.audioTrackController;
  39867. return audioTrackController ? audioTrackController.allAudioTracks : [];
  39868. }
  39869. /**
  39870. * Get the list of selectable audio tracks
  39871. */
  39872. get audioTracks() {
  39873. const audioTrackController = this.audioTrackController;
  39874. return audioTrackController ? audioTrackController.audioTracks : [];
  39875. }
  39876. /**
  39877. * index of the selected audio track (index in audio track lists)
  39878. */
  39879. get audioTrack() {
  39880. const audioTrackController = this.audioTrackController;
  39881. return audioTrackController ? audioTrackController.audioTrack : -1;
  39882. }
  39883. /**
  39884. * selects an audio track, based on its index in audio track lists
  39885. */
  39886. set audioTrack(audioTrackId) {
  39887. const audioTrackController = this.audioTrackController;
  39888. if (audioTrackController) {
  39889. audioTrackController.audioTrack = audioTrackId;
  39890. }
  39891. }
  39892. /**
  39893. * get the complete list of subtitle tracks across all media groups
  39894. */
  39895. get allSubtitleTracks() {
  39896. const subtitleTrackController = this.subtitleTrackController;
  39897. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  39898. }
  39899. /**
  39900. * get alternate subtitle tracks list from playlist
  39901. */
  39902. get subtitleTracks() {
  39903. const subtitleTrackController = this.subtitleTrackController;
  39904. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  39905. }
  39906. /**
  39907. * index of the selected subtitle track (index in subtitle track lists)
  39908. */
  39909. get subtitleTrack() {
  39910. const subtitleTrackController = this.subtitleTrackController;
  39911. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  39912. }
  39913. get media() {
  39914. return this._media;
  39915. }
  39916. /**
  39917. * select an subtitle track, based on its index in subtitle track lists
  39918. */
  39919. set subtitleTrack(subtitleTrackId) {
  39920. const subtitleTrackController = this.subtitleTrackController;
  39921. if (subtitleTrackController) {
  39922. subtitleTrackController.subtitleTrack = subtitleTrackId;
  39923. }
  39924. }
  39925. /**
  39926. * Whether subtitle display is enabled or not
  39927. */
  39928. get subtitleDisplay() {
  39929. const subtitleTrackController = this.subtitleTrackController;
  39930. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  39931. }
  39932. /**
  39933. * Enable/disable subtitle display rendering
  39934. */
  39935. set subtitleDisplay(value) {
  39936. const subtitleTrackController = this.subtitleTrackController;
  39937. if (subtitleTrackController) {
  39938. subtitleTrackController.subtitleDisplay = value;
  39939. }
  39940. }
  39941. /**
  39942. * get mode for Low-Latency HLS loading
  39943. */
  39944. get lowLatencyMode() {
  39945. return this.config.lowLatencyMode;
  39946. }
  39947. /**
  39948. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  39949. */
  39950. set lowLatencyMode(mode) {
  39951. this.config.lowLatencyMode = mode;
  39952. }
  39953. /**
  39954. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  39955. * @returns null prior to loading live Playlist
  39956. */
  39957. get liveSyncPosition() {
  39958. return this.latencyController.liveSyncPosition;
  39959. }
  39960. /**
  39961. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  39962. * @returns 0 before first playlist is loaded
  39963. */
  39964. get latency() {
  39965. return this.latencyController.latency;
  39966. }
  39967. /**
  39968. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  39969. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  39970. * @returns 0 before first playlist is loaded
  39971. */
  39972. get maxLatency() {
  39973. return this.latencyController.maxLatency;
  39974. }
  39975. /**
  39976. * target distance from the edge as calculated by the latency controller
  39977. */
  39978. get targetLatency() {
  39979. return this.latencyController.targetLatency;
  39980. }
  39981. set targetLatency(latency) {
  39982. this.latencyController.targetLatency = latency;
  39983. }
  39984. /**
  39985. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  39986. */
  39987. get drift() {
  39988. return this.latencyController.drift;
  39989. }
  39990. /**
  39991. * set to true when startLoad is called before MANIFEST_PARSED event
  39992. */
  39993. get forceStartLoad() {
  39994. return this.streamController.forceStartLoad;
  39995. }
  39996. /**
  39997. * ContentSteering pathways getter
  39998. */
  39999. get pathways() {
  40000. return this.levelController.pathways;
  40001. }
  40002. /**
  40003. * ContentSteering pathwayPriority getter/setter
  40004. */
  40005. get pathwayPriority() {
  40006. return this.levelController.pathwayPriority;
  40007. }
  40008. set pathwayPriority(pathwayPriority) {
  40009. this.levelController.pathwayPriority = pathwayPriority;
  40010. }
  40011. /**
  40012. * returns true when all SourceBuffers are buffered to the end
  40013. */
  40014. get bufferedToEnd() {
  40015. var _this$bufferControlle;
  40016. return !!((_this$bufferControlle = this.bufferController) != null && _this$bufferControlle.bufferedToEnd);
  40017. }
  40018. /**
  40019. * returns Interstitials Program Manager
  40020. */
  40021. get interstitialsManager() {
  40022. var _this$interstitialsCo;
  40023. return ((_this$interstitialsCo = this.interstitialsController) == null ? void 0 : _this$interstitialsCo.interstitialsManager) || null;
  40024. }
  40025. /**
  40026. * returns mediaCapabilities.decodingInfo for a variant/rendition
  40027. */
  40028. getMediaDecodingInfo(level, audioTracks = this.allAudioTracks) {
  40029. const audioTracksByGroup = getAudioTracksByGroup(audioTracks);
  40030. return getMediaDecodingInfoPromise(level, audioTracksByGroup, navigator.mediaCapabilities);
  40031. }
  40032. }
  40033. Hls.defaultConfig = void 0;
  40034. var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
  40035. function getDefaultExportFromCjs(x) {
  40036. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
  40037. }
  40038. function getAugmentedNamespace(n2) {
  40039. if (n2.__esModule)
  40040. return n2;
  40041. var f2 = n2.default;
  40042. if (typeof f2 == "function") {
  40043. var a2 = function a3() {
  40044. if (this instanceof a3) {
  40045. return Reflect.construct(f2, arguments, this.constructor);
  40046. }
  40047. return f2.apply(this, arguments);
  40048. };
  40049. a2.prototype = f2.prototype;
  40050. } else
  40051. a2 = {};
  40052. Object.defineProperty(a2, "__esModule", { value: true });
  40053. Object.keys(n2).forEach(function(k) {
  40054. var d2 = Object.getOwnPropertyDescriptor(n2, k);
  40055. Object.defineProperty(a2, k, d2.get ? d2 : {
  40056. enumerable: true,
  40057. get: function() {
  40058. return n2[k];
  40059. }
  40060. });
  40061. });
  40062. return a2;
  40063. }
  40064. var cryptoJs = { exports: {} };
  40065. function commonjsRequire(path) {
  40066. throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
  40067. }
  40068. var core = { exports: {} };
  40069. const __viteBrowserExternal = new Proxy({}, {
  40070. get(_2, key) {
  40071. throw new Error(`Module "" has been externalized for browser compatibility. Cannot access ".${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
  40072. }
  40073. });
  40074. const __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  40075. __proto__: null,
  40076. default: __viteBrowserExternal
  40077. }, Symbol.toStringTag, { value: "Module" }));
  40078. const require$$0 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1);
  40079. var hasRequiredCore;
  40080. function requireCore() {
  40081. if (hasRequiredCore)
  40082. return core.exports;
  40083. hasRequiredCore = 1;
  40084. (function(module2, exports2) {
  40085. (function(root, factory) {
  40086. {
  40087. module2.exports = factory();
  40088. }
  40089. })(commonjsGlobal, function() {
  40090. var CryptoJS2 = CryptoJS2 || function(Math2, undefined$1) {
  40091. var crypto2;
  40092. if (typeof window !== "undefined" && window.crypto) {
  40093. crypto2 = window.crypto;
  40094. }
  40095. if (typeof self !== "undefined" && self.crypto) {
  40096. crypto2 = self.crypto;
  40097. }
  40098. if (typeof globalThis !== "undefined" && globalThis.crypto) {
  40099. crypto2 = globalThis.crypto;
  40100. }
  40101. if (!crypto2 && typeof window !== "undefined" && window.msCrypto) {
  40102. crypto2 = window.msCrypto;
  40103. }
  40104. if (!crypto2 && typeof commonjsGlobal !== "undefined" && commonjsGlobal.crypto) {
  40105. crypto2 = commonjsGlobal.crypto;
  40106. }
  40107. if (!crypto2 && typeof commonjsRequire === "function") {
  40108. try {
  40109. crypto2 = require$$0;
  40110. } catch (err) {
  40111. }
  40112. }
  40113. var cryptoSecureRandomInt = function() {
  40114. if (crypto2) {
  40115. if (typeof crypto2.getRandomValues === "function") {
  40116. try {
  40117. return crypto2.getRandomValues(new Uint32Array(1))[0];
  40118. } catch (err) {
  40119. }
  40120. }
  40121. if (typeof crypto2.randomBytes === "function") {
  40122. try {
  40123. return crypto2.randomBytes(4).readInt32LE();
  40124. } catch (err) {
  40125. }
  40126. }
  40127. }
  40128. throw new Error("Native crypto module could not be used to get secure random number.");
  40129. };
  40130. var create = Object.create || /* @__PURE__ */ function() {
  40131. function F2() {
  40132. }
  40133. return function(obj) {
  40134. var subtype;
  40135. F2.prototype = obj;
  40136. subtype = new F2();
  40137. F2.prototype = null;
  40138. return subtype;
  40139. };
  40140. }();
  40141. var C2 = {};
  40142. var C_lib = C2.lib = {};
  40143. var Base = C_lib.Base = /* @__PURE__ */ function() {
  40144. return {
  40145. /**
  40146. * Creates a new object that inherits from this object.
  40147. *
  40148. * @param {Object} overrides Properties to copy into the new object.
  40149. *
  40150. * @return {Object} The new object.
  40151. *
  40152. * @static
  40153. *
  40154. * @example
  40155. *
  40156. * var MyType = CryptoJS.lib.Base.extend({
  40157. * field: 'value',
  40158. *
  40159. * method: function () {
  40160. * }
  40161. * });
  40162. */
  40163. extend: function(overrides) {
  40164. var subtype = create(this);
  40165. if (overrides) {
  40166. subtype.mixIn(overrides);
  40167. }
  40168. if (!subtype.hasOwnProperty("init") || this.init === subtype.init) {
  40169. subtype.init = function() {
  40170. subtype.$super.init.apply(this, arguments);
  40171. };
  40172. }
  40173. subtype.init.prototype = subtype;
  40174. subtype.$super = this;
  40175. return subtype;
  40176. },
  40177. /**
  40178. * Extends this object and runs the init method.
  40179. * Arguments to create() will be passed to init().
  40180. *
  40181. * @return {Object} The new object.
  40182. *
  40183. * @static
  40184. *
  40185. * @example
  40186. *
  40187. * var instance = MyType.create();
  40188. */
  40189. create: function() {
  40190. var instance = this.extend();
  40191. instance.init.apply(instance, arguments);
  40192. return instance;
  40193. },
  40194. /**
  40195. * Initializes a newly created object.
  40196. * Override this method to add some logic when your objects are created.
  40197. *
  40198. * @example
  40199. *
  40200. * var MyType = CryptoJS.lib.Base.extend({
  40201. * init: function () {
  40202. * // ...
  40203. * }
  40204. * });
  40205. */
  40206. init: function() {
  40207. },
  40208. /**
  40209. * Copies properties into this object.
  40210. *
  40211. * @param {Object} properties The properties to mix in.
  40212. *
  40213. * @example
  40214. *
  40215. * MyType.mixIn({
  40216. * field: 'value'
  40217. * });
  40218. */
  40219. mixIn: function(properties) {
  40220. for (var propertyName in properties) {
  40221. if (properties.hasOwnProperty(propertyName)) {
  40222. this[propertyName] = properties[propertyName];
  40223. }
  40224. }
  40225. if (properties.hasOwnProperty("toString")) {
  40226. this.toString = properties.toString;
  40227. }
  40228. },
  40229. /**
  40230. * Creates a copy of this object.
  40231. *
  40232. * @return {Object} The clone.
  40233. *
  40234. * @example
  40235. *
  40236. * var clone = instance.clone();
  40237. */
  40238. clone: function() {
  40239. return this.init.prototype.extend(this);
  40240. }
  40241. };
  40242. }();
  40243. var WordArray = C_lib.WordArray = Base.extend({
  40244. /**
  40245. * Initializes a newly created word array.
  40246. *
  40247. * @param {Array} words (Optional) An array of 32-bit words.
  40248. * @param {number} sigBytes (Optional) The number of significant bytes in the words.
  40249. *
  40250. * @example
  40251. *
  40252. * var wordArray = CryptoJS.lib.WordArray.create();
  40253. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
  40254. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
  40255. */
  40256. init: function(words, sigBytes) {
  40257. words = this.words = words || [];
  40258. if (sigBytes != undefined$1) {
  40259. this.sigBytes = sigBytes;
  40260. } else {
  40261. this.sigBytes = words.length * 4;
  40262. }
  40263. },
  40264. /**
  40265. * Converts this word array to a string.
  40266. *
  40267. * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
  40268. *
  40269. * @return {string} The stringified word array.
  40270. *
  40271. * @example
  40272. *
  40273. * var string = wordArray + '';
  40274. * var string = wordArray.toString();
  40275. * var string = wordArray.toString(CryptoJS.enc.Utf8);
  40276. */
  40277. toString: function(encoder) {
  40278. return (encoder || Hex2).stringify(this);
  40279. },
  40280. /**
  40281. * Concatenates a word array to this word array.
  40282. *
  40283. * @param {WordArray} wordArray The word array to append.
  40284. *
  40285. * @return {WordArray} This word array.
  40286. *
  40287. * @example
  40288. *
  40289. * wordArray1.concat(wordArray2);
  40290. */
  40291. concat: function(wordArray) {
  40292. var thisWords = this.words;
  40293. var thatWords = wordArray.words;
  40294. var thisSigBytes = this.sigBytes;
  40295. var thatSigBytes = wordArray.sigBytes;
  40296. this.clamp();
  40297. if (thisSigBytes % 4) {
  40298. for (var i2 = 0; i2 < thatSigBytes; i2++) {
  40299. var thatByte = thatWords[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
  40300. thisWords[thisSigBytes + i2 >>> 2] |= thatByte << 24 - (thisSigBytes + i2) % 4 * 8;
  40301. }
  40302. } else {
  40303. for (var j2 = 0; j2 < thatSigBytes; j2 += 4) {
  40304. thisWords[thisSigBytes + j2 >>> 2] = thatWords[j2 >>> 2];
  40305. }
  40306. }
  40307. this.sigBytes += thatSigBytes;
  40308. return this;
  40309. },
  40310. /**
  40311. * Removes insignificant bits.
  40312. *
  40313. * @example
  40314. *
  40315. * wordArray.clamp();
  40316. */
  40317. clamp: function() {
  40318. var words = this.words;
  40319. var sigBytes = this.sigBytes;
  40320. words[sigBytes >>> 2] &= 4294967295 << 32 - sigBytes % 4 * 8;
  40321. words.length = Math2.ceil(sigBytes / 4);
  40322. },
  40323. /**
  40324. * Creates a copy of this word array.
  40325. *
  40326. * @return {WordArray} The clone.
  40327. *
  40328. * @example
  40329. *
  40330. * var clone = wordArray.clone();
  40331. */
  40332. clone: function() {
  40333. var clone2 = Base.clone.call(this);
  40334. clone2.words = this.words.slice(0);
  40335. return clone2;
  40336. },
  40337. /**
  40338. * Creates a word array filled with random bytes.
  40339. *
  40340. * @param {number} nBytes The number of random bytes to generate.
  40341. *
  40342. * @return {WordArray} The random word array.
  40343. *
  40344. * @static
  40345. *
  40346. * @example
  40347. *
  40348. * var wordArray = CryptoJS.lib.WordArray.random(16);
  40349. */
  40350. random: function(nBytes) {
  40351. var words = [];
  40352. for (var i2 = 0; i2 < nBytes; i2 += 4) {
  40353. words.push(cryptoSecureRandomInt());
  40354. }
  40355. return new WordArray.init(words, nBytes);
  40356. }
  40357. });
  40358. var C_enc = C2.enc = {};
  40359. var Hex2 = C_enc.Hex = {
  40360. /**
  40361. * Converts a word array to a hex string.
  40362. *
  40363. * @param {WordArray} wordArray The word array.
  40364. *
  40365. * @return {string} The hex string.
  40366. *
  40367. * @static
  40368. *
  40369. * @example
  40370. *
  40371. * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
  40372. */
  40373. stringify: function(wordArray) {
  40374. var words = wordArray.words;
  40375. var sigBytes = wordArray.sigBytes;
  40376. var hexChars = [];
  40377. for (var i2 = 0; i2 < sigBytes; i2++) {
  40378. var bite = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
  40379. hexChars.push((bite >>> 4).toString(16));
  40380. hexChars.push((bite & 15).toString(16));
  40381. }
  40382. return hexChars.join("");
  40383. },
  40384. /**
  40385. * Converts a hex string to a word array.
  40386. *
  40387. * @param {string} hexStr The hex string.
  40388. *
  40389. * @return {WordArray} The word array.
  40390. *
  40391. * @static
  40392. *
  40393. * @example
  40394. *
  40395. * var wordArray = CryptoJS.enc.Hex.parse(hexString);
  40396. */
  40397. parse: function(hexStr) {
  40398. var hexStrLength = hexStr.length;
  40399. var words = [];
  40400. for (var i2 = 0; i2 < hexStrLength; i2 += 2) {
  40401. words[i2 >>> 3] |= parseInt(hexStr.substr(i2, 2), 16) << 24 - i2 % 8 * 4;
  40402. }
  40403. return new WordArray.init(words, hexStrLength / 2);
  40404. }
  40405. };
  40406. var Latin1 = C_enc.Latin1 = {
  40407. /**
  40408. * Converts a word array to a Latin1 string.
  40409. *
  40410. * @param {WordArray} wordArray The word array.
  40411. *
  40412. * @return {string} The Latin1 string.
  40413. *
  40414. * @static
  40415. *
  40416. * @example
  40417. *
  40418. * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
  40419. */
  40420. stringify: function(wordArray) {
  40421. var words = wordArray.words;
  40422. var sigBytes = wordArray.sigBytes;
  40423. var latin1Chars = [];
  40424. for (var i2 = 0; i2 < sigBytes; i2++) {
  40425. var bite = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
  40426. latin1Chars.push(String.fromCharCode(bite));
  40427. }
  40428. return latin1Chars.join("");
  40429. },
  40430. /**
  40431. * Converts a Latin1 string to a word array.
  40432. *
  40433. * @param {string} latin1Str The Latin1 string.
  40434. *
  40435. * @return {WordArray} The word array.
  40436. *
  40437. * @static
  40438. *
  40439. * @example
  40440. *
  40441. * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
  40442. */
  40443. parse: function(latin1Str) {
  40444. var latin1StrLength = latin1Str.length;
  40445. var words = [];
  40446. for (var i2 = 0; i2 < latin1StrLength; i2++) {
  40447. words[i2 >>> 2] |= (latin1Str.charCodeAt(i2) & 255) << 24 - i2 % 4 * 8;
  40448. }
  40449. return new WordArray.init(words, latin1StrLength);
  40450. }
  40451. };
  40452. var Utf8 = C_enc.Utf8 = {
  40453. /**
  40454. * Converts a word array to a UTF-8 string.
  40455. *
  40456. * @param {WordArray} wordArray The word array.
  40457. *
  40458. * @return {string} The UTF-8 string.
  40459. *
  40460. * @static
  40461. *
  40462. * @example
  40463. *
  40464. * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
  40465. */
  40466. stringify: function(wordArray) {
  40467. try {
  40468. return decodeURIComponent(escape(Latin1.stringify(wordArray)));
  40469. } catch (e2) {
  40470. throw new Error("Malformed UTF-8 data");
  40471. }
  40472. },
  40473. /**
  40474. * Converts a UTF-8 string to a word array.
  40475. *
  40476. * @param {string} utf8Str The UTF-8 string.
  40477. *
  40478. * @return {WordArray} The word array.
  40479. *
  40480. * @static
  40481. *
  40482. * @example
  40483. *
  40484. * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
  40485. */
  40486. parse: function(utf8Str) {
  40487. return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
  40488. }
  40489. };
  40490. var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
  40491. /**
  40492. * Resets this block algorithm's data buffer to its initial state.
  40493. *
  40494. * @example
  40495. *
  40496. * bufferedBlockAlgorithm.reset();
  40497. */
  40498. reset: function() {
  40499. this._data = new WordArray.init();
  40500. this._nDataBytes = 0;
  40501. },
  40502. /**
  40503. * Adds new data to this block algorithm's buffer.
  40504. *
  40505. * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
  40506. *
  40507. * @example
  40508. *
  40509. * bufferedBlockAlgorithm._append('data');
  40510. * bufferedBlockAlgorithm._append(wordArray);
  40511. */
  40512. _append: function(data) {
  40513. if (typeof data == "string") {
  40514. data = Utf8.parse(data);
  40515. }
  40516. this._data.concat(data);
  40517. this._nDataBytes += data.sigBytes;
  40518. },
  40519. /**
  40520. * Processes available data blocks.
  40521. *
  40522. * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
  40523. *
  40524. * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
  40525. *
  40526. * @return {WordArray} The processed data.
  40527. *
  40528. * @example
  40529. *
  40530. * var processedData = bufferedBlockAlgorithm._process();
  40531. * var processedData = bufferedBlockAlgorithm._process(!!'flush');
  40532. */
  40533. _process: function(doFlush) {
  40534. var processedWords;
  40535. var data = this._data;
  40536. var dataWords = data.words;
  40537. var dataSigBytes = data.sigBytes;
  40538. var blockSize = this.blockSize;
  40539. var blockSizeBytes = blockSize * 4;
  40540. var nBlocksReady = dataSigBytes / blockSizeBytes;
  40541. if (doFlush) {
  40542. nBlocksReady = Math2.ceil(nBlocksReady);
  40543. } else {
  40544. nBlocksReady = Math2.max((nBlocksReady | 0) - this._minBufferSize, 0);
  40545. }
  40546. var nWordsReady = nBlocksReady * blockSize;
  40547. var nBytesReady = Math2.min(nWordsReady * 4, dataSigBytes);
  40548. if (nWordsReady) {
  40549. for (var offset = 0; offset < nWordsReady; offset += blockSize) {
  40550. this._doProcessBlock(dataWords, offset);
  40551. }
  40552. processedWords = dataWords.splice(0, nWordsReady);
  40553. data.sigBytes -= nBytesReady;
  40554. }
  40555. return new WordArray.init(processedWords, nBytesReady);
  40556. },
  40557. /**
  40558. * Creates a copy of this object.
  40559. *
  40560. * @return {Object} The clone.
  40561. *
  40562. * @example
  40563. *
  40564. * var clone = bufferedBlockAlgorithm.clone();
  40565. */
  40566. clone: function() {
  40567. var clone2 = Base.clone.call(this);
  40568. clone2._data = this._data.clone();
  40569. return clone2;
  40570. },
  40571. _minBufferSize: 0
  40572. });
  40573. C_lib.Hasher = BufferedBlockAlgorithm.extend({
  40574. /**
  40575. * Configuration options.
  40576. */
  40577. cfg: Base.extend(),
  40578. /**
  40579. * Initializes a newly created hasher.
  40580. *
  40581. * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
  40582. *
  40583. * @example
  40584. *
  40585. * var hasher = CryptoJS.algo.SHA256.create();
  40586. */
  40587. init: function(cfg) {
  40588. this.cfg = this.cfg.extend(cfg);
  40589. this.reset();
  40590. },
  40591. /**
  40592. * Resets this hasher to its initial state.
  40593. *
  40594. * @example
  40595. *
  40596. * hasher.reset();
  40597. */
  40598. reset: function() {
  40599. BufferedBlockAlgorithm.reset.call(this);
  40600. this._doReset();
  40601. },
  40602. /**
  40603. * Updates this hasher with a message.
  40604. *
  40605. * @param {WordArray|string} messageUpdate The message to append.
  40606. *
  40607. * @return {Hasher} This hasher.
  40608. *
  40609. * @example
  40610. *
  40611. * hasher.update('message');
  40612. * hasher.update(wordArray);
  40613. */
  40614. update: function(messageUpdate) {
  40615. this._append(messageUpdate);
  40616. this._process();
  40617. return this;
  40618. },
  40619. /**
  40620. * Finalizes the hash computation.
  40621. * Note that the finalize operation is effectively a destructive, read-once operation.
  40622. *
  40623. * @param {WordArray|string} messageUpdate (Optional) A final message update.
  40624. *
  40625. * @return {WordArray} The hash.
  40626. *
  40627. * @example
  40628. *
  40629. * var hash = hasher.finalize();
  40630. * var hash = hasher.finalize('message');
  40631. * var hash = hasher.finalize(wordArray);
  40632. */
  40633. finalize: function(messageUpdate) {
  40634. if (messageUpdate) {
  40635. this._append(messageUpdate);
  40636. }
  40637. var hash2 = this._doFinalize();
  40638. return hash2;
  40639. },
  40640. blockSize: 512 / 32,
  40641. /**
  40642. * Creates a shortcut function to a hasher's object interface.
  40643. *
  40644. * @param {Hasher} hasher The hasher to create a helper for.
  40645. *
  40646. * @return {Function} The shortcut function.
  40647. *
  40648. * @static
  40649. *
  40650. * @example
  40651. *
  40652. * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
  40653. */
  40654. _createHelper: function(hasher) {
  40655. return function(message, cfg) {
  40656. return new hasher.init(cfg).finalize(message);
  40657. };
  40658. },
  40659. /**
  40660. * Creates a shortcut function to the HMAC's object interface.
  40661. *
  40662. * @param {Hasher} hasher The hasher to use in this HMAC helper.
  40663. *
  40664. * @return {Function} The shortcut function.
  40665. *
  40666. * @static
  40667. *
  40668. * @example
  40669. *
  40670. * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
  40671. */
  40672. _createHmacHelper: function(hasher) {
  40673. return function(message, key) {
  40674. return new C_algo.HMAC.init(hasher, key).finalize(message);
  40675. };
  40676. }
  40677. });
  40678. var C_algo = C2.algo = {};
  40679. return C2;
  40680. }(Math);
  40681. return CryptoJS2;
  40682. });
  40683. })(core);
  40684. return core.exports;
  40685. }
  40686. var x64Core = { exports: {} };
  40687. var hasRequiredX64Core;
  40688. function requireX64Core() {
  40689. if (hasRequiredX64Core)
  40690. return x64Core.exports;
  40691. hasRequiredX64Core = 1;
  40692. (function(module2, exports2) {
  40693. (function(root, factory) {
  40694. {
  40695. module2.exports = factory(requireCore());
  40696. }
  40697. })(commonjsGlobal, function(CryptoJS2) {
  40698. (function(undefined$1) {
  40699. var C2 = CryptoJS2;
  40700. var C_lib = C2.lib;
  40701. var Base = C_lib.Base;
  40702. var X32WordArray = C_lib.WordArray;
  40703. var C_x64 = C2.x64 = {};
  40704. C_x64.Word = Base.extend({
  40705. /**
  40706. * Initializes a newly created 64-bit word.
  40707. *
  40708. * @param {number} high The high 32 bits.
  40709. * @param {number} low The low 32 bits.
  40710. *
  40711. * @example
  40712. *
  40713. * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
  40714. */
  40715. init: function(high, low) {
  40716. this.high = high;
  40717. this.low = low;
  40718. }
  40719. /**
  40720. * Bitwise NOTs this word.
  40721. *
  40722. * @return {X64Word} A new x64-Word object after negating.
  40723. *
  40724. * @example
  40725. *
  40726. * var negated = x64Word.not();
  40727. */
  40728. // not: function () {
  40729. // var high = ~this.high;
  40730. // var low = ~this.low;
  40731. // return X64Word.create(high, low);
  40732. // },
  40733. /**
  40734. * Bitwise ANDs this word with the passed word.
  40735. *
  40736. * @param {X64Word} word The x64-Word to AND with this word.
  40737. *
  40738. * @return {X64Word} A new x64-Word object after ANDing.
  40739. *
  40740. * @example
  40741. *
  40742. * var anded = x64Word.and(anotherX64Word);
  40743. */
  40744. // and: function (word) {
  40745. // var high = this.high & word.high;
  40746. // var low = this.low & word.low;
  40747. // return X64Word.create(high, low);
  40748. // },
  40749. /**
  40750. * Bitwise ORs this word with the passed word.
  40751. *
  40752. * @param {X64Word} word The x64-Word to OR with this word.
  40753. *
  40754. * @return {X64Word} A new x64-Word object after ORing.
  40755. *
  40756. * @example
  40757. *
  40758. * var ored = x64Word.or(anotherX64Word);
  40759. */
  40760. // or: function (word) {
  40761. // var high = this.high | word.high;
  40762. // var low = this.low | word.low;
  40763. // return X64Word.create(high, low);
  40764. // },
  40765. /**
  40766. * Bitwise XORs this word with the passed word.
  40767. *
  40768. * @param {X64Word} word The x64-Word to XOR with this word.
  40769. *
  40770. * @return {X64Word} A new x64-Word object after XORing.
  40771. *
  40772. * @example
  40773. *
  40774. * var xored = x64Word.xor(anotherX64Word);
  40775. */
  40776. // xor: function (word) {
  40777. // var high = this.high ^ word.high;
  40778. // var low = this.low ^ word.low;
  40779. // return X64Word.create(high, low);
  40780. // },
  40781. /**
  40782. * Shifts this word n bits to the left.
  40783. *
  40784. * @param {number} n The number of bits to shift.
  40785. *
  40786. * @return {X64Word} A new x64-Word object after shifting.
  40787. *
  40788. * @example
  40789. *
  40790. * var shifted = x64Word.shiftL(25);
  40791. */
  40792. // shiftL: function (n) {
  40793. // if (n < 32) {
  40794. // var high = (this.high << n) | (this.low >>> (32 - n));
  40795. // var low = this.low << n;
  40796. // } else {
  40797. // var high = this.low << (n - 32);
  40798. // var low = 0;
  40799. // }
  40800. // return X64Word.create(high, low);
  40801. // },
  40802. /**
  40803. * Shifts this word n bits to the right.
  40804. *
  40805. * @param {number} n The number of bits to shift.
  40806. *
  40807. * @return {X64Word} A new x64-Word object after shifting.
  40808. *
  40809. * @example
  40810. *
  40811. * var shifted = x64Word.shiftR(7);
  40812. */
  40813. // shiftR: function (n) {
  40814. // if (n < 32) {
  40815. // var low = (this.low >>> n) | (this.high << (32 - n));
  40816. // var high = this.high >>> n;
  40817. // } else {
  40818. // var low = this.high >>> (n - 32);
  40819. // var high = 0;
  40820. // }
  40821. // return X64Word.create(high, low);
  40822. // },
  40823. /**
  40824. * Rotates this word n bits to the left.
  40825. *
  40826. * @param {number} n The number of bits to rotate.
  40827. *
  40828. * @return {X64Word} A new x64-Word object after rotating.
  40829. *
  40830. * @example
  40831. *
  40832. * var rotated = x64Word.rotL(25);
  40833. */
  40834. // rotL: function (n) {
  40835. // return this.shiftL(n).or(this.shiftR(64 - n));
  40836. // },
  40837. /**
  40838. * Rotates this word n bits to the right.
  40839. *
  40840. * @param {number} n The number of bits to rotate.
  40841. *
  40842. * @return {X64Word} A new x64-Word object after rotating.
  40843. *
  40844. * @example
  40845. *
  40846. * var rotated = x64Word.rotR(7);
  40847. */
  40848. // rotR: function (n) {
  40849. // return this.shiftR(n).or(this.shiftL(64 - n));
  40850. // },
  40851. /**
  40852. * Adds this word with the passed word.
  40853. *
  40854. * @param {X64Word} word The x64-Word to add with this word.
  40855. *
  40856. * @return {X64Word} A new x64-Word object after adding.
  40857. *
  40858. * @example
  40859. *
  40860. * var added = x64Word.add(anotherX64Word);
  40861. */
  40862. // add: function (word) {
  40863. // var low = (this.low + word.low) | 0;
  40864. // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
  40865. // var high = (this.high + word.high + carry) | 0;
  40866. // return X64Word.create(high, low);
  40867. // }
  40868. });
  40869. C_x64.WordArray = Base.extend({
  40870. /**
  40871. * Initializes a newly created word array.
  40872. *
  40873. * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
  40874. * @param {number} sigBytes (Optional) The number of significant bytes in the words.
  40875. *
  40876. * @example
  40877. *
  40878. * var wordArray = CryptoJS.x64.WordArray.create();
  40879. *
  40880. * var wordArray = CryptoJS.x64.WordArray.create([
  40881. * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
  40882. * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
  40883. * ]);
  40884. *
  40885. * var wordArray = CryptoJS.x64.WordArray.create([
  40886. * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
  40887. * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
  40888. * ], 10);
  40889. */
  40890. init: function(words, sigBytes) {
  40891. words = this.words = words || [];
  40892. if (sigBytes != undefined$1) {
  40893. this.sigBytes = sigBytes;
  40894. } else {
  40895. this.sigBytes = words.length * 8;
  40896. }
  40897. },
  40898. /**
  40899. * Converts this 64-bit word array to a 32-bit word array.
  40900. *
  40901. * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
  40902. *
  40903. * @example
  40904. *
  40905. * var x32WordArray = x64WordArray.toX32();
  40906. */
  40907. toX32: function() {
  40908. var x64Words = this.words;
  40909. var x64WordsLength = x64Words.length;
  40910. var x32Words = [];
  40911. for (var i2 = 0; i2 < x64WordsLength; i2++) {
  40912. var x64Word = x64Words[i2];
  40913. x32Words.push(x64Word.high);
  40914. x32Words.push(x64Word.low);
  40915. }
  40916. return X32WordArray.create(x32Words, this.sigBytes);
  40917. },
  40918. /**
  40919. * Creates a copy of this word array.
  40920. *
  40921. * @return {X64WordArray} The clone.
  40922. *
  40923. * @example
  40924. *
  40925. * var clone = x64WordArray.clone();
  40926. */
  40927. clone: function() {
  40928. var clone2 = Base.clone.call(this);
  40929. var words = clone2.words = this.words.slice(0);
  40930. var wordsLength = words.length;
  40931. for (var i2 = 0; i2 < wordsLength; i2++) {
  40932. words[i2] = words[i2].clone();
  40933. }
  40934. return clone2;
  40935. }
  40936. });
  40937. })();
  40938. return CryptoJS2;
  40939. });
  40940. })(x64Core);
  40941. return x64Core.exports;
  40942. }
  40943. var libTypedarrays = { exports: {} };
  40944. var hasRequiredLibTypedarrays;
  40945. function requireLibTypedarrays() {
  40946. if (hasRequiredLibTypedarrays)
  40947. return libTypedarrays.exports;
  40948. hasRequiredLibTypedarrays = 1;
  40949. (function(module2, exports2) {
  40950. (function(root, factory) {
  40951. {
  40952. module2.exports = factory(requireCore());
  40953. }
  40954. })(commonjsGlobal, function(CryptoJS2) {
  40955. (function() {
  40956. if (typeof ArrayBuffer != "function") {
  40957. return;
  40958. }
  40959. var C2 = CryptoJS2;
  40960. var C_lib = C2.lib;
  40961. var WordArray = C_lib.WordArray;
  40962. var superInit = WordArray.init;
  40963. var subInit = WordArray.init = function(typedArray) {
  40964. if (typedArray instanceof ArrayBuffer) {
  40965. typedArray = new Uint8Array(typedArray);
  40966. }
  40967. if (typedArray instanceof Int8Array || typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array) {
  40968. typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
  40969. }
  40970. if (typedArray instanceof Uint8Array) {
  40971. var typedArrayByteLength = typedArray.byteLength;
  40972. var words = [];
  40973. for (var i2 = 0; i2 < typedArrayByteLength; i2++) {
  40974. words[i2 >>> 2] |= typedArray[i2] << 24 - i2 % 4 * 8;
  40975. }
  40976. superInit.call(this, words, typedArrayByteLength);
  40977. } else {
  40978. superInit.apply(this, arguments);
  40979. }
  40980. };
  40981. subInit.prototype = WordArray;
  40982. })();
  40983. return CryptoJS2.lib.WordArray;
  40984. });
  40985. })(libTypedarrays);
  40986. return libTypedarrays.exports;
  40987. }
  40988. var encUtf16 = { exports: {} };
  40989. var hasRequiredEncUtf16;
  40990. function requireEncUtf16() {
  40991. if (hasRequiredEncUtf16)
  40992. return encUtf16.exports;
  40993. hasRequiredEncUtf16 = 1;
  40994. (function(module2, exports2) {
  40995. (function(root, factory) {
  40996. {
  40997. module2.exports = factory(requireCore());
  40998. }
  40999. })(commonjsGlobal, function(CryptoJS2) {
  41000. (function() {
  41001. var C2 = CryptoJS2;
  41002. var C_lib = C2.lib;
  41003. var WordArray = C_lib.WordArray;
  41004. var C_enc = C2.enc;
  41005. C_enc.Utf16 = C_enc.Utf16BE = {
  41006. /**
  41007. * Converts a word array to a UTF-16 BE string.
  41008. *
  41009. * @param {WordArray} wordArray The word array.
  41010. *
  41011. * @return {string} The UTF-16 BE string.
  41012. *
  41013. * @static
  41014. *
  41015. * @example
  41016. *
  41017. * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
  41018. */
  41019. stringify: function(wordArray) {
  41020. var words = wordArray.words;
  41021. var sigBytes = wordArray.sigBytes;
  41022. var utf16Chars = [];
  41023. for (var i2 = 0; i2 < sigBytes; i2 += 2) {
  41024. var codePoint = words[i2 >>> 2] >>> 16 - i2 % 4 * 8 & 65535;
  41025. utf16Chars.push(String.fromCharCode(codePoint));
  41026. }
  41027. return utf16Chars.join("");
  41028. },
  41029. /**
  41030. * Converts a UTF-16 BE string to a word array.
  41031. *
  41032. * @param {string} utf16Str The UTF-16 BE string.
  41033. *
  41034. * @return {WordArray} The word array.
  41035. *
  41036. * @static
  41037. *
  41038. * @example
  41039. *
  41040. * var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
  41041. */
  41042. parse: function(utf16Str) {
  41043. var utf16StrLength = utf16Str.length;
  41044. var words = [];
  41045. for (var i2 = 0; i2 < utf16StrLength; i2++) {
  41046. words[i2 >>> 1] |= utf16Str.charCodeAt(i2) << 16 - i2 % 2 * 16;
  41047. }
  41048. return WordArray.create(words, utf16StrLength * 2);
  41049. }
  41050. };
  41051. C_enc.Utf16LE = {
  41052. /**
  41053. * Converts a word array to a UTF-16 LE string.
  41054. *
  41055. * @param {WordArray} wordArray The word array.
  41056. *
  41057. * @return {string} The UTF-16 LE string.
  41058. *
  41059. * @static
  41060. *
  41061. * @example
  41062. *
  41063. * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
  41064. */
  41065. stringify: function(wordArray) {
  41066. var words = wordArray.words;
  41067. var sigBytes = wordArray.sigBytes;
  41068. var utf16Chars = [];
  41069. for (var i2 = 0; i2 < sigBytes; i2 += 2) {
  41070. var codePoint = swapEndian(words[i2 >>> 2] >>> 16 - i2 % 4 * 8 & 65535);
  41071. utf16Chars.push(String.fromCharCode(codePoint));
  41072. }
  41073. return utf16Chars.join("");
  41074. },
  41075. /**
  41076. * Converts a UTF-16 LE string to a word array.
  41077. *
  41078. * @param {string} utf16Str The UTF-16 LE string.
  41079. *
  41080. * @return {WordArray} The word array.
  41081. *
  41082. * @static
  41083. *
  41084. * @example
  41085. *
  41086. * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
  41087. */
  41088. parse: function(utf16Str) {
  41089. var utf16StrLength = utf16Str.length;
  41090. var words = [];
  41091. for (var i2 = 0; i2 < utf16StrLength; i2++) {
  41092. words[i2 >>> 1] |= swapEndian(utf16Str.charCodeAt(i2) << 16 - i2 % 2 * 16);
  41093. }
  41094. return WordArray.create(words, utf16StrLength * 2);
  41095. }
  41096. };
  41097. function swapEndian(word) {
  41098. return word << 8 & 4278255360 | word >>> 8 & 16711935;
  41099. }
  41100. })();
  41101. return CryptoJS2.enc.Utf16;
  41102. });
  41103. })(encUtf16);
  41104. return encUtf16.exports;
  41105. }
  41106. var encBase64 = { exports: {} };
  41107. var hasRequiredEncBase64;
  41108. function requireEncBase64() {
  41109. if (hasRequiredEncBase64)
  41110. return encBase64.exports;
  41111. hasRequiredEncBase64 = 1;
  41112. (function(module2, exports2) {
  41113. (function(root, factory) {
  41114. {
  41115. module2.exports = factory(requireCore());
  41116. }
  41117. })(commonjsGlobal, function(CryptoJS2) {
  41118. (function() {
  41119. var C2 = CryptoJS2;
  41120. var C_lib = C2.lib;
  41121. var WordArray = C_lib.WordArray;
  41122. var C_enc = C2.enc;
  41123. C_enc.Base64 = {
  41124. /**
  41125. * Converts a word array to a Base64 string.
  41126. *
  41127. * @param {WordArray} wordArray The word array.
  41128. *
  41129. * @return {string} The Base64 string.
  41130. *
  41131. * @static
  41132. *
  41133. * @example
  41134. *
  41135. * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
  41136. */
  41137. stringify: function(wordArray) {
  41138. var words = wordArray.words;
  41139. var sigBytes = wordArray.sigBytes;
  41140. var map = this._map;
  41141. wordArray.clamp();
  41142. var base64Chars = [];
  41143. for (var i2 = 0; i2 < sigBytes; i2 += 3) {
  41144. var byte1 = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
  41145. var byte2 = words[i2 + 1 >>> 2] >>> 24 - (i2 + 1) % 4 * 8 & 255;
  41146. var byte3 = words[i2 + 2 >>> 2] >>> 24 - (i2 + 2) % 4 * 8 & 255;
  41147. var triplet = byte1 << 16 | byte2 << 8 | byte3;
  41148. for (var j2 = 0; j2 < 4 && i2 + j2 * 0.75 < sigBytes; j2++) {
  41149. base64Chars.push(map.charAt(triplet >>> 6 * (3 - j2) & 63));
  41150. }
  41151. }
  41152. var paddingChar = map.charAt(64);
  41153. if (paddingChar) {
  41154. while (base64Chars.length % 4) {
  41155. base64Chars.push(paddingChar);
  41156. }
  41157. }
  41158. return base64Chars.join("");
  41159. },
  41160. /**
  41161. * Converts a Base64 string to a word array.
  41162. *
  41163. * @param {string} base64Str The Base64 string.
  41164. *
  41165. * @return {WordArray} The word array.
  41166. *
  41167. * @static
  41168. *
  41169. * @example
  41170. *
  41171. * var wordArray = CryptoJS.enc.Base64.parse(base64String);
  41172. */
  41173. parse: function(base64Str) {
  41174. var base64StrLength = base64Str.length;
  41175. var map = this._map;
  41176. var reverseMap = this._reverseMap;
  41177. if (!reverseMap) {
  41178. reverseMap = this._reverseMap = [];
  41179. for (var j2 = 0; j2 < map.length; j2++) {
  41180. reverseMap[map.charCodeAt(j2)] = j2;
  41181. }
  41182. }
  41183. var paddingChar = map.charAt(64);
  41184. if (paddingChar) {
  41185. var paddingIndex = base64Str.indexOf(paddingChar);
  41186. if (paddingIndex !== -1) {
  41187. base64StrLength = paddingIndex;
  41188. }
  41189. }
  41190. return parseLoop(base64Str, base64StrLength, reverseMap);
  41191. },
  41192. _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
  41193. };
  41194. function parseLoop(base64Str, base64StrLength, reverseMap) {
  41195. var words = [];
  41196. var nBytes = 0;
  41197. for (var i2 = 0; i2 < base64StrLength; i2++) {
  41198. if (i2 % 4) {
  41199. var bits1 = reverseMap[base64Str.charCodeAt(i2 - 1)] << i2 % 4 * 2;
  41200. var bits2 = reverseMap[base64Str.charCodeAt(i2)] >>> 6 - i2 % 4 * 2;
  41201. var bitsCombined = bits1 | bits2;
  41202. words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8;
  41203. nBytes++;
  41204. }
  41205. }
  41206. return WordArray.create(words, nBytes);
  41207. }
  41208. })();
  41209. return CryptoJS2.enc.Base64;
  41210. });
  41211. })(encBase64);
  41212. return encBase64.exports;
  41213. }
  41214. var encBase64url = { exports: {} };
  41215. var hasRequiredEncBase64url;
  41216. function requireEncBase64url() {
  41217. if (hasRequiredEncBase64url)
  41218. return encBase64url.exports;
  41219. hasRequiredEncBase64url = 1;
  41220. (function(module2, exports2) {
  41221. (function(root, factory) {
  41222. {
  41223. module2.exports = factory(requireCore());
  41224. }
  41225. })(commonjsGlobal, function(CryptoJS2) {
  41226. (function() {
  41227. var C2 = CryptoJS2;
  41228. var C_lib = C2.lib;
  41229. var WordArray = C_lib.WordArray;
  41230. var C_enc = C2.enc;
  41231. C_enc.Base64url = {
  41232. /**
  41233. * Converts a word array to a Base64url string.
  41234. *
  41235. * @param {WordArray} wordArray The word array.
  41236. *
  41237. * @param {boolean} urlSafe Whether to use url safe
  41238. *
  41239. * @return {string} The Base64url string.
  41240. *
  41241. * @static
  41242. *
  41243. * @example
  41244. *
  41245. * var base64String = CryptoJS.enc.Base64url.stringify(wordArray);
  41246. */
  41247. stringify: function(wordArray, urlSafe) {
  41248. if (urlSafe === void 0) {
  41249. urlSafe = true;
  41250. }
  41251. var words = wordArray.words;
  41252. var sigBytes = wordArray.sigBytes;
  41253. var map = urlSafe ? this._safe_map : this._map;
  41254. wordArray.clamp();
  41255. var base64Chars = [];
  41256. for (var i2 = 0; i2 < sigBytes; i2 += 3) {
  41257. var byte1 = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
  41258. var byte2 = words[i2 + 1 >>> 2] >>> 24 - (i2 + 1) % 4 * 8 & 255;
  41259. var byte3 = words[i2 + 2 >>> 2] >>> 24 - (i2 + 2) % 4 * 8 & 255;
  41260. var triplet = byte1 << 16 | byte2 << 8 | byte3;
  41261. for (var j2 = 0; j2 < 4 && i2 + j2 * 0.75 < sigBytes; j2++) {
  41262. base64Chars.push(map.charAt(triplet >>> 6 * (3 - j2) & 63));
  41263. }
  41264. }
  41265. var paddingChar = map.charAt(64);
  41266. if (paddingChar) {
  41267. while (base64Chars.length % 4) {
  41268. base64Chars.push(paddingChar);
  41269. }
  41270. }
  41271. return base64Chars.join("");
  41272. },
  41273. /**
  41274. * Converts a Base64url string to a word array.
  41275. *
  41276. * @param {string} base64Str The Base64url string.
  41277. *
  41278. * @param {boolean} urlSafe Whether to use url safe
  41279. *
  41280. * @return {WordArray} The word array.
  41281. *
  41282. * @static
  41283. *
  41284. * @example
  41285. *
  41286. * var wordArray = CryptoJS.enc.Base64url.parse(base64String);
  41287. */
  41288. parse: function(base64Str, urlSafe) {
  41289. if (urlSafe === void 0) {
  41290. urlSafe = true;
  41291. }
  41292. var base64StrLength = base64Str.length;
  41293. var map = urlSafe ? this._safe_map : this._map;
  41294. var reverseMap = this._reverseMap;
  41295. if (!reverseMap) {
  41296. reverseMap = this._reverseMap = [];
  41297. for (var j2 = 0; j2 < map.length; j2++) {
  41298. reverseMap[map.charCodeAt(j2)] = j2;
  41299. }
  41300. }
  41301. var paddingChar = map.charAt(64);
  41302. if (paddingChar) {
  41303. var paddingIndex = base64Str.indexOf(paddingChar);
  41304. if (paddingIndex !== -1) {
  41305. base64StrLength = paddingIndex;
  41306. }
  41307. }
  41308. return parseLoop(base64Str, base64StrLength, reverseMap);
  41309. },
  41310. _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  41311. _safe_map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
  41312. };
  41313. function parseLoop(base64Str, base64StrLength, reverseMap) {
  41314. var words = [];
  41315. var nBytes = 0;
  41316. for (var i2 = 0; i2 < base64StrLength; i2++) {
  41317. if (i2 % 4) {
  41318. var bits1 = reverseMap[base64Str.charCodeAt(i2 - 1)] << i2 % 4 * 2;
  41319. var bits2 = reverseMap[base64Str.charCodeAt(i2)] >>> 6 - i2 % 4 * 2;
  41320. var bitsCombined = bits1 | bits2;
  41321. words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8;
  41322. nBytes++;
  41323. }
  41324. }
  41325. return WordArray.create(words, nBytes);
  41326. }
  41327. })();
  41328. return CryptoJS2.enc.Base64url;
  41329. });
  41330. })(encBase64url);
  41331. return encBase64url.exports;
  41332. }
  41333. var md5 = { exports: {} };
  41334. var hasRequiredMd5;
  41335. function requireMd5() {
  41336. if (hasRequiredMd5)
  41337. return md5.exports;
  41338. hasRequiredMd5 = 1;
  41339. (function(module2, exports2) {
  41340. (function(root, factory) {
  41341. {
  41342. module2.exports = factory(requireCore());
  41343. }
  41344. })(commonjsGlobal, function(CryptoJS2) {
  41345. (function(Math2) {
  41346. var C2 = CryptoJS2;
  41347. var C_lib = C2.lib;
  41348. var WordArray = C_lib.WordArray;
  41349. var Hasher = C_lib.Hasher;
  41350. var C_algo = C2.algo;
  41351. var T2 = [];
  41352. (function() {
  41353. for (var i2 = 0; i2 < 64; i2++) {
  41354. T2[i2] = Math2.abs(Math2.sin(i2 + 1)) * 4294967296 | 0;
  41355. }
  41356. })();
  41357. var MD5 = C_algo.MD5 = Hasher.extend({
  41358. _doReset: function() {
  41359. this._hash = new WordArray.init([
  41360. 1732584193,
  41361. 4023233417,
  41362. 2562383102,
  41363. 271733878
  41364. ]);
  41365. },
  41366. _doProcessBlock: function(M2, offset) {
  41367. for (var i2 = 0; i2 < 16; i2++) {
  41368. var offset_i = offset + i2;
  41369. var M_offset_i = M2[offset_i];
  41370. M2[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 16711935 | (M_offset_i << 24 | M_offset_i >>> 8) & 4278255360;
  41371. }
  41372. var H2 = this._hash.words;
  41373. var M_offset_0 = M2[offset + 0];
  41374. var M_offset_1 = M2[offset + 1];
  41375. var M_offset_2 = M2[offset + 2];
  41376. var M_offset_3 = M2[offset + 3];
  41377. var M_offset_4 = M2[offset + 4];
  41378. var M_offset_5 = M2[offset + 5];
  41379. var M_offset_6 = M2[offset + 6];
  41380. var M_offset_7 = M2[offset + 7];
  41381. var M_offset_8 = M2[offset + 8];
  41382. var M_offset_9 = M2[offset + 9];
  41383. var M_offset_10 = M2[offset + 10];
  41384. var M_offset_11 = M2[offset + 11];
  41385. var M_offset_12 = M2[offset + 12];
  41386. var M_offset_13 = M2[offset + 13];
  41387. var M_offset_14 = M2[offset + 14];
  41388. var M_offset_15 = M2[offset + 15];
  41389. var a2 = H2[0];
  41390. var b2 = H2[1];
  41391. var c2 = H2[2];
  41392. var d2 = H2[3];
  41393. a2 = FF(a2, b2, c2, d2, M_offset_0, 7, T2[0]);
  41394. d2 = FF(d2, a2, b2, c2, M_offset_1, 12, T2[1]);
  41395. c2 = FF(c2, d2, a2, b2, M_offset_2, 17, T2[2]);
  41396. b2 = FF(b2, c2, d2, a2, M_offset_3, 22, T2[3]);
  41397. a2 = FF(a2, b2, c2, d2, M_offset_4, 7, T2[4]);
  41398. d2 = FF(d2, a2, b2, c2, M_offset_5, 12, T2[5]);
  41399. c2 = FF(c2, d2, a2, b2, M_offset_6, 17, T2[6]);
  41400. b2 = FF(b2, c2, d2, a2, M_offset_7, 22, T2[7]);
  41401. a2 = FF(a2, b2, c2, d2, M_offset_8, 7, T2[8]);
  41402. d2 = FF(d2, a2, b2, c2, M_offset_9, 12, T2[9]);
  41403. c2 = FF(c2, d2, a2, b2, M_offset_10, 17, T2[10]);
  41404. b2 = FF(b2, c2, d2, a2, M_offset_11, 22, T2[11]);
  41405. a2 = FF(a2, b2, c2, d2, M_offset_12, 7, T2[12]);
  41406. d2 = FF(d2, a2, b2, c2, M_offset_13, 12, T2[13]);
  41407. c2 = FF(c2, d2, a2, b2, M_offset_14, 17, T2[14]);
  41408. b2 = FF(b2, c2, d2, a2, M_offset_15, 22, T2[15]);
  41409. a2 = GG(a2, b2, c2, d2, M_offset_1, 5, T2[16]);
  41410. d2 = GG(d2, a2, b2, c2, M_offset_6, 9, T2[17]);
  41411. c2 = GG(c2, d2, a2, b2, M_offset_11, 14, T2[18]);
  41412. b2 = GG(b2, c2, d2, a2, M_offset_0, 20, T2[19]);
  41413. a2 = GG(a2, b2, c2, d2, M_offset_5, 5, T2[20]);
  41414. d2 = GG(d2, a2, b2, c2, M_offset_10, 9, T2[21]);
  41415. c2 = GG(c2, d2, a2, b2, M_offset_15, 14, T2[22]);
  41416. b2 = GG(b2, c2, d2, a2, M_offset_4, 20, T2[23]);
  41417. a2 = GG(a2, b2, c2, d2, M_offset_9, 5, T2[24]);
  41418. d2 = GG(d2, a2, b2, c2, M_offset_14, 9, T2[25]);
  41419. c2 = GG(c2, d2, a2, b2, M_offset_3, 14, T2[26]);
  41420. b2 = GG(b2, c2, d2, a2, M_offset_8, 20, T2[27]);
  41421. a2 = GG(a2, b2, c2, d2, M_offset_13, 5, T2[28]);
  41422. d2 = GG(d2, a2, b2, c2, M_offset_2, 9, T2[29]);
  41423. c2 = GG(c2, d2, a2, b2, M_offset_7, 14, T2[30]);
  41424. b2 = GG(b2, c2, d2, a2, M_offset_12, 20, T2[31]);
  41425. a2 = HH(a2, b2, c2, d2, M_offset_5, 4, T2[32]);
  41426. d2 = HH(d2, a2, b2, c2, M_offset_8, 11, T2[33]);
  41427. c2 = HH(c2, d2, a2, b2, M_offset_11, 16, T2[34]);
  41428. b2 = HH(b2, c2, d2, a2, M_offset_14, 23, T2[35]);
  41429. a2 = HH(a2, b2, c2, d2, M_offset_1, 4, T2[36]);
  41430. d2 = HH(d2, a2, b2, c2, M_offset_4, 11, T2[37]);
  41431. c2 = HH(c2, d2, a2, b2, M_offset_7, 16, T2[38]);
  41432. b2 = HH(b2, c2, d2, a2, M_offset_10, 23, T2[39]);
  41433. a2 = HH(a2, b2, c2, d2, M_offset_13, 4, T2[40]);
  41434. d2 = HH(d2, a2, b2, c2, M_offset_0, 11, T2[41]);
  41435. c2 = HH(c2, d2, a2, b2, M_offset_3, 16, T2[42]);
  41436. b2 = HH(b2, c2, d2, a2, M_offset_6, 23, T2[43]);
  41437. a2 = HH(a2, b2, c2, d2, M_offset_9, 4, T2[44]);
  41438. d2 = HH(d2, a2, b2, c2, M_offset_12, 11, T2[45]);
  41439. c2 = HH(c2, d2, a2, b2, M_offset_15, 16, T2[46]);
  41440. b2 = HH(b2, c2, d2, a2, M_offset_2, 23, T2[47]);
  41441. a2 = II(a2, b2, c2, d2, M_offset_0, 6, T2[48]);
  41442. d2 = II(d2, a2, b2, c2, M_offset_7, 10, T2[49]);
  41443. c2 = II(c2, d2, a2, b2, M_offset_14, 15, T2[50]);
  41444. b2 = II(b2, c2, d2, a2, M_offset_5, 21, T2[51]);
  41445. a2 = II(a2, b2, c2, d2, M_offset_12, 6, T2[52]);
  41446. d2 = II(d2, a2, b2, c2, M_offset_3, 10, T2[53]);
  41447. c2 = II(c2, d2, a2, b2, M_offset_10, 15, T2[54]);
  41448. b2 = II(b2, c2, d2, a2, M_offset_1, 21, T2[55]);
  41449. a2 = II(a2, b2, c2, d2, M_offset_8, 6, T2[56]);
  41450. d2 = II(d2, a2, b2, c2, M_offset_15, 10, T2[57]);
  41451. c2 = II(c2, d2, a2, b2, M_offset_6, 15, T2[58]);
  41452. b2 = II(b2, c2, d2, a2, M_offset_13, 21, T2[59]);
  41453. a2 = II(a2, b2, c2, d2, M_offset_4, 6, T2[60]);
  41454. d2 = II(d2, a2, b2, c2, M_offset_11, 10, T2[61]);
  41455. c2 = II(c2, d2, a2, b2, M_offset_2, 15, T2[62]);
  41456. b2 = II(b2, c2, d2, a2, M_offset_9, 21, T2[63]);
  41457. H2[0] = H2[0] + a2 | 0;
  41458. H2[1] = H2[1] + b2 | 0;
  41459. H2[2] = H2[2] + c2 | 0;
  41460. H2[3] = H2[3] + d2 | 0;
  41461. },
  41462. _doFinalize: function() {
  41463. var data = this._data;
  41464. var dataWords = data.words;
  41465. var nBitsTotal = this._nDataBytes * 8;
  41466. var nBitsLeft = data.sigBytes * 8;
  41467. dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  41468. var nBitsTotalH = Math2.floor(nBitsTotal / 4294967296);
  41469. var nBitsTotalL = nBitsTotal;
  41470. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = (nBitsTotalH << 8 | nBitsTotalH >>> 24) & 16711935 | (nBitsTotalH << 24 | nBitsTotalH >>> 8) & 4278255360;
  41471. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotalL << 8 | nBitsTotalL >>> 24) & 16711935 | (nBitsTotalL << 24 | nBitsTotalL >>> 8) & 4278255360;
  41472. data.sigBytes = (dataWords.length + 1) * 4;
  41473. this._process();
  41474. var hash2 = this._hash;
  41475. var H2 = hash2.words;
  41476. for (var i2 = 0; i2 < 4; i2++) {
  41477. var H_i = H2[i2];
  41478. H2[i2] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360;
  41479. }
  41480. return hash2;
  41481. },
  41482. clone: function() {
  41483. var clone2 = Hasher.clone.call(this);
  41484. clone2._hash = this._hash.clone();
  41485. return clone2;
  41486. }
  41487. });
  41488. function FF(a2, b2, c2, d2, x, s2, t2) {
  41489. var n2 = a2 + (b2 & c2 | ~b2 & d2) + x + t2;
  41490. return (n2 << s2 | n2 >>> 32 - s2) + b2;
  41491. }
  41492. function GG(a2, b2, c2, d2, x, s2, t2) {
  41493. var n2 = a2 + (b2 & d2 | c2 & ~d2) + x + t2;
  41494. return (n2 << s2 | n2 >>> 32 - s2) + b2;
  41495. }
  41496. function HH(a2, b2, c2, d2, x, s2, t2) {
  41497. var n2 = a2 + (b2 ^ c2 ^ d2) + x + t2;
  41498. return (n2 << s2 | n2 >>> 32 - s2) + b2;
  41499. }
  41500. function II(a2, b2, c2, d2, x, s2, t2) {
  41501. var n2 = a2 + (c2 ^ (b2 | ~d2)) + x + t2;
  41502. return (n2 << s2 | n2 >>> 32 - s2) + b2;
  41503. }
  41504. C2.MD5 = Hasher._createHelper(MD5);
  41505. C2.HmacMD5 = Hasher._createHmacHelper(MD5);
  41506. })(Math);
  41507. return CryptoJS2.MD5;
  41508. });
  41509. })(md5);
  41510. return md5.exports;
  41511. }
  41512. var sha1 = { exports: {} };
  41513. var hasRequiredSha1;
  41514. function requireSha1() {
  41515. if (hasRequiredSha1)
  41516. return sha1.exports;
  41517. hasRequiredSha1 = 1;
  41518. (function(module2, exports2) {
  41519. (function(root, factory) {
  41520. {
  41521. module2.exports = factory(requireCore());
  41522. }
  41523. })(commonjsGlobal, function(CryptoJS2) {
  41524. (function() {
  41525. var C2 = CryptoJS2;
  41526. var C_lib = C2.lib;
  41527. var WordArray = C_lib.WordArray;
  41528. var Hasher = C_lib.Hasher;
  41529. var C_algo = C2.algo;
  41530. var W2 = [];
  41531. var SHA1 = C_algo.SHA1 = Hasher.extend({
  41532. _doReset: function() {
  41533. this._hash = new WordArray.init([
  41534. 1732584193,
  41535. 4023233417,
  41536. 2562383102,
  41537. 271733878,
  41538. 3285377520
  41539. ]);
  41540. },
  41541. _doProcessBlock: function(M2, offset) {
  41542. var H2 = this._hash.words;
  41543. var a2 = H2[0];
  41544. var b2 = H2[1];
  41545. var c2 = H2[2];
  41546. var d2 = H2[3];
  41547. var e2 = H2[4];
  41548. for (var i2 = 0; i2 < 80; i2++) {
  41549. if (i2 < 16) {
  41550. W2[i2] = M2[offset + i2] | 0;
  41551. } else {
  41552. var n2 = W2[i2 - 3] ^ W2[i2 - 8] ^ W2[i2 - 14] ^ W2[i2 - 16];
  41553. W2[i2] = n2 << 1 | n2 >>> 31;
  41554. }
  41555. var t2 = (a2 << 5 | a2 >>> 27) + e2 + W2[i2];
  41556. if (i2 < 20) {
  41557. t2 += (b2 & c2 | ~b2 & d2) + 1518500249;
  41558. } else if (i2 < 40) {
  41559. t2 += (b2 ^ c2 ^ d2) + 1859775393;
  41560. } else if (i2 < 60) {
  41561. t2 += (b2 & c2 | b2 & d2 | c2 & d2) - 1894007588;
  41562. } else {
  41563. t2 += (b2 ^ c2 ^ d2) - 899497514;
  41564. }
  41565. e2 = d2;
  41566. d2 = c2;
  41567. c2 = b2 << 30 | b2 >>> 2;
  41568. b2 = a2;
  41569. a2 = t2;
  41570. }
  41571. H2[0] = H2[0] + a2 | 0;
  41572. H2[1] = H2[1] + b2 | 0;
  41573. H2[2] = H2[2] + c2 | 0;
  41574. H2[3] = H2[3] + d2 | 0;
  41575. H2[4] = H2[4] + e2 | 0;
  41576. },
  41577. _doFinalize: function() {
  41578. var data = this._data;
  41579. var dataWords = data.words;
  41580. var nBitsTotal = this._nDataBytes * 8;
  41581. var nBitsLeft = data.sigBytes * 8;
  41582. dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  41583. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(nBitsTotal / 4294967296);
  41584. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
  41585. data.sigBytes = dataWords.length * 4;
  41586. this._process();
  41587. return this._hash;
  41588. },
  41589. clone: function() {
  41590. var clone2 = Hasher.clone.call(this);
  41591. clone2._hash = this._hash.clone();
  41592. return clone2;
  41593. }
  41594. });
  41595. C2.SHA1 = Hasher._createHelper(SHA1);
  41596. C2.HmacSHA1 = Hasher._createHmacHelper(SHA1);
  41597. })();
  41598. return CryptoJS2.SHA1;
  41599. });
  41600. })(sha1);
  41601. return sha1.exports;
  41602. }
  41603. var sha256 = { exports: {} };
  41604. var hasRequiredSha256;
  41605. function requireSha256() {
  41606. if (hasRequiredSha256)
  41607. return sha256.exports;
  41608. hasRequiredSha256 = 1;
  41609. (function(module2, exports2) {
  41610. (function(root, factory) {
  41611. {
  41612. module2.exports = factory(requireCore());
  41613. }
  41614. })(commonjsGlobal, function(CryptoJS2) {
  41615. (function(Math2) {
  41616. var C2 = CryptoJS2;
  41617. var C_lib = C2.lib;
  41618. var WordArray = C_lib.WordArray;
  41619. var Hasher = C_lib.Hasher;
  41620. var C_algo = C2.algo;
  41621. var H2 = [];
  41622. var K2 = [];
  41623. (function() {
  41624. function isPrime(n3) {
  41625. var sqrtN = Math2.sqrt(n3);
  41626. for (var factor = 2; factor <= sqrtN; factor++) {
  41627. if (!(n3 % factor)) {
  41628. return false;
  41629. }
  41630. }
  41631. return true;
  41632. }
  41633. function getFractionalBits(n3) {
  41634. return (n3 - (n3 | 0)) * 4294967296 | 0;
  41635. }
  41636. var n2 = 2;
  41637. var nPrime = 0;
  41638. while (nPrime < 64) {
  41639. if (isPrime(n2)) {
  41640. if (nPrime < 8) {
  41641. H2[nPrime] = getFractionalBits(Math2.pow(n2, 1 / 2));
  41642. }
  41643. K2[nPrime] = getFractionalBits(Math2.pow(n2, 1 / 3));
  41644. nPrime++;
  41645. }
  41646. n2++;
  41647. }
  41648. })();
  41649. var W2 = [];
  41650. var SHA256 = C_algo.SHA256 = Hasher.extend({
  41651. _doReset: function() {
  41652. this._hash = new WordArray.init(H2.slice(0));
  41653. },
  41654. _doProcessBlock: function(M2, offset) {
  41655. var H3 = this._hash.words;
  41656. var a2 = H3[0];
  41657. var b2 = H3[1];
  41658. var c2 = H3[2];
  41659. var d2 = H3[3];
  41660. var e2 = H3[4];
  41661. var f2 = H3[5];
  41662. var g2 = H3[6];
  41663. var h2 = H3[7];
  41664. for (var i2 = 0; i2 < 64; i2++) {
  41665. if (i2 < 16) {
  41666. W2[i2] = M2[offset + i2] | 0;
  41667. } else {
  41668. var gamma0x = W2[i2 - 15];
  41669. var gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
  41670. var gamma1x = W2[i2 - 2];
  41671. var gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
  41672. W2[i2] = gamma0 + W2[i2 - 7] + gamma1 + W2[i2 - 16];
  41673. }
  41674. var ch = e2 & f2 ^ ~e2 & g2;
  41675. var maj = a2 & b2 ^ a2 & c2 ^ b2 & c2;
  41676. var sigma0 = (a2 << 30 | a2 >>> 2) ^ (a2 << 19 | a2 >>> 13) ^ (a2 << 10 | a2 >>> 22);
  41677. var sigma1 = (e2 << 26 | e2 >>> 6) ^ (e2 << 21 | e2 >>> 11) ^ (e2 << 7 | e2 >>> 25);
  41678. var t1 = h2 + sigma1 + ch + K2[i2] + W2[i2];
  41679. var t2 = sigma0 + maj;
  41680. h2 = g2;
  41681. g2 = f2;
  41682. f2 = e2;
  41683. e2 = d2 + t1 | 0;
  41684. d2 = c2;
  41685. c2 = b2;
  41686. b2 = a2;
  41687. a2 = t1 + t2 | 0;
  41688. }
  41689. H3[0] = H3[0] + a2 | 0;
  41690. H3[1] = H3[1] + b2 | 0;
  41691. H3[2] = H3[2] + c2 | 0;
  41692. H3[3] = H3[3] + d2 | 0;
  41693. H3[4] = H3[4] + e2 | 0;
  41694. H3[5] = H3[5] + f2 | 0;
  41695. H3[6] = H3[6] + g2 | 0;
  41696. H3[7] = H3[7] + h2 | 0;
  41697. },
  41698. _doFinalize: function() {
  41699. var data = this._data;
  41700. var dataWords = data.words;
  41701. var nBitsTotal = this._nDataBytes * 8;
  41702. var nBitsLeft = data.sigBytes * 8;
  41703. dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  41704. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math2.floor(nBitsTotal / 4294967296);
  41705. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
  41706. data.sigBytes = dataWords.length * 4;
  41707. this._process();
  41708. return this._hash;
  41709. },
  41710. clone: function() {
  41711. var clone2 = Hasher.clone.call(this);
  41712. clone2._hash = this._hash.clone();
  41713. return clone2;
  41714. }
  41715. });
  41716. C2.SHA256 = Hasher._createHelper(SHA256);
  41717. C2.HmacSHA256 = Hasher._createHmacHelper(SHA256);
  41718. })(Math);
  41719. return CryptoJS2.SHA256;
  41720. });
  41721. })(sha256);
  41722. return sha256.exports;
  41723. }
  41724. var sha224 = { exports: {} };
  41725. var hasRequiredSha224;
  41726. function requireSha224() {
  41727. if (hasRequiredSha224)
  41728. return sha224.exports;
  41729. hasRequiredSha224 = 1;
  41730. (function(module2, exports2) {
  41731. (function(root, factory, undef) {
  41732. {
  41733. module2.exports = factory(requireCore(), requireSha256());
  41734. }
  41735. })(commonjsGlobal, function(CryptoJS2) {
  41736. (function() {
  41737. var C2 = CryptoJS2;
  41738. var C_lib = C2.lib;
  41739. var WordArray = C_lib.WordArray;
  41740. var C_algo = C2.algo;
  41741. var SHA256 = C_algo.SHA256;
  41742. var SHA224 = C_algo.SHA224 = SHA256.extend({
  41743. _doReset: function() {
  41744. this._hash = new WordArray.init([
  41745. 3238371032,
  41746. 914150663,
  41747. 812702999,
  41748. 4144912697,
  41749. 4290775857,
  41750. 1750603025,
  41751. 1694076839,
  41752. 3204075428
  41753. ]);
  41754. },
  41755. _doFinalize: function() {
  41756. var hash2 = SHA256._doFinalize.call(this);
  41757. hash2.sigBytes -= 4;
  41758. return hash2;
  41759. }
  41760. });
  41761. C2.SHA224 = SHA256._createHelper(SHA224);
  41762. C2.HmacSHA224 = SHA256._createHmacHelper(SHA224);
  41763. })();
  41764. return CryptoJS2.SHA224;
  41765. });
  41766. })(sha224);
  41767. return sha224.exports;
  41768. }
  41769. var sha512 = { exports: {} };
  41770. var hasRequiredSha512;
  41771. function requireSha512() {
  41772. if (hasRequiredSha512)
  41773. return sha512.exports;
  41774. hasRequiredSha512 = 1;
  41775. (function(module2, exports2) {
  41776. (function(root, factory, undef) {
  41777. {
  41778. module2.exports = factory(requireCore(), requireX64Core());
  41779. }
  41780. })(commonjsGlobal, function(CryptoJS2) {
  41781. (function() {
  41782. var C2 = CryptoJS2;
  41783. var C_lib = C2.lib;
  41784. var Hasher = C_lib.Hasher;
  41785. var C_x64 = C2.x64;
  41786. var X64Word = C_x64.Word;
  41787. var X64WordArray = C_x64.WordArray;
  41788. var C_algo = C2.algo;
  41789. function X64Word_create() {
  41790. return X64Word.create.apply(X64Word, arguments);
  41791. }
  41792. var K2 = [
  41793. X64Word_create(1116352408, 3609767458),
  41794. X64Word_create(1899447441, 602891725),
  41795. X64Word_create(3049323471, 3964484399),
  41796. X64Word_create(3921009573, 2173295548),
  41797. X64Word_create(961987163, 4081628472),
  41798. X64Word_create(1508970993, 3053834265),
  41799. X64Word_create(2453635748, 2937671579),
  41800. X64Word_create(2870763221, 3664609560),
  41801. X64Word_create(3624381080, 2734883394),
  41802. X64Word_create(310598401, 1164996542),
  41803. X64Word_create(607225278, 1323610764),
  41804. X64Word_create(1426881987, 3590304994),
  41805. X64Word_create(1925078388, 4068182383),
  41806. X64Word_create(2162078206, 991336113),
  41807. X64Word_create(2614888103, 633803317),
  41808. X64Word_create(3248222580, 3479774868),
  41809. X64Word_create(3835390401, 2666613458),
  41810. X64Word_create(4022224774, 944711139),
  41811. X64Word_create(264347078, 2341262773),
  41812. X64Word_create(604807628, 2007800933),
  41813. X64Word_create(770255983, 1495990901),
  41814. X64Word_create(1249150122, 1856431235),
  41815. X64Word_create(1555081692, 3175218132),
  41816. X64Word_create(1996064986, 2198950837),
  41817. X64Word_create(2554220882, 3999719339),
  41818. X64Word_create(2821834349, 766784016),
  41819. X64Word_create(2952996808, 2566594879),
  41820. X64Word_create(3210313671, 3203337956),
  41821. X64Word_create(3336571891, 1034457026),
  41822. X64Word_create(3584528711, 2466948901),
  41823. X64Word_create(113926993, 3758326383),
  41824. X64Word_create(338241895, 168717936),
  41825. X64Word_create(666307205, 1188179964),
  41826. X64Word_create(773529912, 1546045734),
  41827. X64Word_create(1294757372, 1522805485),
  41828. X64Word_create(1396182291, 2643833823),
  41829. X64Word_create(1695183700, 2343527390),
  41830. X64Word_create(1986661051, 1014477480),
  41831. X64Word_create(2177026350, 1206759142),
  41832. X64Word_create(2456956037, 344077627),
  41833. X64Word_create(2730485921, 1290863460),
  41834. X64Word_create(2820302411, 3158454273),
  41835. X64Word_create(3259730800, 3505952657),
  41836. X64Word_create(3345764771, 106217008),
  41837. X64Word_create(3516065817, 3606008344),
  41838. X64Word_create(3600352804, 1432725776),
  41839. X64Word_create(4094571909, 1467031594),
  41840. X64Word_create(275423344, 851169720),
  41841. X64Word_create(430227734, 3100823752),
  41842. X64Word_create(506948616, 1363258195),
  41843. X64Word_create(659060556, 3750685593),
  41844. X64Word_create(883997877, 3785050280),
  41845. X64Word_create(958139571, 3318307427),
  41846. X64Word_create(1322822218, 3812723403),
  41847. X64Word_create(1537002063, 2003034995),
  41848. X64Word_create(1747873779, 3602036899),
  41849. X64Word_create(1955562222, 1575990012),
  41850. X64Word_create(2024104815, 1125592928),
  41851. X64Word_create(2227730452, 2716904306),
  41852. X64Word_create(2361852424, 442776044),
  41853. X64Word_create(2428436474, 593698344),
  41854. X64Word_create(2756734187, 3733110249),
  41855. X64Word_create(3204031479, 2999351573),
  41856. X64Word_create(3329325298, 3815920427),
  41857. X64Word_create(3391569614, 3928383900),
  41858. X64Word_create(3515267271, 566280711),
  41859. X64Word_create(3940187606, 3454069534),
  41860. X64Word_create(4118630271, 4000239992),
  41861. X64Word_create(116418474, 1914138554),
  41862. X64Word_create(174292421, 2731055270),
  41863. X64Word_create(289380356, 3203993006),
  41864. X64Word_create(460393269, 320620315),
  41865. X64Word_create(685471733, 587496836),
  41866. X64Word_create(852142971, 1086792851),
  41867. X64Word_create(1017036298, 365543100),
  41868. X64Word_create(1126000580, 2618297676),
  41869. X64Word_create(1288033470, 3409855158),
  41870. X64Word_create(1501505948, 4234509866),
  41871. X64Word_create(1607167915, 987167468),
  41872. X64Word_create(1816402316, 1246189591)
  41873. ];
  41874. var W2 = [];
  41875. (function() {
  41876. for (var i2 = 0; i2 < 80; i2++) {
  41877. W2[i2] = X64Word_create();
  41878. }
  41879. })();
  41880. var SHA512 = C_algo.SHA512 = Hasher.extend({
  41881. _doReset: function() {
  41882. this._hash = new X64WordArray.init([
  41883. new X64Word.init(1779033703, 4089235720),
  41884. new X64Word.init(3144134277, 2227873595),
  41885. new X64Word.init(1013904242, 4271175723),
  41886. new X64Word.init(2773480762, 1595750129),
  41887. new X64Word.init(1359893119, 2917565137),
  41888. new X64Word.init(2600822924, 725511199),
  41889. new X64Word.init(528734635, 4215389547),
  41890. new X64Word.init(1541459225, 327033209)
  41891. ]);
  41892. },
  41893. _doProcessBlock: function(M2, offset) {
  41894. var H2 = this._hash.words;
  41895. var H0 = H2[0];
  41896. var H1 = H2[1];
  41897. var H22 = H2[2];
  41898. var H3 = H2[3];
  41899. var H4 = H2[4];
  41900. var H5 = H2[5];
  41901. var H6 = H2[6];
  41902. var H7 = H2[7];
  41903. var H0h = H0.high;
  41904. var H0l = H0.low;
  41905. var H1h = H1.high;
  41906. var H1l = H1.low;
  41907. var H2h = H22.high;
  41908. var H2l = H22.low;
  41909. var H3h = H3.high;
  41910. var H3l = H3.low;
  41911. var H4h = H4.high;
  41912. var H4l = H4.low;
  41913. var H5h = H5.high;
  41914. var H5l = H5.low;
  41915. var H6h = H6.high;
  41916. var H6l = H6.low;
  41917. var H7h = H7.high;
  41918. var H7l = H7.low;
  41919. var ah = H0h;
  41920. var al = H0l;
  41921. var bh = H1h;
  41922. var bl = H1l;
  41923. var ch = H2h;
  41924. var cl = H2l;
  41925. var dh = H3h;
  41926. var dl = H3l;
  41927. var eh = H4h;
  41928. var el = H4l;
  41929. var fh = H5h;
  41930. var fl = H5l;
  41931. var gh = H6h;
  41932. var gl = H6l;
  41933. var hh = H7h;
  41934. var hl = H7l;
  41935. for (var i2 = 0; i2 < 80; i2++) {
  41936. var Wil;
  41937. var Wih;
  41938. var Wi = W2[i2];
  41939. if (i2 < 16) {
  41940. Wih = Wi.high = M2[offset + i2 * 2] | 0;
  41941. Wil = Wi.low = M2[offset + i2 * 2 + 1] | 0;
  41942. } else {
  41943. var gamma0x = W2[i2 - 15];
  41944. var gamma0xh = gamma0x.high;
  41945. var gamma0xl = gamma0x.low;
  41946. var gamma0h = (gamma0xh >>> 1 | gamma0xl << 31) ^ (gamma0xh >>> 8 | gamma0xl << 24) ^ gamma0xh >>> 7;
  41947. var gamma0l = (gamma0xl >>> 1 | gamma0xh << 31) ^ (gamma0xl >>> 8 | gamma0xh << 24) ^ (gamma0xl >>> 7 | gamma0xh << 25);
  41948. var gamma1x = W2[i2 - 2];
  41949. var gamma1xh = gamma1x.high;
  41950. var gamma1xl = gamma1x.low;
  41951. var gamma1h = (gamma1xh >>> 19 | gamma1xl << 13) ^ (gamma1xh << 3 | gamma1xl >>> 29) ^ gamma1xh >>> 6;
  41952. var gamma1l = (gamma1xl >>> 19 | gamma1xh << 13) ^ (gamma1xl << 3 | gamma1xh >>> 29) ^ (gamma1xl >>> 6 | gamma1xh << 26);
  41953. var Wi7 = W2[i2 - 7];
  41954. var Wi7h = Wi7.high;
  41955. var Wi7l = Wi7.low;
  41956. var Wi16 = W2[i2 - 16];
  41957. var Wi16h = Wi16.high;
  41958. var Wi16l = Wi16.low;
  41959. Wil = gamma0l + Wi7l;
  41960. Wih = gamma0h + Wi7h + (Wil >>> 0 < gamma0l >>> 0 ? 1 : 0);
  41961. Wil = Wil + gamma1l;
  41962. Wih = Wih + gamma1h + (Wil >>> 0 < gamma1l >>> 0 ? 1 : 0);
  41963. Wil = Wil + Wi16l;
  41964. Wih = Wih + Wi16h + (Wil >>> 0 < Wi16l >>> 0 ? 1 : 0);
  41965. Wi.high = Wih;
  41966. Wi.low = Wil;
  41967. }
  41968. var chh = eh & fh ^ ~eh & gh;
  41969. var chl = el & fl ^ ~el & gl;
  41970. var majh = ah & bh ^ ah & ch ^ bh & ch;
  41971. var majl = al & bl ^ al & cl ^ bl & cl;
  41972. var sigma0h = (ah >>> 28 | al << 4) ^ (ah << 30 | al >>> 2) ^ (ah << 25 | al >>> 7);
  41973. var sigma0l = (al >>> 28 | ah << 4) ^ (al << 30 | ah >>> 2) ^ (al << 25 | ah >>> 7);
  41974. var sigma1h = (eh >>> 14 | el << 18) ^ (eh >>> 18 | el << 14) ^ (eh << 23 | el >>> 9);
  41975. var sigma1l = (el >>> 14 | eh << 18) ^ (el >>> 18 | eh << 14) ^ (el << 23 | eh >>> 9);
  41976. var Ki = K2[i2];
  41977. var Kih = Ki.high;
  41978. var Kil = Ki.low;
  41979. var t1l = hl + sigma1l;
  41980. var t1h = hh + sigma1h + (t1l >>> 0 < hl >>> 0 ? 1 : 0);
  41981. var t1l = t1l + chl;
  41982. var t1h = t1h + chh + (t1l >>> 0 < chl >>> 0 ? 1 : 0);
  41983. var t1l = t1l + Kil;
  41984. var t1h = t1h + Kih + (t1l >>> 0 < Kil >>> 0 ? 1 : 0);
  41985. var t1l = t1l + Wil;
  41986. var t1h = t1h + Wih + (t1l >>> 0 < Wil >>> 0 ? 1 : 0);
  41987. var t2l = sigma0l + majl;
  41988. var t2h = sigma0h + majh + (t2l >>> 0 < sigma0l >>> 0 ? 1 : 0);
  41989. hh = gh;
  41990. hl = gl;
  41991. gh = fh;
  41992. gl = fl;
  41993. fh = eh;
  41994. fl = el;
  41995. el = dl + t1l | 0;
  41996. eh = dh + t1h + (el >>> 0 < dl >>> 0 ? 1 : 0) | 0;
  41997. dh = ch;
  41998. dl = cl;
  41999. ch = bh;
  42000. cl = bl;
  42001. bh = ah;
  42002. bl = al;
  42003. al = t1l + t2l | 0;
  42004. ah = t1h + t2h + (al >>> 0 < t1l >>> 0 ? 1 : 0) | 0;
  42005. }
  42006. H0l = H0.low = H0l + al;
  42007. H0.high = H0h + ah + (H0l >>> 0 < al >>> 0 ? 1 : 0);
  42008. H1l = H1.low = H1l + bl;
  42009. H1.high = H1h + bh + (H1l >>> 0 < bl >>> 0 ? 1 : 0);
  42010. H2l = H22.low = H2l + cl;
  42011. H22.high = H2h + ch + (H2l >>> 0 < cl >>> 0 ? 1 : 0);
  42012. H3l = H3.low = H3l + dl;
  42013. H3.high = H3h + dh + (H3l >>> 0 < dl >>> 0 ? 1 : 0);
  42014. H4l = H4.low = H4l + el;
  42015. H4.high = H4h + eh + (H4l >>> 0 < el >>> 0 ? 1 : 0);
  42016. H5l = H5.low = H5l + fl;
  42017. H5.high = H5h + fh + (H5l >>> 0 < fl >>> 0 ? 1 : 0);
  42018. H6l = H6.low = H6l + gl;
  42019. H6.high = H6h + gh + (H6l >>> 0 < gl >>> 0 ? 1 : 0);
  42020. H7l = H7.low = H7l + hl;
  42021. H7.high = H7h + hh + (H7l >>> 0 < hl >>> 0 ? 1 : 0);
  42022. },
  42023. _doFinalize: function() {
  42024. var data = this._data;
  42025. var dataWords = data.words;
  42026. var nBitsTotal = this._nDataBytes * 8;
  42027. var nBitsLeft = data.sigBytes * 8;
  42028. dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  42029. dataWords[(nBitsLeft + 128 >>> 10 << 5) + 30] = Math.floor(nBitsTotal / 4294967296);
  42030. dataWords[(nBitsLeft + 128 >>> 10 << 5) + 31] = nBitsTotal;
  42031. data.sigBytes = dataWords.length * 4;
  42032. this._process();
  42033. var hash2 = this._hash.toX32();
  42034. return hash2;
  42035. },
  42036. clone: function() {
  42037. var clone2 = Hasher.clone.call(this);
  42038. clone2._hash = this._hash.clone();
  42039. return clone2;
  42040. },
  42041. blockSize: 1024 / 32
  42042. });
  42043. C2.SHA512 = Hasher._createHelper(SHA512);
  42044. C2.HmacSHA512 = Hasher._createHmacHelper(SHA512);
  42045. })();
  42046. return CryptoJS2.SHA512;
  42047. });
  42048. })(sha512);
  42049. return sha512.exports;
  42050. }
  42051. var sha384 = { exports: {} };
  42052. var hasRequiredSha384;
  42053. function requireSha384() {
  42054. if (hasRequiredSha384)
  42055. return sha384.exports;
  42056. hasRequiredSha384 = 1;
  42057. (function(module2, exports2) {
  42058. (function(root, factory, undef) {
  42059. {
  42060. module2.exports = factory(requireCore(), requireX64Core(), requireSha512());
  42061. }
  42062. })(commonjsGlobal, function(CryptoJS2) {
  42063. (function() {
  42064. var C2 = CryptoJS2;
  42065. var C_x64 = C2.x64;
  42066. var X64Word = C_x64.Word;
  42067. var X64WordArray = C_x64.WordArray;
  42068. var C_algo = C2.algo;
  42069. var SHA512 = C_algo.SHA512;
  42070. var SHA384 = C_algo.SHA384 = SHA512.extend({
  42071. _doReset: function() {
  42072. this._hash = new X64WordArray.init([
  42073. new X64Word.init(3418070365, 3238371032),
  42074. new X64Word.init(1654270250, 914150663),
  42075. new X64Word.init(2438529370, 812702999),
  42076. new X64Word.init(355462360, 4144912697),
  42077. new X64Word.init(1731405415, 4290775857),
  42078. new X64Word.init(2394180231, 1750603025),
  42079. new X64Word.init(3675008525, 1694076839),
  42080. new X64Word.init(1203062813, 3204075428)
  42081. ]);
  42082. },
  42083. _doFinalize: function() {
  42084. var hash2 = SHA512._doFinalize.call(this);
  42085. hash2.sigBytes -= 16;
  42086. return hash2;
  42087. }
  42088. });
  42089. C2.SHA384 = SHA512._createHelper(SHA384);
  42090. C2.HmacSHA384 = SHA512._createHmacHelper(SHA384);
  42091. })();
  42092. return CryptoJS2.SHA384;
  42093. });
  42094. })(sha384);
  42095. return sha384.exports;
  42096. }
  42097. var sha3 = { exports: {} };
  42098. var hasRequiredSha3;
  42099. function requireSha3() {
  42100. if (hasRequiredSha3)
  42101. return sha3.exports;
  42102. hasRequiredSha3 = 1;
  42103. (function(module2, exports2) {
  42104. (function(root, factory, undef) {
  42105. {
  42106. module2.exports = factory(requireCore(), requireX64Core());
  42107. }
  42108. })(commonjsGlobal, function(CryptoJS2) {
  42109. (function(Math2) {
  42110. var C2 = CryptoJS2;
  42111. var C_lib = C2.lib;
  42112. var WordArray = C_lib.WordArray;
  42113. var Hasher = C_lib.Hasher;
  42114. var C_x64 = C2.x64;
  42115. var X64Word = C_x64.Word;
  42116. var C_algo = C2.algo;
  42117. var RHO_OFFSETS = [];
  42118. var PI_INDEXES = [];
  42119. var ROUND_CONSTANTS = [];
  42120. (function() {
  42121. var x = 1, y2 = 0;
  42122. for (var t2 = 0; t2 < 24; t2++) {
  42123. RHO_OFFSETS[x + 5 * y2] = (t2 + 1) * (t2 + 2) / 2 % 64;
  42124. var newX = y2 % 5;
  42125. var newY = (2 * x + 3 * y2) % 5;
  42126. x = newX;
  42127. y2 = newY;
  42128. }
  42129. for (var x = 0; x < 5; x++) {
  42130. for (var y2 = 0; y2 < 5; y2++) {
  42131. PI_INDEXES[x + 5 * y2] = y2 + (2 * x + 3 * y2) % 5 * 5;
  42132. }
  42133. }
  42134. var LFSR = 1;
  42135. for (var i2 = 0; i2 < 24; i2++) {
  42136. var roundConstantMsw = 0;
  42137. var roundConstantLsw = 0;
  42138. for (var j2 = 0; j2 < 7; j2++) {
  42139. if (LFSR & 1) {
  42140. var bitPosition = (1 << j2) - 1;
  42141. if (bitPosition < 32) {
  42142. roundConstantLsw ^= 1 << bitPosition;
  42143. } else {
  42144. roundConstantMsw ^= 1 << bitPosition - 32;
  42145. }
  42146. }
  42147. if (LFSR & 128) {
  42148. LFSR = LFSR << 1 ^ 113;
  42149. } else {
  42150. LFSR <<= 1;
  42151. }
  42152. }
  42153. ROUND_CONSTANTS[i2] = X64Word.create(roundConstantMsw, roundConstantLsw);
  42154. }
  42155. })();
  42156. var T2 = [];
  42157. (function() {
  42158. for (var i2 = 0; i2 < 25; i2++) {
  42159. T2[i2] = X64Word.create();
  42160. }
  42161. })();
  42162. var SHA3 = C_algo.SHA3 = Hasher.extend({
  42163. /**
  42164. * Configuration options.
  42165. *
  42166. * @property {number} outputLength
  42167. * The desired number of bits in the output hash.
  42168. * Only values permitted are: 224, 256, 384, 512.
  42169. * Default: 512
  42170. */
  42171. cfg: Hasher.cfg.extend({
  42172. outputLength: 512
  42173. }),
  42174. _doReset: function() {
  42175. var state = this._state = [];
  42176. for (var i2 = 0; i2 < 25; i2++) {
  42177. state[i2] = new X64Word.init();
  42178. }
  42179. this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
  42180. },
  42181. _doProcessBlock: function(M2, offset) {
  42182. var state = this._state;
  42183. var nBlockSizeLanes = this.blockSize / 2;
  42184. for (var i2 = 0; i2 < nBlockSizeLanes; i2++) {
  42185. var M2i = M2[offset + 2 * i2];
  42186. var M2i1 = M2[offset + 2 * i2 + 1];
  42187. M2i = (M2i << 8 | M2i >>> 24) & 16711935 | (M2i << 24 | M2i >>> 8) & 4278255360;
  42188. M2i1 = (M2i1 << 8 | M2i1 >>> 24) & 16711935 | (M2i1 << 24 | M2i1 >>> 8) & 4278255360;
  42189. var lane = state[i2];
  42190. lane.high ^= M2i1;
  42191. lane.low ^= M2i;
  42192. }
  42193. for (var round = 0; round < 24; round++) {
  42194. for (var x = 0; x < 5; x++) {
  42195. var tMsw = 0, tLsw = 0;
  42196. for (var y2 = 0; y2 < 5; y2++) {
  42197. var lane = state[x + 5 * y2];
  42198. tMsw ^= lane.high;
  42199. tLsw ^= lane.low;
  42200. }
  42201. var Tx = T2[x];
  42202. Tx.high = tMsw;
  42203. Tx.low = tLsw;
  42204. }
  42205. for (var x = 0; x < 5; x++) {
  42206. var Tx4 = T2[(x + 4) % 5];
  42207. var Tx1 = T2[(x + 1) % 5];
  42208. var Tx1Msw = Tx1.high;
  42209. var Tx1Lsw = Tx1.low;
  42210. var tMsw = Tx4.high ^ (Tx1Msw << 1 | Tx1Lsw >>> 31);
  42211. var tLsw = Tx4.low ^ (Tx1Lsw << 1 | Tx1Msw >>> 31);
  42212. for (var y2 = 0; y2 < 5; y2++) {
  42213. var lane = state[x + 5 * y2];
  42214. lane.high ^= tMsw;
  42215. lane.low ^= tLsw;
  42216. }
  42217. }
  42218. for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
  42219. var tMsw;
  42220. var tLsw;
  42221. var lane = state[laneIndex];
  42222. var laneMsw = lane.high;
  42223. var laneLsw = lane.low;
  42224. var rhoOffset = RHO_OFFSETS[laneIndex];
  42225. if (rhoOffset < 32) {
  42226. tMsw = laneMsw << rhoOffset | laneLsw >>> 32 - rhoOffset;
  42227. tLsw = laneLsw << rhoOffset | laneMsw >>> 32 - rhoOffset;
  42228. } else {
  42229. tMsw = laneLsw << rhoOffset - 32 | laneMsw >>> 64 - rhoOffset;
  42230. tLsw = laneMsw << rhoOffset - 32 | laneLsw >>> 64 - rhoOffset;
  42231. }
  42232. var TPiLane = T2[PI_INDEXES[laneIndex]];
  42233. TPiLane.high = tMsw;
  42234. TPiLane.low = tLsw;
  42235. }
  42236. var T0 = T2[0];
  42237. var state0 = state[0];
  42238. T0.high = state0.high;
  42239. T0.low = state0.low;
  42240. for (var x = 0; x < 5; x++) {
  42241. for (var y2 = 0; y2 < 5; y2++) {
  42242. var laneIndex = x + 5 * y2;
  42243. var lane = state[laneIndex];
  42244. var TLane = T2[laneIndex];
  42245. var Tx1Lane = T2[(x + 1) % 5 + 5 * y2];
  42246. var Tx2Lane = T2[(x + 2) % 5 + 5 * y2];
  42247. lane.high = TLane.high ^ ~Tx1Lane.high & Tx2Lane.high;
  42248. lane.low = TLane.low ^ ~Tx1Lane.low & Tx2Lane.low;
  42249. }
  42250. }
  42251. var lane = state[0];
  42252. var roundConstant = ROUND_CONSTANTS[round];
  42253. lane.high ^= roundConstant.high;
  42254. lane.low ^= roundConstant.low;
  42255. }
  42256. },
  42257. _doFinalize: function() {
  42258. var data = this._data;
  42259. var dataWords = data.words;
  42260. this._nDataBytes * 8;
  42261. var nBitsLeft = data.sigBytes * 8;
  42262. var blockSizeBits = this.blockSize * 32;
  42263. dataWords[nBitsLeft >>> 5] |= 1 << 24 - nBitsLeft % 32;
  42264. dataWords[(Math2.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits >>> 5) - 1] |= 128;
  42265. data.sigBytes = dataWords.length * 4;
  42266. this._process();
  42267. var state = this._state;
  42268. var outputLengthBytes = this.cfg.outputLength / 8;
  42269. var outputLengthLanes = outputLengthBytes / 8;
  42270. var hashWords = [];
  42271. for (var i2 = 0; i2 < outputLengthLanes; i2++) {
  42272. var lane = state[i2];
  42273. var laneMsw = lane.high;
  42274. var laneLsw = lane.low;
  42275. laneMsw = (laneMsw << 8 | laneMsw >>> 24) & 16711935 | (laneMsw << 24 | laneMsw >>> 8) & 4278255360;
  42276. laneLsw = (laneLsw << 8 | laneLsw >>> 24) & 16711935 | (laneLsw << 24 | laneLsw >>> 8) & 4278255360;
  42277. hashWords.push(laneLsw);
  42278. hashWords.push(laneMsw);
  42279. }
  42280. return new WordArray.init(hashWords, outputLengthBytes);
  42281. },
  42282. clone: function() {
  42283. var clone2 = Hasher.clone.call(this);
  42284. var state = clone2._state = this._state.slice(0);
  42285. for (var i2 = 0; i2 < 25; i2++) {
  42286. state[i2] = state[i2].clone();
  42287. }
  42288. return clone2;
  42289. }
  42290. });
  42291. C2.SHA3 = Hasher._createHelper(SHA3);
  42292. C2.HmacSHA3 = Hasher._createHmacHelper(SHA3);
  42293. })(Math);
  42294. return CryptoJS2.SHA3;
  42295. });
  42296. })(sha3);
  42297. return sha3.exports;
  42298. }
  42299. var ripemd160 = { exports: {} };
  42300. var hasRequiredRipemd160;
  42301. function requireRipemd160() {
  42302. if (hasRequiredRipemd160)
  42303. return ripemd160.exports;
  42304. hasRequiredRipemd160 = 1;
  42305. (function(module2, exports2) {
  42306. (function(root, factory) {
  42307. {
  42308. module2.exports = factory(requireCore());
  42309. }
  42310. })(commonjsGlobal, function(CryptoJS2) {
  42311. /** @preserve
  42312. (c) 2012 by Cédric Mesnil. All rights reserved.
  42313. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  42314. - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  42315. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  42316. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42317. */
  42318. (function(Math2) {
  42319. var C2 = CryptoJS2;
  42320. var C_lib = C2.lib;
  42321. var WordArray = C_lib.WordArray;
  42322. var Hasher = C_lib.Hasher;
  42323. var C_algo = C2.algo;
  42324. var _zl = WordArray.create([
  42325. 0,
  42326. 1,
  42327. 2,
  42328. 3,
  42329. 4,
  42330. 5,
  42331. 6,
  42332. 7,
  42333. 8,
  42334. 9,
  42335. 10,
  42336. 11,
  42337. 12,
  42338. 13,
  42339. 14,
  42340. 15,
  42341. 7,
  42342. 4,
  42343. 13,
  42344. 1,
  42345. 10,
  42346. 6,
  42347. 15,
  42348. 3,
  42349. 12,
  42350. 0,
  42351. 9,
  42352. 5,
  42353. 2,
  42354. 14,
  42355. 11,
  42356. 8,
  42357. 3,
  42358. 10,
  42359. 14,
  42360. 4,
  42361. 9,
  42362. 15,
  42363. 8,
  42364. 1,
  42365. 2,
  42366. 7,
  42367. 0,
  42368. 6,
  42369. 13,
  42370. 11,
  42371. 5,
  42372. 12,
  42373. 1,
  42374. 9,
  42375. 11,
  42376. 10,
  42377. 0,
  42378. 8,
  42379. 12,
  42380. 4,
  42381. 13,
  42382. 3,
  42383. 7,
  42384. 15,
  42385. 14,
  42386. 5,
  42387. 6,
  42388. 2,
  42389. 4,
  42390. 0,
  42391. 5,
  42392. 9,
  42393. 7,
  42394. 12,
  42395. 2,
  42396. 10,
  42397. 14,
  42398. 1,
  42399. 3,
  42400. 8,
  42401. 11,
  42402. 6,
  42403. 15,
  42404. 13
  42405. ]);
  42406. var _zr = WordArray.create([
  42407. 5,
  42408. 14,
  42409. 7,
  42410. 0,
  42411. 9,
  42412. 2,
  42413. 11,
  42414. 4,
  42415. 13,
  42416. 6,
  42417. 15,
  42418. 8,
  42419. 1,
  42420. 10,
  42421. 3,
  42422. 12,
  42423. 6,
  42424. 11,
  42425. 3,
  42426. 7,
  42427. 0,
  42428. 13,
  42429. 5,
  42430. 10,
  42431. 14,
  42432. 15,
  42433. 8,
  42434. 12,
  42435. 4,
  42436. 9,
  42437. 1,
  42438. 2,
  42439. 15,
  42440. 5,
  42441. 1,
  42442. 3,
  42443. 7,
  42444. 14,
  42445. 6,
  42446. 9,
  42447. 11,
  42448. 8,
  42449. 12,
  42450. 2,
  42451. 10,
  42452. 0,
  42453. 4,
  42454. 13,
  42455. 8,
  42456. 6,
  42457. 4,
  42458. 1,
  42459. 3,
  42460. 11,
  42461. 15,
  42462. 0,
  42463. 5,
  42464. 12,
  42465. 2,
  42466. 13,
  42467. 9,
  42468. 7,
  42469. 10,
  42470. 14,
  42471. 12,
  42472. 15,
  42473. 10,
  42474. 4,
  42475. 1,
  42476. 5,
  42477. 8,
  42478. 7,
  42479. 6,
  42480. 2,
  42481. 13,
  42482. 14,
  42483. 0,
  42484. 3,
  42485. 9,
  42486. 11
  42487. ]);
  42488. var _sl = WordArray.create([
  42489. 11,
  42490. 14,
  42491. 15,
  42492. 12,
  42493. 5,
  42494. 8,
  42495. 7,
  42496. 9,
  42497. 11,
  42498. 13,
  42499. 14,
  42500. 15,
  42501. 6,
  42502. 7,
  42503. 9,
  42504. 8,
  42505. 7,
  42506. 6,
  42507. 8,
  42508. 13,
  42509. 11,
  42510. 9,
  42511. 7,
  42512. 15,
  42513. 7,
  42514. 12,
  42515. 15,
  42516. 9,
  42517. 11,
  42518. 7,
  42519. 13,
  42520. 12,
  42521. 11,
  42522. 13,
  42523. 6,
  42524. 7,
  42525. 14,
  42526. 9,
  42527. 13,
  42528. 15,
  42529. 14,
  42530. 8,
  42531. 13,
  42532. 6,
  42533. 5,
  42534. 12,
  42535. 7,
  42536. 5,
  42537. 11,
  42538. 12,
  42539. 14,
  42540. 15,
  42541. 14,
  42542. 15,
  42543. 9,
  42544. 8,
  42545. 9,
  42546. 14,
  42547. 5,
  42548. 6,
  42549. 8,
  42550. 6,
  42551. 5,
  42552. 12,
  42553. 9,
  42554. 15,
  42555. 5,
  42556. 11,
  42557. 6,
  42558. 8,
  42559. 13,
  42560. 12,
  42561. 5,
  42562. 12,
  42563. 13,
  42564. 14,
  42565. 11,
  42566. 8,
  42567. 5,
  42568. 6
  42569. ]);
  42570. var _sr = WordArray.create([
  42571. 8,
  42572. 9,
  42573. 9,
  42574. 11,
  42575. 13,
  42576. 15,
  42577. 15,
  42578. 5,
  42579. 7,
  42580. 7,
  42581. 8,
  42582. 11,
  42583. 14,
  42584. 14,
  42585. 12,
  42586. 6,
  42587. 9,
  42588. 13,
  42589. 15,
  42590. 7,
  42591. 12,
  42592. 8,
  42593. 9,
  42594. 11,
  42595. 7,
  42596. 7,
  42597. 12,
  42598. 7,
  42599. 6,
  42600. 15,
  42601. 13,
  42602. 11,
  42603. 9,
  42604. 7,
  42605. 15,
  42606. 11,
  42607. 8,
  42608. 6,
  42609. 6,
  42610. 14,
  42611. 12,
  42612. 13,
  42613. 5,
  42614. 14,
  42615. 13,
  42616. 13,
  42617. 7,
  42618. 5,
  42619. 15,
  42620. 5,
  42621. 8,
  42622. 11,
  42623. 14,
  42624. 14,
  42625. 6,
  42626. 14,
  42627. 6,
  42628. 9,
  42629. 12,
  42630. 9,
  42631. 12,
  42632. 5,
  42633. 15,
  42634. 8,
  42635. 8,
  42636. 5,
  42637. 12,
  42638. 9,
  42639. 12,
  42640. 5,
  42641. 14,
  42642. 6,
  42643. 8,
  42644. 13,
  42645. 6,
  42646. 5,
  42647. 15,
  42648. 13,
  42649. 11,
  42650. 11
  42651. ]);
  42652. var _hl = WordArray.create([0, 1518500249, 1859775393, 2400959708, 2840853838]);
  42653. var _hr = WordArray.create([1352829926, 1548603684, 1836072691, 2053994217, 0]);
  42654. var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
  42655. _doReset: function() {
  42656. this._hash = WordArray.create([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
  42657. },
  42658. _doProcessBlock: function(M2, offset) {
  42659. for (var i2 = 0; i2 < 16; i2++) {
  42660. var offset_i = offset + i2;
  42661. var M_offset_i = M2[offset_i];
  42662. M2[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 16711935 | (M_offset_i << 24 | M_offset_i >>> 8) & 4278255360;
  42663. }
  42664. var H2 = this._hash.words;
  42665. var hl = _hl.words;
  42666. var hr = _hr.words;
  42667. var zl = _zl.words;
  42668. var zr = _zr.words;
  42669. var sl = _sl.words;
  42670. var sr2 = _sr.words;
  42671. var al, bl, cl, dl, el;
  42672. var ar, br, cr, dr, er2;
  42673. ar = al = H2[0];
  42674. br = bl = H2[1];
  42675. cr = cl = H2[2];
  42676. dr = dl = H2[3];
  42677. er2 = el = H2[4];
  42678. var t2;
  42679. for (var i2 = 0; i2 < 80; i2 += 1) {
  42680. t2 = al + M2[offset + zl[i2]] | 0;
  42681. if (i2 < 16) {
  42682. t2 += f1(bl, cl, dl) + hl[0];
  42683. } else if (i2 < 32) {
  42684. t2 += f2(bl, cl, dl) + hl[1];
  42685. } else if (i2 < 48) {
  42686. t2 += f3(bl, cl, dl) + hl[2];
  42687. } else if (i2 < 64) {
  42688. t2 += f4(bl, cl, dl) + hl[3];
  42689. } else {
  42690. t2 += f5(bl, cl, dl) + hl[4];
  42691. }
  42692. t2 = t2 | 0;
  42693. t2 = rotl(t2, sl[i2]);
  42694. t2 = t2 + el | 0;
  42695. al = el;
  42696. el = dl;
  42697. dl = rotl(cl, 10);
  42698. cl = bl;
  42699. bl = t2;
  42700. t2 = ar + M2[offset + zr[i2]] | 0;
  42701. if (i2 < 16) {
  42702. t2 += f5(br, cr, dr) + hr[0];
  42703. } else if (i2 < 32) {
  42704. t2 += f4(br, cr, dr) + hr[1];
  42705. } else if (i2 < 48) {
  42706. t2 += f3(br, cr, dr) + hr[2];
  42707. } else if (i2 < 64) {
  42708. t2 += f2(br, cr, dr) + hr[3];
  42709. } else {
  42710. t2 += f1(br, cr, dr) + hr[4];
  42711. }
  42712. t2 = t2 | 0;
  42713. t2 = rotl(t2, sr2[i2]);
  42714. t2 = t2 + er2 | 0;
  42715. ar = er2;
  42716. er2 = dr;
  42717. dr = rotl(cr, 10);
  42718. cr = br;
  42719. br = t2;
  42720. }
  42721. t2 = H2[1] + cl + dr | 0;
  42722. H2[1] = H2[2] + dl + er2 | 0;
  42723. H2[2] = H2[3] + el + ar | 0;
  42724. H2[3] = H2[4] + al + br | 0;
  42725. H2[4] = H2[0] + bl + cr | 0;
  42726. H2[0] = t2;
  42727. },
  42728. _doFinalize: function() {
  42729. var data = this._data;
  42730. var dataWords = data.words;
  42731. var nBitsTotal = this._nDataBytes * 8;
  42732. var nBitsLeft = data.sigBytes * 8;
  42733. dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  42734. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotal << 8 | nBitsTotal >>> 24) & 16711935 | (nBitsTotal << 24 | nBitsTotal >>> 8) & 4278255360;
  42735. data.sigBytes = (dataWords.length + 1) * 4;
  42736. this._process();
  42737. var hash2 = this._hash;
  42738. var H2 = hash2.words;
  42739. for (var i2 = 0; i2 < 5; i2++) {
  42740. var H_i = H2[i2];
  42741. H2[i2] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360;
  42742. }
  42743. return hash2;
  42744. },
  42745. clone: function() {
  42746. var clone2 = Hasher.clone.call(this);
  42747. clone2._hash = this._hash.clone();
  42748. return clone2;
  42749. }
  42750. });
  42751. function f1(x, y2, z2) {
  42752. return x ^ y2 ^ z2;
  42753. }
  42754. function f2(x, y2, z2) {
  42755. return x & y2 | ~x & z2;
  42756. }
  42757. function f3(x, y2, z2) {
  42758. return (x | ~y2) ^ z2;
  42759. }
  42760. function f4(x, y2, z2) {
  42761. return x & z2 | y2 & ~z2;
  42762. }
  42763. function f5(x, y2, z2) {
  42764. return x ^ (y2 | ~z2);
  42765. }
  42766. function rotl(x, n2) {
  42767. return x << n2 | x >>> 32 - n2;
  42768. }
  42769. C2.RIPEMD160 = Hasher._createHelper(RIPEMD160);
  42770. C2.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
  42771. })();
  42772. return CryptoJS2.RIPEMD160;
  42773. });
  42774. })(ripemd160);
  42775. return ripemd160.exports;
  42776. }
  42777. var hmac = { exports: {} };
  42778. var hasRequiredHmac;
  42779. function requireHmac() {
  42780. if (hasRequiredHmac)
  42781. return hmac.exports;
  42782. hasRequiredHmac = 1;
  42783. (function(module2, exports2) {
  42784. (function(root, factory) {
  42785. {
  42786. module2.exports = factory(requireCore());
  42787. }
  42788. })(commonjsGlobal, function(CryptoJS2) {
  42789. (function() {
  42790. var C2 = CryptoJS2;
  42791. var C_lib = C2.lib;
  42792. var Base = C_lib.Base;
  42793. var C_enc = C2.enc;
  42794. var Utf8 = C_enc.Utf8;
  42795. var C_algo = C2.algo;
  42796. C_algo.HMAC = Base.extend({
  42797. /**
  42798. * Initializes a newly created HMAC.
  42799. *
  42800. * @param {Hasher} hasher The hash algorithm to use.
  42801. * @param {WordArray|string} key The secret key.
  42802. *
  42803. * @example
  42804. *
  42805. * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
  42806. */
  42807. init: function(hasher, key) {
  42808. hasher = this._hasher = new hasher.init();
  42809. if (typeof key == "string") {
  42810. key = Utf8.parse(key);
  42811. }
  42812. var hasherBlockSize = hasher.blockSize;
  42813. var hasherBlockSizeBytes = hasherBlockSize * 4;
  42814. if (key.sigBytes > hasherBlockSizeBytes) {
  42815. key = hasher.finalize(key);
  42816. }
  42817. key.clamp();
  42818. var oKey = this._oKey = key.clone();
  42819. var iKey = this._iKey = key.clone();
  42820. var oKeyWords = oKey.words;
  42821. var iKeyWords = iKey.words;
  42822. for (var i2 = 0; i2 < hasherBlockSize; i2++) {
  42823. oKeyWords[i2] ^= 1549556828;
  42824. iKeyWords[i2] ^= 909522486;
  42825. }
  42826. oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
  42827. this.reset();
  42828. },
  42829. /**
  42830. * Resets this HMAC to its initial state.
  42831. *
  42832. * @example
  42833. *
  42834. * hmacHasher.reset();
  42835. */
  42836. reset: function() {
  42837. var hasher = this._hasher;
  42838. hasher.reset();
  42839. hasher.update(this._iKey);
  42840. },
  42841. /**
  42842. * Updates this HMAC with a message.
  42843. *
  42844. * @param {WordArray|string} messageUpdate The message to append.
  42845. *
  42846. * @return {HMAC} This HMAC instance.
  42847. *
  42848. * @example
  42849. *
  42850. * hmacHasher.update('message');
  42851. * hmacHasher.update(wordArray);
  42852. */
  42853. update: function(messageUpdate) {
  42854. this._hasher.update(messageUpdate);
  42855. return this;
  42856. },
  42857. /**
  42858. * Finalizes the HMAC computation.
  42859. * Note that the finalize operation is effectively a destructive, read-once operation.
  42860. *
  42861. * @param {WordArray|string} messageUpdate (Optional) A final message update.
  42862. *
  42863. * @return {WordArray} The HMAC.
  42864. *
  42865. * @example
  42866. *
  42867. * var hmac = hmacHasher.finalize();
  42868. * var hmac = hmacHasher.finalize('message');
  42869. * var hmac = hmacHasher.finalize(wordArray);
  42870. */
  42871. finalize: function(messageUpdate) {
  42872. var hasher = this._hasher;
  42873. var innerHash = hasher.finalize(messageUpdate);
  42874. hasher.reset();
  42875. var hmac2 = hasher.finalize(this._oKey.clone().concat(innerHash));
  42876. return hmac2;
  42877. }
  42878. });
  42879. })();
  42880. });
  42881. })(hmac);
  42882. return hmac.exports;
  42883. }
  42884. var pbkdf2 = { exports: {} };
  42885. var hasRequiredPbkdf2;
  42886. function requirePbkdf2() {
  42887. if (hasRequiredPbkdf2)
  42888. return pbkdf2.exports;
  42889. hasRequiredPbkdf2 = 1;
  42890. (function(module2, exports2) {
  42891. (function(root, factory, undef) {
  42892. {
  42893. module2.exports = factory(requireCore(), requireSha256(), requireHmac());
  42894. }
  42895. })(commonjsGlobal, function(CryptoJS2) {
  42896. (function() {
  42897. var C2 = CryptoJS2;
  42898. var C_lib = C2.lib;
  42899. var Base = C_lib.Base;
  42900. var WordArray = C_lib.WordArray;
  42901. var C_algo = C2.algo;
  42902. var SHA256 = C_algo.SHA256;
  42903. var HMAC = C_algo.HMAC;
  42904. var PBKDF2 = C_algo.PBKDF2 = Base.extend({
  42905. /**
  42906. * Configuration options.
  42907. *
  42908. * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
  42909. * @property {Hasher} hasher The hasher to use. Default: SHA256
  42910. * @property {number} iterations The number of iterations to perform. Default: 250000
  42911. */
  42912. cfg: Base.extend({
  42913. keySize: 128 / 32,
  42914. hasher: SHA256,
  42915. iterations: 25e4
  42916. }),
  42917. /**
  42918. * Initializes a newly created key derivation function.
  42919. *
  42920. * @param {Object} cfg (Optional) The configuration options to use for the derivation.
  42921. *
  42922. * @example
  42923. *
  42924. * var kdf = CryptoJS.algo.PBKDF2.create();
  42925. * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
  42926. * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
  42927. */
  42928. init: function(cfg) {
  42929. this.cfg = this.cfg.extend(cfg);
  42930. },
  42931. /**
  42932. * Computes the Password-Based Key Derivation Function 2.
  42933. *
  42934. * @param {WordArray|string} password The password.
  42935. * @param {WordArray|string} salt A salt.
  42936. *
  42937. * @return {WordArray} The derived key.
  42938. *
  42939. * @example
  42940. *
  42941. * var key = kdf.compute(password, salt);
  42942. */
  42943. compute: function(password, salt) {
  42944. var cfg = this.cfg;
  42945. var hmac2 = HMAC.create(cfg.hasher, password);
  42946. var derivedKey = WordArray.create();
  42947. var blockIndex = WordArray.create([1]);
  42948. var derivedKeyWords = derivedKey.words;
  42949. var blockIndexWords = blockIndex.words;
  42950. var keySize = cfg.keySize;
  42951. var iterations = cfg.iterations;
  42952. while (derivedKeyWords.length < keySize) {
  42953. var block = hmac2.update(salt).finalize(blockIndex);
  42954. hmac2.reset();
  42955. var blockWords = block.words;
  42956. var blockWordsLength = blockWords.length;
  42957. var intermediate = block;
  42958. for (var i2 = 1; i2 < iterations; i2++) {
  42959. intermediate = hmac2.finalize(intermediate);
  42960. hmac2.reset();
  42961. var intermediateWords = intermediate.words;
  42962. for (var j2 = 0; j2 < blockWordsLength; j2++) {
  42963. blockWords[j2] ^= intermediateWords[j2];
  42964. }
  42965. }
  42966. derivedKey.concat(block);
  42967. blockIndexWords[0]++;
  42968. }
  42969. derivedKey.sigBytes = keySize * 4;
  42970. return derivedKey;
  42971. }
  42972. });
  42973. C2.PBKDF2 = function(password, salt, cfg) {
  42974. return PBKDF2.create(cfg).compute(password, salt);
  42975. };
  42976. })();
  42977. return CryptoJS2.PBKDF2;
  42978. });
  42979. })(pbkdf2);
  42980. return pbkdf2.exports;
  42981. }
  42982. var evpkdf = { exports: {} };
  42983. var hasRequiredEvpkdf;
  42984. function requireEvpkdf() {
  42985. if (hasRequiredEvpkdf)
  42986. return evpkdf.exports;
  42987. hasRequiredEvpkdf = 1;
  42988. (function(module2, exports2) {
  42989. (function(root, factory, undef) {
  42990. {
  42991. module2.exports = factory(requireCore(), requireSha1(), requireHmac());
  42992. }
  42993. })(commonjsGlobal, function(CryptoJS2) {
  42994. (function() {
  42995. var C2 = CryptoJS2;
  42996. var C_lib = C2.lib;
  42997. var Base = C_lib.Base;
  42998. var WordArray = C_lib.WordArray;
  42999. var C_algo = C2.algo;
  43000. var MD5 = C_algo.MD5;
  43001. var EvpKDF = C_algo.EvpKDF = Base.extend({
  43002. /**
  43003. * Configuration options.
  43004. *
  43005. * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
  43006. * @property {Hasher} hasher The hash algorithm to use. Default: MD5
  43007. * @property {number} iterations The number of iterations to perform. Default: 1
  43008. */
  43009. cfg: Base.extend({
  43010. keySize: 128 / 32,
  43011. hasher: MD5,
  43012. iterations: 1
  43013. }),
  43014. /**
  43015. * Initializes a newly created key derivation function.
  43016. *
  43017. * @param {Object} cfg (Optional) The configuration options to use for the derivation.
  43018. *
  43019. * @example
  43020. *
  43021. * var kdf = CryptoJS.algo.EvpKDF.create();
  43022. * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
  43023. * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
  43024. */
  43025. init: function(cfg) {
  43026. this.cfg = this.cfg.extend(cfg);
  43027. },
  43028. /**
  43029. * Derives a key from a password.
  43030. *
  43031. * @param {WordArray|string} password The password.
  43032. * @param {WordArray|string} salt A salt.
  43033. *
  43034. * @return {WordArray} The derived key.
  43035. *
  43036. * @example
  43037. *
  43038. * var key = kdf.compute(password, salt);
  43039. */
  43040. compute: function(password, salt) {
  43041. var block;
  43042. var cfg = this.cfg;
  43043. var hasher = cfg.hasher.create();
  43044. var derivedKey = WordArray.create();
  43045. var derivedKeyWords = derivedKey.words;
  43046. var keySize = cfg.keySize;
  43047. var iterations = cfg.iterations;
  43048. while (derivedKeyWords.length < keySize) {
  43049. if (block) {
  43050. hasher.update(block);
  43051. }
  43052. block = hasher.update(password).finalize(salt);
  43053. hasher.reset();
  43054. for (var i2 = 1; i2 < iterations; i2++) {
  43055. block = hasher.finalize(block);
  43056. hasher.reset();
  43057. }
  43058. derivedKey.concat(block);
  43059. }
  43060. derivedKey.sigBytes = keySize * 4;
  43061. return derivedKey;
  43062. }
  43063. });
  43064. C2.EvpKDF = function(password, salt, cfg) {
  43065. return EvpKDF.create(cfg).compute(password, salt);
  43066. };
  43067. })();
  43068. return CryptoJS2.EvpKDF;
  43069. });
  43070. })(evpkdf);
  43071. return evpkdf.exports;
  43072. }
  43073. var cipherCore = { exports: {} };
  43074. var hasRequiredCipherCore;
  43075. function requireCipherCore() {
  43076. if (hasRequiredCipherCore)
  43077. return cipherCore.exports;
  43078. hasRequiredCipherCore = 1;
  43079. (function(module2, exports2) {
  43080. (function(root, factory, undef) {
  43081. {
  43082. module2.exports = factory(requireCore(), requireEvpkdf());
  43083. }
  43084. })(commonjsGlobal, function(CryptoJS2) {
  43085. CryptoJS2.lib.Cipher || function(undefined$1) {
  43086. var C2 = CryptoJS2;
  43087. var C_lib = C2.lib;
  43088. var Base = C_lib.Base;
  43089. var WordArray = C_lib.WordArray;
  43090. var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
  43091. var C_enc = C2.enc;
  43092. C_enc.Utf8;
  43093. var Base64 = C_enc.Base64;
  43094. var C_algo = C2.algo;
  43095. var EvpKDF = C_algo.EvpKDF;
  43096. var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
  43097. /**
  43098. * Configuration options.
  43099. *
  43100. * @property {WordArray} iv The IV to use for this operation.
  43101. */
  43102. cfg: Base.extend(),
  43103. /**
  43104. * Creates this cipher in encryption mode.
  43105. *
  43106. * @param {WordArray} key The key.
  43107. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  43108. *
  43109. * @return {Cipher} A cipher instance.
  43110. *
  43111. * @static
  43112. *
  43113. * @example
  43114. *
  43115. * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
  43116. */
  43117. createEncryptor: function(key, cfg) {
  43118. return this.create(this._ENC_XFORM_MODE, key, cfg);
  43119. },
  43120. /**
  43121. * Creates this cipher in decryption mode.
  43122. *
  43123. * @param {WordArray} key The key.
  43124. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  43125. *
  43126. * @return {Cipher} A cipher instance.
  43127. *
  43128. * @static
  43129. *
  43130. * @example
  43131. *
  43132. * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
  43133. */
  43134. createDecryptor: function(key, cfg) {
  43135. return this.create(this._DEC_XFORM_MODE, key, cfg);
  43136. },
  43137. /**
  43138. * Initializes a newly created cipher.
  43139. *
  43140. * @param {number} xformMode Either the encryption or decryption transormation mode constant.
  43141. * @param {WordArray} key The key.
  43142. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  43143. *
  43144. * @example
  43145. *
  43146. * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
  43147. */
  43148. init: function(xformMode, key, cfg) {
  43149. this.cfg = this.cfg.extend(cfg);
  43150. this._xformMode = xformMode;
  43151. this._key = key;
  43152. this.reset();
  43153. },
  43154. /**
  43155. * Resets this cipher to its initial state.
  43156. *
  43157. * @example
  43158. *
  43159. * cipher.reset();
  43160. */
  43161. reset: function() {
  43162. BufferedBlockAlgorithm.reset.call(this);
  43163. this._doReset();
  43164. },
  43165. /**
  43166. * Adds data to be encrypted or decrypted.
  43167. *
  43168. * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
  43169. *
  43170. * @return {WordArray} The data after processing.
  43171. *
  43172. * @example
  43173. *
  43174. * var encrypted = cipher.process('data');
  43175. * var encrypted = cipher.process(wordArray);
  43176. */
  43177. process: function(dataUpdate) {
  43178. this._append(dataUpdate);
  43179. return this._process();
  43180. },
  43181. /**
  43182. * Finalizes the encryption or decryption process.
  43183. * Note that the finalize operation is effectively a destructive, read-once operation.
  43184. *
  43185. * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
  43186. *
  43187. * @return {WordArray} The data after final processing.
  43188. *
  43189. * @example
  43190. *
  43191. * var encrypted = cipher.finalize();
  43192. * var encrypted = cipher.finalize('data');
  43193. * var encrypted = cipher.finalize(wordArray);
  43194. */
  43195. finalize: function(dataUpdate) {
  43196. if (dataUpdate) {
  43197. this._append(dataUpdate);
  43198. }
  43199. var finalProcessedData = this._doFinalize();
  43200. return finalProcessedData;
  43201. },
  43202. keySize: 128 / 32,
  43203. ivSize: 128 / 32,
  43204. _ENC_XFORM_MODE: 1,
  43205. _DEC_XFORM_MODE: 2,
  43206. /**
  43207. * Creates shortcut functions to a cipher's object interface.
  43208. *
  43209. * @param {Cipher} cipher The cipher to create a helper for.
  43210. *
  43211. * @return {Object} An object with encrypt and decrypt shortcut functions.
  43212. *
  43213. * @static
  43214. *
  43215. * @example
  43216. *
  43217. * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
  43218. */
  43219. _createHelper: /* @__PURE__ */ function() {
  43220. function selectCipherStrategy(key) {
  43221. if (typeof key == "string") {
  43222. return PasswordBasedCipher;
  43223. } else {
  43224. return SerializableCipher;
  43225. }
  43226. }
  43227. return function(cipher) {
  43228. return {
  43229. encrypt: function(message, key, cfg) {
  43230. return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
  43231. },
  43232. decrypt: function(ciphertext, key, cfg) {
  43233. return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
  43234. }
  43235. };
  43236. };
  43237. }()
  43238. });
  43239. C_lib.StreamCipher = Cipher.extend({
  43240. _doFinalize: function() {
  43241. var finalProcessedBlocks = this._process(true);
  43242. return finalProcessedBlocks;
  43243. },
  43244. blockSize: 1
  43245. });
  43246. var C_mode = C2.mode = {};
  43247. var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
  43248. /**
  43249. * Creates this mode for encryption.
  43250. *
  43251. * @param {Cipher} cipher A block cipher instance.
  43252. * @param {Array} iv The IV words.
  43253. *
  43254. * @static
  43255. *
  43256. * @example
  43257. *
  43258. * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
  43259. */
  43260. createEncryptor: function(cipher, iv) {
  43261. return this.Encryptor.create(cipher, iv);
  43262. },
  43263. /**
  43264. * Creates this mode for decryption.
  43265. *
  43266. * @param {Cipher} cipher A block cipher instance.
  43267. * @param {Array} iv The IV words.
  43268. *
  43269. * @static
  43270. *
  43271. * @example
  43272. *
  43273. * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
  43274. */
  43275. createDecryptor: function(cipher, iv) {
  43276. return this.Decryptor.create(cipher, iv);
  43277. },
  43278. /**
  43279. * Initializes a newly created mode.
  43280. *
  43281. * @param {Cipher} cipher A block cipher instance.
  43282. * @param {Array} iv The IV words.
  43283. *
  43284. * @example
  43285. *
  43286. * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
  43287. */
  43288. init: function(cipher, iv) {
  43289. this._cipher = cipher;
  43290. this._iv = iv;
  43291. }
  43292. });
  43293. var CBC = C_mode.CBC = function() {
  43294. var CBC2 = BlockCipherMode.extend();
  43295. CBC2.Encryptor = CBC2.extend({
  43296. /**
  43297. * Processes the data block at offset.
  43298. *
  43299. * @param {Array} words The data words to operate on.
  43300. * @param {number} offset The offset where the block starts.
  43301. *
  43302. * @example
  43303. *
  43304. * mode.processBlock(data.words, offset);
  43305. */
  43306. processBlock: function(words, offset) {
  43307. var cipher = this._cipher;
  43308. var blockSize = cipher.blockSize;
  43309. xorBlock.call(this, words, offset, blockSize);
  43310. cipher.encryptBlock(words, offset);
  43311. this._prevBlock = words.slice(offset, offset + blockSize);
  43312. }
  43313. });
  43314. CBC2.Decryptor = CBC2.extend({
  43315. /**
  43316. * Processes the data block at offset.
  43317. *
  43318. * @param {Array} words The data words to operate on.
  43319. * @param {number} offset The offset where the block starts.
  43320. *
  43321. * @example
  43322. *
  43323. * mode.processBlock(data.words, offset);
  43324. */
  43325. processBlock: function(words, offset) {
  43326. var cipher = this._cipher;
  43327. var blockSize = cipher.blockSize;
  43328. var thisBlock = words.slice(offset, offset + blockSize);
  43329. cipher.decryptBlock(words, offset);
  43330. xorBlock.call(this, words, offset, blockSize);
  43331. this._prevBlock = thisBlock;
  43332. }
  43333. });
  43334. function xorBlock(words, offset, blockSize) {
  43335. var block;
  43336. var iv = this._iv;
  43337. if (iv) {
  43338. block = iv;
  43339. this._iv = undefined$1;
  43340. } else {
  43341. block = this._prevBlock;
  43342. }
  43343. for (var i2 = 0; i2 < blockSize; i2++) {
  43344. words[offset + i2] ^= block[i2];
  43345. }
  43346. }
  43347. return CBC2;
  43348. }();
  43349. var C_pad = C2.pad = {};
  43350. var Pkcs7 = C_pad.Pkcs7 = {
  43351. /**
  43352. * Pads data using the algorithm defined in PKCS #5/7.
  43353. *
  43354. * @param {WordArray} data The data to pad.
  43355. * @param {number} blockSize The multiple that the data should be padded to.
  43356. *
  43357. * @static
  43358. *
  43359. * @example
  43360. *
  43361. * CryptoJS.pad.Pkcs7.pad(wordArray, 4);
  43362. */
  43363. pad: function(data, blockSize) {
  43364. var blockSizeBytes = blockSize * 4;
  43365. var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
  43366. var paddingWord = nPaddingBytes << 24 | nPaddingBytes << 16 | nPaddingBytes << 8 | nPaddingBytes;
  43367. var paddingWords = [];
  43368. for (var i2 = 0; i2 < nPaddingBytes; i2 += 4) {
  43369. paddingWords.push(paddingWord);
  43370. }
  43371. var padding = WordArray.create(paddingWords, nPaddingBytes);
  43372. data.concat(padding);
  43373. },
  43374. /**
  43375. * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
  43376. *
  43377. * @param {WordArray} data The data to unpad.
  43378. *
  43379. * @static
  43380. *
  43381. * @example
  43382. *
  43383. * CryptoJS.pad.Pkcs7.unpad(wordArray);
  43384. */
  43385. unpad: function(data) {
  43386. var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255;
  43387. data.sigBytes -= nPaddingBytes;
  43388. }
  43389. };
  43390. C_lib.BlockCipher = Cipher.extend({
  43391. /**
  43392. * Configuration options.
  43393. *
  43394. * @property {Mode} mode The block mode to use. Default: CBC
  43395. * @property {Padding} padding The padding strategy to use. Default: Pkcs7
  43396. */
  43397. cfg: Cipher.cfg.extend({
  43398. mode: CBC,
  43399. padding: Pkcs7
  43400. }),
  43401. reset: function() {
  43402. var modeCreator;
  43403. Cipher.reset.call(this);
  43404. var cfg = this.cfg;
  43405. var iv = cfg.iv;
  43406. var mode = cfg.mode;
  43407. if (this._xformMode == this._ENC_XFORM_MODE) {
  43408. modeCreator = mode.createEncryptor;
  43409. } else {
  43410. modeCreator = mode.createDecryptor;
  43411. this._minBufferSize = 1;
  43412. }
  43413. if (this._mode && this._mode.__creator == modeCreator) {
  43414. this._mode.init(this, iv && iv.words);
  43415. } else {
  43416. this._mode = modeCreator.call(mode, this, iv && iv.words);
  43417. this._mode.__creator = modeCreator;
  43418. }
  43419. },
  43420. _doProcessBlock: function(words, offset) {
  43421. this._mode.processBlock(words, offset);
  43422. },
  43423. _doFinalize: function() {
  43424. var finalProcessedBlocks;
  43425. var padding = this.cfg.padding;
  43426. if (this._xformMode == this._ENC_XFORM_MODE) {
  43427. padding.pad(this._data, this.blockSize);
  43428. finalProcessedBlocks = this._process(true);
  43429. } else {
  43430. finalProcessedBlocks = this._process(true);
  43431. padding.unpad(finalProcessedBlocks);
  43432. }
  43433. return finalProcessedBlocks;
  43434. },
  43435. blockSize: 128 / 32
  43436. });
  43437. var CipherParams = C_lib.CipherParams = Base.extend({
  43438. /**
  43439. * Initializes a newly created cipher params object.
  43440. *
  43441. * @param {Object} cipherParams An object with any of the possible cipher parameters.
  43442. *
  43443. * @example
  43444. *
  43445. * var cipherParams = CryptoJS.lib.CipherParams.create({
  43446. * ciphertext: ciphertextWordArray,
  43447. * key: keyWordArray,
  43448. * iv: ivWordArray,
  43449. * salt: saltWordArray,
  43450. * algorithm: CryptoJS.algo.AES,
  43451. * mode: CryptoJS.mode.CBC,
  43452. * padding: CryptoJS.pad.PKCS7,
  43453. * blockSize: 4,
  43454. * formatter: CryptoJS.format.OpenSSL
  43455. * });
  43456. */
  43457. init: function(cipherParams) {
  43458. this.mixIn(cipherParams);
  43459. },
  43460. /**
  43461. * Converts this cipher params object to a string.
  43462. *
  43463. * @param {Format} formatter (Optional) The formatting strategy to use.
  43464. *
  43465. * @return {string} The stringified cipher params.
  43466. *
  43467. * @throws Error If neither the formatter nor the default formatter is set.
  43468. *
  43469. * @example
  43470. *
  43471. * var string = cipherParams + '';
  43472. * var string = cipherParams.toString();
  43473. * var string = cipherParams.toString(CryptoJS.format.OpenSSL);
  43474. */
  43475. toString: function(formatter) {
  43476. return (formatter || this.formatter).stringify(this);
  43477. }
  43478. });
  43479. var C_format = C2.format = {};
  43480. var OpenSSLFormatter = C_format.OpenSSL = {
  43481. /**
  43482. * Converts a cipher params object to an OpenSSL-compatible string.
  43483. *
  43484. * @param {CipherParams} cipherParams The cipher params object.
  43485. *
  43486. * @return {string} The OpenSSL-compatible string.
  43487. *
  43488. * @static
  43489. *
  43490. * @example
  43491. *
  43492. * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
  43493. */
  43494. stringify: function(cipherParams) {
  43495. var wordArray;
  43496. var ciphertext = cipherParams.ciphertext;
  43497. var salt = cipherParams.salt;
  43498. if (salt) {
  43499. wordArray = WordArray.create([1398893684, 1701076831]).concat(salt).concat(ciphertext);
  43500. } else {
  43501. wordArray = ciphertext;
  43502. }
  43503. return wordArray.toString(Base64);
  43504. },
  43505. /**
  43506. * Converts an OpenSSL-compatible string to a cipher params object.
  43507. *
  43508. * @param {string} openSSLStr The OpenSSL-compatible string.
  43509. *
  43510. * @return {CipherParams} The cipher params object.
  43511. *
  43512. * @static
  43513. *
  43514. * @example
  43515. *
  43516. * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
  43517. */
  43518. parse: function(openSSLStr) {
  43519. var salt;
  43520. var ciphertext = Base64.parse(openSSLStr);
  43521. var ciphertextWords = ciphertext.words;
  43522. if (ciphertextWords[0] == 1398893684 && ciphertextWords[1] == 1701076831) {
  43523. salt = WordArray.create(ciphertextWords.slice(2, 4));
  43524. ciphertextWords.splice(0, 4);
  43525. ciphertext.sigBytes -= 16;
  43526. }
  43527. return CipherParams.create({ ciphertext, salt });
  43528. }
  43529. };
  43530. var SerializableCipher = C_lib.SerializableCipher = Base.extend({
  43531. /**
  43532. * Configuration options.
  43533. *
  43534. * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
  43535. */
  43536. cfg: Base.extend({
  43537. format: OpenSSLFormatter
  43538. }),
  43539. /**
  43540. * Encrypts a message.
  43541. *
  43542. * @param {Cipher} cipher The cipher algorithm to use.
  43543. * @param {WordArray|string} message The message to encrypt.
  43544. * @param {WordArray} key The key.
  43545. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  43546. *
  43547. * @return {CipherParams} A cipher params object.
  43548. *
  43549. * @static
  43550. *
  43551. * @example
  43552. *
  43553. * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
  43554. * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
  43555. * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
  43556. */
  43557. encrypt: function(cipher, message, key, cfg) {
  43558. cfg = this.cfg.extend(cfg);
  43559. var encryptor = cipher.createEncryptor(key, cfg);
  43560. var ciphertext = encryptor.finalize(message);
  43561. var cipherCfg = encryptor.cfg;
  43562. return CipherParams.create({
  43563. ciphertext,
  43564. key,
  43565. iv: cipherCfg.iv,
  43566. algorithm: cipher,
  43567. mode: cipherCfg.mode,
  43568. padding: cipherCfg.padding,
  43569. blockSize: cipher.blockSize,
  43570. formatter: cfg.format
  43571. });
  43572. },
  43573. /**
  43574. * Decrypts serialized ciphertext.
  43575. *
  43576. * @param {Cipher} cipher The cipher algorithm to use.
  43577. * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
  43578. * @param {WordArray} key The key.
  43579. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  43580. *
  43581. * @return {WordArray} The plaintext.
  43582. *
  43583. * @static
  43584. *
  43585. * @example
  43586. *
  43587. * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
  43588. * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
  43589. */
  43590. decrypt: function(cipher, ciphertext, key, cfg) {
  43591. cfg = this.cfg.extend(cfg);
  43592. ciphertext = this._parse(ciphertext, cfg.format);
  43593. var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
  43594. return plaintext;
  43595. },
  43596. /**
  43597. * Converts serialized ciphertext to CipherParams,
  43598. * else assumed CipherParams already and returns ciphertext unchanged.
  43599. *
  43600. * @param {CipherParams|string} ciphertext The ciphertext.
  43601. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
  43602. *
  43603. * @return {CipherParams} The unserialized ciphertext.
  43604. *
  43605. * @static
  43606. *
  43607. * @example
  43608. *
  43609. * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
  43610. */
  43611. _parse: function(ciphertext, format2) {
  43612. if (typeof ciphertext == "string") {
  43613. return format2.parse(ciphertext, this);
  43614. } else {
  43615. return ciphertext;
  43616. }
  43617. }
  43618. });
  43619. var C_kdf = C2.kdf = {};
  43620. var OpenSSLKdf = C_kdf.OpenSSL = {
  43621. /**
  43622. * Derives a key and IV from a password.
  43623. *
  43624. * @param {string} password The password to derive from.
  43625. * @param {number} keySize The size in words of the key to generate.
  43626. * @param {number} ivSize The size in words of the IV to generate.
  43627. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
  43628. *
  43629. * @return {CipherParams} A cipher params object with the key, IV, and salt.
  43630. *
  43631. * @static
  43632. *
  43633. * @example
  43634. *
  43635. * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
  43636. * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
  43637. */
  43638. execute: function(password, keySize, ivSize, salt, hasher) {
  43639. if (!salt) {
  43640. salt = WordArray.random(64 / 8);
  43641. }
  43642. if (!hasher) {
  43643. var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
  43644. } else {
  43645. var key = EvpKDF.create({ keySize: keySize + ivSize, hasher }).compute(password, salt);
  43646. }
  43647. var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
  43648. key.sigBytes = keySize * 4;
  43649. return CipherParams.create({ key, iv, salt });
  43650. }
  43651. };
  43652. var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
  43653. /**
  43654. * Configuration options.
  43655. *
  43656. * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
  43657. */
  43658. cfg: SerializableCipher.cfg.extend({
  43659. kdf: OpenSSLKdf
  43660. }),
  43661. /**
  43662. * Encrypts a message using a password.
  43663. *
  43664. * @param {Cipher} cipher The cipher algorithm to use.
  43665. * @param {WordArray|string} message The message to encrypt.
  43666. * @param {string} password The password.
  43667. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  43668. *
  43669. * @return {CipherParams} A cipher params object.
  43670. *
  43671. * @static
  43672. *
  43673. * @example
  43674. *
  43675. * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
  43676. * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
  43677. */
  43678. encrypt: function(cipher, message, password, cfg) {
  43679. cfg = this.cfg.extend(cfg);
  43680. var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, cfg.salt, cfg.hasher);
  43681. cfg.iv = derivedParams.iv;
  43682. var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
  43683. ciphertext.mixIn(derivedParams);
  43684. return ciphertext;
  43685. },
  43686. /**
  43687. * Decrypts serialized ciphertext using a password.
  43688. *
  43689. * @param {Cipher} cipher The cipher algorithm to use.
  43690. * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
  43691. * @param {string} password The password.
  43692. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  43693. *
  43694. * @return {WordArray} The plaintext.
  43695. *
  43696. * @static
  43697. *
  43698. * @example
  43699. *
  43700. * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
  43701. * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
  43702. */
  43703. decrypt: function(cipher, ciphertext, password, cfg) {
  43704. cfg = this.cfg.extend(cfg);
  43705. ciphertext = this._parse(ciphertext, cfg.format);
  43706. var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt, cfg.hasher);
  43707. cfg.iv = derivedParams.iv;
  43708. var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
  43709. return plaintext;
  43710. }
  43711. });
  43712. }();
  43713. });
  43714. })(cipherCore);
  43715. return cipherCore.exports;
  43716. }
  43717. var modeCfb = { exports: {} };
  43718. var hasRequiredModeCfb;
  43719. function requireModeCfb() {
  43720. if (hasRequiredModeCfb)
  43721. return modeCfb.exports;
  43722. hasRequiredModeCfb = 1;
  43723. (function(module2, exports2) {
  43724. (function(root, factory, undef) {
  43725. {
  43726. module2.exports = factory(requireCore(), requireCipherCore());
  43727. }
  43728. })(commonjsGlobal, function(CryptoJS2) {
  43729. CryptoJS2.mode.CFB = function() {
  43730. var CFB = CryptoJS2.lib.BlockCipherMode.extend();
  43731. CFB.Encryptor = CFB.extend({
  43732. processBlock: function(words, offset) {
  43733. var cipher = this._cipher;
  43734. var blockSize = cipher.blockSize;
  43735. generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
  43736. this._prevBlock = words.slice(offset, offset + blockSize);
  43737. }
  43738. });
  43739. CFB.Decryptor = CFB.extend({
  43740. processBlock: function(words, offset) {
  43741. var cipher = this._cipher;
  43742. var blockSize = cipher.blockSize;
  43743. var thisBlock = words.slice(offset, offset + blockSize);
  43744. generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
  43745. this._prevBlock = thisBlock;
  43746. }
  43747. });
  43748. function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
  43749. var keystream;
  43750. var iv = this._iv;
  43751. if (iv) {
  43752. keystream = iv.slice(0);
  43753. this._iv = void 0;
  43754. } else {
  43755. keystream = this._prevBlock;
  43756. }
  43757. cipher.encryptBlock(keystream, 0);
  43758. for (var i2 = 0; i2 < blockSize; i2++) {
  43759. words[offset + i2] ^= keystream[i2];
  43760. }
  43761. }
  43762. return CFB;
  43763. }();
  43764. return CryptoJS2.mode.CFB;
  43765. });
  43766. })(modeCfb);
  43767. return modeCfb.exports;
  43768. }
  43769. var modeCtr = { exports: {} };
  43770. var hasRequiredModeCtr;
  43771. function requireModeCtr() {
  43772. if (hasRequiredModeCtr)
  43773. return modeCtr.exports;
  43774. hasRequiredModeCtr = 1;
  43775. (function(module2, exports2) {
  43776. (function(root, factory, undef) {
  43777. {
  43778. module2.exports = factory(requireCore(), requireCipherCore());
  43779. }
  43780. })(commonjsGlobal, function(CryptoJS2) {
  43781. CryptoJS2.mode.CTR = function() {
  43782. var CTR = CryptoJS2.lib.BlockCipherMode.extend();
  43783. var Encryptor = CTR.Encryptor = CTR.extend({
  43784. processBlock: function(words, offset) {
  43785. var cipher = this._cipher;
  43786. var blockSize = cipher.blockSize;
  43787. var iv = this._iv;
  43788. var counter = this._counter;
  43789. if (iv) {
  43790. counter = this._counter = iv.slice(0);
  43791. this._iv = void 0;
  43792. }
  43793. var keystream = counter.slice(0);
  43794. cipher.encryptBlock(keystream, 0);
  43795. counter[blockSize - 1] = counter[blockSize - 1] + 1 | 0;
  43796. for (var i2 = 0; i2 < blockSize; i2++) {
  43797. words[offset + i2] ^= keystream[i2];
  43798. }
  43799. }
  43800. });
  43801. CTR.Decryptor = Encryptor;
  43802. return CTR;
  43803. }();
  43804. return CryptoJS2.mode.CTR;
  43805. });
  43806. })(modeCtr);
  43807. return modeCtr.exports;
  43808. }
  43809. var modeCtrGladman = { exports: {} };
  43810. var hasRequiredModeCtrGladman;
  43811. function requireModeCtrGladman() {
  43812. if (hasRequiredModeCtrGladman)
  43813. return modeCtrGladman.exports;
  43814. hasRequiredModeCtrGladman = 1;
  43815. (function(module2, exports2) {
  43816. (function(root, factory, undef) {
  43817. {
  43818. module2.exports = factory(requireCore(), requireCipherCore());
  43819. }
  43820. })(commonjsGlobal, function(CryptoJS2) {
  43821. /** @preserve
  43822. * Counter block mode compatible with Dr Brian Gladman fileenc.c
  43823. * derived from CryptoJS.mode.CTR
  43824. * Jan Hruby jhruby.web@gmail.com
  43825. */
  43826. CryptoJS2.mode.CTRGladman = function() {
  43827. var CTRGladman = CryptoJS2.lib.BlockCipherMode.extend();
  43828. function incWord(word) {
  43829. if ((word >> 24 & 255) === 255) {
  43830. var b1 = word >> 16 & 255;
  43831. var b2 = word >> 8 & 255;
  43832. var b3 = word & 255;
  43833. if (b1 === 255) {
  43834. b1 = 0;
  43835. if (b2 === 255) {
  43836. b2 = 0;
  43837. if (b3 === 255) {
  43838. b3 = 0;
  43839. } else {
  43840. ++b3;
  43841. }
  43842. } else {
  43843. ++b2;
  43844. }
  43845. } else {
  43846. ++b1;
  43847. }
  43848. word = 0;
  43849. word += b1 << 16;
  43850. word += b2 << 8;
  43851. word += b3;
  43852. } else {
  43853. word += 1 << 24;
  43854. }
  43855. return word;
  43856. }
  43857. function incCounter(counter) {
  43858. if ((counter[0] = incWord(counter[0])) === 0) {
  43859. counter[1] = incWord(counter[1]);
  43860. }
  43861. return counter;
  43862. }
  43863. var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
  43864. processBlock: function(words, offset) {
  43865. var cipher = this._cipher;
  43866. var blockSize = cipher.blockSize;
  43867. var iv = this._iv;
  43868. var counter = this._counter;
  43869. if (iv) {
  43870. counter = this._counter = iv.slice(0);
  43871. this._iv = void 0;
  43872. }
  43873. incCounter(counter);
  43874. var keystream = counter.slice(0);
  43875. cipher.encryptBlock(keystream, 0);
  43876. for (var i2 = 0; i2 < blockSize; i2++) {
  43877. words[offset + i2] ^= keystream[i2];
  43878. }
  43879. }
  43880. });
  43881. CTRGladman.Decryptor = Encryptor;
  43882. return CTRGladman;
  43883. }();
  43884. return CryptoJS2.mode.CTRGladman;
  43885. });
  43886. })(modeCtrGladman);
  43887. return modeCtrGladman.exports;
  43888. }
  43889. var modeOfb = { exports: {} };
  43890. var hasRequiredModeOfb;
  43891. function requireModeOfb() {
  43892. if (hasRequiredModeOfb)
  43893. return modeOfb.exports;
  43894. hasRequiredModeOfb = 1;
  43895. (function(module2, exports2) {
  43896. (function(root, factory, undef) {
  43897. {
  43898. module2.exports = factory(requireCore(), requireCipherCore());
  43899. }
  43900. })(commonjsGlobal, function(CryptoJS2) {
  43901. CryptoJS2.mode.OFB = function() {
  43902. var OFB = CryptoJS2.lib.BlockCipherMode.extend();
  43903. var Encryptor = OFB.Encryptor = OFB.extend({
  43904. processBlock: function(words, offset) {
  43905. var cipher = this._cipher;
  43906. var blockSize = cipher.blockSize;
  43907. var iv = this._iv;
  43908. var keystream = this._keystream;
  43909. if (iv) {
  43910. keystream = this._keystream = iv.slice(0);
  43911. this._iv = void 0;
  43912. }
  43913. cipher.encryptBlock(keystream, 0);
  43914. for (var i2 = 0; i2 < blockSize; i2++) {
  43915. words[offset + i2] ^= keystream[i2];
  43916. }
  43917. }
  43918. });
  43919. OFB.Decryptor = Encryptor;
  43920. return OFB;
  43921. }();
  43922. return CryptoJS2.mode.OFB;
  43923. });
  43924. })(modeOfb);
  43925. return modeOfb.exports;
  43926. }
  43927. var modeEcb = { exports: {} };
  43928. var hasRequiredModeEcb;
  43929. function requireModeEcb() {
  43930. if (hasRequiredModeEcb)
  43931. return modeEcb.exports;
  43932. hasRequiredModeEcb = 1;
  43933. (function(module2, exports2) {
  43934. (function(root, factory, undef) {
  43935. {
  43936. module2.exports = factory(requireCore(), requireCipherCore());
  43937. }
  43938. })(commonjsGlobal, function(CryptoJS2) {
  43939. CryptoJS2.mode.ECB = function() {
  43940. var ECB = CryptoJS2.lib.BlockCipherMode.extend();
  43941. ECB.Encryptor = ECB.extend({
  43942. processBlock: function(words, offset) {
  43943. this._cipher.encryptBlock(words, offset);
  43944. }
  43945. });
  43946. ECB.Decryptor = ECB.extend({
  43947. processBlock: function(words, offset) {
  43948. this._cipher.decryptBlock(words, offset);
  43949. }
  43950. });
  43951. return ECB;
  43952. }();
  43953. return CryptoJS2.mode.ECB;
  43954. });
  43955. })(modeEcb);
  43956. return modeEcb.exports;
  43957. }
  43958. var padAnsix923 = { exports: {} };
  43959. var hasRequiredPadAnsix923;
  43960. function requirePadAnsix923() {
  43961. if (hasRequiredPadAnsix923)
  43962. return padAnsix923.exports;
  43963. hasRequiredPadAnsix923 = 1;
  43964. (function(module2, exports2) {
  43965. (function(root, factory, undef) {
  43966. {
  43967. module2.exports = factory(requireCore(), requireCipherCore());
  43968. }
  43969. })(commonjsGlobal, function(CryptoJS2) {
  43970. CryptoJS2.pad.AnsiX923 = {
  43971. pad: function(data, blockSize) {
  43972. var dataSigBytes = data.sigBytes;
  43973. var blockSizeBytes = blockSize * 4;
  43974. var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
  43975. var lastBytePos = dataSigBytes + nPaddingBytes - 1;
  43976. data.clamp();
  43977. data.words[lastBytePos >>> 2] |= nPaddingBytes << 24 - lastBytePos % 4 * 8;
  43978. data.sigBytes += nPaddingBytes;
  43979. },
  43980. unpad: function(data) {
  43981. var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255;
  43982. data.sigBytes -= nPaddingBytes;
  43983. }
  43984. };
  43985. return CryptoJS2.pad.Ansix923;
  43986. });
  43987. })(padAnsix923);
  43988. return padAnsix923.exports;
  43989. }
  43990. var padIso10126 = { exports: {} };
  43991. var hasRequiredPadIso10126;
  43992. function requirePadIso10126() {
  43993. if (hasRequiredPadIso10126)
  43994. return padIso10126.exports;
  43995. hasRequiredPadIso10126 = 1;
  43996. (function(module2, exports2) {
  43997. (function(root, factory, undef) {
  43998. {
  43999. module2.exports = factory(requireCore(), requireCipherCore());
  44000. }
  44001. })(commonjsGlobal, function(CryptoJS2) {
  44002. CryptoJS2.pad.Iso10126 = {
  44003. pad: function(data, blockSize) {
  44004. var blockSizeBytes = blockSize * 4;
  44005. var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
  44006. data.concat(CryptoJS2.lib.WordArray.random(nPaddingBytes - 1)).concat(CryptoJS2.lib.WordArray.create([nPaddingBytes << 24], 1));
  44007. },
  44008. unpad: function(data) {
  44009. var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255;
  44010. data.sigBytes -= nPaddingBytes;
  44011. }
  44012. };
  44013. return CryptoJS2.pad.Iso10126;
  44014. });
  44015. })(padIso10126);
  44016. return padIso10126.exports;
  44017. }
  44018. var padIso97971 = { exports: {} };
  44019. var hasRequiredPadIso97971;
  44020. function requirePadIso97971() {
  44021. if (hasRequiredPadIso97971)
  44022. return padIso97971.exports;
  44023. hasRequiredPadIso97971 = 1;
  44024. (function(module2, exports2) {
  44025. (function(root, factory, undef) {
  44026. {
  44027. module2.exports = factory(requireCore(), requireCipherCore());
  44028. }
  44029. })(commonjsGlobal, function(CryptoJS2) {
  44030. CryptoJS2.pad.Iso97971 = {
  44031. pad: function(data, blockSize) {
  44032. data.concat(CryptoJS2.lib.WordArray.create([2147483648], 1));
  44033. CryptoJS2.pad.ZeroPadding.pad(data, blockSize);
  44034. },
  44035. unpad: function(data) {
  44036. CryptoJS2.pad.ZeroPadding.unpad(data);
  44037. data.sigBytes--;
  44038. }
  44039. };
  44040. return CryptoJS2.pad.Iso97971;
  44041. });
  44042. })(padIso97971);
  44043. return padIso97971.exports;
  44044. }
  44045. var padZeropadding = { exports: {} };
  44046. var hasRequiredPadZeropadding;
  44047. function requirePadZeropadding() {
  44048. if (hasRequiredPadZeropadding)
  44049. return padZeropadding.exports;
  44050. hasRequiredPadZeropadding = 1;
  44051. (function(module2, exports2) {
  44052. (function(root, factory, undef) {
  44053. {
  44054. module2.exports = factory(requireCore(), requireCipherCore());
  44055. }
  44056. })(commonjsGlobal, function(CryptoJS2) {
  44057. CryptoJS2.pad.ZeroPadding = {
  44058. pad: function(data, blockSize) {
  44059. var blockSizeBytes = blockSize * 4;
  44060. data.clamp();
  44061. data.sigBytes += blockSizeBytes - (data.sigBytes % blockSizeBytes || blockSizeBytes);
  44062. },
  44063. unpad: function(data) {
  44064. var dataWords = data.words;
  44065. var i2 = data.sigBytes - 1;
  44066. for (var i2 = data.sigBytes - 1; i2 >= 0; i2--) {
  44067. if (dataWords[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255) {
  44068. data.sigBytes = i2 + 1;
  44069. break;
  44070. }
  44071. }
  44072. }
  44073. };
  44074. return CryptoJS2.pad.ZeroPadding;
  44075. });
  44076. })(padZeropadding);
  44077. return padZeropadding.exports;
  44078. }
  44079. var padNopadding = { exports: {} };
  44080. var hasRequiredPadNopadding;
  44081. function requirePadNopadding() {
  44082. if (hasRequiredPadNopadding)
  44083. return padNopadding.exports;
  44084. hasRequiredPadNopadding = 1;
  44085. (function(module2, exports2) {
  44086. (function(root, factory, undef) {
  44087. {
  44088. module2.exports = factory(requireCore(), requireCipherCore());
  44089. }
  44090. })(commonjsGlobal, function(CryptoJS2) {
  44091. CryptoJS2.pad.NoPadding = {
  44092. pad: function() {
  44093. },
  44094. unpad: function() {
  44095. }
  44096. };
  44097. return CryptoJS2.pad.NoPadding;
  44098. });
  44099. })(padNopadding);
  44100. return padNopadding.exports;
  44101. }
  44102. var formatHex = { exports: {} };
  44103. var hasRequiredFormatHex;
  44104. function requireFormatHex() {
  44105. if (hasRequiredFormatHex)
  44106. return formatHex.exports;
  44107. hasRequiredFormatHex = 1;
  44108. (function(module2, exports2) {
  44109. (function(root, factory, undef) {
  44110. {
  44111. module2.exports = factory(requireCore(), requireCipherCore());
  44112. }
  44113. })(commonjsGlobal, function(CryptoJS2) {
  44114. (function(undefined$1) {
  44115. var C2 = CryptoJS2;
  44116. var C_lib = C2.lib;
  44117. var CipherParams = C_lib.CipherParams;
  44118. var C_enc = C2.enc;
  44119. var Hex2 = C_enc.Hex;
  44120. var C_format = C2.format;
  44121. C_format.Hex = {
  44122. /**
  44123. * Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
  44124. *
  44125. * @param {CipherParams} cipherParams The cipher params object.
  44126. *
  44127. * @return {string} The hexadecimally encoded string.
  44128. *
  44129. * @static
  44130. *
  44131. * @example
  44132. *
  44133. * var hexString = CryptoJS.format.Hex.stringify(cipherParams);
  44134. */
  44135. stringify: function(cipherParams) {
  44136. return cipherParams.ciphertext.toString(Hex2);
  44137. },
  44138. /**
  44139. * Converts a hexadecimally encoded ciphertext string to a cipher params object.
  44140. *
  44141. * @param {string} input The hexadecimally encoded string.
  44142. *
  44143. * @return {CipherParams} The cipher params object.
  44144. *
  44145. * @static
  44146. *
  44147. * @example
  44148. *
  44149. * var cipherParams = CryptoJS.format.Hex.parse(hexString);
  44150. */
  44151. parse: function(input) {
  44152. var ciphertext = Hex2.parse(input);
  44153. return CipherParams.create({ ciphertext });
  44154. }
  44155. };
  44156. })();
  44157. return CryptoJS2.format.Hex;
  44158. });
  44159. })(formatHex);
  44160. return formatHex.exports;
  44161. }
  44162. var aes = { exports: {} };
  44163. var hasRequiredAes;
  44164. function requireAes() {
  44165. if (hasRequiredAes)
  44166. return aes.exports;
  44167. hasRequiredAes = 1;
  44168. (function(module2, exports2) {
  44169. (function(root, factory, undef) {
  44170. {
  44171. module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  44172. }
  44173. })(commonjsGlobal, function(CryptoJS2) {
  44174. (function() {
  44175. var C2 = CryptoJS2;
  44176. var C_lib = C2.lib;
  44177. var BlockCipher = C_lib.BlockCipher;
  44178. var C_algo = C2.algo;
  44179. var SBOX = [];
  44180. var INV_SBOX = [];
  44181. var SUB_MIX_0 = [];
  44182. var SUB_MIX_1 = [];
  44183. var SUB_MIX_2 = [];
  44184. var SUB_MIX_3 = [];
  44185. var INV_SUB_MIX_0 = [];
  44186. var INV_SUB_MIX_1 = [];
  44187. var INV_SUB_MIX_2 = [];
  44188. var INV_SUB_MIX_3 = [];
  44189. (function() {
  44190. var d2 = [];
  44191. for (var i2 = 0; i2 < 256; i2++) {
  44192. if (i2 < 128) {
  44193. d2[i2] = i2 << 1;
  44194. } else {
  44195. d2[i2] = i2 << 1 ^ 283;
  44196. }
  44197. }
  44198. var x = 0;
  44199. var xi = 0;
  44200. for (var i2 = 0; i2 < 256; i2++) {
  44201. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  44202. sx = sx >>> 8 ^ sx & 255 ^ 99;
  44203. SBOX[x] = sx;
  44204. INV_SBOX[sx] = x;
  44205. var x2 = d2[x];
  44206. var x4 = d2[x2];
  44207. var x8 = d2[x4];
  44208. var t2 = d2[sx] * 257 ^ sx * 16843008;
  44209. SUB_MIX_0[x] = t2 << 24 | t2 >>> 8;
  44210. SUB_MIX_1[x] = t2 << 16 | t2 >>> 16;
  44211. SUB_MIX_2[x] = t2 << 8 | t2 >>> 24;
  44212. SUB_MIX_3[x] = t2;
  44213. var t2 = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008;
  44214. INV_SUB_MIX_0[sx] = t2 << 24 | t2 >>> 8;
  44215. INV_SUB_MIX_1[sx] = t2 << 16 | t2 >>> 16;
  44216. INV_SUB_MIX_2[sx] = t2 << 8 | t2 >>> 24;
  44217. INV_SUB_MIX_3[sx] = t2;
  44218. if (!x) {
  44219. x = xi = 1;
  44220. } else {
  44221. x = x2 ^ d2[d2[d2[x8 ^ x2]]];
  44222. xi ^= d2[d2[xi]];
  44223. }
  44224. }
  44225. })();
  44226. var RCON = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
  44227. var AES = C_algo.AES = BlockCipher.extend({
  44228. _doReset: function() {
  44229. var t2;
  44230. if (this._nRounds && this._keyPriorReset === this._key) {
  44231. return;
  44232. }
  44233. var key = this._keyPriorReset = this._key;
  44234. var keyWords = key.words;
  44235. var keySize = key.sigBytes / 4;
  44236. var nRounds = this._nRounds = keySize + 6;
  44237. var ksRows = (nRounds + 1) * 4;
  44238. var keySchedule = this._keySchedule = [];
  44239. for (var ksRow = 0; ksRow < ksRows; ksRow++) {
  44240. if (ksRow < keySize) {
  44241. keySchedule[ksRow] = keyWords[ksRow];
  44242. } else {
  44243. t2 = keySchedule[ksRow - 1];
  44244. if (!(ksRow % keySize)) {
  44245. t2 = t2 << 8 | t2 >>> 24;
  44246. t2 = SBOX[t2 >>> 24] << 24 | SBOX[t2 >>> 16 & 255] << 16 | SBOX[t2 >>> 8 & 255] << 8 | SBOX[t2 & 255];
  44247. t2 ^= RCON[ksRow / keySize | 0] << 24;
  44248. } else if (keySize > 6 && ksRow % keySize == 4) {
  44249. t2 = SBOX[t2 >>> 24] << 24 | SBOX[t2 >>> 16 & 255] << 16 | SBOX[t2 >>> 8 & 255] << 8 | SBOX[t2 & 255];
  44250. }
  44251. keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t2;
  44252. }
  44253. }
  44254. var invKeySchedule = this._invKeySchedule = [];
  44255. for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  44256. var ksRow = ksRows - invKsRow;
  44257. if (invKsRow % 4) {
  44258. var t2 = keySchedule[ksRow];
  44259. } else {
  44260. var t2 = keySchedule[ksRow - 4];
  44261. }
  44262. if (invKsRow < 4 || ksRow <= 4) {
  44263. invKeySchedule[invKsRow] = t2;
  44264. } else {
  44265. invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t2 >>> 24]] ^ INV_SUB_MIX_1[SBOX[t2 >>> 16 & 255]] ^ INV_SUB_MIX_2[SBOX[t2 >>> 8 & 255]] ^ INV_SUB_MIX_3[SBOX[t2 & 255]];
  44266. }
  44267. }
  44268. },
  44269. encryptBlock: function(M2, offset) {
  44270. this._doCryptBlock(M2, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
  44271. },
  44272. decryptBlock: function(M2, offset) {
  44273. var t2 = M2[offset + 1];
  44274. M2[offset + 1] = M2[offset + 3];
  44275. M2[offset + 3] = t2;
  44276. this._doCryptBlock(M2, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
  44277. var t2 = M2[offset + 1];
  44278. M2[offset + 1] = M2[offset + 3];
  44279. M2[offset + 3] = t2;
  44280. },
  44281. _doCryptBlock: function(M2, offset, keySchedule, SUB_MIX_02, SUB_MIX_12, SUB_MIX_22, SUB_MIX_32, SBOX2) {
  44282. var nRounds = this._nRounds;
  44283. var s0 = M2[offset] ^ keySchedule[0];
  44284. var s1 = M2[offset + 1] ^ keySchedule[1];
  44285. var s2 = M2[offset + 2] ^ keySchedule[2];
  44286. var s3 = M2[offset + 3] ^ keySchedule[3];
  44287. var ksRow = 4;
  44288. for (var round = 1; round < nRounds; round++) {
  44289. var t0 = SUB_MIX_02[s0 >>> 24] ^ SUB_MIX_12[s1 >>> 16 & 255] ^ SUB_MIX_22[s2 >>> 8 & 255] ^ SUB_MIX_32[s3 & 255] ^ keySchedule[ksRow++];
  44290. var t1 = SUB_MIX_02[s1 >>> 24] ^ SUB_MIX_12[s2 >>> 16 & 255] ^ SUB_MIX_22[s3 >>> 8 & 255] ^ SUB_MIX_32[s0 & 255] ^ keySchedule[ksRow++];
  44291. var t2 = SUB_MIX_02[s2 >>> 24] ^ SUB_MIX_12[s3 >>> 16 & 255] ^ SUB_MIX_22[s0 >>> 8 & 255] ^ SUB_MIX_32[s1 & 255] ^ keySchedule[ksRow++];
  44292. var t3 = SUB_MIX_02[s3 >>> 24] ^ SUB_MIX_12[s0 >>> 16 & 255] ^ SUB_MIX_22[s1 >>> 8 & 255] ^ SUB_MIX_32[s2 & 255] ^ keySchedule[ksRow++];
  44293. s0 = t0;
  44294. s1 = t1;
  44295. s2 = t2;
  44296. s3 = t3;
  44297. }
  44298. var t0 = (SBOX2[s0 >>> 24] << 24 | SBOX2[s1 >>> 16 & 255] << 16 | SBOX2[s2 >>> 8 & 255] << 8 | SBOX2[s3 & 255]) ^ keySchedule[ksRow++];
  44299. var t1 = (SBOX2[s1 >>> 24] << 24 | SBOX2[s2 >>> 16 & 255] << 16 | SBOX2[s3 >>> 8 & 255] << 8 | SBOX2[s0 & 255]) ^ keySchedule[ksRow++];
  44300. var t2 = (SBOX2[s2 >>> 24] << 24 | SBOX2[s3 >>> 16 & 255] << 16 | SBOX2[s0 >>> 8 & 255] << 8 | SBOX2[s1 & 255]) ^ keySchedule[ksRow++];
  44301. var t3 = (SBOX2[s3 >>> 24] << 24 | SBOX2[s0 >>> 16 & 255] << 16 | SBOX2[s1 >>> 8 & 255] << 8 | SBOX2[s2 & 255]) ^ keySchedule[ksRow++];
  44302. M2[offset] = t0;
  44303. M2[offset + 1] = t1;
  44304. M2[offset + 2] = t2;
  44305. M2[offset + 3] = t3;
  44306. },
  44307. keySize: 256 / 32
  44308. });
  44309. C2.AES = BlockCipher._createHelper(AES);
  44310. })();
  44311. return CryptoJS2.AES;
  44312. });
  44313. })(aes);
  44314. return aes.exports;
  44315. }
  44316. var tripledes = { exports: {} };
  44317. var hasRequiredTripledes;
  44318. function requireTripledes() {
  44319. if (hasRequiredTripledes)
  44320. return tripledes.exports;
  44321. hasRequiredTripledes = 1;
  44322. (function(module2, exports2) {
  44323. (function(root, factory, undef) {
  44324. {
  44325. module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  44326. }
  44327. })(commonjsGlobal, function(CryptoJS2) {
  44328. (function() {
  44329. var C2 = CryptoJS2;
  44330. var C_lib = C2.lib;
  44331. var WordArray = C_lib.WordArray;
  44332. var BlockCipher = C_lib.BlockCipher;
  44333. var C_algo = C2.algo;
  44334. var PC1 = [
  44335. 57,
  44336. 49,
  44337. 41,
  44338. 33,
  44339. 25,
  44340. 17,
  44341. 9,
  44342. 1,
  44343. 58,
  44344. 50,
  44345. 42,
  44346. 34,
  44347. 26,
  44348. 18,
  44349. 10,
  44350. 2,
  44351. 59,
  44352. 51,
  44353. 43,
  44354. 35,
  44355. 27,
  44356. 19,
  44357. 11,
  44358. 3,
  44359. 60,
  44360. 52,
  44361. 44,
  44362. 36,
  44363. 63,
  44364. 55,
  44365. 47,
  44366. 39,
  44367. 31,
  44368. 23,
  44369. 15,
  44370. 7,
  44371. 62,
  44372. 54,
  44373. 46,
  44374. 38,
  44375. 30,
  44376. 22,
  44377. 14,
  44378. 6,
  44379. 61,
  44380. 53,
  44381. 45,
  44382. 37,
  44383. 29,
  44384. 21,
  44385. 13,
  44386. 5,
  44387. 28,
  44388. 20,
  44389. 12,
  44390. 4
  44391. ];
  44392. var PC2 = [
  44393. 14,
  44394. 17,
  44395. 11,
  44396. 24,
  44397. 1,
  44398. 5,
  44399. 3,
  44400. 28,
  44401. 15,
  44402. 6,
  44403. 21,
  44404. 10,
  44405. 23,
  44406. 19,
  44407. 12,
  44408. 4,
  44409. 26,
  44410. 8,
  44411. 16,
  44412. 7,
  44413. 27,
  44414. 20,
  44415. 13,
  44416. 2,
  44417. 41,
  44418. 52,
  44419. 31,
  44420. 37,
  44421. 47,
  44422. 55,
  44423. 30,
  44424. 40,
  44425. 51,
  44426. 45,
  44427. 33,
  44428. 48,
  44429. 44,
  44430. 49,
  44431. 39,
  44432. 56,
  44433. 34,
  44434. 53,
  44435. 46,
  44436. 42,
  44437. 50,
  44438. 36,
  44439. 29,
  44440. 32
  44441. ];
  44442. var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
  44443. var SBOX_P = [
  44444. {
  44445. 0: 8421888,
  44446. 268435456: 32768,
  44447. 536870912: 8421378,
  44448. 805306368: 2,
  44449. 1073741824: 512,
  44450. 1342177280: 8421890,
  44451. 1610612736: 8389122,
  44452. 1879048192: 8388608,
  44453. 2147483648: 514,
  44454. 2415919104: 8389120,
  44455. 2684354560: 33280,
  44456. 2952790016: 8421376,
  44457. 3221225472: 32770,
  44458. 3489660928: 8388610,
  44459. 3758096384: 0,
  44460. 4026531840: 33282,
  44461. 134217728: 0,
  44462. 402653184: 8421890,
  44463. 671088640: 33282,
  44464. 939524096: 32768,
  44465. 1207959552: 8421888,
  44466. 1476395008: 512,
  44467. 1744830464: 8421378,
  44468. 2013265920: 2,
  44469. 2281701376: 8389120,
  44470. 2550136832: 33280,
  44471. 2818572288: 8421376,
  44472. 3087007744: 8389122,
  44473. 3355443200: 8388610,
  44474. 3623878656: 32770,
  44475. 3892314112: 514,
  44476. 4160749568: 8388608,
  44477. 1: 32768,
  44478. 268435457: 2,
  44479. 536870913: 8421888,
  44480. 805306369: 8388608,
  44481. 1073741825: 8421378,
  44482. 1342177281: 33280,
  44483. 1610612737: 512,
  44484. 1879048193: 8389122,
  44485. 2147483649: 8421890,
  44486. 2415919105: 8421376,
  44487. 2684354561: 8388610,
  44488. 2952790017: 33282,
  44489. 3221225473: 514,
  44490. 3489660929: 8389120,
  44491. 3758096385: 32770,
  44492. 4026531841: 0,
  44493. 134217729: 8421890,
  44494. 402653185: 8421376,
  44495. 671088641: 8388608,
  44496. 939524097: 512,
  44497. 1207959553: 32768,
  44498. 1476395009: 8388610,
  44499. 1744830465: 2,
  44500. 2013265921: 33282,
  44501. 2281701377: 32770,
  44502. 2550136833: 8389122,
  44503. 2818572289: 514,
  44504. 3087007745: 8421888,
  44505. 3355443201: 8389120,
  44506. 3623878657: 0,
  44507. 3892314113: 33280,
  44508. 4160749569: 8421378
  44509. },
  44510. {
  44511. 0: 1074282512,
  44512. 16777216: 16384,
  44513. 33554432: 524288,
  44514. 50331648: 1074266128,
  44515. 67108864: 1073741840,
  44516. 83886080: 1074282496,
  44517. 100663296: 1073758208,
  44518. 117440512: 16,
  44519. 134217728: 540672,
  44520. 150994944: 1073758224,
  44521. 167772160: 1073741824,
  44522. 184549376: 540688,
  44523. 201326592: 524304,
  44524. 218103808: 0,
  44525. 234881024: 16400,
  44526. 251658240: 1074266112,
  44527. 8388608: 1073758208,
  44528. 25165824: 540688,
  44529. 41943040: 16,
  44530. 58720256: 1073758224,
  44531. 75497472: 1074282512,
  44532. 92274688: 1073741824,
  44533. 109051904: 524288,
  44534. 125829120: 1074266128,
  44535. 142606336: 524304,
  44536. 159383552: 0,
  44537. 176160768: 16384,
  44538. 192937984: 1074266112,
  44539. 209715200: 1073741840,
  44540. 226492416: 540672,
  44541. 243269632: 1074282496,
  44542. 260046848: 16400,
  44543. 268435456: 0,
  44544. 285212672: 1074266128,
  44545. 301989888: 1073758224,
  44546. 318767104: 1074282496,
  44547. 335544320: 1074266112,
  44548. 352321536: 16,
  44549. 369098752: 540688,
  44550. 385875968: 16384,
  44551. 402653184: 16400,
  44552. 419430400: 524288,
  44553. 436207616: 524304,
  44554. 452984832: 1073741840,
  44555. 469762048: 540672,
  44556. 486539264: 1073758208,
  44557. 503316480: 1073741824,
  44558. 520093696: 1074282512,
  44559. 276824064: 540688,
  44560. 293601280: 524288,
  44561. 310378496: 1074266112,
  44562. 327155712: 16384,
  44563. 343932928: 1073758208,
  44564. 360710144: 1074282512,
  44565. 377487360: 16,
  44566. 394264576: 1073741824,
  44567. 411041792: 1074282496,
  44568. 427819008: 1073741840,
  44569. 444596224: 1073758224,
  44570. 461373440: 524304,
  44571. 478150656: 0,
  44572. 494927872: 16400,
  44573. 511705088: 1074266128,
  44574. 528482304: 540672
  44575. },
  44576. {
  44577. 0: 260,
  44578. 1048576: 0,
  44579. 2097152: 67109120,
  44580. 3145728: 65796,
  44581. 4194304: 65540,
  44582. 5242880: 67108868,
  44583. 6291456: 67174660,
  44584. 7340032: 67174400,
  44585. 8388608: 67108864,
  44586. 9437184: 67174656,
  44587. 10485760: 65792,
  44588. 11534336: 67174404,
  44589. 12582912: 67109124,
  44590. 13631488: 65536,
  44591. 14680064: 4,
  44592. 15728640: 256,
  44593. 524288: 67174656,
  44594. 1572864: 67174404,
  44595. 2621440: 0,
  44596. 3670016: 67109120,
  44597. 4718592: 67108868,
  44598. 5767168: 65536,
  44599. 6815744: 65540,
  44600. 7864320: 260,
  44601. 8912896: 4,
  44602. 9961472: 256,
  44603. 11010048: 67174400,
  44604. 12058624: 65796,
  44605. 13107200: 65792,
  44606. 14155776: 67109124,
  44607. 15204352: 67174660,
  44608. 16252928: 67108864,
  44609. 16777216: 67174656,
  44610. 17825792: 65540,
  44611. 18874368: 65536,
  44612. 19922944: 67109120,
  44613. 20971520: 256,
  44614. 22020096: 67174660,
  44615. 23068672: 67108868,
  44616. 24117248: 0,
  44617. 25165824: 67109124,
  44618. 26214400: 67108864,
  44619. 27262976: 4,
  44620. 28311552: 65792,
  44621. 29360128: 67174400,
  44622. 30408704: 260,
  44623. 31457280: 65796,
  44624. 32505856: 67174404,
  44625. 17301504: 67108864,
  44626. 18350080: 260,
  44627. 19398656: 67174656,
  44628. 20447232: 0,
  44629. 21495808: 65540,
  44630. 22544384: 67109120,
  44631. 23592960: 256,
  44632. 24641536: 67174404,
  44633. 25690112: 65536,
  44634. 26738688: 67174660,
  44635. 27787264: 65796,
  44636. 28835840: 67108868,
  44637. 29884416: 67109124,
  44638. 30932992: 67174400,
  44639. 31981568: 4,
  44640. 33030144: 65792
  44641. },
  44642. {
  44643. 0: 2151682048,
  44644. 65536: 2147487808,
  44645. 131072: 4198464,
  44646. 196608: 2151677952,
  44647. 262144: 0,
  44648. 327680: 4198400,
  44649. 393216: 2147483712,
  44650. 458752: 4194368,
  44651. 524288: 2147483648,
  44652. 589824: 4194304,
  44653. 655360: 64,
  44654. 720896: 2147487744,
  44655. 786432: 2151678016,
  44656. 851968: 4160,
  44657. 917504: 4096,
  44658. 983040: 2151682112,
  44659. 32768: 2147487808,
  44660. 98304: 64,
  44661. 163840: 2151678016,
  44662. 229376: 2147487744,
  44663. 294912: 4198400,
  44664. 360448: 2151682112,
  44665. 425984: 0,
  44666. 491520: 2151677952,
  44667. 557056: 4096,
  44668. 622592: 2151682048,
  44669. 688128: 4194304,
  44670. 753664: 4160,
  44671. 819200: 2147483648,
  44672. 884736: 4194368,
  44673. 950272: 4198464,
  44674. 1015808: 2147483712,
  44675. 1048576: 4194368,
  44676. 1114112: 4198400,
  44677. 1179648: 2147483712,
  44678. 1245184: 0,
  44679. 1310720: 4160,
  44680. 1376256: 2151678016,
  44681. 1441792: 2151682048,
  44682. 1507328: 2147487808,
  44683. 1572864: 2151682112,
  44684. 1638400: 2147483648,
  44685. 1703936: 2151677952,
  44686. 1769472: 4198464,
  44687. 1835008: 2147487744,
  44688. 1900544: 4194304,
  44689. 1966080: 64,
  44690. 2031616: 4096,
  44691. 1081344: 2151677952,
  44692. 1146880: 2151682112,
  44693. 1212416: 0,
  44694. 1277952: 4198400,
  44695. 1343488: 4194368,
  44696. 1409024: 2147483648,
  44697. 1474560: 2147487808,
  44698. 1540096: 64,
  44699. 1605632: 2147483712,
  44700. 1671168: 4096,
  44701. 1736704: 2147487744,
  44702. 1802240: 2151678016,
  44703. 1867776: 4160,
  44704. 1933312: 2151682048,
  44705. 1998848: 4194304,
  44706. 2064384: 4198464
  44707. },
  44708. {
  44709. 0: 128,
  44710. 4096: 17039360,
  44711. 8192: 262144,
  44712. 12288: 536870912,
  44713. 16384: 537133184,
  44714. 20480: 16777344,
  44715. 24576: 553648256,
  44716. 28672: 262272,
  44717. 32768: 16777216,
  44718. 36864: 537133056,
  44719. 40960: 536871040,
  44720. 45056: 553910400,
  44721. 49152: 553910272,
  44722. 53248: 0,
  44723. 57344: 17039488,
  44724. 61440: 553648128,
  44725. 2048: 17039488,
  44726. 6144: 553648256,
  44727. 10240: 128,
  44728. 14336: 17039360,
  44729. 18432: 262144,
  44730. 22528: 537133184,
  44731. 26624: 553910272,
  44732. 30720: 536870912,
  44733. 34816: 537133056,
  44734. 38912: 0,
  44735. 43008: 553910400,
  44736. 47104: 16777344,
  44737. 51200: 536871040,
  44738. 55296: 553648128,
  44739. 59392: 16777216,
  44740. 63488: 262272,
  44741. 65536: 262144,
  44742. 69632: 128,
  44743. 73728: 536870912,
  44744. 77824: 553648256,
  44745. 81920: 16777344,
  44746. 86016: 553910272,
  44747. 90112: 537133184,
  44748. 94208: 16777216,
  44749. 98304: 553910400,
  44750. 102400: 553648128,
  44751. 106496: 17039360,
  44752. 110592: 537133056,
  44753. 114688: 262272,
  44754. 118784: 536871040,
  44755. 122880: 0,
  44756. 126976: 17039488,
  44757. 67584: 553648256,
  44758. 71680: 16777216,
  44759. 75776: 17039360,
  44760. 79872: 537133184,
  44761. 83968: 536870912,
  44762. 88064: 17039488,
  44763. 92160: 128,
  44764. 96256: 553910272,
  44765. 100352: 262272,
  44766. 104448: 553910400,
  44767. 108544: 0,
  44768. 112640: 553648128,
  44769. 116736: 16777344,
  44770. 120832: 262144,
  44771. 124928: 537133056,
  44772. 129024: 536871040
  44773. },
  44774. {
  44775. 0: 268435464,
  44776. 256: 8192,
  44777. 512: 270532608,
  44778. 768: 270540808,
  44779. 1024: 268443648,
  44780. 1280: 2097152,
  44781. 1536: 2097160,
  44782. 1792: 268435456,
  44783. 2048: 0,
  44784. 2304: 268443656,
  44785. 2560: 2105344,
  44786. 2816: 8,
  44787. 3072: 270532616,
  44788. 3328: 2105352,
  44789. 3584: 8200,
  44790. 3840: 270540800,
  44791. 128: 270532608,
  44792. 384: 270540808,
  44793. 640: 8,
  44794. 896: 2097152,
  44795. 1152: 2105352,
  44796. 1408: 268435464,
  44797. 1664: 268443648,
  44798. 1920: 8200,
  44799. 2176: 2097160,
  44800. 2432: 8192,
  44801. 2688: 268443656,
  44802. 2944: 270532616,
  44803. 3200: 0,
  44804. 3456: 270540800,
  44805. 3712: 2105344,
  44806. 3968: 268435456,
  44807. 4096: 268443648,
  44808. 4352: 270532616,
  44809. 4608: 270540808,
  44810. 4864: 8200,
  44811. 5120: 2097152,
  44812. 5376: 268435456,
  44813. 5632: 268435464,
  44814. 5888: 2105344,
  44815. 6144: 2105352,
  44816. 6400: 0,
  44817. 6656: 8,
  44818. 6912: 270532608,
  44819. 7168: 8192,
  44820. 7424: 268443656,
  44821. 7680: 270540800,
  44822. 7936: 2097160,
  44823. 4224: 8,
  44824. 4480: 2105344,
  44825. 4736: 2097152,
  44826. 4992: 268435464,
  44827. 5248: 268443648,
  44828. 5504: 8200,
  44829. 5760: 270540808,
  44830. 6016: 270532608,
  44831. 6272: 270540800,
  44832. 6528: 270532616,
  44833. 6784: 8192,
  44834. 7040: 2105352,
  44835. 7296: 2097160,
  44836. 7552: 0,
  44837. 7808: 268435456,
  44838. 8064: 268443656
  44839. },
  44840. {
  44841. 0: 1048576,
  44842. 16: 33555457,
  44843. 32: 1024,
  44844. 48: 1049601,
  44845. 64: 34604033,
  44846. 80: 0,
  44847. 96: 1,
  44848. 112: 34603009,
  44849. 128: 33555456,
  44850. 144: 1048577,
  44851. 160: 33554433,
  44852. 176: 34604032,
  44853. 192: 34603008,
  44854. 208: 1025,
  44855. 224: 1049600,
  44856. 240: 33554432,
  44857. 8: 34603009,
  44858. 24: 0,
  44859. 40: 33555457,
  44860. 56: 34604032,
  44861. 72: 1048576,
  44862. 88: 33554433,
  44863. 104: 33554432,
  44864. 120: 1025,
  44865. 136: 1049601,
  44866. 152: 33555456,
  44867. 168: 34603008,
  44868. 184: 1048577,
  44869. 200: 1024,
  44870. 216: 34604033,
  44871. 232: 1,
  44872. 248: 1049600,
  44873. 256: 33554432,
  44874. 272: 1048576,
  44875. 288: 33555457,
  44876. 304: 34603009,
  44877. 320: 1048577,
  44878. 336: 33555456,
  44879. 352: 34604032,
  44880. 368: 1049601,
  44881. 384: 1025,
  44882. 400: 34604033,
  44883. 416: 1049600,
  44884. 432: 1,
  44885. 448: 0,
  44886. 464: 34603008,
  44887. 480: 33554433,
  44888. 496: 1024,
  44889. 264: 1049600,
  44890. 280: 33555457,
  44891. 296: 34603009,
  44892. 312: 1,
  44893. 328: 33554432,
  44894. 344: 1048576,
  44895. 360: 1025,
  44896. 376: 34604032,
  44897. 392: 33554433,
  44898. 408: 34603008,
  44899. 424: 0,
  44900. 440: 34604033,
  44901. 456: 1049601,
  44902. 472: 1024,
  44903. 488: 33555456,
  44904. 504: 1048577
  44905. },
  44906. {
  44907. 0: 134219808,
  44908. 1: 131072,
  44909. 2: 134217728,
  44910. 3: 32,
  44911. 4: 131104,
  44912. 5: 134350880,
  44913. 6: 134350848,
  44914. 7: 2048,
  44915. 8: 134348800,
  44916. 9: 134219776,
  44917. 10: 133120,
  44918. 11: 134348832,
  44919. 12: 2080,
  44920. 13: 0,
  44921. 14: 134217760,
  44922. 15: 133152,
  44923. 2147483648: 2048,
  44924. 2147483649: 134350880,
  44925. 2147483650: 134219808,
  44926. 2147483651: 134217728,
  44927. 2147483652: 134348800,
  44928. 2147483653: 133120,
  44929. 2147483654: 133152,
  44930. 2147483655: 32,
  44931. 2147483656: 134217760,
  44932. 2147483657: 2080,
  44933. 2147483658: 131104,
  44934. 2147483659: 134350848,
  44935. 2147483660: 0,
  44936. 2147483661: 134348832,
  44937. 2147483662: 134219776,
  44938. 2147483663: 131072,
  44939. 16: 133152,
  44940. 17: 134350848,
  44941. 18: 32,
  44942. 19: 2048,
  44943. 20: 134219776,
  44944. 21: 134217760,
  44945. 22: 134348832,
  44946. 23: 131072,
  44947. 24: 0,
  44948. 25: 131104,
  44949. 26: 134348800,
  44950. 27: 134219808,
  44951. 28: 134350880,
  44952. 29: 133120,
  44953. 30: 2080,
  44954. 31: 134217728,
  44955. 2147483664: 131072,
  44956. 2147483665: 2048,
  44957. 2147483666: 134348832,
  44958. 2147483667: 133152,
  44959. 2147483668: 32,
  44960. 2147483669: 134348800,
  44961. 2147483670: 134217728,
  44962. 2147483671: 134219808,
  44963. 2147483672: 134350880,
  44964. 2147483673: 134217760,
  44965. 2147483674: 134219776,
  44966. 2147483675: 0,
  44967. 2147483676: 133120,
  44968. 2147483677: 2080,
  44969. 2147483678: 131104,
  44970. 2147483679: 134350848
  44971. }
  44972. ];
  44973. var SBOX_MASK = [
  44974. 4160749569,
  44975. 528482304,
  44976. 33030144,
  44977. 2064384,
  44978. 129024,
  44979. 8064,
  44980. 504,
  44981. 2147483679
  44982. ];
  44983. var DES = C_algo.DES = BlockCipher.extend({
  44984. _doReset: function() {
  44985. var key = this._key;
  44986. var keyWords = key.words;
  44987. var keyBits = [];
  44988. for (var i2 = 0; i2 < 56; i2++) {
  44989. var keyBitPos = PC1[i2] - 1;
  44990. keyBits[i2] = keyWords[keyBitPos >>> 5] >>> 31 - keyBitPos % 32 & 1;
  44991. }
  44992. var subKeys = this._subKeys = [];
  44993. for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
  44994. var subKey = subKeys[nSubKey] = [];
  44995. var bitShift = BIT_SHIFTS[nSubKey];
  44996. for (var i2 = 0; i2 < 24; i2++) {
  44997. subKey[i2 / 6 | 0] |= keyBits[(PC2[i2] - 1 + bitShift) % 28] << 31 - i2 % 6;
  44998. subKey[4 + (i2 / 6 | 0)] |= keyBits[28 + (PC2[i2 + 24] - 1 + bitShift) % 28] << 31 - i2 % 6;
  44999. }
  45000. subKey[0] = subKey[0] << 1 | subKey[0] >>> 31;
  45001. for (var i2 = 1; i2 < 7; i2++) {
  45002. subKey[i2] = subKey[i2] >>> (i2 - 1) * 4 + 3;
  45003. }
  45004. subKey[7] = subKey[7] << 5 | subKey[7] >>> 27;
  45005. }
  45006. var invSubKeys = this._invSubKeys = [];
  45007. for (var i2 = 0; i2 < 16; i2++) {
  45008. invSubKeys[i2] = subKeys[15 - i2];
  45009. }
  45010. },
  45011. encryptBlock: function(M2, offset) {
  45012. this._doCryptBlock(M2, offset, this._subKeys);
  45013. },
  45014. decryptBlock: function(M2, offset) {
  45015. this._doCryptBlock(M2, offset, this._invSubKeys);
  45016. },
  45017. _doCryptBlock: function(M2, offset, subKeys) {
  45018. this._lBlock = M2[offset];
  45019. this._rBlock = M2[offset + 1];
  45020. exchangeLR.call(this, 4, 252645135);
  45021. exchangeLR.call(this, 16, 65535);
  45022. exchangeRL.call(this, 2, 858993459);
  45023. exchangeRL.call(this, 8, 16711935);
  45024. exchangeLR.call(this, 1, 1431655765);
  45025. for (var round = 0; round < 16; round++) {
  45026. var subKey = subKeys[round];
  45027. var lBlock = this._lBlock;
  45028. var rBlock = this._rBlock;
  45029. var f2 = 0;
  45030. for (var i2 = 0; i2 < 8; i2++) {
  45031. f2 |= SBOX_P[i2][((rBlock ^ subKey[i2]) & SBOX_MASK[i2]) >>> 0];
  45032. }
  45033. this._lBlock = rBlock;
  45034. this._rBlock = lBlock ^ f2;
  45035. }
  45036. var t2 = this._lBlock;
  45037. this._lBlock = this._rBlock;
  45038. this._rBlock = t2;
  45039. exchangeLR.call(this, 1, 1431655765);
  45040. exchangeRL.call(this, 8, 16711935);
  45041. exchangeRL.call(this, 2, 858993459);
  45042. exchangeLR.call(this, 16, 65535);
  45043. exchangeLR.call(this, 4, 252645135);
  45044. M2[offset] = this._lBlock;
  45045. M2[offset + 1] = this._rBlock;
  45046. },
  45047. keySize: 64 / 32,
  45048. ivSize: 64 / 32,
  45049. blockSize: 64 / 32
  45050. });
  45051. function exchangeLR(offset, mask) {
  45052. var t2 = (this._lBlock >>> offset ^ this._rBlock) & mask;
  45053. this._rBlock ^= t2;
  45054. this._lBlock ^= t2 << offset;
  45055. }
  45056. function exchangeRL(offset, mask) {
  45057. var t2 = (this._rBlock >>> offset ^ this._lBlock) & mask;
  45058. this._lBlock ^= t2;
  45059. this._rBlock ^= t2 << offset;
  45060. }
  45061. C2.DES = BlockCipher._createHelper(DES);
  45062. var TripleDES = C_algo.TripleDES = BlockCipher.extend({
  45063. _doReset: function() {
  45064. var key = this._key;
  45065. var keyWords = key.words;
  45066. if (keyWords.length !== 2 && keyWords.length !== 4 && keyWords.length < 6) {
  45067. throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");
  45068. }
  45069. var key1 = keyWords.slice(0, 2);
  45070. var key2 = keyWords.length < 4 ? keyWords.slice(0, 2) : keyWords.slice(2, 4);
  45071. var key3 = keyWords.length < 6 ? keyWords.slice(0, 2) : keyWords.slice(4, 6);
  45072. this._des1 = DES.createEncryptor(WordArray.create(key1));
  45073. this._des2 = DES.createEncryptor(WordArray.create(key2));
  45074. this._des3 = DES.createEncryptor(WordArray.create(key3));
  45075. },
  45076. encryptBlock: function(M2, offset) {
  45077. this._des1.encryptBlock(M2, offset);
  45078. this._des2.decryptBlock(M2, offset);
  45079. this._des3.encryptBlock(M2, offset);
  45080. },
  45081. decryptBlock: function(M2, offset) {
  45082. this._des3.decryptBlock(M2, offset);
  45083. this._des2.encryptBlock(M2, offset);
  45084. this._des1.decryptBlock(M2, offset);
  45085. },
  45086. keySize: 192 / 32,
  45087. ivSize: 64 / 32,
  45088. blockSize: 64 / 32
  45089. });
  45090. C2.TripleDES = BlockCipher._createHelper(TripleDES);
  45091. })();
  45092. return CryptoJS2.TripleDES;
  45093. });
  45094. })(tripledes);
  45095. return tripledes.exports;
  45096. }
  45097. var rc4 = { exports: {} };
  45098. var hasRequiredRc4;
  45099. function requireRc4() {
  45100. if (hasRequiredRc4)
  45101. return rc4.exports;
  45102. hasRequiredRc4 = 1;
  45103. (function(module2, exports2) {
  45104. (function(root, factory, undef) {
  45105. {
  45106. module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  45107. }
  45108. })(commonjsGlobal, function(CryptoJS2) {
  45109. (function() {
  45110. var C2 = CryptoJS2;
  45111. var C_lib = C2.lib;
  45112. var StreamCipher = C_lib.StreamCipher;
  45113. var C_algo = C2.algo;
  45114. var RC4 = C_algo.RC4 = StreamCipher.extend({
  45115. _doReset: function() {
  45116. var key = this._key;
  45117. var keyWords = key.words;
  45118. var keySigBytes = key.sigBytes;
  45119. var S2 = this._S = [];
  45120. for (var i2 = 0; i2 < 256; i2++) {
  45121. S2[i2] = i2;
  45122. }
  45123. for (var i2 = 0, j2 = 0; i2 < 256; i2++) {
  45124. var keyByteIndex = i2 % keySigBytes;
  45125. var keyByte = keyWords[keyByteIndex >>> 2] >>> 24 - keyByteIndex % 4 * 8 & 255;
  45126. j2 = (j2 + S2[i2] + keyByte) % 256;
  45127. var t2 = S2[i2];
  45128. S2[i2] = S2[j2];
  45129. S2[j2] = t2;
  45130. }
  45131. this._i = this._j = 0;
  45132. },
  45133. _doProcessBlock: function(M2, offset) {
  45134. M2[offset] ^= generateKeystreamWord.call(this);
  45135. },
  45136. keySize: 256 / 32,
  45137. ivSize: 0
  45138. });
  45139. function generateKeystreamWord() {
  45140. var S2 = this._S;
  45141. var i2 = this._i;
  45142. var j2 = this._j;
  45143. var keystreamWord = 0;
  45144. for (var n2 = 0; n2 < 4; n2++) {
  45145. i2 = (i2 + 1) % 256;
  45146. j2 = (j2 + S2[i2]) % 256;
  45147. var t2 = S2[i2];
  45148. S2[i2] = S2[j2];
  45149. S2[j2] = t2;
  45150. keystreamWord |= S2[(S2[i2] + S2[j2]) % 256] << 24 - n2 * 8;
  45151. }
  45152. this._i = i2;
  45153. this._j = j2;
  45154. return keystreamWord;
  45155. }
  45156. C2.RC4 = StreamCipher._createHelper(RC4);
  45157. var RC4Drop = C_algo.RC4Drop = RC4.extend({
  45158. /**
  45159. * Configuration options.
  45160. *
  45161. * @property {number} drop The number of keystream words to drop. Default 192
  45162. */
  45163. cfg: RC4.cfg.extend({
  45164. drop: 192
  45165. }),
  45166. _doReset: function() {
  45167. RC4._doReset.call(this);
  45168. for (var i2 = this.cfg.drop; i2 > 0; i2--) {
  45169. generateKeystreamWord.call(this);
  45170. }
  45171. }
  45172. });
  45173. C2.RC4Drop = StreamCipher._createHelper(RC4Drop);
  45174. })();
  45175. return CryptoJS2.RC4;
  45176. });
  45177. })(rc4);
  45178. return rc4.exports;
  45179. }
  45180. var rabbit = { exports: {} };
  45181. var hasRequiredRabbit;
  45182. function requireRabbit() {
  45183. if (hasRequiredRabbit)
  45184. return rabbit.exports;
  45185. hasRequiredRabbit = 1;
  45186. (function(module2, exports2) {
  45187. (function(root, factory, undef) {
  45188. {
  45189. module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  45190. }
  45191. })(commonjsGlobal, function(CryptoJS2) {
  45192. (function() {
  45193. var C2 = CryptoJS2;
  45194. var C_lib = C2.lib;
  45195. var StreamCipher = C_lib.StreamCipher;
  45196. var C_algo = C2.algo;
  45197. var S2 = [];
  45198. var C_ = [];
  45199. var G2 = [];
  45200. var Rabbit = C_algo.Rabbit = StreamCipher.extend({
  45201. _doReset: function() {
  45202. var K2 = this._key.words;
  45203. var iv = this.cfg.iv;
  45204. for (var i2 = 0; i2 < 4; i2++) {
  45205. K2[i2] = (K2[i2] << 8 | K2[i2] >>> 24) & 16711935 | (K2[i2] << 24 | K2[i2] >>> 8) & 4278255360;
  45206. }
  45207. var X2 = this._X = [
  45208. K2[0],
  45209. K2[3] << 16 | K2[2] >>> 16,
  45210. K2[1],
  45211. K2[0] << 16 | K2[3] >>> 16,
  45212. K2[2],
  45213. K2[1] << 16 | K2[0] >>> 16,
  45214. K2[3],
  45215. K2[2] << 16 | K2[1] >>> 16
  45216. ];
  45217. var C3 = this._C = [
  45218. K2[2] << 16 | K2[2] >>> 16,
  45219. K2[0] & 4294901760 | K2[1] & 65535,
  45220. K2[3] << 16 | K2[3] >>> 16,
  45221. K2[1] & 4294901760 | K2[2] & 65535,
  45222. K2[0] << 16 | K2[0] >>> 16,
  45223. K2[2] & 4294901760 | K2[3] & 65535,
  45224. K2[1] << 16 | K2[1] >>> 16,
  45225. K2[3] & 4294901760 | K2[0] & 65535
  45226. ];
  45227. this._b = 0;
  45228. for (var i2 = 0; i2 < 4; i2++) {
  45229. nextState.call(this);
  45230. }
  45231. for (var i2 = 0; i2 < 8; i2++) {
  45232. C3[i2] ^= X2[i2 + 4 & 7];
  45233. }
  45234. if (iv) {
  45235. var IV = iv.words;
  45236. var IV_0 = IV[0];
  45237. var IV_1 = IV[1];
  45238. var i0 = (IV_0 << 8 | IV_0 >>> 24) & 16711935 | (IV_0 << 24 | IV_0 >>> 8) & 4278255360;
  45239. var i22 = (IV_1 << 8 | IV_1 >>> 24) & 16711935 | (IV_1 << 24 | IV_1 >>> 8) & 4278255360;
  45240. var i1 = i0 >>> 16 | i22 & 4294901760;
  45241. var i3 = i22 << 16 | i0 & 65535;
  45242. C3[0] ^= i0;
  45243. C3[1] ^= i1;
  45244. C3[2] ^= i22;
  45245. C3[3] ^= i3;
  45246. C3[4] ^= i0;
  45247. C3[5] ^= i1;
  45248. C3[6] ^= i22;
  45249. C3[7] ^= i3;
  45250. for (var i2 = 0; i2 < 4; i2++) {
  45251. nextState.call(this);
  45252. }
  45253. }
  45254. },
  45255. _doProcessBlock: function(M2, offset) {
  45256. var X2 = this._X;
  45257. nextState.call(this);
  45258. S2[0] = X2[0] ^ X2[5] >>> 16 ^ X2[3] << 16;
  45259. S2[1] = X2[2] ^ X2[7] >>> 16 ^ X2[5] << 16;
  45260. S2[2] = X2[4] ^ X2[1] >>> 16 ^ X2[7] << 16;
  45261. S2[3] = X2[6] ^ X2[3] >>> 16 ^ X2[1] << 16;
  45262. for (var i2 = 0; i2 < 4; i2++) {
  45263. S2[i2] = (S2[i2] << 8 | S2[i2] >>> 24) & 16711935 | (S2[i2] << 24 | S2[i2] >>> 8) & 4278255360;
  45264. M2[offset + i2] ^= S2[i2];
  45265. }
  45266. },
  45267. blockSize: 128 / 32,
  45268. ivSize: 64 / 32
  45269. });
  45270. function nextState() {
  45271. var X2 = this._X;
  45272. var C3 = this._C;
  45273. for (var i2 = 0; i2 < 8; i2++) {
  45274. C_[i2] = C3[i2];
  45275. }
  45276. C3[0] = C3[0] + 1295307597 + this._b | 0;
  45277. C3[1] = C3[1] + 3545052371 + (C3[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0;
  45278. C3[2] = C3[2] + 886263092 + (C3[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0;
  45279. C3[3] = C3[3] + 1295307597 + (C3[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0;
  45280. C3[4] = C3[4] + 3545052371 + (C3[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0;
  45281. C3[5] = C3[5] + 886263092 + (C3[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0;
  45282. C3[6] = C3[6] + 1295307597 + (C3[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0;
  45283. C3[7] = C3[7] + 3545052371 + (C3[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0;
  45284. this._b = C3[7] >>> 0 < C_[7] >>> 0 ? 1 : 0;
  45285. for (var i2 = 0; i2 < 8; i2++) {
  45286. var gx = X2[i2] + C3[i2];
  45287. var ga = gx & 65535;
  45288. var gb = gx >>> 16;
  45289. var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb;
  45290. var gl = ((gx & 4294901760) * gx | 0) + ((gx & 65535) * gx | 0);
  45291. G2[i2] = gh ^ gl;
  45292. }
  45293. X2[0] = G2[0] + (G2[7] << 16 | G2[7] >>> 16) + (G2[6] << 16 | G2[6] >>> 16) | 0;
  45294. X2[1] = G2[1] + (G2[0] << 8 | G2[0] >>> 24) + G2[7] | 0;
  45295. X2[2] = G2[2] + (G2[1] << 16 | G2[1] >>> 16) + (G2[0] << 16 | G2[0] >>> 16) | 0;
  45296. X2[3] = G2[3] + (G2[2] << 8 | G2[2] >>> 24) + G2[1] | 0;
  45297. X2[4] = G2[4] + (G2[3] << 16 | G2[3] >>> 16) + (G2[2] << 16 | G2[2] >>> 16) | 0;
  45298. X2[5] = G2[5] + (G2[4] << 8 | G2[4] >>> 24) + G2[3] | 0;
  45299. X2[6] = G2[6] + (G2[5] << 16 | G2[5] >>> 16) + (G2[4] << 16 | G2[4] >>> 16) | 0;
  45300. X2[7] = G2[7] + (G2[6] << 8 | G2[6] >>> 24) + G2[5] | 0;
  45301. }
  45302. C2.Rabbit = StreamCipher._createHelper(Rabbit);
  45303. })();
  45304. return CryptoJS2.Rabbit;
  45305. });
  45306. })(rabbit);
  45307. return rabbit.exports;
  45308. }
  45309. var rabbitLegacy = { exports: {} };
  45310. var hasRequiredRabbitLegacy;
  45311. function requireRabbitLegacy() {
  45312. if (hasRequiredRabbitLegacy)
  45313. return rabbitLegacy.exports;
  45314. hasRequiredRabbitLegacy = 1;
  45315. (function(module2, exports2) {
  45316. (function(root, factory, undef) {
  45317. {
  45318. module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  45319. }
  45320. })(commonjsGlobal, function(CryptoJS2) {
  45321. (function() {
  45322. var C2 = CryptoJS2;
  45323. var C_lib = C2.lib;
  45324. var StreamCipher = C_lib.StreamCipher;
  45325. var C_algo = C2.algo;
  45326. var S2 = [];
  45327. var C_ = [];
  45328. var G2 = [];
  45329. var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
  45330. _doReset: function() {
  45331. var K2 = this._key.words;
  45332. var iv = this.cfg.iv;
  45333. var X2 = this._X = [
  45334. K2[0],
  45335. K2[3] << 16 | K2[2] >>> 16,
  45336. K2[1],
  45337. K2[0] << 16 | K2[3] >>> 16,
  45338. K2[2],
  45339. K2[1] << 16 | K2[0] >>> 16,
  45340. K2[3],
  45341. K2[2] << 16 | K2[1] >>> 16
  45342. ];
  45343. var C3 = this._C = [
  45344. K2[2] << 16 | K2[2] >>> 16,
  45345. K2[0] & 4294901760 | K2[1] & 65535,
  45346. K2[3] << 16 | K2[3] >>> 16,
  45347. K2[1] & 4294901760 | K2[2] & 65535,
  45348. K2[0] << 16 | K2[0] >>> 16,
  45349. K2[2] & 4294901760 | K2[3] & 65535,
  45350. K2[1] << 16 | K2[1] >>> 16,
  45351. K2[3] & 4294901760 | K2[0] & 65535
  45352. ];
  45353. this._b = 0;
  45354. for (var i2 = 0; i2 < 4; i2++) {
  45355. nextState.call(this);
  45356. }
  45357. for (var i2 = 0; i2 < 8; i2++) {
  45358. C3[i2] ^= X2[i2 + 4 & 7];
  45359. }
  45360. if (iv) {
  45361. var IV = iv.words;
  45362. var IV_0 = IV[0];
  45363. var IV_1 = IV[1];
  45364. var i0 = (IV_0 << 8 | IV_0 >>> 24) & 16711935 | (IV_0 << 24 | IV_0 >>> 8) & 4278255360;
  45365. var i22 = (IV_1 << 8 | IV_1 >>> 24) & 16711935 | (IV_1 << 24 | IV_1 >>> 8) & 4278255360;
  45366. var i1 = i0 >>> 16 | i22 & 4294901760;
  45367. var i3 = i22 << 16 | i0 & 65535;
  45368. C3[0] ^= i0;
  45369. C3[1] ^= i1;
  45370. C3[2] ^= i22;
  45371. C3[3] ^= i3;
  45372. C3[4] ^= i0;
  45373. C3[5] ^= i1;
  45374. C3[6] ^= i22;
  45375. C3[7] ^= i3;
  45376. for (var i2 = 0; i2 < 4; i2++) {
  45377. nextState.call(this);
  45378. }
  45379. }
  45380. },
  45381. _doProcessBlock: function(M2, offset) {
  45382. var X2 = this._X;
  45383. nextState.call(this);
  45384. S2[0] = X2[0] ^ X2[5] >>> 16 ^ X2[3] << 16;
  45385. S2[1] = X2[2] ^ X2[7] >>> 16 ^ X2[5] << 16;
  45386. S2[2] = X2[4] ^ X2[1] >>> 16 ^ X2[7] << 16;
  45387. S2[3] = X2[6] ^ X2[3] >>> 16 ^ X2[1] << 16;
  45388. for (var i2 = 0; i2 < 4; i2++) {
  45389. S2[i2] = (S2[i2] << 8 | S2[i2] >>> 24) & 16711935 | (S2[i2] << 24 | S2[i2] >>> 8) & 4278255360;
  45390. M2[offset + i2] ^= S2[i2];
  45391. }
  45392. },
  45393. blockSize: 128 / 32,
  45394. ivSize: 64 / 32
  45395. });
  45396. function nextState() {
  45397. var X2 = this._X;
  45398. var C3 = this._C;
  45399. for (var i2 = 0; i2 < 8; i2++) {
  45400. C_[i2] = C3[i2];
  45401. }
  45402. C3[0] = C3[0] + 1295307597 + this._b | 0;
  45403. C3[1] = C3[1] + 3545052371 + (C3[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0;
  45404. C3[2] = C3[2] + 886263092 + (C3[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0;
  45405. C3[3] = C3[3] + 1295307597 + (C3[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0;
  45406. C3[4] = C3[4] + 3545052371 + (C3[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0;
  45407. C3[5] = C3[5] + 886263092 + (C3[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0;
  45408. C3[6] = C3[6] + 1295307597 + (C3[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0;
  45409. C3[7] = C3[7] + 3545052371 + (C3[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0;
  45410. this._b = C3[7] >>> 0 < C_[7] >>> 0 ? 1 : 0;
  45411. for (var i2 = 0; i2 < 8; i2++) {
  45412. var gx = X2[i2] + C3[i2];
  45413. var ga = gx & 65535;
  45414. var gb = gx >>> 16;
  45415. var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb;
  45416. var gl = ((gx & 4294901760) * gx | 0) + ((gx & 65535) * gx | 0);
  45417. G2[i2] = gh ^ gl;
  45418. }
  45419. X2[0] = G2[0] + (G2[7] << 16 | G2[7] >>> 16) + (G2[6] << 16 | G2[6] >>> 16) | 0;
  45420. X2[1] = G2[1] + (G2[0] << 8 | G2[0] >>> 24) + G2[7] | 0;
  45421. X2[2] = G2[2] + (G2[1] << 16 | G2[1] >>> 16) + (G2[0] << 16 | G2[0] >>> 16) | 0;
  45422. X2[3] = G2[3] + (G2[2] << 8 | G2[2] >>> 24) + G2[1] | 0;
  45423. X2[4] = G2[4] + (G2[3] << 16 | G2[3] >>> 16) + (G2[2] << 16 | G2[2] >>> 16) | 0;
  45424. X2[5] = G2[5] + (G2[4] << 8 | G2[4] >>> 24) + G2[3] | 0;
  45425. X2[6] = G2[6] + (G2[5] << 16 | G2[5] >>> 16) + (G2[4] << 16 | G2[4] >>> 16) | 0;
  45426. X2[7] = G2[7] + (G2[6] << 8 | G2[6] >>> 24) + G2[5] | 0;
  45427. }
  45428. C2.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
  45429. })();
  45430. return CryptoJS2.RabbitLegacy;
  45431. });
  45432. })(rabbitLegacy);
  45433. return rabbitLegacy.exports;
  45434. }
  45435. var blowfish = { exports: {} };
  45436. var hasRequiredBlowfish;
  45437. function requireBlowfish() {
  45438. if (hasRequiredBlowfish)
  45439. return blowfish.exports;
  45440. hasRequiredBlowfish = 1;
  45441. (function(module2, exports2) {
  45442. (function(root, factory, undef) {
  45443. {
  45444. module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  45445. }
  45446. })(commonjsGlobal, function(CryptoJS2) {
  45447. (function() {
  45448. var C2 = CryptoJS2;
  45449. var C_lib = C2.lib;
  45450. var BlockCipher = C_lib.BlockCipher;
  45451. var C_algo = C2.algo;
  45452. const N2 = 16;
  45453. const ORIG_P = [
  45454. 608135816,
  45455. 2242054355,
  45456. 320440878,
  45457. 57701188,
  45458. 2752067618,
  45459. 698298832,
  45460. 137296536,
  45461. 3964562569,
  45462. 1160258022,
  45463. 953160567,
  45464. 3193202383,
  45465. 887688300,
  45466. 3232508343,
  45467. 3380367581,
  45468. 1065670069,
  45469. 3041331479,
  45470. 2450970073,
  45471. 2306472731
  45472. ];
  45473. const ORIG_S = [
  45474. [
  45475. 3509652390,
  45476. 2564797868,
  45477. 805139163,
  45478. 3491422135,
  45479. 3101798381,
  45480. 1780907670,
  45481. 3128725573,
  45482. 4046225305,
  45483. 614570311,
  45484. 3012652279,
  45485. 134345442,
  45486. 2240740374,
  45487. 1667834072,
  45488. 1901547113,
  45489. 2757295779,
  45490. 4103290238,
  45491. 227898511,
  45492. 1921955416,
  45493. 1904987480,
  45494. 2182433518,
  45495. 2069144605,
  45496. 3260701109,
  45497. 2620446009,
  45498. 720527379,
  45499. 3318853667,
  45500. 677414384,
  45501. 3393288472,
  45502. 3101374703,
  45503. 2390351024,
  45504. 1614419982,
  45505. 1822297739,
  45506. 2954791486,
  45507. 3608508353,
  45508. 3174124327,
  45509. 2024746970,
  45510. 1432378464,
  45511. 3864339955,
  45512. 2857741204,
  45513. 1464375394,
  45514. 1676153920,
  45515. 1439316330,
  45516. 715854006,
  45517. 3033291828,
  45518. 289532110,
  45519. 2706671279,
  45520. 2087905683,
  45521. 3018724369,
  45522. 1668267050,
  45523. 732546397,
  45524. 1947742710,
  45525. 3462151702,
  45526. 2609353502,
  45527. 2950085171,
  45528. 1814351708,
  45529. 2050118529,
  45530. 680887927,
  45531. 999245976,
  45532. 1800124847,
  45533. 3300911131,
  45534. 1713906067,
  45535. 1641548236,
  45536. 4213287313,
  45537. 1216130144,
  45538. 1575780402,
  45539. 4018429277,
  45540. 3917837745,
  45541. 3693486850,
  45542. 3949271944,
  45543. 596196993,
  45544. 3549867205,
  45545. 258830323,
  45546. 2213823033,
  45547. 772490370,
  45548. 2760122372,
  45549. 1774776394,
  45550. 2652871518,
  45551. 566650946,
  45552. 4142492826,
  45553. 1728879713,
  45554. 2882767088,
  45555. 1783734482,
  45556. 3629395816,
  45557. 2517608232,
  45558. 2874225571,
  45559. 1861159788,
  45560. 326777828,
  45561. 3124490320,
  45562. 2130389656,
  45563. 2716951837,
  45564. 967770486,
  45565. 1724537150,
  45566. 2185432712,
  45567. 2364442137,
  45568. 1164943284,
  45569. 2105845187,
  45570. 998989502,
  45571. 3765401048,
  45572. 2244026483,
  45573. 1075463327,
  45574. 1455516326,
  45575. 1322494562,
  45576. 910128902,
  45577. 469688178,
  45578. 1117454909,
  45579. 936433444,
  45580. 3490320968,
  45581. 3675253459,
  45582. 1240580251,
  45583. 122909385,
  45584. 2157517691,
  45585. 634681816,
  45586. 4142456567,
  45587. 3825094682,
  45588. 3061402683,
  45589. 2540495037,
  45590. 79693498,
  45591. 3249098678,
  45592. 1084186820,
  45593. 1583128258,
  45594. 426386531,
  45595. 1761308591,
  45596. 1047286709,
  45597. 322548459,
  45598. 995290223,
  45599. 1845252383,
  45600. 2603652396,
  45601. 3431023940,
  45602. 2942221577,
  45603. 3202600964,
  45604. 3727903485,
  45605. 1712269319,
  45606. 422464435,
  45607. 3234572375,
  45608. 1170764815,
  45609. 3523960633,
  45610. 3117677531,
  45611. 1434042557,
  45612. 442511882,
  45613. 3600875718,
  45614. 1076654713,
  45615. 1738483198,
  45616. 4213154764,
  45617. 2393238008,
  45618. 3677496056,
  45619. 1014306527,
  45620. 4251020053,
  45621. 793779912,
  45622. 2902807211,
  45623. 842905082,
  45624. 4246964064,
  45625. 1395751752,
  45626. 1040244610,
  45627. 2656851899,
  45628. 3396308128,
  45629. 445077038,
  45630. 3742853595,
  45631. 3577915638,
  45632. 679411651,
  45633. 2892444358,
  45634. 2354009459,
  45635. 1767581616,
  45636. 3150600392,
  45637. 3791627101,
  45638. 3102740896,
  45639. 284835224,
  45640. 4246832056,
  45641. 1258075500,
  45642. 768725851,
  45643. 2589189241,
  45644. 3069724005,
  45645. 3532540348,
  45646. 1274779536,
  45647. 3789419226,
  45648. 2764799539,
  45649. 1660621633,
  45650. 3471099624,
  45651. 4011903706,
  45652. 913787905,
  45653. 3497959166,
  45654. 737222580,
  45655. 2514213453,
  45656. 2928710040,
  45657. 3937242737,
  45658. 1804850592,
  45659. 3499020752,
  45660. 2949064160,
  45661. 2386320175,
  45662. 2390070455,
  45663. 2415321851,
  45664. 4061277028,
  45665. 2290661394,
  45666. 2416832540,
  45667. 1336762016,
  45668. 1754252060,
  45669. 3520065937,
  45670. 3014181293,
  45671. 791618072,
  45672. 3188594551,
  45673. 3933548030,
  45674. 2332172193,
  45675. 3852520463,
  45676. 3043980520,
  45677. 413987798,
  45678. 3465142937,
  45679. 3030929376,
  45680. 4245938359,
  45681. 2093235073,
  45682. 3534596313,
  45683. 375366246,
  45684. 2157278981,
  45685. 2479649556,
  45686. 555357303,
  45687. 3870105701,
  45688. 2008414854,
  45689. 3344188149,
  45690. 4221384143,
  45691. 3956125452,
  45692. 2067696032,
  45693. 3594591187,
  45694. 2921233993,
  45695. 2428461,
  45696. 544322398,
  45697. 577241275,
  45698. 1471733935,
  45699. 610547355,
  45700. 4027169054,
  45701. 1432588573,
  45702. 1507829418,
  45703. 2025931657,
  45704. 3646575487,
  45705. 545086370,
  45706. 48609733,
  45707. 2200306550,
  45708. 1653985193,
  45709. 298326376,
  45710. 1316178497,
  45711. 3007786442,
  45712. 2064951626,
  45713. 458293330,
  45714. 2589141269,
  45715. 3591329599,
  45716. 3164325604,
  45717. 727753846,
  45718. 2179363840,
  45719. 146436021,
  45720. 1461446943,
  45721. 4069977195,
  45722. 705550613,
  45723. 3059967265,
  45724. 3887724982,
  45725. 4281599278,
  45726. 3313849956,
  45727. 1404054877,
  45728. 2845806497,
  45729. 146425753,
  45730. 1854211946
  45731. ],
  45732. [
  45733. 1266315497,
  45734. 3048417604,
  45735. 3681880366,
  45736. 3289982499,
  45737. 290971e4,
  45738. 1235738493,
  45739. 2632868024,
  45740. 2414719590,
  45741. 3970600049,
  45742. 1771706367,
  45743. 1449415276,
  45744. 3266420449,
  45745. 422970021,
  45746. 1963543593,
  45747. 2690192192,
  45748. 3826793022,
  45749. 1062508698,
  45750. 1531092325,
  45751. 1804592342,
  45752. 2583117782,
  45753. 2714934279,
  45754. 4024971509,
  45755. 1294809318,
  45756. 4028980673,
  45757. 1289560198,
  45758. 2221992742,
  45759. 1669523910,
  45760. 35572830,
  45761. 157838143,
  45762. 1052438473,
  45763. 1016535060,
  45764. 1802137761,
  45765. 1753167236,
  45766. 1386275462,
  45767. 3080475397,
  45768. 2857371447,
  45769. 1040679964,
  45770. 2145300060,
  45771. 2390574316,
  45772. 1461121720,
  45773. 2956646967,
  45774. 4031777805,
  45775. 4028374788,
  45776. 33600511,
  45777. 2920084762,
  45778. 1018524850,
  45779. 629373528,
  45780. 3691585981,
  45781. 3515945977,
  45782. 2091462646,
  45783. 2486323059,
  45784. 586499841,
  45785. 988145025,
  45786. 935516892,
  45787. 3367335476,
  45788. 2599673255,
  45789. 2839830854,
  45790. 265290510,
  45791. 3972581182,
  45792. 2759138881,
  45793. 3795373465,
  45794. 1005194799,
  45795. 847297441,
  45796. 406762289,
  45797. 1314163512,
  45798. 1332590856,
  45799. 1866599683,
  45800. 4127851711,
  45801. 750260880,
  45802. 613907577,
  45803. 1450815602,
  45804. 3165620655,
  45805. 3734664991,
  45806. 3650291728,
  45807. 3012275730,
  45808. 3704569646,
  45809. 1427272223,
  45810. 778793252,
  45811. 1343938022,
  45812. 2676280711,
  45813. 2052605720,
  45814. 1946737175,
  45815. 3164576444,
  45816. 3914038668,
  45817. 3967478842,
  45818. 3682934266,
  45819. 1661551462,
  45820. 3294938066,
  45821. 4011595847,
  45822. 840292616,
  45823. 3712170807,
  45824. 616741398,
  45825. 312560963,
  45826. 711312465,
  45827. 1351876610,
  45828. 322626781,
  45829. 1910503582,
  45830. 271666773,
  45831. 2175563734,
  45832. 1594956187,
  45833. 70604529,
  45834. 3617834859,
  45835. 1007753275,
  45836. 1495573769,
  45837. 4069517037,
  45838. 2549218298,
  45839. 2663038764,
  45840. 504708206,
  45841. 2263041392,
  45842. 3941167025,
  45843. 2249088522,
  45844. 1514023603,
  45845. 1998579484,
  45846. 1312622330,
  45847. 694541497,
  45848. 2582060303,
  45849. 2151582166,
  45850. 1382467621,
  45851. 776784248,
  45852. 2618340202,
  45853. 3323268794,
  45854. 2497899128,
  45855. 2784771155,
  45856. 503983604,
  45857. 4076293799,
  45858. 907881277,
  45859. 423175695,
  45860. 432175456,
  45861. 1378068232,
  45862. 4145222326,
  45863. 3954048622,
  45864. 3938656102,
  45865. 3820766613,
  45866. 2793130115,
  45867. 2977904593,
  45868. 26017576,
  45869. 3274890735,
  45870. 3194772133,
  45871. 1700274565,
  45872. 1756076034,
  45873. 4006520079,
  45874. 3677328699,
  45875. 720338349,
  45876. 1533947780,
  45877. 354530856,
  45878. 688349552,
  45879. 3973924725,
  45880. 1637815568,
  45881. 332179504,
  45882. 3949051286,
  45883. 53804574,
  45884. 2852348879,
  45885. 3044236432,
  45886. 1282449977,
  45887. 3583942155,
  45888. 3416972820,
  45889. 4006381244,
  45890. 1617046695,
  45891. 2628476075,
  45892. 3002303598,
  45893. 1686838959,
  45894. 431878346,
  45895. 2686675385,
  45896. 1700445008,
  45897. 1080580658,
  45898. 1009431731,
  45899. 832498133,
  45900. 3223435511,
  45901. 2605976345,
  45902. 2271191193,
  45903. 2516031870,
  45904. 1648197032,
  45905. 4164389018,
  45906. 2548247927,
  45907. 300782431,
  45908. 375919233,
  45909. 238389289,
  45910. 3353747414,
  45911. 2531188641,
  45912. 2019080857,
  45913. 1475708069,
  45914. 455242339,
  45915. 2609103871,
  45916. 448939670,
  45917. 3451063019,
  45918. 1395535956,
  45919. 2413381860,
  45920. 1841049896,
  45921. 1491858159,
  45922. 885456874,
  45923. 4264095073,
  45924. 4001119347,
  45925. 1565136089,
  45926. 3898914787,
  45927. 1108368660,
  45928. 540939232,
  45929. 1173283510,
  45930. 2745871338,
  45931. 3681308437,
  45932. 4207628240,
  45933. 3343053890,
  45934. 4016749493,
  45935. 1699691293,
  45936. 1103962373,
  45937. 3625875870,
  45938. 2256883143,
  45939. 3830138730,
  45940. 1031889488,
  45941. 3479347698,
  45942. 1535977030,
  45943. 4236805024,
  45944. 3251091107,
  45945. 2132092099,
  45946. 1774941330,
  45947. 1199868427,
  45948. 1452454533,
  45949. 157007616,
  45950. 2904115357,
  45951. 342012276,
  45952. 595725824,
  45953. 1480756522,
  45954. 206960106,
  45955. 497939518,
  45956. 591360097,
  45957. 863170706,
  45958. 2375253569,
  45959. 3596610801,
  45960. 1814182875,
  45961. 2094937945,
  45962. 3421402208,
  45963. 1082520231,
  45964. 3463918190,
  45965. 2785509508,
  45966. 435703966,
  45967. 3908032597,
  45968. 1641649973,
  45969. 2842273706,
  45970. 3305899714,
  45971. 1510255612,
  45972. 2148256476,
  45973. 2655287854,
  45974. 3276092548,
  45975. 4258621189,
  45976. 236887753,
  45977. 3681803219,
  45978. 274041037,
  45979. 1734335097,
  45980. 3815195456,
  45981. 3317970021,
  45982. 1899903192,
  45983. 1026095262,
  45984. 4050517792,
  45985. 356393447,
  45986. 2410691914,
  45987. 3873677099,
  45988. 3682840055
  45989. ],
  45990. [
  45991. 3913112168,
  45992. 2491498743,
  45993. 4132185628,
  45994. 2489919796,
  45995. 1091903735,
  45996. 1979897079,
  45997. 3170134830,
  45998. 3567386728,
  45999. 3557303409,
  46000. 857797738,
  46001. 1136121015,
  46002. 1342202287,
  46003. 507115054,
  46004. 2535736646,
  46005. 337727348,
  46006. 3213592640,
  46007. 1301675037,
  46008. 2528481711,
  46009. 1895095763,
  46010. 1721773893,
  46011. 3216771564,
  46012. 62756741,
  46013. 2142006736,
  46014. 835421444,
  46015. 2531993523,
  46016. 1442658625,
  46017. 3659876326,
  46018. 2882144922,
  46019. 676362277,
  46020. 1392781812,
  46021. 170690266,
  46022. 3921047035,
  46023. 1759253602,
  46024. 3611846912,
  46025. 1745797284,
  46026. 664899054,
  46027. 1329594018,
  46028. 3901205900,
  46029. 3045908486,
  46030. 2062866102,
  46031. 2865634940,
  46032. 3543621612,
  46033. 3464012697,
  46034. 1080764994,
  46035. 553557557,
  46036. 3656615353,
  46037. 3996768171,
  46038. 991055499,
  46039. 499776247,
  46040. 1265440854,
  46041. 648242737,
  46042. 3940784050,
  46043. 980351604,
  46044. 3713745714,
  46045. 1749149687,
  46046. 3396870395,
  46047. 4211799374,
  46048. 3640570775,
  46049. 1161844396,
  46050. 3125318951,
  46051. 1431517754,
  46052. 545492359,
  46053. 4268468663,
  46054. 3499529547,
  46055. 1437099964,
  46056. 2702547544,
  46057. 3433638243,
  46058. 2581715763,
  46059. 2787789398,
  46060. 1060185593,
  46061. 1593081372,
  46062. 2418618748,
  46063. 4260947970,
  46064. 69676912,
  46065. 2159744348,
  46066. 86519011,
  46067. 2512459080,
  46068. 3838209314,
  46069. 1220612927,
  46070. 3339683548,
  46071. 133810670,
  46072. 1090789135,
  46073. 1078426020,
  46074. 1569222167,
  46075. 845107691,
  46076. 3583754449,
  46077. 4072456591,
  46078. 1091646820,
  46079. 628848692,
  46080. 1613405280,
  46081. 3757631651,
  46082. 526609435,
  46083. 236106946,
  46084. 48312990,
  46085. 2942717905,
  46086. 3402727701,
  46087. 1797494240,
  46088. 859738849,
  46089. 992217954,
  46090. 4005476642,
  46091. 2243076622,
  46092. 3870952857,
  46093. 3732016268,
  46094. 765654824,
  46095. 3490871365,
  46096. 2511836413,
  46097. 1685915746,
  46098. 3888969200,
  46099. 1414112111,
  46100. 2273134842,
  46101. 3281911079,
  46102. 4080962846,
  46103. 172450625,
  46104. 2569994100,
  46105. 980381355,
  46106. 4109958455,
  46107. 2819808352,
  46108. 2716589560,
  46109. 2568741196,
  46110. 3681446669,
  46111. 3329971472,
  46112. 1835478071,
  46113. 660984891,
  46114. 3704678404,
  46115. 4045999559,
  46116. 3422617507,
  46117. 3040415634,
  46118. 1762651403,
  46119. 1719377915,
  46120. 3470491036,
  46121. 2693910283,
  46122. 3642056355,
  46123. 3138596744,
  46124. 1364962596,
  46125. 2073328063,
  46126. 1983633131,
  46127. 926494387,
  46128. 3423689081,
  46129. 2150032023,
  46130. 4096667949,
  46131. 1749200295,
  46132. 3328846651,
  46133. 309677260,
  46134. 2016342300,
  46135. 1779581495,
  46136. 3079819751,
  46137. 111262694,
  46138. 1274766160,
  46139. 443224088,
  46140. 298511866,
  46141. 1025883608,
  46142. 3806446537,
  46143. 1145181785,
  46144. 168956806,
  46145. 3641502830,
  46146. 3584813610,
  46147. 1689216846,
  46148. 3666258015,
  46149. 3200248200,
  46150. 1692713982,
  46151. 2646376535,
  46152. 4042768518,
  46153. 1618508792,
  46154. 1610833997,
  46155. 3523052358,
  46156. 4130873264,
  46157. 2001055236,
  46158. 3610705100,
  46159. 2202168115,
  46160. 4028541809,
  46161. 2961195399,
  46162. 1006657119,
  46163. 2006996926,
  46164. 3186142756,
  46165. 1430667929,
  46166. 3210227297,
  46167. 1314452623,
  46168. 4074634658,
  46169. 4101304120,
  46170. 2273951170,
  46171. 1399257539,
  46172. 3367210612,
  46173. 3027628629,
  46174. 1190975929,
  46175. 2062231137,
  46176. 2333990788,
  46177. 2221543033,
  46178. 2438960610,
  46179. 1181637006,
  46180. 548689776,
  46181. 2362791313,
  46182. 3372408396,
  46183. 3104550113,
  46184. 3145860560,
  46185. 296247880,
  46186. 1970579870,
  46187. 3078560182,
  46188. 3769228297,
  46189. 1714227617,
  46190. 3291629107,
  46191. 3898220290,
  46192. 166772364,
  46193. 1251581989,
  46194. 493813264,
  46195. 448347421,
  46196. 195405023,
  46197. 2709975567,
  46198. 677966185,
  46199. 3703036547,
  46200. 1463355134,
  46201. 2715995803,
  46202. 1338867538,
  46203. 1343315457,
  46204. 2802222074,
  46205. 2684532164,
  46206. 233230375,
  46207. 2599980071,
  46208. 2000651841,
  46209. 3277868038,
  46210. 1638401717,
  46211. 4028070440,
  46212. 3237316320,
  46213. 6314154,
  46214. 819756386,
  46215. 300326615,
  46216. 590932579,
  46217. 1405279636,
  46218. 3267499572,
  46219. 3150704214,
  46220. 2428286686,
  46221. 3959192993,
  46222. 3461946742,
  46223. 1862657033,
  46224. 1266418056,
  46225. 963775037,
  46226. 2089974820,
  46227. 2263052895,
  46228. 1917689273,
  46229. 448879540,
  46230. 3550394620,
  46231. 3981727096,
  46232. 150775221,
  46233. 3627908307,
  46234. 1303187396,
  46235. 508620638,
  46236. 2975983352,
  46237. 2726630617,
  46238. 1817252668,
  46239. 1876281319,
  46240. 1457606340,
  46241. 908771278,
  46242. 3720792119,
  46243. 3617206836,
  46244. 2455994898,
  46245. 1729034894,
  46246. 1080033504
  46247. ],
  46248. [
  46249. 976866871,
  46250. 3556439503,
  46251. 2881648439,
  46252. 1522871579,
  46253. 1555064734,
  46254. 1336096578,
  46255. 3548522304,
  46256. 2579274686,
  46257. 3574697629,
  46258. 3205460757,
  46259. 3593280638,
  46260. 3338716283,
  46261. 3079412587,
  46262. 564236357,
  46263. 2993598910,
  46264. 1781952180,
  46265. 1464380207,
  46266. 3163844217,
  46267. 3332601554,
  46268. 1699332808,
  46269. 1393555694,
  46270. 1183702653,
  46271. 3581086237,
  46272. 1288719814,
  46273. 691649499,
  46274. 2847557200,
  46275. 2895455976,
  46276. 3193889540,
  46277. 2717570544,
  46278. 1781354906,
  46279. 1676643554,
  46280. 2592534050,
  46281. 3230253752,
  46282. 1126444790,
  46283. 2770207658,
  46284. 2633158820,
  46285. 2210423226,
  46286. 2615765581,
  46287. 2414155088,
  46288. 3127139286,
  46289. 673620729,
  46290. 2805611233,
  46291. 1269405062,
  46292. 4015350505,
  46293. 3341807571,
  46294. 4149409754,
  46295. 1057255273,
  46296. 2012875353,
  46297. 2162469141,
  46298. 2276492801,
  46299. 2601117357,
  46300. 993977747,
  46301. 3918593370,
  46302. 2654263191,
  46303. 753973209,
  46304. 36408145,
  46305. 2530585658,
  46306. 25011837,
  46307. 3520020182,
  46308. 2088578344,
  46309. 530523599,
  46310. 2918365339,
  46311. 1524020338,
  46312. 1518925132,
  46313. 3760827505,
  46314. 3759777254,
  46315. 1202760957,
  46316. 3985898139,
  46317. 3906192525,
  46318. 674977740,
  46319. 4174734889,
  46320. 2031300136,
  46321. 2019492241,
  46322. 3983892565,
  46323. 4153806404,
  46324. 3822280332,
  46325. 352677332,
  46326. 2297720250,
  46327. 60907813,
  46328. 90501309,
  46329. 3286998549,
  46330. 1016092578,
  46331. 2535922412,
  46332. 2839152426,
  46333. 457141659,
  46334. 509813237,
  46335. 4120667899,
  46336. 652014361,
  46337. 1966332200,
  46338. 2975202805,
  46339. 55981186,
  46340. 2327461051,
  46341. 676427537,
  46342. 3255491064,
  46343. 2882294119,
  46344. 3433927263,
  46345. 1307055953,
  46346. 942726286,
  46347. 933058658,
  46348. 2468411793,
  46349. 3933900994,
  46350. 4215176142,
  46351. 1361170020,
  46352. 2001714738,
  46353. 2830558078,
  46354. 3274259782,
  46355. 1222529897,
  46356. 1679025792,
  46357. 2729314320,
  46358. 3714953764,
  46359. 1770335741,
  46360. 151462246,
  46361. 3013232138,
  46362. 1682292957,
  46363. 1483529935,
  46364. 471910574,
  46365. 1539241949,
  46366. 458788160,
  46367. 3436315007,
  46368. 1807016891,
  46369. 3718408830,
  46370. 978976581,
  46371. 1043663428,
  46372. 3165965781,
  46373. 1927990952,
  46374. 4200891579,
  46375. 2372276910,
  46376. 3208408903,
  46377. 3533431907,
  46378. 1412390302,
  46379. 2931980059,
  46380. 4132332400,
  46381. 1947078029,
  46382. 3881505623,
  46383. 4168226417,
  46384. 2941484381,
  46385. 1077988104,
  46386. 1320477388,
  46387. 886195818,
  46388. 18198404,
  46389. 3786409e3,
  46390. 2509781533,
  46391. 112762804,
  46392. 3463356488,
  46393. 1866414978,
  46394. 891333506,
  46395. 18488651,
  46396. 661792760,
  46397. 1628790961,
  46398. 3885187036,
  46399. 3141171499,
  46400. 876946877,
  46401. 2693282273,
  46402. 1372485963,
  46403. 791857591,
  46404. 2686433993,
  46405. 3759982718,
  46406. 3167212022,
  46407. 3472953795,
  46408. 2716379847,
  46409. 445679433,
  46410. 3561995674,
  46411. 3504004811,
  46412. 3574258232,
  46413. 54117162,
  46414. 3331405415,
  46415. 2381918588,
  46416. 3769707343,
  46417. 4154350007,
  46418. 1140177722,
  46419. 4074052095,
  46420. 668550556,
  46421. 3214352940,
  46422. 367459370,
  46423. 261225585,
  46424. 2610173221,
  46425. 4209349473,
  46426. 3468074219,
  46427. 3265815641,
  46428. 314222801,
  46429. 3066103646,
  46430. 3808782860,
  46431. 282218597,
  46432. 3406013506,
  46433. 3773591054,
  46434. 379116347,
  46435. 1285071038,
  46436. 846784868,
  46437. 2669647154,
  46438. 3771962079,
  46439. 3550491691,
  46440. 2305946142,
  46441. 453669953,
  46442. 1268987020,
  46443. 3317592352,
  46444. 3279303384,
  46445. 3744833421,
  46446. 2610507566,
  46447. 3859509063,
  46448. 266596637,
  46449. 3847019092,
  46450. 517658769,
  46451. 3462560207,
  46452. 3443424879,
  46453. 370717030,
  46454. 4247526661,
  46455. 2224018117,
  46456. 4143653529,
  46457. 4112773975,
  46458. 2788324899,
  46459. 2477274417,
  46460. 1456262402,
  46461. 2901442914,
  46462. 1517677493,
  46463. 1846949527,
  46464. 2295493580,
  46465. 3734397586,
  46466. 2176403920,
  46467. 1280348187,
  46468. 1908823572,
  46469. 3871786941,
  46470. 846861322,
  46471. 1172426758,
  46472. 3287448474,
  46473. 3383383037,
  46474. 1655181056,
  46475. 3139813346,
  46476. 901632758,
  46477. 1897031941,
  46478. 2986607138,
  46479. 3066810236,
  46480. 3447102507,
  46481. 1393639104,
  46482. 373351379,
  46483. 950779232,
  46484. 625454576,
  46485. 3124240540,
  46486. 4148612726,
  46487. 2007998917,
  46488. 544563296,
  46489. 2244738638,
  46490. 2330496472,
  46491. 2058025392,
  46492. 1291430526,
  46493. 424198748,
  46494. 50039436,
  46495. 29584100,
  46496. 3605783033,
  46497. 2429876329,
  46498. 2791104160,
  46499. 1057563949,
  46500. 3255363231,
  46501. 3075367218,
  46502. 3463963227,
  46503. 1469046755,
  46504. 985887462
  46505. ]
  46506. ];
  46507. var BLOWFISH_CTX = {
  46508. pbox: [],
  46509. sbox: []
  46510. };
  46511. function F2(ctx, x) {
  46512. let a2 = x >> 24 & 255;
  46513. let b2 = x >> 16 & 255;
  46514. let c2 = x >> 8 & 255;
  46515. let d2 = x & 255;
  46516. let y2 = ctx.sbox[0][a2] + ctx.sbox[1][b2];
  46517. y2 = y2 ^ ctx.sbox[2][c2];
  46518. y2 = y2 + ctx.sbox[3][d2];
  46519. return y2;
  46520. }
  46521. function BlowFish_Encrypt(ctx, left, right) {
  46522. let Xl = left;
  46523. let Xr = right;
  46524. let temp;
  46525. for (let i2 = 0; i2 < N2; ++i2) {
  46526. Xl = Xl ^ ctx.pbox[i2];
  46527. Xr = F2(ctx, Xl) ^ Xr;
  46528. temp = Xl;
  46529. Xl = Xr;
  46530. Xr = temp;
  46531. }
  46532. temp = Xl;
  46533. Xl = Xr;
  46534. Xr = temp;
  46535. Xr = Xr ^ ctx.pbox[N2];
  46536. Xl = Xl ^ ctx.pbox[N2 + 1];
  46537. return { left: Xl, right: Xr };
  46538. }
  46539. function BlowFish_Decrypt(ctx, left, right) {
  46540. let Xl = left;
  46541. let Xr = right;
  46542. let temp;
  46543. for (let i2 = N2 + 1; i2 > 1; --i2) {
  46544. Xl = Xl ^ ctx.pbox[i2];
  46545. Xr = F2(ctx, Xl) ^ Xr;
  46546. temp = Xl;
  46547. Xl = Xr;
  46548. Xr = temp;
  46549. }
  46550. temp = Xl;
  46551. Xl = Xr;
  46552. Xr = temp;
  46553. Xr = Xr ^ ctx.pbox[1];
  46554. Xl = Xl ^ ctx.pbox[0];
  46555. return { left: Xl, right: Xr };
  46556. }
  46557. function BlowFishInit(ctx, key, keysize) {
  46558. for (let Row2 = 0; Row2 < 4; Row2++) {
  46559. ctx.sbox[Row2] = [];
  46560. for (let Col = 0; Col < 256; Col++) {
  46561. ctx.sbox[Row2][Col] = ORIG_S[Row2][Col];
  46562. }
  46563. }
  46564. let keyIndex = 0;
  46565. for (let index2 = 0; index2 < N2 + 2; index2++) {
  46566. ctx.pbox[index2] = ORIG_P[index2] ^ key[keyIndex];
  46567. keyIndex++;
  46568. if (keyIndex >= keysize) {
  46569. keyIndex = 0;
  46570. }
  46571. }
  46572. let Data1 = 0;
  46573. let Data2 = 0;
  46574. let res = 0;
  46575. for (let i2 = 0; i2 < N2 + 2; i2 += 2) {
  46576. res = BlowFish_Encrypt(ctx, Data1, Data2);
  46577. Data1 = res.left;
  46578. Data2 = res.right;
  46579. ctx.pbox[i2] = Data1;
  46580. ctx.pbox[i2 + 1] = Data2;
  46581. }
  46582. for (let i2 = 0; i2 < 4; i2++) {
  46583. for (let j2 = 0; j2 < 256; j2 += 2) {
  46584. res = BlowFish_Encrypt(ctx, Data1, Data2);
  46585. Data1 = res.left;
  46586. Data2 = res.right;
  46587. ctx.sbox[i2][j2] = Data1;
  46588. ctx.sbox[i2][j2 + 1] = Data2;
  46589. }
  46590. }
  46591. return true;
  46592. }
  46593. var Blowfish = C_algo.Blowfish = BlockCipher.extend({
  46594. _doReset: function() {
  46595. if (this._keyPriorReset === this._key) {
  46596. return;
  46597. }
  46598. var key = this._keyPriorReset = this._key;
  46599. var keyWords = key.words;
  46600. var keySize = key.sigBytes / 4;
  46601. BlowFishInit(BLOWFISH_CTX, keyWords, keySize);
  46602. },
  46603. encryptBlock: function(M2, offset) {
  46604. var res = BlowFish_Encrypt(BLOWFISH_CTX, M2[offset], M2[offset + 1]);
  46605. M2[offset] = res.left;
  46606. M2[offset + 1] = res.right;
  46607. },
  46608. decryptBlock: function(M2, offset) {
  46609. var res = BlowFish_Decrypt(BLOWFISH_CTX, M2[offset], M2[offset + 1]);
  46610. M2[offset] = res.left;
  46611. M2[offset + 1] = res.right;
  46612. },
  46613. blockSize: 64 / 32,
  46614. keySize: 128 / 32,
  46615. ivSize: 64 / 32
  46616. });
  46617. C2.Blowfish = BlockCipher._createHelper(Blowfish);
  46618. })();
  46619. return CryptoJS2.Blowfish;
  46620. });
  46621. })(blowfish);
  46622. return blowfish.exports;
  46623. }
  46624. (function(module2, exports2) {
  46625. (function(root, factory, undef) {
  46626. {
  46627. module2.exports = factory(requireCore(), requireX64Core(), requireLibTypedarrays(), requireEncUtf16(), requireEncBase64(), requireEncBase64url(), requireMd5(), requireSha1(), requireSha256(), requireSha224(), requireSha512(), requireSha384(), requireSha3(), requireRipemd160(), requireHmac(), requirePbkdf2(), requireEvpkdf(), requireCipherCore(), requireModeCfb(), requireModeCtr(), requireModeCtrGladman(), requireModeOfb(), requireModeEcb(), requirePadAnsix923(), requirePadIso10126(), requirePadIso97971(), requirePadZeropadding(), requirePadNopadding(), requireFormatHex(), requireAes(), requireTripledes(), requireRc4(), requireRabbit(), requireRabbitLegacy(), requireBlowfish());
  46628. }
  46629. })(commonjsGlobal, function(CryptoJS2) {
  46630. return CryptoJS2;
  46631. });
  46632. })(cryptoJs);
  46633. var cryptoJsExports = cryptoJs.exports;
  46634. const CryptoJS = /* @__PURE__ */ getDefaultExportFromCjs(cryptoJsExports);
  46635. const custom = {
  46636. "^u--(.*)": "@/uni_modules/uview-plus/components/u-$1/u-$1.vue",
  46637. "^up-(.*)": "@/uni_modules/uview-plus/components/u-$1/u-$1.vue",
  46638. "^u-([^-].*)": "@/uni_modules/uview-plus/components/u-$1/u-$1.vue"
  46639. };
  46640. const pages = [
  46641. {
  46642. path: "pages/home/index",
  46643. style: {
  46644. navigationBarTitleText: "",
  46645. enablePullDownRefresh: false
  46646. }
  46647. },
  46648. {
  46649. path: "pages/home/living",
  46650. style: {
  46651. navigationBarTitleText: "",
  46652. navigationBarTextStyle: "black",
  46653. enablePullDownRefresh: false,
  46654. navigationStyle: "custom",
  46655. "app-plus": {
  46656. bounce: "none"
  46657. }
  46658. }
  46659. },
  46660. {
  46661. path: "pages/user/index",
  46662. style: {
  46663. navigationBarTitleText: "",
  46664. navigationBarTextStyle: "black",
  46665. enablePullDownRefresh: false,
  46666. navigationStyle: "custom",
  46667. "app-plus": {
  46668. bounce: "none"
  46669. }
  46670. }
  46671. },
  46672. {
  46673. path: "pages/list/index",
  46674. style: {
  46675. navigationBarTitleText: "直播列表",
  46676. navigationBarTextStyle: "black",
  46677. "app-plus": {
  46678. bounce: "none"
  46679. }
  46680. }
  46681. },
  46682. {
  46683. path: "pages/home/live",
  46684. style: {
  46685. navigationBarTitleText: "",
  46686. navigationBarTextStyle: "black",
  46687. enablePullDownRefresh: false,
  46688. navigationStyle: "custom",
  46689. "app-plus": {
  46690. bounce: "none"
  46691. }
  46692. }
  46693. },
  46694. {
  46695. path: "pages/games/index",
  46696. style: {
  46697. navigationBarTitleText: "",
  46698. navigationBarTextStyle: "black",
  46699. enablePullDownRefresh: false,
  46700. navigationStyle: "custom",
  46701. "app-plus": {
  46702. bounce: "none"
  46703. }
  46704. }
  46705. },
  46706. {
  46707. path: "pages/auth/login",
  46708. style: {
  46709. navigationBarTitleText: "",
  46710. navigationBarTextStyle: "black",
  46711. enablePullDownRefresh: false,
  46712. navigationStyle: "custom",
  46713. "app-plus": {
  46714. bounce: "none"
  46715. }
  46716. }
  46717. },
  46718. {
  46719. path: "pages/auth/findpass",
  46720. style: {
  46721. navigationBarTitleText: "",
  46722. navigationBarTextStyle: "black",
  46723. enablePullDownRefresh: false,
  46724. navigationStyle: "custom",
  46725. "app-plus": {
  46726. bounce: "none"
  46727. }
  46728. }
  46729. },
  46730. {
  46731. path: "pages/auth/h5WxLogin",
  46732. style: {
  46733. navigationBarTitleText: "",
  46734. navigationBarTextStyle: "black",
  46735. enablePullDownRefresh: false,
  46736. navigationStyle: "custom",
  46737. "app-plus": {
  46738. bounce: "none"
  46739. }
  46740. }
  46741. },
  46742. {
  46743. path: "pages/auth/loginIndex",
  46744. style: {
  46745. navigationBarTitleText: "",
  46746. navigationBarTextStyle: "black",
  46747. enablePullDownRefresh: false,
  46748. navigationStyle: "custom",
  46749. "app-plus": {
  46750. bounce: "none"
  46751. }
  46752. }
  46753. },
  46754. {
  46755. path: "pages/auth/register",
  46756. style: {
  46757. navigationBarTitleText: "",
  46758. navigationBarTextStyle: "black",
  46759. enablePullDownRefresh: false,
  46760. navigationStyle: "custom",
  46761. "app-plus": {
  46762. bounce: "none"
  46763. }
  46764. }
  46765. }
  46766. ];
  46767. const subPackages = [
  46768. {
  46769. root: "pages_shop",
  46770. pages: [
  46771. {
  46772. path: "cart",
  46773. style: {
  46774. navigationBarTitleText: "购物车",
  46775. "app-plus": {
  46776. titleNView: false
  46777. }
  46778. }
  46779. },
  46780. {
  46781. path: "goods",
  46782. style: {
  46783. navigationBarTitleText: "商品详情",
  46784. enablePullDownRefresh: false
  46785. }
  46786. },
  46787. {
  46788. path: "store",
  46789. style: {
  46790. navigationBarTitleText: "",
  46791. enablePullDownRefresh: false,
  46792. navigationStyle: "custom",
  46793. navigationBarTextStyle: "black",
  46794. "app-plus": {
  46795. bounce: "none"
  46796. }
  46797. }
  46798. },
  46799. {
  46800. path: "order",
  46801. style: {
  46802. navigationBarTitleText: "我的订单",
  46803. navigationBarTextStyle: "black",
  46804. "app-plus": {
  46805. bounce: "none"
  46806. }
  46807. }
  46808. },
  46809. {
  46810. path: "confirmCreateOrder",
  46811. style: {
  46812. navigationBarTitleText: "确认订单",
  46813. navigationBarTextStyle: "black",
  46814. "app-plus": {
  46815. bounce: "none"
  46816. }
  46817. }
  46818. },
  46819. {
  46820. path: "paymentOrder",
  46821. style: {
  46822. navigationBarTitleText: "支付订单",
  46823. navigationBarTextStyle: "black",
  46824. "app-plus": {
  46825. bounce: "none"
  46826. }
  46827. }
  46828. },
  46829. {
  46830. path: "confirmPackageOrder",
  46831. style: {
  46832. navigationBarTitleText: "确认支付",
  46833. navigationBarTextStyle: "black",
  46834. "app-plus": {
  46835. bounce: "none"
  46836. }
  46837. }
  46838. },
  46839. {
  46840. path: "storeOrder",
  46841. style: {
  46842. navigationBarTitleText: "订单",
  46843. navigationBarTextStyle: "black",
  46844. "app-plus": {
  46845. bounce: "none"
  46846. }
  46847. }
  46848. },
  46849. {
  46850. path: "success",
  46851. style: {
  46852. navigationBarTitleText: "支付成功",
  46853. navigationBarTextStyle: "black",
  46854. "app-plus": {
  46855. bounce: "none"
  46856. }
  46857. }
  46858. }
  46859. ]
  46860. },
  46861. {
  46862. root: "pages_user",
  46863. pages: [
  46864. {
  46865. path: "address",
  46866. style: {
  46867. navigationBarTitleText: "收货地址",
  46868. "app-plus": {
  46869. titleNView: false
  46870. }
  46871. }
  46872. },
  46873. {
  46874. path: "addAddress",
  46875. style: {
  46876. navigationBarTitleText: "新建收货地址",
  46877. navigationBarTextStyle: "black",
  46878. "app-plus": {
  46879. bounce: "none"
  46880. }
  46881. }
  46882. }
  46883. ]
  46884. }
  46885. ];
  46886. const globalStyle = {
  46887. navigationBarTextStyle: "black",
  46888. navigationBarTitleText: "【S直播】",
  46889. navigationBarBackgroundColor: "#f5f5f5",
  46890. backgroundColor: "#f7f8fa"
  46891. };
  46892. const uniIdRouter = {};
  46893. const tabBar = {
  46894. color: "#AEAEAE",
  46895. selectedColor: "#000000",
  46896. fontSize: "12px",
  46897. borderStyle: "black",
  46898. backgroundColor: "#fff",
  46899. list: [
  46900. {
  46901. pagePath: "pages/list/index",
  46902. iconPath: "/static/tabBar/query.png",
  46903. selectedIconPath: "/static/tabBar/query_active.png",
  46904. text: "列表"
  46905. },
  46906. {
  46907. pagePath: "pages/games/index",
  46908. iconPath: "/static/tabBar/pulverize.png",
  46909. selectedIconPath: "/static/tabBar/pulverize_active.png",
  46910. text: "合同粉碎"
  46911. },
  46912. {
  46913. pagePath: "pages/user/index",
  46914. iconPath: "/static/tabBar/user.png",
  46915. selectedIconPath: "/static/tabBar/user_active.png",
  46916. text: "我的"
  46917. }
  46918. ]
  46919. };
  46920. const e = {
  46921. custom,
  46922. pages,
  46923. subPackages,
  46924. globalStyle,
  46925. uniIdRouter,
  46926. tabBar
  46927. };
  46928. var define_process_env_UNI_SECURE_NETWORK_CONFIG_default = [];
  46929. function t(e2) {
  46930. return e2 && e2.__esModule && Object.prototype.hasOwnProperty.call(e2, "default") ? e2.default : e2;
  46931. }
  46932. function n(e2, t2, n2) {
  46933. return e2(n2 = { path: t2, exports: {}, require: function(e3, t3) {
  46934. return function() {
  46935. throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");
  46936. }(null == t3 && n2.path);
  46937. } }, n2.exports), n2.exports;
  46938. }
  46939. var s = n(function(e2, t2) {
  46940. var n2;
  46941. e2.exports = (n2 = n2 || function(e3, t3) {
  46942. var n3 = Object.create || /* @__PURE__ */ function() {
  46943. function e4() {
  46944. }
  46945. return function(t4) {
  46946. var n4;
  46947. return e4.prototype = t4, n4 = new e4(), e4.prototype = null, n4;
  46948. };
  46949. }(), s2 = {}, r2 = s2.lib = {}, i2 = r2.Base = { extend: function(e4) {
  46950. var t4 = n3(this);
  46951. return e4 && t4.mixIn(e4), t4.hasOwnProperty("init") && this.init !== t4.init || (t4.init = function() {
  46952. t4.$super.init.apply(this, arguments);
  46953. }), t4.init.prototype = t4, t4.$super = this, t4;
  46954. }, create: function() {
  46955. var e4 = this.extend();
  46956. return e4.init.apply(e4, arguments), e4;
  46957. }, init: function() {
  46958. }, mixIn: function(e4) {
  46959. for (var t4 in e4)
  46960. e4.hasOwnProperty(t4) && (this[t4] = e4[t4]);
  46961. e4.hasOwnProperty("toString") && (this.toString = e4.toString);
  46962. }, clone: function() {
  46963. return this.init.prototype.extend(this);
  46964. } }, o2 = r2.WordArray = i2.extend({ init: function(e4, n4) {
  46965. e4 = this.words = e4 || [], this.sigBytes = n4 != t3 ? n4 : 4 * e4.length;
  46966. }, toString: function(e4) {
  46967. return (e4 || c2).stringify(this);
  46968. }, concat: function(e4) {
  46969. var t4 = this.words, n4 = e4.words, s3 = this.sigBytes, r3 = e4.sigBytes;
  46970. if (this.clamp(), s3 % 4)
  46971. for (var i3 = 0; i3 < r3; i3++) {
  46972. var o3 = n4[i3 >>> 2] >>> 24 - i3 % 4 * 8 & 255;
  46973. t4[s3 + i3 >>> 2] |= o3 << 24 - (s3 + i3) % 4 * 8;
  46974. }
  46975. else
  46976. for (i3 = 0; i3 < r3; i3 += 4)
  46977. t4[s3 + i3 >>> 2] = n4[i3 >>> 2];
  46978. return this.sigBytes += r3, this;
  46979. }, clamp: function() {
  46980. var t4 = this.words, n4 = this.sigBytes;
  46981. t4[n4 >>> 2] &= 4294967295 << 32 - n4 % 4 * 8, t4.length = e3.ceil(n4 / 4);
  46982. }, clone: function() {
  46983. var e4 = i2.clone.call(this);
  46984. return e4.words = this.words.slice(0), e4;
  46985. }, random: function(t4) {
  46986. for (var n4, s3 = [], r3 = function(t5) {
  46987. var n5 = 987654321, s4 = 4294967295;
  46988. return function() {
  46989. var r4 = ((n5 = 36969 * (65535 & n5) + (n5 >> 16) & s4) << 16) + (t5 = 18e3 * (65535 & t5) + (t5 >> 16) & s4) & s4;
  46990. return r4 /= 4294967296, (r4 += 0.5) * (e3.random() > 0.5 ? 1 : -1);
  46991. };
  46992. }, i3 = 0; i3 < t4; i3 += 4) {
  46993. var a3 = r3(4294967296 * (n4 || e3.random()));
  46994. n4 = 987654071 * a3(), s3.push(4294967296 * a3() | 0);
  46995. }
  46996. return new o2.init(s3, t4);
  46997. } }), a2 = s2.enc = {}, c2 = a2.Hex = { stringify: function(e4) {
  46998. for (var t4 = e4.words, n4 = e4.sigBytes, s3 = [], r3 = 0; r3 < n4; r3++) {
  46999. var i3 = t4[r3 >>> 2] >>> 24 - r3 % 4 * 8 & 255;
  47000. s3.push((i3 >>> 4).toString(16)), s3.push((15 & i3).toString(16));
  47001. }
  47002. return s3.join("");
  47003. }, parse: function(e4) {
  47004. for (var t4 = e4.length, n4 = [], s3 = 0; s3 < t4; s3 += 2)
  47005. n4[s3 >>> 3] |= parseInt(e4.substr(s3, 2), 16) << 24 - s3 % 8 * 4;
  47006. return new o2.init(n4, t4 / 2);
  47007. } }, u2 = a2.Latin1 = { stringify: function(e4) {
  47008. for (var t4 = e4.words, n4 = e4.sigBytes, s3 = [], r3 = 0; r3 < n4; r3++) {
  47009. var i3 = t4[r3 >>> 2] >>> 24 - r3 % 4 * 8 & 255;
  47010. s3.push(String.fromCharCode(i3));
  47011. }
  47012. return s3.join("");
  47013. }, parse: function(e4) {
  47014. for (var t4 = e4.length, n4 = [], s3 = 0; s3 < t4; s3++)
  47015. n4[s3 >>> 2] |= (255 & e4.charCodeAt(s3)) << 24 - s3 % 4 * 8;
  47016. return new o2.init(n4, t4);
  47017. } }, h2 = a2.Utf8 = { stringify: function(e4) {
  47018. try {
  47019. return decodeURIComponent(escape(u2.stringify(e4)));
  47020. } catch (e5) {
  47021. throw new Error("Malformed UTF-8 data");
  47022. }
  47023. }, parse: function(e4) {
  47024. return u2.parse(unescape(encodeURIComponent(e4)));
  47025. } }, l2 = r2.BufferedBlockAlgorithm = i2.extend({ reset: function() {
  47026. this._data = new o2.init(), this._nDataBytes = 0;
  47027. }, _append: function(e4) {
  47028. "string" == typeof e4 && (e4 = h2.parse(e4)), this._data.concat(e4), this._nDataBytes += e4.sigBytes;
  47029. }, _process: function(t4) {
  47030. var n4 = this._data, s3 = n4.words, r3 = n4.sigBytes, i3 = this.blockSize, a3 = r3 / (4 * i3), c3 = (a3 = t4 ? e3.ceil(a3) : e3.max((0 | a3) - this._minBufferSize, 0)) * i3, u3 = e3.min(4 * c3, r3);
  47031. if (c3) {
  47032. for (var h3 = 0; h3 < c3; h3 += i3)
  47033. this._doProcessBlock(s3, h3);
  47034. var l3 = s3.splice(0, c3);
  47035. n4.sigBytes -= u3;
  47036. }
  47037. return new o2.init(l3, u3);
  47038. }, clone: function() {
  47039. var e4 = i2.clone.call(this);
  47040. return e4._data = this._data.clone(), e4;
  47041. }, _minBufferSize: 0 });
  47042. r2.Hasher = l2.extend({ cfg: i2.extend(), init: function(e4) {
  47043. this.cfg = this.cfg.extend(e4), this.reset();
  47044. }, reset: function() {
  47045. l2.reset.call(this), this._doReset();
  47046. }, update: function(e4) {
  47047. return this._append(e4), this._process(), this;
  47048. }, finalize: function(e4) {
  47049. return e4 && this._append(e4), this._doFinalize();
  47050. }, blockSize: 16, _createHelper: function(e4) {
  47051. return function(t4, n4) {
  47052. return new e4.init(n4).finalize(t4);
  47053. };
  47054. }, _createHmacHelper: function(e4) {
  47055. return function(t4, n4) {
  47056. return new d2.HMAC.init(e4, n4).finalize(t4);
  47057. };
  47058. } });
  47059. var d2 = s2.algo = {};
  47060. return s2;
  47061. }(Math), n2);
  47062. }), r = s, i = (n(function(e2, t2) {
  47063. var n2;
  47064. e2.exports = (n2 = r, function(e3) {
  47065. var t3 = n2, s2 = t3.lib, r2 = s2.WordArray, i2 = s2.Hasher, o2 = t3.algo, a2 = [];
  47066. !function() {
  47067. for (var t4 = 0; t4 < 64; t4++)
  47068. a2[t4] = 4294967296 * e3.abs(e3.sin(t4 + 1)) | 0;
  47069. }();
  47070. var c2 = o2.MD5 = i2.extend({ _doReset: function() {
  47071. this._hash = new r2.init([1732584193, 4023233417, 2562383102, 271733878]);
  47072. }, _doProcessBlock: function(e4, t4) {
  47073. for (var n3 = 0; n3 < 16; n3++) {
  47074. var s3 = t4 + n3, r3 = e4[s3];
  47075. e4[s3] = 16711935 & (r3 << 8 | r3 >>> 24) | 4278255360 & (r3 << 24 | r3 >>> 8);
  47076. }
  47077. var i3 = this._hash.words, o3 = e4[t4 + 0], c3 = e4[t4 + 1], p2 = e4[t4 + 2], f2 = e4[t4 + 3], g2 = e4[t4 + 4], m2 = e4[t4 + 5], y2 = e4[t4 + 6], _2 = e4[t4 + 7], w2 = e4[t4 + 8], I2 = e4[t4 + 9], v2 = e4[t4 + 10], S2 = e4[t4 + 11], T2 = e4[t4 + 12], b2 = e4[t4 + 13], E2 = e4[t4 + 14], k2 = e4[t4 + 15], A2 = i3[0], P2 = i3[1], C2 = i3[2], O2 = i3[3];
  47078. A2 = u2(A2, P2, C2, O2, o3, 7, a2[0]), O2 = u2(O2, A2, P2, C2, c3, 12, a2[1]), C2 = u2(C2, O2, A2, P2, p2, 17, a2[2]), P2 = u2(P2, C2, O2, A2, f2, 22, a2[3]), A2 = u2(A2, P2, C2, O2, g2, 7, a2[4]), O2 = u2(O2, A2, P2, C2, m2, 12, a2[5]), C2 = u2(C2, O2, A2, P2, y2, 17, a2[6]), P2 = u2(P2, C2, O2, A2, _2, 22, a2[7]), A2 = u2(A2, P2, C2, O2, w2, 7, a2[8]), O2 = u2(O2, A2, P2, C2, I2, 12, a2[9]), C2 = u2(C2, O2, A2, P2, v2, 17, a2[10]), P2 = u2(P2, C2, O2, A2, S2, 22, a2[11]), A2 = u2(A2, P2, C2, O2, T2, 7, a2[12]), O2 = u2(O2, A2, P2, C2, b2, 12, a2[13]), C2 = u2(C2, O2, A2, P2, E2, 17, a2[14]), A2 = h2(A2, P2 = u2(P2, C2, O2, A2, k2, 22, a2[15]), C2, O2, c3, 5, a2[16]), O2 = h2(O2, A2, P2, C2, y2, 9, a2[17]), C2 = h2(C2, O2, A2, P2, S2, 14, a2[18]), P2 = h2(P2, C2, O2, A2, o3, 20, a2[19]), A2 = h2(A2, P2, C2, O2, m2, 5, a2[20]), O2 = h2(O2, A2, P2, C2, v2, 9, a2[21]), C2 = h2(C2, O2, A2, P2, k2, 14, a2[22]), P2 = h2(P2, C2, O2, A2, g2, 20, a2[23]), A2 = h2(A2, P2, C2, O2, I2, 5, a2[24]), O2 = h2(O2, A2, P2, C2, E2, 9, a2[25]), C2 = h2(C2, O2, A2, P2, f2, 14, a2[26]), P2 = h2(P2, C2, O2, A2, w2, 20, a2[27]), A2 = h2(A2, P2, C2, O2, b2, 5, a2[28]), O2 = h2(O2, A2, P2, C2, p2, 9, a2[29]), C2 = h2(C2, O2, A2, P2, _2, 14, a2[30]), A2 = l2(A2, P2 = h2(P2, C2, O2, A2, T2, 20, a2[31]), C2, O2, m2, 4, a2[32]), O2 = l2(O2, A2, P2, C2, w2, 11, a2[33]), C2 = l2(C2, O2, A2, P2, S2, 16, a2[34]), P2 = l2(P2, C2, O2, A2, E2, 23, a2[35]), A2 = l2(A2, P2, C2, O2, c3, 4, a2[36]), O2 = l2(O2, A2, P2, C2, g2, 11, a2[37]), C2 = l2(C2, O2, A2, P2, _2, 16, a2[38]), P2 = l2(P2, C2, O2, A2, v2, 23, a2[39]), A2 = l2(A2, P2, C2, O2, b2, 4, a2[40]), O2 = l2(O2, A2, P2, C2, o3, 11, a2[41]), C2 = l2(C2, O2, A2, P2, f2, 16, a2[42]), P2 = l2(P2, C2, O2, A2, y2, 23, a2[43]), A2 = l2(A2, P2, C2, O2, I2, 4, a2[44]), O2 = l2(O2, A2, P2, C2, T2, 11, a2[45]), C2 = l2(C2, O2, A2, P2, k2, 16, a2[46]), A2 = d2(A2, P2 = l2(P2, C2, O2, A2, p2, 23, a2[47]), C2, O2, o3, 6, a2[48]), O2 = d2(O2, A2, P2, C2, _2, 10, a2[49]), C2 = d2(C2, O2, A2, P2, E2, 15, a2[50]), P2 = d2(P2, C2, O2, A2, m2, 21, a2[51]), A2 = d2(A2, P2, C2, O2, T2, 6, a2[52]), O2 = d2(O2, A2, P2, C2, f2, 10, a2[53]), C2 = d2(C2, O2, A2, P2, v2, 15, a2[54]), P2 = d2(P2, C2, O2, A2, c3, 21, a2[55]), A2 = d2(A2, P2, C2, O2, w2, 6, a2[56]), O2 = d2(O2, A2, P2, C2, k2, 10, a2[57]), C2 = d2(C2, O2, A2, P2, y2, 15, a2[58]), P2 = d2(P2, C2, O2, A2, b2, 21, a2[59]), A2 = d2(A2, P2, C2, O2, g2, 6, a2[60]), O2 = d2(O2, A2, P2, C2, S2, 10, a2[61]), C2 = d2(C2, O2, A2, P2, p2, 15, a2[62]), P2 = d2(P2, C2, O2, A2, I2, 21, a2[63]), i3[0] = i3[0] + A2 | 0, i3[1] = i3[1] + P2 | 0, i3[2] = i3[2] + C2 | 0, i3[3] = i3[3] + O2 | 0;
  47079. }, _doFinalize: function() {
  47080. var t4 = this._data, n3 = t4.words, s3 = 8 * this._nDataBytes, r3 = 8 * t4.sigBytes;
  47081. n3[r3 >>> 5] |= 128 << 24 - r3 % 32;
  47082. var i3 = e3.floor(s3 / 4294967296), o3 = s3;
  47083. n3[15 + (r3 + 64 >>> 9 << 4)] = 16711935 & (i3 << 8 | i3 >>> 24) | 4278255360 & (i3 << 24 | i3 >>> 8), n3[14 + (r3 + 64 >>> 9 << 4)] = 16711935 & (o3 << 8 | o3 >>> 24) | 4278255360 & (o3 << 24 | o3 >>> 8), t4.sigBytes = 4 * (n3.length + 1), this._process();
  47084. for (var a3 = this._hash, c3 = a3.words, u3 = 0; u3 < 4; u3++) {
  47085. var h3 = c3[u3];
  47086. c3[u3] = 16711935 & (h3 << 8 | h3 >>> 24) | 4278255360 & (h3 << 24 | h3 >>> 8);
  47087. }
  47088. return a3;
  47089. }, clone: function() {
  47090. var e4 = i2.clone.call(this);
  47091. return e4._hash = this._hash.clone(), e4;
  47092. } });
  47093. function u2(e4, t4, n3, s3, r3, i3, o3) {
  47094. var a3 = e4 + (t4 & n3 | ~t4 & s3) + r3 + o3;
  47095. return (a3 << i3 | a3 >>> 32 - i3) + t4;
  47096. }
  47097. function h2(e4, t4, n3, s3, r3, i3, o3) {
  47098. var a3 = e4 + (t4 & s3 | n3 & ~s3) + r3 + o3;
  47099. return (a3 << i3 | a3 >>> 32 - i3) + t4;
  47100. }
  47101. function l2(e4, t4, n3, s3, r3, i3, o3) {
  47102. var a3 = e4 + (t4 ^ n3 ^ s3) + r3 + o3;
  47103. return (a3 << i3 | a3 >>> 32 - i3) + t4;
  47104. }
  47105. function d2(e4, t4, n3, s3, r3, i3, o3) {
  47106. var a3 = e4 + (n3 ^ (t4 | ~s3)) + r3 + o3;
  47107. return (a3 << i3 | a3 >>> 32 - i3) + t4;
  47108. }
  47109. t3.MD5 = i2._createHelper(c2), t3.HmacMD5 = i2._createHmacHelper(c2);
  47110. }(Math), n2.MD5);
  47111. }), n(function(e2, t2) {
  47112. var n2;
  47113. e2.exports = (n2 = r, void function() {
  47114. var e3 = n2, t3 = e3.lib.Base, s2 = e3.enc.Utf8;
  47115. e3.algo.HMAC = t3.extend({ init: function(e4, t4) {
  47116. e4 = this._hasher = new e4.init(), "string" == typeof t4 && (t4 = s2.parse(t4));
  47117. var n3 = e4.blockSize, r2 = 4 * n3;
  47118. t4.sigBytes > r2 && (t4 = e4.finalize(t4)), t4.clamp();
  47119. for (var i2 = this._oKey = t4.clone(), o2 = this._iKey = t4.clone(), a2 = i2.words, c2 = o2.words, u2 = 0; u2 < n3; u2++)
  47120. a2[u2] ^= 1549556828, c2[u2] ^= 909522486;
  47121. i2.sigBytes = o2.sigBytes = r2, this.reset();
  47122. }, reset: function() {
  47123. var e4 = this._hasher;
  47124. e4.reset(), e4.update(this._iKey);
  47125. }, update: function(e4) {
  47126. return this._hasher.update(e4), this;
  47127. }, finalize: function(e4) {
  47128. var t4 = this._hasher, n3 = t4.finalize(e4);
  47129. return t4.reset(), t4.finalize(this._oKey.clone().concat(n3));
  47130. } });
  47131. }());
  47132. }), n(function(e2, t2) {
  47133. e2.exports = r.HmacMD5;
  47134. })), o = n(function(e2, t2) {
  47135. e2.exports = r.enc.Utf8;
  47136. }), a = n(function(e2, t2) {
  47137. var n2;
  47138. e2.exports = (n2 = r, function() {
  47139. var e3 = n2, t3 = e3.lib.WordArray;
  47140. function s2(e4, n3, s3) {
  47141. for (var r2 = [], i2 = 0, o2 = 0; o2 < n3; o2++)
  47142. if (o2 % 4) {
  47143. var a2 = s3[e4.charCodeAt(o2 - 1)] << o2 % 4 * 2, c2 = s3[e4.charCodeAt(o2)] >>> 6 - o2 % 4 * 2;
  47144. r2[i2 >>> 2] |= (a2 | c2) << 24 - i2 % 4 * 8, i2++;
  47145. }
  47146. return t3.create(r2, i2);
  47147. }
  47148. e3.enc.Base64 = { stringify: function(e4) {
  47149. var t4 = e4.words, n3 = e4.sigBytes, s3 = this._map;
  47150. e4.clamp();
  47151. for (var r2 = [], i2 = 0; i2 < n3; i2 += 3)
  47152. for (var o2 = (t4[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255) << 16 | (t4[i2 + 1 >>> 2] >>> 24 - (i2 + 1) % 4 * 8 & 255) << 8 | t4[i2 + 2 >>> 2] >>> 24 - (i2 + 2) % 4 * 8 & 255, a2 = 0; a2 < 4 && i2 + 0.75 * a2 < n3; a2++)
  47153. r2.push(s3.charAt(o2 >>> 6 * (3 - a2) & 63));
  47154. var c2 = s3.charAt(64);
  47155. if (c2)
  47156. for (; r2.length % 4; )
  47157. r2.push(c2);
  47158. return r2.join("");
  47159. }, parse: function(e4) {
  47160. var t4 = e4.length, n3 = this._map, r2 = this._reverseMap;
  47161. if (!r2) {
  47162. r2 = this._reverseMap = [];
  47163. for (var i2 = 0; i2 < n3.length; i2++)
  47164. r2[n3.charCodeAt(i2)] = i2;
  47165. }
  47166. var o2 = n3.charAt(64);
  47167. if (o2) {
  47168. var a2 = e4.indexOf(o2);
  47169. -1 !== a2 && (t4 = a2);
  47170. }
  47171. return s2(e4, t4, r2);
  47172. }, _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" };
  47173. }(), n2.enc.Base64);
  47174. });
  47175. const c = "uni_id_token", u = "uni_id_token_expired", h = "uniIdToken", l = { DEFAULT: "FUNCTION", FUNCTION: "FUNCTION", OBJECT: "OBJECT", CLIENT_DB: "CLIENT_DB" }, d = "pending", p = "fulfilled", f = "rejected";
  47176. function g(e2) {
  47177. return Object.prototype.toString.call(e2).slice(8, -1).toLowerCase();
  47178. }
  47179. function m(e2) {
  47180. return "object" === g(e2);
  47181. }
  47182. function y(e2) {
  47183. return "function" == typeof e2;
  47184. }
  47185. function _(e2) {
  47186. return function() {
  47187. try {
  47188. return e2.apply(e2, arguments);
  47189. } catch (e3) {
  47190. console.error(e3);
  47191. }
  47192. };
  47193. }
  47194. const w = "REJECTED", I = "NOT_PENDING";
  47195. class v {
  47196. constructor({ createPromise: e2, retryRule: t2 = w } = {}) {
  47197. this.createPromise = e2, this.status = null, this.promise = null, this.retryRule = t2;
  47198. }
  47199. get needRetry() {
  47200. if (!this.status)
  47201. return true;
  47202. switch (this.retryRule) {
  47203. case w:
  47204. return this.status === f;
  47205. case I:
  47206. return this.status !== d;
  47207. }
  47208. }
  47209. exec() {
  47210. return this.needRetry ? (this.status = d, this.promise = this.createPromise().then((e2) => (this.status = p, Promise.resolve(e2)), (e2) => (this.status = f, Promise.reject(e2))), this.promise) : this.promise;
  47211. }
  47212. }
  47213. class S {
  47214. constructor() {
  47215. this._callback = {};
  47216. }
  47217. addListener(e2, t2) {
  47218. this._callback[e2] || (this._callback[e2] = []), this._callback[e2].push(t2);
  47219. }
  47220. on(e2, t2) {
  47221. return this.addListener(e2, t2);
  47222. }
  47223. removeListener(e2, t2) {
  47224. if (!t2)
  47225. throw new Error('The "listener" argument must be of type function. Received undefined');
  47226. const n2 = this._callback[e2];
  47227. if (!n2)
  47228. return;
  47229. const s2 = function(e3, t3) {
  47230. for (let n3 = e3.length - 1; n3 >= 0; n3--)
  47231. if (e3[n3] === t3)
  47232. return n3;
  47233. return -1;
  47234. }(n2, t2);
  47235. n2.splice(s2, 1);
  47236. }
  47237. off(e2, t2) {
  47238. return this.removeListener(e2, t2);
  47239. }
  47240. removeAllListener(e2) {
  47241. delete this._callback[e2];
  47242. }
  47243. emit(e2, ...t2) {
  47244. const n2 = this._callback[e2];
  47245. if (n2)
  47246. for (let e3 = 0; e3 < n2.length; e3++)
  47247. n2[e3](...t2);
  47248. }
  47249. }
  47250. function T(e2) {
  47251. return e2 && "string" == typeof e2 ? JSON.parse(e2) : e2;
  47252. }
  47253. const b = true, E = "mp-weixin", A = T(define_process_env_UNI_SECURE_NETWORK_CONFIG_default), P = E, C = T(""), O = T("[]") || [];
  47254. let N = "";
  47255. try {
  47256. N = "__UNI__90F7D71";
  47257. } catch (e2) {
  47258. }
  47259. let L = {};
  47260. function U(e2, t2 = {}) {
  47261. var n2, s2;
  47262. return n2 = L, s2 = e2, Object.prototype.hasOwnProperty.call(n2, s2) || (L[e2] = t2), L[e2];
  47263. }
  47264. const M = ["invoke", "success", "fail", "complete"], q = U("_globalUniCloudInterceptor");
  47265. function F(e2, t2) {
  47266. q[e2] || (q[e2] = {}), m(t2) && Object.keys(t2).forEach((n2) => {
  47267. M.indexOf(n2) > -1 && function(e3, t3, n3) {
  47268. let s2 = q[e3][t3];
  47269. s2 || (s2 = q[e3][t3] = []), -1 === s2.indexOf(n3) && y(n3) && s2.push(n3);
  47270. }(e2, n2, t2[n2]);
  47271. });
  47272. }
  47273. function K(e2, t2) {
  47274. q[e2] || (q[e2] = {}), m(t2) ? Object.keys(t2).forEach((n2) => {
  47275. M.indexOf(n2) > -1 && function(e3, t3, n3) {
  47276. const s2 = q[e3][t3];
  47277. if (!s2)
  47278. return;
  47279. const r2 = s2.indexOf(n3);
  47280. r2 > -1 && s2.splice(r2, 1);
  47281. }(e2, n2, t2[n2]);
  47282. }) : delete q[e2];
  47283. }
  47284. function j(e2, t2) {
  47285. return e2 && 0 !== e2.length ? e2.reduce((e3, n2) => e3.then(() => n2(t2)), Promise.resolve()) : Promise.resolve();
  47286. }
  47287. function $(e2, t2) {
  47288. return q[e2] && q[e2][t2] || [];
  47289. }
  47290. function B(e2) {
  47291. F("callObject", e2);
  47292. }
  47293. const W = U("_globalUniCloudListener"), H = { RESPONSE: "response", NEED_LOGIN: "needLogin", REFRESH_TOKEN: "refreshToken" }, J = { CLIENT_DB: "clientdb", CLOUD_FUNCTION: "cloudfunction", CLOUD_OBJECT: "cloudobject" };
  47294. function z(e2) {
  47295. return W[e2] || (W[e2] = []), W[e2];
  47296. }
  47297. function V(e2, t2) {
  47298. const n2 = z(e2);
  47299. n2.includes(t2) || n2.push(t2);
  47300. }
  47301. function G(e2, t2) {
  47302. const n2 = z(e2), s2 = n2.indexOf(t2);
  47303. -1 !== s2 && n2.splice(s2, 1);
  47304. }
  47305. function Y(e2, t2) {
  47306. const n2 = z(e2);
  47307. for (let e3 = 0; e3 < n2.length; e3++) {
  47308. (0, n2[e3])(t2);
  47309. }
  47310. }
  47311. let Q, X = false;
  47312. function Z() {
  47313. return Q || (Q = new Promise((e2) => {
  47314. X && e2(), function t2() {
  47315. if ("function" == typeof getCurrentPages) {
  47316. const t3 = getCurrentPages();
  47317. t3 && t3[0] && (X = true, e2());
  47318. }
  47319. X || setTimeout(() => {
  47320. t2();
  47321. }, 30);
  47322. }();
  47323. }), Q);
  47324. }
  47325. function ee(e2) {
  47326. const t2 = {};
  47327. for (const n2 in e2) {
  47328. const s2 = e2[n2];
  47329. y(s2) && (t2[n2] = _(s2));
  47330. }
  47331. return t2;
  47332. }
  47333. class te extends Error {
  47334. constructor(e2) {
  47335. const t2 = e2.message || e2.errMsg || "unknown system error";
  47336. super(t2), this.errMsg = t2, this.code = this.errCode = e2.code || e2.errCode || "SYSTEM_ERROR", this.errSubject = this.subject = e2.subject || e2.errSubject, this.cause = e2.cause, this.requestId = e2.requestId;
  47337. }
  47338. toJson(e2 = 0) {
  47339. if (!(e2 >= 10))
  47340. return e2++, { errCode: this.errCode, errMsg: this.errMsg, errSubject: this.errSubject, cause: this.cause && this.cause.toJson ? this.cause.toJson(e2) : this.cause };
  47341. }
  47342. }
  47343. var ne = { request: (e2) => index.request(e2), uploadFile: (e2) => index.uploadFile(e2), setStorageSync: (e2, t2) => index.setStorageSync(e2, t2), getStorageSync: (e2) => index.getStorageSync(e2), removeStorageSync: (e2) => index.removeStorageSync(e2), clearStorageSync: () => index.clearStorageSync(), connectSocket: (e2) => index.connectSocket(e2) };
  47344. function se(e2) {
  47345. return e2 && se(e2.__v_raw) || e2;
  47346. }
  47347. function re() {
  47348. return { token: ne.getStorageSync(c) || ne.getStorageSync(h), tokenExpired: ne.getStorageSync(u) };
  47349. }
  47350. function ie({ token: e2, tokenExpired: t2 } = {}) {
  47351. e2 && ne.setStorageSync(c, e2), t2 && ne.setStorageSync(u, t2);
  47352. }
  47353. let oe, ae;
  47354. function ce() {
  47355. return oe || (oe = wx$1.canIUse("getAppBaseInfo") && wx$1.canIUse("getDeviceInfo") ? { ...index.getAppBaseInfo(), ...index.getDeviceInfo() } : index.getSystemInfoSync()), oe;
  47356. }
  47357. function ue() {
  47358. let e2, t2;
  47359. try {
  47360. if (index.getLaunchOptionsSync) {
  47361. if (index.getLaunchOptionsSync.toString().indexOf("not yet implemented") > -1)
  47362. return;
  47363. const { scene: n2, channel: s2 } = index.getLaunchOptionsSync();
  47364. e2 = s2, t2 = n2;
  47365. }
  47366. } catch (e3) {
  47367. }
  47368. return { channel: e2, scene: t2 };
  47369. }
  47370. let he = {};
  47371. function le() {
  47372. const e2 = index.getLocale && index.getLocale() || "en";
  47373. if (ae)
  47374. return { ...he, ...ae, locale: e2, LOCALE: e2 };
  47375. const t2 = ce(), { deviceId: n2, osName: s2, uniPlatform: r2, appId: i2 } = t2, o2 = ["appId", "appLanguage", "appName", "appVersion", "appVersionCode", "appWgtVersion", "browserName", "browserVersion", "deviceBrand", "deviceId", "deviceModel", "deviceType", "osName", "osVersion", "romName", "romVersion", "ua", "hostName", "hostVersion", "uniPlatform", "uniRuntimeVersion", "uniRuntimeVersionCode", "uniCompilerVersion", "uniCompilerVersionCode"];
  47376. for (const e3 in t2)
  47377. Object.hasOwnProperty.call(t2, e3) && -1 === o2.indexOf(e3) && delete t2[e3];
  47378. return ae = { PLATFORM: r2, OS: s2, APPID: i2, DEVICEID: n2, ...ue(), ...t2 }, { ...he, ...ae, locale: e2, LOCALE: e2 };
  47379. }
  47380. var de = { sign: function(e2, t2) {
  47381. let n2 = "";
  47382. return Object.keys(e2).sort().forEach(function(t3) {
  47383. e2[t3] && (n2 = n2 + "&" + t3 + "=" + e2[t3]);
  47384. }), n2 = n2.slice(1), i(n2, t2).toString();
  47385. }, wrappedRequest: function(e2, t2) {
  47386. return new Promise((n2, s2) => {
  47387. t2(Object.assign(e2, { complete(e3) {
  47388. e3 || (e3 = {});
  47389. const t3 = e3.data && e3.data.header && e3.data.header["x-serverless-request-id"] || e3.header && e3.header["request-id"];
  47390. if (!e3.statusCode || e3.statusCode >= 400) {
  47391. const n3 = e3.data && e3.data.error && e3.data.error.code || "SYS_ERR", r3 = e3.data && e3.data.error && e3.data.error.message || e3.errMsg || "request:fail";
  47392. return s2(new te({ code: n3, message: r3, requestId: t3 }));
  47393. }
  47394. const r2 = e3.data;
  47395. if (r2.error)
  47396. return s2(new te({ code: r2.error.code, message: r2.error.message, requestId: t3 }));
  47397. r2.result = r2.data, r2.requestId = t3, delete r2.data, n2(r2);
  47398. } }));
  47399. });
  47400. }, toBase64: function(e2) {
  47401. return a.stringify(o.parse(e2));
  47402. } };
  47403. var pe = class {
  47404. constructor(e2) {
  47405. ["spaceId", "clientSecret"].forEach((t2) => {
  47406. if (!Object.prototype.hasOwnProperty.call(e2, t2))
  47407. throw new Error(`${t2} required`);
  47408. }), this.config = Object.assign({}, { endpoint: 0 === e2.spaceId.indexOf("mp-") ? "https://api.next.bspapp.com" : "https://api.bspapp.com" }, e2), this.config.provider = "aliyun", this.config.requestUrl = this.config.endpoint + "/client", this.config.envType = this.config.envType || "public", this.config.accessTokenKey = "access_token_" + this.config.spaceId, this.adapter = ne, this._getAccessTokenPromiseHub = new v({ createPromise: () => this.requestAuth(this.setupRequest({ method: "serverless.auth.user.anonymousAuthorize", params: "{}" }, "auth")).then((e3) => {
  47409. if (!e3.result || !e3.result.accessToken)
  47410. throw new te({ code: "AUTH_FAILED", message: "获取accessToken失败" });
  47411. this.setAccessToken(e3.result.accessToken);
  47412. }), retryRule: I });
  47413. }
  47414. get hasAccessToken() {
  47415. return !!this.accessToken;
  47416. }
  47417. setAccessToken(e2) {
  47418. this.accessToken = e2;
  47419. }
  47420. requestWrapped(e2) {
  47421. return de.wrappedRequest(e2, this.adapter.request);
  47422. }
  47423. requestAuth(e2) {
  47424. return this.requestWrapped(e2);
  47425. }
  47426. request(e2, t2) {
  47427. return Promise.resolve().then(() => this.hasAccessToken ? t2 ? this.requestWrapped(e2) : this.requestWrapped(e2).catch((t3) => new Promise((e3, n2) => {
  47428. !t3 || "GATEWAY_INVALID_TOKEN" !== t3.code && "InvalidParameter.InvalidToken" !== t3.code ? n2(t3) : e3();
  47429. }).then(() => this.getAccessToken()).then(() => {
  47430. const t4 = this.rebuildRequest(e2);
  47431. return this.request(t4, true);
  47432. })) : this.getAccessToken().then(() => {
  47433. const t3 = this.rebuildRequest(e2);
  47434. return this.request(t3, true);
  47435. }));
  47436. }
  47437. rebuildRequest(e2) {
  47438. const t2 = Object.assign({}, e2);
  47439. return t2.data.token = this.accessToken, t2.header["x-basement-token"] = this.accessToken, t2.header["x-serverless-sign"] = de.sign(t2.data, this.config.clientSecret), t2;
  47440. }
  47441. setupRequest(e2, t2) {
  47442. const n2 = Object.assign({}, e2, { spaceId: this.config.spaceId, timestamp: Date.now() }), s2 = { "Content-Type": "application/json" };
  47443. return "auth" !== t2 && (n2.token = this.accessToken, s2["x-basement-token"] = this.accessToken), s2["x-serverless-sign"] = de.sign(n2, this.config.clientSecret), { url: this.config.requestUrl, method: "POST", data: n2, dataType: "json", header: s2 };
  47444. }
  47445. getAccessToken() {
  47446. return this._getAccessTokenPromiseHub.exec();
  47447. }
  47448. async authorize() {
  47449. await this.getAccessToken();
  47450. }
  47451. callFunction(e2) {
  47452. const t2 = { method: "serverless.function.runtime.invoke", params: JSON.stringify({ functionTarget: e2.name, functionArgs: e2.data || {} }) };
  47453. return this.request({ ...this.setupRequest(t2), timeout: e2.timeout });
  47454. }
  47455. getOSSUploadOptionsFromPath(e2) {
  47456. const t2 = { method: "serverless.file.resource.generateProximalSign", params: JSON.stringify(e2) };
  47457. return this.request(this.setupRequest(t2));
  47458. }
  47459. uploadFileToOSS({ url: e2, formData: t2, name: n2, filePath: s2, fileType: r2, onUploadProgress: i2 }) {
  47460. return new Promise((o2, a2) => {
  47461. const c2 = this.adapter.uploadFile({ url: e2, formData: t2, name: n2, filePath: s2, fileType: r2, header: { "X-OSS-server-side-encrpytion": "AES256" }, success(e3) {
  47462. e3 && e3.statusCode < 400 ? o2(e3) : a2(new te({ code: "UPLOAD_FAILED", message: "文件上传失败" }));
  47463. }, fail(e3) {
  47464. a2(new te({ code: e3.code || "UPLOAD_FAILED", message: e3.message || e3.errMsg || "文件上传失败" }));
  47465. } });
  47466. "function" == typeof i2 && c2 && "function" == typeof c2.onProgressUpdate && c2.onProgressUpdate((e3) => {
  47467. i2({ loaded: e3.totalBytesSent, total: e3.totalBytesExpectedToSend });
  47468. });
  47469. });
  47470. }
  47471. reportOSSUpload(e2) {
  47472. const t2 = { method: "serverless.file.resource.report", params: JSON.stringify(e2) };
  47473. return this.request(this.setupRequest(t2));
  47474. }
  47475. async uploadFile({ filePath: e2, cloudPath: t2, fileType: n2 = "image", cloudPathAsRealPath: s2 = false, onUploadProgress: r2, config: i2 }) {
  47476. if ("string" !== g(t2))
  47477. throw new te({ code: "INVALID_PARAM", message: "cloudPath必须为字符串类型" });
  47478. if (!(t2 = t2.trim()))
  47479. throw new te({ code: "INVALID_PARAM", message: "cloudPath不可为空" });
  47480. if (/:\/\//.test(t2))
  47481. throw new te({ code: "INVALID_PARAM", message: "cloudPath不合法" });
  47482. const o2 = i2 && i2.envType || this.config.envType;
  47483. if (s2 && ("/" !== t2[0] && (t2 = "/" + t2), t2.indexOf("\\") > -1))
  47484. throw new te({ code: "INVALID_PARAM", message: "使用cloudPath作为路径时,cloudPath不可包含“\\”" });
  47485. const a2 = (await this.getOSSUploadOptionsFromPath({ env: o2, filename: s2 ? t2.split("/").pop() : t2, fileId: s2 ? t2 : void 0 })).result, c2 = "https://" + a2.cdnDomain + "/" + a2.ossPath, { securityToken: u2, accessKeyId: h2, signature: l2, host: d2, ossPath: p2, id: f2, policy: m2, ossCallbackUrl: y2 } = a2, _2 = { "Cache-Control": "max-age=2592000", "Content-Disposition": "attachment", OSSAccessKeyId: h2, Signature: l2, host: d2, id: f2, key: p2, policy: m2, success_action_status: 200 };
  47486. if (u2 && (_2["x-oss-security-token"] = u2), y2) {
  47487. const e3 = JSON.stringify({ callbackUrl: y2, callbackBody: JSON.stringify({ fileId: f2, spaceId: this.config.spaceId }), callbackBodyType: "application/json" });
  47488. _2.callback = de.toBase64(e3);
  47489. }
  47490. const w2 = { url: "https://" + a2.host, formData: _2, fileName: "file", name: "file", filePath: e2, fileType: n2 };
  47491. if (await this.uploadFileToOSS(Object.assign({}, w2, { onUploadProgress: r2 })), y2)
  47492. return { success: true, filePath: e2, fileID: c2 };
  47493. if ((await this.reportOSSUpload({ id: f2 })).success)
  47494. return { success: true, filePath: e2, fileID: c2 };
  47495. throw new te({ code: "UPLOAD_FAILED", message: "文件上传失败" });
  47496. }
  47497. getTempFileURL({ fileList: e2 } = {}) {
  47498. return new Promise((t2, n2) => {
  47499. Array.isArray(e2) && 0 !== e2.length || n2(new te({ code: "INVALID_PARAM", message: "fileList的元素必须是非空的字符串" })), this.getFileInfo({ fileList: e2 }).then((n3) => {
  47500. t2({ fileList: e2.map((e3, t3) => {
  47501. const s2 = n3.fileList[t3];
  47502. return { fileID: e3, tempFileURL: s2 && s2.url || e3 };
  47503. }) });
  47504. });
  47505. });
  47506. }
  47507. async getFileInfo({ fileList: e2 } = {}) {
  47508. if (!Array.isArray(e2) || 0 === e2.length)
  47509. throw new te({ code: "INVALID_PARAM", message: "fileList的元素必须是非空的字符串" });
  47510. const t2 = { method: "serverless.file.resource.info", params: JSON.stringify({ id: e2.map((e3) => e3.split("?")[0]).join(",") }) };
  47511. return { fileList: (await this.request(this.setupRequest(t2))).result };
  47512. }
  47513. };
  47514. var fe = { init(e2) {
  47515. const t2 = new pe(e2), n2 = { signInAnonymously: function() {
  47516. return t2.authorize();
  47517. }, getLoginState: function() {
  47518. return Promise.resolve(false);
  47519. } };
  47520. return t2.auth = function() {
  47521. return n2;
  47522. }, t2.customAuth = t2.auth, t2;
  47523. } };
  47524. const ge = "undefined" != typeof location && "http:" === location.protocol ? "http:" : "https:";
  47525. var me;
  47526. !function(e2) {
  47527. e2.local = "local", e2.none = "none", e2.session = "session";
  47528. }(me || (me = {}));
  47529. var ye = function() {
  47530. }, _e = n(function(e2, t2) {
  47531. var n2;
  47532. e2.exports = (n2 = r, function(e3) {
  47533. var t3 = n2, s2 = t3.lib, r2 = s2.WordArray, i2 = s2.Hasher, o2 = t3.algo, a2 = [], c2 = [];
  47534. !function() {
  47535. function t4(t5) {
  47536. for (var n4 = e3.sqrt(t5), s4 = 2; s4 <= n4; s4++)
  47537. if (!(t5 % s4))
  47538. return false;
  47539. return true;
  47540. }
  47541. function n3(e4) {
  47542. return 4294967296 * (e4 - (0 | e4)) | 0;
  47543. }
  47544. for (var s3 = 2, r3 = 0; r3 < 64; )
  47545. t4(s3) && (r3 < 8 && (a2[r3] = n3(e3.pow(s3, 0.5))), c2[r3] = n3(e3.pow(s3, 1 / 3)), r3++), s3++;
  47546. }();
  47547. var u2 = [], h2 = o2.SHA256 = i2.extend({ _doReset: function() {
  47548. this._hash = new r2.init(a2.slice(0));
  47549. }, _doProcessBlock: function(e4, t4) {
  47550. for (var n3 = this._hash.words, s3 = n3[0], r3 = n3[1], i3 = n3[2], o3 = n3[3], a3 = n3[4], h3 = n3[5], l2 = n3[6], d2 = n3[7], p2 = 0; p2 < 64; p2++) {
  47551. if (p2 < 16)
  47552. u2[p2] = 0 | e4[t4 + p2];
  47553. else {
  47554. var f2 = u2[p2 - 15], g2 = (f2 << 25 | f2 >>> 7) ^ (f2 << 14 | f2 >>> 18) ^ f2 >>> 3, m2 = u2[p2 - 2], y2 = (m2 << 15 | m2 >>> 17) ^ (m2 << 13 | m2 >>> 19) ^ m2 >>> 10;
  47555. u2[p2] = g2 + u2[p2 - 7] + y2 + u2[p2 - 16];
  47556. }
  47557. var _2 = s3 & r3 ^ s3 & i3 ^ r3 & i3, w2 = (s3 << 30 | s3 >>> 2) ^ (s3 << 19 | s3 >>> 13) ^ (s3 << 10 | s3 >>> 22), I2 = d2 + ((a3 << 26 | a3 >>> 6) ^ (a3 << 21 | a3 >>> 11) ^ (a3 << 7 | a3 >>> 25)) + (a3 & h3 ^ ~a3 & l2) + c2[p2] + u2[p2];
  47558. d2 = l2, l2 = h3, h3 = a3, a3 = o3 + I2 | 0, o3 = i3, i3 = r3, r3 = s3, s3 = I2 + (w2 + _2) | 0;
  47559. }
  47560. n3[0] = n3[0] + s3 | 0, n3[1] = n3[1] + r3 | 0, n3[2] = n3[2] + i3 | 0, n3[3] = n3[3] + o3 | 0, n3[4] = n3[4] + a3 | 0, n3[5] = n3[5] + h3 | 0, n3[6] = n3[6] + l2 | 0, n3[7] = n3[7] + d2 | 0;
  47561. }, _doFinalize: function() {
  47562. var t4 = this._data, n3 = t4.words, s3 = 8 * this._nDataBytes, r3 = 8 * t4.sigBytes;
  47563. return n3[r3 >>> 5] |= 128 << 24 - r3 % 32, n3[14 + (r3 + 64 >>> 9 << 4)] = e3.floor(s3 / 4294967296), n3[15 + (r3 + 64 >>> 9 << 4)] = s3, t4.sigBytes = 4 * n3.length, this._process(), this._hash;
  47564. }, clone: function() {
  47565. var e4 = i2.clone.call(this);
  47566. return e4._hash = this._hash.clone(), e4;
  47567. } });
  47568. t3.SHA256 = i2._createHelper(h2), t3.HmacSHA256 = i2._createHmacHelper(h2);
  47569. }(Math), n2.SHA256);
  47570. }), we = _e, Ie = n(function(e2, t2) {
  47571. e2.exports = r.HmacSHA256;
  47572. });
  47573. const ve = () => {
  47574. let e2;
  47575. if (!Promise) {
  47576. e2 = () => {
  47577. }, e2.promise = {};
  47578. const t3 = () => {
  47579. throw new te({ message: 'Your Node runtime does support ES6 Promises. Set "global.Promise" to your preferred implementation of promises.' });
  47580. };
  47581. return Object.defineProperty(e2.promise, "then", { get: t3 }), Object.defineProperty(e2.promise, "catch", { get: t3 }), e2;
  47582. }
  47583. const t2 = new Promise((t3, n2) => {
  47584. e2 = (e3, s2) => e3 ? n2(e3) : t3(s2);
  47585. });
  47586. return e2.promise = t2, e2;
  47587. };
  47588. function Se(e2) {
  47589. return void 0 === e2;
  47590. }
  47591. function Te(e2) {
  47592. return "[object Null]" === Object.prototype.toString.call(e2);
  47593. }
  47594. function be(e2 = "") {
  47595. return e2.replace(/([\s\S]+)\s+(请前往云开发AI小助手查看问题:.*)/, "$1");
  47596. }
  47597. function Ee(e2 = 32) {
  47598. const t2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  47599. let n2 = "";
  47600. for (let s2 = 0; s2 < e2; s2++)
  47601. n2 += t2.charAt(Math.floor(62 * Math.random()));
  47602. return n2;
  47603. }
  47604. var ke;
  47605. function Ae(e2) {
  47606. const t2 = (n2 = e2, "[object Array]" === Object.prototype.toString.call(n2) ? e2 : [e2]);
  47607. var n2;
  47608. for (const e3 of t2) {
  47609. const { isMatch: t3, genAdapter: n3, runtime: s2 } = e3;
  47610. if (t3())
  47611. return { adapter: n3(), runtime: s2 };
  47612. }
  47613. }
  47614. !function(e2) {
  47615. e2.WEB = "web", e2.WX_MP = "wx_mp";
  47616. }(ke || (ke = {}));
  47617. const Pe = { adapter: null, runtime: void 0 }, Ce = ["anonymousUuidKey"];
  47618. class Oe extends ye {
  47619. constructor() {
  47620. super(), Pe.adapter.root.tcbObject || (Pe.adapter.root.tcbObject = {});
  47621. }
  47622. setItem(e2, t2) {
  47623. Pe.adapter.root.tcbObject[e2] = t2;
  47624. }
  47625. getItem(e2) {
  47626. return Pe.adapter.root.tcbObject[e2];
  47627. }
  47628. removeItem(e2) {
  47629. delete Pe.adapter.root.tcbObject[e2];
  47630. }
  47631. clear() {
  47632. delete Pe.adapter.root.tcbObject;
  47633. }
  47634. }
  47635. function xe(e2, t2) {
  47636. switch (e2) {
  47637. case "local":
  47638. return t2.localStorage || new Oe();
  47639. case "none":
  47640. return new Oe();
  47641. default:
  47642. return t2.sessionStorage || new Oe();
  47643. }
  47644. }
  47645. class Ne {
  47646. constructor(e2) {
  47647. if (!this._storage) {
  47648. this._persistence = Pe.adapter.primaryStorage || e2.persistence, this._storage = xe(this._persistence, Pe.adapter);
  47649. const t2 = `access_token_${e2.env}`, n2 = `access_token_expire_${e2.env}`, s2 = `refresh_token_${e2.env}`, r2 = `anonymous_uuid_${e2.env}`, i2 = `login_type_${e2.env}`, o2 = "device_id", a2 = `token_type_${e2.env}`, c2 = `user_info_${e2.env}`;
  47650. this.keys = { accessTokenKey: t2, accessTokenExpireKey: n2, refreshTokenKey: s2, anonymousUuidKey: r2, loginTypeKey: i2, userInfoKey: c2, deviceIdKey: o2, tokenTypeKey: a2 };
  47651. }
  47652. }
  47653. updatePersistence(e2) {
  47654. if (e2 === this._persistence)
  47655. return;
  47656. const t2 = "local" === this._persistence;
  47657. this._persistence = e2;
  47658. const n2 = xe(e2, Pe.adapter);
  47659. for (const e3 in this.keys) {
  47660. const s2 = this.keys[e3];
  47661. if (t2 && Ce.includes(e3))
  47662. continue;
  47663. const r2 = this._storage.getItem(s2);
  47664. Se(r2) || Te(r2) || (n2.setItem(s2, r2), this._storage.removeItem(s2));
  47665. }
  47666. this._storage = n2;
  47667. }
  47668. setStore(e2, t2, n2) {
  47669. if (!this._storage)
  47670. return;
  47671. const s2 = { version: n2 || "localCachev1", content: t2 }, r2 = JSON.stringify(s2);
  47672. try {
  47673. this._storage.setItem(e2, r2);
  47674. } catch (e3) {
  47675. throw e3;
  47676. }
  47677. }
  47678. getStore(e2, t2) {
  47679. try {
  47680. if (!this._storage)
  47681. return;
  47682. } catch (e3) {
  47683. return "";
  47684. }
  47685. t2 = t2 || "localCachev1";
  47686. const n2 = this._storage.getItem(e2);
  47687. if (!n2)
  47688. return "";
  47689. if (n2.indexOf(t2) >= 0) {
  47690. return JSON.parse(n2).content;
  47691. }
  47692. return "";
  47693. }
  47694. removeStore(e2) {
  47695. this._storage.removeItem(e2);
  47696. }
  47697. }
  47698. const Re = {}, Le = {};
  47699. function Ue(e2) {
  47700. return Re[e2];
  47701. }
  47702. class De {
  47703. constructor(e2, t2) {
  47704. this.data = t2 || null, this.name = e2;
  47705. }
  47706. }
  47707. class Me extends De {
  47708. constructor(e2, t2) {
  47709. super("error", { error: e2, data: t2 }), this.error = e2;
  47710. }
  47711. }
  47712. const qe = new class {
  47713. constructor() {
  47714. this._listeners = {};
  47715. }
  47716. on(e2, t2) {
  47717. return function(e3, t3, n2) {
  47718. n2[e3] = n2[e3] || [], n2[e3].push(t3);
  47719. }(e2, t2, this._listeners), this;
  47720. }
  47721. off(e2, t2) {
  47722. return function(e3, t3, n2) {
  47723. if (n2 && n2[e3]) {
  47724. const s2 = n2[e3].indexOf(t3);
  47725. -1 !== s2 && n2[e3].splice(s2, 1);
  47726. }
  47727. }(e2, t2, this._listeners), this;
  47728. }
  47729. fire(e2, t2) {
  47730. if (e2 instanceof Me)
  47731. return console.error(e2.error), this;
  47732. const n2 = "string" == typeof e2 ? new De(e2, t2 || {}) : e2;
  47733. const s2 = n2.name;
  47734. if (this._listens(s2)) {
  47735. n2.target = this;
  47736. const e3 = this._listeners[s2] ? [...this._listeners[s2]] : [];
  47737. for (const t3 of e3)
  47738. t3.call(this, n2);
  47739. }
  47740. return this;
  47741. }
  47742. _listens(e2) {
  47743. return this._listeners[e2] && this._listeners[e2].length > 0;
  47744. }
  47745. }();
  47746. function Fe(e2, t2) {
  47747. qe.on(e2, t2);
  47748. }
  47749. function Ke(e2, t2 = {}) {
  47750. qe.fire(e2, t2);
  47751. }
  47752. function je(e2, t2) {
  47753. qe.off(e2, t2);
  47754. }
  47755. const $e = "loginStateChanged", Be = "loginStateExpire", We = "loginTypeChanged", He = "anonymousConverted", Je = "refreshAccessToken";
  47756. var ze;
  47757. !function(e2) {
  47758. e2.ANONYMOUS = "ANONYMOUS", e2.WECHAT = "WECHAT", e2.WECHAT_PUBLIC = "WECHAT-PUBLIC", e2.WECHAT_OPEN = "WECHAT-OPEN", e2.CUSTOM = "CUSTOM", e2.EMAIL = "EMAIL", e2.USERNAME = "USERNAME", e2.NULL = "NULL";
  47759. }(ze || (ze = {}));
  47760. class Ve {
  47761. constructor() {
  47762. this._fnPromiseMap = /* @__PURE__ */ new Map();
  47763. }
  47764. async run(e2, t2) {
  47765. let n2 = this._fnPromiseMap.get(e2);
  47766. return n2 || (n2 = new Promise(async (n3, s2) => {
  47767. try {
  47768. await this._runIdlePromise();
  47769. const e3 = t2();
  47770. n3(await e3);
  47771. } catch (e3) {
  47772. s2(e3);
  47773. } finally {
  47774. this._fnPromiseMap.delete(e2);
  47775. }
  47776. }), this._fnPromiseMap.set(e2, n2)), n2;
  47777. }
  47778. _runIdlePromise() {
  47779. return Promise.resolve();
  47780. }
  47781. }
  47782. class Ge {
  47783. constructor(e2) {
  47784. this._singlePromise = new Ve(), this._cache = Ue(e2.env), this._baseURL = `https://${e2.env}.ap-shanghai.tcb-api.tencentcloudapi.com`, this._reqClass = new Pe.adapter.reqClass({ timeout: e2.timeout, timeoutMsg: `请求在${e2.timeout / 1e3}s内未完成,已中断`, restrictedMethods: ["post"] });
  47785. }
  47786. _getDeviceId() {
  47787. if (this._deviceID)
  47788. return this._deviceID;
  47789. const { deviceIdKey: e2 } = this._cache.keys;
  47790. let t2 = this._cache.getStore(e2);
  47791. return "string" == typeof t2 && t2.length >= 16 && t2.length <= 48 || (t2 = Ee(), this._cache.setStore(e2, t2)), this._deviceID = t2, t2;
  47792. }
  47793. async _request(e2, t2, n2 = {}) {
  47794. const s2 = { "x-request-id": Ee(), "x-device-id": this._getDeviceId() };
  47795. if (n2.withAccessToken) {
  47796. const { tokenTypeKey: e3 } = this._cache.keys, t3 = await this.getAccessToken(), n3 = this._cache.getStore(e3);
  47797. s2.authorization = `${n3} ${t3}`;
  47798. }
  47799. return this._reqClass["get" === n2.method ? "get" : "post"]({ url: `${this._baseURL}${e2}`, data: t2, headers: s2 });
  47800. }
  47801. async _fetchAccessToken() {
  47802. const { loginTypeKey: e2, accessTokenKey: t2, accessTokenExpireKey: n2, tokenTypeKey: s2 } = this._cache.keys, r2 = this._cache.getStore(e2);
  47803. if (r2 && r2 !== ze.ANONYMOUS)
  47804. throw new te({ code: "INVALID_OPERATION", message: "非匿名登录不支持刷新 access token" });
  47805. const i2 = await this._singlePromise.run("fetchAccessToken", async () => (await this._request("/auth/v1/signin/anonymously", {}, { method: "post" })).data), { access_token: o2, expires_in: a2, token_type: c2 } = i2;
  47806. return this._cache.setStore(s2, c2), this._cache.setStore(t2, o2), this._cache.setStore(n2, Date.now() + 1e3 * a2), o2;
  47807. }
  47808. isAccessTokenExpired(e2, t2) {
  47809. let n2 = true;
  47810. return e2 && t2 && (n2 = t2 < Date.now()), n2;
  47811. }
  47812. async getAccessToken() {
  47813. const { accessTokenKey: e2, accessTokenExpireKey: t2 } = this._cache.keys, n2 = this._cache.getStore(e2), s2 = this._cache.getStore(t2);
  47814. return this.isAccessTokenExpired(n2, s2) ? this._fetchAccessToken() : n2;
  47815. }
  47816. async refreshAccessToken() {
  47817. const { accessTokenKey: e2, accessTokenExpireKey: t2, loginTypeKey: n2 } = this._cache.keys;
  47818. return this._cache.removeStore(e2), this._cache.removeStore(t2), this._cache.setStore(n2, ze.ANONYMOUS), this.getAccessToken();
  47819. }
  47820. async getUserInfo() {
  47821. return this._singlePromise.run("getUserInfo", async () => (await this._request("/auth/v1/user/me", {}, { withAccessToken: true, method: "get" })).data);
  47822. }
  47823. }
  47824. const Ye = ["auth.getJwt", "auth.logout", "auth.signInWithTicket", "auth.signInAnonymously", "auth.signIn", "auth.fetchAccessTokenWithRefreshToken", "auth.signUpWithEmailAndPassword", "auth.activateEndUserMail", "auth.sendPasswordResetEmail", "auth.resetPasswordWithToken", "auth.isUsernameRegistered"], Qe = { "X-SDK-Version": "1.3.5" };
  47825. function Xe(e2, t2, n2) {
  47826. const s2 = e2[t2];
  47827. e2[t2] = function(t3) {
  47828. const r2 = {}, i2 = {};
  47829. n2.forEach((n3) => {
  47830. const { data: s3, headers: o3 } = n3.call(e2, t3);
  47831. Object.assign(r2, s3), Object.assign(i2, o3);
  47832. });
  47833. const o2 = t3.data;
  47834. return o2 && (() => {
  47835. var e3;
  47836. if (e3 = o2, "[object FormData]" !== Object.prototype.toString.call(e3))
  47837. t3.data = { ...o2, ...r2 };
  47838. else
  47839. for (const e4 in r2)
  47840. o2.append(e4, r2[e4]);
  47841. })(), t3.headers = { ...t3.headers || {}, ...i2 }, s2.call(e2, t3);
  47842. };
  47843. }
  47844. function Ze() {
  47845. const e2 = Math.random().toString(16).slice(2);
  47846. return { data: { seqId: e2 }, headers: { ...Qe, "x-seqid": e2 } };
  47847. }
  47848. class et {
  47849. constructor(e2 = {}) {
  47850. var t2;
  47851. this.config = e2, this._reqClass = new Pe.adapter.reqClass({ timeout: this.config.timeout, timeoutMsg: `请求在${this.config.timeout / 1e3}s内未完成,已中断`, restrictedMethods: ["post"] }), this._cache = Ue(this.config.env), this._localCache = (t2 = this.config.env, Le[t2]), this.oauth = new Ge(this.config), Xe(this._reqClass, "post", [Ze]), Xe(this._reqClass, "upload", [Ze]), Xe(this._reqClass, "download", [Ze]);
  47852. }
  47853. async post(e2) {
  47854. return await this._reqClass.post(e2);
  47855. }
  47856. async upload(e2) {
  47857. return await this._reqClass.upload(e2);
  47858. }
  47859. async download(e2) {
  47860. return await this._reqClass.download(e2);
  47861. }
  47862. async refreshAccessToken() {
  47863. let e2, t2;
  47864. this._refreshAccessTokenPromise || (this._refreshAccessTokenPromise = this._refreshAccessToken());
  47865. try {
  47866. e2 = await this._refreshAccessTokenPromise;
  47867. } catch (e3) {
  47868. t2 = e3;
  47869. }
  47870. if (this._refreshAccessTokenPromise = null, this._shouldRefreshAccessTokenHook = null, t2)
  47871. throw t2;
  47872. return e2;
  47873. }
  47874. async _refreshAccessToken() {
  47875. const { accessTokenKey: e2, accessTokenExpireKey: t2, refreshTokenKey: n2, loginTypeKey: s2, anonymousUuidKey: r2 } = this._cache.keys;
  47876. this._cache.removeStore(e2), this._cache.removeStore(t2);
  47877. let i2 = this._cache.getStore(n2);
  47878. if (!i2)
  47879. throw new te({ message: "未登录CloudBase" });
  47880. const o2 = { refresh_token: i2 }, a2 = await this.request("auth.fetchAccessTokenWithRefreshToken", o2);
  47881. if (a2.data.code) {
  47882. const { code: e3 } = a2.data;
  47883. if ("SIGN_PARAM_INVALID" === e3 || "REFRESH_TOKEN_EXPIRED" === e3 || "INVALID_REFRESH_TOKEN" === e3) {
  47884. if (this._cache.getStore(s2) === ze.ANONYMOUS && "INVALID_REFRESH_TOKEN" === e3) {
  47885. const e4 = this._cache.getStore(r2), t3 = this._cache.getStore(n2), s3 = await this.send("auth.signInAnonymously", { anonymous_uuid: e4, refresh_token: t3 });
  47886. return this.setRefreshToken(s3.refresh_token), this._refreshAccessToken();
  47887. }
  47888. Ke(Be), this._cache.removeStore(n2);
  47889. }
  47890. throw new te({ code: a2.data.code, message: `刷新access token失败:${a2.data.code}` });
  47891. }
  47892. if (a2.data.access_token)
  47893. return Ke(Je), this._cache.setStore(e2, a2.data.access_token), this._cache.setStore(t2, a2.data.access_token_expire + Date.now()), { accessToken: a2.data.access_token, accessTokenExpire: a2.data.access_token_expire };
  47894. a2.data.refresh_token && (this._cache.removeStore(n2), this._cache.setStore(n2, a2.data.refresh_token), this._refreshAccessToken());
  47895. }
  47896. async getAccessToken() {
  47897. const { accessTokenKey: e2, accessTokenExpireKey: t2, refreshTokenKey: n2 } = this._cache.keys;
  47898. if (!this._cache.getStore(n2))
  47899. throw new te({ message: "refresh token不存在,登录状态异常" });
  47900. let s2 = this._cache.getStore(e2), r2 = this._cache.getStore(t2), i2 = true;
  47901. return this._shouldRefreshAccessTokenHook && !await this._shouldRefreshAccessTokenHook(s2, r2) && (i2 = false), (!s2 || !r2 || r2 < Date.now()) && i2 ? this.refreshAccessToken() : { accessToken: s2, accessTokenExpire: r2 };
  47902. }
  47903. async request(e2, t2, n2) {
  47904. const s2 = `x-tcb-trace_${this.config.env}`;
  47905. let r2 = "application/x-www-form-urlencoded";
  47906. const i2 = { action: e2, env: this.config.env, dataVersion: "2019-08-16", ...t2 };
  47907. let o2;
  47908. if (-1 === Ye.indexOf(e2) && (this._cache.keys, i2.access_token = await this.oauth.getAccessToken()), "storage.uploadFile" === e2) {
  47909. o2 = new FormData();
  47910. for (let e3 in o2)
  47911. o2.hasOwnProperty(e3) && void 0 !== o2[e3] && o2.append(e3, i2[e3]);
  47912. r2 = "multipart/form-data";
  47913. } else {
  47914. r2 = "application/json", o2 = {};
  47915. for (let e3 in i2)
  47916. void 0 !== i2[e3] && (o2[e3] = i2[e3]);
  47917. }
  47918. let a2 = { headers: { "content-type": r2 } };
  47919. n2 && n2.timeout && (a2.timeout = n2.timeout), n2 && n2.onUploadProgress && (a2.onUploadProgress = n2.onUploadProgress);
  47920. const c2 = this._localCache.getStore(s2);
  47921. c2 && (a2.headers["X-TCB-Trace"] = c2);
  47922. const { parse: u2, inQuery: h2, search: l2 } = t2;
  47923. let d2 = { env: this.config.env };
  47924. u2 && (d2.parse = true), h2 && (d2 = { ...h2, ...d2 });
  47925. let p2 = function(e3, t3, n3 = {}) {
  47926. const s3 = /\?/.test(t3);
  47927. let r3 = "";
  47928. for (let e4 in n3)
  47929. "" === r3 ? !s3 && (t3 += "?") : r3 += "&", r3 += `${e4}=${encodeURIComponent(n3[e4])}`;
  47930. return /^http(s)?\:\/\//.test(t3 += r3) ? t3 : `${e3}${t3}`;
  47931. }(ge, "//tcb-api.tencentcloudapi.com/web", d2);
  47932. l2 && (p2 += l2);
  47933. const f2 = await this.post({ url: p2, data: o2, ...a2 }), g2 = f2.header && f2.header["x-tcb-trace"];
  47934. if (g2 && this._localCache.setStore(s2, g2), 200 !== Number(f2.status) && 200 !== Number(f2.statusCode) || !f2.data)
  47935. throw new te({ code: "NETWORK_ERROR", message: "network request error" });
  47936. return f2;
  47937. }
  47938. async send(e2, t2 = {}, n2 = {}) {
  47939. const s2 = await this.request(e2, t2, { ...n2, onUploadProgress: t2.onUploadProgress });
  47940. if (("ACCESS_TOKEN_DISABLED" === s2.data.code || "ACCESS_TOKEN_EXPIRED" === s2.data.code) && -1 === Ye.indexOf(e2)) {
  47941. await this.oauth.refreshAccessToken();
  47942. const s3 = await this.request(e2, t2, { ...n2, onUploadProgress: t2.onUploadProgress });
  47943. if (s3.data.code)
  47944. throw new te({ code: s3.data.code, message: be(s3.data.message) });
  47945. return s3.data;
  47946. }
  47947. if (s2.data.code)
  47948. throw new te({ code: s2.data.code, message: be(s2.data.message) });
  47949. return s2.data;
  47950. }
  47951. setRefreshToken(e2) {
  47952. const { accessTokenKey: t2, accessTokenExpireKey: n2, refreshTokenKey: s2 } = this._cache.keys;
  47953. this._cache.removeStore(t2), this._cache.removeStore(n2), this._cache.setStore(s2, e2);
  47954. }
  47955. }
  47956. const tt = {};
  47957. function nt(e2) {
  47958. return tt[e2];
  47959. }
  47960. class st {
  47961. constructor(e2) {
  47962. this.config = e2, this._cache = Ue(e2.env), this._request = nt(e2.env);
  47963. }
  47964. setRefreshToken(e2) {
  47965. const { accessTokenKey: t2, accessTokenExpireKey: n2, refreshTokenKey: s2 } = this._cache.keys;
  47966. this._cache.removeStore(t2), this._cache.removeStore(n2), this._cache.setStore(s2, e2);
  47967. }
  47968. setAccessToken(e2, t2) {
  47969. const { accessTokenKey: n2, accessTokenExpireKey: s2 } = this._cache.keys;
  47970. this._cache.setStore(n2, e2), this._cache.setStore(s2, t2);
  47971. }
  47972. async refreshUserInfo() {
  47973. const { data: e2 } = await this._request.send("auth.getUserInfo", {});
  47974. return this.setLocalUserInfo(e2), e2;
  47975. }
  47976. setLocalUserInfo(e2) {
  47977. const { userInfoKey: t2 } = this._cache.keys;
  47978. this._cache.setStore(t2, e2);
  47979. }
  47980. }
  47981. class rt {
  47982. constructor(e2) {
  47983. if (!e2)
  47984. throw new te({ code: "PARAM_ERROR", message: "envId is not defined" });
  47985. this._envId = e2, this._cache = Ue(this._envId), this._request = nt(this._envId), this.setUserInfo();
  47986. }
  47987. linkWithTicket(e2) {
  47988. if ("string" != typeof e2)
  47989. throw new te({ code: "PARAM_ERROR", message: "ticket must be string" });
  47990. return this._request.send("auth.linkWithTicket", { ticket: e2 });
  47991. }
  47992. linkWithRedirect(e2) {
  47993. e2.signInWithRedirect();
  47994. }
  47995. updatePassword(e2, t2) {
  47996. return this._request.send("auth.updatePassword", { oldPassword: t2, newPassword: e2 });
  47997. }
  47998. updateEmail(e2) {
  47999. return this._request.send("auth.updateEmail", { newEmail: e2 });
  48000. }
  48001. updateUsername(e2) {
  48002. if ("string" != typeof e2)
  48003. throw new te({ code: "PARAM_ERROR", message: "username must be a string" });
  48004. return this._request.send("auth.updateUsername", { username: e2 });
  48005. }
  48006. async getLinkedUidList() {
  48007. const { data: e2 } = await this._request.send("auth.getLinkedUidList", {});
  48008. let t2 = false;
  48009. const { users: n2 } = e2;
  48010. return n2.forEach((e3) => {
  48011. e3.wxOpenId && e3.wxPublicId && (t2 = true);
  48012. }), { users: n2, hasPrimaryUid: t2 };
  48013. }
  48014. setPrimaryUid(e2) {
  48015. return this._request.send("auth.setPrimaryUid", { uid: e2 });
  48016. }
  48017. unlink(e2) {
  48018. return this._request.send("auth.unlink", { platform: e2 });
  48019. }
  48020. async update(e2) {
  48021. const { nickName: t2, gender: n2, avatarUrl: s2, province: r2, country: i2, city: o2 } = e2, { data: a2 } = await this._request.send("auth.updateUserInfo", { nickName: t2, gender: n2, avatarUrl: s2, province: r2, country: i2, city: o2 });
  48022. this.setLocalUserInfo(a2);
  48023. }
  48024. async refresh() {
  48025. const e2 = await this._request.oauth.getUserInfo();
  48026. return this.setLocalUserInfo(e2), e2;
  48027. }
  48028. setUserInfo() {
  48029. const { userInfoKey: e2 } = this._cache.keys, t2 = this._cache.getStore(e2);
  48030. ["uid", "loginType", "openid", "wxOpenId", "wxPublicId", "unionId", "qqMiniOpenId", "email", "hasPassword", "customUserId", "nickName", "gender", "avatarUrl"].forEach((e3) => {
  48031. this[e3] = t2[e3];
  48032. }), this.location = { country: t2.country, province: t2.province, city: t2.city };
  48033. }
  48034. setLocalUserInfo(e2) {
  48035. const { userInfoKey: t2 } = this._cache.keys;
  48036. this._cache.setStore(t2, e2), this.setUserInfo();
  48037. }
  48038. }
  48039. class it {
  48040. constructor(e2) {
  48041. if (!e2)
  48042. throw new te({ code: "PARAM_ERROR", message: "envId is not defined" });
  48043. this._cache = Ue(e2);
  48044. const { refreshTokenKey: t2, accessTokenKey: n2, accessTokenExpireKey: s2 } = this._cache.keys, r2 = this._cache.getStore(t2), i2 = this._cache.getStore(n2), o2 = this._cache.getStore(s2);
  48045. this.credential = { refreshToken: r2, accessToken: i2, accessTokenExpire: o2 }, this.user = new rt(e2);
  48046. }
  48047. get isAnonymousAuth() {
  48048. return this.loginType === ze.ANONYMOUS;
  48049. }
  48050. get isCustomAuth() {
  48051. return this.loginType === ze.CUSTOM;
  48052. }
  48053. get isWeixinAuth() {
  48054. return this.loginType === ze.WECHAT || this.loginType === ze.WECHAT_OPEN || this.loginType === ze.WECHAT_PUBLIC;
  48055. }
  48056. get loginType() {
  48057. return this._cache.getStore(this._cache.keys.loginTypeKey);
  48058. }
  48059. }
  48060. class ot extends st {
  48061. async signIn() {
  48062. this._cache.updatePersistence("local"), await this._request.oauth.getAccessToken(), Ke($e), Ke(We, { env: this.config.env, loginType: ze.ANONYMOUS, persistence: "local" });
  48063. const e2 = new it(this.config.env);
  48064. return await e2.user.refresh(), e2;
  48065. }
  48066. async linkAndRetrieveDataWithTicket(e2) {
  48067. const { anonymousUuidKey: t2, refreshTokenKey: n2 } = this._cache.keys, s2 = this._cache.getStore(t2), r2 = this._cache.getStore(n2), i2 = await this._request.send("auth.linkAndRetrieveDataWithTicket", { anonymous_uuid: s2, refresh_token: r2, ticket: e2 });
  48068. if (i2.refresh_token)
  48069. return this._clearAnonymousUUID(), this.setRefreshToken(i2.refresh_token), await this._request.refreshAccessToken(), Ke(He, { env: this.config.env }), Ke(We, { loginType: ze.CUSTOM, persistence: "local" }), { credential: { refreshToken: i2.refresh_token } };
  48070. throw new te({ message: "匿名转化失败" });
  48071. }
  48072. _setAnonymousUUID(e2) {
  48073. const { anonymousUuidKey: t2, loginTypeKey: n2 } = this._cache.keys;
  48074. this._cache.removeStore(t2), this._cache.setStore(t2, e2), this._cache.setStore(n2, ze.ANONYMOUS);
  48075. }
  48076. _clearAnonymousUUID() {
  48077. this._cache.removeStore(this._cache.keys.anonymousUuidKey);
  48078. }
  48079. }
  48080. class at extends st {
  48081. async signIn(e2) {
  48082. if ("string" != typeof e2)
  48083. throw new te({ code: "PARAM_ERROR", message: "ticket must be a string" });
  48084. const { refreshTokenKey: t2 } = this._cache.keys, n2 = await this._request.send("auth.signInWithTicket", { ticket: e2, refresh_token: this._cache.getStore(t2) || "" });
  48085. if (n2.refresh_token)
  48086. return this.setRefreshToken(n2.refresh_token), await this._request.refreshAccessToken(), Ke($e), Ke(We, { env: this.config.env, loginType: ze.CUSTOM, persistence: this.config.persistence }), await this.refreshUserInfo(), new it(this.config.env);
  48087. throw new te({ message: "自定义登录失败" });
  48088. }
  48089. }
  48090. class ct extends st {
  48091. async signIn(e2, t2) {
  48092. if ("string" != typeof e2)
  48093. throw new te({ code: "PARAM_ERROR", message: "email must be a string" });
  48094. const { refreshTokenKey: n2 } = this._cache.keys, s2 = await this._request.send("auth.signIn", { loginType: "EMAIL", email: e2, password: t2, refresh_token: this._cache.getStore(n2) || "" }), { refresh_token: r2, access_token: i2, access_token_expire: o2 } = s2;
  48095. if (r2)
  48096. return this.setRefreshToken(r2), i2 && o2 ? this.setAccessToken(i2, o2) : await this._request.refreshAccessToken(), await this.refreshUserInfo(), Ke($e), Ke(We, { env: this.config.env, loginType: ze.EMAIL, persistence: this.config.persistence }), new it(this.config.env);
  48097. throw s2.code ? new te({ code: s2.code, message: `邮箱登录失败: ${s2.message}` }) : new te({ message: "邮箱登录失败" });
  48098. }
  48099. async activate(e2) {
  48100. return this._request.send("auth.activateEndUserMail", { token: e2 });
  48101. }
  48102. async resetPasswordWithToken(e2, t2) {
  48103. return this._request.send("auth.resetPasswordWithToken", { token: e2, newPassword: t2 });
  48104. }
  48105. }
  48106. class ut extends st {
  48107. async signIn(e2, t2) {
  48108. if ("string" != typeof e2)
  48109. throw new te({ code: "PARAM_ERROR", message: "username must be a string" });
  48110. "string" != typeof t2 && (t2 = "", console.warn("password is empty"));
  48111. const { refreshTokenKey: n2 } = this._cache.keys, s2 = await this._request.send("auth.signIn", { loginType: ze.USERNAME, username: e2, password: t2, refresh_token: this._cache.getStore(n2) || "" }), { refresh_token: r2, access_token_expire: i2, access_token: o2 } = s2;
  48112. if (r2)
  48113. return this.setRefreshToken(r2), o2 && i2 ? this.setAccessToken(o2, i2) : await this._request.refreshAccessToken(), await this.refreshUserInfo(), Ke($e), Ke(We, { env: this.config.env, loginType: ze.USERNAME, persistence: this.config.persistence }), new it(this.config.env);
  48114. throw s2.code ? new te({ code: s2.code, message: `用户名密码登录失败: ${s2.message}` }) : new te({ message: "用户名密码登录失败" });
  48115. }
  48116. }
  48117. class ht {
  48118. constructor(e2) {
  48119. this.config = e2, this._cache = Ue(e2.env), this._request = nt(e2.env), this._onAnonymousConverted = this._onAnonymousConverted.bind(this), this._onLoginTypeChanged = this._onLoginTypeChanged.bind(this), Fe(We, this._onLoginTypeChanged);
  48120. }
  48121. get currentUser() {
  48122. const e2 = this.hasLoginState();
  48123. return e2 && e2.user || null;
  48124. }
  48125. get loginType() {
  48126. return this._cache.getStore(this._cache.keys.loginTypeKey);
  48127. }
  48128. anonymousAuthProvider() {
  48129. return new ot(this.config);
  48130. }
  48131. customAuthProvider() {
  48132. return new at(this.config);
  48133. }
  48134. emailAuthProvider() {
  48135. return new ct(this.config);
  48136. }
  48137. usernameAuthProvider() {
  48138. return new ut(this.config);
  48139. }
  48140. async signInAnonymously() {
  48141. return new ot(this.config).signIn();
  48142. }
  48143. async signInWithEmailAndPassword(e2, t2) {
  48144. return new ct(this.config).signIn(e2, t2);
  48145. }
  48146. signInWithUsernameAndPassword(e2, t2) {
  48147. return new ut(this.config).signIn(e2, t2);
  48148. }
  48149. async linkAndRetrieveDataWithTicket(e2) {
  48150. this._anonymousAuthProvider || (this._anonymousAuthProvider = new ot(this.config)), Fe(He, this._onAnonymousConverted);
  48151. return await this._anonymousAuthProvider.linkAndRetrieveDataWithTicket(e2);
  48152. }
  48153. async signOut() {
  48154. if (this.loginType === ze.ANONYMOUS)
  48155. throw new te({ message: "匿名用户不支持登出操作" });
  48156. const { refreshTokenKey: e2, accessTokenKey: t2, accessTokenExpireKey: n2 } = this._cache.keys, s2 = this._cache.getStore(e2);
  48157. if (!s2)
  48158. return;
  48159. const r2 = await this._request.send("auth.logout", { refresh_token: s2 });
  48160. return this._cache.removeStore(e2), this._cache.removeStore(t2), this._cache.removeStore(n2), Ke($e), Ke(We, { env: this.config.env, loginType: ze.NULL, persistence: this.config.persistence }), r2;
  48161. }
  48162. async signUpWithEmailAndPassword(e2, t2) {
  48163. return this._request.send("auth.signUpWithEmailAndPassword", { email: e2, password: t2 });
  48164. }
  48165. async sendPasswordResetEmail(e2) {
  48166. return this._request.send("auth.sendPasswordResetEmail", { email: e2 });
  48167. }
  48168. onLoginStateChanged(e2) {
  48169. Fe($e, () => {
  48170. const t3 = this.hasLoginState();
  48171. e2.call(this, t3);
  48172. });
  48173. const t2 = this.hasLoginState();
  48174. e2.call(this, t2);
  48175. }
  48176. onLoginStateExpired(e2) {
  48177. Fe(Be, e2.bind(this));
  48178. }
  48179. onAccessTokenRefreshed(e2) {
  48180. Fe(Je, e2.bind(this));
  48181. }
  48182. onAnonymousConverted(e2) {
  48183. Fe(He, e2.bind(this));
  48184. }
  48185. onLoginTypeChanged(e2) {
  48186. Fe(We, () => {
  48187. const t2 = this.hasLoginState();
  48188. e2.call(this, t2);
  48189. });
  48190. }
  48191. async getAccessToken() {
  48192. return { accessToken: (await this._request.getAccessToken()).accessToken, env: this.config.env };
  48193. }
  48194. hasLoginState() {
  48195. const { accessTokenKey: e2, accessTokenExpireKey: t2 } = this._cache.keys, n2 = this._cache.getStore(e2), s2 = this._cache.getStore(t2);
  48196. return this._request.oauth.isAccessTokenExpired(n2, s2) ? null : new it(this.config.env);
  48197. }
  48198. async isUsernameRegistered(e2) {
  48199. if ("string" != typeof e2)
  48200. throw new te({ code: "PARAM_ERROR", message: "username must be a string" });
  48201. const { data: t2 } = await this._request.send("auth.isUsernameRegistered", { username: e2 });
  48202. return t2 && t2.isRegistered;
  48203. }
  48204. getLoginState() {
  48205. return Promise.resolve(this.hasLoginState());
  48206. }
  48207. async signInWithTicket(e2) {
  48208. return new at(this.config).signIn(e2);
  48209. }
  48210. shouldRefreshAccessToken(e2) {
  48211. this._request._shouldRefreshAccessTokenHook = e2.bind(this);
  48212. }
  48213. getUserInfo() {
  48214. return this._request.send("auth.getUserInfo", {}).then((e2) => e2.code ? e2 : { ...e2.data, requestId: e2.seqId });
  48215. }
  48216. getAuthHeader() {
  48217. const { refreshTokenKey: e2, accessTokenKey: t2 } = this._cache.keys, n2 = this._cache.getStore(e2);
  48218. return { "x-cloudbase-credentials": this._cache.getStore(t2) + "/@@/" + n2 };
  48219. }
  48220. _onAnonymousConverted(e2) {
  48221. const { env: t2 } = e2.data;
  48222. t2 === this.config.env && this._cache.updatePersistence(this.config.persistence);
  48223. }
  48224. _onLoginTypeChanged(e2) {
  48225. const { loginType: t2, persistence: n2, env: s2 } = e2.data;
  48226. s2 === this.config.env && (this._cache.updatePersistence(n2), this._cache.setStore(this._cache.keys.loginTypeKey, t2));
  48227. }
  48228. }
  48229. const lt = function(e2, t2) {
  48230. t2 = t2 || ve();
  48231. const n2 = nt(this.config.env), { cloudPath: s2, filePath: r2, onUploadProgress: i2, fileType: o2 = "image" } = e2;
  48232. return n2.send("storage.getUploadMetadata", { path: s2 }).then((e3) => {
  48233. const { data: { url: a2, authorization: c2, token: u2, fileId: h2, cosFileId: l2 }, requestId: d2 } = e3, p2 = { key: s2, signature: c2, "x-cos-meta-fileid": l2, success_action_status: "201", "x-cos-security-token": u2 };
  48234. n2.upload({ url: a2, data: p2, file: r2, name: s2, fileType: o2, onUploadProgress: i2 }).then((e4) => {
  48235. 201 === e4.statusCode ? t2(null, { fileID: h2, requestId: d2 }) : t2(new te({ code: "STORAGE_REQUEST_FAIL", message: `STORAGE_REQUEST_FAIL: ${e4.data}` }));
  48236. }).catch((e4) => {
  48237. t2(e4);
  48238. });
  48239. }).catch((e3) => {
  48240. t2(e3);
  48241. }), t2.promise;
  48242. }, dt = function(e2, t2) {
  48243. t2 = t2 || ve();
  48244. const n2 = nt(this.config.env), { cloudPath: s2 } = e2;
  48245. return n2.send("storage.getUploadMetadata", { path: s2 }).then((e3) => {
  48246. t2(null, e3);
  48247. }).catch((e3) => {
  48248. t2(e3);
  48249. }), t2.promise;
  48250. }, pt = function({ fileList: e2 }, t2) {
  48251. if (t2 = t2 || ve(), !e2 || !Array.isArray(e2))
  48252. return { code: "INVALID_PARAM", message: "fileList必须是非空的数组" };
  48253. for (let t3 of e2)
  48254. if (!t3 || "string" != typeof t3)
  48255. return { code: "INVALID_PARAM", message: "fileList的元素必须是非空的字符串" };
  48256. const n2 = { fileid_list: e2 };
  48257. return nt(this.config.env).send("storage.batchDeleteFile", n2).then((e3) => {
  48258. e3.code ? t2(null, e3) : t2(null, { fileList: e3.data.delete_list, requestId: e3.requestId });
  48259. }).catch((e3) => {
  48260. t2(e3);
  48261. }), t2.promise;
  48262. }, ft = function({ fileList: e2 }, t2) {
  48263. t2 = t2 || ve(), e2 && Array.isArray(e2) || t2(null, { code: "INVALID_PARAM", message: "fileList必须是非空的数组" });
  48264. let n2 = [];
  48265. for (let s3 of e2)
  48266. "object" == typeof s3 ? (s3.hasOwnProperty("fileID") && s3.hasOwnProperty("maxAge") || t2(null, { code: "INVALID_PARAM", message: "fileList的元素必须是包含fileID和maxAge的对象" }), n2.push({ fileid: s3.fileID, max_age: s3.maxAge })) : "string" == typeof s3 ? n2.push({ fileid: s3 }) : t2(null, { code: "INVALID_PARAM", message: "fileList的元素必须是字符串" });
  48267. const s2 = { file_list: n2 };
  48268. return nt(this.config.env).send("storage.batchGetDownloadUrl", s2).then((e3) => {
  48269. e3.code ? t2(null, e3) : t2(null, { fileList: e3.data.download_list, requestId: e3.requestId });
  48270. }).catch((e3) => {
  48271. t2(e3);
  48272. }), t2.promise;
  48273. }, gt = async function({ fileID: e2 }, t2) {
  48274. const n2 = (await ft.call(this, { fileList: [{ fileID: e2, maxAge: 600 }] })).fileList[0];
  48275. if ("SUCCESS" !== n2.code)
  48276. return t2 ? t2(n2) : new Promise((e3) => {
  48277. e3(n2);
  48278. });
  48279. const s2 = nt(this.config.env);
  48280. let r2 = n2.download_url;
  48281. if (r2 = encodeURI(r2), !t2)
  48282. return s2.download({ url: r2 });
  48283. t2(await s2.download({ url: r2 }));
  48284. }, mt = function({ name: e2, data: t2, query: n2, parse: s2, search: r2, timeout: i2 }, o2) {
  48285. const a2 = o2 || ve();
  48286. let c2;
  48287. try {
  48288. c2 = t2 ? JSON.stringify(t2) : "";
  48289. } catch (e3) {
  48290. return Promise.reject(e3);
  48291. }
  48292. if (!e2)
  48293. return Promise.reject(new te({ code: "PARAM_ERROR", message: "函数名不能为空" }));
  48294. const u2 = { inQuery: n2, parse: s2, search: r2, function_name: e2, request_data: c2 };
  48295. return nt(this.config.env).send("functions.invokeFunction", u2, { timeout: i2 }).then((e3) => {
  48296. if (e3.code)
  48297. a2(null, e3);
  48298. else {
  48299. let t3 = e3.data.response_data;
  48300. if (s2)
  48301. a2(null, { result: t3, requestId: e3.requestId });
  48302. else
  48303. try {
  48304. t3 = JSON.parse(e3.data.response_data), a2(null, { result: t3, requestId: e3.requestId });
  48305. } catch (e4) {
  48306. a2(new te({ message: "response data must be json" }));
  48307. }
  48308. }
  48309. return a2.promise;
  48310. }).catch((e3) => {
  48311. a2(e3);
  48312. }), a2.promise;
  48313. }, yt = { timeout: 15e3, persistence: "session" }, _t = 6e5, wt = {};
  48314. class It {
  48315. constructor(e2) {
  48316. this.config = e2 || this.config, this.authObj = void 0;
  48317. }
  48318. init(e2) {
  48319. switch (Pe.adapter || (this.requestClient = new Pe.adapter.reqClass({ timeout: e2.timeout || 5e3, timeoutMsg: `请求在${(e2.timeout || 5e3) / 1e3}s内未完成,已中断` })), this.config = { ...yt, ...e2 }, true) {
  48320. case this.config.timeout > _t:
  48321. console.warn("timeout大于可配置上限[10分钟],已重置为上限数值"), this.config.timeout = _t;
  48322. break;
  48323. case this.config.timeout < 100:
  48324. console.warn("timeout小于可配置下限[100ms],已重置为下限数值"), this.config.timeout = 100;
  48325. }
  48326. return new It(this.config);
  48327. }
  48328. auth({ persistence: e2 } = {}) {
  48329. if (this.authObj)
  48330. return this.authObj;
  48331. const t2 = e2 || Pe.adapter.primaryStorage || yt.persistence;
  48332. var n2;
  48333. return t2 !== this.config.persistence && (this.config.persistence = t2), function(e3) {
  48334. const { env: t3 } = e3;
  48335. Re[t3] = new Ne(e3), Le[t3] = new Ne({ ...e3, persistence: "local" });
  48336. }(this.config), n2 = this.config, tt[n2.env] = new et(n2), this.authObj = new ht(this.config), this.authObj;
  48337. }
  48338. on(e2, t2) {
  48339. return Fe.apply(this, [e2, t2]);
  48340. }
  48341. off(e2, t2) {
  48342. return je.apply(this, [e2, t2]);
  48343. }
  48344. callFunction(e2, t2) {
  48345. return mt.apply(this, [e2, t2]);
  48346. }
  48347. deleteFile(e2, t2) {
  48348. return pt.apply(this, [e2, t2]);
  48349. }
  48350. getTempFileURL(e2, t2) {
  48351. return ft.apply(this, [e2, t2]);
  48352. }
  48353. downloadFile(e2, t2) {
  48354. return gt.apply(this, [e2, t2]);
  48355. }
  48356. uploadFile(e2, t2) {
  48357. return lt.apply(this, [e2, t2]);
  48358. }
  48359. getUploadMetadata(e2, t2) {
  48360. return dt.apply(this, [e2, t2]);
  48361. }
  48362. registerExtension(e2) {
  48363. wt[e2.name] = e2;
  48364. }
  48365. async invokeExtension(e2, t2) {
  48366. const n2 = wt[e2];
  48367. if (!n2)
  48368. throw new te({ message: `扩展${e2} 必须先注册` });
  48369. return await n2.invoke(t2, this);
  48370. }
  48371. useAdapters(e2) {
  48372. const { adapter: t2, runtime: n2 } = Ae(e2) || {};
  48373. t2 && (Pe.adapter = t2), n2 && (Pe.runtime = n2);
  48374. }
  48375. }
  48376. var vt = new It();
  48377. function St(e2, t2, n2) {
  48378. void 0 === n2 && (n2 = {});
  48379. var s2 = /\?/.test(t2), r2 = "";
  48380. for (var i2 in n2)
  48381. "" === r2 ? !s2 && (t2 += "?") : r2 += "&", r2 += i2 + "=" + encodeURIComponent(n2[i2]);
  48382. return /^http(s)?:\/\//.test(t2 += r2) ? t2 : "" + e2 + t2;
  48383. }
  48384. class Tt {
  48385. get(e2) {
  48386. const { url: t2, data: n2, headers: s2, timeout: r2 } = e2;
  48387. return new Promise((e3, i2) => {
  48388. ne.request({ url: St("https:", t2), data: n2, method: "GET", header: s2, timeout: r2, success(t3) {
  48389. e3(t3);
  48390. }, fail(e4) {
  48391. i2(e4);
  48392. } });
  48393. });
  48394. }
  48395. post(e2) {
  48396. const { url: t2, data: n2, headers: s2, timeout: r2 } = e2;
  48397. return new Promise((e3, i2) => {
  48398. ne.request({ url: St("https:", t2), data: n2, method: "POST", header: s2, timeout: r2, success(t3) {
  48399. e3(t3);
  48400. }, fail(e4) {
  48401. i2(e4);
  48402. } });
  48403. });
  48404. }
  48405. upload(e2) {
  48406. return new Promise((t2, n2) => {
  48407. const { url: s2, file: r2, data: i2, headers: o2, fileType: a2 } = e2, c2 = ne.uploadFile({ url: St("https:", s2), name: "file", formData: Object.assign({}, i2), filePath: r2, fileType: a2, header: o2, success(e3) {
  48408. const n3 = { statusCode: e3.statusCode, data: e3.data || {} };
  48409. 200 === e3.statusCode && i2.success_action_status && (n3.statusCode = parseInt(i2.success_action_status, 10)), t2(n3);
  48410. }, fail(e3) {
  48411. n2(new Error(e3.errMsg || "uploadFile:fail"));
  48412. } });
  48413. "function" == typeof e2.onUploadProgress && c2 && "function" == typeof c2.onProgressUpdate && c2.onProgressUpdate((t3) => {
  48414. e2.onUploadProgress({ loaded: t3.totalBytesSent, total: t3.totalBytesExpectedToSend });
  48415. });
  48416. });
  48417. }
  48418. }
  48419. const bt = { setItem(e2, t2) {
  48420. ne.setStorageSync(e2, t2);
  48421. }, getItem: (e2) => ne.getStorageSync(e2), removeItem(e2) {
  48422. ne.removeStorageSync(e2);
  48423. }, clear() {
  48424. ne.clearStorageSync();
  48425. } };
  48426. var Et = { genAdapter: function() {
  48427. return { root: {}, reqClass: Tt, localStorage: bt, primaryStorage: "local" };
  48428. }, isMatch: function() {
  48429. return true;
  48430. }, runtime: "uni_app" };
  48431. vt.useAdapters(Et);
  48432. const kt = vt, At = kt.init;
  48433. kt.init = function(e2) {
  48434. e2.env = e2.spaceId;
  48435. const t2 = At.call(this, e2);
  48436. t2.config.provider = "tencent", t2.config.spaceId = e2.spaceId;
  48437. const n2 = t2.auth;
  48438. return t2.auth = function(e3) {
  48439. const t3 = n2.call(this, e3);
  48440. return ["linkAndRetrieveDataWithTicket", "signInAnonymously", "signOut", "getAccessToken", "getLoginState", "signInWithTicket", "getUserInfo"].forEach((e4) => {
  48441. var n3;
  48442. t3[e4] = (n3 = t3[e4], function(e5) {
  48443. e5 = e5 || {};
  48444. const { success: t4, fail: s2, complete: r2 } = ee(e5);
  48445. if (!(t4 || s2 || r2))
  48446. return n3.call(this, e5);
  48447. n3.call(this, e5).then((e6) => {
  48448. t4 && t4(e6), r2 && r2(e6);
  48449. }, (e6) => {
  48450. s2 && s2(e6), r2 && r2(e6);
  48451. });
  48452. }).bind(t3);
  48453. }), t3;
  48454. }, t2.customAuth = t2.auth, t2;
  48455. };
  48456. var Pt = kt;
  48457. async function Ct(e2, t2) {
  48458. const n2 = `http://${e2}:${t2}/system/ping`;
  48459. try {
  48460. const e3 = await (s2 = { url: n2, timeout: 500 }, new Promise((e4, t3) => {
  48461. ne.request({ ...s2, success(t4) {
  48462. e4(t4);
  48463. }, fail(e5) {
  48464. t3(e5);
  48465. } });
  48466. }));
  48467. return !(!e3.data || 0 !== e3.data.code);
  48468. } catch (e3) {
  48469. return false;
  48470. }
  48471. var s2;
  48472. }
  48473. async function Ot(e2, t2) {
  48474. let n2;
  48475. for (let s2 = 0; s2 < e2.length; s2++) {
  48476. const r2 = e2[s2];
  48477. if (await Ct(r2, t2)) {
  48478. n2 = r2;
  48479. break;
  48480. }
  48481. }
  48482. return { address: n2, port: t2 };
  48483. }
  48484. const xt = { "serverless.file.resource.generateProximalSign": "storage/generate-proximal-sign", "serverless.file.resource.report": "storage/report", "serverless.file.resource.delete": "storage/delete", "serverless.file.resource.getTempFileURL": "storage/get-temp-file-url" };
  48485. var Nt = class {
  48486. constructor(e2) {
  48487. if (["spaceId", "clientSecret"].forEach((t2) => {
  48488. if (!Object.prototype.hasOwnProperty.call(e2, t2))
  48489. throw new Error(`${t2} required`);
  48490. }), !e2.endpoint)
  48491. throw new Error("集群空间未配置ApiEndpoint,配置后需要重新关联服务空间后生效");
  48492. this.config = Object.assign({}, e2), this.config.provider = "dcloud", this.config.requestUrl = this.config.endpoint + "/client", this.config.envType = this.config.envType || "public", this.adapter = ne;
  48493. }
  48494. async request(e2, t2 = true) {
  48495. const n2 = t2;
  48496. return e2 = n2 ? await this.setupLocalRequest(e2) : this.setupRequest(e2), Promise.resolve().then(() => n2 ? this.requestLocal(e2) : de.wrappedRequest(e2, this.adapter.request));
  48497. }
  48498. requestLocal(e2) {
  48499. return new Promise((t2, n2) => {
  48500. this.adapter.request(Object.assign(e2, { complete(e3) {
  48501. if (e3 || (e3 = {}), !e3.statusCode || e3.statusCode >= 400) {
  48502. const t3 = e3.data && e3.data.code || "SYS_ERR", s2 = e3.data && e3.data.message || "request:fail";
  48503. return n2(new te({ code: t3, message: s2 }));
  48504. }
  48505. t2({ success: true, result: e3.data });
  48506. } }));
  48507. });
  48508. }
  48509. setupRequest(e2) {
  48510. const t2 = Object.assign({}, e2, { spaceId: this.config.spaceId, timestamp: Date.now() }), n2 = { "Content-Type": "application/json" };
  48511. n2["x-serverless-sign"] = de.sign(t2, this.config.clientSecret);
  48512. const s2 = le();
  48513. n2["x-client-info"] = encodeURIComponent(JSON.stringify(s2));
  48514. const { token: r2 } = re();
  48515. return n2["x-client-token"] = r2, { url: this.config.requestUrl, method: "POST", data: t2, dataType: "json", header: JSON.parse(JSON.stringify(n2)) };
  48516. }
  48517. async setupLocalRequest(e2) {
  48518. const t2 = le(), { token: n2 } = re(), s2 = Object.assign({}, e2, { spaceId: this.config.spaceId, timestamp: Date.now(), clientInfo: t2, token: n2 }), { address: r2, servePort: i2 } = this.__dev__ && this.__dev__.debugInfo || {}, { address: o2 } = await Ot(r2, i2);
  48519. return { url: `http://${o2}:${i2}/${xt[e2.method]}`, method: "POST", data: s2, dataType: "json", header: JSON.parse(JSON.stringify({ "Content-Type": "application/json" })) };
  48520. }
  48521. callFunction(e2) {
  48522. const t2 = { method: "serverless.function.runtime.invoke", params: JSON.stringify({ functionTarget: e2.name, functionArgs: e2.data || {} }) };
  48523. return this.request(t2, false);
  48524. }
  48525. getUploadFileOptions(e2) {
  48526. const t2 = { method: "serverless.file.resource.generateProximalSign", params: JSON.stringify(e2) };
  48527. return this.request(t2);
  48528. }
  48529. reportUploadFile(e2) {
  48530. const t2 = { method: "serverless.file.resource.report", params: JSON.stringify(e2) };
  48531. return this.request(t2);
  48532. }
  48533. uploadFile({ filePath: e2, cloudPath: t2, fileType: n2 = "image", onUploadProgress: s2 }) {
  48534. if (!t2)
  48535. throw new te({ code: "CLOUDPATH_REQUIRED", message: "cloudPath不可为空" });
  48536. let r2;
  48537. return this.getUploadFileOptions({ cloudPath: t2 }).then((t3) => {
  48538. const { url: i2, formData: o2, name: a2 } = t3.result;
  48539. return r2 = t3.result.fileUrl, new Promise((t4, r3) => {
  48540. const c2 = this.adapter.uploadFile({ url: i2, formData: o2, name: a2, filePath: e2, fileType: n2, success(e3) {
  48541. e3 && e3.statusCode < 400 ? t4(e3) : r3(new te({ code: "UPLOAD_FAILED", message: "文件上传失败" }));
  48542. }, fail(e3) {
  48543. r3(new te({ code: e3.code || "UPLOAD_FAILED", message: e3.message || e3.errMsg || "文件上传失败" }));
  48544. } });
  48545. "function" == typeof s2 && c2 && "function" == typeof c2.onProgressUpdate && c2.onProgressUpdate((e3) => {
  48546. s2({ loaded: e3.totalBytesSent, total: e3.totalBytesExpectedToSend });
  48547. });
  48548. });
  48549. }).then(() => this.reportUploadFile({ cloudPath: t2 })).then((t3) => new Promise((n3, s3) => {
  48550. t3.success ? n3({ success: true, filePath: e2, fileID: r2 }) : s3(new te({ code: "UPLOAD_FAILED", message: "文件上传失败" }));
  48551. }));
  48552. }
  48553. deleteFile({ fileList: e2 }) {
  48554. const t2 = { method: "serverless.file.resource.delete", params: JSON.stringify({ fileList: e2 }) };
  48555. return this.request(t2).then((e3) => {
  48556. if (e3.success)
  48557. return e3.result;
  48558. throw new te({ code: "DELETE_FILE_FAILED", message: "删除文件失败" });
  48559. });
  48560. }
  48561. getTempFileURL({ fileList: e2, maxAge: t2 } = {}) {
  48562. if (!Array.isArray(e2) || 0 === e2.length)
  48563. throw new te({ code: "INVALID_PARAM", message: "fileList的元素必须是非空的字符串" });
  48564. const n2 = { method: "serverless.file.resource.getTempFileURL", params: JSON.stringify({ fileList: e2, maxAge: t2 }) };
  48565. return this.request(n2).then((e3) => {
  48566. if (e3.success)
  48567. return { fileList: e3.result.fileList.map((e4) => ({ fileID: e4.fileID, tempFileURL: e4.tempFileURL })) };
  48568. throw new te({ code: "GET_TEMP_FILE_URL_FAILED", message: "获取临时文件链接失败" });
  48569. });
  48570. }
  48571. };
  48572. var Rt = { init(e2) {
  48573. const t2 = new Nt(e2), n2 = { signInAnonymously: function() {
  48574. return Promise.resolve();
  48575. }, getLoginState: function() {
  48576. return Promise.resolve(false);
  48577. } };
  48578. return t2.auth = function() {
  48579. return n2;
  48580. }, t2.customAuth = t2.auth, t2;
  48581. } }, Lt = n(function(e2, t2) {
  48582. e2.exports = r.enc.Hex;
  48583. });
  48584. function Ut() {
  48585. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(e2) {
  48586. var t2 = 16 * Math.random() | 0;
  48587. return ("x" === e2 ? t2 : 3 & t2 | 8).toString(16);
  48588. });
  48589. }
  48590. function Dt(e2 = "", t2 = {}) {
  48591. const { data: n2, functionName: s2, method: r2, headers: i2, signHeaderKeys: o2 = [], config: a2 } = t2, c2 = String(Date.now()), u2 = Ut(), h2 = Object.assign({}, i2, { "x-from-app-id": a2.spaceAppId, "x-from-env-id": a2.spaceId, "x-to-env-id": a2.spaceId, "x-from-instance-id": c2, "x-from-function-name": s2, "x-client-timestamp": c2, "x-alipay-source": "client", "x-request-id": u2, "x-alipay-callid": u2, "x-trace-id": u2 }), l2 = ["x-from-app-id", "x-from-env-id", "x-to-env-id", "x-from-instance-id", "x-from-function-name", "x-client-timestamp"].concat(o2), [d2 = "", p2 = ""] = e2.split("?") || [], f2 = function(e3) {
  48592. const t3 = "HMAC-SHA256", n3 = e3.signedHeaders.join(";"), s3 = e3.signedHeaders.map((t4) => `${t4.toLowerCase()}:${e3.headers[t4]}
  48593. `).join(""), r3 = we(e3.body).toString(Lt), i3 = `${e3.method.toUpperCase()}
  48594. ${e3.path}
  48595. ${e3.query}
  48596. ${s3}
  48597. ${n3}
  48598. ${r3}
  48599. `, o3 = we(i3).toString(Lt), a3 = `${t3}
  48600. ${e3.timestamp}
  48601. ${o3}
  48602. `, c3 = Ie(a3, e3.secretKey).toString(Lt);
  48603. return `${t3} Credential=${e3.secretId}, SignedHeaders=${n3}, Signature=${c3}`;
  48604. }({ path: d2, query: p2, method: r2, headers: h2, timestamp: c2, body: JSON.stringify(n2), secretId: a2.accessKey, secretKey: a2.secretKey, signedHeaders: l2.sort() });
  48605. return { url: `${a2.endpoint}${e2}`, headers: Object.assign({}, h2, { Authorization: f2 }) };
  48606. }
  48607. function Mt({ url: e2, data: t2, method: n2 = "POST", headers: s2 = {}, timeout: r2 }) {
  48608. return new Promise((i2, o2) => {
  48609. ne.request({ url: e2, method: n2, data: "object" == typeof t2 ? JSON.stringify(t2) : t2, header: s2, dataType: "json", timeout: r2, complete: (e3 = {}) => {
  48610. const t3 = s2["x-trace-id"] || "";
  48611. if (!e3.statusCode || e3.statusCode >= 400) {
  48612. const { message: n3, errMsg: s3, trace_id: r3 } = e3.data || {};
  48613. return o2(new te({ code: "SYS_ERR", message: n3 || s3 || "request:fail", requestId: r3 || t3 }));
  48614. }
  48615. i2({ status: e3.statusCode, data: e3.data, headers: e3.header, requestId: t3 });
  48616. } });
  48617. });
  48618. }
  48619. function qt(e2, t2) {
  48620. const { path: n2, data: s2, method: r2 = "GET" } = e2, { url: i2, headers: o2 } = Dt(n2, { functionName: "", data: s2, method: r2, headers: { "x-alipay-cloud-mode": "oss", "x-data-api-type": "oss", "x-expire-timestamp": Date.now() + 6e4 }, signHeaderKeys: ["x-data-api-type", "x-expire-timestamp"], config: t2 });
  48621. return Mt({ url: i2, data: s2, method: r2, headers: o2 }).then((e3) => {
  48622. const t3 = e3.data || {};
  48623. if (!t3.success)
  48624. throw new te({ code: e3.errCode, message: e3.errMsg, requestId: e3.requestId });
  48625. return t3.data || {};
  48626. }).catch((e3) => {
  48627. throw new te({ code: e3.errCode, message: e3.errMsg, requestId: e3.requestId });
  48628. });
  48629. }
  48630. function Ft(e2 = "") {
  48631. const t2 = e2.trim().replace(/^cloud:\/\//, ""), n2 = t2.indexOf("/");
  48632. if (n2 <= 0)
  48633. throw new te({ code: "INVALID_PARAM", message: "fileID不合法" });
  48634. const s2 = t2.substring(0, n2), r2 = t2.substring(n2 + 1);
  48635. return s2 !== this.config.spaceId && console.warn("file ".concat(e2, " does not belong to env ").concat(this.config.spaceId)), r2;
  48636. }
  48637. function Kt(e2 = "") {
  48638. return "cloud://".concat(this.config.spaceId, "/").concat(e2.replace(/^\/+/, ""));
  48639. }
  48640. class jt {
  48641. constructor(e2) {
  48642. this.config = e2;
  48643. }
  48644. signedURL(e2, t2 = {}) {
  48645. const n2 = `/ws/function/${e2}`, s2 = this.config.wsEndpoint.replace(/^ws(s)?:\/\//, ""), r2 = Object.assign({}, t2, { accessKeyId: this.config.accessKey, signatureNonce: Ut(), timestamp: "" + Date.now() }), i2 = [n2, ["accessKeyId", "authorization", "signatureNonce", "timestamp"].sort().map(function(e3) {
  48646. return r2[e3] ? "".concat(e3, "=").concat(r2[e3]) : null;
  48647. }).filter(Boolean).join("&"), `host:${s2}`].join("\n"), o2 = ["HMAC-SHA256", we(i2).toString(Lt)].join("\n"), a2 = Ie(o2, this.config.secretKey).toString(Lt), c2 = Object.keys(r2).map((e3) => `${e3}=${encodeURIComponent(r2[e3])}`).join("&");
  48648. return `${this.config.wsEndpoint}${n2}?${c2}&signature=${a2}`;
  48649. }
  48650. }
  48651. var $t = class {
  48652. constructor(e2) {
  48653. if (["spaceId", "spaceAppId", "accessKey", "secretKey"].forEach((t2) => {
  48654. if (!Object.prototype.hasOwnProperty.call(e2, t2))
  48655. throw new Error(`${t2} required`);
  48656. }), e2.endpoint) {
  48657. if ("string" != typeof e2.endpoint)
  48658. throw new Error("endpoint must be string");
  48659. if (!/^https:\/\//.test(e2.endpoint))
  48660. throw new Error("endpoint must start with https://");
  48661. e2.endpoint = e2.endpoint.replace(/\/$/, "");
  48662. }
  48663. this.config = Object.assign({}, e2, { endpoint: e2.endpoint || `https://${e2.spaceId}.api-hz.cloudbasefunction.cn`, wsEndpoint: e2.wsEndpoint || `wss://${e2.spaceId}.api-hz.cloudbasefunction.cn` }), this._websocket = new jt(this.config);
  48664. }
  48665. callFunction(e2) {
  48666. return function(e3, t2) {
  48667. const { name: n2, data: s2, async: r2 = false, timeout: i2 } = e3, o2 = "POST", a2 = { "x-to-function-name": n2 };
  48668. r2 && (a2["x-function-invoke-type"] = "async");
  48669. const { url: c2, headers: u2 } = Dt("/functions/invokeFunction", { functionName: n2, data: s2, method: o2, headers: a2, signHeaderKeys: ["x-to-function-name"], config: t2 });
  48670. return Mt({ url: c2, data: s2, method: o2, headers: u2, timeout: i2 }).then((e4) => {
  48671. let t3 = 0;
  48672. if (r2) {
  48673. const n3 = e4.data || {};
  48674. t3 = "200" === n3.errCode ? 0 : n3.errCode, e4.data = n3.data || {}, e4.errMsg = n3.errMsg;
  48675. }
  48676. if (0 !== t3)
  48677. throw new te({ code: t3, message: e4.errMsg, requestId: e4.requestId });
  48678. return { errCode: t3, success: 0 === t3, requestId: e4.requestId, result: e4.data };
  48679. }).catch((e4) => {
  48680. throw new te({ code: e4.errCode, message: e4.errMsg, requestId: e4.requestId });
  48681. });
  48682. }(e2, this.config);
  48683. }
  48684. uploadFileToOSS({ url: e2, filePath: t2, fileType: n2, formData: s2, onUploadProgress: r2 }) {
  48685. return new Promise((i2, o2) => {
  48686. const a2 = ne.uploadFile({ url: e2, filePath: t2, fileType: n2, formData: s2, name: "file", success(e3) {
  48687. e3 && e3.statusCode < 400 ? i2(e3) : o2(new te({ code: "UPLOAD_FAILED", message: "文件上传失败" }));
  48688. }, fail(e3) {
  48689. o2(new te({ code: e3.code || "UPLOAD_FAILED", message: e3.message || e3.errMsg || "文件上传失败" }));
  48690. } });
  48691. "function" == typeof r2 && a2 && "function" == typeof a2.onProgressUpdate && a2.onProgressUpdate((e3) => {
  48692. r2({ loaded: e3.totalBytesSent, total: e3.totalBytesExpectedToSend });
  48693. });
  48694. });
  48695. }
  48696. async uploadFile({ filePath: e2, cloudPath: t2 = "", fileType: n2 = "image", onUploadProgress: s2 }) {
  48697. if ("string" !== g(t2))
  48698. throw new te({ code: "INVALID_PARAM", message: "cloudPath必须为字符串类型" });
  48699. if (!(t2 = t2.trim()))
  48700. throw new te({ code: "INVALID_PARAM", message: "cloudPath不可为空" });
  48701. if (/:\/\//.test(t2))
  48702. throw new te({ code: "INVALID_PARAM", message: "cloudPath不合法" });
  48703. const r2 = await qt({ path: "/".concat(t2.replace(/^\//, ""), "?post_url") }, this.config), { file_id: i2, upload_url: o2, form_data: a2 } = r2, c2 = a2 && a2.reduce((e3, t3) => (e3[t3.key] = t3.value, e3), {});
  48704. return this.uploadFileToOSS({ url: o2, filePath: e2, fileType: n2, formData: c2, onUploadProgress: s2 }).then(() => ({ fileID: i2 }));
  48705. }
  48706. async getTempFileURL({ fileList: e2 }) {
  48707. return new Promise((t2, n2) => {
  48708. (!e2 || e2.length < 0) && t2({ code: "INVALID_PARAM", message: "fileList不能为空数组" }), e2.length > 50 && t2({ code: "INVALID_PARAM", message: "fileList数组长度不能超过50" });
  48709. const s2 = [];
  48710. for (const n3 of e2) {
  48711. let e3;
  48712. "string" !== g(n3) && t2({ code: "INVALID_PARAM", message: "fileList的元素必须是非空的字符串" });
  48713. try {
  48714. e3 = Ft.call(this, n3);
  48715. } catch (t3) {
  48716. console.warn(t3.errCode, t3.errMsg), e3 = n3;
  48717. }
  48718. s2.push({ file_id: e3, expire: 600 });
  48719. }
  48720. qt({ path: "/?download_url", data: { file_list: s2 }, method: "POST" }, this.config).then((e3) => {
  48721. const { file_list: n3 = [] } = e3;
  48722. t2({ fileList: n3.map((e4) => ({ fileID: Kt.call(this, e4.file_id), tempFileURL: e4.download_url })) });
  48723. }).catch((e3) => n2(e3));
  48724. });
  48725. }
  48726. async connectWebSocket(e2) {
  48727. const { name: t2, query: n2 } = e2;
  48728. return ne.connectSocket({ url: this._websocket.signedURL(t2, n2), complete: () => {
  48729. } });
  48730. }
  48731. };
  48732. var Bt = { init: (e2) => {
  48733. e2.provider = "alipay";
  48734. const t2 = new $t(e2);
  48735. return t2.auth = function() {
  48736. return { signInAnonymously: function() {
  48737. return Promise.resolve();
  48738. }, getLoginState: function() {
  48739. return Promise.resolve(true);
  48740. } };
  48741. }, t2;
  48742. } };
  48743. function Wt({ data: e2 }) {
  48744. let t2;
  48745. t2 = le();
  48746. const n2 = JSON.parse(JSON.stringify(e2 || {}));
  48747. if (Object.assign(n2, { clientInfo: t2 }), !n2.uniIdToken) {
  48748. const { token: e3 } = re();
  48749. e3 && (n2.uniIdToken = e3);
  48750. }
  48751. return n2;
  48752. }
  48753. async function Ht(e2 = {}) {
  48754. await this.__dev__.initLocalNetwork();
  48755. const { localAddress: t2, localPort: n2 } = this.__dev__, s2 = { aliyun: "aliyun", tencent: "tcb", alipay: "alipay", dcloud: "dcloud" }[this.config.provider], r2 = this.config.spaceId, i2 = `http://${t2}:${n2}/system/check-function`, o2 = `http://${t2}:${n2}/cloudfunctions/${e2.name}`;
  48756. return new Promise((t3, n3) => {
  48757. ne.request({ method: "POST", url: i2, data: { name: e2.name, platform: P, provider: s2, spaceId: r2 }, timeout: 3e3, success(e3) {
  48758. t3(e3);
  48759. }, fail() {
  48760. t3({ data: { code: "NETWORK_ERROR", message: "连接本地调试服务失败,请检查客户端是否和主机在同一局域网下,自动切换为已部署的云函数。" } });
  48761. } });
  48762. }).then(({ data: e3 } = {}) => {
  48763. const { code: t3, message: n3 } = e3 || {};
  48764. return { code: 0 === t3 ? 0 : t3 || "SYS_ERR", message: n3 || "SYS_ERR" };
  48765. }).then(({ code: t3, message: n3 }) => {
  48766. if (0 !== t3) {
  48767. switch (t3) {
  48768. case "MODULE_ENCRYPTED":
  48769. console.error(`此云函数(${e2.name})依赖加密公共模块不可本地调试,自动切换为云端已部署的云函数`);
  48770. break;
  48771. case "FUNCTION_ENCRYPTED":
  48772. console.error(`此云函数(${e2.name})已加密不可本地调试,自动切换为云端已部署的云函数`);
  48773. break;
  48774. case "ACTION_ENCRYPTED":
  48775. console.error(n3 || "需要访问加密的uni-clientDB-action,自动切换为云端环境");
  48776. break;
  48777. case "NETWORK_ERROR":
  48778. console.error(n3 || "连接本地调试服务失败,请检查客户端是否和主机在同一局域网下");
  48779. break;
  48780. case "SWITCH_TO_CLOUD":
  48781. break;
  48782. default: {
  48783. const e3 = `检测本地调试服务出现错误:${n3},请检查网络环境或重启客户端再试`;
  48784. throw console.error(e3), new Error(e3);
  48785. }
  48786. }
  48787. return this._callCloudFunction(e2);
  48788. }
  48789. return new Promise((t4, n4) => {
  48790. const r3 = Wt.call(this, { data: e2.data });
  48791. ne.request({ method: "POST", url: o2, data: { provider: s2, platform: P, param: r3 }, timeout: e2.timeout, success: ({ statusCode: e3, data: s3 } = {}) => !e3 || e3 >= 400 ? n4(new te({ code: s3.code || "SYS_ERR", message: s3.message || "request:fail" })) : t4({ result: s3 }), fail(e3) {
  48792. n4(new te({ code: e3.code || e3.errCode || "SYS_ERR", message: e3.message || e3.errMsg || "request:fail" }));
  48793. } });
  48794. });
  48795. });
  48796. }
  48797. const Jt = [{ rule: /fc_function_not_found|FUNCTION_NOT_FOUND/, content: ",云函数[{functionName}]在云端不存在,请检查此云函数名称是否正确以及该云函数是否已上传到服务空间", mode: "append" }];
  48798. var zt = /[\\^$.*+?()[\]{}|]/g, Vt = RegExp(zt.source);
  48799. function Gt(e2, t2, n2) {
  48800. return e2.replace(new RegExp((s2 = t2) && Vt.test(s2) ? s2.replace(zt, "\\$&") : s2, "g"), n2);
  48801. var s2;
  48802. }
  48803. const Yt = { NONE: "none", REQUEST: "request", RESPONSE: "response", BOTH: "both" }, Qt = "_globalUniCloudStatus", Xt = "_globalUniCloudSecureNetworkCache__{spaceId}", Zt = "uni-secure-network", en = { SYSTEM_ERROR: { code: 2e4, message: "System error" }, APP_INFO_INVALID: { code: 20101, message: "Invalid client" }, GET_ENCRYPT_KEY_FAILED: { code: 20102, message: "Get encrypt key failed" } };
  48804. function nn(e2) {
  48805. const { errSubject: t2, subject: n2, errCode: s2, errMsg: r2, code: i2, message: o2, cause: a2 } = e2 || {};
  48806. return new te({ subject: t2 || n2 || Zt, code: s2 || i2 || en.SYSTEM_ERROR.code, message: r2 || o2, cause: a2 });
  48807. }
  48808. class sn {
  48809. constructor({ secretType: e2, uniCloudIns: t2 } = {}) {
  48810. this.clientType = "", this.secretType = e2 || Yt.NONE, this.uniCloudIns = t2;
  48811. const { provider: n2, spaceId: s2 } = this.uniCloudIns.config;
  48812. var r2;
  48813. this.provider = n2, this.spaceId = s2, this.scopedGlobalCache = (r2 = this.uniCloudIns, U(Xt.replace("{spaceId}", r2.config.spaceId)));
  48814. }
  48815. getSystemInfo() {
  48816. return this._systemInfo || (this._systemInfo = ce()), this._systemInfo;
  48817. }
  48818. get appId() {
  48819. return this.getSystemInfo().appId;
  48820. }
  48821. get deviceId() {
  48822. return this.getSystemInfo().deviceId;
  48823. }
  48824. async encryptData(e2) {
  48825. return this.secretType === Yt.NONE ? e2 : this.platformEncryptData(e2);
  48826. }
  48827. async decryptResult(e2) {
  48828. if (this.secretType === Yt.NONE)
  48829. return e2;
  48830. const { errCode: t2, errMsg: n2, content: s2 } = e2 || {};
  48831. return t2 || !s2 ? e2 : this.secretType === Yt.REQUEST ? s2 : this.platformDecryptResult(e2);
  48832. }
  48833. wrapVerifyClientCallFunction(e2) {
  48834. const t2 = this;
  48835. return async function({ name: n2, data: s2 = {} } = {}) {
  48836. await t2.prepare(), (s2 = JSON.parse(JSON.stringify(s2)))._uniCloudOptions = await t2.platformGetSignOption();
  48837. let r2 = await e2({ name: n2, data: s2 });
  48838. return t2.isClientKeyNotFound(r2) && (await t2.prepare({ forceUpdate: true }), s2._uniCloudOptions = await t2.platformGetSignOption(), r2 = await e2({ name: n2, data: s2 })), r2;
  48839. };
  48840. }
  48841. wrapEncryptDataCallFunction(e2) {
  48842. const t2 = this;
  48843. return async function({ name: n2, data: s2 = {} } = {}) {
  48844. await t2.prepare();
  48845. const r2 = await t2.encryptData(s2);
  48846. let i2 = await e2({ name: n2, data: r2 });
  48847. if (t2.isClientKeyNotFound(i2)) {
  48848. await t2.prepare({ forceUpdate: true });
  48849. const r3 = await t2.encryptData(s2);
  48850. i2 = await e2({ name: n2, data: r3 });
  48851. }
  48852. return i2.result = await t2.decryptResult(i2.result), i2;
  48853. };
  48854. }
  48855. }
  48856. /*! MIT License. Copyright 2015-2018 Richard Moore <me@ricmoo.com>. See LICENSE.txt. */
  48857. function rn(e2) {
  48858. return parseInt(e2) === e2;
  48859. }
  48860. function on(e2) {
  48861. if (!rn(e2.length))
  48862. return false;
  48863. for (var t2 = 0; t2 < e2.length; t2++)
  48864. if (!rn(e2[t2]) || e2[t2] < 0 || e2[t2] > 255)
  48865. return false;
  48866. return true;
  48867. }
  48868. function an(e2, t2) {
  48869. if (e2.buffer && "Uint8Array" === e2.name)
  48870. return t2 && (e2 = e2.slice ? e2.slice() : Array.prototype.slice.call(e2)), e2;
  48871. if (Array.isArray(e2)) {
  48872. if (!on(e2))
  48873. throw new Error("Array contains invalid value: " + e2);
  48874. return new Uint8Array(e2);
  48875. }
  48876. if (rn(e2.length) && on(e2))
  48877. return new Uint8Array(e2);
  48878. throw new Error("unsupported array-like object");
  48879. }
  48880. function cn(e2) {
  48881. return new Uint8Array(e2);
  48882. }
  48883. function un(e2, t2, n2, s2, r2) {
  48884. null == s2 && null == r2 || (e2 = e2.slice ? e2.slice(s2, r2) : Array.prototype.slice.call(e2, s2, r2)), t2.set(e2, n2);
  48885. }
  48886. var hn, ln = { toBytes: function(e2) {
  48887. var t2 = [], n2 = 0;
  48888. for (e2 = encodeURI(e2); n2 < e2.length; ) {
  48889. var s2 = e2.charCodeAt(n2++);
  48890. 37 === s2 ? (t2.push(parseInt(e2.substr(n2, 2), 16)), n2 += 2) : t2.push(s2);
  48891. }
  48892. return an(t2);
  48893. }, fromBytes: function(e2) {
  48894. for (var t2 = [], n2 = 0; n2 < e2.length; ) {
  48895. var s2 = e2[n2];
  48896. s2 < 128 ? (t2.push(String.fromCharCode(s2)), n2++) : s2 > 191 && s2 < 224 ? (t2.push(String.fromCharCode((31 & s2) << 6 | 63 & e2[n2 + 1])), n2 += 2) : (t2.push(String.fromCharCode((15 & s2) << 12 | (63 & e2[n2 + 1]) << 6 | 63 & e2[n2 + 2])), n2 += 3);
  48897. }
  48898. return t2.join("");
  48899. } }, dn = (hn = "0123456789abcdef", { toBytes: function(e2) {
  48900. for (var t2 = [], n2 = 0; n2 < e2.length; n2 += 2)
  48901. t2.push(parseInt(e2.substr(n2, 2), 16));
  48902. return t2;
  48903. }, fromBytes: function(e2) {
  48904. for (var t2 = [], n2 = 0; n2 < e2.length; n2++) {
  48905. var s2 = e2[n2];
  48906. t2.push(hn[(240 & s2) >> 4] + hn[15 & s2]);
  48907. }
  48908. return t2.join("");
  48909. } }), pn = { 16: 10, 24: 12, 32: 14 }, fn = [1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145], gn = [99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22], mn = [82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125], yn = [3328402341, 4168907908, 4000806809, 4135287693, 4294111757, 3597364157, 3731845041, 2445657428, 1613770832, 33620227, 3462883241, 1445669757, 3892248089, 3050821474, 1303096294, 3967186586, 2412431941, 528646813, 2311702848, 4202528135, 4026202645, 2992200171, 2387036105, 4226871307, 1101901292, 3017069671, 1604494077, 1169141738, 597466303, 1403299063, 3832705686, 2613100635, 1974974402, 3791519004, 1033081774, 1277568618, 1815492186, 2118074177, 4126668546, 2211236943, 1748251740, 1369810420, 3521504564, 4193382664, 3799085459, 2883115123, 1647391059, 706024767, 134480908, 2512897874, 1176707941, 2646852446, 806885416, 932615841, 168101135, 798661301, 235341577, 605164086, 461406363, 3756188221, 3454790438, 1311188841, 2142417613, 3933566367, 302582043, 495158174, 1479289972, 874125870, 907746093, 3698224818, 3025820398, 1537253627, 2756858614, 1983593293, 3084310113, 2108928974, 1378429307, 3722699582, 1580150641, 327451799, 2790478837, 3117535592, 0, 3253595436, 1075847264, 3825007647, 2041688520, 3059440621, 3563743934, 2378943302, 1740553945, 1916352843, 2487896798, 2555137236, 2958579944, 2244988746, 3151024235, 3320835882, 1336584933, 3992714006, 2252555205, 2588757463, 1714631509, 293963156, 2319795663, 3925473552, 67240454, 4269768577, 2689618160, 2017213508, 631218106, 1269344483, 2723238387, 1571005438, 2151694528, 93294474, 1066570413, 563977660, 1882732616, 4059428100, 1673313503, 2008463041, 2950355573, 1109467491, 537923632, 3858759450, 4260623118, 3218264685, 2177748300, 403442708, 638784309, 3287084079, 3193921505, 899127202, 2286175436, 773265209, 2479146071, 1437050866, 4236148354, 2050833735, 3362022572, 3126681063, 840505643, 3866325909, 3227541664, 427917720, 2655997905, 2749160575, 1143087718, 1412049534, 999329963, 193497219, 2353415882, 3354324521, 1807268051, 672404540, 2816401017, 3160301282, 369822493, 2916866934, 3688947771, 1681011286, 1949973070, 336202270, 2454276571, 201721354, 1210328172, 3093060836, 2680341085, 3184776046, 1135389935, 3294782118, 965841320, 831886756, 3554993207, 4068047243, 3588745010, 2345191491, 1849112409, 3664604599, 26054028, 2983581028, 2622377682, 1235855840, 3630984372, 2891339514, 4092916743, 3488279077, 3395642799, 4101667470, 1202630377, 268961816, 1874508501, 4034427016, 1243948399, 1546530418, 941366308, 1470539505, 1941222599, 2546386513, 3421038627, 2715671932, 3899946140, 1042226977, 2521517021, 1639824860, 227249030, 260737669, 3765465232, 2084453954, 1907733956, 3429263018, 2420656344, 100860677, 4160157185, 470683154, 3261161891, 1781871967, 2924959737, 1773779408, 394692241, 2579611992, 974986535, 664706745, 3655459128, 3958962195, 731420851, 571543859, 3530123707, 2849626480, 126783113, 865375399, 765172662, 1008606754, 361203602, 3387549984, 2278477385, 2857719295, 1344809080, 2782912378, 59542671, 1503764984, 160008576, 437062935, 1707065306, 3622233649, 2218934982, 3496503480, 2185314755, 697932208, 1512910199, 504303377, 2075177163, 2824099068, 1841019862, 739644986], _n = [2781242211, 2230877308, 2582542199, 2381740923, 234877682, 3184946027, 2984144751, 1418839493, 1348481072, 50462977, 2848876391, 2102799147, 434634494, 1656084439, 3863849899, 2599188086, 1167051466, 2636087938, 1082771913, 2281340285, 368048890, 3954334041, 3381544775, 201060592, 3963727277, 1739838676, 4250903202, 3930435503, 3206782108, 4149453988, 2531553906, 1536934080, 3262494647, 484572669, 2923271059, 1783375398, 1517041206, 1098792767, 49674231, 1334037708, 1550332980, 4098991525, 886171109, 150598129, 2481090929, 1940642008, 1398944049, 1059722517, 201851908, 1385547719, 1699095331, 1587397571, 674240536, 2704774806, 252314885, 3039795866, 151914247, 908333586, 2602270848, 1038082786, 651029483, 1766729511, 3447698098, 2682942837, 454166793, 2652734339, 1951935532, 775166490, 758520603, 3000790638, 4004797018, 4217086112, 4137964114, 1299594043, 1639438038, 3464344499, 2068982057, 1054729187, 1901997871, 2534638724, 4121318227, 1757008337, 0, 750906861, 1614815264, 535035132, 3363418545, 3988151131, 3201591914, 1183697867, 3647454910, 1265776953, 3734260298, 3566750796, 3903871064, 1250283471, 1807470800, 717615087, 3847203498, 384695291, 3313910595, 3617213773, 1432761139, 2484176261, 3481945413, 283769337, 100925954, 2180939647, 4037038160, 1148730428, 3123027871, 3813386408, 4087501137, 4267549603, 3229630528, 2315620239, 2906624658, 3156319645, 1215313976, 82966005, 3747855548, 3245848246, 1974459098, 1665278241, 807407632, 451280895, 251524083, 1841287890, 1283575245, 337120268, 891687699, 801369324, 3787349855, 2721421207, 3431482436, 959321879, 1469301956, 4065699751, 2197585534, 1199193405, 2898814052, 3887750493, 724703513, 2514908019, 2696962144, 2551808385, 3516813135, 2141445340, 1715741218, 2119445034, 2872807568, 2198571144, 3398190662, 700968686, 3547052216, 1009259540, 2041044702, 3803995742, 487983883, 1991105499, 1004265696, 1449407026, 1316239930, 504629770, 3683797321, 168560134, 1816667172, 3837287516, 1570751170, 1857934291, 4014189740, 2797888098, 2822345105, 2754712981, 936633572, 2347923833, 852879335, 1133234376, 1500395319, 3084545389, 2348912013, 1689376213, 3533459022, 3762923945, 3034082412, 4205598294, 133428468, 634383082, 2949277029, 2398386810, 3913789102, 403703816, 3580869306, 2297460856, 1867130149, 1918643758, 607656988, 4049053350, 3346248884, 1368901318, 600565992, 2090982877, 2632479860, 557719327, 3717614411, 3697393085, 2249034635, 2232388234, 2430627952, 1115438654, 3295786421, 2865522278, 3633334344, 84280067, 33027830, 303828494, 2747425121, 1600795957, 4188952407, 3496589753, 2434238086, 1486471617, 658119965, 3106381470, 953803233, 334231800, 3005978776, 857870609, 3151128937, 1890179545, 2298973838, 2805175444, 3056442267, 574365214, 2450884487, 550103529, 1233637070, 4289353045, 2018519080, 2057691103, 2399374476, 4166623649, 2148108681, 387583245, 3664101311, 836232934, 3330556482, 3100665960, 3280093505, 2955516313, 2002398509, 287182607, 3413881008, 4238890068, 3597515707, 975967766], wn = [1671808611, 2089089148, 2006576759, 2072901243, 4061003762, 1807603307, 1873927791, 3310653893, 810573872, 16974337, 1739181671, 729634347, 4263110654, 3613570519, 2883997099, 1989864566, 3393556426, 2191335298, 3376449993, 2106063485, 4195741690, 1508618841, 1204391495, 4027317232, 2917941677, 3563566036, 2734514082, 2951366063, 2629772188, 2767672228, 1922491506, 3227229120, 3082974647, 4246528509, 2477669779, 644500518, 911895606, 1061256767, 4144166391, 3427763148, 878471220, 2784252325, 3845444069, 4043897329, 1905517169, 3631459288, 827548209, 356461077, 67897348, 3344078279, 593839651, 3277757891, 405286936, 2527147926, 84871685, 2595565466, 118033927, 305538066, 2157648768, 3795705826, 3945188843, 661212711, 2999812018, 1973414517, 152769033, 2208177539, 745822252, 439235610, 455947803, 1857215598, 1525593178, 2700827552, 1391895634, 994932283, 3596728278, 3016654259, 695947817, 3812548067, 795958831, 2224493444, 1408607827, 3513301457, 0, 3979133421, 543178784, 4229948412, 2982705585, 1542305371, 1790891114, 3410398667, 3201918910, 961245753, 1256100938, 1289001036, 1491644504, 3477767631, 3496721360, 4012557807, 2867154858, 4212583931, 1137018435, 1305975373, 861234739, 2241073541, 1171229253, 4178635257, 33948674, 2139225727, 1357946960, 1011120188, 2679776671, 2833468328, 1374921297, 2751356323, 1086357568, 2408187279, 2460827538, 2646352285, 944271416, 4110742005, 3168756668, 3066132406, 3665145818, 560153121, 271589392, 4279952895, 4077846003, 3530407890, 3444343245, 202643468, 322250259, 3962553324, 1608629855, 2543990167, 1154254916, 389623319, 3294073796, 2817676711, 2122513534, 1028094525, 1689045092, 1575467613, 422261273, 1939203699, 1621147744, 2174228865, 1339137615, 3699352540, 577127458, 712922154, 2427141008, 2290289544, 1187679302, 3995715566, 3100863416, 339486740, 3732514782, 1591917662, 186455563, 3681988059, 3762019296, 844522546, 978220090, 169743370, 1239126601, 101321734, 611076132, 1558493276, 3260915650, 3547250131, 2901361580, 1655096418, 2443721105, 2510565781, 3828863972, 2039214713, 3878868455, 3359869896, 928607799, 1840765549, 2374762893, 3580146133, 1322425422, 2850048425, 1823791212, 1459268694, 4094161908, 3928346602, 1706019429, 2056189050, 2934523822, 135794696, 3134549946, 2022240376, 628050469, 779246638, 472135708, 2800834470, 3032970164, 3327236038, 3894660072, 3715932637, 1956440180, 522272287, 1272813131, 3185336765, 2340818315, 2323976074, 1888542832, 1044544574, 3049550261, 1722469478, 1222152264, 50660867, 4127324150, 236067854, 1638122081, 895445557, 1475980887, 3117443513, 2257655686, 3243809217, 489110045, 2662934430, 3778599393, 4162055160, 2561878936, 288563729, 1773916777, 3648039385, 2391345038, 2493985684, 2612407707, 505560094, 2274497927, 3911240169, 3460925390, 1442818645, 678973480, 3749357023, 2358182796, 2717407649, 2306869641, 219617805, 3218761151, 3862026214, 1120306242, 1756942440, 1103331905, 2578459033, 762796589, 252780047, 2966125488, 1425844308, 3151392187, 372911126], In = [1667474886, 2088535288, 2004326894, 2071694838, 4075949567, 1802223062, 1869591006, 3318043793, 808472672, 16843522, 1734846926, 724270422, 4278065639, 3621216949, 2880169549, 1987484396, 3402253711, 2189597983, 3385409673, 2105378810, 4210693615, 1499065266, 1195886990, 4042263547, 2913856577, 3570689971, 2728590687, 2947541573, 2627518243, 2762274643, 1920112356, 3233831835, 3082273397, 4261223649, 2475929149, 640051788, 909531756, 1061110142, 4160160501, 3435941763, 875846760, 2779116625, 3857003729, 4059105529, 1903268834, 3638064043, 825316194, 353713962, 67374088, 3351728789, 589522246, 3284360861, 404236336, 2526454071, 84217610, 2593830191, 117901582, 303183396, 2155911963, 3806477791, 3958056653, 656894286, 2998062463, 1970642922, 151591698, 2206440989, 741110872, 437923380, 454765878, 1852748508, 1515908788, 2694904667, 1381168804, 993742198, 3604373943, 3014905469, 690584402, 3823320797, 791638366, 2223281939, 1398011302, 3520161977, 0, 3991743681, 538992704, 4244381667, 2981218425, 1532751286, 1785380564, 3419096717, 3200178535, 960056178, 1246420628, 1280103576, 1482221744, 3486468741, 3503319995, 4025428677, 2863326543, 4227536621, 1128514950, 1296947098, 859002214, 2240123921, 1162203018, 4193849577, 33687044, 2139062782, 1347481760, 1010582648, 2678045221, 2829640523, 1364325282, 2745433693, 1077985408, 2408548869, 2459086143, 2644360225, 943212656, 4126475505, 3166494563, 3065430391, 3671750063, 555836226, 269496352, 4294908645, 4092792573, 3537006015, 3452783745, 202118168, 320025894, 3974901699, 1600119230, 2543297077, 1145359496, 387397934, 3301201811, 2812801621, 2122220284, 1027426170, 1684319432, 1566435258, 421079858, 1936954854, 1616945344, 2172753945, 1330631070, 3705438115, 572679748, 707427924, 2425400123, 2290647819, 1179044492, 4008585671, 3099120491, 336870440, 3739122087, 1583276732, 185277718, 3688593069, 3772791771, 842159716, 976899700, 168435220, 1229577106, 101059084, 606366792, 1549591736, 3267517855, 3553849021, 2897014595, 1650632388, 2442242105, 2509612081, 3840161747, 2038008818, 3890688725, 3368567691, 926374254, 1835907034, 2374863873, 3587531953, 1313788572, 2846482505, 1819063512, 1448540844, 4109633523, 3941213647, 1701162954, 2054852340, 2930698567, 134748176, 3132806511, 2021165296, 623210314, 774795868, 471606328, 2795958615, 3031746419, 3334885783, 3907527627, 3722280097, 1953799400, 522133822, 1263263126, 3183336545, 2341176845, 2324333839, 1886425312, 1044267644, 3048588401, 1718004428, 1212733584, 50529542, 4143317495, 235803164, 1633788866, 892690282, 1465383342, 3115962473, 2256965911, 3250673817, 488449850, 2661202215, 3789633753, 4177007595, 2560144171, 286339874, 1768537042, 3654906025, 2391705863, 2492770099, 2610673197, 505291324, 2273808917, 3924369609, 3469625735, 1431699370, 673740880, 3755965093, 2358021891, 2711746649, 2307489801, 218961690, 3217021541, 3873845719, 1111672452, 1751693520, 1094828930, 2576986153, 757954394, 252645662, 2964376443, 1414855848, 3149649517, 370555436], vn = [1374988112, 2118214995, 437757123, 975658646, 1001089995, 530400753, 2902087851, 1273168787, 540080725, 2910219766, 2295101073, 4110568485, 1340463100, 3307916247, 641025152, 3043140495, 3736164937, 632953703, 1172967064, 1576976609, 3274667266, 2169303058, 2370213795, 1809054150, 59727847, 361929877, 3211623147, 2505202138, 3569255213, 1484005843, 1239443753, 2395588676, 1975683434, 4102977912, 2572697195, 666464733, 3202437046, 4035489047, 3374361702, 2110667444, 1675577880, 3843699074, 2538681184, 1649639237, 2976151520, 3144396420, 4269907996, 4178062228, 1883793496, 2403728665, 2497604743, 1383856311, 2876494627, 1917518562, 3810496343, 1716890410, 3001755655, 800440835, 2261089178, 3543599269, 807962610, 599762354, 33778362, 3977675356, 2328828971, 2809771154, 4077384432, 1315562145, 1708848333, 101039829, 3509871135, 3299278474, 875451293, 2733856160, 92987698, 2767645557, 193195065, 1080094634, 1584504582, 3178106961, 1042385657, 2531067453, 3711829422, 1306967366, 2438237621, 1908694277, 67556463, 1615861247, 429456164, 3602770327, 2302690252, 1742315127, 2968011453, 126454664, 3877198648, 2043211483, 2709260871, 2084704233, 4169408201, 0, 159417987, 841739592, 504459436, 1817866830, 4245618683, 260388950, 1034867998, 908933415, 168810852, 1750902305, 2606453969, 607530554, 202008497, 2472011535, 3035535058, 463180190, 2160117071, 1641816226, 1517767529, 470948374, 3801332234, 3231722213, 1008918595, 303765277, 235474187, 4069246893, 766945465, 337553864, 1475418501, 2943682380, 4003061179, 2743034109, 4144047775, 1551037884, 1147550661, 1543208500, 2336434550, 3408119516, 3069049960, 3102011747, 3610369226, 1113818384, 328671808, 2227573024, 2236228733, 3535486456, 2935566865, 3341394285, 496906059, 3702665459, 226906860, 2009195472, 733156972, 2842737049, 294930682, 1206477858, 2835123396, 2700099354, 1451044056, 573804783, 2269728455, 3644379585, 2362090238, 2564033334, 2801107407, 2776292904, 3669462566, 1068351396, 742039012, 1350078989, 1784663195, 1417561698, 4136440770, 2430122216, 775550814, 2193862645, 2673705150, 1775276924, 1876241833, 3475313331, 3366754619, 270040487, 3902563182, 3678124923, 3441850377, 1851332852, 3969562369, 2203032232, 3868552805, 2868897406, 566021896, 4011190502, 3135740889, 1248802510, 3936291284, 699432150, 832877231, 708780849, 3332740144, 899835584, 1951317047, 4236429990, 3767586992, 866637845, 4043610186, 1106041591, 2144161806, 395441711, 1984812685, 1139781709, 3433712980, 3835036895, 2664543715, 1282050075, 3240894392, 1181045119, 2640243204, 25965917, 4203181171, 4211818798, 3009879386, 2463879762, 3910161971, 1842759443, 2597806476, 933301370, 1509430414, 3943906441, 3467192302, 3076639029, 3776767469, 2051518780, 2631065433, 1441952575, 404016761, 1942435775, 1408749034, 1610459739, 3745345300, 2017778566, 3400528769, 3110650942, 941896748, 3265478751, 371049330, 3168937228, 675039627, 4279080257, 967311729, 135050206, 3635733660, 1683407248, 2076935265, 3576870512, 1215061108, 3501741890], Sn = [1347548327, 1400783205, 3273267108, 2520393566, 3409685355, 4045380933, 2880240216, 2471224067, 1428173050, 4138563181, 2441661558, 636813900, 4233094615, 3620022987, 2149987652, 2411029155, 1239331162, 1730525723, 2554718734, 3781033664, 46346101, 310463728, 2743944855, 3328955385, 3875770207, 2501218972, 3955191162, 3667219033, 768917123, 3545789473, 692707433, 1150208456, 1786102409, 2029293177, 1805211710, 3710368113, 3065962831, 401639597, 1724457132, 3028143674, 409198410, 2196052529, 1620529459, 1164071807, 3769721975, 2226875310, 486441376, 2499348523, 1483753576, 428819965, 2274680428, 3075636216, 598438867, 3799141122, 1474502543, 711349675, 129166120, 53458370, 2592523643, 2782082824, 4063242375, 2988687269, 3120694122, 1559041666, 730517276, 2460449204, 4042459122, 2706270690, 3446004468, 3573941694, 533804130, 2328143614, 2637442643, 2695033685, 839224033, 1973745387, 957055980, 2856345839, 106852767, 1371368976, 4181598602, 1033297158, 2933734917, 1179510461, 3046200461, 91341917, 1862534868, 4284502037, 605657339, 2547432937, 3431546947, 2003294622, 3182487618, 2282195339, 954669403, 3682191598, 1201765386, 3917234703, 3388507166, 0, 2198438022, 1211247597, 2887651696, 1315723890, 4227665663, 1443857720, 507358933, 657861945, 1678381017, 560487590, 3516619604, 975451694, 2970356327, 261314535, 3535072918, 2652609425, 1333838021, 2724322336, 1767536459, 370938394, 182621114, 3854606378, 1128014560, 487725847, 185469197, 2918353863, 3106780840, 3356761769, 2237133081, 1286567175, 3152976349, 4255350624, 2683765030, 3160175349, 3309594171, 878443390, 1988838185, 3704300486, 1756818940, 1673061617, 3403100636, 272786309, 1075025698, 545572369, 2105887268, 4174560061, 296679730, 1841768865, 1260232239, 4091327024, 3960309330, 3497509347, 1814803222, 2578018489, 4195456072, 575138148, 3299409036, 446754879, 3629546796, 4011996048, 3347532110, 3252238545, 4270639778, 915985419, 3483825537, 681933534, 651868046, 2755636671, 3828103837, 223377554, 2607439820, 1649704518, 3270937875, 3901806776, 1580087799, 4118987695, 3198115200, 2087309459, 2842678573, 3016697106, 1003007129, 2802849917, 1860738147, 2077965243, 164439672, 4100872472, 32283319, 2827177882, 1709610350, 2125135846, 136428751, 3874428392, 3652904859, 3460984630, 3572145929, 3593056380, 2939266226, 824852259, 818324884, 3224740454, 930369212, 2801566410, 2967507152, 355706840, 1257309336, 4148292826, 243256656, 790073846, 2373340630, 1296297904, 1422699085, 3756299780, 3818836405, 457992840, 3099667487, 2135319889, 77422314, 1560382517, 1945798516, 788204353, 1521706781, 1385356242, 870912086, 325965383, 2358957921, 2050466060, 2388260884, 2313884476, 4006521127, 901210569, 3990953189, 1014646705, 1503449823, 1062597235, 2031621326, 3212035895, 3931371469, 1533017514, 350174575, 2256028891, 2177544179, 1052338372, 741876788, 1606591296, 1914052035, 213705253, 2334669897, 1107234197, 1899603969, 3725069491, 2631447780, 2422494913, 1635502980, 1893020342, 1950903388, 1120974935], Tn = [2807058932, 1699970625, 2764249623, 1586903591, 1808481195, 1173430173, 1487645946, 59984867, 4199882800, 1844882806, 1989249228, 1277555970, 3623636965, 3419915562, 1149249077, 2744104290, 1514790577, 459744698, 244860394, 3235995134, 1963115311, 4027744588, 2544078150, 4190530515, 1608975247, 2627016082, 2062270317, 1507497298, 2200818878, 567498868, 1764313568, 3359936201, 2305455554, 2037970062, 1047239e3, 1910319033, 1337376481, 2904027272, 2892417312, 984907214, 1243112415, 830661914, 861968209, 2135253587, 2011214180, 2927934315, 2686254721, 731183368, 1750626376, 4246310725, 1820824798, 4172763771, 3542330227, 48394827, 2404901663, 2871682645, 671593195, 3254988725, 2073724613, 145085239, 2280796200, 2779915199, 1790575107, 2187128086, 472615631, 3029510009, 4075877127, 3802222185, 4107101658, 3201631749, 1646252340, 4270507174, 1402811438, 1436590835, 3778151818, 3950355702, 3963161475, 4020912224, 2667994737, 273792366, 2331590177, 104699613, 95345982, 3175501286, 2377486676, 1560637892, 3564045318, 369057872, 4213447064, 3919042237, 1137477952, 2658625497, 1119727848, 2340947849, 1530455833, 4007360968, 172466556, 266959938, 516552836, 0, 2256734592, 3980931627, 1890328081, 1917742170, 4294704398, 945164165, 3575528878, 958871085, 3647212047, 2787207260, 1423022939, 775562294, 1739656202, 3876557655, 2530391278, 2443058075, 3310321856, 547512796, 1265195639, 437656594, 3121275539, 719700128, 3762502690, 387781147, 218828297, 3350065803, 2830708150, 2848461854, 428169201, 122466165, 3720081049, 1627235199, 648017665, 4122762354, 1002783846, 2117360635, 695634755, 3336358691, 4234721005, 4049844452, 3704280881, 2232435299, 574624663, 287343814, 612205898, 1039717051, 840019705, 2708326185, 793451934, 821288114, 1391201670, 3822090177, 376187827, 3113855344, 1224348052, 1679968233, 2361698556, 1058709744, 752375421, 2431590963, 1321699145, 3519142200, 2734591178, 188127444, 2177869557, 3727205754, 2384911031, 3215212461, 2648976442, 2450346104, 3432737375, 1180849278, 331544205, 3102249176, 4150144569, 2952102595, 2159976285, 2474404304, 766078933, 313773861, 2570832044, 2108100632, 1668212892, 3145456443, 2013908262, 418672217, 3070356634, 2594734927, 1852171925, 3867060991, 3473416636, 3907448597, 2614737639, 919489135, 164948639, 2094410160, 2997825956, 590424639, 2486224549, 1723872674, 3157750862, 3399941250, 3501252752, 3625268135, 2555048196, 3673637356, 1343127501, 4130281361, 3599595085, 2957853679, 1297403050, 81781910, 3051593425, 2283490410, 532201772, 1367295589, 3926170974, 895287692, 1953757831, 1093597963, 492483431, 3528626907, 1446242576, 1192455638, 1636604631, 209336225, 344873464, 1015671571, 669961897, 3375740769, 3857572124, 2973530695, 3747192018, 1933530610, 3464042516, 935293895, 3454686199, 2858115069, 1863638845, 3683022916, 4085369519, 3292445032, 875313188, 1080017571, 3279033885, 621591778, 1233856572, 2504130317, 24197544, 3017672716, 3835484340, 3247465558, 2220981195, 3060847922, 1551124588, 1463996600], bn = [4104605777, 1097159550, 396673818, 660510266, 2875968315, 2638606623, 4200115116, 3808662347, 821712160, 1986918061, 3430322568, 38544885, 3856137295, 718002117, 893681702, 1654886325, 2975484382, 3122358053, 3926825029, 4274053469, 796197571, 1290801793, 1184342925, 3556361835, 2405426947, 2459735317, 1836772287, 1381620373, 3196267988, 1948373848, 3764988233, 3385345166, 3263785589, 2390325492, 1480485785, 3111247143, 3780097726, 2293045232, 548169417, 3459953789, 3746175075, 439452389, 1362321559, 1400849762, 1685577905, 1806599355, 2174754046, 137073913, 1214797936, 1174215055, 3731654548, 2079897426, 1943217067, 1258480242, 529487843, 1437280870, 3945269170, 3049390895, 3313212038, 923313619, 679998e3, 3215307299, 57326082, 377642221, 3474729866, 2041877159, 133361907, 1776460110, 3673476453, 96392454, 878845905, 2801699524, 777231668, 4082475170, 2330014213, 4142626212, 2213296395, 1626319424, 1906247262, 1846563261, 562755902, 3708173718, 1040559837, 3871163981, 1418573201, 3294430577, 114585348, 1343618912, 2566595609, 3186202582, 1078185097, 3651041127, 3896688048, 2307622919, 425408743, 3371096953, 2081048481, 1108339068, 2216610296, 0, 2156299017, 736970802, 292596766, 1517440620, 251657213, 2235061775, 2933202493, 758720310, 265905162, 1554391400, 1532285339, 908999204, 174567692, 1474760595, 4002861748, 2610011675, 3234156416, 3693126241, 2001430874, 303699484, 2478443234, 2687165888, 585122620, 454499602, 151849742, 2345119218, 3064510765, 514443284, 4044981591, 1963412655, 2581445614, 2137062819, 19308535, 1928707164, 1715193156, 4219352155, 1126790795, 600235211, 3992742070, 3841024952, 836553431, 1669664834, 2535604243, 3323011204, 1243905413, 3141400786, 4180808110, 698445255, 2653899549, 2989552604, 2253581325, 3252932727, 3004591147, 1891211689, 2487810577, 3915653703, 4237083816, 4030667424, 2100090966, 865136418, 1229899655, 953270745, 3399679628, 3557504664, 4118925222, 2061379749, 3079546586, 2915017791, 983426092, 2022837584, 1607244650, 2118541908, 2366882550, 3635996816, 972512814, 3283088770, 1568718495, 3499326569, 3576539503, 621982671, 2895723464, 410887952, 2623762152, 1002142683, 645401037, 1494807662, 2595684844, 1335535747, 2507040230, 4293295786, 3167684641, 367585007, 3885750714, 1865862730, 2668221674, 2960971305, 2763173681, 1059270954, 2777952454, 2724642869, 1320957812, 2194319100, 2429595872, 2815956275, 77089521, 3973773121, 3444575871, 2448830231, 1305906550, 4021308739, 2857194700, 2516901860, 3518358430, 1787304780, 740276417, 1699839814, 1592394909, 2352307457, 2272556026, 188821243, 1729977011, 3687994002, 274084841, 3594982253, 3613494426, 2701949495, 4162096729, 322734571, 2837966542, 1640576439, 484830689, 1202797690, 3537852828, 4067639125, 349075736, 3342319475, 4157467219, 4255800159, 1030690015, 1155237496, 2951971274, 1757691577, 607398968, 2738905026, 499347990, 3794078908, 1011452712, 227885567, 2818666809, 213114376, 3034881240, 1455525988, 3414450555, 850817237, 1817998408, 3092726480], En = [0, 235474187, 470948374, 303765277, 941896748, 908933415, 607530554, 708780849, 1883793496, 2118214995, 1817866830, 1649639237, 1215061108, 1181045119, 1417561698, 1517767529, 3767586992, 4003061179, 4236429990, 4069246893, 3635733660, 3602770327, 3299278474, 3400528769, 2430122216, 2664543715, 2362090238, 2193862645, 2835123396, 2801107407, 3035535058, 3135740889, 3678124923, 3576870512, 3341394285, 3374361702, 3810496343, 3977675356, 4279080257, 4043610186, 2876494627, 2776292904, 3076639029, 3110650942, 2472011535, 2640243204, 2403728665, 2169303058, 1001089995, 899835584, 666464733, 699432150, 59727847, 226906860, 530400753, 294930682, 1273168787, 1172967064, 1475418501, 1509430414, 1942435775, 2110667444, 1876241833, 1641816226, 2910219766, 2743034109, 2976151520, 3211623147, 2505202138, 2606453969, 2302690252, 2269728455, 3711829422, 3543599269, 3240894392, 3475313331, 3843699074, 3943906441, 4178062228, 4144047775, 1306967366, 1139781709, 1374988112, 1610459739, 1975683434, 2076935265, 1775276924, 1742315127, 1034867998, 866637845, 566021896, 800440835, 92987698, 193195065, 429456164, 395441711, 1984812685, 2017778566, 1784663195, 1683407248, 1315562145, 1080094634, 1383856311, 1551037884, 101039829, 135050206, 437757123, 337553864, 1042385657, 807962610, 573804783, 742039012, 2531067453, 2564033334, 2328828971, 2227573024, 2935566865, 2700099354, 3001755655, 3168937228, 3868552805, 3902563182, 4203181171, 4102977912, 3736164937, 3501741890, 3265478751, 3433712980, 1106041591, 1340463100, 1576976609, 1408749034, 2043211483, 2009195472, 1708848333, 1809054150, 832877231, 1068351396, 766945465, 599762354, 159417987, 126454664, 361929877, 463180190, 2709260871, 2943682380, 3178106961, 3009879386, 2572697195, 2538681184, 2236228733, 2336434550, 3509871135, 3745345300, 3441850377, 3274667266, 3910161971, 3877198648, 4110568485, 4211818798, 2597806476, 2497604743, 2261089178, 2295101073, 2733856160, 2902087851, 3202437046, 2968011453, 3936291284, 3835036895, 4136440770, 4169408201, 3535486456, 3702665459, 3467192302, 3231722213, 2051518780, 1951317047, 1716890410, 1750902305, 1113818384, 1282050075, 1584504582, 1350078989, 168810852, 67556463, 371049330, 404016761, 841739592, 1008918595, 775550814, 540080725, 3969562369, 3801332234, 4035489047, 4269907996, 3569255213, 3669462566, 3366754619, 3332740144, 2631065433, 2463879762, 2160117071, 2395588676, 2767645557, 2868897406, 3102011747, 3069049960, 202008497, 33778362, 270040487, 504459436, 875451293, 975658646, 675039627, 641025152, 2084704233, 1917518562, 1615861247, 1851332852, 1147550661, 1248802510, 1484005843, 1451044056, 933301370, 967311729, 733156972, 632953703, 260388950, 25965917, 328671808, 496906059, 1206477858, 1239443753, 1543208500, 1441952575, 2144161806, 1908694277, 1675577880, 1842759443, 3610369226, 3644379585, 3408119516, 3307916247, 4011190502, 3776767469, 4077384432, 4245618683, 2809771154, 2842737049, 3144396420, 3043140495, 2673705150, 2438237621, 2203032232, 2370213795], kn = [0, 185469197, 370938394, 487725847, 741876788, 657861945, 975451694, 824852259, 1483753576, 1400783205, 1315723890, 1164071807, 1950903388, 2135319889, 1649704518, 1767536459, 2967507152, 3152976349, 2801566410, 2918353863, 2631447780, 2547432937, 2328143614, 2177544179, 3901806776, 3818836405, 4270639778, 4118987695, 3299409036, 3483825537, 3535072918, 3652904859, 2077965243, 1893020342, 1841768865, 1724457132, 1474502543, 1559041666, 1107234197, 1257309336, 598438867, 681933534, 901210569, 1052338372, 261314535, 77422314, 428819965, 310463728, 3409685355, 3224740454, 3710368113, 3593056380, 3875770207, 3960309330, 4045380933, 4195456072, 2471224067, 2554718734, 2237133081, 2388260884, 3212035895, 3028143674, 2842678573, 2724322336, 4138563181, 4255350624, 3769721975, 3955191162, 3667219033, 3516619604, 3431546947, 3347532110, 2933734917, 2782082824, 3099667487, 3016697106, 2196052529, 2313884476, 2499348523, 2683765030, 1179510461, 1296297904, 1347548327, 1533017514, 1786102409, 1635502980, 2087309459, 2003294622, 507358933, 355706840, 136428751, 53458370, 839224033, 957055980, 605657339, 790073846, 2373340630, 2256028891, 2607439820, 2422494913, 2706270690, 2856345839, 3075636216, 3160175349, 3573941694, 3725069491, 3273267108, 3356761769, 4181598602, 4063242375, 4011996048, 3828103837, 1033297158, 915985419, 730517276, 545572369, 296679730, 446754879, 129166120, 213705253, 1709610350, 1860738147, 1945798516, 2029293177, 1239331162, 1120974935, 1606591296, 1422699085, 4148292826, 4233094615, 3781033664, 3931371469, 3682191598, 3497509347, 3446004468, 3328955385, 2939266226, 2755636671, 3106780840, 2988687269, 2198438022, 2282195339, 2501218972, 2652609425, 1201765386, 1286567175, 1371368976, 1521706781, 1805211710, 1620529459, 2105887268, 1988838185, 533804130, 350174575, 164439672, 46346101, 870912086, 954669403, 636813900, 788204353, 2358957921, 2274680428, 2592523643, 2441661558, 2695033685, 2880240216, 3065962831, 3182487618, 3572145929, 3756299780, 3270937875, 3388507166, 4174560061, 4091327024, 4006521127, 3854606378, 1014646705, 930369212, 711349675, 560487590, 272786309, 457992840, 106852767, 223377554, 1678381017, 1862534868, 1914052035, 2031621326, 1211247597, 1128014560, 1580087799, 1428173050, 32283319, 182621114, 401639597, 486441376, 768917123, 651868046, 1003007129, 818324884, 1503449823, 1385356242, 1333838021, 1150208456, 1973745387, 2125135846, 1673061617, 1756818940, 2970356327, 3120694122, 2802849917, 2887651696, 2637442643, 2520393566, 2334669897, 2149987652, 3917234703, 3799141122, 4284502037, 4100872472, 3309594171, 3460984630, 3545789473, 3629546796, 2050466060, 1899603969, 1814803222, 1730525723, 1443857720, 1560382517, 1075025698, 1260232239, 575138148, 692707433, 878443390, 1062597235, 243256656, 91341917, 409198410, 325965383, 3403100636, 3252238545, 3704300486, 3620022987, 3874428392, 3990953189, 4042459122, 4227665663, 2460449204, 2578018489, 2226875310, 2411029155, 3198115200, 3046200461, 2827177882, 2743944855], An = [0, 218828297, 437656594, 387781147, 875313188, 958871085, 775562294, 590424639, 1750626376, 1699970625, 1917742170, 2135253587, 1551124588, 1367295589, 1180849278, 1265195639, 3501252752, 3720081049, 3399941250, 3350065803, 3835484340, 3919042237, 4270507174, 4085369519, 3102249176, 3051593425, 2734591178, 2952102595, 2361698556, 2177869557, 2530391278, 2614737639, 3145456443, 3060847922, 2708326185, 2892417312, 2404901663, 2187128086, 2504130317, 2555048196, 3542330227, 3727205754, 3375740769, 3292445032, 3876557655, 3926170974, 4246310725, 4027744588, 1808481195, 1723872674, 1910319033, 2094410160, 1608975247, 1391201670, 1173430173, 1224348052, 59984867, 244860394, 428169201, 344873464, 935293895, 984907214, 766078933, 547512796, 1844882806, 1627235199, 2011214180, 2062270317, 1507497298, 1423022939, 1137477952, 1321699145, 95345982, 145085239, 532201772, 313773861, 830661914, 1015671571, 731183368, 648017665, 3175501286, 2957853679, 2807058932, 2858115069, 2305455554, 2220981195, 2474404304, 2658625497, 3575528878, 3625268135, 3473416636, 3254988725, 3778151818, 3963161475, 4213447064, 4130281361, 3599595085, 3683022916, 3432737375, 3247465558, 3802222185, 4020912224, 4172763771, 4122762354, 3201631749, 3017672716, 2764249623, 2848461854, 2331590177, 2280796200, 2431590963, 2648976442, 104699613, 188127444, 472615631, 287343814, 840019705, 1058709744, 671593195, 621591778, 1852171925, 1668212892, 1953757831, 2037970062, 1514790577, 1463996600, 1080017571, 1297403050, 3673637356, 3623636965, 3235995134, 3454686199, 4007360968, 3822090177, 4107101658, 4190530515, 2997825956, 3215212461, 2830708150, 2779915199, 2256734592, 2340947849, 2627016082, 2443058075, 172466556, 122466165, 273792366, 492483431, 1047239e3, 861968209, 612205898, 695634755, 1646252340, 1863638845, 2013908262, 1963115311, 1446242576, 1530455833, 1277555970, 1093597963, 1636604631, 1820824798, 2073724613, 1989249228, 1436590835, 1487645946, 1337376481, 1119727848, 164948639, 81781910, 331544205, 516552836, 1039717051, 821288114, 669961897, 719700128, 2973530695, 3157750862, 2871682645, 2787207260, 2232435299, 2283490410, 2667994737, 2450346104, 3647212047, 3564045318, 3279033885, 3464042516, 3980931627, 3762502690, 4150144569, 4199882800, 3070356634, 3121275539, 2904027272, 2686254721, 2200818878, 2384911031, 2570832044, 2486224549, 3747192018, 3528626907, 3310321856, 3359936201, 3950355702, 3867060991, 4049844452, 4234721005, 1739656202, 1790575107, 2108100632, 1890328081, 1402811438, 1586903591, 1233856572, 1149249077, 266959938, 48394827, 369057872, 418672217, 1002783846, 919489135, 567498868, 752375421, 209336225, 24197544, 376187827, 459744698, 945164165, 895287692, 574624663, 793451934, 1679968233, 1764313568, 2117360635, 1933530610, 1343127501, 1560637892, 1243112415, 1192455638, 3704280881, 3519142200, 3336358691, 3419915562, 3907448597, 3857572124, 4075877127, 4294704398, 3029510009, 3113855344, 2927934315, 2744104290, 2159976285, 2377486676, 2594734927, 2544078150], Pn = [0, 151849742, 303699484, 454499602, 607398968, 758720310, 908999204, 1059270954, 1214797936, 1097159550, 1517440620, 1400849762, 1817998408, 1699839814, 2118541908, 2001430874, 2429595872, 2581445614, 2194319100, 2345119218, 3034881240, 3186202582, 2801699524, 2951971274, 3635996816, 3518358430, 3399679628, 3283088770, 4237083816, 4118925222, 4002861748, 3885750714, 1002142683, 850817237, 698445255, 548169417, 529487843, 377642221, 227885567, 77089521, 1943217067, 2061379749, 1640576439, 1757691577, 1474760595, 1592394909, 1174215055, 1290801793, 2875968315, 2724642869, 3111247143, 2960971305, 2405426947, 2253581325, 2638606623, 2487810577, 3808662347, 3926825029, 4044981591, 4162096729, 3342319475, 3459953789, 3576539503, 3693126241, 1986918061, 2137062819, 1685577905, 1836772287, 1381620373, 1532285339, 1078185097, 1229899655, 1040559837, 923313619, 740276417, 621982671, 439452389, 322734571, 137073913, 19308535, 3871163981, 4021308739, 4104605777, 4255800159, 3263785589, 3414450555, 3499326569, 3651041127, 2933202493, 2815956275, 3167684641, 3049390895, 2330014213, 2213296395, 2566595609, 2448830231, 1305906550, 1155237496, 1607244650, 1455525988, 1776460110, 1626319424, 2079897426, 1928707164, 96392454, 213114376, 396673818, 514443284, 562755902, 679998e3, 865136418, 983426092, 3708173718, 3557504664, 3474729866, 3323011204, 4180808110, 4030667424, 3945269170, 3794078908, 2507040230, 2623762152, 2272556026, 2390325492, 2975484382, 3092726480, 2738905026, 2857194700, 3973773121, 3856137295, 4274053469, 4157467219, 3371096953, 3252932727, 3673476453, 3556361835, 2763173681, 2915017791, 3064510765, 3215307299, 2156299017, 2307622919, 2459735317, 2610011675, 2081048481, 1963412655, 1846563261, 1729977011, 1480485785, 1362321559, 1243905413, 1126790795, 878845905, 1030690015, 645401037, 796197571, 274084841, 425408743, 38544885, 188821243, 3613494426, 3731654548, 3313212038, 3430322568, 4082475170, 4200115116, 3780097726, 3896688048, 2668221674, 2516901860, 2366882550, 2216610296, 3141400786, 2989552604, 2837966542, 2687165888, 1202797690, 1320957812, 1437280870, 1554391400, 1669664834, 1787304780, 1906247262, 2022837584, 265905162, 114585348, 499347990, 349075736, 736970802, 585122620, 972512814, 821712160, 2595684844, 2478443234, 2293045232, 2174754046, 3196267988, 3079546586, 2895723464, 2777952454, 3537852828, 3687994002, 3234156416, 3385345166, 4142626212, 4293295786, 3841024952, 3992742070, 174567692, 57326082, 410887952, 292596766, 777231668, 660510266, 1011452712, 893681702, 1108339068, 1258480242, 1343618912, 1494807662, 1715193156, 1865862730, 1948373848, 2100090966, 2701949495, 2818666809, 3004591147, 3122358053, 2235061775, 2352307457, 2535604243, 2653899549, 3915653703, 3764988233, 4219352155, 4067639125, 3444575871, 3294430577, 3746175075, 3594982253, 836553431, 953270745, 600235211, 718002117, 367585007, 484830689, 133361907, 251657213, 2041877159, 1891211689, 1806599355, 1654886325, 1568718495, 1418573201, 1335535747, 1184342925];
  48910. function Cn(e2) {
  48911. for (var t2 = [], n2 = 0; n2 < e2.length; n2 += 4)
  48912. t2.push(e2[n2] << 24 | e2[n2 + 1] << 16 | e2[n2 + 2] << 8 | e2[n2 + 3]);
  48913. return t2;
  48914. }
  48915. class On {
  48916. constructor(e2) {
  48917. if (!(this instanceof On))
  48918. throw Error("AES must be instanitated with `new`");
  48919. Object.defineProperty(this, "key", { value: an(e2, true) }), this._prepare();
  48920. }
  48921. _prepare() {
  48922. var e2 = pn[this.key.length];
  48923. if (null == e2)
  48924. throw new Error("invalid key size (must be 16, 24 or 32 bytes)");
  48925. this._Ke = [], this._Kd = [];
  48926. for (var t2 = 0; t2 <= e2; t2++)
  48927. this._Ke.push([0, 0, 0, 0]), this._Kd.push([0, 0, 0, 0]);
  48928. var n2, s2 = 4 * (e2 + 1), r2 = this.key.length / 4, i2 = Cn(this.key);
  48929. for (t2 = 0; t2 < r2; t2++)
  48930. n2 = t2 >> 2, this._Ke[n2][t2 % 4] = i2[t2], this._Kd[e2 - n2][t2 % 4] = i2[t2];
  48931. for (var o2, a2 = 0, c2 = r2; c2 < s2; ) {
  48932. if (o2 = i2[r2 - 1], i2[0] ^= gn[o2 >> 16 & 255] << 24 ^ gn[o2 >> 8 & 255] << 16 ^ gn[255 & o2] << 8 ^ gn[o2 >> 24 & 255] ^ fn[a2] << 24, a2 += 1, 8 != r2)
  48933. for (t2 = 1; t2 < r2; t2++)
  48934. i2[t2] ^= i2[t2 - 1];
  48935. else {
  48936. for (t2 = 1; t2 < r2 / 2; t2++)
  48937. i2[t2] ^= i2[t2 - 1];
  48938. o2 = i2[r2 / 2 - 1], i2[r2 / 2] ^= gn[255 & o2] ^ gn[o2 >> 8 & 255] << 8 ^ gn[o2 >> 16 & 255] << 16 ^ gn[o2 >> 24 & 255] << 24;
  48939. for (t2 = r2 / 2 + 1; t2 < r2; t2++)
  48940. i2[t2] ^= i2[t2 - 1];
  48941. }
  48942. for (t2 = 0; t2 < r2 && c2 < s2; )
  48943. u2 = c2 >> 2, h2 = c2 % 4, this._Ke[u2][h2] = i2[t2], this._Kd[e2 - u2][h2] = i2[t2++], c2++;
  48944. }
  48945. for (var u2 = 1; u2 < e2; u2++)
  48946. for (var h2 = 0; h2 < 4; h2++)
  48947. o2 = this._Kd[u2][h2], this._Kd[u2][h2] = En[o2 >> 24 & 255] ^ kn[o2 >> 16 & 255] ^ An[o2 >> 8 & 255] ^ Pn[255 & o2];
  48948. }
  48949. encrypt(e2) {
  48950. if (16 != e2.length)
  48951. throw new Error("invalid plaintext size (must be 16 bytes)");
  48952. for (var t2 = this._Ke.length - 1, n2 = [0, 0, 0, 0], s2 = Cn(e2), r2 = 0; r2 < 4; r2++)
  48953. s2[r2] ^= this._Ke[0][r2];
  48954. for (var i2 = 1; i2 < t2; i2++) {
  48955. for (r2 = 0; r2 < 4; r2++)
  48956. n2[r2] = yn[s2[r2] >> 24 & 255] ^ _n[s2[(r2 + 1) % 4] >> 16 & 255] ^ wn[s2[(r2 + 2) % 4] >> 8 & 255] ^ In[255 & s2[(r2 + 3) % 4]] ^ this._Ke[i2][r2];
  48957. s2 = n2.slice();
  48958. }
  48959. var o2, a2 = cn(16);
  48960. for (r2 = 0; r2 < 4; r2++)
  48961. o2 = this._Ke[t2][r2], a2[4 * r2] = 255 & (gn[s2[r2] >> 24 & 255] ^ o2 >> 24), a2[4 * r2 + 1] = 255 & (gn[s2[(r2 + 1) % 4] >> 16 & 255] ^ o2 >> 16), a2[4 * r2 + 2] = 255 & (gn[s2[(r2 + 2) % 4] >> 8 & 255] ^ o2 >> 8), a2[4 * r2 + 3] = 255 & (gn[255 & s2[(r2 + 3) % 4]] ^ o2);
  48962. return a2;
  48963. }
  48964. decrypt(e2) {
  48965. if (16 != e2.length)
  48966. throw new Error("invalid ciphertext size (must be 16 bytes)");
  48967. for (var t2 = this._Kd.length - 1, n2 = [0, 0, 0, 0], s2 = Cn(e2), r2 = 0; r2 < 4; r2++)
  48968. s2[r2] ^= this._Kd[0][r2];
  48969. for (var i2 = 1; i2 < t2; i2++) {
  48970. for (r2 = 0; r2 < 4; r2++)
  48971. n2[r2] = vn[s2[r2] >> 24 & 255] ^ Sn[s2[(r2 + 3) % 4] >> 16 & 255] ^ Tn[s2[(r2 + 2) % 4] >> 8 & 255] ^ bn[255 & s2[(r2 + 1) % 4]] ^ this._Kd[i2][r2];
  48972. s2 = n2.slice();
  48973. }
  48974. var o2, a2 = cn(16);
  48975. for (r2 = 0; r2 < 4; r2++)
  48976. o2 = this._Kd[t2][r2], a2[4 * r2] = 255 & (mn[s2[r2] >> 24 & 255] ^ o2 >> 24), a2[4 * r2 + 1] = 255 & (mn[s2[(r2 + 3) % 4] >> 16 & 255] ^ o2 >> 16), a2[4 * r2 + 2] = 255 & (mn[s2[(r2 + 2) % 4] >> 8 & 255] ^ o2 >> 8), a2[4 * r2 + 3] = 255 & (mn[255 & s2[(r2 + 1) % 4]] ^ o2);
  48977. return a2;
  48978. }
  48979. }
  48980. class xn {
  48981. constructor(e2) {
  48982. if (!(this instanceof xn))
  48983. throw Error("AES must be instanitated with `new`");
  48984. this.description = "Electronic Code Block", this.name = "ecb", this._aes = new On(e2);
  48985. }
  48986. encrypt(e2) {
  48987. if ((e2 = an(e2)).length % 16 != 0)
  48988. throw new Error("invalid plaintext size (must be multiple of 16 bytes)");
  48989. for (var t2 = cn(e2.length), n2 = cn(16), s2 = 0; s2 < e2.length; s2 += 16)
  48990. un(e2, n2, 0, s2, s2 + 16), un(n2 = this._aes.encrypt(n2), t2, s2);
  48991. return t2;
  48992. }
  48993. decrypt(e2) {
  48994. if ((e2 = an(e2)).length % 16 != 0)
  48995. throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");
  48996. for (var t2 = cn(e2.length), n2 = cn(16), s2 = 0; s2 < e2.length; s2 += 16)
  48997. un(e2, n2, 0, s2, s2 + 16), un(n2 = this._aes.decrypt(n2), t2, s2);
  48998. return t2;
  48999. }
  49000. }
  49001. class Nn {
  49002. constructor(e2, t2) {
  49003. if (!(this instanceof Nn))
  49004. throw Error("AES must be instanitated with `new`");
  49005. if (this.description = "Cipher Block Chaining", this.name = "cbc", t2) {
  49006. if (16 != t2.length)
  49007. throw new Error("invalid initialation vector size (must be 16 bytes)");
  49008. } else
  49009. t2 = cn(16);
  49010. this._lastCipherblock = an(t2, true), this._aes = new On(e2);
  49011. }
  49012. encrypt(e2) {
  49013. if ((e2 = an(e2)).length % 16 != 0)
  49014. throw new Error("invalid plaintext size (must be multiple of 16 bytes)");
  49015. for (var t2 = cn(e2.length), n2 = cn(16), s2 = 0; s2 < e2.length; s2 += 16) {
  49016. un(e2, n2, 0, s2, s2 + 16);
  49017. for (var r2 = 0; r2 < 16; r2++)
  49018. n2[r2] ^= this._lastCipherblock[r2];
  49019. this._lastCipherblock = this._aes.encrypt(n2), un(this._lastCipherblock, t2, s2);
  49020. }
  49021. return t2;
  49022. }
  49023. decrypt(e2) {
  49024. if ((e2 = an(e2)).length % 16 != 0)
  49025. throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");
  49026. for (var t2 = cn(e2.length), n2 = cn(16), s2 = 0; s2 < e2.length; s2 += 16) {
  49027. un(e2, n2, 0, s2, s2 + 16), n2 = this._aes.decrypt(n2);
  49028. for (var r2 = 0; r2 < 16; r2++)
  49029. t2[s2 + r2] = n2[r2] ^ this._lastCipherblock[r2];
  49030. un(e2, this._lastCipherblock, 0, s2, s2 + 16);
  49031. }
  49032. return t2;
  49033. }
  49034. }
  49035. class Rn {
  49036. constructor(e2, t2, n2) {
  49037. if (!(this instanceof Rn))
  49038. throw Error("AES must be instanitated with `new`");
  49039. if (this.description = "Cipher Feedback", this.name = "cfb", t2) {
  49040. if (16 != t2.length)
  49041. throw new Error("invalid initialation vector size (must be 16 size)");
  49042. } else
  49043. t2 = cn(16);
  49044. n2 || (n2 = 1), this.segmentSize = n2, this._shiftRegister = an(t2, true), this._aes = new On(e2);
  49045. }
  49046. encrypt(e2) {
  49047. if (e2.length % this.segmentSize != 0)
  49048. throw new Error("invalid plaintext size (must be segmentSize bytes)");
  49049. for (var t2, n2 = an(e2, true), s2 = 0; s2 < n2.length; s2 += this.segmentSize) {
  49050. t2 = this._aes.encrypt(this._shiftRegister);
  49051. for (var r2 = 0; r2 < this.segmentSize; r2++)
  49052. n2[s2 + r2] ^= t2[r2];
  49053. un(this._shiftRegister, this._shiftRegister, 0, this.segmentSize), un(n2, this._shiftRegister, 16 - this.segmentSize, s2, s2 + this.segmentSize);
  49054. }
  49055. return n2;
  49056. }
  49057. decrypt(e2) {
  49058. if (e2.length % this.segmentSize != 0)
  49059. throw new Error("invalid ciphertext size (must be segmentSize bytes)");
  49060. for (var t2, n2 = an(e2, true), s2 = 0; s2 < n2.length; s2 += this.segmentSize) {
  49061. t2 = this._aes.encrypt(this._shiftRegister);
  49062. for (var r2 = 0; r2 < this.segmentSize; r2++)
  49063. n2[s2 + r2] ^= t2[r2];
  49064. un(this._shiftRegister, this._shiftRegister, 0, this.segmentSize), un(e2, this._shiftRegister, 16 - this.segmentSize, s2, s2 + this.segmentSize);
  49065. }
  49066. return n2;
  49067. }
  49068. }
  49069. class Ln {
  49070. constructor(e2, t2) {
  49071. if (!(this instanceof Ln))
  49072. throw Error("AES must be instanitated with `new`");
  49073. if (this.description = "Output Feedback", this.name = "ofb", t2) {
  49074. if (16 != t2.length)
  49075. throw new Error("invalid initialation vector size (must be 16 bytes)");
  49076. } else
  49077. t2 = cn(16);
  49078. this._lastPrecipher = an(t2, true), this._lastPrecipherIndex = 16, this._aes = new On(e2);
  49079. }
  49080. encrypt(e2) {
  49081. for (var t2 = an(e2, true), n2 = 0; n2 < t2.length; n2++)
  49082. 16 === this._lastPrecipherIndex && (this._lastPrecipher = this._aes.encrypt(this._lastPrecipher), this._lastPrecipherIndex = 0), t2[n2] ^= this._lastPrecipher[this._lastPrecipherIndex++];
  49083. return t2;
  49084. }
  49085. decrypt(e2) {
  49086. return this.encrypt(e2);
  49087. }
  49088. }
  49089. class Un {
  49090. constructor(e2) {
  49091. if (!(this instanceof Un))
  49092. throw Error("Counter must be instanitated with `new`");
  49093. 0 === e2 || e2 || (e2 = 1), "number" == typeof e2 ? (this._counter = cn(16), this.setValue(e2)) : this.setBytes(e2);
  49094. }
  49095. setValue(e2) {
  49096. if ("number" != typeof e2 || parseInt(e2) != e2)
  49097. throw new Error("invalid counter value (must be an integer)");
  49098. if (e2 > Number.MAX_SAFE_INTEGER)
  49099. throw new Error("integer value out of safe range");
  49100. for (var t2 = 15; t2 >= 0; --t2)
  49101. this._counter[t2] = e2 % 256, e2 = parseInt(e2 / 256);
  49102. }
  49103. setBytes(e2) {
  49104. if (16 != (e2 = an(e2, true)).length)
  49105. throw new Error("invalid counter bytes size (must be 16 bytes)");
  49106. this._counter = e2;
  49107. }
  49108. increment() {
  49109. for (var e2 = 15; e2 >= 0; e2--) {
  49110. if (255 !== this._counter[e2]) {
  49111. this._counter[e2]++;
  49112. break;
  49113. }
  49114. this._counter[e2] = 0;
  49115. }
  49116. }
  49117. }
  49118. class Dn {
  49119. constructor(e2, t2) {
  49120. if (!(this instanceof Dn))
  49121. throw Error("AES must be instanitated with `new`");
  49122. this.description = "Counter", this.name = "ctr", t2 instanceof Un || (t2 = new Un(t2)), this._counter = t2, this._remainingCounter = null, this._remainingCounterIndex = 16, this._aes = new On(e2);
  49123. }
  49124. encrypt(e2) {
  49125. for (var t2 = an(e2, true), n2 = 0; n2 < t2.length; n2++)
  49126. 16 === this._remainingCounterIndex && (this._remainingCounter = this._aes.encrypt(this._counter._counter), this._remainingCounterIndex = 0, this._counter.increment()), t2[n2] ^= this._remainingCounter[this._remainingCounterIndex++];
  49127. return t2;
  49128. }
  49129. decrypt(e2) {
  49130. return this.encrypt(e2);
  49131. }
  49132. }
  49133. var Mn = { AES: On, Counter: Un, ModeOfOperation: { ecb: xn, cbc: Nn, cfb: Rn, ofb: Ln, ctr: Dn }, utils: { hex: dn, utf8: ln }, padding: { pkcs7: { pad: function(e2) {
  49134. var t2 = 16 - (e2 = an(e2, true)).length % 16, n2 = cn(e2.length + t2);
  49135. un(e2, n2);
  49136. for (var s2 = e2.length; s2 < n2.length; s2++)
  49137. n2[s2] = t2;
  49138. return n2;
  49139. }, strip: function(e2) {
  49140. if ((e2 = an(e2, true)).length < 16)
  49141. throw new Error("PKCS#7 invalid length");
  49142. var t2 = e2[e2.length - 1];
  49143. if (t2 > 16)
  49144. throw new Error("PKCS#7 padding byte out of range");
  49145. for (var n2 = e2.length - t2, s2 = 0; s2 < t2; s2++)
  49146. if (e2[n2 + s2] !== t2)
  49147. throw new Error("PKCS#7 invalid padding byte");
  49148. var r2 = cn(n2);
  49149. return un(e2, r2, 0, 0, n2), r2;
  49150. } } }, _arrayTest: { coerceArray: an, createArray: cn, copyArray: un } };
  49151. function qn(e2, t2, n2) {
  49152. const s2 = new Uint8Array(index.base64ToArrayBuffer(t2)), r2 = Mn.utils.utf8.toBytes(n2), i2 = Mn.utils.utf8.toBytes(e2), o2 = new Mn.ModeOfOperation.cbc(s2, r2), a2 = Mn.padding.pkcs7.pad(i2), c2 = o2.encrypt(a2);
  49153. return index.arrayBufferToBase64(c2);
  49154. }
  49155. let Kn, jn = null;
  49156. class $n extends sn {
  49157. constructor(e2) {
  49158. super(e2), this.clientType = "mp-weixin", this.userEncryptKey = null;
  49159. }
  49160. isLogin() {
  49161. return !!this.scopedGlobalCache.mpWeixinCode || !!this.scopedGlobalCache.mpWeixinOpenid;
  49162. }
  49163. async prepare() {
  49164. if (!this.isLogin()) {
  49165. if (!this.scopedGlobalCache.initPromise)
  49166. throw new Error("`uniCloud.initSecureNetworkByWeixin` has not yet been called");
  49167. if (await this.scopedGlobalCache.initPromise, !this.isLogin())
  49168. throw new Error("uniCloud.initSecureNetworkByWeixin` has not yet been called or successfully excuted");
  49169. }
  49170. }
  49171. async getUserEncryptKey() {
  49172. if (this.userEncryptKey)
  49173. return this.userEncryptKey;
  49174. if (jn && jn.expireTime) {
  49175. const e2 = Date.now();
  49176. if (jn.expireTime - e2 > 0)
  49177. return this.userEncryptKey = jn, this.userEncryptKey;
  49178. }
  49179. return new Promise((e2, t2) => {
  49180. index.getUserCryptoManager().getLatestUserKey({ success: (t3) => {
  49181. jn = t3, this.userEncryptKey = t3, e2(this.userEncryptKey);
  49182. }, fail: (e3) => {
  49183. t2(nn({ ...en.GET_ENCRYPT_KEY_FAILED, cause: e3 }));
  49184. } });
  49185. });
  49186. }
  49187. getWxAppId() {
  49188. return wx$1.getAccountInfoSync().miniProgram.appId;
  49189. }
  49190. async platformGetSignOption() {
  49191. const { encryptKey: e2, iv: t2, version: n2 } = await this.getUserEncryptKey();
  49192. return { verifyClientSign: qn(JSON.stringify({ data: JSON.stringify({}), appId: this.appId, deviceId: this.deviceId, wxAppId: this.getWxAppId(), simulator: "devtools" === ce().platform, timestamp: Date.now() }), e2, t2), encryptKeyId: n2, mpWeixinCode: this.scopedGlobalCache.mpWeixinCode, mpWeixinOpenid: this.scopedGlobalCache.mpWeixinOpenid };
  49193. }
  49194. async platformEncryptData(e2) {
  49195. const { encryptKey: t2, iv: n2, version: s2 } = await this.getUserEncryptKey(), r2 = { secretType: this.secretType, encryptKeyId: s2, mpWeixinCode: this.scopedGlobalCache.mpWeixinCode, mpWeixinOpenid: this.scopedGlobalCache.mpWeixinOpenid };
  49196. return this.secretType === Yt.RESPONSE ? { content: e2, _uniCloudOptions: r2 } : { content: qn(JSON.stringify({ data: JSON.stringify(e2), appId: this.appId, deviceId: this.deviceId, wxAppId: this.getWxAppId(), simulator: "devtools" === ce().platform, timestamp: Date.now() }), t2, n2), _uniCloudOptions: r2 };
  49197. }
  49198. async platformDecryptResult(e2) {
  49199. const { content: t2 } = e2, { encryptKey: n2, iv: s2 } = await this.getUserEncryptKey();
  49200. return JSON.parse(function(e3, t3, n3) {
  49201. const s3 = new Uint8Array(index.base64ToArrayBuffer(e3)), r2 = new Uint8Array(index.base64ToArrayBuffer(t3)), i2 = Mn.utils.utf8.toBytes(n3), o2 = new Mn.ModeOfOperation.cbc(r2, i2), a2 = Mn.padding.pkcs7.strip(o2.decrypt(s3));
  49202. return Mn.utils.utf8.fromBytes(a2);
  49203. }(t2, n2, s2));
  49204. }
  49205. isClientKeyNotFound() {
  49206. return false;
  49207. }
  49208. }
  49209. function Hn({ secretType: e2 } = {}) {
  49210. return e2 === Yt.REQUEST || e2 === Yt.RESPONSE || e2 === Yt.BOTH;
  49211. }
  49212. function Jn({ name: e2, data: t2 = {} } = {}) {
  49213. return "app" === P;
  49214. }
  49215. function zn({ provider: e2, spaceId: t2, functionName: n2 } = {}) {
  49216. const { appId: s2, uniPlatform: r2, osName: i2 } = ce();
  49217. let o2 = r2;
  49218. "app" === r2 && (o2 = i2);
  49219. const a2 = function({ provider: e3, spaceId: t3 } = {}) {
  49220. const n3 = A;
  49221. if (!n3)
  49222. return {};
  49223. e3 = /* @__PURE__ */ function(e4) {
  49224. return "tencent" === e4 ? "tcb" : e4;
  49225. }(e3);
  49226. const s3 = n3.find((n4) => n4.provider === e3 && n4.spaceId === t3);
  49227. return s3 && s3.config;
  49228. }({ provider: e2, spaceId: t2 });
  49229. if (!a2 || !a2.accessControl || !a2.accessControl.enable)
  49230. return false;
  49231. const c2 = a2.accessControl.function || {}, u2 = Object.keys(c2);
  49232. if (0 === u2.length)
  49233. return true;
  49234. const h2 = function(e3, t3) {
  49235. let n3, s3, r3;
  49236. for (let i3 = 0; i3 < e3.length; i3++) {
  49237. const o3 = e3[i3];
  49238. o3 !== t3 ? "*" !== o3 ? o3.split(",").map((e4) => e4.trim()).indexOf(t3) > -1 && (s3 = o3) : r3 = o3 : n3 = o3;
  49239. }
  49240. return n3 || s3 || r3;
  49241. }(u2, n2);
  49242. if (!h2)
  49243. return false;
  49244. if ((c2[h2] || []).find((e3 = {}) => e3.appId === s2 && (e3.platform || "").toLowerCase() === o2.toLowerCase()))
  49245. return true;
  49246. throw console.error(`此应用[appId: ${s2}, platform: ${o2}]不在云端配置的允许访问的应用列表内,参考:https://uniapp.dcloud.net.cn/uniCloud/secure-network.html#verify-client`), nn(en.APP_INFO_INVALID);
  49247. }
  49248. function Vn({ functionName: e2, result: t2, logPvd: n2 }) {
  49249. if (this.__dev__.debugLog && t2 && t2.requestId) {
  49250. const s2 = JSON.stringify({ spaceId: this.config.spaceId, functionName: e2, requestId: t2.requestId });
  49251. console.log(`[${n2}-request]${s2}[/${n2}-request]`);
  49252. }
  49253. }
  49254. function Gn(e2) {
  49255. const t2 = e2.callFunction, n2 = function(n3) {
  49256. const s2 = n3.name;
  49257. n3.data = Wt.call(e2, { data: n3.data });
  49258. const r2 = { aliyun: "aliyun", tencent: "tcb", tcb: "tcb", alipay: "alipay", dcloud: "dcloud" }[this.config.provider], i2 = Hn(n3), o2 = Jn(n3), a2 = i2 || o2;
  49259. return t2.call(this, n3).then((e3) => (e3.errCode = 0, !a2 && Vn.call(this, { functionName: s2, result: e3, logPvd: r2 }), Promise.resolve(e3)), (e3) => (!a2 && Vn.call(this, { functionName: s2, result: e3, logPvd: r2 }), e3 && e3.message && (e3.message = function({ message: e4 = "", extraInfo: t3 = {}, formatter: n4 = [] } = {}) {
  49260. for (let s3 = 0; s3 < n4.length; s3++) {
  49261. const { rule: r3, content: i3, mode: o3 } = n4[s3], a3 = e4.match(r3);
  49262. if (!a3)
  49263. continue;
  49264. let c2 = i3;
  49265. for (let e5 = 1; e5 < a3.length; e5++)
  49266. c2 = Gt(c2, `{$${e5}}`, a3[e5]);
  49267. for (const e5 in t3)
  49268. c2 = Gt(c2, `{${e5}}`, t3[e5]);
  49269. return "replace" === o3 ? c2 : e4 + c2;
  49270. }
  49271. return e4;
  49272. }({ message: `[${n3.name}]: ${e3.message}`, formatter: Jt, extraInfo: { functionName: s2 } })), Promise.reject(e3)));
  49273. };
  49274. e2.callFunction = function(t3) {
  49275. const { provider: s2, spaceId: r2 } = e2.config, i2 = t3.name;
  49276. let o2, a2;
  49277. if (t3.data = t3.data || {}, e2.__dev__.debugInfo && !e2.__dev__.debugInfo.forceRemote && O ? (e2._callCloudFunction || (e2._callCloudFunction = n2, e2._callLocalFunction = Ht), o2 = Ht) : o2 = n2, o2 = o2.bind(e2), Jn(t3))
  49278. ;
  49279. else if (function({ name: e3, data: t4 = {} }) {
  49280. return "uni-id-co" === e3 && "secureNetworkHandshakeByWeixin" === t4.method;
  49281. }(t3))
  49282. a2 = o2.call(e2, t3);
  49283. else if (Hn(t3)) {
  49284. a2 = new Kn({ secretType: t3.secretType, uniCloudIns: e2 }).wrapEncryptDataCallFunction(n2.bind(e2))(t3);
  49285. } else if (zn({ provider: s2, spaceId: r2, functionName: i2 })) {
  49286. a2 = new Kn({ secretType: t3.secretType, uniCloudIns: e2 }).wrapVerifyClientCallFunction(n2.bind(e2))(t3);
  49287. } else
  49288. a2 = o2(t3);
  49289. return Object.defineProperty(a2, "result", { get: () => (console.warn("当前返回结果为Promise类型,不可直接访问其result属性,详情请参考:https://uniapp.dcloud.net.cn/uniCloud/faq?id=promise"), {}) }), a2.then((e3) => e3);
  49290. };
  49291. }
  49292. Kn = $n;
  49293. const Yn = Symbol("CLIENT_DB_INTERNAL");
  49294. function Qn(e2, t2) {
  49295. return e2.then = "DoNotReturnProxyWithAFunctionNamedThen", e2._internalType = Yn, e2.inspect = null, e2.__v_raw = void 0, new Proxy(e2, { get(e3, n2, s2) {
  49296. if ("_uniClient" === n2)
  49297. return null;
  49298. if ("symbol" == typeof n2)
  49299. return e3[n2];
  49300. if (n2 in e3 || "string" != typeof n2) {
  49301. const t3 = e3[n2];
  49302. return "function" == typeof t3 ? t3.bind(e3) : t3;
  49303. }
  49304. return t2.get(e3, n2, s2);
  49305. } });
  49306. }
  49307. function Xn(e2) {
  49308. return { on: (t2, n2) => {
  49309. e2[t2] = e2[t2] || [], e2[t2].indexOf(n2) > -1 || e2[t2].push(n2);
  49310. }, off: (t2, n2) => {
  49311. e2[t2] = e2[t2] || [];
  49312. const s2 = e2[t2].indexOf(n2);
  49313. -1 !== s2 && e2[t2].splice(s2, 1);
  49314. } };
  49315. }
  49316. const Zn = ["db.Geo", "db.command", "command.aggregate"];
  49317. function es(e2, t2) {
  49318. return Zn.indexOf(`${e2}.${t2}`) > -1;
  49319. }
  49320. function ts(e2) {
  49321. switch (g(e2 = se(e2))) {
  49322. case "array":
  49323. return e2.map((e3) => ts(e3));
  49324. case "object":
  49325. return e2._internalType === Yn || Object.keys(e2).forEach((t2) => {
  49326. e2[t2] = ts(e2[t2]);
  49327. }), e2;
  49328. case "regexp":
  49329. return { $regexp: { source: e2.source, flags: e2.flags } };
  49330. case "date":
  49331. return { $date: e2.toISOString() };
  49332. default:
  49333. return e2;
  49334. }
  49335. }
  49336. function ns(e2) {
  49337. return e2 && e2.content && e2.content.$method;
  49338. }
  49339. class ss {
  49340. constructor(e2, t2, n2) {
  49341. this.content = e2, this.prevStage = t2 || null, this.udb = null, this._database = n2;
  49342. }
  49343. toJSON() {
  49344. let e2 = this;
  49345. const t2 = [e2.content];
  49346. for (; e2.prevStage; )
  49347. e2 = e2.prevStage, t2.push(e2.content);
  49348. return { $db: t2.reverse().map((e3) => ({ $method: e3.$method, $param: ts(e3.$param) })) };
  49349. }
  49350. toString() {
  49351. return JSON.stringify(this.toJSON());
  49352. }
  49353. getAction() {
  49354. const e2 = this.toJSON().$db.find((e3) => "action" === e3.$method);
  49355. return e2 && e2.$param && e2.$param[0];
  49356. }
  49357. getCommand() {
  49358. return { $db: this.toJSON().$db.filter((e2) => "action" !== e2.$method) };
  49359. }
  49360. get isAggregate() {
  49361. let e2 = this;
  49362. for (; e2; ) {
  49363. const t2 = ns(e2), n2 = ns(e2.prevStage);
  49364. if ("aggregate" === t2 && "collection" === n2 || "pipeline" === t2)
  49365. return true;
  49366. e2 = e2.prevStage;
  49367. }
  49368. return false;
  49369. }
  49370. get isCommand() {
  49371. let e2 = this;
  49372. for (; e2; ) {
  49373. if ("command" === ns(e2))
  49374. return true;
  49375. e2 = e2.prevStage;
  49376. }
  49377. return false;
  49378. }
  49379. get isAggregateCommand() {
  49380. let e2 = this;
  49381. for (; e2; ) {
  49382. const t2 = ns(e2), n2 = ns(e2.prevStage);
  49383. if ("aggregate" === t2 && "command" === n2)
  49384. return true;
  49385. e2 = e2.prevStage;
  49386. }
  49387. return false;
  49388. }
  49389. getNextStageFn(e2) {
  49390. const t2 = this;
  49391. return function() {
  49392. return rs({ $method: e2, $param: ts(Array.from(arguments)) }, t2, t2._database);
  49393. };
  49394. }
  49395. get count() {
  49396. return this.isAggregate ? this.getNextStageFn("count") : function() {
  49397. return this._send("count", Array.from(arguments));
  49398. };
  49399. }
  49400. get remove() {
  49401. return this.isCommand ? this.getNextStageFn("remove") : function() {
  49402. return this._send("remove", Array.from(arguments));
  49403. };
  49404. }
  49405. get() {
  49406. return this._send("get", Array.from(arguments));
  49407. }
  49408. get add() {
  49409. return this.isCommand ? this.getNextStageFn("add") : function() {
  49410. return this._send("add", Array.from(arguments));
  49411. };
  49412. }
  49413. update() {
  49414. return this._send("update", Array.from(arguments));
  49415. }
  49416. end() {
  49417. return this._send("end", Array.from(arguments));
  49418. }
  49419. get set() {
  49420. return this.isCommand ? this.getNextStageFn("set") : function() {
  49421. throw new Error("JQL禁止使用set方法");
  49422. };
  49423. }
  49424. _send(e2, t2) {
  49425. const n2 = this.getAction(), s2 = this.getCommand();
  49426. if (s2.$db.push({ $method: e2, $param: ts(t2) }), b) {
  49427. const e3 = s2.$db.find((e4) => "collection" === e4.$method), t3 = e3 && e3.$param;
  49428. t3 && 1 === t3.length && "string" == typeof e3.$param[0] && e3.$param[0].indexOf(",") > -1 && console.warn("检测到使用JQL语法联表查询时,未使用getTemp先过滤主表数据,在主表数据量大的情况下可能会查询缓慢。\n- 如何优化请参考此文档:https://uniapp.dcloud.net.cn/uniCloud/jql?id=lookup-with-temp \n- 如果主表数据量很小请忽略此信息,项目发行时不会出现此提示。");
  49429. }
  49430. return this._database._callCloudFunction({ action: n2, command: s2 });
  49431. }
  49432. }
  49433. function rs(e2, t2, n2) {
  49434. return Qn(new ss(e2, t2, n2), { get(e3, t3) {
  49435. let s2 = "db";
  49436. return e3 && e3.content && (s2 = e3.content.$method), es(s2, t3) ? rs({ $method: t3 }, e3, n2) : function() {
  49437. return rs({ $method: t3, $param: ts(Array.from(arguments)) }, e3, n2);
  49438. };
  49439. } });
  49440. }
  49441. function is({ path: e2, method: t2 }) {
  49442. return class {
  49443. constructor() {
  49444. this.param = Array.from(arguments);
  49445. }
  49446. toJSON() {
  49447. return { $newDb: [...e2.map((e3) => ({ $method: e3 })), { $method: t2, $param: this.param }] };
  49448. }
  49449. toString() {
  49450. return JSON.stringify(this.toJSON());
  49451. }
  49452. };
  49453. }
  49454. class os {
  49455. constructor({ uniClient: e2 = {}, isJQL: t2 = false } = {}) {
  49456. this._uniClient = e2, this._authCallBacks = {}, this._dbCallBacks = {}, e2._isDefault && (this._dbCallBacks = U("_globalUniCloudDatabaseCallback")), t2 || (this.auth = Xn(this._authCallBacks)), this._isJQL = t2, Object.assign(this, Xn(this._dbCallBacks)), this.env = Qn({}, { get: (e3, t3) => ({ $env: t3 }) }), this.Geo = Qn({}, { get: (e3, t3) => is({ path: ["Geo"], method: t3 }) }), this.serverDate = is({ path: [], method: "serverDate" }), this.RegExp = is({ path: [], method: "RegExp" });
  49457. }
  49458. getCloudEnv(e2) {
  49459. if ("string" != typeof e2 || !e2.trim())
  49460. throw new Error("getCloudEnv参数错误");
  49461. return { $env: e2.replace("$cloudEnv_", "") };
  49462. }
  49463. _callback(e2, t2) {
  49464. const n2 = this._dbCallBacks;
  49465. n2[e2] && n2[e2].forEach((e3) => {
  49466. e3(...t2);
  49467. });
  49468. }
  49469. _callbackAuth(e2, t2) {
  49470. const n2 = this._authCallBacks;
  49471. n2[e2] && n2[e2].forEach((e3) => {
  49472. e3(...t2);
  49473. });
  49474. }
  49475. multiSend() {
  49476. const e2 = Array.from(arguments), t2 = e2.map((e3) => {
  49477. const t3 = e3.getAction(), n2 = e3.getCommand();
  49478. if ("getTemp" !== n2.$db[n2.$db.length - 1].$method)
  49479. throw new Error("multiSend只支持子命令内使用getTemp");
  49480. return { action: t3, command: n2 };
  49481. });
  49482. return this._callCloudFunction({ multiCommand: t2, queryList: e2 });
  49483. }
  49484. }
  49485. function as(e2, t2 = {}) {
  49486. return Qn(new e2(t2), { get: (e3, t3) => es("db", t3) ? rs({ $method: t3 }, null, e3) : function() {
  49487. return rs({ $method: t3, $param: ts(Array.from(arguments)) }, null, e3);
  49488. } });
  49489. }
  49490. class cs extends os {
  49491. _parseResult(e2) {
  49492. return this._isJQL ? e2.result : e2;
  49493. }
  49494. _callCloudFunction({ action: e2, command: t2, multiCommand: n2, queryList: s2 }) {
  49495. function r2(e3, t3) {
  49496. if (n2 && s2)
  49497. for (let n3 = 0; n3 < s2.length; n3++) {
  49498. const r3 = s2[n3];
  49499. r3.udb && "function" == typeof r3.udb.setResult && (t3 ? r3.udb.setResult(t3) : r3.udb.setResult(e3.result.dataList[n3]));
  49500. }
  49501. }
  49502. const i2 = this, o2 = this._isJQL ? "databaseForJQL" : "database";
  49503. function a2(e3) {
  49504. return i2._callback("error", [e3]), j($(o2, "fail"), e3).then(() => j($(o2, "complete"), e3)).then(() => (r2(null, e3), Y(H.RESPONSE, { type: J.CLIENT_DB, content: e3 }), Promise.reject(e3)));
  49505. }
  49506. const c2 = j($(o2, "invoke")), u2 = this._uniClient;
  49507. return c2.then(() => u2.callFunction({ name: "DCloud-clientDB", type: l.CLIENT_DB, data: { action: e2, command: t2, multiCommand: n2 } })).then((e3) => {
  49508. const { code: t3, message: n3, token: s3, tokenExpired: c3, systemInfo: u3 = [] } = e3.result;
  49509. if (u3)
  49510. for (let e4 = 0; e4 < u3.length; e4++) {
  49511. const { level: t4, message: n4, detail: s4 } = u3[e4];
  49512. let r3 = "[System Info]" + n4;
  49513. s4 && (r3 = `${r3}
  49514. 详细信息:${s4}`), (console[t4] || console.log)(r3);
  49515. }
  49516. if (t3) {
  49517. return a2(new te({ code: t3, message: n3, requestId: e3.requestId }));
  49518. }
  49519. e3.result.errCode = e3.result.errCode || e3.result.code, e3.result.errMsg = e3.result.errMsg || e3.result.message, s3 && c3 && (ie({ token: s3, tokenExpired: c3 }), this._callbackAuth("refreshToken", [{ token: s3, tokenExpired: c3 }]), this._callback("refreshToken", [{ token: s3, tokenExpired: c3 }]), Y(H.REFRESH_TOKEN, { token: s3, tokenExpired: c3 }));
  49520. const h2 = [{ prop: "affectedDocs", tips: "affectedDocs不再推荐使用,请使用inserted/deleted/updated/data.length替代" }, { prop: "code", tips: "code不再推荐使用,请使用errCode替代" }, { prop: "message", tips: "message不再推荐使用,请使用errMsg替代" }];
  49521. for (let t4 = 0; t4 < h2.length; t4++) {
  49522. const { prop: n4, tips: s4 } = h2[t4];
  49523. if (n4 in e3.result) {
  49524. const t5 = e3.result[n4];
  49525. Object.defineProperty(e3.result, n4, { get: () => (console.warn(s4), t5) });
  49526. }
  49527. }
  49528. return function(e4) {
  49529. return j($(o2, "success"), e4).then(() => j($(o2, "complete"), e4)).then(() => {
  49530. r2(e4, null);
  49531. const t4 = i2._parseResult(e4);
  49532. return Y(H.RESPONSE, { type: J.CLIENT_DB, content: t4 }), Promise.resolve(t4);
  49533. });
  49534. }(e3);
  49535. }, (e3) => {
  49536. /fc_function_not_found|FUNCTION_NOT_FOUND/g.test(e3.message) && console.warn("clientDB未初始化,请在web控制台保存一次schema以开启clientDB");
  49537. return a2(new te({ code: e3.code || "SYSTEM_ERROR", message: e3.message, requestId: e3.requestId }));
  49538. });
  49539. }
  49540. }
  49541. const us = "token无效,跳转登录页面", hs = "token过期,跳转登录页面", ls = { TOKEN_INVALID_TOKEN_EXPIRED: hs, TOKEN_INVALID_INVALID_CLIENTID: us, TOKEN_INVALID: us, TOKEN_INVALID_WRONG_TOKEN: us, TOKEN_INVALID_ANONYMOUS_USER: us }, ds = { "uni-id-token-expired": hs, "uni-id-check-token-failed": us, "uni-id-token-not-exist": us, "uni-id-check-device-feature-failed": us }, ps = { ...ls, ...ds, default: "用户未登录或登录状态过期,自动跳转登录页面" };
  49542. function fs(e2, t2) {
  49543. let n2 = "";
  49544. return n2 = e2 ? `${e2}/${t2}` : t2, n2.replace(/^\//, "");
  49545. }
  49546. function gs(e2 = [], t2 = "") {
  49547. const n2 = [], s2 = [];
  49548. return e2.forEach((e3) => {
  49549. true === e3.needLogin ? n2.push(fs(t2, e3.path)) : false === e3.needLogin && s2.push(fs(t2, e3.path));
  49550. }), { needLoginPage: n2, notNeedLoginPage: s2 };
  49551. }
  49552. function ms(e2) {
  49553. return e2.split("?")[0].replace(/^\//, "");
  49554. }
  49555. function ys() {
  49556. return function(e2) {
  49557. let t2 = e2 && e2.$page && e2.$page.fullPath;
  49558. return t2 ? ("/" !== t2.charAt(0) && (t2 = "/" + t2), t2) : "";
  49559. }(function() {
  49560. const e2 = getCurrentPages();
  49561. return e2[e2.length - 1];
  49562. }());
  49563. }
  49564. function _s() {
  49565. return ms(ys());
  49566. }
  49567. function ws(e2 = "", t2 = {}) {
  49568. if (!e2)
  49569. return false;
  49570. if (!(t2 && t2.list && t2.list.length))
  49571. return false;
  49572. const n2 = t2.list, s2 = ms(e2);
  49573. return n2.some((e3) => e3.pagePath === s2);
  49574. }
  49575. const Is = !!e.uniIdRouter;
  49576. const { loginPage: vs, routerNeedLogin: Ss, resToLogin: Ts, needLoginPage: bs, notNeedLoginPage: Es, loginPageInTabBar: ks } = function({ pages: t2 = [], subPackages: n2 = [], uniIdRouter: s2 = {}, tabBar: r2 = {} } = e) {
  49577. const { loginPage: i2, needLogin: o2 = [], resToLogin: a2 = true } = s2, { needLoginPage: c2, notNeedLoginPage: u2 } = gs(t2), { needLoginPage: h2, notNeedLoginPage: l2 } = function(e2 = []) {
  49578. const t3 = [], n3 = [];
  49579. return e2.forEach((e3) => {
  49580. const { root: s3, pages: r3 = [] } = e3, { needLoginPage: i3, notNeedLoginPage: o3 } = gs(r3, s3);
  49581. t3.push(...i3), n3.push(...o3);
  49582. }), { needLoginPage: t3, notNeedLoginPage: n3 };
  49583. }(n2);
  49584. return { loginPage: i2, routerNeedLogin: o2, resToLogin: a2, needLoginPage: [...c2, ...h2], notNeedLoginPage: [...u2, ...l2], loginPageInTabBar: ws(i2, r2) };
  49585. }();
  49586. if (bs.indexOf(vs) > -1)
  49587. throw new Error(`Login page [${vs}] should not be "needLogin", please check your pages.json`);
  49588. function As(e2) {
  49589. const t2 = _s();
  49590. if ("/" === e2.charAt(0))
  49591. return e2;
  49592. const [n2, s2] = e2.split("?"), r2 = n2.replace(/^\//, "").split("/"), i2 = t2.split("/");
  49593. i2.pop();
  49594. for (let e3 = 0; e3 < r2.length; e3++) {
  49595. const t3 = r2[e3];
  49596. ".." === t3 ? i2.pop() : "." !== t3 && i2.push(t3);
  49597. }
  49598. return "" === i2[0] && i2.shift(), "/" + i2.join("/") + (s2 ? "?" + s2 : "");
  49599. }
  49600. function Ps(e2) {
  49601. const t2 = ms(As(e2));
  49602. return !(Es.indexOf(t2) > -1) && (bs.indexOf(t2) > -1 || Ss.some((t3) => function(e3, t4) {
  49603. return new RegExp(t4).test(e3);
  49604. }(e2, t3)));
  49605. }
  49606. function Cs({ redirect: e2 }) {
  49607. const t2 = ms(e2), n2 = ms(vs);
  49608. return _s() !== n2 && t2 !== n2;
  49609. }
  49610. function Os({ api: e2, redirect: t2 } = {}) {
  49611. if (!t2 || !Cs({ redirect: t2 }))
  49612. return;
  49613. const n2 = function(e3, t3) {
  49614. return "/" !== e3.charAt(0) && (e3 = "/" + e3), t3 ? e3.indexOf("?") > -1 ? e3 + `&uniIdRedirectUrl=${encodeURIComponent(t3)}` : e3 + `?uniIdRedirectUrl=${encodeURIComponent(t3)}` : e3;
  49615. }(vs, t2);
  49616. ks ? "navigateTo" !== e2 && "redirectTo" !== e2 || (e2 = "switchTab") : "switchTab" === e2 && (e2 = "navigateTo");
  49617. const s2 = { navigateTo: index.navigateTo, redirectTo: index.redirectTo, switchTab: index.switchTab, reLaunch: index.reLaunch };
  49618. setTimeout(() => {
  49619. s2[e2]({ url: n2 });
  49620. }, 0);
  49621. }
  49622. function xs({ url: e2 } = {}) {
  49623. const t2 = { abortLoginPageJump: false, autoToLoginPage: false }, n2 = function() {
  49624. const { token: e3, tokenExpired: t3 } = re();
  49625. let n3;
  49626. if (e3) {
  49627. if (t3 < Date.now()) {
  49628. const e4 = "uni-id-token-expired";
  49629. n3 = { errCode: e4, errMsg: ps[e4] };
  49630. }
  49631. } else {
  49632. const e4 = "uni-id-check-token-failed";
  49633. n3 = { errCode: e4, errMsg: ps[e4] };
  49634. }
  49635. return n3;
  49636. }();
  49637. if (Ps(e2) && n2) {
  49638. n2.uniIdRedirectUrl = e2;
  49639. if (z(H.NEED_LOGIN).length > 0)
  49640. return setTimeout(() => {
  49641. Y(H.NEED_LOGIN, n2);
  49642. }, 0), t2.abortLoginPageJump = true, t2;
  49643. t2.autoToLoginPage = true;
  49644. }
  49645. return t2;
  49646. }
  49647. function Ns() {
  49648. !function() {
  49649. const e3 = ys(), { abortLoginPageJump: t2, autoToLoginPage: n2 } = xs({ url: e3 });
  49650. t2 || n2 && Os({ api: "redirectTo", redirect: e3 });
  49651. }();
  49652. const e2 = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
  49653. for (let t2 = 0; t2 < e2.length; t2++) {
  49654. const n2 = e2[t2];
  49655. index.addInterceptor(n2, { invoke(e3) {
  49656. const { abortLoginPageJump: t3, autoToLoginPage: s2 } = xs({ url: e3.url });
  49657. return t3 ? e3 : s2 ? (Os({ api: n2, redirect: As(e3.url) }), false) : e3;
  49658. } });
  49659. }
  49660. }
  49661. function Rs() {
  49662. this.onResponse((e2) => {
  49663. const { type: t2, content: n2 } = e2;
  49664. let s2 = false;
  49665. switch (t2) {
  49666. case "cloudobject":
  49667. s2 = function(e3) {
  49668. if ("object" != typeof e3)
  49669. return false;
  49670. const { errCode: t3 } = e3 || {};
  49671. return t3 in ps;
  49672. }(n2);
  49673. break;
  49674. case "clientdb":
  49675. s2 = function(e3) {
  49676. if ("object" != typeof e3)
  49677. return false;
  49678. const { errCode: t3 } = e3 || {};
  49679. return t3 in ls;
  49680. }(n2);
  49681. }
  49682. s2 && function(e3 = {}) {
  49683. const t3 = z(H.NEED_LOGIN);
  49684. Z().then(() => {
  49685. const n3 = ys();
  49686. if (n3 && Cs({ redirect: n3 }))
  49687. return t3.length > 0 ? Y(H.NEED_LOGIN, Object.assign({ uniIdRedirectUrl: n3 }, e3)) : void (vs && Os({ api: "navigateTo", redirect: n3 }));
  49688. });
  49689. }(n2);
  49690. });
  49691. }
  49692. function Ls(e2) {
  49693. !function(e3) {
  49694. e3.onResponse = function(e4) {
  49695. V(H.RESPONSE, e4);
  49696. }, e3.offResponse = function(e4) {
  49697. G(H.RESPONSE, e4);
  49698. };
  49699. }(e2), function(e3) {
  49700. e3.onNeedLogin = function(e4) {
  49701. V(H.NEED_LOGIN, e4);
  49702. }, e3.offNeedLogin = function(e4) {
  49703. G(H.NEED_LOGIN, e4);
  49704. }, Is && (U(Qt).needLoginInit || (U(Qt).needLoginInit = true, Z().then(() => {
  49705. Ns.call(e3);
  49706. }), Ts && Rs.call(e3)));
  49707. }(e2), function(e3) {
  49708. e3.onRefreshToken = function(e4) {
  49709. V(H.REFRESH_TOKEN, e4);
  49710. }, e3.offRefreshToken = function(e4) {
  49711. G(H.REFRESH_TOKEN, e4);
  49712. };
  49713. }(e2);
  49714. }
  49715. let Us;
  49716. const Ds = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", Ms = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/;
  49717. function qs() {
  49718. const e2 = re().token || "", t2 = e2.split(".");
  49719. if (!e2 || 3 !== t2.length)
  49720. return { uid: null, role: [], permission: [], tokenExpired: 0 };
  49721. let n2;
  49722. try {
  49723. n2 = JSON.parse((s2 = t2[1], decodeURIComponent(Us(s2).split("").map(function(e3) {
  49724. return "%" + ("00" + e3.charCodeAt(0).toString(16)).slice(-2);
  49725. }).join(""))));
  49726. } catch (e3) {
  49727. throw new Error("获取当前用户信息出错,详细错误信息为:" + e3.message);
  49728. }
  49729. var s2;
  49730. return n2.tokenExpired = 1e3 * n2.exp, delete n2.exp, delete n2.iat, n2;
  49731. }
  49732. Us = "function" != typeof atob ? function(e2) {
  49733. if (e2 = String(e2).replace(/[\t\n\f\r ]+/g, ""), !Ms.test(e2))
  49734. throw new Error("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
  49735. var t2;
  49736. e2 += "==".slice(2 - (3 & e2.length));
  49737. for (var n2, s2, r2 = "", i2 = 0; i2 < e2.length; )
  49738. t2 = Ds.indexOf(e2.charAt(i2++)) << 18 | Ds.indexOf(e2.charAt(i2++)) << 12 | (n2 = Ds.indexOf(e2.charAt(i2++))) << 6 | (s2 = Ds.indexOf(e2.charAt(i2++))), r2 += 64 === n2 ? String.fromCharCode(t2 >> 16 & 255) : 64 === s2 ? String.fromCharCode(t2 >> 16 & 255, t2 >> 8 & 255) : String.fromCharCode(t2 >> 16 & 255, t2 >> 8 & 255, 255 & t2);
  49739. return r2;
  49740. } : atob;
  49741. var Fs = n(function(e2, t2) {
  49742. Object.defineProperty(t2, "__esModule", { value: true });
  49743. const n2 = "chooseAndUploadFile:ok", s2 = "chooseAndUploadFile:fail";
  49744. function r2(e3, t3) {
  49745. return e3.tempFiles.forEach((e4, n3) => {
  49746. e4.name || (e4.name = e4.path.substring(e4.path.lastIndexOf("/") + 1)), t3 && (e4.fileType = t3), e4.cloudPath = Date.now() + "_" + n3 + e4.name.substring(e4.name.lastIndexOf("."));
  49747. }), e3.tempFilePaths || (e3.tempFilePaths = e3.tempFiles.map((e4) => e4.path)), e3;
  49748. }
  49749. function i2(e3, t3, { onChooseFile: s3, onUploadProgress: r3 }) {
  49750. return t3.then((e4) => {
  49751. if (s3) {
  49752. const t4 = s3(e4);
  49753. if (void 0 !== t4)
  49754. return Promise.resolve(t4).then((t5) => void 0 === t5 ? e4 : t5);
  49755. }
  49756. return e4;
  49757. }).then((t4) => false === t4 ? { errMsg: n2, tempFilePaths: [], tempFiles: [] } : function(e4, t5, s4 = 5, r4) {
  49758. (t5 = Object.assign({}, t5)).errMsg = n2;
  49759. const i3 = t5.tempFiles, o2 = i3.length;
  49760. let a2 = 0;
  49761. return new Promise((n3) => {
  49762. for (; a2 < s4; )
  49763. c2();
  49764. function c2() {
  49765. const s5 = a2++;
  49766. if (s5 >= o2)
  49767. return void (!i3.find((e5) => !e5.url && !e5.errMsg) && n3(t5));
  49768. const u2 = i3[s5];
  49769. e4.uploadFile({ provider: u2.provider, filePath: u2.path, cloudPath: u2.cloudPath, fileType: u2.fileType, cloudPathAsRealPath: u2.cloudPathAsRealPath, onUploadProgress(e5) {
  49770. e5.index = s5, e5.tempFile = u2, e5.tempFilePath = u2.path, r4 && r4(e5);
  49771. } }).then((e5) => {
  49772. u2.url = e5.fileID, s5 < o2 && c2();
  49773. }).catch((e5) => {
  49774. u2.errMsg = e5.errMsg || e5.message, s5 < o2 && c2();
  49775. });
  49776. }
  49777. });
  49778. }(e3, t4, 5, r3));
  49779. }
  49780. t2.initChooseAndUploadFile = function(e3) {
  49781. return function(t3 = { type: "all" }) {
  49782. return "image" === t3.type ? i2(e3, function(e4) {
  49783. const { count: t4, sizeType: n3, sourceType: i3 = ["album", "camera"], extension: o2 } = e4;
  49784. return new Promise((e5, a2) => {
  49785. index.chooseImage({ count: t4, sizeType: n3, sourceType: i3, extension: o2, success(t5) {
  49786. e5(r2(t5, "image"));
  49787. }, fail(e6) {
  49788. a2({ errMsg: e6.errMsg.replace("chooseImage:fail", s2) });
  49789. } });
  49790. });
  49791. }(t3), t3) : "video" === t3.type ? i2(e3, function(e4) {
  49792. const { camera: t4, compressed: n3, maxDuration: i3, sourceType: o2 = ["album", "camera"], extension: a2 } = e4;
  49793. return new Promise((e5, c2) => {
  49794. index.chooseVideo({ camera: t4, compressed: n3, maxDuration: i3, sourceType: o2, extension: a2, success(t5) {
  49795. const { tempFilePath: n4, duration: s3, size: i4, height: o3, width: a3 } = t5;
  49796. e5(r2({ errMsg: "chooseVideo:ok", tempFilePaths: [n4], tempFiles: [{ name: t5.tempFile && t5.tempFile.name || "", path: n4, size: i4, type: t5.tempFile && t5.tempFile.type || "", width: a3, height: o3, duration: s3, fileType: "video", cloudPath: "" }] }, "video"));
  49797. }, fail(e6) {
  49798. c2({ errMsg: e6.errMsg.replace("chooseVideo:fail", s2) });
  49799. } });
  49800. });
  49801. }(t3), t3) : i2(e3, function(e4) {
  49802. const { count: t4, extension: n3 } = e4;
  49803. return new Promise((e5, i3) => {
  49804. let o2 = index.chooseFile;
  49805. if ("undefined" != typeof wx$1 && "function" == typeof wx$1.chooseMessageFile && (o2 = wx$1.chooseMessageFile), "function" != typeof o2)
  49806. return i3({ errMsg: s2 + " 请指定 type 类型,该平台仅支持选择 image 或 video。" });
  49807. o2({ type: "all", count: t4, extension: n3, success(t5) {
  49808. e5(r2(t5));
  49809. }, fail(e6) {
  49810. i3({ errMsg: e6.errMsg.replace("chooseFile:fail", s2) });
  49811. } });
  49812. });
  49813. }(t3), t3);
  49814. };
  49815. };
  49816. }), Ks = t(Fs);
  49817. const js = { auto: "auto", onready: "onready", manual: "manual" };
  49818. function $s(e2) {
  49819. return { props: { localdata: { type: Array, default: () => [] }, options: { type: [Object, Array], default: () => ({}) }, spaceInfo: { type: Object, default: () => ({}) }, collection: { type: [String, Array], default: "" }, action: { type: String, default: "" }, field: { type: String, default: "" }, orderby: { type: String, default: "" }, where: { type: [String, Object], default: "" }, pageData: { type: String, default: "add" }, pageCurrent: { type: Number, default: 1 }, pageSize: { type: Number, default: 20 }, getcount: { type: [Boolean, String], default: false }, gettree: { type: [Boolean, String], default: false }, gettreepath: { type: [Boolean, String], default: false }, startwith: { type: String, default: "" }, limitlevel: { type: Number, default: 10 }, groupby: { type: String, default: "" }, groupField: { type: String, default: "" }, distinct: { type: [Boolean, String], default: false }, foreignKey: { type: String, default: "" }, loadtime: { type: String, default: "auto" }, manual: { type: Boolean, default: false } }, data: () => ({ mixinDatacomLoading: false, mixinDatacomHasMore: false, mixinDatacomResData: [], mixinDatacomErrorMessage: "", mixinDatacomPage: {}, mixinDatacomError: null }), created() {
  49820. this.mixinDatacomPage = { current: this.pageCurrent, size: this.pageSize, count: 0 }, this.$watch(() => {
  49821. var e3 = [];
  49822. return ["pageCurrent", "pageSize", "localdata", "collection", "action", "field", "orderby", "where", "getont", "getcount", "gettree", "groupby", "groupField", "distinct"].forEach((t2) => {
  49823. e3.push(this[t2]);
  49824. }), e3;
  49825. }, (e3, t2) => {
  49826. if (this.loadtime === js.manual)
  49827. return;
  49828. let n2 = false;
  49829. const s2 = [];
  49830. for (let r2 = 2; r2 < e3.length; r2++)
  49831. e3[r2] !== t2[r2] && (s2.push(e3[r2]), n2 = true);
  49832. e3[0] !== t2[0] && (this.mixinDatacomPage.current = this.pageCurrent), this.mixinDatacomPage.size = this.pageSize, this.onMixinDatacomPropsChange(n2, s2);
  49833. });
  49834. }, methods: { onMixinDatacomPropsChange(e3, t2) {
  49835. }, mixinDatacomEasyGet({ getone: e3 = false, success: t2, fail: n2 } = {}) {
  49836. this.mixinDatacomLoading || (this.mixinDatacomLoading = true, this.mixinDatacomErrorMessage = "", this.mixinDatacomError = null, this.mixinDatacomGet().then((n3) => {
  49837. this.mixinDatacomLoading = false;
  49838. const { data: s2, count: r2 } = n3.result;
  49839. this.getcount && (this.mixinDatacomPage.count = r2), this.mixinDatacomHasMore = s2.length < this.pageSize;
  49840. const i2 = e3 ? s2.length ? s2[0] : void 0 : s2;
  49841. this.mixinDatacomResData = i2, t2 && t2(i2);
  49842. }).catch((e4) => {
  49843. this.mixinDatacomLoading = false, this.mixinDatacomErrorMessage = e4, this.mixinDatacomError = e4, n2 && n2(e4);
  49844. }));
  49845. }, mixinDatacomGet(t2 = {}) {
  49846. let n2;
  49847. t2 = t2 || {}, n2 = "undefined" != typeof __uniX && __uniX ? e2.databaseForJQL(this.spaceInfo) : e2.database(this.spaceInfo);
  49848. const s2 = t2.action || this.action;
  49849. s2 && (n2 = n2.action(s2));
  49850. const r2 = t2.collection || this.collection;
  49851. n2 = Array.isArray(r2) ? n2.collection(...r2) : n2.collection(r2);
  49852. const i2 = t2.where || this.where;
  49853. i2 && Object.keys(i2).length && (n2 = n2.where(i2));
  49854. const o2 = t2.field || this.field;
  49855. o2 && (n2 = n2.field(o2));
  49856. const a2 = t2.foreignKey || this.foreignKey;
  49857. a2 && (n2 = n2.foreignKey(a2));
  49858. const c2 = t2.groupby || this.groupby;
  49859. c2 && (n2 = n2.groupBy(c2));
  49860. const u2 = t2.groupField || this.groupField;
  49861. u2 && (n2 = n2.groupField(u2));
  49862. true === (void 0 !== t2.distinct ? t2.distinct : this.distinct) && (n2 = n2.distinct());
  49863. const h2 = t2.orderby || this.orderby;
  49864. h2 && (n2 = n2.orderBy(h2));
  49865. const l2 = void 0 !== t2.pageCurrent ? t2.pageCurrent : this.mixinDatacomPage.current, d2 = void 0 !== t2.pageSize ? t2.pageSize : this.mixinDatacomPage.size, p2 = void 0 !== t2.getcount ? t2.getcount : this.getcount, f2 = void 0 !== t2.gettree ? t2.gettree : this.gettree, g2 = void 0 !== t2.gettreepath ? t2.gettreepath : this.gettreepath, m2 = { getCount: p2 }, y2 = { limitLevel: void 0 !== t2.limitlevel ? t2.limitlevel : this.limitlevel, startWith: void 0 !== t2.startwith ? t2.startwith : this.startwith };
  49866. return f2 && (m2.getTree = y2), g2 && (m2.getTreePath = y2), n2 = n2.skip(d2 * (l2 - 1)).limit(d2).get(m2), n2;
  49867. } } };
  49868. }
  49869. function Bs(e2) {
  49870. return function(t2, n2 = {}) {
  49871. n2 = function(e3, t3 = {}) {
  49872. return e3.customUI = t3.customUI || e3.customUI, e3.parseSystemError = t3.parseSystemError || e3.parseSystemError, Object.assign(e3.loadingOptions, t3.loadingOptions), Object.assign(e3.errorOptions, t3.errorOptions), "object" == typeof t3.secretMethods && (e3.secretMethods = t3.secretMethods), e3;
  49873. }({ customUI: false, loadingOptions: { title: "加载中...", mask: true }, errorOptions: { type: "modal", retry: false } }, n2);
  49874. const { customUI: s2, loadingOptions: r2, errorOptions: i2, parseSystemError: o2 } = n2, a2 = !s2;
  49875. return new Proxy({}, { get(s3, c2) {
  49876. switch (c2) {
  49877. case "toString":
  49878. return "[object UniCloudObject]";
  49879. case "toJSON":
  49880. return {};
  49881. }
  49882. return function({ fn: e3, interceptorName: t3, getCallbackArgs: n3 } = {}) {
  49883. return async function(...s4) {
  49884. const r3 = n3 ? n3({ params: s4 }) : {};
  49885. let i3, o3;
  49886. try {
  49887. return await j($(t3, "invoke"), { ...r3 }), i3 = await e3(...s4), await j($(t3, "success"), { ...r3, result: i3 }), i3;
  49888. } catch (e4) {
  49889. throw o3 = e4, await j($(t3, "fail"), { ...r3, error: o3 }), o3;
  49890. } finally {
  49891. await j($(t3, "complete"), o3 ? { ...r3, error: o3 } : { ...r3, result: i3 });
  49892. }
  49893. };
  49894. }({ fn: async function s4(...u2) {
  49895. let h2;
  49896. a2 && index.showLoading({ title: r2.title, mask: r2.mask });
  49897. const d2 = { name: t2, type: l.OBJECT, data: { method: c2, params: u2 } };
  49898. "object" == typeof n2.secretMethods && function(e3, t3) {
  49899. const n3 = t3.data.method, s5 = e3.secretMethods || {}, r3 = s5[n3] || s5["*"];
  49900. r3 && (t3.secretType = r3);
  49901. }(n2, d2);
  49902. let p2 = false;
  49903. try {
  49904. h2 = await e2.callFunction(d2);
  49905. } catch (e3) {
  49906. p2 = true, h2 = { result: new te(e3) };
  49907. }
  49908. const { errSubject: f2, errCode: g2, errMsg: m2, newToken: y2 } = h2.result || {};
  49909. if (a2 && index.hideLoading(), y2 && y2.token && y2.tokenExpired && (ie(y2), Y(H.REFRESH_TOKEN, { ...y2 })), g2) {
  49910. let e3 = m2;
  49911. if (p2 && o2) {
  49912. e3 = (await o2({ objectName: t2, methodName: c2, params: u2, errSubject: f2, errCode: g2, errMsg: m2 })).errMsg || m2;
  49913. }
  49914. if (a2)
  49915. if ("toast" === i2.type)
  49916. index.showToast({ title: e3, icon: "none" });
  49917. else {
  49918. if ("modal" !== i2.type)
  49919. throw new Error(`Invalid errorOptions.type: ${i2.type}`);
  49920. {
  49921. const { confirm: t3 } = await async function({ title: e4, content: t4, showCancel: n4, cancelText: s5, confirmText: r3 } = {}) {
  49922. return new Promise((i3, o3) => {
  49923. index.showModal({ title: e4, content: t4, showCancel: n4, cancelText: s5, confirmText: r3, success(e5) {
  49924. i3(e5);
  49925. }, fail() {
  49926. i3({ confirm: false, cancel: true });
  49927. } });
  49928. });
  49929. }({ title: "提示", content: e3, showCancel: i2.retry, cancelText: "取消", confirmText: i2.retry ? "重试" : "确定" });
  49930. if (i2.retry && t3)
  49931. return s4(...u2);
  49932. }
  49933. }
  49934. const n3 = new te({ subject: f2, code: g2, message: m2, requestId: h2.requestId });
  49935. throw n3.detail = h2.result, Y(H.RESPONSE, { type: J.CLOUD_OBJECT, content: n3 }), n3;
  49936. }
  49937. return Y(H.RESPONSE, { type: J.CLOUD_OBJECT, content: h2.result }), h2.result;
  49938. }, interceptorName: "callObject", getCallbackArgs: function({ params: e3 } = {}) {
  49939. return { objectName: t2, methodName: c2, params: e3 };
  49940. } });
  49941. } });
  49942. };
  49943. }
  49944. function Ws(e2) {
  49945. return U(Xt.replace("{spaceId}", e2.config.spaceId));
  49946. }
  49947. async function Hs({ openid: e2, callLoginByWeixin: t2 = false } = {}) {
  49948. const n2 = Ws(this);
  49949. if (e2 && t2)
  49950. throw new Error("[SecureNetwork] openid and callLoginByWeixin cannot be passed at the same time");
  49951. if (e2)
  49952. return n2.mpWeixinOpenid = e2, {};
  49953. const s2 = await new Promise((e3, t3) => {
  49954. index.login({ success(t4) {
  49955. e3(t4.code);
  49956. }, fail(e4) {
  49957. t3(new Error(e4.errMsg));
  49958. } });
  49959. }), r2 = this.importObject("uni-id-co", { customUI: true });
  49960. return await r2.secureNetworkHandshakeByWeixin({ code: s2, callLoginByWeixin: t2 }), n2.mpWeixinCode = s2, { code: s2 };
  49961. }
  49962. async function Js(e2) {
  49963. const t2 = Ws(this);
  49964. return t2.initPromise || (t2.initPromise = Hs.call(this, e2).then((e3) => e3).catch((e3) => {
  49965. throw delete t2.initPromise, e3;
  49966. })), t2.initPromise;
  49967. }
  49968. function zs(e2) {
  49969. return function({ openid: t2, callLoginByWeixin: n2 = false } = {}) {
  49970. return Js.call(e2, { openid: t2, callLoginByWeixin: n2 });
  49971. };
  49972. }
  49973. function Vs(e2) {
  49974. !function(e3) {
  49975. he = e3;
  49976. }(e2);
  49977. }
  49978. function Gs(e2) {
  49979. const t2 = wx$1.canIUse("getAppBaseInfo"), n2 = { getAppBaseInfo: t2 ? index.getAppBaseInfo : index.getSystemInfo, getPushClientId: index.getPushClientId };
  49980. return function(s2) {
  49981. return new Promise((r2, i2) => {
  49982. t2 && "getAppBaseInfo" === e2 ? r2(n2[e2]()) : n2[e2]({ ...s2, success(e3) {
  49983. r2(e3);
  49984. }, fail(e3) {
  49985. i2(e3);
  49986. } });
  49987. });
  49988. };
  49989. }
  49990. class Ys extends S {
  49991. constructor() {
  49992. super(), this._uniPushMessageCallback = this._receivePushMessage.bind(this), this._currentMessageId = -1, this._payloadQueue = [];
  49993. }
  49994. init() {
  49995. return Promise.all([Gs("getAppBaseInfo")(), Gs("getPushClientId")()]).then(([{ appId: e2 } = {}, { cid: t2 } = {}] = []) => {
  49996. if (!e2)
  49997. throw new Error("Invalid appId, please check the manifest.json file");
  49998. if (!t2)
  49999. throw new Error("Invalid push client id");
  50000. this._appId = e2, this._pushClientId = t2, this._seqId = Date.now() + "-" + Math.floor(9e5 * Math.random() + 1e5), this.emit("open"), this._initMessageListener();
  50001. }, (e2) => {
  50002. throw this.emit("error", e2), this.close(), e2;
  50003. });
  50004. }
  50005. async open() {
  50006. return this.init();
  50007. }
  50008. _isUniCloudSSE(e2) {
  50009. if ("receive" !== e2.type)
  50010. return false;
  50011. const t2 = e2 && e2.data && e2.data.payload;
  50012. return !(!t2 || "UNI_CLOUD_SSE" !== t2.channel || t2.seqId !== this._seqId);
  50013. }
  50014. _receivePushMessage(e2) {
  50015. if (!this._isUniCloudSSE(e2))
  50016. return;
  50017. const t2 = e2 && e2.data && e2.data.payload, { action: n2, messageId: s2, message: r2 } = t2;
  50018. this._payloadQueue.push({ action: n2, messageId: s2, message: r2 }), this._consumMessage();
  50019. }
  50020. _consumMessage() {
  50021. for (; ; ) {
  50022. const e2 = this._payloadQueue.find((e3) => e3.messageId === this._currentMessageId + 1);
  50023. if (!e2)
  50024. break;
  50025. this._currentMessageId++, this._parseMessagePayload(e2);
  50026. }
  50027. }
  50028. _parseMessagePayload(e2) {
  50029. const { action: t2, messageId: n2, message: s2 } = e2;
  50030. "end" === t2 ? this._end({ messageId: n2, message: s2 }) : "message" === t2 && this._appendMessage({ messageId: n2, message: s2 });
  50031. }
  50032. _appendMessage({ messageId: e2, message: t2 } = {}) {
  50033. this.emit("message", t2);
  50034. }
  50035. _end({ messageId: e2, message: t2 } = {}) {
  50036. this.emit("end", t2), this.close();
  50037. }
  50038. _initMessageListener() {
  50039. index.onPushMessage(this._uniPushMessageCallback);
  50040. }
  50041. _destroy() {
  50042. index.offPushMessage(this._uniPushMessageCallback);
  50043. }
  50044. toJSON() {
  50045. return { appId: this._appId, pushClientId: this._pushClientId, seqId: this._seqId };
  50046. }
  50047. close() {
  50048. this._destroy(), this.emit("close");
  50049. }
  50050. }
  50051. async function Qs(e2) {
  50052. const t2 = e2.__dev__;
  50053. if (!t2.debugInfo)
  50054. return;
  50055. const { address: n2, servePort: s2 } = t2.debugInfo, { address: r2 } = await Ot(n2, s2);
  50056. if (r2)
  50057. return t2.localAddress = r2, void (t2.localPort = s2);
  50058. const i2 = console["warn"];
  50059. let o2 = "";
  50060. if ("remote" === t2.debugInfo.initialLaunchType ? (t2.debugInfo.forceRemote = true, o2 = "当前客户端和HBuilderX不在同一局域网下(或其他网络原因无法连接HBuilderX),uniCloud本地调试服务不对当前客户端生效。\n- 如果不使用uniCloud本地调试服务,请直接忽略此信息。\n- 如需使用uniCloud本地调试服务,请将客户端与主机连接到同一局域网下并重新运行到客户端。") : o2 = "无法连接uniCloud本地调试服务,请检查当前客户端是否与主机在同一局域网下。\n- 如需使用uniCloud本地调试服务,请将客户端与主机连接到同一局域网下并重新运行到客户端。", o2 += "\n- 如果在HBuilderX开启的状态下切换过网络环境,请重启HBuilderX后再试\n- 检查系统防火墙是否拦截了HBuilderX自带的nodejs\n- 检查是否错误的使用拦截器修改uni.request方法的参数", 0 === P.indexOf("mp-") && (o2 += "\n- 小程序中如何使用uniCloud,请参考:https://uniapp.dcloud.net.cn/uniCloud/publish.html#useinmp"), !t2.debugInfo.forceRemote)
  50061. throw new Error(o2);
  50062. i2(o2);
  50063. }
  50064. function Xs(e2) {
  50065. e2._initPromiseHub || (e2._initPromiseHub = new v({ createPromise: function() {
  50066. let t2 = Promise.resolve();
  50067. var n2;
  50068. n2 = 1, t2 = new Promise((e3) => {
  50069. setTimeout(() => {
  50070. e3();
  50071. }, n2);
  50072. });
  50073. const s2 = e2.auth();
  50074. return t2.then(() => s2.getLoginState()).then((e3) => e3 ? Promise.resolve() : s2.signInAnonymously());
  50075. } }));
  50076. }
  50077. const Zs = { tcb: Pt, tencent: Pt, aliyun: fe, private: Rt, dcloud: Rt, alipay: Bt };
  50078. let er = new class {
  50079. init(e2) {
  50080. let t2 = {};
  50081. const n2 = Zs[e2.provider];
  50082. if (!n2)
  50083. throw new Error("未提供正确的provider参数");
  50084. t2 = n2.init(e2), function(e3) {
  50085. const t3 = {};
  50086. e3.__dev__ = t3, t3.debugLog = "mp-harmony" === P;
  50087. const n3 = C;
  50088. n3 && !n3.code && (t3.debugInfo = n3);
  50089. const s2 = new v({ createPromise: function() {
  50090. return Qs(e3);
  50091. } });
  50092. t3.initLocalNetwork = function() {
  50093. return s2.exec();
  50094. };
  50095. }(t2), Xs(t2), Gn(t2), function(e3) {
  50096. const t3 = e3.uploadFile;
  50097. e3.uploadFile = function(e4) {
  50098. return t3.call(this, e4);
  50099. };
  50100. }(t2), function(e3) {
  50101. e3.database = function(t3) {
  50102. if (t3 && Object.keys(t3).length > 0)
  50103. return e3.init(t3).database();
  50104. if (this._database)
  50105. return this._database;
  50106. const n3 = as(cs, { uniClient: e3 });
  50107. return this._database = n3, n3;
  50108. }, e3.databaseForJQL = function(t3) {
  50109. if (t3 && Object.keys(t3).length > 0)
  50110. return e3.init(t3).databaseForJQL();
  50111. if (this._databaseForJQL)
  50112. return this._databaseForJQL;
  50113. const n3 = as(cs, { uniClient: e3, isJQL: true });
  50114. return this._databaseForJQL = n3, n3;
  50115. };
  50116. }(t2), function(e3) {
  50117. e3.getCurrentUserInfo = qs, e3.chooseAndUploadFile = Ks.initChooseAndUploadFile(e3), Object.assign(e3, { get mixinDatacom() {
  50118. return $s(e3);
  50119. } }), e3.SSEChannel = Ys, e3.initSecureNetworkByWeixin = zs(e3), e3.setCustomClientInfo = Vs, e3.importObject = Bs(e3);
  50120. }(t2);
  50121. return ["callFunction", "uploadFile", "deleteFile", "getTempFileURL", "downloadFile", "chooseAndUploadFile"].forEach((e3) => {
  50122. if (!t2[e3])
  50123. return;
  50124. const n3 = t2[e3];
  50125. t2[e3] = function() {
  50126. return n3.apply(t2, Array.from(arguments));
  50127. }, t2[e3] = (/* @__PURE__ */ function(e4, t3) {
  50128. return function(n4) {
  50129. let s2 = false;
  50130. if ("callFunction" === t3) {
  50131. const e5 = n4 && n4.type || l.DEFAULT;
  50132. s2 = e5 !== l.DEFAULT;
  50133. }
  50134. const r2 = "callFunction" === t3 && !s2, i2 = this._initPromiseHub.exec();
  50135. n4 = n4 || {};
  50136. const { success: o2, fail: a2, complete: c2 } = ee(n4), u2 = i2.then(() => s2 ? Promise.resolve() : j($(t3, "invoke"), n4)).then(() => e4.call(this, n4)).then((e5) => s2 ? Promise.resolve(e5) : j($(t3, "success"), e5).then(() => j($(t3, "complete"), e5)).then(() => (r2 && Y(H.RESPONSE, { type: J.CLOUD_FUNCTION, content: e5 }), Promise.resolve(e5))), (e5) => s2 ? Promise.reject(e5) : j($(t3, "fail"), e5).then(() => j($(t3, "complete"), e5)).then(() => (Y(H.RESPONSE, { type: J.CLOUD_FUNCTION, content: e5 }), Promise.reject(e5))));
  50137. if (!(o2 || a2 || c2))
  50138. return u2;
  50139. u2.then((e5) => {
  50140. o2 && o2(e5), c2 && c2(e5), r2 && Y(H.RESPONSE, { type: J.CLOUD_FUNCTION, content: e5 });
  50141. }, (e5) => {
  50142. a2 && a2(e5), c2 && c2(e5), r2 && Y(H.RESPONSE, { type: J.CLOUD_FUNCTION, content: e5 });
  50143. });
  50144. };
  50145. }(t2[e3], e3)).bind(t2);
  50146. }), t2.init = this.init, t2;
  50147. }
  50148. }();
  50149. (() => {
  50150. const e2 = O;
  50151. let t2 = {};
  50152. if (e2 && 1 === e2.length)
  50153. t2 = e2[0], er = er.init(t2), er._isDefault = true;
  50154. else {
  50155. const t3 = ["auth", "callFunction", "uploadFile", "deleteFile", "getTempFileURL", "downloadFile"], n2 = ["database", "getCurrentUserInfo", "importObject"];
  50156. let s2;
  50157. s2 = e2 && e2.length > 0 ? "应用有多个服务空间,请通过uniCloud.init方法指定要使用的服务空间" : "应用未关联服务空间,请在uniCloud目录右键关联服务空间", [...t3, ...n2].forEach((e3) => {
  50158. er[e3] = function() {
  50159. if (console.error(s2), -1 === n2.indexOf(e3))
  50160. return Promise.reject(new te({ code: "SYS_ERR", message: s2 }));
  50161. console.error(s2);
  50162. };
  50163. });
  50164. }
  50165. if (Object.assign(er, { get mixinDatacom() {
  50166. return $s(er);
  50167. } }), Ls(er), er.addInterceptor = F, er.removeInterceptor = K, er.interceptObject = B, "web" === P)
  50168. ;
  50169. })();
  50170. var tr = er;
  50171. var dayjs_min = { exports: {} };
  50172. (function(module2, exports2) {
  50173. !function(t2, e2) {
  50174. module2.exports = e2();
  50175. }(commonjsGlobal, function() {
  50176. var t2 = 1e3, e2 = 6e4, n2 = 36e5, r2 = "millisecond", i2 = "second", s2 = "minute", u2 = "hour", a2 = "day", o2 = "week", c2 = "month", f2 = "quarter", h2 = "year", d2 = "date", l2 = "Invalid Date", $2 = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y2 = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M2 = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), ordinal: function(t3) {
  50177. var e3 = ["th", "st", "nd", "rd"], n3 = t3 % 100;
  50178. return "[" + t3 + (e3[(n3 - 20) % 10] || e3[n3] || e3[0]) + "]";
  50179. } }, m2 = function(t3, e3, n3) {
  50180. var r3 = String(t3);
  50181. return !r3 || r3.length >= e3 ? t3 : "" + Array(e3 + 1 - r3.length).join(n3) + t3;
  50182. }, v2 = { s: m2, z: function(t3) {
  50183. var e3 = -t3.utcOffset(), n3 = Math.abs(e3), r3 = Math.floor(n3 / 60), i3 = n3 % 60;
  50184. return (e3 <= 0 ? "+" : "-") + m2(r3, 2, "0") + ":" + m2(i3, 2, "0");
  50185. }, m: function t3(e3, n3) {
  50186. if (e3.date() < n3.date())
  50187. return -t3(n3, e3);
  50188. var r3 = 12 * (n3.year() - e3.year()) + (n3.month() - e3.month()), i3 = e3.clone().add(r3, c2), s3 = n3 - i3 < 0, u3 = e3.clone().add(r3 + (s3 ? -1 : 1), c2);
  50189. return +(-(r3 + (n3 - i3) / (s3 ? i3 - u3 : u3 - i3)) || 0);
  50190. }, a: function(t3) {
  50191. return t3 < 0 ? Math.ceil(t3) || 0 : Math.floor(t3);
  50192. }, p: function(t3) {
  50193. return { M: c2, y: h2, w: o2, d: a2, D: d2, h: u2, m: s2, s: i2, ms: r2, Q: f2 }[t3] || String(t3 || "").toLowerCase().replace(/s$/, "");
  50194. }, u: function(t3) {
  50195. return void 0 === t3;
  50196. } }, g2 = "en", D = {};
  50197. D[g2] = M2;
  50198. var p2 = "$isDayjsObject", S2 = function(t3) {
  50199. return t3 instanceof _2 || !(!t3 || !t3[p2]);
  50200. }, w2 = function t3(e3, n3, r3) {
  50201. var i3;
  50202. if (!e3)
  50203. return g2;
  50204. if ("string" == typeof e3) {
  50205. var s3 = e3.toLowerCase();
  50206. D[s3] && (i3 = s3), n3 && (D[s3] = n3, i3 = s3);
  50207. var u3 = e3.split("-");
  50208. if (!i3 && u3.length > 1)
  50209. return t3(u3[0]);
  50210. } else {
  50211. var a3 = e3.name;
  50212. D[a3] = e3, i3 = a3;
  50213. }
  50214. return !r3 && i3 && (g2 = i3), i3 || !r3 && g2;
  50215. }, O2 = function(t3, e3) {
  50216. if (S2(t3))
  50217. return t3.clone();
  50218. var n3 = "object" == typeof e3 ? e3 : {};
  50219. return n3.date = t3, n3.args = arguments, new _2(n3);
  50220. }, b2 = v2;
  50221. b2.l = w2, b2.i = S2, b2.w = function(t3, e3) {
  50222. return O2(t3, { locale: e3.$L, utc: e3.$u, x: e3.$x, $offset: e3.$offset });
  50223. };
  50224. var _2 = function() {
  50225. function M3(t3) {
  50226. this.$L = w2(t3.locale, null, true), this.parse(t3), this.$x = this.$x || t3.x || {}, this[p2] = true;
  50227. }
  50228. var m3 = M3.prototype;
  50229. return m3.parse = function(t3) {
  50230. this.$d = function(t4) {
  50231. var e3 = t4.date, n3 = t4.utc;
  50232. if (null === e3)
  50233. return /* @__PURE__ */ new Date(NaN);
  50234. if (b2.u(e3))
  50235. return /* @__PURE__ */ new Date();
  50236. if (e3 instanceof Date)
  50237. return new Date(e3);
  50238. if ("string" == typeof e3 && !/Z$/i.test(e3)) {
  50239. var r3 = e3.match($2);
  50240. if (r3) {
  50241. var i3 = r3[2] - 1 || 0, s3 = (r3[7] || "0").substring(0, 3);
  50242. return n3 ? new Date(Date.UTC(r3[1], i3, r3[3] || 1, r3[4] || 0, r3[5] || 0, r3[6] || 0, s3)) : new Date(r3[1], i3, r3[3] || 1, r3[4] || 0, r3[5] || 0, r3[6] || 0, s3);
  50243. }
  50244. }
  50245. return new Date(e3);
  50246. }(t3), this.init();
  50247. }, m3.init = function() {
  50248. var t3 = this.$d;
  50249. this.$y = t3.getFullYear(), this.$M = t3.getMonth(), this.$D = t3.getDate(), this.$W = t3.getDay(), this.$H = t3.getHours(), this.$m = t3.getMinutes(), this.$s = t3.getSeconds(), this.$ms = t3.getMilliseconds();
  50250. }, m3.$utils = function() {
  50251. return b2;
  50252. }, m3.isValid = function() {
  50253. return !(this.$d.toString() === l2);
  50254. }, m3.isSame = function(t3, e3) {
  50255. var n3 = O2(t3);
  50256. return this.startOf(e3) <= n3 && n3 <= this.endOf(e3);
  50257. }, m3.isAfter = function(t3, e3) {
  50258. return O2(t3) < this.startOf(e3);
  50259. }, m3.isBefore = function(t3, e3) {
  50260. return this.endOf(e3) < O2(t3);
  50261. }, m3.$g = function(t3, e3, n3) {
  50262. return b2.u(t3) ? this[e3] : this.set(n3, t3);
  50263. }, m3.unix = function() {
  50264. return Math.floor(this.valueOf() / 1e3);
  50265. }, m3.valueOf = function() {
  50266. return this.$d.getTime();
  50267. }, m3.startOf = function(t3, e3) {
  50268. var n3 = this, r3 = !!b2.u(e3) || e3, f3 = b2.p(t3), l3 = function(t4, e4) {
  50269. var i3 = b2.w(n3.$u ? Date.UTC(n3.$y, e4, t4) : new Date(n3.$y, e4, t4), n3);
  50270. return r3 ? i3 : i3.endOf(a2);
  50271. }, $3 = function(t4, e4) {
  50272. return b2.w(n3.toDate()[t4].apply(n3.toDate("s"), (r3 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e4)), n3);
  50273. }, y3 = this.$W, M4 = this.$M, m4 = this.$D, v3 = "set" + (this.$u ? "UTC" : "");
  50274. switch (f3) {
  50275. case h2:
  50276. return r3 ? l3(1, 0) : l3(31, 11);
  50277. case c2:
  50278. return r3 ? l3(1, M4) : l3(0, M4 + 1);
  50279. case o2:
  50280. var g3 = this.$locale().weekStart || 0, D2 = (y3 < g3 ? y3 + 7 : y3) - g3;
  50281. return l3(r3 ? m4 - D2 : m4 + (6 - D2), M4);
  50282. case a2:
  50283. case d2:
  50284. return $3(v3 + "Hours", 0);
  50285. case u2:
  50286. return $3(v3 + "Minutes", 1);
  50287. case s2:
  50288. return $3(v3 + "Seconds", 2);
  50289. case i2:
  50290. return $3(v3 + "Milliseconds", 3);
  50291. default:
  50292. return this.clone();
  50293. }
  50294. }, m3.endOf = function(t3) {
  50295. return this.startOf(t3, false);
  50296. }, m3.$set = function(t3, e3) {
  50297. var n3, o3 = b2.p(t3), f3 = "set" + (this.$u ? "UTC" : ""), l3 = (n3 = {}, n3[a2] = f3 + "Date", n3[d2] = f3 + "Date", n3[c2] = f3 + "Month", n3[h2] = f3 + "FullYear", n3[u2] = f3 + "Hours", n3[s2] = f3 + "Minutes", n3[i2] = f3 + "Seconds", n3[r2] = f3 + "Milliseconds", n3)[o3], $3 = o3 === a2 ? this.$D + (e3 - this.$W) : e3;
  50298. if (o3 === c2 || o3 === h2) {
  50299. var y3 = this.clone().set(d2, 1);
  50300. y3.$d[l3]($3), y3.init(), this.$d = y3.set(d2, Math.min(this.$D, y3.daysInMonth())).$d;
  50301. } else
  50302. l3 && this.$d[l3]($3);
  50303. return this.init(), this;
  50304. }, m3.set = function(t3, e3) {
  50305. return this.clone().$set(t3, e3);
  50306. }, m3.get = function(t3) {
  50307. return this[b2.p(t3)]();
  50308. }, m3.add = function(r3, f3) {
  50309. var d3, l3 = this;
  50310. r3 = Number(r3);
  50311. var $3 = b2.p(f3), y3 = function(t3) {
  50312. var e3 = O2(l3);
  50313. return b2.w(e3.date(e3.date() + Math.round(t3 * r3)), l3);
  50314. };
  50315. if ($3 === c2)
  50316. return this.set(c2, this.$M + r3);
  50317. if ($3 === h2)
  50318. return this.set(h2, this.$y + r3);
  50319. if ($3 === a2)
  50320. return y3(1);
  50321. if ($3 === o2)
  50322. return y3(7);
  50323. var M4 = (d3 = {}, d3[s2] = e2, d3[u2] = n2, d3[i2] = t2, d3)[$3] || 1, m4 = this.$d.getTime() + r3 * M4;
  50324. return b2.w(m4, this);
  50325. }, m3.subtract = function(t3, e3) {
  50326. return this.add(-1 * t3, e3);
  50327. }, m3.format = function(t3) {
  50328. var e3 = this, n3 = this.$locale();
  50329. if (!this.isValid())
  50330. return n3.invalidDate || l2;
  50331. var r3 = t3 || "YYYY-MM-DDTHH:mm:ssZ", i3 = b2.z(this), s3 = this.$H, u3 = this.$m, a3 = this.$M, o3 = n3.weekdays, c3 = n3.months, f3 = n3.meridiem, h3 = function(t4, n4, i4, s4) {
  50332. return t4 && (t4[n4] || t4(e3, r3)) || i4[n4].slice(0, s4);
  50333. }, d3 = function(t4) {
  50334. return b2.s(s3 % 12 || 12, t4, "0");
  50335. }, $3 = f3 || function(t4, e4, n4) {
  50336. var r4 = t4 < 12 ? "AM" : "PM";
  50337. return n4 ? r4.toLowerCase() : r4;
  50338. };
  50339. return r3.replace(y2, function(t4, r4) {
  50340. return r4 || function(t5) {
  50341. switch (t5) {
  50342. case "YY":
  50343. return String(e3.$y).slice(-2);
  50344. case "YYYY":
  50345. return b2.s(e3.$y, 4, "0");
  50346. case "M":
  50347. return a3 + 1;
  50348. case "MM":
  50349. return b2.s(a3 + 1, 2, "0");
  50350. case "MMM":
  50351. return h3(n3.monthsShort, a3, c3, 3);
  50352. case "MMMM":
  50353. return h3(c3, a3);
  50354. case "D":
  50355. return e3.$D;
  50356. case "DD":
  50357. return b2.s(e3.$D, 2, "0");
  50358. case "d":
  50359. return String(e3.$W);
  50360. case "dd":
  50361. return h3(n3.weekdaysMin, e3.$W, o3, 2);
  50362. case "ddd":
  50363. return h3(n3.weekdaysShort, e3.$W, o3, 3);
  50364. case "dddd":
  50365. return o3[e3.$W];
  50366. case "H":
  50367. return String(s3);
  50368. case "HH":
  50369. return b2.s(s3, 2, "0");
  50370. case "h":
  50371. return d3(1);
  50372. case "hh":
  50373. return d3(2);
  50374. case "a":
  50375. return $3(s3, u3, true);
  50376. case "A":
  50377. return $3(s3, u3, false);
  50378. case "m":
  50379. return String(u3);
  50380. case "mm":
  50381. return b2.s(u3, 2, "0");
  50382. case "s":
  50383. return String(e3.$s);
  50384. case "ss":
  50385. return b2.s(e3.$s, 2, "0");
  50386. case "SSS":
  50387. return b2.s(e3.$ms, 3, "0");
  50388. case "Z":
  50389. return i3;
  50390. }
  50391. return null;
  50392. }(t4) || i3.replace(":", "");
  50393. });
  50394. }, m3.utcOffset = function() {
  50395. return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
  50396. }, m3.diff = function(r3, d3, l3) {
  50397. var $3, y3 = this, M4 = b2.p(d3), m4 = O2(r3), v3 = (m4.utcOffset() - this.utcOffset()) * e2, g3 = this - m4, D2 = function() {
  50398. return b2.m(y3, m4);
  50399. };
  50400. switch (M4) {
  50401. case h2:
  50402. $3 = D2() / 12;
  50403. break;
  50404. case c2:
  50405. $3 = D2();
  50406. break;
  50407. case f2:
  50408. $3 = D2() / 3;
  50409. break;
  50410. case o2:
  50411. $3 = (g3 - v3) / 6048e5;
  50412. break;
  50413. case a2:
  50414. $3 = (g3 - v3) / 864e5;
  50415. break;
  50416. case u2:
  50417. $3 = g3 / n2;
  50418. break;
  50419. case s2:
  50420. $3 = g3 / e2;
  50421. break;
  50422. case i2:
  50423. $3 = g3 / t2;
  50424. break;
  50425. default:
  50426. $3 = g3;
  50427. }
  50428. return l3 ? $3 : b2.a($3);
  50429. }, m3.daysInMonth = function() {
  50430. return this.endOf(c2).$D;
  50431. }, m3.$locale = function() {
  50432. return D[this.$L];
  50433. }, m3.locale = function(t3, e3) {
  50434. if (!t3)
  50435. return this.$L;
  50436. var n3 = this.clone(), r3 = w2(t3, e3, true);
  50437. return r3 && (n3.$L = r3), n3;
  50438. }, m3.clone = function() {
  50439. return b2.w(this.$d, this);
  50440. }, m3.toDate = function() {
  50441. return new Date(this.valueOf());
  50442. }, m3.toJSON = function() {
  50443. return this.isValid() ? this.toISOString() : null;
  50444. }, m3.toISOString = function() {
  50445. return this.$d.toISOString();
  50446. }, m3.toString = function() {
  50447. return this.$d.toUTCString();
  50448. }, M3;
  50449. }(), k = _2.prototype;
  50450. return O2.prototype = k, [["$ms", r2], ["$s", i2], ["$m", s2], ["$H", u2], ["$W", a2], ["$M", c2], ["$y", h2], ["$D", d2]].forEach(function(t3) {
  50451. k[t3[1]] = function(e3) {
  50452. return this.$g(e3, t3[0], t3[1]);
  50453. };
  50454. }), O2.extend = function(t3, e3) {
  50455. return t3.$i || (t3(e3, _2, O2), t3.$i = true), O2;
  50456. }, O2.locale = w2, O2.isDayjs = S2, O2.unix = function(t3) {
  50457. return O2(1e3 * t3);
  50458. }, O2.en = D[g2], O2.Ls = D, O2.p = {}, O2;
  50459. });
  50460. })(dayjs_min);
  50461. var dayjs_minExports = dayjs_min.exports;
  50462. const dayjs = /* @__PURE__ */ getDefaultExportFromCjs(dayjs_minExports);
  50463. exports.CryptoJS = CryptoJS;
  50464. exports.Hls = Hls;
  50465. exports._export_sfc = _export_sfc;
  50466. exports.createSSRApp = createSSRApp;
  50467. exports.createStore = createStore;
  50468. exports.dayjs = dayjs;
  50469. exports.e = e$1;
  50470. exports.f = f$1;
  50471. exports.index = index;
  50472. exports.n = n$1;
  50473. exports.nextTick$1 = nextTick$1;
  50474. exports.o = o$1;
  50475. exports.p = p$1;
  50476. exports.resolveComponent = resolveComponent;
  50477. exports.s = s$1;
  50478. exports.sr = sr;
  50479. exports.t = t$1;
  50480. exports.tr = tr;
  50481. exports.useStore = useStore;