app-service.js 2.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691
  1. if (typeof Promise !== "undefined" && !Promise.prototype.finally) {
  2. Promise.prototype.finally = function(callback) {
  3. const promise = this.constructor;
  4. return this.then(
  5. (value) => promise.resolve(callback()).then(() => value),
  6. (reason) => promise.resolve(callback()).then(() => {
  7. throw reason;
  8. })
  9. );
  10. };
  11. }
  12. ;
  13. if (typeof uni !== "undefined" && uni && uni.requireGlobal) {
  14. const global2 = uni.requireGlobal();
  15. ArrayBuffer = global2.ArrayBuffer;
  16. Int8Array = global2.Int8Array;
  17. Uint8Array = global2.Uint8Array;
  18. Uint8ClampedArray = global2.Uint8ClampedArray;
  19. Int16Array = global2.Int16Array;
  20. Uint16Array = global2.Uint16Array;
  21. Int32Array = global2.Int32Array;
  22. Uint32Array = global2.Uint32Array;
  23. Float32Array = global2.Float32Array;
  24. Float64Array = global2.Float64Array;
  25. BigInt64Array = global2.BigInt64Array;
  26. BigUint64Array = global2.BigUint64Array;
  27. }
  28. ;
  29. if (uni.restoreGlobal) {
  30. uni.restoreGlobal(Vue, weex, plus, setTimeout, clearTimeout, setInterval, clearInterval);
  31. }
  32. (function(vue) {
  33. "use strict";
  34. function requireNativePlugin(name) {
  35. return weex.requireModule(name);
  36. }
  37. function formatAppLog(type, filename, ...args) {
  38. if (uni.__log__) {
  39. uni.__log__(type, filename, ...args);
  40. } else {
  41. console[type].apply(console, [...args, filename]);
  42. }
  43. }
  44. function resolveEasycom(component, easycom) {
  45. return typeof component === "string" ? easycom : component;
  46. }
  47. const icons = {
  48. "uicon-level": "",
  49. "uicon-column-line": "",
  50. "uicon-checkbox-mark": "",
  51. "uicon-folder": "",
  52. "uicon-movie": "",
  53. "uicon-star-fill": "",
  54. "uicon-star": "",
  55. "uicon-phone-fill": "",
  56. "uicon-phone": "",
  57. "uicon-apple-fill": "",
  58. "uicon-chrome-circle-fill": "",
  59. "uicon-backspace": "",
  60. "uicon-attach": "",
  61. "uicon-cut": "",
  62. "uicon-empty-car": "",
  63. "uicon-empty-coupon": "",
  64. "uicon-empty-address": "",
  65. "uicon-empty-favor": "",
  66. "uicon-empty-permission": "",
  67. "uicon-empty-news": "",
  68. "uicon-empty-search": "",
  69. "uicon-github-circle-fill": "",
  70. "uicon-rmb": "",
  71. "uicon-person-delete-fill": "",
  72. "uicon-reload": "",
  73. "uicon-order": "",
  74. "uicon-server-man": "",
  75. "uicon-search": "",
  76. "uicon-fingerprint": "",
  77. "uicon-more-dot-fill": "",
  78. "uicon-scan": "",
  79. "uicon-share-square": "",
  80. "uicon-map": "",
  81. "uicon-map-fill": "",
  82. "uicon-tags": "",
  83. "uicon-tags-fill": "",
  84. "uicon-bookmark-fill": "",
  85. "uicon-bookmark": "",
  86. "uicon-eye": "",
  87. "uicon-eye-fill": "",
  88. "uicon-mic": "",
  89. "uicon-mic-off": "",
  90. "uicon-calendar": "",
  91. "uicon-calendar-fill": "",
  92. "uicon-trash": "",
  93. "uicon-trash-fill": "",
  94. "uicon-play-left": "",
  95. "uicon-play-right": "",
  96. "uicon-minus": "",
  97. "uicon-plus": "",
  98. "uicon-info": "",
  99. "uicon-info-circle": "",
  100. "uicon-info-circle-fill": "",
  101. "uicon-question": "",
  102. "uicon-error": "",
  103. "uicon-close": "",
  104. "uicon-checkmark": "",
  105. "uicon-android-circle-fill": "",
  106. "uicon-android-fill": "",
  107. "uicon-ie": "",
  108. "uicon-IE-circle-fill": "",
  109. "uicon-google": "",
  110. "uicon-google-circle-fill": "",
  111. "uicon-setting-fill": "",
  112. "uicon-setting": "",
  113. "uicon-minus-square-fill": "",
  114. "uicon-plus-square-fill": "",
  115. "uicon-heart": "",
  116. "uicon-heart-fill": "",
  117. "uicon-camera": "",
  118. "uicon-camera-fill": "",
  119. "uicon-more-circle": "",
  120. "uicon-more-circle-fill": "",
  121. "uicon-chat": "",
  122. "uicon-chat-fill": "",
  123. "uicon-bag-fill": "",
  124. "uicon-bag": "",
  125. "uicon-error-circle-fill": "",
  126. "uicon-error-circle": "",
  127. "uicon-close-circle": "",
  128. "uicon-close-circle-fill": "",
  129. "uicon-checkmark-circle": "",
  130. "uicon-checkmark-circle-fill": "",
  131. "uicon-question-circle-fill": "",
  132. "uicon-question-circle": "",
  133. "uicon-share": "",
  134. "uicon-share-fill": "",
  135. "uicon-shopping-cart": "",
  136. "uicon-shopping-cart-fill": "",
  137. "uicon-bell": "",
  138. "uicon-bell-fill": "",
  139. "uicon-list": "",
  140. "uicon-list-dot": "",
  141. "uicon-zhihu": "",
  142. "uicon-zhihu-circle-fill": "",
  143. "uicon-zhifubao": "",
  144. "uicon-zhifubao-circle-fill": "",
  145. "uicon-weixin-circle-fill": "",
  146. "uicon-weixin-fill": "",
  147. "uicon-twitter-circle-fill": "",
  148. "uicon-twitter": "",
  149. "uicon-taobao-circle-fill": "",
  150. "uicon-taobao": "",
  151. "uicon-weibo-circle-fill": "",
  152. "uicon-weibo": "",
  153. "uicon-qq-fill": "",
  154. "uicon-qq-circle-fill": "",
  155. "uicon-moments-circel-fill": "",
  156. "uicon-moments": "",
  157. "uicon-qzone": "",
  158. "uicon-qzone-circle-fill": "",
  159. "uicon-baidu-circle-fill": "",
  160. "uicon-baidu": "",
  161. "uicon-facebook-circle-fill": "",
  162. "uicon-facebook": "",
  163. "uicon-car": "",
  164. "uicon-car-fill": "",
  165. "uicon-warning-fill": "",
  166. "uicon-warning": "",
  167. "uicon-clock-fill": "",
  168. "uicon-clock": "",
  169. "uicon-edit-pen": "",
  170. "uicon-edit-pen-fill": "",
  171. "uicon-email": "",
  172. "uicon-email-fill": "",
  173. "uicon-minus-circle": "",
  174. "uicon-minus-circle-fill": "",
  175. "uicon-plus-circle": "",
  176. "uicon-plus-circle-fill": "",
  177. "uicon-file-text": "",
  178. "uicon-file-text-fill": "",
  179. "uicon-pushpin": "",
  180. "uicon-pushpin-fill": "",
  181. "uicon-grid": "",
  182. "uicon-grid-fill": "",
  183. "uicon-play-circle": "",
  184. "uicon-play-circle-fill": "",
  185. "uicon-pause-circle-fill": "",
  186. "uicon-pause": "",
  187. "uicon-pause-circle": "",
  188. "uicon-eye-off": "",
  189. "uicon-eye-off-outline": "",
  190. "uicon-gift-fill": "",
  191. "uicon-gift": "",
  192. "uicon-rmb-circle-fill": "",
  193. "uicon-rmb-circle": "",
  194. "uicon-kefu-ermai": "",
  195. "uicon-server-fill": "",
  196. "uicon-coupon-fill": "",
  197. "uicon-coupon": "",
  198. "uicon-integral": "",
  199. "uicon-integral-fill": "",
  200. "uicon-home-fill": "",
  201. "uicon-home": "",
  202. "uicon-hourglass-half-fill": "",
  203. "uicon-hourglass": "",
  204. "uicon-account": "",
  205. "uicon-plus-people-fill": "",
  206. "uicon-minus-people-fill": "",
  207. "uicon-account-fill": "",
  208. "uicon-thumb-down-fill": "",
  209. "uicon-thumb-down": "",
  210. "uicon-thumb-up": "",
  211. "uicon-thumb-up-fill": "",
  212. "uicon-lock-fill": "",
  213. "uicon-lock-open": "",
  214. "uicon-lock-opened-fill": "",
  215. "uicon-lock": "",
  216. "uicon-red-packet-fill": "",
  217. "uicon-photo-fill": "",
  218. "uicon-photo": "",
  219. "uicon-volume-off-fill": "",
  220. "uicon-volume-off": "",
  221. "uicon-volume-fill": "",
  222. "uicon-volume": "",
  223. "uicon-red-packet": "",
  224. "uicon-download": "",
  225. "uicon-arrow-up-fill": "",
  226. "uicon-arrow-down-fill": "",
  227. "uicon-play-left-fill": "",
  228. "uicon-play-right-fill": "",
  229. "uicon-rewind-left-fill": "",
  230. "uicon-rewind-right-fill": "",
  231. "uicon-arrow-downward": "",
  232. "uicon-arrow-leftward": "",
  233. "uicon-arrow-rightward": "",
  234. "uicon-arrow-upward": "",
  235. "uicon-arrow-down": "",
  236. "uicon-arrow-right": "",
  237. "uicon-arrow-left": "",
  238. "uicon-arrow-up": "",
  239. "uicon-skip-back-left": "",
  240. "uicon-skip-forward-right": "",
  241. "uicon-rewind-right": "",
  242. "uicon-rewind-left": "",
  243. "uicon-arrow-right-double": "",
  244. "uicon-arrow-left-double": "",
  245. "uicon-wifi-off": "",
  246. "uicon-wifi": "",
  247. "uicon-empty-data": "",
  248. "uicon-empty-history": "",
  249. "uicon-empty-list": "",
  250. "uicon-empty-page": "",
  251. "uicon-empty-order": "",
  252. "uicon-man": "",
  253. "uicon-woman": "",
  254. "uicon-man-add": "",
  255. "uicon-man-add-fill": "",
  256. "uicon-man-delete": "",
  257. "uicon-man-delete-fill": "",
  258. "uicon-zh": "",
  259. "uicon-en": ""
  260. };
  261. const version$1 = "3";
  262. {
  263. formatAppLog("log", "at uni_modules/uview-plus/libs/config/config.js:5", `
  264. %c uview-plus V${version$1} %c https://ijry.github.io/uview-plus/
  265. `, "color: #ffffff; background: #3c9cff; padding:5px 0;", "color: #3c9cff;background: #ffffff; padding:5px 0;");
  266. }
  267. const config$1 = {
  268. v: version$1,
  269. version: version$1,
  270. // 主题名称
  271. type: [
  272. "primary",
  273. "success",
  274. "info",
  275. "error",
  276. "warning"
  277. ],
  278. // 颜色部分,本来可以通过scss的:export导出供js使用,但是奈何nvue不支持
  279. color: {
  280. "u-primary": "#2979ff",
  281. "u-warning": "#ff9900",
  282. "u-success": "#19be6b",
  283. "u-error": "#fa3534",
  284. "u-info": "#909399",
  285. "u-main-color": "#303133",
  286. "u-content-color": "#606266",
  287. "u-tips-color": "#909399",
  288. "u-light-color": "#c0c4cc"
  289. },
  290. // 默认单位,可以通过配置为rpx,那么在用于传入组件大小参数为数值时,就默认为rpx
  291. unit: "px"
  292. };
  293. const ActionSheet = {
  294. // action-sheet组件
  295. actionSheet: {
  296. show: false,
  297. title: "",
  298. description: "",
  299. actions: [],
  300. index: "",
  301. cancelText: "",
  302. closeOnClickAction: true,
  303. safeAreaInsetBottom: true,
  304. openType: "",
  305. closeOnClickOverlay: true,
  306. round: 0
  307. }
  308. };
  309. const Album = {
  310. // album 组件
  311. album: {
  312. urls: [],
  313. keyName: "",
  314. singleSize: 180,
  315. multipleSize: 70,
  316. space: 6,
  317. singleMode: "scaleToFill",
  318. multipleMode: "aspectFill",
  319. maxCount: 9,
  320. previewFullImage: true,
  321. rowCount: 3,
  322. showMore: true
  323. }
  324. };
  325. const Alert = {
  326. // alert警告组件
  327. alert: {
  328. title: "",
  329. type: "warning",
  330. description: "",
  331. closable: false,
  332. showIcon: false,
  333. effect: "light",
  334. center: false,
  335. fontSize: 14
  336. }
  337. };
  338. const Avatar = {
  339. // avatar 组件
  340. avatar: {
  341. src: "",
  342. shape: "circle",
  343. size: 40,
  344. mode: "scaleToFill",
  345. text: "",
  346. bgColor: "#c0c4cc",
  347. color: "#ffffff",
  348. fontSize: 18,
  349. icon: "",
  350. mpAvatar: false,
  351. randomBgColor: false,
  352. defaultUrl: "",
  353. colorIndex: "",
  354. name: ""
  355. }
  356. };
  357. const AvatarGroup = {
  358. // avatarGroup 组件
  359. avatarGroup: {
  360. urls: [],
  361. maxCount: 5,
  362. shape: "circle",
  363. mode: "scaleToFill",
  364. showMore: true,
  365. size: 40,
  366. keyName: "",
  367. gap: 0.5,
  368. extraValue: 0
  369. }
  370. };
  371. const Backtop = {
  372. // backtop组件
  373. backtop: {
  374. mode: "circle",
  375. icon: "arrow-upward",
  376. text: "",
  377. duration: 100,
  378. scrollTop: 0,
  379. top: 400,
  380. bottom: 100,
  381. right: 20,
  382. zIndex: 9,
  383. iconStyle: {
  384. color: "#909399",
  385. fontSize: "19px"
  386. }
  387. }
  388. };
  389. const Badge = {
  390. // 徽标数组件
  391. badge: {
  392. isDot: false,
  393. value: "",
  394. show: true,
  395. max: 999,
  396. type: "error",
  397. showZero: false,
  398. bgColor: null,
  399. color: null,
  400. shape: "circle",
  401. numberType: "overflow",
  402. offset: [],
  403. inverted: false,
  404. absolute: false
  405. }
  406. };
  407. const Button = {
  408. // button组件
  409. button: {
  410. hairline: false,
  411. type: "info",
  412. size: "normal",
  413. shape: "square",
  414. plain: false,
  415. disabled: false,
  416. loading: false,
  417. loadingText: "",
  418. loadingMode: "spinner",
  419. loadingSize: 15,
  420. openType: "",
  421. formType: "",
  422. appParameter: "",
  423. hoverStopPropagation: true,
  424. lang: "en",
  425. sessionFrom: "",
  426. sendMessageTitle: "",
  427. sendMessagePath: "",
  428. sendMessageImg: "",
  429. showMessageCard: false,
  430. dataName: "",
  431. throttleTime: 0,
  432. hoverStartTime: 0,
  433. hoverStayTime: 200,
  434. text: "",
  435. icon: "",
  436. iconColor: "",
  437. color: ""
  438. }
  439. };
  440. const Calendar = {
  441. // calendar 组件
  442. calendar: {
  443. title: "日期选择",
  444. showTitle: true,
  445. showSubtitle: true,
  446. mode: "single",
  447. startText: "开始",
  448. endText: "结束",
  449. customList: [],
  450. color: "#3c9cff",
  451. minDate: 0,
  452. maxDate: 0,
  453. defaultDate: null,
  454. maxCount: Number.MAX_SAFE_INTEGER,
  455. // Infinity
  456. rowHeight: 56,
  457. formatter: null,
  458. showLunar: false,
  459. showMark: true,
  460. confirmText: "确定",
  461. confirmDisabledText: "确定",
  462. show: false,
  463. closeOnClickOverlay: false,
  464. readonly: false,
  465. showConfirm: true,
  466. maxRange: Number.MAX_SAFE_INTEGER,
  467. // Infinity
  468. rangePrompt: "",
  469. showRangePrompt: true,
  470. allowSameDay: false,
  471. round: 0,
  472. monthNum: 3
  473. }
  474. };
  475. const CarKeyboard = {
  476. // 车牌号键盘
  477. carKeyboard: {
  478. random: false
  479. }
  480. };
  481. const Cell = {
  482. // cell组件的props
  483. cell: {
  484. customClass: "",
  485. title: "",
  486. label: "",
  487. value: "",
  488. icon: "",
  489. disabled: false,
  490. border: true,
  491. center: false,
  492. url: "",
  493. linkType: "navigateTo",
  494. clickable: false,
  495. isLink: false,
  496. required: false,
  497. arrowDirection: "",
  498. iconStyle: {},
  499. rightIconStyle: {},
  500. rightIcon: "arrow-right",
  501. titleStyle: {},
  502. size: "",
  503. stop: true,
  504. name: ""
  505. }
  506. };
  507. const CellGroup = {
  508. // cell-group组件的props
  509. cellGroup: {
  510. title: "",
  511. border: true,
  512. customStyle: {}
  513. }
  514. };
  515. const Checkbox = {
  516. // checkbox组件
  517. checkbox: {
  518. name: "",
  519. shape: "",
  520. size: "",
  521. checkbox: false,
  522. disabled: "",
  523. activeColor: "",
  524. inactiveColor: "",
  525. iconSize: "",
  526. iconColor: "",
  527. label: "",
  528. labelSize: "",
  529. labelColor: "",
  530. labelDisabled: ""
  531. }
  532. };
  533. const CheckboxGroup = {
  534. // checkbox-group组件
  535. checkboxGroup: {
  536. name: "",
  537. value: [],
  538. shape: "square",
  539. disabled: false,
  540. activeColor: "#2979ff",
  541. inactiveColor: "#c8c9cc",
  542. size: 18,
  543. placement: "row",
  544. labelSize: 14,
  545. labelColor: "#303133",
  546. labelDisabled: false,
  547. iconColor: "#ffffff",
  548. iconSize: 12,
  549. iconPlacement: "left",
  550. borderBottom: false
  551. }
  552. };
  553. const CircleProgress = {
  554. // circleProgress 组件
  555. circleProgress: {
  556. percentage: 30
  557. }
  558. };
  559. const Code = {
  560. // code 组件
  561. code: {
  562. seconds: 60,
  563. startText: "获取验证码",
  564. changeText: "X秒重新获取",
  565. endText: "重新获取",
  566. keepRunning: false,
  567. uniqueKey: ""
  568. }
  569. };
  570. const CodeInput = {
  571. // codeInput 组件
  572. codeInput: {
  573. adjustPosition: true,
  574. maxlength: 6,
  575. dot: false,
  576. mode: "box",
  577. hairline: false,
  578. space: 10,
  579. value: "",
  580. focus: false,
  581. bold: false,
  582. color: "#606266",
  583. fontSize: 18,
  584. size: 35,
  585. disabledKeyboard: false,
  586. borderColor: "#c9cacc",
  587. disabledDot: true
  588. }
  589. };
  590. const Col = {
  591. // col 组件
  592. col: {
  593. span: 12,
  594. offset: 0,
  595. justify: "start",
  596. align: "stretch",
  597. textAlign: "left"
  598. }
  599. };
  600. const Collapse = {
  601. // collapse 组件
  602. collapse: {
  603. value: null,
  604. accordion: false,
  605. border: true
  606. }
  607. };
  608. const CollapseItem = {
  609. // collapseItem 组件
  610. collapseItem: {
  611. title: "",
  612. value: "",
  613. label: "",
  614. disabled: false,
  615. isLink: true,
  616. clickable: true,
  617. border: true,
  618. align: "left",
  619. name: "",
  620. icon: "",
  621. duration: 300
  622. }
  623. };
  624. const ColumnNotice = {
  625. // columnNotice 组件
  626. columnNotice: {
  627. text: "",
  628. icon: "volume",
  629. mode: "",
  630. color: "#f9ae3d",
  631. bgColor: "#fdf6ec",
  632. fontSize: 14,
  633. speed: 80,
  634. step: false,
  635. duration: 1500,
  636. disableTouch: true
  637. }
  638. };
  639. const CountDown = {
  640. // u-count-down 计时器组件
  641. countDown: {
  642. time: 0,
  643. format: "HH:mm:ss",
  644. autoStart: true,
  645. millisecond: false
  646. }
  647. };
  648. const CountTo = {
  649. // countTo 组件
  650. countTo: {
  651. startVal: 0,
  652. endVal: 0,
  653. duration: 2e3,
  654. autoplay: true,
  655. decimals: 0,
  656. useEasing: true,
  657. decimal: ".",
  658. color: "#606266",
  659. fontSize: 22,
  660. bold: false,
  661. separator: ""
  662. }
  663. };
  664. const DatetimePicker = {
  665. // datetimePicker 组件
  666. datetimePicker: {
  667. show: false,
  668. popupMode: "bottom",
  669. showToolbar: true,
  670. value: "",
  671. title: "",
  672. mode: "datetime",
  673. maxDate: new Date((/* @__PURE__ */ new Date()).getFullYear() + 10, 0, 1).getTime(),
  674. minDate: new Date((/* @__PURE__ */ new Date()).getFullYear() - 10, 0, 1).getTime(),
  675. minHour: 0,
  676. maxHour: 23,
  677. minMinute: 0,
  678. maxMinute: 59,
  679. filter: null,
  680. formatter: null,
  681. loading: false,
  682. itemHeight: 44,
  683. cancelText: "取消",
  684. confirmText: "确认",
  685. cancelColor: "#909193",
  686. confirmColor: "#3c9cff",
  687. visibleItemCount: 5,
  688. closeOnClickOverlay: false,
  689. defaultIndex: []
  690. }
  691. };
  692. const Divider = {
  693. // divider组件
  694. divider: {
  695. dashed: false,
  696. hairline: true,
  697. dot: false,
  698. textPosition: "center",
  699. text: "",
  700. textSize: 14,
  701. textColor: "#909399",
  702. lineColor: "#dcdfe6"
  703. }
  704. };
  705. const Empty = {
  706. // empty组件
  707. empty: {
  708. icon: "",
  709. text: "",
  710. textColor: "#c0c4cc",
  711. textSize: 14,
  712. iconColor: "#c0c4cc",
  713. iconSize: 90,
  714. mode: "data",
  715. width: 160,
  716. height: 160,
  717. show: true,
  718. marginTop: 0
  719. }
  720. };
  721. const Form = {
  722. // form 组件
  723. form: {
  724. model: {},
  725. rules: {},
  726. errorType: "message",
  727. borderBottom: true,
  728. labelPosition: "left",
  729. labelWidth: 45,
  730. labelAlign: "left",
  731. labelStyle: {}
  732. }
  733. };
  734. const GormItem = {
  735. // formItem 组件
  736. formItem: {
  737. label: "",
  738. prop: "",
  739. rule: "",
  740. borderBottom: "",
  741. labelPosition: "",
  742. labelWidth: "",
  743. rightIcon: "",
  744. leftIcon: "",
  745. required: false,
  746. leftIconStyle: ""
  747. }
  748. };
  749. const Gap = {
  750. // gap组件
  751. gap: {
  752. bgColor: "transparent",
  753. height: 20,
  754. marginTop: 0,
  755. marginBottom: 0,
  756. customStyle: {}
  757. }
  758. };
  759. const Grid = {
  760. // grid组件
  761. grid: {
  762. col: 3,
  763. border: false,
  764. align: "left"
  765. }
  766. };
  767. const GridItem = {
  768. // grid-item组件
  769. gridItem: {
  770. name: null,
  771. bgColor: "transparent"
  772. }
  773. };
  774. const {
  775. color: color$3
  776. } = config$1;
  777. const Icon = {
  778. // icon组件
  779. icon: {
  780. name: "",
  781. color: color$3["u-content-color"],
  782. size: "16px",
  783. bold: false,
  784. index: "",
  785. hoverClass: "",
  786. customPrefix: "uicon",
  787. label: "",
  788. labelPos: "right",
  789. labelSize: "15px",
  790. labelColor: color$3["u-content-color"],
  791. space: "3px",
  792. imgMode: "",
  793. width: "",
  794. height: "",
  795. top: 0,
  796. stop: false
  797. }
  798. };
  799. const Image = {
  800. // image组件
  801. image: {
  802. src: "",
  803. mode: "aspectFill",
  804. width: "300",
  805. height: "225",
  806. shape: "square",
  807. radius: 0,
  808. lazyLoad: true,
  809. showMenuByLongpress: true,
  810. loadingIcon: "photo",
  811. errorIcon: "error-circle",
  812. showLoading: true,
  813. showError: true,
  814. fade: true,
  815. webp: false,
  816. duration: 500,
  817. bgColor: "#f3f4f6"
  818. }
  819. };
  820. const IndexAnchor = {
  821. // indexAnchor 组件
  822. indexAnchor: {
  823. text: "",
  824. color: "#606266",
  825. size: 14,
  826. bgColor: "#dedede",
  827. height: 32
  828. }
  829. };
  830. const IndexList = {
  831. // indexList 组件
  832. indexList: {
  833. inactiveColor: "#606266",
  834. activeColor: "#5677fc",
  835. indexList: [],
  836. sticky: true,
  837. customNavHeight: 0
  838. }
  839. };
  840. const Input = {
  841. // index 组件
  842. input: {
  843. value: "",
  844. type: "text",
  845. fixed: false,
  846. disabled: false,
  847. disabledColor: "#f5f7fa",
  848. clearable: false,
  849. password: false,
  850. maxlength: -1,
  851. placeholder: null,
  852. placeholderClass: "input-placeholder",
  853. placeholderStyle: "color: #c0c4cc",
  854. showWordLimit: false,
  855. confirmType: "done",
  856. confirmHold: false,
  857. holdKeyboard: false,
  858. focus: false,
  859. autoBlur: false,
  860. disableDefaultPadding: false,
  861. cursor: -1,
  862. cursorSpacing: 30,
  863. selectionStart: -1,
  864. selectionEnd: -1,
  865. adjustPosition: true,
  866. inputAlign: "left",
  867. fontSize: "15px",
  868. color: "#303133",
  869. prefixIcon: "",
  870. prefixIconStyle: "",
  871. suffixIcon: "",
  872. suffixIconStyle: "",
  873. border: "surround",
  874. readonly: false,
  875. shape: "square",
  876. formatter: null
  877. }
  878. };
  879. const Keyboard = {
  880. // 键盘组件
  881. keyboard: {
  882. mode: "number",
  883. dotDisabled: false,
  884. tooltip: true,
  885. showTips: true,
  886. tips: "",
  887. showCancel: true,
  888. showConfirm: true,
  889. random: false,
  890. safeAreaInsetBottom: true,
  891. closeOnClickOverlay: true,
  892. show: false,
  893. overlay: true,
  894. zIndex: 10075,
  895. cancelText: "取消",
  896. confirmText: "确定",
  897. autoChange: false
  898. }
  899. };
  900. const Line = {
  901. // line组件
  902. line: {
  903. color: "#d6d7d9",
  904. length: "100%",
  905. direction: "row",
  906. hairline: true,
  907. margin: 0,
  908. dashed: false
  909. }
  910. };
  911. const LineProgress = {
  912. // lineProgress 组件
  913. lineProgress: {
  914. activeColor: "#19be6b",
  915. inactiveColor: "#ececec",
  916. percentage: 0,
  917. showText: true,
  918. height: 12
  919. }
  920. };
  921. const {
  922. color: color$2
  923. } = config$1;
  924. const Link = {
  925. // link超链接组件props参数
  926. link: {
  927. color: color$2["u-primary"],
  928. fontSize: 15,
  929. underLine: false,
  930. href: "",
  931. mpTips: "链接已复制,请在浏览器打开",
  932. lineColor: "",
  933. text: ""
  934. }
  935. };
  936. const List = {
  937. // list 组件
  938. list: {
  939. showScrollbar: false,
  940. lowerThreshold: 50,
  941. upperThreshold: 0,
  942. scrollTop: 0,
  943. offsetAccuracy: 10,
  944. enableFlex: false,
  945. pagingEnabled: false,
  946. scrollable: true,
  947. scrollIntoView: "",
  948. scrollWithAnimation: false,
  949. enableBackToTop: false,
  950. height: 0,
  951. width: 0,
  952. preLoadScreen: 1
  953. }
  954. };
  955. const ListItem = {
  956. // listItem 组件
  957. listItem: {
  958. anchor: ""
  959. }
  960. };
  961. const {
  962. color: color$1
  963. } = config$1;
  964. const LoadingIcon = {
  965. // loading-icon加载中图标组件
  966. loadingIcon: {
  967. show: true,
  968. color: color$1["u-tips-color"],
  969. textColor: color$1["u-tips-color"],
  970. vertical: false,
  971. mode: "spinner",
  972. size: 24,
  973. textSize: 15,
  974. text: "",
  975. timingFunction: "ease-in-out",
  976. duration: 1200,
  977. inactiveColor: ""
  978. }
  979. };
  980. const LoadingPage = {
  981. // loading-page组件
  982. loadingPage: {
  983. loadingText: "正在加载",
  984. image: "",
  985. loadingMode: "circle",
  986. loading: false,
  987. bgColor: "#ffffff",
  988. color: "#C8C8C8",
  989. fontSize: 19,
  990. iconSize: 28,
  991. loadingColor: "#C8C8C8"
  992. }
  993. };
  994. const Loadmore = {
  995. // loadmore 组件
  996. loadmore: {
  997. status: "loadmore",
  998. bgColor: "transparent",
  999. icon: true,
  1000. fontSize: 14,
  1001. iconSize: 17,
  1002. color: "#606266",
  1003. loadingIcon: "spinner",
  1004. loadmoreText: "加载更多",
  1005. loadingText: "正在加载...",
  1006. nomoreText: "没有更多了",
  1007. isDot: false,
  1008. iconColor: "#b7b7b7",
  1009. marginTop: 10,
  1010. marginBottom: 10,
  1011. height: "auto",
  1012. line: false,
  1013. lineColor: "#E6E8EB",
  1014. dashed: false
  1015. }
  1016. };
  1017. const Modal = {
  1018. // modal 组件
  1019. modal: {
  1020. show: false,
  1021. title: "",
  1022. content: "",
  1023. confirmText: "确认",
  1024. cancelText: "取消",
  1025. showConfirmButton: true,
  1026. showCancelButton: false,
  1027. confirmColor: "#2979ff",
  1028. cancelColor: "#606266",
  1029. buttonReverse: false,
  1030. zoom: true,
  1031. asyncClose: false,
  1032. closeOnClickOverlay: false,
  1033. negativeTop: 0,
  1034. width: "650rpx",
  1035. confirmButtonShape: ""
  1036. }
  1037. };
  1038. const color = {
  1039. primary: "#3c9cff",
  1040. info: "#909399",
  1041. default: "#909399",
  1042. warning: "#f9ae3d",
  1043. error: "#f56c6c",
  1044. success: "#5ac725",
  1045. mainColor: "#303133",
  1046. contentColor: "#606266",
  1047. tipsColor: "#909399",
  1048. lightColor: "#c0c4cc",
  1049. borderColor: "#e4e7ed"
  1050. };
  1051. const Navbar = {
  1052. // navbar 组件
  1053. navbar: {
  1054. safeAreaInsetTop: true,
  1055. placeholder: false,
  1056. fixed: true,
  1057. border: false,
  1058. leftIcon: "arrow-left",
  1059. leftText: "",
  1060. rightText: "",
  1061. rightIcon: "",
  1062. title: "",
  1063. bgColor: "#ffffff",
  1064. titleWidth: "400rpx",
  1065. height: "44px",
  1066. leftIconSize: 20,
  1067. leftIconColor: color.mainColor,
  1068. autoBack: false,
  1069. titleStyle: ""
  1070. }
  1071. };
  1072. const NoNetwork = {
  1073. // noNetwork
  1074. noNetwork: {
  1075. tips: "哎呀,网络信号丢失",
  1076. zIndex: "",
  1077. image: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAABLKADAAQAAAABAAABLAAAAADYYILnAABAAElEQVR4Ae29CZhkV3kefNeq6m2W7tn3nl0aCbHIAgmQPGB+sLCNzSID9g9PYrAf57d/+4+DiW0cy8QBJ06c2In/PLFDHJ78+MGCGNsYgyxwIwktwEijAc1ohtmnZ+2Z7p5eq6vu9r/vuXWrq25VdVV1V3dXVX9Hmj73nv285963vvOd75yraeIEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQaD8E9PbrkvRopSMwMBBYRs+5O/yJS68cPnzYXel4tFP/jXbqjPRFEAiCQNe6Bw/6gdFn9Oy9Q90LLG2DgBBW2wyldIQIPPPCte2a5q3jtR+4ff/4wuBuXotrDwSEsNpjHKUXQODppy+udYJMEUEZgbd94DvnNwlA7YGAEFZ7jOOK78Xp06eTTkq7sxwQhmXuf/754VXl4iSstRAQwmqt8ZLWlkHg0UcD49qYfUjXfLtMtOZ7npExJu4iqZWLl7DWQUAIq3XGSlpaAYHD77q8xwuCOSUoXw8Sl0eMux977DGzQjES3AIICGG1wCBJEysj8PXnz230XXdr5RQFMYbRvWnv6w8UhMhliyGwYghr4Pjg3oEXL34ey9zyC9tiD2ml5h47dr1LN7S6CMjz/A3PvHh1Z6UyJby5EVgRhKUe7Kz/JU0LfvrJo5f+Y3MPibSuFgQGBgasYSd9l6GDsup0WS/T/9RTp9fXmU2SNwECdQ92E7S57iaMeJnPQLK6ixkDLfjlb7546RfrLkQyNBcC3dsP6oHWMd9G+V3JgwPHh7rnm1/yLQ8CbU9Y33zp0j+nZFUMb/DHmB7+SHGY3LUKAk8cObtD00xlHDrfNge+Z2ozU3c9dvx4Yr5lSL6lR6CtCWvg6OAPw9z538ZhhZRl6XrwhW8du1KX/iNejtwvPQIDR8+vSRqJ/obU7GupjdNdh2gW0ZDypJBFR6BtB2rg2OVtuub9JcmpHIpBoK1xfffLzx4f7C0XL2HNiYDp6bs9z23Ypn1fC1Y/9PCFDc3ZW2lVHIG2JKzTp4Ok7nv/G6Q054MIvda+bNb74pEgKGtwGAdL7pcfAa8vOKEZ2kyjWuLr7uDh+/qvN6o8KWdxEWhLwroyeek/g4zuqwU6kNrhyZcu/UktaSXN8iNwuL9/RuvVXtJ9PbPQ1vhmcP6t9+47u9ByJP/SIdB2hDVw9MJHQFYfrQdCph84evFX68kjaZcPAZJWwjMXRFpJ2zr91tfuvrh8vZCa54NA2xGWrunvmg8QWCJ/N4ir7fCYDxatkOeBB7an501agXbygVdvv9IK/ZQ2FiPQdi9osGbH+zRNf7y4m9Xu9Me7N9nv0HXdr5ZS4psHgXpJC9P/wDRTx0Vn1TxjWG9LGrbaUm/Fi5meSvcrkxf/Cg/ow9XqAUk91v3qHT97r6471dJKfHMi8Oyzgx1Z03t1YAQVT2MwgsC3u+yXHzi0faQ5eyGtqgWBtpOw2Ol9+/TM+sTOn8L08MtzgQCy+tOHXr3jA0JWc6HU/HF5Scssr4jXcYqfP6V/T8iq+ceyWgvbUsKKOn38eJAYyl56TAuCEr2WYei//9Crd/5GlFb81kdASVopSFrerKRlaoZj9HR+700H10+0fg+lB21NWBxe2lhNHsUpDZr27mi4dV379R9+za4/iO7Fbx8ECknLCPTsTDJ17O33bJpqnx6u7J60PWFxeAcCbMV56dJfQKf1bkMLfuGh1+76zMoe9vbuPUnLsb2DtmOe5HSxvXsrvWtLBEhaTx29+Ma27Jx0ShAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQaEsEVoQdVluO3BJ06ptHL34b1XRjp4Ch6Rq24+kmjG4Nwwg+9uA9u/73EjRBqhAEihAoe3xwUQq5WTYEzp0b3ZnV/Ncf6O/9AvY9wlh/6dy3X7ncN512Zw9BVLXjuAP4np44vnQtkZoEgVkEhLBmsWiKqwsXpjbPBOn3gRfenwnc+7GBe+zsjclvonFDS9nA9Iy/u3x9+vAP3735VPk4CRUEFhcBIazFxbfm0k9fHD7k+v4nQFaPQIrx8Gmyx/GJ0J/t7ez7mw0b9MmaC2pQQgh0/ZSm4g5TwueWWtqLt0HuVy4CQljLPPYnB0depTn+b3t+8B4t0AdBUv93h2H9xc6da0aXs2m+r1WQsLRnl7NdUvfKRkAIa5nG//r1oGtsZvjTgev/kqYHF/TA+AXoqv4npJemOEiQU1Eo2l+G0movBK1UBBPU7s9E1+ILAkuNgKwSLjXiqO/khVtvARH8dxDBRkMzPrF/V+9/BlG5y9CUqlXinHv9mRPXtvuus88L9H3JPv2zD2yXExCqAicJBIFWRwAvv3Xqwq0/Pnn+lv/K+ZvfPH3p9p5W75O0fxaBp793ce3AwIDMWmYhafiVgNtwSMsXeHp4eNXJC8Nf0PAdRCiuf/XgrnWUqsqotcvnl9DmRkCdweX4b9N7+m/ih+mbMraLM14yJVwcXItKpT1VRve+ArC3Qqn+3gM7132jKEGZm6tXg86J7OhDfuA/iHwPUpfUZSfu2L59tXxEoQxeyxkEgjKeOnLxHb4RqC+NY5H3+2953d4XlrNN7Vq3ENYij+yZwbG9jpt9GkBPQ5H9zgP9607OVeWp87cOQtn9zwJf+xDMNFfj+jryPqXpxj8c2Nn7P+SXey70lidu4IXzb0DNB4tr9751+HV7zxSHyd1CERDCWiiCc+QPjUCnsaqmZ62O5IN7N/VUNP48ee7mAZDTf4Tt049iUG4Guv4ZfNLos9UIbo7qJWoJEHjy+bP7fNsoOcnW0A0/aacef8PdG28sQTNWTBVCWIs01OfPj66BpfqTmq732UnjgT1bei+Vq4pTv7HM8Ceg2/o1qLQug7T+FaaM3IqTLZdewpoHgYEjV9fphvOj+OShWa5V+CxvZtpzv/LwG/aNl4uXsPoRwI+4uEYjAJ2GmdG8L0FK2mYa+tsrkdXZy+P7x2ZuHdW14P+BLdank9q6Qwd3rf+ckFWjR6Tx5Q2cP58K9Jm3VCIr1ogt48lO237r3//96YofeG18y9q7RFklXITxPXV+5DchKb3ZDMy37Nu5tuxG4R9cHH6b42QfAzlds+3EPXu2rfrBIjRFilwkBIIR7SHoJDurFU89ZOd680Gke6JaWomvjoBIWNUxqivFD87fej0e0n8Fwvr0/t1rnyqX+QfnRz7g+8FX8Rv8vL3auF/IqhxKzR2WCPxXqKeq3krDTdj2ierpJEUtCIgOqxaUakwzNBR0D09yiqePHOjveyOkpxLr9VMXb73V97S/h3nDXx7Y2fdPkAYbncW1IgIDxy5vM7LZt/hgrnLtxyaBrJNxv/72N+6tuNhSLp+EVUZACKsyNnXHvHL+1qcgNf2KbSXu2bt9dcmS9qlzo/fARgcmCtpzB3b1/Vg5QiuslLowENyDWDn8cSjl98PgdBviu03N+rl9/WufLEwr18uDwLdevLTF1YK3xnVZ2HI1bUxrT7z5zTuXdRP78qCyeLUKYTUI25OXbm4JPO00TBj+6I7+db8ZL3ZwMOiYdG4dA1lN9HWte2iuI2NAVPapC8O/CGPR34Ip/AZIbIMo7yX8G9QMbcS09P+2b1vf5XgdrXaPfiYns9oeLLEd8D1/B7Dp0E1jGP042pXQj7RKf546cmGzp+tv1TRf6YQD35/QO3seP3xow5IfC9QqmM23naJ0ny9ysXwgq98BWc0kVhv/Nhalbqe8kd/Fr8MOSEr3zEVWrwyO3I29hl+E9LUHGf+nAXI6sGPdd8uV2YphIKnE5IyL6bLxk7cn3bdkHHefrpvJAExMZ1uBZmqeNzXtfzUzk/m/ens7LjV7Px+8d9e1579/44l0duZtge+Np5zEEw8c2pBu9na3YvtEwmrAqNE8IZvNHsep5//yjl3r/0O8yFOXbv0QCO05gP0JGIL+fjw+uj91YeRh/Dp/PtCDM7Zpfmjvjt6Xo7hW9ycmJjaYduf7Hdf/8HTGfa3rG9rYxLSWnsloPg7fijZV8oFM2Ja2a9t6EJd7bCztvHP7us4rrdD/r3/7ct9I99jEI4cOiQ3dIg2YEFYDgOUJDFj1e8TqX7cT4kImXuQr5279A4DeBEX8ayvprU4N3rovcALot/TH13T0fXDTJn0qXk4r3k9OTm4y7a6PzjjORzOOvn1kbEqbnEprPhRzwAKzwFLHk05hv6Yd6N+o3R6beG50aPSdr3qV6IJKkVp5ITIlXOCYn4Yexr0w/DO6YXymHFlR0e5r7tsM3fxgJbI6fW1ivTeT+SsYmr54cFff+5Cu5X+hb94Merp6/J/PusGvTE6724eGJ7RpSFOkKPCUZvBPBccoHBet3Rwe13rX9tw/PjXzZ5hKvr8SfhWKkeA2REAIa4GD6p0feRdWBnvxjv2PckVhVfBf4A29uG/X2i+Ui2eYn8n8NryuDr3jPfWSFV5k44UT137eshIP2K7/64cObbheqZ6lCp+Ydt8TBO7vTM5od1+/NR4SFVhoLpKKt410lnE8LTMzo3V2dLznxLkhYgQ9obiVjEDln7mVjEodfYcpw+MAsftg/7qSDbAnb97sCSb0Yei2fqOcbovVqKNnNO8HmAE9Cv3Wp+uoWjt27HpXNqH9WTKR+kBHKqEFbvo5y3N/avfu4g23R45f3WGa1k9ZicTd0zPTf/f6O7f8dT311Jp2fHzmgJlI/N70jPPe4bEZ6Kg4qw0lqlrLiNKBiLWerpTW25PUbkPXZViW62ecHz+4d8PXojTirzwEyhq8rTwYFtRjvpX/rlwJ+iSXugPbMuyKBOHo3geRJtuT7PujcmVUCuPJlhnL/9NUqvMD2eyM5sxMaIlE4n7XML907tyNjcxHQjty4sZv66Z1xEok/xNW5n4uZSf+8sT5m++vVO58wkEu5sR09pd9w/rWyET2vReujiqygrSopn/zKZN5qMeirotKeTyolm7p/+X06Wvr51ue5Gt9BISwFjiGsLl6N6SrvylXDNTK70D4mX071pwtF88w6Jd/DG/1E1u26NOV0pQL71y3/8PJVOcHMzPTWkcCH2YGOaTTaS2RTN6f1fQvvvDK1bdnbO2JZCr1SeRfn05Pa1PTU0gXJBKW+ecnzlxvCGndhFQ1NRP8bcY1/vjS9bF1V26MwHwsVKiXa3etYVw1TNhYJ3TDjQCO42jJVMcez7J+t9YyJF37ISCEtahjGjxkGDr2DJZ31D8h5vUQJL5RPkXlUMM07u3qSGidICvkzzuSlmlZb0olrK9hD9v9JCrPC196JoPMAolFg6CV+PPj54YeyWecx8Vk2v1Q0rSfhFT18LnBmzBRyNalp5qrSuq7kiAsh4SFa7oZ9M0wzI+cPHOjZPo9V1kS1z4ICGEt4lhiCvZrSa2jol7qzPXJPk6nIGbVbWfUvcr7hO9MP97ZVXpggOu6ajplYStj7l1XvbRMXbPAbp6HzSSBlkraNknrvfVCcPt2sHYi7f3pTDb47KUbYxuvKqkKpYBXKBnV869c3WgbDEixAck0FGFFfEzJzbIsO9C1TyrcymWWsLZGIHoW2rqTzdo5dXyykz0NC8l779i5vu4zwM+eHVntGP5jqVTq/6AkVc5NZ3wNH2lVxNWZNIukMSjiNd9z0+CHp5DXAdX4SAg203w8GB5IATtODHzdK8C15kEjhXvNS9rWA11dnfcMDY9prscss48RySakrOLWqODCoIKAgkuVgsS0urtD60haeV1YYVbbtjUn6/74HXvW/11huFy3PwKzT1r797Upe3jq4sib9u9Y+wxe+vh7W1N7jx49v6ZzbffnQD4/Cj1Pfjx54XiBls6GVuTUc9mQsOIO9mPQFdkIRlz4fy5JLm2ZMOqTcJaXIqpcqnixVe+rdbZ3dbc2OT0D0wZIibHSksmklslknvx+//q3PiKnXcTQae/b+LPQ3r1t0969cOL6G7o6E09qgZegdMJBpVQ1DbKCpyUt6oPKz/4NEJalCAuZFIuEVBJd+jgLh4rvAiFqUVGkhJZMWFp3Z0obGSu/d5gSnWmavuO6h+/cvYHSobgVgoAYjrb4QPMUiGtj1/79jBMkLBwiTlMASlYzTkhWCJyTrGAyMOFkst/BoYMmuIIyGJYcMXMMdNwHPhYN1qWS1t6ZLGaKZL8yzFXTr15BooLLMugHMBRNKgW+It8y9TEcJGt4rvcRFCCEVQbFdg0Swmrxkb0+cf2XOzq73kgdFieEXF2jdEUJKQH6SVWQrNjtZDKlpTPp38U58iUbthk/Ph7sN6zg/xudSGvD4xkq6otcnnjyF0XRRTflkyC0IIJE1JG0QbqGNpMNp5xFhRTcZDNoj66988SFm5vv3LX+WkGUXLYxAuXnCW3c4XbqGs9hwjv+a9lsuN+ahOJSCoLjNDAFvVUll0p1aNPp6adTweSflEszPO48oFn+4yOTmR+6enOshKyYhzWpf/jDuuf6x2aV/qNRaPG/1d0gUXWCA0uu7GhMmkqmerEc8KOVU0lMuyFQ+Ylut562YX9Sncmf7Ojo3BDZWbGLtMkiUVXSWTFNuMqWuYG530f7+/tnGFboxsfdd9mm8XdDo9O7rg6NFq0CFqZr5DWlK9qV0fZqGvZchSuPlevB2VmG/hOV4yWm3RAQwmrhEcW64qu4ykfJho52Vp3J8quBYQooqWDKADftBd6HD+5efyoKj/zR8ew/hWXY56/cnFh7a3RCTTGjuMX0SVB9qzu1qfQM+jO3dBW1g6uVSHv/qVNX10Vh4rc3AkJYLTy+WA/8ou9kJjo7bOh+DLVFZ64TEbCyBktxI5PJZj56R//Gx+NdH5vM4vuI+p8NXh9LjU1iw3EZhXc8TyPuuV9wDaaCfBjTM06N0hVWQmHBDzvSDZ5tvqYR7ZAymh8BIazmH6OKLbzv0KZvJEz3ZzEFnEolaEtV2XEaCLKadrIz//TQnk1/EU85NuH8th8Yf4j9gMZUOrNkZEVZCnsbtTU9KW18GqcKFyjh420sd2+j33pg3F8uTsLaDwEhrBYf04O7N/2t7/o/C2FoGnsIy/YGlvAwSfCvZzLOe+8oR1ZT3u/5uvHJC9dGtJlMrfqjslXVHwjpat2aLi2rjFFLjUSrFUjlO0juddXSSXx7ICCE1QbjiHO0/hofbPgwpnDTOR2V6hWNQqGUx34890noet5yaO+Gko3Y45PO7/uB/lvnrwxrWdha1absbgxo1FWtwplXqYSJY5Nn5lU3bLHQmGA/yko0plVSSjMjIITVzKNTR9sO7dv8RSeb/T9BWmMkKv4D+YzBXuljV7yxd+zfte6VeHGKrHTz4+cv38JWmyUmKzSGG5z7VndoE7kz3uPtq+Welvhwm39weVjOyaoFsBZPI4TV4gNY2Pw79mz8KyebeRIH+VEZTaX0sf27+v794TKmCxNTzr/2NOPj5wZBVjjdYSklq6jN69dyKuhqmWztivYob+RTSkPbe/xMdlMUJn77IiCE1W5jq+s4dYEO6mzsYAmvi/+CrH7LDYxPcBq4HGTFVcG1ULLT5orS1ULIkoSFI2cMHKG8obiXcteOCAhhtdmo6gaOh4EWWlkyYU9gvHswXfgV19d/7+LVkSWfBrItJJhObL/p7elQR8fUZnEV70XxPc01sM+xrzhU7toRgZIHuh07uZL6xA3LBaYB+Ar8rBsfz34YX1j+D5eu317QNGy2xPquSE4mDuXb2IujY2AgytNE67RiKFshzuwCR5s9ZSMlsK0QEMJqq+GkBKOF5yFzRoidK5BoFCeMjM/8mG+a//Xy0Li55KYLBRiTrGjwOQ1br4VMBQuKVJeQKVPxMLlvPwSEsNpsTEECmBLSgbHUpwD1YGwse59l2p+9fmuig4fiNZIowrqq/6Xeqm9Vh9JbjcOKvqFtACX7gV8kTVZvkaRoRQSEsFpx1OZoM2iKxxuHLtDcsZlgLzYZfv7m7XSv+r7fIm234XSP/8o5ktWqzqSyZr89PoXPYDTYkZvziw0NLluKayoEyq4iNVULpTF1IaDjHHZmoAW4aep9geN8fiLt998cGYdtVp7K6iqzXGJFUCAi7jdkuapsBJKcPBwgyP8YRyV7B04Q3dDbpY3jg6gupoMNla5U41BbUN9n0sr1ScKaHwEhrOYfo7paCAW0WiWknihhW/0Tabf/6tDtxpIVSIhGnz1dSXUkDL8fSHKi4/lWPId9Kp3Vxqegp8J/m9f14D6DQ/nmb281FwgkZ1Dj7bnSSFx7ICCE1R7jmO8FJJr8jCvjeNrIxFjDJBpKVaSlXhwDw384MyucBoLAGEfHI5ptO6n1YAq4FjorH9IWjUOnFlF3pj62aui3whbI33ZGQAir/UY3XCVEvzgdw/8NcSyGUhSlpVWQrFg2p39xp0JYLyIohaXxdZ2FGofG6yi85/QS32F0Asu8URgu1+2JgCjd22xcsVElPC85169Gaa1YTkRWJKpSqooBiQQzONvq9sRULKKxtzzAEJw1api2EFZjoW3K0oSwmnJY5tcoSD09HanEDztubnfO/IopyUWC6sUmZUpW5aSqkgwgK04DxxaZrFivacCaIdAuH9zaM1rSDgloOwSEsNpoSMenvU93dXb+EE5taFivKElRqd67qrNmsqIF+yjMF/i56MV2JqadYKxXMDXM6+4Wu04pf/kQEMJaPuwbWvPticwj4Il/NnTrdl7JrqaDC5wTUle1GmdWWVCw1+JotjA6PgnThsIdQrXknF8arkJi/+R355dbcrUaArU9ha3WqxXW3tHR9C5dN//T9eEJ3aGdUwP7T0V7F86Mr0VW4mF6o2NTS/ilaB2HDmb8wA2+08AuS1FNjIAQVhMPTi1NgwRkGKbxRxMz3uaJSRzVUkumOtLwo6Zc7aOkVdEhynN9NQ1cyuNqeEqD67mX9TXGyxXbJhFthYAQVosP58S0909czfqJqzdGODVqaG/IUbCWr2p0yukfp4FUtDfeir1yl8IPUGjPHFy/fqJyKolpJwSEsFp4NEfT6Z3YBvOp8MvMc0hAi9hHNQ1cBrJil5TUZxhfXsTuSdFNhoAQVpMNSD3NMTzzU1PZYAM/ProYkg3UV5rHT8lXmA7SwnwEq4FLLVkRI04HM+n0LdvzvlEPZpK2tREQwmrR8ZucCd7hePr7rw2N5PfxLUZXON1zHKz4kb0KnIttP6Njk8tyaimbwXPrsW/yq3v3bhoqaJZctjkCQlgtOMCYCnU4GedTI+NpQ32XbxH7QOmKG5nzdIWZJz8HNkKygqI9TmSL2JSiovGVn0A39c8WBcpN2yMghNWCQ4zPc0HRbr6GEs6chJFnmfl3knZO4/hmII1B6fiFG9br0s6qAeXPp2WUrhzHeXH/jr6n5pNf8rQuAkJYLTZ2kK7Wul7w6zeGx9DyUsZovOodOizosTg1TM9k1Wogpa7lIisOF+w48E/7E5B1Y/cgtdizsBKbK6c1tNioT6X9n3MDcyePOo7OoJqrC6S0+ZIYV+GSOHxvc18PJCxXG4ed13I727axqTp9yk9rX1jutkj9S4+ASFhLj/m8axwdDdbgELxfGsLpoZyqVXPVU1QugVJUV0dC27p+FaaBWWxknq6ceAljTNMiAf/BoUMbJpewWqmqSRAQCatJBqKWZpgJ731Zx9pJM4aK0hXe5vlKVFEbKFlxs3PvqpSSqpbzKztRm+gnEkktnU6/2GFMfa4wXK5XDgJCWC0y1iAR6/Z49iOjY7C5qkG6mk+3SFQGlEP8FFdnygrNFqBsn1OxP5+K5pGHbcBhqhT8fqu/v39mHkVIljZAQAirRQYx7Wj3Zj3tddQjVVJ4l50CMjHe8mqOTJCCvmoTyIrENXx7Uinbm4Gs2PZUqkObnp76i0N7N36tWl8kvn0RaGnCGhgILKPn3B3+xKVXDh8+nPseX3sOlpt13+P4uonv71WeDqLr1ampFB8S1JrulNaHc9rTMxltcpofOeWns0rTLkeIZUHRnpm5YibMf7kc9UudzYNAyyrd8ZLpWvfgQT8w+oyevXeo++bBtaEtQd9s1/ffRsV3I6eDJCp+nourgH04UZQnhIYfWm1o8xdUGCU8/E/bil89sH3dlQUVJplbHoGWJaxnXri2HTvd1nEEcCBS3z++MLi75UejQgcmJjL92ax/gNJPo6QekhVXAbdvXI3D+XQ1Bcxiu02zTAEjKFIdHTQS/S8Hd2/4YhQm/spFoCUJ6+mnL651gkwRQRmBt33gO+c3teNQYin/oG6aKX5rcKEukqqoWN+Ij5vy81v8UATDG0WGC21jlJ96K6wKPpWd8H8jChN/ZSPQcoR1+vTppJPS7iw3bIZl7n/++eFV5eJaOczX9Z2YvM1LPxWpocBHKv8qHHdMqSphGUqqahaThfj40ITBcbLnsDj6oXvu2bS4n96JVy73TYtASxHWo48GxrUx+5Cu+XY5RH3PMzLGxF0ktXLxrRoGNVPPfNtOolIrgElLGYH2wbZqcipdIFVFlDbfGhqfj9bskCaHHS/7gTt3r73Y+BqkxFZFoKUI6/C7Lu/Bl1jmlKB8PUhcHjHufuyxx/g5lbZw+BL7bX4EoiZqyS0T0uM0j1+82QSl+ua+bhxj7GjD2LicwWkLzaarigbKsmDJ7gcTmezMBw/t3ixntUfAiK8QaBmzhq8/f26j77pbaxo3w+jetPf1B5D2RE3pmzyR4/nH+Mti4Wx1dUrCHO0lSVGqskFUnakkpn6mhu086jgYHkWTW3Wbo4Tli6L5gqYHE47vfeDufVv+YflaIjU3KwItIWEdO3a9Szc0ElDNDqcLbHjmxas7a87QxAnX9ljfxcr+Mzs29ykpi1O8iJjoR/cm5o7dnUl89LRLW93dyWmVIip+Kp7pmlWqIvQ8Mga9Gslm3Efu3LX+K008HNK0ZUSgplnGMrZPGxgYsIKeXa/TA61jPu0w0+7xBx/cd3M+eZspD0wbDgWm+RXP13cODY/jWGKuGAb48jG+agNpilbqlKZoWDqDY2AyjtNUlupzYZlKpXgaxIVMNv0zd+/d+uxcaSVuZSPQ/IT13TN34QRvZW81n6HSDdMLUqmjh9tgd//Fi8OHEl3JL3Z2dh3MzGA7XU664llVWRz/QhLjNYmsmaWp/DjCjqIDdlaZTOZZ1/A+fGj7hjP5OLkQBMog0NSE9cSRszuswNhdpt31BRnazM3U9IuPHDrUuG+419eChqU+cvzqjp7u5P9KJpMPpqc51Zv9QntLkFQBEqZluVCw/7nhaP9i376+8YIouRQEyiLQtIQ1cPT8GjOw7vE8tyFtxBrb2MBXdh579FF99g0vC0nzB548ebNHT2l/aFmJj1BPBYyav9EFLaQ+jdPAVNL8/pZ13a8qiJLLOhAAjvrTRy/d0enbF+69d0tzHFhWR/vnk7Rple6mp+9uFFkRGF8LVj/08IUN8wGp2fIcPLh+4sCu9R+F3ucj0MLf4vaVVnChqYWmdaQS2jpY2vd0djh86Vqh7c3Yxm8dudTPxaW0lrn7yJEjZW0Tm7HdC2lT0xKW1xecgHE3FDWNcb7uDh6+r/96Y0prjlIO7ur7TOD5b3ayzt9ylY0Gl83qKFXZsCXrXdOlrV3djf2LBr556JOshLDmMWhPPXV6vav5O5jVxYLUhNl3iIbV8yiqpbI0bQcP85C2Xu0l3dczC0XUN4Pzb71339mFltOM+Q/0rzu5f2fvu1zH+QDOt3uZ0pbVRMRFouJK5qqeTkhVqyBdtdUmhGV5JI4cudrpd5kHiyp3tTU/8s6r+4rC2vCmaQmLWJO0Ep65INJK2tbpt75298U2HLuiLh3oX/95L+0/kHUyvwTieiUJHVEimVzy1UKeWMqv2pCoKEVFRNXT1aHawnBx80eAZj7TwcxdAc5Gi5fiaNnNT37nCk4xaV/X1IRF2B94YHt63qQVaCcfePX2K+07fMU9U7qtHev+xE/7r3cc70O+6w1gxuV0dHZiusgvJS/O7IskRXLs6KCxqj+B26t9a3uUREWi4plbQlTFYzXvu+7tB3EIUGel/L6e3TNw5NS8zYAqldss4YvzBC9C7559drAja3qvDoyg6pwCP+KBZaVOPPjazS1vMLpQKE9fuPnawDB+EqehPwzWuAuSl8LPg90WVxhJJPWQCUmPBAWTBEz1TFUGpqO3wYYvIPgr2az35a2b1/50V6f1e1NTlVcvEzB0xRekj67usu5FmS2/crvQcaol/zeeObfTSOj91dIq28PxiaOHDx9quy8LtQxhcZBqIS0Dhkl2l/3yA4e2j1Qb2JUUD1Iyz1waOQib0vsxKXsAFvH3wMB0JySwtZC+DBPTN5BOCEnhrI1BuKe9l6tIzsVCiD6E0DOabrwI2elZ09aP7N3aNxjheXvK+a1OENa0EFYEyYL9rz072Ju03ZpNQKj7Xd899cKhNrA9LASvZTY/s9GcHoK0XsrakLS8UklLxyl+/rj+/Qfu2367sJNyTS7SuZfneO7ffweBGScu3NwAqWgrTvTc5jjBZmw87tMCfRXYKQWOgula4OiBOQUZ7DZuhrAGdQXxV0zPuCaGnkv3VPGHOpPw7+QPR62OM5HhdNddGOeX2kmCbSnC4mDlSStVTFr4eLljdHV+702vWz9R66Cu5HS5h5hmHvz3QiOxwJTRo2BGgY06dm7OVhewYGAY6s75oD+ZDs4JPY9JyqSCQ7ABqftd5VFM3/j2Ja4mtsWpJQSq6ZXu5UZTKeJnsHpohiYPRqBn04nkS2+CQWW59BK2dAjwS0Y4IHDz2ERWG8Gnwm7iK9W3sFmbvrqGPzw6gW8eTmvTM07XmTPX28KYd7EQ3rjnvv1QFHbPt3zT9DcMPHd+13zzN1s+/hC2rKOo7NjeQdsxT5LEWrYjbdLw05eHtwWe9jl0542u62HZHZIVpalY/yIlP5X3MHYddLLZfy4fmYiBhNuB509vw+rG3tKY+kOwGHLi7W/cS91jS7v4s9TSnZHGLx8CICH9lXNDX+zpWfXuycnaBV2e3e567nAm4973qv0bzy1fD5qr5oEB7KXt0u7B3Loh7yhWVfypbOalh9+wr6U3mbfklLC5Hi1pDRE4ef7Wj+EEiZ+amqpvJT2bzWjJRLIPR3n9riA5i4DZg720DSIrlsrvHXSZ9p7ZGlrzSgirNcetqVp9/vz5FJTqj6JRejTdq6eBMzNpHP9s//QrF4bvrydfO6f1JrCX1mvcXlo98Kembjotr3wXwmrnp36J+pYNeh5JdqRem83O77gxkpxtW3bgOZ/g1HKJmt3U1Rw+3D+zrc89aunagnWzpq6PdxujLz388L4F78tdbtCEsJZ7BFq8/sHBoMPX/I9hyrGgnuDUUZzrnnz7yQu3HlxQQW2Ued++fZmJ1e5LoPB5k5ZpWCPXz+08du+99zrtAI0QVjuM4jL2YcIZeh+2+9wF49MFtYJSlgmHE0g/JlLWLJQPg7RmhtyXsJ18eja0tivsXhj6xy9ve/mRR5TRcG2ZmjyViN9NPkDN3Dz1FW5z9XM4i+s1ME1YcFNpUIrVLHzJzHnwjl0bn1twgW1UwPHjxxPXpztejR0HFTc+F3YXRwxdfdM9W08D0zrs4wtLaM5rkbCac1xaolWOvurhZIPIih0OdVm2haNTfqUlAFjCRnJP4HBn+iUqz6tVa2nGpTe/etsP2o2s2G8hrGqjL/FlEQC5GHghfplSUSMdvwaEA/9+4vjpa3c2stx2KIsfUek2dr+EuXNF2xEjSJx98w/tbFt7NiGsdniSl6EPp84O3W/Z1oPzXRms1GRKWdCJdeCIlJ+vlGYlh997r+70+EPH8NHJEtLCauCph+7bmj81ox1xEsJqx1Fdij4Zxi9AT2KSYBrtslgxhOD2gWOyz7AstFzx6zFHj1mGobYUYAgC9cHge3ddK5uhjQKFsNpoMJeqK6+8cm0X6noXiWUxHA8WxAdWNyQM45HFKL8dyiRpueM7jllmMGpnjO+1w9fNaxmXxiogaqlR0jQdAkeOBPjczrnOiQ6jw88ESSOA6KT7iQzOHEvavu1pZsLQg4QPP/DdZG9Xx/vWrOr+mfR03SvtNffdxleAQIgvTzjBT0w409Mpu2faufZy+vDhw5WPMa25dEnYqggIYbXqyNXY7i/jCyvdfmaVb5hdVsLp9LJGp43j1/1A7/RdvdMwPRzEboRnLVHe9vEvL3eXBOB4ZMta22H+TiqV2LJQ26u5u6Bju44Z3J7O/Lvp6cwPmBanOwQ4uNHRTWMK21bSvh1Mm642nTWCtKkH07rnTE72aOO0XZq7bIltVQSEsFp15HLthg5J/+aJE12m3tVjOPYq1/dW4cTjHnwMYhXOce8xDd3y/PJW6OpMdsTRVy4iK/rKMR/jwvz825VIHFzT3fkx13UW/dnhRy3GJyeeHEs7n1XNibUPFvY6vtGDw5vV9w0Vofn81qGhZfDhi3HX8SfQ/3HPMse9CWcCX0gel2OIFJIt+2fRH7qWRaYJG85NxldGzV4tGayFSLQ24+q9ULyu9gJfMU5ELTn6wUISTl03NHz1KzyiJLqmX657OLLdSJgoXTO7cBxyN172blier4YCvBsFdSNXV2dC35tKJrbzfPfFdjwvC/qs9MSMxxNRsSqmT6LhUDQHE+jUBE7UnATXTuLsrRn01K2l/x6+qItiR3TNG8V59KNB0DGSfNXGUXwJY2Gm+osNhpSvEBDCasIHgVLTt75/aQ0MnXpBNb2QgNYEntfr4wu/nBYpKQLtxtdwAh0SBX3VDe7nM/Ha5vf1Fb/CURS2bCTAWWuxR229qRsbQQQbUed61LfW14JVKKsTJ5sk8WUcHbtlNANyTOhgcmAGKH7p3m1FWpqtuZCu+LByVdKHVMjpKEQrBwIW9tnpXOIH+QTDSH/D9f0bmCLewDn1I4HmwtAypPDZ/oe9oXKf/aMPsWxSs/RR13FHrURiZE1gDR86tKHEdCDMKX+XCwEhrOVCvqBeHNaW6ui11/mWDtLQ1kEiWodXE4rwYgepAPssTPCMOjIdAk94TZ8pMZjch8HjDorGFUTUAwlkh64be0A9/ZCatiDZWtOyE7ClQmIdJICJFYhA+TRV4Fo5/QIHiUvrTEbkVRCxiJfsSBbfYk87OTExXxdazY5yUgiRKfpHQ1YSkONmAZY+gV4NIeVFfCXoLNA5h/Plb5LzWAyzF+IVXdNnvO/6GcsyhjC1vmWZ7s2pO3fdOqzriy9asnJxZREoerDLppDAhiIAEtCfO3F5rW0a6z1PX4/nf53nG5RqqrpieSnULEVh8cx4E7ugH78H8tG9eP/24oVezY+pkpA8b/abhPF8le75BqdsXUtaFeaTlTI2IByEoU1l8oq1mkokcZHElIRoWmpejMMCMyCvQXyy7JjjuUcgOl4tLCzCMpTHgFpcgkViX/dH/ax2Szf8m2Yqc/MN+1r7BM/C/rfCtRDWEozSkbMjq7NTY5t13dqE6dhG3wsSqlp+C9DDi0ifLrqmT1f6BgUaPjiHN0lJAGAfvpWcI4XjiHIMF6ocO/EjmMa9HeelQ1LT1PRpoce/sJwOTCQtc+kfGQp6Uxl+9JWtmL+jNEaJ0gKBgbsygR58B4sHfwV5aliVWg3vCHv6ymHcdG868IzrVsK6pnd71+/dsmXxbD3m3/W2ybn0T1/bQFe5I8euX+9ybuqbXMPbDA7ZCKV4uMOecyz+9OfmWvj9x9zEw6JW+JuOX298WhE6qtwLEV3TL1tb/AWj7sqwfqaro/sdmcyM+vBp2XzzDEzaBiQsNH+e+eeTjQ+ohwqnG0BYhfVzNYKrkOmpyauYYH8KvD8G6RPBszrC6Jq+ystl0ghzXEZjR5+O4+iZwTh+eG7Yqa5rq/3hGzzTSkXKn4YgIITVABjBP+ZzP7i8ydasrZCetuCHvIvFRs92SEdlpnCYE2LOQi12OA7RNf1yjrphHIyE9yOXPnfNMDg70DpdTf8DWDKs5rRvMVwChAWrUgh21HzllD0NrigqlxKVC7bKQuOOWeGiuI7OTkhb6T8C/Xw3xkel9cXxj6eIxiY3Hhx3X9dHsWJwDaa3l1+zd9Mt/F4tUk/ijWnP+/DBb8++LWqvnh0c7NDGta0pO7kl6zpb8AJzEUr91kYEFdeBRCt69Nm4+AsSl6jwjVGckY6VwPwUpLhLURx9xliWvxFHi/w+zB0SWCnLsVpxnoXesSI2ngp4zmRJXPgf/0IleGH51R6uwjeX5MR76qtITh7+8N9Cp4GF7Sm8Zl1s35pVXVomm/5c1vG+Wm284njHJeJq44/FjixUAld8w7uijW6+xo3MhW2S6+oIVHumqpewglJ87+LFtcFUcqur+1vxwPcZJqYPMOyhXw6GKI4+4/GwQpjCBhe+6XDIpFb06PM+np5hhS5eXzw9bLJ2pBLGv4Fe36BU4kA6IQGw8MUY6MJywVeqDs54Z69zrWdY7jI3G1ZtUiSV6zzDI3IqLLew/wu9jspl+yywrA1pEed5QceXPT3jBb/DLrA5ua5UHZ/4eMTbFx+fwvE3DJO8fANrjlctL7giJhRx9MrfR89R+VgJ1Y6currONuwd0FNsxwtV02mPlWGLy1TxlPHf6Hh8PH9xesvw9yRM+5PIRT2ZIgVKKZxWUY/PT8aTFPji0i3m4Ed1hDWV/7uY9bNGtiGqAyorJRWSqCgdkrQiR5KddrwPlsq8xfhG6efvx8dvtiQczDdmmPaldDBxSVYeZ3GJXxUMWzxq5d4fPz7Ym7X1HTAL2A7NqtJHEQ3qtCPjw3LoxB/v+OMZ5VVzR5aHWRuErYA+y4uu6fM+Xl9J/lh7bFvbY+vmv0bWos9tsXAWSLIiaSnyApHxJz6SbFSFuXTw8i86r5vVRW1m+6IHmUREAuI0lcREP5q2ztWPrO9/YK54xsXHI56+cePvj3qBfimZNS+J5FWMcrjptThsRd4dPX9+DcwEd5iQphwozfkCwJKaLv9ewHYKeicfSudwShcnJDBBOD3MTwGRO0cqLIj73jQTaejDBYaPHTBgJ/i5+HyYijd95sFhRzkzB7yL2IrCtGwezj9nOQVTUlfPwiicifnu5J0qHHd8mXHIG6ZD7JQqIk9kJK6QwAokMWRUhMaSeJ0vcfaiXNhs7PyuwpYV51Vh+EM/Pu2M9GckpyiOuZm2Wvtom+Y4me8xPbvIIujzPu6Wbvyt1ejL3U7Sv/v754ZHsORwaX3KGdwiJhO5pzY+Mivk/urVq52jTnIXlEc78LKu8qAMx/G8kHhyOicosz0ovM3IrIDKb15HSvDoOoqv+hMLYCOWI8ash0vmufryZVcqLz4u8fym3ov1xT/EVp4UDUTn4/iS0xW+sZTMojASmLqGp64iH4FRXJQ2TKj+lv7JVRTVxwQkm9APyaboGnGMzSVR6VR87ipsVT645ovOzi5tamb6zzB1/nqzjz+s9YetwLioZW5C8jq08K9+1IxS8yQsfF6ap1WL2BK8VOaJc6NbPcPrx7wJ++hmHQUPvOaQgMJ3ETtVlERDP0wVsQ19uPgcLQyt/Dc+p4jlL6k/1xa2qVyh5ApEzEoErm/DsPOTXV3de6anq36roFyRdYWVbVSshHJEMt98saIXfIu9koplYZL6m/hUz7kS/Jt0/PE8+Jj6X/Y6k+fv2tA1BKIvB/OC8WnGAmp5dpqx3XW36fjgYK/upXbhFd+BrRlqn16MfkrspkoC4hnirYjbUVWzs4rHx8uL3cerjwt0TA4RcBcsuX8Rn97q54okVsCKJJ9YkSvy1gJR4aOtnAr6OJP+L13d+BKBKMEzHhAfgDh6yzD+vqHjTDDvYpAxLqwEfVdbE9bpIEi6V27tdLP+LnzPrWS/XrRTnz5d4e79+LNY7r4kP+Z7Jv7z1LyPL0B4Tb+ci9cXLy+eJ54e8Rw//rqqcUR+HOrgYVprJbBl5E2w63oI64J7k8mUDZLGhmAXs19ucVkxP8gKQu4ptCxbMy2TW3KAGI4u1P207ztH3CDx/7bL+Cdse8h1Zy5ev7Dp8uHD7blJuy0J69TV8XW6l92Dl3cbLG6g98idbhDgdANcY1ZY9o2N4mpNr96GRf1Da3Wui0RW69F1bWslvp81LD2xDTOGu9DhQzBc7AcYfYlkAqo6A6ozqHNBYJTESGitTGShsp0qQSxT4AcoPJQw0LBlEPhBFakHDjoLvY+XgVIyg7WK77tG8n9pvpHXBbXL+OMBd7FN6KLu+uf27esbX9RHdIkLbxvCGhgYsDb3v2a7obt7YHakpKmYiqgE2ioqJbzIOszXcSov/DAzRRNehyJKvPx4+igv/ZLKEaCkoZxUFMYXE1I8f7Xyq/UHp9CkAlfbCF3NdlhS7IQguA0N2wiJYy1ktC5IISb1Okr5jSYruy2SGlYkIkKLSC3yy/WrUWGzSnjaTUX/QEhYQuNewLCdwBFKRkpOuAfr4sBnwwfDg6B0MHagORhBHNqHw5WxTwYav6lAt/42MBLfrYZXHO9w3Ftr/B0Hp0pY+tkD29ddAz5ln8NGjddSlNPyhHV8aKjbzAS7Dd3egRcvgRHJWyrHASw9Pyp+vlSxEluH0jWAGQF9VVZMpxHVRZ/xSKQU4PR5Xy0+/sLQZCFS9DN/XKtSeh5WrL2x+sMyZv+W67+vwz5eC7oDx12rm9pakNg639B68XL3Qh+2Bm94DySxHhg0daBHSQhiCbyyyMS9SDi8RhEHyYP1qD9qak0S4VGn5VYrSTRKEkKHWYYiHuQmCYb/YKYLqS+3H5LYckxJmz6qhSYJ5yNgzgtuclESpncBfN8Fj3lgJdCSGpHcGECoxrouMoHjzO+4evLLMB1VKxJV8Wyj8Q80Ix043jnTu32hlTdkh08Yn7UWcnio9Qs3pzZm0lN7LCOxIdIZxbuQ1+lAVFFxJB7aMeUIiPkiPRPjo2v6dPF4FVjHnxi/oQK0Az/bymf5uI7ayGLj6eM63nrbF5VNXzV7nv3HViQL3JAEaSV1z0iBNJIgJBCYkSKJYbdjEiSHw7a0BI5s6QBBbINUswMUsQ6E11UojZGccA9dcZDBdQY+TgyFTgkiEKYyIBvstAQzIRk8cBJ+A2j4gZFDFWAqjAp3V5IhQYYwwUJ57ByS0QINzMYK8FyrRxt3KNbXb2qG/UVNT5wDyCt6/A0boGbdqzPA4tD21SPquWihPy1FWHjQzYs3xnZkM95ePIZd8RccBx1xez/UPowp46I4+uVcLD9/8Plq0Gfy6Jp+uez5uqPyY+UtNN5DuVQc06drpv4bIDXsjtsMpdkOSC79QK4Xog3PzwF4IBNCBiIhpBSpoE8jioqWaM2KCRuOqwLXgIQItKIe0lCYD/lZjoqgGIo0+J++SsmMKA8eqQ21qHuUh2PfzQHN6vgG6vVK8GfmQhcbr3Yff+AEi3rtdCtNF8u/eIWD2ATXx4Mg0XH1Vr/hm7sDQw8PvyvTrriKWocEE0C6oM/kJRJHrAykgj6WGlq+JUifu6YfS6pu4/UVa6AgQcXKi78ApekhcWFBwMstEkTX9MvVHw+Lt2ex+4+Pg62CxgsHEwZbAdgWIJfA+ICkfDRYtyAwWWB7Ay8F8VT/KB0bOJ4Gx/CQfUKSwZGrJJs8iZHYgB0zMB+zk8hopQ8hEcEog2ERASIBAOL5fIrVIKLxXKtzKPZLgZUckvGf+/nH5HsK0+Uz3316zeAjj3D23Lwu90w0ZwNpiZ72UnvwfO/AXIFnXfLBxLOsHn6yiLqmr3oQ04LHX9hq6TFHI6txrlYWkHj98UT1lh8vryR/rIKq6aO204drdP8hRWF3itmLUw42QnW1CSTSA2IAIXkWOBYKLWw8wjVqNkEaFqjFwLQNJhWI4ZiFoiq6QX0SbsEo6HMoWVFCYprwjw6FP65BXCSoXJwiOwpnFK9A6yiWkQhRDwA9XAfpwLS/AqnqSKP7jwapquiznXFXMn6x8Yg/X/HySvLHKqiaPlZfvf0H6BloAM/v3tpzHkJwUx59Uxb4GE5Lfnt2ZGS16SX3+F5mq4llfegtwnaSR6J5EC8hPUV6IDaS6aDnoZ5DpYe6AtdgOr4pyhXLNPH0KKCo/DDP7N+S+mI6qHzbQr7AbdgW+iylWn0l5cf6E29ftfSN6L9lGl04x30tOtMHklmLhxpClW9BL4S1T+i2uNPRp+0FflD0AN9A9LHnmHGBBfJCE3QL9ALiguoJqiu+64gDzWGIIAlhzhaSDsMV/yjJi3BxyY9khP9BXBSzEMY/AFORGMmM1yyKZfmm+ZKuJf4uMHV1THEj+o+S864E7zYd/8Dliqp2MamvPbt9uw4dY/M4DnXTuMuXx/scK9iHLcbryzfKwvOJBSGNPl10Tb8WV0xYyMFymDdXXv46Kq+ueChJQI4WlSUqf8StOf5CNdXqr9afxe8/Gm6AoLAqGKyCGLSG350ACFzKM2FvaeOseEhFOsjItdQ2S6wYYmkOdl2+CfLBvmpIV55vYY2Qn6uAxAWC40zbhxSmWArcQj0TSIiSU37mx0kgVesgLereOSz8E5EWJa6Qzyh1hZEcO7xY4Ct9WLfNvwa+5xA2h6uGP6vMPxMsZ8WNf0Gf+cOCw9usq51a5+kNG9Sn1IjJsjoO0LI7EpVra/vxhPdFs7JyjYriohlbTAKGxO1C6oJEljseOLqmTxfPX66OucJK66OUNzuDjK7p05UIbGwX25I/vrj4BYrnD0uZ/Rtvfzz9fPsPIkgkbL0DZNMFRVEHFEY2ZCBTcwMLdfCsCCVN4SwpE9YG+ARNgD24IDHYSYB1yNCYDkLRFoC8oOUG40AKQx5IYyAmlQ6SF7dDoSof0hbJiApzqLs43aPc5UG+AvVQ/4T7nGQFQiJ5kdbAkmgH2Sz0FaWB4gLrad22v4nmuvPt/yzCc1+V4t0e4z93r8PYwDCvNANxLSthkai0jmCf5+jq6y6Y4SkjTfoKprgWufj9Dg3AozBmiK7pl3H8WDH3u0YfLY6u6c/HVS2vSvsxoygyTF2q/qNenEyjJ5NJPYGPRidME1M1/JYqwyoNq32Ihu4J0z5M+WA2DoqwEI9wfmEaEhQJzPNsKNOh0jJwrfRVJqbnNOrC6IGwQFzgHiKrpCuq2kE+FizrMXWE7IWCEKemg7hSiimOQchNIC3EchqpHlBO95TshQThkwF5TL9k+Mm/MZLGzVo3AlQdLzagDle1vCYd/wU9/5Z5ZcyZPnNow/J8ZHZZCGtsbKw3rdn7nIzTx42o0WfP1cPKuYJ6XPFs5q7p8zmKx5v8cdcxDeMPOR1fj+gh4X10TV/dukiC+nJPeLy8eH1hrtm/UVvpKxcrP2oL/dlcs1eQ9PCeo73wGcp+R2Xyvlp74vH19B9EkoA2CYKUlcQqJCQj6vkoyBjh/IurcJiy4Zxy2FMptRBO7sK3kClR0UYUZAX+wMqfC1ICiYHMYBsKSQsSFKaAUEqZLoiK00ASFsgpN0UEUWE6yOkiiArE6NmUb91OWwAAEuNJREFUszCNxA0c/uBoF04W86YOarWQAYjGmHBBEIkUiXEqib025hNmInWknv6zKo77Sh3/RvcfSx5Xl4O4yr5Y7NxiuEEQFT4uvs8yrF5VvosX28LLS185vsiRHkc9YPiJtrCbJIzHyx3gJdfpl80flZWPR6qIxJghus7xjSqj4E9UNn2VvN76Csqq6XIR+48OYEeGlcAaXhLfQwxNQcgQEI9IErOOxBUuCuDLz9Arm5iyOTaYy7Jty8hAb2VCm43ZmwnwQTbgFpAWyA4SGEKhaMdgYNpngKAcpeMCAfFjYGE4yAqco3RZ0LorUqOkxVkf6AgzvFBPFbISSsOUD+WRrWijpcwbmI4Gomj4yxAIv4bPVU+q9sfxk/EP36UlfP49N3vNWr/m9CZdX/zzjDDofAoW3XHVr9NPHdB8p2+uORl/mjFLUktMbBTtkSJbpLCRxYyD5OpJps/4+DJuvq5IIgoLqfi3pLzcRuloM7QSzKImsBSWG80LVKkxkSvOkFHaCjL5QvrPN9rwvaSVtEg2ICmQCNRQkGjwnlOpNktMxdds+GxcRFrIyCmhTQMEUJjl4qwtzPbAOVC8o0DUZroGiMmBpEUfRBZ4DvRUJC4/1GOpij1ML9XU0PJdFxIZGsOpJkkOQ0YdFh5CPodKl0WfRqQkVUhTIEf1iN4GkdJU4Rx/xsJfHkpfMv4cd+IAUJb1+YdkfSU7NXp6+/bti7qquKiEdfVq0Gl2TO2DonYzAcUTCv0slCB8FuGia/q8j7iAPl30aNIPHVKq55w+00MvjFLo05WmV8H5P9XLzydVF/H0xbGl9UGfjm226B98po2u6fO+0f3H9M7SbT1h+FoS00ybSmm+5/RZHxzbwWvVHtSvNuLRR4BKl0vPtHRhWh1SESUsNBkH0qjvNiAx4MA1JDBc4yBmTPmwJArJCFM+dA1SE5XsmFIqRTzKUrZYkMio78IUkauFoW6Mcbin1GWrOR8nqOEUEUQFmuK3ZdEw6NFg92s9j3XLp0CIsAuS8VdPkcKhCZ9/KAc81x/c3NdzFjy6KHZc0YPNh7VhDg9jYnh4co9n2dvx1nLalys7Rimx2xLGigfEJBQ0Xr149FkBVb04BQiTlPAFbTiDxRGKM1pJf5AgarPKG0sQu413N07hkCANO5m0fSebtCwziW5DqMISHTRMJCDF23inYbmsauNCHq+Vn1ta5dErzKN8psP/RiIXVpAegKJQ30Y06AQSEXdAIpdL0wbTNsLpoSIeCwRJHZYBpTusIFAIlPC0iqL5AxoCcmLPQkkLdITRCc0dSFqQD1A51g4pLOXmhZCwDMO2BpH9q6ZtDoU4oKQIy5yEynFnv+mzw+0+/q3Sf5yT4aYs89zq1alLIK7wYeQANcCpgW5AOaqIARzxcudrXrMTz+cuFAxBI1Rw06eLKz3xsnDikt+Mmr9mWBlXrbySeJAlTt8MXJImXHRNv0zx2GpWZ3r0KKqzXHlRHH26+fQf+mkbg56ADjppUuihMJl7BEhGtmnj+4Phj1lEUAzjaQcgJkzcqPPmlI/yjdJV8Trf/+hbeYyP0uMS0zSVF8SEaSELxkhR6a7IC1IVHkNMBWEkCljxYQ7YXgWKrDCHw2ohJDDKSkr5Tst3TANBp7DdgkTFKSOpxYMtV2i3hXQoJjwbBo3L4oibAajdXmSbCl01PEvi6x3PetMvwfi3cv+xHpPRk8GZvo6Oq5y5FvZlvtfqQZ5v5igfH7iRdHqrn/H24McyEb6ejCUxkCwqEATi8JDNKtWRIxI6wrLj+aOyQgIqLT/KTZ+OLYnCFGHE60PdSgzIgVmcfrbt5evjYkB97VeNyv8plx/UYoChElhYgB7KtD3PAUWRpejIVNzNAjNzyDuYRqnrMF5dIx4CkTrlAJQRps2FhZIX5lqYwfFLOygTBeSmkUhDEgNvIC7MR5ML6JhozoCpn+858G1utbH4j7BRT0Z9VlZzbTyOKJCKeCjkqYbkFBJh+DXCPVcKuXKIFURlm8WBoZSFOBCYmk6i33ioT+Kw1CegEMspcFfe+M8+rRySNum/YUwm9I7TPT04NWOBDg/nwtz16xMbEp3mPswIOuI6G7wBSlynz1pQWZEIP0smIcEEWN3QsfJDn+nj9FFSPh73wilgdE2f+eOumo4pPqWI2kI/LKu4RVXLq7H/kJopRUFhnkj4joNT9KC/BlZgAIVD1I+cwASVUBgCIsF1KEQxJLpGPKHGP5LYrAs5ikREnmJ61KF4K5cG1+REVS6HC1JauGroYYcOrLWUEp6MSF0UpoZgK5hV2dgEzeNLYbMBnRQZEUPnOwGMT6GOp57Kg/0WTCMYjnsQHpDmlJFTR5IcNt/alvV1PdF5NsKcLSpGG03L6QcjnWDpeIXqgFYb//A9wGi1+fMPDeqY7nae6uvT530KKp+JebkhHJyX6Fqz33X83tCgRr1d6gXBH+XnFtEwDmEVMBfAtbK7UvHxVTb1gGLQokbFVBZMDtUJHmT+dsPxmqSRU2nkrxkWxhfbOfEVwLov4sIaonSRr1qZy6vy8xliPbn+qPjYHxSm6mJwdB357DfaVtJ/BMLeW0/ayVQSR6TA5AB7h8kwmFeRrFBUSFYkJk7GsM+F5SuiCQmFBEriCskHYcxfEM9ozBjBS/yaKD//rBzndjD3BHswAcmqwFdhOWGugCw5owwpEt9sxMlVGWQEK4GlcAOi1XAcL6eLICfdcMFmNDnH7xdO/YTCHTkxM2B6EiSPbuXmHrZO5eJy4Iu6lfo2Gu8orFfA+PM9UMjnHpBIx9v+/Q9Wm8nMfcMTE1d7u7vP4Ec6fzy1wqOGP3xI63JHjgT2/rsy/boTbMP0pe78dVUWS5wjK0VUjIqNN3kA62ZYeIcfxofXDFNFUZBTT4W6m71mWBlXrb4yWSoEYWh0jVIUdJEmzA6o18mRDN7dCplCEkK8IiP4WRAU9OO8j5wimZB3SAhKYlJEphLkJCaSEP7PEdxsfVG5UWFxP6qPPngTlvBED6IWLN8dTPmg8ocFPPRXWBdlFWqqCEmLlhAgLRtKdLaAkpQNfRUM6DUQGOUiTimNEaT7FvRVw/F6K91XG4/mHf9KPaovvJ36jzfSS1mpc6mUdhnvhZL4a0GjZsKBKK+n0+kt0AHvztCAsIzjeeAeUKVPF1l101cBWCICxcGmcPalUeHRnyguIsJYej79fFnpKxdjrKhu+spVK69Ke+OW6SXlh7Xk/8b7D5umJKY6nUiQAEmp5ZKoD5Ay8kTFzcAsJIrL+ZREYCWAaU4ubXRNP8wfpuSuGubHMwCJhSuGPCiYJIMw5GV6xkfY0Wd+WoPiBAlEhvnzNluw3SKZYTkQHIQ5J1RQDg7Lw/QQGUIdFp4wcC9KgQ/7KkxjucEHROVmc3ZaCFfEjMxUvlPvBZ0WhT1Q1zG06hQKyGPA9qEh4bPRJuO/0p//WvoPyXpa77BPr9L1mn64QiJRT0vlP3jg1oyn0/th1dnN6VOkQyh8wVRuPpLUH9GHi+sckD4vLaj43NSHLwfv8cKjbGxdgc97JUpFpIRbpovKYHTUltkpHYkyEqNYf1gWfZU+Vn+JiMZERS4qKyTAMv1hmwoItLT/aL6OL9cn8A4mknhDkR5CUuh43ExhAXjnIQVxRQ9UwnU1JM73meHISINzlY/1Ir3jwNQBtui5IpU3K2mFZbEUEhgJiHlZhkqI8rws7hPFxBHlZ5romu1CGRSv2HyQEQiLPkwefJcSk2o0mU+F8Z46KswbKd8qvRUWiq7BsuoYlF/q+Jd839p4/KNnFHhw+Fbc819r/y3dHO7qsk9D2lLPBvEq59SLXC6CYSCq1OTk5F48g+FxLyQSvvyzhFK8taaYL1ACiYdkkSOg/HVO4irmAySLlR8+yHy5wnaWysTF7YmnRxdyecMXFDcxx3KjNCUEGUtb2r4Iixwh5qebxEG58v2Hkh0ERqlLp5kClNLkngLSyF8XExrZi089SYbFm9DRg1FCbEKyoxQE8sqFkTOgTwrDVIPCP/k8qpRcGrxMEXmxnpwjUeXbhjpgA2bBNsp0HPQWOiwNOnddw5YcNIdSFyzTlUKehEbrLDxDNn7osjCXPw5FO22qgPfKHn/pf8XxxxetvSvYlX8BxBVKCdGDmPPDhz0W+Oijjxof//jHt+Hh2oko/qKqFx4l0BJQmQIwS3RNn/fxZXqGFbq4nQzimI9tKFs+S1S1KJ9XoQkEfUQwtKg98fSzefMMwmx5F28/IqK2RLjM2b54/gX0H0v6+IiDZSVgHJogfYWNzDMUpCtsUkKg4pKIUJAsnNTlkjNWzfBCPMOhi8JAiCSqPBmyMFVQ1OdctQwLywNZ5cPCpDl80D6IhjzBASQF0sUeREpSJCyE4ceSpJXbEO2612AHepaTSRn/YrtEAD3n8xV/ntv4+S96nyGRO9gccQZmEPiBK3bRi5kPHcG+v2T32n2+53bxNY8oQyWIB0SR9OmqxMeTh5lm/8azx8srEbCQNSqTpUTX+eagwCiPqiWeQAXO/olHV2tPaYUFjWCxsQJjt7MV564K6iOB2Xj1adNGa3PqDMFl4XwSSnAQCUIibqFPlwtTwbiOkoSR+JvLx3KYv9BXaSrlLyifSegQBNMFTAWhiIeFArRZnoX+8Y2EzKhbnuNlYO9wFpZXkwoH5Kmj/6qOFTz+0n8+Y4Y/2pVIcJqY35+YJ6wjEN33ZzL9kPY3hWjx6Sv+RcByLIQAZZYQJSn2C944FRF/QkvjQ31XZDcV04GVPOGl+WdJEhVGbaNPV3d7Va7ZP83U/1ACgzTjkg4gjUFvHhGWkrPAPnnBLNeFSEKKfAbzOu9yBAUdVj6cZURpZuU3XOUILioD93x2IEnxxFGc9c6M+M93cHSNZVzHquBQDeMn4x898wQ2us7pgGvAbyU8/z5e5EupVEqtJirCgp4KHxVI7sbrQIYKHyKF3+yvIvEEX8FsQNk9qXwgBpgQwNo7p9OKrukzfdzF08+WTmYrV35YF+tU8bEpYImInGtLVH+8PkzZ8iQcVpjrawXCLOHH5uo/9JmWjbXHJMQcNhVW8bOklbsumnJw7Q+cgtVK2mJxAUNNKKncp54KHuzAwnjCE01B1UIHA1A80ik/IkdIfTj6mE8MXh2sSKZhdHUd+IcDykwFLj4eMv7Fv+il75c8/xEmeHaojD+jZ4LgbsPVVvO5iutg4oSAFCCiAqVp/jrUKRU8mzVexsube05ff3tiD0Q1wkP/ojrYgeiaftiheHsjLKL4GrudTxYvb0H9h94bpzeAwCD4cAqJf5SmlBjFH5D8ChVC1Q8KyIkrjtgbE64y4lqtINJHel5Hq4q4ZdsYzsWBWaU+rkFWtFzQbiNNnWciNbT/qD4+Hitq/FdE/3mWzmvQU+W4hZZPenQuRHRNfylcvfVjpUqz0Tj6dNE1/fm4euufTx1z5am3/hr6z6lj9A9ElneKwPJ3IYEVEpqKys0YFeUhoDBP4TV/+bjVIkfqKuu8/ixC/+tqR73111V4DYnrrb+G8a+h1tkk9dY/m7MxV7XUzwdP3ApBgCYG6Co+L6/+kcB4X0g0ERFFzwXjojBc5q8ZhqOKtWEoROmLEwSWBIHowVySyqSS5kIABEYhisRFEov8SgRWGD6K9OMgq8IwBIkTBBYXASGsxcW3pUoHgfF5iIiLPv9x+03kuLxMqaqsUj1KJL4gsFgICGEtFrJtUG6OwDhtJHHhqLOl+dBAG0AnXRAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBAFBQBAQBAQBQUAQEAQEAUFAEBAEBIGVhMD/D0fV/fpMMM+gAAAAAElFTkSuQmCC"
  1078. }
  1079. };
  1080. const NoticeBar = {
  1081. // noticeBar
  1082. noticeBar: {
  1083. text: [],
  1084. direction: "row",
  1085. step: false,
  1086. icon: "volume",
  1087. mode: "",
  1088. color: "#f9ae3d",
  1089. bgColor: "#fdf6ec",
  1090. speed: 80,
  1091. fontSize: 14,
  1092. duration: 2e3,
  1093. disableTouch: true,
  1094. url: "",
  1095. linkType: "navigateTo"
  1096. }
  1097. };
  1098. const Notify = {
  1099. // notify组件
  1100. notify: {
  1101. top: 0,
  1102. type: "primary",
  1103. color: "#ffffff",
  1104. bgColor: "",
  1105. message: "",
  1106. duration: 3e3,
  1107. fontSize: 15,
  1108. safeAreaInsetTop: false
  1109. }
  1110. };
  1111. const NumberBox = {
  1112. // 步进器组件
  1113. numberBox: {
  1114. name: "",
  1115. value: 0,
  1116. min: 1,
  1117. max: Number.MAX_SAFE_INTEGER,
  1118. step: 1,
  1119. integer: false,
  1120. disabled: false,
  1121. disabledInput: false,
  1122. asyncChange: false,
  1123. inputWidth: 35,
  1124. showMinus: true,
  1125. showPlus: true,
  1126. decimalLength: null,
  1127. longPress: true,
  1128. color: "#323233",
  1129. buttonSize: 30,
  1130. bgColor: "#EBECEE",
  1131. cursorSpacing: 100,
  1132. disableMinus: false,
  1133. disablePlus: false,
  1134. iconStyle: ""
  1135. }
  1136. };
  1137. const NumberKeyboard = {
  1138. // 数字键盘
  1139. numberKeyboard: {
  1140. mode: "number",
  1141. dotDisabled: false,
  1142. random: false
  1143. }
  1144. };
  1145. const Overlay = {
  1146. // overlay组件
  1147. overlay: {
  1148. show: false,
  1149. zIndex: 10070,
  1150. duration: 300,
  1151. opacity: 0.5
  1152. }
  1153. };
  1154. const Parse = {
  1155. // parse
  1156. parse: {
  1157. copyLink: true,
  1158. errorImg: "",
  1159. lazyLoad: false,
  1160. loadingImg: "",
  1161. pauseVideo: true,
  1162. previewImg: true,
  1163. setTitle: true,
  1164. showImgMenu: true
  1165. }
  1166. };
  1167. const Picker = {
  1168. // picker
  1169. picker: {
  1170. show: false,
  1171. popupMode: "bottom",
  1172. showToolbar: true,
  1173. title: "",
  1174. columns: [],
  1175. loading: false,
  1176. itemHeight: 44,
  1177. cancelText: "取消",
  1178. confirmText: "确定",
  1179. cancelColor: "#909193",
  1180. confirmColor: "#3c9cff",
  1181. visibleItemCount: 5,
  1182. keyName: "text",
  1183. closeOnClickOverlay: false,
  1184. defaultIndex: [],
  1185. immediateChange: false
  1186. }
  1187. };
  1188. const Popup = {
  1189. // popup组件
  1190. popup: {
  1191. show: false,
  1192. overlay: true,
  1193. mode: "bottom",
  1194. duration: 300,
  1195. closeable: false,
  1196. overlayStyle: {},
  1197. closeOnClickOverlay: true,
  1198. zIndex: 10075,
  1199. safeAreaInsetBottom: true,
  1200. safeAreaInsetTop: false,
  1201. closeIconPos: "top-right",
  1202. round: 0,
  1203. zoom: true,
  1204. bgColor: "",
  1205. overlayOpacity: 0.5
  1206. }
  1207. };
  1208. const Radio = {
  1209. // radio组件
  1210. radio: {
  1211. name: "",
  1212. shape: "",
  1213. disabled: "",
  1214. labelDisabled: "",
  1215. activeColor: "",
  1216. inactiveColor: "",
  1217. iconSize: "",
  1218. labelSize: "",
  1219. label: "",
  1220. labelColor: "",
  1221. size: "",
  1222. iconColor: "",
  1223. placement: ""
  1224. }
  1225. };
  1226. const RadioGroup = {
  1227. // radio-group组件
  1228. radioGroup: {
  1229. value: "",
  1230. disabled: false,
  1231. shape: "circle",
  1232. activeColor: "#2979ff",
  1233. inactiveColor: "#c8c9cc",
  1234. name: "",
  1235. size: 18,
  1236. placement: "row",
  1237. label: "",
  1238. labelColor: "#303133",
  1239. labelSize: 14,
  1240. labelDisabled: false,
  1241. iconColor: "#ffffff",
  1242. iconSize: 12,
  1243. borderBottom: false,
  1244. iconPlacement: "left"
  1245. }
  1246. };
  1247. const Rate = {
  1248. // rate组件
  1249. rate: {
  1250. value: 1,
  1251. count: 5,
  1252. disabled: false,
  1253. size: 18,
  1254. inactiveColor: "#b2b2b2",
  1255. activeColor: "#FA3534",
  1256. gutter: 4,
  1257. minCount: 1,
  1258. allowHalf: false,
  1259. activeIcon: "star-fill",
  1260. inactiveIcon: "star",
  1261. touchable: true
  1262. }
  1263. };
  1264. const ReadMore = {
  1265. // readMore
  1266. readMore: {
  1267. showHeight: 400,
  1268. toggle: false,
  1269. closeText: "展开阅读全文",
  1270. openText: "收起",
  1271. color: "#2979ff",
  1272. fontSize: 14,
  1273. textIndent: "2em",
  1274. name: ""
  1275. }
  1276. };
  1277. const Row$1 = {
  1278. // row
  1279. row: {
  1280. gutter: 0,
  1281. justify: "start",
  1282. align: "center"
  1283. }
  1284. };
  1285. const RowNotice = {
  1286. // rowNotice
  1287. rowNotice: {
  1288. text: "",
  1289. icon: "volume",
  1290. mode: "",
  1291. color: "#f9ae3d",
  1292. bgColor: "#fdf6ec",
  1293. fontSize: 14,
  1294. speed: 80
  1295. }
  1296. };
  1297. const ScrollList = {
  1298. // scrollList
  1299. scrollList: {
  1300. indicatorWidth: 50,
  1301. indicatorBarWidth: 20,
  1302. indicator: true,
  1303. indicatorColor: "#f2f2f2",
  1304. indicatorActiveColor: "#3c9cff",
  1305. indicatorStyle: ""
  1306. }
  1307. };
  1308. const Search = {
  1309. // search
  1310. search: {
  1311. shape: "round",
  1312. bgColor: "#f2f2f2",
  1313. placeholder: "请输入关键字",
  1314. clearabled: true,
  1315. focus: false,
  1316. showAction: true,
  1317. actionStyle: {},
  1318. actionText: "搜索",
  1319. inputAlign: "left",
  1320. inputStyle: {},
  1321. disabled: false,
  1322. borderColor: "transparent",
  1323. searchIconColor: "#909399",
  1324. searchIconSize: 22,
  1325. color: "#606266",
  1326. placeholderColor: "#909399",
  1327. searchIcon: "search",
  1328. margin: "0",
  1329. animation: false,
  1330. value: "",
  1331. maxlength: "-1",
  1332. height: 32,
  1333. label: null
  1334. }
  1335. };
  1336. const Section = {
  1337. // u-section组件
  1338. section: {
  1339. title: "",
  1340. subTitle: "更多",
  1341. right: true,
  1342. fontSize: 15,
  1343. bold: true,
  1344. color: "#303133",
  1345. subColor: "#909399",
  1346. showLine: true,
  1347. lineColor: "",
  1348. arrow: true
  1349. }
  1350. };
  1351. const Skeleton = {
  1352. // skeleton
  1353. skeleton: {
  1354. loading: true,
  1355. animate: true,
  1356. rows: 0,
  1357. rowsWidth: "100%",
  1358. rowsHeight: 18,
  1359. title: true,
  1360. titleWidth: "50%",
  1361. titleHeight: 18,
  1362. avatar: false,
  1363. avatarSize: 32,
  1364. avatarShape: "circle"
  1365. }
  1366. };
  1367. const Slider = {
  1368. // slider组件
  1369. slider: {
  1370. value: 0,
  1371. blockSize: 18,
  1372. min: 0,
  1373. max: 100,
  1374. step: 1,
  1375. activeColor: "#2979ff",
  1376. inactiveColor: "#c0c4cc",
  1377. blockColor: "#ffffff",
  1378. showValue: false,
  1379. disabled: false,
  1380. blockStyle: {}
  1381. }
  1382. };
  1383. const StatusBar = {
  1384. // statusBar
  1385. statusBar: {
  1386. bgColor: "transparent"
  1387. }
  1388. };
  1389. const Steps = {
  1390. // steps组件
  1391. steps: {
  1392. direction: "row",
  1393. current: 0,
  1394. activeColor: "#3c9cff",
  1395. inactiveColor: "#969799",
  1396. activeIcon: "",
  1397. inactiveIcon: "",
  1398. dot: false
  1399. }
  1400. };
  1401. const StepsItem = {
  1402. // steps-item组件
  1403. stepsItem: {
  1404. title: "",
  1405. desc: "",
  1406. iconSize: 17,
  1407. error: false
  1408. }
  1409. };
  1410. const Sticky = {
  1411. // sticky组件
  1412. sticky: {
  1413. offsetTop: 0,
  1414. customNavHeight: 0,
  1415. disabled: false,
  1416. bgColor: "transparent",
  1417. zIndex: "",
  1418. index: ""
  1419. }
  1420. };
  1421. const Subsection = {
  1422. // subsection组件
  1423. subsection: {
  1424. list: [],
  1425. current: 0,
  1426. activeColor: "#3c9cff",
  1427. inactiveColor: "#303133",
  1428. mode: "button",
  1429. fontSize: 12,
  1430. bold: true,
  1431. bgColor: "#eeeeef",
  1432. keyName: "name"
  1433. }
  1434. };
  1435. const SwipeAction = {
  1436. // swipe-action组件
  1437. swipeAction: {
  1438. autoClose: true
  1439. }
  1440. };
  1441. const SwipeActionItem = {
  1442. // swipeActionItem 组件
  1443. swipeActionItem: {
  1444. show: false,
  1445. name: "",
  1446. disabled: false,
  1447. threshold: 20,
  1448. autoClose: true,
  1449. options: [],
  1450. duration: 300
  1451. }
  1452. };
  1453. const Swiper = {
  1454. // swiper 组件
  1455. swiper: {
  1456. list: [],
  1457. indicator: false,
  1458. indicatorActiveColor: "#FFFFFF",
  1459. indicatorInactiveColor: "rgba(255, 255, 255, 0.35)",
  1460. indicatorStyle: "",
  1461. indicatorMode: "line",
  1462. autoplay: true,
  1463. current: 0,
  1464. currentItemId: "",
  1465. interval: 3e3,
  1466. duration: 300,
  1467. circular: false,
  1468. previousMargin: 0,
  1469. nextMargin: 0,
  1470. acceleration: false,
  1471. displayMultipleItems: 1,
  1472. easingFunction: "default",
  1473. keyName: "url",
  1474. imgMode: "aspectFill",
  1475. height: 130,
  1476. bgColor: "#f3f4f6",
  1477. radius: 4,
  1478. loading: false,
  1479. showTitle: false
  1480. }
  1481. };
  1482. const SwipterIndicator = {
  1483. // swiperIndicator 组件
  1484. swiperIndicator: {
  1485. length: 0,
  1486. current: 0,
  1487. indicatorActiveColor: "",
  1488. indicatorInactiveColor: "",
  1489. indicatorMode: "line"
  1490. }
  1491. };
  1492. const Switch = {
  1493. // switch
  1494. switch: {
  1495. loading: false,
  1496. disabled: false,
  1497. size: 25,
  1498. activeColor: "#2979ff",
  1499. inactiveColor: "#ffffff",
  1500. value: false,
  1501. activeValue: true,
  1502. inactiveValue: false,
  1503. asyncChange: false,
  1504. space: 0
  1505. }
  1506. };
  1507. const Tabbar = {
  1508. // tabbar
  1509. tabbar: {
  1510. value: null,
  1511. safeAreaInsetBottom: true,
  1512. border: true,
  1513. zIndex: 1,
  1514. activeColor: "#1989fa",
  1515. inactiveColor: "#7d7e80",
  1516. fixed: true,
  1517. placeholder: true
  1518. }
  1519. };
  1520. const TabbarItem = {
  1521. //
  1522. tabbarItem: {
  1523. name: null,
  1524. icon: "",
  1525. badge: null,
  1526. dot: false,
  1527. text: "",
  1528. badgeStyle: "top: 6px;right:2px;"
  1529. }
  1530. };
  1531. const Tabs = {
  1532. //
  1533. tabs: {
  1534. duration: 300,
  1535. list: [],
  1536. lineColor: "#3c9cff",
  1537. activeStyle: {
  1538. color: "#303133"
  1539. },
  1540. inactiveStyle: {
  1541. color: "#606266"
  1542. },
  1543. lineWidth: 20,
  1544. lineHeight: 3,
  1545. lineBgSize: "cover",
  1546. itemStyle: {
  1547. height: "44px"
  1548. },
  1549. scrollable: true,
  1550. current: 0,
  1551. keyName: "name"
  1552. }
  1553. };
  1554. const Tag = {
  1555. // tag 组件
  1556. tag: {
  1557. type: "primary",
  1558. disabled: false,
  1559. size: "medium",
  1560. shape: "square",
  1561. text: "",
  1562. bgColor: "",
  1563. color: "",
  1564. borderColor: "",
  1565. closeColor: "#C6C7CB",
  1566. name: "",
  1567. plainFill: false,
  1568. plain: false,
  1569. closable: false,
  1570. show: true,
  1571. icon: "",
  1572. iconColor: ""
  1573. }
  1574. };
  1575. const Text = {
  1576. // text 组件
  1577. text: {
  1578. type: "",
  1579. show: true,
  1580. text: "",
  1581. prefixIcon: "",
  1582. suffixIcon: "",
  1583. mode: "",
  1584. href: "",
  1585. format: "",
  1586. call: false,
  1587. openType: "",
  1588. bold: false,
  1589. block: false,
  1590. lines: "",
  1591. color: "#303133",
  1592. size: 15,
  1593. iconStyle: {
  1594. fontSize: "15px"
  1595. },
  1596. decoration: "none",
  1597. margin: 0,
  1598. lineHeight: "",
  1599. align: "left",
  1600. wordWrap: "normal"
  1601. }
  1602. };
  1603. const Textarea = {
  1604. // textarea 组件
  1605. textarea: {
  1606. value: "",
  1607. placeholder: "",
  1608. placeholderClass: "textarea-placeholder",
  1609. placeholderStyle: "color: #c0c4cc",
  1610. height: 70,
  1611. confirmType: "done",
  1612. disabled: false,
  1613. count: false,
  1614. focus: false,
  1615. autoHeight: false,
  1616. fixed: false,
  1617. cursorSpacing: 0,
  1618. cursor: "",
  1619. showConfirmBar: true,
  1620. selectionStart: -1,
  1621. selectionEnd: -1,
  1622. adjustPosition: true,
  1623. disableDefaultPadding: false,
  1624. holdKeyboard: false,
  1625. maxlength: 140,
  1626. border: "surround",
  1627. formatter: null
  1628. }
  1629. };
  1630. const Toast = {
  1631. // toast组件
  1632. toast: {
  1633. zIndex: 10090,
  1634. loading: false,
  1635. text: "",
  1636. icon: "",
  1637. type: "",
  1638. loadingMode: "",
  1639. show: "",
  1640. overlay: false,
  1641. position: "center",
  1642. params: {},
  1643. duration: 2e3,
  1644. isTab: false,
  1645. url: "",
  1646. callback: null,
  1647. back: false
  1648. }
  1649. };
  1650. const Toolbar = {
  1651. // toolbar 组件
  1652. toolbar: {
  1653. show: true,
  1654. cancelText: "取消",
  1655. confirmText: "确认",
  1656. cancelColor: "#909193",
  1657. confirmColor: "#3c9cff",
  1658. title: ""
  1659. }
  1660. };
  1661. const Tooltip = {
  1662. // tooltip 组件
  1663. tooltip: {
  1664. text: "",
  1665. copyText: "",
  1666. size: 14,
  1667. color: "#606266",
  1668. bgColor: "transparent",
  1669. direction: "top",
  1670. zIndex: 10071,
  1671. showCopy: true,
  1672. buttons: [],
  1673. overlay: true,
  1674. showToast: true
  1675. }
  1676. };
  1677. const Transition = {
  1678. // transition动画组件的props
  1679. transition: {
  1680. show: false,
  1681. mode: "fade",
  1682. duration: "300",
  1683. timingFunction: "ease-out"
  1684. }
  1685. };
  1686. const Upload = {
  1687. // upload组件
  1688. upload: {
  1689. accept: "image",
  1690. capture: ["album", "camera"],
  1691. compressed: true,
  1692. camera: "back",
  1693. maxDuration: 60,
  1694. uploadIcon: "camera-fill",
  1695. uploadIconColor: "#D3D4D6",
  1696. useBeforeRead: false,
  1697. previewFullImage: true,
  1698. maxCount: 52,
  1699. disabled: false,
  1700. imageMode: "aspectFill",
  1701. name: "",
  1702. sizeType: ["original", "compressed"],
  1703. multiple: false,
  1704. deletable: true,
  1705. maxSize: Number.MAX_VALUE,
  1706. fileList: [],
  1707. uploadText: "",
  1708. width: 80,
  1709. height: 80,
  1710. previewImage: true
  1711. }
  1712. };
  1713. const props$f = {
  1714. ...ActionSheet,
  1715. ...Album,
  1716. ...Alert,
  1717. ...Avatar,
  1718. ...AvatarGroup,
  1719. ...Backtop,
  1720. ...Badge,
  1721. ...Button,
  1722. ...Calendar,
  1723. ...CarKeyboard,
  1724. ...Cell,
  1725. ...CellGroup,
  1726. ...Checkbox,
  1727. ...CheckboxGroup,
  1728. ...CircleProgress,
  1729. ...Code,
  1730. ...CodeInput,
  1731. ...Col,
  1732. ...Collapse,
  1733. ...CollapseItem,
  1734. ...ColumnNotice,
  1735. ...CountDown,
  1736. ...CountTo,
  1737. ...DatetimePicker,
  1738. ...Divider,
  1739. ...Empty,
  1740. ...Form,
  1741. ...GormItem,
  1742. ...Gap,
  1743. ...Grid,
  1744. ...GridItem,
  1745. ...Icon,
  1746. ...Image,
  1747. ...IndexAnchor,
  1748. ...IndexList,
  1749. ...Input,
  1750. ...Keyboard,
  1751. ...Line,
  1752. ...LineProgress,
  1753. ...Link,
  1754. ...List,
  1755. ...ListItem,
  1756. ...LoadingIcon,
  1757. ...LoadingPage,
  1758. ...Loadmore,
  1759. ...Modal,
  1760. ...Navbar,
  1761. ...NoNetwork,
  1762. ...NoticeBar,
  1763. ...Notify,
  1764. ...NumberBox,
  1765. ...NumberKeyboard,
  1766. ...Overlay,
  1767. ...Parse,
  1768. ...Picker,
  1769. ...Popup,
  1770. ...Radio,
  1771. ...RadioGroup,
  1772. ...Rate,
  1773. ...ReadMore,
  1774. ...Row$1,
  1775. ...RowNotice,
  1776. ...ScrollList,
  1777. ...Search,
  1778. ...Section,
  1779. ...Skeleton,
  1780. ...Slider,
  1781. ...StatusBar,
  1782. ...Steps,
  1783. ...StepsItem,
  1784. ...Sticky,
  1785. ...Subsection,
  1786. ...SwipeAction,
  1787. ...SwipeActionItem,
  1788. ...Swiper,
  1789. ...SwipterIndicator,
  1790. ...Switch,
  1791. ...Tabbar,
  1792. ...TabbarItem,
  1793. ...Tabs,
  1794. ...Tag,
  1795. ...Text,
  1796. ...Textarea,
  1797. ...Toast,
  1798. ...Toolbar,
  1799. ...Tooltip,
  1800. ...Transition,
  1801. ...Upload
  1802. };
  1803. const props$e = {
  1804. props: {
  1805. // 图标类名
  1806. name: {
  1807. type: String,
  1808. default: () => props$f.icon.name
  1809. },
  1810. // 图标颜色,可接受主题色
  1811. color: {
  1812. type: String,
  1813. default: () => props$f.icon.color
  1814. },
  1815. // 字体大小,单位px
  1816. size: {
  1817. type: [String, Number],
  1818. default: () => props$f.icon.size
  1819. },
  1820. // 是否显示粗体
  1821. bold: {
  1822. type: Boolean,
  1823. default: () => props$f.icon.bold
  1824. },
  1825. // 点击图标的时候传递事件出去的index(用于区分点击了哪一个)
  1826. index: {
  1827. type: [String, Number],
  1828. default: () => props$f.icon.index
  1829. },
  1830. // 触摸图标时的类名
  1831. hoverClass: {
  1832. type: String,
  1833. default: () => props$f.icon.hoverClass
  1834. },
  1835. // 自定义扩展前缀,方便用户扩展自己的图标库
  1836. customPrefix: {
  1837. type: String,
  1838. default: () => props$f.icon.customPrefix
  1839. },
  1840. // 图标右边或者下面的文字
  1841. label: {
  1842. type: [String, Number],
  1843. default: () => props$f.icon.label
  1844. },
  1845. // label的位置,只能右边或者下边
  1846. labelPos: {
  1847. type: String,
  1848. default: () => props$f.icon.labelPos
  1849. },
  1850. // label的大小
  1851. labelSize: {
  1852. type: [String, Number],
  1853. default: () => props$f.icon.labelSize
  1854. },
  1855. // label的颜色
  1856. labelColor: {
  1857. type: String,
  1858. default: () => props$f.icon.labelColor
  1859. },
  1860. // label与图标的距离
  1861. space: {
  1862. type: [String, Number],
  1863. default: () => props$f.icon.space
  1864. },
  1865. // 图片的mode
  1866. imgMode: {
  1867. type: String,
  1868. default: () => props$f.icon.imgMode
  1869. },
  1870. // 用于显示图片小图标时,图片的宽度
  1871. width: {
  1872. type: [String, Number],
  1873. default: () => props$f.icon.width
  1874. },
  1875. // 用于显示图片小图标时,图片的高度
  1876. height: {
  1877. type: [String, Number],
  1878. default: () => props$f.icon.height
  1879. },
  1880. // 用于解决某些情况下,让图标垂直居中的用途
  1881. top: {
  1882. type: [String, Number],
  1883. default: () => props$f.icon.top
  1884. },
  1885. // 是否阻止事件传播
  1886. stop: {
  1887. type: Boolean,
  1888. default: () => props$f.icon.stop
  1889. }
  1890. }
  1891. };
  1892. const mpMixin = {};
  1893. function email(value2) {
  1894. return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(value2);
  1895. }
  1896. function mobile(value2) {
  1897. return /^1[23456789]\d{9}$/.test(value2);
  1898. }
  1899. function url(value2) {
  1900. return /^((https|http|ftp|rtsp|mms):\/\/)(([0-9a-zA-Z_!~*'().&=+$%-]+: )?[0-9a-zA-Z_!~*'().&=+$%-]+@)?(([0-9]{1,3}.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z].[a-zA-Z]{2,6})(:[0-9]{1,4})?((\/?)|(\/[0-9a-zA-Z_!~*'().;?:@&=+$,%#-]+)+\/?)$/.test(value2);
  1901. }
  1902. function date(value2) {
  1903. if (!value2)
  1904. return false;
  1905. if (number(value2))
  1906. value2 = +value2;
  1907. return !/Invalid|NaN/.test(new Date(value2).toString());
  1908. }
  1909. function dateISO(value2) {
  1910. return /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(value2);
  1911. }
  1912. function number(value2) {
  1913. return /^[\+-]?(\d+\.?\d*|\.\d+|\d\.\d+e\+\d+)$/.test(value2);
  1914. }
  1915. function string(value2) {
  1916. return typeof value2 === "string";
  1917. }
  1918. function digits(value2) {
  1919. return /^\d+$/.test(value2);
  1920. }
  1921. function idCard(value2) {
  1922. return /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(
  1923. value2
  1924. );
  1925. }
  1926. function carNo(value2) {
  1927. const xreg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;
  1928. const creg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
  1929. if (value2.length === 7) {
  1930. return creg.test(value2);
  1931. }
  1932. if (value2.length === 8) {
  1933. return xreg.test(value2);
  1934. }
  1935. return false;
  1936. }
  1937. function amount(value2) {
  1938. return /^[1-9]\d*(,\d{3})*(\.\d{1,2})?$|^0\.\d{1,2}$/.test(value2);
  1939. }
  1940. function chinese(value2) {
  1941. const reg = /^[\u4e00-\u9fa5]+$/gi;
  1942. return reg.test(value2);
  1943. }
  1944. function letter(value2) {
  1945. return /^[a-zA-Z]*$/.test(value2);
  1946. }
  1947. function enOrNum(value2) {
  1948. const reg = /^[0-9a-zA-Z]*$/g;
  1949. return reg.test(value2);
  1950. }
  1951. function contains(value2, param) {
  1952. return value2.indexOf(param) >= 0;
  1953. }
  1954. function range$1(value2, param) {
  1955. return value2 >= param[0] && value2 <= param[1];
  1956. }
  1957. function rangeLength(value2, param) {
  1958. return value2.length >= param[0] && value2.length <= param[1];
  1959. }
  1960. function landline(value2) {
  1961. const reg = /^\d{3,4}-\d{7,8}(-\d{3,4})?$/;
  1962. return reg.test(value2);
  1963. }
  1964. function empty(value2) {
  1965. switch (typeof value2) {
  1966. case "undefined":
  1967. return true;
  1968. case "string":
  1969. if (value2.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, "").length == 0)
  1970. return true;
  1971. break;
  1972. case "boolean":
  1973. if (!value2)
  1974. return true;
  1975. break;
  1976. case "number":
  1977. if (value2 === 0 || isNaN(value2))
  1978. return true;
  1979. break;
  1980. case "object":
  1981. if (value2 === null || value2.length === 0)
  1982. return true;
  1983. for (const i2 in value2) {
  1984. return false;
  1985. }
  1986. return true;
  1987. }
  1988. return false;
  1989. }
  1990. function jsonString(value2) {
  1991. if (typeof value2 === "string") {
  1992. try {
  1993. const obj = JSON.parse(value2);
  1994. if (typeof obj === "object" && obj) {
  1995. return true;
  1996. }
  1997. return false;
  1998. } catch (e2) {
  1999. return false;
  2000. }
  2001. }
  2002. return false;
  2003. }
  2004. function array(value2) {
  2005. if (typeof Array.isArray === "function") {
  2006. return Array.isArray(value2);
  2007. }
  2008. return Object.prototype.toString.call(value2) === "[object Array]";
  2009. }
  2010. function object(value2) {
  2011. return Object.prototype.toString.call(value2) === "[object Object]";
  2012. }
  2013. function code(value2, len = 6) {
  2014. return new RegExp(`^\\d{${len}}$`).test(value2);
  2015. }
  2016. function func(value2) {
  2017. return typeof value2 === "function";
  2018. }
  2019. function promise(value2) {
  2020. return object(value2) && func(value2.then) && func(value2.catch);
  2021. }
  2022. function image(value2) {
  2023. const newValue = value2.split("?")[0];
  2024. const IMAGE_REGEXP = /\.(jpeg|jpg|gif|png|svg|webp|jfif|bmp|dpg)/i;
  2025. return IMAGE_REGEXP.test(newValue);
  2026. }
  2027. function video(value2) {
  2028. const VIDEO_REGEXP = /\.(mp4|mpg|mpeg|dat|asf|avi|rm|rmvb|mov|wmv|flv|mkv|m3u8)/i;
  2029. return VIDEO_REGEXP.test(value2);
  2030. }
  2031. function regExp(o2) {
  2032. return o2 && Object.prototype.toString.call(o2) === "[object RegExp]";
  2033. }
  2034. const test = {
  2035. email,
  2036. mobile,
  2037. url,
  2038. date,
  2039. dateISO,
  2040. number,
  2041. digits,
  2042. idCard,
  2043. carNo,
  2044. amount,
  2045. chinese,
  2046. letter,
  2047. enOrNum,
  2048. contains,
  2049. range: range$1,
  2050. rangeLength,
  2051. empty,
  2052. isEmpty: empty,
  2053. jsonString,
  2054. landline,
  2055. object,
  2056. array,
  2057. code,
  2058. func,
  2059. promise,
  2060. video,
  2061. image,
  2062. regExp,
  2063. string
  2064. };
  2065. function strip(num, precision = 15) {
  2066. return +parseFloat(Number(num).toPrecision(precision));
  2067. }
  2068. function digitLength(num) {
  2069. const eSplit = num.toString().split(/[eE]/);
  2070. const len = (eSplit[0].split(".")[1] || "").length - +(eSplit[1] || 0);
  2071. return len > 0 ? len : 0;
  2072. }
  2073. function float2Fixed(num) {
  2074. if (num.toString().indexOf("e") === -1) {
  2075. return Number(num.toString().replace(".", ""));
  2076. }
  2077. const dLen = digitLength(num);
  2078. return dLen > 0 ? strip(Number(num) * Math.pow(10, dLen)) : Number(num);
  2079. }
  2080. function checkBoundary(num) {
  2081. {
  2082. if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
  2083. formatAppLog("warn", "at uni_modules/uview-plus/libs/function/digit.js:45", `${num} 超出了精度限制,结果可能不正确`);
  2084. }
  2085. }
  2086. }
  2087. function iteratorOperation(arr, operation) {
  2088. const [num1, num2, ...others] = arr;
  2089. let res = operation(num1, num2);
  2090. others.forEach((num) => {
  2091. res = operation(res, num);
  2092. });
  2093. return res;
  2094. }
  2095. function times(...nums) {
  2096. if (nums.length > 2) {
  2097. return iteratorOperation(nums, times);
  2098. }
  2099. const [num1, num2] = nums;
  2100. const num1Changed = float2Fixed(num1);
  2101. const num2Changed = float2Fixed(num2);
  2102. const baseNum = digitLength(num1) + digitLength(num2);
  2103. const leftValue = num1Changed * num2Changed;
  2104. checkBoundary(leftValue);
  2105. return leftValue / Math.pow(10, baseNum);
  2106. }
  2107. function divide(...nums) {
  2108. if (nums.length > 2) {
  2109. return iteratorOperation(nums, divide);
  2110. }
  2111. const [num1, num2] = nums;
  2112. const num1Changed = float2Fixed(num1);
  2113. const num2Changed = float2Fixed(num2);
  2114. checkBoundary(num1Changed);
  2115. checkBoundary(num2Changed);
  2116. return times(num1Changed / num2Changed, strip(Math.pow(10, digitLength(num2) - digitLength(num1))));
  2117. }
  2118. function round(num, ratio) {
  2119. const base = Math.pow(10, ratio);
  2120. let result = divide(Math.round(Math.abs(times(num, base))), base);
  2121. if (num < 0 && result !== 0) {
  2122. result = times(result, -1);
  2123. }
  2124. return result;
  2125. }
  2126. function range(min = 0, max = 0, value2 = 0) {
  2127. return Math.max(min, Math.min(max, Number(value2)));
  2128. }
  2129. function getPx(value2, unit = false) {
  2130. if (number(value2)) {
  2131. return unit ? `${value2}px` : Number(value2);
  2132. }
  2133. if (/(rpx|upx)$/.test(value2)) {
  2134. return unit ? `${uni.rpx2px(parseInt(value2))}px` : Number(uni.rpx2px(parseInt(value2)));
  2135. }
  2136. return unit ? `${parseInt(value2)}px` : parseInt(value2);
  2137. }
  2138. function sleep(value2 = 30) {
  2139. return new Promise((resolve) => {
  2140. setTimeout(() => {
  2141. resolve();
  2142. }, value2);
  2143. });
  2144. }
  2145. function os$1() {
  2146. return uni.getSystemInfoSync().platform.toLowerCase();
  2147. }
  2148. function sys() {
  2149. return uni.getSystemInfoSync();
  2150. }
  2151. function random(min, max) {
  2152. if (min >= 0 && max > 0 && max >= min) {
  2153. const gab = max - min + 1;
  2154. return Math.floor(Math.random() * gab + min);
  2155. }
  2156. return 0;
  2157. }
  2158. function guid(len = 32, firstU = true, radix = null) {
  2159. const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  2160. const uuid2 = [];
  2161. radix = radix || chars.length;
  2162. if (len) {
  2163. for (let i2 = 0; i2 < len; i2++)
  2164. uuid2[i2] = chars[0 | Math.random() * radix];
  2165. } else {
  2166. let r2;
  2167. uuid2[8] = uuid2[13] = uuid2[18] = uuid2[23] = "-";
  2168. uuid2[14] = "4";
  2169. for (let i2 = 0; i2 < 36; i2++) {
  2170. if (!uuid2[i2]) {
  2171. r2 = 0 | Math.random() * 16;
  2172. uuid2[i2] = chars[i2 == 19 ? r2 & 3 | 8 : r2];
  2173. }
  2174. }
  2175. }
  2176. if (firstU) {
  2177. uuid2.shift();
  2178. return `u${uuid2.join("")}`;
  2179. }
  2180. return uuid2.join("");
  2181. }
  2182. function $parent(name = void 0) {
  2183. let parent = this.$parent;
  2184. while (parent) {
  2185. if (parent.$options && parent.$options.name !== name) {
  2186. parent = parent.$parent;
  2187. } else {
  2188. return parent;
  2189. }
  2190. }
  2191. return false;
  2192. }
  2193. function addStyle(customStyle, target = "object") {
  2194. if (empty(customStyle) || typeof customStyle === "object" && target === "object" || target === "string" && typeof customStyle === "string") {
  2195. return customStyle;
  2196. }
  2197. if (target === "object") {
  2198. customStyle = trim(customStyle);
  2199. const styleArray = customStyle.split(";");
  2200. const style = {};
  2201. for (let i2 = 0; i2 < styleArray.length; i2++) {
  2202. if (styleArray[i2]) {
  2203. const item = styleArray[i2].split(":");
  2204. style[trim(item[0])] = trim(item[1]);
  2205. }
  2206. }
  2207. return style;
  2208. }
  2209. let string2 = "";
  2210. if (typeof customStyle === "object") {
  2211. customStyle.forEach((val, i2) => {
  2212. const key = i2.replace(/([A-Z])/g, "-$1").toLowerCase();
  2213. string2 += `${key}:${val};`;
  2214. });
  2215. }
  2216. return trim(string2);
  2217. }
  2218. function addUnit(value2 = "auto", unit = "") {
  2219. if (!unit) {
  2220. unit = config$1.unit || "px";
  2221. }
  2222. value2 = String(value2);
  2223. return number(value2) ? `${value2}${unit}` : value2;
  2224. }
  2225. function deepClone(obj) {
  2226. if ([null, void 0, NaN, false].includes(obj))
  2227. return obj;
  2228. if (typeof obj !== "object" && typeof obj !== "function") {
  2229. return obj;
  2230. }
  2231. const o2 = array(obj) ? [] : {};
  2232. for (const i2 in obj) {
  2233. if (obj.hasOwnProperty(i2)) {
  2234. o2[i2] = typeof obj[i2] === "object" ? deepClone(obj[i2]) : obj[i2];
  2235. }
  2236. }
  2237. return o2;
  2238. }
  2239. function deepMerge$1(targetOrigin = {}, source = {}) {
  2240. let target = deepClone(targetOrigin);
  2241. if (typeof target !== "object" || typeof source !== "object")
  2242. return false;
  2243. for (const prop in source) {
  2244. if (!source.hasOwnProperty(prop))
  2245. continue;
  2246. if (prop in target) {
  2247. if (source[prop] == null) {
  2248. target[prop] = source[prop];
  2249. } else if (typeof target[prop] !== "object") {
  2250. target[prop] = source[prop];
  2251. } else if (typeof source[prop] !== "object") {
  2252. target[prop] = source[prop];
  2253. } else if (target[prop].concat && source[prop].concat) {
  2254. target[prop] = target[prop].concat(source[prop]);
  2255. } else {
  2256. target[prop] = deepMerge$1(target[prop], source[prop]);
  2257. }
  2258. } else {
  2259. target[prop] = source[prop];
  2260. }
  2261. }
  2262. return target;
  2263. }
  2264. function shallowMerge(target, source = {}) {
  2265. if (typeof target !== "object" || typeof source !== "object")
  2266. return false;
  2267. for (const prop in source) {
  2268. if (!source.hasOwnProperty(prop))
  2269. continue;
  2270. if (prop in target) {
  2271. if (source[prop] == null) {
  2272. target[prop] = source[prop];
  2273. } else if (typeof target[prop] !== "object") {
  2274. target[prop] = source[prop];
  2275. } else if (typeof source[prop] !== "object") {
  2276. target[prop] = source[prop];
  2277. } else if (target[prop].concat && source[prop].concat) {
  2278. target[prop] = target[prop].concat(source[prop]);
  2279. } else {
  2280. target[prop] = shallowMerge(target[prop], source[prop]);
  2281. }
  2282. } else {
  2283. target[prop] = source[prop];
  2284. }
  2285. }
  2286. return target;
  2287. }
  2288. function error(err) {
  2289. {
  2290. formatAppLog("error", "at uni_modules/uview-plus/libs/function/index.js:275", `uView提示:${err}`);
  2291. }
  2292. }
  2293. function randomArray(array2 = []) {
  2294. return array2.sort(() => Math.random() - 0.5);
  2295. }
  2296. if (!String.prototype.padStart) {
  2297. String.prototype.padStart = function(maxLength, fillString = " ") {
  2298. if (Object.prototype.toString.call(fillString) !== "[object String]") {
  2299. throw new TypeError(
  2300. "fillString must be String"
  2301. );
  2302. }
  2303. const str = this;
  2304. if (str.length >= maxLength)
  2305. return String(str);
  2306. const fillLength = maxLength - str.length;
  2307. let times2 = Math.ceil(fillLength / fillString.length);
  2308. while (times2 >>= 1) {
  2309. fillString += fillString;
  2310. if (times2 === 1) {
  2311. fillString += fillString;
  2312. }
  2313. }
  2314. return fillString.slice(0, fillLength) + str;
  2315. };
  2316. }
  2317. function timeFormat(dateTime = null, formatStr = "yyyy-mm-dd") {
  2318. let date2;
  2319. if (!dateTime) {
  2320. date2 = /* @__PURE__ */ new Date();
  2321. } else if (/^\d{10}$/.test(dateTime.toString().trim())) {
  2322. date2 = new Date(dateTime * 1e3);
  2323. } else if (typeof dateTime === "string" && /^\d+$/.test(dateTime.trim())) {
  2324. date2 = new Date(Number(dateTime));
  2325. } else {
  2326. date2 = new Date(
  2327. typeof dateTime === "string" ? dateTime.replace(/-/g, "/") : dateTime
  2328. );
  2329. }
  2330. const timeSource = {
  2331. "y": date2.getFullYear().toString(),
  2332. // 年
  2333. "m": (date2.getMonth() + 1).toString().padStart(2, "0"),
  2334. // 月
  2335. "d": date2.getDate().toString().padStart(2, "0"),
  2336. // 日
  2337. "h": date2.getHours().toString().padStart(2, "0"),
  2338. // 时
  2339. "M": date2.getMinutes().toString().padStart(2, "0"),
  2340. // 分
  2341. "s": date2.getSeconds().toString().padStart(2, "0")
  2342. // 秒
  2343. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  2344. };
  2345. for (const key in timeSource) {
  2346. const [ret] = new RegExp(`${key}+`).exec(formatStr) || [];
  2347. if (ret) {
  2348. const beginIndex = key === "y" && ret.length === 2 ? 2 : 0;
  2349. formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex));
  2350. }
  2351. }
  2352. return formatStr;
  2353. }
  2354. function timeFrom(timestamp = null, format2 = "yyyy-mm-dd") {
  2355. if (timestamp == null)
  2356. timestamp = Number(/* @__PURE__ */ new Date());
  2357. timestamp = parseInt(timestamp);
  2358. if (timestamp.toString().length == 10)
  2359. timestamp *= 1e3;
  2360. let timer = (/* @__PURE__ */ new Date()).getTime() - timestamp;
  2361. timer = parseInt(timer / 1e3);
  2362. let tips = "";
  2363. switch (true) {
  2364. case timer < 300:
  2365. tips = "刚刚";
  2366. break;
  2367. case (timer >= 300 && timer < 3600):
  2368. tips = `${parseInt(timer / 60)}分钟前`;
  2369. break;
  2370. case (timer >= 3600 && timer < 86400):
  2371. tips = `${parseInt(timer / 3600)}小时前`;
  2372. break;
  2373. case (timer >= 86400 && timer < 2592e3):
  2374. tips = `${parseInt(timer / 86400)}天前`;
  2375. break;
  2376. default:
  2377. if (format2 === false) {
  2378. if (timer >= 2592e3 && timer < 365 * 86400) {
  2379. tips = `${parseInt(timer / (86400 * 30))}个月前`;
  2380. } else {
  2381. tips = `${parseInt(timer / (86400 * 365))}年前`;
  2382. }
  2383. } else {
  2384. tips = timeFormat(timestamp, format2);
  2385. }
  2386. }
  2387. return tips;
  2388. }
  2389. function trim(str, pos = "both") {
  2390. str = String(str);
  2391. if (pos == "both") {
  2392. return str.replace(/^\s+|\s+$/g, "");
  2393. }
  2394. if (pos == "left") {
  2395. return str.replace(/^\s*/, "");
  2396. }
  2397. if (pos == "right") {
  2398. return str.replace(/(\s*$)/g, "");
  2399. }
  2400. if (pos == "all") {
  2401. return str.replace(/\s+/g, "");
  2402. }
  2403. return str;
  2404. }
  2405. function queryParams(data = {}, isPrefix = true, arrayFormat = "brackets") {
  2406. const prefix = isPrefix ? "?" : "";
  2407. const _result = [];
  2408. if (["indices", "brackets", "repeat", "comma"].indexOf(arrayFormat) == -1)
  2409. arrayFormat = "brackets";
  2410. for (const key in data) {
  2411. const value2 = data[key];
  2412. if (["", void 0, null].indexOf(value2) >= 0) {
  2413. continue;
  2414. }
  2415. if (value2.constructor === Array) {
  2416. switch (arrayFormat) {
  2417. case "indices":
  2418. for (let i2 = 0; i2 < value2.length; i2++) {
  2419. _result.push(`${key}[${i2}]=${value2[i2]}`);
  2420. }
  2421. break;
  2422. case "brackets":
  2423. value2.forEach((_value) => {
  2424. _result.push(`${key}[]=${_value}`);
  2425. });
  2426. break;
  2427. case "repeat":
  2428. value2.forEach((_value) => {
  2429. _result.push(`${key}=${_value}`);
  2430. });
  2431. break;
  2432. case "comma":
  2433. let commaStr = "";
  2434. value2.forEach((_value) => {
  2435. commaStr += (commaStr ? "," : "") + _value;
  2436. });
  2437. _result.push(`${key}=${commaStr}`);
  2438. break;
  2439. default:
  2440. value2.forEach((_value) => {
  2441. _result.push(`${key}[]=${_value}`);
  2442. });
  2443. }
  2444. } else {
  2445. _result.push(`${key}=${value2}`);
  2446. }
  2447. }
  2448. return _result.length ? prefix + _result.join("&") : "";
  2449. }
  2450. function toast(title, duration = 2e3) {
  2451. uni.showToast({
  2452. title: String(title),
  2453. icon: "none",
  2454. duration
  2455. });
  2456. }
  2457. function type2icon(type = "success", fill = false) {
  2458. if (["primary", "info", "error", "warning", "success"].indexOf(type) == -1)
  2459. type = "success";
  2460. let iconName = "";
  2461. switch (type) {
  2462. case "primary":
  2463. iconName = "info-circle";
  2464. break;
  2465. case "info":
  2466. iconName = "info-circle";
  2467. break;
  2468. case "error":
  2469. iconName = "close-circle";
  2470. break;
  2471. case "warning":
  2472. iconName = "error-circle";
  2473. break;
  2474. case "success":
  2475. iconName = "checkmark-circle";
  2476. break;
  2477. default:
  2478. iconName = "checkmark-circle";
  2479. }
  2480. if (fill)
  2481. iconName += "-fill";
  2482. return iconName;
  2483. }
  2484. function priceFormat(number2, decimals = 0, decimalPoint = ".", thousandsSeparator = ",") {
  2485. number2 = `${number2}`.replace(/[^0-9+-Ee.]/g, "");
  2486. const n2 = !isFinite(+number2) ? 0 : +number2;
  2487. const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
  2488. const sep = typeof thousandsSeparator === "undefined" ? "," : thousandsSeparator;
  2489. const dec = typeof decimalPoint === "undefined" ? "." : decimalPoint;
  2490. let s2 = "";
  2491. s2 = (prec ? round(n2, prec) + "" : `${Math.round(n2)}`).split(".");
  2492. const re2 = /(-?\d+)(\d{3})/;
  2493. while (re2.test(s2[0])) {
  2494. s2[0] = s2[0].replace(re2, `$1${sep}$2`);
  2495. }
  2496. if ((s2[1] || "").length < prec) {
  2497. s2[1] = s2[1] || "";
  2498. s2[1] += new Array(prec - s2[1].length + 1).join("0");
  2499. }
  2500. return s2.join(dec);
  2501. }
  2502. function getDuration(value2, unit = true) {
  2503. const valueNum = parseInt(value2);
  2504. if (unit) {
  2505. if (/s$/.test(value2))
  2506. return value2;
  2507. return value2 > 30 ? `${value2}ms` : `${value2}s`;
  2508. }
  2509. if (/ms$/.test(value2))
  2510. return valueNum;
  2511. if (/s$/.test(value2))
  2512. return valueNum > 30 ? valueNum : valueNum * 1e3;
  2513. return valueNum;
  2514. }
  2515. function padZero(value2) {
  2516. return `00${value2}`.slice(-2);
  2517. }
  2518. function formValidate(instance, event) {
  2519. const formItem = $parent.call(instance, "u-form-item");
  2520. const form = $parent.call(instance, "u-form");
  2521. if (formItem && form) {
  2522. form.validateField(formItem.prop, () => {
  2523. }, event);
  2524. }
  2525. }
  2526. function getProperty(obj, key) {
  2527. if (typeof obj !== "object" || null == obj) {
  2528. return "";
  2529. }
  2530. if (typeof key !== "string" || key === "") {
  2531. return "";
  2532. }
  2533. if (key.indexOf(".") !== -1) {
  2534. const keys = key.split(".");
  2535. let firstObj = obj[keys[0]] || {};
  2536. for (let i2 = 1; i2 < keys.length; i2++) {
  2537. if (firstObj) {
  2538. firstObj = firstObj[keys[i2]];
  2539. }
  2540. }
  2541. return firstObj;
  2542. }
  2543. return obj[key];
  2544. }
  2545. function setProperty(obj, key, value2) {
  2546. if (typeof obj !== "object" || null == obj) {
  2547. return;
  2548. }
  2549. const inFn = function(_obj, keys, v2) {
  2550. if (keys.length === 1) {
  2551. _obj[keys[0]] = v2;
  2552. return;
  2553. }
  2554. while (keys.length > 1) {
  2555. const k = keys[0];
  2556. if (!_obj[k] || typeof _obj[k] !== "object") {
  2557. _obj[k] = {};
  2558. }
  2559. keys.shift();
  2560. inFn(_obj[k], keys, v2);
  2561. }
  2562. };
  2563. if (typeof key !== "string" || key === "")
  2564. ;
  2565. else if (key.indexOf(".") !== -1) {
  2566. const keys = key.split(".");
  2567. inFn(obj, keys, value2);
  2568. } else {
  2569. obj[key] = value2;
  2570. }
  2571. }
  2572. function page() {
  2573. const pages2 = getCurrentPages();
  2574. return `/${pages2[pages2.length - 1].route || ""}`;
  2575. }
  2576. function pages$1() {
  2577. const pages2 = getCurrentPages();
  2578. return pages2;
  2579. }
  2580. const index = {
  2581. range,
  2582. getPx,
  2583. sleep,
  2584. os: os$1,
  2585. sys,
  2586. random,
  2587. guid,
  2588. $parent,
  2589. addStyle,
  2590. addUnit,
  2591. deepClone,
  2592. deepMerge: deepMerge$1,
  2593. shallowMerge,
  2594. error,
  2595. randomArray,
  2596. timeFormat,
  2597. timeFrom,
  2598. trim,
  2599. queryParams,
  2600. toast,
  2601. type2icon,
  2602. priceFormat,
  2603. getDuration,
  2604. padZero,
  2605. formValidate,
  2606. getProperty,
  2607. setProperty,
  2608. page,
  2609. pages: pages$1
  2610. // setConfig
  2611. };
  2612. class Router {
  2613. constructor() {
  2614. this.config = {
  2615. type: "navigateTo",
  2616. url: "",
  2617. delta: 1,
  2618. // navigateBack页面后退时,回退的层数
  2619. params: {},
  2620. // 传递的参数
  2621. animationType: "pop-in",
  2622. // 窗口动画,只在APP有效
  2623. animationDuration: 300,
  2624. // 窗口动画持续时间,单位毫秒,只在APP有效
  2625. intercept: false
  2626. // 是否需要拦截
  2627. };
  2628. this.route = this.route.bind(this);
  2629. }
  2630. // 判断url前面是否有"/",如果没有则加上,否则无法跳转
  2631. addRootPath(url2) {
  2632. return url2[0] === "/" ? url2 : `/${url2}`;
  2633. }
  2634. // 整合路由参数
  2635. mixinParam(url2, params) {
  2636. url2 = url2 && this.addRootPath(url2);
  2637. let query = "";
  2638. if (/.*\/.*\?.*=.*/.test(url2)) {
  2639. query = queryParams(params, false);
  2640. return url2 += `&${query}`;
  2641. }
  2642. query = queryParams(params);
  2643. return url2 += query;
  2644. }
  2645. // 对外的方法名称
  2646. async route(options = {}, params = {}) {
  2647. let mergeConfig2 = {};
  2648. if (typeof options === "string") {
  2649. mergeConfig2.url = this.mixinParam(options, params);
  2650. mergeConfig2.type = "navigateTo";
  2651. } else {
  2652. mergeConfig2 = deepMerge$1(this.config, options);
  2653. mergeConfig2.url = this.mixinParam(options.url, options.params);
  2654. }
  2655. if (mergeConfig2.url === page())
  2656. return;
  2657. if (params.intercept) {
  2658. this.config.intercept = params.intercept;
  2659. }
  2660. mergeConfig2.params = params;
  2661. mergeConfig2 = deepMerge$1(this.config, mergeConfig2);
  2662. if (typeof uni.$u.routeIntercept === "function") {
  2663. const isNext = await new Promise((resolve, reject) => {
  2664. uni.$u.routeIntercept(mergeConfig2, resolve);
  2665. });
  2666. isNext && this.openPage(mergeConfig2);
  2667. } else {
  2668. this.openPage(mergeConfig2);
  2669. }
  2670. }
  2671. // 执行路由跳转
  2672. openPage(config2) {
  2673. const {
  2674. url: url2,
  2675. type,
  2676. delta,
  2677. animationType,
  2678. animationDuration
  2679. } = config2;
  2680. if (config2.type == "navigateTo" || config2.type == "to") {
  2681. uni.navigateTo({
  2682. url: url2,
  2683. animationType,
  2684. animationDuration
  2685. });
  2686. }
  2687. if (config2.type == "redirectTo" || config2.type == "redirect") {
  2688. uni.redirectTo({
  2689. url: url2
  2690. });
  2691. }
  2692. if (config2.type == "switchTab" || config2.type == "tab") {
  2693. uni.switchTab({
  2694. url: url2
  2695. });
  2696. }
  2697. if (config2.type == "reLaunch" || config2.type == "launch") {
  2698. uni.reLaunch({
  2699. url: url2
  2700. });
  2701. }
  2702. if (config2.type == "navigateBack" || config2.type == "back") {
  2703. uni.navigateBack({
  2704. delta
  2705. });
  2706. }
  2707. }
  2708. }
  2709. const route = new Router().route;
  2710. const mixin$1 = {
  2711. // 定义每个组件都可能需要用到的外部样式以及类名
  2712. props: {
  2713. // 每个组件都有的父组件传递的样式,可以为字符串或者对象形式
  2714. customStyle: {
  2715. type: [Object, String],
  2716. default: () => ({})
  2717. },
  2718. customClass: {
  2719. type: String,
  2720. default: ""
  2721. },
  2722. // 跳转的页面路径
  2723. url: {
  2724. type: String,
  2725. default: ""
  2726. },
  2727. // 页面跳转的类型
  2728. linkType: {
  2729. type: String,
  2730. default: "navigateTo"
  2731. }
  2732. },
  2733. data() {
  2734. return {};
  2735. },
  2736. onLoad() {
  2737. this.$u.getRect = this.$uGetRect;
  2738. },
  2739. created() {
  2740. this.$u.getRect = this.$uGetRect;
  2741. },
  2742. computed: {
  2743. // 在2.x版本中,将会把$u挂载到uni对象下,导致在模板中无法使用uni.$u.xxx形式
  2744. // 所以这里通过computed计算属性将其附加到this.$u上,就可以在模板或者js中使用uni.$u.xxx
  2745. // 只在nvue环境通过此方式引入完整的$u,其他平台会出现性能问题,非nvue则按需引入(主要原因是props过大)
  2746. $u() {
  2747. return deepMerge$1(uni.$u, {
  2748. props: void 0,
  2749. http: void 0,
  2750. mixin: void 0
  2751. });
  2752. },
  2753. /**
  2754. * 生成bem规则类名
  2755. * 由于微信小程序,H5,nvue之间绑定class的差异,无法通过:class="[bem()]"的形式进行同用
  2756. * 故采用如下折中做法,最后返回的是数组(一般平台)或字符串(支付宝和字节跳动平台),类似['a', 'b', 'c']或'a b c'的形式
  2757. * @param {String} name 组件名称
  2758. * @param {Array} fixed 一直会存在的类名
  2759. * @param {Array} change 会根据变量值为true或者false而出现或者隐藏的类名
  2760. * @returns {Array|string}
  2761. */
  2762. bem() {
  2763. return function(name, fixed, change) {
  2764. const prefix = `u-${name}--`;
  2765. const classes = {};
  2766. if (fixed) {
  2767. fixed.map((item) => {
  2768. classes[prefix + this[item]] = true;
  2769. });
  2770. }
  2771. if (change) {
  2772. change.map((item) => {
  2773. this[item] ? classes[prefix + item] = this[item] : delete classes[prefix + item];
  2774. });
  2775. }
  2776. return Object.keys(classes);
  2777. };
  2778. }
  2779. },
  2780. methods: {
  2781. // 跳转某一个页面
  2782. openPage(urlKey = "url") {
  2783. const url2 = this[urlKey];
  2784. if (url2) {
  2785. route({ type: this.linkType, url: url2 });
  2786. }
  2787. },
  2788. // 查询节点信息
  2789. // 目前此方法在支付宝小程序中无法获取组件跟接点的尺寸,为支付宝的bug(2020-07-21)
  2790. // 解决办法为在组件根部再套一个没有任何作用的view元素
  2791. $uGetRect(selector, all) {
  2792. return new Promise((resolve) => {
  2793. uni.createSelectorQuery().in(this)[all ? "selectAll" : "select"](selector).boundingClientRect((rect) => {
  2794. if (all && Array.isArray(rect) && rect.length) {
  2795. resolve(rect);
  2796. }
  2797. if (!all && rect) {
  2798. resolve(rect);
  2799. }
  2800. }).exec();
  2801. });
  2802. },
  2803. getParentData(parentName = "") {
  2804. if (!this.parent)
  2805. this.parent = {};
  2806. this.parent = $parent.call(this, parentName);
  2807. if (this.parent.children) {
  2808. this.parent.children.indexOf(this) === -1 && this.parent.children.push(this);
  2809. }
  2810. if (this.parent && this.parentData) {
  2811. Object.keys(this.parentData).map((key) => {
  2812. this.parentData[key] = this.parent[key];
  2813. });
  2814. }
  2815. },
  2816. // 阻止事件冒泡
  2817. preventEvent(e2) {
  2818. e2 && typeof e2.stopPropagation === "function" && e2.stopPropagation();
  2819. },
  2820. // 空操作
  2821. noop(e2) {
  2822. this.preventEvent(e2);
  2823. }
  2824. },
  2825. onReachBottom() {
  2826. uni.$emit("uOnReachBottom");
  2827. },
  2828. beforeUnmount() {
  2829. if (this.parent && test.array(this.parent.children)) {
  2830. const childrenList = this.parent.children;
  2831. childrenList.map((child, index2) => {
  2832. if (child === this) {
  2833. childrenList.splice(index2, 1);
  2834. }
  2835. });
  2836. }
  2837. }
  2838. };
  2839. const _export_sfc = (sfc, props2) => {
  2840. const target = sfc.__vccOpts || sfc;
  2841. for (const [key, val] of props2) {
  2842. target[key] = val;
  2843. }
  2844. return target;
  2845. };
  2846. const _sfc_main$A = {
  2847. name: "u-icon",
  2848. data() {
  2849. return {};
  2850. },
  2851. emits: ["click"],
  2852. mixins: [mpMixin, mixin$1, props$e],
  2853. computed: {
  2854. uClasses() {
  2855. let classes = [];
  2856. classes.push(this.customPrefix + "-" + this.name);
  2857. if (this.customPrefix == "uicon") {
  2858. classes.push("u-iconfont");
  2859. } else {
  2860. classes.push(this.customPrefix);
  2861. }
  2862. if (this.color && config$1.type.includes(this.color))
  2863. classes.push("u-icon__icon--" + this.color);
  2864. return classes;
  2865. },
  2866. iconStyle() {
  2867. let style = {};
  2868. style = {
  2869. fontSize: addUnit(this.size),
  2870. lineHeight: addUnit(this.size),
  2871. fontWeight: this.bold ? "bold" : "normal",
  2872. // 某些特殊情况需要设置一个到顶部的距离,才能更好的垂直居中
  2873. top: addUnit(this.top)
  2874. };
  2875. if (this.color && !config$1.type.includes(this.color))
  2876. style.color = this.color;
  2877. return style;
  2878. },
  2879. // 判断传入的name属性,是否图片路径,只要带有"/"均认为是图片形式
  2880. isImg() {
  2881. return this.name.indexOf("/") !== -1;
  2882. },
  2883. imgStyle() {
  2884. let style = {};
  2885. style.width = this.width ? addUnit(this.width) : addUnit(this.size);
  2886. style.height = this.height ? addUnit(this.height) : addUnit(this.size);
  2887. return style;
  2888. },
  2889. // 通过图标名,查找对应的图标
  2890. icon() {
  2891. if (this.customPrefix !== "uicon")
  2892. return "";
  2893. return icons["uicon-" + this.name] || this.name;
  2894. }
  2895. },
  2896. methods: {
  2897. addStyle,
  2898. addUnit,
  2899. clickHandler(e2) {
  2900. this.$emit("click", this.index);
  2901. this.stop && this.preventEvent(e2);
  2902. }
  2903. }
  2904. };
  2905. function _sfc_render$z(_ctx, _cache, $props, $setup, $data, $options) {
  2906. return vue.openBlock(), vue.createElementBlock(
  2907. "view",
  2908. {
  2909. class: vue.normalizeClass(["u-icon", ["u-icon--" + _ctx.labelPos]]),
  2910. onClick: _cache[0] || (_cache[0] = (...args) => $options.clickHandler && $options.clickHandler(...args))
  2911. },
  2912. [
  2913. $options.isImg ? (vue.openBlock(), vue.createElementBlock("image", {
  2914. key: 0,
  2915. class: "u-icon__img",
  2916. src: _ctx.name,
  2917. mode: _ctx.imgMode,
  2918. style: vue.normalizeStyle([$options.imgStyle, $options.addStyle(_ctx.customStyle)])
  2919. }, null, 12, ["src", "mode"])) : (vue.openBlock(), vue.createElementBlock("text", {
  2920. key: 1,
  2921. class: vue.normalizeClass(["u-icon__icon", $options.uClasses]),
  2922. style: vue.normalizeStyle([$options.iconStyle, $options.addStyle(_ctx.customStyle)]),
  2923. "hover-class": _ctx.hoverClass
  2924. }, vue.toDisplayString($options.icon), 15, ["hover-class"])),
  2925. vue.createCommentVNode(' 这里进行空字符串判断,如果仅仅是v-if="label",可能会出现传递0的时候,结果也无法显示 '),
  2926. _ctx.label !== "" ? (vue.openBlock(), vue.createElementBlock(
  2927. "text",
  2928. {
  2929. key: 2,
  2930. class: "u-icon__label",
  2931. style: vue.normalizeStyle({
  2932. color: _ctx.labelColor,
  2933. fontSize: $options.addUnit(_ctx.labelSize),
  2934. marginLeft: _ctx.labelPos == "right" ? $options.addUnit(_ctx.space) : 0,
  2935. marginTop: _ctx.labelPos == "bottom" ? $options.addUnit(_ctx.space) : 0,
  2936. marginRight: _ctx.labelPos == "left" ? $options.addUnit(_ctx.space) : 0,
  2937. marginBottom: _ctx.labelPos == "top" ? $options.addUnit(_ctx.space) : 0
  2938. })
  2939. },
  2940. vue.toDisplayString(_ctx.label),
  2941. 5
  2942. /* TEXT, STYLE */
  2943. )) : vue.createCommentVNode("v-if", true)
  2944. ],
  2945. 2
  2946. /* CLASS */
  2947. );
  2948. }
  2949. const __easycom_0$4 = /* @__PURE__ */ _export_sfc(_sfc_main$A, [["render", _sfc_render$z], ["__scopeId", "data-v-ac70166d"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-icon/u-icon.vue"]]);
  2950. const props$d = {
  2951. props: {
  2952. // 是否展示组件
  2953. show: {
  2954. type: Boolean,
  2955. default: () => props$f.transition.show
  2956. },
  2957. // 使用的动画模式
  2958. mode: {
  2959. type: String,
  2960. default: () => props$f.transition.mode
  2961. },
  2962. // 动画的执行时间,单位ms
  2963. duration: {
  2964. type: [String, Number],
  2965. default: () => props$f.transition.duration
  2966. },
  2967. // 使用的动画过渡函数
  2968. timingFunction: {
  2969. type: String,
  2970. default: () => props$f.transition.timingFunction
  2971. }
  2972. }
  2973. };
  2974. const getClassNames = (name) => ({
  2975. enter: `u-${name}-enter u-${name}-enter-active`,
  2976. "enter-to": `u-${name}-enter-to u-${name}-enter-active`,
  2977. leave: `u-${name}-leave u-${name}-leave-active`,
  2978. "leave-to": `u-${name}-leave-to u-${name}-leave-active`
  2979. });
  2980. const transition = {
  2981. methods: {
  2982. // 组件被点击发出事件
  2983. clickHandler() {
  2984. this.$emit("click");
  2985. },
  2986. // vue版本的组件进场处理
  2987. async vueEnter() {
  2988. const classNames = getClassNames(this.mode);
  2989. this.status = "enter";
  2990. this.$emit("beforeEnter");
  2991. this.inited = true;
  2992. this.display = true;
  2993. this.classes = classNames.enter;
  2994. await vue.nextTick();
  2995. {
  2996. await sleep(20);
  2997. this.$emit("enter");
  2998. this.transitionEnded = false;
  2999. this.$emit("afterEnter");
  3000. this.classes = classNames["enter-to"];
  3001. }
  3002. },
  3003. // 动画离场处理
  3004. async vueLeave() {
  3005. if (!this.display)
  3006. return;
  3007. const classNames = getClassNames(this.mode);
  3008. this.status = "leave";
  3009. this.$emit("beforeLeave");
  3010. this.classes = classNames.leave;
  3011. await vue.nextTick();
  3012. {
  3013. this.transitionEnded = false;
  3014. this.$emit("leave");
  3015. setTimeout(this.onTransitionEnd, this.duration);
  3016. this.classes = classNames["leave-to"];
  3017. }
  3018. },
  3019. // 完成过渡后触发
  3020. onTransitionEnd() {
  3021. if (this.transitionEnded)
  3022. return;
  3023. this.transitionEnded = true;
  3024. this.$emit(this.status === "leave" ? "afterLeave" : "afterEnter");
  3025. if (!this.show && this.display) {
  3026. this.display = false;
  3027. this.inited = false;
  3028. }
  3029. }
  3030. }
  3031. };
  3032. const _sfc_main$z = {
  3033. name: "u-transition",
  3034. data() {
  3035. return {
  3036. inited: false,
  3037. // 是否显示/隐藏组件
  3038. viewStyle: {},
  3039. // 组件内部的样式
  3040. status: "",
  3041. // 记录组件动画的状态
  3042. transitionEnded: false,
  3043. // 组件是否结束的标记
  3044. display: false,
  3045. // 组件是否展示
  3046. classes: ""
  3047. // 应用的类名
  3048. };
  3049. },
  3050. emits: ["click", "beforeEnter", "enter", "afterEnter", "beforeLeave", "leave", "afterLeave"],
  3051. computed: {
  3052. mergeStyle() {
  3053. const { viewStyle, customStyle } = this;
  3054. return {
  3055. transitionDuration: `${this.duration}ms`,
  3056. // display: `${this.display ? '' : 'none'}`,
  3057. transitionTimingFunction: this.timingFunction,
  3058. // 避免自定义样式影响到动画属性,所以写在viewStyle前面
  3059. ...addStyle(customStyle),
  3060. ...viewStyle
  3061. };
  3062. }
  3063. },
  3064. // 将mixin挂在到组件中,实际上为一个vue格式对象。
  3065. mixins: [mpMixin, mixin$1, transition, props$d],
  3066. watch: {
  3067. show: {
  3068. handler(newVal) {
  3069. newVal ? this.vueEnter() : this.vueLeave();
  3070. },
  3071. // 表示同时监听初始化时的props的show的意思
  3072. immediate: true
  3073. }
  3074. }
  3075. };
  3076. function _sfc_render$y(_ctx, _cache, $props, $setup, $data, $options) {
  3077. return $data.inited ? (vue.openBlock(), vue.createElementBlock(
  3078. "view",
  3079. {
  3080. key: 0,
  3081. class: vue.normalizeClass(["u-transition", $data.classes]),
  3082. ref: "u-transition",
  3083. onClick: _cache[0] || (_cache[0] = (...args) => _ctx.clickHandler && _ctx.clickHandler(...args)),
  3084. style: vue.normalizeStyle([$options.mergeStyle]),
  3085. onTouchmove: _cache[1] || (_cache[1] = (...args) => _ctx.noop && _ctx.noop(...args))
  3086. },
  3087. [
  3088. vue.renderSlot(_ctx.$slots, "default", {}, void 0, true)
  3089. ],
  3090. 38
  3091. /* CLASS, STYLE, NEED_HYDRATION */
  3092. )) : vue.createCommentVNode("v-if", true);
  3093. }
  3094. const __easycom_1$6 = /* @__PURE__ */ _export_sfc(_sfc_main$z, [["render", _sfc_render$y], ["__scopeId", "data-v-5cec8177"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-transition/u-transition.vue"]]);
  3095. const props$c = {
  3096. props: {
  3097. // 是否显示遮罩
  3098. show: {
  3099. type: Boolean,
  3100. default: () => props$f.overlay.show
  3101. },
  3102. // 层级z-index
  3103. zIndex: {
  3104. type: [String, Number],
  3105. default: () => props$f.overlay.zIndex
  3106. },
  3107. // 遮罩的过渡时间,单位为ms
  3108. duration: {
  3109. type: [String, Number],
  3110. default: () => props$f.overlay.duration
  3111. },
  3112. // 不透明度值,当做rgba的第四个参数
  3113. opacity: {
  3114. type: [String, Number],
  3115. default: () => props$f.overlay.opacity
  3116. }
  3117. }
  3118. };
  3119. const _sfc_main$y = {
  3120. name: "u-overlay",
  3121. mixins: [mpMixin, mixin$1, props$c],
  3122. computed: {
  3123. overlayStyle() {
  3124. const style = {
  3125. position: "fixed",
  3126. top: 0,
  3127. left: 0,
  3128. right: 0,
  3129. zIndex: this.zIndex,
  3130. bottom: 0,
  3131. "background-color": `rgba(0, 0, 0, ${this.opacity})`
  3132. };
  3133. return deepMerge$1(style, addStyle(this.customStyle));
  3134. }
  3135. },
  3136. emits: ["click"],
  3137. methods: {
  3138. clickHandler() {
  3139. this.$emit("click");
  3140. }
  3141. }
  3142. };
  3143. function _sfc_render$x(_ctx, _cache, $props, $setup, $data, $options) {
  3144. const _component_u_transition = resolveEasycom(vue.resolveDynamicComponent("u-transition"), __easycom_1$6);
  3145. return vue.openBlock(), vue.createBlock(_component_u_transition, {
  3146. show: _ctx.show,
  3147. "custom-class": "u-overlay",
  3148. duration: _ctx.duration,
  3149. "custom-style": $options.overlayStyle,
  3150. onClick: $options.clickHandler
  3151. }, {
  3152. default: vue.withCtx(() => [
  3153. vue.renderSlot(_ctx.$slots, "default", {}, void 0, true)
  3154. ]),
  3155. _: 3
  3156. /* FORWARDED */
  3157. }, 8, ["show", "duration", "custom-style", "onClick"]);
  3158. }
  3159. const __easycom_0$3 = /* @__PURE__ */ _export_sfc(_sfc_main$y, [["render", _sfc_render$x], ["__scopeId", "data-v-9112bed9"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-overlay/u-overlay.vue"]]);
  3160. const props$b = {
  3161. props: {
  3162. bgColor: {
  3163. type: String,
  3164. default: () => props$f.statusBar.bgColor
  3165. }
  3166. }
  3167. };
  3168. const _sfc_main$x = {
  3169. name: "u-status-bar",
  3170. mixins: [mpMixin, mixin$1, props$b],
  3171. data() {
  3172. return {};
  3173. },
  3174. computed: {
  3175. style() {
  3176. const style = {};
  3177. style.height = addUnit(sys().statusBarHeight, "px");
  3178. style.backgroundColor = this.bgColor;
  3179. return deepMerge$1(style, addStyle(this.customStyle));
  3180. }
  3181. }
  3182. };
  3183. function _sfc_render$w(_ctx, _cache, $props, $setup, $data, $options) {
  3184. return vue.openBlock(), vue.createElementBlock(
  3185. "view",
  3186. {
  3187. style: vue.normalizeStyle([$options.style]),
  3188. class: "u-status-bar"
  3189. },
  3190. [
  3191. vue.renderSlot(_ctx.$slots, "default", {}, void 0, true)
  3192. ],
  3193. 4
  3194. /* STYLE */
  3195. );
  3196. }
  3197. const __easycom_1$5 = /* @__PURE__ */ _export_sfc(_sfc_main$x, [["render", _sfc_render$w], ["__scopeId", "data-v-eb8e0cdd"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-status-bar/u-status-bar.vue"]]);
  3198. const props$a = {
  3199. props: {}
  3200. };
  3201. const _sfc_main$w = {
  3202. name: "u-safe-bottom",
  3203. mixins: [mpMixin, mixin$1, props$a],
  3204. data() {
  3205. return {
  3206. safeAreaBottomHeight: 0,
  3207. isNvue: false
  3208. };
  3209. },
  3210. computed: {
  3211. style() {
  3212. const style = {};
  3213. return deepMerge$1(style, addStyle(this.customStyle));
  3214. }
  3215. },
  3216. mounted() {
  3217. }
  3218. };
  3219. function _sfc_render$v(_ctx, _cache, $props, $setup, $data, $options) {
  3220. return vue.openBlock(), vue.createElementBlock(
  3221. "view",
  3222. {
  3223. class: vue.normalizeClass(["u-safe-bottom", [!$data.isNvue && "u-safe-area-inset-bottom"]]),
  3224. style: vue.normalizeStyle([$options.style])
  3225. },
  3226. null,
  3227. 6
  3228. /* CLASS, STYLE */
  3229. );
  3230. }
  3231. const __easycom_3$1 = /* @__PURE__ */ _export_sfc(_sfc_main$w, [["render", _sfc_render$v], ["__scopeId", "data-v-f3d22cfe"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-safe-bottom/u-safe-bottom.vue"]]);
  3232. const props$9 = {
  3233. props: {
  3234. // 是否展示弹窗
  3235. show: {
  3236. type: Boolean,
  3237. default: () => props$f.popup.show
  3238. },
  3239. // 是否显示遮罩
  3240. overlay: {
  3241. type: Boolean,
  3242. default: () => props$f.popup.overlay
  3243. },
  3244. // 弹出的方向,可选值为 top bottom right left center
  3245. mode: {
  3246. type: String,
  3247. default: () => props$f.popup.mode
  3248. },
  3249. // 动画时长,单位ms
  3250. duration: {
  3251. type: [String, Number],
  3252. default: () => props$f.popup.duration
  3253. },
  3254. // 是否显示关闭图标
  3255. closeable: {
  3256. type: Boolean,
  3257. default: () => props$f.popup.closeable
  3258. },
  3259. // 自定义遮罩的样式
  3260. overlayStyle: {
  3261. type: [Object, String],
  3262. default: () => props$f.popup.overlayStyle
  3263. },
  3264. // 点击遮罩是否关闭弹窗
  3265. closeOnClickOverlay: {
  3266. type: Boolean,
  3267. default: () => props$f.popup.closeOnClickOverlay
  3268. },
  3269. // 层级
  3270. zIndex: {
  3271. type: [String, Number],
  3272. default: () => props$f.popup.zIndex
  3273. },
  3274. // 是否为iPhoneX留出底部安全距离
  3275. safeAreaInsetBottom: {
  3276. type: Boolean,
  3277. default: () => props$f.popup.safeAreaInsetBottom
  3278. },
  3279. // 是否留出顶部安全距离(状态栏高度)
  3280. safeAreaInsetTop: {
  3281. type: Boolean,
  3282. default: () => props$f.popup.safeAreaInsetTop
  3283. },
  3284. // 自定义关闭图标位置,top-left为左上角,top-right为右上角,bottom-left为左下角,bottom-right为右下角
  3285. closeIconPos: {
  3286. type: String,
  3287. default: () => props$f.popup.closeIconPos
  3288. },
  3289. // 是否显示圆角
  3290. round: {
  3291. type: [Boolean, String, Number],
  3292. default: () => props$f.popup.round
  3293. },
  3294. // mode=center,也即中部弹出时,是否使用缩放模式
  3295. zoom: {
  3296. type: Boolean,
  3297. default: () => props$f.popup.zoom
  3298. },
  3299. // 弹窗背景色,设置为transparent可去除白色背景
  3300. bgColor: {
  3301. type: String,
  3302. default: () => props$f.popup.bgColor
  3303. },
  3304. // 遮罩的透明度,0-1之间
  3305. overlayOpacity: {
  3306. type: [Number, String],
  3307. default: () => props$f.popup.overlayOpacity
  3308. }
  3309. }
  3310. };
  3311. const _sfc_main$v = {
  3312. name: "u-popup",
  3313. mixins: [mpMixin, mixin$1, props$9],
  3314. data() {
  3315. return {
  3316. overlayDuration: this.duration + 50
  3317. };
  3318. },
  3319. watch: {
  3320. show(newValue, oldValue) {
  3321. }
  3322. },
  3323. computed: {
  3324. transitionStyle() {
  3325. const style = {
  3326. zIndex: this.zIndex,
  3327. position: "fixed",
  3328. display: "flex"
  3329. };
  3330. style[this.mode] = 0;
  3331. if (this.mode === "left") {
  3332. return deepMerge$1(style, {
  3333. bottom: 0,
  3334. top: 0
  3335. });
  3336. } else if (this.mode === "right") {
  3337. return deepMerge$1(style, {
  3338. bottom: 0,
  3339. top: 0
  3340. });
  3341. } else if (this.mode === "top") {
  3342. return deepMerge$1(style, {
  3343. left: 0,
  3344. right: 0
  3345. });
  3346. } else if (this.mode === "bottom") {
  3347. return deepMerge$1(style, {
  3348. left: 0,
  3349. right: 0
  3350. });
  3351. } else if (this.mode === "center") {
  3352. return deepMerge$1(style, {
  3353. alignItems: "center",
  3354. "justify-content": "center",
  3355. top: 0,
  3356. left: 0,
  3357. right: 0,
  3358. bottom: 0
  3359. });
  3360. }
  3361. },
  3362. contentStyle() {
  3363. const style = {};
  3364. sys();
  3365. if (this.mode !== "center") {
  3366. style.flex = 1;
  3367. }
  3368. if (this.bgColor) {
  3369. style.backgroundColor = this.bgColor;
  3370. }
  3371. if (this.round) {
  3372. const value2 = addUnit(this.round);
  3373. if (this.mode === "top") {
  3374. style.borderBottomLeftRadius = value2;
  3375. style.borderBottomRightRadius = value2;
  3376. } else if (this.mode === "bottom") {
  3377. style.borderTopLeftRadius = value2;
  3378. style.borderTopRightRadius = value2;
  3379. } else if (this.mode === "center") {
  3380. style.borderRadius = value2;
  3381. }
  3382. }
  3383. return deepMerge$1(style, addStyle(this.customStyle));
  3384. },
  3385. position() {
  3386. if (this.mode === "center") {
  3387. return this.zoom ? "fade-zoom" : "fade";
  3388. }
  3389. if (this.mode === "left") {
  3390. return "slide-left";
  3391. }
  3392. if (this.mode === "right") {
  3393. return "slide-right";
  3394. }
  3395. if (this.mode === "bottom") {
  3396. return "slide-up";
  3397. }
  3398. if (this.mode === "top") {
  3399. return "slide-down";
  3400. }
  3401. }
  3402. },
  3403. emits: ["open", "close", "click"],
  3404. methods: {
  3405. // 点击遮罩
  3406. overlayClick() {
  3407. if (this.closeOnClickOverlay) {
  3408. this.$emit("close");
  3409. }
  3410. },
  3411. close(e2) {
  3412. this.$emit("close");
  3413. },
  3414. afterEnter() {
  3415. this.$emit("open");
  3416. },
  3417. clickHandler() {
  3418. if (this.mode === "center") {
  3419. this.overlayClick();
  3420. }
  3421. this.$emit("click");
  3422. }
  3423. }
  3424. };
  3425. function _sfc_render$u(_ctx, _cache, $props, $setup, $data, $options) {
  3426. const _component_u_overlay = resolveEasycom(vue.resolveDynamicComponent("u-overlay"), __easycom_0$3);
  3427. const _component_u_status_bar = resolveEasycom(vue.resolveDynamicComponent("u-status-bar"), __easycom_1$5);
  3428. const _component_u_icon = resolveEasycom(vue.resolveDynamicComponent("u-icon"), __easycom_0$4);
  3429. const _component_u_safe_bottom = resolveEasycom(vue.resolveDynamicComponent("u-safe-bottom"), __easycom_3$1);
  3430. const _component_u_transition = resolveEasycom(vue.resolveDynamicComponent("u-transition"), __easycom_1$6);
  3431. return vue.openBlock(), vue.createElementBlock("view", { class: "u-popup" }, [
  3432. _ctx.overlay ? (vue.openBlock(), vue.createBlock(_component_u_overlay, {
  3433. key: 0,
  3434. show: _ctx.show,
  3435. onClick: $options.overlayClick,
  3436. duration: $data.overlayDuration,
  3437. customStyle: _ctx.overlayStyle,
  3438. opacity: _ctx.overlayOpacity
  3439. }, null, 8, ["show", "onClick", "duration", "customStyle", "opacity"])) : vue.createCommentVNode("v-if", true),
  3440. vue.createVNode(_component_u_transition, {
  3441. show: _ctx.show,
  3442. customStyle: $options.transitionStyle,
  3443. mode: $options.position,
  3444. duration: _ctx.duration,
  3445. onAfterEnter: $options.afterEnter,
  3446. onClick: $options.clickHandler
  3447. }, {
  3448. default: vue.withCtx(() => [
  3449. vue.createElementVNode(
  3450. "view",
  3451. {
  3452. class: "u-popup__content",
  3453. style: vue.normalizeStyle([$options.contentStyle]),
  3454. onClick: _cache[1] || (_cache[1] = vue.withModifiers((...args) => _ctx.noop && _ctx.noop(...args), ["stop"]))
  3455. },
  3456. [
  3457. _ctx.safeAreaInsetTop ? (vue.openBlock(), vue.createBlock(_component_u_status_bar, { key: 0 })) : vue.createCommentVNode("v-if", true),
  3458. vue.renderSlot(_ctx.$slots, "default", {}, void 0, true),
  3459. _ctx.closeable ? (vue.openBlock(), vue.createElementBlock(
  3460. "view",
  3461. {
  3462. key: 1,
  3463. onClick: _cache[0] || (_cache[0] = vue.withModifiers((...args) => $options.close && $options.close(...args), ["stop"])),
  3464. class: vue.normalizeClass(["u-popup__content__close", ["u-popup__content__close--" + _ctx.closeIconPos]]),
  3465. "hover-class": "u-popup__content__close--hover",
  3466. "hover-stay-time": "150"
  3467. },
  3468. [
  3469. vue.createVNode(_component_u_icon, {
  3470. name: "close",
  3471. color: "#909399",
  3472. size: "18",
  3473. bold: ""
  3474. })
  3475. ],
  3476. 2
  3477. /* CLASS */
  3478. )) : vue.createCommentVNode("v-if", true),
  3479. _ctx.safeAreaInsetBottom ? (vue.openBlock(), vue.createBlock(_component_u_safe_bottom, { key: 2 })) : vue.createCommentVNode("v-if", true)
  3480. ],
  3481. 4
  3482. /* STYLE */
  3483. )
  3484. ]),
  3485. _: 3
  3486. /* FORWARDED */
  3487. }, 8, ["show", "customStyle", "mode", "duration", "onAfterEnter", "onClick"])
  3488. ]);
  3489. }
  3490. const __easycom_1$4 = /* @__PURE__ */ _export_sfc(_sfc_main$v, [["render", _sfc_render$u], ["__scopeId", "data-v-05c24e9b"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-popup/u-popup.vue"]]);
  3491. let Request$1 = class Request {
  3492. http(router, data = {}, method, contentType) {
  3493. let path = "http://v56c9b8e.natappfree.cc";
  3494. uni.setStorageSync("requestPath", path);
  3495. uni.showLoading({
  3496. title: "加载中"
  3497. });
  3498. return new Promise((resolve, reject) => {
  3499. let token = uni.getStorageSync("AppToken");
  3500. var httpContentType = "application/x-www-form-urlencoded";
  3501. if (contentType != void 0) {
  3502. httpContentType = contentType;
  3503. }
  3504. uni.request({
  3505. header: {
  3506. // 'Content-Type': 'application/x-www-form-urlencoded',
  3507. "Content-Type": httpContentType,
  3508. "AppToken": token
  3509. },
  3510. url: `${path}${router}`,
  3511. data,
  3512. method,
  3513. success: (res) => {
  3514. if (res.code == 401) {
  3515. let pages2 = getCurrentPages();
  3516. let url2 = pages2[pages2.length - 1];
  3517. 如果登录界面已打开, 自动关闭;
  3518. if (url2 != void 0 && url2.route == "/pages/home/index") {
  3519. resolve(res.data);
  3520. return;
  3521. }
  3522. uni.reLaunch({
  3523. url: "/pages/home/index",
  3524. success: () => {
  3525. uni.hideLoading();
  3526. },
  3527. fail: () => {
  3528. uni.hideLoading();
  3529. }
  3530. });
  3531. return;
  3532. }
  3533. if (res.token) {
  3534. uni.setStorageSync("AppToken", res.token);
  3535. }
  3536. resolve(res.data);
  3537. },
  3538. fail: (res) => {
  3539. },
  3540. complete: (res) => {
  3541. if (res.data.code == 401) {
  3542. return false;
  3543. }
  3544. uni.hideLoading();
  3545. }
  3546. });
  3547. });
  3548. }
  3549. };
  3550. let request$6 = new Request$1().http;
  3551. function loginByMp(data) {
  3552. return request$6("/app/user/loginByMp", data, "POST", "application/json;charset=UTF-8");
  3553. }
  3554. function getlive(data) {
  3555. return request$6("/app/live/live", data, "GET", "application/json;charset=UTF-8");
  3556. }
  3557. function gettextlist(data) {
  3558. return request$6("/app/live/msgList", data, "GET", "application/json;charset=UTF-8");
  3559. }
  3560. function getAnswerlist(data) {
  3561. return request$6("/app/question/questionList", data, "GET", "application/json;charset=UTF-8");
  3562. }
  3563. function submitAnswer(data) {
  3564. return request$6("/app/question/answer", data, "POST", "application/json;charset=UTF-8");
  3565. }
  3566. const _imports_0$b = "/static/images/shipin.png";
  3567. const isWechat = () => {
  3568. return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
  3569. };
  3570. const _sfc_main$u = {
  3571. data() {
  3572. return {
  3573. isLogin: false,
  3574. code: "",
  3575. livedata: {},
  3576. path: "http://live.ylrzcloud.com/prod-api",
  3577. iskefu: false,
  3578. isLongPress: false,
  3579. // 是否长按
  3580. timeout: null,
  3581. // 计时器
  3582. liveId: 2
  3583. };
  3584. },
  3585. onLoad(option) {
  3586. },
  3587. onShow() {
  3588. if (uni.getStorageSync("AppToken")) {
  3589. this.getliving();
  3590. }
  3591. },
  3592. methods: {
  3593. open() {
  3594. },
  3595. close() {
  3596. this.iskefu = !this.iskefu;
  3597. },
  3598. longPress() {
  3599. this.timeout = setTimeout(() => {
  3600. this.isLongPress = true;
  3601. uni.saveImageToPhotosAlbum({
  3602. filePath: this.livedata.qwQrCode,
  3603. // 图片的本地路径或网络路径
  3604. success: () => {
  3605. uni.showToast({
  3606. title: "保存成功"
  3607. });
  3608. },
  3609. fail: () => {
  3610. uni.showToast({
  3611. title: "保存失败",
  3612. icon: "none"
  3613. });
  3614. }
  3615. });
  3616. }, 500);
  3617. },
  3618. cancelLongPress() {
  3619. clearTimeout(this.timeout);
  3620. this.isLongPress = false;
  3621. },
  3622. getliving() {
  3623. const param = {
  3624. id: this.liveId
  3625. };
  3626. getlive(param).then((res) => {
  3627. if (res.code == 200) {
  3628. this.livedata = res.data;
  3629. } else {
  3630. uni.showToast({
  3631. title: res.msg,
  3632. icon: "none",
  3633. duration: 2e3
  3634. });
  3635. }
  3636. });
  3637. },
  3638. getWechatCode() {
  3639. if (isWechat) {
  3640. let appid = "wx93ce67750e3cfba3";
  3641. let code2 = this.getUrlCode().code;
  3642. let local = window.location.href.split("#")[0];
  3643. if (code2 == null || code2 === "") {
  3644. window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + encodeURIComponent(local) + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
  3645. } else {
  3646. this.code = code2;
  3647. this.loginByMp();
  3648. }
  3649. }
  3650. },
  3651. loginByMp() {
  3652. if (this.code == null) {
  3653. return;
  3654. }
  3655. uni.showLoading({
  3656. title: "处理中..."
  3657. });
  3658. var data = {
  3659. code: this.code
  3660. };
  3661. loginByMp(data).then(
  3662. (res) => {
  3663. uni.hideLoading();
  3664. if (res.code == 200) {
  3665. formatAppLog("log", "at pages/home/index.vue:159", res);
  3666. uni.setStorageSync("AppToken", res.token);
  3667. uni.setStorageSync("userInfo", JSON.stringify(res.user));
  3668. let beforLoginUrl = uni.getStorageSync("beforLoginPage");
  3669. uni.reLaunch({
  3670. url: beforLoginUrl
  3671. });
  3672. uni.showToast({
  3673. title: "登录成功",
  3674. icon: "none"
  3675. });
  3676. this.getliving();
  3677. } else {
  3678. uni.showToast({
  3679. title: res.msg,
  3680. icon: "none"
  3681. });
  3682. }
  3683. },
  3684. (err) => {
  3685. }
  3686. );
  3687. },
  3688. getUrlCode() {
  3689. var url2 = location.search;
  3690. var theRequest = new Object();
  3691. if (url2.indexOf("?") != -1) {
  3692. var str = url2.substr(1);
  3693. var strs = str.split("&");
  3694. for (var i2 = 0; i2 < strs.length; i2++) {
  3695. theRequest[strs[i2].split("=")[0]] = strs[i2].split("=")[1];
  3696. }
  3697. }
  3698. return theRequest;
  3699. },
  3700. comelive() {
  3701. uni.setStorageSync("AppToken", null);
  3702. if (uni.getStorageSync("AppToken")) {
  3703. uni.navigateTo({
  3704. url: "/pages/home/living"
  3705. });
  3706. } else {
  3707. uni.showToast({
  3708. title: "请登录授权!",
  3709. icon: "none"
  3710. });
  3711. uni.navigateTo({
  3712. url: "/pages/login/login"
  3713. });
  3714. }
  3715. }
  3716. }
  3717. };
  3718. function _sfc_render$t(_ctx, _cache, $props, $setup, $data, $options) {
  3719. const _component_u_icon = resolveEasycom(vue.resolveDynamicComponent("u-icon"), __easycom_0$4);
  3720. const _component_u_popup = resolveEasycom(vue.resolveDynamicComponent("u-popup"), __easycom_1$4);
  3721. return vue.openBlock(), vue.createElementBlock("view", { class: "home column" }, [
  3722. vue.createElementVNode("view", { class: "justify-start align-center" }, [
  3723. vue.createElementVNode("image", {
  3724. src: _imports_0$b,
  3725. class: "wh50 p20"
  3726. }),
  3727. vue.createElementVNode("view", { class: "fs32 bold" }, "道中")
  3728. ]),
  3729. vue.createElementVNode("image", {
  3730. src: $data.livedata.liveImgUrl,
  3731. mode: "widthFix",
  3732. class: "w100"
  3733. }, null, 8, ["src"]),
  3734. vue.createElementVNode("view", { class: "p20" }, [
  3735. vue.createElementVNode("view", { class: "column" }, [
  3736. vue.createElementVNode(
  3737. "text",
  3738. { class: "fs32" },
  3739. vue.toDisplayString($data.livedata.liveName),
  3740. 1
  3741. /* TEXT */
  3742. ),
  3743. vue.createElementVNode(
  3744. "text",
  3745. { class: "color9 fs24 mt20" },
  3746. " 直播时间 " + vue.toDisplayString($data.livedata.startTime) + " —— " + vue.toDisplayString($data.livedata.finishTime),
  3747. 1
  3748. /* TEXT */
  3749. )
  3750. ])
  3751. ]),
  3752. vue.createElementVNode("view", { class: "p20 detail" }, [
  3753. vue.createElementVNode("view", { class: "jianjie mb20" }, "简介"),
  3754. vue.createElementVNode("view", {
  3755. class: "fs24 lh36",
  3756. innerHTML: $data.livedata.liveDesc
  3757. }, null, 8, ["innerHTML"])
  3758. ]),
  3759. vue.createElementVNode("view", { class: "p12 bgf bot-box" }, [
  3760. vue.createElementVNode("view", {
  3761. class: "center",
  3762. onClick: _cache[0] || (_cache[0] = (...args) => $options.comelive && $options.comelive(...args))
  3763. }, "进入直播间")
  3764. ]),
  3765. vue.createVNode(_component_u_popup, {
  3766. show: $data.iskefu,
  3767. onClose: $options.close,
  3768. onOpen: $options.open,
  3769. round: "20rpx",
  3770. bgColor: "#fffee1"
  3771. }, {
  3772. default: vue.withCtx(() => [
  3773. vue.createElementVNode("view", { class: "addchat p20" }, [
  3774. vue.createElementVNode("view", { class: "u-flex-row-reverse u-flex" }, [
  3775. vue.createVNode(_component_u_icon, {
  3776. name: "close",
  3777. size: "18",
  3778. onClick: _cache[1] || (_cache[1] = ($event) => _ctx.showadd = !_ctx.showadd)
  3779. })
  3780. ]),
  3781. vue.createElementVNode("view", { class: "column align-center" }, [
  3782. vue.createElementVNode("view", {
  3783. class: "fs36",
  3784. style: { "color": "#ff5c03" }
  3785. }, "扫码添加助教老师"),
  3786. vue.createElementVNode("view", { class: "fs28 color6" }, "扫码添加助教老师"),
  3787. vue.createElementVNode("view", {
  3788. class: "p10 mt40",
  3789. style: { "border": "#ff5c03 solid 2rpx" }
  3790. }, [
  3791. vue.createElementVNode("image", {
  3792. src: _ctx.codeimg,
  3793. class: "wh180",
  3794. onTouchstart: _cache[2] || (_cache[2] = (...args) => $options.longPress && $options.longPress(...args)),
  3795. onTouchend: _cache[3] || (_cache[3] = (...args) => $options.cancelLongPress && $options.cancelLongPress(...args))
  3796. }, null, 40, ["src"])
  3797. ]),
  3798. vue.createElementVNode("view", { class: "color6 mt20" }, "长按识别二维码")
  3799. ])
  3800. ])
  3801. ]),
  3802. _: 1
  3803. /* STABLE */
  3804. }, 8, ["show", "onClose", "onOpen"])
  3805. ]);
  3806. }
  3807. const PagesHomeIndex = /* @__PURE__ */ _export_sfc(_sfc_main$u, [["render", _sfc_render$t], ["__scopeId", "data-v-4978fed5"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages/home/index.vue"]]);
  3808. const props$8 = {
  3809. props: {
  3810. // 文字颜色
  3811. color: {
  3812. type: String,
  3813. default: () => props$f.link.color
  3814. },
  3815. // 字体大小,单位px
  3816. fontSize: {
  3817. type: [String, Number],
  3818. default: () => props$f.link.fontSize
  3819. },
  3820. // 是否显示下划线
  3821. underLine: {
  3822. type: Boolean,
  3823. default: () => props$f.link.underLine
  3824. },
  3825. // 要跳转的链接
  3826. href: {
  3827. type: String,
  3828. default: () => props$f.link.href
  3829. },
  3830. // 小程序中复制到粘贴板的提示语
  3831. mpTips: {
  3832. type: String,
  3833. default: () => props$f.link.mpTips
  3834. },
  3835. // 下划线颜色
  3836. lineColor: {
  3837. type: String,
  3838. default: () => props$f.link.lineColor
  3839. },
  3840. // 超链接的问题,不使用slot形式传入,是因为nvue下无法修改颜色
  3841. text: {
  3842. type: String,
  3843. default: () => props$f.link.text
  3844. }
  3845. }
  3846. };
  3847. const _sfc_main$t = {
  3848. name: "u-link",
  3849. mixins: [mpMixin, mixin$1, props$8],
  3850. computed: {
  3851. linkStyle() {
  3852. const style = {
  3853. color: this.color,
  3854. fontSize: addUnit(this.fontSize),
  3855. // line-height设置为比字体大小多2px
  3856. lineHeight: addUnit(getPx(this.fontSize) + 2),
  3857. textDecoration: this.underLine ? "underline" : "none"
  3858. };
  3859. return style;
  3860. }
  3861. },
  3862. emits: ["click"],
  3863. methods: {
  3864. addStyle,
  3865. openLink() {
  3866. plus.runtime.openURL(this.href);
  3867. this.$emit("click");
  3868. }
  3869. }
  3870. };
  3871. function _sfc_render$s(_ctx, _cache, $props, $setup, $data, $options) {
  3872. return vue.openBlock(), vue.createElementBlock(
  3873. "text",
  3874. {
  3875. class: "u-link",
  3876. onClick: _cache[0] || (_cache[0] = vue.withModifiers((...args) => $options.openLink && $options.openLink(...args), ["stop"])),
  3877. style: vue.normalizeStyle([$options.linkStyle, $options.addStyle(_ctx.customStyle)])
  3878. },
  3879. vue.toDisplayString(_ctx.text),
  3880. 5
  3881. /* TEXT, STYLE */
  3882. );
  3883. }
  3884. const __easycom_1$3 = /* @__PURE__ */ _export_sfc(_sfc_main$t, [["render", _sfc_render$s], ["__scopeId", "data-v-12f6646d"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-link/u-link.vue"]]);
  3885. const props$7 = {
  3886. props: {
  3887. // 主题颜色
  3888. type: {
  3889. type: String,
  3890. default: () => props$f.text.type
  3891. },
  3892. // 是否显示
  3893. show: {
  3894. type: Boolean,
  3895. default: () => props$f.text.show
  3896. },
  3897. // 显示的值
  3898. text: {
  3899. type: [String, Number],
  3900. default: () => props$f.text.text
  3901. },
  3902. // 前置图标
  3903. prefixIcon: {
  3904. type: String,
  3905. default: () => props$f.text.prefixIcon
  3906. },
  3907. // 后置图标
  3908. suffixIcon: {
  3909. type: String,
  3910. default: () => props$f.text.suffixIcon
  3911. },
  3912. // 文本处理的匹配模式
  3913. // text-普通文本,price-价格,phone-手机号,name-姓名,date-日期,link-超链接
  3914. mode: {
  3915. type: String,
  3916. default: () => props$f.text.mode
  3917. },
  3918. // mode=link下,配置的链接
  3919. href: {
  3920. type: String,
  3921. default: () => props$f.text.href
  3922. },
  3923. // 格式化规则
  3924. format: {
  3925. type: [String, Function],
  3926. default: () => props$f.text.format
  3927. },
  3928. // mode=phone时,点击文本是否拨打电话
  3929. call: {
  3930. type: Boolean,
  3931. default: () => props$f.text.call
  3932. },
  3933. // 小程序的打开方式
  3934. openType: {
  3935. type: String,
  3936. default: () => props$f.text.openType
  3937. },
  3938. // 是否粗体,默认normal
  3939. bold: {
  3940. type: Boolean,
  3941. default: () => props$f.text.bold
  3942. },
  3943. // 是否块状
  3944. block: {
  3945. type: Boolean,
  3946. default: () => props$f.text.block
  3947. },
  3948. // 文本显示的行数,如果设置,超出此行数,将会显示省略号
  3949. lines: {
  3950. type: [String, Number],
  3951. default: () => props$f.text.lines
  3952. },
  3953. // 文本颜色
  3954. color: {
  3955. type: String,
  3956. default: () => props$f.text.color
  3957. },
  3958. // 字体大小
  3959. size: {
  3960. type: [String, Number],
  3961. default: () => props$f.text.size
  3962. },
  3963. // 图标的样式
  3964. iconStyle: {
  3965. type: [Object, String],
  3966. default: () => props$f.text.iconStyle
  3967. },
  3968. // 文字装饰,下划线,中划线等,可选值 none|underline|line-through
  3969. decoration: {
  3970. tepe: String,
  3971. default: () => props$f.text.decoration
  3972. },
  3973. // 外边距,对象、字符串,数值形式均可
  3974. margin: {
  3975. type: [Object, String, Number],
  3976. default: () => props$f.text.margin
  3977. },
  3978. // 文本行高
  3979. lineHeight: {
  3980. type: [String, Number],
  3981. default: () => props$f.text.lineHeight
  3982. },
  3983. // 文本对齐方式,可选值left|center|right
  3984. align: {
  3985. type: String,
  3986. default: () => props$f.text.align
  3987. },
  3988. // 文字换行,可选值break-word|normal|anywhere
  3989. wordWrap: {
  3990. type: String,
  3991. default: () => props$f.text.wordWrap
  3992. }
  3993. }
  3994. };
  3995. const value = {
  3996. computed: {
  3997. // 经处理后需要显示的值
  3998. value() {
  3999. const {
  4000. text,
  4001. mode,
  4002. format: format2,
  4003. href
  4004. } = this;
  4005. if (mode === "price") {
  4006. if (!/^\d+(\.\d+)?$/.test(text)) {
  4007. error("金额模式下,text参数需要为金额格式");
  4008. }
  4009. if (test.func(format2)) {
  4010. return format2(text);
  4011. }
  4012. return priceFormat(text, 2);
  4013. }
  4014. if (mode === "date") {
  4015. !test.date(text) && error("日期模式下,text参数需要为日期或时间戳格式");
  4016. if (test.func(format2)) {
  4017. return format2(text);
  4018. }
  4019. if (format2) {
  4020. return timeFormat(text, format2);
  4021. }
  4022. return timeFormat(text, "yyyy-mm-dd");
  4023. }
  4024. if (mode === "phone") {
  4025. if (test.func(format2)) {
  4026. return format2(text);
  4027. }
  4028. if (format2 === "encrypt") {
  4029. return `${text.substr(0, 3)}****${text.substr(7)}`;
  4030. }
  4031. return text;
  4032. }
  4033. if (mode === "name") {
  4034. !(typeof text === "string") && error("姓名模式下,text参数需要为字符串格式");
  4035. if (test.func(format2)) {
  4036. return format2(text);
  4037. }
  4038. if (format2 === "encrypt") {
  4039. return this.formatName(text);
  4040. }
  4041. return text;
  4042. }
  4043. if (mode === "link") {
  4044. !test.url(href) && error("超链接模式下,href参数需要为URL格式");
  4045. return text;
  4046. }
  4047. return text;
  4048. }
  4049. },
  4050. methods: {
  4051. // 默认的姓名脱敏规则
  4052. formatName(name) {
  4053. let value2 = "";
  4054. if (name.length === 2) {
  4055. value2 = name.substr(0, 1) + "*";
  4056. } else if (name.length > 2) {
  4057. let char = "";
  4058. for (let i2 = 0, len = name.length - 2; i2 < len; i2++) {
  4059. char += "*";
  4060. }
  4061. value2 = name.substr(0, 1) + char + name.substr(-1, 1);
  4062. } else {
  4063. value2 = name;
  4064. }
  4065. return value2;
  4066. }
  4067. }
  4068. };
  4069. const _sfc_main$s = {
  4070. name: "u--text",
  4071. mixins: [mpMixin, mixin$1, value, props$7],
  4072. emits: ["click"],
  4073. computed: {
  4074. valueStyle() {
  4075. const style = {
  4076. textDecoration: this.decoration,
  4077. fontWeight: this.bold ? "bold" : "normal",
  4078. wordWrap: this.wordWrap,
  4079. fontSize: addUnit(this.size)
  4080. };
  4081. !this.type && (style.color = this.color);
  4082. this.isNvue && this.lines && (style.lines = this.lines);
  4083. this.lineHeight && (style.lineHeight = addUnit(this.lineHeight));
  4084. !this.isNvue && this.block && (style.display = "block");
  4085. return deepMerge$1(style, addStyle(this.customStyle));
  4086. },
  4087. isNvue() {
  4088. let nvue = false;
  4089. return nvue;
  4090. },
  4091. isMp() {
  4092. let mp = false;
  4093. return mp;
  4094. }
  4095. },
  4096. data() {
  4097. return {};
  4098. },
  4099. methods: {
  4100. addStyle,
  4101. clickHandler() {
  4102. if (this.call && this.mode === "phone") {
  4103. uni.makePhoneCall({
  4104. phoneNumber: this.text
  4105. });
  4106. }
  4107. this.$emit("click");
  4108. }
  4109. }
  4110. };
  4111. function _sfc_render$r(_ctx, _cache, $props, $setup, $data, $options) {
  4112. const _component_u_icon = resolveEasycom(vue.resolveDynamicComponent("u-icon"), __easycom_0$4);
  4113. const _component_u_link = resolveEasycom(vue.resolveDynamicComponent("u-link"), __easycom_1$3);
  4114. return _ctx.show ? (vue.openBlock(), vue.createElementBlock(
  4115. "view",
  4116. {
  4117. key: 0,
  4118. class: vue.normalizeClass(["u-text", []]),
  4119. style: vue.normalizeStyle({
  4120. margin: _ctx.margin,
  4121. justifyContent: _ctx.align === "left" ? "flex-start" : _ctx.align === "center" ? "center" : "flex-end"
  4122. }),
  4123. onClick: _cache[6] || (_cache[6] = (...args) => $options.clickHandler && $options.clickHandler(...args))
  4124. },
  4125. [
  4126. _ctx.mode === "price" ? (vue.openBlock(), vue.createElementBlock(
  4127. "text",
  4128. {
  4129. key: 0,
  4130. class: vue.normalizeClass(["u-text__price", _ctx.type && `u-text__value--${_ctx.type}`]),
  4131. style: vue.normalizeStyle([$options.valueStyle])
  4132. },
  4133. "¥",
  4134. 6
  4135. /* CLASS, STYLE */
  4136. )) : vue.createCommentVNode("v-if", true),
  4137. _ctx.prefixIcon ? (vue.openBlock(), vue.createElementBlock("view", {
  4138. key: 1,
  4139. class: "u-text__prefix-icon"
  4140. }, [
  4141. vue.createVNode(_component_u_icon, {
  4142. name: _ctx.prefixIcon,
  4143. customStyle: $options.addStyle(_ctx.iconStyle)
  4144. }, null, 8, ["name", "customStyle"])
  4145. ])) : vue.createCommentVNode("v-if", true),
  4146. _ctx.mode === "link" ? (vue.openBlock(), vue.createBlock(_component_u_link, {
  4147. key: 2,
  4148. class: vue.normalizeClass(["u-text__value", [_ctx.type && `u-text__value--${_ctx.type}`, _ctx.lines && `u-line-${_ctx.lines}`]]),
  4149. style: vue.normalizeStyle({ fontWeight: $options.valueStyle.fontWeight, wordWrap: $options.valueStyle.wordWrap, fontSize: $options.valueStyle.fontSize }),
  4150. text: _ctx.value,
  4151. href: _ctx.href,
  4152. underLine: ""
  4153. }, null, 8, ["style", "class", "text", "href"])) : _ctx.openType && $options.isMp ? (vue.openBlock(), vue.createElementBlock("button", {
  4154. key: 3,
  4155. class: "u-reset-button u-text__value",
  4156. style: vue.normalizeStyle([$options.valueStyle]),
  4157. "data-index": _ctx.index,
  4158. openType: _ctx.openType,
  4159. onGetuserinfo: _cache[0] || (_cache[0] = (...args) => _ctx.onGetUserInfo && _ctx.onGetUserInfo(...args)),
  4160. onContact: _cache[1] || (_cache[1] = (...args) => _ctx.onContact && _ctx.onContact(...args)),
  4161. onGetphonenumber: _cache[2] || (_cache[2] = (...args) => _ctx.onGetPhoneNumber && _ctx.onGetPhoneNumber(...args)),
  4162. onError: _cache[3] || (_cache[3] = (...args) => _ctx.onError && _ctx.onError(...args)),
  4163. onLaunchapp: _cache[4] || (_cache[4] = (...args) => _ctx.onLaunchApp && _ctx.onLaunchApp(...args)),
  4164. onOpensetting: _cache[5] || (_cache[5] = (...args) => _ctx.onOpenSetting && _ctx.onOpenSetting(...args)),
  4165. lang: _ctx.lang,
  4166. "session-from": _ctx.sessionFrom,
  4167. "send-message-title": _ctx.sendMessageTitle,
  4168. "send-message-path": _ctx.sendMessagePath,
  4169. "send-message-img": _ctx.sendMessageImg,
  4170. "show-message-card": _ctx.showMessageCard,
  4171. "app-parameter": _ctx.appParameter
  4172. }, vue.toDisplayString(_ctx.value), 45, ["data-index", "openType", "lang", "session-from", "send-message-title", "send-message-path", "send-message-img", "show-message-card", "app-parameter"])) : (vue.openBlock(), vue.createElementBlock(
  4173. "text",
  4174. {
  4175. key: 4,
  4176. class: vue.normalizeClass(["u-text__value", [
  4177. _ctx.type && `u-text__value--${_ctx.type}`,
  4178. _ctx.lines && `u-line-${_ctx.lines}`
  4179. ]]),
  4180. style: vue.normalizeStyle([$options.valueStyle])
  4181. },
  4182. vue.toDisplayString(_ctx.value),
  4183. 7
  4184. /* TEXT, CLASS, STYLE */
  4185. )),
  4186. _ctx.suffixIcon ? (vue.openBlock(), vue.createElementBlock("view", {
  4187. key: 5,
  4188. class: "u-text__suffix-icon"
  4189. }, [
  4190. vue.createVNode(_component_u_icon, {
  4191. name: _ctx.suffixIcon,
  4192. customStyle: $options.addStyle(_ctx.iconStyle)
  4193. }, null, 8, ["name", "customStyle"])
  4194. ])) : vue.createCommentVNode("v-if", true)
  4195. ],
  4196. 4
  4197. /* STYLE */
  4198. )) : vue.createCommentVNode("v-if", true);
  4199. }
  4200. const __easycom_1$2 = /* @__PURE__ */ _export_sfc(_sfc_main$s, [["render", _sfc_render$r], ["__scopeId", "data-v-0a574502"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-text/u-text.vue"]]);
  4201. const props$6 = {
  4202. props: {
  4203. // 头像图片路径(不能为相对路径)
  4204. src: {
  4205. type: String,
  4206. default: () => props$f.avatar.src
  4207. },
  4208. // 头像形状,circle-圆形,square-方形
  4209. shape: {
  4210. type: String,
  4211. default: () => props$f.avatar.shape
  4212. },
  4213. // 头像尺寸
  4214. size: {
  4215. type: [String, Number],
  4216. default: () => props$f.avatar.size
  4217. },
  4218. // 裁剪模式
  4219. mode: {
  4220. type: String,
  4221. default: () => props$f.avatar.mode
  4222. },
  4223. // 显示的文字
  4224. text: {
  4225. type: String,
  4226. default: () => props$f.avatar.text
  4227. },
  4228. // 背景色
  4229. bgColor: {
  4230. type: String,
  4231. default: () => props$f.avatar.bgColor
  4232. },
  4233. // 文字颜色
  4234. color: {
  4235. type: String,
  4236. default: () => props$f.avatar.color
  4237. },
  4238. // 文字大小
  4239. fontSize: {
  4240. type: [String, Number],
  4241. default: () => props$f.avatar.fontSize
  4242. },
  4243. // 显示的图标
  4244. icon: {
  4245. type: String,
  4246. default: () => props$f.avatar.icon
  4247. },
  4248. // 显示小程序头像,只对百度,微信,QQ小程序有效
  4249. mpAvatar: {
  4250. type: Boolean,
  4251. default: () => props$f.avatar.mpAvatar
  4252. },
  4253. // 是否使用随机背景色
  4254. randomBgColor: {
  4255. type: Boolean,
  4256. default: () => props$f.avatar.randomBgColor
  4257. },
  4258. // 加载失败的默认头像(组件有内置默认图片)
  4259. defaultUrl: {
  4260. type: String,
  4261. default: () => props$f.avatar.defaultUrl
  4262. },
  4263. // 如果配置了randomBgColor为true,且配置了此值,则从默认的背景色数组中取出对应索引的颜色值,取值0-19之间
  4264. colorIndex: {
  4265. type: [String, Number],
  4266. // 校验参数规则,索引在0-19之间
  4267. validator(n2) {
  4268. return test.range(n2, [0, 19]) || n2 === "";
  4269. },
  4270. default: () => props$f.avatar.colorIndex
  4271. },
  4272. // 组件标识符
  4273. name: {
  4274. type: String,
  4275. default: () => props$f.avatar.name
  4276. }
  4277. }
  4278. };
  4279. const base64Avatar = "data:image/jpg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/4QMraHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjMtYzAxMSA2Ni4xNDU2NjEsIDIwMTIvMDIvMDYtMTQ6NTY6MjcgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzYgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjREMEQwRkY0RjgwNDExRUE5OTY2RDgxODY3NkJFODMxIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjREMEQwRkY1RjgwNDExRUE5OTY2RDgxODY3NkJFODMxIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6NEQwRDBGRjJGODA0MTFFQTk5NjZEODE4Njc2QkU4MzEiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NEQwRDBGRjNGODA0MTFFQTk5NjZEODE4Njc2QkU4MzEiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7/7gAOQWRvYmUAZMAAAAAB/9sAhAAGBAQEBQQGBQUGCQYFBgkLCAYGCAsMCgoLCgoMEAwMDAwMDBAMDg8QDw4MExMUFBMTHBsbGxwfHx8fHx8fHx8fAQcHBw0MDRgQEBgaFREVGh8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx//wAARCADIAMgDAREAAhEBAxEB/8QAcQABAQEAAwEBAAAAAAAAAAAAAAUEAQMGAgcBAQAAAAAAAAAAAAAAAAAAAAAQAAIBAwICBgkDBQAAAAAAAAABAhEDBCEFMVFBYXGREiKBscHRMkJSEyOh4XLxYjNDFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8A/fAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHbHFyZ/Dam+yLA+Z2L0Pjtyj2poD4AAAAAAAAAAAAAAAAAAAAAAAAKWFs9y6lcvvwQeqj8z9wFaziY1n/HbUX9XF97A7QAGXI23EvJ1goyfzR0YEfN269jeZ+a03pNe0DIAAAAAAAAAAAAAAAAAAAACvtO3RcVkXlWutuL9YFYAAAAAOJRjKLjJVi9GmB5/csH/mu1h/in8PU+QGMAAAAAAAAAAAAAAAAAAaMDG/6MmMH8C80+xAelSSVFolwQAAAAAAAHVlWI37ErUulaPk+hgeYnCUJuElSUXRrrQHAAAAAAAAAAAAAAAAABa2Oz4bM7r4zdF2ICmAAAAAAAAAg7zZ8GX41wuJP0rRgYAAAAAAAAAAAAAAAAAD0m2R8ODaXU33tsDSAAAAAAAAAlb9HyWZcnJd9PcBHAAAAAAAAAAAAAAAAAPS7e64Vn+KA0AAAAAAAAAJm+v8Ftf3ewCKAAAAAAAAAAAAAAAAAX9muqeGo9NttP06+0DcAAAAAAAAAjb7dTu2ra+VOT9P8AQCWAAAAAAAAAAAAAAAAAUNmyPt5Ltv4bui/kuAF0AAAAAAADiUlGLlJ0SVW+oDzOXfd/Ind6JPRdS0QHSAAAAAAAAAAAAAAAAAE2nVaNcGB6Lbs6OTao9LsF51z60BrAAAAAABJ3jOVHjW3r/sa9QEgAAAAAAAAAAAAAAAAAAAPu1duWriuW34ZR4MC9hbnZyEoy8l36XwfYBsAAADaSq9EuLAlZ+7xSdrGdW9Hc5dgEdtt1erfFgAAAAAAAAAAAAAAAAADVjbblX6NR8MH80tEBRs7HYivyzlN8lovaBPzduvY0m6eK10TXtAyAarO55lpJK54orolr+4GqO/Xaea1FvqbXvA+Z77kNeW3GPbV+4DJfzcm/pcm3H6Vou5AdAFLC2ed2Pjv1txa8sV8T6wOL+yZEKu1JXFy4MDBOE4ScZxcZLinoB8gAAAAAAAAAAAB242LeyJ+C3GvN9C7QLmJtePYpKS+5c+p8F2IDYAANJqj1T4oCfk7Nj3G5Wn9qXJax7gJ93Z82D8sVNc4v30A6Xg5i42Z+iLfqARwcyT0sz9MWvWBps7LlTf5Grce9/oBTxdtxseklHxT+uWr9AGoAB138ezfj4bsFJdD6V2MCPm7RdtJzs1uW1xXzL3gTgAAAAAAAAADRhYc8q74I6RWs5ckB6GxYtWLat21SK731sDsAAAAAAAAAAAAAAAASt021NO/YjrxuQXT1oCOAAAAAAABzGLlJRSq26JAelwsWONYjbXxcZvmwO8AAAAAAAAAAAAAAAAAAef3TEWPkVivx3NY9T6UBiAAAAAABo2+VmGXblddIJ8eivRUD0oAAAAAAAAAAAAAAAAAAAYt4tKeFKVNYNSXfRgefAAAAAAAAr7VuSSWPedKaW5v1MCsAAAAAAAAAAAAAAAAAAIe6bj96Ts2n+JPzSXzP3ATgAAAAAAAAFbbt1UUrOQ9FpC4/UwK6aaqtU+DAAAAAAAAAAAAAAA4lKMIuUmoxWrb4ARNx3R3q2rLpa4Sl0y/YCcAAAAAAAAAAANmFud7G8r89r6X0dgFvGzLGRGtuWvTF6NAdwAAAAAAAAAAAy5W442PVN+K59EePp5ARMvOv5MvO6QXCC4AZwAAAAAAAAAAAAAcxlKLUotprg1owN+PvORborq+7Hnwl3gUbO74VzRydt8pKn68ANcJwmqwkpLmnUDkAAAAfNy9atqtyagut0AxXt5xIV8Fbj6lRd7Am5G65V6qUvtwfyx94GMAAAAAAAAAAAAAAAAAAAOU2nVOj5gdsc3LiqRvTpyqwOxbnnrhdfpSfrQB7pnv/AGvuS9gHXPMy5/Fem1yq0v0A6W29XqwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf//Z";
  4280. const _sfc_main$r = {
  4281. name: "u-avatar",
  4282. mixins: [mpMixin, mixin$1, props$6],
  4283. data() {
  4284. return {
  4285. // 如果配置randomBgColor参数为true,在图标或者文字的模式下,会随机从中取出一个颜色值当做背景色
  4286. colors: [
  4287. "#ffb34b",
  4288. "#f2bba9",
  4289. "#f7a196",
  4290. "#f18080",
  4291. "#88a867",
  4292. "#bfbf39",
  4293. "#89c152",
  4294. "#94d554",
  4295. "#f19ec2",
  4296. "#afaae4",
  4297. "#e1b0df",
  4298. "#c38cc1",
  4299. "#72dcdc",
  4300. "#9acdcb",
  4301. "#77b1cc",
  4302. "#448aca",
  4303. "#86cefa",
  4304. "#98d1ee",
  4305. "#73d1f1",
  4306. "#80a7dc"
  4307. ],
  4308. avatarUrl: this.src,
  4309. allowMp: false
  4310. };
  4311. },
  4312. watch: {
  4313. // 监听头像src的变化,赋值给内部的avatarUrl变量,因为图片加载失败时,需要修改图片的src为默认值
  4314. // 而组件内部不能直接修改props的值,所以需要一个中间变量
  4315. src: {
  4316. immediate: true,
  4317. handler(newVal) {
  4318. this.avatarUrl = newVal;
  4319. if (!newVal) {
  4320. this.errorHandler();
  4321. }
  4322. }
  4323. }
  4324. },
  4325. computed: {
  4326. imageStyle() {
  4327. const style = {};
  4328. return style;
  4329. }
  4330. },
  4331. created() {
  4332. this.init();
  4333. },
  4334. emits: ["click"],
  4335. methods: {
  4336. addStyle,
  4337. addUnit,
  4338. random,
  4339. init() {
  4340. },
  4341. // 判断传入的name属性,是否图片路径,只要带有"/"均认为是图片形式
  4342. isImg() {
  4343. return this.src.indexOf("/") !== -1;
  4344. },
  4345. // 图片加载时失败时触发
  4346. errorHandler() {
  4347. this.avatarUrl = this.defaultUrl || base64Avatar;
  4348. },
  4349. clickHandler() {
  4350. this.$emit("click", this.name);
  4351. }
  4352. }
  4353. };
  4354. function _sfc_render$q(_ctx, _cache, $props, $setup, $data, $options) {
  4355. const _component_u_icon = resolveEasycom(vue.resolveDynamicComponent("u-icon"), __easycom_0$4);
  4356. const _component_u_text = resolveEasycom(vue.resolveDynamicComponent("u-text"), __easycom_1$2);
  4357. return vue.openBlock(), vue.createElementBlock(
  4358. "view",
  4359. {
  4360. class: vue.normalizeClass(["u-avatar", [`u-avatar--${_ctx.shape}`]]),
  4361. style: vue.normalizeStyle([{
  4362. backgroundColor: _ctx.text || _ctx.icon ? _ctx.randomBgColor ? $data.colors[_ctx.colorIndex !== "" ? _ctx.colorIndex : $options.random(0, 19)] : _ctx.bgColor : "transparent",
  4363. width: $options.addUnit(_ctx.size),
  4364. height: $options.addUnit(_ctx.size)
  4365. }, $options.addStyle(_ctx.customStyle)]),
  4366. onClick: _cache[1] || (_cache[1] = (...args) => $options.clickHandler && $options.clickHandler(...args))
  4367. },
  4368. [
  4369. vue.renderSlot(_ctx.$slots, "default", {}, () => [
  4370. _ctx.mpAvatar && $data.allowMp ? (vue.openBlock(), vue.createElementBlock(
  4371. vue.Fragment,
  4372. { key: 0 },
  4373. [],
  4374. 64
  4375. /* STABLE_FRAGMENT */
  4376. )) : _ctx.icon ? (vue.openBlock(), vue.createBlock(_component_u_icon, {
  4377. key: 1,
  4378. name: _ctx.icon,
  4379. size: _ctx.fontSize,
  4380. color: _ctx.color
  4381. }, null, 8, ["name", "size", "color"])) : _ctx.text ? (vue.openBlock(), vue.createBlock(_component_u_text, {
  4382. key: 2,
  4383. text: _ctx.text,
  4384. size: _ctx.fontSize,
  4385. color: _ctx.color,
  4386. align: "center",
  4387. customStyle: "justify-content: center"
  4388. }, null, 8, ["text", "size", "color"])) : (vue.openBlock(), vue.createElementBlock("image", {
  4389. key: 3,
  4390. class: vue.normalizeClass(["u-avatar__image", [`u-avatar__image--${_ctx.shape}`]]),
  4391. src: $data.avatarUrl || _ctx.defaultUrl,
  4392. mode: _ctx.mode,
  4393. onError: _cache[0] || (_cache[0] = (...args) => $options.errorHandler && $options.errorHandler(...args)),
  4394. style: vue.normalizeStyle([{
  4395. width: $options.addUnit(_ctx.size),
  4396. height: $options.addUnit(_ctx.size)
  4397. }])
  4398. }, null, 46, ["src", "mode"]))
  4399. ], true)
  4400. ],
  4401. 6
  4402. /* CLASS, STYLE */
  4403. );
  4404. }
  4405. const __easycom_1$1 = /* @__PURE__ */ _export_sfc(_sfc_main$r, [["render", _sfc_render$q], ["__scopeId", "data-v-34d954f9"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-avatar/u-avatar.vue"]]);
  4406. const props$5 = {
  4407. props: {
  4408. // 绑定的值
  4409. modelValue: {
  4410. type: [String, Number],
  4411. default: () => props$f.input.value
  4412. },
  4413. // number-数字输入键盘,app-vue下可以输入浮点数,app-nvue和小程序平台下只能输入整数
  4414. // idcard-身份证输入键盘,微信、支付宝、百度、QQ小程序
  4415. // digit-带小数点的数字键盘,App的nvue页面、微信、支付宝、百度、头条、QQ小程序
  4416. // text-文本输入键盘
  4417. type: {
  4418. type: String,
  4419. default: () => props$f.input.type
  4420. },
  4421. // 如果 textarea 是在一个 position:fixed 的区域,需要显示指定属性 fixed 为 true,
  4422. // 兼容性:微信小程序、百度小程序、字节跳动小程序、QQ小程序
  4423. fixed: {
  4424. type: Boolean,
  4425. default: () => props$f.input.fixed
  4426. },
  4427. // 是否禁用输入框
  4428. disabled: {
  4429. type: Boolean,
  4430. default: () => props$f.input.disabled
  4431. },
  4432. // 禁用状态时的背景色
  4433. disabledColor: {
  4434. type: String,
  4435. default: () => props$f.input.disabledColor
  4436. },
  4437. // 是否显示清除控件
  4438. clearable: {
  4439. type: Boolean,
  4440. default: () => props$f.input.clearable
  4441. },
  4442. // 是否密码类型
  4443. password: {
  4444. type: Boolean,
  4445. default: () => props$f.input.password
  4446. },
  4447. // 最大输入长度,设置为 -1 的时候不限制最大长度
  4448. maxlength: {
  4449. type: [String, Number],
  4450. default: () => props$f.input.maxlength
  4451. },
  4452. // 输入框为空时的占位符
  4453. placeholder: {
  4454. type: String,
  4455. default: () => props$f.input.placeholder
  4456. },
  4457. // 指定placeholder的样式类,注意页面或组件的style中写了scoped时,需要在类名前写/deep/
  4458. placeholderClass: {
  4459. type: String,
  4460. default: () => props$f.input.placeholderClass
  4461. },
  4462. // 指定placeholder的样式
  4463. placeholderStyle: {
  4464. type: [String, Object],
  4465. default: () => props$f.input.placeholderStyle
  4466. },
  4467. // 是否显示输入字数统计,只在 type ="text"或type ="textarea"时有效
  4468. showWordLimit: {
  4469. type: Boolean,
  4470. default: () => props$f.input.showWordLimit
  4471. },
  4472. // 设置右下角按钮的文字,有效值:send|search|next|go|done,兼容性详见uni-app文档
  4473. // https://uniapp.dcloud.io/component/input
  4474. // https://uniapp.dcloud.io/component/textarea
  4475. confirmType: {
  4476. type: String,
  4477. default: () => props$f.input.confirmType
  4478. },
  4479. // 点击键盘右下角按钮时是否保持键盘不收起,H5无效
  4480. confirmHold: {
  4481. type: Boolean,
  4482. default: () => props$f.input.confirmHold
  4483. },
  4484. // focus时,点击页面的时候不收起键盘,微信小程序有效
  4485. holdKeyboard: {
  4486. type: Boolean,
  4487. default: () => props$f.input.holdKeyboard
  4488. },
  4489. // 自动获取焦点
  4490. // 在 H5 平台能否聚焦以及软键盘是否跟随弹出,取决于当前浏览器本身的实现。nvue 页面不支持,需使用组件的 focus()、blur() 方法控制焦点
  4491. focus: {
  4492. type: Boolean,
  4493. default: () => props$f.input.focus
  4494. },
  4495. // 键盘收起时,是否自动失去焦点,目前仅App3.0.0+有效
  4496. autoBlur: {
  4497. type: Boolean,
  4498. default: () => props$f.input.autoBlur
  4499. },
  4500. // 是否去掉 iOS 下的默认内边距,仅微信小程序,且type=textarea时有效
  4501. disableDefaultPadding: {
  4502. type: Boolean,
  4503. default: () => props$f.input.disableDefaultPadding
  4504. },
  4505. // 指定focus时光标的位置
  4506. cursor: {
  4507. type: [String, Number],
  4508. default: () => props$f.input.cursor
  4509. },
  4510. // 输入框聚焦时底部与键盘的距离
  4511. cursorSpacing: {
  4512. type: [String, Number],
  4513. default: () => props$f.input.cursorSpacing
  4514. },
  4515. // 光标起始位置,自动聚集时有效,需与selection-end搭配使用
  4516. selectionStart: {
  4517. type: [String, Number],
  4518. default: () => props$f.input.selectionStart
  4519. },
  4520. // 光标结束位置,自动聚集时有效,需与selection-start搭配使用
  4521. selectionEnd: {
  4522. type: [String, Number],
  4523. default: () => props$f.input.selectionEnd
  4524. },
  4525. // 键盘弹起时,是否自动上推页面
  4526. adjustPosition: {
  4527. type: Boolean,
  4528. default: () => props$f.input.adjustPosition
  4529. },
  4530. // 输入框内容对齐方式,可选值为:left|center|right
  4531. inputAlign: {
  4532. type: String,
  4533. default: () => props$f.input.inputAlign
  4534. },
  4535. // 输入框字体的大小
  4536. fontSize: {
  4537. type: [String, Number],
  4538. default: () => props$f.input.fontSize
  4539. },
  4540. // 输入框字体颜色
  4541. color: {
  4542. type: String,
  4543. default: () => props$f.input.color
  4544. },
  4545. // 输入框前置图标
  4546. prefixIcon: {
  4547. type: String,
  4548. default: () => props$f.input.prefixIcon
  4549. },
  4550. // 前置图标样式,对象或字符串
  4551. prefixIconStyle: {
  4552. type: [String, Object],
  4553. default: () => props$f.input.prefixIconStyle
  4554. },
  4555. // 输入框后置图标
  4556. suffixIcon: {
  4557. type: String,
  4558. default: () => props$f.input.suffixIcon
  4559. },
  4560. // 后置图标样式,对象或字符串
  4561. suffixIconStyle: {
  4562. type: [String, Object],
  4563. default: () => props$f.input.suffixIconStyle
  4564. },
  4565. // 边框类型,surround-四周边框,bottom-底部边框,none-无边框
  4566. border: {
  4567. type: String,
  4568. default: () => props$f.input.border
  4569. },
  4570. // 是否只读,与disabled不同之处在于disabled会置灰组件,而readonly则不会
  4571. readonly: {
  4572. type: Boolean,
  4573. default: () => props$f.input.readonly
  4574. },
  4575. // 输入框形状,circle-圆形,square-方形
  4576. shape: {
  4577. type: String,
  4578. default: () => props$f.input.shape
  4579. },
  4580. // 用于处理或者过滤输入框内容的方法
  4581. formatter: {
  4582. type: [Function, null],
  4583. default: () => props$f.input.formatter
  4584. },
  4585. // 是否忽略组件内对文本合成系统事件的处理
  4586. ignoreCompositionEvent: {
  4587. type: Boolean,
  4588. default: true
  4589. }
  4590. }
  4591. };
  4592. const _sfc_main$q = {
  4593. name: "u-input",
  4594. mixins: [mpMixin, mixin$1, props$5],
  4595. data() {
  4596. return {
  4597. // 清除操作
  4598. clearInput: false,
  4599. // 输入框的值
  4600. innerValue: "",
  4601. // 是否处于获得焦点状态
  4602. focused: false,
  4603. // value是否第一次变化,在watch中,由于加入immediate属性,会在第一次触发,此时不应该认为value发生了变化
  4604. firstChange: true,
  4605. // value绑定值的变化是由内部还是外部引起的
  4606. changeFromInner: false,
  4607. // 过滤处理方法
  4608. innerFormatter: (value2) => value2
  4609. };
  4610. },
  4611. watch: {
  4612. modelValue: {
  4613. immediate: true,
  4614. handler(newVal, oldVal) {
  4615. this.innerValue = newVal;
  4616. this.firstChange = false;
  4617. this.changeFromInner = false;
  4618. }
  4619. }
  4620. },
  4621. computed: {
  4622. // 是否显示清除控件
  4623. isShowClear() {
  4624. const { clearable, readonly, focused, innerValue } = this;
  4625. return !!clearable && !readonly && !!focused && innerValue !== "";
  4626. },
  4627. // 组件的类名
  4628. inputClass() {
  4629. let classes = [], { border, disabled, shape } = this;
  4630. border === "surround" && (classes = classes.concat(["u-border", "u-input--radius"]));
  4631. classes.push(`u-input--${shape}`);
  4632. border === "bottom" && (classes = classes.concat([
  4633. "u-border-bottom",
  4634. "u-input--no-radius"
  4635. ]));
  4636. return classes.join(" ");
  4637. },
  4638. // 组件的样式
  4639. wrapperStyle() {
  4640. const style = {};
  4641. if (this.disabled) {
  4642. style.backgroundColor = this.disabledColor;
  4643. }
  4644. if (this.border === "none") {
  4645. style.padding = "0";
  4646. } else {
  4647. style.paddingTop = "6px";
  4648. style.paddingBottom = "6px";
  4649. style.paddingLeft = "9px";
  4650. style.paddingRight = "9px";
  4651. }
  4652. return deepMerge$1(style, addStyle(this.customStyle));
  4653. },
  4654. // 输入框的样式
  4655. inputStyle() {
  4656. const style = {
  4657. color: this.color,
  4658. fontSize: addUnit(this.fontSize),
  4659. textAlign: this.inputAlign
  4660. };
  4661. return style;
  4662. }
  4663. },
  4664. emits: ["update:modelValue", "focus", "blur", "change", "confirm", "clear", "keyboardheightchange"],
  4665. methods: {
  4666. // 在微信小程序中,不支持将函数当做props参数,故只能通过ref形式调用
  4667. setFormatter(e2) {
  4668. this.innerFormatter = e2;
  4669. },
  4670. // 当键盘输入时,触发input事件
  4671. onInput(e2) {
  4672. let { value: value2 = "" } = e2.detail || {};
  4673. const formatter = this.formatter || this.innerFormatter;
  4674. const formatValue = formatter(value2);
  4675. this.innerValue = value2;
  4676. this.$nextTick(() => {
  4677. this.innerValue = formatValue;
  4678. this.valueChange();
  4679. });
  4680. },
  4681. // 输入框失去焦点时触发
  4682. onBlur(event) {
  4683. this.$emit("blur", event.detail.value);
  4684. sleep(150).then(() => {
  4685. this.focused = false;
  4686. });
  4687. formValidate(this, "blur");
  4688. },
  4689. // 输入框聚焦时触发
  4690. onFocus(event) {
  4691. this.focused = true;
  4692. this.$emit("focus");
  4693. },
  4694. // 点击完成按钮时触发
  4695. onConfirm(event) {
  4696. this.$emit("confirm", this.innerValue);
  4697. },
  4698. // 键盘高度发生变化的时候触发此事件
  4699. // 兼容性:微信小程序2.7.0+、App 3.1.0+
  4700. onkeyboardheightchange(event) {
  4701. this.$emit("keyboardheightchange", event);
  4702. },
  4703. // 内容发生变化,进行处理
  4704. valueChange() {
  4705. if (this.clearInput) {
  4706. this.innerValue = "";
  4707. this.clearInput = false;
  4708. }
  4709. const value2 = this.innerValue;
  4710. this.$nextTick(() => {
  4711. this.$emit("update:modelValue", value2);
  4712. this.changeFromInner = true;
  4713. this.$emit("change", value2);
  4714. formValidate(this, "change");
  4715. });
  4716. },
  4717. // 点击清除控件
  4718. onClear() {
  4719. this.clearInput = true;
  4720. this.innerValue = "";
  4721. this.$nextTick(() => {
  4722. this.valueChange();
  4723. this.$emit("clear");
  4724. });
  4725. },
  4726. /**
  4727. * 在安卓nvue上,事件无法冒泡
  4728. * 在某些时间,我们希望监听u-from-item的点击事件,此时会导致点击u-form-item内的u-input后
  4729. * 无法触发u-form-item的点击事件,这里通过手动调用u-form-item的方法进行触发
  4730. */
  4731. clickHandler() {
  4732. }
  4733. }
  4734. };
  4735. function _sfc_render$p(_ctx, _cache, $props, $setup, $data, $options) {
  4736. const _component_u_icon = resolveEasycom(vue.resolveDynamicComponent("u-icon"), __easycom_0$4);
  4737. return vue.openBlock(), vue.createElementBlock(
  4738. "view",
  4739. {
  4740. class: vue.normalizeClass(["u-input", $options.inputClass]),
  4741. style: vue.normalizeStyle([$options.wrapperStyle])
  4742. },
  4743. [
  4744. vue.createElementVNode("view", { class: "u-input__content" }, [
  4745. _ctx.prefixIcon || _ctx.$slots.prefix ? (vue.openBlock(), vue.createElementBlock("view", {
  4746. key: 0,
  4747. class: "u-input__content__prefix-icon"
  4748. }, [
  4749. vue.renderSlot(_ctx.$slots, "prefix", {}, () => [
  4750. vue.createVNode(_component_u_icon, {
  4751. name: _ctx.prefixIcon,
  4752. size: "18",
  4753. customStyle: _ctx.prefixIconStyle
  4754. }, null, 8, ["name", "customStyle"])
  4755. ], true)
  4756. ])) : vue.createCommentVNode("v-if", true),
  4757. vue.createElementVNode("view", {
  4758. class: "u-input__content__field-wrapper",
  4759. onClick: _cache[5] || (_cache[5] = (...args) => $options.clickHandler && $options.clickHandler(...args))
  4760. }, [
  4761. vue.createCommentVNode(" 根据uni-app的input组件文档,H5和APP中只要声明了password参数(无论true还是false),type均失效,此时\n 为了防止type=number时,又存在password属性,type无效,此时需要设置password为undefined\n "),
  4762. vue.createElementVNode("input", {
  4763. class: "u-input__content__field-wrapper__field",
  4764. style: vue.normalizeStyle([$options.inputStyle]),
  4765. type: _ctx.type,
  4766. focus: _ctx.focus,
  4767. cursor: _ctx.cursor,
  4768. value: $data.innerValue,
  4769. "auto-blur": _ctx.autoBlur,
  4770. disabled: _ctx.disabled || _ctx.readonly,
  4771. maxlength: _ctx.maxlength,
  4772. placeholder: _ctx.placeholder,
  4773. "placeholder-style": _ctx.placeholderStyle,
  4774. "placeholder-class": _ctx.placeholderClass,
  4775. "confirm-type": _ctx.confirmType,
  4776. "confirm-hold": _ctx.confirmHold,
  4777. "hold-keyboard": _ctx.holdKeyboard,
  4778. "cursor-spacing": _ctx.cursorSpacing,
  4779. "adjust-position": _ctx.adjustPosition,
  4780. "selection-end": _ctx.selectionEnd,
  4781. "selection-start": _ctx.selectionStart,
  4782. password: _ctx.password || _ctx.type === "password" || false,
  4783. ignoreCompositionEvent: _ctx.ignoreCompositionEvent,
  4784. onInput: _cache[0] || (_cache[0] = (...args) => $options.onInput && $options.onInput(...args)),
  4785. onBlur: _cache[1] || (_cache[1] = (...args) => $options.onBlur && $options.onBlur(...args)),
  4786. onFocus: _cache[2] || (_cache[2] = (...args) => $options.onFocus && $options.onFocus(...args)),
  4787. onConfirm: _cache[3] || (_cache[3] = (...args) => $options.onConfirm && $options.onConfirm(...args)),
  4788. onKeyboardheightchange: _cache[4] || (_cache[4] = (...args) => $options.onkeyboardheightchange && $options.onkeyboardheightchange(...args))
  4789. }, null, 44, ["type", "focus", "cursor", "value", "auto-blur", "disabled", "maxlength", "placeholder", "placeholder-style", "placeholder-class", "confirm-type", "confirm-hold", "hold-keyboard", "cursor-spacing", "adjust-position", "selection-end", "selection-start", "password", "ignoreCompositionEvent"])
  4790. ]),
  4791. $options.isShowClear ? (vue.openBlock(), vue.createElementBlock("view", {
  4792. key: 1,
  4793. class: "u-input__content__clear",
  4794. onClick: _cache[6] || (_cache[6] = (...args) => $options.onClear && $options.onClear(...args))
  4795. }, [
  4796. vue.createVNode(_component_u_icon, {
  4797. name: "close",
  4798. size: "11",
  4799. color: "#ffffff",
  4800. customStyle: "line-height: 12px"
  4801. })
  4802. ])) : vue.createCommentVNode("v-if", true),
  4803. _ctx.suffixIcon || _ctx.$slots.suffix ? (vue.openBlock(), vue.createElementBlock("view", {
  4804. key: 2,
  4805. class: "u-input__content__subfix-icon"
  4806. }, [
  4807. vue.renderSlot(_ctx.$slots, "suffix", {}, () => [
  4808. vue.createVNode(_component_u_icon, {
  4809. name: _ctx.suffixIcon,
  4810. size: "18",
  4811. customStyle: _ctx.suffixIconStyle
  4812. }, null, 8, ["name", "customStyle"])
  4813. ], true)
  4814. ])) : vue.createCommentVNode("v-if", true)
  4815. ])
  4816. ],
  4817. 6
  4818. /* CLASS, STYLE */
  4819. );
  4820. }
  4821. const __easycom_2$1 = /* @__PURE__ */ _export_sfc(_sfc_main$q, [["render", _sfc_render$p], ["__scopeId", "data-v-df79975b"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-input/u-input.vue"]]);
  4822. var lookup = [
  4823. 0,
  4824. 0,
  4825. 0,
  4826. 0,
  4827. 0,
  4828. 0,
  4829. 0,
  4830. 0,
  4831. 0,
  4832. 0,
  4833. 0,
  4834. 0,
  4835. 0,
  4836. 0,
  4837. 0,
  4838. 0,
  4839. 0,
  4840. 0,
  4841. 0,
  4842. 0,
  4843. 0,
  4844. 0,
  4845. 0,
  4846. 0,
  4847. 0,
  4848. 0,
  4849. 0,
  4850. 0,
  4851. 0,
  4852. 0,
  4853. 0,
  4854. 0,
  4855. 0,
  4856. 0,
  4857. 0,
  4858. 0,
  4859. 0,
  4860. 0,
  4861. 0,
  4862. 0,
  4863. 0,
  4864. 0,
  4865. 0,
  4866. 62,
  4867. 0,
  4868. 62,
  4869. 0,
  4870. 63,
  4871. 52,
  4872. 53,
  4873. 54,
  4874. 55,
  4875. 56,
  4876. 57,
  4877. 58,
  4878. 59,
  4879. 60,
  4880. 61,
  4881. 0,
  4882. 0,
  4883. 0,
  4884. 0,
  4885. 0,
  4886. 0,
  4887. 0,
  4888. 0,
  4889. 1,
  4890. 2,
  4891. 3,
  4892. 4,
  4893. 5,
  4894. 6,
  4895. 7,
  4896. 8,
  4897. 9,
  4898. 10,
  4899. 11,
  4900. 12,
  4901. 13,
  4902. 14,
  4903. 15,
  4904. 16,
  4905. 17,
  4906. 18,
  4907. 19,
  4908. 20,
  4909. 21,
  4910. 22,
  4911. 23,
  4912. 24,
  4913. 25,
  4914. 0,
  4915. 0,
  4916. 0,
  4917. 0,
  4918. 63,
  4919. 0,
  4920. 26,
  4921. 27,
  4922. 28,
  4923. 29,
  4924. 30,
  4925. 31,
  4926. 32,
  4927. 33,
  4928. 34,
  4929. 35,
  4930. 36,
  4931. 37,
  4932. 38,
  4933. 39,
  4934. 40,
  4935. 41,
  4936. 42,
  4937. 43,
  4938. 44,
  4939. 45,
  4940. 46,
  4941. 47,
  4942. 48,
  4943. 49,
  4944. 50,
  4945. 51
  4946. ];
  4947. function base64Decode$1(source, target) {
  4948. var sourceLength = source.length;
  4949. var paddingLength = source[sourceLength - 2] === "=" ? 2 : source[sourceLength - 1] === "=" ? 1 : 0;
  4950. var tmp;
  4951. var byteIndex = 0;
  4952. var baseLength = sourceLength - paddingLength & 4294967292;
  4953. for (var i2 = 0; i2 < baseLength; i2 += 4) {
  4954. tmp = lookup[source.charCodeAt(i2)] << 18 | lookup[source.charCodeAt(i2 + 1)] << 12 | lookup[source.charCodeAt(i2 + 2)] << 6 | lookup[source.charCodeAt(i2 + 3)];
  4955. target[byteIndex++] = tmp >> 16 & 255;
  4956. target[byteIndex++] = tmp >> 8 & 255;
  4957. target[byteIndex++] = tmp & 255;
  4958. }
  4959. if (paddingLength === 1) {
  4960. tmp = lookup[source.charCodeAt(i2)] << 10 | lookup[source.charCodeAt(i2 + 1)] << 4 | lookup[source.charCodeAt(i2 + 2)] >> 2;
  4961. target[byteIndex++] = tmp >> 8 & 255;
  4962. target[byteIndex++] = tmp & 255;
  4963. }
  4964. if (paddingLength === 2) {
  4965. tmp = lookup[source.charCodeAt(i2)] << 2 | lookup[source.charCodeAt(i2 + 1)] >> 4;
  4966. target[byteIndex++] = tmp & 255;
  4967. }
  4968. }
  4969. const $inject_window_crypto = {
  4970. getRandomValues(arr) {
  4971. if (!(arr instanceof Int8Array || arr instanceof Uint8Array || arr instanceof Int16Array || arr instanceof Uint16Array || arr instanceof Int32Array || arr instanceof Uint32Array || arr instanceof Uint8ClampedArray)) {
  4972. throw new Error("Expected an integer array");
  4973. }
  4974. if (arr.byteLength > 65536) {
  4975. throw new Error("Can only request a maximum of 65536 bytes");
  4976. }
  4977. var crypto = requireNativePlugin("DCloud-Crypto");
  4978. base64Decode$1(crypto.getRandomValues(arr.byteLength), new Uint8Array(
  4979. arr.buffer,
  4980. arr.byteOffset,
  4981. arr.byteLength
  4982. ));
  4983. return arr;
  4984. }
  4985. };
  4986. const isFiniteNumber = Number.isFinite || function(value2) {
  4987. return typeof value2 === "number" && isFinite(value2);
  4988. };
  4989. const isSafeInteger = Number.isSafeInteger || function(value2) {
  4990. return typeof value2 === "number" && Math.abs(value2) <= MAX_SAFE_INTEGER;
  4991. };
  4992. const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  4993. let ErrorTypes = /* @__PURE__ */ function(ErrorTypes2) {
  4994. ErrorTypes2["NETWORK_ERROR"] = "networkError";
  4995. ErrorTypes2["MEDIA_ERROR"] = "mediaError";
  4996. ErrorTypes2["KEY_SYSTEM_ERROR"] = "keySystemError";
  4997. ErrorTypes2["MUX_ERROR"] = "muxError";
  4998. ErrorTypes2["OTHER_ERROR"] = "otherError";
  4999. return ErrorTypes2;
  5000. }({});
  5001. let ErrorDetails = /* @__PURE__ */ function(ErrorDetails2) {
  5002. ErrorDetails2["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  5003. ErrorDetails2["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  5004. ErrorDetails2["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  5005. ErrorDetails2["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  5006. ErrorDetails2["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  5007. ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  5008. ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  5009. ErrorDetails2["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  5010. ErrorDetails2["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  5011. ErrorDetails2["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  5012. ErrorDetails2["KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR"] = "keySystemDestroyMediaKeysError";
  5013. ErrorDetails2["KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR"] = "keySystemDestroyCloseSessionError";
  5014. ErrorDetails2["KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR"] = "keySystemDestroyRemoveSessionError";
  5015. ErrorDetails2["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  5016. ErrorDetails2["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  5017. ErrorDetails2["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  5018. ErrorDetails2["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  5019. ErrorDetails2["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  5020. ErrorDetails2["LEVEL_LOAD_ERROR"] = "levelLoadError";
  5021. ErrorDetails2["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  5022. ErrorDetails2["LEVEL_PARSING_ERROR"] = "levelParsingError";
  5023. ErrorDetails2["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  5024. ErrorDetails2["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  5025. ErrorDetails2["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  5026. ErrorDetails2["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  5027. ErrorDetails2["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  5028. ErrorDetails2["FRAG_LOAD_ERROR"] = "fragLoadError";
  5029. ErrorDetails2["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  5030. ErrorDetails2["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  5031. ErrorDetails2["FRAG_PARSING_ERROR"] = "fragParsingError";
  5032. ErrorDetails2["FRAG_GAP"] = "fragGap";
  5033. ErrorDetails2["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  5034. ErrorDetails2["KEY_LOAD_ERROR"] = "keyLoadError";
  5035. ErrorDetails2["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  5036. ErrorDetails2["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  5037. ErrorDetails2["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  5038. ErrorDetails2["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  5039. ErrorDetails2["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  5040. ErrorDetails2["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  5041. ErrorDetails2["BUFFER_FULL_ERROR"] = "bufferFullError";
  5042. ErrorDetails2["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  5043. ErrorDetails2["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  5044. ErrorDetails2["ASSET_LIST_LOAD_ERROR"] = "assetListLoadError";
  5045. ErrorDetails2["ASSET_LIST_LOAD_TIMEOUT"] = "assetListLoadTimeout";
  5046. ErrorDetails2["ASSET_LIST_PARSING_ERROR"] = "assetListParsingError";
  5047. ErrorDetails2["INTERSTITIAL_ASSET_ITEM_ERROR"] = "interstitialAssetItemError";
  5048. ErrorDetails2["INTERNAL_EXCEPTION"] = "internalException";
  5049. ErrorDetails2["INTERNAL_ABORTED"] = "aborted";
  5050. ErrorDetails2["ATTACH_MEDIA_ERROR"] = "attachMediaError";
  5051. ErrorDetails2["UNKNOWN"] = "unknown";
  5052. return ErrorDetails2;
  5053. }({});
  5054. let Events = /* @__PURE__ */ function(Events2) {
  5055. Events2["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  5056. Events2["MEDIA_ATTACHED"] = "hlsMediaAttached";
  5057. Events2["MEDIA_DETACHING"] = "hlsMediaDetaching";
  5058. Events2["MEDIA_DETACHED"] = "hlsMediaDetached";
  5059. Events2["MEDIA_ENDED"] = "hlsMediaEnded";
  5060. Events2["STALL_RESOLVED"] = "hlsStallResolved";
  5061. Events2["BUFFER_RESET"] = "hlsBufferReset";
  5062. Events2["BUFFER_CODECS"] = "hlsBufferCodecs";
  5063. Events2["BUFFER_CREATED"] = "hlsBufferCreated";
  5064. Events2["BUFFER_APPENDING"] = "hlsBufferAppending";
  5065. Events2["BUFFER_APPENDED"] = "hlsBufferAppended";
  5066. Events2["BUFFER_EOS"] = "hlsBufferEos";
  5067. Events2["BUFFERED_TO_END"] = "hlsBufferedToEnd";
  5068. Events2["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  5069. Events2["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  5070. Events2["MANIFEST_LOADING"] = "hlsManifestLoading";
  5071. Events2["MANIFEST_LOADED"] = "hlsManifestLoaded";
  5072. Events2["MANIFEST_PARSED"] = "hlsManifestParsed";
  5073. Events2["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  5074. Events2["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  5075. Events2["LEVEL_LOADING"] = "hlsLevelLoading";
  5076. Events2["LEVEL_LOADED"] = "hlsLevelLoaded";
  5077. Events2["LEVEL_UPDATED"] = "hlsLevelUpdated";
  5078. Events2["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  5079. Events2["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  5080. Events2["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  5081. Events2["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  5082. Events2["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  5083. Events2["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  5084. Events2["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  5085. Events2["AUDIO_TRACK_UPDATED"] = "hlsAudioTrackUpdated";
  5086. Events2["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  5087. Events2["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  5088. Events2["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  5089. Events2["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  5090. Events2["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  5091. Events2["SUBTITLE_TRACK_UPDATED"] = "hlsSubtitleTrackUpdated";
  5092. Events2["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  5093. Events2["CUES_PARSED"] = "hlsCuesParsed";
  5094. Events2["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  5095. Events2["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  5096. Events2["FRAG_LOADING"] = "hlsFragLoading";
  5097. Events2["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  5098. Events2["FRAG_LOADED"] = "hlsFragLoaded";
  5099. Events2["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  5100. Events2["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  5101. Events2["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  5102. Events2["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  5103. Events2["FRAG_PARSED"] = "hlsFragParsed";
  5104. Events2["FRAG_BUFFERED"] = "hlsFragBuffered";
  5105. Events2["FRAG_CHANGED"] = "hlsFragChanged";
  5106. Events2["FPS_DROP"] = "hlsFpsDrop";
  5107. Events2["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  5108. Events2["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  5109. Events2["ERROR"] = "hlsError";
  5110. Events2["DESTROYING"] = "hlsDestroying";
  5111. Events2["KEY_LOADING"] = "hlsKeyLoading";
  5112. Events2["KEY_LOADED"] = "hlsKeyLoaded";
  5113. Events2["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  5114. Events2["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  5115. Events2["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  5116. Events2["ASSET_LIST_LOADING"] = "hlsAssetListLoading";
  5117. Events2["ASSET_LIST_LOADED"] = "hlsAssetListLoaded";
  5118. Events2["INTERSTITIALS_UPDATED"] = "hlsInterstitialsUpdated";
  5119. Events2["INTERSTITIALS_BUFFERED_TO_BOUNDARY"] = "hlsInterstitialsBufferedToBoundary";
  5120. Events2["INTERSTITIAL_ASSET_PLAYER_CREATED"] = "hlsInterstitialAssetPlayerCreated";
  5121. Events2["INTERSTITIAL_STARTED"] = "hlsInterstitialStarted";
  5122. Events2["INTERSTITIAL_ASSET_STARTED"] = "hlsInterstitialAssetStarted";
  5123. Events2["INTERSTITIAL_ASSET_ENDED"] = "hlsInterstitialAssetEnded";
  5124. Events2["INTERSTITIAL_ASSET_ERROR"] = "hlsInterstitialAssetError";
  5125. Events2["INTERSTITIAL_ENDED"] = "hlsInterstitialEnded";
  5126. Events2["INTERSTITIALS_PRIMARY_RESUMED"] = "hlsInterstitialsPrimaryResumed";
  5127. Events2["PLAYOUT_LIMIT_REACHED"] = "hlsPlayoutLimitReached";
  5128. Events2["EVENT_CUE_ENTER"] = "hlsEventCueEnter";
  5129. return Events2;
  5130. }({});
  5131. var PlaylistContextType = {
  5132. MANIFEST: "manifest",
  5133. LEVEL: "level",
  5134. AUDIO_TRACK: "audioTrack",
  5135. SUBTITLE_TRACK: "subtitleTrack"
  5136. };
  5137. var PlaylistLevelType = {
  5138. MAIN: "main",
  5139. AUDIO: "audio",
  5140. SUBTITLE: "subtitle"
  5141. };
  5142. class EWMA {
  5143. // About half of the estimated value will be from the last |halfLife| samples by weight.
  5144. constructor(halfLife, estimate = 0, weight = 0) {
  5145. this.halfLife = void 0;
  5146. this.alpha_ = void 0;
  5147. this.estimate_ = void 0;
  5148. this.totalWeight_ = void 0;
  5149. this.halfLife = halfLife;
  5150. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  5151. this.estimate_ = estimate;
  5152. this.totalWeight_ = weight;
  5153. }
  5154. sample(weight, value2) {
  5155. const adjAlpha = Math.pow(this.alpha_, weight);
  5156. this.estimate_ = value2 * (1 - adjAlpha) + adjAlpha * this.estimate_;
  5157. this.totalWeight_ += weight;
  5158. }
  5159. getTotalWeight() {
  5160. return this.totalWeight_;
  5161. }
  5162. getEstimate() {
  5163. if (this.alpha_) {
  5164. const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  5165. if (zeroFactor) {
  5166. return this.estimate_ / zeroFactor;
  5167. }
  5168. }
  5169. return this.estimate_;
  5170. }
  5171. }
  5172. class EwmaBandWidthEstimator {
  5173. constructor(slow, fast, defaultEstimate, defaultTTFB = 100) {
  5174. this.defaultEstimate_ = void 0;
  5175. this.minWeight_ = void 0;
  5176. this.minDelayMs_ = void 0;
  5177. this.slow_ = void 0;
  5178. this.fast_ = void 0;
  5179. this.defaultTTFB_ = void 0;
  5180. this.ttfb_ = void 0;
  5181. this.defaultEstimate_ = defaultEstimate;
  5182. this.minWeight_ = 1e-3;
  5183. this.minDelayMs_ = 50;
  5184. this.slow_ = new EWMA(slow);
  5185. this.fast_ = new EWMA(fast);
  5186. this.defaultTTFB_ = defaultTTFB;
  5187. this.ttfb_ = new EWMA(slow);
  5188. }
  5189. update(slow, fast) {
  5190. const {
  5191. slow_,
  5192. fast_,
  5193. ttfb_
  5194. } = this;
  5195. if (slow_.halfLife !== slow) {
  5196. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  5197. }
  5198. if (fast_.halfLife !== fast) {
  5199. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  5200. }
  5201. if (ttfb_.halfLife !== slow) {
  5202. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  5203. }
  5204. }
  5205. sample(durationMs, numBytes) {
  5206. durationMs = Math.max(durationMs, this.minDelayMs_);
  5207. const numBits = 8 * numBytes;
  5208. const durationS = durationMs / 1e3;
  5209. const bandwidthInBps = numBits / durationS;
  5210. this.fast_.sample(durationS, bandwidthInBps);
  5211. this.slow_.sample(durationS, bandwidthInBps);
  5212. }
  5213. sampleTTFB(ttfb) {
  5214. const seconds = ttfb / 1e3;
  5215. const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  5216. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  5217. }
  5218. canEstimate() {
  5219. return this.fast_.getTotalWeight() >= this.minWeight_;
  5220. }
  5221. getEstimate() {
  5222. if (this.canEstimate()) {
  5223. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  5224. } else {
  5225. return this.defaultEstimate_;
  5226. }
  5227. }
  5228. getEstimateTTFB() {
  5229. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  5230. return this.ttfb_.getEstimate();
  5231. } else {
  5232. return this.defaultTTFB_;
  5233. }
  5234. }
  5235. get defaultEstimate() {
  5236. return this.defaultEstimate_;
  5237. }
  5238. destroy() {
  5239. }
  5240. }
  5241. function _defineProperty(e2, r2, t2) {
  5242. return (r2 = _toPropertyKey(r2)) in e2 ? Object.defineProperty(e2, r2, {
  5243. value: t2,
  5244. enumerable: true,
  5245. configurable: true,
  5246. writable: true
  5247. }) : e2[r2] = t2, e2;
  5248. }
  5249. function _extends() {
  5250. return _extends = Object.assign ? Object.assign.bind() : function(n2) {
  5251. for (var e2 = 1; e2 < arguments.length; e2++) {
  5252. var t2 = arguments[e2];
  5253. for (var r2 in t2)
  5254. ({}).hasOwnProperty.call(t2, r2) && (n2[r2] = t2[r2]);
  5255. }
  5256. return n2;
  5257. }, _extends.apply(null, arguments);
  5258. }
  5259. function ownKeys(e2, r2) {
  5260. var t2 = Object.keys(e2);
  5261. if (Object.getOwnPropertySymbols) {
  5262. var o2 = Object.getOwnPropertySymbols(e2);
  5263. r2 && (o2 = o2.filter(function(r3) {
  5264. return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
  5265. })), t2.push.apply(t2, o2);
  5266. }
  5267. return t2;
  5268. }
  5269. function _objectSpread2(e2) {
  5270. for (var r2 = 1; r2 < arguments.length; r2++) {
  5271. var t2 = null != arguments[r2] ? arguments[r2] : {};
  5272. r2 % 2 ? ownKeys(Object(t2), true).forEach(function(r3) {
  5273. _defineProperty(e2, r3, t2[r3]);
  5274. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t2)) : ownKeys(Object(t2)).forEach(function(r3) {
  5275. Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t2, r3));
  5276. });
  5277. }
  5278. return e2;
  5279. }
  5280. function _toPrimitive(t2, r2) {
  5281. if ("object" != typeof t2 || !t2)
  5282. return t2;
  5283. var e2 = t2[Symbol.toPrimitive];
  5284. if (void 0 !== e2) {
  5285. var i2 = e2.call(t2, r2);
  5286. if ("object" != typeof i2)
  5287. return i2;
  5288. throw new TypeError("@@toPrimitive must return a primitive value.");
  5289. }
  5290. return ("string" === r2 ? String : Number)(t2);
  5291. }
  5292. function _toPropertyKey(t2) {
  5293. var i2 = _toPrimitive(t2, "string");
  5294. return "symbol" == typeof i2 ? i2 : i2 + "";
  5295. }
  5296. class Logger {
  5297. constructor(label, logger2) {
  5298. this.trace = void 0;
  5299. this.debug = void 0;
  5300. this.log = void 0;
  5301. this.warn = void 0;
  5302. this.info = void 0;
  5303. this.error = void 0;
  5304. const lb = `[${label}]:`;
  5305. this.trace = noop;
  5306. this.debug = logger2.debug.bind(null, lb);
  5307. this.log = logger2.log.bind(null, lb);
  5308. this.warn = logger2.warn.bind(null, lb);
  5309. this.info = logger2.info.bind(null, lb);
  5310. this.error = logger2.error.bind(null, lb);
  5311. }
  5312. }
  5313. const noop = function noop2() {
  5314. };
  5315. const fakeLogger = {
  5316. trace: noop,
  5317. debug: noop,
  5318. log: noop,
  5319. warn: noop,
  5320. info: noop,
  5321. error: noop
  5322. };
  5323. function createLogger() {
  5324. return _extends({}, fakeLogger);
  5325. }
  5326. function consolePrintFn(type, id) {
  5327. const func2 = self.console[type];
  5328. return func2 ? func2.bind(self.console, `${id ? "[" + id + "] " : ""}[${type}] >`) : noop;
  5329. }
  5330. function getLoggerFn(key, debugConfig, id) {
  5331. return debugConfig[key] ? debugConfig[key].bind(debugConfig) : consolePrintFn(key, id);
  5332. }
  5333. const exportedLogger = createLogger();
  5334. function enableLogs(debugConfig, context, id) {
  5335. const newLogger = createLogger();
  5336. if (typeof console === "object" && debugConfig === true || typeof debugConfig === "object") {
  5337. const keys = [
  5338. // Remove out from list here to hard-disable a log-level
  5339. // 'trace',
  5340. "debug",
  5341. "log",
  5342. "info",
  5343. "warn",
  5344. "error"
  5345. ];
  5346. keys.forEach((key) => {
  5347. newLogger[key] = getLoggerFn(key, debugConfig, id);
  5348. });
  5349. try {
  5350. newLogger.log(`Debug logs enabled for "${context}" in hls.js version ${"1.6.7"}`);
  5351. } catch (e2) {
  5352. return createLogger();
  5353. }
  5354. keys.forEach((key) => {
  5355. exportedLogger[key] = getLoggerFn(key, debugConfig);
  5356. });
  5357. } else {
  5358. _extends(exportedLogger, newLogger);
  5359. }
  5360. return newLogger;
  5361. }
  5362. const logger = exportedLogger;
  5363. function getMediaSource(preferManagedMediaSource = true) {
  5364. if (typeof self === "undefined")
  5365. return void 0;
  5366. const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  5367. return mms || self.MediaSource || self.WebKitMediaSource;
  5368. }
  5369. function isManagedMediaSource(source) {
  5370. return typeof self !== "undefined" && source === self.ManagedMediaSource;
  5371. }
  5372. function isCompatibleTrackChange(currentTracks, requiredTracks) {
  5373. const trackNames = Object.keys(currentTracks);
  5374. const requiredTrackNames = Object.keys(requiredTracks);
  5375. const trackCount = trackNames.length;
  5376. const requiredTrackCount = requiredTrackNames.length;
  5377. return !trackCount || !requiredTrackCount || trackCount === requiredTrackCount && !trackNames.some((name) => requiredTrackNames.indexOf(name) === -1);
  5378. }
  5379. function utf8ArrayToStr(array2, exitOnNull = false) {
  5380. if (typeof TextDecoder !== "undefined") {
  5381. const decoder = new TextDecoder("utf-8");
  5382. const decoded = decoder.decode(array2);
  5383. if (exitOnNull) {
  5384. const idx = decoded.indexOf("\0");
  5385. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  5386. }
  5387. return decoded.replace(/\0/g, "");
  5388. }
  5389. const len = array2.length;
  5390. let c2;
  5391. let char2;
  5392. let char3;
  5393. let out = "";
  5394. let i2 = 0;
  5395. while (i2 < len) {
  5396. c2 = array2[i2++];
  5397. if (c2 === 0 && exitOnNull) {
  5398. return out;
  5399. } else if (c2 === 0 || c2 === 3) {
  5400. continue;
  5401. }
  5402. switch (c2 >> 4) {
  5403. case 0:
  5404. case 1:
  5405. case 2:
  5406. case 3:
  5407. case 4:
  5408. case 5:
  5409. case 6:
  5410. case 7:
  5411. out += String.fromCharCode(c2);
  5412. break;
  5413. case 12:
  5414. case 13:
  5415. char2 = array2[i2++];
  5416. out += String.fromCharCode((c2 & 31) << 6 | char2 & 63);
  5417. break;
  5418. case 14:
  5419. char2 = array2[i2++];
  5420. char3 = array2[i2++];
  5421. out += String.fromCharCode((c2 & 15) << 12 | (char2 & 63) << 6 | (char3 & 63) << 0);
  5422. break;
  5423. }
  5424. }
  5425. return out;
  5426. }
  5427. const Hex = {
  5428. hexDump: function(array2) {
  5429. let str = "";
  5430. for (let i2 = 0; i2 < array2.length; i2++) {
  5431. let h2 = array2[i2].toString(16);
  5432. if (h2.length < 2) {
  5433. h2 = "0" + h2;
  5434. }
  5435. str += h2;
  5436. }
  5437. return str;
  5438. }
  5439. };
  5440. function hexToArrayBuffer(str) {
  5441. return Uint8Array.from(str.replace(/^0x/, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")).buffer;
  5442. }
  5443. function getDefaultExportFromCjs$1(x) {
  5444. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
  5445. }
  5446. var urlToolkit = { exports: {} };
  5447. var hasRequiredUrlToolkit;
  5448. function requireUrlToolkit() {
  5449. if (hasRequiredUrlToolkit)
  5450. return urlToolkit.exports;
  5451. hasRequiredUrlToolkit = 1;
  5452. (function(module, exports) {
  5453. (function(root) {
  5454. var URL_REGEX = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  5455. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  5456. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  5457. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  5458. var URLToolkit = {
  5459. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  5460. // E.g
  5461. // With opts.alwaysNormalize = false (default, spec compliant)
  5462. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  5463. // With opts.alwaysNormalize = true (not spec compliant)
  5464. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  5465. buildAbsoluteURL: function(baseURL, relativeURL, opts) {
  5466. opts = opts || {};
  5467. baseURL = baseURL.trim();
  5468. relativeURL = relativeURL.trim();
  5469. if (!relativeURL) {
  5470. if (!opts.alwaysNormalize) {
  5471. return baseURL;
  5472. }
  5473. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  5474. if (!basePartsForNormalise) {
  5475. throw new Error("Error trying to parse base URL.");
  5476. }
  5477. basePartsForNormalise.path = URLToolkit.normalizePath(
  5478. basePartsForNormalise.path
  5479. );
  5480. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  5481. }
  5482. var relativeParts = URLToolkit.parseURL(relativeURL);
  5483. if (!relativeParts) {
  5484. throw new Error("Error trying to parse relative URL.");
  5485. }
  5486. if (relativeParts.scheme) {
  5487. if (!opts.alwaysNormalize) {
  5488. return relativeURL;
  5489. }
  5490. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  5491. return URLToolkit.buildURLFromParts(relativeParts);
  5492. }
  5493. var baseParts = URLToolkit.parseURL(baseURL);
  5494. if (!baseParts) {
  5495. throw new Error("Error trying to parse base URL.");
  5496. }
  5497. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== "/") {
  5498. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  5499. baseParts.netLoc = pathParts[1];
  5500. baseParts.path = pathParts[2];
  5501. }
  5502. if (baseParts.netLoc && !baseParts.path) {
  5503. baseParts.path = "/";
  5504. }
  5505. var builtParts = {
  5506. // 2c) Otherwise, the embedded URL inherits the scheme of
  5507. // the base URL.
  5508. scheme: baseParts.scheme,
  5509. netLoc: relativeParts.netLoc,
  5510. path: null,
  5511. params: relativeParts.params,
  5512. query: relativeParts.query,
  5513. fragment: relativeParts.fragment
  5514. };
  5515. if (!relativeParts.netLoc) {
  5516. builtParts.netLoc = baseParts.netLoc;
  5517. if (relativeParts.path[0] !== "/") {
  5518. if (!relativeParts.path) {
  5519. builtParts.path = baseParts.path;
  5520. if (!relativeParts.params) {
  5521. builtParts.params = baseParts.params;
  5522. if (!relativeParts.query) {
  5523. builtParts.query = baseParts.query;
  5524. }
  5525. }
  5526. } else {
  5527. var baseURLPath = baseParts.path;
  5528. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf("/") + 1) + relativeParts.path;
  5529. builtParts.path = URLToolkit.normalizePath(newPath);
  5530. }
  5531. }
  5532. }
  5533. if (builtParts.path === null) {
  5534. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  5535. }
  5536. return URLToolkit.buildURLFromParts(builtParts);
  5537. },
  5538. parseURL: function(url2) {
  5539. var parts = URL_REGEX.exec(url2);
  5540. if (!parts) {
  5541. return null;
  5542. }
  5543. return {
  5544. scheme: parts[1] || "",
  5545. netLoc: parts[2] || "",
  5546. path: parts[3] || "",
  5547. params: parts[4] || "",
  5548. query: parts[5] || "",
  5549. fragment: parts[6] || ""
  5550. };
  5551. },
  5552. normalizePath: function(path) {
  5553. path = path.split("").reverse().join("").replace(SLASH_DOT_REGEX, "");
  5554. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, "")).length) {
  5555. }
  5556. return path.split("").reverse().join("");
  5557. },
  5558. buildURLFromParts: function(parts) {
  5559. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  5560. }
  5561. };
  5562. module.exports = URLToolkit;
  5563. })();
  5564. })(urlToolkit);
  5565. return urlToolkit.exports;
  5566. }
  5567. var urlToolkitExports = requireUrlToolkit();
  5568. class LoadStats {
  5569. constructor() {
  5570. this.aborted = false;
  5571. this.loaded = 0;
  5572. this.retry = 0;
  5573. this.total = 0;
  5574. this.chunkCount = 0;
  5575. this.bwEstimate = 0;
  5576. this.loading = {
  5577. start: 0,
  5578. first: 0,
  5579. end: 0
  5580. };
  5581. this.parsing = {
  5582. start: 0,
  5583. end: 0
  5584. };
  5585. this.buffering = {
  5586. start: 0,
  5587. first: 0,
  5588. end: 0
  5589. };
  5590. }
  5591. }
  5592. var ElementaryStreamTypes = {
  5593. AUDIO: "audio",
  5594. VIDEO: "video",
  5595. AUDIOVIDEO: "audiovideo"
  5596. };
  5597. class BaseSegment {
  5598. constructor(base) {
  5599. this._byteRange = null;
  5600. this._url = null;
  5601. this._stats = null;
  5602. this._streams = null;
  5603. this.base = void 0;
  5604. this.relurl = void 0;
  5605. if (typeof base === "string") {
  5606. base = {
  5607. url: base
  5608. };
  5609. }
  5610. this.base = base;
  5611. makeEnumerable(this, "stats");
  5612. }
  5613. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  5614. setByteRange(value2, previous) {
  5615. const params = value2.split("@", 2);
  5616. let start;
  5617. if (params.length === 1) {
  5618. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  5619. } else {
  5620. start = parseInt(params[1]);
  5621. }
  5622. this._byteRange = [start, parseInt(params[0]) + start];
  5623. }
  5624. get baseurl() {
  5625. return this.base.url;
  5626. }
  5627. get byteRange() {
  5628. if (this._byteRange === null) {
  5629. return [];
  5630. }
  5631. return this._byteRange;
  5632. }
  5633. get byteRangeStartOffset() {
  5634. return this.byteRange[0];
  5635. }
  5636. get byteRangeEndOffset() {
  5637. return this.byteRange[1];
  5638. }
  5639. get elementaryStreams() {
  5640. if (this._streams === null) {
  5641. this._streams = {
  5642. [ElementaryStreamTypes.AUDIO]: null,
  5643. [ElementaryStreamTypes.VIDEO]: null,
  5644. [ElementaryStreamTypes.AUDIOVIDEO]: null
  5645. };
  5646. }
  5647. return this._streams;
  5648. }
  5649. set elementaryStreams(value2) {
  5650. this._streams = value2;
  5651. }
  5652. get hasStats() {
  5653. return this._stats !== null;
  5654. }
  5655. get hasStreams() {
  5656. return this._streams !== null;
  5657. }
  5658. get stats() {
  5659. if (this._stats === null) {
  5660. this._stats = new LoadStats();
  5661. }
  5662. return this._stats;
  5663. }
  5664. set stats(value2) {
  5665. this._stats = value2;
  5666. }
  5667. get url() {
  5668. if (!this._url && this.baseurl && this.relurl) {
  5669. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  5670. alwaysNormalize: true
  5671. });
  5672. }
  5673. return this._url || "";
  5674. }
  5675. set url(value2) {
  5676. this._url = value2;
  5677. }
  5678. clearElementaryStreamInfo() {
  5679. const {
  5680. elementaryStreams
  5681. } = this;
  5682. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  5683. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  5684. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  5685. }
  5686. }
  5687. function isMediaFragment(frag) {
  5688. return frag.sn !== "initSegment";
  5689. }
  5690. class Fragment extends BaseSegment {
  5691. constructor(type, base) {
  5692. super(base);
  5693. this._decryptdata = null;
  5694. this._programDateTime = null;
  5695. this._ref = null;
  5696. this._bitrate = void 0;
  5697. this.rawProgramDateTime = null;
  5698. this.tagList = [];
  5699. this.duration = 0;
  5700. this.sn = 0;
  5701. this.levelkeys = void 0;
  5702. this.type = void 0;
  5703. this.loader = null;
  5704. this.keyLoader = null;
  5705. this.level = -1;
  5706. this.cc = 0;
  5707. this.startPTS = void 0;
  5708. this.endPTS = void 0;
  5709. this.startDTS = void 0;
  5710. this.endDTS = void 0;
  5711. this.start = 0;
  5712. this.playlistOffset = 0;
  5713. this.deltaPTS = void 0;
  5714. this.maxStartPTS = void 0;
  5715. this.minEndPTS = void 0;
  5716. this.data = void 0;
  5717. this.bitrateTest = false;
  5718. this.title = null;
  5719. this.initSegment = null;
  5720. this.endList = void 0;
  5721. this.gap = void 0;
  5722. this.urlId = 0;
  5723. this.type = type;
  5724. }
  5725. get byteLength() {
  5726. if (this.hasStats) {
  5727. const total = this.stats.total;
  5728. if (total) {
  5729. return total;
  5730. }
  5731. }
  5732. if (this.byteRange) {
  5733. const start = this.byteRange[0];
  5734. const end = this.byteRange[1];
  5735. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  5736. return end - start;
  5737. }
  5738. }
  5739. return null;
  5740. }
  5741. get bitrate() {
  5742. if (this.byteLength) {
  5743. return this.byteLength * 8 / this.duration;
  5744. }
  5745. if (this._bitrate) {
  5746. return this._bitrate;
  5747. }
  5748. return null;
  5749. }
  5750. set bitrate(value2) {
  5751. this._bitrate = value2;
  5752. }
  5753. get decryptdata() {
  5754. const {
  5755. levelkeys
  5756. } = this;
  5757. if (!levelkeys && !this._decryptdata) {
  5758. return null;
  5759. }
  5760. if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
  5761. const key = this.levelkeys.identity;
  5762. if (key) {
  5763. this._decryptdata = key.getDecryptData(this.sn);
  5764. } else {
  5765. const keyFormats = Object.keys(this.levelkeys);
  5766. if (keyFormats.length === 1) {
  5767. return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
  5768. }
  5769. }
  5770. }
  5771. return this._decryptdata;
  5772. }
  5773. get end() {
  5774. return this.start + this.duration;
  5775. }
  5776. get endProgramDateTime() {
  5777. if (this.programDateTime === null) {
  5778. return null;
  5779. }
  5780. const duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  5781. return this.programDateTime + duration * 1e3;
  5782. }
  5783. get encrypted() {
  5784. var _this$_decryptdata;
  5785. if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
  5786. return true;
  5787. } else if (this.levelkeys) {
  5788. const keyFormats = Object.keys(this.levelkeys);
  5789. const len = keyFormats.length;
  5790. if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
  5791. return true;
  5792. }
  5793. }
  5794. return false;
  5795. }
  5796. get programDateTime() {
  5797. if (this._programDateTime === null && this.rawProgramDateTime) {
  5798. this.programDateTime = Date.parse(this.rawProgramDateTime);
  5799. }
  5800. return this._programDateTime;
  5801. }
  5802. set programDateTime(value2) {
  5803. if (!isFiniteNumber(value2)) {
  5804. this._programDateTime = this.rawProgramDateTime = null;
  5805. return;
  5806. }
  5807. this._programDateTime = value2;
  5808. }
  5809. get ref() {
  5810. if (!isMediaFragment(this)) {
  5811. return null;
  5812. }
  5813. if (!this._ref) {
  5814. this._ref = {
  5815. base: this.base,
  5816. start: this.start,
  5817. duration: this.duration,
  5818. sn: this.sn,
  5819. programDateTime: this.programDateTime
  5820. };
  5821. }
  5822. return this._ref;
  5823. }
  5824. addStart(value2) {
  5825. this.setStart(this.start + value2);
  5826. }
  5827. setStart(value2) {
  5828. this.start = value2;
  5829. if (this._ref) {
  5830. this._ref.start = value2;
  5831. }
  5832. }
  5833. setDuration(value2) {
  5834. this.duration = value2;
  5835. if (this._ref) {
  5836. this._ref.duration = value2;
  5837. }
  5838. }
  5839. setKeyFormat(keyFormat) {
  5840. if (this.levelkeys) {
  5841. const key = this.levelkeys[keyFormat];
  5842. if (key && !this._decryptdata) {
  5843. this._decryptdata = key.getDecryptData(this.sn);
  5844. }
  5845. }
  5846. }
  5847. abortRequests() {
  5848. var _this$loader, _this$keyLoader;
  5849. (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
  5850. (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  5851. }
  5852. setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial2 = false) {
  5853. const {
  5854. elementaryStreams
  5855. } = this;
  5856. const info = elementaryStreams[type];
  5857. if (!info) {
  5858. elementaryStreams[type] = {
  5859. startPTS,
  5860. endPTS,
  5861. startDTS,
  5862. endDTS,
  5863. partial: partial2
  5864. };
  5865. return;
  5866. }
  5867. info.startPTS = Math.min(info.startPTS, startPTS);
  5868. info.endPTS = Math.max(info.endPTS, endPTS);
  5869. info.startDTS = Math.min(info.startDTS, startDTS);
  5870. info.endDTS = Math.max(info.endDTS, endDTS);
  5871. }
  5872. }
  5873. class Part extends BaseSegment {
  5874. constructor(partAttrs, frag, base, index2, previous) {
  5875. super(base);
  5876. this.fragOffset = 0;
  5877. this.duration = 0;
  5878. this.gap = false;
  5879. this.independent = false;
  5880. this.relurl = void 0;
  5881. this.fragment = void 0;
  5882. this.index = void 0;
  5883. this.duration = partAttrs.decimalFloatingPoint("DURATION");
  5884. this.gap = partAttrs.bool("GAP");
  5885. this.independent = partAttrs.bool("INDEPENDENT");
  5886. this.relurl = partAttrs.enumeratedString("URI");
  5887. this.fragment = frag;
  5888. this.index = index2;
  5889. const byteRange = partAttrs.enumeratedString("BYTERANGE");
  5890. if (byteRange) {
  5891. this.setByteRange(byteRange, previous);
  5892. }
  5893. if (previous) {
  5894. this.fragOffset = previous.fragOffset + previous.duration;
  5895. }
  5896. }
  5897. get start() {
  5898. return this.fragment.start + this.fragOffset;
  5899. }
  5900. get end() {
  5901. return this.start + this.duration;
  5902. }
  5903. get loaded() {
  5904. const {
  5905. elementaryStreams
  5906. } = this;
  5907. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  5908. }
  5909. }
  5910. function getOwnPropertyDescriptorFromPrototypeChain(object2, property) {
  5911. const prototype = Object.getPrototypeOf(object2);
  5912. if (prototype) {
  5913. const propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, property);
  5914. if (propertyDescriptor) {
  5915. return propertyDescriptor;
  5916. }
  5917. return getOwnPropertyDescriptorFromPrototypeChain(prototype, property);
  5918. }
  5919. }
  5920. function makeEnumerable(object2, property) {
  5921. const d2 = getOwnPropertyDescriptorFromPrototypeChain(object2, property);
  5922. if (d2) {
  5923. d2.enumerable = true;
  5924. Object.defineProperty(object2, property, d2);
  5925. }
  5926. }
  5927. const UINT32_MAX$1 = Math.pow(2, 32) - 1;
  5928. const push = [].push;
  5929. const RemuxerTrackIdConfig = {
  5930. video: 1,
  5931. audio: 2,
  5932. id3: 3,
  5933. text: 4
  5934. };
  5935. function bin2str(data) {
  5936. return String.fromCharCode.apply(null, data);
  5937. }
  5938. function readUint16(buffer, offset) {
  5939. const val = buffer[offset] << 8 | buffer[offset + 1];
  5940. return val < 0 ? 65536 + val : val;
  5941. }
  5942. function readUint32(buffer, offset) {
  5943. const val = readSint32(buffer, offset);
  5944. return val < 0 ? 4294967296 + val : val;
  5945. }
  5946. function readUint64(buffer, offset) {
  5947. let result = readUint32(buffer, offset);
  5948. result *= Math.pow(2, 32);
  5949. result += readUint32(buffer, offset + 4);
  5950. return result;
  5951. }
  5952. function readSint32(buffer, offset) {
  5953. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  5954. }
  5955. function hasMoofData(data) {
  5956. const end = data.byteLength;
  5957. for (let i2 = 0; i2 < end; ) {
  5958. const size = readUint32(data, i2);
  5959. if (size > 8 && data[i2 + 4] === 109 && data[i2 + 5] === 111 && data[i2 + 6] === 111 && data[i2 + 7] === 102) {
  5960. return true;
  5961. }
  5962. i2 = size > 1 ? i2 + size : end;
  5963. }
  5964. return false;
  5965. }
  5966. function findBox(data, path) {
  5967. const results = [];
  5968. if (!path.length) {
  5969. return results;
  5970. }
  5971. const end = data.byteLength;
  5972. for (let i2 = 0; i2 < end; ) {
  5973. const size = readUint32(data, i2);
  5974. const type = bin2str(data.subarray(i2 + 4, i2 + 8));
  5975. const endbox = size > 1 ? i2 + size : end;
  5976. if (type === path[0]) {
  5977. if (path.length === 1) {
  5978. results.push(data.subarray(i2 + 8, endbox));
  5979. } else {
  5980. const subresults = findBox(data.subarray(i2 + 8, endbox), path.slice(1));
  5981. if (subresults.length) {
  5982. push.apply(results, subresults);
  5983. }
  5984. }
  5985. }
  5986. i2 = endbox;
  5987. }
  5988. return results;
  5989. }
  5990. function parseSegmentIndex(sidx) {
  5991. const references = [];
  5992. const version2 = sidx[0];
  5993. let index2 = 8;
  5994. const timescale = readUint32(sidx, index2);
  5995. index2 += 4;
  5996. let earliestPresentationTime = 0;
  5997. let firstOffset = 0;
  5998. if (version2 === 0) {
  5999. earliestPresentationTime = readUint32(sidx, index2);
  6000. firstOffset = readUint32(sidx, index2 + 4);
  6001. index2 += 8;
  6002. } else {
  6003. earliestPresentationTime = readUint64(sidx, index2);
  6004. firstOffset = readUint64(sidx, index2 + 8);
  6005. index2 += 16;
  6006. }
  6007. index2 += 2;
  6008. let startByte = sidx.length + firstOffset;
  6009. const referencesCount = readUint16(sidx, index2);
  6010. index2 += 2;
  6011. for (let i2 = 0; i2 < referencesCount; i2++) {
  6012. let referenceIndex = index2;
  6013. const referenceInfo = readUint32(sidx, referenceIndex);
  6014. referenceIndex += 4;
  6015. const referenceSize = referenceInfo & 2147483647;
  6016. const referenceType = (referenceInfo & 2147483648) >>> 31;
  6017. if (referenceType === 1) {
  6018. logger.warn("SIDX has hierarchical references (not supported)");
  6019. return null;
  6020. }
  6021. const subsegmentDuration = readUint32(sidx, referenceIndex);
  6022. referenceIndex += 4;
  6023. references.push({
  6024. referenceSize,
  6025. subsegmentDuration,
  6026. // unscaled
  6027. info: {
  6028. duration: subsegmentDuration / timescale,
  6029. start: startByte,
  6030. end: startByte + referenceSize - 1
  6031. }
  6032. });
  6033. startByte += referenceSize;
  6034. referenceIndex += 4;
  6035. index2 = referenceIndex;
  6036. }
  6037. return {
  6038. earliestPresentationTime,
  6039. timescale,
  6040. version: version2,
  6041. referencesCount,
  6042. references
  6043. };
  6044. }
  6045. function parseInitSegment(initSegment) {
  6046. const result = [];
  6047. const traks = findBox(initSegment, ["moov", "trak"]);
  6048. for (let i2 = 0; i2 < traks.length; i2++) {
  6049. const trak = traks[i2];
  6050. const tkhd = findBox(trak, ["tkhd"])[0];
  6051. if (tkhd) {
  6052. let version2 = tkhd[0];
  6053. const trackId = readUint32(tkhd, version2 === 0 ? 12 : 20);
  6054. const mdhd = findBox(trak, ["mdia", "mdhd"])[0];
  6055. if (mdhd) {
  6056. version2 = mdhd[0];
  6057. const timescale = readUint32(mdhd, version2 === 0 ? 12 : 20);
  6058. const hdlr = findBox(trak, ["mdia", "hdlr"])[0];
  6059. if (hdlr) {
  6060. const hdlrType = bin2str(hdlr.subarray(8, 12));
  6061. const type = {
  6062. soun: ElementaryStreamTypes.AUDIO,
  6063. vide: ElementaryStreamTypes.VIDEO
  6064. }[hdlrType];
  6065. const stsdBox = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
  6066. const stsd = parseStsd(stsdBox);
  6067. if (type) {
  6068. result[trackId] = {
  6069. timescale,
  6070. type,
  6071. stsd
  6072. };
  6073. result[type] = _objectSpread2({
  6074. timescale,
  6075. id: trackId
  6076. }, stsd);
  6077. } else {
  6078. result[trackId] = {
  6079. timescale,
  6080. type: hdlrType,
  6081. stsd
  6082. };
  6083. }
  6084. }
  6085. }
  6086. }
  6087. }
  6088. const trex = findBox(initSegment, ["moov", "mvex", "trex"]);
  6089. trex.forEach((trex2) => {
  6090. const trackId = readUint32(trex2, 4);
  6091. const track = result[trackId];
  6092. if (track) {
  6093. track.default = {
  6094. duration: readUint32(trex2, 12),
  6095. flags: readUint32(trex2, 20)
  6096. };
  6097. }
  6098. });
  6099. return result;
  6100. }
  6101. function parseStsd(stsd) {
  6102. const sampleEntries = stsd.subarray(8);
  6103. const sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  6104. const fourCC = bin2str(sampleEntries.subarray(4, 8));
  6105. let codec = fourCC;
  6106. let supplemental;
  6107. const encrypted = fourCC === "enca" || fourCC === "encv";
  6108. if (encrypted) {
  6109. const encBox = findBox(sampleEntries, [fourCC])[0];
  6110. const encBoxChildren = encBox.subarray(fourCC === "enca" ? 28 : 78);
  6111. const sinfs = findBox(encBoxChildren, ["sinf"]);
  6112. sinfs.forEach((sinf) => {
  6113. const schm = findBox(sinf, ["schm"])[0];
  6114. if (schm) {
  6115. const scheme = bin2str(schm.subarray(4, 8));
  6116. if (scheme === "cbcs" || scheme === "cenc") {
  6117. const frma = findBox(sinf, ["frma"])[0];
  6118. if (frma) {
  6119. codec = bin2str(frma);
  6120. }
  6121. }
  6122. }
  6123. });
  6124. }
  6125. const codecFourCC = codec;
  6126. switch (codec) {
  6127. case "avc1":
  6128. case "avc2":
  6129. case "avc3":
  6130. case "avc4": {
  6131. const avcCBox = findBox(sampleEntriesEnd, ["avcC"])[0];
  6132. if (avcCBox && avcCBox.length > 3) {
  6133. codec += "." + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  6134. supplemental = parseSupplementalDoViCodec(codecFourCC === "avc1" ? "dva1" : "dvav", sampleEntriesEnd);
  6135. }
  6136. break;
  6137. }
  6138. case "mp4a": {
  6139. const codecBox = findBox(sampleEntries, [fourCC])[0];
  6140. const esdsBox = findBox(codecBox.subarray(28), ["esds"])[0];
  6141. if (esdsBox && esdsBox.length > 7) {
  6142. let i2 = 4;
  6143. if (esdsBox[i2++] !== 3) {
  6144. break;
  6145. }
  6146. i2 = skipBERInteger(esdsBox, i2);
  6147. i2 += 2;
  6148. const flags = esdsBox[i2++];
  6149. if (flags & 128) {
  6150. i2 += 2;
  6151. }
  6152. if (flags & 64) {
  6153. i2 += esdsBox[i2++];
  6154. }
  6155. if (esdsBox[i2++] !== 4) {
  6156. break;
  6157. }
  6158. i2 = skipBERInteger(esdsBox, i2);
  6159. const objectType = esdsBox[i2++];
  6160. if (objectType === 64) {
  6161. codec += "." + toHex(objectType);
  6162. } else {
  6163. break;
  6164. }
  6165. i2 += 12;
  6166. if (esdsBox[i2++] !== 5) {
  6167. break;
  6168. }
  6169. i2 = skipBERInteger(esdsBox, i2);
  6170. const firstByte = esdsBox[i2++];
  6171. let audioObjectType = (firstByte & 248) >> 3;
  6172. if (audioObjectType === 31) {
  6173. audioObjectType += 1 + ((firstByte & 7) << 3) + ((esdsBox[i2] & 224) >> 5);
  6174. }
  6175. codec += "." + audioObjectType;
  6176. }
  6177. break;
  6178. }
  6179. case "hvc1":
  6180. case "hev1": {
  6181. const hvcCBox = findBox(sampleEntriesEnd, ["hvcC"])[0];
  6182. if (hvcCBox && hvcCBox.length > 12) {
  6183. const profileByte = hvcCBox[1];
  6184. const profileSpace = ["", "A", "B", "C"][profileByte >> 6];
  6185. const generalProfileIdc = profileByte & 31;
  6186. const profileCompat = readUint32(hvcCBox, 2);
  6187. const tierFlag = (profileByte & 32) >> 5 ? "H" : "L";
  6188. const levelIDC = hvcCBox[12];
  6189. const constraintIndicator = hvcCBox.subarray(6, 12);
  6190. codec += "." + profileSpace + generalProfileIdc;
  6191. codec += "." + reverse32BitInt(profileCompat).toString(16).toUpperCase();
  6192. codec += "." + tierFlag + levelIDC;
  6193. let constraintString = "";
  6194. for (let i2 = constraintIndicator.length; i2--; ) {
  6195. const byte = constraintIndicator[i2];
  6196. if (byte || constraintString) {
  6197. const encodedByte = byte.toString(16).toUpperCase();
  6198. constraintString = "." + encodedByte + constraintString;
  6199. }
  6200. }
  6201. codec += constraintString;
  6202. }
  6203. supplemental = parseSupplementalDoViCodec(codecFourCC == "hev1" ? "dvhe" : "dvh1", sampleEntriesEnd);
  6204. break;
  6205. }
  6206. case "dvh1":
  6207. case "dvhe":
  6208. case "dvav":
  6209. case "dva1":
  6210. case "dav1": {
  6211. codec = parseSupplementalDoViCodec(codec, sampleEntriesEnd) || codec;
  6212. break;
  6213. }
  6214. case "vp09": {
  6215. const vpcCBox = findBox(sampleEntriesEnd, ["vpcC"])[0];
  6216. if (vpcCBox && vpcCBox.length > 6) {
  6217. const profile = vpcCBox[4];
  6218. const level = vpcCBox[5];
  6219. const bitDepth = vpcCBox[6] >> 4 & 15;
  6220. codec += "." + addLeadingZero(profile) + "." + addLeadingZero(level) + "." + addLeadingZero(bitDepth);
  6221. }
  6222. break;
  6223. }
  6224. case "av01": {
  6225. const av1CBox = findBox(sampleEntriesEnd, ["av1C"])[0];
  6226. if (av1CBox && av1CBox.length > 2) {
  6227. const profile = av1CBox[1] >>> 5;
  6228. const level = av1CBox[1] & 31;
  6229. const tierFlag = av1CBox[2] >>> 7 ? "H" : "M";
  6230. const highBitDepth = (av1CBox[2] & 64) >> 6;
  6231. const twelveBit = (av1CBox[2] & 32) >> 5;
  6232. const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  6233. const monochrome = (av1CBox[2] & 16) >> 4;
  6234. const chromaSubsamplingX = (av1CBox[2] & 8) >> 3;
  6235. const chromaSubsamplingY = (av1CBox[2] & 4) >> 2;
  6236. const chromaSamplePosition = av1CBox[2] & 3;
  6237. const colorPrimaries = 1;
  6238. const transferCharacteristics = 1;
  6239. const matrixCoefficients = 1;
  6240. const videoFullRangeFlag = 0;
  6241. codec += "." + profile + "." + addLeadingZero(level) + tierFlag + "." + addLeadingZero(bitDepth) + "." + monochrome + "." + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + "." + addLeadingZero(colorPrimaries) + "." + addLeadingZero(transferCharacteristics) + "." + addLeadingZero(matrixCoefficients) + "." + videoFullRangeFlag;
  6242. supplemental = parseSupplementalDoViCodec("dav1", sampleEntriesEnd);
  6243. }
  6244. break;
  6245. }
  6246. }
  6247. return {
  6248. codec,
  6249. encrypted,
  6250. supplemental
  6251. };
  6252. }
  6253. function parseSupplementalDoViCodec(fourCC, sampleEntriesEnd) {
  6254. const dvvCResult = findBox(sampleEntriesEnd, ["dvvC"]);
  6255. const dvXCBox = dvvCResult.length ? dvvCResult[0] : findBox(sampleEntriesEnd, ["dvcC"])[0];
  6256. if (dvXCBox) {
  6257. const doViProfile = dvXCBox[2] >> 1 & 127;
  6258. const doViLevel = dvXCBox[2] << 5 & 32 | dvXCBox[3] >> 3 & 31;
  6259. return fourCC + "." + addLeadingZero(doViProfile) + "." + addLeadingZero(doViLevel);
  6260. }
  6261. }
  6262. function reverse32BitInt(val) {
  6263. let result = 0;
  6264. for (let i2 = 0; i2 < 32; i2++) {
  6265. result |= (val >> i2 & 1) << 32 - 1 - i2;
  6266. }
  6267. return result >>> 0;
  6268. }
  6269. function skipBERInteger(bytes, i2) {
  6270. const limit = i2 + 5;
  6271. while (bytes[i2++] & 128 && i2 < limit) {
  6272. }
  6273. return i2;
  6274. }
  6275. function toHex(x) {
  6276. return ("0" + x.toString(16).toUpperCase()).slice(-2);
  6277. }
  6278. function addLeadingZero(num) {
  6279. return (num < 10 ? "0" : "") + num;
  6280. }
  6281. function patchEncyptionData(initSegment, decryptdata) {
  6282. if (!initSegment || !decryptdata) {
  6283. return initSegment;
  6284. }
  6285. const keyId = decryptdata.keyId;
  6286. if (keyId && decryptdata.isCommonEncryption) {
  6287. const traks = findBox(initSegment, ["moov", "trak"]);
  6288. traks.forEach((trak) => {
  6289. const stsd = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
  6290. const sampleEntries = stsd.subarray(8);
  6291. let encBoxes = findBox(sampleEntries, ["enca"]);
  6292. const isAudio = encBoxes.length > 0;
  6293. if (!isAudio) {
  6294. encBoxes = findBox(sampleEntries, ["encv"]);
  6295. }
  6296. encBoxes.forEach((enc) => {
  6297. const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  6298. const sinfBoxes = findBox(encBoxChildren, ["sinf"]);
  6299. sinfBoxes.forEach((sinf) => {
  6300. const tenc = parseSinf(sinf);
  6301. if (tenc) {
  6302. const tencKeyId = tenc.subarray(8, 24);
  6303. if (!tencKeyId.some((b2) => b2 !== 0)) {
  6304. logger.log(`[eme] Patching keyId in 'enc${isAudio ? "a" : "v"}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`);
  6305. tenc.set(keyId, 8);
  6306. }
  6307. }
  6308. });
  6309. });
  6310. });
  6311. }
  6312. return initSegment;
  6313. }
  6314. function parseSinf(sinf) {
  6315. const schm = findBox(sinf, ["schm"])[0];
  6316. if (schm) {
  6317. const scheme = bin2str(schm.subarray(4, 8));
  6318. if (scheme === "cbcs" || scheme === "cenc") {
  6319. return findBox(sinf, ["schi", "tenc"])[0];
  6320. }
  6321. }
  6322. return null;
  6323. }
  6324. function getSampleData(data, initData, logger2) {
  6325. const tracks = {};
  6326. const trafs = findBox(data, ["moof", "traf"]);
  6327. for (let i2 = 0; i2 < trafs.length; i2++) {
  6328. const traf = trafs[i2];
  6329. const tfhd = findBox(traf, ["tfhd"])[0];
  6330. const id = readUint32(tfhd, 4);
  6331. const track = initData[id];
  6332. if (!track) {
  6333. continue;
  6334. }
  6335. const trackTimes = tracks[id] || (tracks[id] = {
  6336. start: NaN,
  6337. duration: 0,
  6338. sampleCount: 0,
  6339. timescale: track.timescale,
  6340. type: track.type
  6341. });
  6342. const tfdt = findBox(traf, ["tfdt"])[0];
  6343. if (tfdt) {
  6344. const version2 = tfdt[0];
  6345. let baseTime = readUint32(tfdt, 4);
  6346. if (version2 === 1) {
  6347. if (baseTime === UINT32_MAX$1) {
  6348. logger2.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);
  6349. } else {
  6350. baseTime *= UINT32_MAX$1 + 1;
  6351. baseTime += readUint32(tfdt, 8);
  6352. }
  6353. }
  6354. if (isFiniteNumber(baseTime) && (!isFiniteNumber(trackTimes.start) || baseTime < trackTimes.start)) {
  6355. trackTimes.start = baseTime;
  6356. }
  6357. }
  6358. const trackDefault = track.default;
  6359. const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  6360. let defaultSampleDuration = (trackDefault == null ? void 0 : trackDefault.duration) || 0;
  6361. if (tfhdFlags & 8) {
  6362. if (tfhdFlags & 2) {
  6363. defaultSampleDuration = readUint32(tfhd, 12);
  6364. } else {
  6365. defaultSampleDuration = readUint32(tfhd, 8);
  6366. }
  6367. }
  6368. const truns = findBox(traf, ["trun"]);
  6369. let sampleDTS = trackTimes.start || 0;
  6370. let rawDuration = 0;
  6371. let sampleDuration = defaultSampleDuration;
  6372. for (let j2 = 0; j2 < truns.length; j2++) {
  6373. const trun = truns[j2];
  6374. const sampleCount = readUint32(trun, 4);
  6375. const sampleIndex = trackTimes.sampleCount;
  6376. trackTimes.sampleCount += sampleCount;
  6377. const dataOffsetPresent = trun[3] & 1;
  6378. const firstSampleFlagsPresent = trun[3] & 4;
  6379. const sampleDurationPresent = trun[2] & 1;
  6380. const sampleSizePresent = trun[2] & 2;
  6381. const sampleFlagsPresent = trun[2] & 4;
  6382. const sampleCompositionTimeOffsetPresent = trun[2] & 8;
  6383. let offset = 8;
  6384. let remaining = sampleCount;
  6385. if (dataOffsetPresent) {
  6386. offset += 4;
  6387. }
  6388. if (firstSampleFlagsPresent && sampleCount) {
  6389. const isNonSyncSample = trun[offset + 1] & 1;
  6390. if (!isNonSyncSample && trackTimes.keyFrameIndex === void 0) {
  6391. trackTimes.keyFrameIndex = sampleIndex;
  6392. }
  6393. offset += 4;
  6394. if (sampleDurationPresent) {
  6395. sampleDuration = readUint32(trun, offset);
  6396. offset += 4;
  6397. } else {
  6398. sampleDuration = defaultSampleDuration;
  6399. }
  6400. if (sampleSizePresent) {
  6401. offset += 4;
  6402. }
  6403. if (sampleCompositionTimeOffsetPresent) {
  6404. offset += 4;
  6405. }
  6406. sampleDTS += sampleDuration;
  6407. rawDuration += sampleDuration;
  6408. remaining--;
  6409. }
  6410. while (remaining--) {
  6411. if (sampleDurationPresent) {
  6412. sampleDuration = readUint32(trun, offset);
  6413. offset += 4;
  6414. } else {
  6415. sampleDuration = defaultSampleDuration;
  6416. }
  6417. if (sampleSizePresent) {
  6418. offset += 4;
  6419. }
  6420. if (sampleFlagsPresent) {
  6421. const isNonSyncSample = trun[offset + 1] & 1;
  6422. if (!isNonSyncSample) {
  6423. if (trackTimes.keyFrameIndex === void 0) {
  6424. trackTimes.keyFrameIndex = trackTimes.sampleCount - (remaining + 1);
  6425. trackTimes.keyFrameStart = sampleDTS;
  6426. }
  6427. }
  6428. offset += 4;
  6429. }
  6430. if (sampleCompositionTimeOffsetPresent) {
  6431. offset += 4;
  6432. }
  6433. sampleDTS += sampleDuration;
  6434. rawDuration += sampleDuration;
  6435. }
  6436. if (!rawDuration && defaultSampleDuration) {
  6437. rawDuration += defaultSampleDuration * sampleCount;
  6438. }
  6439. }
  6440. trackTimes.duration += rawDuration;
  6441. }
  6442. if (!Object.keys(tracks).some((trackId) => tracks[trackId].duration)) {
  6443. let sidxMinStart = Infinity;
  6444. let sidxMaxEnd = 0;
  6445. const sidxs = findBox(data, ["sidx"]);
  6446. for (let i2 = 0; i2 < sidxs.length; i2++) {
  6447. const sidx = parseSegmentIndex(sidxs[i2]);
  6448. if (sidx != null && sidx.references) {
  6449. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  6450. const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0);
  6451. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  6452. }
  6453. }
  6454. if (sidxMaxEnd && isFiniteNumber(sidxMaxEnd)) {
  6455. Object.keys(tracks).forEach((trackId) => {
  6456. if (!tracks[trackId].duration) {
  6457. tracks[trackId].duration = sidxMaxEnd * tracks[trackId].timescale - tracks[trackId].start;
  6458. }
  6459. });
  6460. }
  6461. }
  6462. return tracks;
  6463. }
  6464. function segmentValidRange(data) {
  6465. const segmentedRange = {
  6466. valid: null,
  6467. remainder: null
  6468. };
  6469. const moofs = findBox(data, ["moof"]);
  6470. if (moofs.length < 2) {
  6471. segmentedRange.remainder = data;
  6472. return segmentedRange;
  6473. }
  6474. const last = moofs[moofs.length - 1];
  6475. segmentedRange.valid = data.slice(0, last.byteOffset - 8);
  6476. segmentedRange.remainder = data.slice(last.byteOffset - 8);
  6477. return segmentedRange;
  6478. }
  6479. function appendUint8Array(data1, data2) {
  6480. const temp = new Uint8Array(data1.length + data2.length);
  6481. temp.set(data1);
  6482. temp.set(data2, data1.length);
  6483. return temp;
  6484. }
  6485. function parseSamples(timeOffset, track) {
  6486. const seiSamples = [];
  6487. const videoData = track.samples;
  6488. const timescale = track.timescale;
  6489. const trackId = track.id;
  6490. let isHEVCFlavor = false;
  6491. const moofs = findBox(videoData, ["moof"]);
  6492. moofs.map((moof) => {
  6493. const moofOffset = moof.byteOffset - 8;
  6494. const trafs = findBox(moof, ["traf"]);
  6495. trafs.map((traf) => {
  6496. const baseTime = findBox(traf, ["tfdt"]).map((tfdt) => {
  6497. const version2 = tfdt[0];
  6498. let result = readUint32(tfdt, 4);
  6499. if (version2 === 1) {
  6500. result *= Math.pow(2, 32);
  6501. result += readUint32(tfdt, 8);
  6502. }
  6503. return result / timescale;
  6504. })[0];
  6505. if (baseTime !== void 0) {
  6506. timeOffset = baseTime;
  6507. }
  6508. return findBox(traf, ["tfhd"]).map((tfhd) => {
  6509. const id = readUint32(tfhd, 4);
  6510. const tfhdFlags = readUint32(tfhd, 0) & 16777215;
  6511. const baseDataOffsetPresent = (tfhdFlags & 1) !== 0;
  6512. const sampleDescriptionIndexPresent = (tfhdFlags & 2) !== 0;
  6513. const defaultSampleDurationPresent = (tfhdFlags & 8) !== 0;
  6514. let defaultSampleDuration = 0;
  6515. const defaultSampleSizePresent = (tfhdFlags & 16) !== 0;
  6516. let defaultSampleSize = 0;
  6517. const defaultSampleFlagsPresent = (tfhdFlags & 32) !== 0;
  6518. let tfhdOffset = 8;
  6519. if (id === trackId) {
  6520. if (baseDataOffsetPresent) {
  6521. tfhdOffset += 8;
  6522. }
  6523. if (sampleDescriptionIndexPresent) {
  6524. tfhdOffset += 4;
  6525. }
  6526. if (defaultSampleDurationPresent) {
  6527. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  6528. tfhdOffset += 4;
  6529. }
  6530. if (defaultSampleSizePresent) {
  6531. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  6532. tfhdOffset += 4;
  6533. }
  6534. if (defaultSampleFlagsPresent) {
  6535. tfhdOffset += 4;
  6536. }
  6537. if (track.type === "video") {
  6538. isHEVCFlavor = isHEVC(track.codec);
  6539. }
  6540. findBox(traf, ["trun"]).map((trun) => {
  6541. const version2 = trun[0];
  6542. const flags = readUint32(trun, 0) & 16777215;
  6543. const dataOffsetPresent = (flags & 1) !== 0;
  6544. let dataOffset = 0;
  6545. const firstSampleFlagsPresent = (flags & 4) !== 0;
  6546. const sampleDurationPresent = (flags & 256) !== 0;
  6547. let sampleDuration = 0;
  6548. const sampleSizePresent = (flags & 512) !== 0;
  6549. let sampleSize = 0;
  6550. const sampleFlagsPresent = (flags & 1024) !== 0;
  6551. const sampleCompositionOffsetsPresent = (flags & 2048) !== 0;
  6552. let compositionOffset = 0;
  6553. const sampleCount = readUint32(trun, 4);
  6554. let trunOffset = 8;
  6555. if (dataOffsetPresent) {
  6556. dataOffset = readUint32(trun, trunOffset);
  6557. trunOffset += 4;
  6558. }
  6559. if (firstSampleFlagsPresent) {
  6560. trunOffset += 4;
  6561. }
  6562. let sampleOffset = dataOffset + moofOffset;
  6563. for (let ix = 0; ix < sampleCount; ix++) {
  6564. if (sampleDurationPresent) {
  6565. sampleDuration = readUint32(trun, trunOffset);
  6566. trunOffset += 4;
  6567. } else {
  6568. sampleDuration = defaultSampleDuration;
  6569. }
  6570. if (sampleSizePresent) {
  6571. sampleSize = readUint32(trun, trunOffset);
  6572. trunOffset += 4;
  6573. } else {
  6574. sampleSize = defaultSampleSize;
  6575. }
  6576. if (sampleFlagsPresent) {
  6577. trunOffset += 4;
  6578. }
  6579. if (sampleCompositionOffsetsPresent) {
  6580. if (version2 === 0) {
  6581. compositionOffset = readUint32(trun, trunOffset);
  6582. } else {
  6583. compositionOffset = readSint32(trun, trunOffset);
  6584. }
  6585. trunOffset += 4;
  6586. }
  6587. if (track.type === ElementaryStreamTypes.VIDEO) {
  6588. let naluTotalSize = 0;
  6589. while (naluTotalSize < sampleSize) {
  6590. const naluSize = readUint32(videoData, sampleOffset);
  6591. sampleOffset += 4;
  6592. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  6593. const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  6594. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  6595. }
  6596. sampleOffset += naluSize;
  6597. naluTotalSize += naluSize + 4;
  6598. }
  6599. }
  6600. timeOffset += sampleDuration / timescale;
  6601. }
  6602. });
  6603. }
  6604. });
  6605. });
  6606. });
  6607. return seiSamples;
  6608. }
  6609. function isHEVC(codec) {
  6610. if (!codec) {
  6611. return false;
  6612. }
  6613. const baseCodec = codec.substring(0, 4);
  6614. return baseCodec === "hvc1" || baseCodec === "hev1" || // Dolby Vision
  6615. baseCodec === "dvh1" || baseCodec === "dvhe";
  6616. }
  6617. function isSEIMessage(isHEVCFlavor, naluHeader) {
  6618. if (isHEVCFlavor) {
  6619. const naluType = naluHeader >> 1 & 63;
  6620. return naluType === 39 || naluType === 40;
  6621. } else {
  6622. const naluType = naluHeader & 31;
  6623. return naluType === 6;
  6624. }
  6625. }
  6626. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  6627. const data = discardEPB(unescapedData);
  6628. let seiPtr = 0;
  6629. seiPtr += headerSize;
  6630. let payloadType = 0;
  6631. let payloadSize = 0;
  6632. let b2 = 0;
  6633. while (seiPtr < data.length) {
  6634. payloadType = 0;
  6635. do {
  6636. if (seiPtr >= data.length) {
  6637. break;
  6638. }
  6639. b2 = data[seiPtr++];
  6640. payloadType += b2;
  6641. } while (b2 === 255);
  6642. payloadSize = 0;
  6643. do {
  6644. if (seiPtr >= data.length) {
  6645. break;
  6646. }
  6647. b2 = data[seiPtr++];
  6648. payloadSize += b2;
  6649. } while (b2 === 255);
  6650. const leftOver = data.length - seiPtr;
  6651. let payPtr = seiPtr;
  6652. if (payloadSize < leftOver) {
  6653. seiPtr += payloadSize;
  6654. } else if (payloadSize > leftOver) {
  6655. logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);
  6656. break;
  6657. }
  6658. if (payloadType === 4) {
  6659. const countryCode = data[payPtr++];
  6660. if (countryCode === 181) {
  6661. const providerCode = readUint16(data, payPtr);
  6662. payPtr += 2;
  6663. if (providerCode === 49) {
  6664. const userStructure = readUint32(data, payPtr);
  6665. payPtr += 4;
  6666. if (userStructure === 1195456820) {
  6667. const userDataType = data[payPtr++];
  6668. if (userDataType === 3) {
  6669. const firstByte = data[payPtr++];
  6670. const totalCCs = 31 & firstByte;
  6671. const enabled = 64 & firstByte;
  6672. const totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  6673. const byteArray = new Uint8Array(totalBytes);
  6674. if (enabled) {
  6675. byteArray[0] = firstByte;
  6676. for (let i2 = 1; i2 < totalBytes; i2++) {
  6677. byteArray[i2] = data[payPtr++];
  6678. }
  6679. }
  6680. samples.push({
  6681. type: userDataType,
  6682. payloadType,
  6683. pts,
  6684. bytes: byteArray
  6685. });
  6686. }
  6687. }
  6688. }
  6689. }
  6690. } else if (payloadType === 5) {
  6691. if (payloadSize > 16) {
  6692. const uuidStrArray = [];
  6693. for (let i2 = 0; i2 < 16; i2++) {
  6694. const _b = data[payPtr++].toString(16);
  6695. uuidStrArray.push(_b.length == 1 ? "0" + _b : _b);
  6696. if (i2 === 3 || i2 === 5 || i2 === 7 || i2 === 9) {
  6697. uuidStrArray.push("-");
  6698. }
  6699. }
  6700. const length = payloadSize - 16;
  6701. const userDataBytes = new Uint8Array(length);
  6702. for (let i2 = 0; i2 < length; i2++) {
  6703. userDataBytes[i2] = data[payPtr++];
  6704. }
  6705. samples.push({
  6706. payloadType,
  6707. pts,
  6708. uuid: uuidStrArray.join(""),
  6709. userData: utf8ArrayToStr(userDataBytes),
  6710. userDataBytes
  6711. });
  6712. }
  6713. }
  6714. }
  6715. }
  6716. function discardEPB(data) {
  6717. const length = data.byteLength;
  6718. const EPBPositions = [];
  6719. let i2 = 1;
  6720. while (i2 < length - 2) {
  6721. if (data[i2] === 0 && data[i2 + 1] === 0 && data[i2 + 2] === 3) {
  6722. EPBPositions.push(i2 + 2);
  6723. i2 += 2;
  6724. } else {
  6725. i2++;
  6726. }
  6727. }
  6728. if (EPBPositions.length === 0) {
  6729. return data;
  6730. }
  6731. const newLength = length - EPBPositions.length;
  6732. const newData = new Uint8Array(newLength);
  6733. let sourceIndex = 0;
  6734. for (i2 = 0; i2 < newLength; sourceIndex++, i2++) {
  6735. if (sourceIndex === EPBPositions[0]) {
  6736. sourceIndex++;
  6737. EPBPositions.shift();
  6738. }
  6739. newData[i2] = data[sourceIndex];
  6740. }
  6741. return newData;
  6742. }
  6743. function parseEmsg(data) {
  6744. const version2 = data[0];
  6745. let schemeIdUri = "";
  6746. let value2 = "";
  6747. let timeScale = 0;
  6748. let presentationTimeDelta = 0;
  6749. let presentationTime = 0;
  6750. let eventDuration = 0;
  6751. let id = 0;
  6752. let offset = 0;
  6753. if (version2 === 0) {
  6754. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  6755. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  6756. offset += 1;
  6757. }
  6758. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  6759. offset += 1;
  6760. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  6761. value2 += bin2str(data.subarray(offset, offset + 1));
  6762. offset += 1;
  6763. }
  6764. value2 += bin2str(data.subarray(offset, offset + 1));
  6765. offset += 1;
  6766. timeScale = readUint32(data, 12);
  6767. presentationTimeDelta = readUint32(data, 16);
  6768. eventDuration = readUint32(data, 20);
  6769. id = readUint32(data, 24);
  6770. offset = 28;
  6771. } else if (version2 === 1) {
  6772. offset += 4;
  6773. timeScale = readUint32(data, offset);
  6774. offset += 4;
  6775. const leftPresentationTime = readUint32(data, offset);
  6776. offset += 4;
  6777. const rightPresentationTime = readUint32(data, offset);
  6778. offset += 4;
  6779. presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;
  6780. if (!isSafeInteger(presentationTime)) {
  6781. presentationTime = Number.MAX_SAFE_INTEGER;
  6782. logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box");
  6783. }
  6784. eventDuration = readUint32(data, offset);
  6785. offset += 4;
  6786. id = readUint32(data, offset);
  6787. offset += 4;
  6788. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  6789. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  6790. offset += 1;
  6791. }
  6792. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  6793. offset += 1;
  6794. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  6795. value2 += bin2str(data.subarray(offset, offset + 1));
  6796. offset += 1;
  6797. }
  6798. value2 += bin2str(data.subarray(offset, offset + 1));
  6799. offset += 1;
  6800. }
  6801. const payload = data.subarray(offset, data.byteLength);
  6802. return {
  6803. schemeIdUri,
  6804. value: value2,
  6805. timeScale,
  6806. presentationTime,
  6807. presentationTimeDelta,
  6808. eventDuration,
  6809. id,
  6810. payload
  6811. };
  6812. }
  6813. function mp4Box(type, ...payload) {
  6814. const len = payload.length;
  6815. let size = 8;
  6816. let i2 = len;
  6817. while (i2--) {
  6818. size += payload[i2].byteLength;
  6819. }
  6820. const result = new Uint8Array(size);
  6821. result[0] = size >> 24 & 255;
  6822. result[1] = size >> 16 & 255;
  6823. result[2] = size >> 8 & 255;
  6824. result[3] = size & 255;
  6825. result.set(type, 4);
  6826. for (i2 = 0, size = 8; i2 < len; i2++) {
  6827. result.set(payload[i2], size);
  6828. size += payload[i2].byteLength;
  6829. }
  6830. return result;
  6831. }
  6832. function mp4pssh(systemId, keyids, data) {
  6833. if (systemId.byteLength !== 16) {
  6834. throw new RangeError("Invalid system id");
  6835. }
  6836. let version2;
  6837. let kids;
  6838. {
  6839. version2 = 0;
  6840. kids = new Uint8Array();
  6841. }
  6842. let kidCount;
  6843. if (version2 > 0) {
  6844. kidCount = new Uint8Array(4);
  6845. if (keyids.length > 0) {
  6846. new DataView(kidCount.buffer).setUint32(0, keyids.length, false);
  6847. }
  6848. } else {
  6849. kidCount = new Uint8Array();
  6850. }
  6851. const dataSize = new Uint8Array(4);
  6852. if (data && data.byteLength > 0) {
  6853. new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);
  6854. }
  6855. return mp4Box(
  6856. [112, 115, 115, 104],
  6857. new Uint8Array([
  6858. version2,
  6859. 0,
  6860. 0,
  6861. 0
  6862. // Flags
  6863. ]),
  6864. systemId,
  6865. // 16 bytes
  6866. kidCount,
  6867. kids,
  6868. dataSize,
  6869. data || new Uint8Array()
  6870. );
  6871. }
  6872. const userAgentHevcSupportIsInaccurate = () => {
  6873. return /\(Windows.+Firefox\//i.test(navigator.userAgent);
  6874. };
  6875. const sampleEntryCodesISO = {
  6876. audio: {
  6877. a3ds: 1,
  6878. "ac-3": 0.95,
  6879. "ac-4": 1,
  6880. alac: 0.9,
  6881. alaw: 1,
  6882. dra1: 1,
  6883. "dts+": 1,
  6884. "dts-": 1,
  6885. dtsc: 1,
  6886. dtse: 1,
  6887. dtsh: 1,
  6888. "ec-3": 0.9,
  6889. enca: 1,
  6890. fLaC: 0.9,
  6891. // MP4-RA listed codec entry for FLAC
  6892. flac: 0.9,
  6893. // legacy browser codec name for FLAC
  6894. FLAC: 0.9,
  6895. // some manifests may list "FLAC" with Apple's tools
  6896. g719: 1,
  6897. g726: 1,
  6898. m4ae: 1,
  6899. mha1: 1,
  6900. mha2: 1,
  6901. mhm1: 1,
  6902. mhm2: 1,
  6903. mlpa: 1,
  6904. mp4a: 1,
  6905. "raw ": 1,
  6906. Opus: 1,
  6907. opus: 1,
  6908. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  6909. samr: 1,
  6910. sawb: 1,
  6911. sawp: 1,
  6912. sevc: 1,
  6913. sqcp: 1,
  6914. ssmv: 1,
  6915. twos: 1,
  6916. ulaw: 1
  6917. },
  6918. video: {
  6919. avc1: 1,
  6920. avc2: 1,
  6921. avc3: 1,
  6922. avc4: 1,
  6923. avcp: 1,
  6924. av01: 0.8,
  6925. dav1: 0.8,
  6926. drac: 1,
  6927. dva1: 1,
  6928. dvav: 1,
  6929. dvh1: 0.7,
  6930. dvhe: 0.7,
  6931. encv: 1,
  6932. hev1: 0.75,
  6933. hvc1: 0.75,
  6934. mjp2: 1,
  6935. mp4v: 1,
  6936. mvc1: 1,
  6937. mvc2: 1,
  6938. mvc3: 1,
  6939. mvc4: 1,
  6940. resv: 1,
  6941. rv60: 1,
  6942. s263: 1,
  6943. svc1: 1,
  6944. svc2: 1,
  6945. "vc-1": 1,
  6946. vp08: 1,
  6947. vp09: 0.9
  6948. },
  6949. text: {
  6950. stpp: 1,
  6951. wvtt: 1
  6952. }
  6953. };
  6954. function isCodecType(codec, type) {
  6955. const typeCodes = sampleEntryCodesISO[type];
  6956. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  6957. }
  6958. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) {
  6959. return !codecs.split(",").some((codec) => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource));
  6960. }
  6961. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) {
  6962. var _MediaSource$isTypeSu;
  6963. const MediaSource = getMediaSource(preferManagedMediaSource);
  6964. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  6965. }
  6966. function mimeTypeForCodec(codec, type) {
  6967. return `${type}/mp4;codecs=${codec}`;
  6968. }
  6969. function videoCodecPreferenceValue(videoCodec) {
  6970. if (videoCodec) {
  6971. const fourCC = videoCodec.substring(0, 4);
  6972. return sampleEntryCodesISO.video[fourCC];
  6973. }
  6974. return 2;
  6975. }
  6976. function codecsSetSelectionPreferenceValue(codecSet) {
  6977. const limitedHevcSupport = userAgentHevcSupportIsInaccurate();
  6978. return codecSet.split(",").reduce((num, fourCC) => {
  6979. const lowerPriority = limitedHevcSupport && isHEVC(fourCC);
  6980. const preferenceValue = lowerPriority ? 9 : sampleEntryCodesISO.video[fourCC];
  6981. if (preferenceValue) {
  6982. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  6983. }
  6984. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  6985. }, 0);
  6986. }
  6987. const CODEC_COMPATIBLE_NAMES = {};
  6988. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {
  6989. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  6990. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  6991. }
  6992. const codecsToCheck = {
  6993. // Idealy fLaC and Opus would be first (spec-compliant) but
  6994. // some browsers will report that fLaC is supported then fail.
  6995. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  6996. flac: ["flac", "fLaC", "FLAC"],
  6997. opus: ["opus", "Opus"],
  6998. // Replace audio codec info if browser does not support mp4a.40.34,
  6999. // and demuxer can fallback to 'audio/mpeg' or 'audio/mp4;codecs="mp3"'
  7000. "mp4a.40.34": ["mp3"]
  7001. }[lowerCaseCodec];
  7002. for (let i2 = 0; i2 < codecsToCheck.length; i2++) {
  7003. var _getMediaSource;
  7004. if (isCodecMediaSourceSupported(codecsToCheck[i2], "audio", preferManagedMediaSource)) {
  7005. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i2];
  7006. return codecsToCheck[i2];
  7007. } else if (codecsToCheck[i2] === "mp3" && (_getMediaSource = getMediaSource(preferManagedMediaSource)) != null && _getMediaSource.isTypeSupported("audio/mpeg")) {
  7008. return "";
  7009. }
  7010. }
  7011. return lowerCaseCodec;
  7012. }
  7013. const AUDIO_CODEC_REGEXP = /flac|opus|mp4a\.40\.34/i;
  7014. function getCodecCompatibleName(codec, preferManagedMediaSource = true) {
  7015. return codec.replace(AUDIO_CODEC_REGEXP, (m2) => getCodecCompatibleNameLower(m2.toLowerCase(), preferManagedMediaSource));
  7016. }
  7017. function replaceVideoCodec(originalCodecs, newVideoCodec) {
  7018. const codecs = [];
  7019. if (originalCodecs) {
  7020. const allCodecs = originalCodecs.split(",");
  7021. for (let i2 = 0; i2 < allCodecs.length; i2++) {
  7022. if (!isCodecType(allCodecs[i2], "video")) {
  7023. codecs.push(allCodecs[i2]);
  7024. }
  7025. }
  7026. }
  7027. if (newVideoCodec) {
  7028. codecs.push(newVideoCodec);
  7029. }
  7030. return codecs.join(",");
  7031. }
  7032. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  7033. if (parsedCodec && (parsedCodec.length > 4 || ["ac-3", "ec-3", "alac", "fLaC", "Opus"].indexOf(parsedCodec) !== -1)) {
  7034. if (isCodecSupportedAsType(parsedCodec, "audio") || isCodecSupportedAsType(parsedCodec, "video")) {
  7035. return parsedCodec;
  7036. }
  7037. }
  7038. if (levelCodec) {
  7039. const levelCodecs = levelCodec.split(",");
  7040. if (levelCodecs.length > 1) {
  7041. if (parsedCodec) {
  7042. for (let i2 = levelCodecs.length; i2--; ) {
  7043. if (levelCodecs[i2].substring(0, 4) === parsedCodec.substring(0, 4)) {
  7044. return levelCodecs[i2];
  7045. }
  7046. }
  7047. }
  7048. return levelCodecs[0];
  7049. }
  7050. }
  7051. return levelCodec || parsedCodec;
  7052. }
  7053. function isCodecSupportedAsType(codec, type) {
  7054. return isCodecType(codec, type) && isCodecMediaSourceSupported(codec, type);
  7055. }
  7056. function convertAVC1ToAVCOTI(videoCodecs) {
  7057. const codecs = videoCodecs.split(",");
  7058. for (let i2 = 0; i2 < codecs.length; i2++) {
  7059. const avcdata = codecs[i2].split(".");
  7060. if (avcdata.length > 2 && avcdata[0] === "avc1") {
  7061. codecs[i2] = `avc1.${parseInt(avcdata[1]).toString(16)}${("000" + parseInt(avcdata[2]).toString(16)).slice(-4)}`;
  7062. }
  7063. }
  7064. return codecs.join(",");
  7065. }
  7066. function fillInMissingAV01Params(videoCodec) {
  7067. if (videoCodec.startsWith("av01.")) {
  7068. const av1params = videoCodec.split(".");
  7069. const placeholders = ["0", "111", "01", "01", "01", "0"];
  7070. for (let i2 = av1params.length; i2 > 4 && i2 < 10; i2++) {
  7071. av1params[i2] = placeholders[i2 - 4];
  7072. }
  7073. return av1params.join(".");
  7074. }
  7075. return videoCodec;
  7076. }
  7077. function getM2TSSupportedAudioTypes(preferManagedMediaSource) {
  7078. const MediaSource = getMediaSource(preferManagedMediaSource) || {
  7079. isTypeSupported: () => false
  7080. };
  7081. return {
  7082. mpeg: MediaSource.isTypeSupported("audio/mpeg"),
  7083. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  7084. ac3: MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"')
  7085. };
  7086. }
  7087. function getCodecsForMimeType(mimeType) {
  7088. return mimeType.replace(/^.+codecs=["']?([^"']+).*$/, "$1");
  7089. }
  7090. const SUPPORTED_INFO_DEFAULT = {
  7091. supported: true,
  7092. configurations: [],
  7093. decodingInfoResults: [{
  7094. supported: true,
  7095. powerEfficient: true,
  7096. smooth: true
  7097. }]
  7098. };
  7099. function getUnsupportedResult(error2, configurations) {
  7100. return {
  7101. supported: false,
  7102. configurations,
  7103. decodingInfoResults: [{
  7104. supported: false,
  7105. smooth: false,
  7106. powerEfficient: false
  7107. }],
  7108. error: error2
  7109. };
  7110. }
  7111. function requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) {
  7112. const videoCodecs = level.videoCodec;
  7113. const audioGroups = level.audioCodec ? level.audioGroups : null;
  7114. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  7115. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  7116. const maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2;
  7117. let audioChannels = null;
  7118. if (audioGroups != null && audioGroups.length) {
  7119. try {
  7120. if (audioGroups.length === 1 && audioGroups[0]) {
  7121. audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;
  7122. } else {
  7123. audioChannels = audioGroups.reduce((acc, groupId) => {
  7124. if (groupId) {
  7125. const audioTrackGroup = audioTracksByGroup.groups[groupId];
  7126. if (!audioTrackGroup) {
  7127. throw new Error(`Audio track group ${groupId} not found`);
  7128. }
  7129. Object.keys(audioTrackGroup.channels).forEach((key) => {
  7130. acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];
  7131. });
  7132. }
  7133. return acc;
  7134. }, {
  7135. 2: 0
  7136. });
  7137. }
  7138. } catch (error2) {
  7139. return true;
  7140. }
  7141. }
  7142. return videoCodecs !== void 0 && // Force media capabilities check for HEVC to avoid failure on Windows
  7143. (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);
  7144. }
  7145. function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities, cache = {}) {
  7146. const videoCodecs = level.videoCodec;
  7147. if (!videoCodecs && !level.audioCodec || !mediaCapabilities) {
  7148. return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  7149. }
  7150. const configurations = [];
  7151. const videoDecodeList = makeVideoConfigurations(level);
  7152. const videoCount = videoDecodeList.length;
  7153. const audioDecodeList = makeAudioConfigurations(level, audioTracksByGroup, videoCount > 0);
  7154. const audioCount = audioDecodeList.length;
  7155. for (let i2 = videoCount || 1 * audioCount || 1; i2--; ) {
  7156. const configuration = {
  7157. type: "media-source"
  7158. };
  7159. if (videoCount) {
  7160. configuration.video = videoDecodeList[i2 % videoCount];
  7161. }
  7162. if (audioCount) {
  7163. configuration.audio = audioDecodeList[i2 % audioCount];
  7164. const audioBitrate = configuration.audio.bitrate;
  7165. if (configuration.video && audioBitrate) {
  7166. configuration.video.bitrate -= audioBitrate;
  7167. }
  7168. }
  7169. configurations.push(configuration);
  7170. }
  7171. if (videoCodecs) {
  7172. const ua = navigator.userAgent;
  7173. if (videoCodecs.split(",").some((videoCodec) => isHEVC(videoCodec)) && userAgentHevcSupportIsInaccurate()) {
  7174. return Promise.resolve(getUnsupportedResult(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${ua})`), configurations));
  7175. }
  7176. }
  7177. return Promise.all(configurations.map((configuration) => {
  7178. const decodingInfoKey = getMediaDecodingInfoKey(configuration);
  7179. return cache[decodingInfoKey] || (cache[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  7180. })).then((decodingInfoResults) => ({
  7181. supported: !decodingInfoResults.some((info) => !info.supported),
  7182. configurations,
  7183. decodingInfoResults
  7184. })).catch((error2) => ({
  7185. supported: false,
  7186. configurations,
  7187. decodingInfoResults: [],
  7188. error: error2
  7189. }));
  7190. }
  7191. function makeVideoConfigurations(level) {
  7192. var _level$videoCodec;
  7193. const videoCodecs = (_level$videoCodec = level.videoCodec) == null ? void 0 : _level$videoCodec.split(",");
  7194. const bitrate = getVariantDecodingBitrate(level);
  7195. const width = level.width || 640;
  7196. const height = level.height || 480;
  7197. const framerate = level.frameRate || 30;
  7198. const videoRange = level.videoRange.toLowerCase();
  7199. return videoCodecs ? videoCodecs.map((videoCodec) => {
  7200. const videoConfiguration = {
  7201. contentType: mimeTypeForCodec(fillInMissingAV01Params(videoCodec), "video"),
  7202. width,
  7203. height,
  7204. bitrate,
  7205. framerate
  7206. };
  7207. if (videoRange !== "sdr") {
  7208. videoConfiguration.transferFunction = videoRange;
  7209. }
  7210. return videoConfiguration;
  7211. }) : [];
  7212. }
  7213. function makeAudioConfigurations(level, audioTracksByGroup, hasVideo) {
  7214. var _level$audioCodec;
  7215. const audioCodecs = (_level$audioCodec = level.audioCodec) == null ? void 0 : _level$audioCodec.split(",");
  7216. const combinedBitrate = getVariantDecodingBitrate(level);
  7217. if (audioCodecs && level.audioGroups) {
  7218. return level.audioGroups.reduce((configurations, audioGroupId) => {
  7219. var _audioTracksByGroup$g;
  7220. const tracks = audioGroupId ? (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks : null;
  7221. if (tracks) {
  7222. return tracks.reduce((configs, audioTrack) => {
  7223. if (audioTrack.groupId === audioGroupId) {
  7224. const channelsNumber = parseFloat(audioTrack.channels || "");
  7225. audioCodecs.forEach((audioCodec) => {
  7226. const audioConfiguration = {
  7227. contentType: mimeTypeForCodec(audioCodec, "audio"),
  7228. bitrate: hasVideo ? estimatedAudioBitrate(audioCodec, combinedBitrate) : combinedBitrate
  7229. };
  7230. if (channelsNumber) {
  7231. audioConfiguration.channels = "" + channelsNumber;
  7232. }
  7233. configs.push(audioConfiguration);
  7234. });
  7235. }
  7236. return configs;
  7237. }, configurations);
  7238. }
  7239. return configurations;
  7240. }, []);
  7241. }
  7242. return [];
  7243. }
  7244. function estimatedAudioBitrate(audioCodec, levelBitrate) {
  7245. if (levelBitrate <= 1) {
  7246. return 1;
  7247. }
  7248. let audioBitrate = 128e3;
  7249. if (audioCodec === "ec-3") {
  7250. audioBitrate = 768e3;
  7251. } else if (audioCodec === "ac-3") {
  7252. audioBitrate = 64e4;
  7253. }
  7254. return Math.min(levelBitrate / 2, audioBitrate);
  7255. }
  7256. function getVariantDecodingBitrate(level) {
  7257. return Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate) / 1e3) * 1e3 || 1;
  7258. }
  7259. function getMediaDecodingInfoKey(config2) {
  7260. let key = "";
  7261. const {
  7262. audio,
  7263. video: video2
  7264. } = config2;
  7265. if (video2) {
  7266. const codec = getCodecsForMimeType(video2.contentType);
  7267. key += `${codec}_r${video2.height}x${video2.width}f${Math.ceil(video2.framerate)}${video2.transferFunction || "sd"}_${Math.ceil(video2.bitrate / 1e5)}`;
  7268. }
  7269. if (audio) {
  7270. const codec = getCodecsForMimeType(audio.contentType);
  7271. key += `${video2 ? "_" : ""}${codec}_c${audio.channels}`;
  7272. }
  7273. return key;
  7274. }
  7275. const HdcpLevels = ["NONE", "TYPE-0", "TYPE-1", null];
  7276. function isHdcpLevel(value2) {
  7277. return HdcpLevels.indexOf(value2) > -1;
  7278. }
  7279. const VideoRangeValues = ["SDR", "PQ", "HLG"];
  7280. function isVideoRange(value2) {
  7281. return !!value2 && VideoRangeValues.indexOf(value2) > -1;
  7282. }
  7283. var HlsSkip = {
  7284. No: "",
  7285. Yes: "YES",
  7286. v2: "v2"
  7287. };
  7288. function getSkipValue(details) {
  7289. const {
  7290. canSkipUntil,
  7291. canSkipDateRanges,
  7292. age
  7293. } = details;
  7294. const playlistRecentEnough = age < canSkipUntil / 2;
  7295. if (canSkipUntil && playlistRecentEnough) {
  7296. if (canSkipDateRanges) {
  7297. return HlsSkip.v2;
  7298. }
  7299. return HlsSkip.Yes;
  7300. }
  7301. return HlsSkip.No;
  7302. }
  7303. class HlsUrlParameters {
  7304. constructor(msn, part, skip) {
  7305. this.msn = void 0;
  7306. this.part = void 0;
  7307. this.skip = void 0;
  7308. this.msn = msn;
  7309. this.part = part;
  7310. this.skip = skip;
  7311. }
  7312. addDirectives(uri) {
  7313. const url2 = new self.URL(uri);
  7314. if (this.msn !== void 0) {
  7315. url2.searchParams.set("_HLS_msn", this.msn.toString());
  7316. }
  7317. if (this.part !== void 0) {
  7318. url2.searchParams.set("_HLS_part", this.part.toString());
  7319. }
  7320. if (this.skip) {
  7321. url2.searchParams.set("_HLS_skip", this.skip);
  7322. }
  7323. return url2.href;
  7324. }
  7325. }
  7326. class Level {
  7327. constructor(data) {
  7328. this._attrs = void 0;
  7329. this.audioCodec = void 0;
  7330. this.bitrate = void 0;
  7331. this.codecSet = void 0;
  7332. this.url = void 0;
  7333. this.frameRate = void 0;
  7334. this.height = void 0;
  7335. this.id = void 0;
  7336. this.name = void 0;
  7337. this.supplemental = void 0;
  7338. this.videoCodec = void 0;
  7339. this.width = void 0;
  7340. this.details = void 0;
  7341. this.fragmentError = 0;
  7342. this.loadError = 0;
  7343. this.loaded = void 0;
  7344. this.realBitrate = 0;
  7345. this.supportedPromise = void 0;
  7346. this.supportedResult = void 0;
  7347. this._avgBitrate = 0;
  7348. this._audioGroups = void 0;
  7349. this._subtitleGroups = void 0;
  7350. this._urlId = 0;
  7351. this.url = [data.url];
  7352. this._attrs = [data.attrs];
  7353. this.bitrate = data.bitrate;
  7354. if (data.details) {
  7355. this.details = data.details;
  7356. }
  7357. this.id = data.id || 0;
  7358. this.name = data.name;
  7359. this.width = data.width || 0;
  7360. this.height = data.height || 0;
  7361. this.frameRate = data.attrs.optionalFloat("FRAME-RATE", 0);
  7362. this._avgBitrate = data.attrs.decimalInteger("AVERAGE-BANDWIDTH");
  7363. this.audioCodec = data.audioCodec;
  7364. this.videoCodec = data.videoCodec;
  7365. this.codecSet = [data.videoCodec, data.audioCodec].filter((c2) => !!c2).map((s2) => s2.substring(0, 4)).join(",");
  7366. if ("supplemental" in data) {
  7367. var _data$supplemental;
  7368. this.supplemental = data.supplemental;
  7369. const supplementalVideo = (_data$supplemental = data.supplemental) == null ? void 0 : _data$supplemental.videoCodec;
  7370. if (supplementalVideo && supplementalVideo !== data.videoCodec) {
  7371. this.codecSet += `,${supplementalVideo.substring(0, 4)}`;
  7372. }
  7373. }
  7374. this.addGroupId("audio", data.attrs.AUDIO);
  7375. this.addGroupId("text", data.attrs.SUBTITLES);
  7376. }
  7377. get maxBitrate() {
  7378. return Math.max(this.realBitrate, this.bitrate);
  7379. }
  7380. get averageBitrate() {
  7381. return this._avgBitrate || this.realBitrate || this.bitrate;
  7382. }
  7383. get attrs() {
  7384. return this._attrs[0];
  7385. }
  7386. get codecs() {
  7387. return this.attrs.CODECS || "";
  7388. }
  7389. get pathwayId() {
  7390. return this.attrs["PATHWAY-ID"] || ".";
  7391. }
  7392. get videoRange() {
  7393. return this.attrs["VIDEO-RANGE"] || "SDR";
  7394. }
  7395. get score() {
  7396. return this.attrs.optionalFloat("SCORE", 0);
  7397. }
  7398. get uri() {
  7399. return this.url[0] || "";
  7400. }
  7401. hasAudioGroup(groupId) {
  7402. return hasGroup(this._audioGroups, groupId);
  7403. }
  7404. hasSubtitleGroup(groupId) {
  7405. return hasGroup(this._subtitleGroups, groupId);
  7406. }
  7407. get audioGroups() {
  7408. return this._audioGroups;
  7409. }
  7410. get subtitleGroups() {
  7411. return this._subtitleGroups;
  7412. }
  7413. addGroupId(type, groupId) {
  7414. if (!groupId) {
  7415. return;
  7416. }
  7417. if (type === "audio") {
  7418. let audioGroups = this._audioGroups;
  7419. if (!audioGroups) {
  7420. audioGroups = this._audioGroups = [];
  7421. }
  7422. if (audioGroups.indexOf(groupId) === -1) {
  7423. audioGroups.push(groupId);
  7424. }
  7425. } else if (type === "text") {
  7426. let subtitleGroups = this._subtitleGroups;
  7427. if (!subtitleGroups) {
  7428. subtitleGroups = this._subtitleGroups = [];
  7429. }
  7430. if (subtitleGroups.indexOf(groupId) === -1) {
  7431. subtitleGroups.push(groupId);
  7432. }
  7433. }
  7434. }
  7435. // Deprecated methods (retained for backwards compatibility)
  7436. get urlId() {
  7437. return 0;
  7438. }
  7439. set urlId(value2) {
  7440. }
  7441. get audioGroupIds() {
  7442. return this.audioGroups ? [this.audioGroupId] : void 0;
  7443. }
  7444. get textGroupIds() {
  7445. return this.subtitleGroups ? [this.textGroupId] : void 0;
  7446. }
  7447. get audioGroupId() {
  7448. var _this$audioGroups;
  7449. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  7450. }
  7451. get textGroupId() {
  7452. var _this$subtitleGroups;
  7453. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  7454. }
  7455. addFallback() {
  7456. }
  7457. }
  7458. function hasGroup(groups, groupId) {
  7459. if (!groupId || !groups) {
  7460. return false;
  7461. }
  7462. return groups.indexOf(groupId) !== -1;
  7463. }
  7464. function isHdrSupported() {
  7465. if (typeof matchMedia === "function") {
  7466. const mediaQueryList = matchMedia("(dynamic-range: high)");
  7467. const badQuery = matchMedia("bad query");
  7468. if (mediaQueryList.media !== badQuery.media) {
  7469. return mediaQueryList.matches === true;
  7470. }
  7471. }
  7472. return false;
  7473. }
  7474. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  7475. let preferHDR = false;
  7476. let allowedVideoRanges = [];
  7477. if (currentVideoRange) {
  7478. preferHDR = currentVideoRange !== "SDR";
  7479. allowedVideoRanges = [currentVideoRange];
  7480. }
  7481. if (videoPreference) {
  7482. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  7483. const allowAutoPreferHDR = allowedVideoRanges.join("") !== "SDR" && !videoPreference.videoCodec;
  7484. preferHDR = videoPreference.preferHDR !== void 0 ? videoPreference.preferHDR : allowAutoPreferHDR && isHdrSupported();
  7485. if (!preferHDR) {
  7486. allowedVideoRanges = ["SDR"];
  7487. }
  7488. }
  7489. return {
  7490. preferHDR,
  7491. allowedVideoRanges
  7492. };
  7493. }
  7494. const omitCircularRefsReplacer = (replacer) => {
  7495. const known = /* @__PURE__ */ new WeakSet();
  7496. return (_2, value2) => {
  7497. if (replacer) {
  7498. value2 = replacer(_2, value2);
  7499. }
  7500. if (typeof value2 === "object" && value2 !== null) {
  7501. if (known.has(value2)) {
  7502. return;
  7503. }
  7504. known.add(value2);
  7505. }
  7506. return value2;
  7507. };
  7508. };
  7509. const stringify = (object2, replacer) => JSON.stringify(object2, omitCircularRefsReplacer(replacer));
  7510. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  7511. const codecSets = Object.keys(codecTiers);
  7512. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  7513. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  7514. const videoCodecPreference = videoPreference == null ? void 0 : videoPreference.videoCodec;
  7515. const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  7516. let hasStereo = false;
  7517. let hasCurrentVideoRange = false;
  7518. let minHeight = Infinity;
  7519. let minFramerate = Infinity;
  7520. let minBitrate = Infinity;
  7521. let minIndex = Infinity;
  7522. let selectedScore = 0;
  7523. let videoRanges = [];
  7524. const {
  7525. preferHDR,
  7526. allowedVideoRanges
  7527. } = getVideoSelectionOptions(currentVideoRange, videoPreference);
  7528. for (let i2 = codecSets.length; i2--; ) {
  7529. const tier = codecTiers[codecSets[i2]];
  7530. hasStereo || (hasStereo = tier.channels[2] > 0);
  7531. minHeight = Math.min(minHeight, tier.minHeight);
  7532. minFramerate = Math.min(minFramerate, tier.minFramerate);
  7533. minBitrate = Math.min(minBitrate, tier.minBitrate);
  7534. const matchingVideoRanges = allowedVideoRanges.filter((range2) => tier.videoRanges[range2] > 0);
  7535. if (matchingVideoRanges.length > 0) {
  7536. hasCurrentVideoRange = true;
  7537. }
  7538. }
  7539. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  7540. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  7541. const maxHeight = Math.max(1080, minHeight);
  7542. const maxFramerate = Math.max(30, minFramerate);
  7543. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  7544. currentBw = Math.max(minBitrate, currentBw);
  7545. if (!hasCurrentVideoRange) {
  7546. currentVideoRange = void 0;
  7547. }
  7548. const hasMultipleSets = codecSets.length > 1;
  7549. const codecSet = codecSets.reduce((selected, candidate) => {
  7550. const candidateTier = codecTiers[candidate];
  7551. if (candidate === selected) {
  7552. return selected;
  7553. }
  7554. videoRanges = hasCurrentVideoRange ? allowedVideoRanges.filter((range2) => candidateTier.videoRanges[range2] > 0) : [];
  7555. if (hasMultipleSets) {
  7556. if (candidateTier.minBitrate > currentBw) {
  7557. logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);
  7558. return selected;
  7559. }
  7560. if (!candidateTier.hasDefaultAudio) {
  7561. logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);
  7562. return selected;
  7563. }
  7564. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  7565. logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`);
  7566. return selected;
  7567. }
  7568. if (channelsPreference && !preferStereo) {
  7569. if (!candidateTier.channels[channelsPreference]) {
  7570. logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);
  7571. return selected;
  7572. }
  7573. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels["2"] === 0) {
  7574. logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);
  7575. return selected;
  7576. }
  7577. if (candidateTier.minHeight > maxHeight) {
  7578. logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);
  7579. return selected;
  7580. }
  7581. if (candidateTier.minFramerate > maxFramerate) {
  7582. logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);
  7583. return selected;
  7584. }
  7585. if (!videoRanges.some((range2) => candidateTier.videoRanges[range2] > 0)) {
  7586. logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${stringify(videoRanges)} found`);
  7587. return selected;
  7588. }
  7589. if (videoCodecPreference && candidate.indexOf(videoCodecPreference.substring(0, 4)) % 5 !== 0) {
  7590. logStartCodecCandidateIgnored(candidate, `video codec preference "${videoCodecPreference}" not found`);
  7591. return selected;
  7592. }
  7593. if (candidateTier.maxScore < selectedScore) {
  7594. logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);
  7595. return selected;
  7596. }
  7597. }
  7598. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  7599. return selected;
  7600. }
  7601. minIndex = candidateTier.minIndex;
  7602. selectedScore = candidateTier.maxScore;
  7603. return candidate;
  7604. }, void 0);
  7605. return {
  7606. codecSet,
  7607. videoRanges,
  7608. preferHDR,
  7609. minFramerate,
  7610. minBitrate,
  7611. minIndex
  7612. };
  7613. }
  7614. function logStartCodecCandidateIgnored(codeSet, reason) {
  7615. logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`);
  7616. }
  7617. function getAudioTracksByGroup(allAudioTracks) {
  7618. return allAudioTracks.reduce((audioTracksByGroup, track) => {
  7619. let trackGroup = audioTracksByGroup.groups[track.groupId];
  7620. if (!trackGroup) {
  7621. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  7622. tracks: [],
  7623. channels: {
  7624. 2: 0
  7625. },
  7626. hasDefault: false,
  7627. hasAutoSelect: false
  7628. };
  7629. }
  7630. trackGroup.tracks.push(track);
  7631. const channelsKey = track.channels || "2";
  7632. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  7633. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  7634. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  7635. if (trackGroup.hasDefault) {
  7636. audioTracksByGroup.hasDefaultAudio = true;
  7637. }
  7638. if (trackGroup.hasAutoSelect) {
  7639. audioTracksByGroup.hasAutoSelectAudio = true;
  7640. }
  7641. return audioTracksByGroup;
  7642. }, {
  7643. hasDefaultAudio: false,
  7644. hasAutoSelectAudio: false,
  7645. groups: {}
  7646. });
  7647. }
  7648. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  7649. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level, index2) => {
  7650. if (!level.codecSet) {
  7651. return tiers;
  7652. }
  7653. const audioGroups = level.audioGroups;
  7654. let tier = tiers[level.codecSet];
  7655. if (!tier) {
  7656. tiers[level.codecSet] = tier = {
  7657. minBitrate: Infinity,
  7658. minHeight: Infinity,
  7659. minFramerate: Infinity,
  7660. minIndex: index2,
  7661. maxScore: 0,
  7662. videoRanges: {
  7663. SDR: 0
  7664. },
  7665. channels: {
  7666. "2": 0
  7667. },
  7668. hasDefaultAudio: !audioGroups,
  7669. fragmentError: 0
  7670. };
  7671. }
  7672. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  7673. const lesserWidthOrHeight = Math.min(level.height, level.width);
  7674. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  7675. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  7676. tier.minIndex = Math.min(tier.minIndex, index2);
  7677. tier.maxScore = Math.max(tier.maxScore, level.score);
  7678. tier.fragmentError += level.fragmentError;
  7679. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  7680. if (audioGroups) {
  7681. audioGroups.forEach((audioGroupId) => {
  7682. if (!audioGroupId) {
  7683. return;
  7684. }
  7685. const audioGroup = audioTracksByGroup.groups[audioGroupId];
  7686. if (!audioGroup) {
  7687. return;
  7688. }
  7689. tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio;
  7690. Object.keys(audioGroup.channels).forEach((channels) => {
  7691. tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels];
  7692. });
  7693. });
  7694. }
  7695. return tiers;
  7696. }, {});
  7697. }
  7698. function getBasicSelectionOption(option) {
  7699. if (!option) {
  7700. return option;
  7701. }
  7702. const {
  7703. lang,
  7704. assocLang,
  7705. characteristics,
  7706. channels,
  7707. audioCodec
  7708. } = option;
  7709. return {
  7710. lang,
  7711. assocLang,
  7712. characteristics,
  7713. channels,
  7714. audioCodec
  7715. };
  7716. }
  7717. function findMatchingOption(option, tracks, matchPredicate) {
  7718. if ("attrs" in option) {
  7719. const index2 = tracks.indexOf(option);
  7720. if (index2 !== -1) {
  7721. return index2;
  7722. }
  7723. }
  7724. for (let i2 = 0; i2 < tracks.length; i2++) {
  7725. const track = tracks[i2];
  7726. if (matchesOption(option, track, matchPredicate)) {
  7727. return i2;
  7728. }
  7729. }
  7730. return -1;
  7731. }
  7732. function matchesOption(option, track, matchPredicate) {
  7733. const {
  7734. groupId,
  7735. name,
  7736. lang,
  7737. assocLang,
  7738. default: isDefault
  7739. } = option;
  7740. const forced = option.forced;
  7741. return (groupId === void 0 || track.groupId === groupId) && (name === void 0 || track.name === name) && (lang === void 0 || languagesMatch(lang, track.lang)) && (lang === void 0 || track.assocLang === assocLang) && (isDefault === void 0 || track.default === isDefault) && (forced === void 0 || track.forced === forced) && (!("characteristics" in option) || characteristicsMatch(option.characteristics || "", track.characteristics)) && (matchPredicate === void 0 || matchPredicate(option, track));
  7742. }
  7743. function languagesMatch(languageA, languageB = "--") {
  7744. if (languageA.length === languageB.length) {
  7745. return languageA === languageB;
  7746. }
  7747. return languageA.startsWith(languageB) || languageB.startsWith(languageA);
  7748. }
  7749. function characteristicsMatch(characteristicsA, characteristicsB = "") {
  7750. const arrA = characteristicsA.split(",");
  7751. const arrB = characteristicsB.split(",");
  7752. return arrA.length === arrB.length && !arrA.some((el) => arrB.indexOf(el) === -1);
  7753. }
  7754. function audioMatchPredicate(option, track) {
  7755. const {
  7756. audioCodec,
  7757. channels
  7758. } = option;
  7759. return (audioCodec === void 0 || (track.audioCodec || "").substring(0, 4) === audioCodec.substring(0, 4)) && (channels === void 0 || channels === (track.channels || "2"));
  7760. }
  7761. function findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) {
  7762. const currentLevel = levels[searchIndex];
  7763. const variants = levels.reduce((variantMap, level, index2) => {
  7764. const uri = level.uri;
  7765. const renditions2 = variantMap[uri] || (variantMap[uri] = []);
  7766. renditions2.push(index2);
  7767. return variantMap;
  7768. }, {});
  7769. const renditions = variants[currentLevel.uri];
  7770. if (renditions.length > 1) {
  7771. searchIndex = Math.max.apply(Math, renditions);
  7772. }
  7773. const currentVideoRange = currentLevel.videoRange;
  7774. const currentFrameRate = currentLevel.frameRate;
  7775. const currentVideoCodec = currentLevel.codecSet.substring(0, 4);
  7776. const matchingVideo = searchDownAndUpList(levels, searchIndex, (level) => {
  7777. if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) {
  7778. return false;
  7779. }
  7780. const audioGroups = level.audioGroups;
  7781. const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  7782. return findMatchingOption(option, tracks, matchPredicate) > -1;
  7783. });
  7784. if (matchingVideo > -1) {
  7785. return matchingVideo;
  7786. }
  7787. return searchDownAndUpList(levels, searchIndex, (level) => {
  7788. const audioGroups = level.audioGroups;
  7789. const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  7790. return findMatchingOption(option, tracks, matchPredicate) > -1;
  7791. });
  7792. }
  7793. function searchDownAndUpList(arr, searchIndex, predicate) {
  7794. for (let i2 = searchIndex; i2 > -1; i2--) {
  7795. if (predicate(arr[i2])) {
  7796. return i2;
  7797. }
  7798. }
  7799. for (let i2 = searchIndex + 1; i2 < arr.length; i2++) {
  7800. if (predicate(arr[i2])) {
  7801. return i2;
  7802. }
  7803. }
  7804. return -1;
  7805. }
  7806. function useAlternateAudio(audioTrackUrl, hls) {
  7807. var _hls$loadLevelObj;
  7808. return !!audioTrackUrl && audioTrackUrl !== ((_hls$loadLevelObj = hls.loadLevelObj) == null ? void 0 : _hls$loadLevelObj.uri);
  7809. }
  7810. class AbrController extends Logger {
  7811. constructor(_hls) {
  7812. super("abr", _hls.logger);
  7813. this.hls = void 0;
  7814. this.lastLevelLoadSec = 0;
  7815. this.lastLoadedFragLevel = -1;
  7816. this.firstSelection = -1;
  7817. this._nextAutoLevel = -1;
  7818. this.nextAutoLevelKey = "";
  7819. this.audioTracksByGroup = null;
  7820. this.codecTiers = null;
  7821. this.timer = -1;
  7822. this.fragCurrent = null;
  7823. this.partCurrent = null;
  7824. this.bitrateTestDelay = 0;
  7825. this.rebufferNotice = -1;
  7826. this.supportedCache = {};
  7827. this.bwEstimator = void 0;
  7828. this._abandonRulesCheck = (levelLoaded) => {
  7829. var _ref;
  7830. const {
  7831. fragCurrent: frag,
  7832. partCurrent: part,
  7833. hls
  7834. } = this;
  7835. const {
  7836. autoLevelEnabled,
  7837. media
  7838. } = hls;
  7839. if (!frag || !media) {
  7840. return;
  7841. }
  7842. const now2 = performance.now();
  7843. const stats = part ? part.stats : frag.stats;
  7844. const duration = part ? part.duration : frag.duration;
  7845. const timeLoading = now2 - stats.loading.start;
  7846. const minAutoLevel = hls.minAutoLevel;
  7847. const loadingFragForLevel = frag.level;
  7848. const currentAutoLevel = this._nextAutoLevel;
  7849. if (stats.aborted || stats.loaded && stats.loaded === stats.total || loadingFragForLevel <= minAutoLevel) {
  7850. this.clearTimer();
  7851. this._nextAutoLevel = -1;
  7852. return;
  7853. }
  7854. if (!autoLevelEnabled) {
  7855. return;
  7856. }
  7857. const fragBlockingSwitch = currentAutoLevel > -1 && currentAutoLevel !== loadingFragForLevel;
  7858. const levelChange = !!levelLoaded || fragBlockingSwitch;
  7859. if (!levelChange && (media.paused || !media.playbackRate || !media.readyState)) {
  7860. return;
  7861. }
  7862. const bufferInfo = hls.mainForwardBufferInfo;
  7863. if (!levelChange && bufferInfo === null) {
  7864. return;
  7865. }
  7866. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  7867. const playbackRate = Math.abs(media.playbackRate);
  7868. if (timeLoading <= Math.max(ttfbEstimate, 1e3 * (duration / (playbackRate * 2)))) {
  7869. return;
  7870. }
  7871. const bufferStarvationDelay = bufferInfo ? bufferInfo.len / playbackRate : 0;
  7872. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  7873. const loadedFirstByte = stats.loaded && ttfb > -1;
  7874. const bwEstimate = this.getBwEstimate();
  7875. const levels = hls.levels;
  7876. const level = levels[loadingFragForLevel];
  7877. const expectedLen = Math.max(stats.loaded, Math.round(duration * (frag.bitrate || level.averageBitrate) / 8));
  7878. let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  7879. if (timeStreaming < 1 && loadedFirstByte) {
  7880. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  7881. }
  7882. const loadRate = loadedFirstByte ? stats.loaded * 1e3 / timeStreaming : 0;
  7883. const ttfbSeconds = ttfbEstimate / 1e3;
  7884. const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbSeconds;
  7885. if (fragLoadedDelay <= bufferStarvationDelay) {
  7886. return;
  7887. }
  7888. const bwe = loadRate ? loadRate * 8 : bwEstimate;
  7889. const live = ((_ref = (levelLoaded == null ? void 0 : levelLoaded.details) || this.hls.latestLevelDetails) == null ? void 0 : _ref.live) === true;
  7890. const abrBandWidthUpFactor = this.hls.config.abrBandWidthUpFactor;
  7891. let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  7892. let nextLoadLevel;
  7893. for (nextLoadLevel = loadingFragForLevel - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  7894. const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  7895. const requiresLevelLoad = !levels[nextLoadLevel].details || live;
  7896. fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbSeconds, bwe, duration * levelNextBitrate, requiresLevelLoad);
  7897. if (fragLevelNextLoadedDelay < Math.min(bufferStarvationDelay, duration + ttfbSeconds)) {
  7898. break;
  7899. }
  7900. }
  7901. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  7902. return;
  7903. }
  7904. if (fragLevelNextLoadedDelay > duration * 10) {
  7905. return;
  7906. }
  7907. if (loadedFirstByte) {
  7908. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  7909. } else {
  7910. this.bwEstimator.sampleTTFB(timeLoading);
  7911. }
  7912. const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  7913. if (this.getBwEstimate() * abrBandWidthUpFactor > nextLoadLevelBitrate) {
  7914. this.resetEstimator(nextLoadLevelBitrate);
  7915. }
  7916. const bestSwitchLevel = this.findBestLevel(nextLoadLevelBitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
  7917. if (bestSwitchLevel > -1) {
  7918. nextLoadLevel = bestSwitchLevel;
  7919. }
  7920. this.warn(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of level ${loadingFragForLevel} is loading too slowly;
  7921. Fragment duration: ${frag.duration.toFixed(3)}
  7922. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
  7923. Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
  7924. Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s
  7925. TTFB estimate: ${ttfb | 0} ms
  7926. Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : "Unknown"} bps
  7927. New BW estimate: ${this.getBwEstimate() | 0} bps
  7928. Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
  7929. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  7930. this.clearTimer();
  7931. const abortAndSwitch = () => {
  7932. this.clearTimer();
  7933. if (this.fragCurrent === frag && this.hls.loadLevel === nextLoadLevel && nextLoadLevel > 0) {
  7934. const bufferStarvationDelay2 = this.getStarvationDelay();
  7935. this.warn(`Aborting inflight request ${nextLoadLevel > 0 ? "and switching down" : ""}
  7936. Fragment duration: ${frag.duration.toFixed(3)} s
  7937. Time to underbuffer: ${bufferStarvationDelay2.toFixed(3)} s`);
  7938. frag.abortRequests();
  7939. this.fragCurrent = this.partCurrent = null;
  7940. if (nextLoadLevel > minAutoLevel) {
  7941. let lowestSwitchLevel = this.findBestLevel(this.hls.levels[minAutoLevel].bitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay2, 1, 1);
  7942. if (lowestSwitchLevel === -1) {
  7943. lowestSwitchLevel = minAutoLevel;
  7944. }
  7945. this.hls.nextLoadLevel = this.hls.nextAutoLevel = lowestSwitchLevel;
  7946. this.resetEstimator(this.hls.levels[lowestSwitchLevel].bitrate);
  7947. }
  7948. }
  7949. };
  7950. if (fragBlockingSwitch || fragLoadedDelay > fragLevelNextLoadedDelay * 2) {
  7951. abortAndSwitch();
  7952. } else {
  7953. this.timer = self.setInterval(abortAndSwitch, fragLevelNextLoadedDelay * 1e3);
  7954. }
  7955. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  7956. frag,
  7957. part,
  7958. stats
  7959. });
  7960. };
  7961. this.hls = _hls;
  7962. this.bwEstimator = this.initEstimator();
  7963. this.registerListeners();
  7964. }
  7965. resetEstimator(abrEwmaDefaultEstimate) {
  7966. if (abrEwmaDefaultEstimate) {
  7967. this.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
  7968. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  7969. }
  7970. this.firstSelection = -1;
  7971. this.bwEstimator = this.initEstimator();
  7972. }
  7973. initEstimator() {
  7974. const config2 = this.hls.config;
  7975. return new EwmaBandWidthEstimator(config2.abrEwmaSlowVoD, config2.abrEwmaFastVoD, config2.abrEwmaDefaultEstimate);
  7976. }
  7977. registerListeners() {
  7978. const {
  7979. hls
  7980. } = this;
  7981. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7982. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  7983. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  7984. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  7985. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  7986. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  7987. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  7988. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  7989. hls.on(Events.ERROR, this.onError, this);
  7990. }
  7991. unregisterListeners() {
  7992. const {
  7993. hls
  7994. } = this;
  7995. if (!hls) {
  7996. return;
  7997. }
  7998. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7999. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  8000. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  8001. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  8002. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  8003. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  8004. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  8005. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  8006. hls.off(Events.ERROR, this.onError, this);
  8007. }
  8008. destroy() {
  8009. this.unregisterListeners();
  8010. this.clearTimer();
  8011. this.hls = this._abandonRulesCheck = this.supportedCache = null;
  8012. this.fragCurrent = this.partCurrent = null;
  8013. }
  8014. onManifestLoading(event, data) {
  8015. this.lastLoadedFragLevel = -1;
  8016. this.firstSelection = -1;
  8017. this.lastLevelLoadSec = 0;
  8018. this.supportedCache = {};
  8019. this.fragCurrent = this.partCurrent = null;
  8020. this.onLevelsUpdated();
  8021. this.clearTimer();
  8022. }
  8023. onLevelsUpdated() {
  8024. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  8025. this.lastLoadedFragLevel = this.fragCurrent.level;
  8026. }
  8027. this._nextAutoLevel = -1;
  8028. this.onMaxAutoLevelUpdated();
  8029. this.codecTiers = null;
  8030. this.audioTracksByGroup = null;
  8031. }
  8032. onMaxAutoLevelUpdated() {
  8033. this.firstSelection = -1;
  8034. this.nextAutoLevelKey = "";
  8035. }
  8036. onFragLoading(event, data) {
  8037. const frag = data.frag;
  8038. if (this.ignoreFragment(frag)) {
  8039. return;
  8040. }
  8041. if (!frag.bitrateTest) {
  8042. var _data$part;
  8043. this.fragCurrent = frag;
  8044. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  8045. }
  8046. this.clearTimer();
  8047. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  8048. }
  8049. onLevelSwitching(event, data) {
  8050. this.clearTimer();
  8051. }
  8052. onError(event, data) {
  8053. if (data.fatal) {
  8054. return;
  8055. }
  8056. switch (data.details) {
  8057. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  8058. case ErrorDetails.BUFFER_APPEND_ERROR:
  8059. this.lastLoadedFragLevel = -1;
  8060. this.firstSelection = -1;
  8061. break;
  8062. case ErrorDetails.FRAG_LOAD_TIMEOUT: {
  8063. const frag = data.frag;
  8064. const {
  8065. fragCurrent,
  8066. partCurrent: part
  8067. } = this;
  8068. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  8069. const now2 = performance.now();
  8070. const stats = part ? part.stats : frag.stats;
  8071. const timeLoading = now2 - stats.loading.start;
  8072. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  8073. const loadedFirstByte = stats.loaded && ttfb > -1;
  8074. if (loadedFirstByte) {
  8075. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  8076. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  8077. } else {
  8078. this.bwEstimator.sampleTTFB(timeLoading);
  8079. }
  8080. }
  8081. break;
  8082. }
  8083. }
  8084. }
  8085. getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  8086. const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  8087. const playlistLoadSec = isSwitch ? timeToFirstByteSec + this.lastLevelLoadSec : 0;
  8088. return fragLoadSec + playlistLoadSec;
  8089. }
  8090. onLevelLoaded(event, data) {
  8091. const config2 = this.hls.config;
  8092. const {
  8093. loading
  8094. } = data.stats;
  8095. const timeLoadingMs = loading.end - loading.first;
  8096. if (isFiniteNumber(timeLoadingMs)) {
  8097. this.lastLevelLoadSec = timeLoadingMs / 1e3;
  8098. }
  8099. if (data.details.live) {
  8100. this.bwEstimator.update(config2.abrEwmaSlowLive, config2.abrEwmaFastLive);
  8101. } else {
  8102. this.bwEstimator.update(config2.abrEwmaSlowVoD, config2.abrEwmaFastVoD);
  8103. }
  8104. if (this.timer > -1) {
  8105. this._abandonRulesCheck(data.levelInfo);
  8106. }
  8107. }
  8108. onFragLoaded(event, {
  8109. frag,
  8110. part
  8111. }) {
  8112. const stats = part ? part.stats : frag.stats;
  8113. if (frag.type === PlaylistLevelType.MAIN) {
  8114. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  8115. }
  8116. if (this.ignoreFragment(frag)) {
  8117. return;
  8118. }
  8119. this.clearTimer();
  8120. if (frag.level === this._nextAutoLevel) {
  8121. this._nextAutoLevel = -1;
  8122. }
  8123. this.firstSelection = -1;
  8124. if (this.hls.config.abrMaxWithRealBitrate) {
  8125. const duration = part ? part.duration : frag.duration;
  8126. const level = this.hls.levels[frag.level];
  8127. const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  8128. const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  8129. level.loaded = {
  8130. bytes: loadedBytes,
  8131. duration: loadedDuration
  8132. };
  8133. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  8134. }
  8135. if (frag.bitrateTest) {
  8136. const fragBufferedData = {
  8137. stats,
  8138. frag,
  8139. part,
  8140. id: frag.type
  8141. };
  8142. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  8143. frag.bitrateTest = false;
  8144. } else {
  8145. this.lastLoadedFragLevel = frag.level;
  8146. }
  8147. }
  8148. onFragBuffered(event, data) {
  8149. const {
  8150. frag,
  8151. part
  8152. } = data;
  8153. const stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  8154. if (stats.aborted) {
  8155. return;
  8156. }
  8157. if (this.ignoreFragment(frag)) {
  8158. return;
  8159. }
  8160. const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  8161. this.bwEstimator.sample(processingMs, stats.loaded);
  8162. stats.bwEstimate = this.getBwEstimate();
  8163. if (frag.bitrateTest) {
  8164. this.bitrateTestDelay = processingMs / 1e3;
  8165. } else {
  8166. this.bitrateTestDelay = 0;
  8167. }
  8168. }
  8169. ignoreFragment(frag) {
  8170. return frag.type !== PlaylistLevelType.MAIN || frag.sn === "initSegment";
  8171. }
  8172. clearTimer() {
  8173. if (this.timer > -1) {
  8174. self.clearInterval(this.timer);
  8175. this.timer = -1;
  8176. }
  8177. }
  8178. get firstAutoLevel() {
  8179. const {
  8180. maxAutoLevel,
  8181. minAutoLevel
  8182. } = this.hls;
  8183. const bwEstimate = this.getBwEstimate();
  8184. const maxStartDelay = this.hls.config.maxStarvationDelay;
  8185. const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  8186. if (abrAutoLevel > -1) {
  8187. return abrAutoLevel;
  8188. }
  8189. const firstLevel = this.hls.firstLevel;
  8190. const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  8191. this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);
  8192. return clamped;
  8193. }
  8194. get forcedAutoLevel() {
  8195. if (this.nextAutoLevelKey) {
  8196. return -1;
  8197. }
  8198. return this._nextAutoLevel;
  8199. }
  8200. // return next auto level
  8201. get nextAutoLevel() {
  8202. const forcedAutoLevel = this.forcedAutoLevel;
  8203. const bwEstimator = this.bwEstimator;
  8204. const useEstimate = bwEstimator.canEstimate();
  8205. const loadedFirstFrag = this.lastLoadedFragLevel > -1;
  8206. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  8207. return forcedAutoLevel;
  8208. }
  8209. const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  8210. if (forcedAutoLevel !== -1) {
  8211. const levels = this.hls.levels;
  8212. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  8213. return forcedAutoLevel;
  8214. }
  8215. }
  8216. this._nextAutoLevel = nextABRAutoLevel;
  8217. this.nextAutoLevelKey = this.getAutoLevelKey();
  8218. return nextABRAutoLevel;
  8219. }
  8220. getAutoLevelKey() {
  8221. return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  8222. }
  8223. getNextABRAutoLevel() {
  8224. const {
  8225. fragCurrent,
  8226. partCurrent,
  8227. hls
  8228. } = this;
  8229. if (hls.levels.length <= 1) {
  8230. return hls.loadLevel;
  8231. }
  8232. const {
  8233. maxAutoLevel,
  8234. config: config2,
  8235. minAutoLevel
  8236. } = hls;
  8237. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  8238. const avgbw = this.getBwEstimate();
  8239. const bufferStarvationDelay = this.getStarvationDelay();
  8240. let bwFactor = config2.abrBandWidthFactor;
  8241. let bwUpFactor = config2.abrBandWidthUpFactor;
  8242. if (bufferStarvationDelay) {
  8243. const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  8244. if (_bestLevel >= 0) {
  8245. this.rebufferNotice = -1;
  8246. return _bestLevel;
  8247. }
  8248. }
  8249. let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config2.maxStarvationDelay) : config2.maxStarvationDelay;
  8250. if (!bufferStarvationDelay) {
  8251. const bitrateTestDelay = this.bitrateTestDelay;
  8252. if (bitrateTestDelay) {
  8253. const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config2.maxLoadingDelay) : config2.maxLoadingDelay;
  8254. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  8255. this.info(`bitrate test took ${Math.round(1e3 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1e3 * maxStarvationDelay)} ms`);
  8256. bwFactor = bwUpFactor = 1;
  8257. }
  8258. }
  8259. const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  8260. if (this.rebufferNotice !== bestLevel) {
  8261. this.rebufferNotice = bestLevel;
  8262. this.info(`${bufferStarvationDelay ? "rebuffering expected" : "buffer is empty"}, optimal quality level ${bestLevel}`);
  8263. }
  8264. if (bestLevel > -1) {
  8265. return bestLevel;
  8266. }
  8267. const minLevel = hls.levels[minAutoLevel];
  8268. const autoLevel = hls.loadLevelObj;
  8269. if (autoLevel && (minLevel == null ? void 0 : minLevel.bitrate) < autoLevel.bitrate) {
  8270. return minAutoLevel;
  8271. }
  8272. return hls.loadLevel;
  8273. }
  8274. getStarvationDelay() {
  8275. const hls = this.hls;
  8276. const media = hls.media;
  8277. if (!media) {
  8278. return Infinity;
  8279. }
  8280. const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1;
  8281. const bufferInfo = hls.mainForwardBufferInfo;
  8282. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  8283. }
  8284. getBwEstimate() {
  8285. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  8286. }
  8287. findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  8288. var _this$hls$latestLevel;
  8289. const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  8290. const lastLoadedFragLevel = this.lastLoadedFragLevel;
  8291. const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  8292. const {
  8293. fragCurrent,
  8294. partCurrent
  8295. } = this;
  8296. const {
  8297. levels,
  8298. allAudioTracks,
  8299. loadLevel,
  8300. config: config2
  8301. } = this.hls;
  8302. if (levels.length === 1) {
  8303. return 0;
  8304. }
  8305. const level = levels[selectionBaseLevel];
  8306. const live = !!((_this$hls$latestLevel = this.hls.latestLevelDetails) != null && _this$hls$latestLevel.live);
  8307. const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  8308. let currentCodecSet;
  8309. let currentVideoRange = "SDR";
  8310. let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  8311. const {
  8312. audioPreference,
  8313. videoPreference
  8314. } = config2;
  8315. const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  8316. let minStartIndex = -1;
  8317. if (firstSelection) {
  8318. if (this.firstSelection !== -1) {
  8319. return this.firstSelection;
  8320. }
  8321. const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  8322. const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  8323. const {
  8324. codecSet,
  8325. videoRanges,
  8326. minFramerate,
  8327. minBitrate,
  8328. minIndex,
  8329. preferHDR
  8330. } = startTier;
  8331. minStartIndex = minIndex;
  8332. currentCodecSet = codecSet;
  8333. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  8334. currentFrameRate = minFramerate;
  8335. currentBw = Math.max(currentBw, minBitrate);
  8336. this.log(`picked start tier ${stringify(startTier)}`);
  8337. } else {
  8338. currentCodecSet = level == null ? void 0 : level.codecSet;
  8339. currentVideoRange = level == null ? void 0 : level.videoRange;
  8340. }
  8341. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  8342. const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1e3;
  8343. const levelsSkipped = [];
  8344. for (let i2 = maxAutoLevel; i2 >= minAutoLevel; i2--) {
  8345. var _levelInfo$supportedR, _levelInfo$supportedR2;
  8346. const levelInfo = levels[i2];
  8347. const upSwitch = i2 > selectionBaseLevel;
  8348. if (!levelInfo) {
  8349. continue;
  8350. }
  8351. if (config2.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) {
  8352. const mediaCapabilities = navigator.mediaCapabilities;
  8353. if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === "function" && requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference)) {
  8354. levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities, this.supportedCache);
  8355. levelInfo.supportedPromise.then((decodingInfo) => {
  8356. if (!this.hls) {
  8357. return;
  8358. }
  8359. levelInfo.supportedResult = decodingInfo;
  8360. const levels2 = this.hls.levels;
  8361. const index2 = levels2.indexOf(levelInfo);
  8362. if (decodingInfo.error) {
  8363. this.warn(`MediaCapabilities decodingInfo error: "${decodingInfo.error}" for level ${index2} ${stringify(decodingInfo)}`);
  8364. } else if (!decodingInfo.supported) {
  8365. this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${index2} ${stringify(decodingInfo)}`);
  8366. if (index2 > -1 && levels2.length > 1) {
  8367. this.log(`Removing unsupported level ${index2}`);
  8368. this.hls.removeLevel(index2);
  8369. if (this.hls.loadLevel === -1) {
  8370. this.hls.nextLoadLevel = 0;
  8371. }
  8372. }
  8373. } else if (decodingInfo.decodingInfoResults.some((info) => info.smooth === false || info.powerEfficient === false)) {
  8374. this.log(`MediaCapabilities decodingInfo for level ${index2} not smooth or powerEfficient: ${stringify(decodingInfo)}`);
  8375. }
  8376. });
  8377. } else {
  8378. levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;
  8379. }
  8380. }
  8381. 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)) {
  8382. if (!firstSelection || i2 !== minStartIndex) {
  8383. levelsSkipped.push(i2);
  8384. continue;
  8385. }
  8386. }
  8387. const levelDetails = levelInfo.details;
  8388. const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  8389. let adjustedbw;
  8390. if (!upSwitch) {
  8391. adjustedbw = bwFactor * currentBw;
  8392. } else {
  8393. adjustedbw = bwUpFactor * currentBw;
  8394. }
  8395. const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levelInfo.averageBitrate : levelInfo.maxBitrate;
  8396. const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === void 0);
  8397. const canSwitchWithinTolerance = (
  8398. // if adjusted bw is greater than level bitrate AND
  8399. adjustedbw >= bitrate && // no level change, or new level has no error history
  8400. (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
  8401. // 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 ...
  8402. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  8403. (fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)
  8404. );
  8405. if (canSwitchWithinTolerance) {
  8406. const forcedAutoLevel = this.forcedAutoLevel;
  8407. if (i2 !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  8408. if (levelsSkipped.length) {
  8409. 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}`);
  8410. }
  8411. 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}`);
  8412. }
  8413. if (firstSelection) {
  8414. this.firstSelection = i2;
  8415. }
  8416. return i2;
  8417. }
  8418. }
  8419. return -1;
  8420. }
  8421. set nextAutoLevel(nextLevel) {
  8422. const value2 = this.deriveNextAutoLevel(nextLevel);
  8423. if (this._nextAutoLevel !== value2) {
  8424. this.nextAutoLevelKey = "";
  8425. this._nextAutoLevel = value2;
  8426. }
  8427. }
  8428. deriveNextAutoLevel(nextLevel) {
  8429. const {
  8430. maxAutoLevel,
  8431. minAutoLevel
  8432. } = this.hls;
  8433. return Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  8434. }
  8435. }
  8436. const BinarySearch = {
  8437. /**
  8438. * Searches for an item in an array which matches a certain condition.
  8439. * This requires the condition to only match one item in the array,
  8440. * and for the array to be ordered.
  8441. *
  8442. * @param list The array to search.
  8443. * @param comparisonFn
  8444. * Called and provided a candidate item as the first argument.
  8445. * Should return:
  8446. * > -1 if the item should be located at a lower index than the provided item.
  8447. * > 1 if the item should be located at a higher index than the provided item.
  8448. * > 0 if the item is the item you're looking for.
  8449. *
  8450. * @returns the object if found, otherwise returns null
  8451. */
  8452. search: function(list, comparisonFn) {
  8453. let minIndex = 0;
  8454. let maxIndex = list.length - 1;
  8455. let currentIndex = null;
  8456. let currentElement = null;
  8457. while (minIndex <= maxIndex) {
  8458. currentIndex = (minIndex + maxIndex) / 2 | 0;
  8459. currentElement = list[currentIndex];
  8460. const comparisonResult = comparisonFn(currentElement);
  8461. if (comparisonResult > 0) {
  8462. minIndex = currentIndex + 1;
  8463. } else if (comparisonResult < 0) {
  8464. maxIndex = currentIndex - 1;
  8465. } else {
  8466. return currentElement;
  8467. }
  8468. }
  8469. return null;
  8470. }
  8471. };
  8472. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  8473. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  8474. return null;
  8475. }
  8476. const startPDT = fragments[0].programDateTime;
  8477. if (PDTValue < (startPDT || 0)) {
  8478. return null;
  8479. }
  8480. const endPDT = fragments[fragments.length - 1].endProgramDateTime;
  8481. if (PDTValue >= (endPDT || 0)) {
  8482. return null;
  8483. }
  8484. for (let seg = 0; seg < fragments.length; ++seg) {
  8485. const frag = fragments[seg];
  8486. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  8487. return frag;
  8488. }
  8489. }
  8490. return null;
  8491. }
  8492. function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 5e-3) {
  8493. let fragNext = null;
  8494. if (fragPrevious) {
  8495. fragNext = fragments[1 + fragPrevious.sn - fragments[0].sn] || null;
  8496. const bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  8497. if (bufferEdgeError > 0 && bufferEdgeError < 15e-7) {
  8498. bufferEnd += 15e-7;
  8499. }
  8500. if (fragNext && fragPrevious.level !== fragNext.level && fragNext.end <= fragPrevious.end) {
  8501. fragNext = fragments[2 + fragPrevious.sn - fragments[0].sn] || null;
  8502. }
  8503. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  8504. fragNext = fragments[0];
  8505. }
  8506. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  8507. return fragNext;
  8508. }
  8509. const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  8510. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  8511. return foundFragment;
  8512. }
  8513. return fragNext;
  8514. }
  8515. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  8516. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  8517. const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {
  8518. if (tag[0] === "INF") {
  8519. duration += parseFloat(tag[1]);
  8520. }
  8521. return duration;
  8522. }, nextFragLookupTolerance);
  8523. return fragNext.start <= firstDuration;
  8524. }
  8525. return false;
  8526. }
  8527. function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {
  8528. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  8529. return 0;
  8530. }
  8531. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  8532. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  8533. return 1;
  8534. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  8535. return -1;
  8536. }
  8537. return 0;
  8538. }
  8539. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  8540. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1e3;
  8541. const endProgramDateTime = candidate.endProgramDateTime || 0;
  8542. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  8543. }
  8544. function findNearestWithCC(details, cc, pos) {
  8545. if (details) {
  8546. if (details.startCC <= cc && details.endCC >= cc) {
  8547. let fragments = details.fragments;
  8548. const {
  8549. fragmentHint
  8550. } = details;
  8551. if (fragmentHint) {
  8552. fragments = fragments.concat(fragmentHint);
  8553. }
  8554. let closest;
  8555. BinarySearch.search(fragments, (candidate) => {
  8556. if (candidate.cc < cc) {
  8557. return 1;
  8558. }
  8559. if (candidate.cc > cc) {
  8560. return -1;
  8561. }
  8562. closest = candidate;
  8563. if (candidate.end <= pos) {
  8564. return 1;
  8565. }
  8566. if (candidate.start > pos) {
  8567. return -1;
  8568. }
  8569. return 0;
  8570. });
  8571. return closest || null;
  8572. }
  8573. }
  8574. return null;
  8575. }
  8576. function isTimeoutError(error2) {
  8577. switch (error2.details) {
  8578. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  8579. case ErrorDetails.KEY_LOAD_TIMEOUT:
  8580. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  8581. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  8582. return true;
  8583. }
  8584. return false;
  8585. }
  8586. function getRetryConfig(loadPolicy, error2) {
  8587. const isTimeout = isTimeoutError(error2);
  8588. return loadPolicy.default[`${isTimeout ? "timeout" : "error"}Retry`];
  8589. }
  8590. function getRetryDelay(retryConfig, retryCount) {
  8591. const backoffFactor = retryConfig.backoff === "linear" ? 1 : Math.pow(2, retryCount);
  8592. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  8593. }
  8594. function getLoaderConfigWithoutReties(loderConfig) {
  8595. return _objectSpread2(_objectSpread2({}, loderConfig), {
  8596. errorRetry: null,
  8597. timeoutRetry: null
  8598. });
  8599. }
  8600. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  8601. if (!retryConfig) {
  8602. return false;
  8603. }
  8604. const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  8605. const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  8606. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  8607. }
  8608. function retryForHttpStatus(httpStatus) {
  8609. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  8610. }
  8611. var NetworkErrorAction = {
  8612. DoNothing: 0,
  8613. SendEndCallback: 1,
  8614. SendAlternateToPenaltyBox: 2,
  8615. RemoveAlternatePermanently: 3,
  8616. InsertDiscontinuity: 4,
  8617. RetryRequest: 5
  8618. };
  8619. var ErrorActionFlags = {
  8620. None: 0,
  8621. MoveAllAlternatesMatchingHost: 1,
  8622. MoveAllAlternatesMatchingHDCP: 2,
  8623. SwitchToSDR: 4
  8624. };
  8625. class ErrorController extends Logger {
  8626. constructor(hls) {
  8627. super("error-controller", hls.logger);
  8628. this.hls = void 0;
  8629. this.playlistError = 0;
  8630. this.penalizedRenditions = {};
  8631. this.hls = hls;
  8632. this.registerListeners();
  8633. }
  8634. registerListeners() {
  8635. const hls = this.hls;
  8636. hls.on(Events.ERROR, this.onError, this);
  8637. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8638. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  8639. }
  8640. unregisterListeners() {
  8641. const hls = this.hls;
  8642. if (!hls) {
  8643. return;
  8644. }
  8645. hls.off(Events.ERROR, this.onError, this);
  8646. hls.off(Events.ERROR, this.onErrorOut, this);
  8647. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8648. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  8649. }
  8650. destroy() {
  8651. this.unregisterListeners();
  8652. this.hls = null;
  8653. this.penalizedRenditions = {};
  8654. }
  8655. startLoad(startPosition) {
  8656. }
  8657. stopLoad() {
  8658. this.playlistError = 0;
  8659. }
  8660. getVariantLevelIndex(frag) {
  8661. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  8662. }
  8663. onManifestLoading() {
  8664. this.playlistError = 0;
  8665. this.penalizedRenditions = {};
  8666. }
  8667. onLevelUpdated() {
  8668. this.playlistError = 0;
  8669. }
  8670. onError(event, data) {
  8671. var _data$frag;
  8672. if (data.fatal) {
  8673. return;
  8674. }
  8675. const hls = this.hls;
  8676. const context = data.context;
  8677. switch (data.details) {
  8678. case ErrorDetails.FRAG_LOAD_ERROR:
  8679. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  8680. case ErrorDetails.KEY_LOAD_ERROR:
  8681. case ErrorDetails.KEY_LOAD_TIMEOUT:
  8682. data.errorAction = this.getFragRetryOrSwitchAction(data);
  8683. return;
  8684. case ErrorDetails.FRAG_PARSING_ERROR:
  8685. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  8686. data.errorAction = createDoNothingErrorAction();
  8687. return;
  8688. }
  8689. case ErrorDetails.FRAG_GAP:
  8690. case ErrorDetails.FRAG_DECRYPT_ERROR: {
  8691. data.errorAction = this.getFragRetryOrSwitchAction(data);
  8692. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  8693. return;
  8694. }
  8695. case ErrorDetails.LEVEL_EMPTY_ERROR:
  8696. case ErrorDetails.LEVEL_PARSING_ERROR:
  8697. {
  8698. var _data$context, _data$context$levelDe;
  8699. const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  8700. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  8701. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  8702. } else {
  8703. data.levelRetry = false;
  8704. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  8705. }
  8706. }
  8707. return;
  8708. case ErrorDetails.LEVEL_LOAD_ERROR:
  8709. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  8710. if (typeof (context == null ? void 0 : context.level) === "number") {
  8711. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  8712. }
  8713. return;
  8714. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  8715. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  8716. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  8717. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  8718. if (context) {
  8719. const level = hls.loadLevelObj;
  8720. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  8721. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  8722. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  8723. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  8724. return;
  8725. }
  8726. }
  8727. return;
  8728. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  8729. {
  8730. const level = hls.loadLevelObj;
  8731. const restrictedHdcpLevel = level == null ? void 0 : level.attrs["HDCP-LEVEL"];
  8732. if (restrictedHdcpLevel) {
  8733. data.errorAction = {
  8734. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  8735. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  8736. hdcpLevel: restrictedHdcpLevel
  8737. };
  8738. } else {
  8739. this.keySystemError(data);
  8740. }
  8741. }
  8742. return;
  8743. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  8744. case ErrorDetails.REMUX_ALLOC_ERROR:
  8745. case ErrorDetails.BUFFER_APPEND_ERROR:
  8746. if (!data.errorAction) {
  8747. var _data$level;
  8748. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  8749. }
  8750. return;
  8751. case ErrorDetails.INTERNAL_EXCEPTION:
  8752. case ErrorDetails.BUFFER_APPENDING_ERROR:
  8753. case ErrorDetails.BUFFER_FULL_ERROR:
  8754. case ErrorDetails.LEVEL_SWITCH_ERROR:
  8755. case ErrorDetails.BUFFER_STALLED_ERROR:
  8756. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  8757. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  8758. data.errorAction = createDoNothingErrorAction();
  8759. return;
  8760. }
  8761. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  8762. this.keySystemError(data);
  8763. }
  8764. }
  8765. keySystemError(data) {
  8766. const levelIndex = this.getVariantLevelIndex(data.frag);
  8767. data.levelRetry = false;
  8768. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  8769. }
  8770. getPlaylistRetryOrSwitchAction(data, levelIndex) {
  8771. const hls = this.hls;
  8772. const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  8773. const retryCount = this.playlistError++;
  8774. const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  8775. if (retry) {
  8776. return {
  8777. action: NetworkErrorAction.RetryRequest,
  8778. flags: ErrorActionFlags.None,
  8779. retryConfig,
  8780. retryCount
  8781. };
  8782. }
  8783. const errorAction = this.getLevelSwitchAction(data, levelIndex);
  8784. if (retryConfig) {
  8785. errorAction.retryConfig = retryConfig;
  8786. errorAction.retryCount = retryCount;
  8787. }
  8788. return errorAction;
  8789. }
  8790. getFragRetryOrSwitchAction(data) {
  8791. const hls = this.hls;
  8792. const variantLevelIndex = this.getVariantLevelIndex(data.frag);
  8793. const level = hls.levels[variantLevelIndex];
  8794. const {
  8795. fragLoadPolicy,
  8796. keyLoadPolicy
  8797. } = hls.config;
  8798. const retryConfig = getRetryConfig(data.details.startsWith("key") ? keyLoadPolicy : fragLoadPolicy, data);
  8799. const fragmentErrors = hls.levels.reduce((acc, level2) => acc + level2.fragmentError, 0);
  8800. if (level) {
  8801. if (data.details !== ErrorDetails.FRAG_GAP) {
  8802. level.fragmentError++;
  8803. }
  8804. const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  8805. if (retry) {
  8806. return {
  8807. action: NetworkErrorAction.RetryRequest,
  8808. flags: ErrorActionFlags.None,
  8809. retryConfig,
  8810. retryCount: fragmentErrors
  8811. };
  8812. }
  8813. }
  8814. const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  8815. if (retryConfig) {
  8816. errorAction.retryConfig = retryConfig;
  8817. errorAction.retryCount = fragmentErrors;
  8818. }
  8819. return errorAction;
  8820. }
  8821. getLevelSwitchAction(data, levelIndex) {
  8822. const hls = this.hls;
  8823. if (levelIndex === null || levelIndex === void 0) {
  8824. levelIndex = hls.loadLevel;
  8825. }
  8826. const level = this.hls.levels[levelIndex];
  8827. if (level) {
  8828. var _data$frag2, _data$context2;
  8829. const errorDetails = data.details;
  8830. level.loadError++;
  8831. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  8832. level.fragmentError++;
  8833. }
  8834. let nextLevel = -1;
  8835. const {
  8836. levels,
  8837. loadLevel,
  8838. minAutoLevel,
  8839. maxAutoLevel
  8840. } = hls;
  8841. if (!hls.autoLevelEnabled && !hls.config.preserveManualLevelOnError) {
  8842. hls.loadLevel = -1;
  8843. }
  8844. const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  8845. const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === "audio" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  8846. const findAudioCodecAlternate = isAudioCodecError && levels.some(({
  8847. audioCodec
  8848. }) => level.audioCodec !== audioCodec);
  8849. const isVideoCodecError = data.sourceBufferName === "video" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  8850. const findVideoCodecAlternate = isVideoCodecError && levels.some(({
  8851. codecSet,
  8852. audioCodec
  8853. }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);
  8854. const {
  8855. type: playlistErrorType,
  8856. groupId: playlistErrorGroupId
  8857. } = (_data$context2 = data.context) != null ? _data$context2 : {};
  8858. for (let i2 = levels.length; i2--; ) {
  8859. const candidate = (i2 + loadLevel) % levels.length;
  8860. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  8861. var _level$audioGroups, _level$subtitleGroups;
  8862. const levelCandidate = levels[candidate];
  8863. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  8864. const levelDetails = levels[candidate].details;
  8865. if (levelDetails) {
  8866. const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  8867. if (fragCandidate != null && fragCandidate.gap) {
  8868. continue;
  8869. }
  8870. }
  8871. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  8872. continue;
  8873. } 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) {
  8874. continue;
  8875. }
  8876. nextLevel = candidate;
  8877. break;
  8878. }
  8879. }
  8880. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  8881. data.levelRetry = true;
  8882. this.playlistError = 0;
  8883. return {
  8884. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  8885. flags: ErrorActionFlags.None,
  8886. nextAutoLevel: nextLevel
  8887. };
  8888. }
  8889. }
  8890. return {
  8891. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  8892. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  8893. };
  8894. }
  8895. onErrorOut(event, data) {
  8896. var _data$errorAction;
  8897. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  8898. case NetworkErrorAction.DoNothing:
  8899. break;
  8900. case NetworkErrorAction.SendAlternateToPenaltyBox:
  8901. this.sendAlternateToPenaltyBox(data);
  8902. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  8903. data.fatal = true;
  8904. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  8905. this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`);
  8906. this.hls.recoverMediaError();
  8907. }
  8908. break;
  8909. }
  8910. if (data.fatal) {
  8911. this.hls.stopLoad();
  8912. return;
  8913. }
  8914. }
  8915. sendAlternateToPenaltyBox(data) {
  8916. const hls = this.hls;
  8917. const errorAction = data.errorAction;
  8918. if (!errorAction) {
  8919. return;
  8920. }
  8921. const {
  8922. flags,
  8923. hdcpLevel,
  8924. nextAutoLevel
  8925. } = errorAction;
  8926. switch (flags) {
  8927. case ErrorActionFlags.None:
  8928. this.switchLevel(data, nextAutoLevel);
  8929. break;
  8930. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  8931. if (hdcpLevel) {
  8932. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  8933. errorAction.resolved = true;
  8934. }
  8935. this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`);
  8936. break;
  8937. }
  8938. if (!errorAction.resolved) {
  8939. this.switchLevel(data, nextAutoLevel);
  8940. }
  8941. }
  8942. switchLevel(data, levelIndex) {
  8943. if (levelIndex !== void 0 && data.errorAction) {
  8944. this.warn(`switching to level ${levelIndex} after ${data.details}`);
  8945. this.hls.nextAutoLevel = levelIndex;
  8946. data.errorAction.resolved = true;
  8947. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  8948. if (data.details === ErrorDetails.BUFFER_ADD_CODEC_ERROR && data.mimeType && data.sourceBufferName !== "audiovideo") {
  8949. const codec = getCodecsForMimeType(data.mimeType);
  8950. const levels = this.hls.levels;
  8951. for (let i2 = levels.length; i2--; ) {
  8952. if (levels[i2][`${data.sourceBufferName}Codec`] === codec) {
  8953. this.hls.removeLevel(i2);
  8954. }
  8955. }
  8956. }
  8957. }
  8958. }
  8959. }
  8960. function createDoNothingErrorAction(resolved) {
  8961. const errorAction = {
  8962. action: NetworkErrorAction.DoNothing,
  8963. flags: ErrorActionFlags.None
  8964. };
  8965. if (resolved) {
  8966. errorAction.resolved = true;
  8967. }
  8968. return errorAction;
  8969. }
  8970. var FragmentState = {
  8971. NOT_LOADED: "NOT_LOADED",
  8972. APPENDING: "APPENDING",
  8973. PARTIAL: "PARTIAL",
  8974. OK: "OK"
  8975. };
  8976. class FragmentTracker {
  8977. constructor(hls) {
  8978. this.activePartLists = /* @__PURE__ */ Object.create(null);
  8979. this.endListFragments = /* @__PURE__ */ Object.create(null);
  8980. this.fragments = /* @__PURE__ */ Object.create(null);
  8981. this.timeRanges = /* @__PURE__ */ Object.create(null);
  8982. this.bufferPadding = 0.2;
  8983. this.hls = void 0;
  8984. this.hasGaps = false;
  8985. this.hls = hls;
  8986. this._registerListeners();
  8987. }
  8988. _registerListeners() {
  8989. const {
  8990. hls
  8991. } = this;
  8992. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8993. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  8994. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  8995. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  8996. }
  8997. _unregisterListeners() {
  8998. const {
  8999. hls
  9000. } = this;
  9001. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  9002. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  9003. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  9004. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  9005. }
  9006. destroy() {
  9007. this._unregisterListeners();
  9008. this.fragments = // @ts-ignore
  9009. this.activePartLists = // @ts-ignore
  9010. this.endListFragments = this.timeRanges = null;
  9011. }
  9012. /**
  9013. * Return a Fragment or Part with an appended range that matches the position and levelType
  9014. * Otherwise, return null
  9015. */
  9016. getAppendedFrag(position, levelType) {
  9017. const activeParts = this.activePartLists[levelType];
  9018. if (activeParts) {
  9019. for (let i2 = activeParts.length; i2--; ) {
  9020. const activePart = activeParts[i2];
  9021. if (!activePart) {
  9022. break;
  9023. }
  9024. const appendedPTS = activePart.end;
  9025. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  9026. return activePart;
  9027. }
  9028. }
  9029. }
  9030. return this.getBufferedFrag(position, levelType);
  9031. }
  9032. /**
  9033. * Return a buffered Fragment that matches the position and levelType.
  9034. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  9035. * If not found any Fragment, return null
  9036. */
  9037. getBufferedFrag(position, levelType) {
  9038. return this.getFragAtPos(position, levelType, true);
  9039. }
  9040. getFragAtPos(position, levelType, buffered) {
  9041. const {
  9042. fragments
  9043. } = this;
  9044. const keys = Object.keys(fragments);
  9045. for (let i2 = keys.length; i2--; ) {
  9046. const fragmentEntity = fragments[keys[i2]];
  9047. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && (!buffered || fragmentEntity.buffered)) {
  9048. const frag = fragmentEntity.body;
  9049. if (frag.start <= position && position <= frag.end) {
  9050. return frag;
  9051. }
  9052. }
  9053. }
  9054. return null;
  9055. }
  9056. /**
  9057. * Partial fragments effected by coded frame eviction will be removed
  9058. * The browser will unload parts of the buffer to free up memory for new buffer data
  9059. * 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)
  9060. */
  9061. detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart, removeAppending) {
  9062. if (this.timeRanges) {
  9063. this.timeRanges[elementaryStream] = timeRange;
  9064. }
  9065. const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  9066. Object.keys(this.fragments).forEach((key) => {
  9067. const fragmentEntity = this.fragments[key];
  9068. if (!fragmentEntity) {
  9069. return;
  9070. }
  9071. if (appendedPartSn >= fragmentEntity.body.sn) {
  9072. return;
  9073. }
  9074. if (!fragmentEntity.buffered && (!fragmentEntity.loaded || removeAppending)) {
  9075. if (fragmentEntity.body.type === playlistType) {
  9076. this.removeFragment(fragmentEntity.body);
  9077. }
  9078. return;
  9079. }
  9080. const esData = fragmentEntity.range[elementaryStream];
  9081. if (!esData) {
  9082. return;
  9083. }
  9084. if (esData.time.length === 0) {
  9085. this.removeFragment(fragmentEntity.body);
  9086. return;
  9087. }
  9088. esData.time.some((time) => {
  9089. const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  9090. if (isNotBuffered) {
  9091. this.removeFragment(fragmentEntity.body);
  9092. }
  9093. return isNotBuffered;
  9094. });
  9095. });
  9096. }
  9097. /**
  9098. * Checks if the fragment passed in is loaded in the buffer properly
  9099. * Partially loaded fragments will be registered as a partial fragment
  9100. */
  9101. detectPartialFragments(data) {
  9102. const timeRanges = this.timeRanges;
  9103. if (!timeRanges || data.frag.sn === "initSegment") {
  9104. return;
  9105. }
  9106. const frag = data.frag;
  9107. const fragKey = getFragmentKey(frag);
  9108. const fragmentEntity = this.fragments[fragKey];
  9109. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  9110. return;
  9111. }
  9112. const isFragHint = !frag.relurl;
  9113. Object.keys(timeRanges).forEach((elementaryStream) => {
  9114. const streamInfo = frag.elementaryStreams[elementaryStream];
  9115. if (!streamInfo) {
  9116. return;
  9117. }
  9118. const timeRange = timeRanges[elementaryStream];
  9119. const partial2 = isFragHint || streamInfo.partial === true;
  9120. fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, data.part, partial2, timeRange);
  9121. });
  9122. fragmentEntity.loaded = null;
  9123. if (Object.keys(fragmentEntity.range).length) {
  9124. fragmentEntity.buffered = true;
  9125. const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  9126. if (endList) {
  9127. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  9128. }
  9129. if (!isPartial(fragmentEntity)) {
  9130. this.removeParts(frag.sn - 1, frag.type);
  9131. }
  9132. } else {
  9133. this.removeFragment(fragmentEntity.body);
  9134. }
  9135. }
  9136. removeParts(snToKeep, levelType) {
  9137. const activeParts = this.activePartLists[levelType];
  9138. if (!activeParts) {
  9139. return;
  9140. }
  9141. this.activePartLists[levelType] = filterParts(activeParts, (part) => part.fragment.sn >= snToKeep);
  9142. }
  9143. fragBuffered(frag, force) {
  9144. const fragKey = getFragmentKey(frag);
  9145. let fragmentEntity = this.fragments[fragKey];
  9146. if (!fragmentEntity && force) {
  9147. fragmentEntity = this.fragments[fragKey] = {
  9148. body: frag,
  9149. appendedPTS: null,
  9150. loaded: null,
  9151. buffered: false,
  9152. range: /* @__PURE__ */ Object.create(null)
  9153. };
  9154. if (frag.gap) {
  9155. this.hasGaps = true;
  9156. }
  9157. }
  9158. if (fragmentEntity) {
  9159. fragmentEntity.loaded = null;
  9160. fragmentEntity.buffered = true;
  9161. }
  9162. }
  9163. getBufferedTimes(fragment, part, partial2, timeRange) {
  9164. const buffered = {
  9165. time: [],
  9166. partial: partial2
  9167. };
  9168. const startPTS = fragment.start;
  9169. const endPTS = fragment.end;
  9170. const minEndPTS = fragment.minEndPTS || endPTS;
  9171. const maxStartPTS = fragment.maxStartPTS || startPTS;
  9172. for (let i2 = 0; i2 < timeRange.length; i2++) {
  9173. const startTime = timeRange.start(i2) - this.bufferPadding;
  9174. const endTime = timeRange.end(i2) + this.bufferPadding;
  9175. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  9176. buffered.time.push({
  9177. startPTS: Math.max(startPTS, timeRange.start(i2)),
  9178. endPTS: Math.min(endPTS, timeRange.end(i2))
  9179. });
  9180. break;
  9181. } else if (startPTS < endTime && endPTS > startTime) {
  9182. const start = Math.max(startPTS, timeRange.start(i2));
  9183. const end = Math.min(endPTS, timeRange.end(i2));
  9184. if (end > start) {
  9185. buffered.partial = true;
  9186. buffered.time.push({
  9187. startPTS: start,
  9188. endPTS: end
  9189. });
  9190. }
  9191. } else if (endPTS <= startTime) {
  9192. break;
  9193. }
  9194. }
  9195. return buffered;
  9196. }
  9197. /**
  9198. * Gets the partial fragment for a certain time
  9199. */
  9200. getPartialFragment(time) {
  9201. let bestFragment = null;
  9202. let timePadding;
  9203. let startTime;
  9204. let endTime;
  9205. let bestOverlap = 0;
  9206. const {
  9207. bufferPadding,
  9208. fragments
  9209. } = this;
  9210. Object.keys(fragments).forEach((key) => {
  9211. const fragmentEntity = fragments[key];
  9212. if (!fragmentEntity) {
  9213. return;
  9214. }
  9215. if (isPartial(fragmentEntity)) {
  9216. startTime = fragmentEntity.body.start - bufferPadding;
  9217. endTime = fragmentEntity.body.end + bufferPadding;
  9218. if (time >= startTime && time <= endTime) {
  9219. timePadding = Math.min(time - startTime, endTime - time);
  9220. if (bestOverlap <= timePadding) {
  9221. bestFragment = fragmentEntity.body;
  9222. bestOverlap = timePadding;
  9223. }
  9224. }
  9225. }
  9226. });
  9227. return bestFragment;
  9228. }
  9229. isEndListAppended(type) {
  9230. const lastFragmentEntity = this.endListFragments[type];
  9231. return lastFragmentEntity !== void 0 && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  9232. }
  9233. getState(fragment) {
  9234. const fragKey = getFragmentKey(fragment);
  9235. const fragmentEntity = this.fragments[fragKey];
  9236. if (fragmentEntity) {
  9237. if (!fragmentEntity.buffered) {
  9238. return FragmentState.APPENDING;
  9239. } else if (isPartial(fragmentEntity)) {
  9240. return FragmentState.PARTIAL;
  9241. } else {
  9242. return FragmentState.OK;
  9243. }
  9244. }
  9245. return FragmentState.NOT_LOADED;
  9246. }
  9247. isTimeBuffered(startPTS, endPTS, timeRange) {
  9248. let startTime;
  9249. let endTime;
  9250. for (let i2 = 0; i2 < timeRange.length; i2++) {
  9251. startTime = timeRange.start(i2) - this.bufferPadding;
  9252. endTime = timeRange.end(i2) + this.bufferPadding;
  9253. if (startPTS >= startTime && endPTS <= endTime) {
  9254. return true;
  9255. }
  9256. if (endPTS <= startTime) {
  9257. return false;
  9258. }
  9259. }
  9260. return false;
  9261. }
  9262. onManifestLoading() {
  9263. this.removeAllFragments();
  9264. }
  9265. onFragLoaded(event, data) {
  9266. if (data.frag.sn === "initSegment" || data.frag.bitrateTest) {
  9267. return;
  9268. }
  9269. const frag = data.frag;
  9270. const loaded = data.part ? null : data;
  9271. const fragKey = getFragmentKey(frag);
  9272. this.fragments[fragKey] = {
  9273. body: frag,
  9274. appendedPTS: null,
  9275. loaded,
  9276. buffered: false,
  9277. range: /* @__PURE__ */ Object.create(null)
  9278. };
  9279. }
  9280. onBufferAppended(event, data) {
  9281. const {
  9282. frag,
  9283. part,
  9284. timeRanges,
  9285. type
  9286. } = data;
  9287. if (frag.sn === "initSegment") {
  9288. return;
  9289. }
  9290. const playlistType = frag.type;
  9291. if (part) {
  9292. let activeParts = this.activePartLists[playlistType];
  9293. if (!activeParts) {
  9294. this.activePartLists[playlistType] = activeParts = [];
  9295. }
  9296. activeParts.push(part);
  9297. }
  9298. this.timeRanges = timeRanges;
  9299. const timeRange = timeRanges[type];
  9300. this.detectEvictedFragments(type, timeRange, playlistType, part);
  9301. }
  9302. onFragBuffered(event, data) {
  9303. this.detectPartialFragments(data);
  9304. }
  9305. hasFragment(fragment) {
  9306. const fragKey = getFragmentKey(fragment);
  9307. return !!this.fragments[fragKey];
  9308. }
  9309. hasFragments(type) {
  9310. const {
  9311. fragments
  9312. } = this;
  9313. const keys = Object.keys(fragments);
  9314. if (!type) {
  9315. return keys.length > 0;
  9316. }
  9317. for (let i2 = keys.length; i2--; ) {
  9318. const fragmentEntity = fragments[keys[i2]];
  9319. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === type) {
  9320. return true;
  9321. }
  9322. }
  9323. return false;
  9324. }
  9325. hasParts(type) {
  9326. var _this$activePartLists;
  9327. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  9328. }
  9329. removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  9330. if (withGapOnly && !this.hasGaps) {
  9331. return;
  9332. }
  9333. Object.keys(this.fragments).forEach((key) => {
  9334. const fragmentEntity = this.fragments[key];
  9335. if (!fragmentEntity) {
  9336. return;
  9337. }
  9338. const frag = fragmentEntity.body;
  9339. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  9340. return;
  9341. }
  9342. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  9343. this.removeFragment(frag);
  9344. }
  9345. });
  9346. }
  9347. removeFragment(fragment) {
  9348. const fragKey = getFragmentKey(fragment);
  9349. fragment.clearElementaryStreamInfo();
  9350. const activeParts = this.activePartLists[fragment.type];
  9351. if (activeParts) {
  9352. const snToRemove = fragment.sn;
  9353. this.activePartLists[fragment.type] = filterParts(activeParts, (part) => part.fragment.sn !== snToRemove);
  9354. }
  9355. delete this.fragments[fragKey];
  9356. if (fragment.endList) {
  9357. delete this.endListFragments[fragment.type];
  9358. }
  9359. }
  9360. removeAllFragments() {
  9361. var _this$hls, _this$hls$latestLevel;
  9362. this.fragments = /* @__PURE__ */ Object.create(null);
  9363. this.endListFragments = /* @__PURE__ */ Object.create(null);
  9364. this.activePartLists = /* @__PURE__ */ Object.create(null);
  9365. this.hasGaps = false;
  9366. const partlist = (_this$hls = this.hls) == null ? void 0 : (_this$hls$latestLevel = _this$hls.latestLevelDetails) == null ? void 0 : _this$hls$latestLevel.partList;
  9367. if (partlist) {
  9368. partlist.forEach((part) => part.clearElementaryStreamInfo());
  9369. }
  9370. }
  9371. }
  9372. function isPartial(fragmentEntity) {
  9373. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  9374. 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));
  9375. }
  9376. function getFragmentKey(fragment) {
  9377. return `${fragment.type}_${fragment.level}_${fragment.sn}`;
  9378. }
  9379. function filterParts(partList, predicate) {
  9380. return partList.filter((part) => {
  9381. const keep = predicate(part);
  9382. if (!keep) {
  9383. part.clearElementaryStreamInfo();
  9384. }
  9385. return keep;
  9386. });
  9387. }
  9388. var DecrypterAesMode = {
  9389. cbc: 0,
  9390. ctr: 1
  9391. };
  9392. class AESCrypto {
  9393. constructor(subtle, iv, aesMode) {
  9394. this.subtle = void 0;
  9395. this.aesIV = void 0;
  9396. this.aesMode = void 0;
  9397. this.subtle = subtle;
  9398. this.aesIV = iv;
  9399. this.aesMode = aesMode;
  9400. }
  9401. decrypt(data, key) {
  9402. switch (this.aesMode) {
  9403. case DecrypterAesMode.cbc:
  9404. return this.subtle.decrypt({
  9405. name: "AES-CBC",
  9406. iv: this.aesIV
  9407. }, key, data);
  9408. case DecrypterAesMode.ctr:
  9409. return this.subtle.decrypt(
  9410. {
  9411. name: "AES-CTR",
  9412. counter: this.aesIV,
  9413. length: 64
  9414. },
  9415. //64 : NIST SP800-38A standard suggests that the counter should occupy half of the counter block
  9416. key,
  9417. data
  9418. );
  9419. default:
  9420. throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`);
  9421. }
  9422. }
  9423. }
  9424. function removePadding(array2) {
  9425. const outputBytes = array2.byteLength;
  9426. const paddingBytes = outputBytes && new DataView(array2.buffer).getUint8(outputBytes - 1);
  9427. if (paddingBytes) {
  9428. return array2.slice(0, outputBytes - paddingBytes);
  9429. }
  9430. return array2;
  9431. }
  9432. class AESDecryptor {
  9433. constructor() {
  9434. this.rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
  9435. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  9436. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  9437. this.sBox = new Uint32Array(256);
  9438. this.invSBox = new Uint32Array(256);
  9439. this.key = new Uint32Array(0);
  9440. this.ksRows = 0;
  9441. this.keySize = 0;
  9442. this.keySchedule = void 0;
  9443. this.invKeySchedule = void 0;
  9444. this.initTable();
  9445. }
  9446. // Using view.getUint32() also swaps the byte order.
  9447. uint8ArrayToUint32Array_(arrayBuffer) {
  9448. const view2 = new DataView(arrayBuffer);
  9449. const newArray = new Uint32Array(4);
  9450. for (let i2 = 0; i2 < 4; i2++) {
  9451. newArray[i2] = view2.getUint32(i2 * 4);
  9452. }
  9453. return newArray;
  9454. }
  9455. initTable() {
  9456. const sBox = this.sBox;
  9457. const invSBox = this.invSBox;
  9458. const subMix = this.subMix;
  9459. const subMix0 = subMix[0];
  9460. const subMix1 = subMix[1];
  9461. const subMix2 = subMix[2];
  9462. const subMix3 = subMix[3];
  9463. const invSubMix = this.invSubMix;
  9464. const invSubMix0 = invSubMix[0];
  9465. const invSubMix1 = invSubMix[1];
  9466. const invSubMix2 = invSubMix[2];
  9467. const invSubMix3 = invSubMix[3];
  9468. const d2 = new Uint32Array(256);
  9469. let x = 0;
  9470. let xi = 0;
  9471. let i2 = 0;
  9472. for (i2 = 0; i2 < 256; i2++) {
  9473. if (i2 < 128) {
  9474. d2[i2] = i2 << 1;
  9475. } else {
  9476. d2[i2] = i2 << 1 ^ 283;
  9477. }
  9478. }
  9479. for (i2 = 0; i2 < 256; i2++) {
  9480. let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  9481. sx = sx >>> 8 ^ sx & 255 ^ 99;
  9482. sBox[x] = sx;
  9483. invSBox[sx] = x;
  9484. const x2 = d2[x];
  9485. const x4 = d2[x2];
  9486. const x8 = d2[x4];
  9487. let t2 = d2[sx] * 257 ^ sx * 16843008;
  9488. subMix0[x] = t2 << 24 | t2 >>> 8;
  9489. subMix1[x] = t2 << 16 | t2 >>> 16;
  9490. subMix2[x] = t2 << 8 | t2 >>> 24;
  9491. subMix3[x] = t2;
  9492. t2 = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008;
  9493. invSubMix0[sx] = t2 << 24 | t2 >>> 8;
  9494. invSubMix1[sx] = t2 << 16 | t2 >>> 16;
  9495. invSubMix2[sx] = t2 << 8 | t2 >>> 24;
  9496. invSubMix3[sx] = t2;
  9497. if (!x) {
  9498. x = xi = 1;
  9499. } else {
  9500. x = x2 ^ d2[d2[d2[x8 ^ x2]]];
  9501. xi ^= d2[d2[xi]];
  9502. }
  9503. }
  9504. }
  9505. expandKey(keyBuffer) {
  9506. const key = this.uint8ArrayToUint32Array_(keyBuffer);
  9507. let sameKey = true;
  9508. let offset = 0;
  9509. while (offset < key.length && sameKey) {
  9510. sameKey = key[offset] === this.key[offset];
  9511. offset++;
  9512. }
  9513. if (sameKey) {
  9514. return;
  9515. }
  9516. this.key = key;
  9517. const keySize = this.keySize = key.length;
  9518. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  9519. throw new Error("Invalid aes key size=" + keySize);
  9520. }
  9521. const ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  9522. let ksRow;
  9523. let invKsRow;
  9524. const keySchedule = this.keySchedule = new Uint32Array(ksRows);
  9525. const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  9526. const sbox = this.sBox;
  9527. const rcon = this.rcon;
  9528. const invSubMix = this.invSubMix;
  9529. const invSubMix0 = invSubMix[0];
  9530. const invSubMix1 = invSubMix[1];
  9531. const invSubMix2 = invSubMix[2];
  9532. const invSubMix3 = invSubMix[3];
  9533. let prev;
  9534. let t2;
  9535. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  9536. if (ksRow < keySize) {
  9537. prev = keySchedule[ksRow] = key[ksRow];
  9538. continue;
  9539. }
  9540. t2 = prev;
  9541. if (ksRow % keySize === 0) {
  9542. t2 = t2 << 8 | t2 >>> 24;
  9543. t2 = sbox[t2 >>> 24] << 24 | sbox[t2 >>> 16 & 255] << 16 | sbox[t2 >>> 8 & 255] << 8 | sbox[t2 & 255];
  9544. t2 ^= rcon[ksRow / keySize | 0] << 24;
  9545. } else if (keySize > 6 && ksRow % keySize === 4) {
  9546. t2 = sbox[t2 >>> 24] << 24 | sbox[t2 >>> 16 & 255] << 16 | sbox[t2 >>> 8 & 255] << 8 | sbox[t2 & 255];
  9547. }
  9548. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t2) >>> 0;
  9549. }
  9550. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  9551. ksRow = ksRows - invKsRow;
  9552. if (invKsRow & 3) {
  9553. t2 = keySchedule[ksRow];
  9554. } else {
  9555. t2 = keySchedule[ksRow - 4];
  9556. }
  9557. if (invKsRow < 4 || ksRow <= 4) {
  9558. invKeySchedule[invKsRow] = t2;
  9559. } else {
  9560. invKeySchedule[invKsRow] = invSubMix0[sbox[t2 >>> 24]] ^ invSubMix1[sbox[t2 >>> 16 & 255]] ^ invSubMix2[sbox[t2 >>> 8 & 255]] ^ invSubMix3[sbox[t2 & 255]];
  9561. }
  9562. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  9563. }
  9564. }
  9565. // Adding this as a method greatly improves performance.
  9566. networkToHostOrderSwap(word) {
  9567. return word << 24 | (word & 65280) << 8 | (word & 16711680) >> 8 | word >>> 24;
  9568. }
  9569. decrypt(inputArrayBuffer, offset, aesIV) {
  9570. const nRounds = this.keySize + 6;
  9571. const invKeySchedule = this.invKeySchedule;
  9572. const invSBOX = this.invSBox;
  9573. const invSubMix = this.invSubMix;
  9574. const invSubMix0 = invSubMix[0];
  9575. const invSubMix1 = invSubMix[1];
  9576. const invSubMix2 = invSubMix[2];
  9577. const invSubMix3 = invSubMix[3];
  9578. const initVector = this.uint8ArrayToUint32Array_(aesIV);
  9579. let initVector0 = initVector[0];
  9580. let initVector1 = initVector[1];
  9581. let initVector2 = initVector[2];
  9582. let initVector3 = initVector[3];
  9583. const inputInt32 = new Int32Array(inputArrayBuffer);
  9584. const outputInt32 = new Int32Array(inputInt32.length);
  9585. let t0, t1, t2, t3;
  9586. let s0, s1, s2, s3;
  9587. let inputWords0, inputWords1, inputWords2, inputWords3;
  9588. let ksRow, i2;
  9589. const swapWord = this.networkToHostOrderSwap;
  9590. while (offset < inputInt32.length) {
  9591. inputWords0 = swapWord(inputInt32[offset]);
  9592. inputWords1 = swapWord(inputInt32[offset + 1]);
  9593. inputWords2 = swapWord(inputInt32[offset + 2]);
  9594. inputWords3 = swapWord(inputInt32[offset + 3]);
  9595. s0 = inputWords0 ^ invKeySchedule[0];
  9596. s1 = inputWords3 ^ invKeySchedule[1];
  9597. s2 = inputWords2 ^ invKeySchedule[2];
  9598. s3 = inputWords1 ^ invKeySchedule[3];
  9599. ksRow = 4;
  9600. for (i2 = 1; i2 < nRounds; i2++) {
  9601. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 255] ^ invSubMix2[s2 >> 8 & 255] ^ invSubMix3[s3 & 255] ^ invKeySchedule[ksRow];
  9602. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 255] ^ invSubMix2[s3 >> 8 & 255] ^ invSubMix3[s0 & 255] ^ invKeySchedule[ksRow + 1];
  9603. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 255] ^ invSubMix2[s0 >> 8 & 255] ^ invSubMix3[s1 & 255] ^ invKeySchedule[ksRow + 2];
  9604. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 255] ^ invSubMix2[s1 >> 8 & 255] ^ invSubMix3[s2 & 255] ^ invKeySchedule[ksRow + 3];
  9605. s0 = t0;
  9606. s1 = t1;
  9607. s2 = t2;
  9608. s3 = t3;
  9609. ksRow = ksRow + 4;
  9610. }
  9611. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 255] << 16 ^ invSBOX[s2 >> 8 & 255] << 8 ^ invSBOX[s3 & 255] ^ invKeySchedule[ksRow];
  9612. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 255] << 16 ^ invSBOX[s3 >> 8 & 255] << 8 ^ invSBOX[s0 & 255] ^ invKeySchedule[ksRow + 1];
  9613. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 255] << 16 ^ invSBOX[s0 >> 8 & 255] << 8 ^ invSBOX[s1 & 255] ^ invKeySchedule[ksRow + 2];
  9614. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 255] << 16 ^ invSBOX[s1 >> 8 & 255] << 8 ^ invSBOX[s2 & 255] ^ invKeySchedule[ksRow + 3];
  9615. outputInt32[offset] = swapWord(t0 ^ initVector0);
  9616. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  9617. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  9618. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  9619. initVector0 = inputWords0;
  9620. initVector1 = inputWords1;
  9621. initVector2 = inputWords2;
  9622. initVector3 = inputWords3;
  9623. offset = offset + 4;
  9624. }
  9625. return outputInt32.buffer;
  9626. }
  9627. }
  9628. class FastAESKey {
  9629. constructor(subtle, key, aesMode) {
  9630. this.subtle = void 0;
  9631. this.key = void 0;
  9632. this.aesMode = void 0;
  9633. this.subtle = subtle;
  9634. this.key = key;
  9635. this.aesMode = aesMode;
  9636. }
  9637. expandKey() {
  9638. const subtleAlgoName = getSubtleAlgoName(this.aesMode);
  9639. return this.subtle.importKey("raw", this.key, {
  9640. name: subtleAlgoName
  9641. }, false, ["encrypt", "decrypt"]);
  9642. }
  9643. }
  9644. function getSubtleAlgoName(aesMode) {
  9645. switch (aesMode) {
  9646. case DecrypterAesMode.cbc:
  9647. return "AES-CBC";
  9648. case DecrypterAesMode.ctr:
  9649. return "AES-CTR";
  9650. default:
  9651. throw new Error(`[FastAESKey] invalid aes mode ${aesMode}`);
  9652. }
  9653. }
  9654. const CHUNK_SIZE = 16;
  9655. class Decrypter {
  9656. constructor(config2, {
  9657. removePKCS7Padding = true
  9658. } = {}) {
  9659. this.logEnabled = true;
  9660. this.removePKCS7Padding = void 0;
  9661. this.subtle = null;
  9662. this.softwareDecrypter = null;
  9663. this.key = null;
  9664. this.fastAesKey = null;
  9665. this.remainderData = null;
  9666. this.currentIV = null;
  9667. this.currentResult = null;
  9668. this.useSoftware = void 0;
  9669. this.enableSoftwareAES = void 0;
  9670. this.enableSoftwareAES = config2.enableSoftwareAES;
  9671. this.removePKCS7Padding = removePKCS7Padding;
  9672. if (removePKCS7Padding) {
  9673. try {
  9674. const browserCrypto = self.crypto;
  9675. if (browserCrypto) {
  9676. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  9677. }
  9678. } catch (e2) {
  9679. }
  9680. }
  9681. this.useSoftware = !this.subtle;
  9682. }
  9683. destroy() {
  9684. this.subtle = null;
  9685. this.softwareDecrypter = null;
  9686. this.key = null;
  9687. this.fastAesKey = null;
  9688. this.remainderData = null;
  9689. this.currentIV = null;
  9690. this.currentResult = null;
  9691. }
  9692. isSync() {
  9693. return this.useSoftware;
  9694. }
  9695. flush() {
  9696. const {
  9697. currentResult,
  9698. remainderData
  9699. } = this;
  9700. if (!currentResult || remainderData) {
  9701. this.reset();
  9702. return null;
  9703. }
  9704. const data = new Uint8Array(currentResult);
  9705. this.reset();
  9706. if (this.removePKCS7Padding) {
  9707. return removePadding(data);
  9708. }
  9709. return data;
  9710. }
  9711. reset() {
  9712. this.currentResult = null;
  9713. this.currentIV = null;
  9714. this.remainderData = null;
  9715. if (this.softwareDecrypter) {
  9716. this.softwareDecrypter = null;
  9717. }
  9718. }
  9719. decrypt(data, key, iv, aesMode) {
  9720. if (this.useSoftware) {
  9721. return new Promise((resolve, reject) => {
  9722. const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
  9723. this.softwareDecrypt(dataView, key, iv, aesMode);
  9724. const decryptResult = this.flush();
  9725. if (decryptResult) {
  9726. resolve(decryptResult.buffer);
  9727. } else {
  9728. reject(new Error("[softwareDecrypt] Failed to decrypt data"));
  9729. }
  9730. });
  9731. }
  9732. return this.webCryptoDecrypt(new Uint8Array(data), key, iv, aesMode);
  9733. }
  9734. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  9735. // data is handled in the flush() call
  9736. softwareDecrypt(data, key, iv, aesMode) {
  9737. const {
  9738. currentIV,
  9739. currentResult,
  9740. remainderData
  9741. } = this;
  9742. if (aesMode !== DecrypterAesMode.cbc || key.byteLength !== 16) {
  9743. logger.warn("SoftwareDecrypt: can only handle AES-128-CBC");
  9744. return null;
  9745. }
  9746. this.logOnce("JS AES decrypt");
  9747. if (remainderData) {
  9748. data = appendUint8Array(remainderData, data);
  9749. this.remainderData = null;
  9750. }
  9751. const currentChunk = this.getValidChunk(data);
  9752. if (!currentChunk.length) {
  9753. return null;
  9754. }
  9755. if (currentIV) {
  9756. iv = currentIV;
  9757. }
  9758. let softwareDecrypter = this.softwareDecrypter;
  9759. if (!softwareDecrypter) {
  9760. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  9761. }
  9762. softwareDecrypter.expandKey(key);
  9763. const result = currentResult;
  9764. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  9765. this.currentIV = currentChunk.slice(-16).buffer;
  9766. if (!result) {
  9767. return null;
  9768. }
  9769. return result;
  9770. }
  9771. webCryptoDecrypt(data, key, iv, aesMode) {
  9772. if (this.key !== key || !this.fastAesKey) {
  9773. if (!this.subtle) {
  9774. return Promise.resolve(this.onWebCryptoError(data, key, iv, aesMode));
  9775. }
  9776. this.key = key;
  9777. this.fastAesKey = new FastAESKey(this.subtle, key, aesMode);
  9778. }
  9779. return this.fastAesKey.expandKey().then((aesKey) => {
  9780. if (!this.subtle) {
  9781. return Promise.reject(new Error("web crypto not initialized"));
  9782. }
  9783. this.logOnce("WebCrypto AES decrypt");
  9784. const crypto = new AESCrypto(this.subtle, new Uint8Array(iv), aesMode);
  9785. return crypto.decrypt(data.buffer, aesKey);
  9786. }).catch((err) => {
  9787. logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);
  9788. return this.onWebCryptoError(data, key, iv, aesMode);
  9789. });
  9790. }
  9791. onWebCryptoError(data, key, iv, aesMode) {
  9792. const enableSoftwareAES = this.enableSoftwareAES;
  9793. if (enableSoftwareAES) {
  9794. this.useSoftware = true;
  9795. this.logEnabled = true;
  9796. this.softwareDecrypt(data, key, iv, aesMode);
  9797. const decryptResult = this.flush();
  9798. if (decryptResult) {
  9799. return decryptResult.buffer;
  9800. }
  9801. }
  9802. throw new Error("WebCrypto" + (enableSoftwareAES ? " and softwareDecrypt" : "") + ": failed to decrypt data");
  9803. }
  9804. getValidChunk(data) {
  9805. let currentChunk = data;
  9806. const splitPoint = data.length - data.length % CHUNK_SIZE;
  9807. if (splitPoint !== data.length) {
  9808. currentChunk = data.slice(0, splitPoint);
  9809. this.remainderData = data.slice(splitPoint);
  9810. }
  9811. return currentChunk;
  9812. }
  9813. logOnce(msg) {
  9814. if (!this.logEnabled) {
  9815. return;
  9816. }
  9817. logger.log(`[decrypter]: ${msg}`);
  9818. this.logEnabled = false;
  9819. }
  9820. }
  9821. const MIN_CHUNK_SIZE = Math.pow(2, 17);
  9822. class FragmentLoader {
  9823. constructor(config2) {
  9824. this.config = void 0;
  9825. this.loader = null;
  9826. this.partLoadTimeout = -1;
  9827. this.config = config2;
  9828. }
  9829. destroy() {
  9830. if (this.loader) {
  9831. this.loader.destroy();
  9832. this.loader = null;
  9833. }
  9834. }
  9835. abort() {
  9836. if (this.loader) {
  9837. this.loader.abort();
  9838. }
  9839. }
  9840. load(frag, onProgress) {
  9841. const url2 = frag.url;
  9842. if (!url2) {
  9843. return Promise.reject(new LoadError({
  9844. type: ErrorTypes.NETWORK_ERROR,
  9845. details: ErrorDetails.FRAG_LOAD_ERROR,
  9846. fatal: false,
  9847. frag,
  9848. error: new Error(`Fragment does not have a ${url2 ? "part list" : "url"}`),
  9849. networkDetails: null
  9850. }));
  9851. }
  9852. this.abort();
  9853. const config2 = this.config;
  9854. const FragmentILoader = config2.fLoader;
  9855. const DefaultILoader = config2.loader;
  9856. return new Promise((resolve, reject) => {
  9857. if (this.loader) {
  9858. this.loader.destroy();
  9859. }
  9860. if (frag.gap) {
  9861. if (frag.tagList.some((tags) => tags[0] === "GAP")) {
  9862. reject(createGapLoadError(frag));
  9863. return;
  9864. } else {
  9865. frag.gap = false;
  9866. }
  9867. }
  9868. const loader = this.loader = FragmentILoader ? new FragmentILoader(config2) : new DefaultILoader(config2);
  9869. const loaderContext = createLoaderContext(frag);
  9870. frag.loader = loader;
  9871. const loadPolicy = getLoaderConfigWithoutReties(config2.fragLoadPolicy.default);
  9872. const loaderConfig = {
  9873. loadPolicy,
  9874. timeout: loadPolicy.maxLoadTimeMs,
  9875. maxRetry: 0,
  9876. retryDelay: 0,
  9877. maxRetryDelay: 0,
  9878. highWaterMark: frag.sn === "initSegment" ? Infinity : MIN_CHUNK_SIZE
  9879. };
  9880. frag.stats = loader.stats;
  9881. const callbacks = {
  9882. onSuccess: (response, stats, context, networkDetails) => {
  9883. this.resetLoader(frag, loader);
  9884. let payload = response.data;
  9885. if (context.resetIV && frag.decryptdata) {
  9886. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  9887. payload = payload.slice(16);
  9888. }
  9889. resolve({
  9890. frag,
  9891. part: null,
  9892. payload,
  9893. networkDetails
  9894. });
  9895. },
  9896. onError: (response, context, networkDetails, stats) => {
  9897. this.resetLoader(frag, loader);
  9898. reject(new LoadError({
  9899. type: ErrorTypes.NETWORK_ERROR,
  9900. details: ErrorDetails.FRAG_LOAD_ERROR,
  9901. fatal: false,
  9902. frag,
  9903. response: _objectSpread2({
  9904. url: url2,
  9905. data: void 0
  9906. }, response),
  9907. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  9908. networkDetails,
  9909. stats
  9910. }));
  9911. },
  9912. onAbort: (stats, context, networkDetails) => {
  9913. this.resetLoader(frag, loader);
  9914. reject(new LoadError({
  9915. type: ErrorTypes.NETWORK_ERROR,
  9916. details: ErrorDetails.INTERNAL_ABORTED,
  9917. fatal: false,
  9918. frag,
  9919. error: new Error("Aborted"),
  9920. networkDetails,
  9921. stats
  9922. }));
  9923. },
  9924. onTimeout: (stats, context, networkDetails) => {
  9925. this.resetLoader(frag, loader);
  9926. reject(new LoadError({
  9927. type: ErrorTypes.NETWORK_ERROR,
  9928. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  9929. fatal: false,
  9930. frag,
  9931. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  9932. networkDetails,
  9933. stats
  9934. }));
  9935. }
  9936. };
  9937. if (onProgress) {
  9938. callbacks.onProgress = (stats, context, data, networkDetails) => onProgress({
  9939. frag,
  9940. part: null,
  9941. payload: data,
  9942. networkDetails
  9943. });
  9944. }
  9945. loader.load(loaderContext, loaderConfig, callbacks);
  9946. });
  9947. }
  9948. loadPart(frag, part, onProgress) {
  9949. this.abort();
  9950. const config2 = this.config;
  9951. const FragmentILoader = config2.fLoader;
  9952. const DefaultILoader = config2.loader;
  9953. return new Promise((resolve, reject) => {
  9954. if (this.loader) {
  9955. this.loader.destroy();
  9956. }
  9957. if (frag.gap || part.gap) {
  9958. reject(createGapLoadError(frag, part));
  9959. return;
  9960. }
  9961. const loader = this.loader = FragmentILoader ? new FragmentILoader(config2) : new DefaultILoader(config2);
  9962. const loaderContext = createLoaderContext(frag, part);
  9963. frag.loader = loader;
  9964. const loadPolicy = getLoaderConfigWithoutReties(config2.fragLoadPolicy.default);
  9965. const loaderConfig = {
  9966. loadPolicy,
  9967. timeout: loadPolicy.maxLoadTimeMs,
  9968. maxRetry: 0,
  9969. retryDelay: 0,
  9970. maxRetryDelay: 0,
  9971. highWaterMark: MIN_CHUNK_SIZE
  9972. };
  9973. part.stats = loader.stats;
  9974. loader.load(loaderContext, loaderConfig, {
  9975. onSuccess: (response, stats, context, networkDetails) => {
  9976. this.resetLoader(frag, loader);
  9977. this.updateStatsFromPart(frag, part);
  9978. const partLoadedData = {
  9979. frag,
  9980. part,
  9981. payload: response.data,
  9982. networkDetails
  9983. };
  9984. onProgress(partLoadedData);
  9985. resolve(partLoadedData);
  9986. },
  9987. onError: (response, context, networkDetails, stats) => {
  9988. this.resetLoader(frag, loader);
  9989. reject(new LoadError({
  9990. type: ErrorTypes.NETWORK_ERROR,
  9991. details: ErrorDetails.FRAG_LOAD_ERROR,
  9992. fatal: false,
  9993. frag,
  9994. part,
  9995. response: _objectSpread2({
  9996. url: loaderContext.url,
  9997. data: void 0
  9998. }, response),
  9999. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  10000. networkDetails,
  10001. stats
  10002. }));
  10003. },
  10004. onAbort: (stats, context, networkDetails) => {
  10005. frag.stats.aborted = part.stats.aborted;
  10006. this.resetLoader(frag, loader);
  10007. reject(new LoadError({
  10008. type: ErrorTypes.NETWORK_ERROR,
  10009. details: ErrorDetails.INTERNAL_ABORTED,
  10010. fatal: false,
  10011. frag,
  10012. part,
  10013. error: new Error("Aborted"),
  10014. networkDetails,
  10015. stats
  10016. }));
  10017. },
  10018. onTimeout: (stats, context, networkDetails) => {
  10019. this.resetLoader(frag, loader);
  10020. reject(new LoadError({
  10021. type: ErrorTypes.NETWORK_ERROR,
  10022. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  10023. fatal: false,
  10024. frag,
  10025. part,
  10026. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  10027. networkDetails,
  10028. stats
  10029. }));
  10030. }
  10031. });
  10032. });
  10033. }
  10034. updateStatsFromPart(frag, part) {
  10035. const fragStats = frag.stats;
  10036. const partStats = part.stats;
  10037. const partTotal = partStats.total;
  10038. fragStats.loaded += partStats.loaded;
  10039. if (partTotal) {
  10040. const estTotalParts = Math.round(frag.duration / part.duration);
  10041. const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  10042. const estRemainingParts = estTotalParts - estLoadedParts;
  10043. const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  10044. fragStats.total = fragStats.loaded + estRemainingBytes;
  10045. } else {
  10046. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  10047. }
  10048. const fragLoading = fragStats.loading;
  10049. const partLoading = partStats.loading;
  10050. if (fragLoading.start) {
  10051. fragLoading.first += partLoading.first - partLoading.start;
  10052. } else {
  10053. fragLoading.start = partLoading.start;
  10054. fragLoading.first = partLoading.first;
  10055. }
  10056. fragLoading.end = partLoading.end;
  10057. }
  10058. resetLoader(frag, loader) {
  10059. frag.loader = null;
  10060. if (this.loader === loader) {
  10061. self.clearTimeout(this.partLoadTimeout);
  10062. this.loader = null;
  10063. }
  10064. loader.destroy();
  10065. }
  10066. }
  10067. function createLoaderContext(frag, part = null) {
  10068. const segment = part || frag;
  10069. const loaderContext = {
  10070. frag,
  10071. part,
  10072. responseType: "arraybuffer",
  10073. url: segment.url,
  10074. headers: {},
  10075. rangeStart: 0,
  10076. rangeEnd: 0
  10077. };
  10078. const start = segment.byteRangeStartOffset;
  10079. const end = segment.byteRangeEndOffset;
  10080. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  10081. var _frag$decryptdata;
  10082. let byteRangeStart = start;
  10083. let byteRangeEnd = end;
  10084. if (frag.sn === "initSegment" && isMethodFullSegmentAesCbc((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method)) {
  10085. const fragmentLen = end - start;
  10086. if (fragmentLen % 16) {
  10087. byteRangeEnd = end + (16 - fragmentLen % 16);
  10088. }
  10089. if (start !== 0) {
  10090. loaderContext.resetIV = true;
  10091. byteRangeStart = start - 16;
  10092. }
  10093. }
  10094. loaderContext.rangeStart = byteRangeStart;
  10095. loaderContext.rangeEnd = byteRangeEnd;
  10096. }
  10097. return loaderContext;
  10098. }
  10099. function createGapLoadError(frag, part) {
  10100. const error2 = new Error(`GAP ${frag.gap ? "tag" : "attribute"} found`);
  10101. const errorData = {
  10102. type: ErrorTypes.MEDIA_ERROR,
  10103. details: ErrorDetails.FRAG_GAP,
  10104. fatal: false,
  10105. frag,
  10106. error: error2,
  10107. networkDetails: null
  10108. };
  10109. if (part) {
  10110. errorData.part = part;
  10111. }
  10112. (part ? part : frag).stats.aborted = true;
  10113. return new LoadError(errorData);
  10114. }
  10115. function isMethodFullSegmentAesCbc(method) {
  10116. return method === "AES-128" || method === "AES-256";
  10117. }
  10118. class LoadError extends Error {
  10119. constructor(data) {
  10120. super(data.error.message);
  10121. this.data = void 0;
  10122. this.data = data;
  10123. }
  10124. }
  10125. class TaskLoop extends Logger {
  10126. constructor(label, logger2) {
  10127. super(label, logger2);
  10128. this._boundTick = void 0;
  10129. this._tickTimer = null;
  10130. this._tickInterval = null;
  10131. this._tickCallCount = 0;
  10132. this._boundTick = this.tick.bind(this);
  10133. }
  10134. destroy() {
  10135. this.onHandlerDestroying();
  10136. this.onHandlerDestroyed();
  10137. }
  10138. onHandlerDestroying() {
  10139. this.clearNextTick();
  10140. this.clearInterval();
  10141. }
  10142. onHandlerDestroyed() {
  10143. }
  10144. hasInterval() {
  10145. return !!this._tickInterval;
  10146. }
  10147. hasNextTick() {
  10148. return !!this._tickTimer;
  10149. }
  10150. /**
  10151. * @param millis - Interval time (ms)
  10152. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  10153. */
  10154. setInterval(millis) {
  10155. if (!this._tickInterval) {
  10156. this._tickCallCount = 0;
  10157. this._tickInterval = self.setInterval(this._boundTick, millis);
  10158. return true;
  10159. }
  10160. return false;
  10161. }
  10162. /**
  10163. * @returns True when interval was cleared, false when none was set (no effect)
  10164. */
  10165. clearInterval() {
  10166. if (this._tickInterval) {
  10167. self.clearInterval(this._tickInterval);
  10168. this._tickInterval = null;
  10169. return true;
  10170. }
  10171. return false;
  10172. }
  10173. /**
  10174. * @returns True when timeout was cleared, false when none was set (no effect)
  10175. */
  10176. clearNextTick() {
  10177. if (this._tickTimer) {
  10178. self.clearTimeout(this._tickTimer);
  10179. this._tickTimer = null;
  10180. return true;
  10181. }
  10182. return false;
  10183. }
  10184. /**
  10185. * Will call the subclass doTick implementation in this main loop tick
  10186. * or in the next one (via setTimeout(,0)) in case it has already been called
  10187. * in this tick (in case this is a re-entrant call).
  10188. */
  10189. tick() {
  10190. this._tickCallCount++;
  10191. if (this._tickCallCount === 1) {
  10192. this.doTick();
  10193. if (this._tickCallCount > 1) {
  10194. this.tickImmediate();
  10195. }
  10196. this._tickCallCount = 0;
  10197. }
  10198. }
  10199. tickImmediate() {
  10200. this.clearNextTick();
  10201. this._tickTimer = self.setTimeout(this._boundTick, 0);
  10202. }
  10203. /**
  10204. * For subclass to implement task logic
  10205. * @abstract
  10206. */
  10207. doTick() {
  10208. }
  10209. }
  10210. class ChunkMetadata {
  10211. constructor(level, sn, id, size = 0, part = -1, partial2 = false) {
  10212. this.level = void 0;
  10213. this.sn = void 0;
  10214. this.part = void 0;
  10215. this.id = void 0;
  10216. this.size = void 0;
  10217. this.partial = void 0;
  10218. this.transmuxing = getNewPerformanceTiming();
  10219. this.buffering = {
  10220. audio: getNewPerformanceTiming(),
  10221. video: getNewPerformanceTiming(),
  10222. audiovideo: getNewPerformanceTiming()
  10223. };
  10224. this.level = level;
  10225. this.sn = sn;
  10226. this.id = id;
  10227. this.size = size;
  10228. this.part = part;
  10229. this.partial = partial2;
  10230. }
  10231. }
  10232. function getNewPerformanceTiming() {
  10233. return {
  10234. start: 0,
  10235. executeStart: 0,
  10236. executeEnd: 0,
  10237. end: 0
  10238. };
  10239. }
  10240. const noopBuffered = {
  10241. length: 0,
  10242. start: () => 0,
  10243. end: () => 0
  10244. };
  10245. class BufferHelper {
  10246. /**
  10247. * Return true if `media`'s buffered include `position`
  10248. */
  10249. static isBuffered(media, position) {
  10250. if (media) {
  10251. const buffered = BufferHelper.getBuffered(media);
  10252. for (let i2 = buffered.length; i2--; ) {
  10253. if (position >= buffered.start(i2) && position <= buffered.end(i2)) {
  10254. return true;
  10255. }
  10256. }
  10257. }
  10258. return false;
  10259. }
  10260. static bufferedRanges(media) {
  10261. if (media) {
  10262. const timeRanges = BufferHelper.getBuffered(media);
  10263. return BufferHelper.timeRangesToArray(timeRanges);
  10264. }
  10265. return [];
  10266. }
  10267. static timeRangesToArray(timeRanges) {
  10268. const buffered = [];
  10269. for (let i2 = 0; i2 < timeRanges.length; i2++) {
  10270. buffered.push({
  10271. start: timeRanges.start(i2),
  10272. end: timeRanges.end(i2)
  10273. });
  10274. }
  10275. return buffered;
  10276. }
  10277. static bufferInfo(media, pos, maxHoleDuration) {
  10278. if (media) {
  10279. const buffered = BufferHelper.bufferedRanges(media);
  10280. if (buffered.length) {
  10281. return BufferHelper.bufferedInfo(buffered, pos, maxHoleDuration);
  10282. }
  10283. }
  10284. return {
  10285. len: 0,
  10286. start: pos,
  10287. end: pos,
  10288. bufferedIndex: -1
  10289. };
  10290. }
  10291. static bufferedInfo(buffered, pos, maxHoleDuration) {
  10292. pos = Math.max(0, pos);
  10293. if (buffered.length > 1) {
  10294. buffered.sort((a2, b2) => a2.start - b2.start || b2.end - a2.end);
  10295. }
  10296. let bufferedIndex = -1;
  10297. let buffered2 = [];
  10298. if (maxHoleDuration) {
  10299. for (let i2 = 0; i2 < buffered.length; i2++) {
  10300. if (pos >= buffered[i2].start && pos <= buffered[i2].end) {
  10301. bufferedIndex = i2;
  10302. }
  10303. const buf2len = buffered2.length;
  10304. if (buf2len) {
  10305. const buf2end = buffered2[buf2len - 1].end;
  10306. if (buffered[i2].start - buf2end < maxHoleDuration) {
  10307. if (buffered[i2].end > buf2end) {
  10308. buffered2[buf2len - 1].end = buffered[i2].end;
  10309. }
  10310. } else {
  10311. buffered2.push(buffered[i2]);
  10312. }
  10313. } else {
  10314. buffered2.push(buffered[i2]);
  10315. }
  10316. }
  10317. } else {
  10318. buffered2 = buffered;
  10319. }
  10320. let bufferLen = 0;
  10321. let nextStart;
  10322. let bufferStart = pos;
  10323. let bufferEnd = pos;
  10324. for (let i2 = 0; i2 < buffered2.length; i2++) {
  10325. const start = buffered2[i2].start;
  10326. const end = buffered2[i2].end;
  10327. if (bufferedIndex === -1 && pos >= start && pos <= end) {
  10328. bufferedIndex = i2;
  10329. }
  10330. if (pos + maxHoleDuration >= start && pos < end) {
  10331. bufferStart = start;
  10332. bufferEnd = end;
  10333. bufferLen = bufferEnd - pos;
  10334. } else if (pos + maxHoleDuration < start) {
  10335. nextStart = start;
  10336. break;
  10337. }
  10338. }
  10339. return {
  10340. len: bufferLen,
  10341. start: bufferStart || 0,
  10342. end: bufferEnd || 0,
  10343. nextStart,
  10344. buffered,
  10345. bufferedIndex
  10346. };
  10347. }
  10348. /**
  10349. * Safe method to get buffered property.
  10350. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  10351. */
  10352. static getBuffered(media) {
  10353. try {
  10354. return media.buffered || noopBuffered;
  10355. } catch (e2) {
  10356. logger.log("failed to get media.buffered", e2);
  10357. return noopBuffered;
  10358. }
  10359. }
  10360. }
  10361. const VARIABLE_REPLACEMENT_REGEX = /\{\$([a-zA-Z0-9-_]+)\}/g;
  10362. function hasVariableReferences(str) {
  10363. return VARIABLE_REPLACEMENT_REGEX.test(str);
  10364. }
  10365. function substituteVariables(parsed, value2) {
  10366. if (parsed.variableList !== null || parsed.hasVariableRefs) {
  10367. const variableList = parsed.variableList;
  10368. return value2.replace(VARIABLE_REPLACEMENT_REGEX, (variableReference) => {
  10369. const variableName = variableReference.substring(2, variableReference.length - 1);
  10370. const variableValue = variableList == null ? void 0 : variableList[variableName];
  10371. if (variableValue === void 0) {
  10372. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${variableName}"`));
  10373. return variableReference;
  10374. }
  10375. return variableValue;
  10376. });
  10377. }
  10378. return value2;
  10379. }
  10380. function addVariableDefinition(parsed, attr, parentUrl) {
  10381. let variableList = parsed.variableList;
  10382. if (!variableList) {
  10383. parsed.variableList = variableList = {};
  10384. }
  10385. let NAME;
  10386. let VALUE;
  10387. if ("QUERYPARAM" in attr) {
  10388. NAME = attr.QUERYPARAM;
  10389. try {
  10390. const searchParams = new self.URL(parentUrl).searchParams;
  10391. if (searchParams.has(NAME)) {
  10392. VALUE = searchParams.get(NAME);
  10393. } else {
  10394. throw new Error(`"${NAME}" does not match any query parameter in URI: "${parentUrl}"`);
  10395. }
  10396. } catch (error2) {
  10397. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${error2.message}`));
  10398. }
  10399. } else {
  10400. NAME = attr.NAME;
  10401. VALUE = attr.VALUE;
  10402. }
  10403. if (NAME in variableList) {
  10404. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${NAME}"`));
  10405. } else {
  10406. variableList[NAME] = VALUE || "";
  10407. }
  10408. }
  10409. function importVariableDefinition(parsed, attr, sourceVariableList) {
  10410. const IMPORT = attr.IMPORT;
  10411. if (sourceVariableList && IMPORT in sourceVariableList) {
  10412. let variableList = parsed.variableList;
  10413. if (!variableList) {
  10414. parsed.variableList = variableList = {};
  10415. }
  10416. variableList[IMPORT] = sourceVariableList[IMPORT];
  10417. } else {
  10418. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${IMPORT}"`));
  10419. }
  10420. }
  10421. const DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  10422. const ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  10423. class AttrList {
  10424. constructor(attrs, parsed) {
  10425. if (typeof attrs === "string") {
  10426. attrs = AttrList.parseAttrList(attrs, parsed);
  10427. }
  10428. _extends(this, attrs);
  10429. }
  10430. get clientAttrs() {
  10431. return Object.keys(this).filter((attr) => attr.substring(0, 2) === "X-");
  10432. }
  10433. decimalInteger(attrName) {
  10434. const intValue = parseInt(this[attrName], 10);
  10435. if (intValue > Number.MAX_SAFE_INTEGER) {
  10436. return Infinity;
  10437. }
  10438. return intValue;
  10439. }
  10440. hexadecimalInteger(attrName) {
  10441. if (this[attrName]) {
  10442. let stringValue = (this[attrName] || "0x").slice(2);
  10443. stringValue = (stringValue.length & 1 ? "0" : "") + stringValue;
  10444. const value2 = new Uint8Array(stringValue.length / 2);
  10445. for (let i2 = 0; i2 < stringValue.length / 2; i2++) {
  10446. value2[i2] = parseInt(stringValue.slice(i2 * 2, i2 * 2 + 2), 16);
  10447. }
  10448. return value2;
  10449. }
  10450. return null;
  10451. }
  10452. hexadecimalIntegerAsNumber(attrName) {
  10453. const intValue = parseInt(this[attrName], 16);
  10454. if (intValue > Number.MAX_SAFE_INTEGER) {
  10455. return Infinity;
  10456. }
  10457. return intValue;
  10458. }
  10459. decimalFloatingPoint(attrName) {
  10460. return parseFloat(this[attrName]);
  10461. }
  10462. optionalFloat(attrName, defaultValue) {
  10463. const value2 = this[attrName];
  10464. return value2 ? parseFloat(value2) : defaultValue;
  10465. }
  10466. enumeratedString(attrName) {
  10467. return this[attrName];
  10468. }
  10469. enumeratedStringList(attrName, dict) {
  10470. const attrValue = this[attrName];
  10471. return (attrValue ? attrValue.split(/[ ,]+/) : []).reduce((result, identifier) => {
  10472. result[identifier.toLowerCase()] = true;
  10473. return result;
  10474. }, dict);
  10475. }
  10476. bool(attrName) {
  10477. return this[attrName] === "YES";
  10478. }
  10479. decimalResolution(attrName) {
  10480. const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  10481. if (res === null) {
  10482. return void 0;
  10483. }
  10484. return {
  10485. width: parseInt(res[1], 10),
  10486. height: parseInt(res[2], 10)
  10487. };
  10488. }
  10489. static parseAttrList(input, parsed) {
  10490. let match;
  10491. const attrs = {};
  10492. const quote = '"';
  10493. ATTR_LIST_REGEX.lastIndex = 0;
  10494. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  10495. const name = match[1].trim();
  10496. let value2 = match[2];
  10497. const quotedString = value2.indexOf(quote) === 0 && value2.lastIndexOf(quote) === value2.length - 1;
  10498. let hexadecimalSequence = false;
  10499. if (quotedString) {
  10500. value2 = value2.slice(1, -1);
  10501. } else {
  10502. switch (name) {
  10503. case "IV":
  10504. case "SCTE35-CMD":
  10505. case "SCTE35-IN":
  10506. case "SCTE35-OUT":
  10507. hexadecimalSequence = true;
  10508. }
  10509. }
  10510. if (parsed && (quotedString || hexadecimalSequence)) {
  10511. {
  10512. value2 = substituteVariables(parsed, value2);
  10513. }
  10514. } else if (!hexadecimalSequence && !quotedString) {
  10515. switch (name) {
  10516. case "CLOSED-CAPTIONS":
  10517. if (value2 === "NONE") {
  10518. break;
  10519. }
  10520. case "ALLOWED-CPC":
  10521. case "CLASS":
  10522. case "ASSOC-LANGUAGE":
  10523. case "AUDIO":
  10524. case "BYTERANGE":
  10525. case "CHANNELS":
  10526. case "CHARACTERISTICS":
  10527. case "CODECS":
  10528. case "DATA-ID":
  10529. case "END-DATE":
  10530. case "GROUP-ID":
  10531. case "ID":
  10532. case "IMPORT":
  10533. case "INSTREAM-ID":
  10534. case "KEYFORMAT":
  10535. case "KEYFORMATVERSIONS":
  10536. case "LANGUAGE":
  10537. case "NAME":
  10538. case "PATHWAY-ID":
  10539. case "QUERYPARAM":
  10540. case "RECENTLY-REMOVED-DATERANGES":
  10541. case "SERVER-URI":
  10542. case "STABLE-RENDITION-ID":
  10543. case "STABLE-VARIANT-ID":
  10544. case "START-DATE":
  10545. case "SUBTITLES":
  10546. case "SUPPLEMENTAL-CODECS":
  10547. case "URI":
  10548. case "VALUE":
  10549. case "VIDEO":
  10550. case "X-ASSET-LIST":
  10551. case "X-ASSET-URI":
  10552. logger.warn(`${input}: attribute ${name} is missing quotes`);
  10553. }
  10554. }
  10555. attrs[name] = value2;
  10556. }
  10557. return attrs;
  10558. }
  10559. }
  10560. const CLASS_INTERSTITIAL = "com.apple.hls.interstitial";
  10561. function isDateRangeCueAttribute(attrName) {
  10562. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "CUE" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  10563. }
  10564. function isSCTE35Attribute(attrName) {
  10565. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN" || attrName === "SCTE35-CMD";
  10566. }
  10567. class DateRange {
  10568. constructor(dateRangeAttr, dateRangeWithSameId, tagCount = 0) {
  10569. var _dateRangeWithSameId$;
  10570. this.attr = void 0;
  10571. this.tagAnchor = void 0;
  10572. this.tagOrder = void 0;
  10573. this._startDate = void 0;
  10574. this._endDate = void 0;
  10575. this._dateAtEnd = void 0;
  10576. this._cue = void 0;
  10577. this._badValueForSameId = void 0;
  10578. this.tagAnchor = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagAnchor) || null;
  10579. this.tagOrder = (_dateRangeWithSameId$ = dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagOrder) != null ? _dateRangeWithSameId$ : tagCount;
  10580. if (dateRangeWithSameId) {
  10581. const previousAttr = dateRangeWithSameId.attr;
  10582. for (const key in previousAttr) {
  10583. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  10584. logger.warn(`DATERANGE tag attribute: "${key}" does not match for tags with ID: "${dateRangeAttr.ID}"`);
  10585. this._badValueForSameId = key;
  10586. break;
  10587. }
  10588. }
  10589. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  10590. }
  10591. this.attr = dateRangeAttr;
  10592. if (dateRangeWithSameId) {
  10593. this._startDate = dateRangeWithSameId._startDate;
  10594. this._cue = dateRangeWithSameId._cue;
  10595. this._endDate = dateRangeWithSameId._endDate;
  10596. this._dateAtEnd = dateRangeWithSameId._dateAtEnd;
  10597. } else {
  10598. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  10599. }
  10600. if ("END-DATE" in this.attr) {
  10601. const endDate = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.endDate) || new Date(this.attr["END-DATE"]);
  10602. if (isFiniteNumber(endDate.getTime())) {
  10603. this._endDate = endDate;
  10604. }
  10605. }
  10606. }
  10607. get id() {
  10608. return this.attr.ID;
  10609. }
  10610. get class() {
  10611. return this.attr.CLASS;
  10612. }
  10613. get cue() {
  10614. const _cue = this._cue;
  10615. if (_cue === void 0) {
  10616. return this._cue = this.attr.enumeratedStringList(this.attr.CUE ? "CUE" : "X-CUE", {
  10617. pre: false,
  10618. post: false,
  10619. once: false
  10620. });
  10621. }
  10622. return _cue;
  10623. }
  10624. get startTime() {
  10625. const {
  10626. tagAnchor
  10627. } = this;
  10628. if (tagAnchor === null || tagAnchor.programDateTime === null) {
  10629. logger.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${tagAnchor}`);
  10630. return NaN;
  10631. }
  10632. return tagAnchor.start + (this.startDate.getTime() - tagAnchor.programDateTime) / 1e3;
  10633. }
  10634. get startDate() {
  10635. return this._startDate;
  10636. }
  10637. get endDate() {
  10638. const dateAtEnd = this._endDate || this._dateAtEnd;
  10639. if (dateAtEnd) {
  10640. return dateAtEnd;
  10641. }
  10642. const duration = this.duration;
  10643. if (duration !== null) {
  10644. return this._dateAtEnd = new Date(this._startDate.getTime() + duration * 1e3);
  10645. }
  10646. return null;
  10647. }
  10648. get duration() {
  10649. if ("DURATION" in this.attr) {
  10650. const duration = this.attr.decimalFloatingPoint("DURATION");
  10651. if (isFiniteNumber(duration)) {
  10652. return duration;
  10653. }
  10654. } else if (this._endDate) {
  10655. return (this._endDate.getTime() - this._startDate.getTime()) / 1e3;
  10656. }
  10657. return null;
  10658. }
  10659. get plannedDuration() {
  10660. if ("PLANNED-DURATION" in this.attr) {
  10661. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  10662. }
  10663. return null;
  10664. }
  10665. get endOnNext() {
  10666. return this.attr.bool("END-ON-NEXT");
  10667. }
  10668. get isInterstitial() {
  10669. return this.class === CLASS_INTERSTITIAL;
  10670. }
  10671. get isValid() {
  10672. 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);
  10673. }
  10674. }
  10675. const DEFAULT_TARGET_DURATION = 10;
  10676. class LevelDetails {
  10677. constructor(baseUrl) {
  10678. this.PTSKnown = false;
  10679. this.alignedSliding = false;
  10680. this.averagetargetduration = void 0;
  10681. this.endCC = 0;
  10682. this.endSN = 0;
  10683. this.fragments = void 0;
  10684. this.fragmentHint = void 0;
  10685. this.partList = null;
  10686. this.dateRanges = void 0;
  10687. this.dateRangeTagCount = 0;
  10688. this.live = true;
  10689. this.requestScheduled = -1;
  10690. this.ageHeader = 0;
  10691. this.advancedDateTime = void 0;
  10692. this.updated = true;
  10693. this.advanced = true;
  10694. this.misses = 0;
  10695. this.startCC = 0;
  10696. this.startSN = 0;
  10697. this.startTimeOffset = null;
  10698. this.targetduration = 0;
  10699. this.totalduration = 0;
  10700. this.type = null;
  10701. this.url = void 0;
  10702. this.m3u8 = "";
  10703. this.version = null;
  10704. this.canBlockReload = false;
  10705. this.canSkipUntil = 0;
  10706. this.canSkipDateRanges = false;
  10707. this.skippedSegments = 0;
  10708. this.recentlyRemovedDateranges = void 0;
  10709. this.partHoldBack = 0;
  10710. this.holdBack = 0;
  10711. this.partTarget = 0;
  10712. this.preloadHint = void 0;
  10713. this.renditionReports = void 0;
  10714. this.tuneInGoal = 0;
  10715. this.deltaUpdateFailed = void 0;
  10716. this.driftStartTime = 0;
  10717. this.driftEndTime = 0;
  10718. this.driftStart = 0;
  10719. this.driftEnd = 0;
  10720. this.encryptedFragments = void 0;
  10721. this.playlistParsingError = null;
  10722. this.variableList = null;
  10723. this.hasVariableRefs = false;
  10724. this.appliedTimelineOffset = void 0;
  10725. this.fragments = [];
  10726. this.encryptedFragments = [];
  10727. this.dateRanges = {};
  10728. this.url = baseUrl;
  10729. }
  10730. reloaded(previous) {
  10731. if (!previous) {
  10732. this.advanced = true;
  10733. this.updated = true;
  10734. return;
  10735. }
  10736. const partSnDiff = this.lastPartSn - previous.lastPartSn;
  10737. const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  10738. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  10739. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  10740. if (this.updated || this.advanced) {
  10741. this.misses = Math.floor(previous.misses * 0.6);
  10742. } else {
  10743. this.misses = previous.misses + 1;
  10744. }
  10745. }
  10746. get hasProgramDateTime() {
  10747. if (this.fragments.length) {
  10748. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  10749. }
  10750. return false;
  10751. }
  10752. get levelTargetDuration() {
  10753. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  10754. }
  10755. get drift() {
  10756. const runTime = this.driftEndTime - this.driftStartTime;
  10757. if (runTime > 0) {
  10758. const runDuration = this.driftEnd - this.driftStart;
  10759. return runDuration * 1e3 / runTime;
  10760. }
  10761. return 1;
  10762. }
  10763. get edge() {
  10764. return this.partEnd || this.fragmentEnd;
  10765. }
  10766. get partEnd() {
  10767. var _this$partList;
  10768. if ((_this$partList = this.partList) != null && _this$partList.length) {
  10769. return this.partList[this.partList.length - 1].end;
  10770. }
  10771. return this.fragmentEnd;
  10772. }
  10773. get fragmentEnd() {
  10774. var _this$fragments;
  10775. if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
  10776. return this.fragments[this.fragments.length - 1].end;
  10777. }
  10778. return 0;
  10779. }
  10780. get fragmentStart() {
  10781. var _this$fragments2;
  10782. if ((_this$fragments2 = this.fragments) != null && _this$fragments2.length) {
  10783. return this.fragments[0].start;
  10784. }
  10785. return 0;
  10786. }
  10787. get age() {
  10788. if (this.advancedDateTime) {
  10789. return Math.max(Date.now() - this.advancedDateTime, 0) / 1e3;
  10790. }
  10791. return 0;
  10792. }
  10793. get lastPartIndex() {
  10794. var _this$partList2;
  10795. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  10796. return this.partList[this.partList.length - 1].index;
  10797. }
  10798. return -1;
  10799. }
  10800. get maxPartIndex() {
  10801. const partList = this.partList;
  10802. if (partList) {
  10803. const lastIndex = this.lastPartIndex;
  10804. if (lastIndex !== -1) {
  10805. for (let i2 = partList.length; i2--; ) {
  10806. if (partList[i2].index > lastIndex) {
  10807. return partList[i2].index;
  10808. }
  10809. }
  10810. return lastIndex;
  10811. }
  10812. }
  10813. return 0;
  10814. }
  10815. get lastPartSn() {
  10816. var _this$partList3;
  10817. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  10818. return this.partList[this.partList.length - 1].fragment.sn;
  10819. }
  10820. return this.endSN;
  10821. }
  10822. get expired() {
  10823. if (this.live && this.age && this.misses < 3) {
  10824. const playlistWindowDuration = this.partEnd - this.fragmentStart;
  10825. return this.age > Math.max(playlistWindowDuration, this.totalduration) + this.levelTargetDuration;
  10826. }
  10827. return false;
  10828. }
  10829. }
  10830. function isFullSegmentEncryption(method) {
  10831. return method === "AES-128" || method === "AES-256" || method === "AES-256-CTR";
  10832. }
  10833. function getAesModeFromFullSegmentMethod(method) {
  10834. switch (method) {
  10835. case "AES-128":
  10836. case "AES-256":
  10837. return DecrypterAesMode.cbc;
  10838. case "AES-256-CTR":
  10839. return DecrypterAesMode.ctr;
  10840. default:
  10841. throw new Error(`invalid full segment method ${method}`);
  10842. }
  10843. }
  10844. function base64Decode(base64encodedStr) {
  10845. return Uint8Array.from(atob(base64encodedStr), (c2) => c2.charCodeAt(0));
  10846. }
  10847. function strToUtf8array(str) {
  10848. return Uint8Array.from(unescape(encodeURIComponent(str)), (c2) => c2.charCodeAt(0));
  10849. }
  10850. function getKeyIdBytes(str) {
  10851. const keyIdbytes = strToUtf8array(str).subarray(0, 16);
  10852. const paddedkeyIdbytes = new Uint8Array(16);
  10853. paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);
  10854. return paddedkeyIdbytes;
  10855. }
  10856. function changeEndianness(keyId) {
  10857. const swap = function swap2(array2, from, to) {
  10858. const cur = array2[from];
  10859. array2[from] = array2[to];
  10860. array2[to] = cur;
  10861. };
  10862. swap(keyId, 0, 3);
  10863. swap(keyId, 1, 2);
  10864. swap(keyId, 4, 5);
  10865. swap(keyId, 6, 7);
  10866. }
  10867. function convertDataUriToArrayBytes(uri) {
  10868. const colonsplit = uri.split(":");
  10869. let keydata = null;
  10870. if (colonsplit[0] === "data" && colonsplit.length === 2) {
  10871. const semicolonsplit = colonsplit[1].split(";");
  10872. const commasplit = semicolonsplit[semicolonsplit.length - 1].split(",");
  10873. if (commasplit.length === 2) {
  10874. const isbase64 = commasplit[0] === "base64";
  10875. const data = commasplit[1];
  10876. if (isbase64) {
  10877. semicolonsplit.splice(-1, 1);
  10878. keydata = base64Decode(data);
  10879. } else {
  10880. keydata = getKeyIdBytes(data);
  10881. }
  10882. }
  10883. }
  10884. return keydata;
  10885. }
  10886. const optionalSelf = typeof self !== "undefined" ? self : void 0;
  10887. var KeySystems = {
  10888. CLEARKEY: "org.w3.clearkey",
  10889. FAIRPLAY: "com.apple.fps",
  10890. PLAYREADY: "com.microsoft.playready",
  10891. WIDEVINE: "com.widevine.alpha"
  10892. };
  10893. var KeySystemFormats = {
  10894. CLEARKEY: "org.w3.clearkey",
  10895. FAIRPLAY: "com.apple.streamingkeydelivery",
  10896. PLAYREADY: "com.microsoft.playready",
  10897. WIDEVINE: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
  10898. };
  10899. function keySystemFormatToKeySystemDomain(format2) {
  10900. switch (format2) {
  10901. case KeySystemFormats.FAIRPLAY:
  10902. return KeySystems.FAIRPLAY;
  10903. case KeySystemFormats.PLAYREADY:
  10904. return KeySystems.PLAYREADY;
  10905. case KeySystemFormats.WIDEVINE:
  10906. return KeySystems.WIDEVINE;
  10907. case KeySystemFormats.CLEARKEY:
  10908. return KeySystems.CLEARKEY;
  10909. }
  10910. }
  10911. function keySystemDomainToKeySystemFormat(keySystem) {
  10912. switch (keySystem) {
  10913. case KeySystems.FAIRPLAY:
  10914. return KeySystemFormats.FAIRPLAY;
  10915. case KeySystems.PLAYREADY:
  10916. return KeySystemFormats.PLAYREADY;
  10917. case KeySystems.WIDEVINE:
  10918. return KeySystemFormats.WIDEVINE;
  10919. case KeySystems.CLEARKEY:
  10920. return KeySystemFormats.CLEARKEY;
  10921. }
  10922. }
  10923. function getKeySystemsForConfig(config2) {
  10924. const {
  10925. drmSystems,
  10926. widevineLicenseUrl
  10927. } = config2;
  10928. const keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter((keySystem) => !!drmSystems[keySystem]) : [];
  10929. if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {
  10930. keySystemsToAttempt.push(KeySystems.WIDEVINE);
  10931. }
  10932. return keySystemsToAttempt;
  10933. }
  10934. const requestMediaKeySystemAccess = function(_optionalSelf$navigat) {
  10935. if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) {
  10936. return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
  10937. } else {
  10938. return null;
  10939. }
  10940. }();
  10941. function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
  10942. let initDataTypes;
  10943. switch (keySystem) {
  10944. case KeySystems.FAIRPLAY:
  10945. initDataTypes = ["cenc", "sinf"];
  10946. break;
  10947. case KeySystems.WIDEVINE:
  10948. case KeySystems.PLAYREADY:
  10949. initDataTypes = ["cenc"];
  10950. break;
  10951. case KeySystems.CLEARKEY:
  10952. initDataTypes = ["cenc", "keyids"];
  10953. break;
  10954. default:
  10955. throw new Error(`Unknown key-system: ${keySystem}`);
  10956. }
  10957. return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions);
  10958. }
  10959. function createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) {
  10960. const baseConfig = {
  10961. initDataTypes,
  10962. persistentState: drmSystemOptions.persistentState || "optional",
  10963. distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || "optional",
  10964. sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || "temporary"],
  10965. audioCapabilities: audioCodecs.map((codec) => ({
  10966. contentType: `audio/mp4; codecs=${codec}`,
  10967. robustness: drmSystemOptions.audioRobustness || "",
  10968. encryptionScheme: drmSystemOptions.audioEncryptionScheme || null
  10969. })),
  10970. videoCapabilities: videoCodecs.map((codec) => ({
  10971. contentType: `video/mp4; codecs=${codec}`,
  10972. robustness: drmSystemOptions.videoRobustness || "",
  10973. encryptionScheme: drmSystemOptions.videoEncryptionScheme || null
  10974. }))
  10975. };
  10976. return [baseConfig];
  10977. }
  10978. function isPersistentSessionType(drmSystemOptions) {
  10979. var _drmSystemOptions$ses;
  10980. return drmSystemOptions.sessionType === "persistent-license" || !!((_drmSystemOptions$ses = drmSystemOptions.sessionTypes) != null && _drmSystemOptions$ses.some((type) => type === "persistent-license"));
  10981. }
  10982. function parsePlayReadyWRM(keyBytes) {
  10983. const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);
  10984. const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));
  10985. const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf("<"), keyByteStr.length);
  10986. const parser = new DOMParser();
  10987. const xmlDoc = parser.parseFromString(xmlKeyBytes, "text/xml");
  10988. const keyData = xmlDoc.getElementsByTagName("KID")[0];
  10989. if (keyData) {
  10990. const keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute("VALUE");
  10991. if (keyId) {
  10992. const keyIdArray = base64Decode(keyId).subarray(0, 16);
  10993. changeEndianness(keyIdArray);
  10994. return keyIdArray;
  10995. }
  10996. }
  10997. return null;
  10998. }
  10999. let keyUriToKeyIdMap = {};
  11000. class LevelKey {
  11001. static clearKeyUriToKeyIdMap() {
  11002. keyUriToKeyIdMap = {};
  11003. }
  11004. constructor(method, uri, format2, formatversions = [1], iv = null, keyId) {
  11005. this.uri = void 0;
  11006. this.method = void 0;
  11007. this.keyFormat = void 0;
  11008. this.keyFormatVersions = void 0;
  11009. this.encrypted = void 0;
  11010. this.isCommonEncryption = void 0;
  11011. this.iv = null;
  11012. this.key = null;
  11013. this.keyId = null;
  11014. this.pssh = null;
  11015. this.method = method;
  11016. this.uri = uri;
  11017. this.keyFormat = format2;
  11018. this.keyFormatVersions = formatversions;
  11019. this.iv = iv;
  11020. this.encrypted = method ? method !== "NONE" : false;
  11021. this.isCommonEncryption = this.encrypted && !isFullSegmentEncryption(method);
  11022. if (keyId != null && keyId.startsWith("0x")) {
  11023. this.keyId = new Uint8Array(hexToArrayBuffer(keyId));
  11024. }
  11025. }
  11026. matches(key) {
  11027. var _key$iv, _this$iv;
  11028. 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(","));
  11029. }
  11030. isSupported() {
  11031. if (this.method) {
  11032. if (isFullSegmentEncryption(this.method) || this.method === "NONE") {
  11033. return true;
  11034. }
  11035. if (this.keyFormat === "identity") {
  11036. return this.method === "SAMPLE-AES";
  11037. } else {
  11038. switch (this.keyFormat) {
  11039. case KeySystemFormats.FAIRPLAY:
  11040. case KeySystemFormats.WIDEVINE:
  11041. case KeySystemFormats.PLAYREADY:
  11042. case KeySystemFormats.CLEARKEY:
  11043. return ["ISO-23001-7", "SAMPLE-AES", "SAMPLE-AES-CENC", "SAMPLE-AES-CTR"].indexOf(this.method) !== -1;
  11044. }
  11045. }
  11046. }
  11047. return false;
  11048. }
  11049. getDecryptData(sn) {
  11050. if (!this.encrypted || !this.uri) {
  11051. return null;
  11052. }
  11053. if (isFullSegmentEncryption(this.method) && this.uri && !this.iv) {
  11054. if (typeof sn !== "number") {
  11055. logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`);
  11056. sn = 0;
  11057. }
  11058. const iv = createInitializationVector(sn);
  11059. const decryptdata = new LevelKey(this.method, this.uri, "identity", this.keyFormatVersions, iv);
  11060. return decryptdata;
  11061. }
  11062. if (this.pssh && this.keyId) {
  11063. return this;
  11064. }
  11065. const keyBytes = convertDataUriToArrayBytes(this.uri);
  11066. if (keyBytes) {
  11067. switch (this.keyFormat) {
  11068. case KeySystemFormats.WIDEVINE:
  11069. this.pssh = keyBytes;
  11070. if (!this.keyId && keyBytes.length >= 22) {
  11071. const offset = keyBytes.length - 22;
  11072. this.keyId = keyBytes.subarray(offset, offset + 16);
  11073. }
  11074. break;
  11075. case KeySystemFormats.PLAYREADY: {
  11076. const PlayReadyKeySystemUUID = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]);
  11077. this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);
  11078. this.keyId = parsePlayReadyWRM(keyBytes);
  11079. break;
  11080. }
  11081. default: {
  11082. let keydata = keyBytes.subarray(0, 16);
  11083. if (keydata.length !== 16) {
  11084. const padded = new Uint8Array(16);
  11085. padded.set(keydata, 16 - keydata.length);
  11086. keydata = padded;
  11087. }
  11088. this.keyId = keydata;
  11089. break;
  11090. }
  11091. }
  11092. }
  11093. if (!this.keyId || this.keyId.byteLength !== 16) {
  11094. let keyId = keyUriToKeyIdMap[this.uri];
  11095. if (!keyId) {
  11096. const val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;
  11097. keyId = new Uint8Array(16);
  11098. const dv = new DataView(keyId.buffer, 12, 4);
  11099. dv.setUint32(0, val);
  11100. keyUriToKeyIdMap[this.uri] = keyId;
  11101. }
  11102. this.keyId = keyId;
  11103. }
  11104. return this;
  11105. }
  11106. }
  11107. function createInitializationVector(segmentNumber) {
  11108. const uint8View = new Uint8Array(16);
  11109. for (let i2 = 12; i2 < 16; i2++) {
  11110. uint8View[i2] = segmentNumber >> 8 * (15 - i2) & 255;
  11111. }
  11112. return uint8View;
  11113. }
  11114. 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;
  11115. const MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  11116. const IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m;
  11117. const LEVEL_PLAYLIST_REGEX_FAST = new RegExp([
  11118. /#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  11119. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  11120. /(?!#) *(\S[^\r\n]*)/.source,
  11121. // segment URI, group 3 => the URI (note newline is not eaten)
  11122. /#.*/.source
  11123. // All other non-segment oriented tags will match with all groups empty
  11124. ].join("|"), "g");
  11125. 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("|"));
  11126. class M3U8Parser {
  11127. static findGroup(groups, mediaGroupId) {
  11128. for (let i2 = 0; i2 < groups.length; i2++) {
  11129. const group = groups[i2];
  11130. if (group.id === mediaGroupId) {
  11131. return group;
  11132. }
  11133. }
  11134. }
  11135. static resolve(url2, baseUrl) {
  11136. return urlToolkitExports.buildAbsoluteURL(baseUrl, url2, {
  11137. alwaysNormalize: true
  11138. });
  11139. }
  11140. static isMediaPlaylist(str) {
  11141. return IS_MEDIA_PLAYLIST.test(str);
  11142. }
  11143. static parseMasterPlaylist(string2, baseurl) {
  11144. const hasVariableRefs = hasVariableReferences(string2);
  11145. const parsed = {
  11146. contentSteering: null,
  11147. levels: [],
  11148. playlistParsingError: null,
  11149. sessionData: null,
  11150. sessionKeys: null,
  11151. startTimeOffset: null,
  11152. variableList: null,
  11153. hasVariableRefs
  11154. };
  11155. const levelsWithKnownCodecs = [];
  11156. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  11157. let result;
  11158. while ((result = MASTER_PLAYLIST_REGEX.exec(string2)) != null) {
  11159. if (result[1]) {
  11160. var _level$unknownCodecs;
  11161. const attrs = new AttrList(result[1], parsed);
  11162. const uri = substituteVariables(parsed, result[2]);
  11163. const level = {
  11164. attrs,
  11165. bitrate: attrs.decimalInteger("BANDWIDTH") || attrs.decimalInteger("AVERAGE-BANDWIDTH"),
  11166. name: attrs.NAME,
  11167. url: M3U8Parser.resolve(uri, baseurl)
  11168. };
  11169. const resolution = attrs.decimalResolution("RESOLUTION");
  11170. if (resolution) {
  11171. level.width = resolution.width;
  11172. level.height = resolution.height;
  11173. }
  11174. setCodecs(attrs.CODECS, level);
  11175. const supplementalCodecs = attrs["SUPPLEMENTAL-CODECS"];
  11176. if (supplementalCodecs) {
  11177. level.supplemental = {};
  11178. setCodecs(supplementalCodecs, level.supplemental);
  11179. }
  11180. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  11181. levelsWithKnownCodecs.push(level);
  11182. }
  11183. parsed.levels.push(level);
  11184. } else if (result[3]) {
  11185. const tag = result[3];
  11186. const attributes = result[4];
  11187. switch (tag) {
  11188. case "SESSION-DATA": {
  11189. const sessionAttrs = new AttrList(attributes, parsed);
  11190. const dataId = sessionAttrs["DATA-ID"];
  11191. if (dataId) {
  11192. if (parsed.sessionData === null) {
  11193. parsed.sessionData = {};
  11194. }
  11195. parsed.sessionData[dataId] = sessionAttrs;
  11196. }
  11197. break;
  11198. }
  11199. case "SESSION-KEY": {
  11200. const sessionKey = parseKey(attributes, baseurl, parsed);
  11201. if (sessionKey.encrypted && sessionKey.isSupported()) {
  11202. if (parsed.sessionKeys === null) {
  11203. parsed.sessionKeys = [];
  11204. }
  11205. parsed.sessionKeys.push(sessionKey);
  11206. } else {
  11207. logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`);
  11208. }
  11209. break;
  11210. }
  11211. case "DEFINE": {
  11212. {
  11213. const variableAttributes = new AttrList(attributes, parsed);
  11214. addVariableDefinition(parsed, variableAttributes, baseurl);
  11215. }
  11216. break;
  11217. }
  11218. case "CONTENT-STEERING": {
  11219. const contentSteeringAttributes = new AttrList(attributes, parsed);
  11220. parsed.contentSteering = {
  11221. uri: M3U8Parser.resolve(contentSteeringAttributes["SERVER-URI"], baseurl),
  11222. pathwayId: contentSteeringAttributes["PATHWAY-ID"] || "."
  11223. };
  11224. break;
  11225. }
  11226. case "START": {
  11227. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  11228. break;
  11229. }
  11230. }
  11231. }
  11232. }
  11233. const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  11234. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  11235. if (parsed.levels.length === 0) {
  11236. parsed.playlistParsingError = new Error("no levels found in manifest");
  11237. }
  11238. return parsed;
  11239. }
  11240. static parseMasterPlaylistMedia(string2, baseurl, parsed) {
  11241. let result;
  11242. const results = {};
  11243. const levels = parsed.levels;
  11244. const groupsByType = {
  11245. AUDIO: levels.map((level) => ({
  11246. id: level.attrs.AUDIO,
  11247. audioCodec: level.audioCodec
  11248. })),
  11249. SUBTITLES: levels.map((level) => ({
  11250. id: level.attrs.SUBTITLES,
  11251. textCodec: level.textCodec
  11252. })),
  11253. "CLOSED-CAPTIONS": []
  11254. };
  11255. let id = 0;
  11256. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  11257. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string2)) !== null) {
  11258. const attrs = new AttrList(result[1], parsed);
  11259. const type = attrs.TYPE;
  11260. if (type) {
  11261. const groups = groupsByType[type];
  11262. const medias = results[type] || [];
  11263. results[type] = medias;
  11264. const lang = attrs.LANGUAGE;
  11265. const assocLang = attrs["ASSOC-LANGUAGE"];
  11266. const channels = attrs.CHANNELS;
  11267. const characteristics = attrs.CHARACTERISTICS;
  11268. const instreamId = attrs["INSTREAM-ID"];
  11269. const media = {
  11270. attrs,
  11271. bitrate: 0,
  11272. id: id++,
  11273. groupId: attrs["GROUP-ID"] || "",
  11274. name: attrs.NAME || lang || "",
  11275. type,
  11276. default: attrs.bool("DEFAULT"),
  11277. autoselect: attrs.bool("AUTOSELECT"),
  11278. forced: attrs.bool("FORCED"),
  11279. lang,
  11280. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ""
  11281. };
  11282. if (assocLang) {
  11283. media.assocLang = assocLang;
  11284. }
  11285. if (channels) {
  11286. media.channels = channels;
  11287. }
  11288. if (characteristics) {
  11289. media.characteristics = characteristics;
  11290. }
  11291. if (instreamId) {
  11292. media.instreamId = instreamId;
  11293. }
  11294. if (groups != null && groups.length) {
  11295. const groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  11296. assignCodec(media, groupCodec, "audioCodec");
  11297. assignCodec(media, groupCodec, "textCodec");
  11298. }
  11299. medias.push(media);
  11300. }
  11301. }
  11302. return results;
  11303. }
  11304. static parseLevelPlaylist(string2, baseurl, id, type, levelUrlId, multivariantVariableList) {
  11305. var _LEVEL_PLAYLIST_REGEX;
  11306. const base = {
  11307. url: baseurl
  11308. };
  11309. const level = new LevelDetails(baseurl);
  11310. const fragments = level.fragments;
  11311. const programDateTimes = [];
  11312. let currentInitSegment = null;
  11313. let currentSN = 0;
  11314. let currentPart = 0;
  11315. let totalduration = 0;
  11316. let discontinuityCounter = 0;
  11317. let currentBitrate = 0;
  11318. let prevFrag = null;
  11319. let frag = new Fragment(type, base);
  11320. let result;
  11321. let i2;
  11322. let levelkeys;
  11323. let firstPdtIndex = -1;
  11324. let createNextFrag = false;
  11325. let nextByteRange = null;
  11326. let serverControlAttrs;
  11327. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  11328. level.m3u8 = string2;
  11329. level.hasVariableRefs = hasVariableReferences(string2);
  11330. if (((_LEVEL_PLAYLIST_REGEX = LEVEL_PLAYLIST_REGEX_FAST.exec(string2)) == null ? void 0 : _LEVEL_PLAYLIST_REGEX[0]) !== "#EXTM3U") {
  11331. level.playlistParsingError = new Error("Missing format identifier #EXTM3U");
  11332. return level;
  11333. }
  11334. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string2)) !== null) {
  11335. if (createNextFrag) {
  11336. createNextFrag = false;
  11337. frag = new Fragment(type, base);
  11338. frag.playlistOffset = totalduration;
  11339. frag.start = totalduration;
  11340. frag.sn = currentSN;
  11341. frag.cc = discontinuityCounter;
  11342. if (currentBitrate) {
  11343. frag.bitrate = currentBitrate;
  11344. }
  11345. frag.level = id;
  11346. if (currentInitSegment) {
  11347. frag.initSegment = currentInitSegment;
  11348. if (currentInitSegment.rawProgramDateTime) {
  11349. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  11350. currentInitSegment.rawProgramDateTime = null;
  11351. }
  11352. if (nextByteRange) {
  11353. frag.setByteRange(nextByteRange);
  11354. nextByteRange = null;
  11355. }
  11356. }
  11357. }
  11358. const duration = result[1];
  11359. if (duration) {
  11360. frag.duration = parseFloat(duration);
  11361. const title = (" " + result[2]).slice(1);
  11362. frag.title = title || null;
  11363. frag.tagList.push(title ? ["INF", duration, title] : ["INF", duration]);
  11364. } else if (result[3]) {
  11365. if (isFiniteNumber(frag.duration)) {
  11366. frag.playlistOffset = totalduration;
  11367. frag.start = totalduration;
  11368. if (levelkeys) {
  11369. setFragLevelKeys(frag, levelkeys, level);
  11370. }
  11371. frag.sn = currentSN;
  11372. frag.level = id;
  11373. frag.cc = discontinuityCounter;
  11374. fragments.push(frag);
  11375. const uri = (" " + result[3]).slice(1);
  11376. frag.relurl = substituteVariables(level, uri);
  11377. assignProgramDateTime(frag, prevFrag, programDateTimes);
  11378. prevFrag = frag;
  11379. totalduration += frag.duration;
  11380. currentSN++;
  11381. currentPart = 0;
  11382. createNextFrag = true;
  11383. }
  11384. } else {
  11385. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  11386. if (!result) {
  11387. logger.warn("No matches on slow regex match for level playlist!");
  11388. continue;
  11389. }
  11390. for (i2 = 1; i2 < result.length; i2++) {
  11391. if (result[i2] !== void 0) {
  11392. break;
  11393. }
  11394. }
  11395. const tag = (" " + result[i2]).slice(1);
  11396. const value1 = (" " + result[i2 + 1]).slice(1);
  11397. const value2 = result[i2 + 2] ? (" " + result[i2 + 2]).slice(1) : null;
  11398. switch (tag) {
  11399. case "BYTERANGE":
  11400. if (prevFrag) {
  11401. frag.setByteRange(value1, prevFrag);
  11402. } else {
  11403. frag.setByteRange(value1);
  11404. }
  11405. break;
  11406. case "PROGRAM-DATE-TIME":
  11407. frag.rawProgramDateTime = value1;
  11408. frag.tagList.push(["PROGRAM-DATE-TIME", value1]);
  11409. if (firstPdtIndex === -1) {
  11410. firstPdtIndex = fragments.length;
  11411. }
  11412. break;
  11413. case "PLAYLIST-TYPE":
  11414. if (level.type) {
  11415. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  11416. }
  11417. level.type = value1.toUpperCase();
  11418. break;
  11419. case "MEDIA-SEQUENCE":
  11420. if (level.startSN !== 0) {
  11421. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  11422. } else if (fragments.length > 0) {
  11423. assignMustAppearBeforeSegmentsError(level, tag, result);
  11424. }
  11425. currentSN = level.startSN = parseInt(value1);
  11426. break;
  11427. case "SKIP": {
  11428. if (level.skippedSegments) {
  11429. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  11430. }
  11431. const skipAttrs = new AttrList(value1, level);
  11432. const skippedSegments = skipAttrs.decimalInteger("SKIPPED-SEGMENTS");
  11433. if (isFiniteNumber(skippedSegments)) {
  11434. level.skippedSegments += skippedSegments;
  11435. for (let _i = skippedSegments; _i--; ) {
  11436. fragments.push(null);
  11437. }
  11438. currentSN += skippedSegments;
  11439. }
  11440. const recentlyRemovedDateranges = skipAttrs.enumeratedString("RECENTLY-REMOVED-DATERANGES");
  11441. if (recentlyRemovedDateranges) {
  11442. level.recentlyRemovedDateranges = (level.recentlyRemovedDateranges || []).concat(recentlyRemovedDateranges.split(" "));
  11443. }
  11444. break;
  11445. }
  11446. case "TARGETDURATION":
  11447. if (level.targetduration !== 0) {
  11448. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  11449. }
  11450. level.targetduration = Math.max(parseInt(value1), 1);
  11451. break;
  11452. case "VERSION":
  11453. if (level.version !== null) {
  11454. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  11455. }
  11456. level.version = parseInt(value1);
  11457. break;
  11458. case "INDEPENDENT-SEGMENTS":
  11459. break;
  11460. case "ENDLIST":
  11461. if (!level.live) {
  11462. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  11463. }
  11464. level.live = false;
  11465. break;
  11466. case "#":
  11467. if (value1 || value2) {
  11468. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  11469. }
  11470. break;
  11471. case "DISCONTINUITY":
  11472. discontinuityCounter++;
  11473. frag.tagList.push(["DIS"]);
  11474. break;
  11475. case "GAP":
  11476. frag.gap = true;
  11477. frag.tagList.push([tag]);
  11478. break;
  11479. case "BITRATE":
  11480. frag.tagList.push([tag, value1]);
  11481. currentBitrate = parseInt(value1) * 1e3;
  11482. if (isFiniteNumber(currentBitrate)) {
  11483. frag.bitrate = currentBitrate;
  11484. } else {
  11485. currentBitrate = 0;
  11486. }
  11487. break;
  11488. case "DATERANGE": {
  11489. const dateRangeAttr = new AttrList(value1, level);
  11490. const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID], level.dateRangeTagCount);
  11491. level.dateRangeTagCount++;
  11492. if (dateRange.isValid || level.skippedSegments) {
  11493. level.dateRanges[dateRange.id] = dateRange;
  11494. } else {
  11495. logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`);
  11496. }
  11497. frag.tagList.push(["EXT-X-DATERANGE", value1]);
  11498. break;
  11499. }
  11500. case "DEFINE": {
  11501. {
  11502. const variableAttributes = new AttrList(value1, level);
  11503. if ("IMPORT" in variableAttributes) {
  11504. importVariableDefinition(level, variableAttributes, multivariantVariableList);
  11505. } else {
  11506. addVariableDefinition(level, variableAttributes, baseurl);
  11507. }
  11508. }
  11509. break;
  11510. }
  11511. case "DISCONTINUITY-SEQUENCE":
  11512. if (level.startCC !== 0) {
  11513. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  11514. } else if (fragments.length > 0) {
  11515. assignMustAppearBeforeSegmentsError(level, tag, result);
  11516. }
  11517. level.startCC = discontinuityCounter = parseInt(value1);
  11518. break;
  11519. case "KEY": {
  11520. const levelKey = parseKey(value1, baseurl, level);
  11521. if (levelKey.isSupported()) {
  11522. if (levelKey.method === "NONE") {
  11523. levelkeys = void 0;
  11524. break;
  11525. }
  11526. if (!levelkeys) {
  11527. levelkeys = {};
  11528. }
  11529. const currentKey = levelkeys[levelKey.keyFormat];
  11530. if (!(currentKey != null && currentKey.matches(levelKey))) {
  11531. if (currentKey) {
  11532. levelkeys = _extends({}, levelkeys);
  11533. }
  11534. levelkeys[levelKey.keyFormat] = levelKey;
  11535. }
  11536. } else {
  11537. logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${value1}"`);
  11538. }
  11539. break;
  11540. }
  11541. case "START":
  11542. level.startTimeOffset = parseStartTimeOffset(value1);
  11543. break;
  11544. case "MAP": {
  11545. const mapAttrs = new AttrList(value1, level);
  11546. if (frag.duration) {
  11547. const init = new Fragment(type, base);
  11548. setInitSegment(init, mapAttrs, id, levelkeys);
  11549. currentInitSegment = init;
  11550. frag.initSegment = currentInitSegment;
  11551. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  11552. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  11553. }
  11554. } else {
  11555. const end = frag.byteRangeEndOffset;
  11556. if (end) {
  11557. const start = frag.byteRangeStartOffset;
  11558. nextByteRange = `${end - start}@${start}`;
  11559. } else {
  11560. nextByteRange = null;
  11561. }
  11562. setInitSegment(frag, mapAttrs, id, levelkeys);
  11563. currentInitSegment = frag;
  11564. createNextFrag = true;
  11565. }
  11566. currentInitSegment.cc = discontinuityCounter;
  11567. break;
  11568. }
  11569. case "SERVER-CONTROL": {
  11570. if (serverControlAttrs) {
  11571. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  11572. }
  11573. serverControlAttrs = new AttrList(value1);
  11574. level.canBlockReload = serverControlAttrs.bool("CAN-BLOCK-RELOAD");
  11575. level.canSkipUntil = serverControlAttrs.optionalFloat("CAN-SKIP-UNTIL", 0);
  11576. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool("CAN-SKIP-DATERANGES");
  11577. level.partHoldBack = serverControlAttrs.optionalFloat("PART-HOLD-BACK", 0);
  11578. level.holdBack = serverControlAttrs.optionalFloat("HOLD-BACK", 0);
  11579. break;
  11580. }
  11581. case "PART-INF": {
  11582. if (level.partTarget) {
  11583. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  11584. }
  11585. const partInfAttrs = new AttrList(value1);
  11586. level.partTarget = partInfAttrs.decimalFloatingPoint("PART-TARGET");
  11587. break;
  11588. }
  11589. case "PART": {
  11590. let partList = level.partList;
  11591. if (!partList) {
  11592. partList = level.partList = [];
  11593. }
  11594. const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : void 0;
  11595. const index2 = currentPart++;
  11596. const partAttrs = new AttrList(value1, level);
  11597. const part = new Part(partAttrs, frag, base, index2, previousFragmentPart);
  11598. partList.push(part);
  11599. frag.duration += part.duration;
  11600. break;
  11601. }
  11602. case "PRELOAD-HINT": {
  11603. const preloadHintAttrs = new AttrList(value1, level);
  11604. level.preloadHint = preloadHintAttrs;
  11605. break;
  11606. }
  11607. case "RENDITION-REPORT": {
  11608. const renditionReportAttrs = new AttrList(value1, level);
  11609. level.renditionReports = level.renditionReports || [];
  11610. level.renditionReports.push(renditionReportAttrs);
  11611. break;
  11612. }
  11613. default:
  11614. logger.warn(`line parsed but not handled: ${result}`);
  11615. break;
  11616. }
  11617. }
  11618. }
  11619. if (prevFrag && !prevFrag.relurl) {
  11620. fragments.pop();
  11621. totalduration -= prevFrag.duration;
  11622. if (level.partList) {
  11623. level.fragmentHint = prevFrag;
  11624. }
  11625. } else if (level.partList) {
  11626. assignProgramDateTime(frag, prevFrag, programDateTimes);
  11627. frag.cc = discontinuityCounter;
  11628. level.fragmentHint = frag;
  11629. if (levelkeys) {
  11630. setFragLevelKeys(frag, levelkeys, level);
  11631. }
  11632. }
  11633. if (!level.targetduration) {
  11634. level.playlistParsingError = new Error(`#EXT-X-TARGETDURATION is required`);
  11635. }
  11636. const fragmentLength = fragments.length;
  11637. const firstFragment = fragments[0];
  11638. const lastFragment = fragments[fragmentLength - 1];
  11639. totalduration += level.skippedSegments * level.targetduration;
  11640. if (totalduration > 0 && fragmentLength && lastFragment) {
  11641. level.averagetargetduration = totalduration / fragmentLength;
  11642. const lastSn = lastFragment.sn;
  11643. level.endSN = lastSn !== "initSegment" ? lastSn : 0;
  11644. if (!level.live) {
  11645. lastFragment.endList = true;
  11646. }
  11647. if (firstFragment && level.startCC === void 0) {
  11648. level.startCC = firstFragment.cc;
  11649. }
  11650. if (firstPdtIndex > 0) {
  11651. backfillProgramDateTimes(fragments, firstPdtIndex);
  11652. if (firstFragment) {
  11653. programDateTimes.unshift(firstFragment);
  11654. }
  11655. }
  11656. } else {
  11657. level.endSN = 0;
  11658. level.startCC = 0;
  11659. }
  11660. if (level.fragmentHint) {
  11661. totalduration += level.fragmentHint.duration;
  11662. }
  11663. level.totalduration = totalduration;
  11664. if (programDateTimes.length && level.dateRangeTagCount && firstFragment) {
  11665. mapDateRanges(programDateTimes, level);
  11666. }
  11667. level.endCC = discontinuityCounter;
  11668. return level;
  11669. }
  11670. }
  11671. function mapDateRanges(programDateTimes, details) {
  11672. const programDateTimeCount = programDateTimes.length;
  11673. if (!programDateTimeCount) {
  11674. return;
  11675. }
  11676. const lastProgramDateTime = programDateTimes[programDateTimeCount - 1];
  11677. const playlistEnd = details.live ? Infinity : details.totalduration;
  11678. const dateRangeIds = Object.keys(details.dateRanges);
  11679. for (let i2 = dateRangeIds.length; i2--; ) {
  11680. const dateRange = details.dateRanges[dateRangeIds[i2]];
  11681. const startDateTime = dateRange.startDate.getTime();
  11682. dateRange.tagAnchor = lastProgramDateTime.ref;
  11683. for (let j2 = programDateTimeCount; j2--; ) {
  11684. const fragIndex = findFragmentWithStartDate(details, startDateTime, programDateTimes, j2, playlistEnd);
  11685. if (fragIndex !== -1) {
  11686. dateRange.tagAnchor = details.fragments[fragIndex].ref;
  11687. break;
  11688. }
  11689. }
  11690. }
  11691. }
  11692. function findFragmentWithStartDate(details, startDateTime, programDateTimes, index2, endTime) {
  11693. const pdtFragment = programDateTimes[index2];
  11694. if (pdtFragment) {
  11695. const pdtStart = pdtFragment.programDateTime;
  11696. if (startDateTime >= pdtStart || index2 === 0) {
  11697. var _programDateTimes;
  11698. const durationBetweenPdt = (((_programDateTimes = programDateTimes[index2 + 1]) == null ? void 0 : _programDateTimes.start) || endTime) - pdtFragment.start;
  11699. if (startDateTime <= pdtStart + durationBetweenPdt * 1e3) {
  11700. const startIndex = programDateTimes[index2].sn - details.startSN;
  11701. const fragments = details.fragments;
  11702. if (fragments.length > programDateTimes.length) {
  11703. const endSegment = programDateTimes[index2 + 1] || fragments[fragments.length - 1];
  11704. const endIndex = endSegment.sn - details.startSN;
  11705. for (let i2 = endIndex; i2 > startIndex; i2--) {
  11706. const fragStartDateTime = fragments[i2].programDateTime;
  11707. if (startDateTime >= fragStartDateTime && startDateTime < fragStartDateTime + fragments[i2].duration * 1e3) {
  11708. return i2;
  11709. }
  11710. }
  11711. }
  11712. return startIndex;
  11713. }
  11714. }
  11715. }
  11716. return -1;
  11717. }
  11718. function parseKey(keyTagAttributes, baseurl, parsed) {
  11719. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  11720. const keyAttrs = new AttrList(keyTagAttributes, parsed);
  11721. const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : "";
  11722. const decrypturi = keyAttrs.URI;
  11723. const decryptiv = keyAttrs.hexadecimalInteger("IV");
  11724. const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  11725. const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : "identity";
  11726. if (decrypturi && keyAttrs.IV && !decryptiv) {
  11727. logger.error(`Invalid IV: ${keyAttrs.IV}`);
  11728. }
  11729. const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : "";
  11730. const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : "1").split("/").map(Number).filter(Number.isFinite);
  11731. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv, keyAttrs.KEYID);
  11732. }
  11733. function parseStartTimeOffset(startAttributes) {
  11734. const startAttrs = new AttrList(startAttributes);
  11735. const startTimeOffset = startAttrs.decimalFloatingPoint("TIME-OFFSET");
  11736. if (isFiniteNumber(startTimeOffset)) {
  11737. return startTimeOffset;
  11738. }
  11739. return null;
  11740. }
  11741. function setCodecs(codecsAttributeValue, level) {
  11742. let codecs = (codecsAttributeValue || "").split(/[ ,]+/).filter((c2) => c2);
  11743. ["video", "audio", "text"].forEach((type) => {
  11744. const filtered = codecs.filter((codec) => isCodecType(codec, type));
  11745. if (filtered.length) {
  11746. level[`${type}Codec`] = filtered.map((c2) => c2.split("/")[0]).join(",");
  11747. codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);
  11748. }
  11749. });
  11750. level.unknownCodecs = codecs;
  11751. }
  11752. function assignCodec(media, groupItem, codecProperty) {
  11753. const codecValue = groupItem[codecProperty];
  11754. if (codecValue) {
  11755. media[codecProperty] = codecValue;
  11756. }
  11757. }
  11758. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  11759. let fragPrev = fragments[firstPdtIndex];
  11760. for (let i2 = firstPdtIndex; i2--; ) {
  11761. const frag = fragments[i2];
  11762. if (!frag) {
  11763. return;
  11764. }
  11765. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1e3;
  11766. fragPrev = frag;
  11767. }
  11768. }
  11769. function assignProgramDateTime(frag, prevFrag, programDateTimes) {
  11770. if (frag.rawProgramDateTime) {
  11771. programDateTimes.push(frag);
  11772. } else if (prevFrag != null && prevFrag.programDateTime) {
  11773. frag.programDateTime = prevFrag.endProgramDateTime;
  11774. }
  11775. }
  11776. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  11777. frag.relurl = mapAttrs.URI;
  11778. if (mapAttrs.BYTERANGE) {
  11779. frag.setByteRange(mapAttrs.BYTERANGE);
  11780. }
  11781. frag.level = id;
  11782. frag.sn = "initSegment";
  11783. if (levelkeys) {
  11784. frag.levelkeys = levelkeys;
  11785. }
  11786. frag.initSegment = null;
  11787. }
  11788. function setFragLevelKeys(frag, levelkeys, level) {
  11789. frag.levelkeys = levelkeys;
  11790. const {
  11791. encryptedFragments
  11792. } = level;
  11793. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some((format2) => levelkeys[format2].isCommonEncryption)) {
  11794. encryptedFragments.push(frag);
  11795. }
  11796. }
  11797. function assignMultipleMediaPlaylistTagOccuranceError(level, tag, result) {
  11798. level.playlistParsingError = new Error(`#EXT-X-${tag} must not appear more than once (${result[0]})`);
  11799. }
  11800. function assignMustAppearBeforeSegmentsError(level, tag, result) {
  11801. level.playlistParsingError = new Error(`#EXT-X-${tag} must appear before the first Media Segment (${result[0]})`);
  11802. }
  11803. function updateFromToPTS(fragFrom, fragTo) {
  11804. const fragToPTS = fragTo.startPTS;
  11805. if (isFiniteNumber(fragToPTS)) {
  11806. let duration = 0;
  11807. let frag;
  11808. if (fragTo.sn > fragFrom.sn) {
  11809. duration = fragToPTS - fragFrom.start;
  11810. frag = fragFrom;
  11811. } else {
  11812. duration = fragFrom.start - fragToPTS;
  11813. frag = fragTo;
  11814. }
  11815. if (frag.duration !== duration) {
  11816. frag.setDuration(duration);
  11817. }
  11818. } else if (fragTo.sn > fragFrom.sn) {
  11819. const contiguous = fragFrom.cc === fragTo.cc;
  11820. if (contiguous && fragFrom.minEndPTS) {
  11821. fragTo.setStart(fragFrom.start + (fragFrom.minEndPTS - fragFrom.start));
  11822. } else {
  11823. fragTo.setStart(fragFrom.start + fragFrom.duration);
  11824. }
  11825. } else {
  11826. fragTo.setStart(Math.max(fragFrom.start - fragTo.duration, 0));
  11827. }
  11828. }
  11829. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  11830. const parsedMediaDuration = endPTS - startPTS;
  11831. if (parsedMediaDuration <= 0) {
  11832. logger.warn("Fragment should have a positive duration", frag);
  11833. endPTS = startPTS + frag.duration;
  11834. endDTS = startDTS + frag.duration;
  11835. }
  11836. let maxStartPTS = startPTS;
  11837. let minEndPTS = endPTS;
  11838. const fragStartPts = frag.startPTS;
  11839. const fragEndPts = frag.endPTS;
  11840. if (isFiniteNumber(fragStartPts)) {
  11841. const deltaPTS = Math.abs(fragStartPts - startPTS);
  11842. if (!isFiniteNumber(frag.deltaPTS)) {
  11843. frag.deltaPTS = deltaPTS;
  11844. } else {
  11845. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  11846. }
  11847. maxStartPTS = Math.max(startPTS, fragStartPts);
  11848. startPTS = Math.min(startPTS, fragStartPts);
  11849. startDTS = Math.min(startDTS, frag.startDTS);
  11850. minEndPTS = Math.min(endPTS, fragEndPts);
  11851. endPTS = Math.max(endPTS, fragEndPts);
  11852. endDTS = Math.max(endDTS, frag.endDTS);
  11853. }
  11854. const drift = startPTS - frag.start;
  11855. if (frag.start !== 0) {
  11856. frag.setStart(startPTS);
  11857. }
  11858. frag.setDuration(endPTS - frag.start);
  11859. frag.startPTS = startPTS;
  11860. frag.maxStartPTS = maxStartPTS;
  11861. frag.startDTS = startDTS;
  11862. frag.endPTS = endPTS;
  11863. frag.minEndPTS = minEndPTS;
  11864. frag.endDTS = endDTS;
  11865. const sn = frag.sn;
  11866. if (!details || sn < details.startSN || sn > details.endSN) {
  11867. return 0;
  11868. }
  11869. let i2;
  11870. const fragIdx = sn - details.startSN;
  11871. const fragments = details.fragments;
  11872. fragments[fragIdx] = frag;
  11873. for (i2 = fragIdx; i2 > 0; i2--) {
  11874. updateFromToPTS(fragments[i2], fragments[i2 - 1]);
  11875. }
  11876. for (i2 = fragIdx; i2 < fragments.length - 1; i2++) {
  11877. updateFromToPTS(fragments[i2], fragments[i2 + 1]);
  11878. }
  11879. if (details.fragmentHint) {
  11880. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  11881. }
  11882. details.PTSKnown = details.alignedSliding = true;
  11883. return drift;
  11884. }
  11885. function mergeDetails(oldDetails, newDetails) {
  11886. if (oldDetails === newDetails) {
  11887. return;
  11888. }
  11889. let currentInitSegment = null;
  11890. const oldFragments = oldDetails.fragments;
  11891. for (let i2 = oldFragments.length - 1; i2 >= 0; i2--) {
  11892. const oldInit = oldFragments[i2].initSegment;
  11893. if (oldInit) {
  11894. currentInitSegment = oldInit;
  11895. break;
  11896. }
  11897. }
  11898. if (oldDetails.fragmentHint) {
  11899. delete oldDetails.fragmentHint.endPTS;
  11900. }
  11901. let PTSFrag;
  11902. mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag, newFragIndex, newFragments2) => {
  11903. if ((!newDetails.startCC || newDetails.skippedSegments) && newFrag.cc !== oldFrag.cc) {
  11904. const ccOffset = oldFrag.cc - newFrag.cc;
  11905. for (let i2 = newFragIndex; i2 < newFragments2.length; i2++) {
  11906. newFragments2[i2].cc += ccOffset;
  11907. }
  11908. newDetails.endCC = newFragments2[newFragments2.length - 1].cc;
  11909. }
  11910. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  11911. newFrag.setStart(newFrag.startPTS = oldFrag.startPTS);
  11912. newFrag.startDTS = oldFrag.startDTS;
  11913. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  11914. newFrag.endPTS = oldFrag.endPTS;
  11915. newFrag.endDTS = oldFrag.endDTS;
  11916. newFrag.minEndPTS = oldFrag.minEndPTS;
  11917. newFrag.setDuration(oldFrag.endPTS - oldFrag.startPTS);
  11918. if (newFrag.duration) {
  11919. PTSFrag = newFrag;
  11920. }
  11921. newDetails.PTSKnown = newDetails.alignedSliding = true;
  11922. }
  11923. if (oldFrag.hasStreams) {
  11924. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  11925. }
  11926. newFrag.loader = oldFrag.loader;
  11927. if (oldFrag.hasStats) {
  11928. newFrag.stats = oldFrag.stats;
  11929. }
  11930. if (oldFrag.initSegment) {
  11931. newFrag.initSegment = oldFrag.initSegment;
  11932. currentInitSegment = oldFrag.initSegment;
  11933. }
  11934. });
  11935. const newFragments = newDetails.fragments;
  11936. const fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments;
  11937. if (currentInitSegment) {
  11938. fragmentsToCheck.forEach((frag) => {
  11939. var _currentInitSegment;
  11940. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  11941. frag.initSegment = currentInitSegment;
  11942. }
  11943. });
  11944. }
  11945. if (newDetails.skippedSegments) {
  11946. newDetails.deltaUpdateFailed = newFragments.some((frag) => !frag);
  11947. if (newDetails.deltaUpdateFailed) {
  11948. logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");
  11949. for (let i2 = newDetails.skippedSegments; i2--; ) {
  11950. newFragments.shift();
  11951. }
  11952. newDetails.startSN = newFragments[0].sn;
  11953. } else {
  11954. if (newDetails.canSkipDateRanges) {
  11955. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails);
  11956. }
  11957. const programDateTimes = oldDetails.fragments.filter((frag) => frag.rawProgramDateTime);
  11958. if (oldDetails.hasProgramDateTime && !newDetails.hasProgramDateTime) {
  11959. for (let i2 = 1; i2 < fragmentsToCheck.length; i2++) {
  11960. if (fragmentsToCheck[i2].programDateTime === null) {
  11961. assignProgramDateTime(fragmentsToCheck[i2], fragmentsToCheck[i2 - 1], programDateTimes);
  11962. }
  11963. }
  11964. }
  11965. mapDateRanges(programDateTimes, newDetails);
  11966. }
  11967. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  11968. }
  11969. if (!newDetails.startCC) {
  11970. var _fragPriorToNewStart$;
  11971. const fragPriorToNewStart = getFragmentWithSN(oldDetails, newDetails.startSN - 1);
  11972. newDetails.startCC = (_fragPriorToNewStart$ = fragPriorToNewStart == null ? void 0 : fragPriorToNewStart.cc) != null ? _fragPriorToNewStart$ : newFragments[0].cc;
  11973. }
  11974. mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {
  11975. newPart.elementaryStreams = oldPart.elementaryStreams;
  11976. newPart.stats = oldPart.stats;
  11977. });
  11978. if (PTSFrag) {
  11979. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  11980. } else {
  11981. adjustSliding(oldDetails, newDetails);
  11982. }
  11983. if (newFragments.length) {
  11984. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  11985. }
  11986. newDetails.driftStartTime = oldDetails.driftStartTime;
  11987. newDetails.driftStart = oldDetails.driftStart;
  11988. const advancedDateTime = newDetails.advancedDateTime;
  11989. if (newDetails.advanced && advancedDateTime) {
  11990. const edge = newDetails.edge;
  11991. if (!newDetails.driftStart) {
  11992. newDetails.driftStartTime = advancedDateTime;
  11993. newDetails.driftStart = edge;
  11994. }
  11995. newDetails.driftEndTime = advancedDateTime;
  11996. newDetails.driftEnd = edge;
  11997. } else {
  11998. newDetails.driftEndTime = oldDetails.driftEndTime;
  11999. newDetails.driftEnd = oldDetails.driftEnd;
  12000. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  12001. }
  12002. if (newDetails.requestScheduled === -1) {
  12003. newDetails.requestScheduled = oldDetails.requestScheduled;
  12004. }
  12005. }
  12006. function mergeDateRanges(oldDateRanges, newDetails) {
  12007. const {
  12008. dateRanges: deltaDateRanges,
  12009. recentlyRemovedDateranges
  12010. } = newDetails;
  12011. const dateRanges = _extends({}, oldDateRanges);
  12012. if (recentlyRemovedDateranges) {
  12013. recentlyRemovedDateranges.forEach((id) => {
  12014. delete dateRanges[id];
  12015. });
  12016. }
  12017. const mergeIds = Object.keys(dateRanges);
  12018. const mergeCount = mergeIds.length;
  12019. if (mergeCount) {
  12020. Object.keys(deltaDateRanges).forEach((id) => {
  12021. const mergedDateRange = dateRanges[id];
  12022. const dateRange = new DateRange(deltaDateRanges[id].attr, mergedDateRange);
  12023. if (dateRange.isValid) {
  12024. dateRanges[id] = dateRange;
  12025. if (!mergedDateRange) {
  12026. dateRange.tagOrder += mergeCount;
  12027. }
  12028. } else {
  12029. logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${stringify(deltaDateRanges[id].attr)}"`);
  12030. }
  12031. });
  12032. }
  12033. return dateRanges;
  12034. }
  12035. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  12036. if (oldParts && newParts) {
  12037. let delta = 0;
  12038. for (let i2 = 0, len = oldParts.length; i2 <= len; i2++) {
  12039. const oldPart = oldParts[i2];
  12040. const newPart = newParts[i2 + delta];
  12041. if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {
  12042. intersectionFn(oldPart, newPart);
  12043. } else {
  12044. delta--;
  12045. }
  12046. }
  12047. }
  12048. }
  12049. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  12050. const skippedSegments = newDetails.skippedSegments;
  12051. const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  12052. const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  12053. const delta = newDetails.startSN - oldDetails.startSN;
  12054. const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  12055. const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  12056. for (let i2 = start; i2 <= end; i2++) {
  12057. const oldFrag = oldFrags[delta + i2];
  12058. let newFrag = newFrags[i2];
  12059. if (skippedSegments && !newFrag && oldFrag) {
  12060. newFrag = newDetails.fragments[i2] = oldFrag;
  12061. }
  12062. if (oldFrag && newFrag) {
  12063. intersectionFn(oldFrag, newFrag, i2, newFrags);
  12064. if (oldFrag.url && oldFrag.url !== newFrag.url) {
  12065. newDetails.playlistParsingError = getSequenceError(`media sequence mismatch ${newFrag.sn}:`, oldDetails, newDetails, oldFrag, newFrag);
  12066. return;
  12067. } else if (oldFrag.cc !== newFrag.cc) {
  12068. newDetails.playlistParsingError = getSequenceError(`discontinuity sequence mismatch (${oldFrag.cc}!=${newFrag.cc})`, oldDetails, newDetails, oldFrag, newFrag);
  12069. return;
  12070. }
  12071. }
  12072. }
  12073. }
  12074. function getSequenceError(message, oldDetails, newDetails, oldFrag, newFrag) {
  12075. return new Error(`${message} ${newFrag.url}
  12076. Playlist starting @${oldDetails.startSN}
  12077. ${oldDetails.m3u8}
  12078. Playlist starting @${newDetails.startSN}
  12079. ${newDetails.m3u8}`);
  12080. }
  12081. function adjustSliding(oldDetails, newDetails, matchingStableVariantOrRendition = true) {
  12082. const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  12083. const oldFragments = oldDetails.fragments;
  12084. const advancedOrStable = delta >= 0;
  12085. let sliding = 0;
  12086. if (advancedOrStable && delta < oldFragments.length) {
  12087. sliding = oldFragments[delta].start;
  12088. } else if (advancedOrStable && newDetails.startSN === oldDetails.endSN + 1) {
  12089. sliding = oldDetails.fragmentEnd;
  12090. } else if (advancedOrStable && matchingStableVariantOrRendition) {
  12091. sliding = oldDetails.fragmentStart + delta * newDetails.levelTargetDuration;
  12092. } else if (!newDetails.skippedSegments && newDetails.fragmentStart === 0) {
  12093. sliding = oldDetails.fragmentStart;
  12094. } else {
  12095. return;
  12096. }
  12097. addSliding(newDetails, sliding);
  12098. }
  12099. function addSliding(details, sliding) {
  12100. if (sliding) {
  12101. const fragments = details.fragments;
  12102. for (let i2 = details.skippedSegments; i2 < fragments.length; i2++) {
  12103. fragments[i2].addStart(sliding);
  12104. }
  12105. if (details.fragmentHint) {
  12106. details.fragmentHint.addStart(sliding);
  12107. }
  12108. }
  12109. }
  12110. function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {
  12111. let reloadInterval = 1e3 * newDetails.targetduration;
  12112. if (newDetails.updated) {
  12113. const fragments = newDetails.fragments;
  12114. const liveEdgeMaxTargetDurations = 4;
  12115. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  12116. const lastSegmentDuration = fragments[fragments.length - 1].duration * 1e3;
  12117. if (lastSegmentDuration < reloadInterval) {
  12118. reloadInterval = lastSegmentDuration;
  12119. }
  12120. }
  12121. } else {
  12122. reloadInterval /= 2;
  12123. }
  12124. return Math.round(reloadInterval);
  12125. }
  12126. function getFragmentWithSN(details, sn, fragCurrent) {
  12127. if (!details) {
  12128. return null;
  12129. }
  12130. let fragment = details.fragments[sn - details.startSN];
  12131. if (fragment) {
  12132. return fragment;
  12133. }
  12134. fragment = details.fragmentHint;
  12135. if (fragment && fragment.sn === sn) {
  12136. return fragment;
  12137. }
  12138. if (sn < details.startSN && fragCurrent && fragCurrent.sn === sn) {
  12139. return fragCurrent;
  12140. }
  12141. return null;
  12142. }
  12143. function getPartWith(details, sn, partIndex) {
  12144. if (!details) {
  12145. return null;
  12146. }
  12147. return findPart(details.partList, sn, partIndex);
  12148. }
  12149. function findPart(partList, sn, partIndex) {
  12150. if (partList) {
  12151. for (let i2 = partList.length; i2--; ) {
  12152. const part = partList[i2];
  12153. if (part.index === partIndex && part.fragment.sn === sn) {
  12154. return part;
  12155. }
  12156. }
  12157. }
  12158. return null;
  12159. }
  12160. function reassignFragmentLevelIndexes(levels) {
  12161. levels.forEach((level, index2) => {
  12162. var _level$details;
  12163. (_level$details = level.details) == null ? void 0 : _level$details.fragments.forEach((fragment) => {
  12164. fragment.level = index2;
  12165. if (fragment.initSegment) {
  12166. fragment.initSegment.level = index2;
  12167. }
  12168. });
  12169. });
  12170. }
  12171. function findFirstFragWithCC(fragments, cc) {
  12172. for (let i2 = 0, len = fragments.length; i2 < len; i2++) {
  12173. var _fragments$i;
  12174. if (((_fragments$i = fragments[i2]) == null ? void 0 : _fragments$i.cc) === cc) {
  12175. return fragments[i2];
  12176. }
  12177. }
  12178. return null;
  12179. }
  12180. function shouldAlignOnDiscontinuities(refDetails, details) {
  12181. if (refDetails) {
  12182. if (details.startCC < refDetails.endCC && details.endCC > refDetails.startCC) {
  12183. return true;
  12184. }
  12185. }
  12186. return false;
  12187. }
  12188. function adjustFragmentStart(frag, sliding) {
  12189. if (frag) {
  12190. const start = frag.start + sliding;
  12191. frag.start = frag.startPTS = start;
  12192. frag.endPTS = start + frag.duration;
  12193. }
  12194. }
  12195. function adjustSlidingStart(sliding, details) {
  12196. const fragments = details.fragments;
  12197. for (let i2 = 0, len = fragments.length; i2 < len; i2++) {
  12198. adjustFragmentStart(fragments[i2], sliding);
  12199. }
  12200. if (details.fragmentHint) {
  12201. adjustFragmentStart(details.fragmentHint, sliding);
  12202. }
  12203. details.alignedSliding = true;
  12204. }
  12205. function alignStream(switchDetails, details) {
  12206. if (!switchDetails) {
  12207. return;
  12208. }
  12209. alignDiscontinuities(details, switchDetails);
  12210. if (!details.alignedSliding && switchDetails) {
  12211. alignMediaPlaylistByPDT(details, switchDetails);
  12212. }
  12213. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  12214. adjustSliding(switchDetails, details, false);
  12215. }
  12216. }
  12217. function alignDiscontinuities(details, refDetails) {
  12218. if (!shouldAlignOnDiscontinuities(refDetails, details)) {
  12219. return;
  12220. }
  12221. const targetCC = Math.min(refDetails.endCC, details.endCC);
  12222. const refFrag = findFirstFragWithCC(refDetails.fragments, targetCC);
  12223. const frag = findFirstFragWithCC(details.fragments, targetCC);
  12224. if (!refFrag || !frag) {
  12225. return;
  12226. }
  12227. logger.log(`Aligning playlist at start of dicontinuity sequence ${targetCC}`);
  12228. const delta = refFrag.start - frag.start;
  12229. adjustSlidingStart(delta, details);
  12230. }
  12231. function alignMediaPlaylistByPDT(details, refDetails) {
  12232. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  12233. return;
  12234. }
  12235. const fragments = details.fragments;
  12236. const refFragments = refDetails.fragments;
  12237. if (!fragments.length || !refFragments.length) {
  12238. return;
  12239. }
  12240. let refFrag;
  12241. let frag;
  12242. const targetCC = Math.min(refDetails.endCC, details.endCC);
  12243. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  12244. refFrag = findFirstFragWithCC(refFragments, targetCC);
  12245. frag = findFirstFragWithCC(fragments, targetCC);
  12246. }
  12247. if (!refFrag || !frag) {
  12248. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  12249. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  12250. }
  12251. const refPDT = refFrag.programDateTime;
  12252. const targetPDT = frag.programDateTime;
  12253. if (!refPDT || !targetPDT) {
  12254. return;
  12255. }
  12256. const delta = (targetPDT - refPDT) / 1e3 - (frag.start - refFrag.start);
  12257. adjustSlidingStart(delta, details);
  12258. }
  12259. const TimeRanges = {
  12260. toString: function(r2) {
  12261. let log = "";
  12262. const len = r2.length;
  12263. for (let i2 = 0; i2 < len; i2++) {
  12264. log += `[${r2.start(i2).toFixed(3)}-${r2.end(i2).toFixed(3)}]`;
  12265. }
  12266. return log;
  12267. }
  12268. };
  12269. const State = {
  12270. STOPPED: "STOPPED",
  12271. IDLE: "IDLE",
  12272. KEY_LOADING: "KEY_LOADING",
  12273. FRAG_LOADING: "FRAG_LOADING",
  12274. FRAG_LOADING_WAITING_RETRY: "FRAG_LOADING_WAITING_RETRY",
  12275. WAITING_TRACK: "WAITING_TRACK",
  12276. PARSING: "PARSING",
  12277. PARSED: "PARSED",
  12278. ENDED: "ENDED",
  12279. ERROR: "ERROR",
  12280. WAITING_INIT_PTS: "WAITING_INIT_PTS",
  12281. WAITING_LEVEL: "WAITING_LEVEL"
  12282. };
  12283. class BaseStreamController extends TaskLoop {
  12284. constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  12285. super(logPrefix, hls.logger);
  12286. this.hls = void 0;
  12287. this.fragPrevious = null;
  12288. this.fragCurrent = null;
  12289. this.fragmentTracker = void 0;
  12290. this.transmuxer = null;
  12291. this._state = State.STOPPED;
  12292. this.playlistType = void 0;
  12293. this.media = null;
  12294. this.mediaBuffer = null;
  12295. this.config = void 0;
  12296. this.bitrateTest = false;
  12297. this.lastCurrentTime = 0;
  12298. this.nextLoadPosition = 0;
  12299. this.startPosition = 0;
  12300. this.startTimeOffset = null;
  12301. this.retryDate = 0;
  12302. this.levels = null;
  12303. this.fragmentLoader = void 0;
  12304. this.keyLoader = void 0;
  12305. this.levelLastLoaded = null;
  12306. this.startFragRequested = false;
  12307. this.decrypter = void 0;
  12308. this.initPTS = [];
  12309. this.buffering = true;
  12310. this.loadingParts = false;
  12311. this.loopSn = void 0;
  12312. this.onMediaSeeking = () => {
  12313. const {
  12314. config: config2,
  12315. fragCurrent,
  12316. media,
  12317. mediaBuffer,
  12318. state
  12319. } = this;
  12320. const currentTime = media ? media.currentTime : 0;
  12321. const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config2.maxBufferHole);
  12322. const noFowardBuffer = !bufferInfo.len;
  12323. this.log(`Media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}, ${noFowardBuffer ? "out of" : "in"} buffer`);
  12324. if (this.state === State.ENDED) {
  12325. this.resetLoadingState();
  12326. } else if (fragCurrent) {
  12327. const tolerance = config2.maxFragLookUpTolerance;
  12328. const fragStartOffset = fragCurrent.start - tolerance;
  12329. const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  12330. if (noFowardBuffer || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  12331. const pastFragment = currentTime > fragEndOffset;
  12332. if (currentTime < fragStartOffset || pastFragment) {
  12333. if (pastFragment && fragCurrent.loader) {
  12334. this.log(`Cancelling fragment load for seek (sn: ${fragCurrent.sn})`);
  12335. fragCurrent.abortRequests();
  12336. this.resetLoadingState();
  12337. }
  12338. this.fragPrevious = null;
  12339. }
  12340. }
  12341. }
  12342. if (media) {
  12343. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  12344. const lastCurrentTime = this.lastCurrentTime;
  12345. if (currentTime > lastCurrentTime) {
  12346. this.lastCurrentTime = currentTime;
  12347. }
  12348. if (!this.loadingParts) {
  12349. const bufferEnd = Math.max(bufferInfo.end, currentTime);
  12350. const shouldLoadParts = this.shouldLoadParts(this.getLevelDetails(), bufferEnd);
  12351. if (shouldLoadParts) {
  12352. this.log(`LL-Part loading ON after seeking to ${currentTime.toFixed(2)} with buffer @${bufferEnd.toFixed(2)}`);
  12353. this.loadingParts = shouldLoadParts;
  12354. }
  12355. }
  12356. }
  12357. if (!this.hls.hasEnoughToStart) {
  12358. this.log(`Setting ${noFowardBuffer ? "startPosition" : "nextLoadPosition"} to ${currentTime} for seek without enough to start`);
  12359. this.nextLoadPosition = currentTime;
  12360. if (noFowardBuffer) {
  12361. this.startPosition = currentTime;
  12362. }
  12363. }
  12364. this.tickImmediate();
  12365. };
  12366. this.onMediaEnded = () => {
  12367. this.log(`setting startPosition to 0 because media ended`);
  12368. this.startPosition = this.lastCurrentTime = 0;
  12369. };
  12370. this.playlistType = playlistType;
  12371. this.hls = hls;
  12372. this.fragmentLoader = new FragmentLoader(hls.config);
  12373. this.keyLoader = keyLoader;
  12374. this.fragmentTracker = fragmentTracker;
  12375. this.config = hls.config;
  12376. this.decrypter = new Decrypter(hls.config);
  12377. }
  12378. registerListeners() {
  12379. const {
  12380. hls
  12381. } = this;
  12382. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  12383. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  12384. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  12385. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  12386. hls.on(Events.ERROR, this.onError, this);
  12387. }
  12388. unregisterListeners() {
  12389. const {
  12390. hls
  12391. } = this;
  12392. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  12393. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  12394. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  12395. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  12396. hls.off(Events.ERROR, this.onError, this);
  12397. }
  12398. doTick() {
  12399. this.onTickEnd();
  12400. }
  12401. onTickEnd() {
  12402. }
  12403. startLoad(startPosition) {
  12404. }
  12405. stopLoad() {
  12406. if (this.state === State.STOPPED) {
  12407. return;
  12408. }
  12409. this.fragmentLoader.abort();
  12410. this.keyLoader.abort(this.playlistType);
  12411. const frag = this.fragCurrent;
  12412. if (frag != null && frag.loader) {
  12413. frag.abortRequests();
  12414. this.fragmentTracker.removeFragment(frag);
  12415. }
  12416. this.resetTransmuxer();
  12417. this.fragCurrent = null;
  12418. this.fragPrevious = null;
  12419. this.clearInterval();
  12420. this.clearNextTick();
  12421. this.state = State.STOPPED;
  12422. }
  12423. get startPositionValue() {
  12424. const {
  12425. nextLoadPosition,
  12426. startPosition
  12427. } = this;
  12428. if (startPosition === -1 && nextLoadPosition) {
  12429. return nextLoadPosition;
  12430. }
  12431. return startPosition;
  12432. }
  12433. get bufferingEnabled() {
  12434. return this.buffering;
  12435. }
  12436. pauseBuffering() {
  12437. this.buffering = false;
  12438. }
  12439. resumeBuffering() {
  12440. this.buffering = true;
  12441. }
  12442. get inFlightFrag() {
  12443. return {
  12444. frag: this.fragCurrent,
  12445. state: this.state
  12446. };
  12447. }
  12448. _streamEnded(bufferInfo, levelDetails) {
  12449. if (levelDetails.live || !this.media) {
  12450. return false;
  12451. }
  12452. const bufferEnd = bufferInfo.end || 0;
  12453. const timelineStart = this.config.timelineOffset || 0;
  12454. if (bufferEnd <= timelineStart) {
  12455. return false;
  12456. }
  12457. const bufferedRanges = bufferInfo.buffered;
  12458. if (this.config.maxBufferHole && bufferedRanges && bufferedRanges.length > 1) {
  12459. bufferInfo = BufferHelper.bufferedInfo(bufferedRanges, bufferInfo.start, 0);
  12460. }
  12461. const nextStart = bufferInfo.nextStart;
  12462. const hasSecondBufferedRange = nextStart && nextStart > timelineStart && nextStart < levelDetails.edge;
  12463. if (hasSecondBufferedRange) {
  12464. return false;
  12465. }
  12466. if (this.media.currentTime < bufferInfo.start) {
  12467. return false;
  12468. }
  12469. const partList = levelDetails.partList;
  12470. if (partList != null && partList.length) {
  12471. const lastPart = partList[partList.length - 1];
  12472. const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  12473. return lastPartBuffered;
  12474. }
  12475. const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  12476. return this.fragmentTracker.isEndListAppended(playlistType);
  12477. }
  12478. getLevelDetails() {
  12479. if (this.levels && this.levelLastLoaded !== null) {
  12480. var _this$levelLastLoaded;
  12481. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  12482. }
  12483. }
  12484. get timelineOffset() {
  12485. const configuredTimelineOffset = this.config.timelineOffset;
  12486. if (configuredTimelineOffset) {
  12487. var _this$getLevelDetails;
  12488. return ((_this$getLevelDetails = this.getLevelDetails()) == null ? void 0 : _this$getLevelDetails.appliedTimelineOffset) || configuredTimelineOffset;
  12489. }
  12490. return 0;
  12491. }
  12492. onMediaAttached(event, data) {
  12493. const media = this.media = this.mediaBuffer = data.media;
  12494. media.removeEventListener("seeking", this.onMediaSeeking);
  12495. media.removeEventListener("ended", this.onMediaEnded);
  12496. media.addEventListener("seeking", this.onMediaSeeking);
  12497. media.addEventListener("ended", this.onMediaEnded);
  12498. const config2 = this.config;
  12499. if (this.levels && config2.autoStartLoad && this.state === State.STOPPED) {
  12500. this.startLoad(config2.startPosition);
  12501. }
  12502. }
  12503. onMediaDetaching(event, data) {
  12504. const transferringMedia = !!data.transferMedia;
  12505. const media = this.media;
  12506. if (media === null) {
  12507. return;
  12508. }
  12509. if (media.ended) {
  12510. this.log("MSE detaching and video ended, reset startPosition");
  12511. this.startPosition = this.lastCurrentTime = 0;
  12512. }
  12513. media.removeEventListener("seeking", this.onMediaSeeking);
  12514. media.removeEventListener("ended", this.onMediaEnded);
  12515. if (this.keyLoader && !transferringMedia) {
  12516. this.keyLoader.detach();
  12517. }
  12518. this.media = this.mediaBuffer = null;
  12519. this.loopSn = void 0;
  12520. if (transferringMedia) {
  12521. this.resetLoadingState();
  12522. this.resetTransmuxer();
  12523. return;
  12524. }
  12525. this.loadingParts = false;
  12526. this.fragmentTracker.removeAllFragments();
  12527. this.stopLoad();
  12528. }
  12529. onManifestLoading() {
  12530. this.initPTS = [];
  12531. this.levels = this.levelLastLoaded = this.fragCurrent = null;
  12532. this.lastCurrentTime = this.startPosition = 0;
  12533. this.startFragRequested = false;
  12534. }
  12535. onError(event, data) {
  12536. }
  12537. onManifestLoaded(event, data) {
  12538. this.startTimeOffset = data.startTimeOffset;
  12539. }
  12540. onHandlerDestroying() {
  12541. this.stopLoad();
  12542. if (this.transmuxer) {
  12543. this.transmuxer.destroy();
  12544. this.transmuxer = null;
  12545. }
  12546. super.onHandlerDestroying();
  12547. this.hls = this.onMediaSeeking = this.onMediaEnded = null;
  12548. }
  12549. onHandlerDestroyed() {
  12550. this.state = State.STOPPED;
  12551. if (this.fragmentLoader) {
  12552. this.fragmentLoader.destroy();
  12553. }
  12554. if (this.keyLoader) {
  12555. this.keyLoader.destroy();
  12556. }
  12557. if (this.decrypter) {
  12558. this.decrypter.destroy();
  12559. }
  12560. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  12561. super.onHandlerDestroyed();
  12562. }
  12563. loadFragment(frag, level, targetBufferTime) {
  12564. this.startFragRequested = true;
  12565. this._loadFragForPlayback(frag, level, targetBufferTime);
  12566. }
  12567. _loadFragForPlayback(fragment, level, targetBufferTime) {
  12568. const progressCallback = (data) => {
  12569. const frag = data.frag;
  12570. if (this.fragContextChanged(frag)) {
  12571. this.warn(`${frag.type} sn: ${frag.sn}${data.part ? " part: " + data.part.index : ""} of ${this.fragInfo(frag, false, data.part)}) was dropped during download.`);
  12572. this.fragmentTracker.removeFragment(frag);
  12573. return;
  12574. }
  12575. frag.stats.chunkCount++;
  12576. this._handleFragmentLoadProgress(data);
  12577. };
  12578. this._doFragLoad(fragment, level, targetBufferTime, progressCallback).then((data) => {
  12579. if (!data) {
  12580. return;
  12581. }
  12582. const state = this.state;
  12583. const frag = data.frag;
  12584. if (this.fragContextChanged(frag)) {
  12585. if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {
  12586. this.fragmentTracker.removeFragment(frag);
  12587. this.state = State.IDLE;
  12588. }
  12589. return;
  12590. }
  12591. if ("payload" in data) {
  12592. this.log(`Loaded ${frag.type} sn: ${frag.sn} of ${this.playlistLabel()} ${frag.level}`);
  12593. this.hls.trigger(Events.FRAG_LOADED, data);
  12594. }
  12595. this._handleFragmentLoadComplete(data);
  12596. }).catch((reason) => {
  12597. if (this.state === State.STOPPED || this.state === State.ERROR) {
  12598. return;
  12599. }
  12600. this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);
  12601. this.resetFragmentLoading(fragment);
  12602. });
  12603. }
  12604. clearTrackerIfNeeded(frag) {
  12605. var _this$mediaBuffer;
  12606. const {
  12607. fragmentTracker
  12608. } = this;
  12609. const fragState = fragmentTracker.getState(frag);
  12610. if (fragState === FragmentState.APPENDING) {
  12611. const playlistType = frag.type;
  12612. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  12613. const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  12614. const backtrackFragment = this.backtrackFragment;
  12615. const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  12616. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  12617. fragmentTracker.removeFragment(frag);
  12618. }
  12619. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  12620. fragmentTracker.removeAllFragments();
  12621. } else if (fragmentTracker.hasParts(frag.type)) {
  12622. fragmentTracker.detectPartialFragments({
  12623. frag,
  12624. part: null,
  12625. stats: frag.stats,
  12626. id: frag.type
  12627. });
  12628. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  12629. fragmentTracker.removeFragment(frag);
  12630. }
  12631. }
  12632. }
  12633. checkLiveUpdate(details) {
  12634. if (details.updated && !details.live) {
  12635. const lastFragment = details.fragments[details.fragments.length - 1];
  12636. this.fragmentTracker.detectPartialFragments({
  12637. frag: lastFragment,
  12638. part: null,
  12639. stats: lastFragment.stats,
  12640. id: lastFragment.type
  12641. });
  12642. }
  12643. if (!details.fragments[0]) {
  12644. details.deltaUpdateFailed = true;
  12645. }
  12646. }
  12647. waitForLive(levelInfo) {
  12648. const details = levelInfo.details;
  12649. return (details == null ? void 0 : details.live) && details.type !== "EVENT" && (this.levelLastLoaded !== levelInfo || details.expired);
  12650. }
  12651. flushMainBuffer(startOffset, endOffset, type = null) {
  12652. if (!(startOffset - endOffset)) {
  12653. return;
  12654. }
  12655. const flushScope = {
  12656. startOffset,
  12657. endOffset,
  12658. type
  12659. };
  12660. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  12661. }
  12662. _loadInitSegment(fragment, level) {
  12663. this._doFragLoad(fragment, level).then((data) => {
  12664. const frag = data == null ? void 0 : data.frag;
  12665. if (!frag || this.fragContextChanged(frag) || !this.levels) {
  12666. throw new Error("init load aborted");
  12667. }
  12668. return data;
  12669. }).then((data) => {
  12670. const {
  12671. hls
  12672. } = this;
  12673. const {
  12674. frag,
  12675. payload
  12676. } = data;
  12677. const decryptData = frag.decryptdata;
  12678. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  12679. const startTime = self.performance.now();
  12680. return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
  12681. hls.trigger(Events.ERROR, {
  12682. type: ErrorTypes.MEDIA_ERROR,
  12683. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  12684. fatal: false,
  12685. error: err,
  12686. reason: err.message,
  12687. frag
  12688. });
  12689. throw err;
  12690. }).then((decryptedData) => {
  12691. const endTime = self.performance.now();
  12692. hls.trigger(Events.FRAG_DECRYPTED, {
  12693. frag,
  12694. payload: decryptedData,
  12695. stats: {
  12696. tstart: startTime,
  12697. tdecrypt: endTime
  12698. }
  12699. });
  12700. data.payload = decryptedData;
  12701. return this.completeInitSegmentLoad(data);
  12702. });
  12703. }
  12704. return this.completeInitSegmentLoad(data);
  12705. }).catch((reason) => {
  12706. if (this.state === State.STOPPED || this.state === State.ERROR) {
  12707. return;
  12708. }
  12709. this.warn(reason);
  12710. this.resetFragmentLoading(fragment);
  12711. });
  12712. }
  12713. completeInitSegmentLoad(data) {
  12714. const {
  12715. levels
  12716. } = this;
  12717. if (!levels) {
  12718. throw new Error("init load aborted, missing levels");
  12719. }
  12720. const stats = data.frag.stats;
  12721. if (this.state !== State.STOPPED) {
  12722. this.state = State.IDLE;
  12723. }
  12724. data.frag.data = new Uint8Array(data.payload);
  12725. stats.parsing.start = stats.buffering.start = self.performance.now();
  12726. stats.parsing.end = stats.buffering.end = self.performance.now();
  12727. this.tick();
  12728. }
  12729. fragContextChanged(frag) {
  12730. const {
  12731. fragCurrent
  12732. } = this;
  12733. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  12734. }
  12735. fragBufferedComplete(frag, part) {
  12736. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  12737. 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)"})`);
  12738. if (isMediaFragment(frag)) {
  12739. var _this$levels;
  12740. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  12741. const el = frag.elementaryStreams;
  12742. if (!Object.keys(el).some((type) => !!el[type])) {
  12743. this.state = State.IDLE;
  12744. return;
  12745. }
  12746. }
  12747. const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  12748. if (level != null && level.fragmentError) {
  12749. this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);
  12750. level.fragmentError = 0;
  12751. }
  12752. }
  12753. this.state = State.IDLE;
  12754. }
  12755. _handleFragmentLoadComplete(fragLoadedEndData) {
  12756. const {
  12757. transmuxer
  12758. } = this;
  12759. if (!transmuxer) {
  12760. return;
  12761. }
  12762. const {
  12763. frag,
  12764. part,
  12765. partsLoaded
  12766. } = fragLoadedEndData;
  12767. const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some((fragLoaded) => !fragLoaded);
  12768. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  12769. transmuxer.flush(chunkMeta);
  12770. }
  12771. _handleFragmentLoadProgress(frag) {
  12772. }
  12773. _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {
  12774. var _frag$decryptdata;
  12775. this.fragCurrent = frag;
  12776. const details = level == null ? void 0 : level.details;
  12777. if (!this.levels || !details) {
  12778. throw new Error(`frag load aborted, missing level${details ? "" : " detail"}s`);
  12779. }
  12780. let keyLoadingPromise = null;
  12781. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  12782. this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.playlistLabel()} ${frag.level}`);
  12783. this.state = State.KEY_LOADING;
  12784. this.fragCurrent = frag;
  12785. keyLoadingPromise = this.keyLoader.load(frag).then((keyLoadedData) => {
  12786. if (!this.fragContextChanged(keyLoadedData.frag)) {
  12787. this.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  12788. if (this.state === State.KEY_LOADING) {
  12789. this.state = State.IDLE;
  12790. }
  12791. return keyLoadedData;
  12792. }
  12793. });
  12794. this.hls.trigger(Events.KEY_LOADING, {
  12795. frag
  12796. });
  12797. if (this.fragCurrent === null) {
  12798. keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`));
  12799. }
  12800. } else if (!frag.encrypted) {
  12801. keyLoadingPromise = this.keyLoader.loadClear(frag, details.encryptedFragments, this.startFragRequested);
  12802. if (keyLoadingPromise) {
  12803. this.log(`[eme] blocking frag load until media-keys acquired`);
  12804. }
  12805. }
  12806. const fragPrevious = this.fragPrevious;
  12807. if (isMediaFragment(frag) && (!fragPrevious || frag.sn !== fragPrevious.sn)) {
  12808. const shouldLoadParts = this.shouldLoadParts(level.details, frag.end);
  12809. if (shouldLoadParts !== this.loadingParts) {
  12810. this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} loading sn ${fragPrevious == null ? void 0 : fragPrevious.sn}->${frag.sn}`);
  12811. this.loadingParts = shouldLoadParts;
  12812. }
  12813. }
  12814. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  12815. if (this.loadingParts && isMediaFragment(frag)) {
  12816. const partList = details.partList;
  12817. if (partList && progressCallback) {
  12818. if (targetBufferTime > frag.end && details.fragmentHint) {
  12819. frag = details.fragmentHint;
  12820. }
  12821. const partIndex = this.getNextPart(partList, frag, targetBufferTime);
  12822. if (partIndex > -1) {
  12823. const part = partList[partIndex];
  12824. frag = this.fragCurrent = part.fragment;
  12825. 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))}`);
  12826. this.nextLoadPosition = part.start + part.duration;
  12827. this.state = State.FRAG_LOADING;
  12828. let _result;
  12829. if (keyLoadingPromise) {
  12830. _result = keyLoadingPromise.then((keyLoadedData) => {
  12831. if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
  12832. return null;
  12833. }
  12834. return this.doFragPartsLoad(frag, part, level, progressCallback);
  12835. }).catch((error2) => this.handleFragLoadError(error2));
  12836. } else {
  12837. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch((error2) => this.handleFragLoadError(error2));
  12838. }
  12839. this.hls.trigger(Events.FRAG_LOADING, {
  12840. frag,
  12841. part,
  12842. targetBufferTime
  12843. });
  12844. if (this.fragCurrent === null) {
  12845. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));
  12846. }
  12847. return _result;
  12848. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  12849. return Promise.resolve(null);
  12850. }
  12851. }
  12852. }
  12853. if (isMediaFragment(frag) && this.loadingParts) {
  12854. this.log(`LL-Part loading OFF after next part miss @${targetBufferTime.toFixed(2)}`);
  12855. this.loadingParts = false;
  12856. } else if (!frag.url) {
  12857. return Promise.resolve(null);
  12858. }
  12859. 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))}`);
  12860. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  12861. this.nextLoadPosition = frag.start + frag.duration;
  12862. }
  12863. this.state = State.FRAG_LOADING;
  12864. const dataOnProgress = this.config.progressive;
  12865. let result;
  12866. if (dataOnProgress && keyLoadingPromise) {
  12867. result = keyLoadingPromise.then((keyLoadedData) => {
  12868. if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  12869. return null;
  12870. }
  12871. return this.fragmentLoader.load(frag, progressCallback);
  12872. }).catch((error2) => this.handleFragLoadError(error2));
  12873. } else {
  12874. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : void 0), keyLoadingPromise]).then(([fragLoadedData]) => {
  12875. if (!dataOnProgress && fragLoadedData && progressCallback) {
  12876. progressCallback(fragLoadedData);
  12877. }
  12878. return fragLoadedData;
  12879. }).catch((error2) => this.handleFragLoadError(error2));
  12880. }
  12881. this.hls.trigger(Events.FRAG_LOADING, {
  12882. frag,
  12883. targetBufferTime
  12884. });
  12885. if (this.fragCurrent === null) {
  12886. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));
  12887. }
  12888. return result;
  12889. }
  12890. doFragPartsLoad(frag, fromPart, level, progressCallback) {
  12891. return new Promise((resolve, reject) => {
  12892. var _level$details;
  12893. const partsLoaded = [];
  12894. const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  12895. const loadPart = (part) => {
  12896. this.fragmentLoader.loadPart(frag, part, progressCallback).then((partLoadedData) => {
  12897. partsLoaded[part.index] = partLoadedData;
  12898. const loadedPart = partLoadedData.part;
  12899. this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  12900. const nextPart = getPartWith(level.details, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  12901. if (nextPart) {
  12902. loadPart(nextPart);
  12903. } else {
  12904. return resolve({
  12905. frag,
  12906. part: loadedPart,
  12907. partsLoaded
  12908. });
  12909. }
  12910. }).catch(reject);
  12911. };
  12912. loadPart(fromPart);
  12913. });
  12914. }
  12915. handleFragLoadError(error2) {
  12916. if ("data" in error2) {
  12917. const data = error2.data;
  12918. if (error2.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  12919. this.handleFragLoadAborted(data.frag, data.part);
  12920. } else {
  12921. this.hls.trigger(Events.ERROR, data);
  12922. }
  12923. } else {
  12924. this.hls.trigger(Events.ERROR, {
  12925. type: ErrorTypes.OTHER_ERROR,
  12926. details: ErrorDetails.INTERNAL_EXCEPTION,
  12927. err: error2,
  12928. error: error2,
  12929. fatal: true
  12930. });
  12931. }
  12932. return null;
  12933. }
  12934. _handleTransmuxerFlush(chunkMeta) {
  12935. const context = this.getCurrentContext(chunkMeta);
  12936. if (!context || this.state !== State.PARSING) {
  12937. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  12938. this.state = State.IDLE;
  12939. }
  12940. return;
  12941. }
  12942. const {
  12943. frag,
  12944. part,
  12945. level
  12946. } = context;
  12947. const now2 = self.performance.now();
  12948. frag.stats.parsing.end = now2;
  12949. if (part) {
  12950. part.stats.parsing.end = now2;
  12951. }
  12952. const levelDetails = this.getLevelDetails();
  12953. const loadingPartsAtEdge = levelDetails && frag.sn > levelDetails.endSN;
  12954. const shouldLoadParts = loadingPartsAtEdge || this.shouldLoadParts(levelDetails, frag.end);
  12955. if (shouldLoadParts !== this.loadingParts) {
  12956. this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} after parsing segment ending @${frag.end.toFixed(2)}`);
  12957. this.loadingParts = shouldLoadParts;
  12958. }
  12959. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  12960. }
  12961. shouldLoadParts(details, bufferEnd) {
  12962. if (this.config.lowLatencyMode) {
  12963. if (!details) {
  12964. return this.loadingParts;
  12965. }
  12966. if (details != null && details.partList) {
  12967. var _details$fragmentHint;
  12968. const firstPart = details.partList[0];
  12969. const safePartStart = firstPart.end + (((_details$fragmentHint = details.fragmentHint) == null ? void 0 : _details$fragmentHint.duration) || 0);
  12970. if (bufferEnd >= safePartStart) {
  12971. var _this$media;
  12972. const playhead = this.hls.hasEnoughToStart ? ((_this$media = this.media) == null ? void 0 : _this$media.currentTime) || this.lastCurrentTime : this.getLoadPosition();
  12973. if (playhead > firstPart.start - firstPart.fragment.duration) {
  12974. return true;
  12975. }
  12976. }
  12977. }
  12978. }
  12979. return false;
  12980. }
  12981. getCurrentContext(chunkMeta) {
  12982. const {
  12983. levels,
  12984. fragCurrent
  12985. } = this;
  12986. const {
  12987. level: levelIndex,
  12988. sn,
  12989. part: partIndex
  12990. } = chunkMeta;
  12991. if (!(levels != null && levels[levelIndex])) {
  12992. this.warn(`Levels object was unset while buffering fragment ${sn} of ${this.playlistLabel()} ${levelIndex}. The current chunk will not be buffered.`);
  12993. return null;
  12994. }
  12995. const level = levels[levelIndex];
  12996. const levelDetails = level.details;
  12997. const part = partIndex > -1 ? getPartWith(levelDetails, sn, partIndex) : null;
  12998. const frag = part ? part.fragment : getFragmentWithSN(levelDetails, sn, fragCurrent);
  12999. if (!frag) {
  13000. return null;
  13001. }
  13002. if (fragCurrent && fragCurrent !== frag) {
  13003. frag.stats = fragCurrent.stats;
  13004. }
  13005. return {
  13006. frag,
  13007. part,
  13008. level
  13009. };
  13010. }
  13011. bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  13012. var _buffer;
  13013. if (!data || this.state !== State.PARSING) {
  13014. return;
  13015. }
  13016. const {
  13017. data1,
  13018. data2
  13019. } = data;
  13020. let buffer = data1;
  13021. if (data1 && data2) {
  13022. buffer = appendUint8Array(data1, data2);
  13023. }
  13024. if (!((_buffer = buffer) != null && _buffer.length)) {
  13025. return;
  13026. }
  13027. const offsetTimestamp = this.initPTS[frag.cc];
  13028. const offset = offsetTimestamp ? -offsetTimestamp.baseTime / offsetTimestamp.timescale : void 0;
  13029. const segment = {
  13030. type: data.type,
  13031. frag,
  13032. part,
  13033. chunkMeta,
  13034. offset,
  13035. parent: frag.type,
  13036. data: buffer
  13037. };
  13038. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  13039. if (data.dropped && data.independent && !part) {
  13040. if (noBacktracking) {
  13041. return;
  13042. }
  13043. this.flushBufferGap(frag);
  13044. }
  13045. }
  13046. flushBufferGap(frag) {
  13047. const media = this.media;
  13048. if (!media) {
  13049. return;
  13050. }
  13051. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  13052. this.flushMainBuffer(0, frag.start);
  13053. return;
  13054. }
  13055. const currentTime = media.currentTime;
  13056. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  13057. const fragDuration = frag.duration;
  13058. const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  13059. const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  13060. if (frag.start - start > segmentFraction) {
  13061. this.flushMainBuffer(start, frag.start);
  13062. }
  13063. }
  13064. getFwdBufferInfo(bufferable, type) {
  13065. var _this$media2;
  13066. const pos = this.getLoadPosition();
  13067. if (!isFiniteNumber(pos)) {
  13068. return null;
  13069. }
  13070. const backwardSeek = this.lastCurrentTime > pos;
  13071. const maxBufferHole = backwardSeek || (_this$media2 = this.media) != null && _this$media2.paused ? 0 : this.config.maxBufferHole;
  13072. return this.getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole);
  13073. }
  13074. getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole) {
  13075. const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  13076. if (bufferInfo.len === 0 && bufferInfo.nextStart !== void 0) {
  13077. const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  13078. if (bufferedFragAtPos && (bufferInfo.nextStart <= bufferedFragAtPos.end || bufferedFragAtPos.gap)) {
  13079. const gapDuration = Math.max(Math.min(bufferInfo.nextStart, bufferedFragAtPos.end) - pos, maxBufferHole);
  13080. return BufferHelper.bufferInfo(bufferable, pos, gapDuration);
  13081. }
  13082. }
  13083. return bufferInfo;
  13084. }
  13085. getMaxBufferLength(levelBitrate) {
  13086. const {
  13087. config: config2
  13088. } = this;
  13089. let maxBufLen;
  13090. if (levelBitrate) {
  13091. maxBufLen = Math.max(8 * config2.maxBufferSize / levelBitrate, config2.maxBufferLength);
  13092. } else {
  13093. maxBufLen = config2.maxBufferLength;
  13094. }
  13095. return Math.min(maxBufLen, config2.maxMaxBufferLength);
  13096. }
  13097. reduceMaxBufferLength(threshold, fragDuration) {
  13098. const config2 = this.config;
  13099. const minLength = Math.max(Math.min(threshold - fragDuration, config2.maxBufferLength), fragDuration);
  13100. const reducedLength = Math.max(threshold - fragDuration * 3, config2.maxMaxBufferLength / 2, minLength);
  13101. if (reducedLength >= minLength) {
  13102. config2.maxMaxBufferLength = reducedLength;
  13103. this.warn(`Reduce max buffer length to ${reducedLength}s`);
  13104. return true;
  13105. }
  13106. return false;
  13107. }
  13108. getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {
  13109. var _this$fragmentTracker;
  13110. const fragOrPart = (_this$fragmentTracker = this.fragmentTracker) == null ? void 0 : _this$fragmentTracker.getAppendedFrag(position, playlistType);
  13111. if (fragOrPart && "fragment" in fragOrPart) {
  13112. return fragOrPart.fragment;
  13113. }
  13114. return fragOrPart;
  13115. }
  13116. getNextFragment(pos, levelDetails) {
  13117. const fragments = levelDetails.fragments;
  13118. const fragLen = fragments.length;
  13119. if (!fragLen) {
  13120. return null;
  13121. }
  13122. const {
  13123. config: config2
  13124. } = this;
  13125. const start = fragments[0].start;
  13126. const canLoadParts = config2.lowLatencyMode && !!levelDetails.partList;
  13127. let frag = null;
  13128. if (levelDetails.live) {
  13129. const initialLiveManifestSize = config2.initialLiveManifestSize;
  13130. if (fragLen < initialLiveManifestSize) {
  13131. this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);
  13132. return null;
  13133. }
  13134. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  13135. var _frag;
  13136. if (canLoadParts && !this.loadingParts) {
  13137. this.log(`LL-Part loading ON for initial live fragment`);
  13138. this.loadingParts = true;
  13139. }
  13140. frag = this.getInitialLiveFragment(levelDetails);
  13141. const mainStart = this.hls.startPosition;
  13142. const liveSyncPosition = this.hls.liveSyncPosition;
  13143. const startPosition = frag ? (mainStart !== -1 && mainStart >= start ? mainStart : liveSyncPosition) || frag.start : pos;
  13144. 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}`);
  13145. this.startPosition = this.nextLoadPosition = startPosition;
  13146. }
  13147. } else if (pos <= start) {
  13148. frag = fragments[0];
  13149. }
  13150. if (!frag) {
  13151. const end = this.loadingParts ? levelDetails.partEnd : levelDetails.fragmentEnd;
  13152. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  13153. }
  13154. let programFrag = this.filterReplacedPrimary(frag, levelDetails);
  13155. if (!programFrag && frag) {
  13156. const curSNIdx = frag.sn - levelDetails.startSN;
  13157. programFrag = this.filterReplacedPrimary(fragments[curSNIdx + 1] || null, levelDetails);
  13158. }
  13159. return this.mapToInitFragWhenRequired(programFrag);
  13160. }
  13161. isLoopLoading(frag, targetBufferTime) {
  13162. const trackerState = this.fragmentTracker.getState(frag);
  13163. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  13164. }
  13165. getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  13166. let nextFragment = null;
  13167. if (frag.gap) {
  13168. nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  13169. if (nextFragment && !nextFragment.gap && bufferInfo.nextStart) {
  13170. const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType, 0);
  13171. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  13172. const sn = nextFragment.sn;
  13173. if (this.loopSn !== sn) {
  13174. this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${sn}`);
  13175. this.loopSn = sn;
  13176. }
  13177. return null;
  13178. }
  13179. }
  13180. }
  13181. this.loopSn = void 0;
  13182. return nextFragment;
  13183. }
  13184. get primaryPrefetch() {
  13185. if (interstitialsEnabled(this.hls.config)) {
  13186. var _this$hls$interstitia, _this$hls$interstitia2;
  13187. 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;
  13188. if (playingInterstitial) {
  13189. return true;
  13190. }
  13191. }
  13192. return false;
  13193. }
  13194. filterReplacedPrimary(frag, details) {
  13195. if (!frag) {
  13196. return frag;
  13197. }
  13198. if (interstitialsEnabled(this.hls.config) && frag.type !== PlaylistLevelType.SUBTITLE) {
  13199. const interstitials = this.hls.interstitialsManager;
  13200. const bufferingItem = interstitials == null ? void 0 : interstitials.bufferingItem;
  13201. if (bufferingItem) {
  13202. const bufferingInterstitial = bufferingItem.event;
  13203. if (bufferingInterstitial) {
  13204. if (bufferingInterstitial.appendInPlace || Math.abs(frag.start - bufferingItem.start) > 1 || bufferingItem.start === 0) {
  13205. return null;
  13206. }
  13207. } else {
  13208. if (frag.end <= bufferingItem.start && (details == null ? void 0 : details.live) === false) {
  13209. return null;
  13210. }
  13211. if (frag.start > bufferingItem.end && bufferingItem.nextEvent) {
  13212. if (bufferingItem.nextEvent.appendInPlace || frag.start - bufferingItem.end > 1) {
  13213. return null;
  13214. }
  13215. }
  13216. }
  13217. }
  13218. const playerQueue = interstitials == null ? void 0 : interstitials.playerQueue;
  13219. if (playerQueue) {
  13220. for (let i2 = playerQueue.length; i2--; ) {
  13221. const interstitial = playerQueue[i2].interstitial;
  13222. if (interstitial.appendInPlace && frag.start >= interstitial.startTime && frag.end <= interstitial.resumeTime) {
  13223. return null;
  13224. }
  13225. }
  13226. }
  13227. }
  13228. return frag;
  13229. }
  13230. mapToInitFragWhenRequired(frag) {
  13231. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  13232. return frag.initSegment;
  13233. }
  13234. return frag;
  13235. }
  13236. getNextPart(partList, frag, targetBufferTime) {
  13237. let nextPart = -1;
  13238. let contiguous = false;
  13239. let independentAttrOmitted = true;
  13240. for (let i2 = 0, len = partList.length; i2 < len; i2++) {
  13241. const part = partList[i2];
  13242. independentAttrOmitted = independentAttrOmitted && !part.independent;
  13243. if (nextPart > -1 && targetBufferTime < part.start) {
  13244. break;
  13245. }
  13246. const loaded = part.loaded;
  13247. if (loaded) {
  13248. nextPart = -1;
  13249. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  13250. nextPart = i2;
  13251. }
  13252. contiguous = loaded;
  13253. }
  13254. return nextPart;
  13255. }
  13256. loadedEndOfParts(partList, targetBufferTime) {
  13257. const lastPart = partList[partList.length - 1];
  13258. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  13259. }
  13260. /*
  13261. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  13262. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  13263. start and end times for each fragment in the playlist (after which this method will not need to be called).
  13264. */
  13265. getInitialLiveFragment(levelDetails) {
  13266. const fragments = levelDetails.fragments;
  13267. const fragPrevious = this.fragPrevious;
  13268. let frag = null;
  13269. if (fragPrevious) {
  13270. if (levelDetails.hasProgramDateTime) {
  13271. this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
  13272. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  13273. }
  13274. if (!frag) {
  13275. const targetSN = fragPrevious.sn + 1;
  13276. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  13277. const fragNext = fragments[targetSN - levelDetails.startSN];
  13278. if (fragPrevious.cc === fragNext.cc) {
  13279. frag = fragNext;
  13280. this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
  13281. }
  13282. }
  13283. if (!frag) {
  13284. frag = findNearestWithCC(levelDetails, fragPrevious.cc, fragPrevious.end);
  13285. if (frag) {
  13286. this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
  13287. }
  13288. }
  13289. }
  13290. } else {
  13291. const liveStart = this.hls.liveSyncPosition;
  13292. if (liveStart !== null) {
  13293. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  13294. }
  13295. }
  13296. return frag;
  13297. }
  13298. /*
  13299. This method finds the best matching fragment given the provided position.
  13300. */
  13301. getFragmentAtPosition(bufferEnd, end, levelDetails) {
  13302. const {
  13303. config: config2
  13304. } = this;
  13305. let {
  13306. fragPrevious
  13307. } = this;
  13308. let {
  13309. fragments,
  13310. endSN
  13311. } = levelDetails;
  13312. const {
  13313. fragmentHint
  13314. } = levelDetails;
  13315. const {
  13316. maxFragLookUpTolerance
  13317. } = config2;
  13318. const partList = levelDetails.partList;
  13319. const loadingParts = !!(this.loadingParts && partList != null && partList.length && fragmentHint);
  13320. if (loadingParts && fragmentHint && !this.bitrateTest && partList[partList.length - 1].fragment.sn === fragmentHint.sn) {
  13321. fragments = fragments.concat(fragmentHint);
  13322. endSN = fragmentHint.sn;
  13323. }
  13324. let frag;
  13325. if (bufferEnd < end) {
  13326. var _this$media3;
  13327. const backwardSeek = bufferEnd < this.lastCurrentTime;
  13328. const lookupTolerance = backwardSeek || bufferEnd > end - maxFragLookUpTolerance || (_this$media3 = this.media) != null && _this$media3.paused || !this.startFragRequested ? 0 : maxFragLookUpTolerance;
  13329. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  13330. } else {
  13331. frag = fragments[fragments.length - 1];
  13332. }
  13333. if (frag) {
  13334. const curSNIdx = frag.sn - levelDetails.startSN;
  13335. const fragState = this.fragmentTracker.getState(frag);
  13336. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  13337. fragPrevious = frag;
  13338. }
  13339. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn || !levelDetails.live && !loadingParts)) {
  13340. const sameLevel = fragPrevious && frag.level === fragPrevious.level;
  13341. if (sameLevel) {
  13342. const nextFrag = fragments[curSNIdx + 1];
  13343. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  13344. frag = nextFrag;
  13345. } else {
  13346. frag = null;
  13347. }
  13348. }
  13349. }
  13350. }
  13351. return frag;
  13352. }
  13353. alignPlaylists(details, previousDetails, switchDetails) {
  13354. const length = details.fragments.length;
  13355. if (!length) {
  13356. this.warn(`No fragments in live playlist`);
  13357. return 0;
  13358. }
  13359. const slidingStart = details.fragmentStart;
  13360. const firstLevelLoad = !previousDetails;
  13361. const aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  13362. if (firstLevelLoad || !aligned && !slidingStart) {
  13363. alignStream(switchDetails, details);
  13364. const alignedSlidingStart = details.fragmentStart;
  13365. this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : "na"}->${details.startSN} fragments: ${length}`);
  13366. return alignedSlidingStart;
  13367. }
  13368. return slidingStart;
  13369. }
  13370. waitForCdnTuneIn(details) {
  13371. const advancePartLimit = 3;
  13372. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  13373. }
  13374. setStartPosition(details, sliding) {
  13375. let startPosition = this.startPosition;
  13376. if (startPosition < sliding) {
  13377. startPosition = -1;
  13378. }
  13379. const timelineOffset = this.timelineOffset;
  13380. if (startPosition === -1) {
  13381. const offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  13382. const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  13383. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  13384. startPosition = sliding + startTimeOffset;
  13385. if (startTimeOffset < 0) {
  13386. startPosition += details.edge;
  13387. }
  13388. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  13389. this.log(`Setting startPosition to ${startPosition} for start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? "multivariant" : "media"} playlist`);
  13390. this.startPosition = startPosition;
  13391. } else if (details.live) {
  13392. startPosition = this.hls.liveSyncPosition || sliding;
  13393. this.log(`Setting startPosition to -1 to start at live edge ${startPosition}`);
  13394. this.startPosition = -1;
  13395. } else {
  13396. this.log(`setting startPosition to 0 by default`);
  13397. this.startPosition = startPosition = 0;
  13398. }
  13399. this.lastCurrentTime = startPosition + timelineOffset;
  13400. }
  13401. this.nextLoadPosition = startPosition + timelineOffset;
  13402. }
  13403. getLoadPosition() {
  13404. var _this$hls;
  13405. const {
  13406. media
  13407. } = this;
  13408. let pos = 0;
  13409. if ((_this$hls = this.hls) != null && _this$hls.hasEnoughToStart && media) {
  13410. pos = media.currentTime;
  13411. } else if (this.nextLoadPosition >= 0) {
  13412. pos = this.nextLoadPosition;
  13413. }
  13414. return pos;
  13415. }
  13416. handleFragLoadAborted(frag, part) {
  13417. if (this.transmuxer && frag.type === this.playlistType && isMediaFragment(frag) && frag.stats.aborted) {
  13418. this.log(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of ${this.playlistLabel()} ${frag.level} was aborted`);
  13419. this.resetFragmentLoading(frag);
  13420. }
  13421. }
  13422. resetFragmentLoading(frag) {
  13423. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  13424. this.state = State.IDLE;
  13425. }
  13426. }
  13427. onFragmentOrKeyLoadError(filterType, data) {
  13428. if (data.chunkMeta && !data.frag) {
  13429. const context = this.getCurrentContext(data.chunkMeta);
  13430. if (context) {
  13431. data.frag = context.frag;
  13432. }
  13433. }
  13434. const frag = data.frag;
  13435. if (!frag || frag.type !== filterType || !this.levels) {
  13436. return;
  13437. }
  13438. if (this.fragContextChanged(frag)) {
  13439. var _this$fragCurrent;
  13440. this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.url}`);
  13441. return;
  13442. }
  13443. const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  13444. if (gapTagEncountered) {
  13445. this.fragmentTracker.fragBuffered(frag, true);
  13446. }
  13447. const errorAction = data.errorAction;
  13448. const {
  13449. action,
  13450. flags,
  13451. retryCount = 0,
  13452. retryConfig
  13453. } = errorAction || {};
  13454. const couldRetry = !!errorAction && !!retryConfig;
  13455. const retry = couldRetry && action === NetworkErrorAction.RetryRequest;
  13456. const noAlternate = couldRetry && !errorAction.resolved && flags === ErrorActionFlags.MoveAllAlternatesMatchingHost;
  13457. if (!retry && noAlternate && isMediaFragment(frag) && !frag.endList) {
  13458. this.resetFragmentErrors(filterType);
  13459. this.treatAsGap(frag);
  13460. errorAction.resolved = true;
  13461. } else if ((retry || noAlternate) && retryCount < retryConfig.maxNumRetry) {
  13462. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  13463. const delay = getRetryDelay(retryConfig, retryCount);
  13464. this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);
  13465. errorAction.resolved = true;
  13466. this.retryDate = self.performance.now() + delay;
  13467. this.state = State.FRAG_LOADING_WAITING_RETRY;
  13468. } else if (retryConfig && errorAction) {
  13469. this.resetFragmentErrors(filterType);
  13470. if (retryCount < retryConfig.maxNumRetry) {
  13471. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  13472. errorAction.resolved = true;
  13473. }
  13474. } else {
  13475. this.warn(`${data.details} reached or exceeded max retry (${retryCount})`);
  13476. return;
  13477. }
  13478. } else if (action === NetworkErrorAction.SendAlternateToPenaltyBox) {
  13479. this.state = State.WAITING_LEVEL;
  13480. } else {
  13481. this.state = State.ERROR;
  13482. }
  13483. this.tickImmediate();
  13484. }
  13485. reduceLengthAndFlushBuffer(data) {
  13486. if (this.state === State.PARSING || this.state === State.PARSED) {
  13487. const frag = data.frag;
  13488. const playlistType = data.parent;
  13489. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  13490. const buffered = bufferedInfo && bufferedInfo.len > 0.5;
  13491. if (buffered) {
  13492. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  13493. }
  13494. const flushBuffer = !buffered;
  13495. if (flushBuffer) {
  13496. this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`);
  13497. }
  13498. if (frag) {
  13499. this.fragmentTracker.removeFragment(frag);
  13500. this.nextLoadPosition = frag.start;
  13501. }
  13502. this.resetLoadingState();
  13503. return flushBuffer;
  13504. }
  13505. return false;
  13506. }
  13507. resetFragmentErrors(filterType) {
  13508. if (filterType === PlaylistLevelType.AUDIO) {
  13509. this.fragCurrent = null;
  13510. }
  13511. if (!this.hls.hasEnoughToStart) {
  13512. this.startFragRequested = false;
  13513. }
  13514. if (this.state !== State.STOPPED) {
  13515. this.state = State.IDLE;
  13516. }
  13517. }
  13518. afterBufferFlushed(media, bufferType, playlistType) {
  13519. if (!media) {
  13520. return;
  13521. }
  13522. const bufferedTimeRanges = BufferHelper.getBuffered(media);
  13523. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  13524. if (this.state === State.ENDED) {
  13525. this.resetLoadingState();
  13526. }
  13527. }
  13528. resetLoadingState() {
  13529. this.log("Reset loading state");
  13530. this.fragCurrent = null;
  13531. this.fragPrevious = null;
  13532. if (this.state !== State.STOPPED) {
  13533. this.state = State.IDLE;
  13534. }
  13535. }
  13536. resetStartWhenNotLoaded(level) {
  13537. if (!this.hls.hasEnoughToStart) {
  13538. this.startFragRequested = false;
  13539. const details = level ? level.details : null;
  13540. if (details != null && details.live) {
  13541. this.log(`resetting startPosition for live start`);
  13542. this.startPosition = -1;
  13543. this.setStartPosition(details, details.fragmentStart);
  13544. this.resetLoadingState();
  13545. } else {
  13546. this.nextLoadPosition = this.startPosition;
  13547. }
  13548. }
  13549. }
  13550. resetWhenMissingContext(chunkMeta) {
  13551. this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of ${this.playlistLabel()} ${chunkMeta.level}. This chunk will not be buffered.`);
  13552. this.removeUnbufferedFrags();
  13553. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  13554. this.resetLoadingState();
  13555. }
  13556. removeUnbufferedFrags(start = 0) {
  13557. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  13558. }
  13559. updateLevelTiming(frag, part, level, partial2) {
  13560. const details = level.details;
  13561. if (!details) {
  13562. this.warn("level.details undefined");
  13563. return;
  13564. }
  13565. const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => {
  13566. const info = frag.elementaryStreams[type];
  13567. if (info) {
  13568. const parsedDuration = info.endPTS - info.startPTS;
  13569. if (parsedDuration <= 0) {
  13570. this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`);
  13571. return result || false;
  13572. }
  13573. const drift = partial2 ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  13574. this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  13575. details,
  13576. level,
  13577. drift,
  13578. type,
  13579. frag,
  13580. start: info.startPTS,
  13581. end: info.endPTS
  13582. });
  13583. return true;
  13584. }
  13585. return result;
  13586. }, false);
  13587. if (!parsed) {
  13588. var _this$transmuxer;
  13589. if (level.fragmentError === 0) {
  13590. this.treatAsGap(frag, level);
  13591. }
  13592. if (((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  13593. const error2 = new Error(`Found no media in fragment ${frag.sn} of ${this.playlistLabel()} ${frag.level} resetting transmuxer to fallback to playlist timing`);
  13594. this.warn(error2.message);
  13595. this.hls.trigger(Events.ERROR, {
  13596. type: ErrorTypes.MEDIA_ERROR,
  13597. details: ErrorDetails.FRAG_PARSING_ERROR,
  13598. fatal: false,
  13599. error: error2,
  13600. frag,
  13601. reason: `Found no media in msn ${frag.sn} of ${this.playlistLabel()} "${level.url}"`
  13602. });
  13603. if (!this.hls) {
  13604. return;
  13605. }
  13606. this.resetTransmuxer();
  13607. }
  13608. }
  13609. this.state = State.PARSED;
  13610. this.log(`Parsed ${frag.type} sn: ${frag.sn}${part ? " part: " + part.index : ""} of ${this.fragInfo(frag, false, part)})`);
  13611. this.hls.trigger(Events.FRAG_PARSED, {
  13612. frag,
  13613. part
  13614. });
  13615. }
  13616. playlistLabel() {
  13617. return this.playlistType === PlaylistLevelType.MAIN ? "level" : "track";
  13618. }
  13619. fragInfo(frag, pts = true, part) {
  13620. var _ref, _ref2;
  13621. 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") : ""}`;
  13622. }
  13623. treatAsGap(frag, level) {
  13624. if (level) {
  13625. level.fragmentError++;
  13626. }
  13627. frag.gap = true;
  13628. this.fragmentTracker.removeFragment(frag);
  13629. this.fragmentTracker.fragBuffered(frag, true);
  13630. }
  13631. resetTransmuxer() {
  13632. var _this$transmuxer2;
  13633. (_this$transmuxer2 = this.transmuxer) == null ? void 0 : _this$transmuxer2.reset();
  13634. }
  13635. recoverWorkerError(data) {
  13636. if (data.event === "demuxerWorker") {
  13637. this.fragmentTracker.removeAllFragments();
  13638. if (this.transmuxer) {
  13639. this.transmuxer.destroy();
  13640. this.transmuxer = null;
  13641. }
  13642. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  13643. this.resetLoadingState();
  13644. }
  13645. }
  13646. set state(nextState) {
  13647. const previousState = this._state;
  13648. if (previousState !== nextState) {
  13649. this._state = nextState;
  13650. this.log(`${previousState}->${nextState}`);
  13651. }
  13652. }
  13653. get state() {
  13654. return this._state;
  13655. }
  13656. }
  13657. function interstitialsEnabled(config2) {
  13658. return !!config2.interstitialsController && config2.enableInterstitialPlayback !== false;
  13659. }
  13660. class ChunkCache {
  13661. constructor() {
  13662. this.chunks = [];
  13663. this.dataLength = 0;
  13664. }
  13665. push(chunk) {
  13666. this.chunks.push(chunk);
  13667. this.dataLength += chunk.length;
  13668. }
  13669. flush() {
  13670. const {
  13671. chunks,
  13672. dataLength
  13673. } = this;
  13674. let result;
  13675. if (!chunks.length) {
  13676. return new Uint8Array(0);
  13677. } else if (chunks.length === 1) {
  13678. result = chunks[0];
  13679. } else {
  13680. result = concatUint8Arrays(chunks, dataLength);
  13681. }
  13682. this.reset();
  13683. return result;
  13684. }
  13685. reset() {
  13686. this.chunks.length = 0;
  13687. this.dataLength = 0;
  13688. }
  13689. }
  13690. function concatUint8Arrays(chunks, dataLength) {
  13691. const result = new Uint8Array(dataLength);
  13692. let offset = 0;
  13693. for (let i2 = 0; i2 < chunks.length; i2++) {
  13694. const chunk = chunks[i2];
  13695. result.set(chunk, offset);
  13696. offset += chunk.length;
  13697. }
  13698. return result;
  13699. }
  13700. var eventemitter3 = { exports: {} };
  13701. var hasRequiredEventemitter3;
  13702. function requireEventemitter3() {
  13703. if (hasRequiredEventemitter3)
  13704. return eventemitter3.exports;
  13705. hasRequiredEventemitter3 = 1;
  13706. (function(module) {
  13707. var has = Object.prototype.hasOwnProperty, prefix = "~";
  13708. function Events2() {
  13709. }
  13710. if (Object.create) {
  13711. Events2.prototype = /* @__PURE__ */ Object.create(null);
  13712. if (!new Events2().__proto__)
  13713. prefix = false;
  13714. }
  13715. function EE(fn, context, once) {
  13716. this.fn = fn;
  13717. this.context = context;
  13718. this.once = once || false;
  13719. }
  13720. function addListener(emitter, event, fn, context, once) {
  13721. if (typeof fn !== "function") {
  13722. throw new TypeError("The listener must be a function");
  13723. }
  13724. var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
  13725. if (!emitter._events[evt])
  13726. emitter._events[evt] = listener, emitter._eventsCount++;
  13727. else if (!emitter._events[evt].fn)
  13728. emitter._events[evt].push(listener);
  13729. else
  13730. emitter._events[evt] = [emitter._events[evt], listener];
  13731. return emitter;
  13732. }
  13733. function clearEvent(emitter, evt) {
  13734. if (--emitter._eventsCount === 0)
  13735. emitter._events = new Events2();
  13736. else
  13737. delete emitter._events[evt];
  13738. }
  13739. function EventEmitter2() {
  13740. this._events = new Events2();
  13741. this._eventsCount = 0;
  13742. }
  13743. EventEmitter2.prototype.eventNames = function eventNames() {
  13744. var names = [], events, name;
  13745. if (this._eventsCount === 0)
  13746. return names;
  13747. for (name in events = this._events) {
  13748. if (has.call(events, name))
  13749. names.push(prefix ? name.slice(1) : name);
  13750. }
  13751. if (Object.getOwnPropertySymbols) {
  13752. return names.concat(Object.getOwnPropertySymbols(events));
  13753. }
  13754. return names;
  13755. };
  13756. EventEmitter2.prototype.listeners = function listeners(event) {
  13757. var evt = prefix ? prefix + event : event, handlers = this._events[evt];
  13758. if (!handlers)
  13759. return [];
  13760. if (handlers.fn)
  13761. return [handlers.fn];
  13762. for (var i2 = 0, l2 = handlers.length, ee2 = new Array(l2); i2 < l2; i2++) {
  13763. ee2[i2] = handlers[i2].fn;
  13764. }
  13765. return ee2;
  13766. };
  13767. EventEmitter2.prototype.listenerCount = function listenerCount(event) {
  13768. var evt = prefix ? prefix + event : event, listeners = this._events[evt];
  13769. if (!listeners)
  13770. return 0;
  13771. if (listeners.fn)
  13772. return 1;
  13773. return listeners.length;
  13774. };
  13775. EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  13776. var evt = prefix ? prefix + event : event;
  13777. if (!this._events[evt])
  13778. return false;
  13779. var listeners = this._events[evt], len = arguments.length, args, i2;
  13780. if (listeners.fn) {
  13781. if (listeners.once)
  13782. this.removeListener(event, listeners.fn, void 0, true);
  13783. switch (len) {
  13784. case 1:
  13785. return listeners.fn.call(listeners.context), true;
  13786. case 2:
  13787. return listeners.fn.call(listeners.context, a1), true;
  13788. case 3:
  13789. return listeners.fn.call(listeners.context, a1, a2), true;
  13790. case 4:
  13791. return listeners.fn.call(listeners.context, a1, a2, a3), true;
  13792. case 5:
  13793. return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  13794. case 6:
  13795. return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  13796. }
  13797. for (i2 = 1, args = new Array(len - 1); i2 < len; i2++) {
  13798. args[i2 - 1] = arguments[i2];
  13799. }
  13800. listeners.fn.apply(listeners.context, args);
  13801. } else {
  13802. var length = listeners.length, j2;
  13803. for (i2 = 0; i2 < length; i2++) {
  13804. if (listeners[i2].once)
  13805. this.removeListener(event, listeners[i2].fn, void 0, true);
  13806. switch (len) {
  13807. case 1:
  13808. listeners[i2].fn.call(listeners[i2].context);
  13809. break;
  13810. case 2:
  13811. listeners[i2].fn.call(listeners[i2].context, a1);
  13812. break;
  13813. case 3:
  13814. listeners[i2].fn.call(listeners[i2].context, a1, a2);
  13815. break;
  13816. case 4:
  13817. listeners[i2].fn.call(listeners[i2].context, a1, a2, a3);
  13818. break;
  13819. default:
  13820. if (!args)
  13821. for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) {
  13822. args[j2 - 1] = arguments[j2];
  13823. }
  13824. listeners[i2].fn.apply(listeners[i2].context, args);
  13825. }
  13826. }
  13827. }
  13828. return true;
  13829. };
  13830. EventEmitter2.prototype.on = function on(event, fn, context) {
  13831. return addListener(this, event, fn, context, false);
  13832. };
  13833. EventEmitter2.prototype.once = function once(event, fn, context) {
  13834. return addListener(this, event, fn, context, true);
  13835. };
  13836. EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
  13837. var evt = prefix ? prefix + event : event;
  13838. if (!this._events[evt])
  13839. return this;
  13840. if (!fn) {
  13841. clearEvent(this, evt);
  13842. return this;
  13843. }
  13844. var listeners = this._events[evt];
  13845. if (listeners.fn) {
  13846. if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
  13847. clearEvent(this, evt);
  13848. }
  13849. } else {
  13850. for (var i2 = 0, events = [], length = listeners.length; i2 < length; i2++) {
  13851. if (listeners[i2].fn !== fn || once && !listeners[i2].once || context && listeners[i2].context !== context) {
  13852. events.push(listeners[i2]);
  13853. }
  13854. }
  13855. if (events.length)
  13856. this._events[evt] = events.length === 1 ? events[0] : events;
  13857. else
  13858. clearEvent(this, evt);
  13859. }
  13860. return this;
  13861. };
  13862. EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
  13863. var evt;
  13864. if (event) {
  13865. evt = prefix ? prefix + event : event;
  13866. if (this._events[evt])
  13867. clearEvent(this, evt);
  13868. } else {
  13869. this._events = new Events2();
  13870. this._eventsCount = 0;
  13871. }
  13872. return this;
  13873. };
  13874. EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
  13875. EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
  13876. EventEmitter2.prefixed = prefix;
  13877. EventEmitter2.EventEmitter = EventEmitter2;
  13878. {
  13879. module.exports = EventEmitter2;
  13880. }
  13881. })(eventemitter3);
  13882. return eventemitter3.exports;
  13883. }
  13884. var eventemitter3Exports = requireEventemitter3();
  13885. var EventEmitter = /* @__PURE__ */ getDefaultExportFromCjs$1(eventemitter3Exports);
  13886. const version = "1.6.7";
  13887. const workerStore = {};
  13888. function hasUMDWorker() {
  13889. return typeof __HLS_WORKER_BUNDLE__ === "function";
  13890. }
  13891. function injectWorker() {
  13892. const workerContext = workerStore[version];
  13893. if (workerContext) {
  13894. workerContext.clientCount++;
  13895. return workerContext;
  13896. }
  13897. const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
  13898. type: "text/javascript"
  13899. });
  13900. const objectURL = self.URL.createObjectURL(blob);
  13901. const worker = new self.Worker(objectURL);
  13902. const result = {
  13903. worker,
  13904. objectURL,
  13905. clientCount: 1
  13906. };
  13907. workerStore[version] = result;
  13908. return result;
  13909. }
  13910. function loadWorker(path) {
  13911. const workerContext = workerStore[path];
  13912. if (workerContext) {
  13913. workerContext.clientCount++;
  13914. return workerContext;
  13915. }
  13916. const scriptURL = new self.URL(path, self.location.href).href;
  13917. const worker = new self.Worker(scriptURL);
  13918. const result = {
  13919. worker,
  13920. scriptURL,
  13921. clientCount: 1
  13922. };
  13923. workerStore[path] = result;
  13924. return result;
  13925. }
  13926. function removeWorkerFromStore(path) {
  13927. const workerContext = workerStore[path || version];
  13928. if (workerContext) {
  13929. const clientCount = workerContext.clientCount--;
  13930. if (clientCount === 1) {
  13931. const {
  13932. worker,
  13933. objectURL
  13934. } = workerContext;
  13935. delete workerStore[path || version];
  13936. if (objectURL) {
  13937. self.URL.revokeObjectURL(objectURL);
  13938. }
  13939. worker.terminate();
  13940. }
  13941. }
  13942. }
  13943. function isId3Footer(data, offset) {
  13944. if (offset + 10 <= data.length) {
  13945. if (data[offset] === 51 && data[offset + 1] === 68 && data[offset + 2] === 73) {
  13946. if (data[offset + 3] < 255 && data[offset + 4] < 255) {
  13947. if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
  13948. return true;
  13949. }
  13950. }
  13951. }
  13952. }
  13953. return false;
  13954. }
  13955. function isId3Header(data, offset) {
  13956. if (offset + 10 <= data.length) {
  13957. if (data[offset] === 73 && data[offset + 1] === 68 && data[offset + 2] === 51) {
  13958. if (data[offset + 3] < 255 && data[offset + 4] < 255) {
  13959. if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
  13960. return true;
  13961. }
  13962. }
  13963. }
  13964. }
  13965. return false;
  13966. }
  13967. function readId3Size(data, offset) {
  13968. let size = 0;
  13969. size = (data[offset] & 127) << 21;
  13970. size |= (data[offset + 1] & 127) << 14;
  13971. size |= (data[offset + 2] & 127) << 7;
  13972. size |= data[offset + 3] & 127;
  13973. return size;
  13974. }
  13975. function getId3Data(data, offset) {
  13976. const front = offset;
  13977. let length = 0;
  13978. while (isId3Header(data, offset)) {
  13979. length += 10;
  13980. const size = readId3Size(data, offset + 6);
  13981. length += size;
  13982. if (isId3Footer(data, offset + 10)) {
  13983. length += 10;
  13984. }
  13985. offset += length;
  13986. }
  13987. if (length > 0) {
  13988. return data.subarray(front, front + length);
  13989. }
  13990. return void 0;
  13991. }
  13992. function getAudioConfig(observer, data, offset, manifestCodec) {
  13993. const adtsSamplingRates = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
  13994. const byte2 = data[offset + 2];
  13995. const adtsSamplingIndex = byte2 >> 2 & 15;
  13996. if (adtsSamplingIndex > 12) {
  13997. const error2 = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);
  13998. observer.emit(Events.ERROR, Events.ERROR, {
  13999. type: ErrorTypes.MEDIA_ERROR,
  14000. details: ErrorDetails.FRAG_PARSING_ERROR,
  14001. fatal: true,
  14002. error: error2,
  14003. reason: error2.message
  14004. });
  14005. return;
  14006. }
  14007. const adtsObjectType = (byte2 >> 6 & 3) + 1;
  14008. const channelCount = data[offset + 3] >> 6 & 3 | (byte2 & 1) << 2;
  14009. const codec = "mp4a.40." + adtsObjectType;
  14010. const samplerate = adtsSamplingRates[adtsSamplingIndex];
  14011. let aacSampleIndex = adtsSamplingIndex;
  14012. if (adtsObjectType === 5 || adtsObjectType === 29) {
  14013. aacSampleIndex -= 3;
  14014. }
  14015. const config2 = [adtsObjectType << 3 | (aacSampleIndex & 14) >> 1, (aacSampleIndex & 1) << 7 | channelCount << 3];
  14016. logger.log(`manifest codec:${manifestCodec}, parsed codec:${codec}, channels:${channelCount}, rate:${samplerate} (ADTS object type:${adtsObjectType} sampling index:${adtsSamplingIndex})`);
  14017. return {
  14018. config: config2,
  14019. samplerate,
  14020. channelCount,
  14021. codec,
  14022. parsedCodec: codec,
  14023. manifestCodec
  14024. };
  14025. }
  14026. function isHeaderPattern$1(data, offset) {
  14027. return data[offset] === 255 && (data[offset + 1] & 246) === 240;
  14028. }
  14029. function getHeaderLength(data, offset) {
  14030. return data[offset + 1] & 1 ? 7 : 9;
  14031. }
  14032. function getFullFrameLength(data, offset) {
  14033. return (data[offset + 3] & 3) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 224) >>> 5;
  14034. }
  14035. function canGetFrameLength(data, offset) {
  14036. return offset + 5 < data.length;
  14037. }
  14038. function isHeader$1(data, offset) {
  14039. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  14040. }
  14041. function canParse$1(data, offset) {
  14042. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  14043. }
  14044. function probe$1(data, offset) {
  14045. if (isHeader$1(data, offset)) {
  14046. const headerLength = getHeaderLength(data, offset);
  14047. if (offset + headerLength >= data.length) {
  14048. return false;
  14049. }
  14050. const frameLength = getFullFrameLength(data, offset);
  14051. if (frameLength <= headerLength) {
  14052. return false;
  14053. }
  14054. const newOffset = offset + frameLength;
  14055. return newOffset === data.length || isHeader$1(data, newOffset);
  14056. }
  14057. return false;
  14058. }
  14059. function initTrackConfig(track, observer, data, offset, audioCodec) {
  14060. if (!track.samplerate) {
  14061. const config2 = getAudioConfig(observer, data, offset, audioCodec);
  14062. if (!config2) {
  14063. return;
  14064. }
  14065. _extends(track, config2);
  14066. }
  14067. }
  14068. function getFrameDuration(samplerate) {
  14069. return 1024 * 9e4 / samplerate;
  14070. }
  14071. function parseFrameHeader(data, offset) {
  14072. const headerLength = getHeaderLength(data, offset);
  14073. if (offset + headerLength <= data.length) {
  14074. const frameLength = getFullFrameLength(data, offset) - headerLength;
  14075. if (frameLength > 0) {
  14076. return {
  14077. headerLength,
  14078. frameLength
  14079. };
  14080. }
  14081. }
  14082. }
  14083. function appendFrame$2(track, data, offset, pts, frameIndex) {
  14084. const frameDuration = getFrameDuration(track.samplerate);
  14085. const stamp = pts + frameIndex * frameDuration;
  14086. const header = parseFrameHeader(data, offset);
  14087. let unit;
  14088. if (header) {
  14089. const {
  14090. frameLength,
  14091. headerLength
  14092. } = header;
  14093. const _length = headerLength + frameLength;
  14094. const missing = Math.max(0, offset + _length - data.length);
  14095. if (missing) {
  14096. unit = new Uint8Array(_length - headerLength);
  14097. unit.set(data.subarray(offset + headerLength, data.length), 0);
  14098. } else {
  14099. unit = data.subarray(offset + headerLength, offset + _length);
  14100. }
  14101. const _sample = {
  14102. unit,
  14103. pts: stamp
  14104. };
  14105. if (!missing) {
  14106. track.samples.push(_sample);
  14107. }
  14108. return {
  14109. sample: _sample,
  14110. length: _length,
  14111. missing
  14112. };
  14113. }
  14114. const length = data.length - offset;
  14115. unit = new Uint8Array(length);
  14116. unit.set(data.subarray(offset, data.length), 0);
  14117. const sample = {
  14118. unit,
  14119. pts: stamp
  14120. };
  14121. return {
  14122. sample,
  14123. length,
  14124. missing: -1
  14125. };
  14126. }
  14127. function canParseId3(data, offset) {
  14128. return isId3Header(data, offset) && readId3Size(data, offset + 6) + 10 <= data.length - offset;
  14129. }
  14130. function toArrayBuffer(view2) {
  14131. if (view2 instanceof ArrayBuffer) {
  14132. return view2;
  14133. } else {
  14134. if (view2.byteOffset == 0 && view2.byteLength == view2.buffer.byteLength) {
  14135. return view2.buffer;
  14136. }
  14137. return new Uint8Array(view2).buffer;
  14138. }
  14139. }
  14140. function toUint8(data, offset = 0, length = Infinity) {
  14141. return view(data, offset, length, Uint8Array);
  14142. }
  14143. function view(data, offset, length, Type) {
  14144. const buffer = unsafeGetArrayBuffer(data);
  14145. let bytesPerElement = 1;
  14146. if ("BYTES_PER_ELEMENT" in Type) {
  14147. bytesPerElement = Type.BYTES_PER_ELEMENT;
  14148. }
  14149. const dataOffset = isArrayBufferView(data) ? data.byteOffset : 0;
  14150. const dataEnd = (dataOffset + data.byteLength) / bytesPerElement;
  14151. const rawStart = (dataOffset + offset) / bytesPerElement;
  14152. const start = Math.floor(Math.max(0, Math.min(rawStart, dataEnd)));
  14153. const end = Math.floor(Math.min(start + Math.max(length, 0), dataEnd));
  14154. return new Type(buffer, start, end - start);
  14155. }
  14156. function unsafeGetArrayBuffer(view2) {
  14157. if (view2 instanceof ArrayBuffer) {
  14158. return view2;
  14159. } else {
  14160. return view2.buffer;
  14161. }
  14162. }
  14163. function isArrayBufferView(obj) {
  14164. return obj && obj.buffer instanceof ArrayBuffer && obj.byteLength !== void 0 && obj.byteOffset !== void 0;
  14165. }
  14166. function decodeId3ImageFrame(frame) {
  14167. const metadataFrame = {
  14168. key: frame.type,
  14169. description: "",
  14170. data: "",
  14171. mimeType: null,
  14172. pictureType: null
  14173. };
  14174. const utf8Encoding = 3;
  14175. if (frame.size < 2) {
  14176. return void 0;
  14177. }
  14178. if (frame.data[0] !== utf8Encoding) {
  14179. formatAppLog("log", "at node_modules/hls.js/dist/hls.mjs:10637", "Ignore frame with unrecognized character encoding");
  14180. return void 0;
  14181. }
  14182. const mimeTypeEndIndex = frame.data.subarray(1).indexOf(0);
  14183. if (mimeTypeEndIndex === -1) {
  14184. return void 0;
  14185. }
  14186. const mimeType = utf8ArrayToStr(toUint8(frame.data, 1, mimeTypeEndIndex));
  14187. const pictureType = frame.data[2 + mimeTypeEndIndex];
  14188. const descriptionEndIndex = frame.data.subarray(3 + mimeTypeEndIndex).indexOf(0);
  14189. if (descriptionEndIndex === -1) {
  14190. return void 0;
  14191. }
  14192. const description = utf8ArrayToStr(toUint8(frame.data, 3 + mimeTypeEndIndex, descriptionEndIndex));
  14193. let data;
  14194. if (mimeType === "-->") {
  14195. data = utf8ArrayToStr(toUint8(frame.data, 4 + mimeTypeEndIndex + descriptionEndIndex));
  14196. } else {
  14197. data = toArrayBuffer(frame.data.subarray(4 + mimeTypeEndIndex + descriptionEndIndex));
  14198. }
  14199. metadataFrame.mimeType = mimeType;
  14200. metadataFrame.pictureType = pictureType;
  14201. metadataFrame.description = description;
  14202. metadataFrame.data = data;
  14203. return metadataFrame;
  14204. }
  14205. function decodeId3PrivFrame(frame) {
  14206. if (frame.size < 2) {
  14207. return void 0;
  14208. }
  14209. const owner = utf8ArrayToStr(frame.data, true);
  14210. const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  14211. return {
  14212. key: frame.type,
  14213. info: owner,
  14214. data: privateData.buffer
  14215. };
  14216. }
  14217. function decodeId3TextFrame(frame) {
  14218. if (frame.size < 2) {
  14219. return void 0;
  14220. }
  14221. if (frame.type === "TXXX") {
  14222. let index2 = 1;
  14223. const description = utf8ArrayToStr(frame.data.subarray(index2), true);
  14224. index2 += description.length + 1;
  14225. const value2 = utf8ArrayToStr(frame.data.subarray(index2));
  14226. return {
  14227. key: frame.type,
  14228. info: description,
  14229. data: value2
  14230. };
  14231. }
  14232. const text = utf8ArrayToStr(frame.data.subarray(1));
  14233. return {
  14234. key: frame.type,
  14235. info: "",
  14236. data: text
  14237. };
  14238. }
  14239. function decodeId3UrlFrame(frame) {
  14240. if (frame.type === "WXXX") {
  14241. if (frame.size < 2) {
  14242. return void 0;
  14243. }
  14244. let index2 = 1;
  14245. const description = utf8ArrayToStr(frame.data.subarray(index2), true);
  14246. index2 += description.length + 1;
  14247. const value2 = utf8ArrayToStr(frame.data.subarray(index2));
  14248. return {
  14249. key: frame.type,
  14250. info: description,
  14251. data: value2
  14252. };
  14253. }
  14254. const url2 = utf8ArrayToStr(frame.data);
  14255. return {
  14256. key: frame.type,
  14257. info: "",
  14258. data: url2
  14259. };
  14260. }
  14261. function decodeId3Frame(frame) {
  14262. if (frame.type === "PRIV") {
  14263. return decodeId3PrivFrame(frame);
  14264. } else if (frame.type[0] === "W") {
  14265. return decodeId3UrlFrame(frame);
  14266. } else if (frame.type === "APIC") {
  14267. return decodeId3ImageFrame(frame);
  14268. }
  14269. return decodeId3TextFrame(frame);
  14270. }
  14271. function getId3FrameData(data) {
  14272. const type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  14273. const size = readId3Size(data, 4);
  14274. const offset = 10;
  14275. return {
  14276. type,
  14277. size,
  14278. data: data.subarray(offset, offset + size)
  14279. };
  14280. }
  14281. const HEADER_FOOTER_SIZE = 10;
  14282. const FRAME_SIZE = 10;
  14283. function getId3Frames(id3Data) {
  14284. let offset = 0;
  14285. const frames = [];
  14286. while (isId3Header(id3Data, offset)) {
  14287. const size = readId3Size(id3Data, offset + 6);
  14288. if (id3Data[offset + 5] >> 6 & 1) {
  14289. offset += HEADER_FOOTER_SIZE;
  14290. }
  14291. offset += HEADER_FOOTER_SIZE;
  14292. const end = offset + size;
  14293. while (offset + FRAME_SIZE < end) {
  14294. const frameData = getId3FrameData(id3Data.subarray(offset));
  14295. const frame = decodeId3Frame(frameData);
  14296. if (frame) {
  14297. frames.push(frame);
  14298. }
  14299. offset += frameData.size + HEADER_FOOTER_SIZE;
  14300. }
  14301. if (isId3Footer(id3Data, offset)) {
  14302. offset += HEADER_FOOTER_SIZE;
  14303. }
  14304. }
  14305. return frames;
  14306. }
  14307. function isId3TimestampFrame(frame) {
  14308. return frame && frame.key === "PRIV" && frame.info === "com.apple.streaming.transportStreamTimestamp";
  14309. }
  14310. function readId3Timestamp(timeStampFrame) {
  14311. if (timeStampFrame.data.byteLength === 8) {
  14312. const data = new Uint8Array(timeStampFrame.data);
  14313. const pts33Bit = data[3] & 1;
  14314. let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  14315. timestamp /= 45;
  14316. if (pts33Bit) {
  14317. timestamp += 4772185884e-2;
  14318. }
  14319. return Math.round(timestamp);
  14320. }
  14321. return void 0;
  14322. }
  14323. function getId3Timestamp(data) {
  14324. const frames = getId3Frames(data);
  14325. for (let i2 = 0; i2 < frames.length; i2++) {
  14326. const frame = frames[i2];
  14327. if (isId3TimestampFrame(frame)) {
  14328. return readId3Timestamp(frame);
  14329. }
  14330. }
  14331. return void 0;
  14332. }
  14333. let MetadataSchema = /* @__PURE__ */ function(MetadataSchema2) {
  14334. MetadataSchema2["audioId3"] = "org.id3";
  14335. MetadataSchema2["dateRange"] = "com.apple.quicktime.HLS";
  14336. MetadataSchema2["emsg"] = "https://aomedia.org/emsg/ID3";
  14337. MetadataSchema2["misbklv"] = "urn:misb:KLV:bin:1910.1";
  14338. return MetadataSchema2;
  14339. }({});
  14340. function dummyTrack(type = "", inputTimeScale = 9e4) {
  14341. return {
  14342. type,
  14343. id: -1,
  14344. pid: -1,
  14345. inputTimeScale,
  14346. sequenceNumber: -1,
  14347. samples: [],
  14348. dropped: 0
  14349. };
  14350. }
  14351. class BaseAudioDemuxer {
  14352. constructor() {
  14353. this._audioTrack = void 0;
  14354. this._id3Track = void 0;
  14355. this.frameIndex = 0;
  14356. this.cachedData = null;
  14357. this.basePTS = null;
  14358. this.initPTS = null;
  14359. this.lastPTS = null;
  14360. }
  14361. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  14362. this._id3Track = {
  14363. type: "id3",
  14364. id: 3,
  14365. pid: -1,
  14366. inputTimeScale: 9e4,
  14367. sequenceNumber: 0,
  14368. samples: [],
  14369. dropped: 0
  14370. };
  14371. }
  14372. resetTimeStamp(deaultTimestamp) {
  14373. this.initPTS = deaultTimestamp;
  14374. this.resetContiguity();
  14375. }
  14376. resetContiguity() {
  14377. this.basePTS = null;
  14378. this.lastPTS = null;
  14379. this.frameIndex = 0;
  14380. }
  14381. canParse(data, offset) {
  14382. return false;
  14383. }
  14384. appendFrame(track, data, offset) {
  14385. }
  14386. // feed incoming data to the front of the parsing pipeline
  14387. demux(data, timeOffset) {
  14388. if (this.cachedData) {
  14389. data = appendUint8Array(this.cachedData, data);
  14390. this.cachedData = null;
  14391. }
  14392. let id3Data = getId3Data(data, 0);
  14393. let offset = id3Data ? id3Data.length : 0;
  14394. let lastDataIndex;
  14395. const track = this._audioTrack;
  14396. const id3Track = this._id3Track;
  14397. const timestamp = id3Data ? getId3Timestamp(id3Data) : void 0;
  14398. const length = data.length;
  14399. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  14400. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  14401. this.lastPTS = this.basePTS;
  14402. }
  14403. if (this.lastPTS === null) {
  14404. this.lastPTS = this.basePTS;
  14405. }
  14406. if (id3Data && id3Data.length > 0) {
  14407. id3Track.samples.push({
  14408. pts: this.lastPTS,
  14409. dts: this.lastPTS,
  14410. data: id3Data,
  14411. type: MetadataSchema.audioId3,
  14412. duration: Number.POSITIVE_INFINITY
  14413. });
  14414. }
  14415. while (offset < length) {
  14416. if (this.canParse(data, offset)) {
  14417. const frame = this.appendFrame(track, data, offset);
  14418. if (frame) {
  14419. this.frameIndex++;
  14420. this.lastPTS = frame.sample.pts;
  14421. offset += frame.length;
  14422. lastDataIndex = offset;
  14423. } else {
  14424. offset = length;
  14425. }
  14426. } else if (canParseId3(data, offset)) {
  14427. id3Data = getId3Data(data, offset);
  14428. id3Track.samples.push({
  14429. pts: this.lastPTS,
  14430. dts: this.lastPTS,
  14431. data: id3Data,
  14432. type: MetadataSchema.audioId3,
  14433. duration: Number.POSITIVE_INFINITY
  14434. });
  14435. offset += id3Data.length;
  14436. lastDataIndex = offset;
  14437. } else {
  14438. offset++;
  14439. }
  14440. if (offset === length && lastDataIndex !== length) {
  14441. const partialData = data.slice(lastDataIndex);
  14442. if (this.cachedData) {
  14443. this.cachedData = appendUint8Array(this.cachedData, partialData);
  14444. } else {
  14445. this.cachedData = partialData;
  14446. }
  14447. }
  14448. }
  14449. return {
  14450. audioTrack: track,
  14451. videoTrack: dummyTrack(),
  14452. id3Track,
  14453. textTrack: dummyTrack()
  14454. };
  14455. }
  14456. demuxSampleAes(data, keyData, timeOffset) {
  14457. return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  14458. }
  14459. flush(timeOffset) {
  14460. const cachedData = this.cachedData;
  14461. if (cachedData) {
  14462. this.cachedData = null;
  14463. this.demux(cachedData, 0);
  14464. }
  14465. return {
  14466. audioTrack: this._audioTrack,
  14467. videoTrack: dummyTrack(),
  14468. id3Track: this._id3Track,
  14469. textTrack: dummyTrack()
  14470. };
  14471. }
  14472. destroy() {
  14473. this.cachedData = null;
  14474. this._audioTrack = this._id3Track = void 0;
  14475. }
  14476. }
  14477. const initPTSFn = (timestamp, timeOffset, initPTS) => {
  14478. if (isFiniteNumber(timestamp)) {
  14479. return timestamp * 90;
  14480. }
  14481. const init90kHz = initPTS ? initPTS.baseTime * 9e4 / initPTS.timescale : 0;
  14482. return timeOffset * 9e4 + init90kHz;
  14483. };
  14484. let chromeVersion$1 = null;
  14485. 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];
  14486. const SamplingRateMap = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3];
  14487. const SamplesCoefficients = [
  14488. // MPEG 2.5
  14489. [
  14490. 0,
  14491. // Reserved
  14492. 72,
  14493. // Layer3
  14494. 144,
  14495. // Layer2
  14496. 12
  14497. // Layer1
  14498. ],
  14499. // Reserved
  14500. [
  14501. 0,
  14502. // Reserved
  14503. 0,
  14504. // Layer3
  14505. 0,
  14506. // Layer2
  14507. 0
  14508. // Layer1
  14509. ],
  14510. // MPEG 2
  14511. [
  14512. 0,
  14513. // Reserved
  14514. 72,
  14515. // Layer3
  14516. 144,
  14517. // Layer2
  14518. 12
  14519. // Layer1
  14520. ],
  14521. // MPEG 1
  14522. [
  14523. 0,
  14524. // Reserved
  14525. 144,
  14526. // Layer3
  14527. 144,
  14528. // Layer2
  14529. 12
  14530. // Layer1
  14531. ]
  14532. ];
  14533. const BytesInSlot = [
  14534. 0,
  14535. // Reserved
  14536. 1,
  14537. // Layer3
  14538. 1,
  14539. // Layer2
  14540. 4
  14541. // Layer1
  14542. ];
  14543. function appendFrame$1(track, data, offset, pts, frameIndex) {
  14544. if (offset + 24 > data.length) {
  14545. return;
  14546. }
  14547. const header = parseHeader(data, offset);
  14548. if (header && offset + header.frameLength <= data.length) {
  14549. const frameDuration = header.samplesPerFrame * 9e4 / header.sampleRate;
  14550. const stamp = pts + frameIndex * frameDuration;
  14551. const sample = {
  14552. unit: data.subarray(offset, offset + header.frameLength),
  14553. pts: stamp,
  14554. dts: stamp
  14555. };
  14556. track.config = [];
  14557. track.channelCount = header.channelCount;
  14558. track.samplerate = header.sampleRate;
  14559. track.samples.push(sample);
  14560. return {
  14561. sample,
  14562. length: header.frameLength,
  14563. missing: 0
  14564. };
  14565. }
  14566. }
  14567. function parseHeader(data, offset) {
  14568. const mpegVersion = data[offset + 1] >> 3 & 3;
  14569. const mpegLayer = data[offset + 1] >> 1 & 3;
  14570. const bitRateIndex = data[offset + 2] >> 4 & 15;
  14571. const sampleRateIndex = data[offset + 2] >> 2 & 3;
  14572. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  14573. const paddingBit = data[offset + 2] >> 1 & 1;
  14574. const channelMode = data[offset + 3] >> 6;
  14575. const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  14576. const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1e3;
  14577. const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  14578. const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  14579. const channelCount = channelMode === 3 ? 1 : 2;
  14580. const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  14581. const bytesInSlot = BytesInSlot[mpegLayer];
  14582. const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  14583. const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  14584. if (chromeVersion$1 === null) {
  14585. const userAgent = navigator.userAgent || "";
  14586. const result = userAgent.match(/Chrome\/(\d+)/i);
  14587. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  14588. }
  14589. const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  14590. if (needChromeFix && mpegLayer === 2 && bitRate >= 224e3 && channelMode === 0) {
  14591. data[offset + 3] = data[offset + 3] | 128;
  14592. }
  14593. return {
  14594. sampleRate,
  14595. channelCount,
  14596. frameLength,
  14597. samplesPerFrame
  14598. };
  14599. }
  14600. }
  14601. function isHeaderPattern(data, offset) {
  14602. return data[offset] === 255 && (data[offset + 1] & 224) === 224 && (data[offset + 1] & 6) !== 0;
  14603. }
  14604. function isHeader(data, offset) {
  14605. return offset + 1 < data.length && isHeaderPattern(data, offset);
  14606. }
  14607. function canParse(data, offset) {
  14608. const headerSize = 4;
  14609. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  14610. }
  14611. function probe(data, offset) {
  14612. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  14613. const headerLength = 4;
  14614. const header = parseHeader(data, offset);
  14615. let frameLength = headerLength;
  14616. if (header != null && header.frameLength) {
  14617. frameLength = header.frameLength;
  14618. }
  14619. const newOffset = offset + frameLength;
  14620. return newOffset === data.length || isHeader(data, newOffset);
  14621. }
  14622. return false;
  14623. }
  14624. class AACDemuxer extends BaseAudioDemuxer {
  14625. constructor(observer, config2) {
  14626. super();
  14627. this.observer = void 0;
  14628. this.config = void 0;
  14629. this.observer = observer;
  14630. this.config = config2;
  14631. }
  14632. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  14633. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  14634. this._audioTrack = {
  14635. container: "audio/adts",
  14636. type: "audio",
  14637. id: 2,
  14638. pid: -1,
  14639. sequenceNumber: 0,
  14640. segmentCodec: "aac",
  14641. samples: [],
  14642. manifestCodec: audioCodec,
  14643. duration: trackDuration,
  14644. inputTimeScale: 9e4,
  14645. dropped: 0
  14646. };
  14647. }
  14648. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  14649. static probe(data, logger2) {
  14650. if (!data) {
  14651. return false;
  14652. }
  14653. const id3Data = getId3Data(data, 0);
  14654. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  14655. if (probe(data, offset)) {
  14656. return false;
  14657. }
  14658. for (let length = data.length; offset < length; offset++) {
  14659. if (probe$1(data, offset)) {
  14660. logger2.log("ADTS sync word found !");
  14661. return true;
  14662. }
  14663. }
  14664. return false;
  14665. }
  14666. canParse(data, offset) {
  14667. return canParse$1(data, offset);
  14668. }
  14669. appendFrame(track, data, offset) {
  14670. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  14671. const frame = appendFrame$2(track, data, offset, this.basePTS, this.frameIndex);
  14672. if (frame && frame.missing === 0) {
  14673. return frame;
  14674. }
  14675. }
  14676. }
  14677. const getAudioBSID = (data, offset) => {
  14678. let bsid = 0;
  14679. let numBits = 5;
  14680. offset += numBits;
  14681. const temp = new Uint32Array(1);
  14682. const mask = new Uint32Array(1);
  14683. const byte = new Uint8Array(1);
  14684. while (numBits > 0) {
  14685. byte[0] = data[offset];
  14686. const bits = Math.min(numBits, 8);
  14687. const shift = 8 - bits;
  14688. mask[0] = 4278190080 >>> 24 + shift << shift;
  14689. temp[0] = (byte[0] & mask[0]) >> shift;
  14690. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  14691. offset += 1;
  14692. numBits -= bits;
  14693. }
  14694. return bsid;
  14695. };
  14696. class AC3Demuxer extends BaseAudioDemuxer {
  14697. constructor(observer) {
  14698. super();
  14699. this.observer = void 0;
  14700. this.observer = observer;
  14701. }
  14702. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  14703. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  14704. this._audioTrack = {
  14705. container: "audio/ac-3",
  14706. type: "audio",
  14707. id: 2,
  14708. pid: -1,
  14709. sequenceNumber: 0,
  14710. segmentCodec: "ac3",
  14711. samples: [],
  14712. manifestCodec: audioCodec,
  14713. duration: trackDuration,
  14714. inputTimeScale: 9e4,
  14715. dropped: 0
  14716. };
  14717. }
  14718. canParse(data, offset) {
  14719. return offset + 64 < data.length;
  14720. }
  14721. appendFrame(track, data, offset) {
  14722. const frameLength = appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  14723. if (frameLength !== -1) {
  14724. const sample = track.samples[track.samples.length - 1];
  14725. return {
  14726. sample,
  14727. length: frameLength,
  14728. missing: 0
  14729. };
  14730. }
  14731. }
  14732. static probe(data) {
  14733. if (!data) {
  14734. return false;
  14735. }
  14736. const id3Data = getId3Data(data, 0);
  14737. if (!id3Data) {
  14738. return false;
  14739. }
  14740. const offset = id3Data.length;
  14741. if (data[offset] === 11 && data[offset + 1] === 119 && getId3Timestamp(id3Data) !== void 0 && // check the bsid to confirm ac-3
  14742. getAudioBSID(data, offset) < 16) {
  14743. return true;
  14744. }
  14745. return false;
  14746. }
  14747. }
  14748. function appendFrame(track, data, start, pts, frameIndex) {
  14749. if (start + 8 > data.length) {
  14750. return -1;
  14751. }
  14752. if (data[start] !== 11 || data[start + 1] !== 119) {
  14753. return -1;
  14754. }
  14755. const samplingRateCode = data[start + 4] >> 6;
  14756. if (samplingRateCode >= 3) {
  14757. return -1;
  14758. }
  14759. const samplingRateMap = [48e3, 44100, 32e3];
  14760. const sampleRate = samplingRateMap[samplingRateCode];
  14761. const frameSizeCode = data[start + 4] & 63;
  14762. 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];
  14763. const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;
  14764. if (start + frameLength > data.length) {
  14765. return -1;
  14766. }
  14767. const channelMode = data[start + 6] >> 5;
  14768. let skipCount = 0;
  14769. if (channelMode === 2) {
  14770. skipCount += 2;
  14771. } else {
  14772. if (channelMode & 1 && channelMode !== 1) {
  14773. skipCount += 2;
  14774. }
  14775. if (channelMode & 4) {
  14776. skipCount += 2;
  14777. }
  14778. }
  14779. const lfeon = (data[start + 6] << 8 | data[start + 7]) >> 12 - skipCount & 1;
  14780. const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];
  14781. const channelCount = channelsMap[channelMode] + lfeon;
  14782. const bsid = data[start + 5] >> 3;
  14783. const bsmod = data[start + 5] & 7;
  14784. const config2 = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 224]);
  14785. const frameDuration = 1536 / sampleRate * 9e4;
  14786. const stamp = pts + frameIndex * frameDuration;
  14787. const unit = data.subarray(start, start + frameLength);
  14788. track.config = config2;
  14789. track.channelCount = channelCount;
  14790. track.samplerate = sampleRate;
  14791. track.samples.push({
  14792. unit,
  14793. pts: stamp
  14794. });
  14795. return frameLength;
  14796. }
  14797. class MP3Demuxer extends BaseAudioDemuxer {
  14798. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  14799. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  14800. this._audioTrack = {
  14801. container: "audio/mpeg",
  14802. type: "audio",
  14803. id: 2,
  14804. pid: -1,
  14805. sequenceNumber: 0,
  14806. segmentCodec: "mp3",
  14807. samples: [],
  14808. manifestCodec: audioCodec,
  14809. duration: trackDuration,
  14810. inputTimeScale: 9e4,
  14811. dropped: 0
  14812. };
  14813. }
  14814. static probe(data) {
  14815. if (!data) {
  14816. return false;
  14817. }
  14818. const id3Data = getId3Data(data, 0);
  14819. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  14820. 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)
  14821. getAudioBSID(data, offset) <= 16) {
  14822. return false;
  14823. }
  14824. for (let length = data.length; offset < length; offset++) {
  14825. if (probe(data, offset)) {
  14826. logger.log("MPEG Audio sync word found !");
  14827. return true;
  14828. }
  14829. }
  14830. return false;
  14831. }
  14832. canParse(data, offset) {
  14833. return canParse(data, offset);
  14834. }
  14835. appendFrame(track, data, offset) {
  14836. if (this.basePTS === null) {
  14837. return;
  14838. }
  14839. return appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  14840. }
  14841. }
  14842. const emsgSchemePattern = /\/emsg[-/]ID3/i;
  14843. class MP4Demuxer {
  14844. constructor(observer, config2) {
  14845. this.remainderData = null;
  14846. this.timeOffset = 0;
  14847. this.config = void 0;
  14848. this.videoTrack = void 0;
  14849. this.audioTrack = void 0;
  14850. this.id3Track = void 0;
  14851. this.txtTrack = void 0;
  14852. this.config = config2;
  14853. }
  14854. resetTimeStamp() {
  14855. }
  14856. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  14857. const videoTrack = this.videoTrack = dummyTrack("video", 1);
  14858. const audioTrack = this.audioTrack = dummyTrack("audio", 1);
  14859. const captionTrack = this.txtTrack = dummyTrack("text", 1);
  14860. this.id3Track = dummyTrack("id3", 1);
  14861. this.timeOffset = 0;
  14862. if (!(initSegment != null && initSegment.byteLength)) {
  14863. return;
  14864. }
  14865. const initData = parseInitSegment(initSegment);
  14866. if (initData.video) {
  14867. const {
  14868. id,
  14869. timescale,
  14870. codec,
  14871. supplemental
  14872. } = initData.video;
  14873. videoTrack.id = id;
  14874. videoTrack.timescale = captionTrack.timescale = timescale;
  14875. videoTrack.codec = codec;
  14876. videoTrack.supplemental = supplemental;
  14877. }
  14878. if (initData.audio) {
  14879. const {
  14880. id,
  14881. timescale,
  14882. codec
  14883. } = initData.audio;
  14884. audioTrack.id = id;
  14885. audioTrack.timescale = timescale;
  14886. audioTrack.codec = codec;
  14887. }
  14888. captionTrack.id = RemuxerTrackIdConfig.text;
  14889. videoTrack.sampleDuration = 0;
  14890. videoTrack.duration = audioTrack.duration = trackDuration;
  14891. }
  14892. resetContiguity() {
  14893. this.remainderData = null;
  14894. }
  14895. static probe(data) {
  14896. return hasMoofData(data);
  14897. }
  14898. demux(data, timeOffset) {
  14899. this.timeOffset = timeOffset;
  14900. let videoSamples = data;
  14901. const videoTrack = this.videoTrack;
  14902. const textTrack = this.txtTrack;
  14903. if (this.config.progressive) {
  14904. if (this.remainderData) {
  14905. videoSamples = appendUint8Array(this.remainderData, data);
  14906. }
  14907. const segmentedData = segmentValidRange(videoSamples);
  14908. this.remainderData = segmentedData.remainder;
  14909. videoTrack.samples = segmentedData.valid || new Uint8Array();
  14910. } else {
  14911. videoTrack.samples = videoSamples;
  14912. }
  14913. const id3Track = this.extractID3Track(videoTrack, timeOffset);
  14914. textTrack.samples = parseSamples(timeOffset, videoTrack);
  14915. return {
  14916. videoTrack,
  14917. audioTrack: this.audioTrack,
  14918. id3Track,
  14919. textTrack: this.txtTrack
  14920. };
  14921. }
  14922. flush() {
  14923. const timeOffset = this.timeOffset;
  14924. const videoTrack = this.videoTrack;
  14925. const textTrack = this.txtTrack;
  14926. videoTrack.samples = this.remainderData || new Uint8Array();
  14927. this.remainderData = null;
  14928. const id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  14929. textTrack.samples = parseSamples(timeOffset, videoTrack);
  14930. return {
  14931. videoTrack,
  14932. audioTrack: dummyTrack(),
  14933. id3Track,
  14934. textTrack: dummyTrack()
  14935. };
  14936. }
  14937. extractID3Track(videoTrack, timeOffset) {
  14938. const id3Track = this.id3Track;
  14939. if (videoTrack.samples.length) {
  14940. const emsgs = findBox(videoTrack.samples, ["emsg"]);
  14941. if (emsgs) {
  14942. emsgs.forEach((data) => {
  14943. const emsgInfo = parseEmsg(data);
  14944. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  14945. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  14946. let duration = emsgInfo.eventDuration === 4294967295 ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  14947. if (duration <= 1e-3) {
  14948. duration = Number.POSITIVE_INFINITY;
  14949. }
  14950. const payload = emsgInfo.payload;
  14951. id3Track.samples.push({
  14952. data: payload,
  14953. len: payload.byteLength,
  14954. dts: pts,
  14955. pts,
  14956. type: MetadataSchema.emsg,
  14957. duration
  14958. });
  14959. } else if (this.config.enableEmsgKLVMetadata && emsgInfo.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")) {
  14960. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  14961. id3Track.samples.push({
  14962. data: emsgInfo.payload,
  14963. len: emsgInfo.payload.byteLength,
  14964. dts: pts,
  14965. pts,
  14966. type: MetadataSchema.misbklv,
  14967. duration: Number.POSITIVE_INFINITY
  14968. });
  14969. }
  14970. });
  14971. }
  14972. }
  14973. return id3Track;
  14974. }
  14975. demuxSampleAes(data, keyData, timeOffset) {
  14976. return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"));
  14977. }
  14978. destroy() {
  14979. this.config = null;
  14980. this.remainderData = null;
  14981. this.videoTrack = this.audioTrack = this.id3Track = this.txtTrack = void 0;
  14982. }
  14983. }
  14984. function getEmsgStartTime(emsgInfo, timeOffset) {
  14985. return isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  14986. }
  14987. class SampleAesDecrypter {
  14988. constructor(observer, config2, keyData) {
  14989. this.keyData = void 0;
  14990. this.decrypter = void 0;
  14991. this.keyData = keyData;
  14992. this.decrypter = new Decrypter(config2, {
  14993. removePKCS7Padding: false
  14994. });
  14995. }
  14996. decryptBuffer(encryptedData) {
  14997. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, DecrypterAesMode.cbc);
  14998. }
  14999. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  15000. decryptAacSample(samples, sampleIndex, callback) {
  15001. const curUnit = samples[sampleIndex].unit;
  15002. if (curUnit.length <= 16) {
  15003. return;
  15004. }
  15005. const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  15006. const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  15007. this.decryptBuffer(encryptedBuffer).then((decryptedBuffer) => {
  15008. const decryptedData = new Uint8Array(decryptedBuffer);
  15009. curUnit.set(decryptedData, 16);
  15010. if (!this.decrypter.isSync()) {
  15011. this.decryptAacSamples(samples, sampleIndex + 1, callback);
  15012. }
  15013. });
  15014. }
  15015. decryptAacSamples(samples, sampleIndex, callback) {
  15016. for (; ; sampleIndex++) {
  15017. if (sampleIndex >= samples.length) {
  15018. callback();
  15019. return;
  15020. }
  15021. if (samples[sampleIndex].unit.length < 32) {
  15022. continue;
  15023. }
  15024. this.decryptAacSample(samples, sampleIndex, callback);
  15025. if (!this.decrypter.isSync()) {
  15026. return;
  15027. }
  15028. }
  15029. }
  15030. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  15031. getAvcEncryptedData(decodedData) {
  15032. const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  15033. const encryptedData = new Int8Array(encryptedDataLen);
  15034. let outputPos = 0;
  15035. for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  15036. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  15037. }
  15038. return encryptedData;
  15039. }
  15040. getAvcDecryptedUnit(decodedData, decryptedData) {
  15041. const uint8DecryptedData = new Uint8Array(decryptedData);
  15042. let inputPos = 0;
  15043. for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  15044. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  15045. }
  15046. return decodedData;
  15047. }
  15048. decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  15049. const decodedData = discardEPB(curUnit.data);
  15050. const encryptedData = this.getAvcEncryptedData(decodedData);
  15051. this.decryptBuffer(encryptedData.buffer).then((decryptedBuffer) => {
  15052. curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  15053. if (!this.decrypter.isSync()) {
  15054. this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  15055. }
  15056. });
  15057. }
  15058. decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  15059. if (samples instanceof Uint8Array) {
  15060. throw new Error("Cannot decrypt samples of type Uint8Array");
  15061. }
  15062. for (; ; sampleIndex++, unitIndex = 0) {
  15063. if (sampleIndex >= samples.length) {
  15064. callback();
  15065. return;
  15066. }
  15067. const curUnits = samples[sampleIndex].units;
  15068. for (; ; unitIndex++) {
  15069. if (unitIndex >= curUnits.length) {
  15070. break;
  15071. }
  15072. const curUnit = curUnits[unitIndex];
  15073. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  15074. continue;
  15075. }
  15076. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  15077. if (!this.decrypter.isSync()) {
  15078. return;
  15079. }
  15080. }
  15081. }
  15082. }
  15083. }
  15084. class BaseVideoParser {
  15085. constructor() {
  15086. this.VideoSample = null;
  15087. }
  15088. createVideoSample(key, pts, dts) {
  15089. return {
  15090. key,
  15091. frame: false,
  15092. pts,
  15093. dts,
  15094. units: [],
  15095. length: 0
  15096. };
  15097. }
  15098. getLastNalUnit(samples) {
  15099. var _VideoSample;
  15100. let VideoSample = this.VideoSample;
  15101. let lastUnit;
  15102. if (!VideoSample || VideoSample.units.length === 0) {
  15103. VideoSample = samples[samples.length - 1];
  15104. }
  15105. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  15106. const units = VideoSample.units;
  15107. lastUnit = units[units.length - 1];
  15108. }
  15109. return lastUnit;
  15110. }
  15111. pushAccessUnit(VideoSample, videoTrack) {
  15112. if (VideoSample.units.length && VideoSample.frame) {
  15113. if (VideoSample.pts === void 0) {
  15114. const samples = videoTrack.samples;
  15115. const nbSamples = samples.length;
  15116. if (nbSamples) {
  15117. const lastSample = samples[nbSamples - 1];
  15118. VideoSample.pts = lastSample.pts;
  15119. VideoSample.dts = lastSample.dts;
  15120. } else {
  15121. videoTrack.dropped++;
  15122. return;
  15123. }
  15124. }
  15125. videoTrack.samples.push(VideoSample);
  15126. }
  15127. }
  15128. parseNALu(track, array2, endOfSegment) {
  15129. const len = array2.byteLength;
  15130. let state = track.naluState || 0;
  15131. const lastState = state;
  15132. const units = [];
  15133. let i2 = 0;
  15134. let value2;
  15135. let overflow;
  15136. let unitType;
  15137. let lastUnitStart = -1;
  15138. let lastUnitType = 0;
  15139. if (state === -1) {
  15140. lastUnitStart = 0;
  15141. lastUnitType = this.getNALuType(array2, 0);
  15142. state = 0;
  15143. i2 = 1;
  15144. }
  15145. while (i2 < len) {
  15146. value2 = array2[i2++];
  15147. if (!state) {
  15148. state = value2 ? 0 : 1;
  15149. continue;
  15150. }
  15151. if (state === 1) {
  15152. state = value2 ? 0 : 2;
  15153. continue;
  15154. }
  15155. if (!value2) {
  15156. state = 3;
  15157. } else if (value2 === 1) {
  15158. overflow = i2 - state - 1;
  15159. if (lastUnitStart >= 0) {
  15160. const unit = {
  15161. data: array2.subarray(lastUnitStart, overflow),
  15162. type: lastUnitType
  15163. };
  15164. units.push(unit);
  15165. } else {
  15166. const lastUnit = this.getLastNalUnit(track.samples);
  15167. if (lastUnit) {
  15168. if (lastState && i2 <= 4 - lastState) {
  15169. if (lastUnit.state) {
  15170. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  15171. }
  15172. }
  15173. if (overflow > 0) {
  15174. lastUnit.data = appendUint8Array(lastUnit.data, array2.subarray(0, overflow));
  15175. lastUnit.state = 0;
  15176. }
  15177. }
  15178. }
  15179. if (i2 < len) {
  15180. unitType = this.getNALuType(array2, i2);
  15181. lastUnitStart = i2;
  15182. lastUnitType = unitType;
  15183. state = 0;
  15184. } else {
  15185. state = -1;
  15186. }
  15187. } else {
  15188. state = 0;
  15189. }
  15190. }
  15191. if (lastUnitStart >= 0 && state >= 0) {
  15192. const unit = {
  15193. data: array2.subarray(lastUnitStart, len),
  15194. type: lastUnitType,
  15195. state
  15196. };
  15197. units.push(unit);
  15198. }
  15199. if (units.length === 0) {
  15200. const lastUnit = this.getLastNalUnit(track.samples);
  15201. if (lastUnit) {
  15202. lastUnit.data = appendUint8Array(lastUnit.data, array2);
  15203. }
  15204. }
  15205. track.naluState = state;
  15206. return units;
  15207. }
  15208. }
  15209. class ExpGolomb {
  15210. constructor(data) {
  15211. this.data = void 0;
  15212. this.bytesAvailable = void 0;
  15213. this.word = void 0;
  15214. this.bitsAvailable = void 0;
  15215. this.data = data;
  15216. this.bytesAvailable = data.byteLength;
  15217. this.word = 0;
  15218. this.bitsAvailable = 0;
  15219. }
  15220. // ():void
  15221. loadWord() {
  15222. const data = this.data;
  15223. const bytesAvailable = this.bytesAvailable;
  15224. const position = data.byteLength - bytesAvailable;
  15225. const workingBytes = new Uint8Array(4);
  15226. const availableBytes = Math.min(4, bytesAvailable);
  15227. if (availableBytes === 0) {
  15228. throw new Error("no bytes available");
  15229. }
  15230. workingBytes.set(data.subarray(position, position + availableBytes));
  15231. this.word = new DataView(workingBytes.buffer).getUint32(0);
  15232. this.bitsAvailable = availableBytes * 8;
  15233. this.bytesAvailable -= availableBytes;
  15234. }
  15235. // (count:int):void
  15236. skipBits(count) {
  15237. let skipBytes;
  15238. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  15239. if (this.bitsAvailable > count) {
  15240. this.word <<= count;
  15241. this.bitsAvailable -= count;
  15242. } else {
  15243. count -= this.bitsAvailable;
  15244. skipBytes = count >> 3;
  15245. count -= skipBytes << 3;
  15246. this.bytesAvailable -= skipBytes;
  15247. this.loadWord();
  15248. this.word <<= count;
  15249. this.bitsAvailable -= count;
  15250. }
  15251. }
  15252. // (size:int):uint
  15253. readBits(size) {
  15254. let bits = Math.min(this.bitsAvailable, size);
  15255. const valu = this.word >>> 32 - bits;
  15256. if (size > 32) {
  15257. logger.error("Cannot read more than 32 bits at a time");
  15258. }
  15259. this.bitsAvailable -= bits;
  15260. if (this.bitsAvailable > 0) {
  15261. this.word <<= bits;
  15262. } else if (this.bytesAvailable > 0) {
  15263. this.loadWord();
  15264. } else {
  15265. throw new Error("no bits available");
  15266. }
  15267. bits = size - bits;
  15268. if (bits > 0 && this.bitsAvailable) {
  15269. return valu << bits | this.readBits(bits);
  15270. } else {
  15271. return valu;
  15272. }
  15273. }
  15274. // ():uint
  15275. skipLZ() {
  15276. let leadingZeroCount;
  15277. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  15278. if ((this.word & 2147483648 >>> leadingZeroCount) !== 0) {
  15279. this.word <<= leadingZeroCount;
  15280. this.bitsAvailable -= leadingZeroCount;
  15281. return leadingZeroCount;
  15282. }
  15283. }
  15284. this.loadWord();
  15285. return leadingZeroCount + this.skipLZ();
  15286. }
  15287. // ():void
  15288. skipUEG() {
  15289. this.skipBits(1 + this.skipLZ());
  15290. }
  15291. // ():void
  15292. skipEG() {
  15293. this.skipBits(1 + this.skipLZ());
  15294. }
  15295. // ():uint
  15296. readUEG() {
  15297. const clz = this.skipLZ();
  15298. return this.readBits(clz + 1) - 1;
  15299. }
  15300. // ():int
  15301. readEG() {
  15302. const valu = this.readUEG();
  15303. if (1 & valu) {
  15304. return 1 + valu >>> 1;
  15305. } else {
  15306. return -1 * (valu >>> 1);
  15307. }
  15308. }
  15309. // Some convenience functions
  15310. // :Boolean
  15311. readBoolean() {
  15312. return this.readBits(1) === 1;
  15313. }
  15314. // ():int
  15315. readUByte() {
  15316. return this.readBits(8);
  15317. }
  15318. // ():int
  15319. readUShort() {
  15320. return this.readBits(16);
  15321. }
  15322. // ():int
  15323. readUInt() {
  15324. return this.readBits(32);
  15325. }
  15326. }
  15327. class AvcVideoParser extends BaseVideoParser {
  15328. parsePES(track, textTrack, pes, endOfSegment) {
  15329. const units = this.parseNALu(track, pes.data, endOfSegment);
  15330. let VideoSample = this.VideoSample;
  15331. let push2;
  15332. let spsfound = false;
  15333. pes.data = null;
  15334. if (VideoSample && units.length && !track.audFound) {
  15335. this.pushAccessUnit(VideoSample, track);
  15336. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  15337. }
  15338. units.forEach((unit) => {
  15339. var _VideoSample2, _VideoSample3;
  15340. switch (unit.type) {
  15341. case 1: {
  15342. let iskey = false;
  15343. push2 = true;
  15344. const data = unit.data;
  15345. if (spsfound && data.length > 4) {
  15346. const sliceType = this.readSliceType(data);
  15347. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  15348. iskey = true;
  15349. }
  15350. }
  15351. if (iskey) {
  15352. var _VideoSample;
  15353. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  15354. this.pushAccessUnit(VideoSample, track);
  15355. VideoSample = this.VideoSample = null;
  15356. }
  15357. }
  15358. if (!VideoSample) {
  15359. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  15360. }
  15361. VideoSample.frame = true;
  15362. VideoSample.key = iskey;
  15363. break;
  15364. }
  15365. case 5:
  15366. push2 = true;
  15367. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  15368. this.pushAccessUnit(VideoSample, track);
  15369. VideoSample = this.VideoSample = null;
  15370. }
  15371. if (!VideoSample) {
  15372. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  15373. }
  15374. VideoSample.key = true;
  15375. VideoSample.frame = true;
  15376. break;
  15377. case 6: {
  15378. push2 = true;
  15379. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  15380. break;
  15381. }
  15382. case 7: {
  15383. var _track$pixelRatio, _track$pixelRatio2;
  15384. push2 = true;
  15385. spsfound = true;
  15386. const sps = unit.data;
  15387. const config2 = this.readSPS(sps);
  15388. if (!track.sps || track.width !== config2.width || track.height !== config2.height || ((_track$pixelRatio = track.pixelRatio) == null ? void 0 : _track$pixelRatio[0]) !== config2.pixelRatio[0] || ((_track$pixelRatio2 = track.pixelRatio) == null ? void 0 : _track$pixelRatio2[1]) !== config2.pixelRatio[1]) {
  15389. track.width = config2.width;
  15390. track.height = config2.height;
  15391. track.pixelRatio = config2.pixelRatio;
  15392. track.sps = [sps];
  15393. const codecarray = sps.subarray(1, 4);
  15394. let codecstring = "avc1.";
  15395. for (let i2 = 0; i2 < 3; i2++) {
  15396. let h2 = codecarray[i2].toString(16);
  15397. if (h2.length < 2) {
  15398. h2 = "0" + h2;
  15399. }
  15400. codecstring += h2;
  15401. }
  15402. track.codec = codecstring;
  15403. }
  15404. break;
  15405. }
  15406. case 8:
  15407. push2 = true;
  15408. track.pps = [unit.data];
  15409. break;
  15410. case 9:
  15411. push2 = true;
  15412. track.audFound = true;
  15413. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  15414. this.pushAccessUnit(VideoSample, track);
  15415. VideoSample = null;
  15416. }
  15417. if (!VideoSample) {
  15418. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  15419. }
  15420. break;
  15421. case 12:
  15422. push2 = true;
  15423. break;
  15424. default:
  15425. push2 = false;
  15426. break;
  15427. }
  15428. if (VideoSample && push2) {
  15429. const units2 = VideoSample.units;
  15430. units2.push(unit);
  15431. }
  15432. });
  15433. if (endOfSegment && VideoSample) {
  15434. this.pushAccessUnit(VideoSample, track);
  15435. this.VideoSample = null;
  15436. }
  15437. }
  15438. getNALuType(data, offset) {
  15439. return data[offset] & 31;
  15440. }
  15441. readSliceType(data) {
  15442. const eg = new ExpGolomb(data);
  15443. eg.readUByte();
  15444. eg.readUEG();
  15445. return eg.readUEG();
  15446. }
  15447. /**
  15448. * The scaling list is optionally transmitted as part of a sequence parameter
  15449. * set and is not relevant to transmuxing.
  15450. * @param count the number of entries in this scaling list
  15451. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  15452. */
  15453. skipScalingList(count, reader) {
  15454. let lastScale = 8;
  15455. let nextScale = 8;
  15456. let deltaScale;
  15457. for (let j2 = 0; j2 < count; j2++) {
  15458. if (nextScale !== 0) {
  15459. deltaScale = reader.readEG();
  15460. nextScale = (lastScale + deltaScale + 256) % 256;
  15461. }
  15462. lastScale = nextScale === 0 ? lastScale : nextScale;
  15463. }
  15464. }
  15465. /**
  15466. * Read a sequence parameter set and return some interesting video
  15467. * properties. A sequence parameter set is the H264 metadata that
  15468. * describes the properties of upcoming video frames.
  15469. * @returns an object with configuration parsed from the
  15470. * sequence parameter set, including the dimensions of the
  15471. * associated video frames.
  15472. */
  15473. readSPS(sps) {
  15474. const eg = new ExpGolomb(sps);
  15475. let frameCropLeftOffset = 0;
  15476. let frameCropRightOffset = 0;
  15477. let frameCropTopOffset = 0;
  15478. let frameCropBottomOffset = 0;
  15479. let numRefFramesInPicOrderCntCycle;
  15480. let scalingListCount;
  15481. let i2;
  15482. const readUByte = eg.readUByte.bind(eg);
  15483. const readBits = eg.readBits.bind(eg);
  15484. const readUEG = eg.readUEG.bind(eg);
  15485. const readBoolean = eg.readBoolean.bind(eg);
  15486. const skipBits = eg.skipBits.bind(eg);
  15487. const skipEG = eg.skipEG.bind(eg);
  15488. const skipUEG = eg.skipUEG.bind(eg);
  15489. const skipScalingList = this.skipScalingList.bind(this);
  15490. readUByte();
  15491. const profileIdc = readUByte();
  15492. readBits(5);
  15493. skipBits(3);
  15494. readUByte();
  15495. skipUEG();
  15496. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  15497. const chromaFormatIdc = readUEG();
  15498. if (chromaFormatIdc === 3) {
  15499. skipBits(1);
  15500. }
  15501. skipUEG();
  15502. skipUEG();
  15503. skipBits(1);
  15504. if (readBoolean()) {
  15505. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  15506. for (i2 = 0; i2 < scalingListCount; i2++) {
  15507. if (readBoolean()) {
  15508. if (i2 < 6) {
  15509. skipScalingList(16, eg);
  15510. } else {
  15511. skipScalingList(64, eg);
  15512. }
  15513. }
  15514. }
  15515. }
  15516. }
  15517. skipUEG();
  15518. const picOrderCntType = readUEG();
  15519. if (picOrderCntType === 0) {
  15520. readUEG();
  15521. } else if (picOrderCntType === 1) {
  15522. skipBits(1);
  15523. skipEG();
  15524. skipEG();
  15525. numRefFramesInPicOrderCntCycle = readUEG();
  15526. for (i2 = 0; i2 < numRefFramesInPicOrderCntCycle; i2++) {
  15527. skipEG();
  15528. }
  15529. }
  15530. skipUEG();
  15531. skipBits(1);
  15532. const picWidthInMbsMinus1 = readUEG();
  15533. const picHeightInMapUnitsMinus1 = readUEG();
  15534. const frameMbsOnlyFlag = readBits(1);
  15535. if (frameMbsOnlyFlag === 0) {
  15536. skipBits(1);
  15537. }
  15538. skipBits(1);
  15539. if (readBoolean()) {
  15540. frameCropLeftOffset = readUEG();
  15541. frameCropRightOffset = readUEG();
  15542. frameCropTopOffset = readUEG();
  15543. frameCropBottomOffset = readUEG();
  15544. }
  15545. let pixelRatio = [1, 1];
  15546. if (readBoolean()) {
  15547. if (readBoolean()) {
  15548. const aspectRatioIdc = readUByte();
  15549. switch (aspectRatioIdc) {
  15550. case 1:
  15551. pixelRatio = [1, 1];
  15552. break;
  15553. case 2:
  15554. pixelRatio = [12, 11];
  15555. break;
  15556. case 3:
  15557. pixelRatio = [10, 11];
  15558. break;
  15559. case 4:
  15560. pixelRatio = [16, 11];
  15561. break;
  15562. case 5:
  15563. pixelRatio = [40, 33];
  15564. break;
  15565. case 6:
  15566. pixelRatio = [24, 11];
  15567. break;
  15568. case 7:
  15569. pixelRatio = [20, 11];
  15570. break;
  15571. case 8:
  15572. pixelRatio = [32, 11];
  15573. break;
  15574. case 9:
  15575. pixelRatio = [80, 33];
  15576. break;
  15577. case 10:
  15578. pixelRatio = [18, 11];
  15579. break;
  15580. case 11:
  15581. pixelRatio = [15, 11];
  15582. break;
  15583. case 12:
  15584. pixelRatio = [64, 33];
  15585. break;
  15586. case 13:
  15587. pixelRatio = [160, 99];
  15588. break;
  15589. case 14:
  15590. pixelRatio = [4, 3];
  15591. break;
  15592. case 15:
  15593. pixelRatio = [3, 2];
  15594. break;
  15595. case 16:
  15596. pixelRatio = [2, 1];
  15597. break;
  15598. case 255: {
  15599. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  15600. break;
  15601. }
  15602. }
  15603. }
  15604. }
  15605. return {
  15606. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  15607. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  15608. pixelRatio
  15609. };
  15610. }
  15611. }
  15612. class HevcVideoParser extends BaseVideoParser {
  15613. constructor(...args) {
  15614. super(...args);
  15615. this.initVPS = null;
  15616. }
  15617. parsePES(track, textTrack, pes, endOfSegment) {
  15618. const units = this.parseNALu(track, pes.data, endOfSegment);
  15619. let VideoSample = this.VideoSample;
  15620. let push2;
  15621. let spsfound = false;
  15622. pes.data = null;
  15623. if (VideoSample && units.length && !track.audFound) {
  15624. this.pushAccessUnit(VideoSample, track);
  15625. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  15626. }
  15627. units.forEach((unit) => {
  15628. var _VideoSample2, _VideoSample3;
  15629. switch (unit.type) {
  15630. case 0:
  15631. case 1:
  15632. case 2:
  15633. case 3:
  15634. case 4:
  15635. case 5:
  15636. case 6:
  15637. case 7:
  15638. case 8:
  15639. case 9:
  15640. if (!VideoSample) {
  15641. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  15642. }
  15643. VideoSample.frame = true;
  15644. push2 = true;
  15645. break;
  15646. case 16:
  15647. case 17:
  15648. case 18:
  15649. case 21:
  15650. push2 = true;
  15651. if (spsfound) {
  15652. var _VideoSample;
  15653. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  15654. this.pushAccessUnit(VideoSample, track);
  15655. VideoSample = this.VideoSample = null;
  15656. }
  15657. }
  15658. if (!VideoSample) {
  15659. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  15660. }
  15661. VideoSample.key = true;
  15662. VideoSample.frame = true;
  15663. break;
  15664. case 19:
  15665. case 20:
  15666. push2 = true;
  15667. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  15668. this.pushAccessUnit(VideoSample, track);
  15669. VideoSample = this.VideoSample = null;
  15670. }
  15671. if (!VideoSample) {
  15672. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  15673. }
  15674. VideoSample.key = true;
  15675. VideoSample.frame = true;
  15676. break;
  15677. case 39:
  15678. push2 = true;
  15679. parseSEIMessageFromNALu(
  15680. unit.data,
  15681. 2,
  15682. // NALu header size
  15683. pes.pts,
  15684. textTrack.samples
  15685. );
  15686. break;
  15687. case 32:
  15688. push2 = true;
  15689. if (!track.vps) {
  15690. if (typeof track.params !== "object") {
  15691. track.params = {};
  15692. }
  15693. track.params = _extends(track.params, this.readVPS(unit.data));
  15694. this.initVPS = unit.data;
  15695. }
  15696. track.vps = [unit.data];
  15697. break;
  15698. case 33:
  15699. push2 = true;
  15700. spsfound = true;
  15701. if (track.vps !== void 0 && track.vps[0] !== this.initVPS && track.sps !== void 0 && !this.matchSPS(track.sps[0], unit.data)) {
  15702. this.initVPS = track.vps[0];
  15703. track.sps = track.pps = void 0;
  15704. }
  15705. if (!track.sps) {
  15706. const config2 = this.readSPS(unit.data);
  15707. track.width = config2.width;
  15708. track.height = config2.height;
  15709. track.pixelRatio = config2.pixelRatio;
  15710. track.codec = config2.codecString;
  15711. track.sps = [];
  15712. if (typeof track.params !== "object") {
  15713. track.params = {};
  15714. }
  15715. for (const prop in config2.params) {
  15716. track.params[prop] = config2.params[prop];
  15717. }
  15718. }
  15719. this.pushParameterSet(track.sps, unit.data, track.vps);
  15720. if (!VideoSample) {
  15721. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  15722. }
  15723. VideoSample.key = true;
  15724. break;
  15725. case 34:
  15726. push2 = true;
  15727. if (typeof track.params === "object") {
  15728. if (!track.pps) {
  15729. track.pps = [];
  15730. const config2 = this.readPPS(unit.data);
  15731. for (const prop in config2) {
  15732. track.params[prop] = config2[prop];
  15733. }
  15734. }
  15735. this.pushParameterSet(track.pps, unit.data, track.vps);
  15736. }
  15737. break;
  15738. case 35:
  15739. push2 = true;
  15740. track.audFound = true;
  15741. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  15742. this.pushAccessUnit(VideoSample, track);
  15743. VideoSample = null;
  15744. }
  15745. if (!VideoSample) {
  15746. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  15747. }
  15748. break;
  15749. default:
  15750. push2 = false;
  15751. break;
  15752. }
  15753. if (VideoSample && push2) {
  15754. const units2 = VideoSample.units;
  15755. units2.push(unit);
  15756. }
  15757. });
  15758. if (endOfSegment && VideoSample) {
  15759. this.pushAccessUnit(VideoSample, track);
  15760. this.VideoSample = null;
  15761. }
  15762. }
  15763. pushParameterSet(parameterSets, data, vps) {
  15764. if (vps && vps[0] === this.initVPS || !vps && !parameterSets.length) {
  15765. parameterSets.push(data);
  15766. }
  15767. }
  15768. getNALuType(data, offset) {
  15769. return (data[offset] & 126) >>> 1;
  15770. }
  15771. ebsp2rbsp(arr) {
  15772. const dst = new Uint8Array(arr.byteLength);
  15773. let dstIdx = 0;
  15774. for (let i2 = 0; i2 < arr.byteLength; i2++) {
  15775. if (i2 >= 2) {
  15776. if (arr[i2] === 3 && arr[i2 - 1] === 0 && arr[i2 - 2] === 0) {
  15777. continue;
  15778. }
  15779. }
  15780. dst[dstIdx] = arr[i2];
  15781. dstIdx++;
  15782. }
  15783. return new Uint8Array(dst.buffer, 0, dstIdx);
  15784. }
  15785. pushAccessUnit(VideoSample, videoTrack) {
  15786. super.pushAccessUnit(VideoSample, videoTrack);
  15787. if (this.initVPS) {
  15788. this.initVPS = null;
  15789. }
  15790. }
  15791. readVPS(vps) {
  15792. const eg = new ExpGolomb(vps);
  15793. eg.readUByte();
  15794. eg.readUByte();
  15795. eg.readBits(4);
  15796. eg.skipBits(2);
  15797. eg.readBits(6);
  15798. const max_sub_layers_minus1 = eg.readBits(3);
  15799. const temporal_id_nesting_flag = eg.readBoolean();
  15800. return {
  15801. numTemporalLayers: max_sub_layers_minus1 + 1,
  15802. temporalIdNested: temporal_id_nesting_flag
  15803. };
  15804. }
  15805. readSPS(sps) {
  15806. const eg = new ExpGolomb(this.ebsp2rbsp(sps));
  15807. eg.readUByte();
  15808. eg.readUByte();
  15809. eg.readBits(4);
  15810. const max_sub_layers_minus1 = eg.readBits(3);
  15811. eg.readBoolean();
  15812. const general_profile_space = eg.readBits(2);
  15813. const general_tier_flag = eg.readBoolean();
  15814. const general_profile_idc = eg.readBits(5);
  15815. const general_profile_compatibility_flags_1 = eg.readUByte();
  15816. const general_profile_compatibility_flags_2 = eg.readUByte();
  15817. const general_profile_compatibility_flags_3 = eg.readUByte();
  15818. const general_profile_compatibility_flags_4 = eg.readUByte();
  15819. const general_constraint_indicator_flags_1 = eg.readUByte();
  15820. const general_constraint_indicator_flags_2 = eg.readUByte();
  15821. const general_constraint_indicator_flags_3 = eg.readUByte();
  15822. const general_constraint_indicator_flags_4 = eg.readUByte();
  15823. const general_constraint_indicator_flags_5 = eg.readUByte();
  15824. const general_constraint_indicator_flags_6 = eg.readUByte();
  15825. const general_level_idc = eg.readUByte();
  15826. const sub_layer_profile_present_flags = [];
  15827. const sub_layer_level_present_flags = [];
  15828. for (let i2 = 0; i2 < max_sub_layers_minus1; i2++) {
  15829. sub_layer_profile_present_flags.push(eg.readBoolean());
  15830. sub_layer_level_present_flags.push(eg.readBoolean());
  15831. }
  15832. if (max_sub_layers_minus1 > 0) {
  15833. for (let i2 = max_sub_layers_minus1; i2 < 8; i2++) {
  15834. eg.readBits(2);
  15835. }
  15836. }
  15837. for (let i2 = 0; i2 < max_sub_layers_minus1; i2++) {
  15838. if (sub_layer_profile_present_flags[i2]) {
  15839. eg.readUByte();
  15840. eg.readUByte();
  15841. eg.readUByte();
  15842. eg.readUByte();
  15843. eg.readUByte();
  15844. eg.readUByte();
  15845. eg.readUByte();
  15846. eg.readUByte();
  15847. eg.readUByte();
  15848. eg.readUByte();
  15849. eg.readUByte();
  15850. }
  15851. if (sub_layer_level_present_flags[i2]) {
  15852. eg.readUByte();
  15853. }
  15854. }
  15855. eg.readUEG();
  15856. const chroma_format_idc = eg.readUEG();
  15857. if (chroma_format_idc == 3) {
  15858. eg.skipBits(1);
  15859. }
  15860. const pic_width_in_luma_samples = eg.readUEG();
  15861. const pic_height_in_luma_samples = eg.readUEG();
  15862. const conformance_window_flag = eg.readBoolean();
  15863. let pic_left_offset = 0, pic_right_offset = 0, pic_top_offset = 0, pic_bottom_offset = 0;
  15864. if (conformance_window_flag) {
  15865. pic_left_offset += eg.readUEG();
  15866. pic_right_offset += eg.readUEG();
  15867. pic_top_offset += eg.readUEG();
  15868. pic_bottom_offset += eg.readUEG();
  15869. }
  15870. const bit_depth_luma_minus8 = eg.readUEG();
  15871. const bit_depth_chroma_minus8 = eg.readUEG();
  15872. const log2_max_pic_order_cnt_lsb_minus4 = eg.readUEG();
  15873. const sub_layer_ordering_info_present_flag = eg.readBoolean();
  15874. for (let i2 = sub_layer_ordering_info_present_flag ? 0 : max_sub_layers_minus1; i2 <= max_sub_layers_minus1; i2++) {
  15875. eg.skipUEG();
  15876. eg.skipUEG();
  15877. eg.skipUEG();
  15878. }
  15879. eg.skipUEG();
  15880. eg.skipUEG();
  15881. eg.skipUEG();
  15882. eg.skipUEG();
  15883. eg.skipUEG();
  15884. eg.skipUEG();
  15885. const scaling_list_enabled_flag = eg.readBoolean();
  15886. if (scaling_list_enabled_flag) {
  15887. const sps_scaling_list_data_present_flag = eg.readBoolean();
  15888. if (sps_scaling_list_data_present_flag) {
  15889. for (let sizeId = 0; sizeId < 4; sizeId++) {
  15890. for (let matrixId = 0; matrixId < (sizeId === 3 ? 2 : 6); matrixId++) {
  15891. const scaling_list_pred_mode_flag = eg.readBoolean();
  15892. if (!scaling_list_pred_mode_flag) {
  15893. eg.readUEG();
  15894. } else {
  15895. const coefNum = Math.min(64, 1 << 4 + (sizeId << 1));
  15896. if (sizeId > 1) {
  15897. eg.readEG();
  15898. }
  15899. for (let i2 = 0; i2 < coefNum; i2++) {
  15900. eg.readEG();
  15901. }
  15902. }
  15903. }
  15904. }
  15905. }
  15906. }
  15907. eg.readBoolean();
  15908. eg.readBoolean();
  15909. const pcm_enabled_flag = eg.readBoolean();
  15910. if (pcm_enabled_flag) {
  15911. eg.readUByte();
  15912. eg.skipUEG();
  15913. eg.skipUEG();
  15914. eg.readBoolean();
  15915. }
  15916. const num_short_term_ref_pic_sets = eg.readUEG();
  15917. let num_delta_pocs = 0;
  15918. for (let i2 = 0; i2 < num_short_term_ref_pic_sets; i2++) {
  15919. let inter_ref_pic_set_prediction_flag = false;
  15920. if (i2 !== 0) {
  15921. inter_ref_pic_set_prediction_flag = eg.readBoolean();
  15922. }
  15923. if (inter_ref_pic_set_prediction_flag) {
  15924. if (i2 === num_short_term_ref_pic_sets) {
  15925. eg.readUEG();
  15926. }
  15927. eg.readBoolean();
  15928. eg.readUEG();
  15929. let next_num_delta_pocs = 0;
  15930. for (let j2 = 0; j2 <= num_delta_pocs; j2++) {
  15931. const used_by_curr_pic_flag = eg.readBoolean();
  15932. let use_delta_flag = false;
  15933. if (!used_by_curr_pic_flag) {
  15934. use_delta_flag = eg.readBoolean();
  15935. }
  15936. if (used_by_curr_pic_flag || use_delta_flag) {
  15937. next_num_delta_pocs++;
  15938. }
  15939. }
  15940. num_delta_pocs = next_num_delta_pocs;
  15941. } else {
  15942. const num_negative_pics = eg.readUEG();
  15943. const num_positive_pics = eg.readUEG();
  15944. num_delta_pocs = num_negative_pics + num_positive_pics;
  15945. for (let j2 = 0; j2 < num_negative_pics; j2++) {
  15946. eg.readUEG();
  15947. eg.readBoolean();
  15948. }
  15949. for (let j2 = 0; j2 < num_positive_pics; j2++) {
  15950. eg.readUEG();
  15951. eg.readBoolean();
  15952. }
  15953. }
  15954. }
  15955. const long_term_ref_pics_present_flag = eg.readBoolean();
  15956. if (long_term_ref_pics_present_flag) {
  15957. const num_long_term_ref_pics_sps = eg.readUEG();
  15958. for (let i2 = 0; i2 < num_long_term_ref_pics_sps; i2++) {
  15959. for (let j2 = 0; j2 < log2_max_pic_order_cnt_lsb_minus4 + 4; j2++) {
  15960. eg.readBits(1);
  15961. }
  15962. eg.readBits(1);
  15963. }
  15964. }
  15965. let min_spatial_segmentation_idc = 0;
  15966. let sar_width = 1, sar_height = 1;
  15967. let fps_fixed = true, fps_den = 1, fps_num = 0;
  15968. eg.readBoolean();
  15969. eg.readBoolean();
  15970. let default_display_window_flag = false;
  15971. const vui_parameters_present_flag = eg.readBoolean();
  15972. if (vui_parameters_present_flag) {
  15973. const aspect_ratio_info_present_flag = eg.readBoolean();
  15974. if (aspect_ratio_info_present_flag) {
  15975. const aspect_ratio_idc = eg.readUByte();
  15976. const sar_width_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  15977. const sar_height_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  15978. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  15979. sar_width = sar_width_table[aspect_ratio_idc - 1];
  15980. sar_height = sar_height_table[aspect_ratio_idc - 1];
  15981. } else if (aspect_ratio_idc === 255) {
  15982. sar_width = eg.readBits(16);
  15983. sar_height = eg.readBits(16);
  15984. }
  15985. }
  15986. const overscan_info_present_flag = eg.readBoolean();
  15987. if (overscan_info_present_flag) {
  15988. eg.readBoolean();
  15989. }
  15990. const video_signal_type_present_flag = eg.readBoolean();
  15991. if (video_signal_type_present_flag) {
  15992. eg.readBits(3);
  15993. eg.readBoolean();
  15994. const colour_description_present_flag = eg.readBoolean();
  15995. if (colour_description_present_flag) {
  15996. eg.readUByte();
  15997. eg.readUByte();
  15998. eg.readUByte();
  15999. }
  16000. }
  16001. const chroma_loc_info_present_flag = eg.readBoolean();
  16002. if (chroma_loc_info_present_flag) {
  16003. eg.readUEG();
  16004. eg.readUEG();
  16005. }
  16006. eg.readBoolean();
  16007. eg.readBoolean();
  16008. eg.readBoolean();
  16009. default_display_window_flag = eg.readBoolean();
  16010. if (default_display_window_flag) {
  16011. pic_left_offset += eg.readUEG();
  16012. pic_right_offset += eg.readUEG();
  16013. pic_top_offset += eg.readUEG();
  16014. pic_bottom_offset += eg.readUEG();
  16015. }
  16016. const vui_timing_info_present_flag = eg.readBoolean();
  16017. if (vui_timing_info_present_flag) {
  16018. fps_den = eg.readBits(32);
  16019. fps_num = eg.readBits(32);
  16020. const vui_poc_proportional_to_timing_flag = eg.readBoolean();
  16021. if (vui_poc_proportional_to_timing_flag) {
  16022. eg.readUEG();
  16023. }
  16024. const vui_hrd_parameters_present_flag = eg.readBoolean();
  16025. if (vui_hrd_parameters_present_flag) {
  16026. const nal_hrd_parameters_present_flag = eg.readBoolean();
  16027. const vcl_hrd_parameters_present_flag = eg.readBoolean();
  16028. let sub_pic_hrd_params_present_flag = false;
  16029. if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
  16030. sub_pic_hrd_params_present_flag = eg.readBoolean();
  16031. if (sub_pic_hrd_params_present_flag) {
  16032. eg.readUByte();
  16033. eg.readBits(5);
  16034. eg.readBoolean();
  16035. eg.readBits(5);
  16036. }
  16037. eg.readBits(4);
  16038. eg.readBits(4);
  16039. if (sub_pic_hrd_params_present_flag) {
  16040. eg.readBits(4);
  16041. }
  16042. eg.readBits(5);
  16043. eg.readBits(5);
  16044. eg.readBits(5);
  16045. }
  16046. for (let i2 = 0; i2 <= max_sub_layers_minus1; i2++) {
  16047. fps_fixed = eg.readBoolean();
  16048. const fixed_pic_rate_within_cvs_flag = fps_fixed || eg.readBoolean();
  16049. let low_delay_hrd_flag = false;
  16050. if (fixed_pic_rate_within_cvs_flag) {
  16051. eg.readEG();
  16052. } else {
  16053. low_delay_hrd_flag = eg.readBoolean();
  16054. }
  16055. const cpb_cnt = low_delay_hrd_flag ? 1 : eg.readUEG() + 1;
  16056. if (nal_hrd_parameters_present_flag) {
  16057. for (let j2 = 0; j2 < cpb_cnt; j2++) {
  16058. eg.readUEG();
  16059. eg.readUEG();
  16060. if (sub_pic_hrd_params_present_flag) {
  16061. eg.readUEG();
  16062. eg.readUEG();
  16063. }
  16064. eg.skipBits(1);
  16065. }
  16066. }
  16067. if (vcl_hrd_parameters_present_flag) {
  16068. for (let j2 = 0; j2 < cpb_cnt; j2++) {
  16069. eg.readUEG();
  16070. eg.readUEG();
  16071. if (sub_pic_hrd_params_present_flag) {
  16072. eg.readUEG();
  16073. eg.readUEG();
  16074. }
  16075. eg.skipBits(1);
  16076. }
  16077. }
  16078. }
  16079. }
  16080. }
  16081. const bitstream_restriction_flag = eg.readBoolean();
  16082. if (bitstream_restriction_flag) {
  16083. eg.readBoolean();
  16084. eg.readBoolean();
  16085. eg.readBoolean();
  16086. min_spatial_segmentation_idc = eg.readUEG();
  16087. }
  16088. }
  16089. let width = pic_width_in_luma_samples, height = pic_height_in_luma_samples;
  16090. if (conformance_window_flag || default_display_window_flag) {
  16091. let chroma_scale_w = 1, chroma_scale_h = 1;
  16092. if (chroma_format_idc === 1) {
  16093. chroma_scale_w = chroma_scale_h = 2;
  16094. } else if (chroma_format_idc == 2) {
  16095. chroma_scale_w = 2;
  16096. }
  16097. width = pic_width_in_luma_samples - chroma_scale_w * pic_right_offset - chroma_scale_w * pic_left_offset;
  16098. height = pic_height_in_luma_samples - chroma_scale_h * pic_bottom_offset - chroma_scale_h * pic_top_offset;
  16099. }
  16100. const profile_space_string = general_profile_space ? ["A", "B", "C"][general_profile_space] : "";
  16101. 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;
  16102. let profile_compatibility_rev = 0;
  16103. for (let i2 = 0; i2 < 32; i2++) {
  16104. profile_compatibility_rev = (profile_compatibility_rev | (profile_compatibility_buf >> i2 & 1) << 31 - i2) >>> 0;
  16105. }
  16106. let profile_compatibility_flags_string = profile_compatibility_rev.toString(16);
  16107. if (general_profile_idc === 1 && profile_compatibility_flags_string === "2") {
  16108. profile_compatibility_flags_string = "6";
  16109. }
  16110. const tier_flag_string = general_tier_flag ? "H" : "L";
  16111. return {
  16112. codecString: `hvc1.${profile_space_string}${general_profile_idc}.${profile_compatibility_flags_string}.${tier_flag_string}${general_level_idc}.B0`,
  16113. params: {
  16114. general_tier_flag,
  16115. general_profile_idc,
  16116. general_profile_space,
  16117. general_profile_compatibility_flags: [general_profile_compatibility_flags_1, general_profile_compatibility_flags_2, general_profile_compatibility_flags_3, general_profile_compatibility_flags_4],
  16118. 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],
  16119. general_level_idc,
  16120. bit_depth: bit_depth_luma_minus8 + 8,
  16121. bit_depth_luma_minus8,
  16122. bit_depth_chroma_minus8,
  16123. min_spatial_segmentation_idc,
  16124. chroma_format_idc,
  16125. frame_rate: {
  16126. fixed: fps_fixed,
  16127. fps: fps_num / fps_den
  16128. }
  16129. },
  16130. width,
  16131. height,
  16132. pixelRatio: [sar_width, sar_height]
  16133. };
  16134. }
  16135. readPPS(pps) {
  16136. const eg = new ExpGolomb(this.ebsp2rbsp(pps));
  16137. eg.readUByte();
  16138. eg.readUByte();
  16139. eg.skipUEG();
  16140. eg.skipUEG();
  16141. eg.skipBits(2);
  16142. eg.skipBits(3);
  16143. eg.skipBits(2);
  16144. eg.skipUEG();
  16145. eg.skipUEG();
  16146. eg.skipEG();
  16147. eg.skipBits(2);
  16148. const cu_qp_delta_enabled_flag = eg.readBoolean();
  16149. if (cu_qp_delta_enabled_flag) {
  16150. eg.skipUEG();
  16151. }
  16152. eg.skipEG();
  16153. eg.skipEG();
  16154. eg.skipBits(4);
  16155. const tiles_enabled_flag = eg.readBoolean();
  16156. const entropy_coding_sync_enabled_flag = eg.readBoolean();
  16157. let parallelismType = 1;
  16158. if (entropy_coding_sync_enabled_flag && tiles_enabled_flag) {
  16159. parallelismType = 0;
  16160. } else if (entropy_coding_sync_enabled_flag) {
  16161. parallelismType = 3;
  16162. } else if (tiles_enabled_flag) {
  16163. parallelismType = 2;
  16164. }
  16165. return {
  16166. parallelismType
  16167. };
  16168. }
  16169. matchSPS(sps1, sps2) {
  16170. return String.fromCharCode.apply(null, sps1).substr(3) === String.fromCharCode.apply(null, sps2).substr(3);
  16171. }
  16172. }
  16173. const PACKET_LENGTH = 188;
  16174. class TSDemuxer {
  16175. constructor(observer, config2, typeSupported, logger2) {
  16176. this.logger = void 0;
  16177. this.observer = void 0;
  16178. this.config = void 0;
  16179. this.typeSupported = void 0;
  16180. this.sampleAes = null;
  16181. this.pmtParsed = false;
  16182. this.audioCodec = void 0;
  16183. this.videoCodec = void 0;
  16184. this._pmtId = -1;
  16185. this._videoTrack = void 0;
  16186. this._audioTrack = void 0;
  16187. this._id3Track = void 0;
  16188. this._txtTrack = void 0;
  16189. this.aacOverFlow = null;
  16190. this.remainderData = null;
  16191. this.videoParser = void 0;
  16192. this.observer = observer;
  16193. this.config = config2;
  16194. this.typeSupported = typeSupported;
  16195. this.logger = logger2;
  16196. this.videoParser = null;
  16197. }
  16198. static probe(data, logger2) {
  16199. const syncOffset = TSDemuxer.syncOffset(data);
  16200. if (syncOffset > 0) {
  16201. logger2.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);
  16202. }
  16203. return syncOffset !== -1;
  16204. }
  16205. static syncOffset(data) {
  16206. const length = data.length;
  16207. let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  16208. let i2 = 0;
  16209. while (i2 < scanwindow) {
  16210. let foundPat = false;
  16211. let packetStart = -1;
  16212. let tsPackets = 0;
  16213. for (let j2 = i2; j2 < length; j2 += PACKET_LENGTH) {
  16214. if (data[j2] === 71 && (length - j2 === PACKET_LENGTH || data[j2 + PACKET_LENGTH] === 71)) {
  16215. tsPackets++;
  16216. if (packetStart === -1) {
  16217. packetStart = j2;
  16218. if (packetStart !== 0) {
  16219. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  16220. }
  16221. }
  16222. if (!foundPat) {
  16223. foundPat = parsePID(data, j2) === 0;
  16224. }
  16225. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j2 + PACKET_LENGTH > scanwindow)) {
  16226. return packetStart;
  16227. }
  16228. } else if (tsPackets) {
  16229. return -1;
  16230. } else {
  16231. break;
  16232. }
  16233. }
  16234. i2++;
  16235. }
  16236. return -1;
  16237. }
  16238. /**
  16239. * Creates a track model internal to demuxer used to drive remuxing input
  16240. */
  16241. static createTrack(type, duration) {
  16242. return {
  16243. container: type === "video" || type === "audio" ? "video/mp2t" : void 0,
  16244. type,
  16245. id: RemuxerTrackIdConfig[type],
  16246. pid: -1,
  16247. inputTimeScale: 9e4,
  16248. sequenceNumber: 0,
  16249. samples: [],
  16250. dropped: 0,
  16251. duration: type === "audio" ? duration : void 0
  16252. };
  16253. }
  16254. /**
  16255. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  16256. * Resets all internal track instances of the demuxer.
  16257. */
  16258. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  16259. this.pmtParsed = false;
  16260. this._pmtId = -1;
  16261. this._videoTrack = TSDemuxer.createTrack("video");
  16262. this._videoTrack.duration = trackDuration;
  16263. this._audioTrack = TSDemuxer.createTrack("audio", trackDuration);
  16264. this._id3Track = TSDemuxer.createTrack("id3");
  16265. this._txtTrack = TSDemuxer.createTrack("text");
  16266. this._audioTrack.segmentCodec = "aac";
  16267. this.aacOverFlow = null;
  16268. this.remainderData = null;
  16269. this.audioCodec = audioCodec;
  16270. this.videoCodec = videoCodec;
  16271. }
  16272. resetTimeStamp() {
  16273. }
  16274. resetContiguity() {
  16275. const {
  16276. _audioTrack,
  16277. _videoTrack,
  16278. _id3Track
  16279. } = this;
  16280. if (_audioTrack) {
  16281. _audioTrack.pesData = null;
  16282. }
  16283. if (_videoTrack) {
  16284. _videoTrack.pesData = null;
  16285. }
  16286. if (_id3Track) {
  16287. _id3Track.pesData = null;
  16288. }
  16289. this.aacOverFlow = null;
  16290. this.remainderData = null;
  16291. }
  16292. demux(data, timeOffset, isSampleAes = false, flush = false) {
  16293. if (!isSampleAes) {
  16294. this.sampleAes = null;
  16295. }
  16296. let pes;
  16297. const videoTrack = this._videoTrack;
  16298. const audioTrack = this._audioTrack;
  16299. const id3Track = this._id3Track;
  16300. const textTrack = this._txtTrack;
  16301. let videoPid = videoTrack.pid;
  16302. let videoData = videoTrack.pesData;
  16303. let audioPid = audioTrack.pid;
  16304. let id3Pid = id3Track.pid;
  16305. let audioData = audioTrack.pesData;
  16306. let id3Data = id3Track.pesData;
  16307. let unknownPID = null;
  16308. let pmtParsed = this.pmtParsed;
  16309. let pmtId = this._pmtId;
  16310. let len = data.length;
  16311. if (this.remainderData) {
  16312. data = appendUint8Array(this.remainderData, data);
  16313. len = data.length;
  16314. this.remainderData = null;
  16315. }
  16316. if (len < PACKET_LENGTH && !flush) {
  16317. this.remainderData = data;
  16318. return {
  16319. audioTrack,
  16320. videoTrack,
  16321. id3Track,
  16322. textTrack
  16323. };
  16324. }
  16325. const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  16326. len -= (len - syncOffset) % PACKET_LENGTH;
  16327. if (len < data.byteLength && !flush) {
  16328. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  16329. }
  16330. let tsPacketErrors = 0;
  16331. for (let start = syncOffset; start < len; start += PACKET_LENGTH) {
  16332. if (data[start] === 71) {
  16333. const stt = !!(data[start + 1] & 64);
  16334. const pid = parsePID(data, start);
  16335. const atf = (data[start + 3] & 48) >> 4;
  16336. let offset;
  16337. if (atf > 1) {
  16338. offset = start + 5 + data[start + 4];
  16339. if (offset === start + PACKET_LENGTH) {
  16340. continue;
  16341. }
  16342. } else {
  16343. offset = start + 4;
  16344. }
  16345. switch (pid) {
  16346. case videoPid:
  16347. if (stt) {
  16348. if (videoData && (pes = parsePES(videoData, this.logger))) {
  16349. if (this.videoParser === null) {
  16350. switch (videoTrack.segmentCodec) {
  16351. case "avc":
  16352. this.videoParser = new AvcVideoParser();
  16353. break;
  16354. case "hevc":
  16355. {
  16356. this.videoParser = new HevcVideoParser();
  16357. }
  16358. break;
  16359. }
  16360. }
  16361. if (this.videoParser !== null) {
  16362. this.videoParser.parsePES(videoTrack, textTrack, pes, false);
  16363. }
  16364. }
  16365. videoData = {
  16366. data: [],
  16367. size: 0
  16368. };
  16369. }
  16370. if (videoData) {
  16371. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  16372. videoData.size += start + PACKET_LENGTH - offset;
  16373. }
  16374. break;
  16375. case audioPid:
  16376. if (stt) {
  16377. if (audioData && (pes = parsePES(audioData, this.logger))) {
  16378. switch (audioTrack.segmentCodec) {
  16379. case "aac":
  16380. this.parseAACPES(audioTrack, pes);
  16381. break;
  16382. case "mp3":
  16383. this.parseMPEGPES(audioTrack, pes);
  16384. break;
  16385. case "ac3":
  16386. {
  16387. this.parseAC3PES(audioTrack, pes);
  16388. }
  16389. break;
  16390. }
  16391. }
  16392. audioData = {
  16393. data: [],
  16394. size: 0
  16395. };
  16396. }
  16397. if (audioData) {
  16398. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  16399. audioData.size += start + PACKET_LENGTH - offset;
  16400. }
  16401. break;
  16402. case id3Pid:
  16403. if (stt) {
  16404. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  16405. this.parseID3PES(id3Track, pes);
  16406. }
  16407. id3Data = {
  16408. data: [],
  16409. size: 0
  16410. };
  16411. }
  16412. if (id3Data) {
  16413. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  16414. id3Data.size += start + PACKET_LENGTH - offset;
  16415. }
  16416. break;
  16417. case 0:
  16418. if (stt) {
  16419. offset += data[offset] + 1;
  16420. }
  16421. pmtId = this._pmtId = parsePAT(data, offset);
  16422. break;
  16423. case pmtId: {
  16424. if (stt) {
  16425. offset += data[offset] + 1;
  16426. }
  16427. const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer, this.logger);
  16428. videoPid = parsedPIDs.videoPid;
  16429. if (videoPid > 0) {
  16430. videoTrack.pid = videoPid;
  16431. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  16432. }
  16433. audioPid = parsedPIDs.audioPid;
  16434. if (audioPid > 0) {
  16435. audioTrack.pid = audioPid;
  16436. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  16437. }
  16438. id3Pid = parsedPIDs.id3Pid;
  16439. if (id3Pid > 0) {
  16440. id3Track.pid = id3Pid;
  16441. }
  16442. if (unknownPID !== null && !pmtParsed) {
  16443. this.logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);
  16444. unknownPID = null;
  16445. start = syncOffset - 188;
  16446. }
  16447. pmtParsed = this.pmtParsed = true;
  16448. break;
  16449. }
  16450. case 17:
  16451. case 8191:
  16452. break;
  16453. default:
  16454. unknownPID = pid;
  16455. break;
  16456. }
  16457. } else {
  16458. tsPacketErrors++;
  16459. }
  16460. }
  16461. if (tsPacketErrors > 0) {
  16462. emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`), void 0, this.logger);
  16463. }
  16464. videoTrack.pesData = videoData;
  16465. audioTrack.pesData = audioData;
  16466. id3Track.pesData = id3Data;
  16467. const demuxResult = {
  16468. audioTrack,
  16469. videoTrack,
  16470. id3Track,
  16471. textTrack
  16472. };
  16473. if (flush) {
  16474. this.extractRemainingSamples(demuxResult);
  16475. }
  16476. return demuxResult;
  16477. }
  16478. flush() {
  16479. const {
  16480. remainderData
  16481. } = this;
  16482. this.remainderData = null;
  16483. let result;
  16484. if (remainderData) {
  16485. result = this.demux(remainderData, -1, false, true);
  16486. } else {
  16487. result = {
  16488. videoTrack: this._videoTrack,
  16489. audioTrack: this._audioTrack,
  16490. id3Track: this._id3Track,
  16491. textTrack: this._txtTrack
  16492. };
  16493. }
  16494. this.extractRemainingSamples(result);
  16495. if (this.sampleAes) {
  16496. return this.decrypt(result, this.sampleAes);
  16497. }
  16498. return result;
  16499. }
  16500. extractRemainingSamples(demuxResult) {
  16501. const {
  16502. audioTrack,
  16503. videoTrack,
  16504. id3Track,
  16505. textTrack
  16506. } = demuxResult;
  16507. const videoData = videoTrack.pesData;
  16508. const audioData = audioTrack.pesData;
  16509. const id3Data = id3Track.pesData;
  16510. let pes;
  16511. if (videoData && (pes = parsePES(videoData, this.logger))) {
  16512. if (this.videoParser === null) {
  16513. switch (videoTrack.segmentCodec) {
  16514. case "avc":
  16515. this.videoParser = new AvcVideoParser();
  16516. break;
  16517. case "hevc":
  16518. {
  16519. this.videoParser = new HevcVideoParser();
  16520. }
  16521. break;
  16522. }
  16523. }
  16524. if (this.videoParser !== null) {
  16525. this.videoParser.parsePES(videoTrack, textTrack, pes, true);
  16526. videoTrack.pesData = null;
  16527. }
  16528. } else {
  16529. videoTrack.pesData = videoData;
  16530. }
  16531. if (audioData && (pes = parsePES(audioData, this.logger))) {
  16532. switch (audioTrack.segmentCodec) {
  16533. case "aac":
  16534. this.parseAACPES(audioTrack, pes);
  16535. break;
  16536. case "mp3":
  16537. this.parseMPEGPES(audioTrack, pes);
  16538. break;
  16539. case "ac3":
  16540. {
  16541. this.parseAC3PES(audioTrack, pes);
  16542. }
  16543. break;
  16544. }
  16545. audioTrack.pesData = null;
  16546. } else {
  16547. if (audioData != null && audioData.size) {
  16548. this.logger.log("last AAC PES packet truncated,might overlap between fragments");
  16549. }
  16550. audioTrack.pesData = audioData;
  16551. }
  16552. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  16553. this.parseID3PES(id3Track, pes);
  16554. id3Track.pesData = null;
  16555. } else {
  16556. id3Track.pesData = id3Data;
  16557. }
  16558. }
  16559. demuxSampleAes(data, keyData, timeOffset) {
  16560. const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  16561. const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  16562. return this.decrypt(demuxResult, sampleAes);
  16563. }
  16564. decrypt(demuxResult, sampleAes) {
  16565. return new Promise((resolve) => {
  16566. const {
  16567. audioTrack,
  16568. videoTrack
  16569. } = demuxResult;
  16570. if (audioTrack.samples && audioTrack.segmentCodec === "aac") {
  16571. sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {
  16572. if (videoTrack.samples) {
  16573. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  16574. resolve(demuxResult);
  16575. });
  16576. } else {
  16577. resolve(demuxResult);
  16578. }
  16579. });
  16580. } else if (videoTrack.samples) {
  16581. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  16582. resolve(demuxResult);
  16583. });
  16584. }
  16585. });
  16586. }
  16587. destroy() {
  16588. if (this.observer) {
  16589. this.observer.removeAllListeners();
  16590. }
  16591. this.config = this.logger = this.observer = null;
  16592. this.aacOverFlow = this.videoParser = this.remainderData = this.sampleAes = null;
  16593. this._videoTrack = this._audioTrack = this._id3Track = this._txtTrack = void 0;
  16594. }
  16595. parseAACPES(track, pes) {
  16596. let startOffset = 0;
  16597. const aacOverFlow = this.aacOverFlow;
  16598. let data = pes.data;
  16599. if (aacOverFlow) {
  16600. this.aacOverFlow = null;
  16601. const frameMissingBytes = aacOverFlow.missing;
  16602. const sampleLength = aacOverFlow.sample.unit.byteLength;
  16603. if (frameMissingBytes === -1) {
  16604. data = appendUint8Array(aacOverFlow.sample.unit, data);
  16605. } else {
  16606. const frameOverflowBytes = sampleLength - frameMissingBytes;
  16607. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  16608. track.samples.push(aacOverFlow.sample);
  16609. startOffset = aacOverFlow.missing;
  16610. }
  16611. }
  16612. let offset;
  16613. let len;
  16614. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  16615. if (isHeader$1(data, offset)) {
  16616. break;
  16617. }
  16618. }
  16619. if (offset !== startOffset) {
  16620. let reason;
  16621. const recoverable = offset < len - 1;
  16622. if (recoverable) {
  16623. reason = `AAC PES did not start with ADTS header,offset:${offset}`;
  16624. } else {
  16625. reason = "No ADTS header found in AAC PES";
  16626. }
  16627. emitParsingError(this.observer, new Error(reason), recoverable, this.logger);
  16628. if (!recoverable) {
  16629. return;
  16630. }
  16631. }
  16632. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  16633. let pts;
  16634. if (pes.pts !== void 0) {
  16635. pts = pes.pts;
  16636. } else if (aacOverFlow) {
  16637. const frameDuration = getFrameDuration(track.samplerate);
  16638. pts = aacOverFlow.sample.pts + frameDuration;
  16639. } else {
  16640. this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");
  16641. return;
  16642. }
  16643. let frameIndex = 0;
  16644. let frame;
  16645. while (offset < len) {
  16646. frame = appendFrame$2(track, data, offset, pts, frameIndex);
  16647. offset += frame.length;
  16648. if (!frame.missing) {
  16649. frameIndex++;
  16650. for (; offset < len - 1; offset++) {
  16651. if (isHeader$1(data, offset)) {
  16652. break;
  16653. }
  16654. }
  16655. } else {
  16656. this.aacOverFlow = frame;
  16657. break;
  16658. }
  16659. }
  16660. }
  16661. parseMPEGPES(track, pes) {
  16662. const data = pes.data;
  16663. const length = data.length;
  16664. let frameIndex = 0;
  16665. let offset = 0;
  16666. const pts = pes.pts;
  16667. if (pts === void 0) {
  16668. this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");
  16669. return;
  16670. }
  16671. while (offset < length) {
  16672. if (isHeader(data, offset)) {
  16673. const frame = appendFrame$1(track, data, offset, pts, frameIndex);
  16674. if (frame) {
  16675. offset += frame.length;
  16676. frameIndex++;
  16677. } else {
  16678. break;
  16679. }
  16680. } else {
  16681. offset++;
  16682. }
  16683. }
  16684. }
  16685. parseAC3PES(track, pes) {
  16686. {
  16687. const data = pes.data;
  16688. const pts = pes.pts;
  16689. if (pts === void 0) {
  16690. this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");
  16691. return;
  16692. }
  16693. const length = data.length;
  16694. let frameIndex = 0;
  16695. let offset = 0;
  16696. let parsed;
  16697. while (offset < length && (parsed = appendFrame(track, data, offset, pts, frameIndex++)) > 0) {
  16698. offset += parsed;
  16699. }
  16700. }
  16701. }
  16702. parseID3PES(id3Track, pes) {
  16703. if (pes.pts === void 0) {
  16704. this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");
  16705. return;
  16706. }
  16707. const id3Sample = _extends({}, pes, {
  16708. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  16709. duration: Number.POSITIVE_INFINITY
  16710. });
  16711. id3Track.samples.push(id3Sample);
  16712. }
  16713. }
  16714. function parsePID(data, offset) {
  16715. return ((data[offset + 1] & 31) << 8) + data[offset + 2];
  16716. }
  16717. function parsePAT(data, offset) {
  16718. return (data[offset + 10] & 31) << 8 | data[offset + 11];
  16719. }
  16720. function parsePMT(data, offset, typeSupported, isSampleAes, observer, logger2) {
  16721. const result = {
  16722. audioPid: -1,
  16723. videoPid: -1,
  16724. id3Pid: -1,
  16725. segmentVideoCodec: "avc",
  16726. segmentAudioCodec: "aac"
  16727. };
  16728. const sectionLength = (data[offset + 1] & 15) << 8 | data[offset + 2];
  16729. const tableEnd = offset + 3 + sectionLength - 4;
  16730. const programInfoLength = (data[offset + 10] & 15) << 8 | data[offset + 11];
  16731. offset += 12 + programInfoLength;
  16732. while (offset < tableEnd) {
  16733. const pid = parsePID(data, offset);
  16734. const esInfoLength = (data[offset + 3] & 15) << 8 | data[offset + 4];
  16735. switch (data[offset]) {
  16736. case 207:
  16737. if (!isSampleAes) {
  16738. logEncryptedSamplesFoundInUnencryptedStream("ADTS AAC", logger2);
  16739. break;
  16740. }
  16741. case 15:
  16742. if (result.audioPid === -1) {
  16743. result.audioPid = pid;
  16744. }
  16745. break;
  16746. case 21:
  16747. if (result.id3Pid === -1) {
  16748. result.id3Pid = pid;
  16749. }
  16750. break;
  16751. case 219:
  16752. if (!isSampleAes) {
  16753. logEncryptedSamplesFoundInUnencryptedStream("H.264", logger2);
  16754. break;
  16755. }
  16756. case 27:
  16757. if (result.videoPid === -1) {
  16758. result.videoPid = pid;
  16759. }
  16760. break;
  16761. case 3:
  16762. case 4:
  16763. if (!typeSupported.mpeg && !typeSupported.mp3) {
  16764. logger2.log("MPEG audio found, not supported in this browser");
  16765. } else if (result.audioPid === -1) {
  16766. result.audioPid = pid;
  16767. result.segmentAudioCodec = "mp3";
  16768. }
  16769. break;
  16770. case 193:
  16771. if (!isSampleAes) {
  16772. logEncryptedSamplesFoundInUnencryptedStream("AC-3", logger2);
  16773. break;
  16774. }
  16775. case 129:
  16776. {
  16777. if (!typeSupported.ac3) {
  16778. logger2.log("AC-3 audio found, not supported in this browser");
  16779. } else if (result.audioPid === -1) {
  16780. result.audioPid = pid;
  16781. result.segmentAudioCodec = "ac3";
  16782. }
  16783. }
  16784. break;
  16785. case 6:
  16786. if (result.audioPid === -1 && esInfoLength > 0) {
  16787. let parsePos = offset + 5;
  16788. let remaining = esInfoLength;
  16789. while (remaining > 2) {
  16790. const descriptorId = data[parsePos];
  16791. switch (descriptorId) {
  16792. case 106:
  16793. {
  16794. if (typeSupported.ac3 !== true) {
  16795. logger2.log("AC-3 audio found, not supported in this browser for now");
  16796. } else {
  16797. result.audioPid = pid;
  16798. result.segmentAudioCodec = "ac3";
  16799. }
  16800. }
  16801. break;
  16802. }
  16803. const descriptorLen = data[parsePos + 1] + 2;
  16804. parsePos += descriptorLen;
  16805. remaining -= descriptorLen;
  16806. }
  16807. }
  16808. break;
  16809. case 194:
  16810. case 135:
  16811. emitParsingError(observer, new Error("Unsupported EC-3 in M2TS found"), void 0, logger2);
  16812. return result;
  16813. case 36:
  16814. {
  16815. if (result.videoPid === -1) {
  16816. result.videoPid = pid;
  16817. result.segmentVideoCodec = "hevc";
  16818. logger2.log("HEVC in M2TS found");
  16819. }
  16820. }
  16821. break;
  16822. }
  16823. offset += esInfoLength + 5;
  16824. }
  16825. return result;
  16826. }
  16827. function emitParsingError(observer, error2, levelRetry, logger2) {
  16828. logger2.warn(`parsing error: ${error2.message}`);
  16829. observer.emit(Events.ERROR, Events.ERROR, {
  16830. type: ErrorTypes.MEDIA_ERROR,
  16831. details: ErrorDetails.FRAG_PARSING_ERROR,
  16832. fatal: false,
  16833. levelRetry,
  16834. error: error2,
  16835. reason: error2.message
  16836. });
  16837. }
  16838. function logEncryptedSamplesFoundInUnencryptedStream(type, logger2) {
  16839. logger2.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);
  16840. }
  16841. function parsePES(stream, logger2) {
  16842. let i2 = 0;
  16843. let frag;
  16844. let pesLen;
  16845. let pesHdrLen;
  16846. let pesPts;
  16847. let pesDts;
  16848. const data = stream.data;
  16849. if (!stream || stream.size === 0) {
  16850. return null;
  16851. }
  16852. while (data[0].length < 19 && data.length > 1) {
  16853. data[0] = appendUint8Array(data[0], data[1]);
  16854. data.splice(1, 1);
  16855. }
  16856. frag = data[0];
  16857. const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  16858. if (pesPrefix === 1) {
  16859. pesLen = (frag[4] << 8) + frag[5];
  16860. if (pesLen && pesLen > stream.size - 6) {
  16861. return null;
  16862. }
  16863. const pesFlags = frag[7];
  16864. if (pesFlags & 192) {
  16865. pesPts = (frag[9] & 14) * 536870912 + // 1 << 29
  16866. (frag[10] & 255) * 4194304 + // 1 << 22
  16867. (frag[11] & 254) * 16384 + // 1 << 14
  16868. (frag[12] & 255) * 128 + // 1 << 7
  16869. (frag[13] & 254) / 2;
  16870. if (pesFlags & 64) {
  16871. pesDts = (frag[14] & 14) * 536870912 + // 1 << 29
  16872. (frag[15] & 255) * 4194304 + // 1 << 22
  16873. (frag[16] & 254) * 16384 + // 1 << 14
  16874. (frag[17] & 255) * 128 + // 1 << 7
  16875. (frag[18] & 254) / 2;
  16876. if (pesPts - pesDts > 60 * 9e4) {
  16877. logger2.warn(`${Math.round((pesPts - pesDts) / 9e4)}s delta between PTS and DTS, align them`);
  16878. pesPts = pesDts;
  16879. }
  16880. } else {
  16881. pesDts = pesPts;
  16882. }
  16883. }
  16884. pesHdrLen = frag[8];
  16885. let payloadStartOffset = pesHdrLen + 9;
  16886. if (stream.size <= payloadStartOffset) {
  16887. return null;
  16888. }
  16889. stream.size -= payloadStartOffset;
  16890. const pesData = new Uint8Array(stream.size);
  16891. for (let j2 = 0, dataLen = data.length; j2 < dataLen; j2++) {
  16892. frag = data[j2];
  16893. let len = frag.byteLength;
  16894. if (payloadStartOffset) {
  16895. if (payloadStartOffset > len) {
  16896. payloadStartOffset -= len;
  16897. continue;
  16898. } else {
  16899. frag = frag.subarray(payloadStartOffset);
  16900. len -= payloadStartOffset;
  16901. payloadStartOffset = 0;
  16902. }
  16903. }
  16904. pesData.set(frag, i2);
  16905. i2 += len;
  16906. }
  16907. if (pesLen) {
  16908. pesLen -= pesHdrLen + 3;
  16909. }
  16910. return {
  16911. data: pesData,
  16912. pts: pesPts,
  16913. dts: pesDts,
  16914. len: pesLen
  16915. };
  16916. }
  16917. return null;
  16918. }
  16919. class AAC {
  16920. static getSilentFrame(codec, channelCount) {
  16921. switch (codec) {
  16922. case "mp4a.40.2":
  16923. if (channelCount === 1) {
  16924. return new Uint8Array([0, 200, 0, 128, 35, 128]);
  16925. } else if (channelCount === 2) {
  16926. return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);
  16927. } else if (channelCount === 3) {
  16928. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);
  16929. } else if (channelCount === 4) {
  16930. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);
  16931. } else if (channelCount === 5) {
  16932. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 56]);
  16933. } else if (channelCount === 6) {
  16934. 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]);
  16935. }
  16936. break;
  16937. default:
  16938. if (channelCount === 1) {
  16939. 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]);
  16940. } else if (channelCount === 2) {
  16941. 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]);
  16942. } else if (channelCount === 3) {
  16943. 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]);
  16944. }
  16945. break;
  16946. }
  16947. return void 0;
  16948. }
  16949. }
  16950. const UINT32_MAX = Math.pow(2, 32) - 1;
  16951. class MP4 {
  16952. static init() {
  16953. MP4.types = {
  16954. avc1: [],
  16955. // codingname
  16956. avcC: [],
  16957. hvc1: [],
  16958. hvcC: [],
  16959. btrt: [],
  16960. dinf: [],
  16961. dref: [],
  16962. esds: [],
  16963. ftyp: [],
  16964. hdlr: [],
  16965. mdat: [],
  16966. mdhd: [],
  16967. mdia: [],
  16968. mfhd: [],
  16969. minf: [],
  16970. moof: [],
  16971. moov: [],
  16972. mp4a: [],
  16973. ".mp3": [],
  16974. dac3: [],
  16975. "ac-3": [],
  16976. mvex: [],
  16977. mvhd: [],
  16978. pasp: [],
  16979. sdtp: [],
  16980. stbl: [],
  16981. stco: [],
  16982. stsc: [],
  16983. stsd: [],
  16984. stsz: [],
  16985. stts: [],
  16986. tfdt: [],
  16987. tfhd: [],
  16988. traf: [],
  16989. trak: [],
  16990. trun: [],
  16991. trex: [],
  16992. tkhd: [],
  16993. vmhd: [],
  16994. smhd: []
  16995. };
  16996. let i2;
  16997. for (i2 in MP4.types) {
  16998. if (MP4.types.hasOwnProperty(i2)) {
  16999. MP4.types[i2] = [i2.charCodeAt(0), i2.charCodeAt(1), i2.charCodeAt(2), i2.charCodeAt(3)];
  17000. }
  17001. }
  17002. const videoHdlr = new Uint8Array([
  17003. 0,
  17004. // version 0
  17005. 0,
  17006. 0,
  17007. 0,
  17008. // flags
  17009. 0,
  17010. 0,
  17011. 0,
  17012. 0,
  17013. // pre_defined
  17014. 118,
  17015. 105,
  17016. 100,
  17017. 101,
  17018. // handler_type: 'vide'
  17019. 0,
  17020. 0,
  17021. 0,
  17022. 0,
  17023. // reserved
  17024. 0,
  17025. 0,
  17026. 0,
  17027. 0,
  17028. // reserved
  17029. 0,
  17030. 0,
  17031. 0,
  17032. 0,
  17033. // reserved
  17034. 86,
  17035. 105,
  17036. 100,
  17037. 101,
  17038. 111,
  17039. 72,
  17040. 97,
  17041. 110,
  17042. 100,
  17043. 108,
  17044. 101,
  17045. 114,
  17046. 0
  17047. // name: 'VideoHandler'
  17048. ]);
  17049. const audioHdlr = new Uint8Array([
  17050. 0,
  17051. // version 0
  17052. 0,
  17053. 0,
  17054. 0,
  17055. // flags
  17056. 0,
  17057. 0,
  17058. 0,
  17059. 0,
  17060. // pre_defined
  17061. 115,
  17062. 111,
  17063. 117,
  17064. 110,
  17065. // handler_type: 'soun'
  17066. 0,
  17067. 0,
  17068. 0,
  17069. 0,
  17070. // reserved
  17071. 0,
  17072. 0,
  17073. 0,
  17074. 0,
  17075. // reserved
  17076. 0,
  17077. 0,
  17078. 0,
  17079. 0,
  17080. // reserved
  17081. 83,
  17082. 111,
  17083. 117,
  17084. 110,
  17085. 100,
  17086. 72,
  17087. 97,
  17088. 110,
  17089. 100,
  17090. 108,
  17091. 101,
  17092. 114,
  17093. 0
  17094. // name: 'SoundHandler'
  17095. ]);
  17096. MP4.HDLR_TYPES = {
  17097. video: videoHdlr,
  17098. audio: audioHdlr
  17099. };
  17100. const dref = new Uint8Array([
  17101. 0,
  17102. // version 0
  17103. 0,
  17104. 0,
  17105. 0,
  17106. // flags
  17107. 0,
  17108. 0,
  17109. 0,
  17110. 1,
  17111. // entry_count
  17112. 0,
  17113. 0,
  17114. 0,
  17115. 12,
  17116. // entry_size
  17117. 117,
  17118. 114,
  17119. 108,
  17120. 32,
  17121. // 'url' type
  17122. 0,
  17123. // version 0
  17124. 0,
  17125. 0,
  17126. 1
  17127. // entry_flags
  17128. ]);
  17129. const stco = new Uint8Array([
  17130. 0,
  17131. // version
  17132. 0,
  17133. 0,
  17134. 0,
  17135. // flags
  17136. 0,
  17137. 0,
  17138. 0,
  17139. 0
  17140. // entry_count
  17141. ]);
  17142. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  17143. MP4.STSZ = new Uint8Array([
  17144. 0,
  17145. // version
  17146. 0,
  17147. 0,
  17148. 0,
  17149. // flags
  17150. 0,
  17151. 0,
  17152. 0,
  17153. 0,
  17154. // sample_size
  17155. 0,
  17156. 0,
  17157. 0,
  17158. 0
  17159. // sample_count
  17160. ]);
  17161. MP4.VMHD = new Uint8Array([
  17162. 0,
  17163. // version
  17164. 0,
  17165. 0,
  17166. 1,
  17167. // flags
  17168. 0,
  17169. 0,
  17170. // graphicsmode
  17171. 0,
  17172. 0,
  17173. 0,
  17174. 0,
  17175. 0,
  17176. 0
  17177. // opcolor
  17178. ]);
  17179. MP4.SMHD = new Uint8Array([
  17180. 0,
  17181. // version
  17182. 0,
  17183. 0,
  17184. 0,
  17185. // flags
  17186. 0,
  17187. 0,
  17188. // balance
  17189. 0,
  17190. 0
  17191. // reserved
  17192. ]);
  17193. MP4.STSD = new Uint8Array([
  17194. 0,
  17195. // version 0
  17196. 0,
  17197. 0,
  17198. 0,
  17199. // flags
  17200. 0,
  17201. 0,
  17202. 0,
  17203. 1
  17204. ]);
  17205. const majorBrand = new Uint8Array([105, 115, 111, 109]);
  17206. const avc1Brand = new Uint8Array([97, 118, 99, 49]);
  17207. const minorVersion = new Uint8Array([0, 0, 0, 1]);
  17208. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  17209. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  17210. }
  17211. static box(type, ...payload) {
  17212. let size = 8;
  17213. let i2 = payload.length;
  17214. const len = i2;
  17215. while (i2--) {
  17216. size += payload[i2].byteLength;
  17217. }
  17218. const result = new Uint8Array(size);
  17219. result[0] = size >> 24 & 255;
  17220. result[1] = size >> 16 & 255;
  17221. result[2] = size >> 8 & 255;
  17222. result[3] = size & 255;
  17223. result.set(type, 4);
  17224. for (i2 = 0, size = 8; i2 < len; i2++) {
  17225. result.set(payload[i2], size);
  17226. size += payload[i2].byteLength;
  17227. }
  17228. return result;
  17229. }
  17230. static hdlr(type) {
  17231. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  17232. }
  17233. static mdat(data) {
  17234. return MP4.box(MP4.types.mdat, data);
  17235. }
  17236. static mdhd(timescale, duration) {
  17237. duration *= timescale;
  17238. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  17239. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  17240. return MP4.box(MP4.types.mdhd, new Uint8Array([
  17241. 1,
  17242. // version 1
  17243. 0,
  17244. 0,
  17245. 0,
  17246. // flags
  17247. 0,
  17248. 0,
  17249. 0,
  17250. 0,
  17251. 0,
  17252. 0,
  17253. 0,
  17254. 2,
  17255. // creation_time
  17256. 0,
  17257. 0,
  17258. 0,
  17259. 0,
  17260. 0,
  17261. 0,
  17262. 0,
  17263. 3,
  17264. // modification_time
  17265. timescale >> 24 & 255,
  17266. timescale >> 16 & 255,
  17267. timescale >> 8 & 255,
  17268. timescale & 255,
  17269. // timescale
  17270. upperWordDuration >> 24,
  17271. upperWordDuration >> 16 & 255,
  17272. upperWordDuration >> 8 & 255,
  17273. upperWordDuration & 255,
  17274. lowerWordDuration >> 24,
  17275. lowerWordDuration >> 16 & 255,
  17276. lowerWordDuration >> 8 & 255,
  17277. lowerWordDuration & 255,
  17278. 85,
  17279. 196,
  17280. // 'und' language (undetermined)
  17281. 0,
  17282. 0
  17283. ]));
  17284. }
  17285. static mdia(track) {
  17286. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale || 0, track.duration || 0), MP4.hdlr(track.type), MP4.minf(track));
  17287. }
  17288. static mfhd(sequenceNumber) {
  17289. return MP4.box(MP4.types.mfhd, new Uint8Array([
  17290. 0,
  17291. 0,
  17292. 0,
  17293. 0,
  17294. // flags
  17295. sequenceNumber >> 24,
  17296. sequenceNumber >> 16 & 255,
  17297. sequenceNumber >> 8 & 255,
  17298. sequenceNumber & 255
  17299. // sequence_number
  17300. ]));
  17301. }
  17302. static minf(track) {
  17303. if (track.type === "audio") {
  17304. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  17305. } else {
  17306. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  17307. }
  17308. }
  17309. static moof(sn, baseMediaDecodeTime, track) {
  17310. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  17311. }
  17312. static moov(tracks) {
  17313. let i2 = tracks.length;
  17314. const boxes = [];
  17315. while (i2--) {
  17316. boxes[i2] = MP4.trak(tracks[i2]);
  17317. }
  17318. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale || 0, tracks[0].duration || 0)].concat(boxes).concat(MP4.mvex(tracks)));
  17319. }
  17320. static mvex(tracks) {
  17321. let i2 = tracks.length;
  17322. const boxes = [];
  17323. while (i2--) {
  17324. boxes[i2] = MP4.trex(tracks[i2]);
  17325. }
  17326. return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);
  17327. }
  17328. static mvhd(timescale, duration) {
  17329. duration *= timescale;
  17330. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  17331. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  17332. const bytes = new Uint8Array([
  17333. 1,
  17334. // version 1
  17335. 0,
  17336. 0,
  17337. 0,
  17338. // flags
  17339. 0,
  17340. 0,
  17341. 0,
  17342. 0,
  17343. 0,
  17344. 0,
  17345. 0,
  17346. 2,
  17347. // creation_time
  17348. 0,
  17349. 0,
  17350. 0,
  17351. 0,
  17352. 0,
  17353. 0,
  17354. 0,
  17355. 3,
  17356. // modification_time
  17357. timescale >> 24 & 255,
  17358. timescale >> 16 & 255,
  17359. timescale >> 8 & 255,
  17360. timescale & 255,
  17361. // timescale
  17362. upperWordDuration >> 24,
  17363. upperWordDuration >> 16 & 255,
  17364. upperWordDuration >> 8 & 255,
  17365. upperWordDuration & 255,
  17366. lowerWordDuration >> 24,
  17367. lowerWordDuration >> 16 & 255,
  17368. lowerWordDuration >> 8 & 255,
  17369. lowerWordDuration & 255,
  17370. 0,
  17371. 1,
  17372. 0,
  17373. 0,
  17374. // 1.0 rate
  17375. 1,
  17376. 0,
  17377. // 1.0 volume
  17378. 0,
  17379. 0,
  17380. // reserved
  17381. 0,
  17382. 0,
  17383. 0,
  17384. 0,
  17385. // reserved
  17386. 0,
  17387. 0,
  17388. 0,
  17389. 0,
  17390. // reserved
  17391. 0,
  17392. 1,
  17393. 0,
  17394. 0,
  17395. 0,
  17396. 0,
  17397. 0,
  17398. 0,
  17399. 0,
  17400. 0,
  17401. 0,
  17402. 0,
  17403. 0,
  17404. 0,
  17405. 0,
  17406. 0,
  17407. 0,
  17408. 1,
  17409. 0,
  17410. 0,
  17411. 0,
  17412. 0,
  17413. 0,
  17414. 0,
  17415. 0,
  17416. 0,
  17417. 0,
  17418. 0,
  17419. 0,
  17420. 0,
  17421. 0,
  17422. 0,
  17423. 64,
  17424. 0,
  17425. 0,
  17426. 0,
  17427. // transformation: unity matrix
  17428. 0,
  17429. 0,
  17430. 0,
  17431. 0,
  17432. 0,
  17433. 0,
  17434. 0,
  17435. 0,
  17436. 0,
  17437. 0,
  17438. 0,
  17439. 0,
  17440. 0,
  17441. 0,
  17442. 0,
  17443. 0,
  17444. 0,
  17445. 0,
  17446. 0,
  17447. 0,
  17448. 0,
  17449. 0,
  17450. 0,
  17451. 0,
  17452. // pre_defined
  17453. 255,
  17454. 255,
  17455. 255,
  17456. 255
  17457. // next_track_ID
  17458. ]);
  17459. return MP4.box(MP4.types.mvhd, bytes);
  17460. }
  17461. static sdtp(track) {
  17462. const samples = track.samples || [];
  17463. const bytes = new Uint8Array(4 + samples.length);
  17464. let i2;
  17465. let flags;
  17466. for (i2 = 0; i2 < samples.length; i2++) {
  17467. flags = samples[i2].flags;
  17468. bytes[i2 + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  17469. }
  17470. return MP4.box(MP4.types.sdtp, bytes);
  17471. }
  17472. static stbl(track) {
  17473. return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
  17474. }
  17475. static avc1(track) {
  17476. let sps = [];
  17477. let pps = [];
  17478. let i2;
  17479. let data;
  17480. let len;
  17481. for (i2 = 0; i2 < track.sps.length; i2++) {
  17482. data = track.sps[i2];
  17483. len = data.byteLength;
  17484. sps.push(len >>> 8 & 255);
  17485. sps.push(len & 255);
  17486. sps = sps.concat(Array.prototype.slice.call(data));
  17487. }
  17488. for (i2 = 0; i2 < track.pps.length; i2++) {
  17489. data = track.pps[i2];
  17490. len = data.byteLength;
  17491. pps.push(len >>> 8 & 255);
  17492. pps.push(len & 255);
  17493. pps = pps.concat(Array.prototype.slice.call(data));
  17494. }
  17495. const avcc = MP4.box(MP4.types.avcC, new Uint8Array([
  17496. 1,
  17497. // version
  17498. sps[3],
  17499. // profile
  17500. sps[4],
  17501. // profile compat
  17502. sps[5],
  17503. // level
  17504. 252 | 3,
  17505. // lengthSizeMinusOne, hard-coded to 4 bytes
  17506. 224 | track.sps.length
  17507. // 3bit reserved (111) + numOfSequenceParameterSets
  17508. ].concat(sps).concat([
  17509. track.pps.length
  17510. // numOfPictureParameterSets
  17511. ]).concat(pps)));
  17512. const width = track.width;
  17513. const height = track.height;
  17514. const hSpacing = track.pixelRatio[0];
  17515. const vSpacing = track.pixelRatio[1];
  17516. return MP4.box(
  17517. MP4.types.avc1,
  17518. new Uint8Array([
  17519. 0,
  17520. 0,
  17521. 0,
  17522. // reserved
  17523. 0,
  17524. 0,
  17525. 0,
  17526. // reserved
  17527. 0,
  17528. 1,
  17529. // data_reference_index
  17530. 0,
  17531. 0,
  17532. // pre_defined
  17533. 0,
  17534. 0,
  17535. // reserved
  17536. 0,
  17537. 0,
  17538. 0,
  17539. 0,
  17540. 0,
  17541. 0,
  17542. 0,
  17543. 0,
  17544. 0,
  17545. 0,
  17546. 0,
  17547. 0,
  17548. // pre_defined
  17549. width >> 8 & 255,
  17550. width & 255,
  17551. // width
  17552. height >> 8 & 255,
  17553. height & 255,
  17554. // height
  17555. 0,
  17556. 72,
  17557. 0,
  17558. 0,
  17559. // horizresolution
  17560. 0,
  17561. 72,
  17562. 0,
  17563. 0,
  17564. // vertresolution
  17565. 0,
  17566. 0,
  17567. 0,
  17568. 0,
  17569. // reserved
  17570. 0,
  17571. 1,
  17572. // frame_count
  17573. 18,
  17574. 100,
  17575. 97,
  17576. 105,
  17577. 108,
  17578. // dailymotion/hls.js
  17579. 121,
  17580. 109,
  17581. 111,
  17582. 116,
  17583. 105,
  17584. 111,
  17585. 110,
  17586. 47,
  17587. 104,
  17588. 108,
  17589. 115,
  17590. 46,
  17591. 106,
  17592. 115,
  17593. 0,
  17594. 0,
  17595. 0,
  17596. 0,
  17597. 0,
  17598. 0,
  17599. 0,
  17600. 0,
  17601. 0,
  17602. 0,
  17603. 0,
  17604. 0,
  17605. 0,
  17606. // compressorname
  17607. 0,
  17608. 24,
  17609. // depth = 24
  17610. 17,
  17611. 17
  17612. ]),
  17613. // pre_defined = -1
  17614. avcc,
  17615. MP4.box(MP4.types.btrt, new Uint8Array([
  17616. 0,
  17617. 28,
  17618. 156,
  17619. 128,
  17620. // bufferSizeDB
  17621. 0,
  17622. 45,
  17623. 198,
  17624. 192,
  17625. // maxBitrate
  17626. 0,
  17627. 45,
  17628. 198,
  17629. 192
  17630. ])),
  17631. // avgBitrate
  17632. MP4.box(MP4.types.pasp, new Uint8Array([
  17633. hSpacing >> 24,
  17634. // hSpacing
  17635. hSpacing >> 16 & 255,
  17636. hSpacing >> 8 & 255,
  17637. hSpacing & 255,
  17638. vSpacing >> 24,
  17639. // vSpacing
  17640. vSpacing >> 16 & 255,
  17641. vSpacing >> 8 & 255,
  17642. vSpacing & 255
  17643. ]))
  17644. );
  17645. }
  17646. static esds(track) {
  17647. const config2 = track.config;
  17648. return new Uint8Array([
  17649. 0,
  17650. // version 0
  17651. 0,
  17652. 0,
  17653. 0,
  17654. // flags
  17655. 3,
  17656. // descriptor_type
  17657. 25,
  17658. // length
  17659. 0,
  17660. 1,
  17661. // es_id
  17662. 0,
  17663. // stream_priority
  17664. 4,
  17665. // descriptor_type
  17666. 17,
  17667. // length
  17668. 64,
  17669. // codec : mpeg4_audio
  17670. 21,
  17671. // stream_type
  17672. 0,
  17673. 0,
  17674. 0,
  17675. // buffer_size
  17676. 0,
  17677. 0,
  17678. 0,
  17679. 0,
  17680. // maxBitrate
  17681. 0,
  17682. 0,
  17683. 0,
  17684. 0,
  17685. // avgBitrate
  17686. 5,
  17687. // descriptor_type
  17688. 2,
  17689. // length
  17690. ...config2,
  17691. 6,
  17692. 1,
  17693. 2
  17694. // GASpecificConfig)); // length + audio config descriptor
  17695. ]);
  17696. }
  17697. static audioStsd(track) {
  17698. const samplerate = track.samplerate || 0;
  17699. return new Uint8Array([
  17700. 0,
  17701. 0,
  17702. 0,
  17703. // reserved
  17704. 0,
  17705. 0,
  17706. 0,
  17707. // reserved
  17708. 0,
  17709. 1,
  17710. // data_reference_index
  17711. 0,
  17712. 0,
  17713. 0,
  17714. 0,
  17715. 0,
  17716. 0,
  17717. 0,
  17718. 0,
  17719. // reserved
  17720. 0,
  17721. track.channelCount || 0,
  17722. // channelcount
  17723. 0,
  17724. 16,
  17725. // sampleSize:16bits
  17726. 0,
  17727. 0,
  17728. 0,
  17729. 0,
  17730. // reserved2
  17731. samplerate >> 8 & 255,
  17732. samplerate & 255,
  17733. //
  17734. 0,
  17735. 0
  17736. ]);
  17737. }
  17738. static mp4a(track) {
  17739. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));
  17740. }
  17741. static mp3(track) {
  17742. return MP4.box(MP4.types[".mp3"], MP4.audioStsd(track));
  17743. }
  17744. static ac3(track) {
  17745. return MP4.box(MP4.types["ac-3"], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));
  17746. }
  17747. static stsd(track) {
  17748. const {
  17749. segmentCodec
  17750. } = track;
  17751. if (track.type === "audio") {
  17752. if (segmentCodec === "aac") {
  17753. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  17754. }
  17755. if (segmentCodec === "ac3" && track.config) {
  17756. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));
  17757. }
  17758. if (segmentCodec === "mp3" && track.codec === "mp3") {
  17759. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  17760. }
  17761. } else {
  17762. if (track.pps && track.sps) {
  17763. if (segmentCodec === "avc") {
  17764. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  17765. }
  17766. if (segmentCodec === "hevc" && track.vps) {
  17767. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.hvc1(track));
  17768. }
  17769. } else {
  17770. throw new Error(`video track missing pps or sps`);
  17771. }
  17772. }
  17773. throw new Error(`unsupported ${track.type} segment codec (${segmentCodec}/${track.codec})`);
  17774. }
  17775. static tkhd(track) {
  17776. const id = track.id;
  17777. const duration = (track.duration || 0) * (track.timescale || 0);
  17778. const width = track.width || 0;
  17779. const height = track.height || 0;
  17780. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  17781. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  17782. return MP4.box(MP4.types.tkhd, new Uint8Array([
  17783. 1,
  17784. // version 1
  17785. 0,
  17786. 0,
  17787. 7,
  17788. // flags
  17789. 0,
  17790. 0,
  17791. 0,
  17792. 0,
  17793. 0,
  17794. 0,
  17795. 0,
  17796. 2,
  17797. // creation_time
  17798. 0,
  17799. 0,
  17800. 0,
  17801. 0,
  17802. 0,
  17803. 0,
  17804. 0,
  17805. 3,
  17806. // modification_time
  17807. id >> 24 & 255,
  17808. id >> 16 & 255,
  17809. id >> 8 & 255,
  17810. id & 255,
  17811. // track_ID
  17812. 0,
  17813. 0,
  17814. 0,
  17815. 0,
  17816. // reserved
  17817. upperWordDuration >> 24,
  17818. upperWordDuration >> 16 & 255,
  17819. upperWordDuration >> 8 & 255,
  17820. upperWordDuration & 255,
  17821. lowerWordDuration >> 24,
  17822. lowerWordDuration >> 16 & 255,
  17823. lowerWordDuration >> 8 & 255,
  17824. lowerWordDuration & 255,
  17825. 0,
  17826. 0,
  17827. 0,
  17828. 0,
  17829. 0,
  17830. 0,
  17831. 0,
  17832. 0,
  17833. // reserved
  17834. 0,
  17835. 0,
  17836. // layer
  17837. 0,
  17838. 0,
  17839. // alternate_group
  17840. 0,
  17841. 0,
  17842. // non-audio track volume
  17843. 0,
  17844. 0,
  17845. // reserved
  17846. 0,
  17847. 1,
  17848. 0,
  17849. 0,
  17850. 0,
  17851. 0,
  17852. 0,
  17853. 0,
  17854. 0,
  17855. 0,
  17856. 0,
  17857. 0,
  17858. 0,
  17859. 0,
  17860. 0,
  17861. 0,
  17862. 0,
  17863. 1,
  17864. 0,
  17865. 0,
  17866. 0,
  17867. 0,
  17868. 0,
  17869. 0,
  17870. 0,
  17871. 0,
  17872. 0,
  17873. 0,
  17874. 0,
  17875. 0,
  17876. 0,
  17877. 0,
  17878. 64,
  17879. 0,
  17880. 0,
  17881. 0,
  17882. // transformation: unity matrix
  17883. width >> 8 & 255,
  17884. width & 255,
  17885. 0,
  17886. 0,
  17887. // width
  17888. height >> 8 & 255,
  17889. height & 255,
  17890. 0,
  17891. 0
  17892. // height
  17893. ]));
  17894. }
  17895. static traf(track, baseMediaDecodeTime) {
  17896. const sampleDependencyTable = MP4.sdtp(track);
  17897. const id = track.id;
  17898. const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  17899. const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  17900. return MP4.box(
  17901. MP4.types.traf,
  17902. MP4.box(MP4.types.tfhd, new Uint8Array([
  17903. 0,
  17904. // version 0
  17905. 0,
  17906. 0,
  17907. 0,
  17908. // flags
  17909. id >> 24,
  17910. id >> 16 & 255,
  17911. id >> 8 & 255,
  17912. id & 255
  17913. // track_ID
  17914. ])),
  17915. MP4.box(MP4.types.tfdt, new Uint8Array([
  17916. 1,
  17917. // version 1
  17918. 0,
  17919. 0,
  17920. 0,
  17921. // flags
  17922. upperWordBaseMediaDecodeTime >> 24,
  17923. upperWordBaseMediaDecodeTime >> 16 & 255,
  17924. upperWordBaseMediaDecodeTime >> 8 & 255,
  17925. upperWordBaseMediaDecodeTime & 255,
  17926. lowerWordBaseMediaDecodeTime >> 24,
  17927. lowerWordBaseMediaDecodeTime >> 16 & 255,
  17928. lowerWordBaseMediaDecodeTime >> 8 & 255,
  17929. lowerWordBaseMediaDecodeTime & 255
  17930. ])),
  17931. MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
  17932. 20 + // tfdt
  17933. 8 + // traf header
  17934. 16 + // mfhd
  17935. 8 + // moof header
  17936. 8),
  17937. // mdat header
  17938. sampleDependencyTable
  17939. );
  17940. }
  17941. /**
  17942. * Generate a track box.
  17943. * @param track a track definition
  17944. */
  17945. static trak(track) {
  17946. track.duration = track.duration || 4294967295;
  17947. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  17948. }
  17949. static trex(track) {
  17950. const id = track.id;
  17951. return MP4.box(MP4.types.trex, new Uint8Array([
  17952. 0,
  17953. // version 0
  17954. 0,
  17955. 0,
  17956. 0,
  17957. // flags
  17958. id >> 24,
  17959. id >> 16 & 255,
  17960. id >> 8 & 255,
  17961. id & 255,
  17962. // track_ID
  17963. 0,
  17964. 0,
  17965. 0,
  17966. 1,
  17967. // default_sample_description_index
  17968. 0,
  17969. 0,
  17970. 0,
  17971. 0,
  17972. // default_sample_duration
  17973. 0,
  17974. 0,
  17975. 0,
  17976. 0,
  17977. // default_sample_size
  17978. 0,
  17979. 1,
  17980. 0,
  17981. 1
  17982. // default_sample_flags
  17983. ]));
  17984. }
  17985. static trun(track, offset) {
  17986. const samples = track.samples || [];
  17987. const len = samples.length;
  17988. const arraylen = 12 + 16 * len;
  17989. const array2 = new Uint8Array(arraylen);
  17990. let i2;
  17991. let sample;
  17992. let duration;
  17993. let size;
  17994. let flags;
  17995. let cts;
  17996. offset += 8 + arraylen;
  17997. array2.set([
  17998. track.type === "video" ? 1 : 0,
  17999. // version 1 for video with signed-int sample_composition_time_offset
  18000. 0,
  18001. 15,
  18002. 1,
  18003. // flags
  18004. len >>> 24 & 255,
  18005. len >>> 16 & 255,
  18006. len >>> 8 & 255,
  18007. len & 255,
  18008. // sample_count
  18009. offset >>> 24 & 255,
  18010. offset >>> 16 & 255,
  18011. offset >>> 8 & 255,
  18012. offset & 255
  18013. // data_offset
  18014. ], 0);
  18015. for (i2 = 0; i2 < len; i2++) {
  18016. sample = samples[i2];
  18017. duration = sample.duration;
  18018. size = sample.size;
  18019. flags = sample.flags;
  18020. cts = sample.cts;
  18021. array2.set([
  18022. duration >>> 24 & 255,
  18023. duration >>> 16 & 255,
  18024. duration >>> 8 & 255,
  18025. duration & 255,
  18026. // sample_duration
  18027. size >>> 24 & 255,
  18028. size >>> 16 & 255,
  18029. size >>> 8 & 255,
  18030. size & 255,
  18031. // sample_size
  18032. flags.isLeading << 2 | flags.dependsOn,
  18033. flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync,
  18034. flags.degradPrio & 240 << 8,
  18035. flags.degradPrio & 15,
  18036. // sample_flags
  18037. cts >>> 24 & 255,
  18038. cts >>> 16 & 255,
  18039. cts >>> 8 & 255,
  18040. cts & 255
  18041. // sample_composition_time_offset
  18042. ], 12 + 16 * i2);
  18043. }
  18044. return MP4.box(MP4.types.trun, array2);
  18045. }
  18046. static initSegment(tracks) {
  18047. if (!MP4.types) {
  18048. MP4.init();
  18049. }
  18050. const movie = MP4.moov(tracks);
  18051. const result = appendUint8Array(MP4.FTYP, movie);
  18052. return result;
  18053. }
  18054. static hvc1(track) {
  18055. const ps2 = track.params;
  18056. const units = [track.vps, track.sps, track.pps];
  18057. const NALuLengthSize = 4;
  18058. const config2 = 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]);
  18059. let length = config2.length;
  18060. for (let i2 = 0; i2 < units.length; i2 += 1) {
  18061. length += 3;
  18062. for (let j2 = 0; j2 < units[i2].length; j2 += 1) {
  18063. length += 2 + units[i2][j2].length;
  18064. }
  18065. }
  18066. const hvcC = new Uint8Array(length);
  18067. hvcC.set(config2, 0);
  18068. length = config2.length;
  18069. const iMax = units.length - 1;
  18070. for (let i2 = 0; i2 < units.length; i2 += 1) {
  18071. hvcC.set(new Uint8Array([32 + i2 | (i2 === iMax ? 128 : 0), 0, units[i2].length]), length);
  18072. length += 3;
  18073. for (let j2 = 0; j2 < units[i2].length; j2 += 1) {
  18074. hvcC.set(new Uint8Array([units[i2][j2].length >> 8, units[i2][j2].length & 255]), length);
  18075. length += 2;
  18076. hvcC.set(units[i2][j2], length);
  18077. length += units[i2][j2].length;
  18078. }
  18079. }
  18080. const hvcc = MP4.box(MP4.types.hvcC, hvcC);
  18081. const width = track.width;
  18082. const height = track.height;
  18083. const hSpacing = track.pixelRatio[0];
  18084. const vSpacing = track.pixelRatio[1];
  18085. return MP4.box(
  18086. MP4.types.hvc1,
  18087. new Uint8Array([
  18088. 0,
  18089. 0,
  18090. 0,
  18091. // reserved
  18092. 0,
  18093. 0,
  18094. 0,
  18095. // reserved
  18096. 0,
  18097. 1,
  18098. // data_reference_index
  18099. 0,
  18100. 0,
  18101. // pre_defined
  18102. 0,
  18103. 0,
  18104. // reserved
  18105. 0,
  18106. 0,
  18107. 0,
  18108. 0,
  18109. 0,
  18110. 0,
  18111. 0,
  18112. 0,
  18113. 0,
  18114. 0,
  18115. 0,
  18116. 0,
  18117. // pre_defined
  18118. width >> 8 & 255,
  18119. width & 255,
  18120. // width
  18121. height >> 8 & 255,
  18122. height & 255,
  18123. // height
  18124. 0,
  18125. 72,
  18126. 0,
  18127. 0,
  18128. // horizresolution
  18129. 0,
  18130. 72,
  18131. 0,
  18132. 0,
  18133. // vertresolution
  18134. 0,
  18135. 0,
  18136. 0,
  18137. 0,
  18138. // reserved
  18139. 0,
  18140. 1,
  18141. // frame_count
  18142. 18,
  18143. 100,
  18144. 97,
  18145. 105,
  18146. 108,
  18147. // dailymotion/hls.js
  18148. 121,
  18149. 109,
  18150. 111,
  18151. 116,
  18152. 105,
  18153. 111,
  18154. 110,
  18155. 47,
  18156. 104,
  18157. 108,
  18158. 115,
  18159. 46,
  18160. 106,
  18161. 115,
  18162. 0,
  18163. 0,
  18164. 0,
  18165. 0,
  18166. 0,
  18167. 0,
  18168. 0,
  18169. 0,
  18170. 0,
  18171. 0,
  18172. 0,
  18173. 0,
  18174. 0,
  18175. // compressorname
  18176. 0,
  18177. 24,
  18178. // depth = 24
  18179. 17,
  18180. 17
  18181. ]),
  18182. // pre_defined = -1
  18183. hvcc,
  18184. MP4.box(MP4.types.btrt, new Uint8Array([
  18185. 0,
  18186. 28,
  18187. 156,
  18188. 128,
  18189. // bufferSizeDB
  18190. 0,
  18191. 45,
  18192. 198,
  18193. 192,
  18194. // maxBitrate
  18195. 0,
  18196. 45,
  18197. 198,
  18198. 192
  18199. ])),
  18200. // avgBitrate
  18201. MP4.box(MP4.types.pasp, new Uint8Array([
  18202. hSpacing >> 24,
  18203. // hSpacing
  18204. hSpacing >> 16 & 255,
  18205. hSpacing >> 8 & 255,
  18206. hSpacing & 255,
  18207. vSpacing >> 24,
  18208. // vSpacing
  18209. vSpacing >> 16 & 255,
  18210. vSpacing >> 8 & 255,
  18211. vSpacing & 255
  18212. ]))
  18213. );
  18214. }
  18215. }
  18216. MP4.types = void 0;
  18217. MP4.HDLR_TYPES = void 0;
  18218. MP4.STTS = void 0;
  18219. MP4.STSC = void 0;
  18220. MP4.STCO = void 0;
  18221. MP4.STSZ = void 0;
  18222. MP4.VMHD = void 0;
  18223. MP4.SMHD = void 0;
  18224. MP4.STSD = void 0;
  18225. MP4.FTYP = void 0;
  18226. MP4.DINF = void 0;
  18227. const MPEG_TS_CLOCK_FREQ_HZ = 9e4;
  18228. function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round2 = false) {
  18229. const result = baseTime * destScale * srcBase;
  18230. return round2 ? Math.round(result) : result;
  18231. }
  18232. function toTimescaleFromScale(baseTime, destScale, srcScale = 1, round2 = false) {
  18233. return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round2);
  18234. }
  18235. function toMsFromMpegTsClock(baseTime, round2 = false) {
  18236. return toTimescaleFromBase(baseTime, 1e3, 1 / MPEG_TS_CLOCK_FREQ_HZ, round2);
  18237. }
  18238. function toMpegTsClockFromTimescale(baseTime, srcScale = 1) {
  18239. return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
  18240. }
  18241. const MAX_SILENT_FRAME_DURATION = 10 * 1e3;
  18242. const AAC_SAMPLES_PER_FRAME = 1024;
  18243. const MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  18244. const AC3_SAMPLES_PER_FRAME = 1536;
  18245. let chromeVersion = null;
  18246. let safariWebkitVersion = null;
  18247. function createMp4Sample(isKeyframe, duration, size, cts) {
  18248. return {
  18249. duration,
  18250. size,
  18251. cts,
  18252. flags: {
  18253. isLeading: 0,
  18254. isDependedOn: 0,
  18255. hasRedundancy: 0,
  18256. degradPrio: 0,
  18257. dependsOn: isKeyframe ? 2 : 1,
  18258. isNonSync: isKeyframe ? 0 : 1
  18259. }
  18260. };
  18261. }
  18262. class MP4Remuxer extends Logger {
  18263. constructor(observer, config2, typeSupported, logger2) {
  18264. super("mp4-remuxer", logger2);
  18265. this.observer = void 0;
  18266. this.config = void 0;
  18267. this.typeSupported = void 0;
  18268. this.ISGenerated = false;
  18269. this._initPTS = null;
  18270. this._initDTS = null;
  18271. this.nextVideoTs = null;
  18272. this.nextAudioTs = null;
  18273. this.videoSampleDuration = null;
  18274. this.isAudioContiguous = false;
  18275. this.isVideoContiguous = false;
  18276. this.videoTrackConfig = void 0;
  18277. this.observer = observer;
  18278. this.config = config2;
  18279. this.typeSupported = typeSupported;
  18280. this.ISGenerated = false;
  18281. if (chromeVersion === null) {
  18282. const userAgent = navigator.userAgent || "";
  18283. const result = userAgent.match(/Chrome\/(\d+)/i);
  18284. chromeVersion = result ? parseInt(result[1]) : 0;
  18285. }
  18286. if (safariWebkitVersion === null) {
  18287. const result = navigator.userAgent.match(/Safari\/(\d+)/i);
  18288. safariWebkitVersion = result ? parseInt(result[1]) : 0;
  18289. }
  18290. }
  18291. destroy() {
  18292. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  18293. }
  18294. resetTimeStamp(defaultTimeStamp) {
  18295. this.log("initPTS & initDTS reset");
  18296. this._initPTS = this._initDTS = defaultTimeStamp;
  18297. }
  18298. resetNextTimestamp() {
  18299. this.log("reset next timestamp");
  18300. this.isVideoContiguous = false;
  18301. this.isAudioContiguous = false;
  18302. }
  18303. resetInitSegment() {
  18304. this.log("ISGenerated flag reset");
  18305. this.ISGenerated = false;
  18306. this.videoTrackConfig = void 0;
  18307. }
  18308. getVideoStartPts(videoSamples) {
  18309. let rolloverDetected = false;
  18310. const firstPts = videoSamples[0].pts;
  18311. const startPTS = videoSamples.reduce((minPTS, sample) => {
  18312. let pts = sample.pts;
  18313. let delta = pts - minPTS;
  18314. if (delta < -4294967296) {
  18315. rolloverDetected = true;
  18316. pts = normalizePts(pts, firstPts);
  18317. delta = pts - minPTS;
  18318. }
  18319. if (delta > 0) {
  18320. return minPTS;
  18321. }
  18322. return pts;
  18323. }, firstPts);
  18324. if (rolloverDetected) {
  18325. this.debug("PTS rollover detected");
  18326. }
  18327. return startPTS;
  18328. }
  18329. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  18330. let video2;
  18331. let audio;
  18332. let initSegment;
  18333. let text;
  18334. let id3;
  18335. let independent;
  18336. let audioTimeOffset = timeOffset;
  18337. let videoTimeOffset = timeOffset;
  18338. const hasAudio = audioTrack.pid > -1;
  18339. const hasVideo = videoTrack.pid > -1;
  18340. const length = videoTrack.samples.length;
  18341. const enoughAudioSamples = audioTrack.samples.length > 0;
  18342. const enoughVideoSamples = flush && length > 0 || length > 1;
  18343. const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  18344. if (canRemuxAvc) {
  18345. if (this.ISGenerated) {
  18346. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  18347. const config2 = this.videoTrackConfig;
  18348. if (config2 && (videoTrack.width !== config2.width || videoTrack.height !== config2.height || ((_videoTrack$pixelRati = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati[0]) !== ((_config$pixelRatio = config2.pixelRatio) == null ? void 0 : _config$pixelRatio[0]) || ((_videoTrack$pixelRati2 = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati2[1]) !== ((_config$pixelRatio2 = config2.pixelRatio) == null ? void 0 : _config$pixelRatio2[1])) || !config2 && enoughVideoSamples || this.nextAudioTs === null && enoughAudioSamples) {
  18349. this.resetInitSegment();
  18350. }
  18351. }
  18352. if (!this.ISGenerated) {
  18353. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  18354. }
  18355. const isVideoContiguous = this.isVideoContiguous;
  18356. let firstKeyFrameIndex = -1;
  18357. let firstKeyFramePTS;
  18358. if (enoughVideoSamples) {
  18359. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  18360. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  18361. independent = true;
  18362. if (firstKeyFrameIndex > 0) {
  18363. this.warn(`Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);
  18364. const startPTS = this.getVideoStartPts(videoTrack.samples);
  18365. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  18366. videoTrack.dropped += firstKeyFrameIndex;
  18367. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  18368. firstKeyFramePTS = videoTimeOffset;
  18369. } else if (firstKeyFrameIndex === -1) {
  18370. this.warn(`No keyframe found out of ${length} video samples`);
  18371. independent = false;
  18372. }
  18373. }
  18374. }
  18375. if (this.ISGenerated) {
  18376. if (enoughAudioSamples && enoughVideoSamples) {
  18377. const startPTS = this.getVideoStartPts(videoTrack.samples);
  18378. const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;
  18379. const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  18380. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  18381. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  18382. }
  18383. if (enoughAudioSamples) {
  18384. if (!audioTrack.samplerate) {
  18385. this.warn("regenerate InitSegment as audio detected");
  18386. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  18387. }
  18388. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : void 0);
  18389. if (enoughVideoSamples) {
  18390. const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  18391. if (!videoTrack.inputTimeScale) {
  18392. this.warn("regenerate InitSegment as video detected");
  18393. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  18394. }
  18395. video2 = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  18396. }
  18397. } else if (enoughVideoSamples) {
  18398. video2 = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  18399. }
  18400. if (video2) {
  18401. video2.firstKeyFrame = firstKeyFrameIndex;
  18402. video2.independent = firstKeyFrameIndex !== -1;
  18403. video2.firstKeyFramePTS = firstKeyFramePTS;
  18404. }
  18405. }
  18406. }
  18407. if (this.ISGenerated && this._initPTS && this._initDTS) {
  18408. if (id3Track.samples.length) {
  18409. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  18410. }
  18411. if (textTrack.samples.length) {
  18412. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  18413. }
  18414. }
  18415. return {
  18416. audio,
  18417. video: video2,
  18418. initSegment,
  18419. independent,
  18420. text,
  18421. id3
  18422. };
  18423. }
  18424. generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  18425. const audioSamples = audioTrack.samples;
  18426. const videoSamples = videoTrack.samples;
  18427. const typeSupported = this.typeSupported;
  18428. const tracks = {};
  18429. const _initPTS = this._initPTS;
  18430. let computePTSDTS = !_initPTS || accurateTimeOffset;
  18431. let container = "audio/mp4";
  18432. let initPTS;
  18433. let initDTS;
  18434. let timescale;
  18435. let trackId;
  18436. if (computePTSDTS) {
  18437. initPTS = initDTS = Infinity;
  18438. }
  18439. if (audioTrack.config && audioSamples.length) {
  18440. audioTrack.timescale = audioTrack.samplerate;
  18441. switch (audioTrack.segmentCodec) {
  18442. case "mp3":
  18443. if (typeSupported.mpeg) {
  18444. container = "audio/mpeg";
  18445. audioTrack.codec = "";
  18446. } else if (typeSupported.mp3) {
  18447. audioTrack.codec = "mp3";
  18448. }
  18449. break;
  18450. case "ac3":
  18451. audioTrack.codec = "ac-3";
  18452. break;
  18453. }
  18454. tracks.audio = {
  18455. id: "audio",
  18456. container,
  18457. codec: audioTrack.codec,
  18458. initSegment: audioTrack.segmentCodec === "mp3" && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  18459. metadata: {
  18460. channelCount: audioTrack.channelCount
  18461. }
  18462. };
  18463. if (computePTSDTS) {
  18464. trackId = audioTrack.id;
  18465. timescale = audioTrack.inputTimeScale;
  18466. if (!_initPTS || timescale !== _initPTS.timescale) {
  18467. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  18468. } else {
  18469. computePTSDTS = false;
  18470. }
  18471. }
  18472. }
  18473. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  18474. videoTrack.timescale = videoTrack.inputTimeScale;
  18475. tracks.video = {
  18476. id: "main",
  18477. container: "video/mp4",
  18478. codec: videoTrack.codec,
  18479. initSegment: MP4.initSegment([videoTrack]),
  18480. metadata: {
  18481. width: videoTrack.width,
  18482. height: videoTrack.height
  18483. }
  18484. };
  18485. if (computePTSDTS) {
  18486. trackId = videoTrack.id;
  18487. timescale = videoTrack.inputTimeScale;
  18488. if (!_initPTS || timescale !== _initPTS.timescale) {
  18489. const startPTS = this.getVideoStartPts(videoSamples);
  18490. const startOffset = Math.round(timescale * timeOffset);
  18491. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  18492. initPTS = Math.min(initPTS, startPTS - startOffset);
  18493. } else {
  18494. computePTSDTS = false;
  18495. }
  18496. }
  18497. this.videoTrackConfig = {
  18498. width: videoTrack.width,
  18499. height: videoTrack.height,
  18500. pixelRatio: videoTrack.pixelRatio
  18501. };
  18502. }
  18503. if (Object.keys(tracks).length) {
  18504. this.ISGenerated = true;
  18505. if (computePTSDTS) {
  18506. this._initPTS = {
  18507. baseTime: initPTS,
  18508. timescale
  18509. };
  18510. this._initDTS = {
  18511. baseTime: initDTS,
  18512. timescale
  18513. };
  18514. } else {
  18515. initPTS = timescale = void 0;
  18516. }
  18517. return {
  18518. tracks,
  18519. initPTS,
  18520. timescale,
  18521. trackId
  18522. };
  18523. }
  18524. }
  18525. remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  18526. const timeScale = track.inputTimeScale;
  18527. const inputSamples = track.samples;
  18528. const outputSamples = [];
  18529. const nbSamples = inputSamples.length;
  18530. const initPTS = this._initPTS;
  18531. const initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  18532. let nextVideoTs = this.nextVideoTs;
  18533. let offset = 8;
  18534. let mp4SampleDuration = this.videoSampleDuration;
  18535. let firstDTS;
  18536. let lastDTS;
  18537. let minPTS = Number.POSITIVE_INFINITY;
  18538. let maxPTS = Number.NEGATIVE_INFINITY;
  18539. let sortSamples = false;
  18540. if (!contiguous || nextVideoTs === null) {
  18541. const pts = initTime + timeOffset * timeScale;
  18542. const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  18543. if (chromeVersion && nextVideoTs !== null && Math.abs(pts - cts - (nextVideoTs + initTime)) < 15e3) {
  18544. contiguous = true;
  18545. } else {
  18546. nextVideoTs = pts - cts - initTime;
  18547. }
  18548. }
  18549. const nextVideoPts = nextVideoTs + initTime;
  18550. for (let i2 = 0; i2 < nbSamples; i2++) {
  18551. const sample = inputSamples[i2];
  18552. sample.pts = normalizePts(sample.pts, nextVideoPts);
  18553. sample.dts = normalizePts(sample.dts, nextVideoPts);
  18554. if (sample.dts < inputSamples[i2 > 0 ? i2 - 1 : i2].dts) {
  18555. sortSamples = true;
  18556. }
  18557. }
  18558. if (sortSamples) {
  18559. inputSamples.sort(function(a2, b2) {
  18560. const deltadts = a2.dts - b2.dts;
  18561. const deltapts = a2.pts - b2.pts;
  18562. return deltadts || deltapts;
  18563. });
  18564. }
  18565. firstDTS = inputSamples[0].dts;
  18566. lastDTS = inputSamples[inputSamples.length - 1].dts;
  18567. const inputDuration = lastDTS - firstDTS;
  18568. const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  18569. if (contiguous) {
  18570. const delta = firstDTS - nextVideoPts;
  18571. const foundHole = delta > averageSampleDuration;
  18572. const foundOverlap = delta < -1;
  18573. if (foundHole || foundOverlap) {
  18574. if (foundHole) {
  18575. this.warn(`${(track.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);
  18576. } else {
  18577. this.warn(`${(track.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);
  18578. }
  18579. if (!foundOverlap || nextVideoPts >= inputSamples[0].pts || chromeVersion) {
  18580. firstDTS = nextVideoPts;
  18581. const firstPTS = inputSamples[0].pts - delta;
  18582. if (foundHole) {
  18583. inputSamples[0].dts = firstDTS;
  18584. inputSamples[0].pts = firstPTS;
  18585. } else {
  18586. let isPTSOrderRetained = true;
  18587. for (let i2 = 0; i2 < inputSamples.length; i2++) {
  18588. if (inputSamples[i2].dts > firstPTS && isPTSOrderRetained) {
  18589. break;
  18590. }
  18591. const prevPTS = inputSamples[i2].pts;
  18592. inputSamples[i2].dts -= delta;
  18593. inputSamples[i2].pts -= delta;
  18594. if (i2 < inputSamples.length - 1) {
  18595. const nextSamplePTS = inputSamples[i2 + 1].pts;
  18596. const currentSamplePTS = inputSamples[i2].pts;
  18597. const currentOrder = nextSamplePTS <= currentSamplePTS;
  18598. const prevOrder = nextSamplePTS <= prevPTS;
  18599. isPTSOrderRetained = currentOrder == prevOrder;
  18600. }
  18601. }
  18602. }
  18603. this.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);
  18604. }
  18605. }
  18606. }
  18607. firstDTS = Math.max(0, firstDTS);
  18608. let nbNalu = 0;
  18609. let naluLen = 0;
  18610. let dtsStep = firstDTS;
  18611. for (let i2 = 0; i2 < nbSamples; i2++) {
  18612. const sample = inputSamples[i2];
  18613. const units = sample.units;
  18614. const nbUnits = units.length;
  18615. let sampleLen = 0;
  18616. for (let j2 = 0; j2 < nbUnits; j2++) {
  18617. sampleLen += units[j2].data.length;
  18618. }
  18619. naluLen += sampleLen;
  18620. nbNalu += nbUnits;
  18621. sample.length = sampleLen;
  18622. if (sample.dts < dtsStep) {
  18623. sample.dts = dtsStep;
  18624. dtsStep += averageSampleDuration / 4 | 0 || 1;
  18625. } else {
  18626. dtsStep = sample.dts;
  18627. }
  18628. minPTS = Math.min(sample.pts, minPTS);
  18629. maxPTS = Math.max(sample.pts, maxPTS);
  18630. }
  18631. lastDTS = inputSamples[nbSamples - 1].dts;
  18632. const mdatSize = naluLen + 4 * nbNalu + 8;
  18633. let mdat;
  18634. try {
  18635. mdat = new Uint8Array(mdatSize);
  18636. } catch (err) {
  18637. this.observer.emit(Events.ERROR, Events.ERROR, {
  18638. type: ErrorTypes.MUX_ERROR,
  18639. details: ErrorDetails.REMUX_ALLOC_ERROR,
  18640. fatal: false,
  18641. error: err,
  18642. bytes: mdatSize,
  18643. reason: `fail allocating video mdat ${mdatSize}`
  18644. });
  18645. return;
  18646. }
  18647. const view2 = new DataView(mdat.buffer);
  18648. view2.setUint32(0, mdatSize);
  18649. mdat.set(MP4.types.mdat, 4);
  18650. let stretchedLastFrame = false;
  18651. let minDtsDelta = Number.POSITIVE_INFINITY;
  18652. let minPtsDelta = Number.POSITIVE_INFINITY;
  18653. let maxDtsDelta = Number.NEGATIVE_INFINITY;
  18654. let maxPtsDelta = Number.NEGATIVE_INFINITY;
  18655. for (let i2 = 0; i2 < nbSamples; i2++) {
  18656. const VideoSample = inputSamples[i2];
  18657. const VideoSampleUnits = VideoSample.units;
  18658. let mp4SampleLength = 0;
  18659. for (let j2 = 0, nbUnits = VideoSampleUnits.length; j2 < nbUnits; j2++) {
  18660. const unit = VideoSampleUnits[j2];
  18661. const unitData = unit.data;
  18662. const unitDataLen = unit.data.byteLength;
  18663. view2.setUint32(offset, unitDataLen);
  18664. offset += 4;
  18665. mdat.set(unitData, offset);
  18666. offset += unitDataLen;
  18667. mp4SampleLength += 4 + unitDataLen;
  18668. }
  18669. let ptsDelta;
  18670. if (i2 < nbSamples - 1) {
  18671. mp4SampleDuration = inputSamples[i2 + 1].dts - VideoSample.dts;
  18672. ptsDelta = inputSamples[i2 + 1].pts - VideoSample.pts;
  18673. } else {
  18674. const config2 = this.config;
  18675. const lastFrameDuration = i2 > 0 ? VideoSample.dts - inputSamples[i2 - 1].dts : averageSampleDuration;
  18676. ptsDelta = i2 > 0 ? VideoSample.pts - inputSamples[i2 - 1].pts : averageSampleDuration;
  18677. if (config2.stretchShortVideoTrack && this.nextAudioTs !== null) {
  18678. const gapTolerance = Math.floor(config2.maxBufferHole * timeScale);
  18679. const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioTs + initTime) - VideoSample.pts;
  18680. if (deltaToFrameEnd > gapTolerance) {
  18681. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  18682. if (mp4SampleDuration < 0) {
  18683. mp4SampleDuration = lastFrameDuration;
  18684. } else {
  18685. stretchedLastFrame = true;
  18686. }
  18687. this.log(`It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);
  18688. } else {
  18689. mp4SampleDuration = lastFrameDuration;
  18690. }
  18691. } else {
  18692. mp4SampleDuration = lastFrameDuration;
  18693. }
  18694. }
  18695. const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  18696. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  18697. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  18698. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  18699. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  18700. outputSamples.push(createMp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  18701. }
  18702. if (outputSamples.length) {
  18703. if (chromeVersion) {
  18704. if (chromeVersion < 70) {
  18705. const flags = outputSamples[0].flags;
  18706. flags.dependsOn = 2;
  18707. flags.isNonSync = 0;
  18708. }
  18709. } else if (safariWebkitVersion) {
  18710. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  18711. this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");
  18712. let dts = firstDTS;
  18713. for (let i2 = 0, len = outputSamples.length; i2 < len; i2++) {
  18714. const nextDts = dts + outputSamples[i2].duration;
  18715. const pts = dts + outputSamples[i2].cts;
  18716. if (i2 < len - 1) {
  18717. const nextPts = nextDts + outputSamples[i2 + 1].cts;
  18718. outputSamples[i2].duration = nextPts - pts;
  18719. } else {
  18720. outputSamples[i2].duration = i2 ? outputSamples[i2 - 1].duration : averageSampleDuration;
  18721. }
  18722. outputSamples[i2].cts = 0;
  18723. dts = nextDts;
  18724. }
  18725. }
  18726. }
  18727. }
  18728. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  18729. const endDTS = lastDTS + mp4SampleDuration;
  18730. this.nextVideoTs = nextVideoTs = endDTS - initTime;
  18731. this.videoSampleDuration = mp4SampleDuration;
  18732. this.isVideoContiguous = true;
  18733. const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends(track, {
  18734. samples: outputSamples
  18735. }));
  18736. const type = "video";
  18737. const data = {
  18738. data1: moof,
  18739. data2: mdat,
  18740. startPTS: (minPTS - initTime) / timeScale,
  18741. endPTS: (maxPTS + mp4SampleDuration - initTime) / timeScale,
  18742. startDTS: (firstDTS - initTime) / timeScale,
  18743. endDTS: nextVideoTs / timeScale,
  18744. type,
  18745. hasAudio: false,
  18746. hasVideo: true,
  18747. nb: outputSamples.length,
  18748. dropped: track.dropped
  18749. };
  18750. track.samples = [];
  18751. track.dropped = 0;
  18752. return data;
  18753. }
  18754. getSamplesPerFrame(track) {
  18755. switch (track.segmentCodec) {
  18756. case "mp3":
  18757. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  18758. case "ac3":
  18759. return AC3_SAMPLES_PER_FRAME;
  18760. default:
  18761. return AAC_SAMPLES_PER_FRAME;
  18762. }
  18763. }
  18764. remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  18765. const inputTimeScale = track.inputTimeScale;
  18766. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  18767. const scaleFactor = inputTimeScale / mp4timeScale;
  18768. const mp4SampleDuration = this.getSamplesPerFrame(track);
  18769. const inputSampleDuration = mp4SampleDuration * scaleFactor;
  18770. const initPTS = this._initPTS;
  18771. const rawMPEG = track.segmentCodec === "mp3" && this.typeSupported.mpeg;
  18772. const outputSamples = [];
  18773. const alignedWithVideo = videoTimeOffset !== void 0;
  18774. let inputSamples = track.samples;
  18775. let offset = rawMPEG ? 0 : 8;
  18776. let nextAudioTs = this.nextAudioTs || -1;
  18777. const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  18778. const timeOffsetMpegTS = initTime + timeOffset * inputTimeScale;
  18779. 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);
  18780. inputSamples.forEach(function(sample) {
  18781. sample.pts = normalizePts(sample.pts, timeOffsetMpegTS);
  18782. });
  18783. if (!contiguous || nextAudioTs < 0) {
  18784. inputSamples = inputSamples.filter((sample) => sample.pts >= 0);
  18785. if (!inputSamples.length) {
  18786. return;
  18787. }
  18788. if (videoTimeOffset === 0) {
  18789. nextAudioTs = 0;
  18790. } else if (accurateTimeOffset && !alignedWithVideo) {
  18791. nextAudioTs = Math.max(0, timeOffsetMpegTS - initTime);
  18792. } else {
  18793. nextAudioTs = inputSamples[0].pts - initTime;
  18794. }
  18795. }
  18796. if (track.segmentCodec === "aac") {
  18797. const maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  18798. for (let i2 = 0, nextPts = nextAudioTs + initTime; i2 < inputSamples.length; i2++) {
  18799. const sample = inputSamples[i2];
  18800. const pts = sample.pts;
  18801. const delta = pts - nextPts;
  18802. const duration = Math.abs(1e3 * delta / inputTimeScale);
  18803. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  18804. if (i2 === 0) {
  18805. this.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps marker by ${Math.round(1e3 * delta / inputTimeScale)} ms.`);
  18806. this.nextAudioTs = nextAudioTs = pts - initTime;
  18807. nextPts = pts;
  18808. }
  18809. } else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  18810. let missing = Math.round(delta / inputSampleDuration);
  18811. nextPts = pts - missing * inputSampleDuration;
  18812. while (nextPts < 0 && missing && inputSampleDuration) {
  18813. missing--;
  18814. nextPts += inputSampleDuration;
  18815. }
  18816. if (i2 === 0) {
  18817. this.nextAudioTs = nextAudioTs = nextPts - initTime;
  18818. }
  18819. this.warn(`Injecting ${missing} audio frames @ ${((nextPts - initTime) / inputTimeScale).toFixed(3)}s due to ${Math.round(1e3 * delta / inputTimeScale)} ms gap.`);
  18820. for (let j2 = 0; j2 < missing; j2++) {
  18821. let fillFrame = AAC.getSilentFrame(track.parsedCodec || track.manifestCodec || track.codec, track.channelCount);
  18822. if (!fillFrame) {
  18823. this.log("Unable to get silent frame for given audio codec; duplicating last frame instead.");
  18824. fillFrame = sample.unit.subarray();
  18825. }
  18826. inputSamples.splice(i2, 0, {
  18827. unit: fillFrame,
  18828. pts: nextPts
  18829. });
  18830. nextPts += inputSampleDuration;
  18831. i2++;
  18832. }
  18833. }
  18834. sample.pts = nextPts;
  18835. nextPts += inputSampleDuration;
  18836. }
  18837. }
  18838. let firstPTS = null;
  18839. let lastPTS = null;
  18840. let mdat;
  18841. let mdatSize = 0;
  18842. let sampleLength = inputSamples.length;
  18843. while (sampleLength--) {
  18844. mdatSize += inputSamples[sampleLength].unit.byteLength;
  18845. }
  18846. for (let j2 = 0, _nbSamples = inputSamples.length; j2 < _nbSamples; j2++) {
  18847. const audioSample = inputSamples[j2];
  18848. const unit = audioSample.unit;
  18849. let pts = audioSample.pts;
  18850. if (lastPTS !== null) {
  18851. const prevSample = outputSamples[j2 - 1];
  18852. prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);
  18853. } else {
  18854. if (contiguous && track.segmentCodec === "aac") {
  18855. pts = nextAudioTs + initTime;
  18856. }
  18857. firstPTS = pts;
  18858. if (mdatSize > 0) {
  18859. mdatSize += offset;
  18860. try {
  18861. mdat = new Uint8Array(mdatSize);
  18862. } catch (err) {
  18863. this.observer.emit(Events.ERROR, Events.ERROR, {
  18864. type: ErrorTypes.MUX_ERROR,
  18865. details: ErrorDetails.REMUX_ALLOC_ERROR,
  18866. fatal: false,
  18867. error: err,
  18868. bytes: mdatSize,
  18869. reason: `fail allocating audio mdat ${mdatSize}`
  18870. });
  18871. return;
  18872. }
  18873. if (!rawMPEG) {
  18874. const view2 = new DataView(mdat.buffer);
  18875. view2.setUint32(0, mdatSize);
  18876. mdat.set(MP4.types.mdat, 4);
  18877. }
  18878. } else {
  18879. return;
  18880. }
  18881. }
  18882. mdat.set(unit, offset);
  18883. const unitLen = unit.byteLength;
  18884. offset += unitLen;
  18885. outputSamples.push(createMp4Sample(true, mp4SampleDuration, unitLen, 0));
  18886. lastPTS = pts;
  18887. }
  18888. const nbSamples = outputSamples.length;
  18889. if (!nbSamples) {
  18890. return;
  18891. }
  18892. const lastSample = outputSamples[outputSamples.length - 1];
  18893. nextAudioTs = lastPTS - initTime;
  18894. this.nextAudioTs = nextAudioTs + scaleFactor * lastSample.duration;
  18895. const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  18896. samples: outputSamples
  18897. }));
  18898. track.samples = [];
  18899. const start = (firstPTS - initTime) / inputTimeScale;
  18900. const end = nextAudioTs / inputTimeScale;
  18901. const type = "audio";
  18902. const audioData = {
  18903. data1: moof,
  18904. data2: mdat,
  18905. startPTS: start,
  18906. endPTS: end,
  18907. startDTS: start,
  18908. endDTS: end,
  18909. type,
  18910. hasAudio: true,
  18911. hasVideo: false,
  18912. nb: nbSamples
  18913. };
  18914. this.isAudioContiguous = true;
  18915. return audioData;
  18916. }
  18917. }
  18918. function normalizePts(value2, reference) {
  18919. let offset;
  18920. if (reference === null) {
  18921. return value2;
  18922. }
  18923. if (reference < value2) {
  18924. offset = -8589934592;
  18925. } else {
  18926. offset = 8589934592;
  18927. }
  18928. while (Math.abs(value2 - reference) > 4294967296) {
  18929. value2 += offset;
  18930. }
  18931. return value2;
  18932. }
  18933. function findKeyframeIndex(samples) {
  18934. for (let i2 = 0; i2 < samples.length; i2++) {
  18935. if (samples[i2].key) {
  18936. return i2;
  18937. }
  18938. }
  18939. return -1;
  18940. }
  18941. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  18942. const length = track.samples.length;
  18943. if (!length) {
  18944. return;
  18945. }
  18946. const inputTimeScale = track.inputTimeScale;
  18947. for (let index2 = 0; index2 < length; index2++) {
  18948. const sample = track.samples[index2];
  18949. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  18950. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  18951. }
  18952. const samples = track.samples;
  18953. track.samples = [];
  18954. return {
  18955. samples
  18956. };
  18957. }
  18958. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  18959. const length = track.samples.length;
  18960. if (!length) {
  18961. return;
  18962. }
  18963. const inputTimeScale = track.inputTimeScale;
  18964. for (let index2 = 0; index2 < length; index2++) {
  18965. const sample = track.samples[index2];
  18966. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  18967. }
  18968. track.samples.sort((a2, b2) => a2.pts - b2.pts);
  18969. const samples = track.samples;
  18970. track.samples = [];
  18971. return {
  18972. samples
  18973. };
  18974. }
  18975. class PassThroughRemuxer extends Logger {
  18976. constructor(observer, config2, typeSupported, logger2) {
  18977. super("passthrough-remuxer", logger2);
  18978. this.emitInitSegment = false;
  18979. this.audioCodec = void 0;
  18980. this.videoCodec = void 0;
  18981. this.initData = void 0;
  18982. this.initPTS = null;
  18983. this.initTracks = void 0;
  18984. this.lastEndTime = null;
  18985. this.isVideoContiguous = false;
  18986. }
  18987. destroy() {
  18988. }
  18989. resetTimeStamp(defaultInitPTS) {
  18990. this.lastEndTime = null;
  18991. const initPTS = this.initPTS;
  18992. if (initPTS && defaultInitPTS) {
  18993. if (initPTS.baseTime === defaultInitPTS.baseTime && initPTS.timescale === defaultInitPTS.timescale) {
  18994. return;
  18995. }
  18996. }
  18997. this.initPTS = defaultInitPTS;
  18998. }
  18999. resetNextTimestamp() {
  19000. this.isVideoContiguous = false;
  19001. this.lastEndTime = null;
  19002. }
  19003. resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  19004. this.audioCodec = audioCodec;
  19005. this.videoCodec = videoCodec;
  19006. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  19007. this.emitInitSegment = true;
  19008. }
  19009. generateInitSegment(initSegment) {
  19010. let {
  19011. audioCodec,
  19012. videoCodec
  19013. } = this;
  19014. if (!(initSegment != null && initSegment.byteLength)) {
  19015. this.initTracks = void 0;
  19016. this.initData = void 0;
  19017. return;
  19018. }
  19019. const initData = this.initData = parseInitSegment(initSegment);
  19020. if (initData.audio) {
  19021. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO, this);
  19022. }
  19023. if (initData.video) {
  19024. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO, this);
  19025. }
  19026. const tracks = {};
  19027. if (initData.audio && initData.video) {
  19028. tracks.audiovideo = {
  19029. container: "video/mp4",
  19030. codec: audioCodec + "," + videoCodec,
  19031. supplemental: initData.video.supplemental,
  19032. initSegment,
  19033. id: "main"
  19034. };
  19035. } else if (initData.audio) {
  19036. tracks.audio = {
  19037. container: "audio/mp4",
  19038. codec: audioCodec,
  19039. initSegment,
  19040. id: "audio"
  19041. };
  19042. } else if (initData.video) {
  19043. tracks.video = {
  19044. container: "video/mp4",
  19045. codec: videoCodec,
  19046. supplemental: initData.video.supplemental,
  19047. initSegment,
  19048. id: "main"
  19049. };
  19050. } else {
  19051. this.warn("initSegment does not contain moov or trak boxes.");
  19052. }
  19053. this.initTracks = tracks;
  19054. }
  19055. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  19056. var _initData, _initData2;
  19057. let {
  19058. initPTS,
  19059. lastEndTime
  19060. } = this;
  19061. const result = {
  19062. audio: void 0,
  19063. video: void 0,
  19064. text: textTrack,
  19065. id3: id3Track,
  19066. initSegment: void 0
  19067. };
  19068. if (!isFiniteNumber(lastEndTime)) {
  19069. lastEndTime = this.lastEndTime = timeOffset || 0;
  19070. }
  19071. const data = videoTrack.samples;
  19072. if (!(data != null && data.length)) {
  19073. return result;
  19074. }
  19075. const initSegment = {
  19076. initPTS: void 0,
  19077. timescale: void 0,
  19078. trackId: void 0
  19079. };
  19080. let initData = this.initData;
  19081. if (!((_initData = initData) != null && _initData.length)) {
  19082. this.generateInitSegment(data);
  19083. initData = this.initData;
  19084. }
  19085. if (!((_initData2 = initData) != null && _initData2.length)) {
  19086. this.warn("Failed to generate initSegment.");
  19087. return result;
  19088. }
  19089. if (this.emitInitSegment) {
  19090. initSegment.tracks = this.initTracks;
  19091. this.emitInitSegment = false;
  19092. }
  19093. const trackSampleData = getSampleData(data, initData, this);
  19094. const audioSampleTimestamps = initData.audio ? trackSampleData[initData.audio.id] : null;
  19095. const videoSampleTimestamps = initData.video ? trackSampleData[initData.video.id] : null;
  19096. const videoStartTime = toStartEndOrDefault(videoSampleTimestamps, Infinity);
  19097. const audioStartTime = toStartEndOrDefault(audioSampleTimestamps, Infinity);
  19098. const videoEndTime = toStartEndOrDefault(videoSampleTimestamps, 0, true);
  19099. const audioEndTime = toStartEndOrDefault(audioSampleTimestamps, 0, true);
  19100. let baseOffsetSamples;
  19101. let decodeTime = timeOffset;
  19102. let duration = 0;
  19103. if (audioSampleTimestamps && (!videoSampleTimestamps || !initPTS && audioStartTime < videoStartTime || initPTS && initPTS.trackId === initData.audio.id)) {
  19104. initSegment.trackId = initData.audio.id;
  19105. baseOffsetSamples = audioSampleTimestamps;
  19106. duration = audioEndTime - audioStartTime;
  19107. } else if (videoSampleTimestamps) {
  19108. initSegment.trackId = initData.video.id;
  19109. baseOffsetSamples = videoSampleTimestamps;
  19110. duration = videoEndTime - videoStartTime;
  19111. }
  19112. if (baseOffsetSamples) {
  19113. const timescale = baseOffsetSamples.timescale;
  19114. decodeTime = baseOffsetSamples.start / timescale;
  19115. initSegment.initPTS = baseOffsetSamples.start - timeOffset * timescale;
  19116. initSegment.timescale = timescale;
  19117. if (!initPTS) {
  19118. this.initPTS = initPTS = {
  19119. baseTime: initSegment.initPTS,
  19120. timescale,
  19121. trackId: initSegment.trackId
  19122. };
  19123. }
  19124. }
  19125. if ((accurateTimeOffset || !initPTS) && (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale)) {
  19126. initSegment.initPTS = decodeTime - timeOffset;
  19127. initSegment.timescale = 1;
  19128. if (initPTS && initPTS.timescale === 1) {
  19129. this.warn(`Adjusting initPTS @${timeOffset} from ${initPTS.baseTime / initPTS.timescale} to ${initSegment.initPTS}`);
  19130. }
  19131. this.initPTS = initPTS = {
  19132. baseTime: initSegment.initPTS,
  19133. timescale: 1
  19134. };
  19135. }
  19136. const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  19137. const endTime = startTime + duration;
  19138. if (duration > 0) {
  19139. this.lastEndTime = endTime;
  19140. } else {
  19141. this.warn("Duration parsed from mp4 should be greater than zero");
  19142. this.resetNextTimestamp();
  19143. }
  19144. const hasAudio = !!initData.audio;
  19145. const hasVideo = !!initData.video;
  19146. let type = "";
  19147. if (hasAudio) {
  19148. type += "audio";
  19149. }
  19150. if (hasVideo) {
  19151. type += "video";
  19152. }
  19153. const track = {
  19154. data1: data,
  19155. startPTS: startTime,
  19156. startDTS: startTime,
  19157. endPTS: endTime,
  19158. endDTS: endTime,
  19159. type,
  19160. hasAudio,
  19161. hasVideo,
  19162. nb: 1,
  19163. dropped: 0
  19164. };
  19165. result.audio = hasAudio && !hasVideo ? track : void 0;
  19166. result.video = hasVideo ? track : void 0;
  19167. const videoSampleCount = videoSampleTimestamps == null ? void 0 : videoSampleTimestamps.sampleCount;
  19168. if (videoSampleCount) {
  19169. const firstKeyFrame = videoSampleTimestamps.keyFrameIndex;
  19170. const independent = firstKeyFrame !== -1;
  19171. track.nb = videoSampleCount;
  19172. track.dropped = firstKeyFrame === 0 || this.isVideoContiguous ? 0 : independent ? firstKeyFrame : videoSampleCount;
  19173. track.independent = independent;
  19174. track.firstKeyFrame = firstKeyFrame;
  19175. if (independent && videoSampleTimestamps.keyFrameStart) {
  19176. track.firstKeyFramePTS = (videoSampleTimestamps.keyFrameStart - initPTS.baseTime) / initPTS.timescale;
  19177. }
  19178. if (!this.isVideoContiguous) {
  19179. result.independent = independent;
  19180. }
  19181. this.isVideoContiguous || (this.isVideoContiguous = independent);
  19182. if (track.dropped) {
  19183. this.warn(`fmp4 does not start with IDR: firstIDR ${firstKeyFrame}/${videoSampleCount} dropped: ${track.dropped} start: ${track.firstKeyFramePTS || "NA"}`);
  19184. }
  19185. }
  19186. result.initSegment = initSegment;
  19187. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  19188. if (textTrack.samples.length) {
  19189. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  19190. }
  19191. return result;
  19192. }
  19193. }
  19194. function toStartEndOrDefault(trackTimes, defaultValue, end = false) {
  19195. return (trackTimes == null ? void 0 : trackTimes.start) !== void 0 ? (trackTimes.start + (end ? trackTimes.duration : 0)) / trackTimes.timescale : defaultValue;
  19196. }
  19197. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  19198. if (initPTS === null) {
  19199. return true;
  19200. }
  19201. const minDuration = Math.max(duration, 1);
  19202. const startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  19203. return Math.abs(startTime - timeOffset) > minDuration;
  19204. }
  19205. function getParsedTrackCodec(track, type, logger2) {
  19206. const parsedCodec = track == null ? void 0 : track.codec;
  19207. if (parsedCodec && parsedCodec.length > 4) {
  19208. return parsedCodec;
  19209. }
  19210. if (type === ElementaryStreamTypes.AUDIO) {
  19211. if (parsedCodec === "ec-3" || parsedCodec === "ac-3" || parsedCodec === "alac") {
  19212. return parsedCodec;
  19213. }
  19214. if (parsedCodec === "fLaC" || parsedCodec === "Opus") {
  19215. const preferManagedMediaSource = false;
  19216. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  19217. }
  19218. logger2.warn(`Unhandled audio codec "${parsedCodec}" in mp4 MAP`);
  19219. return parsedCodec || "mp4a";
  19220. }
  19221. logger2.warn(`Unhandled video codec "${parsedCodec}" in mp4 MAP`);
  19222. return parsedCodec || "avc1";
  19223. }
  19224. let now;
  19225. try {
  19226. now = self.performance.now.bind(self.performance);
  19227. } catch (err) {
  19228. now = Date.now;
  19229. }
  19230. const muxConfig = [{
  19231. demux: MP4Demuxer,
  19232. remux: PassThroughRemuxer
  19233. }, {
  19234. demux: TSDemuxer,
  19235. remux: MP4Remuxer
  19236. }, {
  19237. demux: AACDemuxer,
  19238. remux: MP4Remuxer
  19239. }, {
  19240. demux: MP3Demuxer,
  19241. remux: MP4Remuxer
  19242. }];
  19243. {
  19244. muxConfig.splice(2, 0, {
  19245. demux: AC3Demuxer,
  19246. remux: MP4Remuxer
  19247. });
  19248. }
  19249. class Transmuxer {
  19250. constructor(observer, typeSupported, config2, vendor, id, logger2) {
  19251. this.asyncResult = false;
  19252. this.logger = void 0;
  19253. this.observer = void 0;
  19254. this.typeSupported = void 0;
  19255. this.config = void 0;
  19256. this.id = void 0;
  19257. this.demuxer = void 0;
  19258. this.remuxer = void 0;
  19259. this.decrypter = void 0;
  19260. this.probe = void 0;
  19261. this.decryptionPromise = null;
  19262. this.transmuxConfig = void 0;
  19263. this.currentTransmuxState = void 0;
  19264. this.observer = observer;
  19265. this.typeSupported = typeSupported;
  19266. this.config = config2;
  19267. this.id = id;
  19268. this.logger = logger2;
  19269. }
  19270. configure(transmuxConfig) {
  19271. this.transmuxConfig = transmuxConfig;
  19272. if (this.decrypter) {
  19273. this.decrypter.reset();
  19274. }
  19275. }
  19276. push(data, decryptdata, chunkMeta, state) {
  19277. const stats = chunkMeta.transmuxing;
  19278. stats.executeStart = now();
  19279. let uintData = new Uint8Array(data);
  19280. const {
  19281. currentTransmuxState,
  19282. transmuxConfig
  19283. } = this;
  19284. if (state) {
  19285. this.currentTransmuxState = state;
  19286. }
  19287. const {
  19288. contiguous,
  19289. discontinuity,
  19290. trackSwitch,
  19291. accurateTimeOffset,
  19292. timeOffset,
  19293. initSegmentChange
  19294. } = state || currentTransmuxState;
  19295. const {
  19296. audioCodec,
  19297. videoCodec,
  19298. defaultInitPts,
  19299. duration,
  19300. initSegmentData
  19301. } = transmuxConfig;
  19302. const keyData = getEncryptionType(uintData, decryptdata);
  19303. if (keyData && isFullSegmentEncryption(keyData.method)) {
  19304. const decrypter = this.getDecrypter();
  19305. const aesMode = getAesModeFromFullSegmentMethod(keyData.method);
  19306. if (decrypter.isSync()) {
  19307. let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode);
  19308. const loadingParts = chunkMeta.part > -1;
  19309. if (loadingParts) {
  19310. const _data = decrypter.flush();
  19311. decryptedData = _data ? _data.buffer : _data;
  19312. }
  19313. if (!decryptedData) {
  19314. stats.executeEnd = now();
  19315. return emptyResult(chunkMeta);
  19316. }
  19317. uintData = new Uint8Array(decryptedData);
  19318. } else {
  19319. this.asyncResult = true;
  19320. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode).then((decryptedData) => {
  19321. const result2 = this.push(decryptedData, null, chunkMeta);
  19322. this.decryptionPromise = null;
  19323. return result2;
  19324. });
  19325. return this.decryptionPromise;
  19326. }
  19327. }
  19328. const resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  19329. if (resetMuxers) {
  19330. const error2 = this.configureTransmuxer(uintData);
  19331. if (error2) {
  19332. this.logger.warn(`[transmuxer] ${error2.message}`);
  19333. this.observer.emit(Events.ERROR, Events.ERROR, {
  19334. type: ErrorTypes.MEDIA_ERROR,
  19335. details: ErrorDetails.FRAG_PARSING_ERROR,
  19336. fatal: false,
  19337. error: error2,
  19338. reason: error2.message
  19339. });
  19340. stats.executeEnd = now();
  19341. return emptyResult(chunkMeta);
  19342. }
  19343. }
  19344. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  19345. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  19346. }
  19347. if (discontinuity || initSegmentChange || resetMuxers) {
  19348. this.resetInitialTimestamp(defaultInitPts);
  19349. }
  19350. if (!contiguous) {
  19351. this.resetContiguity();
  19352. }
  19353. const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  19354. this.asyncResult = isPromise$1(result);
  19355. const currentState = this.currentTransmuxState;
  19356. currentState.contiguous = true;
  19357. currentState.discontinuity = false;
  19358. currentState.trackSwitch = false;
  19359. stats.executeEnd = now();
  19360. return result;
  19361. }
  19362. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  19363. flush(chunkMeta) {
  19364. const stats = chunkMeta.transmuxing;
  19365. stats.executeStart = now();
  19366. const {
  19367. decrypter,
  19368. currentTransmuxState,
  19369. decryptionPromise
  19370. } = this;
  19371. if (decryptionPromise) {
  19372. this.asyncResult = true;
  19373. return decryptionPromise.then(() => {
  19374. return this.flush(chunkMeta);
  19375. });
  19376. }
  19377. const transmuxResults = [];
  19378. const {
  19379. timeOffset
  19380. } = currentTransmuxState;
  19381. if (decrypter) {
  19382. const decryptedData = decrypter.flush();
  19383. if (decryptedData) {
  19384. transmuxResults.push(this.push(decryptedData.buffer, null, chunkMeta));
  19385. }
  19386. }
  19387. const {
  19388. demuxer,
  19389. remuxer
  19390. } = this;
  19391. if (!demuxer || !remuxer) {
  19392. stats.executeEnd = now();
  19393. const emptyResults = [emptyResult(chunkMeta)];
  19394. if (this.asyncResult) {
  19395. return Promise.resolve(emptyResults);
  19396. }
  19397. return emptyResults;
  19398. }
  19399. const demuxResultOrPromise = demuxer.flush(timeOffset);
  19400. if (isPromise$1(demuxResultOrPromise)) {
  19401. this.asyncResult = true;
  19402. return demuxResultOrPromise.then((demuxResult) => {
  19403. this.flushRemux(transmuxResults, demuxResult, chunkMeta);
  19404. return transmuxResults;
  19405. });
  19406. }
  19407. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  19408. if (this.asyncResult) {
  19409. return Promise.resolve(transmuxResults);
  19410. }
  19411. return transmuxResults;
  19412. }
  19413. flushRemux(transmuxResults, demuxResult, chunkMeta) {
  19414. const {
  19415. audioTrack,
  19416. videoTrack,
  19417. id3Track,
  19418. textTrack
  19419. } = demuxResult;
  19420. const {
  19421. accurateTimeOffset,
  19422. timeOffset
  19423. } = this.currentTransmuxState;
  19424. 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}`);
  19425. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  19426. transmuxResults.push({
  19427. remuxResult,
  19428. chunkMeta
  19429. });
  19430. chunkMeta.transmuxing.executeEnd = now();
  19431. }
  19432. resetInitialTimestamp(defaultInitPts) {
  19433. const {
  19434. demuxer,
  19435. remuxer
  19436. } = this;
  19437. if (!demuxer || !remuxer) {
  19438. return;
  19439. }
  19440. demuxer.resetTimeStamp(defaultInitPts);
  19441. remuxer.resetTimeStamp(defaultInitPts);
  19442. }
  19443. resetContiguity() {
  19444. const {
  19445. demuxer,
  19446. remuxer
  19447. } = this;
  19448. if (!demuxer || !remuxer) {
  19449. return;
  19450. }
  19451. demuxer.resetContiguity();
  19452. remuxer.resetNextTimestamp();
  19453. }
  19454. resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  19455. const {
  19456. demuxer,
  19457. remuxer
  19458. } = this;
  19459. if (!demuxer || !remuxer) {
  19460. return;
  19461. }
  19462. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  19463. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  19464. }
  19465. destroy() {
  19466. if (this.demuxer) {
  19467. this.demuxer.destroy();
  19468. this.demuxer = void 0;
  19469. }
  19470. if (this.remuxer) {
  19471. this.remuxer.destroy();
  19472. this.remuxer = void 0;
  19473. }
  19474. }
  19475. transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  19476. let result;
  19477. if (keyData && keyData.method === "SAMPLE-AES") {
  19478. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  19479. } else {
  19480. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  19481. }
  19482. return result;
  19483. }
  19484. transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  19485. const {
  19486. audioTrack,
  19487. videoTrack,
  19488. id3Track,
  19489. textTrack
  19490. } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);
  19491. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  19492. return {
  19493. remuxResult,
  19494. chunkMeta
  19495. };
  19496. }
  19497. transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  19498. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then((demuxResult) => {
  19499. const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);
  19500. return {
  19501. remuxResult,
  19502. chunkMeta
  19503. };
  19504. });
  19505. }
  19506. configureTransmuxer(data) {
  19507. const {
  19508. config: config2,
  19509. observer,
  19510. typeSupported
  19511. } = this;
  19512. let mux;
  19513. for (let i2 = 0, len = muxConfig.length; i2 < len; i2++) {
  19514. var _muxConfig$i$demux;
  19515. if ((_muxConfig$i$demux = muxConfig[i2].demux) != null && _muxConfig$i$demux.probe(data, this.logger)) {
  19516. mux = muxConfig[i2];
  19517. break;
  19518. }
  19519. }
  19520. if (!mux) {
  19521. return new Error("Failed to find demuxer by probing fragment data");
  19522. }
  19523. const demuxer = this.demuxer;
  19524. const remuxer = this.remuxer;
  19525. const Remuxer = mux.remux;
  19526. const Demuxer = mux.demux;
  19527. if (!remuxer || !(remuxer instanceof Remuxer)) {
  19528. this.remuxer = new Remuxer(observer, config2, typeSupported, this.logger);
  19529. }
  19530. if (!demuxer || !(demuxer instanceof Demuxer)) {
  19531. this.demuxer = new Demuxer(observer, config2, typeSupported, this.logger);
  19532. this.probe = Demuxer.probe;
  19533. }
  19534. }
  19535. needsProbing(discontinuity, trackSwitch) {
  19536. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  19537. }
  19538. getDecrypter() {
  19539. let decrypter = this.decrypter;
  19540. if (!decrypter) {
  19541. decrypter = this.decrypter = new Decrypter(this.config);
  19542. }
  19543. return decrypter;
  19544. }
  19545. }
  19546. function getEncryptionType(data, decryptData) {
  19547. let encryptionType = null;
  19548. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  19549. encryptionType = decryptData;
  19550. }
  19551. return encryptionType;
  19552. }
  19553. const emptyResult = (chunkMeta) => ({
  19554. remuxResult: {},
  19555. chunkMeta
  19556. });
  19557. function isPromise$1(p2) {
  19558. return "then" in p2 && p2.then instanceof Function;
  19559. }
  19560. class TransmuxConfig {
  19561. constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  19562. this.audioCodec = void 0;
  19563. this.videoCodec = void 0;
  19564. this.initSegmentData = void 0;
  19565. this.duration = void 0;
  19566. this.defaultInitPts = void 0;
  19567. this.audioCodec = audioCodec;
  19568. this.videoCodec = videoCodec;
  19569. this.initSegmentData = initSegmentData;
  19570. this.duration = duration;
  19571. this.defaultInitPts = defaultInitPts || null;
  19572. }
  19573. }
  19574. class TransmuxState {
  19575. constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  19576. this.discontinuity = void 0;
  19577. this.contiguous = void 0;
  19578. this.accurateTimeOffset = void 0;
  19579. this.trackSwitch = void 0;
  19580. this.timeOffset = void 0;
  19581. this.initSegmentChange = void 0;
  19582. this.discontinuity = discontinuity;
  19583. this.contiguous = contiguous;
  19584. this.accurateTimeOffset = accurateTimeOffset;
  19585. this.trackSwitch = trackSwitch;
  19586. this.timeOffset = timeOffset;
  19587. this.initSegmentChange = initSegmentChange;
  19588. }
  19589. }
  19590. let transmuxerInstanceCount = 0;
  19591. class TransmuxerInterface {
  19592. constructor(_hls, id, onTransmuxComplete, onFlush) {
  19593. this.error = null;
  19594. this.hls = void 0;
  19595. this.id = void 0;
  19596. this.instanceNo = transmuxerInstanceCount++;
  19597. this.observer = void 0;
  19598. this.frag = null;
  19599. this.part = null;
  19600. this.useWorker = void 0;
  19601. this.workerContext = null;
  19602. this.transmuxer = null;
  19603. this.onTransmuxComplete = void 0;
  19604. this.onFlush = void 0;
  19605. this.onWorkerMessage = (event) => {
  19606. const data = event.data;
  19607. const hls = this.hls;
  19608. if (!hls || !(data != null && data.event) || data.instanceNo !== this.instanceNo) {
  19609. return;
  19610. }
  19611. switch (data.event) {
  19612. case "init": {
  19613. var _this$workerContext;
  19614. const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  19615. if (objectURL) {
  19616. self.URL.revokeObjectURL(objectURL);
  19617. }
  19618. break;
  19619. }
  19620. case "transmuxComplete": {
  19621. this.handleTransmuxComplete(data.data);
  19622. break;
  19623. }
  19624. case "flush": {
  19625. this.onFlush(data.data);
  19626. break;
  19627. }
  19628. case "workerLog": {
  19629. if (hls.logger[data.data.logType]) {
  19630. hls.logger[data.data.logType](data.data.message);
  19631. }
  19632. break;
  19633. }
  19634. default: {
  19635. data.data = data.data || {};
  19636. data.data.frag = this.frag;
  19637. data.data.part = this.part;
  19638. data.data.id = this.id;
  19639. hls.trigger(data.event, data.data);
  19640. break;
  19641. }
  19642. }
  19643. };
  19644. this.onWorkerError = (event) => {
  19645. if (!this.hls) {
  19646. return;
  19647. }
  19648. const error2 = new Error(`${event.message} (${event.filename}:${event.lineno})`);
  19649. this.hls.config.enableWorker = false;
  19650. this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`);
  19651. this.hls.trigger(Events.ERROR, {
  19652. type: ErrorTypes.OTHER_ERROR,
  19653. details: ErrorDetails.INTERNAL_EXCEPTION,
  19654. fatal: false,
  19655. event: "demuxerWorker",
  19656. error: error2
  19657. });
  19658. };
  19659. const config2 = _hls.config;
  19660. this.hls = _hls;
  19661. this.id = id;
  19662. this.useWorker = !!config2.enableWorker;
  19663. this.onTransmuxComplete = onTransmuxComplete;
  19664. this.onFlush = onFlush;
  19665. const forwardMessage = (ev, data) => {
  19666. data = data || {};
  19667. data.frag = this.frag || void 0;
  19668. if (ev === Events.ERROR) {
  19669. data = data;
  19670. data.parent = this.id;
  19671. data.part = this.part;
  19672. this.error = data.error;
  19673. }
  19674. this.hls.trigger(ev, data);
  19675. };
  19676. this.observer = new EventEmitter();
  19677. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  19678. this.observer.on(Events.ERROR, forwardMessage);
  19679. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config2.preferManagedMediaSource);
  19680. if (this.useWorker && typeof Worker !== "undefined") {
  19681. const logger2 = this.hls.logger;
  19682. const canCreateWorker = config2.workerPath || hasUMDWorker();
  19683. if (canCreateWorker) {
  19684. try {
  19685. if (config2.workerPath) {
  19686. logger2.log(`loading Web Worker ${config2.workerPath} for "${id}"`);
  19687. this.workerContext = loadWorker(config2.workerPath);
  19688. } else {
  19689. logger2.log(`injecting Web Worker for "${id}"`);
  19690. this.workerContext = injectWorker();
  19691. }
  19692. const {
  19693. worker
  19694. } = this.workerContext;
  19695. worker.addEventListener("message", this.onWorkerMessage);
  19696. worker.addEventListener("error", this.onWorkerError);
  19697. worker.postMessage({
  19698. instanceNo: this.instanceNo,
  19699. cmd: "init",
  19700. typeSupported: m2tsTypeSupported,
  19701. id,
  19702. config: stringify(config2)
  19703. });
  19704. } catch (err) {
  19705. logger2.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err);
  19706. this.terminateWorker();
  19707. this.error = null;
  19708. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config2, "", id, _hls.logger);
  19709. }
  19710. return;
  19711. }
  19712. }
  19713. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config2, "", id, _hls.logger);
  19714. }
  19715. reset() {
  19716. this.frag = null;
  19717. this.part = null;
  19718. if (this.workerContext) {
  19719. const instanceNo = this.instanceNo;
  19720. this.instanceNo = transmuxerInstanceCount++;
  19721. const config2 = this.hls.config;
  19722. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config2.preferManagedMediaSource);
  19723. this.workerContext.worker.postMessage({
  19724. instanceNo: this.instanceNo,
  19725. cmd: "reset",
  19726. resetNo: instanceNo,
  19727. typeSupported: m2tsTypeSupported,
  19728. id: this.id,
  19729. config: stringify(config2)
  19730. });
  19731. }
  19732. }
  19733. terminateWorker() {
  19734. if (this.workerContext) {
  19735. const {
  19736. worker
  19737. } = this.workerContext;
  19738. this.workerContext = null;
  19739. worker.removeEventListener("message", this.onWorkerMessage);
  19740. worker.removeEventListener("error", this.onWorkerError);
  19741. removeWorkerFromStore(this.hls.config.workerPath);
  19742. }
  19743. }
  19744. destroy() {
  19745. if (this.workerContext) {
  19746. this.terminateWorker();
  19747. this.onWorkerMessage = this.onWorkerError = null;
  19748. } else {
  19749. const transmuxer = this.transmuxer;
  19750. if (transmuxer) {
  19751. transmuxer.destroy();
  19752. this.transmuxer = null;
  19753. }
  19754. }
  19755. const observer = this.observer;
  19756. if (observer) {
  19757. observer.removeAllListeners();
  19758. }
  19759. this.frag = null;
  19760. this.part = null;
  19761. this.observer = null;
  19762. this.hls = null;
  19763. }
  19764. push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  19765. var _frag$initSegment, _lastFrag$initSegment;
  19766. chunkMeta.transmuxing.start = self.performance.now();
  19767. const {
  19768. instanceNo,
  19769. transmuxer
  19770. } = this;
  19771. const timeOffset = part ? part.start : frag.start;
  19772. const decryptdata = frag.decryptdata;
  19773. const lastFrag = this.frag;
  19774. const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  19775. const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  19776. const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  19777. const partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  19778. const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  19779. const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  19780. const now2 = self.performance.now();
  19781. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  19782. frag.stats.parsing.start = now2;
  19783. }
  19784. if (part && (partDiff || !contiguous)) {
  19785. part.stats.parsing.start = now2;
  19786. }
  19787. const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  19788. const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  19789. if (!contiguous || discontinuity || initSegmentChange) {
  19790. 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}
  19791. discontinuity: ${discontinuity}
  19792. trackSwitch: ${trackSwitch}
  19793. contiguous: ${contiguous}
  19794. accurateTimeOffset: ${accurateTimeOffset}
  19795. timeOffset: ${timeOffset}
  19796. initSegmentChange: ${initSegmentChange}`);
  19797. const config2 = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  19798. this.configureTransmuxer(config2);
  19799. }
  19800. this.frag = frag;
  19801. this.part = part;
  19802. if (this.workerContext) {
  19803. this.workerContext.worker.postMessage({
  19804. instanceNo,
  19805. cmd: "demux",
  19806. data,
  19807. decryptdata,
  19808. chunkMeta,
  19809. state
  19810. }, data instanceof ArrayBuffer ? [data] : []);
  19811. } else if (transmuxer) {
  19812. const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  19813. if (isPromise$1(transmuxResult)) {
  19814. transmuxResult.then((data2) => {
  19815. this.handleTransmuxComplete(data2);
  19816. }).catch((error2) => {
  19817. this.transmuxerError(error2, chunkMeta, "transmuxer-interface push error");
  19818. });
  19819. } else {
  19820. this.handleTransmuxComplete(transmuxResult);
  19821. }
  19822. }
  19823. }
  19824. flush(chunkMeta) {
  19825. chunkMeta.transmuxing.start = self.performance.now();
  19826. const {
  19827. instanceNo,
  19828. transmuxer
  19829. } = this;
  19830. if (this.workerContext) {
  19831. this.workerContext.worker.postMessage({
  19832. instanceNo,
  19833. cmd: "flush",
  19834. chunkMeta
  19835. });
  19836. } else if (transmuxer) {
  19837. const transmuxResult = transmuxer.flush(chunkMeta);
  19838. if (isPromise$1(transmuxResult)) {
  19839. transmuxResult.then((data) => {
  19840. this.handleFlushResult(data, chunkMeta);
  19841. }).catch((error2) => {
  19842. this.transmuxerError(error2, chunkMeta, "transmuxer-interface flush error");
  19843. });
  19844. } else {
  19845. this.handleFlushResult(transmuxResult, chunkMeta);
  19846. }
  19847. }
  19848. }
  19849. transmuxerError(error2, chunkMeta, reason) {
  19850. if (!this.hls) {
  19851. return;
  19852. }
  19853. this.error = error2;
  19854. this.hls.trigger(Events.ERROR, {
  19855. type: ErrorTypes.MEDIA_ERROR,
  19856. details: ErrorDetails.FRAG_PARSING_ERROR,
  19857. chunkMeta,
  19858. frag: this.frag || void 0,
  19859. part: this.part || void 0,
  19860. fatal: false,
  19861. error: error2,
  19862. err: error2,
  19863. reason
  19864. });
  19865. }
  19866. handleFlushResult(results, chunkMeta) {
  19867. results.forEach((result) => {
  19868. this.handleTransmuxComplete(result);
  19869. });
  19870. this.onFlush(chunkMeta);
  19871. }
  19872. configureTransmuxer(config2) {
  19873. const {
  19874. instanceNo,
  19875. transmuxer
  19876. } = this;
  19877. if (this.workerContext) {
  19878. this.workerContext.worker.postMessage({
  19879. instanceNo,
  19880. cmd: "configure",
  19881. config: config2
  19882. });
  19883. } else if (transmuxer) {
  19884. transmuxer.configure(config2);
  19885. }
  19886. }
  19887. handleTransmuxComplete(result) {
  19888. result.chunkMeta.transmuxing.end = self.performance.now();
  19889. this.onTransmuxComplete(result);
  19890. }
  19891. }
  19892. const TICK_INTERVAL$3 = 100;
  19893. class AudioStreamController extends BaseStreamController {
  19894. constructor(hls, fragmentTracker, keyLoader) {
  19895. super(hls, fragmentTracker, keyLoader, "audio-stream-controller", PlaylistLevelType.AUDIO);
  19896. this.mainAnchor = null;
  19897. this.mainFragLoading = null;
  19898. this.audioOnly = false;
  19899. this.bufferedTrack = null;
  19900. this.switchingTrack = null;
  19901. this.trackId = -1;
  19902. this.waitingData = null;
  19903. this.mainDetails = null;
  19904. this.flushing = false;
  19905. this.bufferFlushed = false;
  19906. this.cachedTrackLoadedData = null;
  19907. this.registerListeners();
  19908. }
  19909. onHandlerDestroying() {
  19910. this.unregisterListeners();
  19911. super.onHandlerDestroying();
  19912. this.resetItem();
  19913. }
  19914. resetItem() {
  19915. this.mainDetails = this.mainAnchor = this.mainFragLoading = this.bufferedTrack = this.switchingTrack = this.waitingData = this.cachedTrackLoadedData = null;
  19916. }
  19917. registerListeners() {
  19918. super.registerListeners();
  19919. const {
  19920. hls
  19921. } = this;
  19922. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  19923. hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  19924. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  19925. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  19926. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  19927. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  19928. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  19929. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  19930. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  19931. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  19932. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  19933. }
  19934. unregisterListeners() {
  19935. const {
  19936. hls
  19937. } = this;
  19938. if (!hls) {
  19939. return;
  19940. }
  19941. super.unregisterListeners();
  19942. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  19943. hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  19944. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  19945. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  19946. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  19947. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  19948. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  19949. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  19950. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  19951. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  19952. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  19953. }
  19954. // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
  19955. onInitPtsFound(event, {
  19956. frag,
  19957. id,
  19958. initPTS,
  19959. timescale
  19960. }) {
  19961. if (id === PlaylistLevelType.MAIN) {
  19962. const cc = frag.cc;
  19963. const inFlightFrag = this.fragCurrent;
  19964. this.initPTS[cc] = {
  19965. baseTime: initPTS,
  19966. timescale
  19967. };
  19968. this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}/${timescale}`);
  19969. this.mainAnchor = frag;
  19970. if (this.state === State.WAITING_INIT_PTS) {
  19971. const waitingData = this.waitingData;
  19972. if (!waitingData && !this.loadingParts || waitingData && waitingData.frag.cc !== cc) {
  19973. this.syncWithAnchor(frag, waitingData == null ? void 0 : waitingData.frag);
  19974. }
  19975. } else if (!this.hls.hasEnoughToStart && inFlightFrag && inFlightFrag.cc !== cc) {
  19976. inFlightFrag.abortRequests();
  19977. this.syncWithAnchor(frag, inFlightFrag);
  19978. } else if (this.state === State.IDLE) {
  19979. this.tick();
  19980. }
  19981. }
  19982. }
  19983. getLoadPosition() {
  19984. if (!this.startFragRequested && this.nextLoadPosition >= 0) {
  19985. return this.nextLoadPosition;
  19986. }
  19987. return super.getLoadPosition();
  19988. }
  19989. syncWithAnchor(mainAnchor, waitingToAppend) {
  19990. var _this$mainFragLoading;
  19991. const mainFragLoading = ((_this$mainFragLoading = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading.frag) || null;
  19992. if (waitingToAppend) {
  19993. if ((mainFragLoading == null ? void 0 : mainFragLoading.cc) === waitingToAppend.cc) {
  19994. return;
  19995. }
  19996. }
  19997. const targetDiscontinuity = (mainFragLoading || mainAnchor).cc;
  19998. const trackDetails = this.getLevelDetails();
  19999. const pos = this.getLoadPosition();
  20000. const syncFrag = findNearestWithCC(trackDetails, targetDiscontinuity, pos);
  20001. if (syncFrag) {
  20002. this.log(`Syncing with main frag at ${syncFrag.start} cc ${syncFrag.cc}`);
  20003. this.startFragRequested = false;
  20004. this.nextLoadPosition = syncFrag.start;
  20005. this.resetLoadingState();
  20006. if (this.state === State.IDLE) {
  20007. this.doTickIdle();
  20008. }
  20009. }
  20010. }
  20011. startLoad(startPosition, skipSeekToStartPosition) {
  20012. if (!this.levels) {
  20013. this.startPosition = startPosition;
  20014. this.state = State.STOPPED;
  20015. return;
  20016. }
  20017. const lastCurrentTime = this.lastCurrentTime;
  20018. this.stopLoad();
  20019. this.setInterval(TICK_INTERVAL$3);
  20020. if (lastCurrentTime > 0 && startPosition === -1) {
  20021. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  20022. startPosition = lastCurrentTime;
  20023. this.state = State.IDLE;
  20024. } else {
  20025. this.state = State.WAITING_TRACK;
  20026. }
  20027. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  20028. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  20029. this.tick();
  20030. }
  20031. doTick() {
  20032. switch (this.state) {
  20033. case State.IDLE:
  20034. this.doTickIdle();
  20035. break;
  20036. case State.WAITING_TRACK: {
  20037. const {
  20038. levels,
  20039. trackId
  20040. } = this;
  20041. const currenTrack = levels == null ? void 0 : levels[trackId];
  20042. const details = currenTrack == null ? void 0 : currenTrack.details;
  20043. if (details && !this.waitForLive(currenTrack)) {
  20044. if (this.waitForCdnTuneIn(details)) {
  20045. break;
  20046. }
  20047. this.state = State.WAITING_INIT_PTS;
  20048. }
  20049. break;
  20050. }
  20051. case State.FRAG_LOADING_WAITING_RETRY: {
  20052. var _this$media;
  20053. const now2 = performance.now();
  20054. const retryDate = this.retryDate;
  20055. if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  20056. const {
  20057. levels,
  20058. trackId
  20059. } = this;
  20060. this.log("RetryDate reached, switch back to IDLE state");
  20061. this.resetStartWhenNotLoaded((levels == null ? void 0 : levels[trackId]) || null);
  20062. this.state = State.IDLE;
  20063. }
  20064. break;
  20065. }
  20066. case State.WAITING_INIT_PTS: {
  20067. const waitingData = this.waitingData;
  20068. if (waitingData) {
  20069. const {
  20070. frag,
  20071. part,
  20072. cache,
  20073. complete
  20074. } = waitingData;
  20075. const mainAnchor = this.mainAnchor;
  20076. if (this.initPTS[frag.cc] !== void 0) {
  20077. this.waitingData = null;
  20078. this.state = State.FRAG_LOADING;
  20079. const payload = cache.flush().buffer;
  20080. const data = {
  20081. frag,
  20082. part,
  20083. payload,
  20084. networkDetails: null
  20085. };
  20086. this._handleFragmentLoadProgress(data);
  20087. if (complete) {
  20088. super._handleFragmentLoadComplete(data);
  20089. }
  20090. } else if (mainAnchor && mainAnchor.cc !== waitingData.frag.cc) {
  20091. this.syncWithAnchor(mainAnchor, waitingData.frag);
  20092. }
  20093. } else {
  20094. this.state = State.IDLE;
  20095. }
  20096. }
  20097. }
  20098. this.onTickEnd();
  20099. }
  20100. resetLoadingState() {
  20101. const waitingData = this.waitingData;
  20102. if (waitingData) {
  20103. this.fragmentTracker.removeFragment(waitingData.frag);
  20104. this.waitingData = null;
  20105. }
  20106. super.resetLoadingState();
  20107. }
  20108. onTickEnd() {
  20109. const {
  20110. media
  20111. } = this;
  20112. if (!(media != null && media.readyState)) {
  20113. return;
  20114. }
  20115. this.lastCurrentTime = media.currentTime;
  20116. }
  20117. doTickIdle() {
  20118. var _this$mainFragLoading2;
  20119. const {
  20120. hls,
  20121. levels,
  20122. media,
  20123. trackId
  20124. } = this;
  20125. const config2 = hls.config;
  20126. if (!this.buffering || !media && !this.primaryPrefetch && (this.startFragRequested || !config2.startFragPrefetch) || !(levels != null && levels[trackId])) {
  20127. return;
  20128. }
  20129. const levelInfo = levels[trackId];
  20130. const trackDetails = levelInfo.details;
  20131. if (!trackDetails || this.waitForLive(levelInfo) || this.waitForCdnTuneIn(trackDetails)) {
  20132. this.state = State.WAITING_TRACK;
  20133. this.startFragRequested = false;
  20134. return;
  20135. }
  20136. const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;
  20137. if (this.bufferFlushed && bufferable) {
  20138. this.bufferFlushed = false;
  20139. this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO);
  20140. }
  20141. const bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO);
  20142. if (bufferInfo === null) {
  20143. return;
  20144. }
  20145. if (!this.switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {
  20146. hls.trigger(Events.BUFFER_EOS, {
  20147. type: "audio"
  20148. });
  20149. this.state = State.ENDED;
  20150. return;
  20151. }
  20152. const bufferLen = bufferInfo.len;
  20153. const maxBufLen = hls.maxBufferLength;
  20154. const fragments = trackDetails.fragments;
  20155. const start = fragments[0].start;
  20156. const loadPosition = this.getLoadPosition();
  20157. const targetBufferTime = this.flushing ? loadPosition : bufferInfo.end;
  20158. if (this.switchingTrack && media) {
  20159. const pos = loadPosition;
  20160. if (trackDetails.PTSKnown && pos < start) {
  20161. if (bufferInfo.end > start || bufferInfo.nextStart) {
  20162. this.log("Alt audio track ahead of main track, seek to start of alt audio track");
  20163. media.currentTime = start + 0.05;
  20164. }
  20165. }
  20166. }
  20167. if (bufferLen >= maxBufLen && !this.switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) {
  20168. return;
  20169. }
  20170. let frag = this.getNextFragment(targetBufferTime, trackDetails);
  20171. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  20172. frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  20173. }
  20174. if (!frag) {
  20175. this.bufferFlushed = true;
  20176. return;
  20177. }
  20178. let mainFragLoading = ((_this$mainFragLoading2 = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading2.frag) || null;
  20179. if (!this.audioOnly && this.startFragRequested && mainFragLoading && isMediaFragment(frag) && !frag.endList && (!trackDetails.live || !this.loadingParts && targetBufferTime < this.hls.liveSyncPosition)) {
  20180. if (this.fragmentTracker.getState(mainFragLoading) === FragmentState.OK) {
  20181. this.mainFragLoading = mainFragLoading = null;
  20182. }
  20183. if (mainFragLoading && isMediaFragment(mainFragLoading)) {
  20184. if (frag.start > mainFragLoading.end) {
  20185. const mainFragAtPos = this.fragmentTracker.getFragAtPos(targetBufferTime, PlaylistLevelType.MAIN);
  20186. if (mainFragAtPos && mainFragAtPos.end > mainFragLoading.end) {
  20187. mainFragLoading = mainFragAtPos;
  20188. this.mainFragLoading = {
  20189. frag: mainFragAtPos,
  20190. targetBufferTime: null
  20191. };
  20192. }
  20193. }
  20194. const atBufferSyncLimit = frag.start > mainFragLoading.end;
  20195. if (atBufferSyncLimit) {
  20196. return;
  20197. }
  20198. }
  20199. }
  20200. this.loadFragment(frag, levelInfo, targetBufferTime);
  20201. }
  20202. onMediaDetaching(event, data) {
  20203. this.bufferFlushed = this.flushing = false;
  20204. super.onMediaDetaching(event, data);
  20205. }
  20206. onAudioTracksUpdated(event, {
  20207. audioTracks
  20208. }) {
  20209. this.resetTransmuxer();
  20210. this.levels = audioTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
  20211. }
  20212. onAudioTrackSwitching(event, data) {
  20213. const altAudio = !!data.url;
  20214. this.trackId = data.id;
  20215. const {
  20216. fragCurrent
  20217. } = this;
  20218. if (fragCurrent) {
  20219. fragCurrent.abortRequests();
  20220. this.removeUnbufferedFrags(fragCurrent.start);
  20221. }
  20222. this.resetLoadingState();
  20223. if (altAudio) {
  20224. this.switchingTrack = data;
  20225. this.flushAudioIfNeeded(data);
  20226. if (this.state !== State.STOPPED) {
  20227. this.setInterval(TICK_INTERVAL$3);
  20228. this.state = State.IDLE;
  20229. this.tick();
  20230. }
  20231. } else {
  20232. this.resetTransmuxer();
  20233. this.switchingTrack = null;
  20234. this.bufferedTrack = data;
  20235. this.clearInterval();
  20236. }
  20237. }
  20238. onManifestLoading() {
  20239. super.onManifestLoading();
  20240. this.bufferFlushed = this.flushing = this.audioOnly = false;
  20241. this.resetItem();
  20242. this.trackId = -1;
  20243. }
  20244. onLevelLoaded(event, data) {
  20245. this.mainDetails = data.details;
  20246. const cachedTrackLoadedData = this.cachedTrackLoadedData;
  20247. if (cachedTrackLoadedData) {
  20248. this.cachedTrackLoadedData = null;
  20249. this.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED, cachedTrackLoadedData);
  20250. }
  20251. }
  20252. onAudioTrackLoaded(event, data) {
  20253. var _trackLevel$details;
  20254. const {
  20255. levels
  20256. } = this;
  20257. const {
  20258. details: newDetails,
  20259. id: trackId,
  20260. groupId,
  20261. track
  20262. } = data;
  20263. if (!levels) {
  20264. this.warn(`Audio tracks reset while loading track ${trackId} "${track.name}" of "${groupId}"`);
  20265. return;
  20266. }
  20267. const mainDetails = this.mainDetails;
  20268. if (!mainDetails || newDetails.endCC > mainDetails.endCC || mainDetails.expired) {
  20269. this.cachedTrackLoadedData = data;
  20270. if (this.state !== State.STOPPED) {
  20271. this.state = State.WAITING_TRACK;
  20272. }
  20273. return;
  20274. }
  20275. this.cachedTrackLoadedData = null;
  20276. this.log(`Audio track ${trackId} "${track.name}" of "${groupId}" loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
  20277. const trackLevel = levels[trackId];
  20278. let sliding = 0;
  20279. if (newDetails.live || (_trackLevel$details = trackLevel.details) != null && _trackLevel$details.live) {
  20280. this.checkLiveUpdate(newDetails);
  20281. if (newDetails.deltaUpdateFailed) {
  20282. return;
  20283. }
  20284. if (trackLevel.details) {
  20285. var _this$levelLastLoaded;
  20286. sliding = this.alignPlaylists(newDetails, trackLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  20287. }
  20288. if (!newDetails.alignedSliding) {
  20289. alignDiscontinuities(newDetails, mainDetails);
  20290. if (!newDetails.alignedSliding) {
  20291. alignMediaPlaylistByPDT(newDetails, mainDetails);
  20292. }
  20293. sliding = newDetails.fragmentStart;
  20294. }
  20295. }
  20296. trackLevel.details = newDetails;
  20297. this.levelLastLoaded = trackLevel;
  20298. if (!this.startFragRequested) {
  20299. this.setStartPosition(mainDetails, sliding);
  20300. }
  20301. this.hls.trigger(Events.AUDIO_TRACK_UPDATED, {
  20302. details: newDetails,
  20303. id: trackId,
  20304. groupId: data.groupId
  20305. });
  20306. if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
  20307. this.state = State.IDLE;
  20308. }
  20309. this.tick();
  20310. }
  20311. _handleFragmentLoadProgress(data) {
  20312. var _frag$initSegment;
  20313. const frag = data.frag;
  20314. const {
  20315. part,
  20316. payload
  20317. } = data;
  20318. const {
  20319. config: config2,
  20320. trackId,
  20321. levels
  20322. } = this;
  20323. if (!levels) {
  20324. this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  20325. return;
  20326. }
  20327. const track = levels[trackId];
  20328. if (!track) {
  20329. this.warn("Audio track is undefined on fragment load progress");
  20330. return;
  20331. }
  20332. const details = track.details;
  20333. if (!details) {
  20334. this.warn("Audio track details undefined on fragment load progress");
  20335. this.removeUnbufferedFrags(frag.start);
  20336. return;
  20337. }
  20338. const audioCodec = config2.defaultAudioCodec || track.audioCodec || "mp4a.40.2";
  20339. let transmuxer = this.transmuxer;
  20340. if (!transmuxer) {
  20341. transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  20342. }
  20343. const initPTS = this.initPTS[frag.cc];
  20344. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  20345. if (initPTS !== void 0) {
  20346. const accurateTimeOffset = false;
  20347. const partIndex = part ? part.index : -1;
  20348. const partial2 = partIndex !== -1;
  20349. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial2);
  20350. transmuxer.push(payload, initSegmentData, audioCodec, "", frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  20351. } else {
  20352. 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}`);
  20353. const {
  20354. cache
  20355. } = this.waitingData = this.waitingData || {
  20356. frag,
  20357. part,
  20358. cache: new ChunkCache(),
  20359. complete: false
  20360. };
  20361. cache.push(new Uint8Array(payload));
  20362. if (this.state !== State.STOPPED) {
  20363. this.state = State.WAITING_INIT_PTS;
  20364. }
  20365. }
  20366. }
  20367. _handleFragmentLoadComplete(fragLoadedData) {
  20368. if (this.waitingData) {
  20369. this.waitingData.complete = true;
  20370. return;
  20371. }
  20372. super._handleFragmentLoadComplete(fragLoadedData);
  20373. }
  20374. onBufferReset() {
  20375. this.mediaBuffer = null;
  20376. }
  20377. onBufferCreated(event, data) {
  20378. this.bufferFlushed = this.flushing = false;
  20379. const audioTrack = data.tracks.audio;
  20380. if (audioTrack) {
  20381. this.mediaBuffer = audioTrack.buffer || null;
  20382. }
  20383. }
  20384. onFragLoading(event, data) {
  20385. if (!this.audioOnly && data.frag.type === PlaylistLevelType.MAIN && isMediaFragment(data.frag)) {
  20386. this.mainFragLoading = data;
  20387. if (this.state === State.IDLE) {
  20388. this.tick();
  20389. }
  20390. }
  20391. }
  20392. onFragBuffered(event, data) {
  20393. const {
  20394. frag,
  20395. part
  20396. } = data;
  20397. if (frag.type !== PlaylistLevelType.AUDIO) {
  20398. if (!this.audioOnly && frag.type === PlaylistLevelType.MAIN && !frag.elementaryStreams.video && !frag.elementaryStreams.audiovideo) {
  20399. this.audioOnly = true;
  20400. this.mainFragLoading = null;
  20401. }
  20402. return;
  20403. }
  20404. if (this.fragContextChanged(frag)) {
  20405. 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"}`);
  20406. return;
  20407. }
  20408. if (isMediaFragment(frag)) {
  20409. this.fragPrevious = frag;
  20410. const track = this.switchingTrack;
  20411. if (track) {
  20412. this.bufferedTrack = track;
  20413. this.switchingTrack = null;
  20414. this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, track));
  20415. }
  20416. }
  20417. this.fragBufferedComplete(frag, part);
  20418. if (this.media) {
  20419. this.tick();
  20420. }
  20421. }
  20422. onError(event, data) {
  20423. var _data$context;
  20424. if (data.fatal) {
  20425. this.state = State.ERROR;
  20426. return;
  20427. }
  20428. switch (data.details) {
  20429. case ErrorDetails.FRAG_GAP:
  20430. case ErrorDetails.FRAG_PARSING_ERROR:
  20431. case ErrorDetails.FRAG_DECRYPT_ERROR:
  20432. case ErrorDetails.FRAG_LOAD_ERROR:
  20433. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  20434. case ErrorDetails.KEY_LOAD_ERROR:
  20435. case ErrorDetails.KEY_LOAD_TIMEOUT:
  20436. this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);
  20437. break;
  20438. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  20439. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  20440. case ErrorDetails.LEVEL_PARSING_ERROR:
  20441. if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) {
  20442. this.state = State.IDLE;
  20443. }
  20444. break;
  20445. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  20446. case ErrorDetails.BUFFER_APPEND_ERROR:
  20447. if (data.parent !== "audio") {
  20448. return;
  20449. }
  20450. if (!this.reduceLengthAndFlushBuffer(data)) {
  20451. this.resetLoadingState();
  20452. }
  20453. break;
  20454. case ErrorDetails.BUFFER_FULL_ERROR:
  20455. if (data.parent !== "audio") {
  20456. return;
  20457. }
  20458. if (this.reduceLengthAndFlushBuffer(data)) {
  20459. this.bufferedTrack = null;
  20460. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
  20461. }
  20462. break;
  20463. case ErrorDetails.INTERNAL_EXCEPTION:
  20464. this.recoverWorkerError(data);
  20465. break;
  20466. }
  20467. }
  20468. onBufferFlushing(event, {
  20469. type
  20470. }) {
  20471. if (type !== ElementaryStreamTypes.VIDEO) {
  20472. this.flushing = true;
  20473. }
  20474. }
  20475. onBufferFlushed(event, {
  20476. type
  20477. }) {
  20478. if (type !== ElementaryStreamTypes.VIDEO) {
  20479. this.flushing = false;
  20480. this.bufferFlushed = true;
  20481. if (this.state === State.ENDED) {
  20482. this.state = State.IDLE;
  20483. }
  20484. const mediaBuffer = this.mediaBuffer || this.media;
  20485. if (mediaBuffer) {
  20486. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO);
  20487. this.tick();
  20488. }
  20489. }
  20490. }
  20491. _handleTransmuxComplete(transmuxResult) {
  20492. var _id3$samples;
  20493. const id = "audio";
  20494. const {
  20495. hls
  20496. } = this;
  20497. const {
  20498. remuxResult,
  20499. chunkMeta
  20500. } = transmuxResult;
  20501. const context = this.getCurrentContext(chunkMeta);
  20502. if (!context) {
  20503. this.resetWhenMissingContext(chunkMeta);
  20504. return;
  20505. }
  20506. const {
  20507. frag,
  20508. part,
  20509. level
  20510. } = context;
  20511. const {
  20512. details
  20513. } = level;
  20514. const {
  20515. audio,
  20516. text,
  20517. id3,
  20518. initSegment
  20519. } = remuxResult;
  20520. if (this.fragContextChanged(frag) || !details) {
  20521. this.fragmentTracker.removeFragment(frag);
  20522. return;
  20523. }
  20524. this.state = State.PARSING;
  20525. if (this.switchingTrack && audio) {
  20526. this.completeAudioSwitch(this.switchingTrack);
  20527. }
  20528. if (initSegment != null && initSegment.tracks) {
  20529. const mapFragment = frag.initSegment || frag;
  20530. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  20531. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  20532. frag: mapFragment,
  20533. id,
  20534. tracks: initSegment.tracks
  20535. });
  20536. }
  20537. if (audio) {
  20538. const {
  20539. startPTS,
  20540. endPTS,
  20541. startDTS,
  20542. endDTS
  20543. } = audio;
  20544. if (part) {
  20545. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  20546. startPTS,
  20547. endPTS,
  20548. startDTS,
  20549. endDTS
  20550. };
  20551. }
  20552. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  20553. this.bufferFragmentData(audio, frag, part, chunkMeta);
  20554. }
  20555. if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  20556. const emittedID3 = _extends({
  20557. id,
  20558. frag,
  20559. details
  20560. }, id3);
  20561. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  20562. }
  20563. if (text) {
  20564. const emittedText = _extends({
  20565. id,
  20566. frag,
  20567. details
  20568. }, text);
  20569. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  20570. }
  20571. }
  20572. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  20573. if (this.state !== State.PARSING) {
  20574. return;
  20575. }
  20576. if (tracks.video) {
  20577. delete tracks.video;
  20578. }
  20579. if (tracks.audiovideo) {
  20580. delete tracks.audiovideo;
  20581. }
  20582. if (!tracks.audio) {
  20583. return;
  20584. }
  20585. const track = tracks.audio;
  20586. track.id = PlaylistLevelType.AUDIO;
  20587. const variantAudioCodecs = currentLevel.audioCodec;
  20588. this.log(`Init audio buffer, container:${track.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track.codec}]`);
  20589. if (variantAudioCodecs && variantAudioCodecs.split(",").length === 1) {
  20590. track.levelCodec = variantAudioCodecs;
  20591. }
  20592. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  20593. const initSegment = track.initSegment;
  20594. if (initSegment != null && initSegment.byteLength) {
  20595. const segment = {
  20596. type: "audio",
  20597. frag,
  20598. part: null,
  20599. chunkMeta,
  20600. parent: frag.type,
  20601. data: initSegment
  20602. };
  20603. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  20604. }
  20605. this.tickImmediate();
  20606. }
  20607. loadFragment(frag, track, targetBufferTime) {
  20608. const fragState = this.fragmentTracker.getState(frag);
  20609. if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  20610. var _track$details;
  20611. if (!isMediaFragment(frag)) {
  20612. this._loadInitSegment(frag, track);
  20613. } else if ((_track$details = track.details) != null && _track$details.live && !this.initPTS[frag.cc]) {
  20614. this.log(`Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`);
  20615. this.state = State.WAITING_INIT_PTS;
  20616. const mainDetails = this.mainDetails;
  20617. if (mainDetails && mainDetails.fragmentStart !== track.details.fragmentStart) {
  20618. alignMediaPlaylistByPDT(track.details, mainDetails);
  20619. }
  20620. } else {
  20621. super.loadFragment(frag, track, targetBufferTime);
  20622. }
  20623. } else {
  20624. this.clearTrackerIfNeeded(frag);
  20625. }
  20626. }
  20627. flushAudioIfNeeded(switchingTrack) {
  20628. if (this.media && this.bufferedTrack) {
  20629. const {
  20630. name,
  20631. lang,
  20632. assocLang,
  20633. characteristics,
  20634. audioCodec,
  20635. channels
  20636. } = this.bufferedTrack;
  20637. if (!matchesOption({
  20638. name,
  20639. lang,
  20640. assocLang,
  20641. characteristics,
  20642. audioCodec,
  20643. channels
  20644. }, switchingTrack, audioMatchPredicate)) {
  20645. if (useAlternateAudio(switchingTrack.url, this.hls)) {
  20646. this.log("Switching audio track : flushing all audio");
  20647. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
  20648. this.bufferedTrack = null;
  20649. } else {
  20650. this.bufferedTrack = switchingTrack;
  20651. }
  20652. }
  20653. }
  20654. }
  20655. completeAudioSwitch(switchingTrack) {
  20656. const {
  20657. hls
  20658. } = this;
  20659. this.flushAudioIfNeeded(switchingTrack);
  20660. this.bufferedTrack = switchingTrack;
  20661. this.switchingTrack = null;
  20662. hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, switchingTrack));
  20663. }
  20664. }
  20665. class BasePlaylistController extends Logger {
  20666. constructor(hls, logPrefix) {
  20667. super(logPrefix, hls.logger);
  20668. this.hls = void 0;
  20669. this.canLoad = false;
  20670. this.timer = -1;
  20671. this.hls = hls;
  20672. }
  20673. destroy() {
  20674. this.clearTimer();
  20675. this.hls = this.log = this.warn = null;
  20676. }
  20677. clearTimer() {
  20678. if (this.timer !== -1) {
  20679. self.clearTimeout(this.timer);
  20680. this.timer = -1;
  20681. }
  20682. }
  20683. startLoad() {
  20684. this.canLoad = true;
  20685. this.loadPlaylist();
  20686. }
  20687. stopLoad() {
  20688. this.canLoad = false;
  20689. this.clearTimer();
  20690. }
  20691. switchParams(playlistUri, previous, current) {
  20692. const renditionReports = previous == null ? void 0 : previous.renditionReports;
  20693. if (renditionReports) {
  20694. let foundIndex = -1;
  20695. for (let i2 = 0; i2 < renditionReports.length; i2++) {
  20696. const attr = renditionReports[i2];
  20697. let uri;
  20698. try {
  20699. uri = new self.URL(attr.URI, previous.url).href;
  20700. } catch (error2) {
  20701. this.warn(`Could not construct new URL for Rendition Report: ${error2}`);
  20702. uri = attr.URI || "";
  20703. }
  20704. if (uri === playlistUri) {
  20705. foundIndex = i2;
  20706. break;
  20707. } else if (uri === playlistUri.substring(0, uri.length)) {
  20708. foundIndex = i2;
  20709. }
  20710. }
  20711. if (foundIndex !== -1) {
  20712. const attr = renditionReports[foundIndex];
  20713. const msn = parseInt(attr["LAST-MSN"]) || (previous == null ? void 0 : previous.lastPartSn);
  20714. let part = parseInt(attr["LAST-PART"]) || (previous == null ? void 0 : previous.lastPartIndex);
  20715. if (this.hls.config.lowLatencyMode) {
  20716. const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  20717. if (part >= 0 && currentGoal > previous.partTarget) {
  20718. part += 1;
  20719. }
  20720. }
  20721. const skip = current && getSkipValue(current);
  20722. return new HlsUrlParameters(msn, part >= 0 ? part : void 0, skip);
  20723. }
  20724. }
  20725. }
  20726. loadPlaylist(hlsUrlParameters) {
  20727. this.clearTimer();
  20728. }
  20729. loadingPlaylist(playlist, hlsUrlParameters) {
  20730. this.clearTimer();
  20731. }
  20732. shouldLoadPlaylist(playlist) {
  20733. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  20734. }
  20735. getUrlWithDirectives(uri, hlsUrlParameters) {
  20736. if (hlsUrlParameters) {
  20737. try {
  20738. return hlsUrlParameters.addDirectives(uri);
  20739. } catch (error2) {
  20740. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error2}`);
  20741. }
  20742. }
  20743. return uri;
  20744. }
  20745. playlistLoaded(index2, data, previousDetails) {
  20746. const {
  20747. details,
  20748. stats
  20749. } = data;
  20750. const now2 = self.performance.now();
  20751. const elapsed = stats.loading.first ? Math.max(0, now2 - stats.loading.first) : 0;
  20752. details.advancedDateTime = Date.now() - elapsed;
  20753. const timelineOffset = this.hls.config.timelineOffset;
  20754. if (timelineOffset !== details.appliedTimelineOffset) {
  20755. const offset = Math.max(timelineOffset || 0, 0);
  20756. details.appliedTimelineOffset = offset;
  20757. details.fragments.forEach((frag) => {
  20758. frag.start = frag.playlistOffset + offset;
  20759. });
  20760. }
  20761. if (details.live || previousDetails != null && previousDetails.live) {
  20762. const levelOrTrack = "levelInfo" in data ? data.levelInfo : data.track;
  20763. details.reloaded(previousDetails);
  20764. if (previousDetails && details.fragments.length > 0) {
  20765. mergeDetails(previousDetails, details);
  20766. const error2 = details.playlistParsingError;
  20767. if (error2) {
  20768. this.warn(error2);
  20769. const hls = this.hls;
  20770. if (!hls.config.ignorePlaylistParsingErrors) {
  20771. var _details$fragments$;
  20772. const {
  20773. networkDetails
  20774. } = data;
  20775. hls.trigger(Events.ERROR, {
  20776. type: ErrorTypes.NETWORK_ERROR,
  20777. details: ErrorDetails.LEVEL_PARSING_ERROR,
  20778. fatal: false,
  20779. url: details.url,
  20780. error: error2,
  20781. reason: error2.message,
  20782. level: data.level || void 0,
  20783. parent: (_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.type,
  20784. networkDetails,
  20785. stats
  20786. });
  20787. return;
  20788. }
  20789. details.playlistParsingError = null;
  20790. }
  20791. }
  20792. if (details.requestScheduled === -1) {
  20793. details.requestScheduled = stats.loading.start;
  20794. }
  20795. const bufferInfo = this.hls.mainForwardBufferInfo;
  20796. const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  20797. const distanceToLiveEdgeMs = (details.edge - position) * 1e3;
  20798. const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  20799. if (details.requestScheduled + reloadInterval < now2) {
  20800. details.requestScheduled = now2;
  20801. } else {
  20802. details.requestScheduled += reloadInterval;
  20803. }
  20804. this.log(`live playlist ${index2} ${details.advanced ? "REFRESHED " + details.lastPartSn + "-" + details.lastPartIndex : details.updated ? "UPDATED" : "MISSED"}`);
  20805. if (!this.canLoad || !details.live) {
  20806. return;
  20807. }
  20808. let deliveryDirectives;
  20809. let msn = void 0;
  20810. let part = void 0;
  20811. if (details.canBlockReload && details.endSN && details.advanced) {
  20812. const lowLatencyMode = this.hls.config.lowLatencyMode;
  20813. const lastPartSn = details.lastPartSn;
  20814. const endSn = details.endSN;
  20815. const lastPartIndex = details.lastPartIndex;
  20816. const hasParts = lastPartIndex !== -1;
  20817. const atLastPartOfSegment = lastPartSn === endSn;
  20818. if (hasParts) {
  20819. if (atLastPartOfSegment) {
  20820. msn = endSn + 1;
  20821. part = lowLatencyMode ? 0 : lastPartIndex;
  20822. } else {
  20823. msn = lastPartSn;
  20824. part = lowLatencyMode ? lastPartIndex + 1 : details.maxPartIndex;
  20825. }
  20826. } else {
  20827. msn = endSn + 1;
  20828. }
  20829. const lastAdvanced = details.age;
  20830. const cdnAge = lastAdvanced + details.ageHeader;
  20831. let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  20832. if (currentGoal > 0) {
  20833. if (cdnAge > details.targetduration * 3) {
  20834. this.log(`Playlist last advanced ${lastAdvanced.toFixed(2)}s ago. Omitting segment and part directives.`);
  20835. msn = void 0;
  20836. part = void 0;
  20837. } else if (previousDetails != null && previousDetails.tuneInGoal && cdnAge - details.partTarget > previousDetails.tuneInGoal) {
  20838. this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);
  20839. currentGoal = 0;
  20840. } else {
  20841. const segments = Math.floor(currentGoal / details.targetduration);
  20842. msn += segments;
  20843. if (part !== void 0) {
  20844. const parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  20845. part += parts;
  20846. }
  20847. this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);
  20848. }
  20849. details.tuneInGoal = currentGoal;
  20850. }
  20851. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  20852. if (lowLatencyMode || !atLastPartOfSegment) {
  20853. details.requestScheduled = now2;
  20854. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  20855. return;
  20856. }
  20857. } else if (details.canBlockReload || details.canSkipUntil) {
  20858. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  20859. }
  20860. if (deliveryDirectives && msn !== void 0 && details.canBlockReload) {
  20861. details.requestScheduled = stats.loading.first + Math.max(reloadInterval - elapsed * 2, reloadInterval / 2);
  20862. }
  20863. this.scheduleLoading(levelOrTrack, deliveryDirectives, details);
  20864. } else {
  20865. this.clearTimer();
  20866. }
  20867. }
  20868. scheduleLoading(levelOrTrack, deliveryDirectives, updatedDetails) {
  20869. const details = updatedDetails || levelOrTrack.details;
  20870. if (!details) {
  20871. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  20872. return;
  20873. }
  20874. const now2 = self.performance.now();
  20875. const requestScheduled = details.requestScheduled;
  20876. if (now2 >= requestScheduled) {
  20877. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  20878. return;
  20879. }
  20880. const estimatedTimeUntilUpdate = requestScheduled - now2;
  20881. this.log(`reload live playlist ${levelOrTrack.name || levelOrTrack.bitrate + "bps"} in ${Math.round(estimatedTimeUntilUpdate)} ms`);
  20882. this.clearTimer();
  20883. this.timer = self.setTimeout(() => this.loadingPlaylist(levelOrTrack, deliveryDirectives), estimatedTimeUntilUpdate);
  20884. }
  20885. getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  20886. let skip = getSkipValue(details);
  20887. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  20888. msn = previousDeliveryDirectives.msn;
  20889. part = previousDeliveryDirectives.part;
  20890. skip = HlsSkip.No;
  20891. }
  20892. return new HlsUrlParameters(msn, part, skip);
  20893. }
  20894. checkRetry(errorEvent) {
  20895. const errorDetails = errorEvent.details;
  20896. const isTimeout = isTimeoutError(errorEvent);
  20897. const errorAction = errorEvent.errorAction;
  20898. const {
  20899. action,
  20900. retryCount = 0,
  20901. retryConfig
  20902. } = errorAction || {};
  20903. const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  20904. if (retry) {
  20905. var _errorEvent$context;
  20906. if (retryCount >= retryConfig.maxNumRetry) {
  20907. return false;
  20908. }
  20909. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  20910. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`);
  20911. this.loadPlaylist();
  20912. } else {
  20913. const delay = getRetryDelay(retryConfig, retryCount);
  20914. this.clearTimer();
  20915. this.timer = self.setTimeout(() => this.loadPlaylist(), delay);
  20916. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay}ms`);
  20917. }
  20918. errorEvent.levelRetry = true;
  20919. errorAction.resolved = true;
  20920. }
  20921. return retry;
  20922. }
  20923. }
  20924. function subtitleOptionsIdentical(trackList1, trackList2) {
  20925. if (trackList1.length !== trackList2.length) {
  20926. return false;
  20927. }
  20928. for (let i2 = 0; i2 < trackList1.length; i2++) {
  20929. if (!mediaAttributesIdentical(trackList1[i2].attrs, trackList2[i2].attrs)) {
  20930. return false;
  20931. }
  20932. }
  20933. return true;
  20934. }
  20935. function mediaAttributesIdentical(attrs1, attrs2, customAttributes) {
  20936. const stableRenditionId = attrs1["STABLE-RENDITION-ID"];
  20937. if (stableRenditionId && !customAttributes) {
  20938. return stableRenditionId === attrs2["STABLE-RENDITION-ID"];
  20939. }
  20940. return !(customAttributes || ["LANGUAGE", "NAME", "CHARACTERISTICS", "AUTOSELECT", "DEFAULT", "FORCED", "ASSOC-LANGUAGE"]).some((subtitleAttribute) => attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]);
  20941. }
  20942. function subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) {
  20943. return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || "").toLowerCase());
  20944. }
  20945. class AudioTrackController extends BasePlaylistController {
  20946. constructor(hls) {
  20947. super(hls, "audio-track-controller");
  20948. this.tracks = [];
  20949. this.groupIds = null;
  20950. this.tracksInGroup = [];
  20951. this.trackId = -1;
  20952. this.currentTrack = null;
  20953. this.selectDefaultTrack = true;
  20954. this.registerListeners();
  20955. }
  20956. registerListeners() {
  20957. const {
  20958. hls
  20959. } = this;
  20960. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  20961. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  20962. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  20963. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  20964. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  20965. hls.on(Events.ERROR, this.onError, this);
  20966. }
  20967. unregisterListeners() {
  20968. const {
  20969. hls
  20970. } = this;
  20971. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  20972. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  20973. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  20974. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  20975. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  20976. hls.off(Events.ERROR, this.onError, this);
  20977. }
  20978. destroy() {
  20979. this.unregisterListeners();
  20980. this.tracks.length = 0;
  20981. this.tracksInGroup.length = 0;
  20982. this.currentTrack = null;
  20983. super.destroy();
  20984. }
  20985. onManifestLoading() {
  20986. this.tracks = [];
  20987. this.tracksInGroup = [];
  20988. this.groupIds = null;
  20989. this.currentTrack = null;
  20990. this.trackId = -1;
  20991. this.selectDefaultTrack = true;
  20992. }
  20993. onManifestParsed(event, data) {
  20994. this.tracks = data.audioTracks || [];
  20995. }
  20996. onAudioTrackLoaded(event, data) {
  20997. const {
  20998. id,
  20999. groupId,
  21000. details
  21001. } = data;
  21002. const trackInActiveGroup = this.tracksInGroup[id];
  21003. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  21004. this.warn(`Audio track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  21005. return;
  21006. }
  21007. const curDetails = trackInActiveGroup.details;
  21008. trackInActiveGroup.details = data.details;
  21009. this.log(`Audio track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  21010. if (id === this.trackId) {
  21011. this.playlistLoaded(id, data, curDetails);
  21012. }
  21013. }
  21014. onLevelLoading(event, data) {
  21015. this.switchLevel(data.level);
  21016. }
  21017. onLevelSwitching(event, data) {
  21018. this.switchLevel(data.level);
  21019. }
  21020. switchLevel(levelIndex) {
  21021. const levelInfo = this.hls.levels[levelIndex];
  21022. if (!levelInfo) {
  21023. return;
  21024. }
  21025. const audioGroups = levelInfo.audioGroups || null;
  21026. const currentGroups = this.groupIds;
  21027. let currentTrack = this.currentTrack;
  21028. 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)) {
  21029. this.groupIds = audioGroups;
  21030. this.trackId = -1;
  21031. this.currentTrack = null;
  21032. const audioTracks = this.tracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  21033. if (audioTracks.length) {
  21034. if (this.selectDefaultTrack && !audioTracks.some((track) => track.default)) {
  21035. this.selectDefaultTrack = false;
  21036. }
  21037. audioTracks.forEach((track, i2) => {
  21038. track.id = i2;
  21039. });
  21040. } else if (!currentTrack && !this.tracksInGroup.length) {
  21041. return;
  21042. }
  21043. this.tracksInGroup = audioTracks;
  21044. const audioPreference = this.hls.config.audioPreference;
  21045. if (!currentTrack && audioPreference) {
  21046. const groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate);
  21047. if (groupIndex > -1) {
  21048. currentTrack = audioTracks[groupIndex];
  21049. } else {
  21050. const allIndex = findMatchingOption(audioPreference, this.tracks);
  21051. currentTrack = this.tracks[allIndex];
  21052. }
  21053. }
  21054. let trackId = this.findTrackId(currentTrack);
  21055. if (trackId === -1 && currentTrack) {
  21056. trackId = this.findTrackId(null);
  21057. }
  21058. const audioTracksUpdated = {
  21059. audioTracks
  21060. };
  21061. this.log(`Updating audio tracks, ${audioTracks.length} track(s) found in group(s): ${audioGroups == null ? void 0 : audioGroups.join(",")}`);
  21062. this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);
  21063. const selectedTrackId = this.trackId;
  21064. if (trackId !== -1 && selectedTrackId === -1) {
  21065. this.setAudioTrack(trackId);
  21066. } else if (audioTracks.length && selectedTrackId === -1) {
  21067. var _this$groupIds;
  21068. const error2 = 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}`);
  21069. this.warn(error2.message);
  21070. this.hls.trigger(Events.ERROR, {
  21071. type: ErrorTypes.MEDIA_ERROR,
  21072. details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  21073. fatal: true,
  21074. error: error2
  21075. });
  21076. }
  21077. }
  21078. }
  21079. onError(event, data) {
  21080. if (data.fatal || !data.context) {
  21081. return;
  21082. }
  21083. if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  21084. this.checkRetry(data);
  21085. }
  21086. }
  21087. get allAudioTracks() {
  21088. return this.tracks;
  21089. }
  21090. get audioTracks() {
  21091. return this.tracksInGroup;
  21092. }
  21093. get audioTrack() {
  21094. return this.trackId;
  21095. }
  21096. set audioTrack(newId) {
  21097. this.selectDefaultTrack = false;
  21098. this.setAudioTrack(newId);
  21099. }
  21100. setAudioOption(audioOption) {
  21101. const hls = this.hls;
  21102. hls.config.audioPreference = audioOption;
  21103. if (audioOption) {
  21104. const allAudioTracks = this.allAudioTracks;
  21105. this.selectDefaultTrack = false;
  21106. if (allAudioTracks.length) {
  21107. const currentTrack = this.currentTrack;
  21108. if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) {
  21109. return currentTrack;
  21110. }
  21111. const groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate);
  21112. if (groupIndex > -1) {
  21113. const track = this.tracksInGroup[groupIndex];
  21114. this.setAudioTrack(groupIndex);
  21115. return track;
  21116. } else if (currentTrack) {
  21117. let searchIndex = hls.loadLevel;
  21118. if (searchIndex === -1) {
  21119. searchIndex = hls.firstAutoLevel;
  21120. }
  21121. const switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate);
  21122. if (switchIndex === -1) {
  21123. return null;
  21124. }
  21125. hls.nextLoadLevel = switchIndex;
  21126. }
  21127. if (audioOption.channels || audioOption.audioCodec) {
  21128. const withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks);
  21129. if (withoutCodecAndChannelsMatch > -1) {
  21130. return allAudioTracks[withoutCodecAndChannelsMatch];
  21131. }
  21132. }
  21133. }
  21134. }
  21135. return null;
  21136. }
  21137. setAudioTrack(newId) {
  21138. const tracks = this.tracksInGroup;
  21139. if (newId < 0 || newId >= tracks.length) {
  21140. this.warn(`Invalid audio track id: ${newId}`);
  21141. return;
  21142. }
  21143. this.selectDefaultTrack = false;
  21144. const lastTrack = this.currentTrack;
  21145. const track = tracks[newId];
  21146. const trackLoaded = track.details && !track.details.live;
  21147. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  21148. return;
  21149. }
  21150. this.log(`Switching to audio-track ${newId} "${track.name}" lang:${track.lang} group:${track.groupId} channels:${track.channels}`);
  21151. this.trackId = newId;
  21152. this.currentTrack = track;
  21153. this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread2({}, track));
  21154. if (trackLoaded) {
  21155. return;
  21156. }
  21157. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  21158. this.loadPlaylist(hlsUrlParameters);
  21159. }
  21160. findTrackId(currentTrack) {
  21161. const audioTracks = this.tracksInGroup;
  21162. for (let i2 = 0; i2 < audioTracks.length; i2++) {
  21163. const track = audioTracks[i2];
  21164. if (this.selectDefaultTrack && !track.default) {
  21165. continue;
  21166. }
  21167. if (!currentTrack || matchesOption(currentTrack, track, audioMatchPredicate)) {
  21168. return i2;
  21169. }
  21170. }
  21171. if (currentTrack) {
  21172. const {
  21173. name,
  21174. lang,
  21175. assocLang,
  21176. characteristics,
  21177. audioCodec,
  21178. channels
  21179. } = currentTrack;
  21180. for (let i2 = 0; i2 < audioTracks.length; i2++) {
  21181. const track = audioTracks[i2];
  21182. if (matchesOption({
  21183. name,
  21184. lang,
  21185. assocLang,
  21186. characteristics,
  21187. audioCodec,
  21188. channels
  21189. }, track, audioMatchPredicate)) {
  21190. return i2;
  21191. }
  21192. }
  21193. for (let i2 = 0; i2 < audioTracks.length; i2++) {
  21194. const track = audioTracks[i2];
  21195. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
  21196. return i2;
  21197. }
  21198. }
  21199. for (let i2 = 0; i2 < audioTracks.length; i2++) {
  21200. const track = audioTracks[i2];
  21201. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) {
  21202. return i2;
  21203. }
  21204. }
  21205. }
  21206. return -1;
  21207. }
  21208. loadPlaylist(hlsUrlParameters) {
  21209. super.loadPlaylist();
  21210. const audioTrack = this.currentTrack;
  21211. if (!this.shouldLoadPlaylist(audioTrack)) {
  21212. return;
  21213. }
  21214. if (useAlternateAudio(audioTrack.url, this.hls)) {
  21215. this.scheduleLoading(audioTrack, hlsUrlParameters);
  21216. }
  21217. }
  21218. loadingPlaylist(audioTrack, hlsUrlParameters) {
  21219. super.loadingPlaylist(audioTrack, hlsUrlParameters);
  21220. const id = audioTrack.id;
  21221. const groupId = audioTrack.groupId;
  21222. const url2 = this.getUrlWithDirectives(audioTrack.url, hlsUrlParameters);
  21223. const details = audioTrack.details;
  21224. const age = details == null ? void 0 : details.age;
  21225. 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 || "" : "") : ""} ${url2}`);
  21226. this.hls.trigger(Events.AUDIO_TRACK_LOADING, {
  21227. url: url2,
  21228. id,
  21229. groupId,
  21230. deliveryDirectives: hlsUrlParameters || null,
  21231. track: audioTrack
  21232. });
  21233. }
  21234. }
  21235. class BufferOperationQueue {
  21236. constructor(sourceBufferReference) {
  21237. this.tracks = void 0;
  21238. this.queues = {
  21239. video: [],
  21240. audio: [],
  21241. audiovideo: []
  21242. };
  21243. this.tracks = sourceBufferReference;
  21244. }
  21245. destroy() {
  21246. this.tracks = this.queues = null;
  21247. }
  21248. append(operation, type, pending) {
  21249. if (this.queues === null || this.tracks === null) {
  21250. return;
  21251. }
  21252. const queue = this.queues[type];
  21253. queue.push(operation);
  21254. if (queue.length === 1 && !pending) {
  21255. this.executeNext(type);
  21256. }
  21257. }
  21258. appendBlocker(type) {
  21259. return new Promise((resolve) => {
  21260. const operation = {
  21261. label: "async-blocker",
  21262. execute: resolve,
  21263. onStart: () => {
  21264. },
  21265. onComplete: () => {
  21266. },
  21267. onError: () => {
  21268. }
  21269. };
  21270. this.append(operation, type);
  21271. });
  21272. }
  21273. prependBlocker(type) {
  21274. return new Promise((resolve) => {
  21275. if (this.queues) {
  21276. const operation = {
  21277. label: "async-blocker-prepend",
  21278. execute: resolve,
  21279. onStart: () => {
  21280. },
  21281. onComplete: () => {
  21282. },
  21283. onError: () => {
  21284. }
  21285. };
  21286. this.queues[type].unshift(operation);
  21287. }
  21288. });
  21289. }
  21290. removeBlockers() {
  21291. if (this.queues === null) {
  21292. return;
  21293. }
  21294. [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach((queue) => {
  21295. var _queue$;
  21296. const label = (_queue$ = queue[0]) == null ? void 0 : _queue$.label;
  21297. if (label === "async-blocker" || label === "async-blocker-prepend") {
  21298. queue[0].execute();
  21299. queue.splice(0, 1);
  21300. }
  21301. });
  21302. }
  21303. unblockAudio(op) {
  21304. if (this.queues === null) {
  21305. return;
  21306. }
  21307. const queue = this.queues.audio;
  21308. if (queue[0] === op) {
  21309. this.shiftAndExecuteNext("audio");
  21310. }
  21311. }
  21312. executeNext(type) {
  21313. if (this.queues === null || this.tracks === null) {
  21314. return;
  21315. }
  21316. const queue = this.queues[type];
  21317. if (queue.length) {
  21318. const operation = queue[0];
  21319. try {
  21320. operation.execute();
  21321. } catch (error2) {
  21322. var _this$tracks$type;
  21323. operation.onError(error2);
  21324. if (this.queues === null || this.tracks === null) {
  21325. return;
  21326. }
  21327. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  21328. if (!(sb != null && sb.updating)) {
  21329. this.shiftAndExecuteNext(type);
  21330. }
  21331. }
  21332. }
  21333. }
  21334. shiftAndExecuteNext(type) {
  21335. if (this.queues === null) {
  21336. return;
  21337. }
  21338. this.queues[type].shift();
  21339. this.executeNext(type);
  21340. }
  21341. current(type) {
  21342. var _this$queues;
  21343. return ((_this$queues = this.queues) == null ? void 0 : _this$queues[type][0]) || null;
  21344. }
  21345. toString() {
  21346. const {
  21347. queues,
  21348. tracks
  21349. } = this;
  21350. if (queues === null || tracks === null) {
  21351. return `<destroyed>`;
  21352. }
  21353. return `
  21354. ${this.list("video")}
  21355. ${this.list("audio")}
  21356. ${this.list("audiovideo")}}`;
  21357. }
  21358. list(type) {
  21359. var _this$queues2, _this$tracks;
  21360. return (_this$queues2 = this.queues) != null && _this$queues2[type] || (_this$tracks = this.tracks) != null && _this$tracks[type] ? `${type}: (${this.listSbInfo(type)}) ${this.listOps(type)}` : "";
  21361. }
  21362. listSbInfo(type) {
  21363. var _this$tracks2;
  21364. const track = (_this$tracks2 = this.tracks) == null ? void 0 : _this$tracks2[type];
  21365. const sb = track == null ? void 0 : track.buffer;
  21366. if (!sb) {
  21367. return "none";
  21368. }
  21369. return `SourceBuffer${sb.updating ? " updating" : ""}${track.ended ? " ended" : ""}${track.ending ? " ending" : ""}`;
  21370. }
  21371. listOps(type) {
  21372. var _this$queues3;
  21373. return ((_this$queues3 = this.queues) == null ? void 0 : _this$queues3[type].map((op) => op.label).join(", ")) || "";
  21374. }
  21375. }
  21376. const VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  21377. const TRACK_REMOVED_ERROR_NAME = "HlsJsTrackRemovedError";
  21378. class HlsJsTrackRemovedError extends Error {
  21379. constructor(message) {
  21380. super(message);
  21381. this.name = TRACK_REMOVED_ERROR_NAME;
  21382. }
  21383. }
  21384. class BufferController extends Logger {
  21385. constructor(hls, fragmentTracker) {
  21386. super("buffer-controller", hls.logger);
  21387. this.hls = void 0;
  21388. this.fragmentTracker = void 0;
  21389. this.details = null;
  21390. this._objectUrl = null;
  21391. this.operationQueue = null;
  21392. this.bufferCodecEventsTotal = 0;
  21393. this.media = null;
  21394. this.mediaSource = null;
  21395. this.lastMpegAudioChunk = null;
  21396. this.blockedAudioAppend = null;
  21397. this.lastVideoAppendEnd = 0;
  21398. this.appendSource = void 0;
  21399. this.transferData = void 0;
  21400. this.overrides = void 0;
  21401. this.appendErrors = {
  21402. audio: 0,
  21403. video: 0,
  21404. audiovideo: 0
  21405. };
  21406. this.tracks = {};
  21407. this.sourceBuffers = [[null, null], [null, null]];
  21408. this._onEndStreaming = (event) => {
  21409. var _this$mediaSource;
  21410. if (!this.hls) {
  21411. return;
  21412. }
  21413. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) !== "open") {
  21414. return;
  21415. }
  21416. this.hls.pauseBuffering();
  21417. };
  21418. this._onStartStreaming = (event) => {
  21419. if (!this.hls) {
  21420. return;
  21421. }
  21422. this.hls.resumeBuffering();
  21423. };
  21424. this._onMediaSourceOpen = (e2) => {
  21425. const {
  21426. media,
  21427. mediaSource
  21428. } = this;
  21429. if (e2) {
  21430. this.log("Media source opened");
  21431. }
  21432. if (!media || !mediaSource) {
  21433. return;
  21434. }
  21435. mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
  21436. media.removeEventListener("emptied", this._onMediaEmptied);
  21437. this.updateDuration();
  21438. this.hls.trigger(Events.MEDIA_ATTACHED, {
  21439. media,
  21440. mediaSource
  21441. });
  21442. if (this.mediaSource !== null) {
  21443. this.checkPendingTracks();
  21444. }
  21445. };
  21446. this._onMediaSourceClose = () => {
  21447. this.log("Media source closed");
  21448. };
  21449. this._onMediaSourceEnded = () => {
  21450. this.log("Media source ended");
  21451. };
  21452. this._onMediaEmptied = () => {
  21453. const {
  21454. mediaSrc,
  21455. _objectUrl
  21456. } = this;
  21457. if (mediaSrc !== _objectUrl) {
  21458. this.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);
  21459. }
  21460. };
  21461. this.hls = hls;
  21462. this.fragmentTracker = fragmentTracker;
  21463. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  21464. this.initTracks();
  21465. this.registerListeners();
  21466. }
  21467. hasSourceTypes() {
  21468. return Object.keys(this.tracks).length > 0;
  21469. }
  21470. destroy() {
  21471. this.unregisterListeners();
  21472. this.details = null;
  21473. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  21474. this.transferData = this.overrides = void 0;
  21475. if (this.operationQueue) {
  21476. this.operationQueue.destroy();
  21477. this.operationQueue = null;
  21478. }
  21479. this.hls = this.fragmentTracker = null;
  21480. this._onMediaSourceOpen = this._onMediaSourceClose = null;
  21481. this._onMediaSourceEnded = null;
  21482. this._onStartStreaming = this._onEndStreaming = null;
  21483. }
  21484. registerListeners() {
  21485. const {
  21486. hls
  21487. } = this;
  21488. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21489. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21490. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21491. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  21492. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  21493. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  21494. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  21495. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  21496. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  21497. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  21498. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  21499. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  21500. hls.on(Events.ERROR, this.onError, this);
  21501. }
  21502. unregisterListeners() {
  21503. const {
  21504. hls
  21505. } = this;
  21506. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21507. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21508. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21509. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  21510. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  21511. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  21512. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  21513. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  21514. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  21515. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  21516. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  21517. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  21518. hls.off(Events.ERROR, this.onError, this);
  21519. }
  21520. transferMedia() {
  21521. const {
  21522. media,
  21523. mediaSource
  21524. } = this;
  21525. if (!media) {
  21526. return null;
  21527. }
  21528. const tracks = {};
  21529. if (this.operationQueue) {
  21530. const updating = this.isUpdating();
  21531. if (!updating) {
  21532. this.operationQueue.removeBlockers();
  21533. }
  21534. const queued = this.isQueued();
  21535. if (updating || queued) {
  21536. this.warn(`Transfering MediaSource with${queued ? " operations in queue" : ""}${updating ? " updating SourceBuffer(s)" : ""} ${this.operationQueue}`);
  21537. }
  21538. this.operationQueue.destroy();
  21539. }
  21540. const transferData = this.transferData;
  21541. if (!this.sourceBufferCount && transferData && transferData.mediaSource === mediaSource) {
  21542. _extends(tracks, transferData.tracks);
  21543. } else {
  21544. this.sourceBuffers.forEach((tuple) => {
  21545. const [type] = tuple;
  21546. if (type) {
  21547. tracks[type] = _extends({}, this.tracks[type]);
  21548. this.removeBuffer(type);
  21549. }
  21550. tuple[0] = tuple[1] = null;
  21551. });
  21552. }
  21553. return {
  21554. media,
  21555. mediaSource,
  21556. tracks
  21557. };
  21558. }
  21559. initTracks() {
  21560. const tracks = {};
  21561. this.sourceBuffers = [[null, null], [null, null]];
  21562. this.tracks = tracks;
  21563. this.resetQueue();
  21564. this.resetAppendErrors();
  21565. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  21566. this.lastVideoAppendEnd = 0;
  21567. }
  21568. onManifestLoading() {
  21569. this.bufferCodecEventsTotal = 0;
  21570. this.details = null;
  21571. }
  21572. onManifestParsed(event, data) {
  21573. var _this$transferData;
  21574. let codecEvents = 2;
  21575. if (data.audio && !data.video || !data.altAudio) {
  21576. codecEvents = 1;
  21577. }
  21578. this.bufferCodecEventsTotal = codecEvents;
  21579. this.log(`${codecEvents} bufferCodec event(s) expected.`);
  21580. if ((_this$transferData = this.transferData) != null && _this$transferData.mediaSource && this.sourceBufferCount && codecEvents) {
  21581. this.bufferCreated();
  21582. }
  21583. }
  21584. onMediaAttaching(event, data) {
  21585. const media = this.media = data.media;
  21586. const MediaSource = getMediaSource(this.appendSource);
  21587. this.transferData = this.overrides = void 0;
  21588. if (media && MediaSource) {
  21589. const transferringMedia = !!data.mediaSource;
  21590. if (transferringMedia || data.overrides) {
  21591. this.transferData = data;
  21592. this.overrides = data.overrides;
  21593. }
  21594. const ms2 = this.mediaSource = data.mediaSource || new MediaSource();
  21595. this.assignMediaSource(ms2);
  21596. if (transferringMedia) {
  21597. this._objectUrl = media.src;
  21598. this.attachTransferred();
  21599. } else {
  21600. const objectUrl = this._objectUrl = self.URL.createObjectURL(ms2);
  21601. if (this.appendSource) {
  21602. try {
  21603. media.removeAttribute("src");
  21604. const MMS = self.ManagedMediaSource;
  21605. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms2 instanceof MMS;
  21606. removeSourceChildren(media);
  21607. addSource(media, objectUrl);
  21608. media.load();
  21609. } catch (error2) {
  21610. media.src = objectUrl;
  21611. }
  21612. } else {
  21613. media.src = objectUrl;
  21614. }
  21615. }
  21616. media.addEventListener("emptied", this._onMediaEmptied);
  21617. }
  21618. }
  21619. assignMediaSource(ms2) {
  21620. var _this$transferData2, _ms$constructor;
  21621. 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}`);
  21622. ms2.addEventListener("sourceopen", this._onMediaSourceOpen);
  21623. ms2.addEventListener("sourceended", this._onMediaSourceEnded);
  21624. ms2.addEventListener("sourceclose", this._onMediaSourceClose);
  21625. if (this.appendSource) {
  21626. ms2.addEventListener("startstreaming", this._onStartStreaming);
  21627. ms2.addEventListener("endstreaming", this._onEndStreaming);
  21628. }
  21629. }
  21630. attachTransferred() {
  21631. const media = this.media;
  21632. const data = this.transferData;
  21633. if (!data || !media) {
  21634. return;
  21635. }
  21636. const requiredTracks = this.tracks;
  21637. const transferredTracks = data.tracks;
  21638. const trackNames = transferredTracks ? Object.keys(transferredTracks) : null;
  21639. const trackCount = trackNames ? trackNames.length : 0;
  21640. const mediaSourceOpenCallback = () => {
  21641. if (this.media && this.mediaSourceOpenOrEnded) {
  21642. this._onMediaSourceOpen();
  21643. }
  21644. };
  21645. if (transferredTracks && trackNames && trackCount) {
  21646. if (!this.tracksReady) {
  21647. this.hls.config.startFragPrefetch = true;
  21648. this.log(`attachTransferred: waiting for SourceBuffer track info`);
  21649. return;
  21650. }
  21651. this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
  21652. required tracks: ${stringify(requiredTracks, (key, value2) => key === "initSegment" ? void 0 : value2)};
  21653. transfer tracks: ${stringify(transferredTracks, (key, value2) => key === "initSegment" ? void 0 : value2)}}`);
  21654. if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {
  21655. data.mediaSource = null;
  21656. data.tracks = void 0;
  21657. const currentTime = media.currentTime;
  21658. const details = this.details;
  21659. const startTime = Math.max(currentTime, (details == null ? void 0 : details.fragments[0].start) || 0);
  21660. if (startTime - currentTime > 1) {
  21661. this.log(`attachTransferred: waiting for playback to reach new tracks start time ${currentTime} -> ${startTime}`);
  21662. return;
  21663. }
  21664. this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(transferredTracks)}"->"${Object.keys(requiredTracks)}") start time: ${startTime} currentTime: ${currentTime}`);
  21665. this.onMediaDetaching(Events.MEDIA_DETACHING, {});
  21666. this.onMediaAttaching(Events.MEDIA_ATTACHING, data);
  21667. media.currentTime = startTime;
  21668. return;
  21669. }
  21670. this.transferData = void 0;
  21671. trackNames.forEach((trackName) => {
  21672. const type = trackName;
  21673. const track = transferredTracks[type];
  21674. if (track) {
  21675. const sb = track.buffer;
  21676. if (sb) {
  21677. const fragmentTracker = this.fragmentTracker;
  21678. const playlistType = track.id;
  21679. if (fragmentTracker.hasFragments(playlistType) || fragmentTracker.hasParts(playlistType)) {
  21680. const bufferedTimeRanges = BufferHelper.getBuffered(sb);
  21681. fragmentTracker.detectEvictedFragments(type, bufferedTimeRanges, playlistType, null, true);
  21682. }
  21683. const sbIndex = sourceBufferNameToIndex(type);
  21684. const sbTuple = [type, sb];
  21685. this.sourceBuffers[sbIndex] = sbTuple;
  21686. if (sb.updating && this.operationQueue) {
  21687. this.operationQueue.prependBlocker(type);
  21688. }
  21689. this.trackSourceBuffer(type, track);
  21690. }
  21691. }
  21692. });
  21693. mediaSourceOpenCallback();
  21694. this.bufferCreated();
  21695. } else {
  21696. this.log(`attachTransferred: MediaSource w/o SourceBuffers`);
  21697. mediaSourceOpenCallback();
  21698. }
  21699. }
  21700. get mediaSourceOpenOrEnded() {
  21701. var _this$mediaSource2;
  21702. const readyState = (_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState;
  21703. return readyState === "open" || readyState === "ended";
  21704. }
  21705. onMediaDetaching(event, data) {
  21706. const transferringMedia = !!data.transferMedia;
  21707. this.transferData = this.overrides = void 0;
  21708. const {
  21709. media,
  21710. mediaSource,
  21711. _objectUrl
  21712. } = this;
  21713. if (mediaSource) {
  21714. this.log(`media source ${transferringMedia ? "transferring" : "detaching"}`);
  21715. if (transferringMedia) {
  21716. this.sourceBuffers.forEach(([type]) => {
  21717. if (type) {
  21718. this.removeBuffer(type);
  21719. }
  21720. });
  21721. this.resetQueue();
  21722. } else {
  21723. if (this.mediaSourceOpenOrEnded) {
  21724. const open = mediaSource.readyState === "open";
  21725. try {
  21726. const sourceBuffers = mediaSource.sourceBuffers;
  21727. for (let i2 = sourceBuffers.length; i2--; ) {
  21728. if (open) {
  21729. sourceBuffers[i2].abort();
  21730. }
  21731. mediaSource.removeSourceBuffer(sourceBuffers[i2]);
  21732. }
  21733. if (open) {
  21734. mediaSource.endOfStream();
  21735. }
  21736. } catch (err) {
  21737. this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);
  21738. }
  21739. }
  21740. if (this.sourceBufferCount) {
  21741. this.onBufferReset();
  21742. }
  21743. }
  21744. mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
  21745. mediaSource.removeEventListener("sourceended", this._onMediaSourceEnded);
  21746. mediaSource.removeEventListener("sourceclose", this._onMediaSourceClose);
  21747. if (this.appendSource) {
  21748. mediaSource.removeEventListener("startstreaming", this._onStartStreaming);
  21749. mediaSource.removeEventListener("endstreaming", this._onEndStreaming);
  21750. }
  21751. this.mediaSource = null;
  21752. this._objectUrl = null;
  21753. }
  21754. if (media) {
  21755. media.removeEventListener("emptied", this._onMediaEmptied);
  21756. if (!transferringMedia) {
  21757. if (_objectUrl) {
  21758. self.URL.revokeObjectURL(_objectUrl);
  21759. }
  21760. if (this.mediaSrc === _objectUrl) {
  21761. media.removeAttribute("src");
  21762. if (this.appendSource) {
  21763. removeSourceChildren(media);
  21764. }
  21765. media.load();
  21766. } else {
  21767. this.warn("media|source.src was changed by a third party - skip cleanup");
  21768. }
  21769. }
  21770. this.media = null;
  21771. }
  21772. this.hls.trigger(Events.MEDIA_DETACHED, data);
  21773. }
  21774. onBufferReset() {
  21775. this.sourceBuffers.forEach(([type]) => {
  21776. if (type) {
  21777. this.resetBuffer(type);
  21778. }
  21779. });
  21780. this.initTracks();
  21781. }
  21782. resetBuffer(type) {
  21783. var _this$tracks$type;
  21784. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  21785. this.removeBuffer(type);
  21786. if (sb) {
  21787. try {
  21788. var _this$mediaSource3;
  21789. if ((_this$mediaSource3 = this.mediaSource) != null && _this$mediaSource3.sourceBuffers.length) {
  21790. this.mediaSource.removeSourceBuffer(sb);
  21791. }
  21792. } catch (err) {
  21793. this.warn(`onBufferReset ${type}`, err);
  21794. }
  21795. }
  21796. delete this.tracks[type];
  21797. }
  21798. removeBuffer(type) {
  21799. this.removeBufferListeners(type);
  21800. this.sourceBuffers[sourceBufferNameToIndex(type)] = [null, null];
  21801. const track = this.tracks[type];
  21802. if (track) {
  21803. track.buffer = void 0;
  21804. }
  21805. }
  21806. resetQueue() {
  21807. if (this.operationQueue) {
  21808. this.operationQueue.destroy();
  21809. }
  21810. this.operationQueue = new BufferOperationQueue(this.tracks);
  21811. }
  21812. onBufferCodecs(event, data) {
  21813. const tracks = this.tracks;
  21814. const trackNames = Object.keys(data);
  21815. this.log(`BUFFER_CODECS: "${trackNames}" (current SB count ${this.sourceBufferCount})`);
  21816. const unmuxedToMuxed = "audiovideo" in data && (tracks.audio || tracks.video) || tracks.audiovideo && ("audio" in data || "video" in data);
  21817. const muxedToUnmuxed = !unmuxedToMuxed && this.sourceBufferCount && this.media && trackNames.some((sbName) => !tracks[sbName]);
  21818. if (unmuxedToMuxed || muxedToUnmuxed) {
  21819. this.warn(`Unsupported transition between "${Object.keys(tracks)}" and "${trackNames}" SourceBuffers`);
  21820. return;
  21821. }
  21822. trackNames.forEach((trackName) => {
  21823. var _this$transferData3, _this$transferData3$t, _trackCodec;
  21824. const parsedTrack = data[trackName];
  21825. const {
  21826. id,
  21827. codec,
  21828. levelCodec,
  21829. container,
  21830. metadata,
  21831. supplemental
  21832. } = parsedTrack;
  21833. let track = tracks[trackName];
  21834. const transferredTrack = (_this$transferData3 = this.transferData) == null ? void 0 : (_this$transferData3$t = _this$transferData3.tracks) == null ? void 0 : _this$transferData3$t[trackName];
  21835. const sbTrack = transferredTrack != null && transferredTrack.buffer ? transferredTrack : track;
  21836. const sbCodec = (sbTrack == null ? void 0 : sbTrack.pendingCodec) || (sbTrack == null ? void 0 : sbTrack.codec);
  21837. const trackLevelCodec = sbTrack == null ? void 0 : sbTrack.levelCodec;
  21838. if (!track) {
  21839. track = tracks[trackName] = {
  21840. buffer: void 0,
  21841. listeners: [],
  21842. codec,
  21843. supplemental,
  21844. container,
  21845. levelCodec,
  21846. metadata,
  21847. id
  21848. };
  21849. }
  21850. const currentCodecFull = pickMostCompleteCodecName(sbCodec, trackLevelCodec);
  21851. const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
  21852. let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  21853. const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
  21854. if (trackCodec && currentCodecFull && currentCodec !== nextCodec) {
  21855. if (trackName.slice(0, 5) === "audio") {
  21856. trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
  21857. }
  21858. this.log(`switching codec ${sbCodec} to ${trackCodec}`);
  21859. if (trackCodec !== (track.pendingCodec || track.codec)) {
  21860. track.pendingCodec = trackCodec;
  21861. }
  21862. track.container = container;
  21863. this.appendChangeType(trackName, container, trackCodec);
  21864. }
  21865. });
  21866. if (this.tracksReady || this.sourceBufferCount) {
  21867. data.tracks = this.sourceBufferTracks;
  21868. }
  21869. if (this.sourceBufferCount) {
  21870. return;
  21871. }
  21872. if (this.mediaSourceOpenOrEnded) {
  21873. this.checkPendingTracks();
  21874. }
  21875. }
  21876. get sourceBufferTracks() {
  21877. return Object.keys(this.tracks).reduce((baseTracks, type) => {
  21878. const track = this.tracks[type];
  21879. baseTracks[type] = {
  21880. id: track.id,
  21881. container: track.container,
  21882. codec: track.codec,
  21883. levelCodec: track.levelCodec
  21884. };
  21885. return baseTracks;
  21886. }, {});
  21887. }
  21888. appendChangeType(type, container, codec) {
  21889. const mimeType = `${container};codecs=${codec}`;
  21890. const operation = {
  21891. label: `change-type=${mimeType}`,
  21892. execute: () => {
  21893. const track = this.tracks[type];
  21894. if (track) {
  21895. const sb = track.buffer;
  21896. if (sb != null && sb.changeType) {
  21897. this.log(`changing ${type} sourceBuffer type to ${mimeType}`);
  21898. sb.changeType(mimeType);
  21899. track.codec = codec;
  21900. track.container = container;
  21901. }
  21902. }
  21903. this.shiftAndExecuteNext(type);
  21904. },
  21905. onStart: () => {
  21906. },
  21907. onComplete: () => {
  21908. },
  21909. onError: (error2) => {
  21910. this.warn(`Failed to change ${type} SourceBuffer type`, error2);
  21911. }
  21912. };
  21913. this.append(operation, type, this.isPending(this.tracks[type]));
  21914. }
  21915. blockAudio(partOrFrag) {
  21916. var _this$fragmentTracker;
  21917. const pStart = partOrFrag.start;
  21918. const pTime = pStart + partOrFrag.duration * 0.05;
  21919. const atGap = ((_this$fragmentTracker = this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker.gap) === true;
  21920. if (atGap) {
  21921. return;
  21922. }
  21923. const op = {
  21924. label: "block-audio",
  21925. execute: () => {
  21926. var _this$fragmentTracker2;
  21927. const videoTrack = this.tracks.video;
  21928. 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) {
  21929. this.blockedAudioAppend = null;
  21930. this.shiftAndExecuteNext("audio");
  21931. }
  21932. },
  21933. onStart: () => {
  21934. },
  21935. onComplete: () => {
  21936. },
  21937. onError: (error2) => {
  21938. this.warn("Error executing block-audio operation", error2);
  21939. }
  21940. };
  21941. this.blockedAudioAppend = {
  21942. op,
  21943. frag: partOrFrag
  21944. };
  21945. this.append(op, "audio", true);
  21946. }
  21947. unblockAudio() {
  21948. const {
  21949. blockedAudioAppend,
  21950. operationQueue
  21951. } = this;
  21952. if (blockedAudioAppend && operationQueue) {
  21953. this.blockedAudioAppend = null;
  21954. operationQueue.unblockAudio(blockedAudioAppend.op);
  21955. }
  21956. }
  21957. onBufferAppending(event, eventData) {
  21958. const {
  21959. tracks
  21960. } = this;
  21961. const {
  21962. data,
  21963. type,
  21964. parent,
  21965. frag,
  21966. part,
  21967. chunkMeta,
  21968. offset
  21969. } = eventData;
  21970. const chunkStats = chunkMeta.buffering[type];
  21971. const {
  21972. sn,
  21973. cc
  21974. } = frag;
  21975. const bufferAppendingStart = self.performance.now();
  21976. chunkStats.start = bufferAppendingStart;
  21977. const fragBuffering = frag.stats.buffering;
  21978. const partBuffering = part ? part.stats.buffering : null;
  21979. if (fragBuffering.start === 0) {
  21980. fragBuffering.start = bufferAppendingStart;
  21981. }
  21982. if (partBuffering && partBuffering.start === 0) {
  21983. partBuffering.start = bufferAppendingStart;
  21984. }
  21985. const audioTrack = tracks.audio;
  21986. let checkTimestampOffset = false;
  21987. if (type === "audio" && (audioTrack == null ? void 0 : audioTrack.container) === "audio/mpeg") {
  21988. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  21989. this.lastMpegAudioChunk = chunkMeta;
  21990. }
  21991. const videoTrack = tracks.video;
  21992. const videoSb = videoTrack == null ? void 0 : videoTrack.buffer;
  21993. if (videoSb && sn !== "initSegment") {
  21994. const partOrFrag = part || frag;
  21995. const blockedAudioAppend = this.blockedAudioAppend;
  21996. if (type === "audio" && parent !== "main" && !this.blockedAudioAppend) {
  21997. const pStart = partOrFrag.start;
  21998. const pTime = pStart + partOrFrag.duration * 0.05;
  21999. const vbuffered = videoSb.buffered;
  22000. const vappending = this.currentOp("video");
  22001. if (!vbuffered.length && !vappending) {
  22002. this.blockAudio(partOrFrag);
  22003. } else if (!vappending && !BufferHelper.isBuffered(videoSb, pTime) && this.lastVideoAppendEnd < pTime) {
  22004. this.blockAudio(partOrFrag);
  22005. }
  22006. } else if (type === "video") {
  22007. const videoAppendEnd = partOrFrag.end;
  22008. if (blockedAudioAppend) {
  22009. const audioStart = blockedAudioAppend.frag.start;
  22010. if (videoAppendEnd > audioStart || videoAppendEnd < this.lastVideoAppendEnd || BufferHelper.isBuffered(videoSb, audioStart)) {
  22011. this.unblockAudio();
  22012. }
  22013. }
  22014. this.lastVideoAppendEnd = videoAppendEnd;
  22015. }
  22016. }
  22017. const fragStart = (part || frag).start;
  22018. const operation = {
  22019. label: `append-${type}`,
  22020. execute: () => {
  22021. var _this$tracks$type2;
  22022. chunkStats.executeStart = self.performance.now();
  22023. const sb = (_this$tracks$type2 = this.tracks[type]) == null ? void 0 : _this$tracks$type2.buffer;
  22024. if (sb) {
  22025. if (checkTimestampOffset) {
  22026. this.updateTimestampOffset(sb, fragStart, 0.1, type, sn, cc);
  22027. } else if (offset !== void 0 && isFiniteNumber(offset)) {
  22028. this.updateTimestampOffset(sb, offset, 1e-6, type, sn, cc);
  22029. }
  22030. }
  22031. this.appendExecutor(data, type);
  22032. },
  22033. onStart: () => {
  22034. },
  22035. onComplete: () => {
  22036. const end = self.performance.now();
  22037. chunkStats.executeEnd = chunkStats.end = end;
  22038. if (fragBuffering.first === 0) {
  22039. fragBuffering.first = end;
  22040. }
  22041. if (partBuffering && partBuffering.first === 0) {
  22042. partBuffering.first = end;
  22043. }
  22044. const timeRanges = {};
  22045. this.sourceBuffers.forEach(([type2, sb]) => {
  22046. if (type2) {
  22047. timeRanges[type2] = BufferHelper.getBuffered(sb);
  22048. }
  22049. });
  22050. this.appendErrors[type] = 0;
  22051. if (type === "audio" || type === "video") {
  22052. this.appendErrors.audiovideo = 0;
  22053. } else {
  22054. this.appendErrors.audio = 0;
  22055. this.appendErrors.video = 0;
  22056. }
  22057. this.hls.trigger(Events.BUFFER_APPENDED, {
  22058. type,
  22059. frag,
  22060. part,
  22061. chunkMeta,
  22062. parent: frag.type,
  22063. timeRanges
  22064. });
  22065. },
  22066. onError: (error2) => {
  22067. var _this$media;
  22068. const event2 = {
  22069. type: ErrorTypes.MEDIA_ERROR,
  22070. parent: frag.type,
  22071. details: ErrorDetails.BUFFER_APPEND_ERROR,
  22072. sourceBufferName: type,
  22073. frag,
  22074. part,
  22075. chunkMeta,
  22076. error: error2,
  22077. err: error2,
  22078. fatal: false
  22079. };
  22080. const mediaError = (_this$media = this.media) == null ? void 0 : _this$media.error;
  22081. if (error2.code === DOMException.QUOTA_EXCEEDED_ERR || error2.name == "QuotaExceededError" || `quota` in error2) {
  22082. event2.details = ErrorDetails.BUFFER_FULL_ERROR;
  22083. } else if (error2.code === DOMException.INVALID_STATE_ERR && this.mediaSourceOpenOrEnded && !mediaError) {
  22084. event2.errorAction = createDoNothingErrorAction(true);
  22085. } else if (error2.name === TRACK_REMOVED_ERROR_NAME && this.sourceBufferCount === 0) {
  22086. event2.errorAction = createDoNothingErrorAction(true);
  22087. } else {
  22088. const appendErrorCount = ++this.appendErrors[type];
  22089. this.warn(`Failed ${appendErrorCount}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer (${mediaError ? mediaError : "no media error"})`);
  22090. if (appendErrorCount >= this.hls.config.appendErrorMaxRetry || !!mediaError) {
  22091. event2.fatal = true;
  22092. }
  22093. }
  22094. this.hls.trigger(Events.ERROR, event2);
  22095. }
  22096. };
  22097. this.append(operation, type, this.isPending(this.tracks[type]));
  22098. }
  22099. getFlushOp(type, start, end) {
  22100. this.log(`queuing "${type}" remove ${start}-${end}`);
  22101. return {
  22102. label: "remove",
  22103. execute: () => {
  22104. this.removeExecutor(type, start, end);
  22105. },
  22106. onStart: () => {
  22107. },
  22108. onComplete: () => {
  22109. this.hls.trigger(Events.BUFFER_FLUSHED, {
  22110. type
  22111. });
  22112. },
  22113. onError: (error2) => {
  22114. this.warn(`Failed to remove ${start}-${end} from "${type}" SourceBuffer`, error2);
  22115. }
  22116. };
  22117. }
  22118. onBufferFlushing(event, data) {
  22119. const {
  22120. type,
  22121. startOffset,
  22122. endOffset
  22123. } = data;
  22124. if (type) {
  22125. this.append(this.getFlushOp(type, startOffset, endOffset), type);
  22126. } else {
  22127. this.sourceBuffers.forEach(([type2]) => {
  22128. if (type2) {
  22129. this.append(this.getFlushOp(type2, startOffset, endOffset), type2);
  22130. }
  22131. });
  22132. }
  22133. }
  22134. onFragParsed(event, data) {
  22135. const {
  22136. frag,
  22137. part
  22138. } = data;
  22139. const buffersAppendedTo = [];
  22140. const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  22141. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  22142. buffersAppendedTo.push("audiovideo");
  22143. } else {
  22144. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  22145. buffersAppendedTo.push("audio");
  22146. }
  22147. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  22148. buffersAppendedTo.push("video");
  22149. }
  22150. }
  22151. const onUnblocked = () => {
  22152. const now2 = self.performance.now();
  22153. frag.stats.buffering.end = now2;
  22154. if (part) {
  22155. part.stats.buffering.end = now2;
  22156. }
  22157. const stats = part ? part.stats : frag.stats;
  22158. this.hls.trigger(Events.FRAG_BUFFERED, {
  22159. frag,
  22160. part,
  22161. stats,
  22162. id: frag.type
  22163. });
  22164. };
  22165. if (buffersAppendedTo.length === 0) {
  22166. this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);
  22167. }
  22168. this.blockBuffers(onUnblocked, buffersAppendedTo).catch((error2) => {
  22169. this.warn(`Fragment buffered callback ${error2}`);
  22170. this.stepOperationQueue(this.sourceBufferTypes);
  22171. });
  22172. }
  22173. onFragChanged(event, data) {
  22174. this.trimBuffers();
  22175. }
  22176. get bufferedToEnd() {
  22177. return this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  22178. var _this$tracks$type3, _this$tracks$type4;
  22179. 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));
  22180. });
  22181. }
  22182. // on BUFFER_EOS mark matching sourcebuffer(s) as "ending" and "ended" and queue endOfStream after remaining operations(s)
  22183. // an undefined data.type will mark all buffers as EOS.
  22184. onBufferEos(event, data) {
  22185. var _this$overrides;
  22186. this.sourceBuffers.forEach(([type]) => {
  22187. if (type) {
  22188. const track = this.tracks[type];
  22189. if (!data.type || data.type === type) {
  22190. track.ending = true;
  22191. if (!track.ended) {
  22192. track.ended = true;
  22193. this.log(`${type} buffer reached EOS`);
  22194. }
  22195. }
  22196. }
  22197. });
  22198. const allowEndOfStream = ((_this$overrides = this.overrides) == null ? void 0 : _this$overrides.endOfStream) !== false;
  22199. const allTracksEnding = this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  22200. var _this$tracks$type5;
  22201. return type && !((_this$tracks$type5 = this.tracks[type]) != null && _this$tracks$type5.ended);
  22202. });
  22203. if (allTracksEnding) {
  22204. if (allowEndOfStream) {
  22205. this.log(`Queueing EOS`);
  22206. this.blockUntilOpen(() => {
  22207. this.tracksEnded();
  22208. const {
  22209. mediaSource
  22210. } = this;
  22211. if (!mediaSource || mediaSource.readyState !== "open") {
  22212. if (mediaSource) {
  22213. this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);
  22214. }
  22215. return;
  22216. }
  22217. this.log(`Calling mediaSource.endOfStream()`);
  22218. mediaSource.endOfStream();
  22219. this.hls.trigger(Events.BUFFERED_TO_END, void 0);
  22220. });
  22221. } else {
  22222. this.tracksEnded();
  22223. this.hls.trigger(Events.BUFFERED_TO_END, void 0);
  22224. }
  22225. }
  22226. }
  22227. tracksEnded() {
  22228. this.sourceBuffers.forEach(([type]) => {
  22229. if (type !== null) {
  22230. const track = this.tracks[type];
  22231. if (track) {
  22232. track.ending = false;
  22233. }
  22234. }
  22235. });
  22236. }
  22237. onLevelUpdated(event, {
  22238. details
  22239. }) {
  22240. if (!details.fragments.length) {
  22241. return;
  22242. }
  22243. this.details = details;
  22244. this.updateDuration();
  22245. }
  22246. updateDuration() {
  22247. this.blockUntilOpen(() => {
  22248. const durationAndRange = this.getDurationAndRange();
  22249. if (!durationAndRange) {
  22250. return;
  22251. }
  22252. this.updateMediaSource(durationAndRange);
  22253. });
  22254. }
  22255. onError(event, data) {
  22256. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && data.frag) {
  22257. var _data$errorAction;
  22258. const nextAutoLevel = (_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.nextAutoLevel;
  22259. if (isFiniteNumber(nextAutoLevel) && nextAutoLevel !== data.frag.level) {
  22260. this.resetAppendErrors();
  22261. }
  22262. }
  22263. }
  22264. resetAppendErrors() {
  22265. this.appendErrors = {
  22266. audio: 0,
  22267. video: 0,
  22268. audiovideo: 0
  22269. };
  22270. }
  22271. trimBuffers() {
  22272. const {
  22273. hls,
  22274. details,
  22275. media
  22276. } = this;
  22277. if (!media || details === null) {
  22278. return;
  22279. }
  22280. if (!this.sourceBufferCount) {
  22281. return;
  22282. }
  22283. const config2 = hls.config;
  22284. const currentTime = media.currentTime;
  22285. const targetDuration = details.levelTargetDuration;
  22286. const backBufferLength = details.live && config2.liveBackBufferLength !== null ? config2.liveBackBufferLength : config2.backBufferLength;
  22287. if (isFiniteNumber(backBufferLength) && backBufferLength >= 0) {
  22288. const maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  22289. const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  22290. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  22291. }
  22292. if (isFiniteNumber(config2.frontBufferFlushThreshold) && config2.frontBufferFlushThreshold > 0) {
  22293. const frontBufferLength = Math.max(config2.maxBufferLength, config2.frontBufferFlushThreshold);
  22294. const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  22295. const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  22296. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  22297. }
  22298. }
  22299. flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  22300. this.sourceBuffers.forEach(([type, sb]) => {
  22301. if (sb) {
  22302. const buffered = BufferHelper.getBuffered(sb);
  22303. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  22304. var _this$details;
  22305. this.hls.trigger(Events.BACK_BUFFER_REACHED, {
  22306. bufferEnd: targetBackBufferPosition
  22307. });
  22308. const track = this.tracks[type];
  22309. if ((_this$details = this.details) != null && _this$details.live) {
  22310. this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  22311. bufferEnd: targetBackBufferPosition
  22312. });
  22313. } else if (track != null && track.ended) {
  22314. this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`);
  22315. return;
  22316. }
  22317. this.hls.trigger(Events.BUFFER_FLUSHING, {
  22318. startOffset: 0,
  22319. endOffset: targetBackBufferPosition,
  22320. type
  22321. });
  22322. }
  22323. }
  22324. });
  22325. }
  22326. flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  22327. this.sourceBuffers.forEach(([type, sb]) => {
  22328. if (sb) {
  22329. const buffered = BufferHelper.getBuffered(sb);
  22330. const numBufferedRanges = buffered.length;
  22331. if (numBufferedRanges < 2) {
  22332. return;
  22333. }
  22334. const bufferStart = buffered.start(numBufferedRanges - 1);
  22335. const bufferEnd = buffered.end(numBufferedRanges - 1);
  22336. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  22337. return;
  22338. }
  22339. this.hls.trigger(Events.BUFFER_FLUSHING, {
  22340. startOffset: bufferStart,
  22341. endOffset: Infinity,
  22342. type
  22343. });
  22344. }
  22345. });
  22346. }
  22347. /**
  22348. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  22349. * 'liveDurationInfinity` is set to `true`
  22350. * More details: https://github.com/video-dev/hls.js/issues/355
  22351. */
  22352. getDurationAndRange() {
  22353. var _this$overrides2;
  22354. const {
  22355. details,
  22356. mediaSource
  22357. } = this;
  22358. if (!details || !this.media || (mediaSource == null ? void 0 : mediaSource.readyState) !== "open") {
  22359. return null;
  22360. }
  22361. const playlistEnd = details.edge;
  22362. if (details.live && this.hls.config.liveDurationInfinity) {
  22363. const len = details.fragments.length;
  22364. if (len && details.live && !!mediaSource.setLiveSeekableRange) {
  22365. const start = Math.max(0, details.fragmentStart);
  22366. const end = Math.max(start, playlistEnd);
  22367. return {
  22368. duration: Infinity,
  22369. start,
  22370. end
  22371. };
  22372. }
  22373. return {
  22374. duration: Infinity
  22375. };
  22376. }
  22377. const overrideDuration = (_this$overrides2 = this.overrides) == null ? void 0 : _this$overrides2.duration;
  22378. if (overrideDuration) {
  22379. if (!isFiniteNumber(overrideDuration)) {
  22380. return null;
  22381. }
  22382. return {
  22383. duration: overrideDuration
  22384. };
  22385. }
  22386. const mediaDuration = this.media.duration;
  22387. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  22388. if (playlistEnd > msDuration && playlistEnd > mediaDuration || !isFiniteNumber(mediaDuration)) {
  22389. return {
  22390. duration: playlistEnd
  22391. };
  22392. }
  22393. return null;
  22394. }
  22395. updateMediaSource({
  22396. duration,
  22397. start,
  22398. end
  22399. }) {
  22400. const mediaSource = this.mediaSource;
  22401. if (!this.media || !mediaSource || mediaSource.readyState !== "open") {
  22402. return;
  22403. }
  22404. if (mediaSource.duration !== duration) {
  22405. if (isFiniteNumber(duration)) {
  22406. this.log(`Updating MediaSource duration to ${duration.toFixed(3)}`);
  22407. }
  22408. mediaSource.duration = duration;
  22409. }
  22410. if (start !== void 0 && end !== void 0) {
  22411. this.log(`MediaSource duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`);
  22412. mediaSource.setLiveSeekableRange(start, end);
  22413. }
  22414. }
  22415. get tracksReady() {
  22416. const pendingTrackCount = this.pendingTrackCount;
  22417. return pendingTrackCount > 0 && (pendingTrackCount >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  22418. }
  22419. checkPendingTracks() {
  22420. const {
  22421. bufferCodecEventsTotal,
  22422. pendingTrackCount,
  22423. tracks
  22424. } = this;
  22425. this.log(`checkPendingTracks (pending: ${pendingTrackCount} codec events expected: ${bufferCodecEventsTotal}) ${stringify(tracks)}`);
  22426. if (this.tracksReady) {
  22427. var _this$transferData4;
  22428. const transferredTracks = (_this$transferData4 = this.transferData) == null ? void 0 : _this$transferData4.tracks;
  22429. if (transferredTracks && Object.keys(transferredTracks).length) {
  22430. this.attachTransferred();
  22431. } else {
  22432. this.createSourceBuffers();
  22433. }
  22434. }
  22435. }
  22436. bufferCreated() {
  22437. if (this.sourceBufferCount) {
  22438. const tracks = {};
  22439. this.sourceBuffers.forEach(([type, buffer]) => {
  22440. if (type) {
  22441. const track = this.tracks[type];
  22442. tracks[type] = {
  22443. buffer,
  22444. container: track.container,
  22445. codec: track.codec,
  22446. supplemental: track.supplemental,
  22447. levelCodec: track.levelCodec,
  22448. id: track.id,
  22449. metadata: track.metadata
  22450. };
  22451. }
  22452. });
  22453. this.hls.trigger(Events.BUFFER_CREATED, {
  22454. tracks
  22455. });
  22456. this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`);
  22457. this.sourceBuffers.forEach(([type]) => {
  22458. this.executeNext(type);
  22459. });
  22460. } else {
  22461. const error2 = new Error("could not create source buffer for media codec(s)");
  22462. this.hls.trigger(Events.ERROR, {
  22463. type: ErrorTypes.MEDIA_ERROR,
  22464. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  22465. fatal: true,
  22466. error: error2,
  22467. reason: error2.message
  22468. });
  22469. }
  22470. }
  22471. createSourceBuffers() {
  22472. const {
  22473. tracks,
  22474. sourceBuffers,
  22475. mediaSource
  22476. } = this;
  22477. if (!mediaSource) {
  22478. throw new Error("createSourceBuffers called when mediaSource was null");
  22479. }
  22480. for (const trackName in tracks) {
  22481. const type = trackName;
  22482. const track = tracks[type];
  22483. if (this.isPending(track)) {
  22484. const codec = this.getTrackCodec(track, type);
  22485. const mimeType = `${track.container};codecs=${codec}`;
  22486. track.codec = codec;
  22487. this.log(`creating sourceBuffer(${mimeType})${this.currentOp(type) ? " Queued" : ""} ${stringify(track)}`);
  22488. try {
  22489. const sb = mediaSource.addSourceBuffer(mimeType);
  22490. const sbIndex = sourceBufferNameToIndex(type);
  22491. const sbTuple = [type, sb];
  22492. sourceBuffers[sbIndex] = sbTuple;
  22493. track.buffer = sb;
  22494. } catch (error2) {
  22495. var _this$operationQueue;
  22496. this.error(`error while trying to add sourceBuffer: ${error2.message}`);
  22497. this.shiftAndExecuteNext(type);
  22498. (_this$operationQueue = this.operationQueue) == null ? void 0 : _this$operationQueue.removeBlockers();
  22499. delete this.tracks[type];
  22500. this.hls.trigger(Events.ERROR, {
  22501. type: ErrorTypes.MEDIA_ERROR,
  22502. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  22503. fatal: false,
  22504. error: error2,
  22505. sourceBufferName: type,
  22506. mimeType,
  22507. parent: track.id
  22508. });
  22509. return;
  22510. }
  22511. this.trackSourceBuffer(type, track);
  22512. }
  22513. }
  22514. this.bufferCreated();
  22515. }
  22516. getTrackCodec(track, trackName) {
  22517. const supplementalCodec = track.supplemental;
  22518. let trackCodec = track.codec;
  22519. if (supplementalCodec && (trackName === "video" || trackName === "audiovideo") && areCodecsMediaSourceSupported(supplementalCodec, "video")) {
  22520. trackCodec = replaceVideoCodec(trackCodec, supplementalCodec);
  22521. }
  22522. const codec = pickMostCompleteCodecName(trackCodec, track.levelCodec);
  22523. if (codec) {
  22524. if (trackName.slice(0, 5) === "audio") {
  22525. return getCodecCompatibleName(codec, this.appendSource);
  22526. }
  22527. return codec;
  22528. }
  22529. return "";
  22530. }
  22531. trackSourceBuffer(type, track) {
  22532. const buffer = track.buffer;
  22533. if (!buffer) {
  22534. return;
  22535. }
  22536. const codec = this.getTrackCodec(track, type);
  22537. this.tracks[type] = {
  22538. buffer,
  22539. codec,
  22540. container: track.container,
  22541. levelCodec: track.levelCodec,
  22542. supplemental: track.supplemental,
  22543. metadata: track.metadata,
  22544. id: track.id,
  22545. listeners: []
  22546. };
  22547. this.removeBufferListeners(type);
  22548. this.addBufferListener(type, "updatestart", this.onSBUpdateStart);
  22549. this.addBufferListener(type, "updateend", this.onSBUpdateEnd);
  22550. this.addBufferListener(type, "error", this.onSBUpdateError);
  22551. if (this.appendSource) {
  22552. this.addBufferListener(type, "bufferedchange", (type2, event) => {
  22553. const removedRanges = event.removedRanges;
  22554. if (removedRanges != null && removedRanges.length) {
  22555. this.hls.trigger(Events.BUFFER_FLUSHED, {
  22556. type: type2
  22557. });
  22558. }
  22559. });
  22560. }
  22561. }
  22562. get mediaSrc() {
  22563. var _this$media2, _this$media2$querySel;
  22564. 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;
  22565. return media == null ? void 0 : media.src;
  22566. }
  22567. onSBUpdateStart(type) {
  22568. const operation = this.currentOp(type);
  22569. if (!operation) {
  22570. return;
  22571. }
  22572. operation.onStart();
  22573. }
  22574. onSBUpdateEnd(type) {
  22575. var _this$mediaSource4;
  22576. if (((_this$mediaSource4 = this.mediaSource) == null ? void 0 : _this$mediaSource4.readyState) === "closed") {
  22577. this.resetBuffer(type);
  22578. return;
  22579. }
  22580. const operation = this.currentOp(type);
  22581. if (!operation) {
  22582. return;
  22583. }
  22584. operation.onComplete();
  22585. this.shiftAndExecuteNext(type);
  22586. }
  22587. onSBUpdateError(type, event) {
  22588. var _this$mediaSource5;
  22589. const error2 = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource5 = this.mediaSource) == null ? void 0 : _this$mediaSource5.readyState}`);
  22590. this.error(`${error2}`, event);
  22591. this.hls.trigger(Events.ERROR, {
  22592. type: ErrorTypes.MEDIA_ERROR,
  22593. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  22594. sourceBufferName: type,
  22595. error: error2,
  22596. fatal: false
  22597. });
  22598. const operation = this.currentOp(type);
  22599. if (operation) {
  22600. operation.onError(error2);
  22601. }
  22602. }
  22603. updateTimestampOffset(sb, timestampOffset, tolerance, type, sn, cc) {
  22604. const delta = timestampOffset - sb.timestampOffset;
  22605. if (Math.abs(delta) >= tolerance) {
  22606. this.log(`Updating ${type} SourceBuffer timestampOffset to ${timestampOffset} (sn: ${sn} cc: ${cc})`);
  22607. sb.timestampOffset = timestampOffset;
  22608. }
  22609. }
  22610. // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually
  22611. removeExecutor(type, startOffset, endOffset) {
  22612. const {
  22613. media,
  22614. mediaSource
  22615. } = this;
  22616. const track = this.tracks[type];
  22617. const sb = track == null ? void 0 : track.buffer;
  22618. if (!media || !mediaSource || !sb) {
  22619. this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`);
  22620. this.shiftAndExecuteNext(type);
  22621. return;
  22622. }
  22623. const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  22624. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  22625. const removeStart = Math.max(0, startOffset);
  22626. const removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  22627. if (removeEnd > removeStart && (!track.ending || track.ended)) {
  22628. track.ended = false;
  22629. this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`);
  22630. sb.remove(removeStart, removeEnd);
  22631. } else {
  22632. this.shiftAndExecuteNext(type);
  22633. }
  22634. }
  22635. // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually
  22636. appendExecutor(data, type) {
  22637. const track = this.tracks[type];
  22638. const sb = track == null ? void 0 : track.buffer;
  22639. if (!sb) {
  22640. throw new HlsJsTrackRemovedError(`Attempting to append to the ${type} SourceBuffer, but it does not exist`);
  22641. }
  22642. track.ending = false;
  22643. track.ended = false;
  22644. sb.appendBuffer(data);
  22645. }
  22646. blockUntilOpen(callback) {
  22647. if (this.isUpdating() || this.isQueued()) {
  22648. this.blockBuffers(callback).catch((error2) => {
  22649. this.warn(`SourceBuffer blocked callback ${error2}`);
  22650. this.stepOperationQueue(this.sourceBufferTypes);
  22651. });
  22652. } else {
  22653. try {
  22654. callback();
  22655. } catch (error2) {
  22656. this.warn(`Callback run without blocking ${this.operationQueue} ${error2}`);
  22657. }
  22658. }
  22659. }
  22660. isUpdating() {
  22661. return this.sourceBuffers.some(([type, sb]) => type && sb.updating);
  22662. }
  22663. isQueued() {
  22664. return this.sourceBuffers.some(([type]) => type && !!this.currentOp(type));
  22665. }
  22666. isPending(track) {
  22667. return !!track && !track.buffer;
  22668. }
  22669. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  22670. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  22671. // upon completion, since we already do it here
  22672. blockBuffers(onUnblocked, bufferNames = this.sourceBufferTypes) {
  22673. if (!bufferNames.length) {
  22674. this.log("Blocking operation requested, but no SourceBuffers exist");
  22675. return Promise.resolve().then(onUnblocked);
  22676. }
  22677. const {
  22678. operationQueue
  22679. } = this;
  22680. const blockingOperations = bufferNames.map((type) => this.appendBlocker(type));
  22681. const audioBlocked = bufferNames.length > 1 && !!this.blockedAudioAppend;
  22682. if (audioBlocked) {
  22683. this.unblockAudio();
  22684. }
  22685. return Promise.all(blockingOperations).then((result) => {
  22686. if (operationQueue !== this.operationQueue) {
  22687. return;
  22688. }
  22689. onUnblocked();
  22690. this.stepOperationQueue(this.sourceBufferTypes);
  22691. });
  22692. }
  22693. stepOperationQueue(bufferNames) {
  22694. bufferNames.forEach((type) => {
  22695. var _this$tracks$type6;
  22696. const sb = (_this$tracks$type6 = this.tracks[type]) == null ? void 0 : _this$tracks$type6.buffer;
  22697. if (!sb || sb.updating) {
  22698. return;
  22699. }
  22700. this.shiftAndExecuteNext(type);
  22701. });
  22702. }
  22703. append(operation, type, pending) {
  22704. if (this.operationQueue) {
  22705. this.operationQueue.append(operation, type, pending);
  22706. }
  22707. }
  22708. appendBlocker(type) {
  22709. if (this.operationQueue) {
  22710. return this.operationQueue.appendBlocker(type);
  22711. }
  22712. }
  22713. currentOp(type) {
  22714. if (this.operationQueue) {
  22715. return this.operationQueue.current(type);
  22716. }
  22717. return null;
  22718. }
  22719. executeNext(type) {
  22720. if (type && this.operationQueue) {
  22721. this.operationQueue.executeNext(type);
  22722. }
  22723. }
  22724. shiftAndExecuteNext(type) {
  22725. if (this.operationQueue) {
  22726. this.operationQueue.shiftAndExecuteNext(type);
  22727. }
  22728. }
  22729. get pendingTrackCount() {
  22730. return Object.keys(this.tracks).reduce((acc, type) => acc + (this.isPending(this.tracks[type]) ? 1 : 0), 0);
  22731. }
  22732. get sourceBufferCount() {
  22733. return this.sourceBuffers.reduce((acc, [type]) => acc + (type ? 1 : 0), 0);
  22734. }
  22735. get sourceBufferTypes() {
  22736. return this.sourceBuffers.map(([type]) => type).filter((type) => !!type);
  22737. }
  22738. addBufferListener(type, event, fn) {
  22739. const track = this.tracks[type];
  22740. if (!track) {
  22741. return;
  22742. }
  22743. const buffer = track.buffer;
  22744. if (!buffer) {
  22745. return;
  22746. }
  22747. const listener = fn.bind(this, type);
  22748. track.listeners.push({
  22749. event,
  22750. listener
  22751. });
  22752. buffer.addEventListener(event, listener);
  22753. }
  22754. removeBufferListeners(type) {
  22755. const track = this.tracks[type];
  22756. if (!track) {
  22757. return;
  22758. }
  22759. const buffer = track.buffer;
  22760. if (!buffer) {
  22761. return;
  22762. }
  22763. track.listeners.forEach((l2) => {
  22764. buffer.removeEventListener(l2.event, l2.listener);
  22765. });
  22766. track.listeners.length = 0;
  22767. }
  22768. }
  22769. function removeSourceChildren(node) {
  22770. const sourceChildren = node.querySelectorAll("source");
  22771. [].slice.call(sourceChildren).forEach((source) => {
  22772. node.removeChild(source);
  22773. });
  22774. }
  22775. function addSource(media, url2) {
  22776. const source = self.document.createElement("source");
  22777. source.type = "video/mp4";
  22778. source.src = url2;
  22779. media.appendChild(source);
  22780. }
  22781. function sourceBufferNameToIndex(type) {
  22782. return type === "audio" ? 1 : 0;
  22783. }
  22784. class CapLevelController {
  22785. constructor(hls) {
  22786. this.hls = void 0;
  22787. this.autoLevelCapping = void 0;
  22788. this.firstLevel = void 0;
  22789. this.media = void 0;
  22790. this.restrictedLevels = void 0;
  22791. this.timer = void 0;
  22792. this.clientRect = void 0;
  22793. this.streamController = void 0;
  22794. this.hls = hls;
  22795. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  22796. this.firstLevel = -1;
  22797. this.media = null;
  22798. this.restrictedLevels = [];
  22799. this.timer = void 0;
  22800. this.clientRect = null;
  22801. this.registerListeners();
  22802. }
  22803. setStreamController(streamController) {
  22804. this.streamController = streamController;
  22805. }
  22806. destroy() {
  22807. if (this.hls) {
  22808. this.unregisterListener();
  22809. }
  22810. if (this.timer) {
  22811. this.stopCapping();
  22812. }
  22813. this.media = null;
  22814. this.clientRect = null;
  22815. this.hls = this.streamController = null;
  22816. }
  22817. registerListeners() {
  22818. const {
  22819. hls
  22820. } = this;
  22821. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  22822. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  22823. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  22824. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  22825. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  22826. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  22827. }
  22828. unregisterListener() {
  22829. const {
  22830. hls
  22831. } = this;
  22832. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  22833. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  22834. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  22835. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  22836. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  22837. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  22838. }
  22839. onFpsDropLevelCapping(event, data) {
  22840. const level = this.hls.levels[data.droppedLevel];
  22841. if (this.isLevelAllowed(level)) {
  22842. this.restrictedLevels.push({
  22843. bitrate: level.bitrate,
  22844. height: level.height,
  22845. width: level.width
  22846. });
  22847. }
  22848. }
  22849. onMediaAttaching(event, data) {
  22850. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  22851. this.clientRect = null;
  22852. if (this.timer && this.hls.levels.length) {
  22853. this.detectPlayerSize();
  22854. }
  22855. }
  22856. onManifestParsed(event, data) {
  22857. const hls = this.hls;
  22858. this.restrictedLevels = [];
  22859. this.firstLevel = data.firstLevel;
  22860. if (hls.config.capLevelToPlayerSize && data.video) {
  22861. this.startCapping();
  22862. }
  22863. }
  22864. onLevelsUpdated(event, data) {
  22865. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  22866. this.detectPlayerSize();
  22867. }
  22868. }
  22869. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  22870. // to the first level
  22871. onBufferCodecs(event, data) {
  22872. const hls = this.hls;
  22873. if (hls.config.capLevelToPlayerSize && data.video) {
  22874. this.startCapping();
  22875. }
  22876. }
  22877. onMediaDetaching() {
  22878. this.stopCapping();
  22879. this.media = null;
  22880. }
  22881. detectPlayerSize() {
  22882. if (this.media) {
  22883. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  22884. this.clientRect = null;
  22885. return;
  22886. }
  22887. const levels = this.hls.levels;
  22888. if (levels.length) {
  22889. const hls = this.hls;
  22890. const maxLevel = this.getMaxLevel(levels.length - 1);
  22891. if (maxLevel !== this.autoLevelCapping) {
  22892. hls.logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);
  22893. }
  22894. hls.autoLevelCapping = maxLevel;
  22895. if (hls.autoLevelEnabled && hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  22896. this.streamController.nextLevelSwitch();
  22897. }
  22898. this.autoLevelCapping = hls.autoLevelCapping;
  22899. }
  22900. }
  22901. }
  22902. /*
  22903. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  22904. */
  22905. getMaxLevel(capLevelIndex) {
  22906. const levels = this.hls.levels;
  22907. if (!levels.length) {
  22908. return -1;
  22909. }
  22910. const validLevels = levels.filter((level, index2) => this.isLevelAllowed(level) && index2 <= capLevelIndex);
  22911. this.clientRect = null;
  22912. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  22913. }
  22914. startCapping() {
  22915. if (this.timer) {
  22916. return;
  22917. }
  22918. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  22919. self.clearInterval(this.timer);
  22920. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1e3);
  22921. this.detectPlayerSize();
  22922. }
  22923. stopCapping() {
  22924. this.restrictedLevels = [];
  22925. this.firstLevel = -1;
  22926. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  22927. if (this.timer) {
  22928. self.clearInterval(this.timer);
  22929. this.timer = void 0;
  22930. }
  22931. }
  22932. getDimensions() {
  22933. if (this.clientRect) {
  22934. return this.clientRect;
  22935. }
  22936. const media = this.media;
  22937. const boundsRect = {
  22938. width: 0,
  22939. height: 0
  22940. };
  22941. if (media) {
  22942. const clientRect = media.getBoundingClientRect();
  22943. boundsRect.width = clientRect.width;
  22944. boundsRect.height = clientRect.height;
  22945. if (!boundsRect.width && !boundsRect.height) {
  22946. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  22947. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  22948. }
  22949. }
  22950. this.clientRect = boundsRect;
  22951. return boundsRect;
  22952. }
  22953. get mediaWidth() {
  22954. return this.getDimensions().width * this.contentScaleFactor;
  22955. }
  22956. get mediaHeight() {
  22957. return this.getDimensions().height * this.contentScaleFactor;
  22958. }
  22959. get contentScaleFactor() {
  22960. let pixelRatio = 1;
  22961. if (!this.hls.config.ignoreDevicePixelRatio) {
  22962. try {
  22963. pixelRatio = self.devicePixelRatio;
  22964. } catch (e2) {
  22965. }
  22966. }
  22967. return Math.min(pixelRatio, this.hls.config.maxDevicePixelRatio);
  22968. }
  22969. isLevelAllowed(level) {
  22970. const restrictedLevels = this.restrictedLevels;
  22971. return !restrictedLevels.some((restrictedLevel) => {
  22972. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  22973. });
  22974. }
  22975. static getMaxLevelByMediaSize(levels, width, height) {
  22976. if (!(levels != null && levels.length)) {
  22977. return -1;
  22978. }
  22979. const atGreatestBandwidth = (curLevel, nextLevel) => {
  22980. if (!nextLevel) {
  22981. return true;
  22982. }
  22983. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  22984. };
  22985. let maxLevelIndex = levels.length - 1;
  22986. const squareSize = Math.max(width, height);
  22987. for (let i2 = 0; i2 < levels.length; i2 += 1) {
  22988. const level = levels[i2];
  22989. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i2 + 1])) {
  22990. maxLevelIndex = i2;
  22991. break;
  22992. }
  22993. }
  22994. return maxLevelIndex;
  22995. }
  22996. }
  22997. const CmObjectType = {
  22998. /**
  22999. * text file, such as a manifest or playlist
  23000. */
  23001. MANIFEST: "m",
  23002. /**
  23003. * audio only
  23004. */
  23005. AUDIO: "a",
  23006. /**
  23007. * video only
  23008. */
  23009. VIDEO: "v",
  23010. /**
  23011. * muxed audio and video
  23012. */
  23013. MUXED: "av",
  23014. /**
  23015. * init segment
  23016. */
  23017. INIT: "i",
  23018. /**
  23019. * caption or subtitle
  23020. */
  23021. CAPTION: "c",
  23022. /**
  23023. * ISOBMFF timed text track
  23024. */
  23025. TIMED_TEXT: "tt",
  23026. /**
  23027. * cryptographic key, license or certificate.
  23028. */
  23029. KEY: "k",
  23030. /**
  23031. * other
  23032. */
  23033. OTHER: "o"
  23034. };
  23035. const CmcdObjectType = CmObjectType;
  23036. const CmStreamingFormat = {
  23037. /**
  23038. * HTTP Live Streaming (HLS)
  23039. */
  23040. HLS: "h"
  23041. };
  23042. const CmcdStreamingFormat = CmStreamingFormat;
  23043. const CMCD_OBJECT = "CMCD-Object";
  23044. const CMCD_REQUEST = "CMCD-Request";
  23045. const CMCD_SESSION = "CMCD-Session";
  23046. const CMCD_STATUS = "CMCD-Status";
  23047. const CmcdHeaderField = {
  23048. /**
  23049. * keys whose values vary with the object being requested.
  23050. */
  23051. OBJECT: CMCD_OBJECT,
  23052. /**
  23053. * keys whose values vary with each request.
  23054. */
  23055. REQUEST: CMCD_REQUEST,
  23056. /**
  23057. * keys whose values are expected to be invariant over the life of the session.
  23058. */
  23059. SESSION: CMCD_SESSION,
  23060. /**
  23061. * keys whose values do not vary with every request or object.
  23062. */
  23063. STATUS: CMCD_STATUS
  23064. };
  23065. const CmcdHeaderMap = {
  23066. [CmcdHeaderField.OBJECT]: ["br", "ab", "d", "ot", "tb", "tpb", "lb", "tab", "lab", "url"],
  23067. [CmcdHeaderField.REQUEST]: ["pb", "bl", "tbl", "dl", "ltc", "mtp", "nor", "nrr", "rc", "sn", "sta", "su", "ttfb", "ttfbb", "ttlb", "cmsdd", "cmsds", "smrt", "df", "cs"],
  23068. [CmcdHeaderField.SESSION]: ["cid", "pr", "sf", "sid", "st", "v", "msd"],
  23069. [CmcdHeaderField.STATUS]: ["bs", "bsd", "cdn", "rtp", "bg", "pt", "ec", "e"]
  23070. };
  23071. class SfItem {
  23072. constructor(value2, params) {
  23073. if (Array.isArray(value2)) {
  23074. value2 = value2.map((v2) => v2 instanceof SfItem ? v2 : new SfItem(v2));
  23075. }
  23076. this.value = value2;
  23077. this.params = params;
  23078. }
  23079. }
  23080. const DICT = "Dict";
  23081. function format(value2) {
  23082. if (Array.isArray(value2)) {
  23083. return JSON.stringify(value2);
  23084. }
  23085. if (value2 instanceof Map) {
  23086. return "Map{}";
  23087. }
  23088. if (value2 instanceof Set) {
  23089. return "Set{}";
  23090. }
  23091. if (typeof value2 === "object") {
  23092. return JSON.stringify(value2);
  23093. }
  23094. return String(value2);
  23095. }
  23096. function throwError(action, src, type, cause) {
  23097. return new Error(`failed to ${action} "${format(src)}" as ${type}`, {
  23098. cause
  23099. });
  23100. }
  23101. function serializeError(src, type, cause) {
  23102. return throwError("serialize", src, type, cause);
  23103. }
  23104. class SfToken {
  23105. constructor(description) {
  23106. this.description = description;
  23107. }
  23108. }
  23109. const BARE_ITEM = "Bare Item";
  23110. const BOOLEAN = "Boolean";
  23111. function serializeBoolean(value2) {
  23112. if (typeof value2 !== "boolean") {
  23113. throw serializeError(value2, BOOLEAN);
  23114. }
  23115. return value2 ? "?1" : "?0";
  23116. }
  23117. function encodeBase64(binary) {
  23118. return btoa(String.fromCharCode(...binary));
  23119. }
  23120. const BYTES = "Byte Sequence";
  23121. function serializeByteSequence(value2) {
  23122. if (ArrayBuffer.isView(value2) === false) {
  23123. throw serializeError(value2, BYTES);
  23124. }
  23125. return `:${encodeBase64(value2)}:`;
  23126. }
  23127. const INTEGER = "Integer";
  23128. function isInvalidInt(value2) {
  23129. return value2 < -999999999999999 || 999999999999999 < value2;
  23130. }
  23131. function serializeInteger(value2) {
  23132. if (isInvalidInt(value2)) {
  23133. throw serializeError(value2, INTEGER);
  23134. }
  23135. return value2.toString();
  23136. }
  23137. function serializeDate(value2) {
  23138. return `@${serializeInteger(value2.getTime() / 1e3)}`;
  23139. }
  23140. function roundToEven(value2, precision) {
  23141. if (value2 < 0) {
  23142. return -roundToEven(-value2, precision);
  23143. }
  23144. const decimalShift = Math.pow(10, precision);
  23145. const isEquidistant = Math.abs(value2 * decimalShift % 1 - 0.5) < Number.EPSILON;
  23146. if (isEquidistant) {
  23147. const flooredValue = Math.floor(value2 * decimalShift);
  23148. return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;
  23149. } else {
  23150. return Math.round(value2 * decimalShift) / decimalShift;
  23151. }
  23152. }
  23153. const DECIMAL = "Decimal";
  23154. function serializeDecimal(value2) {
  23155. const roundedValue = roundToEven(value2, 3);
  23156. if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {
  23157. throw serializeError(value2, DECIMAL);
  23158. }
  23159. const stringValue = roundedValue.toString();
  23160. return stringValue.includes(".") ? stringValue : `${stringValue}.0`;
  23161. }
  23162. const STRING = "String";
  23163. const STRING_REGEX = /[\x00-\x1f\x7f]+/;
  23164. function serializeString(value2) {
  23165. if (STRING_REGEX.test(value2)) {
  23166. throw serializeError(value2, STRING);
  23167. }
  23168. return `"${value2.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`)}"`;
  23169. }
  23170. function symbolToStr(symbol) {
  23171. return symbol.description || symbol.toString().slice(7, -1);
  23172. }
  23173. const TOKEN = "Token";
  23174. function serializeToken(token) {
  23175. const value2 = symbolToStr(token);
  23176. if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value2) === false) {
  23177. throw serializeError(value2, TOKEN);
  23178. }
  23179. return value2;
  23180. }
  23181. function serializeBareItem(value2) {
  23182. switch (typeof value2) {
  23183. case "number":
  23184. if (!isFiniteNumber(value2)) {
  23185. throw serializeError(value2, BARE_ITEM);
  23186. }
  23187. if (Number.isInteger(value2)) {
  23188. return serializeInteger(value2);
  23189. }
  23190. return serializeDecimal(value2);
  23191. case "string":
  23192. return serializeString(value2);
  23193. case "symbol":
  23194. return serializeToken(value2);
  23195. case "boolean":
  23196. return serializeBoolean(value2);
  23197. case "object":
  23198. if (value2 instanceof Date) {
  23199. return serializeDate(value2);
  23200. }
  23201. if (value2 instanceof Uint8Array) {
  23202. return serializeByteSequence(value2);
  23203. }
  23204. if (value2 instanceof SfToken) {
  23205. return serializeToken(value2);
  23206. }
  23207. default:
  23208. throw serializeError(value2, BARE_ITEM);
  23209. }
  23210. }
  23211. const KEY = "Key";
  23212. function serializeKey(value2) {
  23213. if (/^[a-z*][a-z0-9\-_.*]*$/.test(value2) === false) {
  23214. throw serializeError(value2, KEY);
  23215. }
  23216. return value2;
  23217. }
  23218. function serializeParams(params) {
  23219. if (params == null) {
  23220. return "";
  23221. }
  23222. return Object.entries(params).map(([key, value2]) => {
  23223. if (value2 === true) {
  23224. return `;${serializeKey(key)}`;
  23225. }
  23226. return `;${serializeKey(key)}=${serializeBareItem(value2)}`;
  23227. }).join("");
  23228. }
  23229. function serializeItem(value2) {
  23230. if (value2 instanceof SfItem) {
  23231. return `${serializeBareItem(value2.value)}${serializeParams(value2.params)}`;
  23232. } else {
  23233. return serializeBareItem(value2);
  23234. }
  23235. }
  23236. function serializeInnerList(value2) {
  23237. return `(${value2.value.map(serializeItem).join(" ")})${serializeParams(value2.params)}`;
  23238. }
  23239. function serializeDict(dict, options = {
  23240. whitespace: true
  23241. }) {
  23242. if (typeof dict !== "object") {
  23243. throw serializeError(dict, DICT);
  23244. }
  23245. const entries = dict instanceof Map ? dict.entries() : Object.entries(dict);
  23246. const optionalWhiteSpace = (options === null || options === void 0 ? void 0 : options.whitespace) ? " " : "";
  23247. return Array.from(entries).map(([key, item]) => {
  23248. if (item instanceof SfItem === false) {
  23249. item = new SfItem(item);
  23250. }
  23251. let output = serializeKey(key);
  23252. if (item.value === true) {
  23253. output += serializeParams(item.params);
  23254. } else {
  23255. output += "=";
  23256. if (Array.isArray(item.value)) {
  23257. output += serializeInnerList(item);
  23258. } else {
  23259. output += serializeItem(item);
  23260. }
  23261. }
  23262. return output;
  23263. }).join(`,${optionalWhiteSpace}`);
  23264. }
  23265. function encodeSfDict(value2, options) {
  23266. return serializeDict(value2, options);
  23267. }
  23268. function isTokenField(key) {
  23269. return ["ot", "sf", "st", "e", "sta"].includes(key);
  23270. }
  23271. function isValid(value2) {
  23272. if (typeof value2 === "number") {
  23273. return isFiniteNumber(value2);
  23274. }
  23275. return value2 != null && value2 !== "" && value2 !== false;
  23276. }
  23277. function urlToRelativePath(url2, base) {
  23278. const to = new URL(url2);
  23279. const from = new URL(base);
  23280. if (to.origin !== from.origin) {
  23281. return url2;
  23282. }
  23283. const toPath = to.pathname.split("/").slice(1);
  23284. const fromPath = from.pathname.split("/").slice(1, -1);
  23285. while (toPath[0] === fromPath[0]) {
  23286. toPath.shift();
  23287. fromPath.shift();
  23288. }
  23289. while (fromPath.length) {
  23290. fromPath.shift();
  23291. toPath.unshift("..");
  23292. }
  23293. return toPath.join("/");
  23294. }
  23295. const toRounded = (value2) => Math.round(value2);
  23296. const toUrlSafe = (value2, options) => {
  23297. if (options === null || options === void 0 ? void 0 : options.baseUrl) {
  23298. value2 = urlToRelativePath(value2, options.baseUrl);
  23299. }
  23300. return encodeURIComponent(value2);
  23301. };
  23302. const toHundred = (value2) => toRounded(value2 / 100) * 100;
  23303. const CmcdFormatters = {
  23304. /**
  23305. * Bitrate (kbps) rounded integer
  23306. */
  23307. br: toRounded,
  23308. /**
  23309. * Duration (milliseconds) rounded integer
  23310. */
  23311. d: toRounded,
  23312. /**
  23313. * Buffer Length (milliseconds) rounded nearest 100ms
  23314. */
  23315. bl: toHundred,
  23316. /**
  23317. * Deadline (milliseconds) rounded nearest 100ms
  23318. */
  23319. dl: toHundred,
  23320. /**
  23321. * Measured Throughput (kbps) rounded nearest 100kbps
  23322. */
  23323. mtp: toHundred,
  23324. /**
  23325. * Next Object Request URL encoded
  23326. */
  23327. nor: toUrlSafe,
  23328. /**
  23329. * Requested maximum throughput (kbps) rounded nearest 100kbps
  23330. */
  23331. rtp: toHundred,
  23332. /**
  23333. * Top Bitrate (kbps) rounded integer
  23334. */
  23335. tb: toRounded
  23336. };
  23337. function processCmcd(obj, options) {
  23338. const results = {};
  23339. if (obj == null || typeof obj !== "object") {
  23340. return results;
  23341. }
  23342. const keys = Object.keys(obj).sort();
  23343. const formatters = _extends({}, CmcdFormatters, options === null || options === void 0 ? void 0 : options.formatters);
  23344. const filter = options === null || options === void 0 ? void 0 : options.filter;
  23345. keys.forEach((key) => {
  23346. if ((filter === null || filter === void 0 ? void 0 : filter(key)) === false) {
  23347. return;
  23348. }
  23349. let value2 = obj[key];
  23350. const formatter = formatters[key];
  23351. if (formatter) {
  23352. value2 = formatter(value2, options);
  23353. }
  23354. if (key === "v" && value2 === 1) {
  23355. return;
  23356. }
  23357. if (key == "pr" && value2 === 1) {
  23358. return;
  23359. }
  23360. if (!isValid(value2)) {
  23361. return;
  23362. }
  23363. if (isTokenField(key) && typeof value2 === "string") {
  23364. value2 = new SfToken(value2);
  23365. }
  23366. results[key] = value2;
  23367. });
  23368. return results;
  23369. }
  23370. function encodeCmcd(cmcd, options = {}) {
  23371. if (!cmcd) {
  23372. return "";
  23373. }
  23374. return encodeSfDict(processCmcd(cmcd, options), _extends({
  23375. whitespace: false
  23376. }, options));
  23377. }
  23378. function toCmcdHeaders(cmcd, options = {}) {
  23379. const result = {};
  23380. if (!cmcd) {
  23381. return result;
  23382. }
  23383. const entries = Object.entries(cmcd);
  23384. const headerMap = Object.entries(CmcdHeaderMap).concat(Object.entries((options === null || options === void 0 ? void 0 : options.customHeaderMap) || {}));
  23385. const shards = entries.reduce((acc, entry) => {
  23386. var _a, _b;
  23387. const [key, value2] = entry;
  23388. const field = ((_a = headerMap.find((entry2) => entry2[1].includes(key))) === null || _a === void 0 ? void 0 : _a[0]) || CmcdHeaderField.REQUEST;
  23389. (_b = acc[field]) !== null && _b !== void 0 ? _b : acc[field] = {};
  23390. acc[field][key] = value2;
  23391. return acc;
  23392. }, {});
  23393. return Object.entries(shards).reduce((acc, [field, value2]) => {
  23394. acc[field] = encodeCmcd(value2, options);
  23395. return acc;
  23396. }, result);
  23397. }
  23398. function appendCmcdHeaders(headers, cmcd, options) {
  23399. return _extends(headers, toCmcdHeaders(cmcd, options));
  23400. }
  23401. const CMCD_PARAM = "CMCD";
  23402. function toCmcdQuery(cmcd, options = {}) {
  23403. if (!cmcd) {
  23404. return "";
  23405. }
  23406. const params = encodeCmcd(cmcd, options);
  23407. return `${CMCD_PARAM}=${encodeURIComponent(params)}`;
  23408. }
  23409. const REGEX = /CMCD=[^&#]+/;
  23410. function appendCmcdQuery(url2, cmcd, options) {
  23411. const query = toCmcdQuery(cmcd, options);
  23412. if (!query) {
  23413. return url2;
  23414. }
  23415. if (REGEX.test(url2)) {
  23416. return url2.replace(REGEX, query);
  23417. }
  23418. const separator = url2.includes("?") ? "&" : "?";
  23419. return `${url2}${separator}${query}`;
  23420. }
  23421. class CMCDController {
  23422. constructor(hls) {
  23423. this.hls = void 0;
  23424. this.config = void 0;
  23425. this.media = void 0;
  23426. this.sid = void 0;
  23427. this.cid = void 0;
  23428. this.useHeaders = false;
  23429. this.includeKeys = void 0;
  23430. this.initialized = false;
  23431. this.starved = false;
  23432. this.buffering = true;
  23433. this.audioBuffer = void 0;
  23434. this.videoBuffer = void 0;
  23435. this.onWaiting = () => {
  23436. if (this.initialized) {
  23437. this.starved = true;
  23438. }
  23439. this.buffering = true;
  23440. };
  23441. this.onPlaying = () => {
  23442. if (!this.initialized) {
  23443. this.initialized = true;
  23444. }
  23445. this.buffering = false;
  23446. };
  23447. this.applyPlaylistData = (context) => {
  23448. try {
  23449. this.apply(context, {
  23450. ot: CmcdObjectType.MANIFEST,
  23451. su: !this.initialized
  23452. });
  23453. } catch (error2) {
  23454. this.hls.logger.warn("Could not generate manifest CMCD data.", error2);
  23455. }
  23456. };
  23457. this.applyFragmentData = (context) => {
  23458. try {
  23459. const {
  23460. frag,
  23461. part
  23462. } = context;
  23463. const level = this.hls.levels[frag.level];
  23464. const ot2 = this.getObjectType(frag);
  23465. const data = {
  23466. d: (part || frag).duration * 1e3,
  23467. ot: ot2
  23468. };
  23469. if (ot2 === CmcdObjectType.VIDEO || ot2 === CmcdObjectType.AUDIO || ot2 == CmcdObjectType.MUXED) {
  23470. data.br = level.bitrate / 1e3;
  23471. data.tb = this.getTopBandwidth(ot2) / 1e3;
  23472. data.bl = this.getBufferLength(ot2);
  23473. }
  23474. const next = part ? this.getNextPart(part) : this.getNextFrag(frag);
  23475. if (next != null && next.url && next.url !== frag.url) {
  23476. data.nor = next.url;
  23477. }
  23478. this.apply(context, data);
  23479. } catch (error2) {
  23480. this.hls.logger.warn("Could not generate segment CMCD data.", error2);
  23481. }
  23482. };
  23483. this.hls = hls;
  23484. const config2 = this.config = hls.config;
  23485. const {
  23486. cmcd
  23487. } = config2;
  23488. if (cmcd != null) {
  23489. config2.pLoader = this.createPlaylistLoader();
  23490. config2.fLoader = this.createFragmentLoader();
  23491. this.sid = cmcd.sessionId || hls.sessionId;
  23492. this.cid = cmcd.contentId;
  23493. this.useHeaders = cmcd.useHeaders === true;
  23494. this.includeKeys = cmcd.includeKeys;
  23495. this.registerListeners();
  23496. }
  23497. }
  23498. registerListeners() {
  23499. const hls = this.hls;
  23500. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  23501. hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  23502. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  23503. }
  23504. unregisterListeners() {
  23505. const hls = this.hls;
  23506. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  23507. hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  23508. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  23509. }
  23510. destroy() {
  23511. this.unregisterListeners();
  23512. this.onMediaDetached();
  23513. this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
  23514. this.onWaiting = this.onPlaying = this.media = null;
  23515. }
  23516. onMediaAttached(event, data) {
  23517. this.media = data.media;
  23518. this.media.addEventListener("waiting", this.onWaiting);
  23519. this.media.addEventListener("playing", this.onPlaying);
  23520. }
  23521. onMediaDetached() {
  23522. if (!this.media) {
  23523. return;
  23524. }
  23525. this.media.removeEventListener("waiting", this.onWaiting);
  23526. this.media.removeEventListener("playing", this.onPlaying);
  23527. this.media = null;
  23528. }
  23529. onBufferCreated(event, data) {
  23530. var _data$tracks$audio, _data$tracks$video;
  23531. this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer;
  23532. this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer;
  23533. }
  23534. /**
  23535. * Create baseline CMCD data
  23536. */
  23537. createData() {
  23538. var _this$media;
  23539. return {
  23540. v: 1,
  23541. sf: CmcdStreamingFormat.HLS,
  23542. sid: this.sid,
  23543. cid: this.cid,
  23544. pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate,
  23545. mtp: this.hls.bandwidthEstimate / 1e3
  23546. };
  23547. }
  23548. /**
  23549. * Apply CMCD data to a request.
  23550. */
  23551. apply(context, data = {}) {
  23552. _extends(data, this.createData());
  23553. const isVideo = data.ot === CmcdObjectType.INIT || data.ot === CmcdObjectType.VIDEO || data.ot === CmcdObjectType.MUXED;
  23554. if (this.starved && isVideo) {
  23555. data.bs = true;
  23556. data.su = true;
  23557. this.starved = false;
  23558. }
  23559. if (data.su == null) {
  23560. data.su = this.buffering;
  23561. }
  23562. const {
  23563. includeKeys
  23564. } = this;
  23565. if (includeKeys) {
  23566. data = Object.keys(data).reduce((acc, key) => {
  23567. includeKeys.includes(key) && (acc[key] = data[key]);
  23568. return acc;
  23569. }, {});
  23570. }
  23571. const options = {
  23572. baseUrl: context.url
  23573. };
  23574. if (this.useHeaders) {
  23575. if (!context.headers) {
  23576. context.headers = {};
  23577. }
  23578. appendCmcdHeaders(context.headers, data, options);
  23579. } else {
  23580. context.url = appendCmcdQuery(context.url, data, options);
  23581. }
  23582. }
  23583. getNextFrag(fragment) {
  23584. var _this$hls$levels$frag;
  23585. const levelDetails = (_this$hls$levels$frag = this.hls.levels[fragment.level]) == null ? void 0 : _this$hls$levels$frag.details;
  23586. if (levelDetails) {
  23587. const index2 = fragment.sn - levelDetails.startSN;
  23588. return levelDetails.fragments[index2 + 1];
  23589. }
  23590. return void 0;
  23591. }
  23592. getNextPart(part) {
  23593. var _this$hls$levels$frag2, _this$hls$levels$frag3;
  23594. const {
  23595. index: index2,
  23596. fragment
  23597. } = part;
  23598. 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;
  23599. if (partList) {
  23600. const {
  23601. sn
  23602. } = fragment;
  23603. for (let i2 = partList.length - 1; i2 >= 0; i2--) {
  23604. const p2 = partList[i2];
  23605. if (p2.index === index2 && p2.fragment.sn === sn) {
  23606. return partList[i2 + 1];
  23607. }
  23608. }
  23609. }
  23610. return void 0;
  23611. }
  23612. /**
  23613. * The CMCD object type.
  23614. */
  23615. getObjectType(fragment) {
  23616. const {
  23617. type
  23618. } = fragment;
  23619. if (type === "subtitle") {
  23620. return CmcdObjectType.TIMED_TEXT;
  23621. }
  23622. if (fragment.sn === "initSegment") {
  23623. return CmcdObjectType.INIT;
  23624. }
  23625. if (type === "audio") {
  23626. return CmcdObjectType.AUDIO;
  23627. }
  23628. if (type === "main") {
  23629. if (!this.hls.audioTracks.length) {
  23630. return CmcdObjectType.MUXED;
  23631. }
  23632. return CmcdObjectType.VIDEO;
  23633. }
  23634. return void 0;
  23635. }
  23636. /**
  23637. * Get the highest bitrate.
  23638. */
  23639. getTopBandwidth(type) {
  23640. let bitrate = 0;
  23641. let levels;
  23642. const hls = this.hls;
  23643. if (type === CmcdObjectType.AUDIO) {
  23644. levels = hls.audioTracks;
  23645. } else {
  23646. const max = hls.maxAutoLevel;
  23647. const len = max > -1 ? max + 1 : hls.levels.length;
  23648. levels = hls.levels.slice(0, len);
  23649. }
  23650. levels.forEach((level) => {
  23651. if (level.bitrate > bitrate) {
  23652. bitrate = level.bitrate;
  23653. }
  23654. });
  23655. return bitrate > 0 ? bitrate : NaN;
  23656. }
  23657. /**
  23658. * Get the buffer length for a media type in milliseconds
  23659. */
  23660. getBufferLength(type) {
  23661. const media = this.media;
  23662. const buffer = type === CmcdObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;
  23663. if (!buffer || !media) {
  23664. return NaN;
  23665. }
  23666. const info = BufferHelper.bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);
  23667. return info.len * 1e3;
  23668. }
  23669. /**
  23670. * Create a playlist loader
  23671. */
  23672. createPlaylistLoader() {
  23673. const {
  23674. pLoader
  23675. } = this.config;
  23676. const apply = this.applyPlaylistData;
  23677. const Ctor = pLoader || this.config.loader;
  23678. return class CmcdPlaylistLoader {
  23679. constructor(config2) {
  23680. this.loader = void 0;
  23681. this.loader = new Ctor(config2);
  23682. }
  23683. get stats() {
  23684. return this.loader.stats;
  23685. }
  23686. get context() {
  23687. return this.loader.context;
  23688. }
  23689. destroy() {
  23690. this.loader.destroy();
  23691. }
  23692. abort() {
  23693. this.loader.abort();
  23694. }
  23695. load(context, config2, callbacks) {
  23696. apply(context);
  23697. this.loader.load(context, config2, callbacks);
  23698. }
  23699. };
  23700. }
  23701. /**
  23702. * Create a playlist loader
  23703. */
  23704. createFragmentLoader() {
  23705. const {
  23706. fLoader
  23707. } = this.config;
  23708. const apply = this.applyFragmentData;
  23709. const Ctor = fLoader || this.config.loader;
  23710. return class CmcdFragmentLoader {
  23711. constructor(config2) {
  23712. this.loader = void 0;
  23713. this.loader = new Ctor(config2);
  23714. }
  23715. get stats() {
  23716. return this.loader.stats;
  23717. }
  23718. get context() {
  23719. return this.loader.context;
  23720. }
  23721. destroy() {
  23722. this.loader.destroy();
  23723. }
  23724. abort() {
  23725. this.loader.abort();
  23726. }
  23727. load(context, config2, callbacks) {
  23728. apply(context);
  23729. this.loader.load(context, config2, callbacks);
  23730. }
  23731. };
  23732. }
  23733. }
  23734. const PATHWAY_PENALTY_DURATION_MS = 3e5;
  23735. class ContentSteeringController extends Logger {
  23736. constructor(hls) {
  23737. super("content-steering", hls.logger);
  23738. this.hls = void 0;
  23739. this.loader = null;
  23740. this.uri = null;
  23741. this.pathwayId = ".";
  23742. this._pathwayPriority = null;
  23743. this.timeToLoad = 300;
  23744. this.reloadTimer = -1;
  23745. this.updated = 0;
  23746. this.started = false;
  23747. this.enabled = true;
  23748. this.levels = null;
  23749. this.audioTracks = null;
  23750. this.subtitleTracks = null;
  23751. this.penalizedPathways = {};
  23752. this.hls = hls;
  23753. this.registerListeners();
  23754. }
  23755. registerListeners() {
  23756. const hls = this.hls;
  23757. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  23758. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  23759. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  23760. hls.on(Events.ERROR, this.onError, this);
  23761. }
  23762. unregisterListeners() {
  23763. const hls = this.hls;
  23764. if (!hls) {
  23765. return;
  23766. }
  23767. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  23768. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  23769. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  23770. hls.off(Events.ERROR, this.onError, this);
  23771. }
  23772. pathways() {
  23773. return (this.levels || []).reduce((pathways, level) => {
  23774. if (pathways.indexOf(level.pathwayId) === -1) {
  23775. pathways.push(level.pathwayId);
  23776. }
  23777. return pathways;
  23778. }, []);
  23779. }
  23780. get pathwayPriority() {
  23781. return this._pathwayPriority;
  23782. }
  23783. set pathwayPriority(pathwayPriority) {
  23784. this.updatePathwayPriority(pathwayPriority);
  23785. }
  23786. startLoad() {
  23787. this.started = true;
  23788. this.clearTimeout();
  23789. if (this.enabled && this.uri) {
  23790. if (this.updated) {
  23791. const ttl = this.timeToLoad * 1e3 - (performance.now() - this.updated);
  23792. if (ttl > 0) {
  23793. this.scheduleRefresh(this.uri, ttl);
  23794. return;
  23795. }
  23796. }
  23797. this.loadSteeringManifest(this.uri);
  23798. }
  23799. }
  23800. stopLoad() {
  23801. this.started = false;
  23802. if (this.loader) {
  23803. this.loader.destroy();
  23804. this.loader = null;
  23805. }
  23806. this.clearTimeout();
  23807. }
  23808. clearTimeout() {
  23809. if (this.reloadTimer !== -1) {
  23810. self.clearTimeout(this.reloadTimer);
  23811. this.reloadTimer = -1;
  23812. }
  23813. }
  23814. destroy() {
  23815. this.unregisterListeners();
  23816. this.stopLoad();
  23817. this.hls = null;
  23818. this.levels = this.audioTracks = this.subtitleTracks = null;
  23819. }
  23820. removeLevel(levelToRemove) {
  23821. const levels = this.levels;
  23822. if (levels) {
  23823. this.levels = levels.filter((level) => level !== levelToRemove);
  23824. }
  23825. }
  23826. onManifestLoading() {
  23827. this.stopLoad();
  23828. this.enabled = true;
  23829. this.timeToLoad = 300;
  23830. this.updated = 0;
  23831. this.uri = null;
  23832. this.pathwayId = ".";
  23833. this.levels = this.audioTracks = this.subtitleTracks = null;
  23834. }
  23835. onManifestLoaded(event, data) {
  23836. const {
  23837. contentSteering
  23838. } = data;
  23839. if (contentSteering === null) {
  23840. return;
  23841. }
  23842. this.pathwayId = contentSteering.pathwayId;
  23843. this.uri = contentSteering.uri;
  23844. if (this.started) {
  23845. this.startLoad();
  23846. }
  23847. }
  23848. onManifestParsed(event, data) {
  23849. this.audioTracks = data.audioTracks;
  23850. this.subtitleTracks = data.subtitleTracks;
  23851. }
  23852. onError(event, data) {
  23853. const {
  23854. errorAction
  23855. } = data;
  23856. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  23857. const levels = this.levels;
  23858. let pathwayPriority = this._pathwayPriority;
  23859. let errorPathway = this.pathwayId;
  23860. if (data.context) {
  23861. const {
  23862. groupId,
  23863. pathwayId,
  23864. type
  23865. } = data.context;
  23866. if (groupId && levels) {
  23867. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  23868. } else if (pathwayId) {
  23869. errorPathway = pathwayId;
  23870. }
  23871. }
  23872. if (!(errorPathway in this.penalizedPathways)) {
  23873. this.penalizedPathways[errorPathway] = performance.now();
  23874. }
  23875. if (!pathwayPriority && levels) {
  23876. pathwayPriority = this.pathways();
  23877. }
  23878. if (pathwayPriority && pathwayPriority.length > 1) {
  23879. this.updatePathwayPriority(pathwayPriority);
  23880. errorAction.resolved = this.pathwayId !== errorPathway;
  23881. }
  23882. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && !data.fatal) {
  23883. errorAction.resolved = true;
  23884. } else if (!errorAction.resolved) {
  23885. 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)}`);
  23886. }
  23887. }
  23888. }
  23889. filterParsedLevels(levels) {
  23890. this.levels = levels;
  23891. let pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  23892. if (pathwayLevels.length === 0) {
  23893. const pathwayId = levels[0].pathwayId;
  23894. this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`);
  23895. pathwayLevels = this.getLevelsForPathway(pathwayId);
  23896. this.pathwayId = pathwayId;
  23897. }
  23898. if (pathwayLevels.length !== levels.length) {
  23899. this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`);
  23900. }
  23901. return pathwayLevels;
  23902. }
  23903. getLevelsForPathway(pathwayId) {
  23904. if (this.levels === null) {
  23905. return [];
  23906. }
  23907. return this.levels.filter((level) => pathwayId === level.pathwayId);
  23908. }
  23909. updatePathwayPriority(pathwayPriority) {
  23910. this._pathwayPriority = pathwayPriority;
  23911. let levels;
  23912. const penalizedPathways = this.penalizedPathways;
  23913. const now2 = performance.now();
  23914. Object.keys(penalizedPathways).forEach((pathwayId) => {
  23915. if (now2 - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  23916. delete penalizedPathways[pathwayId];
  23917. }
  23918. });
  23919. for (let i2 = 0; i2 < pathwayPriority.length; i2++) {
  23920. const pathwayId = pathwayPriority[i2];
  23921. if (pathwayId in penalizedPathways) {
  23922. continue;
  23923. }
  23924. if (pathwayId === this.pathwayId) {
  23925. return;
  23926. }
  23927. const selectedIndex = this.hls.nextLoadLevel;
  23928. const selectedLevel = this.hls.levels[selectedIndex];
  23929. levels = this.getLevelsForPathway(pathwayId);
  23930. if (levels.length > 0) {
  23931. this.log(`Setting Pathway to "${pathwayId}"`);
  23932. this.pathwayId = pathwayId;
  23933. reassignFragmentLevelIndexes(levels);
  23934. this.hls.trigger(Events.LEVELS_UPDATED, {
  23935. levels
  23936. });
  23937. const levelAfterChange = this.hls.levels[selectedIndex];
  23938. if (selectedLevel && levelAfterChange && this.levels) {
  23939. if (levelAfterChange.attrs["STABLE-VARIANT-ID"] !== selectedLevel.attrs["STABLE-VARIANT-ID"] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  23940. this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);
  23941. }
  23942. this.hls.nextLoadLevel = selectedIndex;
  23943. }
  23944. break;
  23945. }
  23946. }
  23947. }
  23948. getPathwayForGroupId(groupId, type, defaultPathway) {
  23949. const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  23950. for (let i2 = 0; i2 < levels.length; i2++) {
  23951. if (type === PlaylistContextType.AUDIO_TRACK && levels[i2].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i2].hasSubtitleGroup(groupId)) {
  23952. return levels[i2].pathwayId;
  23953. }
  23954. }
  23955. return defaultPathway;
  23956. }
  23957. clonePathways(pathwayClones) {
  23958. const levels = this.levels;
  23959. if (!levels) {
  23960. return;
  23961. }
  23962. const audioGroupCloneMap = {};
  23963. const subtitleGroupCloneMap = {};
  23964. pathwayClones.forEach((pathwayClone) => {
  23965. const {
  23966. ID: cloneId,
  23967. "BASE-ID": baseId,
  23968. "URI-REPLACEMENT": uriReplacement
  23969. } = pathwayClone;
  23970. if (levels.some((level) => level.pathwayId === cloneId)) {
  23971. return;
  23972. }
  23973. const clonedVariants = this.getLevelsForPathway(baseId).map((baseLevel) => {
  23974. const attributes = new AttrList(baseLevel.attrs);
  23975. attributes["PATHWAY-ID"] = cloneId;
  23976. const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;
  23977. const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;
  23978. if (clonedAudioGroupId) {
  23979. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  23980. attributes.AUDIO = clonedAudioGroupId;
  23981. }
  23982. if (clonedSubtitleGroupId) {
  23983. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  23984. attributes.SUBTITLES = clonedSubtitleGroupId;
  23985. }
  23986. const url2 = performUriReplacement(baseLevel.uri, attributes["STABLE-VARIANT-ID"], "PER-VARIANT-URIS", uriReplacement);
  23987. const clonedLevel = new Level({
  23988. attrs: attributes,
  23989. audioCodec: baseLevel.audioCodec,
  23990. bitrate: baseLevel.bitrate,
  23991. height: baseLevel.height,
  23992. name: baseLevel.name,
  23993. url: url2,
  23994. videoCodec: baseLevel.videoCodec,
  23995. width: baseLevel.width
  23996. });
  23997. if (baseLevel.audioGroups) {
  23998. for (let i2 = 1; i2 < baseLevel.audioGroups.length; i2++) {
  23999. clonedLevel.addGroupId("audio", `${baseLevel.audioGroups[i2]}_clone_${cloneId}`);
  24000. }
  24001. }
  24002. if (baseLevel.subtitleGroups) {
  24003. for (let i2 = 1; i2 < baseLevel.subtitleGroups.length; i2++) {
  24004. clonedLevel.addGroupId("text", `${baseLevel.subtitleGroups[i2]}_clone_${cloneId}`);
  24005. }
  24006. }
  24007. return clonedLevel;
  24008. });
  24009. levels.push(...clonedVariants);
  24010. cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  24011. cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  24012. });
  24013. }
  24014. loadSteeringManifest(uri) {
  24015. const config2 = this.hls.config;
  24016. const Loader = config2.loader;
  24017. if (this.loader) {
  24018. this.loader.destroy();
  24019. }
  24020. this.loader = new Loader(config2);
  24021. let url2;
  24022. try {
  24023. url2 = new self.URL(uri);
  24024. } catch (error2) {
  24025. this.enabled = false;
  24026. this.log(`Failed to parse Steering Manifest URI: ${uri}`);
  24027. return;
  24028. }
  24029. if (url2.protocol !== "data:") {
  24030. const throughput = (this.hls.bandwidthEstimate || config2.abrEwmaDefaultEstimate) | 0;
  24031. url2.searchParams.set("_HLS_pathway", this.pathwayId);
  24032. url2.searchParams.set("_HLS_throughput", "" + throughput);
  24033. }
  24034. const context = {
  24035. responseType: "json",
  24036. url: url2.href
  24037. };
  24038. const loadPolicy = config2.steeringManifestLoadPolicy.default;
  24039. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  24040. const loaderConfig = {
  24041. loadPolicy,
  24042. timeout: loadPolicy.maxLoadTimeMs,
  24043. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  24044. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  24045. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  24046. };
  24047. const callbacks = {
  24048. onSuccess: (response, stats, context2, networkDetails) => {
  24049. this.log(`Loaded steering manifest: "${url2}"`);
  24050. const steeringData = response.data;
  24051. if ((steeringData == null ? void 0 : steeringData.VERSION) !== 1) {
  24052. this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);
  24053. return;
  24054. }
  24055. this.updated = performance.now();
  24056. this.timeToLoad = steeringData.TTL;
  24057. const {
  24058. "RELOAD-URI": reloadUri,
  24059. "PATHWAY-CLONES": pathwayClones,
  24060. "PATHWAY-PRIORITY": pathwayPriority
  24061. } = steeringData;
  24062. if (reloadUri) {
  24063. try {
  24064. this.uri = new self.URL(reloadUri, url2).href;
  24065. } catch (error2) {
  24066. this.enabled = false;
  24067. this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);
  24068. return;
  24069. }
  24070. }
  24071. this.scheduleRefresh(this.uri || context2.url);
  24072. if (pathwayClones) {
  24073. this.clonePathways(pathwayClones);
  24074. }
  24075. const loadedSteeringData = {
  24076. steeringManifest: steeringData,
  24077. url: url2.toString()
  24078. };
  24079. this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  24080. if (pathwayPriority) {
  24081. this.updatePathwayPriority(pathwayPriority);
  24082. }
  24083. },
  24084. onError: (error2, context2, networkDetails, stats) => {
  24085. this.log(`Error loading steering manifest: ${error2.code} ${error2.text} (${context2.url})`);
  24086. this.stopLoad();
  24087. if (error2.code === 410) {
  24088. this.enabled = false;
  24089. this.log(`Steering manifest ${context2.url} no longer available`);
  24090. return;
  24091. }
  24092. let ttl = this.timeToLoad * 1e3;
  24093. if (error2.code === 429) {
  24094. const loader = this.loader;
  24095. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === "function") {
  24096. const retryAfter = loader.getResponseHeader("Retry-After");
  24097. if (retryAfter) {
  24098. ttl = parseFloat(retryAfter) * 1e3;
  24099. }
  24100. }
  24101. this.log(`Steering manifest ${context2.url} rate limited`);
  24102. return;
  24103. }
  24104. this.scheduleRefresh(this.uri || context2.url, ttl);
  24105. },
  24106. onTimeout: (stats, context2, networkDetails) => {
  24107. this.log(`Timeout loading steering manifest (${context2.url})`);
  24108. this.scheduleRefresh(this.uri || context2.url);
  24109. }
  24110. };
  24111. this.log(`Requesting steering manifest: ${url2}`);
  24112. this.loader.load(context, loaderConfig, callbacks);
  24113. }
  24114. scheduleRefresh(uri, ttlMs = this.timeToLoad * 1e3) {
  24115. this.clearTimeout();
  24116. this.reloadTimer = self.setTimeout(() => {
  24117. var _this$hls;
  24118. const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;
  24119. if (media && !media.ended) {
  24120. this.loadSteeringManifest(uri);
  24121. return;
  24122. }
  24123. this.scheduleRefresh(uri, this.timeToLoad * 1e3);
  24124. }, ttlMs);
  24125. }
  24126. }
  24127. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  24128. if (!tracks) {
  24129. return;
  24130. }
  24131. Object.keys(groupCloneMap).forEach((audioGroupId) => {
  24132. const clonedTracks = tracks.filter((track) => track.groupId === audioGroupId).map((track) => {
  24133. const clonedTrack = _extends({}, track);
  24134. clonedTrack.details = void 0;
  24135. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  24136. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs["STABLE-RENDITION-ID"], "PER-RENDITION-URIS", uriReplacement);
  24137. clonedTrack.groupId = clonedTrack.attrs["GROUP-ID"] = groupCloneMap[audioGroupId];
  24138. clonedTrack.attrs["PATHWAY-ID"] = cloneId;
  24139. return clonedTrack;
  24140. });
  24141. tracks.push(...clonedTracks);
  24142. });
  24143. }
  24144. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  24145. const {
  24146. HOST: host,
  24147. PARAMS: params,
  24148. [perOptionKey]: perOptionUris
  24149. } = uriReplacement;
  24150. let perVariantUri;
  24151. if (stableId) {
  24152. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  24153. if (perVariantUri) {
  24154. uri = perVariantUri;
  24155. }
  24156. }
  24157. const url2 = new self.URL(uri);
  24158. if (host && !perVariantUri) {
  24159. url2.host = host;
  24160. }
  24161. if (params) {
  24162. Object.keys(params).sort().forEach((key) => {
  24163. if (key) {
  24164. url2.searchParams.set(key, params[key]);
  24165. }
  24166. });
  24167. }
  24168. return url2.href;
  24169. }
  24170. function addEventListener(el, type, listener) {
  24171. removeEventListener(el, type, listener);
  24172. el.addEventListener(type, listener);
  24173. }
  24174. function removeEventListener(el, type, listener) {
  24175. el.removeEventListener(type, listener);
  24176. }
  24177. class EMEController extends Logger {
  24178. constructor(hls) {
  24179. super("eme", hls.logger);
  24180. this.hls = void 0;
  24181. this.config = void 0;
  24182. this.media = null;
  24183. this.keyFormatPromise = null;
  24184. this.keySystemAccessPromises = {};
  24185. this._requestLicenseFailureCount = 0;
  24186. this.mediaKeySessions = [];
  24187. this.keyIdToKeySessionPromise = {};
  24188. this.mediaKeys = null;
  24189. this.setMediaKeysQueue = EMEController.CDMCleanupPromise ? [EMEController.CDMCleanupPromise] : [];
  24190. this.onWaitingForKey = (event) => {
  24191. this.log(`"${event.type}" event`);
  24192. };
  24193. this.hls = hls;
  24194. this.config = hls.config;
  24195. this.registerListeners();
  24196. }
  24197. destroy() {
  24198. this.onDestroying();
  24199. this.onMediaDetached();
  24200. const config2 = this.config;
  24201. config2.requestMediaKeySystemAccessFunc = null;
  24202. config2.licenseXhrSetup = config2.licenseResponseCallback = void 0;
  24203. config2.drmSystems = config2.drmSystemOptions = {};
  24204. this.hls = this.config = this.keyIdToKeySessionPromise = null;
  24205. this.onWaitingForKey = null;
  24206. }
  24207. registerListeners() {
  24208. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  24209. this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  24210. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24211. this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  24212. this.hls.on(Events.DESTROYING, this.onDestroying, this);
  24213. }
  24214. unregisterListeners() {
  24215. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  24216. this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  24217. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24218. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  24219. this.hls.off(Events.DESTROYING, this.onDestroying, this);
  24220. }
  24221. getLicenseServerUrl(keySystem) {
  24222. const {
  24223. drmSystems,
  24224. widevineLicenseUrl
  24225. } = this.config;
  24226. const keySystemConfiguration = drmSystems[keySystem];
  24227. if (keySystemConfiguration) {
  24228. return keySystemConfiguration.licenseUrl;
  24229. }
  24230. if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {
  24231. return widevineLicenseUrl;
  24232. }
  24233. }
  24234. getLicenseServerUrlOrThrow(keySystem) {
  24235. const url2 = this.getLicenseServerUrl(keySystem);
  24236. if (url2 === void 0) {
  24237. throw new Error(`no license server URL configured for key-system "${keySystem}"`);
  24238. }
  24239. return url2;
  24240. }
  24241. getServerCertificateUrl(keySystem) {
  24242. const {
  24243. drmSystems
  24244. } = this.config;
  24245. const keySystemConfiguration = drmSystems[keySystem];
  24246. if (keySystemConfiguration) {
  24247. return keySystemConfiguration.serverCertificateUrl;
  24248. } else {
  24249. this.log(`No Server Certificate in config.drmSystems["${keySystem}"]`);
  24250. }
  24251. }
  24252. attemptKeySystemAccess(keySystemsToAttempt) {
  24253. const levels = this.hls.levels;
  24254. const uniqueCodec = (value2, i2, a2) => !!value2 && a2.indexOf(value2) === i2;
  24255. const audioCodecs = levels.map((level) => level.audioCodec).filter(uniqueCodec);
  24256. const videoCodecs = levels.map((level) => level.videoCodec).filter(uniqueCodec);
  24257. if (audioCodecs.length + videoCodecs.length === 0) {
  24258. videoCodecs.push("avc1.42e01e");
  24259. }
  24260. return new Promise((resolve, reject) => {
  24261. const attempt = (keySystems) => {
  24262. const keySystem = keySystems.shift();
  24263. this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then((mediaKeys) => resolve({
  24264. keySystem,
  24265. mediaKeys
  24266. })).catch((error2) => {
  24267. if (keySystems.length) {
  24268. attempt(keySystems);
  24269. } else if (error2 instanceof EMEKeyError) {
  24270. reject(error2);
  24271. } else {
  24272. reject(new EMEKeyError({
  24273. type: ErrorTypes.KEY_SYSTEM_ERROR,
  24274. details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  24275. error: error2,
  24276. fatal: true
  24277. }, error2.message));
  24278. }
  24279. });
  24280. };
  24281. attempt(keySystemsToAttempt);
  24282. });
  24283. }
  24284. requestMediaKeySystemAccess(keySystem, supportedConfigurations) {
  24285. const {
  24286. requestMediaKeySystemAccessFunc
  24287. } = this.config;
  24288. if (!(typeof requestMediaKeySystemAccessFunc === "function")) {
  24289. let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;
  24290. if (requestMediaKeySystemAccess === null && self.location.protocol === "http:") {
  24291. errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;
  24292. }
  24293. return Promise.reject(new Error(errMessage));
  24294. }
  24295. return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);
  24296. }
  24297. getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) {
  24298. const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions);
  24299. const keySystemAccessPromises = this.keySystemAccessPromises[keySystem];
  24300. let keySystemAccess = keySystemAccessPromises == null ? void 0 : keySystemAccessPromises.keySystemAccess;
  24301. if (!keySystemAccess) {
  24302. this.log(`Requesting encrypted media "${keySystem}" key-system access with config: ${stringify(mediaKeySystemConfigs)}`);
  24303. keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
  24304. const _keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = {
  24305. keySystemAccess
  24306. };
  24307. keySystemAccess.catch((error2) => {
  24308. this.log(`Failed to obtain access to key-system "${keySystem}": ${error2}`);
  24309. });
  24310. return keySystemAccess.then((mediaKeySystemAccess) => {
  24311. this.log(`Access for key-system "${mediaKeySystemAccess.keySystem}" obtained`);
  24312. const certificateRequest = this.fetchServerCertificate(keySystem);
  24313. this.log(`Create media-keys for "${keySystem}"`);
  24314. _keySystemAccessPromises.mediaKeys = mediaKeySystemAccess.createMediaKeys().then((mediaKeys) => {
  24315. this.log(`Media-keys created for "${keySystem}"`);
  24316. _keySystemAccessPromises.hasMediaKeys = true;
  24317. return certificateRequest.then((certificate) => {
  24318. if (certificate) {
  24319. return this.setMediaKeysServerCertificate(mediaKeys, keySystem, certificate);
  24320. }
  24321. return mediaKeys;
  24322. });
  24323. });
  24324. _keySystemAccessPromises.mediaKeys.catch((error2) => {
  24325. this.error(`Failed to create media-keys for "${keySystem}"}: ${error2}`);
  24326. });
  24327. return _keySystemAccessPromises.mediaKeys;
  24328. });
  24329. }
  24330. return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys);
  24331. }
  24332. createMediaKeySessionContext({
  24333. decryptdata,
  24334. keySystem,
  24335. mediaKeys
  24336. }) {
  24337. this.log(`Creating key-system session "${keySystem}" keyId: ${Hex.hexDump(decryptdata.keyId || [])}`);
  24338. const mediaKeysSession = mediaKeys.createSession();
  24339. const mediaKeySessionContext = {
  24340. decryptdata,
  24341. keySystem,
  24342. mediaKeys,
  24343. mediaKeysSession,
  24344. keyStatus: "status-pending"
  24345. };
  24346. this.mediaKeySessions.push(mediaKeySessionContext);
  24347. return mediaKeySessionContext;
  24348. }
  24349. renewKeySession(mediaKeySessionContext) {
  24350. const decryptdata = mediaKeySessionContext.decryptdata;
  24351. if (decryptdata.pssh) {
  24352. const keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext);
  24353. const keyId = this.getKeyIdString(decryptdata);
  24354. const scheme = "cenc";
  24355. this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh.buffer, "expired");
  24356. } else {
  24357. this.warn(`Could not renew expired session. Missing pssh initData.`);
  24358. }
  24359. this.removeSession(mediaKeySessionContext);
  24360. }
  24361. getKeyIdString(decryptdata) {
  24362. if (!decryptdata) {
  24363. throw new Error("Could not read keyId of undefined decryptdata");
  24364. }
  24365. if (decryptdata.keyId === null) {
  24366. throw new Error("keyId is null");
  24367. }
  24368. return Hex.hexDump(decryptdata.keyId);
  24369. }
  24370. updateKeySession(mediaKeySessionContext, data) {
  24371. var _mediaKeySessionConte;
  24372. const keySession = mediaKeySessionContext.mediaKeysSession;
  24373. this.log(`Updating key-session "${keySession.sessionId}" for keyID ${Hex.hexDump(((_mediaKeySessionConte = mediaKeySessionContext.decryptdata) == null ? void 0 : _mediaKeySessionConte.keyId) || [])}
  24374. } (data length: ${data ? data.byteLength : data})`);
  24375. return keySession.update(data);
  24376. }
  24377. getSelectedKeySystemFormats() {
  24378. return Object.keys(this.keySystemAccessPromises).map((keySystem) => ({
  24379. keySystem,
  24380. hasMediaKeys: this.keySystemAccessPromises[keySystem].hasMediaKeys
  24381. })).filter(({
  24382. hasMediaKeys
  24383. }) => !!hasMediaKeys).map(({
  24384. keySystem
  24385. }) => keySystemDomainToKeySystemFormat(keySystem)).filter((keySystem) => !!keySystem);
  24386. }
  24387. getKeySystemAccess(keySystemsToAttempt) {
  24388. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  24389. keySystem,
  24390. mediaKeys
  24391. }) => {
  24392. return this.attemptSetMediaKeys(keySystem, mediaKeys);
  24393. });
  24394. }
  24395. selectKeySystem(keySystemsToAttempt) {
  24396. return new Promise((resolve, reject) => {
  24397. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  24398. keySystem
  24399. }) => {
  24400. const keySystemFormat = keySystemDomainToKeySystemFormat(keySystem);
  24401. if (keySystemFormat) {
  24402. resolve(keySystemFormat);
  24403. } else {
  24404. reject(new Error(`Unable to find format for key-system "${keySystem}"`));
  24405. }
  24406. }).catch(reject);
  24407. });
  24408. }
  24409. selectKeySystemFormat(frag) {
  24410. const keyFormats = Object.keys(frag.levelkeys || {});
  24411. if (!this.keyFormatPromise) {
  24412. this.log(`Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${frag.level}) key formats ${keyFormats.join(", ")}`);
  24413. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  24414. }
  24415. return this.keyFormatPromise;
  24416. }
  24417. getKeyFormatPromise(keyFormats) {
  24418. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  24419. const keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter((value2) => !!value2 && keySystemsInConfig.indexOf(value2) !== -1);
  24420. return this.selectKeySystem(keySystemsToAttempt);
  24421. }
  24422. loadKey(data) {
  24423. const decryptdata = data.keyInfo.decryptdata;
  24424. const keyId = this.getKeyIdString(decryptdata);
  24425. const keyDetails = `(keyId: ${keyId} format: "${decryptdata.keyFormat}" method: ${decryptdata.method} uri: ${decryptdata.uri})`;
  24426. this.log(`Starting session for key ${keyDetails}`);
  24427. let keyContextPromise = this.keyIdToKeySessionPromise[keyId];
  24428. if (!keyContextPromise) {
  24429. keyContextPromise = this.getKeySystemForKeyPromise(decryptdata).then(({
  24430. keySystem,
  24431. mediaKeys
  24432. }) => {
  24433. this.throwIfDestroyed();
  24434. this.log(`Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`);
  24435. return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {
  24436. this.throwIfDestroyed();
  24437. return this.createMediaKeySessionContext({
  24438. keySystem,
  24439. mediaKeys,
  24440. decryptdata
  24441. });
  24442. });
  24443. });
  24444. const keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] = keyContextPromise.then((keySessionContext) => {
  24445. const scheme = "cenc";
  24446. const initData = decryptdata.pssh ? decryptdata.pssh.buffer : null;
  24447. return this.generateRequestWithPreferredKeySession(keySessionContext, scheme, initData, "playlist-key");
  24448. });
  24449. keySessionContextPromise.catch((error2) => this.handleError(error2));
  24450. }
  24451. return keyContextPromise;
  24452. }
  24453. throwIfDestroyed(message = "Invalid state") {
  24454. if (!this.hls) {
  24455. throw new Error("invalid state");
  24456. }
  24457. }
  24458. handleError(error2) {
  24459. if (!this.hls) {
  24460. return;
  24461. }
  24462. this.error(error2.message);
  24463. if (error2 instanceof EMEKeyError) {
  24464. this.hls.trigger(Events.ERROR, error2.data);
  24465. } else {
  24466. this.hls.trigger(Events.ERROR, {
  24467. type: ErrorTypes.KEY_SYSTEM_ERROR,
  24468. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  24469. error: error2,
  24470. fatal: true
  24471. });
  24472. }
  24473. }
  24474. getKeySystemForKeyPromise(decryptdata) {
  24475. const keyId = this.getKeyIdString(decryptdata);
  24476. const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];
  24477. if (!mediaKeySessionContext) {
  24478. const keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat);
  24479. const keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config);
  24480. return this.attemptKeySystemAccess(keySystemsToAttempt);
  24481. }
  24482. return mediaKeySessionContext;
  24483. }
  24484. getKeySystemSelectionPromise(keySystemsToAttempt) {
  24485. if (!keySystemsToAttempt.length) {
  24486. keySystemsToAttempt = getKeySystemsForConfig(this.config);
  24487. }
  24488. if (keySystemsToAttempt.length === 0) {
  24489. throw new EMEKeyError({
  24490. type: ErrorTypes.KEY_SYSTEM_ERROR,
  24491. details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,
  24492. fatal: true
  24493. }, `Missing key-system license configuration options ${stringify({
  24494. drmSystems: this.config.drmSystems
  24495. })}`);
  24496. }
  24497. return this.attemptKeySystemAccess(keySystemsToAttempt);
  24498. }
  24499. attemptSetMediaKeys(keySystem, mediaKeys) {
  24500. if (this.mediaKeys === mediaKeys) {
  24501. return Promise.resolve();
  24502. }
  24503. const queue = this.setMediaKeysQueue.slice();
  24504. this.log(`Setting media-keys for "${keySystem}"`);
  24505. const setMediaKeysPromise = Promise.all(queue).then(() => {
  24506. if (!this.media) {
  24507. this.mediaKeys = null;
  24508. throw new Error("Attempted to set mediaKeys without media element attached");
  24509. }
  24510. return this.media.setMediaKeys(mediaKeys);
  24511. });
  24512. this.mediaKeys = mediaKeys;
  24513. this.setMediaKeysQueue.push(setMediaKeysPromise);
  24514. return setMediaKeysPromise.then(() => {
  24515. this.log(`Media-keys set for "${keySystem}"`);
  24516. queue.push(setMediaKeysPromise);
  24517. this.setMediaKeysQueue = this.setMediaKeysQueue.filter((p2) => queue.indexOf(p2) === -1);
  24518. });
  24519. }
  24520. generateRequestWithPreferredKeySession(context, initDataType, initData, reason) {
  24521. var _this$config$drmSyste, _this$config$drmSyste2;
  24522. 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;
  24523. if (generateRequestFilter) {
  24524. try {
  24525. const mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData, context);
  24526. if (!mappedInitData) {
  24527. throw new Error("Invalid response from configured generateRequest filter");
  24528. }
  24529. initDataType = mappedInitData.initDataType;
  24530. initData = mappedInitData.initData ? mappedInitData.initData : null;
  24531. context.decryptdata.pssh = initData ? new Uint8Array(initData) : null;
  24532. } catch (error2) {
  24533. var _this$hls;
  24534. this.warn(error2.message);
  24535. if ((_this$hls = this.hls) != null && _this$hls.config.debug) {
  24536. throw error2;
  24537. }
  24538. }
  24539. }
  24540. if (initData === null) {
  24541. this.log(`Skipping key-session request for "${reason}" (no initData)`);
  24542. return Promise.resolve(context);
  24543. }
  24544. const keyId = this.getKeyIdString(context.decryptdata);
  24545. this.log(`Generating key-session request for "${reason}": ${keyId} (init data type: ${initDataType} length: ${initData ? initData.byteLength : null})`);
  24546. const licenseStatus = new EventEmitter();
  24547. const onmessage = context._onmessage = (event) => {
  24548. const keySession = context.mediaKeysSession;
  24549. if (!keySession) {
  24550. licenseStatus.emit("error", new Error("invalid state"));
  24551. return;
  24552. }
  24553. const {
  24554. messageType,
  24555. message
  24556. } = event;
  24557. this.log(`"${messageType}" message event for session "${keySession.sessionId}" message size: ${message.byteLength}`);
  24558. if (messageType === "license-request" || messageType === "license-renewal") {
  24559. this.renewLicense(context, message).catch((error2) => {
  24560. if (licenseStatus.eventNames().length) {
  24561. licenseStatus.emit("error", error2);
  24562. } else {
  24563. this.handleError(error2);
  24564. }
  24565. });
  24566. } else if (messageType === "license-release") {
  24567. if (context.keySystem === KeySystems.FAIRPLAY) {
  24568. this.updateKeySession(context, strToUtf8array("acknowledged"));
  24569. this.removeSession(context);
  24570. }
  24571. } else {
  24572. this.warn(`unhandled media key message type "${messageType}"`);
  24573. }
  24574. };
  24575. const onkeystatuseschange = context._onkeystatuseschange = (event) => {
  24576. const keySession = context.mediaKeysSession;
  24577. if (!keySession) {
  24578. licenseStatus.emit("error", new Error("invalid state"));
  24579. return;
  24580. }
  24581. this.onKeyStatusChange(context);
  24582. const keyStatus = context.keyStatus;
  24583. licenseStatus.emit("keyStatus", keyStatus);
  24584. if (keyStatus === "expired") {
  24585. this.warn(`${context.keySystem} expired for key ${keyId}`);
  24586. this.renewKeySession(context);
  24587. }
  24588. };
  24589. addEventListener(context.mediaKeysSession, "message", onmessage);
  24590. addEventListener(context.mediaKeysSession, "keystatuseschange", onkeystatuseschange);
  24591. const keyUsablePromise = new Promise((resolve, reject) => {
  24592. licenseStatus.on("error", reject);
  24593. licenseStatus.on("keyStatus", (keyStatus) => {
  24594. if (keyStatus.startsWith("usable")) {
  24595. resolve();
  24596. } else if (keyStatus === "output-restricted") {
  24597. reject(new EMEKeyError({
  24598. type: ErrorTypes.KEY_SYSTEM_ERROR,
  24599. details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,
  24600. fatal: false
  24601. }, "HDCP level output restricted"));
  24602. } else if (keyStatus === "internal-error") {
  24603. reject(new EMEKeyError({
  24604. type: ErrorTypes.KEY_SYSTEM_ERROR,
  24605. details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,
  24606. fatal: true
  24607. }, `key status changed to "${keyStatus}"`));
  24608. } else if (keyStatus === "expired") {
  24609. reject(new Error("key expired while generating request"));
  24610. } else {
  24611. this.warn(`unhandled key status change "${keyStatus}"`);
  24612. }
  24613. });
  24614. });
  24615. return context.mediaKeysSession.generateRequest(initDataType, initData).then(() => {
  24616. var _context$mediaKeysSes;
  24617. this.log(`Request generated for key-session "${(_context$mediaKeysSes = context.mediaKeysSession) == null ? void 0 : _context$mediaKeysSes.sessionId}" keyId: ${keyId}`);
  24618. }).catch((error2) => {
  24619. throw new EMEKeyError({
  24620. type: ErrorTypes.KEY_SYSTEM_ERROR,
  24621. details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
  24622. error: error2,
  24623. fatal: false
  24624. }, `Error generating key-session request: ${error2}`);
  24625. }).then(() => keyUsablePromise).catch((error2) => {
  24626. licenseStatus.removeAllListeners();
  24627. this.removeSession(context);
  24628. throw error2;
  24629. }).then(() => {
  24630. licenseStatus.removeAllListeners();
  24631. return context;
  24632. });
  24633. }
  24634. onKeyStatusChange(mediaKeySessionContext) {
  24635. mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach((status2, keyId) => {
  24636. if (typeof keyId === "string" && typeof status2 === "object") {
  24637. const temp = keyId;
  24638. keyId = status2;
  24639. status2 = temp;
  24640. }
  24641. 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}`);
  24642. mediaKeySessionContext.keyStatus = status2;
  24643. });
  24644. }
  24645. fetchServerCertificate(keySystem) {
  24646. const config2 = this.config;
  24647. const Loader = config2.loader;
  24648. const certLoader = new Loader(config2);
  24649. const url2 = this.getServerCertificateUrl(keySystem);
  24650. if (!url2) {
  24651. return Promise.resolve();
  24652. }
  24653. this.log(`Fetching server certificate for "${keySystem}"`);
  24654. return new Promise((resolve, reject) => {
  24655. const loaderContext = {
  24656. responseType: "arraybuffer",
  24657. url: url2
  24658. };
  24659. const loadPolicy = config2.certLoadPolicy.default;
  24660. const loaderConfig = {
  24661. loadPolicy,
  24662. timeout: loadPolicy.maxLoadTimeMs,
  24663. maxRetry: 0,
  24664. retryDelay: 0,
  24665. maxRetryDelay: 0
  24666. };
  24667. const loaderCallbacks = {
  24668. onSuccess: (response, stats, context, networkDetails) => {
  24669. resolve(response.data);
  24670. },
  24671. onError: (response, contex, networkDetails, stats) => {
  24672. reject(new EMEKeyError({
  24673. type: ErrorTypes.KEY_SYSTEM_ERROR,
  24674. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  24675. fatal: true,
  24676. networkDetails,
  24677. response: _objectSpread2({
  24678. url: loaderContext.url,
  24679. data: void 0
  24680. }, response)
  24681. }, `"${keySystem}" certificate request failed (${url2}). Status: ${response.code} (${response.text})`));
  24682. },
  24683. onTimeout: (stats, context, networkDetails) => {
  24684. reject(new EMEKeyError({
  24685. type: ErrorTypes.KEY_SYSTEM_ERROR,
  24686. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  24687. fatal: true,
  24688. networkDetails,
  24689. response: {
  24690. url: loaderContext.url,
  24691. data: void 0
  24692. }
  24693. }, `"${keySystem}" certificate request timed out (${url2})`));
  24694. },
  24695. onAbort: (stats, context, networkDetails) => {
  24696. reject(new Error("aborted"));
  24697. }
  24698. };
  24699. certLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  24700. });
  24701. }
  24702. setMediaKeysServerCertificate(mediaKeys, keySystem, cert) {
  24703. return new Promise((resolve, reject) => {
  24704. mediaKeys.setServerCertificate(cert).then((success) => {
  24705. this.log(`setServerCertificate ${success ? "success" : "not supported by CDM"} (${cert == null ? void 0 : cert.byteLength}) on "${keySystem}"`);
  24706. resolve(mediaKeys);
  24707. }).catch((error2) => {
  24708. reject(new EMEKeyError({
  24709. type: ErrorTypes.KEY_SYSTEM_ERROR,
  24710. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,
  24711. error: error2,
  24712. fatal: true
  24713. }, error2.message));
  24714. });
  24715. });
  24716. }
  24717. renewLicense(context, keyMessage) {
  24718. return this.requestLicense(context, new Uint8Array(keyMessage)).then((data) => {
  24719. return this.updateKeySession(context, new Uint8Array(data)).catch((error2) => {
  24720. throw new EMEKeyError({
  24721. type: ErrorTypes.KEY_SYSTEM_ERROR,
  24722. details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,
  24723. error: error2,
  24724. fatal: true
  24725. }, error2.message);
  24726. });
  24727. });
  24728. }
  24729. unpackPlayReadyKeyMessage(xhr, licenseChallenge) {
  24730. const xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer));
  24731. if (!xmlString.includes("PlayReadyKeyMessage")) {
  24732. xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  24733. return licenseChallenge;
  24734. }
  24735. const keyMessageXml = new DOMParser().parseFromString(xmlString, "application/xml");
  24736. const headers = keyMessageXml.querySelectorAll("HttpHeader");
  24737. if (headers.length > 0) {
  24738. let header;
  24739. for (let i2 = 0, len = headers.length; i2 < len; i2++) {
  24740. var _header$querySelector, _header$querySelector2;
  24741. header = headers[i2];
  24742. const name = (_header$querySelector = header.querySelector("name")) == null ? void 0 : _header$querySelector.textContent;
  24743. const value2 = (_header$querySelector2 = header.querySelector("value")) == null ? void 0 : _header$querySelector2.textContent;
  24744. if (name && value2) {
  24745. xhr.setRequestHeader(name, value2);
  24746. }
  24747. }
  24748. }
  24749. const challengeElement = keyMessageXml.querySelector("Challenge");
  24750. const challengeText = challengeElement == null ? void 0 : challengeElement.textContent;
  24751. if (!challengeText) {
  24752. throw new Error(`Cannot find <Challenge> in key message`);
  24753. }
  24754. return strToUtf8array(atob(challengeText));
  24755. }
  24756. setupLicenseXHR(xhr, url2, keysListItem, licenseChallenge) {
  24757. const licenseXhrSetup = this.config.licenseXhrSetup;
  24758. if (!licenseXhrSetup) {
  24759. xhr.open("POST", url2, true);
  24760. return Promise.resolve({
  24761. xhr,
  24762. licenseChallenge
  24763. });
  24764. }
  24765. return Promise.resolve().then(() => {
  24766. if (!keysListItem.decryptdata) {
  24767. throw new Error("Key removed");
  24768. }
  24769. return licenseXhrSetup.call(this.hls, xhr, url2, keysListItem, licenseChallenge);
  24770. }).catch((error2) => {
  24771. if (!keysListItem.decryptdata) {
  24772. throw error2;
  24773. }
  24774. xhr.open("POST", url2, true);
  24775. return licenseXhrSetup.call(this.hls, xhr, url2, keysListItem, licenseChallenge);
  24776. }).then((licenseXhrSetupResult) => {
  24777. if (!xhr.readyState) {
  24778. xhr.open("POST", url2, true);
  24779. }
  24780. const finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge;
  24781. return {
  24782. xhr,
  24783. licenseChallenge: finalLicenseChallenge
  24784. };
  24785. });
  24786. }
  24787. requestLicense(keySessionContext, licenseChallenge) {
  24788. const keyLoadPolicy = this.config.keyLoadPolicy.default;
  24789. return new Promise((resolve, reject) => {
  24790. const url2 = this.getLicenseServerUrlOrThrow(keySessionContext.keySystem);
  24791. this.log(`Sending license request to URL: ${url2}`);
  24792. const xhr = new XMLHttpRequest();
  24793. xhr.responseType = "arraybuffer";
  24794. xhr.onreadystatechange = () => {
  24795. if (!this.hls || !keySessionContext.mediaKeysSession) {
  24796. return reject(new Error("invalid state"));
  24797. }
  24798. if (xhr.readyState === 4) {
  24799. if (xhr.status === 200) {
  24800. this._requestLicenseFailureCount = 0;
  24801. let data = xhr.response;
  24802. this.log(`License received ${data instanceof ArrayBuffer ? data.byteLength : data}`);
  24803. const licenseResponseCallback = this.config.licenseResponseCallback;
  24804. if (licenseResponseCallback) {
  24805. try {
  24806. data = licenseResponseCallback.call(this.hls, xhr, url2, keySessionContext);
  24807. } catch (error2) {
  24808. this.error(error2);
  24809. }
  24810. }
  24811. resolve(data);
  24812. } else {
  24813. const retryConfig = keyLoadPolicy.errorRetry;
  24814. const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;
  24815. this._requestLicenseFailureCount++;
  24816. if (this._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) {
  24817. reject(new EMEKeyError({
  24818. type: ErrorTypes.KEY_SYSTEM_ERROR,
  24819. details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  24820. fatal: true,
  24821. networkDetails: xhr,
  24822. response: {
  24823. url: url2,
  24824. data: void 0,
  24825. code: xhr.status,
  24826. text: xhr.statusText
  24827. }
  24828. }, `License Request XHR failed (${url2}). Status: ${xhr.status} (${xhr.statusText})`));
  24829. } else {
  24830. const attemptsLeft = maxNumRetry - this._requestLicenseFailureCount + 1;
  24831. this.warn(`Retrying license request, ${attemptsLeft} attempts left`);
  24832. this.requestLicense(keySessionContext, licenseChallenge).then(resolve, reject);
  24833. }
  24834. }
  24835. }
  24836. };
  24837. if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) {
  24838. keySessionContext.licenseXhr.abort();
  24839. }
  24840. keySessionContext.licenseXhr = xhr;
  24841. this.setupLicenseXHR(xhr, url2, keySessionContext, licenseChallenge).then(({
  24842. xhr: xhr2,
  24843. licenseChallenge: licenseChallenge2
  24844. }) => {
  24845. if (keySessionContext.keySystem == KeySystems.PLAYREADY) {
  24846. licenseChallenge2 = this.unpackPlayReadyKeyMessage(xhr2, licenseChallenge2);
  24847. }
  24848. xhr2.send(licenseChallenge2);
  24849. });
  24850. });
  24851. }
  24852. onDestroying() {
  24853. this.unregisterListeners();
  24854. this._clear();
  24855. }
  24856. onMediaAttached(event, data) {
  24857. if (!this.config.emeEnabled) {
  24858. return;
  24859. }
  24860. const media = data.media;
  24861. this.media = media;
  24862. addEventListener(media, "waitingforkey", this.onWaitingForKey);
  24863. }
  24864. onMediaDetached() {
  24865. const media = this.media;
  24866. if (media) {
  24867. removeEventListener(media, "waitingforkey", this.onWaitingForKey);
  24868. this.media = null;
  24869. this.mediaKeys = null;
  24870. }
  24871. }
  24872. _clear() {
  24873. var _media$setMediaKeys;
  24874. this._requestLicenseFailureCount = 0;
  24875. this.keyIdToKeySessionPromise = {};
  24876. if (!this.mediaKeys && !this.mediaKeySessions.length) {
  24877. return;
  24878. }
  24879. const media = this.media;
  24880. const mediaKeysList = this.mediaKeySessions.slice();
  24881. this.mediaKeySessions = [];
  24882. this.mediaKeys = null;
  24883. LevelKey.clearKeyUriToKeyIdMap();
  24884. const keySessionCount = mediaKeysList.length;
  24885. 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((error2) => {
  24886. var _this$hls2;
  24887. this.log(`Could not clear media keys: ${error2}`);
  24888. (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.trigger(Events.ERROR, {
  24889. type: ErrorTypes.OTHER_ERROR,
  24890. details: ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,
  24891. fatal: false,
  24892. error: new Error(`Could not clear media keys: ${error2}`)
  24893. });
  24894. }))).catch((error2) => {
  24895. var _this$hls3;
  24896. this.log(`Could not close sessions and clear media keys: ${error2}`);
  24897. (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.trigger(Events.ERROR, {
  24898. type: ErrorTypes.OTHER_ERROR,
  24899. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  24900. fatal: false,
  24901. error: new Error(`Could not close sessions and clear media keys: ${error2}`)
  24902. });
  24903. }).then(() => {
  24904. if (keySessionCount) {
  24905. this.log("finished closing key sessions and clearing media keys");
  24906. }
  24907. });
  24908. }
  24909. onManifestLoading() {
  24910. this.keyFormatPromise = null;
  24911. }
  24912. onManifestLoaded(event, {
  24913. sessionKeys
  24914. }) {
  24915. if (!sessionKeys || !this.config.emeEnabled) {
  24916. return;
  24917. }
  24918. if (!this.keyFormatPromise) {
  24919. const keyFormats = sessionKeys.reduce((formats, sessionKey) => {
  24920. if (formats.indexOf(sessionKey.keyFormat) === -1) {
  24921. formats.push(sessionKey.keyFormat);
  24922. }
  24923. return formats;
  24924. }, []);
  24925. this.log(`Selecting key-system from session-keys ${keyFormats.join(", ")}`);
  24926. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  24927. }
  24928. }
  24929. removeSession(mediaKeySessionContext) {
  24930. const {
  24931. mediaKeysSession,
  24932. licenseXhr
  24933. } = mediaKeySessionContext;
  24934. if (mediaKeysSession) {
  24935. this.log(`Remove licenses and keys and close session ${mediaKeysSession.sessionId}`);
  24936. if (mediaKeySessionContext._onmessage) {
  24937. mediaKeysSession.removeEventListener("message", mediaKeySessionContext._onmessage);
  24938. mediaKeySessionContext._onmessage = void 0;
  24939. }
  24940. if (mediaKeySessionContext._onkeystatuseschange) {
  24941. mediaKeysSession.removeEventListener("keystatuseschange", mediaKeySessionContext._onkeystatuseschange);
  24942. mediaKeySessionContext._onkeystatuseschange = void 0;
  24943. }
  24944. if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {
  24945. licenseXhr.abort();
  24946. }
  24947. mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = void 0;
  24948. const index2 = this.mediaKeySessions.indexOf(mediaKeySessionContext);
  24949. if (index2 > -1) {
  24950. this.mediaKeySessions.splice(index2, 1);
  24951. }
  24952. const {
  24953. drmSystemOptions
  24954. } = this.config;
  24955. const removePromise = isPersistentSessionType(drmSystemOptions) ? new Promise((resolve, reject) => {
  24956. self.setTimeout(() => reject(new Error(`MediaKeySession.remove() timeout`)), 8e3);
  24957. mediaKeysSession.remove().then(resolve);
  24958. }) : Promise.resolve();
  24959. return removePromise.catch((error2) => {
  24960. var _this$hls4;
  24961. this.log(`Could not remove session: ${error2}`);
  24962. (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.trigger(Events.ERROR, {
  24963. type: ErrorTypes.OTHER_ERROR,
  24964. details: ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,
  24965. fatal: false,
  24966. error: new Error(`Could not remove session: ${error2}`)
  24967. });
  24968. }).then(() => {
  24969. return mediaKeysSession.close();
  24970. }).catch((error2) => {
  24971. var _this$hls5;
  24972. this.log(`Could not close session: ${error2}`);
  24973. (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.trigger(Events.ERROR, {
  24974. type: ErrorTypes.OTHER_ERROR,
  24975. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  24976. fatal: false,
  24977. error: new Error(`Could not close session: ${error2}`)
  24978. });
  24979. });
  24980. }
  24981. }
  24982. }
  24983. EMEController.CDMCleanupPromise = void 0;
  24984. class EMEKeyError extends Error {
  24985. constructor(data, message) {
  24986. super(message);
  24987. this.data = void 0;
  24988. data.error || (data.error = new Error(message));
  24989. this.data = data;
  24990. data.err = data.error;
  24991. }
  24992. }
  24993. class FPSController {
  24994. constructor(hls) {
  24995. this.hls = void 0;
  24996. this.isVideoPlaybackQualityAvailable = false;
  24997. this.timer = void 0;
  24998. this.media = null;
  24999. this.lastTime = void 0;
  25000. this.lastDroppedFrames = 0;
  25001. this.lastDecodedFrames = 0;
  25002. this.streamController = void 0;
  25003. this.hls = hls;
  25004. this.registerListeners();
  25005. }
  25006. setStreamController(streamController) {
  25007. this.streamController = streamController;
  25008. }
  25009. registerListeners() {
  25010. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  25011. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25012. }
  25013. unregisterListeners() {
  25014. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  25015. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25016. }
  25017. destroy() {
  25018. if (this.timer) {
  25019. clearInterval(this.timer);
  25020. }
  25021. this.unregisterListeners();
  25022. this.isVideoPlaybackQualityAvailable = false;
  25023. this.media = null;
  25024. }
  25025. onMediaAttaching(event, data) {
  25026. const config2 = this.hls.config;
  25027. if (config2.capLevelOnFPSDrop) {
  25028. const media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  25029. this.media = media;
  25030. if (media && typeof media.getVideoPlaybackQuality === "function") {
  25031. this.isVideoPlaybackQualityAvailable = true;
  25032. }
  25033. self.clearInterval(this.timer);
  25034. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config2.fpsDroppedMonitoringPeriod);
  25035. }
  25036. }
  25037. onMediaDetaching() {
  25038. this.media = null;
  25039. }
  25040. checkFPS(video2, decodedFrames, droppedFrames) {
  25041. const currentTime = performance.now();
  25042. if (decodedFrames) {
  25043. if (this.lastTime) {
  25044. const currentPeriod = currentTime - this.lastTime;
  25045. const currentDropped = droppedFrames - this.lastDroppedFrames;
  25046. const currentDecoded = decodedFrames - this.lastDecodedFrames;
  25047. const droppedFPS = 1e3 * currentDropped / currentPeriod;
  25048. const hls = this.hls;
  25049. hls.trigger(Events.FPS_DROP, {
  25050. currentDropped,
  25051. currentDecoded,
  25052. totalDroppedFrames: droppedFrames
  25053. });
  25054. if (droppedFPS > 0) {
  25055. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  25056. let currentLevel = hls.currentLevel;
  25057. hls.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: " + currentLevel);
  25058. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  25059. currentLevel = currentLevel - 1;
  25060. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  25061. level: currentLevel,
  25062. droppedLevel: hls.currentLevel
  25063. });
  25064. hls.autoLevelCapping = currentLevel;
  25065. this.streamController.nextLevelSwitch();
  25066. }
  25067. }
  25068. }
  25069. }
  25070. this.lastTime = currentTime;
  25071. this.lastDroppedFrames = droppedFrames;
  25072. this.lastDecodedFrames = decodedFrames;
  25073. }
  25074. }
  25075. checkFPSInterval() {
  25076. const video2 = this.media;
  25077. if (video2) {
  25078. if (this.isVideoPlaybackQualityAvailable) {
  25079. const videoPlaybackQuality = video2.getVideoPlaybackQuality();
  25080. this.checkFPS(video2, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  25081. } else {
  25082. this.checkFPS(video2, video2.webkitDecodedFrameCount, video2.webkitDroppedFrameCount);
  25083. }
  25084. }
  25085. }
  25086. }
  25087. function sendAddTrackEvent(track, videoEl) {
  25088. let event;
  25089. try {
  25090. event = new Event("addtrack");
  25091. } catch (err) {
  25092. event = document.createEvent("Event");
  25093. event.initEvent("addtrack", false, false);
  25094. }
  25095. event.track = track;
  25096. videoEl.dispatchEvent(event);
  25097. }
  25098. function addCueToTrack(track, cue) {
  25099. const mode = track.mode;
  25100. if (mode === "disabled") {
  25101. track.mode = "hidden";
  25102. }
  25103. if (track.cues && !track.cues.getCueById(cue.id)) {
  25104. try {
  25105. track.addCue(cue);
  25106. if (!track.cues.getCueById(cue.id)) {
  25107. throw new Error(`addCue is failed for: ${cue}`);
  25108. }
  25109. } catch (err) {
  25110. logger.debug(`[texttrack-utils]: ${err}`);
  25111. try {
  25112. const textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  25113. textTrackCue.id = cue.id;
  25114. track.addCue(textTrackCue);
  25115. } catch (err2) {
  25116. logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`);
  25117. }
  25118. }
  25119. }
  25120. if (mode === "disabled") {
  25121. track.mode = mode;
  25122. }
  25123. }
  25124. function clearCurrentCues(track, enterHandler) {
  25125. const mode = track.mode;
  25126. if (mode === "disabled") {
  25127. track.mode = "hidden";
  25128. }
  25129. if (track.cues) {
  25130. for (let i2 = track.cues.length; i2--; ) {
  25131. if (enterHandler) {
  25132. track.cues[i2].removeEventListener("enter", enterHandler);
  25133. }
  25134. track.removeCue(track.cues[i2]);
  25135. }
  25136. }
  25137. if (mode === "disabled") {
  25138. track.mode = mode;
  25139. }
  25140. }
  25141. function removeCuesInRange(track, start, end, predicate) {
  25142. const mode = track.mode;
  25143. if (mode === "disabled") {
  25144. track.mode = "hidden";
  25145. }
  25146. if (track.cues && track.cues.length > 0) {
  25147. const cues = getCuesInRange(track.cues, start, end);
  25148. for (let i2 = 0; i2 < cues.length; i2++) {
  25149. if (!predicate || predicate(cues[i2])) {
  25150. track.removeCue(cues[i2]);
  25151. }
  25152. }
  25153. }
  25154. if (mode === "disabled") {
  25155. track.mode = mode;
  25156. }
  25157. }
  25158. function getFirstCueIndexFromTime(cues, time) {
  25159. if (time <= cues[0].startTime) {
  25160. return 0;
  25161. }
  25162. const len = cues.length - 1;
  25163. if (time > cues[len].endTime) {
  25164. return -1;
  25165. }
  25166. let left = 0;
  25167. let right = len;
  25168. let mid;
  25169. while (left <= right) {
  25170. mid = Math.floor((right + left) / 2);
  25171. if (time < cues[mid].startTime) {
  25172. right = mid - 1;
  25173. } else if (time > cues[mid].startTime && left < len) {
  25174. left = mid + 1;
  25175. } else {
  25176. return mid;
  25177. }
  25178. }
  25179. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  25180. }
  25181. function getCuesInRange(cues, start, end) {
  25182. const cuesFound = [];
  25183. const firstCueInRange = getFirstCueIndexFromTime(cues, start);
  25184. if (firstCueInRange > -1) {
  25185. for (let i2 = firstCueInRange, len = cues.length; i2 < len; i2++) {
  25186. const cue = cues[i2];
  25187. if (cue.startTime >= start && cue.endTime <= end) {
  25188. cuesFound.push(cue);
  25189. } else if (cue.startTime > end) {
  25190. return cuesFound;
  25191. }
  25192. }
  25193. }
  25194. return cuesFound;
  25195. }
  25196. function filterSubtitleTracks(textTrackList) {
  25197. const tracks = [];
  25198. for (let i2 = 0; i2 < textTrackList.length; i2++) {
  25199. const track = textTrackList[i2];
  25200. if ((track.kind === "subtitles" || track.kind === "captions") && track.label) {
  25201. tracks.push(textTrackList[i2]);
  25202. }
  25203. }
  25204. return tracks;
  25205. }
  25206. class SubtitleTrackController extends BasePlaylistController {
  25207. constructor(hls) {
  25208. super(hls, "subtitle-track-controller");
  25209. this.media = null;
  25210. this.tracks = [];
  25211. this.groupIds = null;
  25212. this.tracksInGroup = [];
  25213. this.trackId = -1;
  25214. this.currentTrack = null;
  25215. this.selectDefaultTrack = true;
  25216. this.queuedDefaultTrack = -1;
  25217. this.useTextTrackPolling = false;
  25218. this.subtitlePollingInterval = -1;
  25219. this._subtitleDisplay = true;
  25220. this.asyncPollTrackChange = () => this.pollTrackChange(0);
  25221. this.onTextTracksChanged = () => {
  25222. if (!this.useTextTrackPolling) {
  25223. self.clearInterval(this.subtitlePollingInterval);
  25224. }
  25225. if (!this.media || !this.hls.config.renderTextTracksNatively) {
  25226. return;
  25227. }
  25228. let textTrack = null;
  25229. const tracks = filterSubtitleTracks(this.media.textTracks);
  25230. for (let i2 = 0; i2 < tracks.length; i2++) {
  25231. if (tracks[i2].mode === "hidden") {
  25232. textTrack = tracks[i2];
  25233. } else if (tracks[i2].mode === "showing") {
  25234. textTrack = tracks[i2];
  25235. break;
  25236. }
  25237. }
  25238. const trackId = this.findTrackForTextTrack(textTrack);
  25239. if (this.subtitleTrack !== trackId) {
  25240. this.setSubtitleTrack(trackId);
  25241. }
  25242. };
  25243. this.registerListeners();
  25244. }
  25245. destroy() {
  25246. this.unregisterListeners();
  25247. this.tracks.length = 0;
  25248. this.tracksInGroup.length = 0;
  25249. this.currentTrack = null;
  25250. this.onTextTracksChanged = this.asyncPollTrackChange = null;
  25251. super.destroy();
  25252. }
  25253. get subtitleDisplay() {
  25254. return this._subtitleDisplay;
  25255. }
  25256. set subtitleDisplay(value2) {
  25257. this._subtitleDisplay = value2;
  25258. if (this.trackId > -1) {
  25259. this.toggleTrackModes();
  25260. }
  25261. }
  25262. registerListeners() {
  25263. const {
  25264. hls
  25265. } = this;
  25266. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  25267. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25268. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  25269. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  25270. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  25271. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  25272. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  25273. hls.on(Events.ERROR, this.onError, this);
  25274. }
  25275. unregisterListeners() {
  25276. const {
  25277. hls
  25278. } = this;
  25279. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  25280. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25281. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  25282. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  25283. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  25284. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  25285. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  25286. hls.off(Events.ERROR, this.onError, this);
  25287. }
  25288. // Listen for subtitle track change, then extract the current track ID.
  25289. onMediaAttached(event, data) {
  25290. this.media = data.media;
  25291. if (!this.media) {
  25292. return;
  25293. }
  25294. if (this.queuedDefaultTrack > -1) {
  25295. this.subtitleTrack = this.queuedDefaultTrack;
  25296. this.queuedDefaultTrack = -1;
  25297. }
  25298. this.useTextTrackPolling = !(this.media.textTracks && "onchange" in this.media.textTracks);
  25299. if (this.useTextTrackPolling) {
  25300. this.pollTrackChange(500);
  25301. } else {
  25302. this.media.textTracks.addEventListener("change", this.asyncPollTrackChange);
  25303. }
  25304. }
  25305. pollTrackChange(timeout2) {
  25306. self.clearInterval(this.subtitlePollingInterval);
  25307. this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout2);
  25308. }
  25309. onMediaDetaching(event, data) {
  25310. const media = this.media;
  25311. if (!media) {
  25312. return;
  25313. }
  25314. const transferringMedia = !!data.transferMedia;
  25315. self.clearInterval(this.subtitlePollingInterval);
  25316. if (!this.useTextTrackPolling) {
  25317. media.textTracks.removeEventListener("change", this.asyncPollTrackChange);
  25318. }
  25319. if (this.trackId > -1) {
  25320. this.queuedDefaultTrack = this.trackId;
  25321. }
  25322. this.subtitleTrack = -1;
  25323. this.media = null;
  25324. if (transferringMedia) {
  25325. return;
  25326. }
  25327. const textTracks = filterSubtitleTracks(media.textTracks);
  25328. textTracks.forEach((track) => {
  25329. clearCurrentCues(track);
  25330. });
  25331. }
  25332. onManifestLoading() {
  25333. this.tracks = [];
  25334. this.groupIds = null;
  25335. this.tracksInGroup = [];
  25336. this.trackId = -1;
  25337. this.currentTrack = null;
  25338. this.selectDefaultTrack = true;
  25339. }
  25340. // Fired whenever a new manifest is loaded.
  25341. onManifestParsed(event, data) {
  25342. this.tracks = data.subtitleTracks;
  25343. }
  25344. onSubtitleTrackLoaded(event, data) {
  25345. const {
  25346. id,
  25347. groupId,
  25348. details
  25349. } = data;
  25350. const trackInActiveGroup = this.tracksInGroup[id];
  25351. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  25352. this.warn(`Subtitle track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  25353. return;
  25354. }
  25355. const curDetails = trackInActiveGroup.details;
  25356. trackInActiveGroup.details = data.details;
  25357. this.log(`Subtitle track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  25358. if (id === this.trackId) {
  25359. this.playlistLoaded(id, data, curDetails);
  25360. }
  25361. }
  25362. onLevelLoading(event, data) {
  25363. this.switchLevel(data.level);
  25364. }
  25365. onLevelSwitching(event, data) {
  25366. this.switchLevel(data.level);
  25367. }
  25368. switchLevel(levelIndex) {
  25369. const levelInfo = this.hls.levels[levelIndex];
  25370. if (!levelInfo) {
  25371. return;
  25372. }
  25373. const subtitleGroups = levelInfo.subtitleGroups || null;
  25374. const currentGroups = this.groupIds;
  25375. let currentTrack = this.currentTrack;
  25376. 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)) {
  25377. this.groupIds = subtitleGroups;
  25378. this.trackId = -1;
  25379. this.currentTrack = null;
  25380. const subtitleTracks = this.tracks.filter((track) => !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1);
  25381. if (subtitleTracks.length) {
  25382. if (this.selectDefaultTrack && !subtitleTracks.some((track) => track.default)) {
  25383. this.selectDefaultTrack = false;
  25384. }
  25385. subtitleTracks.forEach((track, i2) => {
  25386. track.id = i2;
  25387. });
  25388. } else if (!currentTrack && !this.tracksInGroup.length) {
  25389. return;
  25390. }
  25391. this.tracksInGroup = subtitleTracks;
  25392. const subtitlePreference = this.hls.config.subtitlePreference;
  25393. if (!currentTrack && subtitlePreference) {
  25394. this.selectDefaultTrack = false;
  25395. const groupIndex = findMatchingOption(subtitlePreference, subtitleTracks);
  25396. if (groupIndex > -1) {
  25397. currentTrack = subtitleTracks[groupIndex];
  25398. } else {
  25399. const allIndex = findMatchingOption(subtitlePreference, this.tracks);
  25400. currentTrack = this.tracks[allIndex];
  25401. }
  25402. }
  25403. let trackId = this.findTrackId(currentTrack);
  25404. if (trackId === -1 && currentTrack) {
  25405. trackId = this.findTrackId(null);
  25406. }
  25407. const subtitleTracksUpdated = {
  25408. subtitleTracks
  25409. };
  25410. this.log(`Updating subtitle tracks, ${subtitleTracks.length} track(s) found in "${subtitleGroups == null ? void 0 : subtitleGroups.join(",")}" group-id`);
  25411. this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
  25412. if (trackId !== -1 && this.trackId === -1) {
  25413. this.setSubtitleTrack(trackId);
  25414. }
  25415. }
  25416. }
  25417. findTrackId(currentTrack) {
  25418. const tracks = this.tracksInGroup;
  25419. const selectDefault = this.selectDefaultTrack;
  25420. for (let i2 = 0; i2 < tracks.length; i2++) {
  25421. const track = tracks[i2];
  25422. if (selectDefault && !track.default || !selectDefault && !currentTrack) {
  25423. continue;
  25424. }
  25425. if (!currentTrack || matchesOption(track, currentTrack)) {
  25426. return i2;
  25427. }
  25428. }
  25429. if (currentTrack) {
  25430. for (let i2 = 0; i2 < tracks.length; i2++) {
  25431. const track = tracks[i2];
  25432. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
  25433. return i2;
  25434. }
  25435. }
  25436. for (let i2 = 0; i2 < tracks.length; i2++) {
  25437. const track = tracks[i2];
  25438. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) {
  25439. return i2;
  25440. }
  25441. }
  25442. }
  25443. return -1;
  25444. }
  25445. findTrackForTextTrack(textTrack) {
  25446. if (textTrack) {
  25447. const tracks = this.tracksInGroup;
  25448. for (let i2 = 0; i2 < tracks.length; i2++) {
  25449. const track = tracks[i2];
  25450. if (subtitleTrackMatchesTextTrack(track, textTrack)) {
  25451. return i2;
  25452. }
  25453. }
  25454. }
  25455. return -1;
  25456. }
  25457. onError(event, data) {
  25458. if (data.fatal || !data.context) {
  25459. return;
  25460. }
  25461. if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  25462. this.checkRetry(data);
  25463. }
  25464. }
  25465. get allSubtitleTracks() {
  25466. return this.tracks;
  25467. }
  25468. /** get alternate subtitle tracks list from playlist **/
  25469. get subtitleTracks() {
  25470. return this.tracksInGroup;
  25471. }
  25472. /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
  25473. get subtitleTrack() {
  25474. return this.trackId;
  25475. }
  25476. set subtitleTrack(newId) {
  25477. this.selectDefaultTrack = false;
  25478. this.setSubtitleTrack(newId);
  25479. }
  25480. setSubtitleOption(subtitleOption) {
  25481. this.hls.config.subtitlePreference = subtitleOption;
  25482. if (subtitleOption) {
  25483. if (subtitleOption.id === -1) {
  25484. this.setSubtitleTrack(-1);
  25485. return null;
  25486. }
  25487. const allSubtitleTracks = this.allSubtitleTracks;
  25488. this.selectDefaultTrack = false;
  25489. if (allSubtitleTracks.length) {
  25490. const currentTrack = this.currentTrack;
  25491. if (currentTrack && matchesOption(subtitleOption, currentTrack)) {
  25492. return currentTrack;
  25493. }
  25494. const groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup);
  25495. if (groupIndex > -1) {
  25496. const track = this.tracksInGroup[groupIndex];
  25497. this.setSubtitleTrack(groupIndex);
  25498. return track;
  25499. } else if (currentTrack) {
  25500. return null;
  25501. } else {
  25502. const allIndex = findMatchingOption(subtitleOption, allSubtitleTracks);
  25503. if (allIndex > -1) {
  25504. return allSubtitleTracks[allIndex];
  25505. }
  25506. }
  25507. }
  25508. }
  25509. return null;
  25510. }
  25511. loadPlaylist(hlsUrlParameters) {
  25512. super.loadPlaylist();
  25513. if (this.shouldLoadPlaylist(this.currentTrack)) {
  25514. this.scheduleLoading(this.currentTrack, hlsUrlParameters);
  25515. }
  25516. }
  25517. loadingPlaylist(currentTrack, hlsUrlParameters) {
  25518. super.loadingPlaylist(currentTrack, hlsUrlParameters);
  25519. const id = currentTrack.id;
  25520. const groupId = currentTrack.groupId;
  25521. const url2 = this.getUrlWithDirectives(currentTrack.url, hlsUrlParameters);
  25522. const details = currentTrack.details;
  25523. const age = details == null ? void 0 : details.age;
  25524. 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 || "" : "") : ""} ${url2}`);
  25525. this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {
  25526. url: url2,
  25527. id,
  25528. groupId,
  25529. deliveryDirectives: hlsUrlParameters || null,
  25530. track: currentTrack
  25531. });
  25532. }
  25533. /**
  25534. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  25535. * This operates on the DOM textTracks.
  25536. * A value of -1 will disable all subtitle tracks.
  25537. */
  25538. toggleTrackModes() {
  25539. const {
  25540. media
  25541. } = this;
  25542. if (!media) {
  25543. return;
  25544. }
  25545. const textTracks = filterSubtitleTracks(media.textTracks);
  25546. const currentTrack = this.currentTrack;
  25547. let nextTrack;
  25548. if (currentTrack) {
  25549. nextTrack = textTracks.filter((textTrack) => subtitleTrackMatchesTextTrack(currentTrack, textTrack))[0];
  25550. if (!nextTrack) {
  25551. this.warn(`Unable to find subtitle TextTrack with name "${currentTrack.name}" and language "${currentTrack.lang}"`);
  25552. }
  25553. }
  25554. [].slice.call(textTracks).forEach((track) => {
  25555. if (track.mode !== "disabled" && track !== nextTrack) {
  25556. track.mode = "disabled";
  25557. }
  25558. });
  25559. if (nextTrack) {
  25560. const mode = this.subtitleDisplay ? "showing" : "hidden";
  25561. if (nextTrack.mode !== mode) {
  25562. nextTrack.mode = mode;
  25563. }
  25564. }
  25565. }
  25566. /**
  25567. * This method is responsible for validating the subtitle index and periodically reloading if live.
  25568. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  25569. */
  25570. setSubtitleTrack(newId) {
  25571. const tracks = this.tracksInGroup;
  25572. if (!this.media) {
  25573. this.queuedDefaultTrack = newId;
  25574. return;
  25575. }
  25576. if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) {
  25577. this.warn(`Invalid subtitle track id: ${newId}`);
  25578. return;
  25579. }
  25580. this.selectDefaultTrack = false;
  25581. const lastTrack = this.currentTrack;
  25582. const track = tracks[newId] || null;
  25583. this.trackId = newId;
  25584. this.currentTrack = track;
  25585. this.toggleTrackModes();
  25586. if (!track) {
  25587. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  25588. id: newId
  25589. });
  25590. return;
  25591. }
  25592. const trackLoaded = !!track.details && !track.details.live;
  25593. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  25594. return;
  25595. }
  25596. this.log(`Switching to subtitle-track ${newId}` + (track ? ` "${track.name}" lang:${track.lang} group:${track.groupId}` : ""));
  25597. const {
  25598. id,
  25599. groupId = "",
  25600. name,
  25601. type,
  25602. url: url2
  25603. } = track;
  25604. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  25605. id,
  25606. groupId,
  25607. name,
  25608. type,
  25609. url: url2
  25610. });
  25611. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  25612. this.loadPlaylist(hlsUrlParameters);
  25613. }
  25614. }
  25615. function uuid() {
  25616. try {
  25617. return $inject_window_crypto.randomUUID();
  25618. } catch (error2) {
  25619. try {
  25620. const url2 = URL.createObjectURL(new Blob());
  25621. const uuid2 = url2.toString();
  25622. URL.revokeObjectURL(url2);
  25623. return uuid2.slice(uuid2.lastIndexOf("/") + 1);
  25624. } catch (error3) {
  25625. let dt2 = (/* @__PURE__ */ new Date()).getTime();
  25626. const uuid2 = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c2) => {
  25627. const r2 = (dt2 + Math.random() * 16) % 16 | 0;
  25628. dt2 = Math.floor(dt2 / 16);
  25629. return (c2 == "x" ? r2 : r2 & 3 | 8).toString(16);
  25630. });
  25631. return uuid2;
  25632. }
  25633. }
  25634. }
  25635. function hash(text) {
  25636. let hash2 = 5381;
  25637. let i2 = text.length;
  25638. while (i2) {
  25639. hash2 = hash2 * 33 ^ text.charCodeAt(--i2);
  25640. }
  25641. return (hash2 >>> 0).toString();
  25642. }
  25643. const ALIGNED_END_THRESHOLD_SECONDS = 0.025;
  25644. let TimelineOccupancy = /* @__PURE__ */ function(TimelineOccupancy2) {
  25645. TimelineOccupancy2[TimelineOccupancy2["Point"] = 0] = "Point";
  25646. TimelineOccupancy2[TimelineOccupancy2["Range"] = 1] = "Range";
  25647. return TimelineOccupancy2;
  25648. }({});
  25649. function generateAssetIdentifier(interstitial, uri, assetListIndex) {
  25650. return `${interstitial.identifier}-${assetListIndex + 1}-${hash(uri)}`;
  25651. }
  25652. class InterstitialEvent {
  25653. constructor(dateRange, base) {
  25654. this.base = void 0;
  25655. this._duration = null;
  25656. this._timelineStart = null;
  25657. this.appendInPlaceDisabled = void 0;
  25658. this.appendInPlaceStarted = void 0;
  25659. this.dateRange = void 0;
  25660. this.hasPlayed = false;
  25661. this.cumulativeDuration = 0;
  25662. this.resumeOffset = NaN;
  25663. this.playoutLimit = NaN;
  25664. this.restrictions = {
  25665. skip: false,
  25666. jump: false
  25667. };
  25668. this.snapOptions = {
  25669. out: false,
  25670. in: false
  25671. };
  25672. this.assetList = [];
  25673. this.assetListLoader = void 0;
  25674. this.assetListResponse = null;
  25675. this.resumeAnchor = void 0;
  25676. this.error = void 0;
  25677. this.resetOnResume = void 0;
  25678. this.base = base;
  25679. this.dateRange = dateRange;
  25680. this.setDateRange(dateRange);
  25681. }
  25682. setDateRange(dateRange) {
  25683. this.dateRange = dateRange;
  25684. this.resumeOffset = dateRange.attr.optionalFloat("X-RESUME-OFFSET", this.resumeOffset);
  25685. this.playoutLimit = dateRange.attr.optionalFloat("X-PLAYOUT-LIMIT", this.playoutLimit);
  25686. this.restrictions = dateRange.attr.enumeratedStringList("X-RESTRICT", this.restrictions);
  25687. this.snapOptions = dateRange.attr.enumeratedStringList("X-SNAP", this.snapOptions);
  25688. }
  25689. reset() {
  25690. var _this$assetListLoader;
  25691. this.appendInPlaceStarted = false;
  25692. (_this$assetListLoader = this.assetListLoader) == null ? void 0 : _this$assetListLoader.destroy();
  25693. this.assetListLoader = void 0;
  25694. if (!this.supplementsPrimary) {
  25695. this.assetListResponse = null;
  25696. this.assetList = [];
  25697. this._duration = null;
  25698. }
  25699. }
  25700. isAssetPastPlayoutLimit(assetIndex) {
  25701. var _this$assetList$asset;
  25702. if (assetIndex > 0 && assetIndex >= this.assetList.length) {
  25703. return true;
  25704. }
  25705. const playoutLimit = this.playoutLimit;
  25706. if (assetIndex <= 0 || isNaN(playoutLimit)) {
  25707. return false;
  25708. }
  25709. if (playoutLimit === 0) {
  25710. return true;
  25711. }
  25712. const assetOffset = ((_this$assetList$asset = this.assetList[assetIndex]) == null ? void 0 : _this$assetList$asset.startOffset) || 0;
  25713. return assetOffset > playoutLimit;
  25714. }
  25715. findAssetIndex(asset) {
  25716. const index2 = this.assetList.indexOf(asset);
  25717. return index2;
  25718. }
  25719. get identifier() {
  25720. return this.dateRange.id;
  25721. }
  25722. get startDate() {
  25723. return this.dateRange.startDate;
  25724. }
  25725. get startTime() {
  25726. const startTime = this.dateRange.startTime;
  25727. if (this.snapOptions.out) {
  25728. const frag = this.dateRange.tagAnchor;
  25729. if (frag) {
  25730. return getSnapToFragmentTime(startTime, frag);
  25731. }
  25732. }
  25733. return startTime;
  25734. }
  25735. get startOffset() {
  25736. return this.cue.pre ? 0 : this.startTime;
  25737. }
  25738. get startIsAligned() {
  25739. if (this.startTime === 0 || this.snapOptions.out) {
  25740. return true;
  25741. }
  25742. const frag = this.dateRange.tagAnchor;
  25743. if (frag) {
  25744. const startTime = this.dateRange.startTime;
  25745. const snappedStart = getSnapToFragmentTime(startTime, frag);
  25746. return startTime - snappedStart < 0.1;
  25747. }
  25748. return false;
  25749. }
  25750. get resumptionOffset() {
  25751. const resumeOffset = this.resumeOffset;
  25752. const offset = isFiniteNumber(resumeOffset) ? resumeOffset : this.duration;
  25753. return this.cumulativeDuration + offset;
  25754. }
  25755. get resumeTime() {
  25756. const resumeTime = this.startOffset + this.resumptionOffset;
  25757. if (this.snapOptions.in) {
  25758. const frag = this.resumeAnchor;
  25759. if (frag) {
  25760. return getSnapToFragmentTime(resumeTime, frag);
  25761. }
  25762. }
  25763. return resumeTime;
  25764. }
  25765. get appendInPlace() {
  25766. if (this.appendInPlaceStarted) {
  25767. return true;
  25768. }
  25769. if (this.appendInPlaceDisabled) {
  25770. return false;
  25771. }
  25772. if (!this.cue.once && !this.cue.pre && // preroll starts at startPosition before startPosition is known (live)
  25773. this.startIsAligned && (isNaN(this.playoutLimit) && isNaN(this.resumeOffset) || this.resumeOffset && this.duration && Math.abs(this.resumeOffset - this.duration) < ALIGNED_END_THRESHOLD_SECONDS)) {
  25774. return true;
  25775. }
  25776. return false;
  25777. }
  25778. set appendInPlace(value2) {
  25779. if (this.appendInPlaceStarted) {
  25780. this.resetOnResume = !value2;
  25781. return;
  25782. }
  25783. this.appendInPlaceDisabled = !value2;
  25784. }
  25785. // Extended timeline start time
  25786. get timelineStart() {
  25787. if (this._timelineStart !== null) {
  25788. return this._timelineStart;
  25789. }
  25790. return this.startTime;
  25791. }
  25792. set timelineStart(value2) {
  25793. this._timelineStart = value2;
  25794. }
  25795. get duration() {
  25796. const playoutLimit = this.playoutLimit;
  25797. let duration;
  25798. if (this._duration !== null) {
  25799. duration = this._duration;
  25800. } else if (this.dateRange.duration) {
  25801. duration = this.dateRange.duration;
  25802. } else {
  25803. duration = this.dateRange.plannedDuration || 0;
  25804. }
  25805. if (!isNaN(playoutLimit) && playoutLimit < duration) {
  25806. duration = playoutLimit;
  25807. }
  25808. return duration;
  25809. }
  25810. set duration(value2) {
  25811. this._duration = value2;
  25812. }
  25813. get cue() {
  25814. return this.dateRange.cue;
  25815. }
  25816. get timelineOccupancy() {
  25817. if (this.dateRange.attr["X-TIMELINE-OCCUPIES"] === "RANGE") {
  25818. return TimelineOccupancy.Range;
  25819. }
  25820. return TimelineOccupancy.Point;
  25821. }
  25822. get supplementsPrimary() {
  25823. return this.dateRange.attr["X-TIMELINE-STYLE"] === "PRIMARY";
  25824. }
  25825. get contentMayVary() {
  25826. return this.dateRange.attr["X-CONTENT-MAY-VARY"] !== "NO";
  25827. }
  25828. get assetUrl() {
  25829. return this.dateRange.attr["X-ASSET-URI"];
  25830. }
  25831. get assetListUrl() {
  25832. return this.dateRange.attr["X-ASSET-LIST"];
  25833. }
  25834. get baseUrl() {
  25835. return this.base.url;
  25836. }
  25837. get assetListLoaded() {
  25838. return this.assetList.length > 0 || this.assetListResponse !== null;
  25839. }
  25840. toString() {
  25841. return eventToString(this);
  25842. }
  25843. }
  25844. function getSnapToFragmentTime(time, frag) {
  25845. return time - frag.start < frag.duration / 2 && !(Math.abs(time - (frag.start + frag.duration)) < ALIGNED_END_THRESHOLD_SECONDS) ? frag.start : frag.start + frag.duration;
  25846. }
  25847. function getInterstitialUrl(uri, sessionId, baseUrl) {
  25848. const url2 = new self.URL(uri, baseUrl);
  25849. if (url2.protocol !== "data:") {
  25850. url2.searchParams.set("_HLS_primary_id", sessionId);
  25851. }
  25852. return url2;
  25853. }
  25854. function getNextAssetIndex(interstitial, assetListIndex) {
  25855. while ((_interstitial$assetLi = interstitial.assetList[++assetListIndex]) != null && _interstitial$assetLi.error) {
  25856. var _interstitial$assetLi;
  25857. }
  25858. return assetListIndex;
  25859. }
  25860. function eventToString(interstitial) {
  25861. return `["${interstitial.identifier}" ${interstitial.cue.pre ? "<pre>" : interstitial.cue.post ? "<post>" : ""}${interstitial.timelineStart.toFixed(2)}-${interstitial.resumeTime.toFixed(2)}]`;
  25862. }
  25863. function eventAssetToString(asset) {
  25864. const start = asset.timelineStart;
  25865. const duration = asset.duration || 0;
  25866. return `["${asset.identifier}" ${start.toFixed(2)}-${(start + duration).toFixed(2)}]`;
  25867. }
  25868. class HlsAssetPlayer {
  25869. constructor(HlsPlayerClass, userConfig, interstitial, assetItem) {
  25870. this.hls = void 0;
  25871. this.interstitial = void 0;
  25872. this.assetItem = void 0;
  25873. this.tracks = null;
  25874. this.hasDetails = false;
  25875. this.mediaAttached = null;
  25876. this._currentTime = void 0;
  25877. this._bufferedEosTime = void 0;
  25878. this.checkPlayout = () => {
  25879. if (this.reachedPlayout(this.currentTime)) {
  25880. this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED, {});
  25881. }
  25882. };
  25883. const hls = this.hls = new HlsPlayerClass(userConfig);
  25884. this.interstitial = interstitial;
  25885. this.assetItem = assetItem;
  25886. let uri = assetItem.uri;
  25887. try {
  25888. uri = getInterstitialUrl(uri, userConfig.primarySessionId).href;
  25889. } catch (error2) {
  25890. }
  25891. hls.loadSource(uri);
  25892. const detailsLoaded = () => {
  25893. this.hasDetails = true;
  25894. };
  25895. hls.once(Events.LEVEL_LOADED, detailsLoaded);
  25896. hls.once(Events.AUDIO_TRACK_LOADED, detailsLoaded);
  25897. hls.once(Events.SUBTITLE_TRACK_LOADED, detailsLoaded);
  25898. hls.on(Events.MEDIA_ATTACHING, (name, {
  25899. media
  25900. }) => {
  25901. this.removeMediaListeners();
  25902. this.mediaAttached = media;
  25903. const event = this.interstitial;
  25904. if (event.playoutLimit) {
  25905. media.addEventListener("timeupdate", this.checkPlayout);
  25906. if (this.appendInPlace) {
  25907. hls.on(Events.BUFFER_APPENDED, () => {
  25908. const bufferedEnd = this.bufferedEnd;
  25909. if (this.reachedPlayout(bufferedEnd)) {
  25910. this._bufferedEosTime = bufferedEnd;
  25911. hls.trigger(Events.BUFFERED_TO_END, void 0);
  25912. }
  25913. });
  25914. }
  25915. }
  25916. });
  25917. }
  25918. get appendInPlace() {
  25919. var _this$interstitial;
  25920. return ((_this$interstitial = this.interstitial) == null ? void 0 : _this$interstitial.appendInPlace) || false;
  25921. }
  25922. bufferedInPlaceToEnd(media) {
  25923. var _this$hls;
  25924. if (!this.appendInPlace) {
  25925. return false;
  25926. }
  25927. if ((_this$hls = this.hls) != null && _this$hls.bufferedToEnd) {
  25928. return true;
  25929. }
  25930. if (!media || !this._bufferedEosTime) {
  25931. return false;
  25932. }
  25933. const start = this.timelineOffset;
  25934. const bufferInfo = BufferHelper.bufferInfo(media, start, 0);
  25935. const bufferedEnd = this.getAssetTime(bufferInfo.end);
  25936. return bufferedEnd >= this._bufferedEosTime - 0.02;
  25937. }
  25938. reachedPlayout(time) {
  25939. const interstitial = this.interstitial;
  25940. const playoutLimit = interstitial.playoutLimit;
  25941. return this.startOffset + time >= playoutLimit;
  25942. }
  25943. get destroyed() {
  25944. var _this$hls2;
  25945. return !((_this$hls2 = this.hls) != null && _this$hls2.userConfig);
  25946. }
  25947. get assetId() {
  25948. return this.assetItem.identifier;
  25949. }
  25950. get interstitialId() {
  25951. return this.assetItem.parentIdentifier;
  25952. }
  25953. get media() {
  25954. var _this$hls3;
  25955. return ((_this$hls3 = this.hls) == null ? void 0 : _this$hls3.media) || null;
  25956. }
  25957. get bufferedEnd() {
  25958. const media = this.media || this.mediaAttached;
  25959. if (!media) {
  25960. if (this._bufferedEosTime) {
  25961. return this._bufferedEosTime;
  25962. }
  25963. return this.currentTime;
  25964. }
  25965. const bufferInfo = BufferHelper.bufferInfo(media, media.currentTime, 1e-3);
  25966. return this.getAssetTime(bufferInfo.end);
  25967. }
  25968. get currentTime() {
  25969. const media = this.media || this.mediaAttached;
  25970. if (!media) {
  25971. return this._currentTime || 0;
  25972. }
  25973. return this.getAssetTime(media.currentTime);
  25974. }
  25975. get duration() {
  25976. const duration = this.assetItem.duration;
  25977. if (!duration) {
  25978. return 0;
  25979. }
  25980. return duration;
  25981. }
  25982. get remaining() {
  25983. const duration = this.duration;
  25984. if (!duration) {
  25985. return 0;
  25986. }
  25987. return Math.max(0, duration - this.currentTime);
  25988. }
  25989. get startOffset() {
  25990. return this.assetItem.startOffset;
  25991. }
  25992. get timelineOffset() {
  25993. var _this$hls4;
  25994. return ((_this$hls4 = this.hls) == null ? void 0 : _this$hls4.config.timelineOffset) || 0;
  25995. }
  25996. set timelineOffset(value2) {
  25997. const timelineOffset = this.timelineOffset;
  25998. if (value2 !== timelineOffset) {
  25999. const diff = value2 - timelineOffset;
  26000. if (Math.abs(diff) > 1 / 9e4) {
  26001. if (this.hasDetails) {
  26002. throw new Error(`Cannot set timelineOffset after playlists are loaded`);
  26003. }
  26004. this.hls.config.timelineOffset = value2;
  26005. }
  26006. }
  26007. }
  26008. getAssetTime(time) {
  26009. const timelineOffset = this.timelineOffset;
  26010. const duration = this.duration;
  26011. return Math.min(Math.max(0, time - timelineOffset), duration);
  26012. }
  26013. removeMediaListeners() {
  26014. const media = this.mediaAttached;
  26015. if (media) {
  26016. this._currentTime = media.currentTime;
  26017. this.bufferSnapShot();
  26018. media.removeEventListener("timeupdate", this.checkPlayout);
  26019. }
  26020. }
  26021. bufferSnapShot() {
  26022. if (this.mediaAttached) {
  26023. var _this$hls5;
  26024. if ((_this$hls5 = this.hls) != null && _this$hls5.bufferedToEnd) {
  26025. this._bufferedEosTime = this.bufferedEnd;
  26026. }
  26027. }
  26028. }
  26029. destroy() {
  26030. this.removeMediaListeners();
  26031. this.hls.destroy();
  26032. this.hls = this.interstitial = null;
  26033. this.tracks = this.mediaAttached = this.checkPlayout = null;
  26034. }
  26035. attachMedia(data) {
  26036. this.hls.attachMedia(data);
  26037. }
  26038. detachMedia() {
  26039. this.removeMediaListeners();
  26040. this.mediaAttached = null;
  26041. this.hls.detachMedia();
  26042. }
  26043. resumeBuffering() {
  26044. this.hls.resumeBuffering();
  26045. }
  26046. pauseBuffering() {
  26047. this.hls.pauseBuffering();
  26048. }
  26049. transferMedia() {
  26050. this.bufferSnapShot();
  26051. return this.hls.transferMedia();
  26052. }
  26053. resetDetails() {
  26054. const hls = this.hls;
  26055. if (this.hasDetails) {
  26056. hls.stopLoad();
  26057. const deleteDetails = (obj) => delete obj.details;
  26058. hls.levels.forEach(deleteDetails);
  26059. hls.allAudioTracks.forEach(deleteDetails);
  26060. hls.allSubtitleTracks.forEach(deleteDetails);
  26061. this.hasDetails = false;
  26062. }
  26063. }
  26064. on(event, listener, context) {
  26065. this.hls.on(event, listener);
  26066. }
  26067. once(event, listener, context) {
  26068. this.hls.once(event, listener);
  26069. }
  26070. off(event, listener, context) {
  26071. this.hls.off(event, listener);
  26072. }
  26073. toString() {
  26074. var _this$hls6;
  26075. return `HlsAssetPlayer: ${eventAssetToString(this.assetItem)} ${(_this$hls6 = this.hls) == null ? void 0 : _this$hls6.sessionId} ${this.appendInPlace ? "append-in-place" : ""}`;
  26076. }
  26077. }
  26078. const ABUTTING_THRESHOLD_SECONDS = 0.033;
  26079. class InterstitialsSchedule extends Logger {
  26080. constructor(onScheduleUpdate, logger2) {
  26081. super("interstitials-sched", logger2);
  26082. this.onScheduleUpdate = void 0;
  26083. this.eventMap = {};
  26084. this.events = null;
  26085. this.items = null;
  26086. this.durations = {
  26087. primary: 0,
  26088. playout: 0,
  26089. integrated: 0
  26090. };
  26091. this.onScheduleUpdate = onScheduleUpdate;
  26092. }
  26093. destroy() {
  26094. this.reset();
  26095. this.onScheduleUpdate = null;
  26096. }
  26097. reset() {
  26098. this.eventMap = {};
  26099. this.setDurations(0, 0, 0);
  26100. if (this.events) {
  26101. this.events.forEach((interstitial) => interstitial.reset());
  26102. }
  26103. this.events = this.items = null;
  26104. }
  26105. resetErrorsInRange(start, end) {
  26106. if (this.events) {
  26107. return this.events.reduce((count, interstitial) => {
  26108. if (start <= interstitial.startOffset && end > interstitial.startOffset) {
  26109. delete interstitial.error;
  26110. return count + 1;
  26111. }
  26112. return count;
  26113. }, 0);
  26114. }
  26115. return 0;
  26116. }
  26117. get duration() {
  26118. const items = this.items;
  26119. return items ? items[items.length - 1].end : 0;
  26120. }
  26121. get length() {
  26122. return this.items ? this.items.length : 0;
  26123. }
  26124. getEvent(identifier) {
  26125. return identifier ? this.eventMap[identifier] || null : null;
  26126. }
  26127. hasEvent(identifier) {
  26128. return identifier in this.eventMap;
  26129. }
  26130. findItemIndex(item, time) {
  26131. if (item.event) {
  26132. return this.findEventIndex(item.event.identifier);
  26133. }
  26134. let index2 = -1;
  26135. if (item.nextEvent) {
  26136. index2 = this.findEventIndex(item.nextEvent.identifier) - 1;
  26137. } else if (item.previousEvent) {
  26138. index2 = this.findEventIndex(item.previousEvent.identifier) + 1;
  26139. }
  26140. const items = this.items;
  26141. if (items) {
  26142. if (!items[index2]) {
  26143. if (time === void 0) {
  26144. time = item.start;
  26145. }
  26146. index2 = this.findItemIndexAtTime(time);
  26147. }
  26148. while (index2 >= 0 && (_items$index = items[index2]) != null && _items$index.event) {
  26149. var _items$index;
  26150. index2--;
  26151. }
  26152. }
  26153. return index2;
  26154. }
  26155. findItemIndexAtTime(timelinePos, timelineType) {
  26156. const items = this.items;
  26157. if (items) {
  26158. for (let i2 = 0; i2 < items.length; i2++) {
  26159. let timeRange = items[i2];
  26160. if (timelineType && timelineType !== "primary") {
  26161. timeRange = timeRange[timelineType];
  26162. }
  26163. if (timelinePos === timeRange.start || timelinePos > timeRange.start && timelinePos < timeRange.end) {
  26164. return i2;
  26165. }
  26166. }
  26167. }
  26168. return -1;
  26169. }
  26170. findJumpRestrictedIndex(startIndex, endIndex) {
  26171. const items = this.items;
  26172. if (items) {
  26173. for (let i2 = startIndex; i2 <= endIndex; i2++) {
  26174. if (!items[i2]) {
  26175. break;
  26176. }
  26177. const event = items[i2].event;
  26178. if (event != null && event.restrictions.jump && !event.appendInPlace) {
  26179. return i2;
  26180. }
  26181. }
  26182. }
  26183. return -1;
  26184. }
  26185. findEventIndex(identifier) {
  26186. const items = this.items;
  26187. if (items) {
  26188. for (let i2 = items.length; i2--; ) {
  26189. var _items$i$event;
  26190. if (((_items$i$event = items[i2].event) == null ? void 0 : _items$i$event.identifier) === identifier) {
  26191. return i2;
  26192. }
  26193. }
  26194. }
  26195. return -1;
  26196. }
  26197. findAssetIndex(event, timelinePos) {
  26198. const assetList = event.assetList;
  26199. const length = assetList.length;
  26200. if (length > 1) {
  26201. for (let i2 = 0; i2 < length; i2++) {
  26202. const asset = assetList[i2];
  26203. if (!asset.error) {
  26204. const timelineStart = asset.timelineStart;
  26205. if (timelinePos === timelineStart || timelinePos > timelineStart && timelinePos < timelineStart + (asset.duration || 0)) {
  26206. return i2;
  26207. }
  26208. }
  26209. }
  26210. }
  26211. return 0;
  26212. }
  26213. get assetIdAtEnd() {
  26214. var _this$items, _this$items2;
  26215. const interstitialAtEnd = (_this$items = this.items) == null ? void 0 : (_this$items2 = _this$items[this.length - 1]) == null ? void 0 : _this$items2.event;
  26216. if (interstitialAtEnd) {
  26217. const assetList = interstitialAtEnd.assetList;
  26218. const assetAtEnd = assetList[assetList.length - 1];
  26219. if (assetAtEnd) {
  26220. return assetAtEnd.identifier;
  26221. }
  26222. }
  26223. return null;
  26224. }
  26225. parseInterstitialDateRanges(mediaSelection, enableAppendInPlace) {
  26226. const details = mediaSelection.main.details;
  26227. const {
  26228. dateRanges
  26229. } = details;
  26230. const previousInterstitialEvents = this.events;
  26231. const interstitialEvents = this.parseDateRanges(dateRanges, {
  26232. url: details.url
  26233. }, enableAppendInPlace);
  26234. const ids = Object.keys(dateRanges);
  26235. const removedInterstitials = previousInterstitialEvents ? previousInterstitialEvents.filter((event) => !ids.includes(event.identifier)) : [];
  26236. if (interstitialEvents.length) {
  26237. interstitialEvents.sort((a2, b2) => {
  26238. const aPre = a2.cue.pre;
  26239. const aPost = a2.cue.post;
  26240. const bPre = b2.cue.pre;
  26241. const bPost = b2.cue.post;
  26242. if (aPre && !bPre) {
  26243. return -1;
  26244. }
  26245. if (bPre && !aPre) {
  26246. return 1;
  26247. }
  26248. if (aPost && !bPost) {
  26249. return 1;
  26250. }
  26251. if (bPost && !aPost) {
  26252. return -1;
  26253. }
  26254. if (!aPre && !bPre && !aPost && !bPost) {
  26255. const startA = a2.startTime;
  26256. const startB = b2.startTime;
  26257. if (startA !== startB) {
  26258. return startA - startB;
  26259. }
  26260. }
  26261. return a2.dateRange.tagOrder - b2.dateRange.tagOrder;
  26262. });
  26263. }
  26264. this.events = interstitialEvents;
  26265. removedInterstitials.forEach((interstitial) => {
  26266. this.removeEvent(interstitial);
  26267. });
  26268. this.updateSchedule(mediaSelection, removedInterstitials);
  26269. }
  26270. updateSchedule(mediaSelection, removedInterstitials = []) {
  26271. const events = this.events || [];
  26272. if (events.length || removedInterstitials.length || this.length < 2) {
  26273. const currentItems = this.items;
  26274. const updatedItems = this.parseSchedule(events, mediaSelection);
  26275. const updated = removedInterstitials.length || (currentItems == null ? void 0 : currentItems.length) !== updatedItems.length || updatedItems.some((item, i2) => {
  26276. return Math.abs(item.playout.start - currentItems[i2].playout.start) > 5e-3 || Math.abs(item.playout.end - currentItems[i2].playout.end) > 5e-3;
  26277. });
  26278. if (updated) {
  26279. this.items = updatedItems;
  26280. this.onScheduleUpdate(removedInterstitials, currentItems);
  26281. }
  26282. }
  26283. }
  26284. parseDateRanges(dateRanges, baseData, enableAppendInPlace) {
  26285. const interstitialEvents = [];
  26286. const ids = Object.keys(dateRanges);
  26287. for (let i2 = 0; i2 < ids.length; i2++) {
  26288. const id = ids[i2];
  26289. const dateRange = dateRanges[id];
  26290. if (dateRange.isInterstitial) {
  26291. let interstitial = this.eventMap[id];
  26292. if (interstitial) {
  26293. interstitial.setDateRange(dateRange);
  26294. } else {
  26295. interstitial = new InterstitialEvent(dateRange, baseData);
  26296. this.eventMap[id] = interstitial;
  26297. if (enableAppendInPlace === false) {
  26298. interstitial.appendInPlace = enableAppendInPlace;
  26299. }
  26300. }
  26301. interstitialEvents.push(interstitial);
  26302. }
  26303. }
  26304. return interstitialEvents;
  26305. }
  26306. parseSchedule(interstitialEvents, mediaSelection) {
  26307. const schedule = [];
  26308. const details = mediaSelection.main.details;
  26309. const primaryDuration = details.live ? Infinity : details.edge;
  26310. let playoutDuration = 0;
  26311. interstitialEvents = interstitialEvents.filter((event) => !event.error && !(event.cue.once && event.hasPlayed));
  26312. if (interstitialEvents.length) {
  26313. this.resolveOffsets(interstitialEvents, mediaSelection);
  26314. let primaryPosition = 0;
  26315. let integratedTime = 0;
  26316. interstitialEvents.forEach((interstitial, i2) => {
  26317. const preroll = interstitial.cue.pre;
  26318. const postroll = interstitial.cue.post;
  26319. const previousEvent = interstitialEvents[i2 - 1] || null;
  26320. const appendInPlace = interstitial.appendInPlace;
  26321. const eventStart = postroll ? primaryDuration : interstitial.startOffset;
  26322. const interstitialDuration = interstitial.duration;
  26323. const timelineDuration = interstitial.timelineOccupancy === TimelineOccupancy.Range ? interstitialDuration : 0;
  26324. const resumptionOffset = interstitial.resumptionOffset;
  26325. const inSameStartTimeSequence = (previousEvent == null ? void 0 : previousEvent.startTime) === eventStart;
  26326. const start = eventStart + interstitial.cumulativeDuration;
  26327. let end = appendInPlace ? start + interstitialDuration : eventStart + resumptionOffset;
  26328. if (preroll || !postroll && eventStart <= 0) {
  26329. const integratedStart = integratedTime;
  26330. integratedTime += timelineDuration;
  26331. interstitial.timelineStart = start;
  26332. const playoutStart = playoutDuration;
  26333. playoutDuration += interstitialDuration;
  26334. schedule.push({
  26335. event: interstitial,
  26336. start,
  26337. end,
  26338. playout: {
  26339. start: playoutStart,
  26340. end: playoutDuration
  26341. },
  26342. integrated: {
  26343. start: integratedStart,
  26344. end: integratedTime
  26345. }
  26346. });
  26347. } else if (eventStart <= primaryDuration) {
  26348. if (!inSameStartTimeSequence) {
  26349. const segmentDuration = eventStart - primaryPosition;
  26350. if (segmentDuration > ABUTTING_THRESHOLD_SECONDS) {
  26351. const timelineStart = primaryPosition;
  26352. const _integratedStart = integratedTime;
  26353. integratedTime += segmentDuration;
  26354. const _playoutStart = playoutDuration;
  26355. playoutDuration += segmentDuration;
  26356. const primarySegment = {
  26357. previousEvent: interstitialEvents[i2 - 1] || null,
  26358. nextEvent: interstitial,
  26359. start: timelineStart,
  26360. end: timelineStart + segmentDuration,
  26361. playout: {
  26362. start: _playoutStart,
  26363. end: playoutDuration
  26364. },
  26365. integrated: {
  26366. start: _integratedStart,
  26367. end: integratedTime
  26368. }
  26369. };
  26370. schedule.push(primarySegment);
  26371. } else if (segmentDuration > 0 && previousEvent) {
  26372. previousEvent.cumulativeDuration += segmentDuration;
  26373. schedule[schedule.length - 1].end = eventStart;
  26374. }
  26375. }
  26376. if (postroll) {
  26377. end = start;
  26378. }
  26379. interstitial.timelineStart = start;
  26380. const integratedStart = integratedTime;
  26381. integratedTime += timelineDuration;
  26382. const playoutStart = playoutDuration;
  26383. playoutDuration += interstitialDuration;
  26384. schedule.push({
  26385. event: interstitial,
  26386. start,
  26387. end,
  26388. playout: {
  26389. start: playoutStart,
  26390. end: playoutDuration
  26391. },
  26392. integrated: {
  26393. start: integratedStart,
  26394. end: integratedTime
  26395. }
  26396. });
  26397. } else {
  26398. return;
  26399. }
  26400. const resumeTime = interstitial.resumeTime;
  26401. if (postroll || resumeTime > primaryDuration) {
  26402. primaryPosition = primaryDuration;
  26403. } else {
  26404. primaryPosition = resumeTime;
  26405. }
  26406. });
  26407. if (primaryPosition < primaryDuration) {
  26408. var _schedule;
  26409. const timelineStart = primaryPosition;
  26410. const integratedStart = integratedTime;
  26411. const segmentDuration = primaryDuration - primaryPosition;
  26412. integratedTime += segmentDuration;
  26413. const playoutStart = playoutDuration;
  26414. playoutDuration += segmentDuration;
  26415. schedule.push({
  26416. previousEvent: ((_schedule = schedule[schedule.length - 1]) == null ? void 0 : _schedule.event) || null,
  26417. nextEvent: null,
  26418. start: primaryPosition,
  26419. end: timelineStart + segmentDuration,
  26420. playout: {
  26421. start: playoutStart,
  26422. end: playoutDuration
  26423. },
  26424. integrated: {
  26425. start: integratedStart,
  26426. end: integratedTime
  26427. }
  26428. });
  26429. }
  26430. this.setDurations(primaryDuration, playoutDuration, integratedTime);
  26431. } else {
  26432. const start = 0;
  26433. schedule.push({
  26434. previousEvent: null,
  26435. nextEvent: null,
  26436. start,
  26437. end: primaryDuration,
  26438. playout: {
  26439. start,
  26440. end: primaryDuration
  26441. },
  26442. integrated: {
  26443. start,
  26444. end: primaryDuration
  26445. }
  26446. });
  26447. this.setDurations(primaryDuration, primaryDuration, primaryDuration);
  26448. }
  26449. return schedule;
  26450. }
  26451. setDurations(primary, playout, integrated) {
  26452. this.durations = {
  26453. primary,
  26454. playout,
  26455. integrated
  26456. };
  26457. }
  26458. resolveOffsets(interstitialEvents, mediaSelection) {
  26459. const details = mediaSelection.main.details;
  26460. const primaryDuration = details.live ? Infinity : details.edge;
  26461. let cumulativeDuration = 0;
  26462. let lastScheduledStart = -1;
  26463. interstitialEvents.forEach((interstitial, i2) => {
  26464. const preroll = interstitial.cue.pre;
  26465. const postroll = interstitial.cue.post;
  26466. const eventStart = preroll ? 0 : postroll ? primaryDuration : interstitial.startTime;
  26467. this.updateAssetDurations(interstitial);
  26468. const inSameStartTimeSequence = lastScheduledStart === eventStart;
  26469. if (inSameStartTimeSequence) {
  26470. interstitial.cumulativeDuration = cumulativeDuration;
  26471. } else {
  26472. cumulativeDuration = 0;
  26473. lastScheduledStart = eventStart;
  26474. }
  26475. if (!postroll && interstitial.snapOptions.in) {
  26476. interstitial.resumeAnchor = findFragmentByPTS(null, details.fragments, interstitial.startOffset + interstitial.resumptionOffset, 0, 0) || void 0;
  26477. }
  26478. if (interstitial.appendInPlace && !interstitial.appendInPlaceStarted) {
  26479. const alignedSegmentStart = this.primaryCanResumeInPlaceAt(interstitial, mediaSelection);
  26480. if (!alignedSegmentStart) {
  26481. interstitial.appendInPlace = false;
  26482. }
  26483. }
  26484. if (!interstitial.appendInPlace && i2 + 1 < interstitialEvents.length) {
  26485. const timeBetween = interstitialEvents[i2 + 1].startTime - interstitialEvents[i2].resumeTime;
  26486. if (timeBetween < ABUTTING_THRESHOLD_SECONDS) {
  26487. interstitialEvents[i2 + 1].appendInPlace = false;
  26488. if (interstitialEvents[i2 + 1].appendInPlace) {
  26489. this.warn(`Could not change append strategy for abutting event ${interstitial}`);
  26490. }
  26491. }
  26492. }
  26493. const resumeOffset = isFiniteNumber(interstitial.resumeOffset) ? interstitial.resumeOffset : interstitial.duration;
  26494. cumulativeDuration += resumeOffset;
  26495. });
  26496. }
  26497. primaryCanResumeInPlaceAt(interstitial, mediaSelection) {
  26498. const resumeTime = interstitial.resumeTime;
  26499. const resumesInPlaceAt = interstitial.startTime + interstitial.resumptionOffset;
  26500. if (Math.abs(resumeTime - resumesInPlaceAt) > ALIGNED_END_THRESHOLD_SECONDS) {
  26501. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with estimated timeline end ${resumesInPlaceAt}`);
  26502. return false;
  26503. }
  26504. if (!mediaSelection) {
  26505. this.log(`"${interstitial.identifier}" resumption ${resumeTime} can not be aligned with media (none selected)`);
  26506. return false;
  26507. }
  26508. const playlists = Object.keys(mediaSelection);
  26509. return !playlists.some((playlistType) => {
  26510. const details = mediaSelection[playlistType].details;
  26511. const playlistEnd = details.edge;
  26512. if (resumeTime >= playlistEnd) {
  26513. this.log(`"${interstitial.identifier}" resumption ${resumeTime} past ${playlistType} playlist end ${playlistEnd}`);
  26514. return false;
  26515. }
  26516. const startFragment = findFragmentByPTS(null, details.fragments, resumeTime);
  26517. if (!startFragment) {
  26518. this.log(`"${interstitial.identifier}" resumption ${resumeTime} does not align with any fragments in ${playlistType} playlist (${details.fragStart}-${details.fragmentEnd})`);
  26519. return true;
  26520. }
  26521. const allowance = playlistType === "audio" ? 0.175 : 0;
  26522. const alignedWithSegment = Math.abs(startFragment.start - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance || Math.abs(startFragment.end - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance;
  26523. if (!alignedWithSegment) {
  26524. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with ${playlistType} fragment bounds (${startFragment.start}-${startFragment.end} sn: ${startFragment.sn} cc: ${startFragment.cc})`);
  26525. return true;
  26526. }
  26527. return false;
  26528. });
  26529. }
  26530. updateAssetDurations(interstitial) {
  26531. if (!interstitial.assetListLoaded) {
  26532. return;
  26533. }
  26534. const eventStart = interstitial.timelineStart;
  26535. let sumDuration = 0;
  26536. let hasUnknownDuration = false;
  26537. let hasErrors = false;
  26538. interstitial.assetList.forEach((asset, i2) => {
  26539. const timelineStart = eventStart + sumDuration;
  26540. asset.startOffset = sumDuration;
  26541. asset.timelineStart = timelineStart;
  26542. hasUnknownDuration || (hasUnknownDuration = asset.duration === null);
  26543. hasErrors || (hasErrors = !!asset.error);
  26544. const duration = asset.error ? 0 : asset.duration || 0;
  26545. sumDuration += duration;
  26546. });
  26547. if (hasUnknownDuration && !hasErrors) {
  26548. interstitial.duration = Math.max(sumDuration, interstitial.duration);
  26549. } else {
  26550. interstitial.duration = sumDuration;
  26551. }
  26552. }
  26553. removeEvent(interstitial) {
  26554. interstitial.reset();
  26555. delete this.eventMap[interstitial.identifier];
  26556. }
  26557. }
  26558. function segmentToString(segment) {
  26559. return `[${segment.event ? '"' + segment.event.identifier + '"' : "primary"}: ${segment.start.toFixed(2)}-${segment.end.toFixed(2)}]`;
  26560. }
  26561. class AssetListLoader {
  26562. constructor(hls) {
  26563. this.hls = void 0;
  26564. this.hls = hls;
  26565. }
  26566. destroy() {
  26567. this.hls = null;
  26568. }
  26569. loadAssetList(interstitial, hlsStartOffset) {
  26570. const assetListUrl = interstitial.assetListUrl;
  26571. let url2;
  26572. try {
  26573. url2 = getInterstitialUrl(assetListUrl, this.hls.sessionId, interstitial.baseUrl);
  26574. } catch (error2) {
  26575. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, error2, assetListUrl);
  26576. this.hls.trigger(Events.ERROR, errorData);
  26577. return;
  26578. }
  26579. if (hlsStartOffset && url2.protocol !== "data:") {
  26580. url2.searchParams.set("_HLS_start_offset", "" + hlsStartOffset);
  26581. }
  26582. const config2 = this.hls.config;
  26583. const Loader = config2.loader;
  26584. const loader = new Loader(config2);
  26585. const context = {
  26586. responseType: "json",
  26587. url: url2.href
  26588. };
  26589. const loadPolicy = config2.interstitialAssetListLoadPolicy.default;
  26590. const loaderConfig = {
  26591. loadPolicy,
  26592. timeout: loadPolicy.maxLoadTimeMs,
  26593. maxRetry: 0,
  26594. retryDelay: 0,
  26595. maxRetryDelay: 0
  26596. };
  26597. const callbacks = {
  26598. onSuccess: (response, stats, context2, networkDetails) => {
  26599. const assetListResponse = response.data;
  26600. const assets = assetListResponse == null ? void 0 : assetListResponse.ASSETS;
  26601. if (!Array.isArray(assets)) {
  26602. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_PARSING_ERROR, new Error(`Invalid interstitial asset list`), context2.url, stats, networkDetails);
  26603. this.hls.trigger(Events.ERROR, errorData);
  26604. return;
  26605. }
  26606. interstitial.assetListResponse = assetListResponse;
  26607. this.hls.trigger(Events.ASSET_LIST_LOADED, {
  26608. event: interstitial,
  26609. assetListResponse,
  26610. networkDetails
  26611. });
  26612. },
  26613. onError: (error2, context2, networkDetails, stats) => {
  26614. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, new Error(`Error loading X-ASSET-LIST: HTTP status ${error2.code} ${error2.text} (${context2.url})`), context2.url, stats, networkDetails);
  26615. this.hls.trigger(Events.ERROR, errorData);
  26616. },
  26617. onTimeout: (stats, context2, networkDetails) => {
  26618. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_TIMEOUT, new Error(`Timeout loading X-ASSET-LIST (${context2.url})`), context2.url, stats, networkDetails);
  26619. this.hls.trigger(Events.ERROR, errorData);
  26620. }
  26621. };
  26622. loader.load(context, loaderConfig, callbacks);
  26623. this.hls.trigger(Events.ASSET_LIST_LOADING, {
  26624. event: interstitial
  26625. });
  26626. return loader;
  26627. }
  26628. assignAssetListError(interstitial, details, error2, url2, stats, networkDetails) {
  26629. interstitial.error = error2;
  26630. return {
  26631. type: ErrorTypes.NETWORK_ERROR,
  26632. details,
  26633. fatal: false,
  26634. interstitial,
  26635. url: url2,
  26636. error: error2,
  26637. networkDetails,
  26638. stats
  26639. };
  26640. }
  26641. }
  26642. function playWithCatch(media) {
  26643. media == null ? void 0 : media.play().catch(() => {
  26644. });
  26645. }
  26646. class InterstitialsController extends Logger {
  26647. constructor(hls, HlsPlayerClass) {
  26648. super("interstitials", hls.logger);
  26649. this.HlsPlayerClass = void 0;
  26650. this.hls = void 0;
  26651. this.assetListLoader = void 0;
  26652. this.mediaSelection = null;
  26653. this.altSelection = null;
  26654. this.media = null;
  26655. this.detachedData = null;
  26656. this.requiredTracks = null;
  26657. this.manager = null;
  26658. this.playerQueue = [];
  26659. this.bufferedPos = -1;
  26660. this.timelinePos = -1;
  26661. this.schedule = void 0;
  26662. this.playingItem = null;
  26663. this.bufferingItem = null;
  26664. this.waitingItem = null;
  26665. this.endedItem = null;
  26666. this.playingAsset = null;
  26667. this.endedAsset = null;
  26668. this.bufferingAsset = null;
  26669. this.shouldPlay = false;
  26670. this.onPlay = () => {
  26671. this.shouldPlay = true;
  26672. };
  26673. this.onPause = () => {
  26674. this.shouldPlay = false;
  26675. };
  26676. this.onSeeking = () => {
  26677. const currentTime = this.currentTime;
  26678. if (currentTime === void 0 || this.playbackDisabled) {
  26679. return;
  26680. }
  26681. const diff = currentTime - this.timelinePos;
  26682. const roundingError = Math.abs(diff) < 1 / 7056e5;
  26683. if (roundingError) {
  26684. return;
  26685. }
  26686. const backwardSeek = diff <= -0.01;
  26687. this.timelinePos = currentTime;
  26688. this.bufferedPos = currentTime;
  26689. const playingItem = this.playingItem;
  26690. if (!playingItem) {
  26691. this.checkBuffer();
  26692. return;
  26693. }
  26694. if (backwardSeek) {
  26695. const resetCount = this.schedule.resetErrorsInRange(currentTime, currentTime - diff);
  26696. if (resetCount) {
  26697. this.updateSchedule();
  26698. }
  26699. }
  26700. this.checkBuffer();
  26701. if (backwardSeek && currentTime < playingItem.start || currentTime >= playingItem.end) {
  26702. var _this$media;
  26703. const scheduleIndex = this.schedule.findItemIndexAtTime(this.timelinePos);
  26704. if (!this.isInterstitial(playingItem) && (_this$media = this.media) != null && _this$media.paused) {
  26705. this.shouldPlay = false;
  26706. }
  26707. if (!backwardSeek) {
  26708. const playingIndex = this.findItemIndex(playingItem);
  26709. if (scheduleIndex > playingIndex) {
  26710. const jumpIndex = this.schedule.findJumpRestrictedIndex(playingIndex + 1, scheduleIndex);
  26711. if (jumpIndex > playingIndex) {
  26712. this.setSchedulePosition(jumpIndex);
  26713. return;
  26714. }
  26715. }
  26716. }
  26717. this.setSchedulePosition(scheduleIndex);
  26718. return;
  26719. }
  26720. const playingAsset = this.playingAsset;
  26721. if (!playingAsset) {
  26722. if (this.playingLastItem && this.isInterstitial(playingItem)) {
  26723. const restartAsset = playingItem.event.assetList[0];
  26724. if (restartAsset) {
  26725. this.endedItem = this.playingItem;
  26726. this.playingItem = null;
  26727. this.setScheduleToAssetAtTime(currentTime, restartAsset);
  26728. }
  26729. }
  26730. return;
  26731. }
  26732. const start = playingAsset.timelineStart;
  26733. const duration = playingAsset.duration || 0;
  26734. if (backwardSeek && currentTime < start || currentTime >= start + duration) {
  26735. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  26736. }
  26737. };
  26738. this.onTimeupdate = () => {
  26739. const currentTime = this.currentTime;
  26740. if (currentTime === void 0 || this.playbackDisabled) {
  26741. return;
  26742. }
  26743. if (currentTime > this.timelinePos) {
  26744. this.timelinePos = currentTime;
  26745. if (currentTime > this.bufferedPos) {
  26746. this.checkBuffer();
  26747. }
  26748. } else {
  26749. return;
  26750. }
  26751. const playingItem = this.playingItem;
  26752. if (!playingItem || this.playingLastItem) {
  26753. return;
  26754. }
  26755. if (currentTime >= playingItem.end) {
  26756. this.timelinePos = playingItem.end;
  26757. const playingIndex = this.findItemIndex(playingItem);
  26758. this.setSchedulePosition(playingIndex + 1);
  26759. }
  26760. const playingAsset = this.playingAsset;
  26761. if (!playingAsset) {
  26762. return;
  26763. }
  26764. const end = playingAsset.timelineStart + (playingAsset.duration || 0);
  26765. if (currentTime >= end) {
  26766. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  26767. }
  26768. };
  26769. this.onScheduleUpdate = (removedInterstitials, previousItems) => {
  26770. const schedule = this.schedule;
  26771. const playingItem = this.playingItem;
  26772. const interstitialEvents = schedule.events || [];
  26773. const scheduleItems = schedule.items || [];
  26774. const durations = schedule.durations;
  26775. const removedIds = removedInterstitials.map((interstitial) => interstitial.identifier);
  26776. const interstitialsUpdated = !!(interstitialEvents.length || removedIds.length);
  26777. if (interstitialsUpdated || previousItems) {
  26778. this.log(`INTERSTITIALS_UPDATED (${interstitialEvents.length}): ${interstitialEvents}
  26779. Schedule: ${scheduleItems.map((seg) => segmentToString(seg))} pos: ${this.timelinePos}`);
  26780. }
  26781. if (removedIds.length) {
  26782. this.log(`Removed events ${removedIds}`);
  26783. }
  26784. this.playerQueue.forEach((player) => {
  26785. if (player.interstitial.appendInPlace) {
  26786. const timelineStart = player.assetItem.timelineStart;
  26787. const diff = player.timelineOffset - timelineStart;
  26788. if (diff) {
  26789. try {
  26790. player.timelineOffset = timelineStart;
  26791. } catch (e2) {
  26792. if (Math.abs(diff) > ALIGNED_END_THRESHOLD_SECONDS) {
  26793. this.warn(`${e2} ("${player.assetId}" ${player.timelineOffset}->${timelineStart})`);
  26794. }
  26795. }
  26796. }
  26797. }
  26798. });
  26799. let trimInPlaceForPlayout = null;
  26800. if (playingItem) {
  26801. const updatedPlayingItem = this.updateItem(playingItem, this.timelinePos);
  26802. if (this.itemsMatch(playingItem, updatedPlayingItem)) {
  26803. this.playingItem = updatedPlayingItem;
  26804. this.waitingItem = this.endedItem = null;
  26805. trimInPlaceForPlayout = () => this.trimInPlace(updatedPlayingItem, playingItem);
  26806. }
  26807. } else {
  26808. this.waitingItem = this.updateItem(this.waitingItem);
  26809. this.endedItem = this.updateItem(this.endedItem);
  26810. }
  26811. const bufferingItem = this.bufferingItem;
  26812. if (bufferingItem) {
  26813. const updatedBufferingItem = this.updateItem(bufferingItem, this.bufferedPos);
  26814. if (this.itemsMatch(bufferingItem, updatedBufferingItem)) {
  26815. this.bufferingItem = updatedBufferingItem;
  26816. trimInPlaceForPlayout || (trimInPlaceForPlayout = () => this.trimInPlace(updatedBufferingItem, bufferingItem));
  26817. } else if (bufferingItem.event) {
  26818. this.bufferingItem = this.playingItem;
  26819. this.clearInterstitial(bufferingItem.event, null);
  26820. }
  26821. }
  26822. removedInterstitials.forEach((interstitial) => {
  26823. interstitial.assetList.forEach((asset) => {
  26824. this.clearAssetPlayer(asset.identifier, null);
  26825. });
  26826. });
  26827. if (interstitialsUpdated || previousItems) {
  26828. this.hls.trigger(Events.INTERSTITIALS_UPDATED, {
  26829. events: interstitialEvents.slice(0),
  26830. schedule: scheduleItems.slice(0),
  26831. durations,
  26832. removedIds
  26833. });
  26834. if (this.isInterstitial(playingItem) && removedIds.includes(playingItem.event.identifier)) {
  26835. this.warn(`Interstitial "${playingItem.event.identifier}" removed while playing`);
  26836. this.primaryFallback(playingItem.event);
  26837. return;
  26838. }
  26839. if (trimInPlaceForPlayout) {
  26840. trimInPlaceForPlayout();
  26841. }
  26842. this.checkBuffer();
  26843. }
  26844. };
  26845. this.hls = hls;
  26846. this.HlsPlayerClass = HlsPlayerClass;
  26847. this.assetListLoader = new AssetListLoader(hls);
  26848. this.schedule = new InterstitialsSchedule(this.onScheduleUpdate, hls.logger);
  26849. this.registerListeners();
  26850. }
  26851. registerListeners() {
  26852. const hls = this.hls;
  26853. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  26854. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  26855. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  26856. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  26857. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  26858. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  26859. hls.on(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  26860. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  26861. hls.on(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  26862. hls.on(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  26863. hls.on(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  26864. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  26865. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  26866. hls.on(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  26867. hls.on(Events.MEDIA_ENDED, this.onMediaEnded, this);
  26868. hls.on(Events.ERROR, this.onError, this);
  26869. hls.on(Events.DESTROYING, this.onDestroying, this);
  26870. }
  26871. unregisterListeners() {
  26872. const hls = this.hls;
  26873. if (!hls) {
  26874. return;
  26875. }
  26876. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  26877. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  26878. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  26879. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  26880. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  26881. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  26882. hls.off(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  26883. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  26884. hls.off(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  26885. hls.off(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  26886. hls.off(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  26887. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  26888. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  26889. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  26890. hls.off(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  26891. hls.off(Events.MEDIA_ENDED, this.onMediaEnded, this);
  26892. hls.off(Events.ERROR, this.onError, this);
  26893. hls.off(Events.DESTROYING, this.onDestroying, this);
  26894. }
  26895. startLoad() {
  26896. this.resumeBuffering();
  26897. }
  26898. stopLoad() {
  26899. this.pauseBuffering();
  26900. }
  26901. resumeBuffering() {
  26902. var _this$getBufferingPla;
  26903. (_this$getBufferingPla = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla.resumeBuffering();
  26904. }
  26905. pauseBuffering() {
  26906. var _this$getBufferingPla2;
  26907. (_this$getBufferingPla2 = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla2.pauseBuffering();
  26908. }
  26909. destroy() {
  26910. this.unregisterListeners();
  26911. this.stopLoad();
  26912. if (this.assetListLoader) {
  26913. this.assetListLoader.destroy();
  26914. }
  26915. this.emptyPlayerQueue();
  26916. this.clearScheduleState();
  26917. if (this.schedule) {
  26918. this.schedule.destroy();
  26919. }
  26920. this.media = this.detachedData = this.mediaSelection = this.requiredTracks = this.altSelection = this.manager = null;
  26921. this.hls = this.HlsPlayerClass = this.schedule = this.log = null;
  26922. this.assetListLoader = null;
  26923. this.onPlay = this.onPause = this.onSeeking = this.onTimeupdate = null;
  26924. this.onScheduleUpdate = null;
  26925. }
  26926. onDestroying() {
  26927. const media = this.primaryMedia || this.media;
  26928. if (media) {
  26929. this.removeMediaListeners(media);
  26930. }
  26931. }
  26932. removeMediaListeners(media) {
  26933. removeEventListener(media, "play", this.onPlay);
  26934. removeEventListener(media, "pause", this.onPause);
  26935. removeEventListener(media, "seeking", this.onSeeking);
  26936. removeEventListener(media, "timeupdate", this.onTimeupdate);
  26937. }
  26938. onMediaAttaching(event, data) {
  26939. const media = this.media = data.media;
  26940. addEventListener(media, "seeking", this.onSeeking);
  26941. addEventListener(media, "timeupdate", this.onTimeupdate);
  26942. addEventListener(media, "play", this.onPlay);
  26943. addEventListener(media, "pause", this.onPause);
  26944. }
  26945. onMediaAttached(event, data) {
  26946. const playingItem = this.effectivePlayingItem;
  26947. const detachedMedia = this.detachedData;
  26948. this.detachedData = null;
  26949. if (playingItem === null) {
  26950. this.checkStart();
  26951. } else if (!detachedMedia) {
  26952. this.clearScheduleState();
  26953. const playingIndex = this.findItemIndex(playingItem);
  26954. this.setSchedulePosition(playingIndex);
  26955. }
  26956. }
  26957. clearScheduleState() {
  26958. this.playingItem = this.bufferingItem = this.waitingItem = this.endedItem = this.playingAsset = this.endedAsset = this.bufferingAsset = null;
  26959. }
  26960. onMediaDetaching(event, data) {
  26961. const transferringMedia = !!data.transferMedia;
  26962. const media = this.media;
  26963. this.media = null;
  26964. if (transferringMedia) {
  26965. return;
  26966. }
  26967. if (media) {
  26968. this.removeMediaListeners(media);
  26969. }
  26970. if (this.detachedData) {
  26971. const player = this.getBufferingPlayer();
  26972. if (player) {
  26973. this.playingAsset = this.endedAsset = this.bufferingAsset = this.bufferingItem = this.waitingItem = this.detachedData = null;
  26974. player.detachMedia();
  26975. }
  26976. this.shouldPlay = false;
  26977. }
  26978. }
  26979. get interstitialsManager() {
  26980. if (!this.manager) {
  26981. if (!this.hls) {
  26982. return null;
  26983. }
  26984. const c2 = this;
  26985. const effectiveBufferingItem = () => c2.bufferingItem || c2.waitingItem;
  26986. const getAssetPlayer = (asset) => asset ? c2.getAssetPlayer(asset.identifier) : asset;
  26987. const getMappedTime = (item, timelineType, asset, controllerField, assetPlayerField) => {
  26988. if (item) {
  26989. let time = item[timelineType].start;
  26990. const interstitial = item.event;
  26991. if (interstitial) {
  26992. if (timelineType === "playout" || interstitial.timelineOccupancy !== TimelineOccupancy.Point) {
  26993. const assetPlayer = getAssetPlayer(asset);
  26994. if ((assetPlayer == null ? void 0 : assetPlayer.interstitial) === interstitial) {
  26995. time += assetPlayer.assetItem.startOffset + assetPlayer[assetPlayerField];
  26996. }
  26997. }
  26998. } else {
  26999. const value2 = controllerField === "bufferedPos" ? getBufferedEnd() : c2[controllerField];
  27000. time += value2 - item.start;
  27001. }
  27002. return time;
  27003. }
  27004. return 0;
  27005. };
  27006. const findMappedTime = (primaryTime, timelineType) => {
  27007. if (primaryTime !== 0 && timelineType !== "primary" && c2.schedule.length) {
  27008. var _c$schedule$items;
  27009. const index2 = c2.schedule.findItemIndexAtTime(primaryTime);
  27010. const item = (_c$schedule$items = c2.schedule.items) == null ? void 0 : _c$schedule$items[index2];
  27011. if (item) {
  27012. const diff = item[timelineType].start - item.start;
  27013. return primaryTime + diff;
  27014. }
  27015. }
  27016. return primaryTime;
  27017. };
  27018. const getBufferedEnd = () => {
  27019. const value2 = c2.bufferedPos;
  27020. if (value2 === Number.MAX_VALUE) {
  27021. return getMappedDuration("primary");
  27022. }
  27023. return Math.max(value2, 0);
  27024. };
  27025. const getMappedDuration = (timelineType) => {
  27026. var _c$primaryDetails;
  27027. if ((_c$primaryDetails = c2.primaryDetails) != null && _c$primaryDetails.live) {
  27028. return c2.primaryDetails.edge;
  27029. }
  27030. return c2.schedule.durations[timelineType];
  27031. };
  27032. const seekTo = (time, timelineType) => {
  27033. var _item$event, _c$schedule$items2;
  27034. const item = c2.effectivePlayingItem;
  27035. if (item != null && (_item$event = item.event) != null && _item$event.restrictions.skip) {
  27036. return;
  27037. }
  27038. c2.log(`seek to ${time} "${timelineType}"`);
  27039. const playingItem = c2.effectivePlayingItem;
  27040. const targetIndex = c2.schedule.findItemIndexAtTime(time, timelineType);
  27041. const targetItem = (_c$schedule$items2 = c2.schedule.items) == null ? void 0 : _c$schedule$items2[targetIndex];
  27042. const bufferingPlayer = c2.getBufferingPlayer();
  27043. const bufferingInterstitial = bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial;
  27044. const appendInPlace = bufferingInterstitial == null ? void 0 : bufferingInterstitial.appendInPlace;
  27045. const seekInItem = playingItem && c2.itemsMatch(playingItem, targetItem);
  27046. if (playingItem && (appendInPlace || seekInItem)) {
  27047. const assetPlayer = getAssetPlayer(c2.playingAsset);
  27048. const media = (assetPlayer == null ? void 0 : assetPlayer.media) || c2.primaryMedia;
  27049. if (media) {
  27050. const currentTime = timelineType === "primary" ? media.currentTime : getMappedTime(playingItem, timelineType, c2.playingAsset, "timelinePos", "currentTime");
  27051. const diff = time - currentTime;
  27052. const seekToTime = (appendInPlace ? currentTime : media.currentTime) + diff;
  27053. if (seekToTime >= 0 && (!assetPlayer || appendInPlace || seekToTime <= assetPlayer.duration)) {
  27054. media.currentTime = seekToTime;
  27055. return;
  27056. }
  27057. }
  27058. }
  27059. if (targetItem) {
  27060. let seekToTime = time;
  27061. if (timelineType !== "primary") {
  27062. const primarySegmentStart = targetItem[timelineType].start;
  27063. const diff = time - primarySegmentStart;
  27064. seekToTime = targetItem.start + diff;
  27065. }
  27066. const targetIsPrimary = !c2.isInterstitial(targetItem);
  27067. if ((!c2.isInterstitial(playingItem) || playingItem.event.appendInPlace) && (targetIsPrimary || targetItem.event.appendInPlace)) {
  27068. const media = c2.media || (appendInPlace ? bufferingPlayer == null ? void 0 : bufferingPlayer.media : null);
  27069. if (media) {
  27070. media.currentTime = seekToTime;
  27071. }
  27072. } else if (playingItem) {
  27073. const playingIndex = c2.findItemIndex(playingItem);
  27074. if (targetIndex > playingIndex) {
  27075. const jumpIndex = c2.schedule.findJumpRestrictedIndex(playingIndex + 1, targetIndex);
  27076. if (jumpIndex > playingIndex) {
  27077. c2.setSchedulePosition(jumpIndex);
  27078. return;
  27079. }
  27080. }
  27081. let assetIndex = 0;
  27082. if (targetIsPrimary) {
  27083. c2.timelinePos = seekToTime;
  27084. c2.checkBuffer();
  27085. } else {
  27086. var _targetItem$event;
  27087. const assetList = targetItem == null ? void 0 : (_targetItem$event = targetItem.event) == null ? void 0 : _targetItem$event.assetList;
  27088. if (assetList) {
  27089. const eventTime = time - (targetItem[timelineType] || targetItem).start;
  27090. for (let i2 = assetList.length; i2--; ) {
  27091. const asset = assetList[i2];
  27092. if (asset.duration && eventTime >= asset.startOffset && eventTime < asset.startOffset + asset.duration) {
  27093. assetIndex = i2;
  27094. break;
  27095. }
  27096. }
  27097. }
  27098. }
  27099. c2.setSchedulePosition(targetIndex, assetIndex);
  27100. }
  27101. }
  27102. };
  27103. const getActiveInterstitial = () => {
  27104. const playingItem = c2.effectivePlayingItem;
  27105. if (c2.isInterstitial(playingItem)) {
  27106. return playingItem;
  27107. }
  27108. const bufferingItem = effectiveBufferingItem();
  27109. if (c2.isInterstitial(bufferingItem)) {
  27110. return bufferingItem;
  27111. }
  27112. return null;
  27113. };
  27114. const interstitialPlayer = {
  27115. get currentTime() {
  27116. const interstitialItem = getActiveInterstitial();
  27117. const playingItem = c2.effectivePlayingItem;
  27118. if (playingItem && playingItem === interstitialItem) {
  27119. return getMappedTime(playingItem, "playout", c2.effectivePlayingAsset, "timelinePos", "currentTime") - playingItem.playout.start;
  27120. }
  27121. return 0;
  27122. },
  27123. set currentTime(time) {
  27124. const interstitialItem = getActiveInterstitial();
  27125. const playingItem = c2.effectivePlayingItem;
  27126. if (playingItem && playingItem === interstitialItem) {
  27127. seekTo(time + playingItem.playout.start, "playout");
  27128. }
  27129. },
  27130. get duration() {
  27131. const interstitialItem = getActiveInterstitial();
  27132. if (interstitialItem) {
  27133. return interstitialItem.playout.end - interstitialItem.playout.start;
  27134. }
  27135. return 0;
  27136. },
  27137. get assetPlayers() {
  27138. var _getActiveInterstitia;
  27139. const assetList = (_getActiveInterstitia = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia.event.assetList;
  27140. if (assetList) {
  27141. return assetList.map((asset) => c2.getAssetPlayer(asset.identifier));
  27142. }
  27143. return [];
  27144. },
  27145. get playingIndex() {
  27146. var _getActiveInterstitia2;
  27147. const interstitial = (_getActiveInterstitia2 = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia2.event;
  27148. if (interstitial && c2.effectivePlayingAsset) {
  27149. return interstitial.findAssetIndex(c2.effectivePlayingAsset);
  27150. }
  27151. return -1;
  27152. },
  27153. get scheduleItem() {
  27154. return getActiveInterstitial();
  27155. }
  27156. };
  27157. this.manager = {
  27158. get events() {
  27159. var _c$schedule, _c$schedule$events;
  27160. return ((_c$schedule = c2.schedule) == null ? void 0 : (_c$schedule$events = _c$schedule.events) == null ? void 0 : _c$schedule$events.slice(0)) || [];
  27161. },
  27162. get schedule() {
  27163. var _c$schedule2, _c$schedule2$items;
  27164. return ((_c$schedule2 = c2.schedule) == null ? void 0 : (_c$schedule2$items = _c$schedule2.items) == null ? void 0 : _c$schedule2$items.slice(0)) || [];
  27165. },
  27166. get interstitialPlayer() {
  27167. if (getActiveInterstitial()) {
  27168. return interstitialPlayer;
  27169. }
  27170. return null;
  27171. },
  27172. get playerQueue() {
  27173. return c2.playerQueue.slice(0);
  27174. },
  27175. get bufferingAsset() {
  27176. return c2.bufferingAsset;
  27177. },
  27178. get bufferingItem() {
  27179. return effectiveBufferingItem();
  27180. },
  27181. get bufferingIndex() {
  27182. const item = effectiveBufferingItem();
  27183. return c2.findItemIndex(item);
  27184. },
  27185. get playingAsset() {
  27186. return c2.effectivePlayingAsset;
  27187. },
  27188. get playingItem() {
  27189. return c2.effectivePlayingItem;
  27190. },
  27191. get playingIndex() {
  27192. const item = c2.effectivePlayingItem;
  27193. return c2.findItemIndex(item);
  27194. },
  27195. primary: {
  27196. get bufferedEnd() {
  27197. return getBufferedEnd();
  27198. },
  27199. get currentTime() {
  27200. const timelinePos = c2.timelinePos;
  27201. return timelinePos > 0 ? timelinePos : 0;
  27202. },
  27203. set currentTime(time) {
  27204. seekTo(time, "primary");
  27205. },
  27206. get duration() {
  27207. return getMappedDuration("primary");
  27208. },
  27209. get seekableStart() {
  27210. var _c$primaryDetails2;
  27211. return ((_c$primaryDetails2 = c2.primaryDetails) == null ? void 0 : _c$primaryDetails2.fragmentStart) || 0;
  27212. }
  27213. },
  27214. integrated: {
  27215. get bufferedEnd() {
  27216. return getMappedTime(effectiveBufferingItem(), "integrated", c2.bufferingAsset, "bufferedPos", "bufferedEnd");
  27217. },
  27218. get currentTime() {
  27219. return getMappedTime(c2.effectivePlayingItem, "integrated", c2.effectivePlayingAsset, "timelinePos", "currentTime");
  27220. },
  27221. set currentTime(time) {
  27222. seekTo(time, "integrated");
  27223. },
  27224. get duration() {
  27225. return getMappedDuration("integrated");
  27226. },
  27227. get seekableStart() {
  27228. var _c$primaryDetails3;
  27229. return findMappedTime(((_c$primaryDetails3 = c2.primaryDetails) == null ? void 0 : _c$primaryDetails3.fragmentStart) || 0, "integrated");
  27230. }
  27231. },
  27232. skip: () => {
  27233. const item = c2.effectivePlayingItem;
  27234. const event = item == null ? void 0 : item.event;
  27235. if (event && !event.restrictions.skip) {
  27236. const index2 = c2.findItemIndex(item);
  27237. if (event.appendInPlace) {
  27238. const time = item.playout.start + item.event.duration;
  27239. seekTo(time + 1e-3, "playout");
  27240. } else {
  27241. c2.advanceAfterAssetEnded(event, index2, Infinity);
  27242. }
  27243. }
  27244. }
  27245. };
  27246. }
  27247. return this.manager;
  27248. }
  27249. // Schedule getters
  27250. get effectivePlayingItem() {
  27251. return this.waitingItem || this.playingItem || this.endedItem;
  27252. }
  27253. get effectivePlayingAsset() {
  27254. return this.playingAsset || this.endedAsset;
  27255. }
  27256. get playingLastItem() {
  27257. var _this$schedule;
  27258. const playingItem = this.playingItem;
  27259. const items = (_this$schedule = this.schedule) == null ? void 0 : _this$schedule.items;
  27260. if (!this.playbackStarted || !playingItem || !items) {
  27261. return false;
  27262. }
  27263. return this.findItemIndex(playingItem) === items.length - 1;
  27264. }
  27265. get playbackStarted() {
  27266. return this.effectivePlayingItem !== null;
  27267. }
  27268. // Media getters and event callbacks
  27269. get currentTime() {
  27270. var _this$bufferingItem, _this$bufferingItem$e, _media;
  27271. if (this.mediaSelection === null) {
  27272. return void 0;
  27273. }
  27274. const queuedForPlayback = this.waitingItem || this.playingItem;
  27275. if (this.isInterstitial(queuedForPlayback) && !queuedForPlayback.event.appendInPlace) {
  27276. return void 0;
  27277. }
  27278. let media = this.media;
  27279. if (!media && (_this$bufferingItem = this.bufferingItem) != null && (_this$bufferingItem$e = _this$bufferingItem.event) != null && _this$bufferingItem$e.appendInPlace) {
  27280. media = this.primaryMedia;
  27281. }
  27282. const currentTime = (_media = media) == null ? void 0 : _media.currentTime;
  27283. if (currentTime === void 0 || !isFiniteNumber(currentTime)) {
  27284. return void 0;
  27285. }
  27286. return currentTime;
  27287. }
  27288. get primaryMedia() {
  27289. var _this$detachedData;
  27290. return this.media || ((_this$detachedData = this.detachedData) == null ? void 0 : _this$detachedData.media) || null;
  27291. }
  27292. isInterstitial(item) {
  27293. return !!(item != null && item.event);
  27294. }
  27295. retreiveMediaSource(assetId, toSegment) {
  27296. const player = this.getAssetPlayer(assetId);
  27297. if (player) {
  27298. this.transferMediaFromPlayer(player, toSegment);
  27299. }
  27300. }
  27301. transferMediaFromPlayer(player, toSegment) {
  27302. const appendInPlace = player.interstitial.appendInPlace;
  27303. const playerMedia = player.media;
  27304. if (appendInPlace && playerMedia === this.primaryMedia) {
  27305. this.bufferingAsset = null;
  27306. if (!toSegment || this.isInterstitial(toSegment) && !toSegment.event.appendInPlace) {
  27307. if (toSegment && playerMedia) {
  27308. this.detachedData = {
  27309. media: playerMedia
  27310. };
  27311. return;
  27312. }
  27313. }
  27314. const attachMediaSourceData = player.transferMedia();
  27315. this.log(`transfer MediaSource from ${player} ${stringify(attachMediaSourceData)}`);
  27316. this.detachedData = attachMediaSourceData;
  27317. } else if (toSegment && playerMedia) {
  27318. this.shouldPlay || (this.shouldPlay = !playerMedia.paused);
  27319. }
  27320. }
  27321. transferMediaTo(player, media) {
  27322. var _this$detachedData2, _attachMediaSourceDat;
  27323. if (player.media === media) {
  27324. return;
  27325. }
  27326. let attachMediaSourceData = null;
  27327. const primaryPlayer = this.hls;
  27328. const isAssetPlayer = player !== primaryPlayer;
  27329. const appendInPlace = isAssetPlayer && player.interstitial.appendInPlace;
  27330. const detachedMediaSource = (_this$detachedData2 = this.detachedData) == null ? void 0 : _this$detachedData2.mediaSource;
  27331. let logFromSource;
  27332. if (primaryPlayer.media) {
  27333. if (appendInPlace) {
  27334. attachMediaSourceData = primaryPlayer.transferMedia();
  27335. this.detachedData = attachMediaSourceData;
  27336. }
  27337. logFromSource = `Primary`;
  27338. } else if (detachedMediaSource) {
  27339. const bufferingPlayer = this.getBufferingPlayer();
  27340. if (bufferingPlayer) {
  27341. attachMediaSourceData = bufferingPlayer.transferMedia();
  27342. logFromSource = `${bufferingPlayer}`;
  27343. } else {
  27344. logFromSource = `detached MediaSource`;
  27345. }
  27346. } else {
  27347. logFromSource = `detached media`;
  27348. }
  27349. if (!attachMediaSourceData) {
  27350. if (detachedMediaSource) {
  27351. attachMediaSourceData = this.detachedData;
  27352. this.log(`using detachedData: MediaSource ${stringify(attachMediaSourceData)}`);
  27353. } else if (!this.detachedData || primaryPlayer.media === media) {
  27354. const playerQueue = this.playerQueue;
  27355. if (playerQueue.length > 1) {
  27356. playerQueue.forEach((queuedPlayer) => {
  27357. if (isAssetPlayer && queuedPlayer.interstitial.appendInPlace !== appendInPlace) {
  27358. const interstitial = queuedPlayer.interstitial;
  27359. this.clearInterstitial(queuedPlayer.interstitial, null);
  27360. interstitial.appendInPlace = false;
  27361. if (interstitial.appendInPlace) {
  27362. this.warn(`Could not change append strategy for queued assets ${interstitial}`);
  27363. }
  27364. }
  27365. });
  27366. }
  27367. this.hls.detachMedia();
  27368. this.detachedData = {
  27369. media
  27370. };
  27371. }
  27372. }
  27373. const transferring = attachMediaSourceData && "mediaSource" in attachMediaSourceData && ((_attachMediaSourceDat = attachMediaSourceData.mediaSource) == null ? void 0 : _attachMediaSourceDat.readyState) !== "closed";
  27374. const dataToAttach = transferring && attachMediaSourceData ? attachMediaSourceData : media;
  27375. this.log(`${transferring ? "transfering MediaSource" : "attaching media"} to ${isAssetPlayer ? player : "Primary"} from ${logFromSource}`);
  27376. if (dataToAttach === attachMediaSourceData) {
  27377. const isAssetAtEndOfSchedule = isAssetPlayer && player.assetId === this.schedule.assetIdAtEnd;
  27378. dataToAttach.overrides = {
  27379. duration: this.schedule.duration,
  27380. endOfStream: !isAssetPlayer || isAssetAtEndOfSchedule,
  27381. cueRemoval: !isAssetPlayer
  27382. };
  27383. }
  27384. player.attachMedia(dataToAttach);
  27385. }
  27386. onInterstitialCueEnter() {
  27387. this.onTimeupdate();
  27388. }
  27389. // Scheduling methods
  27390. checkStart() {
  27391. const schedule = this.schedule;
  27392. const interstitialEvents = schedule.events;
  27393. if (!interstitialEvents || this.playbackDisabled || !this.media) {
  27394. return;
  27395. }
  27396. if (this.bufferedPos === -1) {
  27397. this.bufferedPos = 0;
  27398. }
  27399. const timelinePos = this.timelinePos;
  27400. const effectivePlayingItem = this.effectivePlayingItem;
  27401. if (timelinePos === -1) {
  27402. const startPosition = this.hls.startPosition;
  27403. this.timelinePos = startPosition;
  27404. if (interstitialEvents.length && interstitialEvents[0].cue.pre) {
  27405. const index2 = schedule.findEventIndex(interstitialEvents[0].identifier);
  27406. this.setSchedulePosition(index2);
  27407. } else if (startPosition >= 0 || !this.primaryLive) {
  27408. const start = this.timelinePos = startPosition > 0 ? startPosition : 0;
  27409. const index2 = schedule.findItemIndexAtTime(start);
  27410. this.setSchedulePosition(index2);
  27411. }
  27412. } else if (effectivePlayingItem && !this.playingItem) {
  27413. const index2 = schedule.findItemIndex(effectivePlayingItem);
  27414. this.setSchedulePosition(index2);
  27415. }
  27416. }
  27417. advanceAfterAssetEnded(interstitial, index2, assetListIndex) {
  27418. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex);
  27419. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  27420. this.setSchedulePosition(index2, nextAssetIndex);
  27421. } else {
  27422. const scheduleItems = this.schedule.items;
  27423. if (scheduleItems) {
  27424. const nextIndex = index2 + 1;
  27425. const scheduleLength = scheduleItems.length;
  27426. if (nextIndex >= scheduleLength) {
  27427. this.setSchedulePosition(-1);
  27428. return;
  27429. }
  27430. const resumptionTime = interstitial.resumeTime;
  27431. if (this.timelinePos < resumptionTime) {
  27432. this.timelinePos = resumptionTime;
  27433. this.checkBuffer();
  27434. }
  27435. this.setSchedulePosition(nextIndex);
  27436. }
  27437. }
  27438. }
  27439. setScheduleToAssetAtTime(time, playingAsset) {
  27440. const schedule = this.schedule;
  27441. const parentIdentifier = playingAsset.parentIdentifier;
  27442. const interstitial = schedule.getEvent(parentIdentifier);
  27443. if (interstitial) {
  27444. const itemIndex = schedule.findEventIndex(parentIdentifier);
  27445. const assetListIndex = schedule.findAssetIndex(interstitial, time);
  27446. this.advanceAfterAssetEnded(interstitial, itemIndex, assetListIndex - 1);
  27447. }
  27448. }
  27449. setSchedulePosition(index2, assetListIndex) {
  27450. const scheduleItems = this.schedule.items;
  27451. if (!scheduleItems || this.playbackDisabled) {
  27452. return;
  27453. }
  27454. this.log(`setSchedulePosition ${index2}, ${assetListIndex}`);
  27455. const scheduledItem = index2 >= 0 ? scheduleItems[index2] : null;
  27456. const currentItem = this.playingItem;
  27457. const playingLastItem = this.playingLastItem;
  27458. if (this.isInterstitial(currentItem)) {
  27459. var _interstitial$assetLi;
  27460. const interstitial = currentItem.event;
  27461. const playingAsset = this.playingAsset;
  27462. const assetId = playingAsset == null ? void 0 : playingAsset.identifier;
  27463. const player = assetId ? this.getAssetPlayer(assetId) : null;
  27464. if (player && assetId && (!this.eventItemsMatch(currentItem, scheduledItem) || assetListIndex !== void 0 && assetId !== ((_interstitial$assetLi = interstitial.assetList) == null ? void 0 : _interstitial$assetLi[assetListIndex].identifier))) {
  27465. var _this$detachedData3;
  27466. const playingAssetListIndex = interstitial.findAssetIndex(playingAsset);
  27467. this.log(`INTERSTITIAL_ASSET_ENDED ${playingAssetListIndex + 1}/${interstitial.assetList.length} ${eventAssetToString(playingAsset)}`);
  27468. this.endedAsset = playingAsset;
  27469. this.playingAsset = null;
  27470. this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED, {
  27471. asset: playingAsset,
  27472. assetListIndex: playingAssetListIndex,
  27473. event: interstitial,
  27474. schedule: scheduleItems.slice(0),
  27475. scheduleIndex: index2,
  27476. player
  27477. });
  27478. if (currentItem !== this.playingItem) {
  27479. if (this.itemsMatch(currentItem, this.playingItem) && !this.playingAsset) {
  27480. this.advanceAfterAssetEnded(interstitial, this.findItemIndex(this.playingItem), playingAssetListIndex);
  27481. }
  27482. return;
  27483. }
  27484. this.retreiveMediaSource(assetId, scheduledItem);
  27485. if (player.media && !((_this$detachedData3 = this.detachedData) != null && _this$detachedData3.mediaSource)) {
  27486. player.detachMedia();
  27487. }
  27488. }
  27489. if (!this.eventItemsMatch(currentItem, scheduledItem)) {
  27490. this.endedItem = currentItem;
  27491. this.playingItem = null;
  27492. this.log(`INTERSTITIAL_ENDED ${interstitial} ${segmentToString(currentItem)}`);
  27493. interstitial.hasPlayed = true;
  27494. this.hls.trigger(Events.INTERSTITIAL_ENDED, {
  27495. event: interstitial,
  27496. schedule: scheduleItems.slice(0),
  27497. scheduleIndex: index2
  27498. });
  27499. if (interstitial.cue.once) {
  27500. this.updateSchedule();
  27501. const items = this.schedule.items;
  27502. if (scheduledItem && items) {
  27503. const updatedIndex = this.findItemIndex(scheduledItem);
  27504. this.advanceSchedule(updatedIndex, items, assetListIndex, currentItem, playingLastItem);
  27505. }
  27506. return;
  27507. }
  27508. }
  27509. }
  27510. this.advanceSchedule(index2, scheduleItems, assetListIndex, currentItem, playingLastItem);
  27511. }
  27512. advanceSchedule(index2, scheduleItems, assetListIndex, currentItem, playedLastItem) {
  27513. const scheduledItem = index2 >= 0 ? scheduleItems[index2] : null;
  27514. const media = this.primaryMedia;
  27515. const playerQueue = this.playerQueue;
  27516. if (playerQueue.length) {
  27517. playerQueue.forEach((player) => {
  27518. const interstitial = player.interstitial;
  27519. const queuedIndex = this.schedule.findEventIndex(interstitial.identifier);
  27520. if (queuedIndex < index2 || queuedIndex > index2 + 1) {
  27521. this.clearInterstitial(interstitial, scheduledItem);
  27522. }
  27523. });
  27524. }
  27525. if (this.isInterstitial(scheduledItem)) {
  27526. this.timelinePos = Math.min(Math.max(this.timelinePos, scheduledItem.start), scheduledItem.end);
  27527. const interstitial = scheduledItem.event;
  27528. if (assetListIndex === void 0) {
  27529. assetListIndex = this.schedule.findAssetIndex(interstitial, this.timelinePos);
  27530. const assetIndexCandidate = getNextAssetIndex(interstitial, assetListIndex - 1);
  27531. if (interstitial.isAssetPastPlayoutLimit(assetIndexCandidate)) {
  27532. this.advanceAfterAssetEnded(interstitial, index2, assetListIndex);
  27533. return;
  27534. }
  27535. assetListIndex = assetIndexCandidate;
  27536. }
  27537. const waitingItem = this.waitingItem;
  27538. if (!this.assetsBuffered(scheduledItem, media)) {
  27539. this.setBufferingItem(scheduledItem);
  27540. }
  27541. let player = this.preloadAssets(interstitial, assetListIndex);
  27542. if (!this.eventItemsMatch(scheduledItem, waitingItem || currentItem)) {
  27543. this.waitingItem = scheduledItem;
  27544. this.log(`INTERSTITIAL_STARTED ${segmentToString(scheduledItem)} ${interstitial.appendInPlace ? "append in place" : ""}`);
  27545. this.hls.trigger(Events.INTERSTITIAL_STARTED, {
  27546. event: interstitial,
  27547. schedule: scheduleItems.slice(0),
  27548. scheduleIndex: index2
  27549. });
  27550. }
  27551. if (!interstitial.assetListLoaded) {
  27552. this.log(`Waiting for ASSET-LIST to complete loading ${interstitial}`);
  27553. return;
  27554. }
  27555. if (interstitial.assetListLoader) {
  27556. interstitial.assetListLoader.destroy();
  27557. interstitial.assetListLoader = void 0;
  27558. }
  27559. if (!media) {
  27560. this.log(`Waiting for attachMedia to start Interstitial ${interstitial}`);
  27561. return;
  27562. }
  27563. this.waitingItem = this.endedItem = null;
  27564. this.playingItem = scheduledItem;
  27565. const assetItem = interstitial.assetList[assetListIndex];
  27566. if (!assetItem) {
  27567. const nextItem = scheduleItems[index2 + 1];
  27568. const _media2 = this.media;
  27569. if (nextItem && _media2 && !this.isInterstitial(nextItem) && _media2.currentTime < nextItem.start) {
  27570. _media2.currentTime = this.timelinePos = nextItem.start;
  27571. }
  27572. this.advanceAfterAssetEnded(interstitial, index2, assetListIndex || 0);
  27573. return;
  27574. }
  27575. if (!player) {
  27576. player = this.getAssetPlayer(assetItem.identifier);
  27577. }
  27578. if (player === null || player.destroyed) {
  27579. const assetListLength = interstitial.assetList.length;
  27580. this.warn(`asset ${assetListIndex + 1}/${assetListLength} player destroyed ${interstitial}`);
  27581. player = this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  27582. }
  27583. if (!this.eventItemsMatch(scheduledItem, this.bufferingItem)) {
  27584. if (interstitial.appendInPlace && this.isAssetBuffered(assetItem)) {
  27585. return;
  27586. }
  27587. }
  27588. this.startAssetPlayer(player, assetListIndex, scheduleItems, index2, media);
  27589. if (this.shouldPlay) {
  27590. playWithCatch(player.media);
  27591. }
  27592. } else if (scheduledItem !== null) {
  27593. this.resumePrimary(scheduledItem, index2, currentItem);
  27594. if (this.shouldPlay) {
  27595. playWithCatch(this.hls.media);
  27596. }
  27597. } else if (playedLastItem && this.isInterstitial(currentItem)) {
  27598. this.endedItem = null;
  27599. this.playingItem = currentItem;
  27600. if (!currentItem.event.appendInPlace) {
  27601. this.attachPrimary(this.schedule.durations.primary, null);
  27602. }
  27603. }
  27604. }
  27605. get playbackDisabled() {
  27606. return this.hls.config.enableInterstitialPlayback === false;
  27607. }
  27608. get primaryDetails() {
  27609. var _this$mediaSelection, _this$mediaSelection$;
  27610. return (_this$mediaSelection = this.mediaSelection) == null ? void 0 : (_this$mediaSelection$ = _this$mediaSelection.main) == null ? void 0 : _this$mediaSelection$.details;
  27611. }
  27612. get primaryLive() {
  27613. var _this$primaryDetails;
  27614. return !!((_this$primaryDetails = this.primaryDetails) != null && _this$primaryDetails.live);
  27615. }
  27616. resumePrimary(scheduledItem, index2, fromItem) {
  27617. var _this$detachedData4;
  27618. this.playingItem = scheduledItem;
  27619. this.playingAsset = this.endedAsset = null;
  27620. this.waitingItem = this.endedItem = null;
  27621. this.bufferedToItem(scheduledItem);
  27622. this.log(`resuming ${segmentToString(scheduledItem)}`);
  27623. if (!((_this$detachedData4 = this.detachedData) != null && _this$detachedData4.mediaSource)) {
  27624. let timelinePos = this.timelinePos;
  27625. if (timelinePos < scheduledItem.start || timelinePos >= scheduledItem.end) {
  27626. timelinePos = this.getPrimaryResumption(scheduledItem, index2);
  27627. this.timelinePos = timelinePos;
  27628. }
  27629. this.attachPrimary(timelinePos, scheduledItem);
  27630. }
  27631. if (!fromItem) {
  27632. return;
  27633. }
  27634. const scheduleItems = this.schedule.items;
  27635. if (!scheduleItems) {
  27636. return;
  27637. }
  27638. this.log(`INTERSTITIALS_PRIMARY_RESUMED ${segmentToString(scheduledItem)}`);
  27639. this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED, {
  27640. schedule: scheduleItems.slice(0),
  27641. scheduleIndex: index2
  27642. });
  27643. this.checkBuffer();
  27644. }
  27645. getPrimaryResumption(scheduledItem, index2) {
  27646. const itemStart = scheduledItem.start;
  27647. if (this.primaryLive) {
  27648. const details = this.primaryDetails;
  27649. if (index2 === 0) {
  27650. return this.hls.startPosition;
  27651. } else if (details && (itemStart < details.fragmentStart || itemStart > details.edge)) {
  27652. return this.hls.liveSyncPosition || -1;
  27653. }
  27654. }
  27655. return itemStart;
  27656. }
  27657. isAssetBuffered(asset) {
  27658. const player = this.getAssetPlayer(asset.identifier);
  27659. if (player != null && player.hls) {
  27660. return player.hls.bufferedToEnd;
  27661. }
  27662. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  27663. return bufferInfo.end + 1 >= asset.timelineStart + (asset.duration || 0);
  27664. }
  27665. attachPrimary(timelinePos, item, skipSeekToStartPosition) {
  27666. if (item) {
  27667. this.setBufferingItem(item);
  27668. } else {
  27669. this.bufferingItem = this.playingItem;
  27670. }
  27671. this.bufferingAsset = null;
  27672. const media = this.primaryMedia;
  27673. if (!media) {
  27674. return;
  27675. }
  27676. const hls = this.hls;
  27677. if (hls.media) {
  27678. this.checkBuffer();
  27679. } else {
  27680. this.transferMediaTo(hls, media);
  27681. if (skipSeekToStartPosition) {
  27682. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  27683. }
  27684. }
  27685. if (!skipSeekToStartPosition) {
  27686. this.timelinePos = timelinePos;
  27687. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  27688. }
  27689. }
  27690. startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition) {
  27691. var _hls$mainForwardBuffe;
  27692. const hls = this.hls;
  27693. if (!hls.loadingEnabled || !hls.media || Math.abs((((_hls$mainForwardBuffe = hls.mainForwardBufferInfo) == null ? void 0 : _hls$mainForwardBuffe.start) || hls.media.currentTime) - timelinePos) > 0.5) {
  27694. hls.startLoad(timelinePos, skipSeekToStartPosition);
  27695. } else if (!hls.bufferingEnabled) {
  27696. hls.resumeBuffering();
  27697. }
  27698. }
  27699. // HLS.js event callbacks
  27700. onManifestLoading() {
  27701. this.stopLoad();
  27702. this.schedule.reset();
  27703. this.emptyPlayerQueue();
  27704. this.clearScheduleState();
  27705. this.shouldPlay = false;
  27706. this.bufferedPos = this.timelinePos = -1;
  27707. this.mediaSelection = this.altSelection = this.manager = this.requiredTracks = null;
  27708. this.hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  27709. this.hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  27710. }
  27711. onLevelUpdated(event, data) {
  27712. if (data.level === -1) {
  27713. return;
  27714. }
  27715. const main = this.hls.levels[data.level];
  27716. const currentSelection = _objectSpread2(_objectSpread2({}, this.mediaSelection || this.altSelection), {}, {
  27717. main
  27718. });
  27719. this.mediaSelection = currentSelection;
  27720. this.schedule.parseInterstitialDateRanges(currentSelection, this.hls.config.interstitialAppendInPlace);
  27721. if (!this.effectivePlayingItem && this.schedule.items) {
  27722. this.checkStart();
  27723. }
  27724. }
  27725. onAudioTrackUpdated(event, data) {
  27726. const audio = this.hls.audioTracks[data.id];
  27727. const previousSelection = this.mediaSelection;
  27728. if (!previousSelection) {
  27729. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  27730. audio
  27731. });
  27732. return;
  27733. }
  27734. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  27735. audio
  27736. });
  27737. this.mediaSelection = currentSelection;
  27738. }
  27739. onSubtitleTrackUpdated(event, data) {
  27740. const subtitles = this.hls.subtitleTracks[data.id];
  27741. const previousSelection = this.mediaSelection;
  27742. if (!previousSelection) {
  27743. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  27744. subtitles
  27745. });
  27746. return;
  27747. }
  27748. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  27749. subtitles
  27750. });
  27751. this.mediaSelection = currentSelection;
  27752. }
  27753. onAudioTrackSwitching(event, data) {
  27754. const audioOption = getBasicSelectionOption(data);
  27755. this.playerQueue.forEach((player) => player.hls.setAudioOption(data) || player.hls.setAudioOption(audioOption));
  27756. }
  27757. onSubtitleTrackSwitch(event, data) {
  27758. const subtitleOption = getBasicSelectionOption(data);
  27759. this.playerQueue.forEach((player) => player.hls.setSubtitleOption(data) || data.id !== -1 && player.hls.setSubtitleOption(subtitleOption));
  27760. }
  27761. onBufferCodecs(event, data) {
  27762. const requiredTracks = data.tracks;
  27763. if (requiredTracks) {
  27764. this.requiredTracks = requiredTracks;
  27765. }
  27766. }
  27767. onBufferAppended(event, data) {
  27768. this.checkBuffer();
  27769. }
  27770. onBufferFlushed(event, data) {
  27771. const playingItem = this.playingItem;
  27772. if (playingItem && !this.itemsMatch(playingItem, this.bufferingItem) && !this.isInterstitial(playingItem)) {
  27773. const timelinePos = this.timelinePos;
  27774. this.bufferedPos = timelinePos;
  27775. this.checkBuffer();
  27776. }
  27777. }
  27778. onBufferedToEnd(event) {
  27779. const interstitialEvents = this.schedule.events;
  27780. if (this.bufferedPos < Number.MAX_VALUE && interstitialEvents) {
  27781. for (let i2 = 0; i2 < interstitialEvents.length; i2++) {
  27782. const interstitial = interstitialEvents[i2];
  27783. if (interstitial.cue.post) {
  27784. var _this$schedule$items;
  27785. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  27786. const item = (_this$schedule$items = this.schedule.items) == null ? void 0 : _this$schedule$items[scheduleIndex];
  27787. if (this.isInterstitial(item) && this.eventItemsMatch(item, this.bufferingItem)) {
  27788. this.bufferedToItem(item, 0);
  27789. }
  27790. break;
  27791. }
  27792. }
  27793. this.bufferedPos = Number.MAX_VALUE;
  27794. }
  27795. }
  27796. onMediaEnded(event) {
  27797. const playingItem = this.playingItem;
  27798. if (!this.playingLastItem && playingItem) {
  27799. const playingIndex = this.findItemIndex(playingItem);
  27800. this.setSchedulePosition(playingIndex + 1);
  27801. } else {
  27802. this.shouldPlay = false;
  27803. }
  27804. }
  27805. updateItem(previousItem, time) {
  27806. const items = this.schedule.items;
  27807. if (previousItem && items) {
  27808. const index2 = this.findItemIndex(previousItem, time);
  27809. return items[index2] || null;
  27810. }
  27811. return null;
  27812. }
  27813. trimInPlace(updatedItem, itemBeforeUpdate) {
  27814. if (this.isInterstitial(updatedItem) && updatedItem.event.appendInPlace && itemBeforeUpdate.end - updatedItem.end > 0.25) {
  27815. updatedItem.event.assetList.forEach((asset, index2) => {
  27816. if (updatedItem.event.isAssetPastPlayoutLimit(index2)) {
  27817. this.clearAssetPlayer(asset.identifier, null);
  27818. }
  27819. });
  27820. const flushStart = updatedItem.end + 0.25;
  27821. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, flushStart, 0);
  27822. if (bufferInfo.end > flushStart || (bufferInfo.nextStart || 0) > flushStart) {
  27823. this.attachPrimary(flushStart, null);
  27824. this.flushFrontBuffer(flushStart);
  27825. }
  27826. }
  27827. }
  27828. itemsMatch(a2, b2) {
  27829. return !!b2 && (a2 === b2 || a2.event && b2.event && this.eventItemsMatch(a2, b2) || !a2.event && !b2.event && this.findItemIndex(a2) === this.findItemIndex(b2));
  27830. }
  27831. eventItemsMatch(a2, b2) {
  27832. var _b$event;
  27833. return !!b2 && (a2 === b2 || a2.event.identifier === ((_b$event = b2.event) == null ? void 0 : _b$event.identifier));
  27834. }
  27835. findItemIndex(item, time) {
  27836. return item ? this.schedule.findItemIndex(item, time) : -1;
  27837. }
  27838. updateSchedule() {
  27839. const mediaSelection = this.mediaSelection;
  27840. if (!mediaSelection) {
  27841. return;
  27842. }
  27843. this.schedule.updateSchedule(mediaSelection, []);
  27844. }
  27845. // Schedule buffer control
  27846. checkBuffer(starved) {
  27847. const items = this.schedule.items;
  27848. if (!items) {
  27849. return;
  27850. }
  27851. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  27852. if (starved) {
  27853. this.bufferedPos = this.timelinePos;
  27854. }
  27855. starved || (starved = bufferInfo.len < 1);
  27856. this.updateBufferedPos(bufferInfo.end, items, starved);
  27857. }
  27858. updateBufferedPos(bufferEnd, items, bufferIsEmpty) {
  27859. const schedule = this.schedule;
  27860. const bufferingItem = this.bufferingItem;
  27861. if (this.bufferedPos > bufferEnd) {
  27862. return;
  27863. }
  27864. if (items.length === 1 && this.itemsMatch(items[0], bufferingItem)) {
  27865. this.bufferedPos = bufferEnd;
  27866. return;
  27867. }
  27868. const playingItem = this.playingItem;
  27869. const playingIndex = this.findItemIndex(playingItem);
  27870. let bufferEndIndex = schedule.findItemIndexAtTime(bufferEnd);
  27871. if (this.bufferedPos < bufferEnd) {
  27872. var _nextItemToBuffer$eve, _bufferingItem$event;
  27873. const bufferingIndex = this.findItemIndex(bufferingItem);
  27874. const nextToBufferIndex = Math.min(bufferingIndex + 1, items.length - 1);
  27875. const nextItemToBuffer = items[nextToBufferIndex];
  27876. if (bufferEndIndex === -1 && bufferingItem && bufferEnd >= bufferingItem.end || (_nextItemToBuffer$eve = nextItemToBuffer.event) != null && _nextItemToBuffer$eve.appendInPlace && bufferEnd + 0.01 >= nextItemToBuffer.start) {
  27877. bufferEndIndex = nextToBufferIndex;
  27878. }
  27879. if (nextToBufferIndex - playingIndex > 1 && (bufferingItem == null ? void 0 : (_bufferingItem$event = bufferingItem.event) == null ? void 0 : _bufferingItem$event.appendInPlace) === false) {
  27880. return;
  27881. }
  27882. this.bufferedPos = bufferEnd;
  27883. if (bufferEndIndex > bufferingIndex && bufferEndIndex > playingIndex) {
  27884. this.bufferedToItem(nextItemToBuffer);
  27885. } else {
  27886. const details = this.primaryDetails;
  27887. if (this.primaryLive && details && bufferEnd > details.edge - details.targetduration && nextItemToBuffer.start < details.edge + this.hls.config.interstitialLiveLookAhead && this.isInterstitial(nextItemToBuffer)) {
  27888. this.preloadAssets(nextItemToBuffer.event, 0);
  27889. }
  27890. }
  27891. } else if (bufferIsEmpty && playingItem && !this.itemsMatch(playingItem, bufferingItem)) {
  27892. if (bufferEndIndex === playingIndex) {
  27893. this.bufferedToItem(playingItem);
  27894. } else if (bufferEndIndex === playingIndex + 1) {
  27895. this.bufferedToItem(items[bufferEndIndex]);
  27896. }
  27897. }
  27898. }
  27899. assetsBuffered(item, media) {
  27900. const assetList = item.event.assetList;
  27901. if (assetList.length === 0) {
  27902. return false;
  27903. }
  27904. return !item.event.assetList.some((asset) => {
  27905. const player = this.getAssetPlayer(asset.identifier);
  27906. return !(player != null && player.bufferedInPlaceToEnd(media));
  27907. });
  27908. }
  27909. setBufferingItem(item) {
  27910. const bufferingLast = this.bufferingItem;
  27911. const schedule = this.schedule;
  27912. if (!this.itemsMatch(item, bufferingLast)) {
  27913. const {
  27914. items,
  27915. events
  27916. } = schedule;
  27917. if (!items || !events) {
  27918. return bufferingLast;
  27919. }
  27920. const isInterstitial = this.isInterstitial(item);
  27921. const bufferingPlayer = this.getBufferingPlayer();
  27922. this.bufferingItem = item;
  27923. this.bufferedPos = Math.max(item.start, Math.min(item.end, this.timelinePos));
  27924. const timeRemaining = bufferingPlayer ? bufferingPlayer.remaining : bufferingLast ? bufferingLast.end - this.timelinePos : 0;
  27925. this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${segmentToString(item)}` + (bufferingLast ? ` (${timeRemaining.toFixed(2)} remaining)` : ""));
  27926. if (!this.playbackDisabled) {
  27927. if (isInterstitial) {
  27928. item.event.assetList.forEach((asset) => {
  27929. const player = this.getAssetPlayer(asset.identifier);
  27930. if (player) {
  27931. player.resumeBuffering();
  27932. }
  27933. });
  27934. } else {
  27935. this.hls.resumeBuffering();
  27936. this.playerQueue.forEach((player) => player.pauseBuffering());
  27937. }
  27938. }
  27939. this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY, {
  27940. events: events.slice(0),
  27941. schedule: items.slice(0),
  27942. bufferingIndex: this.findItemIndex(item),
  27943. playingIndex: this.findItemIndex(this.playingItem)
  27944. });
  27945. } else if (this.bufferingItem !== item) {
  27946. this.bufferingItem = item;
  27947. }
  27948. return bufferingLast;
  27949. }
  27950. bufferedToItem(item, assetListIndex = 0) {
  27951. const bufferingLast = this.setBufferingItem(item);
  27952. if (this.playbackDisabled) {
  27953. return;
  27954. }
  27955. if (this.isInterstitial(item)) {
  27956. this.bufferedToEvent(item, assetListIndex);
  27957. } else if (bufferingLast !== null) {
  27958. this.bufferingAsset = null;
  27959. const detachedData = this.detachedData;
  27960. if (detachedData) {
  27961. if (detachedData.mediaSource) {
  27962. const skipSeekToStartPosition = true;
  27963. this.attachPrimary(item.start, item, skipSeekToStartPosition);
  27964. } else {
  27965. this.preloadPrimary(item);
  27966. }
  27967. } else {
  27968. this.preloadPrimary(item);
  27969. }
  27970. }
  27971. }
  27972. preloadPrimary(item) {
  27973. const index2 = this.findItemIndex(item);
  27974. const timelinePos = this.getPrimaryResumption(item, index2);
  27975. this.startLoadingPrimaryAt(timelinePos);
  27976. }
  27977. bufferedToEvent(item, assetListIndex) {
  27978. const interstitial = item.event;
  27979. const neverLoaded = interstitial.assetList.length === 0 && !interstitial.assetListLoader;
  27980. const playOnce = interstitial.cue.once;
  27981. if (neverLoaded || !playOnce) {
  27982. const player = this.preloadAssets(interstitial, assetListIndex);
  27983. if (player != null && player.interstitial.appendInPlace) {
  27984. const assetItem = interstitial.assetList[assetListIndex];
  27985. const media = this.primaryMedia;
  27986. if (assetItem && media) {
  27987. this.bufferAssetPlayer(player, media);
  27988. }
  27989. }
  27990. }
  27991. }
  27992. preloadAssets(interstitial, assetListIndex) {
  27993. const uri = interstitial.assetUrl;
  27994. const assetListLength = interstitial.assetList.length;
  27995. const neverLoaded = assetListLength === 0 && !interstitial.assetListLoader;
  27996. const playOnce = interstitial.cue.once;
  27997. if (neverLoaded) {
  27998. const timelineStart = interstitial.timelineStart;
  27999. if (interstitial.appendInPlace) {
  28000. var _playingItem$nextEven;
  28001. const playingItem = this.playingItem;
  28002. if (!this.isInterstitial(playingItem) && (playingItem == null ? void 0 : (_playingItem$nextEven = playingItem.nextEvent) == null ? void 0 : _playingItem$nextEven.identifier) === interstitial.identifier) {
  28003. this.flushFrontBuffer(timelineStart + 0.25);
  28004. }
  28005. }
  28006. let hlsStartOffset;
  28007. let liveStartPosition = 0;
  28008. if (!this.playingItem && this.primaryLive) {
  28009. liveStartPosition = this.hls.startPosition;
  28010. if (liveStartPosition === -1) {
  28011. liveStartPosition = this.hls.liveSyncPosition || 0;
  28012. }
  28013. }
  28014. if (liveStartPosition && !(interstitial.cue.pre || interstitial.cue.post)) {
  28015. const startOffset = liveStartPosition - timelineStart;
  28016. if (startOffset > 0) {
  28017. hlsStartOffset = Math.round(startOffset * 1e3) / 1e3;
  28018. }
  28019. }
  28020. this.log(`Load interstitial asset ${assetListIndex + 1}/${uri ? 1 : assetListLength} ${interstitial}${hlsStartOffset ? ` live-start: ${liveStartPosition} start-offset: ${hlsStartOffset}` : ""}`);
  28021. if (uri) {
  28022. return this.createAsset(interstitial, 0, 0, timelineStart, interstitial.duration, uri);
  28023. }
  28024. const assetListLoader = this.assetListLoader.loadAssetList(interstitial, hlsStartOffset);
  28025. if (assetListLoader) {
  28026. interstitial.assetListLoader = assetListLoader;
  28027. }
  28028. } else if (!playOnce && assetListLength) {
  28029. for (let i2 = assetListIndex; i2 < assetListLength; i2++) {
  28030. const asset = interstitial.assetList[i2];
  28031. const playerIndex = this.getAssetPlayerQueueIndex(asset.identifier);
  28032. if ((playerIndex === -1 || this.playerQueue[playerIndex].destroyed) && !asset.error) {
  28033. this.createAssetPlayer(interstitial, asset, i2);
  28034. }
  28035. }
  28036. return this.getAssetPlayer(interstitial.assetList[assetListIndex].identifier);
  28037. }
  28038. return null;
  28039. }
  28040. flushFrontBuffer(startOffset) {
  28041. const requiredTracks = this.requiredTracks;
  28042. if (!requiredTracks) {
  28043. return;
  28044. }
  28045. this.log(`Removing front buffer starting at ${startOffset}`);
  28046. const sourceBufferNames = Object.keys(requiredTracks);
  28047. sourceBufferNames.forEach((type) => {
  28048. this.hls.trigger(Events.BUFFER_FLUSHING, {
  28049. startOffset,
  28050. endOffset: Infinity,
  28051. type
  28052. });
  28053. });
  28054. }
  28055. // Interstitial Asset Player control
  28056. getAssetPlayerQueueIndex(assetId) {
  28057. const playerQueue = this.playerQueue;
  28058. for (let i2 = 0; i2 < playerQueue.length; i2++) {
  28059. if (assetId === playerQueue[i2].assetId) {
  28060. return i2;
  28061. }
  28062. }
  28063. return -1;
  28064. }
  28065. getAssetPlayer(assetId) {
  28066. const index2 = this.getAssetPlayerQueueIndex(assetId);
  28067. return this.playerQueue[index2] || null;
  28068. }
  28069. getBufferingPlayer() {
  28070. const {
  28071. playerQueue,
  28072. primaryMedia
  28073. } = this;
  28074. if (primaryMedia) {
  28075. for (let i2 = 0; i2 < playerQueue.length; i2++) {
  28076. if (playerQueue[i2].media === primaryMedia) {
  28077. return playerQueue[i2];
  28078. }
  28079. }
  28080. }
  28081. return null;
  28082. }
  28083. createAsset(interstitial, assetListIndex, startOffset, timelineStart, duration, uri) {
  28084. const assetItem = {
  28085. parentIdentifier: interstitial.identifier,
  28086. identifier: generateAssetIdentifier(interstitial, uri, assetListIndex),
  28087. duration,
  28088. startOffset,
  28089. timelineStart,
  28090. uri
  28091. };
  28092. return this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  28093. }
  28094. createAssetPlayer(interstitial, assetItem, assetListIndex) {
  28095. const primary = this.hls;
  28096. const userConfig = primary.userConfig;
  28097. let videoPreference = userConfig.videoPreference;
  28098. const currentLevel = primary.loadLevelObj || primary.levels[primary.currentLevel];
  28099. if (videoPreference || currentLevel) {
  28100. videoPreference = _extends({}, videoPreference);
  28101. if (currentLevel.videoCodec) {
  28102. videoPreference.videoCodec = currentLevel.videoCodec;
  28103. }
  28104. if (currentLevel.videoRange) {
  28105. videoPreference.allowedVideoRanges = [currentLevel.videoRange];
  28106. }
  28107. }
  28108. const selectedAudio = primary.audioTracks[primary.audioTrack];
  28109. const selectedSubtitle = primary.subtitleTracks[primary.subtitleTrack];
  28110. let startPosition = 0;
  28111. if (this.primaryLive || interstitial.appendInPlace) {
  28112. const timePastStart = this.timelinePos - assetItem.timelineStart;
  28113. if (timePastStart > 1) {
  28114. const duration = assetItem.duration;
  28115. if (duration && timePastStart < duration) {
  28116. startPosition = timePastStart;
  28117. }
  28118. }
  28119. }
  28120. const assetId = assetItem.identifier;
  28121. const playerConfig = _objectSpread2(_objectSpread2({}, userConfig), {}, {
  28122. autoStartLoad: true,
  28123. startFragPrefetch: true,
  28124. primarySessionId: primary.sessionId,
  28125. assetPlayerId: assetId,
  28126. abrEwmaDefaultEstimate: primary.bandwidthEstimate,
  28127. interstitialsController: void 0,
  28128. startPosition,
  28129. liveDurationInfinity: false,
  28130. testBandwidth: false,
  28131. videoPreference,
  28132. audioPreference: selectedAudio || userConfig.audioPreference,
  28133. subtitlePreference: selectedSubtitle || userConfig.subtitlePreference
  28134. });
  28135. if (interstitial.appendInPlace) {
  28136. interstitial.appendInPlaceStarted = true;
  28137. if (assetItem.timelineStart) {
  28138. playerConfig.timelineOffset = assetItem.timelineStart;
  28139. }
  28140. }
  28141. const cmcd = playerConfig.cmcd;
  28142. if (cmcd != null && cmcd.sessionId && cmcd.contentId) {
  28143. playerConfig.cmcd = _extends({}, cmcd, {
  28144. contentId: hash(assetItem.uri)
  28145. });
  28146. }
  28147. if (this.getAssetPlayer(assetId)) {
  28148. this.warn(`Duplicate date range identifier ${interstitial} and asset ${assetId}`);
  28149. }
  28150. const player = new HlsAssetPlayer(this.HlsPlayerClass, playerConfig, interstitial, assetItem);
  28151. this.playerQueue.push(player);
  28152. interstitial.assetList[assetListIndex] = assetItem;
  28153. const updateAssetPlayerDetails = (details) => {
  28154. if (details.live) {
  28155. const error2 = new Error(`Interstitials MUST be VOD assets ${interstitial}`);
  28156. const errorData = {
  28157. fatal: true,
  28158. type: ErrorTypes.OTHER_ERROR,
  28159. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  28160. error: error2
  28161. };
  28162. this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error2.message);
  28163. return;
  28164. }
  28165. const duration = details.edge - details.fragmentStart;
  28166. const currentAssetDuration = assetItem.duration;
  28167. if (currentAssetDuration === null || duration > currentAssetDuration) {
  28168. this.log(`Interstitial asset "${assetId}" duration change ${currentAssetDuration} > ${duration}`);
  28169. assetItem.duration = duration;
  28170. this.updateSchedule();
  28171. }
  28172. };
  28173. player.on(Events.LEVEL_UPDATED, (event, {
  28174. details
  28175. }) => updateAssetPlayerDetails(details));
  28176. player.on(Events.LEVEL_PTS_UPDATED, (event, {
  28177. details
  28178. }) => updateAssetPlayerDetails(details));
  28179. const onBufferCodecs = (event, data) => {
  28180. const inQueuPlayer = this.getAssetPlayer(assetId);
  28181. if (inQueuPlayer && data.tracks) {
  28182. inQueuPlayer.off(Events.BUFFER_CODECS, onBufferCodecs);
  28183. inQueuPlayer.tracks = data.tracks;
  28184. const media = this.primaryMedia;
  28185. if (this.bufferingAsset === inQueuPlayer.assetItem && media && !inQueuPlayer.media) {
  28186. this.bufferAssetPlayer(inQueuPlayer, media);
  28187. }
  28188. }
  28189. };
  28190. player.on(Events.BUFFER_CODECS, onBufferCodecs);
  28191. const bufferedToEnd = () => {
  28192. var _this$schedule$items2;
  28193. const inQueuPlayer = this.getAssetPlayer(assetId);
  28194. this.log(`buffered to end of asset ${inQueuPlayer}`);
  28195. if (!inQueuPlayer) {
  28196. return;
  28197. }
  28198. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  28199. const item = (_this$schedule$items2 = this.schedule.items) == null ? void 0 : _this$schedule$items2[scheduleIndex];
  28200. if (this.isInterstitial(item)) {
  28201. const assetListIndex2 = interstitial.findAssetIndex(assetItem);
  28202. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex2);
  28203. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  28204. this.bufferedToItem(item, nextAssetIndex);
  28205. } else {
  28206. var _this$schedule$items3;
  28207. const nextItem = (_this$schedule$items3 = this.schedule.items) == null ? void 0 : _this$schedule$items3[scheduleIndex + 1];
  28208. if (nextItem) {
  28209. this.bufferedToItem(nextItem);
  28210. }
  28211. }
  28212. }
  28213. };
  28214. player.on(Events.BUFFERED_TO_END, bufferedToEnd);
  28215. const endedWithAssetIndex = (assetIndex) => {
  28216. return () => {
  28217. const inQueuPlayer = this.getAssetPlayer(assetId);
  28218. if (!inQueuPlayer) {
  28219. return;
  28220. }
  28221. this.shouldPlay = true;
  28222. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  28223. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetIndex);
  28224. };
  28225. };
  28226. player.once(Events.MEDIA_ENDED, endedWithAssetIndex(assetListIndex));
  28227. player.once(Events.PLAYOUT_LIMIT_REACHED, endedWithAssetIndex(Infinity));
  28228. player.on(Events.ERROR, (event, data) => {
  28229. const inQueuPlayer = this.getAssetPlayer(assetId);
  28230. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  28231. if (inQueuPlayer != null && inQueuPlayer.media) {
  28232. const assetCurrentTime = inQueuPlayer.currentTime;
  28233. const distanceFromEnd = inQueuPlayer.duration - assetCurrentTime;
  28234. if (assetCurrentTime && interstitial.appendInPlace && distanceFromEnd / inQueuPlayer.media.playbackRate < 0.5) {
  28235. this.log(`Advancing buffer past end of asset ${assetId} ${interstitial} at ${inQueuPlayer.media.currentTime}`);
  28236. bufferedToEnd();
  28237. } else {
  28238. this.warn(`Stalled at ${assetCurrentTime} of ${assetCurrentTime + distanceFromEnd} in asset ${assetId} ${interstitial}`);
  28239. this.onTimeupdate();
  28240. this.checkBuffer(true);
  28241. }
  28242. }
  28243. return;
  28244. }
  28245. this.handleAssetItemError(data, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, `Asset player error ${data.error} ${interstitial}`);
  28246. });
  28247. player.on(Events.DESTROYING, () => {
  28248. const inQueuPlayer = this.getAssetPlayer(assetId);
  28249. if (!inQueuPlayer) {
  28250. return;
  28251. }
  28252. const error2 = new Error(`Asset player destroyed unexpectedly ${assetId}`);
  28253. const errorData = {
  28254. fatal: true,
  28255. type: ErrorTypes.OTHER_ERROR,
  28256. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  28257. error: error2
  28258. };
  28259. this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error2.message);
  28260. });
  28261. this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${eventAssetToString(assetItem)}`);
  28262. this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED, {
  28263. asset: assetItem,
  28264. assetListIndex,
  28265. event: interstitial,
  28266. player
  28267. });
  28268. return player;
  28269. }
  28270. clearInterstitial(interstitial, toSegment) {
  28271. interstitial.assetList.forEach((asset) => {
  28272. this.clearAssetPlayer(asset.identifier, toSegment);
  28273. });
  28274. interstitial.reset();
  28275. }
  28276. resetAssetPlayer(assetId) {
  28277. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  28278. if (playerIndex !== -1) {
  28279. this.log(`reset asset player "${assetId}" after error`);
  28280. const player = this.playerQueue[playerIndex];
  28281. this.transferMediaFromPlayer(player, null);
  28282. player.resetDetails();
  28283. }
  28284. }
  28285. clearAssetPlayer(assetId, toSegment) {
  28286. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  28287. if (playerIndex !== -1) {
  28288. this.log(`clear asset player "${assetId}" toSegment: ${toSegment ? segmentToString(toSegment) : toSegment}`);
  28289. const player = this.playerQueue[playerIndex];
  28290. this.transferMediaFromPlayer(player, toSegment);
  28291. this.playerQueue.splice(playerIndex, 1);
  28292. player.destroy();
  28293. }
  28294. }
  28295. emptyPlayerQueue() {
  28296. let player;
  28297. while (player = this.playerQueue.pop()) {
  28298. player.destroy();
  28299. }
  28300. this.playerQueue = [];
  28301. }
  28302. startAssetPlayer(player, assetListIndex, scheduleItems, scheduleIndex, media) {
  28303. const {
  28304. interstitial,
  28305. assetItem,
  28306. assetId
  28307. } = player;
  28308. const assetListLength = interstitial.assetList.length;
  28309. const playingAsset = this.playingAsset;
  28310. this.endedAsset = null;
  28311. this.playingAsset = assetItem;
  28312. if (!playingAsset || playingAsset.identifier !== assetId) {
  28313. if (playingAsset) {
  28314. this.clearAssetPlayer(playingAsset.identifier, scheduleItems[scheduleIndex]);
  28315. delete playingAsset.error;
  28316. }
  28317. this.log(`INTERSTITIAL_ASSET_STARTED ${assetListIndex + 1}/${assetListLength} ${eventAssetToString(assetItem)}`);
  28318. this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED, {
  28319. asset: assetItem,
  28320. assetListIndex,
  28321. event: interstitial,
  28322. schedule: scheduleItems.slice(0),
  28323. scheduleIndex,
  28324. player
  28325. });
  28326. }
  28327. this.bufferAssetPlayer(player, media);
  28328. }
  28329. bufferAssetPlayer(player, media) {
  28330. var _this$schedule$items4, _this$detachedData5;
  28331. const {
  28332. interstitial,
  28333. assetItem
  28334. } = player;
  28335. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  28336. const item = (_this$schedule$items4 = this.schedule.items) == null ? void 0 : _this$schedule$items4[scheduleIndex];
  28337. if (!item) {
  28338. return;
  28339. }
  28340. this.setBufferingItem(item);
  28341. this.bufferingAsset = assetItem;
  28342. const bufferingPlayer = this.getBufferingPlayer();
  28343. if (bufferingPlayer === player) {
  28344. return;
  28345. }
  28346. const appendInPlaceNext = interstitial.appendInPlace;
  28347. if (appendInPlaceNext && (bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial.appendInPlace) === false) {
  28348. return;
  28349. }
  28350. const activeTracks = (bufferingPlayer == null ? void 0 : bufferingPlayer.tracks) || ((_this$detachedData5 = this.detachedData) == null ? void 0 : _this$detachedData5.tracks) || this.requiredTracks;
  28351. if (appendInPlaceNext && assetItem !== this.playingAsset) {
  28352. if (!player.tracks) {
  28353. return;
  28354. }
  28355. if (activeTracks && !isCompatibleTrackChange(activeTracks, player.tracks)) {
  28356. const error2 = new Error(`Asset ${eventAssetToString(assetItem)} SourceBuffer tracks ('${Object.keys(player.tracks)}') are not compatible with primary content tracks ('${Object.keys(activeTracks)}')`);
  28357. const errorData = {
  28358. fatal: true,
  28359. type: ErrorTypes.OTHER_ERROR,
  28360. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  28361. error: error2
  28362. };
  28363. const assetListIndex = interstitial.findAssetIndex(assetItem);
  28364. this.handleAssetItemError(errorData, interstitial, scheduleIndex, assetListIndex, error2.message);
  28365. return;
  28366. }
  28367. }
  28368. this.transferMediaTo(player, media);
  28369. }
  28370. handleAssetItemError(data, interstitial, scheduleIndex, assetListIndex, errorMessage) {
  28371. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  28372. return;
  28373. }
  28374. const assetItem = interstitial.assetList[assetListIndex];
  28375. this.warn(`INTERSTITIAL_ASSET_ERROR ${assetItem ? eventAssetToString(assetItem) : assetItem} ${data.error}`);
  28376. const assetId = assetItem == null ? void 0 : assetItem.identifier;
  28377. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  28378. const player = this.playerQueue[playerIndex] || null;
  28379. const items = this.schedule.items;
  28380. const interstitialAssetError = _extends({}, data, {
  28381. fatal: false,
  28382. errorAction: createDoNothingErrorAction(true),
  28383. asset: assetItem,
  28384. assetListIndex,
  28385. event: interstitial,
  28386. schedule: items,
  28387. scheduleIndex,
  28388. player
  28389. });
  28390. this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR, interstitialAssetError);
  28391. if (!data.fatal) {
  28392. return;
  28393. }
  28394. const playingAsset = this.playingAsset;
  28395. const error2 = new Error(errorMessage);
  28396. if (assetItem) {
  28397. this.clearAssetPlayer(assetId, null);
  28398. assetItem.error = error2;
  28399. }
  28400. if (!interstitial.assetList.some((asset) => !asset.error)) {
  28401. interstitial.error = error2;
  28402. } else {
  28403. for (let i2 = assetListIndex; i2 < interstitial.assetList.length; i2++) {
  28404. this.resetAssetPlayer(interstitial.assetList[i2].identifier);
  28405. }
  28406. this.updateSchedule();
  28407. }
  28408. if (interstitial.error) {
  28409. this.primaryFallback(interstitial);
  28410. } else if (playingAsset && playingAsset.identifier === assetId) {
  28411. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetListIndex);
  28412. }
  28413. }
  28414. primaryFallback(interstitial) {
  28415. const flushStart = interstitial.timelineStart;
  28416. const playingItem = this.effectivePlayingItem;
  28417. this.updateSchedule();
  28418. if (playingItem) {
  28419. this.log(`Fallback to primary from event "${interstitial.identifier}" start: ${flushStart} pos: ${this.timelinePos} playing: ${playingItem ? segmentToString(playingItem) : "<none>"} error: ${interstitial.error}`);
  28420. let timelinePos = this.timelinePos;
  28421. if (timelinePos === -1) {
  28422. timelinePos = this.hls.startPosition;
  28423. }
  28424. const newPlayingItem = this.updateItem(playingItem, timelinePos);
  28425. if (this.itemsMatch(playingItem, newPlayingItem)) {
  28426. this.clearInterstitial(interstitial, null);
  28427. }
  28428. if (interstitial.appendInPlace) {
  28429. this.attachPrimary(flushStart, null);
  28430. this.flushFrontBuffer(flushStart);
  28431. }
  28432. const scheduleIndex = this.schedule.findItemIndexAtTime(timelinePos);
  28433. this.setSchedulePosition(scheduleIndex);
  28434. } else {
  28435. this.checkStart();
  28436. }
  28437. }
  28438. // Asset List loading
  28439. onAssetListLoaded(event, data) {
  28440. var _this$bufferingItem2;
  28441. const interstitial = data.event;
  28442. const interstitialId = interstitial.identifier;
  28443. const assets = data.assetListResponse.ASSETS;
  28444. if (!this.schedule.hasEvent(interstitialId)) {
  28445. return;
  28446. }
  28447. const eventStart = interstitial.timelineStart;
  28448. const previousDuration = interstitial.duration;
  28449. let sumDuration = 0;
  28450. assets.forEach((asset, assetListIndex) => {
  28451. const duration = parseFloat(asset.DURATION);
  28452. this.createAsset(interstitial, assetListIndex, sumDuration, eventStart + sumDuration, duration, asset.URI);
  28453. sumDuration += duration;
  28454. });
  28455. interstitial.duration = sumDuration;
  28456. this.log(`Loaded asset-list with duration: ${sumDuration} (was: ${previousDuration}) ${interstitial}`);
  28457. const waitingItem = this.waitingItem;
  28458. const waitingForItem = (waitingItem == null ? void 0 : waitingItem.event.identifier) === interstitialId;
  28459. this.updateSchedule();
  28460. const bufferingEvent = (_this$bufferingItem2 = this.bufferingItem) == null ? void 0 : _this$bufferingItem2.event;
  28461. if (waitingForItem) {
  28462. var _this$schedule$items5;
  28463. const scheduleIndex = this.schedule.findEventIndex(interstitialId);
  28464. const item = (_this$schedule$items5 = this.schedule.items) == null ? void 0 : _this$schedule$items5[scheduleIndex];
  28465. if (item) {
  28466. if (!this.playingItem && this.timelinePos > item.end) {
  28467. const index2 = this.schedule.findItemIndexAtTime(this.timelinePos);
  28468. if (index2 !== scheduleIndex) {
  28469. interstitial.error = new Error(`Interstitial no longer within playback range ${this.timelinePos} ${interstitial}`);
  28470. this.primaryFallback(interstitial);
  28471. return;
  28472. }
  28473. }
  28474. this.setBufferingItem(item);
  28475. }
  28476. this.setSchedulePosition(scheduleIndex);
  28477. } else if ((bufferingEvent == null ? void 0 : bufferingEvent.identifier) === interstitialId && bufferingEvent.appendInPlace) {
  28478. const assetItem = interstitial.assetList[0];
  28479. const player = this.getAssetPlayer(assetItem.identifier);
  28480. const media = this.primaryMedia;
  28481. if (assetItem && player && media) {
  28482. this.bufferAssetPlayer(player, media);
  28483. }
  28484. }
  28485. }
  28486. onError(event, data) {
  28487. switch (data.details) {
  28488. case ErrorDetails.ASSET_LIST_PARSING_ERROR:
  28489. case ErrorDetails.ASSET_LIST_LOAD_ERROR:
  28490. case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT: {
  28491. const interstitial = data.interstitial;
  28492. if (interstitial) {
  28493. this.primaryFallback(interstitial);
  28494. }
  28495. break;
  28496. }
  28497. case ErrorDetails.BUFFER_STALLED_ERROR: {
  28498. this.onTimeupdate();
  28499. this.checkBuffer(true);
  28500. break;
  28501. }
  28502. }
  28503. }
  28504. }
  28505. const TICK_INTERVAL$2 = 500;
  28506. class SubtitleStreamController extends BaseStreamController {
  28507. constructor(hls, fragmentTracker, keyLoader) {
  28508. super(hls, fragmentTracker, keyLoader, "subtitle-stream-controller", PlaylistLevelType.SUBTITLE);
  28509. this.currentTrackId = -1;
  28510. this.tracksBuffered = [];
  28511. this.mainDetails = null;
  28512. this.registerListeners();
  28513. }
  28514. onHandlerDestroying() {
  28515. this.unregisterListeners();
  28516. super.onHandlerDestroying();
  28517. this.mainDetails = null;
  28518. }
  28519. registerListeners() {
  28520. super.registerListeners();
  28521. const {
  28522. hls
  28523. } = this;
  28524. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  28525. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  28526. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  28527. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  28528. hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  28529. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  28530. }
  28531. unregisterListeners() {
  28532. super.unregisterListeners();
  28533. const {
  28534. hls
  28535. } = this;
  28536. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  28537. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  28538. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  28539. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  28540. hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  28541. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  28542. }
  28543. startLoad(startPosition, skipSeekToStartPosition) {
  28544. this.stopLoad();
  28545. this.state = State.IDLE;
  28546. this.setInterval(TICK_INTERVAL$2);
  28547. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  28548. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  28549. this.tick();
  28550. }
  28551. onManifestLoading() {
  28552. super.onManifestLoading();
  28553. this.mainDetails = null;
  28554. }
  28555. onMediaDetaching(event, data) {
  28556. this.tracksBuffered = [];
  28557. super.onMediaDetaching(event, data);
  28558. }
  28559. onLevelLoaded(event, data) {
  28560. this.mainDetails = data.details;
  28561. }
  28562. onSubtitleFragProcessed(event, data) {
  28563. const {
  28564. frag,
  28565. success
  28566. } = data;
  28567. if (!this.fragContextChanged(frag)) {
  28568. if (isMediaFragment(frag)) {
  28569. this.fragPrevious = frag;
  28570. }
  28571. this.state = State.IDLE;
  28572. }
  28573. if (!success) {
  28574. return;
  28575. }
  28576. const buffered = this.tracksBuffered[this.currentTrackId];
  28577. if (!buffered) {
  28578. return;
  28579. }
  28580. let timeRange;
  28581. const fragStart = frag.start;
  28582. for (let i2 = 0; i2 < buffered.length; i2++) {
  28583. if (fragStart >= buffered[i2].start && fragStart <= buffered[i2].end) {
  28584. timeRange = buffered[i2];
  28585. break;
  28586. }
  28587. }
  28588. const fragEnd = frag.start + frag.duration;
  28589. if (timeRange) {
  28590. timeRange.end = fragEnd;
  28591. } else {
  28592. timeRange = {
  28593. start: fragStart,
  28594. end: fragEnd
  28595. };
  28596. buffered.push(timeRange);
  28597. }
  28598. this.fragmentTracker.fragBuffered(frag);
  28599. this.fragBufferedComplete(frag, null);
  28600. if (this.media) {
  28601. this.tick();
  28602. }
  28603. }
  28604. onBufferFlushing(event, data) {
  28605. const {
  28606. startOffset,
  28607. endOffset
  28608. } = data;
  28609. if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
  28610. const endOffsetSubtitles = endOffset - 1;
  28611. if (endOffsetSubtitles <= 0) {
  28612. return;
  28613. }
  28614. data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
  28615. this.tracksBuffered.forEach((buffered) => {
  28616. for (let i2 = 0; i2 < buffered.length; ) {
  28617. if (buffered[i2].end <= endOffsetSubtitles) {
  28618. buffered.shift();
  28619. continue;
  28620. } else if (buffered[i2].start < endOffsetSubtitles) {
  28621. buffered[i2].start = endOffsetSubtitles;
  28622. } else {
  28623. break;
  28624. }
  28625. i2++;
  28626. }
  28627. });
  28628. this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE);
  28629. }
  28630. }
  28631. // If something goes wrong, proceed to next frag, if we were processing one.
  28632. onError(event, data) {
  28633. const frag = data.frag;
  28634. if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) {
  28635. if (data.details === ErrorDetails.FRAG_GAP) {
  28636. this.fragmentTracker.fragBuffered(frag, true);
  28637. }
  28638. if (this.fragCurrent) {
  28639. this.fragCurrent.abortRequests();
  28640. }
  28641. if (this.state !== State.STOPPED) {
  28642. this.state = State.IDLE;
  28643. }
  28644. }
  28645. }
  28646. // Got all new subtitle levels.
  28647. onSubtitleTracksUpdated(event, {
  28648. subtitleTracks
  28649. }) {
  28650. if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) {
  28651. this.levels = subtitleTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
  28652. return;
  28653. }
  28654. this.tracksBuffered = [];
  28655. this.levels = subtitleTracks.map((mediaPlaylist) => {
  28656. const level = new Level(mediaPlaylist);
  28657. this.tracksBuffered[level.id] = [];
  28658. return level;
  28659. });
  28660. this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE);
  28661. this.fragPrevious = null;
  28662. this.mediaBuffer = null;
  28663. }
  28664. onSubtitleTrackSwitch(event, data) {
  28665. var _this$levels;
  28666. this.currentTrackId = data.id;
  28667. if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) {
  28668. this.clearInterval();
  28669. return;
  28670. }
  28671. const currentTrack = this.levels[this.currentTrackId];
  28672. if (currentTrack != null && currentTrack.details) {
  28673. this.mediaBuffer = this.mediaBufferTimeRanges;
  28674. } else {
  28675. this.mediaBuffer = null;
  28676. }
  28677. if (currentTrack && this.state !== State.STOPPED) {
  28678. this.setInterval(TICK_INTERVAL$2);
  28679. }
  28680. }
  28681. // Got a new set of subtitle fragments.
  28682. onSubtitleTrackLoaded(event, data) {
  28683. var _track$details;
  28684. const {
  28685. currentTrackId,
  28686. levels
  28687. } = this;
  28688. const {
  28689. details: newDetails,
  28690. id: trackId
  28691. } = data;
  28692. if (!levels) {
  28693. this.warn(`Subtitle tracks were reset while loading level ${trackId}`);
  28694. return;
  28695. }
  28696. const track = levels[trackId];
  28697. if (trackId >= levels.length || !track) {
  28698. return;
  28699. }
  28700. this.log(`Subtitle track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
  28701. this.mediaBuffer = this.mediaBufferTimeRanges;
  28702. let sliding = 0;
  28703. if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {
  28704. if (newDetails.deltaUpdateFailed) {
  28705. return;
  28706. }
  28707. const mainDetails = this.mainDetails;
  28708. if (!mainDetails) {
  28709. this.startFragRequested = false;
  28710. return;
  28711. }
  28712. const mainSlidingStartFragment = mainDetails.fragments[0];
  28713. if (!track.details) {
  28714. if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
  28715. alignMediaPlaylistByPDT(newDetails, mainDetails);
  28716. sliding = newDetails.fragmentStart;
  28717. } else if (mainSlidingStartFragment) {
  28718. sliding = mainSlidingStartFragment.start;
  28719. addSliding(newDetails, sliding);
  28720. }
  28721. } else {
  28722. var _this$levelLastLoaded;
  28723. sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  28724. if (sliding === 0 && mainSlidingStartFragment) {
  28725. sliding = mainSlidingStartFragment.start;
  28726. addSliding(newDetails, sliding);
  28727. }
  28728. }
  28729. if (mainDetails && !this.startFragRequested) {
  28730. this.setStartPosition(mainDetails, sliding);
  28731. }
  28732. }
  28733. track.details = newDetails;
  28734. this.levelLastLoaded = track;
  28735. if (trackId !== currentTrackId) {
  28736. return;
  28737. }
  28738. this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED, {
  28739. details: newDetails,
  28740. id: trackId,
  28741. groupId: data.groupId
  28742. });
  28743. this.tick();
  28744. if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) {
  28745. const foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0);
  28746. if (!foundFrag) {
  28747. this.warn("Subtitle playlist not aligned with playback");
  28748. track.details = void 0;
  28749. }
  28750. }
  28751. }
  28752. _handleFragmentLoadComplete(fragLoadedData) {
  28753. const {
  28754. frag,
  28755. payload
  28756. } = fragLoadedData;
  28757. const decryptData = frag.decryptdata;
  28758. const hls = this.hls;
  28759. if (this.fragContextChanged(frag)) {
  28760. return;
  28761. }
  28762. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  28763. const startTime = performance.now();
  28764. this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
  28765. hls.trigger(Events.ERROR, {
  28766. type: ErrorTypes.MEDIA_ERROR,
  28767. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  28768. fatal: false,
  28769. error: err,
  28770. reason: err.message,
  28771. frag
  28772. });
  28773. throw err;
  28774. }).then((decryptedData) => {
  28775. const endTime = performance.now();
  28776. hls.trigger(Events.FRAG_DECRYPTED, {
  28777. frag,
  28778. payload: decryptedData,
  28779. stats: {
  28780. tstart: startTime,
  28781. tdecrypt: endTime
  28782. }
  28783. });
  28784. }).catch((err) => {
  28785. this.warn(`${err.name}: ${err.message}`);
  28786. this.state = State.IDLE;
  28787. });
  28788. }
  28789. }
  28790. doTick() {
  28791. if (!this.media) {
  28792. this.state = State.IDLE;
  28793. return;
  28794. }
  28795. if (this.state === State.IDLE) {
  28796. const {
  28797. currentTrackId,
  28798. levels
  28799. } = this;
  28800. const track = levels == null ? void 0 : levels[currentTrackId];
  28801. if (!track || !levels.length || !track.details) {
  28802. return;
  28803. }
  28804. if (this.waitForLive(track)) {
  28805. return;
  28806. }
  28807. const {
  28808. config: config2
  28809. } = this;
  28810. const currentTime = this.getLoadPosition();
  28811. const bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config2.maxBufferHole);
  28812. const {
  28813. end: targetBufferTime,
  28814. len: bufferLen
  28815. } = bufferedInfo;
  28816. const trackDetails = track.details;
  28817. const maxBufLen = this.hls.maxBufferLength + trackDetails.levelTargetDuration;
  28818. if (bufferLen > maxBufLen) {
  28819. return;
  28820. }
  28821. const fragments = trackDetails.fragments;
  28822. const fragLen = fragments.length;
  28823. const end = trackDetails.edge;
  28824. let foundFrag = null;
  28825. const fragPrevious = this.fragPrevious;
  28826. if (targetBufferTime < end) {
  28827. const tolerance = config2.maxFragLookUpTolerance;
  28828. const lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance;
  28829. foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance);
  28830. if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
  28831. foundFrag = fragments[0];
  28832. }
  28833. } else {
  28834. foundFrag = fragments[fragLen - 1];
  28835. }
  28836. foundFrag = this.filterReplacedPrimary(foundFrag, track.details);
  28837. if (!foundFrag) {
  28838. return;
  28839. }
  28840. const curSNIdx = foundFrag.sn - trackDetails.startSN;
  28841. const prevFrag = fragments[curSNIdx - 1];
  28842. if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) {
  28843. foundFrag = prevFrag;
  28844. }
  28845. if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
  28846. const fragToLoad = this.mapToInitFragWhenRequired(foundFrag);
  28847. if (fragToLoad) {
  28848. this.loadFragment(fragToLoad, track, targetBufferTime);
  28849. }
  28850. }
  28851. }
  28852. }
  28853. loadFragment(frag, level, targetBufferTime) {
  28854. if (!isMediaFragment(frag)) {
  28855. this._loadInitSegment(frag, level);
  28856. } else {
  28857. super.loadFragment(frag, level, targetBufferTime);
  28858. }
  28859. }
  28860. get mediaBufferTimeRanges() {
  28861. return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []);
  28862. }
  28863. }
  28864. class BufferableInstance {
  28865. constructor(timeranges) {
  28866. this.buffered = void 0;
  28867. const getRange = (name, index2, length) => {
  28868. index2 = index2 >>> 0;
  28869. if (index2 > length - 1) {
  28870. throw new DOMException(`Failed to execute '${name}' on 'TimeRanges': The index provided (${index2}) is greater than the maximum bound (${length})`);
  28871. }
  28872. return timeranges[index2][name];
  28873. };
  28874. this.buffered = {
  28875. get length() {
  28876. return timeranges.length;
  28877. },
  28878. end(index2) {
  28879. return getRange("end", index2, timeranges.length);
  28880. },
  28881. start(index2) {
  28882. return getRange("start", index2, timeranges.length);
  28883. }
  28884. };
  28885. }
  28886. }
  28887. const specialCea608CharsCodes = {
  28888. 42: 225,
  28889. // lowercase a, acute accent
  28890. 92: 233,
  28891. // lowercase e, acute accent
  28892. 94: 237,
  28893. // lowercase i, acute accent
  28894. 95: 243,
  28895. // lowercase o, acute accent
  28896. 96: 250,
  28897. // lowercase u, acute accent
  28898. 123: 231,
  28899. // lowercase c with cedilla
  28900. 124: 247,
  28901. // division symbol
  28902. 125: 209,
  28903. // uppercase N tilde
  28904. 126: 241,
  28905. // lowercase n tilde
  28906. 127: 9608,
  28907. // Full block
  28908. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  28909. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  28910. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  28911. 128: 174,
  28912. // Registered symbol (R)
  28913. 129: 176,
  28914. // degree sign
  28915. 130: 189,
  28916. // 1/2 symbol
  28917. 131: 191,
  28918. // Inverted (open) question mark
  28919. 132: 8482,
  28920. // Trademark symbol (TM)
  28921. 133: 162,
  28922. // Cents symbol
  28923. 134: 163,
  28924. // Pounds sterling
  28925. 135: 9834,
  28926. // Music 8'th note
  28927. 136: 224,
  28928. // lowercase a, grave accent
  28929. 137: 32,
  28930. // transparent space (regular)
  28931. 138: 232,
  28932. // lowercase e, grave accent
  28933. 139: 226,
  28934. // lowercase a, circumflex accent
  28935. 140: 234,
  28936. // lowercase e, circumflex accent
  28937. 141: 238,
  28938. // lowercase i, circumflex accent
  28939. 142: 244,
  28940. // lowercase o, circumflex accent
  28941. 143: 251,
  28942. // lowercase u, circumflex accent
  28943. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  28944. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  28945. 144: 193,
  28946. // capital letter A with acute
  28947. 145: 201,
  28948. // capital letter E with acute
  28949. 146: 211,
  28950. // capital letter O with acute
  28951. 147: 218,
  28952. // capital letter U with acute
  28953. 148: 220,
  28954. // capital letter U with diaresis
  28955. 149: 252,
  28956. // lowercase letter U with diaeresis
  28957. 150: 8216,
  28958. // opening single quote
  28959. 151: 161,
  28960. // inverted exclamation mark
  28961. 152: 42,
  28962. // asterisk
  28963. 153: 8217,
  28964. // closing single quote
  28965. 154: 9473,
  28966. // box drawings heavy horizontal
  28967. 155: 169,
  28968. // copyright sign
  28969. 156: 8480,
  28970. // Service mark
  28971. 157: 8226,
  28972. // (round) bullet
  28973. 158: 8220,
  28974. // Left double quotation mark
  28975. 159: 8221,
  28976. // Right double quotation mark
  28977. 160: 192,
  28978. // uppercase A, grave accent
  28979. 161: 194,
  28980. // uppercase A, circumflex
  28981. 162: 199,
  28982. // uppercase C with cedilla
  28983. 163: 200,
  28984. // uppercase E, grave accent
  28985. 164: 202,
  28986. // uppercase E, circumflex
  28987. 165: 203,
  28988. // capital letter E with diaresis
  28989. 166: 235,
  28990. // lowercase letter e with diaresis
  28991. 167: 206,
  28992. // uppercase I, circumflex
  28993. 168: 207,
  28994. // uppercase I, with diaresis
  28995. 169: 239,
  28996. // lowercase i, with diaresis
  28997. 170: 212,
  28998. // uppercase O, circumflex
  28999. 171: 217,
  29000. // uppercase U, grave accent
  29001. 172: 249,
  29002. // lowercase u, grave accent
  29003. 173: 219,
  29004. // uppercase U, circumflex
  29005. 174: 171,
  29006. // left-pointing double angle quotation mark
  29007. 175: 187,
  29008. // right-pointing double angle quotation mark
  29009. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  29010. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  29011. 176: 195,
  29012. // Uppercase A, tilde
  29013. 177: 227,
  29014. // Lowercase a, tilde
  29015. 178: 205,
  29016. // Uppercase I, acute accent
  29017. 179: 204,
  29018. // Uppercase I, grave accent
  29019. 180: 236,
  29020. // Lowercase i, grave accent
  29021. 181: 210,
  29022. // Uppercase O, grave accent
  29023. 182: 242,
  29024. // Lowercase o, grave accent
  29025. 183: 213,
  29026. // Uppercase O, tilde
  29027. 184: 245,
  29028. // Lowercase o, tilde
  29029. 185: 123,
  29030. // Open curly brace
  29031. 186: 125,
  29032. // Closing curly brace
  29033. 187: 92,
  29034. // Backslash
  29035. 188: 94,
  29036. // Caret
  29037. 189: 95,
  29038. // Underscore
  29039. 190: 124,
  29040. // Pipe (vertical line)
  29041. 191: 8764,
  29042. // Tilde operator
  29043. 192: 196,
  29044. // Uppercase A, umlaut
  29045. 193: 228,
  29046. // Lowercase A, umlaut
  29047. 194: 214,
  29048. // Uppercase O, umlaut
  29049. 195: 246,
  29050. // Lowercase o, umlaut
  29051. 196: 223,
  29052. // Esszett (sharp S)
  29053. 197: 165,
  29054. // Yen symbol
  29055. 198: 164,
  29056. // Generic currency sign
  29057. 199: 9475,
  29058. // Box drawings heavy vertical
  29059. 200: 197,
  29060. // Uppercase A, ring
  29061. 201: 229,
  29062. // Lowercase A, ring
  29063. 202: 216,
  29064. // Uppercase O, stroke
  29065. 203: 248,
  29066. // Lowercase o, strok
  29067. 204: 9487,
  29068. // Box drawings heavy down and right
  29069. 205: 9491,
  29070. // Box drawings heavy down and left
  29071. 206: 9495,
  29072. // Box drawings heavy up and right
  29073. 207: 9499
  29074. // Box drawings heavy up and left
  29075. };
  29076. const getCharForByte = (byte) => String.fromCharCode(specialCea608CharsCodes[byte] || byte);
  29077. const NR_ROWS = 15;
  29078. const NR_COLS = 100;
  29079. const rowsLowCh1 = {
  29080. 17: 1,
  29081. 18: 3,
  29082. 21: 5,
  29083. 22: 7,
  29084. 23: 9,
  29085. 16: 11,
  29086. 19: 12,
  29087. 20: 14
  29088. };
  29089. const rowsHighCh1 = {
  29090. 17: 2,
  29091. 18: 4,
  29092. 21: 6,
  29093. 22: 8,
  29094. 23: 10,
  29095. 19: 13,
  29096. 20: 15
  29097. };
  29098. const rowsLowCh2 = {
  29099. 25: 1,
  29100. 26: 3,
  29101. 29: 5,
  29102. 30: 7,
  29103. 31: 9,
  29104. 24: 11,
  29105. 27: 12,
  29106. 28: 14
  29107. };
  29108. const rowsHighCh2 = {
  29109. 25: 2,
  29110. 26: 4,
  29111. 29: 6,
  29112. 30: 8,
  29113. 31: 10,
  29114. 27: 13,
  29115. 28: 15
  29116. };
  29117. const backgroundColors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "black", "transparent"];
  29118. class CaptionsLogger {
  29119. constructor() {
  29120. this.time = null;
  29121. this.verboseLevel = 0;
  29122. }
  29123. log(severity, msg) {
  29124. if (this.verboseLevel >= severity) {
  29125. const m2 = typeof msg === "function" ? msg() : msg;
  29126. logger.log(`${this.time} [${severity}] ${m2}`);
  29127. }
  29128. }
  29129. }
  29130. const numArrayToHexArray = function numArrayToHexArray2(numArray) {
  29131. const hexArray = [];
  29132. for (let j2 = 0; j2 < numArray.length; j2++) {
  29133. hexArray.push(numArray[j2].toString(16));
  29134. }
  29135. return hexArray;
  29136. };
  29137. class PenState {
  29138. constructor() {
  29139. this.foreground = "white";
  29140. this.underline = false;
  29141. this.italics = false;
  29142. this.background = "black";
  29143. this.flash = false;
  29144. }
  29145. reset() {
  29146. this.foreground = "white";
  29147. this.underline = false;
  29148. this.italics = false;
  29149. this.background = "black";
  29150. this.flash = false;
  29151. }
  29152. setStyles(styles) {
  29153. const attribs = ["foreground", "underline", "italics", "background", "flash"];
  29154. for (let i2 = 0; i2 < attribs.length; i2++) {
  29155. const style = attribs[i2];
  29156. if (styles.hasOwnProperty(style)) {
  29157. this[style] = styles[style];
  29158. }
  29159. }
  29160. }
  29161. isDefault() {
  29162. return this.foreground === "white" && !this.underline && !this.italics && this.background === "black" && !this.flash;
  29163. }
  29164. equals(other) {
  29165. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  29166. }
  29167. copy(newPenState) {
  29168. this.foreground = newPenState.foreground;
  29169. this.underline = newPenState.underline;
  29170. this.italics = newPenState.italics;
  29171. this.background = newPenState.background;
  29172. this.flash = newPenState.flash;
  29173. }
  29174. toString() {
  29175. return "color=" + this.foreground + ", underline=" + this.underline + ", italics=" + this.italics + ", background=" + this.background + ", flash=" + this.flash;
  29176. }
  29177. }
  29178. class StyledUnicodeChar {
  29179. constructor() {
  29180. this.uchar = " ";
  29181. this.penState = new PenState();
  29182. }
  29183. reset() {
  29184. this.uchar = " ";
  29185. this.penState.reset();
  29186. }
  29187. setChar(uchar, newPenState) {
  29188. this.uchar = uchar;
  29189. this.penState.copy(newPenState);
  29190. }
  29191. setPenState(newPenState) {
  29192. this.penState.copy(newPenState);
  29193. }
  29194. equals(other) {
  29195. return this.uchar === other.uchar && this.penState.equals(other.penState);
  29196. }
  29197. copy(newChar) {
  29198. this.uchar = newChar.uchar;
  29199. this.penState.copy(newChar.penState);
  29200. }
  29201. isEmpty() {
  29202. return this.uchar === " " && this.penState.isDefault();
  29203. }
  29204. }
  29205. class Row {
  29206. constructor(logger2) {
  29207. this.chars = [];
  29208. this.pos = 0;
  29209. this.currPenState = new PenState();
  29210. this.cueStartTime = null;
  29211. this.logger = void 0;
  29212. for (let i2 = 0; i2 < NR_COLS; i2++) {
  29213. this.chars.push(new StyledUnicodeChar());
  29214. }
  29215. this.logger = logger2;
  29216. }
  29217. equals(other) {
  29218. for (let i2 = 0; i2 < NR_COLS; i2++) {
  29219. if (!this.chars[i2].equals(other.chars[i2])) {
  29220. return false;
  29221. }
  29222. }
  29223. return true;
  29224. }
  29225. copy(other) {
  29226. for (let i2 = 0; i2 < NR_COLS; i2++) {
  29227. this.chars[i2].copy(other.chars[i2]);
  29228. }
  29229. }
  29230. isEmpty() {
  29231. let empty2 = true;
  29232. for (let i2 = 0; i2 < NR_COLS; i2++) {
  29233. if (!this.chars[i2].isEmpty()) {
  29234. empty2 = false;
  29235. break;
  29236. }
  29237. }
  29238. return empty2;
  29239. }
  29240. /**
  29241. * Set the cursor to a valid column.
  29242. */
  29243. setCursor(absPos) {
  29244. if (this.pos !== absPos) {
  29245. this.pos = absPos;
  29246. }
  29247. if (this.pos < 0) {
  29248. this.logger.log(3, "Negative cursor position " + this.pos);
  29249. this.pos = 0;
  29250. } else if (this.pos > NR_COLS) {
  29251. this.logger.log(3, "Too large cursor position " + this.pos);
  29252. this.pos = NR_COLS;
  29253. }
  29254. }
  29255. /**
  29256. * Move the cursor relative to current position.
  29257. */
  29258. moveCursor(relPos) {
  29259. const newPos = this.pos + relPos;
  29260. if (relPos > 1) {
  29261. for (let i2 = this.pos + 1; i2 < newPos + 1; i2++) {
  29262. this.chars[i2].setPenState(this.currPenState);
  29263. }
  29264. }
  29265. this.setCursor(newPos);
  29266. }
  29267. /**
  29268. * Backspace, move one step back and clear character.
  29269. */
  29270. backSpace() {
  29271. this.moveCursor(-1);
  29272. this.chars[this.pos].setChar(" ", this.currPenState);
  29273. }
  29274. insertChar(byte) {
  29275. if (byte >= 144) {
  29276. this.backSpace();
  29277. }
  29278. const char = getCharForByte(byte);
  29279. if (this.pos >= NR_COLS) {
  29280. this.logger.log(0, () => "Cannot insert " + byte.toString(16) + " (" + char + ") at position " + this.pos + ". Skipping it!");
  29281. return;
  29282. }
  29283. this.chars[this.pos].setChar(char, this.currPenState);
  29284. this.moveCursor(1);
  29285. }
  29286. clearFromPos(startPos) {
  29287. let i2;
  29288. for (i2 = startPos; i2 < NR_COLS; i2++) {
  29289. this.chars[i2].reset();
  29290. }
  29291. }
  29292. clear() {
  29293. this.clearFromPos(0);
  29294. this.pos = 0;
  29295. this.currPenState.reset();
  29296. }
  29297. clearToEndOfRow() {
  29298. this.clearFromPos(this.pos);
  29299. }
  29300. getTextString() {
  29301. const chars = [];
  29302. let empty2 = true;
  29303. for (let i2 = 0; i2 < NR_COLS; i2++) {
  29304. const char = this.chars[i2].uchar;
  29305. if (char !== " ") {
  29306. empty2 = false;
  29307. }
  29308. chars.push(char);
  29309. }
  29310. if (empty2) {
  29311. return "";
  29312. } else {
  29313. return chars.join("");
  29314. }
  29315. }
  29316. setPenStyles(styles) {
  29317. this.currPenState.setStyles(styles);
  29318. const currChar = this.chars[this.pos];
  29319. currChar.setPenState(this.currPenState);
  29320. }
  29321. }
  29322. class CaptionScreen {
  29323. constructor(logger2) {
  29324. this.rows = [];
  29325. this.currRow = NR_ROWS - 1;
  29326. this.nrRollUpRows = null;
  29327. this.lastOutputScreen = null;
  29328. this.logger = void 0;
  29329. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  29330. this.rows.push(new Row(logger2));
  29331. }
  29332. this.logger = logger2;
  29333. }
  29334. reset() {
  29335. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  29336. this.rows[i2].clear();
  29337. }
  29338. this.currRow = NR_ROWS - 1;
  29339. }
  29340. equals(other) {
  29341. let equal = true;
  29342. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  29343. if (!this.rows[i2].equals(other.rows[i2])) {
  29344. equal = false;
  29345. break;
  29346. }
  29347. }
  29348. return equal;
  29349. }
  29350. copy(other) {
  29351. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  29352. this.rows[i2].copy(other.rows[i2]);
  29353. }
  29354. }
  29355. isEmpty() {
  29356. let empty2 = true;
  29357. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  29358. if (!this.rows[i2].isEmpty()) {
  29359. empty2 = false;
  29360. break;
  29361. }
  29362. }
  29363. return empty2;
  29364. }
  29365. backSpace() {
  29366. const row = this.rows[this.currRow];
  29367. row.backSpace();
  29368. }
  29369. clearToEndOfRow() {
  29370. const row = this.rows[this.currRow];
  29371. row.clearToEndOfRow();
  29372. }
  29373. /**
  29374. * Insert a character (without styling) in the current row.
  29375. */
  29376. insertChar(char) {
  29377. const row = this.rows[this.currRow];
  29378. row.insertChar(char);
  29379. }
  29380. setPen(styles) {
  29381. const row = this.rows[this.currRow];
  29382. row.setPenStyles(styles);
  29383. }
  29384. moveCursor(relPos) {
  29385. const row = this.rows[this.currRow];
  29386. row.moveCursor(relPos);
  29387. }
  29388. setCursor(absPos) {
  29389. this.logger.log(2, "setCursor: " + absPos);
  29390. const row = this.rows[this.currRow];
  29391. row.setCursor(absPos);
  29392. }
  29393. setPAC(pacData) {
  29394. this.logger.log(2, () => "pacData = " + stringify(pacData));
  29395. let newRow = pacData.row - 1;
  29396. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  29397. newRow = this.nrRollUpRows - 1;
  29398. }
  29399. if (this.nrRollUpRows && this.currRow !== newRow) {
  29400. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  29401. this.rows[i2].clear();
  29402. }
  29403. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  29404. const lastOutputScreen = this.lastOutputScreen;
  29405. if (lastOutputScreen) {
  29406. const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  29407. const time = this.logger.time;
  29408. if (prevLineTime !== null && time !== null && prevLineTime < time) {
  29409. for (let i2 = 0; i2 < this.nrRollUpRows; i2++) {
  29410. this.rows[newRow - this.nrRollUpRows + i2 + 1].copy(lastOutputScreen.rows[topRowIndex + i2]);
  29411. }
  29412. }
  29413. }
  29414. }
  29415. this.currRow = newRow;
  29416. const row = this.rows[this.currRow];
  29417. if (pacData.indent !== null) {
  29418. const indent = pacData.indent;
  29419. const prevPos = Math.max(indent - 1, 0);
  29420. row.setCursor(pacData.indent);
  29421. pacData.color = row.chars[prevPos].penState.foreground;
  29422. }
  29423. const styles = {
  29424. foreground: pacData.color,
  29425. underline: pacData.underline,
  29426. italics: pacData.italics,
  29427. background: "black",
  29428. flash: false
  29429. };
  29430. this.setPen(styles);
  29431. }
  29432. /**
  29433. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  29434. */
  29435. setBkgData(bkgData) {
  29436. this.logger.log(2, () => "bkgData = " + stringify(bkgData));
  29437. this.backSpace();
  29438. this.setPen(bkgData);
  29439. this.insertChar(32);
  29440. }
  29441. setRollUpRows(nrRows) {
  29442. this.nrRollUpRows = nrRows;
  29443. }
  29444. rollUp() {
  29445. if (this.nrRollUpRows === null) {
  29446. this.logger.log(3, "roll_up but nrRollUpRows not set yet");
  29447. return;
  29448. }
  29449. this.logger.log(1, () => this.getDisplayText());
  29450. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  29451. const topRow = this.rows.splice(topRowIndex, 1)[0];
  29452. topRow.clear();
  29453. this.rows.splice(this.currRow, 0, topRow);
  29454. this.logger.log(2, "Rolling up");
  29455. }
  29456. /**
  29457. * Get all non-empty rows with as unicode text.
  29458. */
  29459. getDisplayText(asOneRow) {
  29460. asOneRow = asOneRow || false;
  29461. const displayText = [];
  29462. let text = "";
  29463. let rowNr = -1;
  29464. for (let i2 = 0; i2 < NR_ROWS; i2++) {
  29465. const rowText = this.rows[i2].getTextString();
  29466. if (rowText) {
  29467. rowNr = i2 + 1;
  29468. if (asOneRow) {
  29469. displayText.push("Row " + rowNr + ": '" + rowText + "'");
  29470. } else {
  29471. displayText.push(rowText.trim());
  29472. }
  29473. }
  29474. }
  29475. if (displayText.length > 0) {
  29476. if (asOneRow) {
  29477. text = "[" + displayText.join(" | ") + "]";
  29478. } else {
  29479. text = displayText.join("\n");
  29480. }
  29481. }
  29482. return text;
  29483. }
  29484. getTextAndFormat() {
  29485. return this.rows;
  29486. }
  29487. }
  29488. class Cea608Channel {
  29489. constructor(channelNumber, outputFilter, logger2) {
  29490. this.chNr = void 0;
  29491. this.outputFilter = void 0;
  29492. this.mode = void 0;
  29493. this.verbose = void 0;
  29494. this.displayedMemory = void 0;
  29495. this.nonDisplayedMemory = void 0;
  29496. this.lastOutputScreen = void 0;
  29497. this.currRollUpRow = void 0;
  29498. this.writeScreen = void 0;
  29499. this.cueStartTime = void 0;
  29500. this.logger = void 0;
  29501. this.chNr = channelNumber;
  29502. this.outputFilter = outputFilter;
  29503. this.mode = null;
  29504. this.verbose = 0;
  29505. this.displayedMemory = new CaptionScreen(logger2);
  29506. this.nonDisplayedMemory = new CaptionScreen(logger2);
  29507. this.lastOutputScreen = new CaptionScreen(logger2);
  29508. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  29509. this.writeScreen = this.displayedMemory;
  29510. this.mode = null;
  29511. this.cueStartTime = null;
  29512. this.logger = logger2;
  29513. }
  29514. reset() {
  29515. this.mode = null;
  29516. this.displayedMemory.reset();
  29517. this.nonDisplayedMemory.reset();
  29518. this.lastOutputScreen.reset();
  29519. this.outputFilter.reset();
  29520. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  29521. this.writeScreen = this.displayedMemory;
  29522. this.mode = null;
  29523. this.cueStartTime = null;
  29524. }
  29525. getHandler() {
  29526. return this.outputFilter;
  29527. }
  29528. setHandler(newHandler) {
  29529. this.outputFilter = newHandler;
  29530. }
  29531. setPAC(pacData) {
  29532. this.writeScreen.setPAC(pacData);
  29533. }
  29534. setBkgData(bkgData) {
  29535. this.writeScreen.setBkgData(bkgData);
  29536. }
  29537. setMode(newMode) {
  29538. if (newMode === this.mode) {
  29539. return;
  29540. }
  29541. this.mode = newMode;
  29542. this.logger.log(2, () => "MODE=" + newMode);
  29543. if (this.mode === "MODE_POP-ON") {
  29544. this.writeScreen = this.nonDisplayedMemory;
  29545. } else {
  29546. this.writeScreen = this.displayedMemory;
  29547. this.writeScreen.reset();
  29548. }
  29549. if (this.mode !== "MODE_ROLL-UP") {
  29550. this.displayedMemory.nrRollUpRows = null;
  29551. this.nonDisplayedMemory.nrRollUpRows = null;
  29552. }
  29553. this.mode = newMode;
  29554. }
  29555. insertChars(chars) {
  29556. for (let i2 = 0; i2 < chars.length; i2++) {
  29557. this.writeScreen.insertChar(chars[i2]);
  29558. }
  29559. const screen = this.writeScreen === this.displayedMemory ? "DISP" : "NON_DISP";
  29560. this.logger.log(2, () => screen + ": " + this.writeScreen.getDisplayText(true));
  29561. if (this.mode === "MODE_PAINT-ON" || this.mode === "MODE_ROLL-UP") {
  29562. this.logger.log(1, () => "DISPLAYED: " + this.displayedMemory.getDisplayText(true));
  29563. this.outputDataUpdate();
  29564. }
  29565. }
  29566. ccRCL() {
  29567. this.logger.log(2, "RCL - Resume Caption Loading");
  29568. this.setMode("MODE_POP-ON");
  29569. }
  29570. ccBS() {
  29571. this.logger.log(2, "BS - BackSpace");
  29572. if (this.mode === "MODE_TEXT") {
  29573. return;
  29574. }
  29575. this.writeScreen.backSpace();
  29576. if (this.writeScreen === this.displayedMemory) {
  29577. this.outputDataUpdate();
  29578. }
  29579. }
  29580. ccAOF() {
  29581. }
  29582. ccAON() {
  29583. }
  29584. ccDER() {
  29585. this.logger.log(2, "DER- Delete to End of Row");
  29586. this.writeScreen.clearToEndOfRow();
  29587. this.outputDataUpdate();
  29588. }
  29589. ccRU(nrRows) {
  29590. this.logger.log(2, "RU(" + nrRows + ") - Roll Up");
  29591. this.writeScreen = this.displayedMemory;
  29592. this.setMode("MODE_ROLL-UP");
  29593. this.writeScreen.setRollUpRows(nrRows);
  29594. }
  29595. ccFON() {
  29596. this.logger.log(2, "FON - Flash On");
  29597. this.writeScreen.setPen({
  29598. flash: true
  29599. });
  29600. }
  29601. ccRDC() {
  29602. this.logger.log(2, "RDC - Resume Direct Captioning");
  29603. this.setMode("MODE_PAINT-ON");
  29604. }
  29605. ccTR() {
  29606. this.logger.log(2, "TR");
  29607. this.setMode("MODE_TEXT");
  29608. }
  29609. ccRTD() {
  29610. this.logger.log(2, "RTD");
  29611. this.setMode("MODE_TEXT");
  29612. }
  29613. ccEDM() {
  29614. this.logger.log(2, "EDM - Erase Displayed Memory");
  29615. this.displayedMemory.reset();
  29616. this.outputDataUpdate(true);
  29617. }
  29618. ccCR() {
  29619. this.logger.log(2, "CR - Carriage Return");
  29620. this.writeScreen.rollUp();
  29621. this.outputDataUpdate(true);
  29622. }
  29623. ccENM() {
  29624. this.logger.log(2, "ENM - Erase Non-displayed Memory");
  29625. this.nonDisplayedMemory.reset();
  29626. }
  29627. ccEOC() {
  29628. this.logger.log(2, "EOC - End Of Caption");
  29629. if (this.mode === "MODE_POP-ON") {
  29630. const tmp = this.displayedMemory;
  29631. this.displayedMemory = this.nonDisplayedMemory;
  29632. this.nonDisplayedMemory = tmp;
  29633. this.writeScreen = this.nonDisplayedMemory;
  29634. this.logger.log(1, () => "DISP: " + this.displayedMemory.getDisplayText());
  29635. }
  29636. this.outputDataUpdate(true);
  29637. }
  29638. ccTO(nrCols) {
  29639. this.logger.log(2, "TO(" + nrCols + ") - Tab Offset");
  29640. this.writeScreen.moveCursor(nrCols);
  29641. }
  29642. ccMIDROW(secondByte) {
  29643. const styles = {
  29644. flash: false
  29645. };
  29646. styles.underline = secondByte % 2 === 1;
  29647. styles.italics = secondByte >= 46;
  29648. if (!styles.italics) {
  29649. const colorIndex = Math.floor(secondByte / 2) - 16;
  29650. const colors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta"];
  29651. styles.foreground = colors[colorIndex];
  29652. } else {
  29653. styles.foreground = "white";
  29654. }
  29655. this.logger.log(2, "MIDROW: " + stringify(styles));
  29656. this.writeScreen.setPen(styles);
  29657. }
  29658. outputDataUpdate(dispatch = false) {
  29659. const time = this.logger.time;
  29660. if (time === null) {
  29661. return;
  29662. }
  29663. if (this.outputFilter) {
  29664. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  29665. this.cueStartTime = time;
  29666. } else {
  29667. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  29668. this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
  29669. if (dispatch && this.outputFilter.dispatchCue) {
  29670. this.outputFilter.dispatchCue();
  29671. }
  29672. this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
  29673. }
  29674. }
  29675. this.lastOutputScreen.copy(this.displayedMemory);
  29676. }
  29677. }
  29678. cueSplitAtTime(t2) {
  29679. if (this.outputFilter) {
  29680. if (!this.displayedMemory.isEmpty()) {
  29681. if (this.outputFilter.newCue) {
  29682. this.outputFilter.newCue(this.cueStartTime, t2, this.displayedMemory);
  29683. }
  29684. this.cueStartTime = t2;
  29685. }
  29686. }
  29687. }
  29688. }
  29689. class Cea608Parser {
  29690. constructor(field, out1, out2) {
  29691. this.channels = void 0;
  29692. this.currentChannel = 0;
  29693. this.cmdHistory = createCmdHistory();
  29694. this.logger = void 0;
  29695. const logger2 = this.logger = new CaptionsLogger();
  29696. this.channels = [null, new Cea608Channel(field, out1, logger2), new Cea608Channel(field + 1, out2, logger2)];
  29697. }
  29698. getHandler(channel) {
  29699. return this.channels[channel].getHandler();
  29700. }
  29701. setHandler(channel, newHandler) {
  29702. this.channels[channel].setHandler(newHandler);
  29703. }
  29704. /**
  29705. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  29706. */
  29707. addData(time, byteList) {
  29708. this.logger.time = time;
  29709. for (let i2 = 0; i2 < byteList.length; i2 += 2) {
  29710. const a2 = byteList[i2] & 127;
  29711. const b2 = byteList[i2 + 1] & 127;
  29712. let cmdFound = false;
  29713. let charsFound = null;
  29714. if (a2 === 0 && b2 === 0) {
  29715. continue;
  29716. } else {
  29717. this.logger.log(3, () => "[" + numArrayToHexArray([byteList[i2], byteList[i2 + 1]]) + "] -> (" + numArrayToHexArray([a2, b2]) + ")");
  29718. }
  29719. const cmdHistory = this.cmdHistory;
  29720. const isControlCode = a2 >= 16 && a2 <= 31;
  29721. if (isControlCode) {
  29722. if (hasCmdRepeated(a2, b2, cmdHistory)) {
  29723. setLastCmd(null, null, cmdHistory);
  29724. this.logger.log(3, () => "Repeated command (" + numArrayToHexArray([a2, b2]) + ") is dropped");
  29725. continue;
  29726. }
  29727. setLastCmd(a2, b2, this.cmdHistory);
  29728. cmdFound = this.parseCmd(a2, b2);
  29729. if (!cmdFound) {
  29730. cmdFound = this.parseMidrow(a2, b2);
  29731. }
  29732. if (!cmdFound) {
  29733. cmdFound = this.parsePAC(a2, b2);
  29734. }
  29735. if (!cmdFound) {
  29736. cmdFound = this.parseBackgroundAttributes(a2, b2);
  29737. }
  29738. } else {
  29739. setLastCmd(null, null, cmdHistory);
  29740. }
  29741. if (!cmdFound) {
  29742. charsFound = this.parseChars(a2, b2);
  29743. if (charsFound) {
  29744. const currChNr = this.currentChannel;
  29745. if (currChNr && currChNr > 0) {
  29746. const channel = this.channels[currChNr];
  29747. channel.insertChars(charsFound);
  29748. } else {
  29749. this.logger.log(2, "No channel found yet. TEXT-MODE?");
  29750. }
  29751. }
  29752. }
  29753. if (!cmdFound && !charsFound) {
  29754. this.logger.log(2, () => "Couldn't parse cleaned data " + numArrayToHexArray([a2, b2]) + " orig: " + numArrayToHexArray([byteList[i2], byteList[i2 + 1]]));
  29755. }
  29756. }
  29757. }
  29758. /**
  29759. * Parse Command.
  29760. * @returns True if a command was found
  29761. */
  29762. parseCmd(a2, b2) {
  29763. const cond1 = (a2 === 20 || a2 === 28 || a2 === 21 || a2 === 29) && b2 >= 32 && b2 <= 47;
  29764. const cond2 = (a2 === 23 || a2 === 31) && b2 >= 33 && b2 <= 35;
  29765. if (!(cond1 || cond2)) {
  29766. return false;
  29767. }
  29768. const chNr = a2 === 20 || a2 === 21 || a2 === 23 ? 1 : 2;
  29769. const channel = this.channels[chNr];
  29770. if (a2 === 20 || a2 === 21 || a2 === 28 || a2 === 29) {
  29771. if (b2 === 32) {
  29772. channel.ccRCL();
  29773. } else if (b2 === 33) {
  29774. channel.ccBS();
  29775. } else if (b2 === 34) {
  29776. channel.ccAOF();
  29777. } else if (b2 === 35) {
  29778. channel.ccAON();
  29779. } else if (b2 === 36) {
  29780. channel.ccDER();
  29781. } else if (b2 === 37) {
  29782. channel.ccRU(2);
  29783. } else if (b2 === 38) {
  29784. channel.ccRU(3);
  29785. } else if (b2 === 39) {
  29786. channel.ccRU(4);
  29787. } else if (b2 === 40) {
  29788. channel.ccFON();
  29789. } else if (b2 === 41) {
  29790. channel.ccRDC();
  29791. } else if (b2 === 42) {
  29792. channel.ccTR();
  29793. } else if (b2 === 43) {
  29794. channel.ccRTD();
  29795. } else if (b2 === 44) {
  29796. channel.ccEDM();
  29797. } else if (b2 === 45) {
  29798. channel.ccCR();
  29799. } else if (b2 === 46) {
  29800. channel.ccENM();
  29801. } else if (b2 === 47) {
  29802. channel.ccEOC();
  29803. }
  29804. } else {
  29805. channel.ccTO(b2 - 32);
  29806. }
  29807. this.currentChannel = chNr;
  29808. return true;
  29809. }
  29810. /**
  29811. * Parse midrow styling command
  29812. */
  29813. parseMidrow(a2, b2) {
  29814. let chNr = 0;
  29815. if ((a2 === 17 || a2 === 25) && b2 >= 32 && b2 <= 47) {
  29816. if (a2 === 17) {
  29817. chNr = 1;
  29818. } else {
  29819. chNr = 2;
  29820. }
  29821. if (chNr !== this.currentChannel) {
  29822. this.logger.log(0, "Mismatch channel in midrow parsing");
  29823. return false;
  29824. }
  29825. const channel = this.channels[chNr];
  29826. if (!channel) {
  29827. return false;
  29828. }
  29829. channel.ccMIDROW(b2);
  29830. this.logger.log(3, () => "MIDROW (" + numArrayToHexArray([a2, b2]) + ")");
  29831. return true;
  29832. }
  29833. return false;
  29834. }
  29835. /**
  29836. * Parse Preable Access Codes (Table 53).
  29837. * @returns {Boolean} Tells if PAC found
  29838. */
  29839. parsePAC(a2, b2) {
  29840. let row;
  29841. const case1 = (a2 >= 17 && a2 <= 23 || a2 >= 25 && a2 <= 31) && b2 >= 64 && b2 <= 127;
  29842. const case2 = (a2 === 16 || a2 === 24) && b2 >= 64 && b2 <= 95;
  29843. if (!(case1 || case2)) {
  29844. return false;
  29845. }
  29846. const chNr = a2 <= 23 ? 1 : 2;
  29847. if (b2 >= 64 && b2 <= 95) {
  29848. row = chNr === 1 ? rowsLowCh1[a2] : rowsLowCh2[a2];
  29849. } else {
  29850. row = chNr === 1 ? rowsHighCh1[a2] : rowsHighCh2[a2];
  29851. }
  29852. const channel = this.channels[chNr];
  29853. if (!channel) {
  29854. return false;
  29855. }
  29856. channel.setPAC(this.interpretPAC(row, b2));
  29857. this.currentChannel = chNr;
  29858. return true;
  29859. }
  29860. /**
  29861. * Interpret the second byte of the pac, and return the information.
  29862. * @returns pacData with style parameters
  29863. */
  29864. interpretPAC(row, byte) {
  29865. let pacIndex;
  29866. const pacData = {
  29867. color: null,
  29868. italics: false,
  29869. indent: null,
  29870. underline: false,
  29871. row
  29872. };
  29873. if (byte > 95) {
  29874. pacIndex = byte - 96;
  29875. } else {
  29876. pacIndex = byte - 64;
  29877. }
  29878. pacData.underline = (pacIndex & 1) === 1;
  29879. if (pacIndex <= 13) {
  29880. pacData.color = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "white"][Math.floor(pacIndex / 2)];
  29881. } else if (pacIndex <= 15) {
  29882. pacData.italics = true;
  29883. pacData.color = "white";
  29884. } else {
  29885. pacData.indent = Math.floor((pacIndex - 16) / 2) * 4;
  29886. }
  29887. return pacData;
  29888. }
  29889. /**
  29890. * Parse characters.
  29891. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  29892. */
  29893. parseChars(a2, b2) {
  29894. let channelNr;
  29895. let charCodes = null;
  29896. let charCode1 = null;
  29897. if (a2 >= 25) {
  29898. channelNr = 2;
  29899. charCode1 = a2 - 8;
  29900. } else {
  29901. channelNr = 1;
  29902. charCode1 = a2;
  29903. }
  29904. if (charCode1 >= 17 && charCode1 <= 19) {
  29905. let oneCode;
  29906. if (charCode1 === 17) {
  29907. oneCode = b2 + 80;
  29908. } else if (charCode1 === 18) {
  29909. oneCode = b2 + 112;
  29910. } else {
  29911. oneCode = b2 + 144;
  29912. }
  29913. this.logger.log(2, () => "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
  29914. charCodes = [oneCode];
  29915. } else if (a2 >= 32 && a2 <= 127) {
  29916. charCodes = b2 === 0 ? [a2] : [a2, b2];
  29917. }
  29918. if (charCodes) {
  29919. this.logger.log(3, () => "Char codes = " + numArrayToHexArray(charCodes).join(","));
  29920. }
  29921. return charCodes;
  29922. }
  29923. /**
  29924. * Parse extended background attributes as well as new foreground color black.
  29925. * @returns True if background attributes are found
  29926. */
  29927. parseBackgroundAttributes(a2, b2) {
  29928. const case1 = (a2 === 16 || a2 === 24) && b2 >= 32 && b2 <= 47;
  29929. const case2 = (a2 === 23 || a2 === 31) && b2 >= 45 && b2 <= 47;
  29930. if (!(case1 || case2)) {
  29931. return false;
  29932. }
  29933. let index2;
  29934. const bkgData = {};
  29935. if (a2 === 16 || a2 === 24) {
  29936. index2 = Math.floor((b2 - 32) / 2);
  29937. bkgData.background = backgroundColors[index2];
  29938. if (b2 % 2 === 1) {
  29939. bkgData.background = bkgData.background + "_semi";
  29940. }
  29941. } else if (b2 === 45) {
  29942. bkgData.background = "transparent";
  29943. } else {
  29944. bkgData.foreground = "black";
  29945. if (b2 === 47) {
  29946. bkgData.underline = true;
  29947. }
  29948. }
  29949. const chNr = a2 <= 23 ? 1 : 2;
  29950. const channel = this.channels[chNr];
  29951. channel.setBkgData(bkgData);
  29952. return true;
  29953. }
  29954. /**
  29955. * Reset state of parser and its channels.
  29956. */
  29957. reset() {
  29958. for (let i2 = 0; i2 < Object.keys(this.channels).length; i2++) {
  29959. const channel = this.channels[i2];
  29960. if (channel) {
  29961. channel.reset();
  29962. }
  29963. }
  29964. setLastCmd(null, null, this.cmdHistory);
  29965. }
  29966. /**
  29967. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  29968. */
  29969. cueSplitAtTime(t2) {
  29970. for (let i2 = 0; i2 < this.channels.length; i2++) {
  29971. const channel = this.channels[i2];
  29972. if (channel) {
  29973. channel.cueSplitAtTime(t2);
  29974. }
  29975. }
  29976. }
  29977. }
  29978. function setLastCmd(a2, b2, cmdHistory) {
  29979. cmdHistory.a = a2;
  29980. cmdHistory.b = b2;
  29981. }
  29982. function hasCmdRepeated(a2, b2, cmdHistory) {
  29983. return cmdHistory.a === a2 && cmdHistory.b === b2;
  29984. }
  29985. function createCmdHistory() {
  29986. return {
  29987. a: null,
  29988. b: null
  29989. };
  29990. }
  29991. var VTTCue = function() {
  29992. if (optionalSelf != null && optionalSelf.VTTCue) {
  29993. return self.VTTCue;
  29994. }
  29995. const AllowedDirections = ["", "lr", "rl"];
  29996. const AllowedAlignments = ["start", "middle", "end", "left", "right"];
  29997. function isAllowedValue(allowed, value2) {
  29998. if (typeof value2 !== "string") {
  29999. return false;
  30000. }
  30001. if (!Array.isArray(allowed)) {
  30002. return false;
  30003. }
  30004. const lcValue = value2.toLowerCase();
  30005. if (~allowed.indexOf(lcValue)) {
  30006. return lcValue;
  30007. }
  30008. return false;
  30009. }
  30010. function findDirectionSetting(value2) {
  30011. return isAllowedValue(AllowedDirections, value2);
  30012. }
  30013. function findAlignSetting(value2) {
  30014. return isAllowedValue(AllowedAlignments, value2);
  30015. }
  30016. function extend(obj, ...rest) {
  30017. let i2 = 1;
  30018. for (; i2 < arguments.length; i2++) {
  30019. const cobj = arguments[i2];
  30020. for (const p2 in cobj) {
  30021. obj[p2] = cobj[p2];
  30022. }
  30023. }
  30024. return obj;
  30025. }
  30026. function VTTCue2(startTime, endTime, text) {
  30027. const cue = this;
  30028. const baseObj = {
  30029. enumerable: true
  30030. };
  30031. cue.hasBeenReset = false;
  30032. let _id = "";
  30033. let _pauseOnExit = false;
  30034. let _startTime = startTime;
  30035. let _endTime = endTime;
  30036. let _text = text;
  30037. let _region = null;
  30038. let _vertical = "";
  30039. let _snapToLines = true;
  30040. let _line = "auto";
  30041. let _lineAlign = "start";
  30042. let _position = 50;
  30043. let _positionAlign = "middle";
  30044. let _size = 50;
  30045. let _align = "middle";
  30046. Object.defineProperty(cue, "id", extend({}, baseObj, {
  30047. get: function() {
  30048. return _id;
  30049. },
  30050. set: function(value2) {
  30051. _id = "" + value2;
  30052. }
  30053. }));
  30054. Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, {
  30055. get: function() {
  30056. return _pauseOnExit;
  30057. },
  30058. set: function(value2) {
  30059. _pauseOnExit = !!value2;
  30060. }
  30061. }));
  30062. Object.defineProperty(cue, "startTime", extend({}, baseObj, {
  30063. get: function() {
  30064. return _startTime;
  30065. },
  30066. set: function(value2) {
  30067. if (typeof value2 !== "number") {
  30068. throw new TypeError("Start time must be set to a number.");
  30069. }
  30070. _startTime = value2;
  30071. this.hasBeenReset = true;
  30072. }
  30073. }));
  30074. Object.defineProperty(cue, "endTime", extend({}, baseObj, {
  30075. get: function() {
  30076. return _endTime;
  30077. },
  30078. set: function(value2) {
  30079. if (typeof value2 !== "number") {
  30080. throw new TypeError("End time must be set to a number.");
  30081. }
  30082. _endTime = value2;
  30083. this.hasBeenReset = true;
  30084. }
  30085. }));
  30086. Object.defineProperty(cue, "text", extend({}, baseObj, {
  30087. get: function() {
  30088. return _text;
  30089. },
  30090. set: function(value2) {
  30091. _text = "" + value2;
  30092. this.hasBeenReset = true;
  30093. }
  30094. }));
  30095. Object.defineProperty(cue, "region", extend({}, baseObj, {
  30096. get: function() {
  30097. return _region;
  30098. },
  30099. set: function(value2) {
  30100. _region = value2;
  30101. this.hasBeenReset = true;
  30102. }
  30103. }));
  30104. Object.defineProperty(cue, "vertical", extend({}, baseObj, {
  30105. get: function() {
  30106. return _vertical;
  30107. },
  30108. set: function(value2) {
  30109. const setting = findDirectionSetting(value2);
  30110. if (setting === false) {
  30111. throw new SyntaxError("An invalid or illegal string was specified.");
  30112. }
  30113. _vertical = setting;
  30114. this.hasBeenReset = true;
  30115. }
  30116. }));
  30117. Object.defineProperty(cue, "snapToLines", extend({}, baseObj, {
  30118. get: function() {
  30119. return _snapToLines;
  30120. },
  30121. set: function(value2) {
  30122. _snapToLines = !!value2;
  30123. this.hasBeenReset = true;
  30124. }
  30125. }));
  30126. Object.defineProperty(cue, "line", extend({}, baseObj, {
  30127. get: function() {
  30128. return _line;
  30129. },
  30130. set: function(value2) {
  30131. if (typeof value2 !== "number" && value2 !== "auto") {
  30132. throw new SyntaxError("An invalid number or illegal string was specified.");
  30133. }
  30134. _line = value2;
  30135. this.hasBeenReset = true;
  30136. }
  30137. }));
  30138. Object.defineProperty(cue, "lineAlign", extend({}, baseObj, {
  30139. get: function() {
  30140. return _lineAlign;
  30141. },
  30142. set: function(value2) {
  30143. const setting = findAlignSetting(value2);
  30144. if (!setting) {
  30145. throw new SyntaxError("An invalid or illegal string was specified.");
  30146. }
  30147. _lineAlign = setting;
  30148. this.hasBeenReset = true;
  30149. }
  30150. }));
  30151. Object.defineProperty(cue, "position", extend({}, baseObj, {
  30152. get: function() {
  30153. return _position;
  30154. },
  30155. set: function(value2) {
  30156. if (value2 < 0 || value2 > 100) {
  30157. throw new Error("Position must be between 0 and 100.");
  30158. }
  30159. _position = value2;
  30160. this.hasBeenReset = true;
  30161. }
  30162. }));
  30163. Object.defineProperty(cue, "positionAlign", extend({}, baseObj, {
  30164. get: function() {
  30165. return _positionAlign;
  30166. },
  30167. set: function(value2) {
  30168. const setting = findAlignSetting(value2);
  30169. if (!setting) {
  30170. throw new SyntaxError("An invalid or illegal string was specified.");
  30171. }
  30172. _positionAlign = setting;
  30173. this.hasBeenReset = true;
  30174. }
  30175. }));
  30176. Object.defineProperty(cue, "size", extend({}, baseObj, {
  30177. get: function() {
  30178. return _size;
  30179. },
  30180. set: function(value2) {
  30181. if (value2 < 0 || value2 > 100) {
  30182. throw new Error("Size must be between 0 and 100.");
  30183. }
  30184. _size = value2;
  30185. this.hasBeenReset = true;
  30186. }
  30187. }));
  30188. Object.defineProperty(cue, "align", extend({}, baseObj, {
  30189. get: function() {
  30190. return _align;
  30191. },
  30192. set: function(value2) {
  30193. const setting = findAlignSetting(value2);
  30194. if (!setting) {
  30195. throw new SyntaxError("An invalid or illegal string was specified.");
  30196. }
  30197. _align = setting;
  30198. this.hasBeenReset = true;
  30199. }
  30200. }));
  30201. cue.displayState = void 0;
  30202. }
  30203. VTTCue2.prototype.getCueAsHTML = function() {
  30204. const WebVTT = self.WebVTT;
  30205. return WebVTT.convertCueToDOMTree(self, this.text);
  30206. };
  30207. return VTTCue2;
  30208. }();
  30209. class StringDecoder {
  30210. decode(data, options) {
  30211. if (!data) {
  30212. return "";
  30213. }
  30214. if (typeof data !== "string") {
  30215. throw new Error("Error - expected string data.");
  30216. }
  30217. return decodeURIComponent(encodeURIComponent(data));
  30218. }
  30219. }
  30220. function parseTimeStamp(input) {
  30221. function computeSeconds(h2, m3, s2, f2) {
  30222. return (h2 | 0) * 3600 + (m3 | 0) * 60 + (s2 | 0) + parseFloat(f2 || 0);
  30223. }
  30224. const m2 = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
  30225. if (!m2) {
  30226. return null;
  30227. }
  30228. if (parseFloat(m2[2]) > 59) {
  30229. return computeSeconds(m2[2], m2[3], 0, m2[4]);
  30230. }
  30231. return computeSeconds(m2[1], m2[2], m2[3], m2[4]);
  30232. }
  30233. class Settings {
  30234. constructor() {
  30235. this.values = /* @__PURE__ */ Object.create(null);
  30236. }
  30237. // Only accept the first assignment to any key.
  30238. set(k, v2) {
  30239. if (!this.get(k) && v2 !== "") {
  30240. this.values[k] = v2;
  30241. }
  30242. }
  30243. // Return the value for a key, or a default value.
  30244. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  30245. // a number of possible default values as properties where 'defaultKey' is
  30246. // the key of the property that will be chosen; otherwise it's assumed to be
  30247. // a single value.
  30248. get(k, dflt, defaultKey) {
  30249. if (defaultKey) {
  30250. return this.has(k) ? this.values[k] : dflt[defaultKey];
  30251. }
  30252. return this.has(k) ? this.values[k] : dflt;
  30253. }
  30254. // Check whether we have a value for a key.
  30255. has(k) {
  30256. return k in this.values;
  30257. }
  30258. // Accept a setting if its one of the given alternatives.
  30259. alt(k, v2, a2) {
  30260. for (let n2 = 0; n2 < a2.length; ++n2) {
  30261. if (v2 === a2[n2]) {
  30262. this.set(k, v2);
  30263. break;
  30264. }
  30265. }
  30266. }
  30267. // Accept a setting if its a valid (signed) integer.
  30268. integer(k, v2) {
  30269. if (/^-?\d+$/.test(v2)) {
  30270. this.set(k, parseInt(v2, 10));
  30271. }
  30272. }
  30273. // Accept a setting if its a valid percentage.
  30274. percent(k, v2) {
  30275. if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v2)) {
  30276. const percent = parseFloat(v2);
  30277. if (percent >= 0 && percent <= 100) {
  30278. this.set(k, percent);
  30279. return true;
  30280. }
  30281. }
  30282. return false;
  30283. }
  30284. }
  30285. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  30286. const groups = groupDelim ? input.split(groupDelim) : [input];
  30287. for (const i2 in groups) {
  30288. if (typeof groups[i2] !== "string") {
  30289. continue;
  30290. }
  30291. const kv = groups[i2].split(keyValueDelim);
  30292. if (kv.length !== 2) {
  30293. continue;
  30294. }
  30295. const k = kv[0];
  30296. const v2 = kv[1];
  30297. callback(k, v2);
  30298. }
  30299. }
  30300. const defaults$1 = new VTTCue(0, 0, "");
  30301. const center = defaults$1.align === "middle" ? "middle" : "center";
  30302. function parseCue(input, cue, regionList) {
  30303. const oInput = input;
  30304. function consumeTimeStamp() {
  30305. const ts2 = parseTimeStamp(input);
  30306. if (ts2 === null) {
  30307. throw new Error("Malformed timestamp: " + oInput);
  30308. }
  30309. input = input.replace(/^[^\sa-zA-Z-]+/, "");
  30310. return ts2;
  30311. }
  30312. function consumeCueSettings(input2, cue2) {
  30313. const settings = new Settings();
  30314. parseOptions(input2, function(k, v2) {
  30315. let vals;
  30316. switch (k) {
  30317. case "region":
  30318. for (let i2 = regionList.length - 1; i2 >= 0; i2--) {
  30319. if (regionList[i2].id === v2) {
  30320. settings.set(k, regionList[i2].region);
  30321. break;
  30322. }
  30323. }
  30324. break;
  30325. case "vertical":
  30326. settings.alt(k, v2, ["rl", "lr"]);
  30327. break;
  30328. case "line":
  30329. vals = v2.split(",");
  30330. settings.integer(k, vals[0]);
  30331. if (settings.percent(k, vals[0])) {
  30332. settings.set("snapToLines", false);
  30333. }
  30334. settings.alt(k, vals[0], ["auto"]);
  30335. if (vals.length === 2) {
  30336. settings.alt("lineAlign", vals[1], ["start", center, "end"]);
  30337. }
  30338. break;
  30339. case "position":
  30340. vals = v2.split(",");
  30341. settings.percent(k, vals[0]);
  30342. if (vals.length === 2) {
  30343. settings.alt("positionAlign", vals[1], ["start", center, "end", "line-left", "line-right", "auto"]);
  30344. }
  30345. break;
  30346. case "size":
  30347. settings.percent(k, v2);
  30348. break;
  30349. case "align":
  30350. settings.alt(k, v2, ["start", center, "end", "left", "right"]);
  30351. break;
  30352. }
  30353. }, /:/, /\s/);
  30354. cue2.region = settings.get("region", null);
  30355. cue2.vertical = settings.get("vertical", "");
  30356. let line = settings.get("line", "auto");
  30357. if (line === "auto" && defaults$1.line === -1) {
  30358. line = -1;
  30359. }
  30360. cue2.line = line;
  30361. cue2.lineAlign = settings.get("lineAlign", "start");
  30362. cue2.snapToLines = settings.get("snapToLines", true);
  30363. cue2.size = settings.get("size", 100);
  30364. cue2.align = settings.get("align", center);
  30365. let position = settings.get("position", "auto");
  30366. if (position === "auto" && defaults$1.position === 50) {
  30367. position = cue2.align === "start" || cue2.align === "left" ? 0 : cue2.align === "end" || cue2.align === "right" ? 100 : 50;
  30368. }
  30369. cue2.position = position;
  30370. }
  30371. function skipWhitespace() {
  30372. input = input.replace(/^\s+/, "");
  30373. }
  30374. skipWhitespace();
  30375. cue.startTime = consumeTimeStamp();
  30376. skipWhitespace();
  30377. if (input.slice(0, 3) !== "-->") {
  30378. throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  30379. }
  30380. input = input.slice(3);
  30381. skipWhitespace();
  30382. cue.endTime = consumeTimeStamp();
  30383. skipWhitespace();
  30384. consumeCueSettings(input, cue);
  30385. }
  30386. function fixLineBreaks(input) {
  30387. return input.replace(/<br(?: \/)?>/gi, "\n");
  30388. }
  30389. class VTTParser {
  30390. constructor() {
  30391. this.state = "INITIAL";
  30392. this.buffer = "";
  30393. this.decoder = new StringDecoder();
  30394. this.regionList = [];
  30395. this.cue = null;
  30396. this.oncue = void 0;
  30397. this.onparsingerror = void 0;
  30398. this.onflush = void 0;
  30399. }
  30400. parse(data) {
  30401. const _this = this;
  30402. if (data) {
  30403. _this.buffer += _this.decoder.decode(data, {
  30404. stream: true
  30405. });
  30406. }
  30407. function collectNextLine() {
  30408. let buffer = _this.buffer;
  30409. let pos = 0;
  30410. buffer = fixLineBreaks(buffer);
  30411. while (pos < buffer.length && buffer[pos] !== "\r" && buffer[pos] !== "\n") {
  30412. ++pos;
  30413. }
  30414. const line = buffer.slice(0, pos);
  30415. if (buffer[pos] === "\r") {
  30416. ++pos;
  30417. }
  30418. if (buffer[pos] === "\n") {
  30419. ++pos;
  30420. }
  30421. _this.buffer = buffer.slice(pos);
  30422. return line;
  30423. }
  30424. function parseHeader2(input) {
  30425. parseOptions(input, function(k, v2) {
  30426. }, /:/);
  30427. }
  30428. try {
  30429. let line = "";
  30430. if (_this.state === "INITIAL") {
  30431. if (!/\r\n|\n/.test(_this.buffer)) {
  30432. return this;
  30433. }
  30434. line = collectNextLine();
  30435. const m2 = line.match(/^()?WEBVTT([ \t].*)?$/);
  30436. if (!(m2 != null && m2[0])) {
  30437. throw new Error("Malformed WebVTT signature.");
  30438. }
  30439. _this.state = "HEADER";
  30440. }
  30441. let alreadyCollectedLine = false;
  30442. while (_this.buffer) {
  30443. if (!/\r\n|\n/.test(_this.buffer)) {
  30444. return this;
  30445. }
  30446. if (!alreadyCollectedLine) {
  30447. line = collectNextLine();
  30448. } else {
  30449. alreadyCollectedLine = false;
  30450. }
  30451. switch (_this.state) {
  30452. case "HEADER":
  30453. if (/:/.test(line)) {
  30454. parseHeader2(line);
  30455. } else if (!line) {
  30456. _this.state = "ID";
  30457. }
  30458. continue;
  30459. case "NOTE":
  30460. if (!line) {
  30461. _this.state = "ID";
  30462. }
  30463. continue;
  30464. case "ID":
  30465. if (/^NOTE($|[ \t])/.test(line)) {
  30466. _this.state = "NOTE";
  30467. break;
  30468. }
  30469. if (!line) {
  30470. continue;
  30471. }
  30472. _this.cue = new VTTCue(0, 0, "");
  30473. _this.state = "CUE";
  30474. if (line.indexOf("-->") === -1) {
  30475. _this.cue.id = line;
  30476. continue;
  30477. }
  30478. case "CUE":
  30479. if (!_this.cue) {
  30480. _this.state = "BADCUE";
  30481. continue;
  30482. }
  30483. try {
  30484. parseCue(line, _this.cue, _this.regionList);
  30485. } catch (e2) {
  30486. _this.cue = null;
  30487. _this.state = "BADCUE";
  30488. continue;
  30489. }
  30490. _this.state = "CUETEXT";
  30491. continue;
  30492. case "CUETEXT":
  30493. {
  30494. const hasSubstring = line.indexOf("-->") !== -1;
  30495. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  30496. if (_this.oncue && _this.cue) {
  30497. _this.oncue(_this.cue);
  30498. }
  30499. _this.cue = null;
  30500. _this.state = "ID";
  30501. continue;
  30502. }
  30503. if (_this.cue === null) {
  30504. continue;
  30505. }
  30506. if (_this.cue.text) {
  30507. _this.cue.text += "\n";
  30508. }
  30509. _this.cue.text += line;
  30510. }
  30511. continue;
  30512. case "BADCUE":
  30513. if (!line) {
  30514. _this.state = "ID";
  30515. }
  30516. }
  30517. }
  30518. } catch (e2) {
  30519. if (_this.state === "CUETEXT" && _this.cue && _this.oncue) {
  30520. _this.oncue(_this.cue);
  30521. }
  30522. _this.cue = null;
  30523. _this.state = _this.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  30524. }
  30525. return this;
  30526. }
  30527. flush() {
  30528. const _this = this;
  30529. try {
  30530. if (_this.cue || _this.state === "HEADER") {
  30531. _this.buffer += "\n\n";
  30532. _this.parse();
  30533. }
  30534. if (_this.state === "INITIAL" || _this.state === "BADWEBVTT") {
  30535. throw new Error("Malformed WebVTT signature.");
  30536. }
  30537. } catch (e2) {
  30538. if (_this.onparsingerror) {
  30539. _this.onparsingerror(e2);
  30540. }
  30541. }
  30542. if (_this.onflush) {
  30543. _this.onflush();
  30544. }
  30545. return this;
  30546. }
  30547. }
  30548. const LINEBREAKS = /\r\n|\n\r|\n|\r/g;
  30549. const startsWith = function startsWith2(inputString, searchString, position = 0) {
  30550. return inputString.slice(position, position + searchString.length) === searchString;
  30551. };
  30552. const cueString2millis = function cueString2millis2(timeString) {
  30553. let ts2 = parseInt(timeString.slice(-3));
  30554. const secs = parseInt(timeString.slice(-6, -4));
  30555. const mins = parseInt(timeString.slice(-9, -7));
  30556. const hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(":"))) : 0;
  30557. if (!isFiniteNumber(ts2) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {
  30558. throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);
  30559. }
  30560. ts2 += 1e3 * secs;
  30561. ts2 += 60 * 1e3 * mins;
  30562. ts2 += 60 * 60 * 1e3 * hours;
  30563. return ts2;
  30564. };
  30565. function generateCueId(startTime, endTime, text) {
  30566. return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
  30567. }
  30568. const calculateOffset = function calculateOffset2(vttCCs, cc, presentationTime) {
  30569. let currCC = vttCCs[cc];
  30570. let prevCC = vttCCs[currCC.prevCC];
  30571. if (!prevCC || !prevCC.new && currCC.new) {
  30572. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  30573. currCC.new = false;
  30574. return;
  30575. }
  30576. while ((_prevCC = prevCC) != null && _prevCC.new) {
  30577. var _prevCC;
  30578. vttCCs.ccOffset += currCC.start - prevCC.start;
  30579. currCC.new = false;
  30580. currCC = prevCC;
  30581. prevCC = vttCCs[currCC.prevCC];
  30582. }
  30583. vttCCs.presentationOffset = presentationTime;
  30584. };
  30585. function parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) {
  30586. const parser = new VTTParser();
  30587. const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, "\n").split("\n");
  30588. const cues = [];
  30589. const init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0;
  30590. let cueTime = "00:00.000";
  30591. let timestampMapMPEGTS = 0;
  30592. let timestampMapLOCAL = 0;
  30593. let parsingError;
  30594. let inHeader = true;
  30595. parser.oncue = function(cue) {
  30596. const currCC = vttCCs[cc];
  30597. let cueOffset = vttCCs.ccOffset;
  30598. const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 9e4;
  30599. if (currCC != null && currCC.new) {
  30600. if (timestampMapLOCAL !== void 0) {
  30601. cueOffset = vttCCs.ccOffset = currCC.start;
  30602. } else {
  30603. calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
  30604. }
  30605. }
  30606. if (webVttMpegTsMapOffset) {
  30607. if (!initPTS) {
  30608. parsingError = new Error("Missing initPTS for VTT MPEGTS");
  30609. return;
  30610. }
  30611. cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
  30612. }
  30613. const duration = cue.endTime - cue.startTime;
  30614. const startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 9e4, timeOffset * 9e4) / 9e4;
  30615. cue.startTime = Math.max(startTime, 0);
  30616. cue.endTime = Math.max(startTime + duration, 0);
  30617. const text = cue.text.trim();
  30618. cue.text = decodeURIComponent(encodeURIComponent(text));
  30619. if (!cue.id) {
  30620. cue.id = generateCueId(cue.startTime, cue.endTime, text);
  30621. }
  30622. if (cue.endTime > 0) {
  30623. cues.push(cue);
  30624. }
  30625. };
  30626. parser.onparsingerror = function(error2) {
  30627. parsingError = error2;
  30628. };
  30629. parser.onflush = function() {
  30630. if (parsingError) {
  30631. errorCallBack(parsingError);
  30632. return;
  30633. }
  30634. callBack(cues);
  30635. };
  30636. vttLines.forEach((line) => {
  30637. if (inHeader) {
  30638. if (startsWith(line, "X-TIMESTAMP-MAP=")) {
  30639. inHeader = false;
  30640. line.slice(16).split(",").forEach((timestamp) => {
  30641. if (startsWith(timestamp, "LOCAL:")) {
  30642. cueTime = timestamp.slice(6);
  30643. } else if (startsWith(timestamp, "MPEGTS:")) {
  30644. timestampMapMPEGTS = parseInt(timestamp.slice(7));
  30645. }
  30646. });
  30647. try {
  30648. timestampMapLOCAL = cueString2millis(cueTime) / 1e3;
  30649. } catch (error2) {
  30650. parsingError = error2;
  30651. }
  30652. return;
  30653. } else if (line === "") {
  30654. inHeader = false;
  30655. }
  30656. }
  30657. parser.parse(line + "\n");
  30658. });
  30659. parser.flush();
  30660. }
  30661. const IMSC1_CODEC = "stpp.ttml.im1t";
  30662. const HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;
  30663. const TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
  30664. const textAlignToLineAlign = {
  30665. left: "start",
  30666. center: "center",
  30667. right: "end",
  30668. start: "start",
  30669. end: "end"
  30670. };
  30671. function parseIMSC1(payload, initPTS, callBack, errorCallBack) {
  30672. const results = findBox(new Uint8Array(payload), ["mdat"]);
  30673. if (results.length === 0) {
  30674. errorCallBack(new Error("Could not parse IMSC1 mdat"));
  30675. return;
  30676. }
  30677. const ttmlList = results.map((mdat) => utf8ArrayToStr(mdat));
  30678. const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);
  30679. try {
  30680. ttmlList.forEach((ttml) => callBack(parseTTML(ttml, syncTime)));
  30681. } catch (error2) {
  30682. errorCallBack(error2);
  30683. }
  30684. }
  30685. function parseTTML(ttml, syncTime) {
  30686. const parser = new DOMParser();
  30687. const xmlDoc = parser.parseFromString(ttml, "text/xml");
  30688. const tt2 = xmlDoc.getElementsByTagName("tt")[0];
  30689. if (!tt2) {
  30690. throw new Error("Invalid ttml");
  30691. }
  30692. const defaultRateInfo = {
  30693. frameRate: 30,
  30694. subFrameRate: 1,
  30695. frameRateMultiplier: 0,
  30696. tickRate: 0
  30697. };
  30698. const rateInfo = Object.keys(defaultRateInfo).reduce((result, key) => {
  30699. result[key] = tt2.getAttribute(`ttp:${key}`) || defaultRateInfo[key];
  30700. return result;
  30701. }, {});
  30702. const trim2 = tt2.getAttribute("xml:space") !== "preserve";
  30703. const styleElements = collectionToDictionary(getElementCollection(tt2, "styling", "style"));
  30704. const regionElements = collectionToDictionary(getElementCollection(tt2, "layout", "region"));
  30705. const cueElements = getElementCollection(tt2, "body", "[begin]");
  30706. return [].map.call(cueElements, (cueElement) => {
  30707. const cueText = getTextContent(cueElement, trim2);
  30708. if (!cueText || !cueElement.hasAttribute("begin")) {
  30709. return null;
  30710. }
  30711. const startTime = parseTtmlTime(cueElement.getAttribute("begin"), rateInfo);
  30712. const duration = parseTtmlTime(cueElement.getAttribute("dur"), rateInfo);
  30713. let endTime = parseTtmlTime(cueElement.getAttribute("end"), rateInfo);
  30714. if (startTime === null) {
  30715. throw timestampParsingError(cueElement);
  30716. }
  30717. if (endTime === null) {
  30718. if (duration === null) {
  30719. throw timestampParsingError(cueElement);
  30720. }
  30721. endTime = startTime + duration;
  30722. }
  30723. const cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);
  30724. cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);
  30725. const region = regionElements[cueElement.getAttribute("region")];
  30726. const style = styleElements[cueElement.getAttribute("style")];
  30727. const styles = getTtmlStyles(region, style, styleElements);
  30728. const {
  30729. textAlign
  30730. } = styles;
  30731. if (textAlign) {
  30732. const lineAlign = textAlignToLineAlign[textAlign];
  30733. if (lineAlign) {
  30734. cue.lineAlign = lineAlign;
  30735. }
  30736. cue.align = textAlign;
  30737. }
  30738. _extends(cue, styles);
  30739. return cue;
  30740. }).filter((cue) => cue !== null);
  30741. }
  30742. function getElementCollection(fromElement, parentName, childName) {
  30743. const parent = fromElement.getElementsByTagName(parentName)[0];
  30744. if (parent) {
  30745. return [].slice.call(parent.querySelectorAll(childName));
  30746. }
  30747. return [];
  30748. }
  30749. function collectionToDictionary(elementsWithId) {
  30750. return elementsWithId.reduce((dict, element) => {
  30751. const id = element.getAttribute("xml:id");
  30752. if (id) {
  30753. dict[id] = element;
  30754. }
  30755. return dict;
  30756. }, {});
  30757. }
  30758. function getTextContent(element, trim2) {
  30759. return [].slice.call(element.childNodes).reduce((str, node, i2) => {
  30760. var _node$childNodes;
  30761. if (node.nodeName === "br" && i2) {
  30762. return str + "\n";
  30763. }
  30764. if ((_node$childNodes = node.childNodes) != null && _node$childNodes.length) {
  30765. return getTextContent(node, trim2);
  30766. } else if (trim2) {
  30767. return str + node.textContent.trim().replace(/\s+/g, " ");
  30768. }
  30769. return str + node.textContent;
  30770. }, "");
  30771. }
  30772. function getTtmlStyles(region, style, styleElements) {
  30773. const ttsNs = "http://www.w3.org/ns/ttml#styling";
  30774. let regionStyle = null;
  30775. const styleAttributes = [
  30776. "displayAlign",
  30777. "textAlign",
  30778. "color",
  30779. "backgroundColor",
  30780. "fontSize",
  30781. "fontFamily"
  30782. // 'fontWeight',
  30783. // 'lineHeight',
  30784. // 'wrapOption',
  30785. // 'fontStyle',
  30786. // 'direction',
  30787. // 'writingMode'
  30788. ];
  30789. const regionStyleName = region != null && region.hasAttribute("style") ? region.getAttribute("style") : null;
  30790. if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {
  30791. regionStyle = styleElements[regionStyleName];
  30792. }
  30793. return styleAttributes.reduce((styles, name) => {
  30794. const value2 = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name);
  30795. if (value2) {
  30796. styles[name] = value2;
  30797. }
  30798. return styles;
  30799. }, {});
  30800. }
  30801. function getAttributeNS(element, ns2, name) {
  30802. if (!element) {
  30803. return null;
  30804. }
  30805. return element.hasAttributeNS(ns2, name) ? element.getAttributeNS(ns2, name) : null;
  30806. }
  30807. function timestampParsingError(node) {
  30808. return new Error(`Could not parse ttml timestamp ${node}`);
  30809. }
  30810. function parseTtmlTime(timeAttributeValue, rateInfo) {
  30811. if (!timeAttributeValue) {
  30812. return null;
  30813. }
  30814. let seconds = parseTimeStamp(timeAttributeValue);
  30815. if (seconds === null) {
  30816. if (HMSF_REGEX.test(timeAttributeValue)) {
  30817. seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
  30818. } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
  30819. seconds = parseTimeUnits(timeAttributeValue, rateInfo);
  30820. }
  30821. }
  30822. return seconds;
  30823. }
  30824. function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
  30825. const m2 = HMSF_REGEX.exec(timeAttributeValue);
  30826. const frames = (m2[4] | 0) + (m2[5] | 0) / rateInfo.subFrameRate;
  30827. return (m2[1] | 0) * 3600 + (m2[2] | 0) * 60 + (m2[3] | 0) + frames / rateInfo.frameRate;
  30828. }
  30829. function parseTimeUnits(timeAttributeValue, rateInfo) {
  30830. const m2 = TIME_UNIT_REGEX.exec(timeAttributeValue);
  30831. const value2 = Number(m2[1]);
  30832. const unit = m2[2];
  30833. switch (unit) {
  30834. case "h":
  30835. return value2 * 3600;
  30836. case "m":
  30837. return value2 * 60;
  30838. case "ms":
  30839. return value2 * 1e3;
  30840. case "f":
  30841. return value2 / rateInfo.frameRate;
  30842. case "t":
  30843. return value2 / rateInfo.tickRate;
  30844. }
  30845. return value2;
  30846. }
  30847. class OutputFilter {
  30848. constructor(timelineController, trackName) {
  30849. this.timelineController = void 0;
  30850. this.cueRanges = [];
  30851. this.trackName = void 0;
  30852. this.startTime = null;
  30853. this.endTime = null;
  30854. this.screen = null;
  30855. this.timelineController = timelineController;
  30856. this.trackName = trackName;
  30857. }
  30858. dispatchCue() {
  30859. if (this.startTime === null) {
  30860. return;
  30861. }
  30862. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
  30863. this.startTime = null;
  30864. }
  30865. newCue(startTime, endTime, screen) {
  30866. if (this.startTime === null || this.startTime > startTime) {
  30867. this.startTime = startTime;
  30868. }
  30869. this.endTime = endTime;
  30870. this.screen = screen;
  30871. this.timelineController.createCaptionsTrack(this.trackName);
  30872. }
  30873. reset() {
  30874. this.cueRanges = [];
  30875. this.startTime = null;
  30876. }
  30877. }
  30878. class TimelineController {
  30879. constructor(hls) {
  30880. this.hls = void 0;
  30881. this.media = null;
  30882. this.config = void 0;
  30883. this.enabled = true;
  30884. this.Cues = void 0;
  30885. this.textTracks = [];
  30886. this.tracks = [];
  30887. this.initPTS = [];
  30888. this.unparsedVttFrags = [];
  30889. this.captionsTracks = {};
  30890. this.nonNativeCaptionsTracks = {};
  30891. this.cea608Parser1 = void 0;
  30892. this.cea608Parser2 = void 0;
  30893. this.lastCc = -1;
  30894. this.lastSn = -1;
  30895. this.lastPartIndex = -1;
  30896. this.prevCC = -1;
  30897. this.vttCCs = newVTTCCs();
  30898. this.captionsProperties = void 0;
  30899. this.hls = hls;
  30900. this.config = hls.config;
  30901. this.Cues = hls.config.cueHandler;
  30902. this.captionsProperties = {
  30903. textTrack1: {
  30904. label: this.config.captionsTextTrack1Label,
  30905. languageCode: this.config.captionsTextTrack1LanguageCode
  30906. },
  30907. textTrack2: {
  30908. label: this.config.captionsTextTrack2Label,
  30909. languageCode: this.config.captionsTextTrack2LanguageCode
  30910. },
  30911. textTrack3: {
  30912. label: this.config.captionsTextTrack3Label,
  30913. languageCode: this.config.captionsTextTrack3LanguageCode
  30914. },
  30915. textTrack4: {
  30916. label: this.config.captionsTextTrack4Label,
  30917. languageCode: this.config.captionsTextTrack4LanguageCode
  30918. }
  30919. };
  30920. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  30921. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  30922. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  30923. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  30924. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  30925. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  30926. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  30927. hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  30928. hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  30929. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  30930. hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  30931. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  30932. }
  30933. destroy() {
  30934. const {
  30935. hls
  30936. } = this;
  30937. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  30938. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  30939. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  30940. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  30941. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  30942. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  30943. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  30944. hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  30945. hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  30946. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  30947. hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  30948. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  30949. this.hls = this.config = this.media = null;
  30950. this.cea608Parser1 = this.cea608Parser2 = void 0;
  30951. }
  30952. initCea608Parsers() {
  30953. const channel1 = new OutputFilter(this, "textTrack1");
  30954. const channel2 = new OutputFilter(this, "textTrack2");
  30955. const channel3 = new OutputFilter(this, "textTrack3");
  30956. const channel4 = new OutputFilter(this, "textTrack4");
  30957. this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);
  30958. this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);
  30959. }
  30960. addCues(trackName, startTime, endTime, screen, cueRanges) {
  30961. let merged = false;
  30962. for (let i2 = cueRanges.length; i2--; ) {
  30963. const cueRange = cueRanges[i2];
  30964. const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  30965. if (overlap >= 0) {
  30966. cueRange[0] = Math.min(cueRange[0], startTime);
  30967. cueRange[1] = Math.max(cueRange[1], endTime);
  30968. merged = true;
  30969. if (overlap / (endTime - startTime) > 0.5) {
  30970. return;
  30971. }
  30972. }
  30973. }
  30974. if (!merged) {
  30975. cueRanges.push([startTime, endTime]);
  30976. }
  30977. if (this.config.renderTextTracksNatively) {
  30978. const track = this.captionsTracks[trackName];
  30979. this.Cues.newCue(track, startTime, endTime, screen);
  30980. } else {
  30981. const cues = this.Cues.newCue(null, startTime, endTime, screen);
  30982. this.hls.trigger(Events.CUES_PARSED, {
  30983. type: "captions",
  30984. cues,
  30985. track: trackName
  30986. });
  30987. }
  30988. }
  30989. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  30990. onInitPtsFound(event, {
  30991. frag,
  30992. id,
  30993. initPTS,
  30994. timescale
  30995. }) {
  30996. const {
  30997. unparsedVttFrags
  30998. } = this;
  30999. if (id === PlaylistLevelType.MAIN) {
  31000. this.initPTS[frag.cc] = {
  31001. baseTime: initPTS,
  31002. timescale
  31003. };
  31004. }
  31005. if (unparsedVttFrags.length) {
  31006. this.unparsedVttFrags = [];
  31007. unparsedVttFrags.forEach((data) => {
  31008. if (this.initPTS[data.frag.cc]) {
  31009. this.onFragLoaded(Events.FRAG_LOADED, data);
  31010. } else {
  31011. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  31012. success: false,
  31013. frag: data.frag,
  31014. error: new Error("Subtitle discontinuity domain does not match main")
  31015. });
  31016. }
  31017. });
  31018. }
  31019. }
  31020. getExistingTrack(label, language) {
  31021. const {
  31022. media
  31023. } = this;
  31024. if (media) {
  31025. for (let i2 = 0; i2 < media.textTracks.length; i2++) {
  31026. const textTrack = media.textTracks[i2];
  31027. if (canReuseVttTextTrack(textTrack, {
  31028. name: label,
  31029. lang: language,
  31030. characteristics: "transcribes-spoken-dialog,describes-music-and-sound"
  31031. })) {
  31032. return textTrack;
  31033. }
  31034. }
  31035. }
  31036. return null;
  31037. }
  31038. createCaptionsTrack(trackName) {
  31039. if (this.config.renderTextTracksNatively) {
  31040. this.createNativeTrack(trackName);
  31041. } else {
  31042. this.createNonNativeTrack(trackName);
  31043. }
  31044. }
  31045. createNativeTrack(trackName) {
  31046. if (this.captionsTracks[trackName]) {
  31047. return;
  31048. }
  31049. const {
  31050. captionsProperties,
  31051. captionsTracks,
  31052. media
  31053. } = this;
  31054. const {
  31055. label,
  31056. languageCode
  31057. } = captionsProperties[trackName];
  31058. const existingTrack = this.getExistingTrack(label, languageCode);
  31059. if (!existingTrack) {
  31060. const textTrack = this.createTextTrack("captions", label, languageCode);
  31061. if (textTrack) {
  31062. textTrack[trackName] = true;
  31063. captionsTracks[trackName] = textTrack;
  31064. }
  31065. } else {
  31066. captionsTracks[trackName] = existingTrack;
  31067. clearCurrentCues(captionsTracks[trackName]);
  31068. sendAddTrackEvent(captionsTracks[trackName], media);
  31069. }
  31070. }
  31071. createNonNativeTrack(trackName) {
  31072. if (this.nonNativeCaptionsTracks[trackName]) {
  31073. return;
  31074. }
  31075. const trackProperties = this.captionsProperties[trackName];
  31076. if (!trackProperties) {
  31077. return;
  31078. }
  31079. const label = trackProperties.label;
  31080. const track = {
  31081. _id: trackName,
  31082. label,
  31083. kind: "captions",
  31084. default: trackProperties.media ? !!trackProperties.media.default : false,
  31085. closedCaptions: trackProperties.media
  31086. };
  31087. this.nonNativeCaptionsTracks[trackName] = track;
  31088. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  31089. tracks: [track]
  31090. });
  31091. }
  31092. createTextTrack(kind, label, lang) {
  31093. const media = this.media;
  31094. if (!media) {
  31095. return;
  31096. }
  31097. return media.addTextTrack(kind, label, lang);
  31098. }
  31099. onMediaAttaching(event, data) {
  31100. this.media = data.media;
  31101. if (!data.mediaSource) {
  31102. this._cleanTracks();
  31103. }
  31104. }
  31105. onMediaDetaching(event, data) {
  31106. const transferringMedia = !!data.transferMedia;
  31107. this.media = null;
  31108. if (transferringMedia) {
  31109. return;
  31110. }
  31111. const {
  31112. captionsTracks
  31113. } = this;
  31114. Object.keys(captionsTracks).forEach((trackName) => {
  31115. clearCurrentCues(captionsTracks[trackName]);
  31116. delete captionsTracks[trackName];
  31117. });
  31118. this.nonNativeCaptionsTracks = {};
  31119. }
  31120. onManifestLoading() {
  31121. this.lastCc = -1;
  31122. this.lastSn = -1;
  31123. this.lastPartIndex = -1;
  31124. this.prevCC = -1;
  31125. this.vttCCs = newVTTCCs();
  31126. this._cleanTracks();
  31127. this.tracks = [];
  31128. this.captionsTracks = {};
  31129. this.nonNativeCaptionsTracks = {};
  31130. this.textTracks = [];
  31131. this.unparsedVttFrags = [];
  31132. this.initPTS = [];
  31133. if (this.cea608Parser1 && this.cea608Parser2) {
  31134. this.cea608Parser1.reset();
  31135. this.cea608Parser2.reset();
  31136. }
  31137. }
  31138. _cleanTracks() {
  31139. const {
  31140. media
  31141. } = this;
  31142. if (!media) {
  31143. return;
  31144. }
  31145. const textTracks = media.textTracks;
  31146. if (textTracks) {
  31147. for (let i2 = 0; i2 < textTracks.length; i2++) {
  31148. clearCurrentCues(textTracks[i2]);
  31149. }
  31150. }
  31151. }
  31152. onSubtitleTracksUpdated(event, data) {
  31153. const tracks = data.subtitleTracks || [];
  31154. const hasIMSC1 = tracks.some((track) => track.textCodec === IMSC1_CODEC);
  31155. if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
  31156. const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);
  31157. if (listIsIdentical) {
  31158. this.tracks = tracks;
  31159. return;
  31160. }
  31161. this.textTracks = [];
  31162. this.tracks = tracks;
  31163. if (this.config.renderTextTracksNatively) {
  31164. const media = this.media;
  31165. const inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null;
  31166. this.tracks.forEach((track, index2) => {
  31167. let textTrack;
  31168. if (inUseTracks) {
  31169. let inUseTrack = null;
  31170. for (let i2 = 0; i2 < inUseTracks.length; i2++) {
  31171. if (inUseTracks[i2] && canReuseVttTextTrack(inUseTracks[i2], track)) {
  31172. inUseTrack = inUseTracks[i2];
  31173. inUseTracks[i2] = null;
  31174. break;
  31175. }
  31176. }
  31177. if (inUseTrack) {
  31178. textTrack = inUseTrack;
  31179. }
  31180. }
  31181. if (textTrack) {
  31182. clearCurrentCues(textTrack);
  31183. } else {
  31184. const textTrackKind = captionsOrSubtitlesFromCharacteristics(track);
  31185. textTrack = this.createTextTrack(textTrackKind, track.name, track.lang);
  31186. if (textTrack) {
  31187. textTrack.mode = "disabled";
  31188. }
  31189. }
  31190. if (textTrack) {
  31191. this.textTracks.push(textTrack);
  31192. }
  31193. });
  31194. if (inUseTracks != null && inUseTracks.length) {
  31195. const unusedTextTracks = inUseTracks.filter((t2) => t2 !== null).map((t2) => t2.label);
  31196. if (unusedTextTracks.length) {
  31197. this.hls.logger.warn(`Media element contains unused subtitle tracks: ${unusedTextTracks.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);
  31198. }
  31199. }
  31200. } else if (this.tracks.length) {
  31201. const tracksList = this.tracks.map((track) => {
  31202. return {
  31203. label: track.name,
  31204. kind: track.type.toLowerCase(),
  31205. default: track.default,
  31206. subtitleTrack: track
  31207. };
  31208. });
  31209. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  31210. tracks: tracksList
  31211. });
  31212. }
  31213. }
  31214. }
  31215. onManifestLoaded(event, data) {
  31216. if (this.config.enableCEA708Captions && data.captions) {
  31217. data.captions.forEach((captionsTrack) => {
  31218. const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
  31219. if (!instreamIdMatch) {
  31220. return;
  31221. }
  31222. const trackName = `textTrack${instreamIdMatch[1]}`;
  31223. const trackProperties = this.captionsProperties[trackName];
  31224. if (!trackProperties) {
  31225. return;
  31226. }
  31227. trackProperties.label = captionsTrack.name;
  31228. if (captionsTrack.lang) {
  31229. trackProperties.languageCode = captionsTrack.lang;
  31230. }
  31231. trackProperties.media = captionsTrack;
  31232. });
  31233. }
  31234. }
  31235. closedCaptionsForLevel(frag) {
  31236. const level = this.hls.levels[frag.level];
  31237. return level == null ? void 0 : level.attrs["CLOSED-CAPTIONS"];
  31238. }
  31239. onFragLoading(event, data) {
  31240. if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {
  31241. var _data$part$index, _data$part;
  31242. const {
  31243. cea608Parser1,
  31244. cea608Parser2,
  31245. lastSn
  31246. } = this;
  31247. const {
  31248. cc,
  31249. sn
  31250. } = data.frag;
  31251. const partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1;
  31252. if (cea608Parser1 && cea608Parser2) {
  31253. if (sn !== lastSn + 1 || sn === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) {
  31254. cea608Parser1.reset();
  31255. cea608Parser2.reset();
  31256. }
  31257. }
  31258. this.lastCc = cc;
  31259. this.lastSn = sn;
  31260. this.lastPartIndex = partIndex;
  31261. }
  31262. }
  31263. onFragLoaded(event, data) {
  31264. const {
  31265. frag,
  31266. payload
  31267. } = data;
  31268. if (frag.type === PlaylistLevelType.SUBTITLE) {
  31269. if (payload.byteLength) {
  31270. const decryptData = frag.decryptdata;
  31271. const decrypted = "stats" in data;
  31272. if (decryptData == null || !decryptData.encrypted || decrypted) {
  31273. const trackPlaylistMedia = this.tracks[frag.level];
  31274. const vttCCs = this.vttCCs;
  31275. if (!vttCCs[frag.cc]) {
  31276. vttCCs[frag.cc] = {
  31277. start: frag.start,
  31278. prevCC: this.prevCC,
  31279. new: true
  31280. };
  31281. this.prevCC = frag.cc;
  31282. }
  31283. if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) {
  31284. this._parseIMSC1(frag, payload);
  31285. } else {
  31286. this._parseVTTs(data);
  31287. }
  31288. }
  31289. } else {
  31290. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  31291. success: false,
  31292. frag,
  31293. error: new Error("Empty subtitle payload")
  31294. });
  31295. }
  31296. }
  31297. }
  31298. _parseIMSC1(frag, payload) {
  31299. const hls = this.hls;
  31300. parseIMSC1(payload, this.initPTS[frag.cc], (cues) => {
  31301. this._appendCues(cues, frag.level);
  31302. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  31303. success: true,
  31304. frag
  31305. });
  31306. }, (error2) => {
  31307. hls.logger.log(`Failed to parse IMSC1: ${error2}`);
  31308. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  31309. success: false,
  31310. frag,
  31311. error: error2
  31312. });
  31313. });
  31314. }
  31315. _parseVTTs(data) {
  31316. var _frag$initSegment;
  31317. const {
  31318. frag,
  31319. payload
  31320. } = data;
  31321. const {
  31322. initPTS,
  31323. unparsedVttFrags
  31324. } = this;
  31325. const maxAvCC = initPTS.length - 1;
  31326. if (!initPTS[frag.cc] && maxAvCC === -1) {
  31327. unparsedVttFrags.push(data);
  31328. return;
  31329. }
  31330. const hls = this.hls;
  31331. const payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)).buffer : payload;
  31332. parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, (cues) => {
  31333. this._appendCues(cues, frag.level);
  31334. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  31335. success: true,
  31336. frag
  31337. });
  31338. }, (error2) => {
  31339. const missingInitPTS = error2.message === "Missing initPTS for VTT MPEGTS";
  31340. if (missingInitPTS) {
  31341. unparsedVttFrags.push(data);
  31342. } else {
  31343. this._fallbackToIMSC1(frag, payload);
  31344. }
  31345. hls.logger.log(`Failed to parse VTT cue: ${error2}`);
  31346. if (missingInitPTS && maxAvCC > frag.cc) {
  31347. return;
  31348. }
  31349. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  31350. success: false,
  31351. frag,
  31352. error: error2
  31353. });
  31354. });
  31355. }
  31356. _fallbackToIMSC1(frag, payload) {
  31357. const trackPlaylistMedia = this.tracks[frag.level];
  31358. if (!trackPlaylistMedia.textCodec) {
  31359. parseIMSC1(payload, this.initPTS[frag.cc], () => {
  31360. trackPlaylistMedia.textCodec = IMSC1_CODEC;
  31361. this._parseIMSC1(frag, payload);
  31362. }, () => {
  31363. trackPlaylistMedia.textCodec = "wvtt";
  31364. });
  31365. }
  31366. }
  31367. _appendCues(cues, fragLevel) {
  31368. const hls = this.hls;
  31369. if (this.config.renderTextTracksNatively) {
  31370. const textTrack = this.textTracks[fragLevel];
  31371. if (!textTrack || textTrack.mode === "disabled") {
  31372. return;
  31373. }
  31374. cues.forEach((cue) => addCueToTrack(textTrack, cue));
  31375. } else {
  31376. const currentTrack = this.tracks[fragLevel];
  31377. if (!currentTrack) {
  31378. return;
  31379. }
  31380. const track = currentTrack.default ? "default" : "subtitles" + fragLevel;
  31381. hls.trigger(Events.CUES_PARSED, {
  31382. type: "subtitles",
  31383. cues,
  31384. track
  31385. });
  31386. }
  31387. }
  31388. onFragDecrypted(event, data) {
  31389. const {
  31390. frag
  31391. } = data;
  31392. if (frag.type === PlaylistLevelType.SUBTITLE) {
  31393. this.onFragLoaded(Events.FRAG_LOADED, data);
  31394. }
  31395. }
  31396. onSubtitleTracksCleared() {
  31397. this.tracks = [];
  31398. this.captionsTracks = {};
  31399. }
  31400. onFragParsingUserdata(event, data) {
  31401. if (!this.enabled || !this.config.enableCEA708Captions) {
  31402. return;
  31403. }
  31404. const {
  31405. frag,
  31406. samples
  31407. } = data;
  31408. if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === "NONE") {
  31409. return;
  31410. }
  31411. for (let i2 = 0; i2 < samples.length; i2++) {
  31412. const ccBytes = samples[i2].bytes;
  31413. if (ccBytes) {
  31414. if (!this.cea608Parser1) {
  31415. this.initCea608Parsers();
  31416. }
  31417. const ccdatas = this.extractCea608Data(ccBytes);
  31418. this.cea608Parser1.addData(samples[i2].pts, ccdatas[0]);
  31419. this.cea608Parser2.addData(samples[i2].pts, ccdatas[1]);
  31420. }
  31421. }
  31422. }
  31423. onBufferFlushing(event, {
  31424. startOffset,
  31425. endOffset,
  31426. endOffsetSubtitles,
  31427. type
  31428. }) {
  31429. const {
  31430. media
  31431. } = this;
  31432. if (!media || media.currentTime < endOffset) {
  31433. return;
  31434. }
  31435. if (!type || type === "video") {
  31436. const {
  31437. captionsTracks
  31438. } = this;
  31439. Object.keys(captionsTracks).forEach((trackName) => removeCuesInRange(captionsTracks[trackName], startOffset, endOffset));
  31440. }
  31441. if (this.config.renderTextTracksNatively) {
  31442. if (startOffset === 0 && endOffsetSubtitles !== void 0) {
  31443. const {
  31444. textTracks
  31445. } = this;
  31446. Object.keys(textTracks).forEach((trackName) => removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles));
  31447. }
  31448. }
  31449. }
  31450. extractCea608Data(byteArray) {
  31451. const actualCCBytes = [[], []];
  31452. const count = byteArray[0] & 31;
  31453. let position = 2;
  31454. for (let j2 = 0; j2 < count; j2++) {
  31455. const tmpByte = byteArray[position++];
  31456. const ccbyte1 = 127 & byteArray[position++];
  31457. const ccbyte2 = 127 & byteArray[position++];
  31458. if (ccbyte1 === 0 && ccbyte2 === 0) {
  31459. continue;
  31460. }
  31461. const ccValid = (4 & tmpByte) !== 0;
  31462. if (ccValid) {
  31463. const ccType = 3 & tmpByte;
  31464. if (0 === ccType || 1 === ccType) {
  31465. actualCCBytes[ccType].push(ccbyte1);
  31466. actualCCBytes[ccType].push(ccbyte2);
  31467. }
  31468. }
  31469. }
  31470. return actualCCBytes;
  31471. }
  31472. }
  31473. function captionsOrSubtitlesFromCharacteristics(track) {
  31474. if (track.characteristics) {
  31475. if (/transcribes-spoken-dialog/gi.test(track.characteristics) && /describes-music-and-sound/gi.test(track.characteristics)) {
  31476. return "captions";
  31477. }
  31478. }
  31479. return "subtitles";
  31480. }
  31481. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  31482. return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack);
  31483. }
  31484. function intersection(x1, x2, y1, y2) {
  31485. return Math.min(x2, y2) - Math.max(x1, y1);
  31486. }
  31487. function newVTTCCs() {
  31488. return {
  31489. ccOffset: 0,
  31490. presentationOffset: 0,
  31491. 0: {
  31492. start: 0,
  31493. prevCC: -1,
  31494. new: true
  31495. }
  31496. };
  31497. }
  31498. const WHITESPACE_CHAR = /\s/;
  31499. const Cues = {
  31500. newCue(track, startTime, endTime, captionScreen) {
  31501. const result = [];
  31502. let row;
  31503. let cue;
  31504. let indenting;
  31505. let indent;
  31506. let text;
  31507. const Cue = self.VTTCue || self.TextTrackCue;
  31508. for (let r2 = 0; r2 < captionScreen.rows.length; r2++) {
  31509. row = captionScreen.rows[r2];
  31510. indenting = true;
  31511. indent = 0;
  31512. text = "";
  31513. if (!row.isEmpty()) {
  31514. var _track$cues;
  31515. for (let c2 = 0; c2 < row.chars.length; c2++) {
  31516. if (WHITESPACE_CHAR.test(row.chars[c2].uchar) && indenting) {
  31517. indent++;
  31518. } else {
  31519. text += row.chars[c2].uchar;
  31520. indenting = false;
  31521. }
  31522. }
  31523. row.cueStartTime = startTime;
  31524. if (startTime === endTime) {
  31525. endTime += 1e-4;
  31526. }
  31527. if (indent >= 16) {
  31528. indent--;
  31529. } else {
  31530. indent++;
  31531. }
  31532. const cueText = fixLineBreaks(text.trim());
  31533. const id = generateCueId(startTime, endTime, cueText);
  31534. if (!(track != null && (_track$cues = track.cues) != null && _track$cues.getCueById(id))) {
  31535. cue = new Cue(startTime, endTime, cueText);
  31536. cue.id = id;
  31537. cue.line = r2 + 1;
  31538. cue.align = "left";
  31539. cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
  31540. result.push(cue);
  31541. }
  31542. }
  31543. }
  31544. if (track && result.length) {
  31545. result.sort((cueA, cueB) => {
  31546. if (cueA.line === "auto" || cueB.line === "auto") {
  31547. return 0;
  31548. }
  31549. if (cueA.line > 8 && cueB.line > 8) {
  31550. return cueB.line - cueA.line;
  31551. }
  31552. return cueA.line - cueB.line;
  31553. });
  31554. result.forEach((cue2) => addCueToTrack(track, cue2));
  31555. }
  31556. return result;
  31557. }
  31558. };
  31559. function fetchSupported() {
  31560. if (
  31561. // @ts-ignore
  31562. self.fetch && self.AbortController && self.ReadableStream && self.Request
  31563. ) {
  31564. try {
  31565. new self.ReadableStream({});
  31566. return true;
  31567. } catch (e2) {
  31568. }
  31569. }
  31570. return false;
  31571. }
  31572. const BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  31573. class FetchLoader {
  31574. constructor(config2) {
  31575. this.fetchSetup = void 0;
  31576. this.requestTimeout = void 0;
  31577. this.request = null;
  31578. this.response = null;
  31579. this.controller = void 0;
  31580. this.context = null;
  31581. this.config = null;
  31582. this.callbacks = null;
  31583. this.stats = void 0;
  31584. this.loader = null;
  31585. this.fetchSetup = config2.fetchSetup || getRequest;
  31586. this.controller = new self.AbortController();
  31587. this.stats = new LoadStats();
  31588. }
  31589. destroy() {
  31590. this.loader = this.callbacks = this.context = this.config = this.request = null;
  31591. this.abortInternal();
  31592. this.response = null;
  31593. this.fetchSetup = this.controller = this.stats = null;
  31594. }
  31595. abortInternal() {
  31596. if (this.controller && !this.stats.loading.end) {
  31597. this.stats.aborted = true;
  31598. this.controller.abort();
  31599. }
  31600. }
  31601. abort() {
  31602. var _this$callbacks;
  31603. this.abortInternal();
  31604. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  31605. this.callbacks.onAbort(this.stats, this.context, this.response);
  31606. }
  31607. }
  31608. load(context, config2, callbacks) {
  31609. const stats = this.stats;
  31610. if (stats.loading.start) {
  31611. throw new Error("Loader can only be used once.");
  31612. }
  31613. stats.loading.start = self.performance.now();
  31614. const initParams = getRequestParameters(context, this.controller.signal);
  31615. const isArrayBuffer = context.responseType === "arraybuffer";
  31616. const LENGTH = isArrayBuffer ? "byteLength" : "length";
  31617. const {
  31618. maxTimeToFirstByteMs,
  31619. maxLoadTimeMs
  31620. } = config2.loadPolicy;
  31621. this.context = context;
  31622. this.config = config2;
  31623. this.callbacks = callbacks;
  31624. this.request = this.fetchSetup(context, initParams);
  31625. self.clearTimeout(this.requestTimeout);
  31626. config2.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  31627. this.requestTimeout = self.setTimeout(() => {
  31628. if (this.callbacks) {
  31629. this.abortInternal();
  31630. this.callbacks.onTimeout(stats, context, this.response);
  31631. }
  31632. }, config2.timeout);
  31633. const fetchPromise = isPromise$1(this.request) ? this.request.then(self.fetch) : self.fetch(this.request);
  31634. fetchPromise.then((response) => {
  31635. var _this$callbacks2;
  31636. this.response = this.loader = response;
  31637. const first = Math.max(self.performance.now(), stats.loading.start);
  31638. self.clearTimeout(this.requestTimeout);
  31639. config2.timeout = maxLoadTimeMs;
  31640. this.requestTimeout = self.setTimeout(() => {
  31641. if (this.callbacks) {
  31642. this.abortInternal();
  31643. this.callbacks.onTimeout(stats, context, this.response);
  31644. }
  31645. }, maxLoadTimeMs - (first - stats.loading.start));
  31646. if (!response.ok) {
  31647. const {
  31648. status: status2,
  31649. statusText
  31650. } = response;
  31651. throw new FetchError(statusText || "fetch, bad network response", status2, response);
  31652. }
  31653. stats.loading.first = first;
  31654. stats.total = getContentLength(response.headers) || stats.total;
  31655. const onProgress = (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onProgress;
  31656. if (onProgress && isFiniteNumber(config2.highWaterMark)) {
  31657. return this.loadProgressively(response, stats, context, config2.highWaterMark, onProgress);
  31658. }
  31659. if (isArrayBuffer) {
  31660. return response.arrayBuffer();
  31661. }
  31662. if (context.responseType === "json") {
  31663. return response.json();
  31664. }
  31665. return response.text();
  31666. }).then((responseData) => {
  31667. var _this$callbacks3, _this$callbacks4;
  31668. const response = this.response;
  31669. if (!response) {
  31670. throw new Error("loader destroyed");
  31671. }
  31672. self.clearTimeout(this.requestTimeout);
  31673. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  31674. const total = responseData[LENGTH];
  31675. if (total) {
  31676. stats.loaded = stats.total = total;
  31677. }
  31678. const loaderResponse = {
  31679. url: response.url,
  31680. data: responseData,
  31681. code: response.status
  31682. };
  31683. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  31684. if (onProgress && !isFiniteNumber(config2.highWaterMark)) {
  31685. onProgress(stats, context, responseData, response);
  31686. }
  31687. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(loaderResponse, stats, context, response);
  31688. }).catch((error2) => {
  31689. var _this$callbacks5;
  31690. self.clearTimeout(this.requestTimeout);
  31691. if (stats.aborted) {
  31692. return;
  31693. }
  31694. const code2 = !error2 ? 0 : error2.code || 0;
  31695. const text = !error2 ? null : error2.message;
  31696. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  31697. code: code2,
  31698. text
  31699. }, context, error2 ? error2.details : null, stats);
  31700. });
  31701. }
  31702. getCacheAge() {
  31703. let result = null;
  31704. if (this.response) {
  31705. const ageHeader = this.response.headers.get("age");
  31706. result = ageHeader ? parseFloat(ageHeader) : null;
  31707. }
  31708. return result;
  31709. }
  31710. getResponseHeader(name) {
  31711. return this.response ? this.response.headers.get(name) : null;
  31712. }
  31713. loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {
  31714. const chunkCache = new ChunkCache();
  31715. const reader = response.body.getReader();
  31716. const pump = () => {
  31717. return reader.read().then((data) => {
  31718. if (data.done) {
  31719. if (chunkCache.dataLength) {
  31720. onProgress(stats, context, chunkCache.flush().buffer, response);
  31721. }
  31722. return Promise.resolve(new ArrayBuffer(0));
  31723. }
  31724. const chunk = data.value;
  31725. const len = chunk.length;
  31726. stats.loaded += len;
  31727. if (len < highWaterMark || chunkCache.dataLength) {
  31728. chunkCache.push(chunk);
  31729. if (chunkCache.dataLength >= highWaterMark) {
  31730. onProgress(stats, context, chunkCache.flush().buffer, response);
  31731. }
  31732. } else {
  31733. onProgress(stats, context, chunk.buffer, response);
  31734. }
  31735. return pump();
  31736. }).catch(() => {
  31737. return Promise.reject();
  31738. });
  31739. };
  31740. return pump();
  31741. }
  31742. }
  31743. function getRequestParameters(context, signal) {
  31744. const initParams = {
  31745. method: "GET",
  31746. mode: "cors",
  31747. credentials: "same-origin",
  31748. signal,
  31749. headers: new self.Headers(_extends({}, context.headers))
  31750. };
  31751. if (context.rangeEnd) {
  31752. initParams.headers.set("Range", "bytes=" + context.rangeStart + "-" + String(context.rangeEnd - 1));
  31753. }
  31754. return initParams;
  31755. }
  31756. function getByteRangeLength(byteRangeHeader) {
  31757. const result = BYTERANGE.exec(byteRangeHeader);
  31758. if (result) {
  31759. return parseInt(result[2]) - parseInt(result[1]) + 1;
  31760. }
  31761. }
  31762. function getContentLength(headers) {
  31763. const contentRange = headers.get("Content-Range");
  31764. if (contentRange) {
  31765. const byteRangeLength = getByteRangeLength(contentRange);
  31766. if (isFiniteNumber(byteRangeLength)) {
  31767. return byteRangeLength;
  31768. }
  31769. }
  31770. const contentLength = headers.get("Content-Length");
  31771. if (contentLength) {
  31772. return parseInt(contentLength);
  31773. }
  31774. }
  31775. function getRequest(context, initParams) {
  31776. return new self.Request(context.url, initParams);
  31777. }
  31778. class FetchError extends Error {
  31779. constructor(message, code2, details) {
  31780. super(message);
  31781. this.code = void 0;
  31782. this.details = void 0;
  31783. this.code = code2;
  31784. this.details = details;
  31785. }
  31786. }
  31787. const AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  31788. class XhrLoader {
  31789. constructor(config2) {
  31790. this.xhrSetup = void 0;
  31791. this.requestTimeout = void 0;
  31792. this.retryTimeout = void 0;
  31793. this.retryDelay = void 0;
  31794. this.config = null;
  31795. this.callbacks = null;
  31796. this.context = null;
  31797. this.loader = null;
  31798. this.stats = void 0;
  31799. this.xhrSetup = config2 ? config2.xhrSetup || null : null;
  31800. this.stats = new LoadStats();
  31801. this.retryDelay = 0;
  31802. }
  31803. destroy() {
  31804. this.callbacks = null;
  31805. this.abortInternal();
  31806. this.loader = null;
  31807. this.config = null;
  31808. this.context = null;
  31809. this.xhrSetup = null;
  31810. }
  31811. abortInternal() {
  31812. const loader = this.loader;
  31813. self.clearTimeout(this.requestTimeout);
  31814. self.clearTimeout(this.retryTimeout);
  31815. if (loader) {
  31816. loader.onreadystatechange = null;
  31817. loader.onprogress = null;
  31818. if (loader.readyState !== 4) {
  31819. this.stats.aborted = true;
  31820. loader.abort();
  31821. }
  31822. }
  31823. }
  31824. abort() {
  31825. var _this$callbacks;
  31826. this.abortInternal();
  31827. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  31828. this.callbacks.onAbort(this.stats, this.context, this.loader);
  31829. }
  31830. }
  31831. load(context, config2, callbacks) {
  31832. if (this.stats.loading.start) {
  31833. throw new Error("Loader can only be used once.");
  31834. }
  31835. this.stats.loading.start = self.performance.now();
  31836. this.context = context;
  31837. this.config = config2;
  31838. this.callbacks = callbacks;
  31839. this.loadInternal();
  31840. }
  31841. loadInternal() {
  31842. const {
  31843. config: config2,
  31844. context
  31845. } = this;
  31846. if (!config2 || !context) {
  31847. return;
  31848. }
  31849. const xhr = this.loader = new self.XMLHttpRequest();
  31850. const stats = this.stats;
  31851. stats.loading.first = 0;
  31852. stats.loaded = 0;
  31853. stats.aborted = false;
  31854. const xhrSetup = this.xhrSetup;
  31855. if (xhrSetup) {
  31856. Promise.resolve().then(() => {
  31857. if (this.loader !== xhr || this.stats.aborted)
  31858. return;
  31859. return xhrSetup(xhr, context.url);
  31860. }).catch((error2) => {
  31861. if (this.loader !== xhr || this.stats.aborted)
  31862. return;
  31863. xhr.open("GET", context.url, true);
  31864. return xhrSetup(xhr, context.url);
  31865. }).then(() => {
  31866. if (this.loader !== xhr || this.stats.aborted)
  31867. return;
  31868. this.openAndSendXhr(xhr, context, config2);
  31869. }).catch((error2) => {
  31870. var _this$callbacks2;
  31871. (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onError({
  31872. code: xhr.status,
  31873. text: error2.message
  31874. }, context, xhr, stats);
  31875. return;
  31876. });
  31877. } else {
  31878. this.openAndSendXhr(xhr, context, config2);
  31879. }
  31880. }
  31881. openAndSendXhr(xhr, context, config2) {
  31882. if (!xhr.readyState) {
  31883. xhr.open("GET", context.url, true);
  31884. }
  31885. const headers = context.headers;
  31886. const {
  31887. maxTimeToFirstByteMs,
  31888. maxLoadTimeMs
  31889. } = config2.loadPolicy;
  31890. if (headers) {
  31891. for (const header in headers) {
  31892. xhr.setRequestHeader(header, headers[header]);
  31893. }
  31894. }
  31895. if (context.rangeEnd) {
  31896. xhr.setRequestHeader("Range", "bytes=" + context.rangeStart + "-" + (context.rangeEnd - 1));
  31897. }
  31898. xhr.onreadystatechange = this.readystatechange.bind(this);
  31899. xhr.onprogress = this.loadprogress.bind(this);
  31900. xhr.responseType = context.responseType;
  31901. self.clearTimeout(this.requestTimeout);
  31902. config2.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  31903. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config2.timeout);
  31904. xhr.send();
  31905. }
  31906. readystatechange() {
  31907. const {
  31908. context,
  31909. loader: xhr,
  31910. stats
  31911. } = this;
  31912. if (!context || !xhr) {
  31913. return;
  31914. }
  31915. const readyState = xhr.readyState;
  31916. const config2 = this.config;
  31917. if (stats.aborted) {
  31918. return;
  31919. }
  31920. if (readyState >= 2) {
  31921. if (stats.loading.first === 0) {
  31922. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  31923. if (config2.timeout !== config2.loadPolicy.maxLoadTimeMs) {
  31924. self.clearTimeout(this.requestTimeout);
  31925. config2.timeout = config2.loadPolicy.maxLoadTimeMs;
  31926. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config2.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  31927. }
  31928. }
  31929. if (readyState === 4) {
  31930. self.clearTimeout(this.requestTimeout);
  31931. xhr.onreadystatechange = null;
  31932. xhr.onprogress = null;
  31933. const status2 = xhr.status;
  31934. const useResponseText = xhr.responseType === "text" ? xhr.responseText : null;
  31935. if (status2 >= 200 && status2 < 300) {
  31936. const data = useResponseText != null ? useResponseText : xhr.response;
  31937. if (data != null) {
  31938. var _this$callbacks3, _this$callbacks4;
  31939. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  31940. const len = xhr.responseType === "arraybuffer" ? data.byteLength : data.length;
  31941. stats.loaded = stats.total = len;
  31942. stats.bwEstimate = stats.total * 8e3 / (stats.loading.end - stats.loading.first);
  31943. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  31944. if (onProgress) {
  31945. onProgress(stats, context, data, xhr);
  31946. }
  31947. const _response = {
  31948. url: xhr.responseURL,
  31949. data,
  31950. code: status2
  31951. };
  31952. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(_response, stats, context, xhr);
  31953. return;
  31954. }
  31955. }
  31956. const retryConfig = config2.loadPolicy.errorRetry;
  31957. const retryCount = stats.retry;
  31958. const response = {
  31959. url: context.url,
  31960. data: void 0,
  31961. code: status2
  31962. };
  31963. if (shouldRetry(retryConfig, retryCount, false, response)) {
  31964. this.retry(retryConfig);
  31965. } else {
  31966. var _this$callbacks5;
  31967. logger.error(`${status2} while loading ${context.url}`);
  31968. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  31969. code: status2,
  31970. text: xhr.statusText
  31971. }, context, xhr, stats);
  31972. }
  31973. }
  31974. }
  31975. }
  31976. loadtimeout() {
  31977. if (!this.config)
  31978. return;
  31979. const retryConfig = this.config.loadPolicy.timeoutRetry;
  31980. const retryCount = this.stats.retry;
  31981. if (shouldRetry(retryConfig, retryCount, true)) {
  31982. this.retry(retryConfig);
  31983. } else {
  31984. var _this$context;
  31985. logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);
  31986. const callbacks = this.callbacks;
  31987. if (callbacks) {
  31988. this.abortInternal();
  31989. callbacks.onTimeout(this.stats, this.context, this.loader);
  31990. }
  31991. }
  31992. }
  31993. retry(retryConfig) {
  31994. const {
  31995. context,
  31996. stats
  31997. } = this;
  31998. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  31999. stats.retry++;
  32000. logger.warn(`${status ? "HTTP Status " + status : "Timeout"} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`);
  32001. this.abortInternal();
  32002. this.loader = null;
  32003. self.clearTimeout(this.retryTimeout);
  32004. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  32005. }
  32006. loadprogress(event) {
  32007. const stats = this.stats;
  32008. stats.loaded = event.loaded;
  32009. if (event.lengthComputable) {
  32010. stats.total = event.total;
  32011. }
  32012. }
  32013. getCacheAge() {
  32014. let result = null;
  32015. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  32016. const ageHeader = this.loader.getResponseHeader("age");
  32017. result = ageHeader ? parseFloat(ageHeader) : null;
  32018. }
  32019. return result;
  32020. }
  32021. getResponseHeader(name) {
  32022. if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, "im").test(this.loader.getAllResponseHeaders())) {
  32023. return this.loader.getResponseHeader(name);
  32024. }
  32025. return null;
  32026. }
  32027. }
  32028. const defaultLoadPolicy = {
  32029. maxTimeToFirstByteMs: 8e3,
  32030. maxLoadTimeMs: 2e4,
  32031. timeoutRetry: null,
  32032. errorRetry: null
  32033. };
  32034. const hlsDefaultConfig = _objectSpread2(_objectSpread2({
  32035. autoStartLoad: true,
  32036. // used by stream-controller
  32037. startPosition: -1,
  32038. // used by stream-controller
  32039. defaultAudioCodec: void 0,
  32040. // used by stream-controller
  32041. debug: false,
  32042. // used by logger
  32043. capLevelOnFPSDrop: false,
  32044. // used by fps-controller
  32045. capLevelToPlayerSize: false,
  32046. // used by cap-level-controller
  32047. ignoreDevicePixelRatio: false,
  32048. // used by cap-level-controller
  32049. maxDevicePixelRatio: Number.POSITIVE_INFINITY,
  32050. // used by cap-level-controller
  32051. preferManagedMediaSource: true,
  32052. initialLiveManifestSize: 1,
  32053. // used by stream-controller
  32054. maxBufferLength: 30,
  32055. // used by stream-controller
  32056. backBufferLength: Infinity,
  32057. // used by buffer-controller
  32058. frontBufferFlushThreshold: Infinity,
  32059. startOnSegmentBoundary: false,
  32060. // used by stream-controller
  32061. maxBufferSize: 60 * 1e3 * 1e3,
  32062. // used by stream-controller
  32063. maxFragLookUpTolerance: 0.25,
  32064. // used by stream-controller
  32065. maxBufferHole: 0.1,
  32066. // used by stream-controller and gap-controller
  32067. detectStallWithCurrentTimeMs: 1250,
  32068. // used by gap-controller
  32069. highBufferWatchdogPeriod: 2,
  32070. // used by gap-controller
  32071. nudgeOffset: 0.1,
  32072. // used by gap-controller
  32073. nudgeMaxRetry: 3,
  32074. // used by gap-controller
  32075. nudgeOnVideoHole: true,
  32076. // used by gap-controller
  32077. liveSyncMode: "edge",
  32078. // used by stream-controller
  32079. liveSyncDurationCount: 3,
  32080. // used by latency-controller
  32081. liveSyncOnStallIncrease: 1,
  32082. // used by latency-controller
  32083. liveMaxLatencyDurationCount: Infinity,
  32084. // used by latency-controller
  32085. liveSyncDuration: void 0,
  32086. // used by latency-controller
  32087. liveMaxLatencyDuration: void 0,
  32088. // used by latency-controller
  32089. maxLiveSyncPlaybackRate: 1,
  32090. // used by latency-controller
  32091. liveDurationInfinity: false,
  32092. // used by buffer-controller
  32093. /**
  32094. * @deprecated use backBufferLength
  32095. */
  32096. liveBackBufferLength: null,
  32097. // used by buffer-controller
  32098. maxMaxBufferLength: 600,
  32099. // used by stream-controller
  32100. enableWorker: true,
  32101. // used by transmuxer
  32102. workerPath: null,
  32103. // used by transmuxer
  32104. enableSoftwareAES: true,
  32105. // used by decrypter
  32106. startLevel: void 0,
  32107. // used by level-controller
  32108. startFragPrefetch: false,
  32109. // used by stream-controller
  32110. fpsDroppedMonitoringPeriod: 5e3,
  32111. // used by fps-controller
  32112. fpsDroppedMonitoringThreshold: 0.2,
  32113. // used by fps-controller
  32114. appendErrorMaxRetry: 3,
  32115. // used by buffer-controller
  32116. ignorePlaylistParsingErrors: false,
  32117. loader: XhrLoader,
  32118. // loader: FetchLoader,
  32119. fLoader: void 0,
  32120. // used by fragment-loader
  32121. pLoader: void 0,
  32122. // used by playlist-loader
  32123. xhrSetup: void 0,
  32124. // used by xhr-loader
  32125. licenseXhrSetup: void 0,
  32126. // used by eme-controller
  32127. licenseResponseCallback: void 0,
  32128. // used by eme-controller
  32129. abrController: AbrController,
  32130. bufferController: BufferController,
  32131. capLevelController: CapLevelController,
  32132. errorController: ErrorController,
  32133. fpsController: FPSController,
  32134. stretchShortVideoTrack: false,
  32135. // used by mp4-remuxer
  32136. maxAudioFramesDrift: 1,
  32137. // used by mp4-remuxer
  32138. forceKeyFrameOnDiscontinuity: true,
  32139. // used by ts-demuxer
  32140. abrEwmaFastLive: 3,
  32141. // used by abr-controller
  32142. abrEwmaSlowLive: 9,
  32143. // used by abr-controller
  32144. abrEwmaFastVoD: 3,
  32145. // used by abr-controller
  32146. abrEwmaSlowVoD: 9,
  32147. // used by abr-controller
  32148. abrEwmaDefaultEstimate: 5e5,
  32149. // 500 kbps // used by abr-controller
  32150. abrEwmaDefaultEstimateMax: 5e6,
  32151. // 5 mbps
  32152. abrBandWidthFactor: 0.95,
  32153. // used by abr-controller
  32154. abrBandWidthUpFactor: 0.7,
  32155. // used by abr-controller
  32156. abrMaxWithRealBitrate: false,
  32157. // used by abr-controller
  32158. maxStarvationDelay: 4,
  32159. // used by abr-controller
  32160. maxLoadingDelay: 4,
  32161. // used by abr-controller
  32162. minAutoBitrate: 0,
  32163. // used by hls
  32164. emeEnabled: false,
  32165. // used by eme-controller
  32166. widevineLicenseUrl: void 0,
  32167. // used by eme-controller
  32168. drmSystems: {},
  32169. // used by eme-controller
  32170. drmSystemOptions: {},
  32171. // used by eme-controller
  32172. requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess,
  32173. // used by eme-controller
  32174. requireKeySystemAccessOnStart: false,
  32175. // used by eme-controller
  32176. testBandwidth: true,
  32177. progressive: false,
  32178. lowLatencyMode: true,
  32179. cmcd: void 0,
  32180. enableDateRangeMetadataCues: true,
  32181. enableEmsgMetadataCues: true,
  32182. enableEmsgKLVMetadata: false,
  32183. enableID3MetadataCues: true,
  32184. enableInterstitialPlayback: true,
  32185. interstitialAppendInPlace: true,
  32186. interstitialLiveLookAhead: 10,
  32187. useMediaCapabilities: true,
  32188. preserveManualLevelOnError: false,
  32189. certLoadPolicy: {
  32190. default: defaultLoadPolicy
  32191. },
  32192. keyLoadPolicy: {
  32193. default: {
  32194. maxTimeToFirstByteMs: 8e3,
  32195. maxLoadTimeMs: 2e4,
  32196. timeoutRetry: {
  32197. maxNumRetry: 1,
  32198. retryDelayMs: 1e3,
  32199. maxRetryDelayMs: 2e4,
  32200. backoff: "linear"
  32201. },
  32202. errorRetry: {
  32203. maxNumRetry: 8,
  32204. retryDelayMs: 1e3,
  32205. maxRetryDelayMs: 2e4,
  32206. backoff: "linear"
  32207. }
  32208. }
  32209. },
  32210. manifestLoadPolicy: {
  32211. default: {
  32212. maxTimeToFirstByteMs: Infinity,
  32213. maxLoadTimeMs: 2e4,
  32214. timeoutRetry: {
  32215. maxNumRetry: 2,
  32216. retryDelayMs: 0,
  32217. maxRetryDelayMs: 0
  32218. },
  32219. errorRetry: {
  32220. maxNumRetry: 1,
  32221. retryDelayMs: 1e3,
  32222. maxRetryDelayMs: 8e3
  32223. }
  32224. }
  32225. },
  32226. playlistLoadPolicy: {
  32227. default: {
  32228. maxTimeToFirstByteMs: 1e4,
  32229. maxLoadTimeMs: 2e4,
  32230. timeoutRetry: {
  32231. maxNumRetry: 2,
  32232. retryDelayMs: 0,
  32233. maxRetryDelayMs: 0
  32234. },
  32235. errorRetry: {
  32236. maxNumRetry: 2,
  32237. retryDelayMs: 1e3,
  32238. maxRetryDelayMs: 8e3
  32239. }
  32240. }
  32241. },
  32242. fragLoadPolicy: {
  32243. default: {
  32244. maxTimeToFirstByteMs: 1e4,
  32245. maxLoadTimeMs: 12e4,
  32246. timeoutRetry: {
  32247. maxNumRetry: 4,
  32248. retryDelayMs: 0,
  32249. maxRetryDelayMs: 0
  32250. },
  32251. errorRetry: {
  32252. maxNumRetry: 6,
  32253. retryDelayMs: 1e3,
  32254. maxRetryDelayMs: 8e3
  32255. }
  32256. }
  32257. },
  32258. steeringManifestLoadPolicy: {
  32259. default: {
  32260. maxTimeToFirstByteMs: 1e4,
  32261. maxLoadTimeMs: 2e4,
  32262. timeoutRetry: {
  32263. maxNumRetry: 2,
  32264. retryDelayMs: 0,
  32265. maxRetryDelayMs: 0
  32266. },
  32267. errorRetry: {
  32268. maxNumRetry: 1,
  32269. retryDelayMs: 1e3,
  32270. maxRetryDelayMs: 8e3
  32271. }
  32272. }
  32273. },
  32274. interstitialAssetListLoadPolicy: {
  32275. default: {
  32276. maxTimeToFirstByteMs: 1e4,
  32277. maxLoadTimeMs: 3e4,
  32278. timeoutRetry: {
  32279. maxNumRetry: 0,
  32280. retryDelayMs: 0,
  32281. maxRetryDelayMs: 0
  32282. },
  32283. errorRetry: {
  32284. maxNumRetry: 0,
  32285. retryDelayMs: 1e3,
  32286. maxRetryDelayMs: 8e3
  32287. }
  32288. }
  32289. },
  32290. // These default settings are deprecated in favor of the above policies
  32291. // and are maintained for backwards compatibility
  32292. manifestLoadingTimeOut: 1e4,
  32293. manifestLoadingMaxRetry: 1,
  32294. manifestLoadingRetryDelay: 1e3,
  32295. manifestLoadingMaxRetryTimeout: 64e3,
  32296. levelLoadingTimeOut: 1e4,
  32297. levelLoadingMaxRetry: 4,
  32298. levelLoadingRetryDelay: 1e3,
  32299. levelLoadingMaxRetryTimeout: 64e3,
  32300. fragLoadingTimeOut: 2e4,
  32301. fragLoadingMaxRetry: 6,
  32302. fragLoadingRetryDelay: 1e3,
  32303. fragLoadingMaxRetryTimeout: 64e3
  32304. }, timelineConfig()), {}, {
  32305. subtitleStreamController: SubtitleStreamController,
  32306. subtitleTrackController: SubtitleTrackController,
  32307. timelineController: TimelineController,
  32308. audioStreamController: AudioStreamController,
  32309. audioTrackController: AudioTrackController,
  32310. emeController: EMEController,
  32311. cmcdController: CMCDController,
  32312. contentSteeringController: ContentSteeringController,
  32313. interstitialsController: InterstitialsController
  32314. });
  32315. function timelineConfig() {
  32316. return {
  32317. cueHandler: Cues,
  32318. // used by timeline-controller
  32319. enableWebVTT: true,
  32320. // used by timeline-controller
  32321. enableIMSC1: true,
  32322. // used by timeline-controller
  32323. enableCEA708Captions: true,
  32324. // used by timeline-controller
  32325. captionsTextTrack1Label: "English",
  32326. // used by timeline-controller
  32327. captionsTextTrack1LanguageCode: "en",
  32328. // used by timeline-controller
  32329. captionsTextTrack2Label: "Spanish",
  32330. // used by timeline-controller
  32331. captionsTextTrack2LanguageCode: "es",
  32332. // used by timeline-controller
  32333. captionsTextTrack3Label: "Unknown CC",
  32334. // used by timeline-controller
  32335. captionsTextTrack3LanguageCode: "",
  32336. // used by timeline-controller
  32337. captionsTextTrack4Label: "Unknown CC",
  32338. // used by timeline-controller
  32339. captionsTextTrack4LanguageCode: "",
  32340. // used by timeline-controller
  32341. renderTextTracksNatively: true
  32342. };
  32343. }
  32344. function mergeConfig$3(defaultConfig2, userConfig, logger2) {
  32345. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  32346. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  32347. }
  32348. if (userConfig.liveMaxLatencyDurationCount !== void 0 && (userConfig.liveSyncDurationCount === void 0 || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  32349. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  32350. }
  32351. if (userConfig.liveMaxLatencyDuration !== void 0 && (userConfig.liveSyncDuration === void 0 || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  32352. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  32353. }
  32354. const defaultsCopy = deepCpy(defaultConfig2);
  32355. const deprecatedSettingTypes = ["manifest", "level", "frag"];
  32356. const deprecatedSettings = ["TimeOut", "MaxRetry", "RetryDelay", "MaxRetryTimeout"];
  32357. deprecatedSettingTypes.forEach((type) => {
  32358. const policyName = `${type === "level" ? "playlist" : type}LoadPolicy`;
  32359. const policyNotSet = userConfig[policyName] === void 0;
  32360. const report = [];
  32361. deprecatedSettings.forEach((setting) => {
  32362. const deprecatedSetting = `${type}Loading${setting}`;
  32363. const value2 = userConfig[deprecatedSetting];
  32364. if (value2 !== void 0 && policyNotSet) {
  32365. report.push(deprecatedSetting);
  32366. const settings = defaultsCopy[policyName].default;
  32367. userConfig[policyName] = {
  32368. default: settings
  32369. };
  32370. switch (setting) {
  32371. case "TimeOut":
  32372. settings.maxLoadTimeMs = value2;
  32373. settings.maxTimeToFirstByteMs = value2;
  32374. break;
  32375. case "MaxRetry":
  32376. settings.errorRetry.maxNumRetry = value2;
  32377. settings.timeoutRetry.maxNumRetry = value2;
  32378. break;
  32379. case "RetryDelay":
  32380. settings.errorRetry.retryDelayMs = value2;
  32381. settings.timeoutRetry.retryDelayMs = value2;
  32382. break;
  32383. case "MaxRetryTimeout":
  32384. settings.errorRetry.maxRetryDelayMs = value2;
  32385. settings.timeoutRetry.maxRetryDelayMs = value2;
  32386. break;
  32387. }
  32388. }
  32389. });
  32390. if (report.length) {
  32391. logger2.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${stringify(userConfig[policyName])}`);
  32392. }
  32393. });
  32394. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  32395. }
  32396. function deepCpy(obj) {
  32397. if (obj && typeof obj === "object") {
  32398. if (Array.isArray(obj)) {
  32399. return obj.map(deepCpy);
  32400. }
  32401. return Object.keys(obj).reduce((result, key) => {
  32402. result[key] = deepCpy(obj[key]);
  32403. return result;
  32404. }, {});
  32405. }
  32406. return obj;
  32407. }
  32408. function enableStreamingMode(config2, logger2) {
  32409. const currentLoader = config2.loader;
  32410. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  32411. logger2.log("[config]: Custom loader detected, cannot enable progressive streaming");
  32412. config2.progressive = false;
  32413. } else {
  32414. const canStreamProgressively = fetchSupported();
  32415. if (canStreamProgressively) {
  32416. config2.loader = FetchLoader;
  32417. config2.progressive = true;
  32418. config2.enableSoftwareAES = true;
  32419. logger2.log("[config]: Progressive streaming enabled, using FetchLoader");
  32420. }
  32421. }
  32422. }
  32423. const MAX_START_GAP_JUMP = 2;
  32424. const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  32425. const SKIP_BUFFER_RANGE_START = 0.05;
  32426. const TICK_INTERVAL$1 = 100;
  32427. class GapController extends TaskLoop {
  32428. constructor(hls, fragmentTracker) {
  32429. super("gap-controller", hls.logger);
  32430. this.hls = null;
  32431. this.fragmentTracker = null;
  32432. this.media = null;
  32433. this.mediaSource = void 0;
  32434. this.nudgeRetry = 0;
  32435. this.stallReported = false;
  32436. this.stalled = null;
  32437. this.moved = false;
  32438. this.seeking = false;
  32439. this.buffered = {};
  32440. this.lastCurrentTime = 0;
  32441. this.ended = 0;
  32442. this.waiting = 0;
  32443. this.onMediaPlaying = () => {
  32444. this.ended = 0;
  32445. this.waiting = 0;
  32446. };
  32447. this.onMediaWaiting = () => {
  32448. var _this$media;
  32449. if ((_this$media = this.media) != null && _this$media.seeking) {
  32450. return;
  32451. }
  32452. this.waiting = self.performance.now();
  32453. this.tick();
  32454. };
  32455. this.onMediaEnded = () => {
  32456. if (this.hls) {
  32457. var _this$media2;
  32458. this.ended = ((_this$media2 = this.media) == null ? void 0 : _this$media2.currentTime) || 1;
  32459. this.hls.trigger(Events.MEDIA_ENDED, {
  32460. stalled: false
  32461. });
  32462. }
  32463. };
  32464. this.hls = hls;
  32465. this.fragmentTracker = fragmentTracker;
  32466. this.registerListeners();
  32467. }
  32468. registerListeners() {
  32469. const {
  32470. hls
  32471. } = this;
  32472. if (hls) {
  32473. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  32474. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  32475. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  32476. }
  32477. }
  32478. unregisterListeners() {
  32479. const {
  32480. hls
  32481. } = this;
  32482. if (hls) {
  32483. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  32484. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  32485. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  32486. }
  32487. }
  32488. destroy() {
  32489. super.destroy();
  32490. this.unregisterListeners();
  32491. this.media = this.hls = this.fragmentTracker = null;
  32492. this.mediaSource = void 0;
  32493. }
  32494. onMediaAttached(event, data) {
  32495. this.setInterval(TICK_INTERVAL$1);
  32496. this.mediaSource = data.mediaSource;
  32497. const media = this.media = data.media;
  32498. addEventListener(media, "playing", this.onMediaPlaying);
  32499. addEventListener(media, "waiting", this.onMediaWaiting);
  32500. addEventListener(media, "ended", this.onMediaEnded);
  32501. }
  32502. onMediaDetaching(event, data) {
  32503. this.clearInterval();
  32504. const {
  32505. media
  32506. } = this;
  32507. if (media) {
  32508. removeEventListener(media, "playing", this.onMediaPlaying);
  32509. removeEventListener(media, "waiting", this.onMediaWaiting);
  32510. removeEventListener(media, "ended", this.onMediaEnded);
  32511. this.media = null;
  32512. }
  32513. this.mediaSource = void 0;
  32514. }
  32515. onBufferAppended(event, data) {
  32516. this.buffered = data.timeRanges;
  32517. }
  32518. get hasBuffered() {
  32519. return Object.keys(this.buffered).length > 0;
  32520. }
  32521. tick() {
  32522. var _this$media3;
  32523. if (!((_this$media3 = this.media) != null && _this$media3.readyState) || !this.hasBuffered) {
  32524. return;
  32525. }
  32526. const currentTime = this.media.currentTime;
  32527. this.poll(currentTime, this.lastCurrentTime);
  32528. this.lastCurrentTime = currentTime;
  32529. }
  32530. /**
  32531. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  32532. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  32533. *
  32534. * @param lastCurrentTime - Previously read playhead position
  32535. */
  32536. poll(currentTime, lastCurrentTime) {
  32537. var _this$hls, _this$hls2;
  32538. const config2 = (_this$hls = this.hls) == null ? void 0 : _this$hls.config;
  32539. if (!config2) {
  32540. return;
  32541. }
  32542. const media = this.media;
  32543. if (!media) {
  32544. return;
  32545. }
  32546. const {
  32547. seeking
  32548. } = media;
  32549. const seeked = this.seeking && !seeking;
  32550. const beginSeek = !this.seeking && seeking;
  32551. const pausedEndedOrHalted = media.paused && !seeking || media.ended || media.playbackRate === 0;
  32552. this.seeking = seeking;
  32553. if (currentTime !== lastCurrentTime) {
  32554. if (lastCurrentTime) {
  32555. this.ended = 0;
  32556. }
  32557. this.moved = true;
  32558. if (!seeking) {
  32559. this.nudgeRetry = 0;
  32560. if (config2.nudgeOnVideoHole && !pausedEndedOrHalted && currentTime > lastCurrentTime) {
  32561. this.nudgeOnVideoHole(currentTime, lastCurrentTime);
  32562. }
  32563. }
  32564. if (this.waiting === 0) {
  32565. this.stallResolved(currentTime);
  32566. }
  32567. return;
  32568. }
  32569. if (beginSeek || seeked) {
  32570. if (seeked) {
  32571. this.stallResolved(currentTime);
  32572. }
  32573. return;
  32574. }
  32575. if (pausedEndedOrHalted) {
  32576. this.nudgeRetry = 0;
  32577. this.stallResolved(currentTime);
  32578. if (!this.ended && media.ended && this.hls) {
  32579. this.ended = currentTime || 1;
  32580. this.hls.trigger(Events.MEDIA_ENDED, {
  32581. stalled: false
  32582. });
  32583. }
  32584. return;
  32585. }
  32586. if (!BufferHelper.getBuffered(media).length) {
  32587. this.nudgeRetry = 0;
  32588. return;
  32589. }
  32590. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  32591. const nextStart = bufferInfo.nextStart || 0;
  32592. const fragmentTracker = this.fragmentTracker;
  32593. if (seeking && fragmentTracker && this.hls) {
  32594. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, currentTime);
  32595. const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  32596. const noBufferHole = !nextStart || inFlightDependency || nextStart - currentTime > MAX_START_GAP_JUMP && !fragmentTracker.getPartialFragment(currentTime);
  32597. if (hasEnoughBuffer || noBufferHole) {
  32598. return;
  32599. }
  32600. this.moved = false;
  32601. }
  32602. const levelDetails = (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails;
  32603. if (!this.moved && this.stalled !== null && fragmentTracker) {
  32604. const isBuffered = bufferInfo.len > 0;
  32605. if (!isBuffered && !nextStart) {
  32606. return;
  32607. }
  32608. const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  32609. const isLive = !!(levelDetails != null && levelDetails.live);
  32610. const maxStartGapJump = isLive ? levelDetails.targetduration * 2 : MAX_START_GAP_JUMP;
  32611. const partialOrGap = fragmentTracker.getPartialFragment(currentTime);
  32612. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  32613. if (!media.paused) {
  32614. this._trySkipBufferHole(partialOrGap);
  32615. }
  32616. return;
  32617. }
  32618. }
  32619. const detectStallWithCurrentTimeMs = config2.detectStallWithCurrentTimeMs;
  32620. const tnow = self.performance.now();
  32621. const tWaiting = this.waiting;
  32622. let stalled = this.stalled;
  32623. if (stalled === null) {
  32624. if (tWaiting > 0 && tnow - tWaiting < detectStallWithCurrentTimeMs) {
  32625. stalled = this.stalled = tWaiting;
  32626. } else {
  32627. this.stalled = tnow;
  32628. return;
  32629. }
  32630. }
  32631. const stalledDuration = tnow - stalled;
  32632. if (!seeking && (stalledDuration >= detectStallWithCurrentTimeMs || tWaiting) && this.hls) {
  32633. var _this$mediaSource;
  32634. 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) {
  32635. if (this.ended) {
  32636. return;
  32637. }
  32638. this.ended = currentTime || 1;
  32639. this.hls.trigger(Events.MEDIA_ENDED, {
  32640. stalled: true
  32641. });
  32642. return;
  32643. }
  32644. this._reportStall(bufferInfo);
  32645. if (!this.media || !this.hls) {
  32646. return;
  32647. }
  32648. }
  32649. const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config2.maxBufferHole);
  32650. this._tryFixBufferStall(bufferedWithHoles, stalledDuration, currentTime);
  32651. }
  32652. stallResolved(currentTime) {
  32653. const stalled = this.stalled;
  32654. if (stalled && this.hls) {
  32655. this.stalled = null;
  32656. if (this.stallReported) {
  32657. const stalledDuration = self.performance.now() - stalled;
  32658. this.log(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);
  32659. this.stallReported = false;
  32660. this.waiting = 0;
  32661. this.hls.trigger(Events.STALL_RESOLVED, {});
  32662. }
  32663. }
  32664. }
  32665. nudgeOnVideoHole(currentTime, lastCurrentTime) {
  32666. var _this$buffered$audio;
  32667. const videoSourceBuffered = this.buffered.video;
  32668. 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)) {
  32669. const audioBufferInfo = BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio), currentTime, 0);
  32670. if (audioBufferInfo.len > 1 && lastCurrentTime >= audioBufferInfo.start) {
  32671. const videoTimes = BufferHelper.timeRangesToArray(videoSourceBuffered);
  32672. const lastBufferedIndex = BufferHelper.bufferedInfo(videoTimes, lastCurrentTime, 0).bufferedIndex;
  32673. if (lastBufferedIndex > -1 && lastBufferedIndex < videoTimes.length - 1) {
  32674. const bufferedIndex = BufferHelper.bufferedInfo(videoTimes, currentTime, 0).bufferedIndex;
  32675. const holeStart = videoTimes[lastBufferedIndex].end;
  32676. const holeEnd = videoTimes[lastBufferedIndex + 1].start;
  32677. if ((bufferedIndex === -1 || bufferedIndex > lastBufferedIndex) && holeEnd - holeStart < 1 && // `maxBufferHole` may be too small and setting it to 0 should not disable this feature
  32678. currentTime - holeStart < 2) {
  32679. const error2 = new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${currentTime} hole: ${holeStart} -> ${holeEnd} buffered index: ${bufferedIndex}`);
  32680. this.warn(error2.message);
  32681. this.media.currentTime += 1e-6;
  32682. const frag = this.fragmentTracker.getPartialFragment(currentTime) || void 0;
  32683. const bufferInfo = BufferHelper.bufferInfo(this.media, currentTime, 0);
  32684. this.hls.trigger(Events.ERROR, {
  32685. type: ErrorTypes.MEDIA_ERROR,
  32686. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  32687. fatal: false,
  32688. error: error2,
  32689. reason: error2.message,
  32690. frag,
  32691. buffer: bufferInfo.len,
  32692. bufferInfo
  32693. });
  32694. }
  32695. }
  32696. }
  32697. }
  32698. }
  32699. /**
  32700. * Detects and attempts to fix known buffer stalling issues.
  32701. * @param bufferInfo - The properties of the current buffer.
  32702. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  32703. * @private
  32704. */
  32705. _tryFixBufferStall(bufferInfo, stalledDurationMs, currentTime) {
  32706. var _this$hls3, _this$hls4;
  32707. const {
  32708. fragmentTracker,
  32709. media
  32710. } = this;
  32711. const config2 = (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.config;
  32712. if (!media || !fragmentTracker || !config2) {
  32713. return;
  32714. }
  32715. const levelDetails = (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.latestLevelDetails;
  32716. const partial2 = fragmentTracker.getPartialFragment(currentTime);
  32717. if (partial2 || levelDetails != null && levelDetails.live && currentTime < levelDetails.fragmentStart) {
  32718. const targetTime = this._trySkipBufferHole(partial2);
  32719. if (targetTime || !this.media) {
  32720. return;
  32721. }
  32722. }
  32723. const bufferedRanges = bufferInfo.buffered;
  32724. const adjacentTraversal = this.adjacentTraversal(bufferInfo, currentTime);
  32725. if ((bufferedRanges && bufferedRanges.length > 1 && bufferInfo.len > config2.maxBufferHole || bufferInfo.nextStart && (bufferInfo.nextStart - currentTime < config2.maxBufferHole || adjacentTraversal)) && (stalledDurationMs > config2.highBufferWatchdogPeriod * 1e3 || this.waiting)) {
  32726. this.warn("Trying to nudge playhead over buffer-hole");
  32727. this._tryNudgeBuffer(bufferInfo);
  32728. }
  32729. }
  32730. adjacentTraversal(bufferInfo, currentTime) {
  32731. const fragmentTracker = this.fragmentTracker;
  32732. const nextStart = bufferInfo.nextStart;
  32733. if (fragmentTracker && nextStart) {
  32734. const current = fragmentTracker.getFragAtPos(currentTime, PlaylistLevelType.MAIN);
  32735. const next = fragmentTracker.getFragAtPos(nextStart, PlaylistLevelType.MAIN);
  32736. if (current && next) {
  32737. return next.sn - current.sn < 2;
  32738. }
  32739. }
  32740. return false;
  32741. }
  32742. /**
  32743. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  32744. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  32745. * @private
  32746. */
  32747. _reportStall(bufferInfo) {
  32748. const {
  32749. hls,
  32750. media,
  32751. stallReported,
  32752. stalled
  32753. } = this;
  32754. if (!stallReported && stalled !== null && media && hls) {
  32755. this.stallReported = true;
  32756. const error2 = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${stringify(bufferInfo)})`);
  32757. this.warn(error2.message);
  32758. hls.trigger(Events.ERROR, {
  32759. type: ErrorTypes.MEDIA_ERROR,
  32760. details: ErrorDetails.BUFFER_STALLED_ERROR,
  32761. fatal: false,
  32762. error: error2,
  32763. buffer: bufferInfo.len,
  32764. bufferInfo,
  32765. stalled: {
  32766. start: stalled
  32767. }
  32768. });
  32769. }
  32770. }
  32771. /**
  32772. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  32773. * @param partial - The partial fragment found at the current time (where playback is stalling).
  32774. * @private
  32775. */
  32776. _trySkipBufferHole(partial2) {
  32777. var _this$hls5;
  32778. const {
  32779. fragmentTracker,
  32780. media
  32781. } = this;
  32782. const config2 = (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.config;
  32783. if (!media || !fragmentTracker || !config2) {
  32784. return 0;
  32785. }
  32786. const currentTime = media.currentTime;
  32787. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  32788. const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  32789. if (startTime && this.hls) {
  32790. const bufferStarved = bufferInfo.len <= config2.maxBufferHole;
  32791. const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  32792. const gapLength = startTime - currentTime;
  32793. if (gapLength > 0 && (bufferStarved || waiting)) {
  32794. if (gapLength > config2.maxBufferHole) {
  32795. let startGap = false;
  32796. if (currentTime === 0) {
  32797. const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  32798. if (startFrag && startTime < startFrag.end) {
  32799. startGap = true;
  32800. }
  32801. }
  32802. if (!startGap) {
  32803. const startProvisioned = partial2 || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  32804. if (startProvisioned) {
  32805. var _this$hls$loadLevelOb;
  32806. if (!((_this$hls$loadLevelOb = this.hls.loadLevelObj) != null && _this$hls$loadLevelOb.details)) {
  32807. return 0;
  32808. }
  32809. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, startTime);
  32810. if (inFlightDependency) {
  32811. return 0;
  32812. }
  32813. let moreToLoad = false;
  32814. let pos = startProvisioned.end;
  32815. while (pos < startTime) {
  32816. const provisioned = fragmentTracker.getAppendedFrag(pos, PlaylistLevelType.MAIN) || fragmentTracker.getPartialFragment(pos);
  32817. if (provisioned) {
  32818. pos += provisioned.duration;
  32819. } else {
  32820. moreToLoad = true;
  32821. break;
  32822. }
  32823. }
  32824. if (moreToLoad) {
  32825. return 0;
  32826. }
  32827. }
  32828. }
  32829. }
  32830. const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  32831. this.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);
  32832. this.moved = true;
  32833. media.currentTime = targetTime;
  32834. if (!(partial2 != null && partial2.gap)) {
  32835. const error2 = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);
  32836. this.hls.trigger(Events.ERROR, {
  32837. type: ErrorTypes.MEDIA_ERROR,
  32838. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  32839. fatal: false,
  32840. error: error2,
  32841. reason: error2.message,
  32842. frag: partial2 || void 0,
  32843. buffer: bufferInfo.len,
  32844. bufferInfo
  32845. });
  32846. }
  32847. return targetTime;
  32848. }
  32849. }
  32850. return 0;
  32851. }
  32852. /**
  32853. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  32854. * @private
  32855. */
  32856. _tryNudgeBuffer(bufferInfo) {
  32857. const {
  32858. hls,
  32859. media,
  32860. nudgeRetry
  32861. } = this;
  32862. const config2 = hls == null ? void 0 : hls.config;
  32863. if (!media || !config2) {
  32864. return 0;
  32865. }
  32866. const currentTime = media.currentTime;
  32867. this.nudgeRetry++;
  32868. if (nudgeRetry < config2.nudgeMaxRetry) {
  32869. const targetTime = currentTime + (nudgeRetry + 1) * config2.nudgeOffset;
  32870. const error2 = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);
  32871. this.warn(error2.message);
  32872. media.currentTime = targetTime;
  32873. hls.trigger(Events.ERROR, {
  32874. type: ErrorTypes.MEDIA_ERROR,
  32875. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  32876. error: error2,
  32877. fatal: false,
  32878. buffer: bufferInfo.len,
  32879. bufferInfo
  32880. });
  32881. } else {
  32882. const error2 = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config2.nudgeMaxRetry} nudges`);
  32883. this.error(error2.message);
  32884. hls.trigger(Events.ERROR, {
  32885. type: ErrorTypes.MEDIA_ERROR,
  32886. details: ErrorDetails.BUFFER_STALLED_ERROR,
  32887. error: error2,
  32888. fatal: true,
  32889. buffer: bufferInfo.len,
  32890. bufferInfo
  32891. });
  32892. }
  32893. }
  32894. }
  32895. function getInFlightDependency(inFlightFragments, currentTime) {
  32896. const main = inFlight(inFlightFragments.main);
  32897. if (main && main.start <= currentTime) {
  32898. return main;
  32899. }
  32900. const audio = inFlight(inFlightFragments.audio);
  32901. if (audio && audio.start <= currentTime) {
  32902. return audio;
  32903. }
  32904. return null;
  32905. }
  32906. function inFlight(inFlightData) {
  32907. if (!inFlightData) {
  32908. return null;
  32909. }
  32910. switch (inFlightData.state) {
  32911. case State.IDLE:
  32912. case State.STOPPED:
  32913. case State.ENDED:
  32914. case State.ERROR:
  32915. return null;
  32916. }
  32917. return inFlightData.frag;
  32918. }
  32919. const MIN_CUE_DURATION = 0.25;
  32920. function getCueClass() {
  32921. if (typeof self === "undefined")
  32922. return void 0;
  32923. return self.VTTCue || self.TextTrackCue;
  32924. }
  32925. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  32926. let cue = new Cue(startTime, endTime, "");
  32927. try {
  32928. cue.value = data;
  32929. if (type) {
  32930. cue.type = type;
  32931. }
  32932. } catch (e2) {
  32933. cue = new Cue(startTime, endTime, stringify(type ? _objectSpread2({
  32934. type
  32935. }, data) : data));
  32936. }
  32937. return cue;
  32938. }
  32939. const MAX_CUE_ENDTIME = (() => {
  32940. const Cue = getCueClass();
  32941. try {
  32942. Cue && new Cue(0, Number.POSITIVE_INFINITY, "");
  32943. } catch (e2) {
  32944. return Number.MAX_VALUE;
  32945. }
  32946. return Number.POSITIVE_INFINITY;
  32947. })();
  32948. class ID3TrackController {
  32949. constructor(hls) {
  32950. this.hls = void 0;
  32951. this.id3Track = null;
  32952. this.media = null;
  32953. this.dateRangeCuesAppended = {};
  32954. this.removeCues = true;
  32955. this.onEventCueEnter = () => {
  32956. if (!this.hls) {
  32957. return;
  32958. }
  32959. this.hls.trigger(Events.EVENT_CUE_ENTER, {});
  32960. };
  32961. this.hls = hls;
  32962. this._registerListeners();
  32963. }
  32964. destroy() {
  32965. this._unregisterListeners();
  32966. this.id3Track = null;
  32967. this.media = null;
  32968. this.dateRangeCuesAppended = {};
  32969. this.hls = this.onEventCueEnter = null;
  32970. }
  32971. _registerListeners() {
  32972. const {
  32973. hls
  32974. } = this;
  32975. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  32976. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  32977. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  32978. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  32979. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  32980. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  32981. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  32982. hls.on(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  32983. }
  32984. _unregisterListeners() {
  32985. const {
  32986. hls
  32987. } = this;
  32988. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  32989. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  32990. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  32991. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  32992. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  32993. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  32994. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  32995. hls.off(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  32996. }
  32997. // Add ID3 metatadata text track.
  32998. onMediaAttaching(event, data) {
  32999. var _data$overrides;
  33000. this.media = data.media;
  33001. if (((_data$overrides = data.overrides) == null ? void 0 : _data$overrides.cueRemoval) === false) {
  33002. this.removeCues = false;
  33003. }
  33004. }
  33005. onMediaAttached() {
  33006. const details = this.hls.latestLevelDetails;
  33007. if (details) {
  33008. this.updateDateRangeCues(details);
  33009. }
  33010. }
  33011. onMediaDetaching(event, data) {
  33012. this.media = null;
  33013. const transferringMedia = !!data.transferMedia;
  33014. if (transferringMedia) {
  33015. return;
  33016. }
  33017. if (this.id3Track) {
  33018. if (this.removeCues) {
  33019. clearCurrentCues(this.id3Track, this.onEventCueEnter);
  33020. }
  33021. this.id3Track = null;
  33022. }
  33023. this.dateRangeCuesAppended = {};
  33024. }
  33025. onManifestLoading() {
  33026. this.dateRangeCuesAppended = {};
  33027. }
  33028. createTrack(media) {
  33029. const track = this.getID3Track(media.textTracks);
  33030. track.mode = "hidden";
  33031. return track;
  33032. }
  33033. getID3Track(textTracks) {
  33034. if (!this.media) {
  33035. return;
  33036. }
  33037. for (let i2 = 0; i2 < textTracks.length; i2++) {
  33038. const textTrack = textTracks[i2];
  33039. if (textTrack.kind === "metadata" && textTrack.label === "id3") {
  33040. sendAddTrackEvent(textTrack, this.media);
  33041. return textTrack;
  33042. }
  33043. }
  33044. return this.media.addTextTrack("metadata", "id3");
  33045. }
  33046. onFragParsingMetadata(event, data) {
  33047. if (!this.media) {
  33048. return;
  33049. }
  33050. const {
  33051. hls: {
  33052. config: {
  33053. enableEmsgMetadataCues,
  33054. enableID3MetadataCues
  33055. }
  33056. }
  33057. } = this;
  33058. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  33059. return;
  33060. }
  33061. const {
  33062. samples
  33063. } = data;
  33064. if (!this.id3Track) {
  33065. this.id3Track = this.createTrack(this.media);
  33066. }
  33067. const Cue = getCueClass();
  33068. if (!Cue) {
  33069. return;
  33070. }
  33071. for (let i2 = 0; i2 < samples.length; i2++) {
  33072. const type = samples[i2].type;
  33073. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  33074. continue;
  33075. }
  33076. const frames = getId3Frames(samples[i2].data);
  33077. if (frames) {
  33078. const startTime = samples[i2].pts;
  33079. let endTime = startTime + samples[i2].duration;
  33080. if (endTime > MAX_CUE_ENDTIME) {
  33081. endTime = MAX_CUE_ENDTIME;
  33082. }
  33083. const timeDiff = endTime - startTime;
  33084. if (timeDiff <= 0) {
  33085. endTime = startTime + MIN_CUE_DURATION;
  33086. }
  33087. for (let j2 = 0; j2 < frames.length; j2++) {
  33088. const frame = frames[j2];
  33089. if (!isId3TimestampFrame(frame)) {
  33090. this.updateId3CueEnds(startTime, type);
  33091. const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  33092. if (cue) {
  33093. this.id3Track.addCue(cue);
  33094. }
  33095. }
  33096. }
  33097. }
  33098. }
  33099. }
  33100. updateId3CueEnds(startTime, type) {
  33101. var _this$id3Track;
  33102. const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  33103. if (cues) {
  33104. for (let i2 = cues.length; i2--; ) {
  33105. const cue = cues[i2];
  33106. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  33107. cue.endTime = startTime;
  33108. }
  33109. }
  33110. }
  33111. }
  33112. onBufferFlushing(event, {
  33113. startOffset,
  33114. endOffset,
  33115. type
  33116. }) {
  33117. const {
  33118. id3Track,
  33119. hls
  33120. } = this;
  33121. if (!hls) {
  33122. return;
  33123. }
  33124. const {
  33125. config: {
  33126. enableEmsgMetadataCues,
  33127. enableID3MetadataCues
  33128. }
  33129. } = hls;
  33130. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  33131. let predicate;
  33132. if (type === "audio") {
  33133. predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  33134. } else if (type === "video") {
  33135. predicate = (cue) => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  33136. } else {
  33137. predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  33138. }
  33139. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  33140. }
  33141. }
  33142. onLevelUpdated(event, {
  33143. details
  33144. }) {
  33145. this.updateDateRangeCues(details, true);
  33146. }
  33147. onLevelPtsUpdated(event, data) {
  33148. if (Math.abs(data.drift) > 0.01) {
  33149. this.updateDateRangeCues(data.details);
  33150. }
  33151. }
  33152. updateDateRangeCues(details, removeOldCues) {
  33153. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  33154. return;
  33155. }
  33156. const {
  33157. id3Track
  33158. } = this;
  33159. const {
  33160. dateRanges
  33161. } = details;
  33162. const ids = Object.keys(dateRanges);
  33163. let dateRangeCuesAppended = this.dateRangeCuesAppended;
  33164. if (id3Track && removeOldCues) {
  33165. var _id3Track$cues;
  33166. if ((_id3Track$cues = id3Track.cues) != null && _id3Track$cues.length) {
  33167. const idsToRemove = Object.keys(dateRangeCuesAppended).filter((id) => !ids.includes(id));
  33168. for (let i2 = idsToRemove.length; i2--; ) {
  33169. const id = idsToRemove[i2];
  33170. const cues = dateRangeCuesAppended[id].cues;
  33171. delete dateRangeCuesAppended[id];
  33172. Object.keys(cues).forEach((key) => {
  33173. try {
  33174. const cue = cues[key];
  33175. cue.removeEventListener("enter", this.onEventCueEnter);
  33176. id3Track.removeCue(cue);
  33177. } catch (e2) {
  33178. }
  33179. });
  33180. }
  33181. } else {
  33182. dateRangeCuesAppended = this.dateRangeCuesAppended = {};
  33183. }
  33184. }
  33185. const lastFragment = details.fragments[details.fragments.length - 1];
  33186. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  33187. return;
  33188. }
  33189. if (!this.id3Track) {
  33190. this.id3Track = this.createTrack(this.media);
  33191. }
  33192. const Cue = getCueClass();
  33193. for (let i2 = 0; i2 < ids.length; i2++) {
  33194. const id = ids[i2];
  33195. const dateRange = dateRanges[id];
  33196. const startTime = dateRange.startTime;
  33197. const appendedDateRangeCues = dateRangeCuesAppended[id];
  33198. const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  33199. let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  33200. let endTime = MAX_CUE_ENDTIME;
  33201. const {
  33202. duration,
  33203. endDate
  33204. } = dateRange;
  33205. if (endDate && duration !== null) {
  33206. endTime = startTime + duration;
  33207. durationKnown = true;
  33208. } else if (dateRange.endOnNext && !durationKnown) {
  33209. const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id2) => {
  33210. if (id2 !== dateRange.id) {
  33211. const otherDateRange = dateRanges[id2];
  33212. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  33213. return otherDateRange;
  33214. }
  33215. }
  33216. return candidateDateRange;
  33217. }, null);
  33218. if (nextDateRangeWithSameClass) {
  33219. endTime = nextDateRangeWithSameClass.startTime;
  33220. durationKnown = true;
  33221. }
  33222. }
  33223. const attributes = Object.keys(dateRange.attr);
  33224. for (let j2 = 0; j2 < attributes.length; j2++) {
  33225. const key = attributes[j2];
  33226. if (!isDateRangeCueAttribute(key)) {
  33227. continue;
  33228. }
  33229. const cue = cues[key];
  33230. if (cue) {
  33231. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  33232. cue.endTime = endTime;
  33233. } else if (Math.abs(cue.startTime - startTime) > 0.01) {
  33234. cue.startTime = startTime;
  33235. cue.endTime = endTime;
  33236. }
  33237. } else if (Cue) {
  33238. let data = dateRange.attr[key];
  33239. if (isSCTE35Attribute(key)) {
  33240. data = hexToArrayBuffer(data);
  33241. }
  33242. const payload = {
  33243. key,
  33244. data
  33245. };
  33246. const _cue = createCueWithDataFields(Cue, startTime, endTime, payload, MetadataSchema.dateRange);
  33247. if (_cue) {
  33248. _cue.id = id;
  33249. this.id3Track.addCue(_cue);
  33250. cues[key] = _cue;
  33251. if (this.hls.config.interstitialsController) {
  33252. if (key === "X-ASSET-LIST" || key === "X-ASSET-URL") {
  33253. _cue.addEventListener("enter", this.onEventCueEnter);
  33254. }
  33255. }
  33256. }
  33257. }
  33258. }
  33259. dateRangeCuesAppended[id] = {
  33260. cues,
  33261. dateRange,
  33262. durationKnown
  33263. };
  33264. }
  33265. }
  33266. }
  33267. class LatencyController {
  33268. constructor(hls) {
  33269. this.hls = void 0;
  33270. this.config = void 0;
  33271. this.media = null;
  33272. this.currentTime = 0;
  33273. this.stallCount = 0;
  33274. this._latency = null;
  33275. this._targetLatencyUpdated = false;
  33276. this.onTimeupdate = () => {
  33277. const {
  33278. media
  33279. } = this;
  33280. const levelDetails = this.levelDetails;
  33281. if (!media || !levelDetails) {
  33282. return;
  33283. }
  33284. this.currentTime = media.currentTime;
  33285. const latency = this.computeLatency();
  33286. if (latency === null) {
  33287. return;
  33288. }
  33289. this._latency = latency;
  33290. const {
  33291. lowLatencyMode,
  33292. maxLiveSyncPlaybackRate
  33293. } = this.config;
  33294. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  33295. return;
  33296. }
  33297. const targetLatency = this.targetLatency;
  33298. if (targetLatency === null) {
  33299. return;
  33300. }
  33301. const distanceFromTarget = latency - targetLatency;
  33302. const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  33303. const inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  33304. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  33305. const max = Math.min(2, Math.max(1, maxLiveSyncPlaybackRate));
  33306. const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  33307. const playbackRate = Math.min(max, Math.max(1, rate));
  33308. this.changeMediaPlaybackRate(media, playbackRate);
  33309. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  33310. this.changeMediaPlaybackRate(media, 1);
  33311. }
  33312. };
  33313. this.hls = hls;
  33314. this.config = hls.config;
  33315. this.registerListeners();
  33316. }
  33317. get levelDetails() {
  33318. var _this$hls;
  33319. return ((_this$hls = this.hls) == null ? void 0 : _this$hls.latestLevelDetails) || null;
  33320. }
  33321. get latency() {
  33322. return this._latency || 0;
  33323. }
  33324. get maxLatency() {
  33325. const {
  33326. config: config2
  33327. } = this;
  33328. if (config2.liveMaxLatencyDuration !== void 0) {
  33329. return config2.liveMaxLatencyDuration;
  33330. }
  33331. const levelDetails = this.levelDetails;
  33332. return levelDetails ? config2.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  33333. }
  33334. get targetLatency() {
  33335. const levelDetails = this.levelDetails;
  33336. if (levelDetails === null || this.hls === null) {
  33337. return null;
  33338. }
  33339. const {
  33340. holdBack,
  33341. partHoldBack,
  33342. targetduration
  33343. } = levelDetails;
  33344. const {
  33345. liveSyncDuration,
  33346. liveSyncDurationCount,
  33347. lowLatencyMode
  33348. } = this.config;
  33349. const userConfig = this.hls.userConfig;
  33350. let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  33351. if (this._targetLatencyUpdated || userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  33352. targetLatency = liveSyncDuration !== void 0 ? liveSyncDuration : liveSyncDurationCount * targetduration;
  33353. }
  33354. const maxLiveSyncOnStallIncrease = targetduration;
  33355. return targetLatency + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  33356. }
  33357. set targetLatency(latency) {
  33358. this.stallCount = 0;
  33359. this.config.liveSyncDuration = latency;
  33360. this._targetLatencyUpdated = true;
  33361. }
  33362. get liveSyncPosition() {
  33363. const liveEdge = this.estimateLiveEdge();
  33364. const targetLatency = this.targetLatency;
  33365. if (liveEdge === null || targetLatency === null) {
  33366. return null;
  33367. }
  33368. const levelDetails = this.levelDetails;
  33369. if (levelDetails === null) {
  33370. return null;
  33371. }
  33372. const edge = levelDetails.edge;
  33373. const syncPosition = liveEdge - targetLatency - this.edgeStalled;
  33374. const min = edge - levelDetails.totalduration;
  33375. const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  33376. return Math.min(Math.max(min, syncPosition), max);
  33377. }
  33378. get drift() {
  33379. const levelDetails = this.levelDetails;
  33380. if (levelDetails === null) {
  33381. return 1;
  33382. }
  33383. return levelDetails.drift;
  33384. }
  33385. get edgeStalled() {
  33386. const levelDetails = this.levelDetails;
  33387. if (levelDetails === null) {
  33388. return 0;
  33389. }
  33390. const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  33391. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  33392. }
  33393. get forwardBufferLength() {
  33394. const {
  33395. media
  33396. } = this;
  33397. const levelDetails = this.levelDetails;
  33398. if (!media || !levelDetails) {
  33399. return 0;
  33400. }
  33401. const bufferedRanges = media.buffered.length;
  33402. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  33403. }
  33404. destroy() {
  33405. this.unregisterListeners();
  33406. this.onMediaDetaching();
  33407. this.hls = null;
  33408. }
  33409. registerListeners() {
  33410. const {
  33411. hls
  33412. } = this;
  33413. if (!hls) {
  33414. return;
  33415. }
  33416. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  33417. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  33418. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  33419. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  33420. hls.on(Events.ERROR, this.onError, this);
  33421. }
  33422. unregisterListeners() {
  33423. const {
  33424. hls
  33425. } = this;
  33426. if (!hls) {
  33427. return;
  33428. }
  33429. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  33430. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  33431. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  33432. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  33433. hls.off(Events.ERROR, this.onError, this);
  33434. }
  33435. onMediaAttached(event, data) {
  33436. this.media = data.media;
  33437. this.media.addEventListener("timeupdate", this.onTimeupdate);
  33438. }
  33439. onMediaDetaching() {
  33440. if (this.media) {
  33441. this.media.removeEventListener("timeupdate", this.onTimeupdate);
  33442. this.media = null;
  33443. }
  33444. }
  33445. onManifestLoading() {
  33446. this._latency = null;
  33447. this.stallCount = 0;
  33448. }
  33449. onLevelUpdated(event, {
  33450. details
  33451. }) {
  33452. if (details.advanced) {
  33453. this.onTimeupdate();
  33454. }
  33455. if (!details.live && this.media) {
  33456. this.media.removeEventListener("timeupdate", this.onTimeupdate);
  33457. }
  33458. }
  33459. onError(event, data) {
  33460. var _this$levelDetails;
  33461. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  33462. return;
  33463. }
  33464. this.stallCount++;
  33465. if (this.hls && (_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  33466. this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency");
  33467. }
  33468. }
  33469. changeMediaPlaybackRate(media, playbackRate) {
  33470. var _this$hls2, _this$targetLatency;
  33471. if (media.playbackRate === playbackRate) {
  33472. return;
  33473. }
  33474. (_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}`);
  33475. media.playbackRate = playbackRate;
  33476. }
  33477. estimateLiveEdge() {
  33478. const levelDetails = this.levelDetails;
  33479. if (levelDetails === null) {
  33480. return null;
  33481. }
  33482. return levelDetails.edge + levelDetails.age;
  33483. }
  33484. computeLatency() {
  33485. const liveEdge = this.estimateLiveEdge();
  33486. if (liveEdge === null) {
  33487. return null;
  33488. }
  33489. return liveEdge - this.currentTime;
  33490. }
  33491. }
  33492. class LevelController extends BasePlaylistController {
  33493. constructor(hls, contentSteeringController) {
  33494. super(hls, "level-controller");
  33495. this._levels = [];
  33496. this._firstLevel = -1;
  33497. this._maxAutoLevel = -1;
  33498. this._startLevel = void 0;
  33499. this.currentLevel = null;
  33500. this.currentLevelIndex = -1;
  33501. this.manualLevelIndex = -1;
  33502. this.steering = void 0;
  33503. this.onParsedComplete = void 0;
  33504. this.steering = contentSteeringController;
  33505. this._registerListeners();
  33506. }
  33507. _registerListeners() {
  33508. const {
  33509. hls
  33510. } = this;
  33511. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  33512. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  33513. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  33514. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  33515. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  33516. hls.on(Events.ERROR, this.onError, this);
  33517. }
  33518. _unregisterListeners() {
  33519. const {
  33520. hls
  33521. } = this;
  33522. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  33523. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  33524. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  33525. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  33526. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  33527. hls.off(Events.ERROR, this.onError, this);
  33528. }
  33529. destroy() {
  33530. this._unregisterListeners();
  33531. this.steering = null;
  33532. this.resetLevels();
  33533. super.destroy();
  33534. }
  33535. stopLoad() {
  33536. const levels = this._levels;
  33537. levels.forEach((level) => {
  33538. level.loadError = 0;
  33539. level.fragmentError = 0;
  33540. });
  33541. super.stopLoad();
  33542. }
  33543. resetLevels() {
  33544. this._startLevel = void 0;
  33545. this.manualLevelIndex = -1;
  33546. this.currentLevelIndex = -1;
  33547. this.currentLevel = null;
  33548. this._levels = [];
  33549. this._maxAutoLevel = -1;
  33550. }
  33551. onManifestLoading(event, data) {
  33552. this.resetLevels();
  33553. }
  33554. onManifestLoaded(event, data) {
  33555. const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  33556. const levels = [];
  33557. const redundantSet = {};
  33558. const generatePathwaySet = {};
  33559. let resolutionFound = false;
  33560. let videoCodecFound = false;
  33561. let audioCodecFound = false;
  33562. data.levels.forEach((levelParsed) => {
  33563. const attributes = levelParsed.attrs;
  33564. let {
  33565. audioCodec,
  33566. videoCodec
  33567. } = levelParsed;
  33568. if (audioCodec) {
  33569. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource) || void 0;
  33570. }
  33571. if (videoCodec) {
  33572. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  33573. }
  33574. const {
  33575. width,
  33576. height,
  33577. unknownCodecs
  33578. } = levelParsed;
  33579. let unknownUnsupportedCodecCount = unknownCodecs ? unknownCodecs.length : 0;
  33580. if (unknownCodecs) {
  33581. for (let i2 = unknownUnsupportedCodecCount; i2--; ) {
  33582. const unknownCodec = unknownCodecs[i2];
  33583. if (this.isAudioSupported(unknownCodec)) {
  33584. levelParsed.audioCodec = audioCodec = audioCodec ? `${audioCodec},${unknownCodec}` : unknownCodec;
  33585. unknownUnsupportedCodecCount--;
  33586. sampleEntryCodesISO.audio[audioCodec.substring(0, 4)] = 2;
  33587. } else if (this.isVideoSupported(unknownCodec)) {
  33588. levelParsed.videoCodec = videoCodec = videoCodec ? `${videoCodec},${unknownCodec}` : unknownCodec;
  33589. unknownUnsupportedCodecCount--;
  33590. sampleEntryCodesISO.video[videoCodec.substring(0, 4)] = 2;
  33591. }
  33592. }
  33593. }
  33594. resolutionFound || (resolutionFound = !!(width && height));
  33595. videoCodecFound || (videoCodecFound = !!videoCodec);
  33596. audioCodecFound || (audioCodecFound = !!audioCodec);
  33597. if (unknownUnsupportedCodecCount || audioCodec && !this.isAudioSupported(audioCodec) || videoCodec && !this.isVideoSupported(videoCodec)) {
  33598. this.log(`Some or all CODECS not supported "${attributes.CODECS}"`);
  33599. return;
  33600. }
  33601. const {
  33602. CODECS,
  33603. "FRAME-RATE": FRAMERATE,
  33604. "HDCP-LEVEL": HDCP,
  33605. "PATHWAY-ID": PATHWAY,
  33606. RESOLUTION,
  33607. "VIDEO-RANGE": VIDEO_RANGE
  33608. } = attributes;
  33609. const contentSteeringPrefix = `${PATHWAY || "."}-`;
  33610. const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;
  33611. if (!redundantSet[levelKey]) {
  33612. const level = this.createLevel(levelParsed);
  33613. redundantSet[levelKey] = level;
  33614. generatePathwaySet[levelKey] = 1;
  33615. levels.push(level);
  33616. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs["PATHWAY-ID"]) {
  33617. const pathwayCount = generatePathwaySet[levelKey] += 1;
  33618. levelParsed.attrs["PATHWAY-ID"] = new Array(pathwayCount + 1).join(".");
  33619. const level = this.createLevel(levelParsed);
  33620. redundantSet[levelKey] = level;
  33621. levels.push(level);
  33622. } else {
  33623. redundantSet[levelKey].addGroupId("audio", attributes.AUDIO);
  33624. redundantSet[levelKey].addGroupId("text", attributes.SUBTITLES);
  33625. }
  33626. });
  33627. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  33628. }
  33629. createLevel(levelParsed) {
  33630. const level = new Level(levelParsed);
  33631. const supplemental = levelParsed.supplemental;
  33632. if (supplemental != null && supplemental.videoCodec && !this.isVideoSupported(supplemental.videoCodec)) {
  33633. const error2 = new Error(`SUPPLEMENTAL-CODECS not supported "${supplemental.videoCodec}"`);
  33634. this.log(error2.message);
  33635. level.supportedResult = getUnsupportedResult(error2, []);
  33636. }
  33637. return level;
  33638. }
  33639. isAudioSupported(codec) {
  33640. return areCodecsMediaSourceSupported(codec, "audio", this.hls.config.preferManagedMediaSource);
  33641. }
  33642. isVideoSupported(codec) {
  33643. return areCodecsMediaSourceSupported(codec, "video", this.hls.config.preferManagedMediaSource);
  33644. }
  33645. filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  33646. let audioTracks = [];
  33647. let subtitleTracks = [];
  33648. let levels = filteredLevels;
  33649. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  33650. levels = levels.filter(({
  33651. videoCodec,
  33652. videoRange,
  33653. width,
  33654. height
  33655. }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange));
  33656. }
  33657. if (levels.length === 0) {
  33658. Promise.resolve().then(() => {
  33659. if (this.hls) {
  33660. let message = "no level with compatible codecs found in manifest";
  33661. let reason = message;
  33662. if (data.levels.length) {
  33663. reason = `one or more CODECS in variant not supported: ${stringify(data.levels.map((level) => level.attrs.CODECS).filter((value2, index2, array2) => array2.indexOf(value2) === index2))}`;
  33664. this.warn(reason);
  33665. message += ` (${reason})`;
  33666. }
  33667. const error2 = new Error(message);
  33668. this.hls.trigger(Events.ERROR, {
  33669. type: ErrorTypes.MEDIA_ERROR,
  33670. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  33671. fatal: true,
  33672. url: data.url,
  33673. error: error2,
  33674. reason
  33675. });
  33676. }
  33677. });
  33678. return;
  33679. }
  33680. if (data.audioTracks) {
  33681. audioTracks = data.audioTracks.filter((track) => !track.audioCodec || this.isAudioSupported(track.audioCodec));
  33682. assignTrackIdsByGroup(audioTracks);
  33683. }
  33684. if (data.subtitles) {
  33685. subtitleTracks = data.subtitles;
  33686. assignTrackIdsByGroup(subtitleTracks);
  33687. }
  33688. const unsortedLevels = levels.slice(0);
  33689. levels.sort((a2, b2) => {
  33690. if (a2.attrs["HDCP-LEVEL"] !== b2.attrs["HDCP-LEVEL"]) {
  33691. return (a2.attrs["HDCP-LEVEL"] || "") > (b2.attrs["HDCP-LEVEL"] || "") ? 1 : -1;
  33692. }
  33693. if (resolutionFound && a2.height !== b2.height) {
  33694. return a2.height - b2.height;
  33695. }
  33696. if (a2.frameRate !== b2.frameRate) {
  33697. return a2.frameRate - b2.frameRate;
  33698. }
  33699. if (a2.videoRange !== b2.videoRange) {
  33700. return VideoRangeValues.indexOf(a2.videoRange) - VideoRangeValues.indexOf(b2.videoRange);
  33701. }
  33702. if (a2.videoCodec !== b2.videoCodec) {
  33703. const valueA = videoCodecPreferenceValue(a2.videoCodec);
  33704. const valueB = videoCodecPreferenceValue(b2.videoCodec);
  33705. if (valueA !== valueB) {
  33706. return valueB - valueA;
  33707. }
  33708. }
  33709. if (a2.uri === b2.uri && a2.codecSet !== b2.codecSet) {
  33710. const valueA = codecsSetSelectionPreferenceValue(a2.codecSet);
  33711. const valueB = codecsSetSelectionPreferenceValue(b2.codecSet);
  33712. if (valueA !== valueB) {
  33713. return valueB - valueA;
  33714. }
  33715. }
  33716. if (a2.averageBitrate !== b2.averageBitrate) {
  33717. return a2.averageBitrate - b2.averageBitrate;
  33718. }
  33719. return 0;
  33720. });
  33721. let firstLevelInPlaylist = unsortedLevels[0];
  33722. if (this.steering) {
  33723. levels = this.steering.filterParsedLevels(levels);
  33724. if (levels.length !== unsortedLevels.length) {
  33725. for (let i2 = 0; i2 < unsortedLevels.length; i2++) {
  33726. if (unsortedLevels[i2].pathwayId === levels[0].pathwayId) {
  33727. firstLevelInPlaylist = unsortedLevels[i2];
  33728. break;
  33729. }
  33730. }
  33731. }
  33732. }
  33733. this._levels = levels;
  33734. for (let i2 = 0; i2 < levels.length; i2++) {
  33735. if (levels[i2] === firstLevelInPlaylist) {
  33736. var _this$hls$userConfig;
  33737. this._firstLevel = i2;
  33738. const firstLevelBitrate = firstLevelInPlaylist.bitrate;
  33739. const bandwidthEstimate = this.hls.bandwidthEstimate;
  33740. this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);
  33741. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === void 0) {
  33742. const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  33743. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === this.hls.abrEwmaDefaultEstimate) {
  33744. this.hls.bandwidthEstimate = startingBwEstimate;
  33745. }
  33746. }
  33747. break;
  33748. }
  33749. }
  33750. const audioOnly = audioCodecFound && !videoCodecFound;
  33751. const config2 = this.hls.config;
  33752. const altAudioEnabled = !!(config2.audioStreamController && config2.audioTrackController);
  33753. const edata = {
  33754. levels,
  33755. audioTracks,
  33756. subtitleTracks,
  33757. sessionData: data.sessionData,
  33758. sessionKeys: data.sessionKeys,
  33759. firstLevel: this._firstLevel,
  33760. stats: data.stats,
  33761. audio: audioCodecFound,
  33762. video: videoCodecFound,
  33763. altAudio: altAudioEnabled && !audioOnly && audioTracks.some((t2) => !!t2.url)
  33764. };
  33765. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  33766. }
  33767. get levels() {
  33768. if (this._levels.length === 0) {
  33769. return null;
  33770. }
  33771. return this._levels;
  33772. }
  33773. get loadLevelObj() {
  33774. return this.currentLevel;
  33775. }
  33776. get level() {
  33777. return this.currentLevelIndex;
  33778. }
  33779. set level(newLevel) {
  33780. const levels = this._levels;
  33781. if (levels.length === 0) {
  33782. return;
  33783. }
  33784. if (newLevel < 0 || newLevel >= levels.length) {
  33785. const error2 = new Error("invalid level idx");
  33786. const fatal = newLevel < 0;
  33787. this.hls.trigger(Events.ERROR, {
  33788. type: ErrorTypes.OTHER_ERROR,
  33789. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  33790. level: newLevel,
  33791. fatal,
  33792. error: error2,
  33793. reason: error2.message
  33794. });
  33795. if (fatal) {
  33796. return;
  33797. }
  33798. newLevel = Math.min(newLevel, levels.length - 1);
  33799. }
  33800. const lastLevelIndex = this.currentLevelIndex;
  33801. const lastLevel = this.currentLevel;
  33802. const lastPathwayId = lastLevel ? lastLevel.attrs["PATHWAY-ID"] : void 0;
  33803. const level = levels[newLevel];
  33804. const pathwayId = level.attrs["PATHWAY-ID"];
  33805. this.currentLevelIndex = newLevel;
  33806. this.currentLevel = level;
  33807. if (lastLevelIndex === newLevel && lastLevel && lastPathwayId === pathwayId) {
  33808. return;
  33809. }
  33810. 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 : ""}`);
  33811. const levelSwitchingData = {
  33812. level: newLevel,
  33813. attrs: level.attrs,
  33814. details: level.details,
  33815. bitrate: level.bitrate,
  33816. averageBitrate: level.averageBitrate,
  33817. maxBitrate: level.maxBitrate,
  33818. realBitrate: level.realBitrate,
  33819. width: level.width,
  33820. height: level.height,
  33821. codecSet: level.codecSet,
  33822. audioCodec: level.audioCodec,
  33823. videoCodec: level.videoCodec,
  33824. audioGroups: level.audioGroups,
  33825. subtitleGroups: level.subtitleGroups,
  33826. loaded: level.loaded,
  33827. loadError: level.loadError,
  33828. fragmentError: level.fragmentError,
  33829. name: level.name,
  33830. id: level.id,
  33831. uri: level.uri,
  33832. url: level.url,
  33833. urlId: 0,
  33834. audioGroupIds: level.audioGroupIds,
  33835. textGroupIds: level.textGroupIds
  33836. };
  33837. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  33838. const levelDetails = level.details;
  33839. if (!levelDetails || levelDetails.live) {
  33840. const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  33841. this.loadPlaylist(hlsUrlParameters);
  33842. }
  33843. }
  33844. get manualLevel() {
  33845. return this.manualLevelIndex;
  33846. }
  33847. set manualLevel(newLevel) {
  33848. this.manualLevelIndex = newLevel;
  33849. if (this._startLevel === void 0) {
  33850. this._startLevel = newLevel;
  33851. }
  33852. if (newLevel !== -1) {
  33853. this.level = newLevel;
  33854. }
  33855. }
  33856. get firstLevel() {
  33857. return this._firstLevel;
  33858. }
  33859. set firstLevel(newLevel) {
  33860. this._firstLevel = newLevel;
  33861. }
  33862. get startLevel() {
  33863. if (this._startLevel === void 0) {
  33864. const configStartLevel = this.hls.config.startLevel;
  33865. if (configStartLevel !== void 0) {
  33866. return configStartLevel;
  33867. }
  33868. return this.hls.firstAutoLevel;
  33869. }
  33870. return this._startLevel;
  33871. }
  33872. set startLevel(newLevel) {
  33873. this._startLevel = newLevel;
  33874. }
  33875. get pathways() {
  33876. if (this.steering) {
  33877. return this.steering.pathways();
  33878. }
  33879. return [];
  33880. }
  33881. get pathwayPriority() {
  33882. if (this.steering) {
  33883. return this.steering.pathwayPriority;
  33884. }
  33885. return null;
  33886. }
  33887. set pathwayPriority(pathwayPriority) {
  33888. if (this.steering) {
  33889. const pathwaysList = this.steering.pathways();
  33890. const filteredPathwayPriority = pathwayPriority.filter((pathwayId) => {
  33891. return pathwaysList.indexOf(pathwayId) !== -1;
  33892. });
  33893. if (pathwayPriority.length < 1) {
  33894. this.warn(`pathwayPriority ${pathwayPriority} should contain at least one pathway from list: ${pathwaysList}`);
  33895. return;
  33896. }
  33897. this.steering.pathwayPriority = filteredPathwayPriority;
  33898. }
  33899. }
  33900. onError(event, data) {
  33901. if (data.fatal || !data.context) {
  33902. return;
  33903. }
  33904. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  33905. this.checkRetry(data);
  33906. }
  33907. }
  33908. // reset errors on the successful load of a fragment
  33909. onFragBuffered(event, {
  33910. frag
  33911. }) {
  33912. if (frag !== void 0 && frag.type === PlaylistLevelType.MAIN) {
  33913. const el = frag.elementaryStreams;
  33914. if (!Object.keys(el).some((type) => !!el[type])) {
  33915. return;
  33916. }
  33917. const level = this._levels[frag.level];
  33918. if (level != null && level.loadError) {
  33919. this.log(`Resetting level error count of ${level.loadError} on frag buffered`);
  33920. level.loadError = 0;
  33921. }
  33922. }
  33923. }
  33924. onLevelLoaded(event, data) {
  33925. var _data$deliveryDirecti2;
  33926. const {
  33927. level,
  33928. details
  33929. } = data;
  33930. const curLevel = data.levelInfo;
  33931. if (!curLevel) {
  33932. var _data$deliveryDirecti;
  33933. this.warn(`Invalid level index ${level}`);
  33934. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  33935. details.deltaUpdateFailed = true;
  33936. }
  33937. return;
  33938. }
  33939. if (curLevel === this.currentLevel || data.withoutMultiVariant) {
  33940. if (curLevel.fragmentError === 0) {
  33941. curLevel.loadError = 0;
  33942. }
  33943. let previousDetails = curLevel.details;
  33944. if (previousDetails === data.details && previousDetails.advanced) {
  33945. previousDetails = void 0;
  33946. }
  33947. this.playlistLoaded(level, data, previousDetails);
  33948. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  33949. details.deltaUpdateFailed = true;
  33950. }
  33951. }
  33952. loadPlaylist(hlsUrlParameters) {
  33953. super.loadPlaylist();
  33954. if (this.shouldLoadPlaylist(this.currentLevel)) {
  33955. this.scheduleLoading(this.currentLevel, hlsUrlParameters);
  33956. }
  33957. }
  33958. loadingPlaylist(currentLevel, hlsUrlParameters) {
  33959. super.loadingPlaylist(currentLevel, hlsUrlParameters);
  33960. const url2 = this.getUrlWithDirectives(currentLevel.uri, hlsUrlParameters);
  33961. const currentLevelIndex = this.currentLevelIndex;
  33962. const pathwayId = currentLevel.attrs["PATHWAY-ID"];
  33963. const details = currentLevel.details;
  33964. const age = details == null ? void 0 : details.age;
  33965. 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 || "" : "") : ""} ${url2}`);
  33966. this.hls.trigger(Events.LEVEL_LOADING, {
  33967. url: url2,
  33968. level: currentLevelIndex,
  33969. levelInfo: currentLevel,
  33970. pathwayId: currentLevel.attrs["PATHWAY-ID"],
  33971. id: 0,
  33972. // Deprecated Level urlId
  33973. deliveryDirectives: hlsUrlParameters || null
  33974. });
  33975. }
  33976. get nextLoadLevel() {
  33977. if (this.manualLevelIndex !== -1) {
  33978. return this.manualLevelIndex;
  33979. } else {
  33980. return this.hls.nextAutoLevel;
  33981. }
  33982. }
  33983. set nextLoadLevel(nextLevel) {
  33984. this.level = nextLevel;
  33985. if (this.manualLevelIndex === -1) {
  33986. this.hls.nextAutoLevel = nextLevel;
  33987. }
  33988. }
  33989. removeLevel(levelIndex) {
  33990. var _this$currentLevel;
  33991. if (this._levels.length === 1) {
  33992. return;
  33993. }
  33994. const levels = this._levels.filter((level, index2) => {
  33995. if (index2 !== levelIndex) {
  33996. return true;
  33997. }
  33998. if (this.steering) {
  33999. this.steering.removeLevel(level);
  34000. }
  34001. if (level === this.currentLevel) {
  34002. this.currentLevel = null;
  34003. this.currentLevelIndex = -1;
  34004. if (level.details) {
  34005. level.details.fragments.forEach((f2) => f2.level = -1);
  34006. }
  34007. }
  34008. return false;
  34009. });
  34010. reassignFragmentLevelIndexes(levels);
  34011. this._levels = levels;
  34012. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  34013. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  34014. }
  34015. if (this.manualLevelIndex > -1) {
  34016. this.manualLevelIndex = this.currentLevelIndex;
  34017. }
  34018. const maxLevel = levels.length - 1;
  34019. this._firstLevel = Math.min(this._firstLevel, maxLevel);
  34020. if (this._startLevel) {
  34021. this._startLevel = Math.min(this._startLevel, maxLevel);
  34022. }
  34023. this.hls.trigger(Events.LEVELS_UPDATED, {
  34024. levels
  34025. });
  34026. }
  34027. onLevelsUpdated(event, {
  34028. levels
  34029. }) {
  34030. this._levels = levels;
  34031. }
  34032. checkMaxAutoUpdated() {
  34033. const {
  34034. autoLevelCapping,
  34035. maxAutoLevel,
  34036. maxHdcpLevel
  34037. } = this.hls;
  34038. if (this._maxAutoLevel !== maxAutoLevel) {
  34039. this._maxAutoLevel = maxAutoLevel;
  34040. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  34041. autoLevelCapping,
  34042. levels: this.levels,
  34043. maxAutoLevel,
  34044. minAutoLevel: this.hls.minAutoLevel,
  34045. maxHdcpLevel
  34046. });
  34047. }
  34048. }
  34049. }
  34050. function assignTrackIdsByGroup(tracks) {
  34051. const groups = {};
  34052. tracks.forEach((track) => {
  34053. const groupId = track.groupId || "";
  34054. track.id = groups[groupId] = groups[groupId] || 0;
  34055. groups[groupId]++;
  34056. });
  34057. }
  34058. function getSourceBuffer() {
  34059. return self.SourceBuffer || self.WebKitSourceBuffer;
  34060. }
  34061. function isMSESupported() {
  34062. const mediaSource = getMediaSource();
  34063. if (!mediaSource) {
  34064. return false;
  34065. }
  34066. const sourceBuffer = getSourceBuffer();
  34067. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === "function" && typeof sourceBuffer.prototype.remove === "function";
  34068. }
  34069. function isSupported() {
  34070. if (!isMSESupported()) {
  34071. return false;
  34072. }
  34073. const mediaSource = getMediaSource();
  34074. 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"))));
  34075. }
  34076. function changeTypeSupported() {
  34077. var _sourceBuffer$prototy;
  34078. const sourceBuffer = getSourceBuffer();
  34079. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === "function";
  34080. }
  34081. const TICK_INTERVAL = 100;
  34082. class StreamController extends BaseStreamController {
  34083. constructor(hls, fragmentTracker, keyLoader) {
  34084. super(hls, fragmentTracker, keyLoader, "stream-controller", PlaylistLevelType.MAIN);
  34085. this.audioCodecSwap = false;
  34086. this.level = -1;
  34087. this._forceStartLoad = false;
  34088. this._hasEnoughToStart = false;
  34089. this.altAudio = 0;
  34090. this.audioOnly = false;
  34091. this.fragPlaying = null;
  34092. this.fragLastKbps = 0;
  34093. this.couldBacktrack = false;
  34094. this.backtrackFragment = null;
  34095. this.audioCodecSwitch = false;
  34096. this.videoBuffer = null;
  34097. this.onMediaPlaying = () => {
  34098. this.tick();
  34099. };
  34100. this.onMediaSeeked = () => {
  34101. const media = this.media;
  34102. const currentTime = media ? media.currentTime : null;
  34103. if (currentTime === null || !isFiniteNumber(currentTime)) {
  34104. return;
  34105. }
  34106. this.log(`Media seeked to ${currentTime.toFixed(3)}`);
  34107. if (!this.getBufferedFrag(currentTime)) {
  34108. return;
  34109. }
  34110. const bufferInfo = this.getFwdBufferInfoAtPos(media, currentTime, PlaylistLevelType.MAIN, 0);
  34111. if (bufferInfo === null || bufferInfo.len === 0) {
  34112. this.warn(`Main forward buffer length at ${currentTime} on "seeked" event ${bufferInfo ? bufferInfo.len : "empty"})`);
  34113. return;
  34114. }
  34115. this.tick();
  34116. };
  34117. this.registerListeners();
  34118. }
  34119. registerListeners() {
  34120. super.registerListeners();
  34121. const {
  34122. hls
  34123. } = this;
  34124. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  34125. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  34126. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  34127. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  34128. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  34129. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  34130. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  34131. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  34132. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  34133. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  34134. }
  34135. unregisterListeners() {
  34136. super.unregisterListeners();
  34137. const {
  34138. hls
  34139. } = this;
  34140. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  34141. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  34142. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  34143. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  34144. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  34145. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  34146. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  34147. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  34148. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  34149. }
  34150. onHandlerDestroying() {
  34151. this.onMediaPlaying = this.onMediaSeeked = null;
  34152. this.unregisterListeners();
  34153. super.onHandlerDestroying();
  34154. }
  34155. startLoad(startPosition, skipSeekToStartPosition) {
  34156. if (this.levels) {
  34157. const {
  34158. lastCurrentTime,
  34159. hls
  34160. } = this;
  34161. this.stopLoad();
  34162. this.setInterval(TICK_INTERVAL);
  34163. this.level = -1;
  34164. if (!this.startFragRequested) {
  34165. let startLevel = hls.startLevel;
  34166. if (startLevel === -1) {
  34167. if (hls.config.testBandwidth && this.levels.length > 1) {
  34168. startLevel = 0;
  34169. this.bitrateTest = true;
  34170. } else {
  34171. startLevel = hls.firstAutoLevel;
  34172. }
  34173. }
  34174. hls.nextLoadLevel = startLevel;
  34175. this.level = hls.loadLevel;
  34176. this._hasEnoughToStart = !!skipSeekToStartPosition;
  34177. }
  34178. if (lastCurrentTime > 0 && startPosition === -1 && !skipSeekToStartPosition) {
  34179. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  34180. startPosition = lastCurrentTime;
  34181. }
  34182. this.state = State.IDLE;
  34183. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  34184. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  34185. this.tick();
  34186. } else {
  34187. this._forceStartLoad = true;
  34188. this.state = State.STOPPED;
  34189. }
  34190. }
  34191. stopLoad() {
  34192. this._forceStartLoad = false;
  34193. super.stopLoad();
  34194. }
  34195. doTick() {
  34196. switch (this.state) {
  34197. case State.WAITING_LEVEL: {
  34198. const {
  34199. levels,
  34200. level
  34201. } = this;
  34202. const currentLevel = levels == null ? void 0 : levels[level];
  34203. const details = currentLevel == null ? void 0 : currentLevel.details;
  34204. if (details && (!details.live || this.levelLastLoaded === currentLevel && !this.waitForLive(currentLevel))) {
  34205. if (this.waitForCdnTuneIn(details)) {
  34206. break;
  34207. }
  34208. this.state = State.IDLE;
  34209. break;
  34210. } else if (this.hls.nextLoadLevel !== this.level) {
  34211. this.state = State.IDLE;
  34212. break;
  34213. }
  34214. break;
  34215. }
  34216. case State.FRAG_LOADING_WAITING_RETRY:
  34217. {
  34218. var _this$media;
  34219. const now2 = self.performance.now();
  34220. const retryDate = this.retryDate;
  34221. if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  34222. const {
  34223. levels,
  34224. level
  34225. } = this;
  34226. const currentLevel = levels == null ? void 0 : levels[level];
  34227. this.resetStartWhenNotLoaded(currentLevel || null);
  34228. this.state = State.IDLE;
  34229. }
  34230. }
  34231. break;
  34232. }
  34233. if (this.state === State.IDLE) {
  34234. this.doTickIdle();
  34235. }
  34236. this.onTickEnd();
  34237. }
  34238. onTickEnd() {
  34239. var _this$media2;
  34240. super.onTickEnd();
  34241. if ((_this$media2 = this.media) != null && _this$media2.readyState && this.media.seeking === false) {
  34242. this.lastCurrentTime = this.media.currentTime;
  34243. }
  34244. this.checkFragmentChanged();
  34245. }
  34246. doTickIdle() {
  34247. const {
  34248. hls,
  34249. levelLastLoaded,
  34250. levels,
  34251. media
  34252. } = this;
  34253. if (levelLastLoaded === null || !media && !this.primaryPrefetch && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  34254. return;
  34255. }
  34256. if (this.altAudio && this.audioOnly) {
  34257. return;
  34258. }
  34259. const level = this.buffering ? hls.nextLoadLevel : hls.loadLevel;
  34260. if (!(levels != null && levels[level])) {
  34261. return;
  34262. }
  34263. const levelInfo = levels[level];
  34264. const bufferInfo = this.getMainFwdBufferInfo();
  34265. if (bufferInfo === null) {
  34266. return;
  34267. }
  34268. const lastDetails = this.getLevelDetails();
  34269. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  34270. const data = {};
  34271. if (this.altAudio === 2) {
  34272. data.type = "video";
  34273. }
  34274. this.hls.trigger(Events.BUFFER_EOS, data);
  34275. this.state = State.ENDED;
  34276. return;
  34277. }
  34278. if (!this.buffering) {
  34279. return;
  34280. }
  34281. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  34282. this.log(`Adapting to level ${level} from level ${this.level}`);
  34283. }
  34284. this.level = hls.nextLoadLevel = level;
  34285. const levelDetails = levelInfo.details;
  34286. if (!levelDetails || this.state === State.WAITING_LEVEL || this.waitForLive(levelInfo)) {
  34287. this.level = level;
  34288. this.state = State.WAITING_LEVEL;
  34289. this.startFragRequested = false;
  34290. return;
  34291. }
  34292. const bufferLen = bufferInfo.len;
  34293. const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  34294. if (bufferLen >= maxBufLen) {
  34295. return;
  34296. }
  34297. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  34298. this.backtrackFragment = null;
  34299. }
  34300. const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  34301. let frag = this.getNextFragment(targetBufferTime, levelDetails);
  34302. if (this.couldBacktrack && !this.fragPrevious && frag && isMediaFragment(frag) && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  34303. var _this$backtrackFragme;
  34304. const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  34305. const fragIdx = backtrackSn - levelDetails.startSN;
  34306. const backtrackFrag = levelDetails.fragments[fragIdx - 1];
  34307. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  34308. frag = backtrackFrag;
  34309. this.fragmentTracker.removeFragment(backtrackFrag);
  34310. }
  34311. } else if (this.backtrackFragment && bufferInfo.len) {
  34312. this.backtrackFragment = null;
  34313. }
  34314. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  34315. const gapStart = frag.gap;
  34316. if (!gapStart) {
  34317. const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  34318. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  34319. if (mediaBuffer) {
  34320. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  34321. }
  34322. }
  34323. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  34324. }
  34325. if (!frag) {
  34326. return;
  34327. }
  34328. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  34329. frag = frag.initSegment;
  34330. }
  34331. this.loadFragment(frag, levelInfo, targetBufferTime);
  34332. }
  34333. loadFragment(frag, level, targetBufferTime) {
  34334. const fragState = this.fragmentTracker.getState(frag);
  34335. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  34336. if (!isMediaFragment(frag)) {
  34337. this._loadInitSegment(frag, level);
  34338. } else if (this.bitrateTest) {
  34339. this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);
  34340. this._loadBitrateTestFrag(frag, level);
  34341. } else {
  34342. super.loadFragment(frag, level, targetBufferTime);
  34343. }
  34344. } else {
  34345. this.clearTrackerIfNeeded(frag);
  34346. }
  34347. }
  34348. getBufferedFrag(position) {
  34349. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  34350. }
  34351. followingBufferedFrag(frag) {
  34352. if (frag) {
  34353. return this.getBufferedFrag(frag.end + 0.5);
  34354. }
  34355. return null;
  34356. }
  34357. /*
  34358. on immediate level switch :
  34359. - pause playback if playing
  34360. - cancel any pending load request
  34361. - and trigger a buffer flush
  34362. */
  34363. immediateLevelSwitch() {
  34364. this.abortCurrentFrag();
  34365. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  34366. }
  34367. /**
  34368. * try to switch ASAP without breaking video playback:
  34369. * in order to ensure smooth but quick level switching,
  34370. * we need to find the next flushable buffer range
  34371. * we should take into account new segment fetch time
  34372. */
  34373. nextLevelSwitch() {
  34374. const {
  34375. levels,
  34376. media
  34377. } = this;
  34378. if (media != null && media.readyState) {
  34379. let fetchdelay;
  34380. const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  34381. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  34382. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  34383. }
  34384. const levelDetails = this.getLevelDetails();
  34385. if (levelDetails != null && levelDetails.live) {
  34386. const bufferInfo = this.getMainFwdBufferInfo();
  34387. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  34388. return;
  34389. }
  34390. }
  34391. if (!media.paused && levels) {
  34392. const nextLevelId = this.hls.nextLoadLevel;
  34393. const nextLevel = levels[nextLevelId];
  34394. const fragLastKbps = this.fragLastKbps;
  34395. if (fragLastKbps && this.fragCurrent) {
  34396. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1e3 * fragLastKbps) + 1;
  34397. } else {
  34398. fetchdelay = 0;
  34399. }
  34400. } else {
  34401. fetchdelay = 0;
  34402. }
  34403. const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  34404. if (bufferedFrag) {
  34405. const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  34406. if (nextBufferedFrag) {
  34407. this.abortCurrentFrag();
  34408. const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  34409. const fragDuration = nextBufferedFrag.duration;
  34410. 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)));
  34411. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  34412. }
  34413. }
  34414. }
  34415. }
  34416. abortCurrentFrag() {
  34417. const fragCurrent = this.fragCurrent;
  34418. this.fragCurrent = null;
  34419. this.backtrackFragment = null;
  34420. if (fragCurrent) {
  34421. fragCurrent.abortRequests();
  34422. this.fragmentTracker.removeFragment(fragCurrent);
  34423. }
  34424. switch (this.state) {
  34425. case State.KEY_LOADING:
  34426. case State.FRAG_LOADING:
  34427. case State.FRAG_LOADING_WAITING_RETRY:
  34428. case State.PARSING:
  34429. case State.PARSED:
  34430. this.state = State.IDLE;
  34431. break;
  34432. }
  34433. this.nextLoadPosition = this.getLoadPosition();
  34434. }
  34435. flushMainBuffer(startOffset, endOffset) {
  34436. super.flushMainBuffer(startOffset, endOffset, this.altAudio === 2 ? "video" : null);
  34437. }
  34438. onMediaAttached(event, data) {
  34439. super.onMediaAttached(event, data);
  34440. const media = data.media;
  34441. addEventListener(media, "playing", this.onMediaPlaying);
  34442. addEventListener(media, "seeked", this.onMediaSeeked);
  34443. }
  34444. onMediaDetaching(event, data) {
  34445. const {
  34446. media
  34447. } = this;
  34448. if (media) {
  34449. removeEventListener(media, "playing", this.onMediaPlaying);
  34450. removeEventListener(media, "seeked", this.onMediaSeeked);
  34451. }
  34452. this.videoBuffer = null;
  34453. this.fragPlaying = null;
  34454. super.onMediaDetaching(event, data);
  34455. const transferringMedia = !!data.transferMedia;
  34456. if (transferringMedia) {
  34457. return;
  34458. }
  34459. this._hasEnoughToStart = false;
  34460. }
  34461. onManifestLoading() {
  34462. super.onManifestLoading();
  34463. this.log("Trigger BUFFER_RESET");
  34464. this.hls.trigger(Events.BUFFER_RESET, void 0);
  34465. this.couldBacktrack = false;
  34466. this.fragLastKbps = 0;
  34467. this.fragPlaying = this.backtrackFragment = null;
  34468. this.altAudio = 0;
  34469. this.audioOnly = false;
  34470. }
  34471. onManifestParsed(event, data) {
  34472. let aac = false;
  34473. let heaac = false;
  34474. data.levels.forEach((level) => {
  34475. const codec = level.audioCodec;
  34476. if (codec) {
  34477. aac = aac || codec.indexOf("mp4a.40.2") !== -1;
  34478. heaac = heaac || codec.indexOf("mp4a.40.5") !== -1;
  34479. }
  34480. });
  34481. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  34482. if (this.audioCodecSwitch) {
  34483. this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC");
  34484. }
  34485. this.levels = data.levels;
  34486. this.startFragRequested = false;
  34487. }
  34488. onLevelLoading(event, data) {
  34489. const {
  34490. levels
  34491. } = this;
  34492. if (!levels || this.state !== State.IDLE) {
  34493. return;
  34494. }
  34495. const level = data.levelInfo;
  34496. if (!level.details || level.details.live && (this.levelLastLoaded !== level || level.details.expired) || this.waitForCdnTuneIn(level.details)) {
  34497. this.state = State.WAITING_LEVEL;
  34498. }
  34499. }
  34500. onLevelLoaded(event, data) {
  34501. var _curLevel$details;
  34502. const {
  34503. levels,
  34504. startFragRequested
  34505. } = this;
  34506. const newLevelId = data.level;
  34507. const newDetails = data.details;
  34508. const duration = newDetails.totalduration;
  34509. if (!levels) {
  34510. this.warn(`Levels were reset while loading level ${newLevelId}`);
  34511. return;
  34512. }
  34513. this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`);
  34514. const curLevel = data.levelInfo;
  34515. const fragCurrent = this.fragCurrent;
  34516. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  34517. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  34518. this.abortCurrentFrag();
  34519. }
  34520. }
  34521. let sliding = 0;
  34522. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  34523. var _this$levelLastLoaded;
  34524. this.checkLiveUpdate(newDetails);
  34525. if (newDetails.deltaUpdateFailed) {
  34526. return;
  34527. }
  34528. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  34529. }
  34530. curLevel.details = newDetails;
  34531. this.levelLastLoaded = curLevel;
  34532. if (!startFragRequested) {
  34533. this.setStartPosition(newDetails, sliding);
  34534. }
  34535. this.hls.trigger(Events.LEVEL_UPDATED, {
  34536. details: newDetails,
  34537. level: newLevelId
  34538. });
  34539. if (this.state === State.WAITING_LEVEL) {
  34540. if (this.waitForCdnTuneIn(newDetails)) {
  34541. return;
  34542. }
  34543. this.state = State.IDLE;
  34544. }
  34545. if (startFragRequested && newDetails.live) {
  34546. this.synchronizeToLiveEdge(newDetails);
  34547. }
  34548. this.tick();
  34549. }
  34550. synchronizeToLiveEdge(levelDetails) {
  34551. const {
  34552. config: config2,
  34553. media
  34554. } = this;
  34555. if (!media) {
  34556. return;
  34557. }
  34558. const liveSyncPosition = this.hls.liveSyncPosition;
  34559. const currentTime = this.getLoadPosition();
  34560. const start = levelDetails.fragmentStart;
  34561. const end = levelDetails.edge;
  34562. const withinSlidingWindow = currentTime >= start - config2.maxFragLookUpTolerance && currentTime <= end;
  34563. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  34564. const maxLatency = config2.liveMaxLatencyDuration !== void 0 ? config2.liveMaxLatencyDuration : config2.liveMaxLatencyDurationCount * levelDetails.targetduration;
  34565. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  34566. if (!this._hasEnoughToStart) {
  34567. this.nextLoadPosition = liveSyncPosition;
  34568. }
  34569. if (media.readyState) {
  34570. this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
  34571. if (this.config.liveSyncMode === "buffered") {
  34572. var _bufferInfo$buffered;
  34573. const bufferInfo = BufferHelper.bufferInfo(media, liveSyncPosition, 0);
  34574. if (!(bufferInfo != null && (_bufferInfo$buffered = bufferInfo.buffered) != null && _bufferInfo$buffered.length)) {
  34575. media.currentTime = liveSyncPosition;
  34576. return;
  34577. }
  34578. const isLiveSyncInBuffer = bufferInfo.start <= currentTime;
  34579. if (isLiveSyncInBuffer) {
  34580. media.currentTime = liveSyncPosition;
  34581. return;
  34582. }
  34583. const {
  34584. nextStart
  34585. } = BufferHelper.bufferedInfo(bufferInfo.buffered, currentTime, 0);
  34586. if (nextStart) {
  34587. media.currentTime = nextStart;
  34588. }
  34589. } else {
  34590. media.currentTime = liveSyncPosition;
  34591. }
  34592. }
  34593. }
  34594. }
  34595. }
  34596. _handleFragmentLoadProgress(data) {
  34597. var _frag$initSegment;
  34598. const frag = data.frag;
  34599. const {
  34600. part,
  34601. payload
  34602. } = data;
  34603. const {
  34604. levels
  34605. } = this;
  34606. if (!levels) {
  34607. this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  34608. return;
  34609. }
  34610. const currentLevel = levels[frag.level];
  34611. if (!currentLevel) {
  34612. this.warn(`Level ${frag.level} not found on progress`);
  34613. return;
  34614. }
  34615. const details = currentLevel.details;
  34616. if (!details) {
  34617. this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);
  34618. this.fragmentTracker.removeFragment(frag);
  34619. return;
  34620. }
  34621. const videoCodec = currentLevel.videoCodec;
  34622. const accurateTimeOffset = details.PTSKnown || !details.live;
  34623. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  34624. const audioCodec = this._getAudioCodec(currentLevel);
  34625. const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  34626. const partIndex = part ? part.index : -1;
  34627. const partial2 = partIndex !== -1;
  34628. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial2);
  34629. const initPTS = this.initPTS[frag.cc];
  34630. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  34631. }
  34632. onAudioTrackSwitching(event, data) {
  34633. const hls = this.hls;
  34634. const fromAltAudio = this.altAudio === 2;
  34635. const altAudio = useAlternateAudio(data.url, hls);
  34636. if (!altAudio) {
  34637. if (this.mediaBuffer !== this.media) {
  34638. this.log("Switching on main audio, use media.buffered to schedule main fragment loading");
  34639. this.mediaBuffer = this.media;
  34640. const fragCurrent = this.fragCurrent;
  34641. if (fragCurrent) {
  34642. this.log("Switching to main audio track, cancel main fragment load");
  34643. fragCurrent.abortRequests();
  34644. this.fragmentTracker.removeFragment(fragCurrent);
  34645. }
  34646. this.resetTransmuxer();
  34647. this.resetLoadingState();
  34648. } else if (this.audioOnly) {
  34649. this.resetTransmuxer();
  34650. }
  34651. if (fromAltAudio) {
  34652. this.fragmentTracker.removeAllFragments();
  34653. hls.once(Events.BUFFER_FLUSHED, () => {
  34654. var _this$hls;
  34655. (_this$hls = this.hls) == null ? void 0 : _this$hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  34656. });
  34657. hls.trigger(Events.BUFFER_FLUSHING, {
  34658. startOffset: 0,
  34659. endOffset: Number.POSITIVE_INFINITY,
  34660. type: null
  34661. });
  34662. return;
  34663. }
  34664. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  34665. } else {
  34666. this.altAudio = 1;
  34667. }
  34668. }
  34669. onAudioTrackSwitched(event, data) {
  34670. const altAudio = useAlternateAudio(data.url, this.hls);
  34671. if (altAudio) {
  34672. const videoBuffer = this.videoBuffer;
  34673. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  34674. this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading");
  34675. this.mediaBuffer = videoBuffer;
  34676. }
  34677. }
  34678. this.altAudio = altAudio ? 2 : 0;
  34679. this.tick();
  34680. }
  34681. onBufferCreated(event, data) {
  34682. const tracks = data.tracks;
  34683. let mediaTrack;
  34684. let name;
  34685. let alternate = false;
  34686. for (const type in tracks) {
  34687. const track = tracks[type];
  34688. if (track.id === "main") {
  34689. name = type;
  34690. mediaTrack = track;
  34691. if (type === "video") {
  34692. const videoTrack = tracks[type];
  34693. if (videoTrack) {
  34694. this.videoBuffer = videoTrack.buffer;
  34695. }
  34696. }
  34697. } else {
  34698. alternate = true;
  34699. }
  34700. }
  34701. if (alternate && mediaTrack) {
  34702. this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);
  34703. this.mediaBuffer = mediaTrack.buffer;
  34704. } else {
  34705. this.mediaBuffer = this.media;
  34706. }
  34707. }
  34708. onFragBuffered(event, data) {
  34709. const {
  34710. frag,
  34711. part
  34712. } = data;
  34713. const bufferedMainFragment = frag.type === PlaylistLevelType.MAIN;
  34714. if (bufferedMainFragment) {
  34715. if (this.fragContextChanged(frag)) {
  34716. this.warn(`Fragment ${frag.sn}${part ? " p: " + part.index : ""} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);
  34717. if (this.state === State.PARSED) {
  34718. this.state = State.IDLE;
  34719. }
  34720. return;
  34721. }
  34722. const stats = part ? part.stats : frag.stats;
  34723. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  34724. if (isMediaFragment(frag)) {
  34725. this.fragPrevious = frag;
  34726. }
  34727. this.fragBufferedComplete(frag, part);
  34728. }
  34729. const media = this.media;
  34730. if (!media) {
  34731. return;
  34732. }
  34733. if (!this._hasEnoughToStart && BufferHelper.getBuffered(media).length) {
  34734. this._hasEnoughToStart = true;
  34735. this.seekToStartPos();
  34736. }
  34737. if (bufferedMainFragment) {
  34738. this.tick();
  34739. }
  34740. }
  34741. get hasEnoughToStart() {
  34742. return this._hasEnoughToStart;
  34743. }
  34744. onError(event, data) {
  34745. var _data$context;
  34746. if (data.fatal) {
  34747. this.state = State.ERROR;
  34748. return;
  34749. }
  34750. switch (data.details) {
  34751. case ErrorDetails.FRAG_GAP:
  34752. case ErrorDetails.FRAG_PARSING_ERROR:
  34753. case ErrorDetails.FRAG_DECRYPT_ERROR:
  34754. case ErrorDetails.FRAG_LOAD_ERROR:
  34755. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  34756. case ErrorDetails.KEY_LOAD_ERROR:
  34757. case ErrorDetails.KEY_LOAD_TIMEOUT:
  34758. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  34759. break;
  34760. case ErrorDetails.LEVEL_LOAD_ERROR:
  34761. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  34762. case ErrorDetails.LEVEL_PARSING_ERROR:
  34763. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  34764. this.state = State.IDLE;
  34765. }
  34766. break;
  34767. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  34768. case ErrorDetails.BUFFER_APPEND_ERROR:
  34769. if (data.parent !== "main") {
  34770. return;
  34771. }
  34772. if (this.reduceLengthAndFlushBuffer(data)) {
  34773. this.resetLoadingState();
  34774. }
  34775. break;
  34776. case ErrorDetails.BUFFER_FULL_ERROR:
  34777. if (data.parent !== "main") {
  34778. return;
  34779. }
  34780. if (this.reduceLengthAndFlushBuffer(data)) {
  34781. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  34782. }
  34783. break;
  34784. case ErrorDetails.INTERNAL_EXCEPTION:
  34785. this.recoverWorkerError(data);
  34786. break;
  34787. }
  34788. }
  34789. onFragLoadEmergencyAborted() {
  34790. this.state = State.IDLE;
  34791. if (!this._hasEnoughToStart) {
  34792. this.startFragRequested = false;
  34793. this.nextLoadPosition = this.lastCurrentTime;
  34794. }
  34795. this.tickImmediate();
  34796. }
  34797. onBufferFlushed(event, {
  34798. type
  34799. }) {
  34800. if (type !== ElementaryStreamTypes.AUDIO || !this.altAudio) {
  34801. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  34802. if (mediaBuffer) {
  34803. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  34804. this.tick();
  34805. }
  34806. }
  34807. }
  34808. onLevelsUpdated(event, data) {
  34809. if (this.level > -1 && this.fragCurrent) {
  34810. this.level = this.fragCurrent.level;
  34811. if (this.level === -1) {
  34812. this.resetWhenMissingContext(this.fragCurrent);
  34813. }
  34814. }
  34815. this.levels = data.levels;
  34816. }
  34817. swapAudioCodec() {
  34818. this.audioCodecSwap = !this.audioCodecSwap;
  34819. }
  34820. /**
  34821. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  34822. */
  34823. seekToStartPos() {
  34824. const {
  34825. media
  34826. } = this;
  34827. if (!media) {
  34828. return;
  34829. }
  34830. const currentTime = media.currentTime;
  34831. let startPosition = this.startPosition;
  34832. if (startPosition >= 0 && currentTime < startPosition) {
  34833. if (media.seeking) {
  34834. this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
  34835. return;
  34836. }
  34837. const timelineOffset = this.timelineOffset;
  34838. if (timelineOffset && startPosition) {
  34839. startPosition += timelineOffset;
  34840. }
  34841. const details = this.getLevelDetails();
  34842. const buffered = BufferHelper.getBuffered(media);
  34843. const bufferStart = buffered.length ? buffered.start(0) : 0;
  34844. const delta = bufferStart - startPosition;
  34845. const skipTolerance = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
  34846. if (this.config.startOnSegmentBoundary || delta > 0 && (delta < skipTolerance || this.loadingParts && delta < 2 * ((details == null ? void 0 : details.partTarget) || 0))) {
  34847. this.log(`adjusting start position by ${delta} to match buffer start`);
  34848. startPosition += delta;
  34849. this.startPosition = startPosition;
  34850. }
  34851. if (currentTime < startPosition) {
  34852. this.log(`seek to target start position ${startPosition} from current time ${currentTime} buffer start ${bufferStart}`);
  34853. media.currentTime = startPosition;
  34854. }
  34855. }
  34856. }
  34857. _getAudioCodec(currentLevel) {
  34858. let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  34859. if (this.audioCodecSwap && audioCodec) {
  34860. this.log("Swapping audio codec");
  34861. if (audioCodec.indexOf("mp4a.40.5") !== -1) {
  34862. audioCodec = "mp4a.40.2";
  34863. } else {
  34864. audioCodec = "mp4a.40.5";
  34865. }
  34866. }
  34867. return audioCodec;
  34868. }
  34869. _loadBitrateTestFrag(fragment, level) {
  34870. fragment.bitrateTest = true;
  34871. this._doFragLoad(fragment, level).then((data) => {
  34872. const {
  34873. hls
  34874. } = this;
  34875. const frag = data == null ? void 0 : data.frag;
  34876. if (!frag || this.fragContextChanged(frag)) {
  34877. return;
  34878. }
  34879. level.fragmentError = 0;
  34880. this.state = State.IDLE;
  34881. this.startFragRequested = false;
  34882. this.bitrateTest = false;
  34883. const stats = frag.stats;
  34884. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  34885. hls.trigger(Events.FRAG_LOADED, data);
  34886. frag.bitrateTest = false;
  34887. });
  34888. }
  34889. _handleTransmuxComplete(transmuxResult) {
  34890. var _id3$samples;
  34891. const id = this.playlistType;
  34892. const {
  34893. hls
  34894. } = this;
  34895. const {
  34896. remuxResult,
  34897. chunkMeta
  34898. } = transmuxResult;
  34899. const context = this.getCurrentContext(chunkMeta);
  34900. if (!context) {
  34901. this.resetWhenMissingContext(chunkMeta);
  34902. return;
  34903. }
  34904. const {
  34905. frag,
  34906. part,
  34907. level
  34908. } = context;
  34909. const {
  34910. video: video2,
  34911. text,
  34912. id3,
  34913. initSegment
  34914. } = remuxResult;
  34915. const {
  34916. details
  34917. } = level;
  34918. const audio = this.altAudio ? void 0 : remuxResult.audio;
  34919. if (this.fragContextChanged(frag)) {
  34920. this.fragmentTracker.removeFragment(frag);
  34921. return;
  34922. }
  34923. this.state = State.PARSING;
  34924. if (initSegment) {
  34925. if (initSegment != null && initSegment.tracks) {
  34926. const mapFragment = frag.initSegment || frag;
  34927. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  34928. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  34929. frag: mapFragment,
  34930. id,
  34931. tracks: initSegment.tracks
  34932. });
  34933. }
  34934. const baseTime = initSegment.initPTS;
  34935. const timescale = initSegment.timescale;
  34936. const initPTS = this.initPTS[frag.cc];
  34937. if (isFiniteNumber(baseTime) && (!initPTS || initPTS.baseTime !== baseTime || initPTS.timescale !== timescale)) {
  34938. this.initPTS[frag.cc] = {
  34939. baseTime,
  34940. timescale
  34941. };
  34942. hls.trigger(Events.INIT_PTS_FOUND, {
  34943. frag,
  34944. id,
  34945. initPTS: baseTime,
  34946. timescale
  34947. });
  34948. }
  34949. }
  34950. if (video2 && details) {
  34951. if (audio && video2.type === "audiovideo") {
  34952. this.logMuxedErr(frag);
  34953. }
  34954. const prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  34955. const isFirstFragment = frag.sn === details.startSN;
  34956. const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  34957. if (remuxResult.independent !== false) {
  34958. const {
  34959. startPTS,
  34960. endPTS,
  34961. startDTS,
  34962. endDTS
  34963. } = video2;
  34964. if (part) {
  34965. part.elementaryStreams[video2.type] = {
  34966. startPTS,
  34967. endPTS,
  34968. startDTS,
  34969. endDTS
  34970. };
  34971. } else {
  34972. if (video2.firstKeyFrame && video2.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  34973. this.couldBacktrack = true;
  34974. }
  34975. if (video2.dropped && video2.independent) {
  34976. const bufferInfo = this.getMainFwdBufferInfo();
  34977. const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  34978. const startTime = video2.firstKeyFramePTS ? video2.firstKeyFramePTS : startPTS;
  34979. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  34980. this.backtrack(frag);
  34981. return;
  34982. } else if (isFirstInDiscontinuity) {
  34983. frag.gap = true;
  34984. }
  34985. frag.setElementaryStreamInfo(video2.type, frag.start, endPTS, frag.start, endDTS, true);
  34986. } else if (isFirstFragment && startPTS - (details.appliedTimelineOffset || 0) > MAX_START_GAP_JUMP) {
  34987. frag.gap = true;
  34988. }
  34989. }
  34990. frag.setElementaryStreamInfo(video2.type, startPTS, endPTS, startDTS, endDTS);
  34991. if (this.backtrackFragment) {
  34992. this.backtrackFragment = frag;
  34993. }
  34994. this.bufferFragmentData(video2, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  34995. } else if (isFirstFragment || isFirstInDiscontinuity) {
  34996. frag.gap = true;
  34997. } else {
  34998. this.backtrack(frag);
  34999. return;
  35000. }
  35001. }
  35002. if (audio) {
  35003. const {
  35004. startPTS,
  35005. endPTS,
  35006. startDTS,
  35007. endDTS
  35008. } = audio;
  35009. if (part) {
  35010. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  35011. startPTS,
  35012. endPTS,
  35013. startDTS,
  35014. endDTS
  35015. };
  35016. }
  35017. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  35018. this.bufferFragmentData(audio, frag, part, chunkMeta);
  35019. }
  35020. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  35021. const emittedID3 = {
  35022. id,
  35023. frag,
  35024. details,
  35025. samples: id3.samples
  35026. };
  35027. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  35028. }
  35029. if (details && text) {
  35030. const emittedText = {
  35031. id,
  35032. frag,
  35033. details,
  35034. samples: text.samples
  35035. };
  35036. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  35037. }
  35038. }
  35039. logMuxedErr(frag) {
  35040. this.warn(`${isMediaFragment(frag) ? "Media" : "Init"} segment with muxed audiovideo where only video expected: ${frag.url}`);
  35041. }
  35042. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  35043. if (this.state !== State.PARSING) {
  35044. return;
  35045. }
  35046. this.audioOnly = !!tracks.audio && !tracks.video;
  35047. if (this.altAudio && !this.audioOnly) {
  35048. delete tracks.audio;
  35049. if (tracks.audiovideo) {
  35050. this.logMuxedErr(frag);
  35051. }
  35052. }
  35053. const {
  35054. audio,
  35055. video: video2,
  35056. audiovideo
  35057. } = tracks;
  35058. if (audio) {
  35059. const levelCodec = currentLevel.audioCodec;
  35060. let audioCodec = pickMostCompleteCodecName(audio.codec, levelCodec);
  35061. if (audioCodec === "mp4a") {
  35062. audioCodec = "mp4a.40.5";
  35063. }
  35064. const ua = navigator.userAgent.toLowerCase();
  35065. if (this.audioCodecSwitch) {
  35066. if (audioCodec) {
  35067. if (audioCodec.indexOf("mp4a.40.5") !== -1) {
  35068. audioCodec = "mp4a.40.2";
  35069. } else {
  35070. audioCodec = "mp4a.40.5";
  35071. }
  35072. }
  35073. const audioMetadata = audio.metadata;
  35074. if (audioMetadata && "channelCount" in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf("firefox") === -1) {
  35075. audioCodec = "mp4a.40.5";
  35076. }
  35077. }
  35078. if (audioCodec && audioCodec.indexOf("mp4a.40.5") !== -1 && ua.indexOf("android") !== -1 && audio.container !== "audio/mpeg") {
  35079. audioCodec = "mp4a.40.2";
  35080. this.log(`Android: force audio codec to ${audioCodec}`);
  35081. }
  35082. if (levelCodec && levelCodec !== audioCodec) {
  35083. this.log(`Swapping manifest audio codec "${levelCodec}" for "${audioCodec}"`);
  35084. }
  35085. audio.levelCodec = audioCodec;
  35086. audio.id = PlaylistLevelType.MAIN;
  35087. this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ""}/${levelCodec || ""}/${audio.codec}]`);
  35088. delete tracks.audiovideo;
  35089. }
  35090. if (video2) {
  35091. video2.levelCodec = currentLevel.videoCodec;
  35092. video2.id = PlaylistLevelType.MAIN;
  35093. const parsedVideoCodec = video2.codec;
  35094. if ((parsedVideoCodec == null ? void 0 : parsedVideoCodec.length) === 4) {
  35095. switch (parsedVideoCodec) {
  35096. case "hvc1":
  35097. case "hev1":
  35098. video2.codec = "hvc1.1.6.L120.90";
  35099. break;
  35100. case "av01":
  35101. video2.codec = "av01.0.04M.08";
  35102. break;
  35103. case "avc1":
  35104. video2.codec = "avc1.42e01e";
  35105. break;
  35106. }
  35107. }
  35108. this.log(`Init video buffer, container:${video2.container}, codecs[level/parsed]=[${currentLevel.videoCodec || ""}/${parsedVideoCodec}]${video2.codec !== parsedVideoCodec ? " parsed-corrected=" + video2.codec : ""}${video2.supplemental ? " supplemental=" + video2.supplemental : ""}`);
  35109. delete tracks.audiovideo;
  35110. }
  35111. if (audiovideo) {
  35112. this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);
  35113. delete tracks.video;
  35114. delete tracks.audio;
  35115. }
  35116. const trackTypes = Object.keys(tracks);
  35117. if (trackTypes.length) {
  35118. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  35119. if (!this.hls) {
  35120. return;
  35121. }
  35122. trackTypes.forEach((trackName) => {
  35123. const track = tracks[trackName];
  35124. const initSegment = track.initSegment;
  35125. if (initSegment != null && initSegment.byteLength) {
  35126. this.hls.trigger(Events.BUFFER_APPENDING, {
  35127. type: trackName,
  35128. data: initSegment,
  35129. frag,
  35130. part: null,
  35131. chunkMeta,
  35132. parent: frag.type
  35133. });
  35134. }
  35135. });
  35136. }
  35137. this.tickImmediate();
  35138. }
  35139. getMainFwdBufferInfo() {
  35140. const bufferOutput = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
  35141. return this.getFwdBufferInfo(bufferOutput, PlaylistLevelType.MAIN);
  35142. }
  35143. get maxBufferLength() {
  35144. const {
  35145. levels,
  35146. level
  35147. } = this;
  35148. const levelInfo = levels == null ? void 0 : levels[level];
  35149. if (!levelInfo) {
  35150. return this.config.maxBufferLength;
  35151. }
  35152. return this.getMaxBufferLength(levelInfo.maxBitrate);
  35153. }
  35154. backtrack(frag) {
  35155. this.couldBacktrack = true;
  35156. this.backtrackFragment = frag;
  35157. this.resetTransmuxer();
  35158. this.flushBufferGap(frag);
  35159. this.fragmentTracker.removeFragment(frag);
  35160. this.fragPrevious = null;
  35161. this.nextLoadPosition = frag.start;
  35162. this.state = State.IDLE;
  35163. }
  35164. checkFragmentChanged() {
  35165. const video2 = this.media;
  35166. let fragPlayingCurrent = null;
  35167. if (video2 && video2.readyState > 1 && video2.seeking === false) {
  35168. const currentTime = video2.currentTime;
  35169. if (BufferHelper.isBuffered(video2, currentTime)) {
  35170. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  35171. } else if (BufferHelper.isBuffered(video2, currentTime + 0.1)) {
  35172. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  35173. }
  35174. if (fragPlayingCurrent) {
  35175. this.backtrackFragment = null;
  35176. const fragPlaying = this.fragPlaying;
  35177. const fragCurrentLevel = fragPlayingCurrent.level;
  35178. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  35179. this.fragPlaying = fragPlayingCurrent;
  35180. this.hls.trigger(Events.FRAG_CHANGED, {
  35181. frag: fragPlayingCurrent
  35182. });
  35183. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  35184. this.hls.trigger(Events.LEVEL_SWITCHED, {
  35185. level: fragCurrentLevel
  35186. });
  35187. }
  35188. }
  35189. }
  35190. }
  35191. }
  35192. get nextLevel() {
  35193. const frag = this.nextBufferedFrag;
  35194. if (frag) {
  35195. return frag.level;
  35196. }
  35197. return -1;
  35198. }
  35199. get currentFrag() {
  35200. var _this$media3;
  35201. if (this.fragPlaying) {
  35202. return this.fragPlaying;
  35203. }
  35204. const currentTime = ((_this$media3 = this.media) == null ? void 0 : _this$media3.currentTime) || this.lastCurrentTime;
  35205. if (isFiniteNumber(currentTime)) {
  35206. return this.getAppendedFrag(currentTime);
  35207. }
  35208. return null;
  35209. }
  35210. get currentProgramDateTime() {
  35211. var _this$media4;
  35212. const currentTime = ((_this$media4 = this.media) == null ? void 0 : _this$media4.currentTime) || this.lastCurrentTime;
  35213. if (isFiniteNumber(currentTime)) {
  35214. const details = this.getLevelDetails();
  35215. const frag = this.currentFrag || (details ? findFragmentByPTS(null, details.fragments, currentTime) : null);
  35216. if (frag) {
  35217. const programDateTime = frag.programDateTime;
  35218. if (programDateTime !== null) {
  35219. const epocMs = programDateTime + (currentTime - frag.start) * 1e3;
  35220. return new Date(epocMs);
  35221. }
  35222. }
  35223. }
  35224. return null;
  35225. }
  35226. get currentLevel() {
  35227. const frag = this.currentFrag;
  35228. if (frag) {
  35229. return frag.level;
  35230. }
  35231. return -1;
  35232. }
  35233. get nextBufferedFrag() {
  35234. const frag = this.currentFrag;
  35235. if (frag) {
  35236. return this.followingBufferedFrag(frag);
  35237. }
  35238. return null;
  35239. }
  35240. get forceStartLoad() {
  35241. return this._forceStartLoad;
  35242. }
  35243. }
  35244. class KeyLoader {
  35245. constructor(config2) {
  35246. this.config = void 0;
  35247. this.keyUriToKeyInfo = {};
  35248. this.emeController = null;
  35249. this.config = config2;
  35250. }
  35251. abort(type) {
  35252. for (const uri in this.keyUriToKeyInfo) {
  35253. const loader = this.keyUriToKeyInfo[uri].loader;
  35254. if (loader) {
  35255. var _loader$context;
  35256. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  35257. return;
  35258. }
  35259. loader.abort();
  35260. }
  35261. }
  35262. }
  35263. detach() {
  35264. for (const uri in this.keyUriToKeyInfo) {
  35265. const keyInfo = this.keyUriToKeyInfo[uri];
  35266. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  35267. delete this.keyUriToKeyInfo[uri];
  35268. }
  35269. }
  35270. }
  35271. destroy() {
  35272. this.detach();
  35273. for (const uri in this.keyUriToKeyInfo) {
  35274. const loader = this.keyUriToKeyInfo[uri].loader;
  35275. if (loader) {
  35276. loader.destroy();
  35277. }
  35278. }
  35279. this.keyUriToKeyInfo = {};
  35280. }
  35281. createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error2, networkDetails, response) {
  35282. return new LoadError({
  35283. type: ErrorTypes.NETWORK_ERROR,
  35284. details,
  35285. fatal: false,
  35286. frag,
  35287. response,
  35288. error: error2,
  35289. networkDetails
  35290. });
  35291. }
  35292. loadClear(loadingFrag, encryptedFragments, startFragRequested) {
  35293. if (this.emeController && this.config.emeEnabled && !this.emeController.getSelectedKeySystemFormats().length) {
  35294. if (encryptedFragments.length) {
  35295. for (let i2 = 0, l2 = encryptedFragments.length; i2 < l2; i2++) {
  35296. const frag = encryptedFragments[i2];
  35297. if (loadingFrag.cc <= frag.cc && (!isMediaFragment(loadingFrag) || !isMediaFragment(frag) || loadingFrag.sn < frag.sn) || !startFragRequested && i2 == l2 - 1) {
  35298. return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
  35299. if (!this.emeController) {
  35300. return;
  35301. }
  35302. frag.setKeyFormat(keySystemFormat);
  35303. const keySystem = keySystemFormatToKeySystemDomain(keySystemFormat);
  35304. if (keySystem) {
  35305. return this.emeController.getKeySystemAccess([keySystem]);
  35306. }
  35307. });
  35308. }
  35309. }
  35310. }
  35311. if (this.config.requireKeySystemAccessOnStart) {
  35312. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  35313. if (keySystemsInConfig.length) {
  35314. return this.emeController.getKeySystemAccess(keySystemsInConfig);
  35315. }
  35316. }
  35317. }
  35318. return null;
  35319. }
  35320. load(frag) {
  35321. if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) {
  35322. return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
  35323. return this.loadInternal(frag, keySystemFormat);
  35324. });
  35325. }
  35326. return this.loadInternal(frag);
  35327. }
  35328. loadInternal(frag, keySystemFormat) {
  35329. var _keyInfo, _keyInfo2;
  35330. if (keySystemFormat) {
  35331. frag.setKeyFormat(keySystemFormat);
  35332. }
  35333. const decryptdata = frag.decryptdata;
  35334. if (!decryptdata) {
  35335. const error2 = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : "Missing decryption data on fragment in onKeyLoading");
  35336. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error2));
  35337. }
  35338. const uri = decryptdata.uri;
  35339. if (!uri) {
  35340. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`)));
  35341. }
  35342. let keyInfo = this.keyUriToKeyInfo[uri];
  35343. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  35344. decryptdata.key = keyInfo.decryptdata.key;
  35345. return Promise.resolve({
  35346. frag,
  35347. keyInfo
  35348. });
  35349. }
  35350. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  35351. var _keyInfo$mediaKeySess;
  35352. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  35353. case void 0:
  35354. case "status-pending":
  35355. case "usable":
  35356. case "usable-in-future":
  35357. return keyInfo.keyLoadPromise.then((keyLoadedData) => {
  35358. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  35359. return {
  35360. frag,
  35361. keyInfo
  35362. };
  35363. });
  35364. }
  35365. }
  35366. keyInfo = this.keyUriToKeyInfo[uri] = {
  35367. decryptdata,
  35368. keyLoadPromise: null,
  35369. loader: null,
  35370. mediaKeySessionContext: null
  35371. };
  35372. switch (decryptdata.method) {
  35373. case "ISO-23001-7":
  35374. case "SAMPLE-AES":
  35375. case "SAMPLE-AES-CENC":
  35376. case "SAMPLE-AES-CTR":
  35377. if (decryptdata.keyFormat === "identity") {
  35378. return this.loadKeyHTTP(keyInfo, frag);
  35379. }
  35380. return this.loadKeyEME(keyInfo, frag);
  35381. case "AES-128":
  35382. case "AES-256":
  35383. case "AES-256-CTR":
  35384. return this.loadKeyHTTP(keyInfo, frag);
  35385. default:
  35386. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`)));
  35387. }
  35388. }
  35389. loadKeyEME(keyInfo, frag) {
  35390. const keyLoadedData = {
  35391. frag,
  35392. keyInfo
  35393. };
  35394. if (this.emeController && this.config.emeEnabled) {
  35395. const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  35396. if (keySessionContextPromise) {
  35397. return (keyInfo.keyLoadPromise = keySessionContextPromise.then((keySessionContext) => {
  35398. keyInfo.mediaKeySessionContext = keySessionContext;
  35399. return keyLoadedData;
  35400. })).catch((error2) => {
  35401. keyInfo.keyLoadPromise = null;
  35402. throw error2;
  35403. });
  35404. }
  35405. }
  35406. return Promise.resolve(keyLoadedData);
  35407. }
  35408. loadKeyHTTP(keyInfo, frag) {
  35409. const config2 = this.config;
  35410. const Loader = config2.loader;
  35411. const keyLoader = new Loader(config2);
  35412. frag.keyLoader = keyInfo.loader = keyLoader;
  35413. return keyInfo.keyLoadPromise = new Promise((resolve, reject) => {
  35414. const loaderContext = {
  35415. keyInfo,
  35416. frag,
  35417. responseType: "arraybuffer",
  35418. url: keyInfo.decryptdata.uri
  35419. };
  35420. const loadPolicy = config2.keyLoadPolicy.default;
  35421. const loaderConfig = {
  35422. loadPolicy,
  35423. timeout: loadPolicy.maxLoadTimeMs,
  35424. maxRetry: 0,
  35425. retryDelay: 0,
  35426. maxRetryDelay: 0
  35427. };
  35428. const loaderCallbacks = {
  35429. onSuccess: (response, stats, context, networkDetails) => {
  35430. const {
  35431. frag: frag2,
  35432. keyInfo: keyInfo2,
  35433. url: uri
  35434. } = context;
  35435. if (!frag2.decryptdata || keyInfo2 !== this.keyUriToKeyInfo[uri]) {
  35436. return reject(this.createKeyLoadError(frag2, ErrorDetails.KEY_LOAD_ERROR, new Error("after key load, decryptdata unset or changed"), networkDetails));
  35437. }
  35438. keyInfo2.decryptdata.key = frag2.decryptdata.key = new Uint8Array(response.data);
  35439. frag2.keyLoader = null;
  35440. keyInfo2.loader = null;
  35441. resolve({
  35442. frag: frag2,
  35443. keyInfo: keyInfo2
  35444. });
  35445. },
  35446. onError: (response, context, networkDetails, stats) => {
  35447. this.resetLoader(context);
  35448. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({
  35449. url: loaderContext.url,
  35450. data: void 0
  35451. }, response)));
  35452. },
  35453. onTimeout: (stats, context, networkDetails) => {
  35454. this.resetLoader(context);
  35455. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error("key loading timed out"), networkDetails));
  35456. },
  35457. onAbort: (stats, context, networkDetails) => {
  35458. this.resetLoader(context);
  35459. reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error("key loading aborted"), networkDetails));
  35460. }
  35461. };
  35462. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  35463. });
  35464. }
  35465. resetLoader(context) {
  35466. const {
  35467. frag,
  35468. keyInfo,
  35469. url: uri
  35470. } = context;
  35471. const loader = keyInfo.loader;
  35472. if (frag.keyLoader === loader) {
  35473. frag.keyLoader = null;
  35474. keyInfo.loader = null;
  35475. }
  35476. delete this.keyUriToKeyInfo[uri];
  35477. if (loader) {
  35478. loader.destroy();
  35479. }
  35480. }
  35481. }
  35482. function mapContextToLevelType(context) {
  35483. const {
  35484. type
  35485. } = context;
  35486. switch (type) {
  35487. case PlaylistContextType.AUDIO_TRACK:
  35488. return PlaylistLevelType.AUDIO;
  35489. case PlaylistContextType.SUBTITLE_TRACK:
  35490. return PlaylistLevelType.SUBTITLE;
  35491. default:
  35492. return PlaylistLevelType.MAIN;
  35493. }
  35494. }
  35495. function getResponseUrl(response, context) {
  35496. let url2 = response.url;
  35497. if (url2 === void 0 || url2.indexOf("data:") === 0) {
  35498. url2 = context.url;
  35499. }
  35500. return url2;
  35501. }
  35502. class PlaylistLoader {
  35503. constructor(hls) {
  35504. this.hls = void 0;
  35505. this.loaders = /* @__PURE__ */ Object.create(null);
  35506. this.variableList = null;
  35507. this.onManifestLoaded = this.checkAutostartLoad;
  35508. this.hls = hls;
  35509. this.registerListeners();
  35510. }
  35511. startLoad(startPosition) {
  35512. }
  35513. stopLoad() {
  35514. this.destroyInternalLoaders();
  35515. }
  35516. registerListeners() {
  35517. const {
  35518. hls
  35519. } = this;
  35520. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  35521. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  35522. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  35523. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  35524. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  35525. }
  35526. unregisterListeners() {
  35527. const {
  35528. hls
  35529. } = this;
  35530. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  35531. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  35532. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  35533. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  35534. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  35535. }
  35536. /**
  35537. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  35538. */
  35539. createInternalLoader(context) {
  35540. const config2 = this.hls.config;
  35541. const PLoader = config2.pLoader;
  35542. const Loader = config2.loader;
  35543. const InternalLoader = PLoader || Loader;
  35544. const loader = new InternalLoader(config2);
  35545. this.loaders[context.type] = loader;
  35546. return loader;
  35547. }
  35548. getInternalLoader(context) {
  35549. return this.loaders[context.type];
  35550. }
  35551. resetInternalLoader(contextType) {
  35552. if (this.loaders[contextType]) {
  35553. delete this.loaders[contextType];
  35554. }
  35555. }
  35556. /**
  35557. * Call `destroy` on all internal loader instances mapped (one per context type)
  35558. */
  35559. destroyInternalLoaders() {
  35560. for (const contextType in this.loaders) {
  35561. const loader = this.loaders[contextType];
  35562. if (loader) {
  35563. loader.destroy();
  35564. }
  35565. this.resetInternalLoader(contextType);
  35566. }
  35567. }
  35568. destroy() {
  35569. this.variableList = null;
  35570. this.unregisterListeners();
  35571. this.destroyInternalLoaders();
  35572. }
  35573. onManifestLoading(event, data) {
  35574. const {
  35575. url: url2
  35576. } = data;
  35577. this.variableList = null;
  35578. this.load({
  35579. id: null,
  35580. level: 0,
  35581. responseType: "text",
  35582. type: PlaylistContextType.MANIFEST,
  35583. url: url2,
  35584. deliveryDirectives: null,
  35585. levelOrTrack: null
  35586. });
  35587. }
  35588. onLevelLoading(event, data) {
  35589. const {
  35590. id,
  35591. level,
  35592. pathwayId,
  35593. url: url2,
  35594. deliveryDirectives,
  35595. levelInfo
  35596. } = data;
  35597. this.load({
  35598. id,
  35599. level,
  35600. pathwayId,
  35601. responseType: "text",
  35602. type: PlaylistContextType.LEVEL,
  35603. url: url2,
  35604. deliveryDirectives,
  35605. levelOrTrack: levelInfo
  35606. });
  35607. }
  35608. onAudioTrackLoading(event, data) {
  35609. const {
  35610. id,
  35611. groupId,
  35612. url: url2,
  35613. deliveryDirectives,
  35614. track
  35615. } = data;
  35616. this.load({
  35617. id,
  35618. groupId,
  35619. level: null,
  35620. responseType: "text",
  35621. type: PlaylistContextType.AUDIO_TRACK,
  35622. url: url2,
  35623. deliveryDirectives,
  35624. levelOrTrack: track
  35625. });
  35626. }
  35627. onSubtitleTrackLoading(event, data) {
  35628. const {
  35629. id,
  35630. groupId,
  35631. url: url2,
  35632. deliveryDirectives,
  35633. track
  35634. } = data;
  35635. this.load({
  35636. id,
  35637. groupId,
  35638. level: null,
  35639. responseType: "text",
  35640. type: PlaylistContextType.SUBTITLE_TRACK,
  35641. url: url2,
  35642. deliveryDirectives,
  35643. levelOrTrack: track
  35644. });
  35645. }
  35646. onLevelsUpdated(event, data) {
  35647. const loader = this.loaders[PlaylistContextType.LEVEL];
  35648. if (loader) {
  35649. const context = loader.context;
  35650. if (context && !data.levels.some((lvl) => lvl === context.levelOrTrack)) {
  35651. loader.abort();
  35652. delete this.loaders[PlaylistContextType.LEVEL];
  35653. }
  35654. }
  35655. }
  35656. load(context) {
  35657. var _context$deliveryDire;
  35658. const config2 = this.hls.config;
  35659. let loader = this.getInternalLoader(context);
  35660. if (loader) {
  35661. const logger2 = this.hls.logger;
  35662. const loaderContext = loader.context;
  35663. if (loaderContext && loaderContext.levelOrTrack === context.levelOrTrack && (loaderContext.url === context.url || loaderContext.deliveryDirectives && !context.deliveryDirectives)) {
  35664. if (loaderContext.url === context.url) {
  35665. logger2.log(`[playlist-loader]: ignore ${context.url} ongoing request`);
  35666. } else {
  35667. logger2.log(`[playlist-loader]: ignore ${context.url} in favor of ${loaderContext.url}`);
  35668. }
  35669. return;
  35670. }
  35671. logger2.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);
  35672. loader.abort();
  35673. }
  35674. let loadPolicy;
  35675. if (context.type === PlaylistContextType.MANIFEST) {
  35676. loadPolicy = config2.manifestLoadPolicy.default;
  35677. } else {
  35678. loadPolicy = _extends({}, config2.playlistLoadPolicy.default, {
  35679. timeoutRetry: null,
  35680. errorRetry: null
  35681. });
  35682. }
  35683. loader = this.createInternalLoader(context);
  35684. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  35685. let levelDetails;
  35686. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  35687. levelDetails = this.hls.levels[context.level].details;
  35688. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  35689. levelDetails = this.hls.audioTracks[context.id].details;
  35690. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  35691. levelDetails = this.hls.subtitleTracks[context.id].details;
  35692. }
  35693. if (levelDetails) {
  35694. const partTarget = levelDetails.partTarget;
  35695. const targetDuration = levelDetails.targetduration;
  35696. if (partTarget && targetDuration) {
  35697. const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1e3;
  35698. loadPolicy = _extends({}, loadPolicy, {
  35699. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  35700. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  35701. });
  35702. }
  35703. }
  35704. }
  35705. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  35706. const loaderConfig = {
  35707. loadPolicy,
  35708. timeout: loadPolicy.maxLoadTimeMs,
  35709. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  35710. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  35711. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  35712. };
  35713. const loaderCallbacks = {
  35714. onSuccess: (response, stats, context2, networkDetails) => {
  35715. const loader2 = this.getInternalLoader(context2);
  35716. this.resetInternalLoader(context2.type);
  35717. const string2 = response.data;
  35718. if (string2.indexOf("#EXTM3U") !== 0) {
  35719. this.handleManifestParsingError(response, context2, new Error("no EXTM3U delimiter"), networkDetails || null, stats);
  35720. return;
  35721. }
  35722. stats.parsing.start = performance.now();
  35723. if (M3U8Parser.isMediaPlaylist(string2) || context2.type !== PlaylistContextType.MANIFEST) {
  35724. this.handleTrackOrLevelPlaylist(response, stats, context2, networkDetails || null, loader2);
  35725. } else {
  35726. this.handleMasterPlaylist(response, stats, context2, networkDetails);
  35727. }
  35728. },
  35729. onError: (response, context2, networkDetails, stats) => {
  35730. this.handleNetworkError(context2, networkDetails, false, response, stats);
  35731. },
  35732. onTimeout: (stats, context2, networkDetails) => {
  35733. this.handleNetworkError(context2, networkDetails, true, void 0, stats);
  35734. }
  35735. };
  35736. loader.load(context, loaderConfig, loaderCallbacks);
  35737. }
  35738. checkAutostartLoad() {
  35739. if (!this.hls) {
  35740. return;
  35741. }
  35742. const {
  35743. config: {
  35744. autoStartLoad,
  35745. startPosition
  35746. },
  35747. forceStartLoad
  35748. } = this.hls;
  35749. if (autoStartLoad || forceStartLoad) {
  35750. this.hls.logger.log(`${autoStartLoad ? "auto" : "force"} startLoad with configured startPosition ${startPosition}`);
  35751. this.hls.startLoad(startPosition);
  35752. }
  35753. }
  35754. handleMasterPlaylist(response, stats, context, networkDetails) {
  35755. const hls = this.hls;
  35756. const string2 = response.data;
  35757. const url2 = getResponseUrl(response, context);
  35758. const parsedResult = M3U8Parser.parseMasterPlaylist(string2, url2);
  35759. if (parsedResult.playlistParsingError) {
  35760. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  35761. return;
  35762. }
  35763. const {
  35764. contentSteering,
  35765. levels,
  35766. sessionData,
  35767. sessionKeys,
  35768. startTimeOffset,
  35769. variableList
  35770. } = parsedResult;
  35771. this.variableList = variableList;
  35772. const {
  35773. AUDIO: audioTracks = [],
  35774. SUBTITLES: subtitles,
  35775. "CLOSED-CAPTIONS": captions
  35776. } = M3U8Parser.parseMasterPlaylistMedia(string2, url2, parsedResult);
  35777. if (audioTracks.length) {
  35778. const embeddedAudioFound = audioTracks.some((audioTrack) => !audioTrack.url);
  35779. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  35780. this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one");
  35781. audioTracks.unshift({
  35782. type: "main",
  35783. name: "main",
  35784. groupId: "main",
  35785. default: false,
  35786. autoselect: false,
  35787. forced: false,
  35788. id: -1,
  35789. attrs: new AttrList({}),
  35790. bitrate: 0,
  35791. url: ""
  35792. });
  35793. }
  35794. }
  35795. hls.trigger(Events.MANIFEST_LOADED, {
  35796. levels,
  35797. audioTracks,
  35798. subtitles,
  35799. captions,
  35800. contentSteering,
  35801. url: url2,
  35802. stats,
  35803. networkDetails,
  35804. sessionData,
  35805. sessionKeys,
  35806. startTimeOffset,
  35807. variableList
  35808. });
  35809. }
  35810. handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  35811. const hls = this.hls;
  35812. const {
  35813. id,
  35814. level,
  35815. type
  35816. } = context;
  35817. const url2 = getResponseUrl(response, context);
  35818. const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  35819. const levelType = mapContextToLevelType(context);
  35820. const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url2, levelId, levelType, 0, this.variableList);
  35821. if (type === PlaylistContextType.MANIFEST) {
  35822. const singleLevel = {
  35823. attrs: new AttrList({}),
  35824. bitrate: 0,
  35825. details: levelDetails,
  35826. name: "",
  35827. url: url2
  35828. };
  35829. levelDetails.requestScheduled = stats.loading.start + computeReloadInterval(levelDetails, 0);
  35830. hls.trigger(Events.MANIFEST_LOADED, {
  35831. levels: [singleLevel],
  35832. audioTracks: [],
  35833. url: url2,
  35834. stats,
  35835. networkDetails,
  35836. sessionData: null,
  35837. sessionKeys: null,
  35838. contentSteering: null,
  35839. startTimeOffset: null,
  35840. variableList: null
  35841. });
  35842. }
  35843. stats.parsing.end = performance.now();
  35844. context.levelDetails = levelDetails;
  35845. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  35846. }
  35847. handleManifestParsingError(response, context, error2, networkDetails, stats) {
  35848. this.hls.trigger(Events.ERROR, {
  35849. type: ErrorTypes.NETWORK_ERROR,
  35850. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  35851. fatal: context.type === PlaylistContextType.MANIFEST,
  35852. url: response.url,
  35853. err: error2,
  35854. error: error2,
  35855. reason: error2.message,
  35856. response,
  35857. context,
  35858. networkDetails,
  35859. stats
  35860. });
  35861. }
  35862. handleNetworkError(context, networkDetails, timeout2 = false, response, stats) {
  35863. let message = `A network ${timeout2 ? "timeout" : "error" + (response ? " (status " + response.code + ")" : "")} occurred while loading ${context.type}`;
  35864. if (context.type === PlaylistContextType.LEVEL) {
  35865. message += `: ${context.level} id: ${context.id}`;
  35866. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  35867. message += ` id: ${context.id} group-id: "${context.groupId}"`;
  35868. }
  35869. const error2 = new Error(message);
  35870. this.hls.logger.warn(`[playlist-loader]: ${message}`);
  35871. let details = ErrorDetails.UNKNOWN;
  35872. let fatal = false;
  35873. const loader = this.getInternalLoader(context);
  35874. switch (context.type) {
  35875. case PlaylistContextType.MANIFEST:
  35876. details = timeout2 ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  35877. fatal = true;
  35878. break;
  35879. case PlaylistContextType.LEVEL:
  35880. details = timeout2 ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  35881. fatal = false;
  35882. break;
  35883. case PlaylistContextType.AUDIO_TRACK:
  35884. details = timeout2 ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  35885. fatal = false;
  35886. break;
  35887. case PlaylistContextType.SUBTITLE_TRACK:
  35888. details = timeout2 ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  35889. fatal = false;
  35890. break;
  35891. }
  35892. if (loader) {
  35893. this.resetInternalLoader(context.type);
  35894. }
  35895. const errorData = {
  35896. type: ErrorTypes.NETWORK_ERROR,
  35897. details,
  35898. fatal,
  35899. url: context.url,
  35900. loader,
  35901. context,
  35902. error: error2,
  35903. networkDetails,
  35904. stats
  35905. };
  35906. if (response) {
  35907. const url2 = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  35908. errorData.response = _objectSpread2({
  35909. url: url2,
  35910. data: void 0
  35911. }, response);
  35912. }
  35913. this.hls.trigger(Events.ERROR, errorData);
  35914. }
  35915. handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  35916. const hls = this.hls;
  35917. const {
  35918. type,
  35919. level,
  35920. id,
  35921. groupId,
  35922. deliveryDirectives
  35923. } = context;
  35924. const url2 = getResponseUrl(response, context);
  35925. const parent = mapContextToLevelType(context);
  35926. const levelIndex = typeof context.level === "number" && parent === PlaylistLevelType.MAIN ? level : void 0;
  35927. if (!levelDetails.fragments.length) {
  35928. const _error = levelDetails.playlistParsingError = new Error("No Segments found in Playlist");
  35929. hls.trigger(Events.ERROR, {
  35930. type: ErrorTypes.NETWORK_ERROR,
  35931. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  35932. fatal: false,
  35933. url: url2,
  35934. error: _error,
  35935. reason: _error.message,
  35936. response,
  35937. context,
  35938. level: levelIndex,
  35939. parent,
  35940. networkDetails,
  35941. stats
  35942. });
  35943. return;
  35944. }
  35945. if (!levelDetails.targetduration) {
  35946. levelDetails.playlistParsingError = new Error("Missing Target Duration");
  35947. }
  35948. const error2 = levelDetails.playlistParsingError;
  35949. if (error2) {
  35950. this.hls.logger.warn(error2);
  35951. if (!hls.config.ignorePlaylistParsingErrors) {
  35952. hls.trigger(Events.ERROR, {
  35953. type: ErrorTypes.NETWORK_ERROR,
  35954. details: ErrorDetails.LEVEL_PARSING_ERROR,
  35955. fatal: false,
  35956. url: url2,
  35957. error: error2,
  35958. reason: error2.message,
  35959. response,
  35960. context,
  35961. level: levelIndex,
  35962. parent,
  35963. networkDetails,
  35964. stats
  35965. });
  35966. return;
  35967. }
  35968. levelDetails.playlistParsingError = null;
  35969. }
  35970. if (levelDetails.live && loader) {
  35971. if (loader.getCacheAge) {
  35972. levelDetails.ageHeader = loader.getCacheAge() || 0;
  35973. }
  35974. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  35975. levelDetails.ageHeader = 0;
  35976. }
  35977. }
  35978. switch (type) {
  35979. case PlaylistContextType.MANIFEST:
  35980. case PlaylistContextType.LEVEL:
  35981. hls.trigger(Events.LEVEL_LOADED, {
  35982. details: levelDetails,
  35983. levelInfo: context.levelOrTrack || hls.levels[0],
  35984. level: levelIndex || 0,
  35985. id: id || 0,
  35986. stats,
  35987. networkDetails,
  35988. deliveryDirectives,
  35989. withoutMultiVariant: type === PlaylistContextType.MANIFEST
  35990. });
  35991. break;
  35992. case PlaylistContextType.AUDIO_TRACK:
  35993. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  35994. details: levelDetails,
  35995. track: context.levelOrTrack,
  35996. id: id || 0,
  35997. groupId: groupId || "",
  35998. stats,
  35999. networkDetails,
  36000. deliveryDirectives
  36001. });
  36002. break;
  36003. case PlaylistContextType.SUBTITLE_TRACK:
  36004. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  36005. details: levelDetails,
  36006. track: context.levelOrTrack,
  36007. id: id || 0,
  36008. groupId: groupId || "",
  36009. stats,
  36010. networkDetails,
  36011. deliveryDirectives
  36012. });
  36013. break;
  36014. }
  36015. }
  36016. }
  36017. class Hls {
  36018. /**
  36019. * Get the video-dev/hls.js package version.
  36020. */
  36021. static get version() {
  36022. return version;
  36023. }
  36024. /**
  36025. * Check if the required MediaSource Extensions are available.
  36026. */
  36027. static isMSESupported() {
  36028. return isMSESupported();
  36029. }
  36030. /**
  36031. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  36032. */
  36033. static isSupported() {
  36034. return isSupported();
  36035. }
  36036. /**
  36037. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  36038. */
  36039. static getMediaSource() {
  36040. return getMediaSource();
  36041. }
  36042. static get Events() {
  36043. return Events;
  36044. }
  36045. static get MetadataSchema() {
  36046. return MetadataSchema;
  36047. }
  36048. static get ErrorTypes() {
  36049. return ErrorTypes;
  36050. }
  36051. static get ErrorDetails() {
  36052. return ErrorDetails;
  36053. }
  36054. /**
  36055. * Get the default configuration applied to new instances.
  36056. */
  36057. static get DefaultConfig() {
  36058. if (!Hls.defaultConfig) {
  36059. return hlsDefaultConfig;
  36060. }
  36061. return Hls.defaultConfig;
  36062. }
  36063. /**
  36064. * Replace the default configuration applied to new instances.
  36065. */
  36066. static set DefaultConfig(defaultConfig2) {
  36067. Hls.defaultConfig = defaultConfig2;
  36068. }
  36069. /**
  36070. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  36071. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  36072. */
  36073. constructor(userConfig = {}) {
  36074. this.config = void 0;
  36075. this.userConfig = void 0;
  36076. this.logger = void 0;
  36077. this.coreComponents = void 0;
  36078. this.networkControllers = void 0;
  36079. this._emitter = new EventEmitter();
  36080. this._autoLevelCapping = -1;
  36081. this._maxHdcpLevel = null;
  36082. this.abrController = void 0;
  36083. this.bufferController = void 0;
  36084. this.capLevelController = void 0;
  36085. this.latencyController = void 0;
  36086. this.levelController = void 0;
  36087. this.streamController = void 0;
  36088. this.audioStreamController = void 0;
  36089. this.subtititleStreamController = void 0;
  36090. this.audioTrackController = void 0;
  36091. this.subtitleTrackController = void 0;
  36092. this.interstitialsController = void 0;
  36093. this.gapController = void 0;
  36094. this.emeController = void 0;
  36095. this.cmcdController = void 0;
  36096. this._media = null;
  36097. this._url = null;
  36098. this._sessionId = void 0;
  36099. this.triggeringException = void 0;
  36100. this.started = false;
  36101. const logger2 = this.logger = enableLogs(userConfig.debug || false, "Hls instance", userConfig.assetPlayerId);
  36102. const config2 = this.config = mergeConfig$3(Hls.DefaultConfig, userConfig, logger2);
  36103. this.userConfig = userConfig;
  36104. if (config2.progressive) {
  36105. enableStreamingMode(config2, logger2);
  36106. }
  36107. const {
  36108. abrController: _AbrController,
  36109. bufferController: _BufferController,
  36110. capLevelController: _CapLevelController,
  36111. errorController: _ErrorController,
  36112. fpsController: _FpsController
  36113. } = config2;
  36114. const errorController = new _ErrorController(this);
  36115. const abrController = this.abrController = new _AbrController(this);
  36116. const fragmentTracker = new FragmentTracker(this);
  36117. const _InterstitialsController = config2.interstitialsController;
  36118. const interstitialsController = _InterstitialsController ? this.interstitialsController = new _InterstitialsController(this, Hls) : null;
  36119. const bufferController = this.bufferController = new _BufferController(this, fragmentTracker);
  36120. const capLevelController = this.capLevelController = new _CapLevelController(this);
  36121. const fpsController = new _FpsController(this);
  36122. const playListLoader = new PlaylistLoader(this);
  36123. const _ContentSteeringController = config2.contentSteeringController;
  36124. const contentSteering = _ContentSteeringController ? new _ContentSteeringController(this) : null;
  36125. const levelController = this.levelController = new LevelController(this, contentSteering);
  36126. const id3TrackController = new ID3TrackController(this);
  36127. const keyLoader = new KeyLoader(this.config);
  36128. const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  36129. const gapController = this.gapController = new GapController(this, fragmentTracker);
  36130. capLevelController.setStreamController(streamController);
  36131. fpsController.setStreamController(streamController);
  36132. const networkControllers = [playListLoader, levelController, streamController];
  36133. if (interstitialsController) {
  36134. networkControllers.splice(1, 0, interstitialsController);
  36135. }
  36136. if (contentSteering) {
  36137. networkControllers.splice(1, 0, contentSteering);
  36138. }
  36139. this.networkControllers = networkControllers;
  36140. const coreComponents = [abrController, bufferController, gapController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  36141. this.audioTrackController = this.createController(config2.audioTrackController, networkControllers);
  36142. const AudioStreamControllerClass = config2.audioStreamController;
  36143. if (AudioStreamControllerClass) {
  36144. networkControllers.push(this.audioStreamController = new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  36145. }
  36146. this.subtitleTrackController = this.createController(config2.subtitleTrackController, networkControllers);
  36147. const SubtitleStreamControllerClass = config2.subtitleStreamController;
  36148. if (SubtitleStreamControllerClass) {
  36149. networkControllers.push(this.subtititleStreamController = new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  36150. }
  36151. this.createController(config2.timelineController, coreComponents);
  36152. keyLoader.emeController = this.emeController = this.createController(config2.emeController, coreComponents);
  36153. this.cmcdController = this.createController(config2.cmcdController, coreComponents);
  36154. this.latencyController = this.createController(LatencyController, coreComponents);
  36155. this.coreComponents = coreComponents;
  36156. networkControllers.push(errorController);
  36157. const onErrorOut = errorController.onErrorOut;
  36158. if (typeof onErrorOut === "function") {
  36159. this.on(Events.ERROR, onErrorOut, errorController);
  36160. }
  36161. this.on(Events.MANIFEST_LOADED, playListLoader.onManifestLoaded, playListLoader);
  36162. }
  36163. createController(ControllerClass, components) {
  36164. if (ControllerClass) {
  36165. const controllerInstance = new ControllerClass(this);
  36166. if (components) {
  36167. components.push(controllerInstance);
  36168. }
  36169. return controllerInstance;
  36170. }
  36171. return null;
  36172. }
  36173. // Delegate the EventEmitter through the public API of Hls.js
  36174. on(event, listener, context = this) {
  36175. this._emitter.on(event, listener, context);
  36176. }
  36177. once(event, listener, context = this) {
  36178. this._emitter.once(event, listener, context);
  36179. }
  36180. removeAllListeners(event) {
  36181. this._emitter.removeAllListeners(event);
  36182. }
  36183. off(event, listener, context = this, once) {
  36184. this._emitter.off(event, listener, context, once);
  36185. }
  36186. listeners(event) {
  36187. return this._emitter.listeners(event);
  36188. }
  36189. emit(event, name, eventObject) {
  36190. return this._emitter.emit(event, name, eventObject);
  36191. }
  36192. trigger(event, eventObject) {
  36193. if (this.config.debug) {
  36194. return this.emit(event, event, eventObject);
  36195. } else {
  36196. try {
  36197. return this.emit(event, event, eventObject);
  36198. } catch (error2) {
  36199. this.logger.error("An internal error happened while handling event " + event + '. Error message: "' + error2.message + '". Here is a stacktrace:', error2);
  36200. if (!this.triggeringException) {
  36201. this.triggeringException = true;
  36202. const fatal = event === Events.ERROR;
  36203. this.trigger(Events.ERROR, {
  36204. type: ErrorTypes.OTHER_ERROR,
  36205. details: ErrorDetails.INTERNAL_EXCEPTION,
  36206. fatal,
  36207. event,
  36208. error: error2
  36209. });
  36210. this.triggeringException = false;
  36211. }
  36212. }
  36213. }
  36214. return false;
  36215. }
  36216. listenerCount(event) {
  36217. return this._emitter.listenerCount(event);
  36218. }
  36219. /**
  36220. * Dispose of the instance
  36221. */
  36222. destroy() {
  36223. this.logger.log("destroy");
  36224. this.trigger(Events.DESTROYING, void 0);
  36225. this.detachMedia();
  36226. this.removeAllListeners();
  36227. this._autoLevelCapping = -1;
  36228. this._url = null;
  36229. this.networkControllers.forEach((component) => component.destroy());
  36230. this.networkControllers.length = 0;
  36231. this.coreComponents.forEach((component) => component.destroy());
  36232. this.coreComponents.length = 0;
  36233. const config2 = this.config;
  36234. config2.xhrSetup = config2.fetchSetup = void 0;
  36235. this.userConfig = null;
  36236. }
  36237. /**
  36238. * Attaches Hls.js to a media element
  36239. */
  36240. attachMedia(data) {
  36241. if (!data || "media" in data && !data.media) {
  36242. const error2 = new Error(`attachMedia failed: invalid argument (${data})`);
  36243. this.trigger(Events.ERROR, {
  36244. type: ErrorTypes.OTHER_ERROR,
  36245. details: ErrorDetails.ATTACH_MEDIA_ERROR,
  36246. fatal: true,
  36247. error: error2
  36248. });
  36249. return;
  36250. }
  36251. this.logger.log(`attachMedia`);
  36252. if (this._media) {
  36253. this.logger.warn(`media must be detached before attaching`);
  36254. this.detachMedia();
  36255. }
  36256. const attachMediaSource = "media" in data;
  36257. const media = attachMediaSource ? data.media : data;
  36258. const attachingData = attachMediaSource ? data : {
  36259. media
  36260. };
  36261. this._media = media;
  36262. this.trigger(Events.MEDIA_ATTACHING, attachingData);
  36263. }
  36264. /**
  36265. * Detach Hls.js from the media
  36266. */
  36267. detachMedia() {
  36268. this.logger.log("detachMedia");
  36269. this.trigger(Events.MEDIA_DETACHING, {});
  36270. this._media = null;
  36271. }
  36272. /**
  36273. * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance
  36274. */
  36275. transferMedia() {
  36276. this._media = null;
  36277. const transferMedia = this.bufferController.transferMedia();
  36278. this.trigger(Events.MEDIA_DETACHING, {
  36279. transferMedia
  36280. });
  36281. return transferMedia;
  36282. }
  36283. /**
  36284. * Set the source URL. Can be relative or absolute.
  36285. */
  36286. loadSource(url2) {
  36287. this.stopLoad();
  36288. const media = this.media;
  36289. const loadedSource = this._url;
  36290. const loadingSource = this._url = urlToolkitExports.buildAbsoluteURL(self.location.href, url2, {
  36291. alwaysNormalize: true
  36292. });
  36293. this._autoLevelCapping = -1;
  36294. this._maxHdcpLevel = null;
  36295. this.logger.log(`loadSource:${loadingSource}`);
  36296. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  36297. this.detachMedia();
  36298. this.attachMedia(media);
  36299. }
  36300. this.trigger(Events.MANIFEST_LOADING, {
  36301. url: url2
  36302. });
  36303. }
  36304. /**
  36305. * Gets the currently loaded URL
  36306. */
  36307. get url() {
  36308. return this._url;
  36309. }
  36310. /**
  36311. * Whether or not enough has been buffered to seek to start position or use `media.currentTime` to determine next load position
  36312. */
  36313. get hasEnoughToStart() {
  36314. return this.streamController.hasEnoughToStart;
  36315. }
  36316. /**
  36317. * Get the startPosition set on startLoad(position) or on autostart with config.startPosition
  36318. */
  36319. get startPosition() {
  36320. return this.streamController.startPositionValue;
  36321. }
  36322. /**
  36323. * Start loading data from the stream source.
  36324. * Depending on default config, client starts loading automatically when a source is set.
  36325. *
  36326. * @param startPosition - Set the start position to stream from.
  36327. * Defaults to -1 (None: starts from earliest point)
  36328. */
  36329. startLoad(startPosition = -1, skipSeekToStartPosition) {
  36330. this.logger.log(`startLoad(${startPosition + (skipSeekToStartPosition ? ", <skip seek to start>" : "")})`);
  36331. this.started = true;
  36332. this.resumeBuffering();
  36333. for (let i2 = 0; i2 < this.networkControllers.length; i2++) {
  36334. this.networkControllers[i2].startLoad(startPosition, skipSeekToStartPosition);
  36335. if (!this.started || !this.networkControllers) {
  36336. break;
  36337. }
  36338. }
  36339. }
  36340. /**
  36341. * Stop loading of any stream data.
  36342. */
  36343. stopLoad() {
  36344. this.logger.log("stopLoad");
  36345. this.started = false;
  36346. for (let i2 = 0; i2 < this.networkControllers.length; i2++) {
  36347. this.networkControllers[i2].stopLoad();
  36348. if (this.started || !this.networkControllers) {
  36349. break;
  36350. }
  36351. }
  36352. }
  36353. /**
  36354. * Returns whether loading, toggled with `startLoad()` and `stopLoad()`, is active or not`.
  36355. */
  36356. get loadingEnabled() {
  36357. return this.started;
  36358. }
  36359. /**
  36360. * Returns state of fragment loading toggled by calling `pauseBuffering()` and `resumeBuffering()`.
  36361. */
  36362. get bufferingEnabled() {
  36363. return this.streamController.bufferingEnabled;
  36364. }
  36365. /**
  36366. * Resumes stream controller segment loading after `pauseBuffering` has been called.
  36367. */
  36368. resumeBuffering() {
  36369. if (!this.bufferingEnabled) {
  36370. this.logger.log(`resume buffering`);
  36371. this.networkControllers.forEach((controller) => {
  36372. if (controller.resumeBuffering) {
  36373. controller.resumeBuffering();
  36374. }
  36375. });
  36376. }
  36377. }
  36378. /**
  36379. * Prevents stream controller from loading new segments until `resumeBuffering` is called.
  36380. * This allows for media buffering to be paused without interupting playlist loading.
  36381. */
  36382. pauseBuffering() {
  36383. if (this.bufferingEnabled) {
  36384. this.logger.log(`pause buffering`);
  36385. this.networkControllers.forEach((controller) => {
  36386. if (controller.pauseBuffering) {
  36387. controller.pauseBuffering();
  36388. }
  36389. });
  36390. }
  36391. }
  36392. get inFlightFragments() {
  36393. const inFlightData = {
  36394. [PlaylistLevelType.MAIN]: this.streamController.inFlightFrag
  36395. };
  36396. if (this.audioStreamController) {
  36397. inFlightData[PlaylistLevelType.AUDIO] = this.audioStreamController.inFlightFrag;
  36398. }
  36399. if (this.subtititleStreamController) {
  36400. inFlightData[PlaylistLevelType.SUBTITLE] = this.subtititleStreamController.inFlightFrag;
  36401. }
  36402. return inFlightData;
  36403. }
  36404. /**
  36405. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  36406. */
  36407. swapAudioCodec() {
  36408. this.logger.log("swapAudioCodec");
  36409. this.streamController.swapAudioCodec();
  36410. }
  36411. /**
  36412. * When the media-element fails, this allows to detach and then re-attach it
  36413. * as one call (convenience method).
  36414. *
  36415. * Automatic recovery of media-errors by this process is configurable.
  36416. */
  36417. recoverMediaError() {
  36418. this.logger.log("recoverMediaError");
  36419. const media = this._media;
  36420. const time = media == null ? void 0 : media.currentTime;
  36421. this.detachMedia();
  36422. if (media) {
  36423. this.attachMedia(media);
  36424. if (time) {
  36425. this.startLoad(time);
  36426. }
  36427. }
  36428. }
  36429. removeLevel(levelIndex) {
  36430. this.levelController.removeLevel(levelIndex);
  36431. }
  36432. /**
  36433. * @returns a UUID for this player instance
  36434. */
  36435. get sessionId() {
  36436. let _sessionId = this._sessionId;
  36437. if (!_sessionId) {
  36438. _sessionId = this._sessionId = uuid();
  36439. }
  36440. return _sessionId;
  36441. }
  36442. /**
  36443. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  36444. */
  36445. get levels() {
  36446. const levels = this.levelController.levels;
  36447. return levels ? levels : [];
  36448. }
  36449. /**
  36450. * @returns LevelDetails of last loaded level (variant) or `null` prior to loading a media playlist.
  36451. */
  36452. get latestLevelDetails() {
  36453. return this.streamController.getLevelDetails() || null;
  36454. }
  36455. /**
  36456. * @returns Level object of selected level (variant) or `null` prior to selecting a level or once the level is removed.
  36457. */
  36458. get loadLevelObj() {
  36459. return this.levelController.loadLevelObj;
  36460. }
  36461. /**
  36462. * Index of quality level (variant) currently played
  36463. */
  36464. get currentLevel() {
  36465. return this.streamController.currentLevel;
  36466. }
  36467. /**
  36468. * 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.
  36469. */
  36470. set currentLevel(newLevel) {
  36471. this.logger.log(`set currentLevel:${newLevel}`);
  36472. this.levelController.manualLevel = newLevel;
  36473. this.streamController.immediateLevelSwitch();
  36474. }
  36475. /**
  36476. * Index of next quality level loaded as scheduled by stream controller.
  36477. */
  36478. get nextLevel() {
  36479. return this.streamController.nextLevel;
  36480. }
  36481. /**
  36482. * Set quality level index for next loaded data.
  36483. * This will switch the video quality asap, without interrupting playback.
  36484. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  36485. * @param newLevel - Pass -1 for automatic level selection
  36486. */
  36487. set nextLevel(newLevel) {
  36488. this.logger.log(`set nextLevel:${newLevel}`);
  36489. this.levelController.manualLevel = newLevel;
  36490. this.streamController.nextLevelSwitch();
  36491. }
  36492. /**
  36493. * Return the quality level of the currently or last (of none is loaded currently) segment
  36494. */
  36495. get loadLevel() {
  36496. return this.levelController.level;
  36497. }
  36498. /**
  36499. * Set quality level index for next loaded data in a conservative way.
  36500. * This will switch the quality without flushing, but interrupt current loading.
  36501. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  36502. * @param newLevel - Pass -1 for automatic level selection
  36503. */
  36504. set loadLevel(newLevel) {
  36505. this.logger.log(`set loadLevel:${newLevel}`);
  36506. this.levelController.manualLevel = newLevel;
  36507. }
  36508. /**
  36509. * get next quality level loaded
  36510. */
  36511. get nextLoadLevel() {
  36512. return this.levelController.nextLoadLevel;
  36513. }
  36514. /**
  36515. * Set quality level of next loaded segment in a fully "non-destructive" way.
  36516. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  36517. */
  36518. set nextLoadLevel(level) {
  36519. this.levelController.nextLoadLevel = level;
  36520. }
  36521. /**
  36522. * Return "first level": like a default level, if not set,
  36523. * falls back to index of first level referenced in manifest
  36524. */
  36525. get firstLevel() {
  36526. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  36527. }
  36528. /**
  36529. * Sets "first-level", see getter.
  36530. */
  36531. set firstLevel(newLevel) {
  36532. this.logger.log(`set firstLevel:${newLevel}`);
  36533. this.levelController.firstLevel = newLevel;
  36534. }
  36535. /**
  36536. * Return the desired start level for the first fragment that will be loaded.
  36537. * The default value of -1 indicates automatic start level selection.
  36538. * Setting hls.nextAutoLevel without setting a startLevel will result in
  36539. * the nextAutoLevel value being used for one fragment load.
  36540. */
  36541. get startLevel() {
  36542. const startLevel = this.levelController.startLevel;
  36543. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  36544. return this.abrController.forcedAutoLevel;
  36545. }
  36546. return startLevel;
  36547. }
  36548. /**
  36549. * set start level (level of first fragment that will be played back)
  36550. * if not overrided by user, first level appearing in manifest will be used as start level
  36551. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  36552. * (determined from download of first segment)
  36553. */
  36554. set startLevel(newLevel) {
  36555. this.logger.log(`set startLevel:${newLevel}`);
  36556. if (newLevel !== -1) {
  36557. newLevel = Math.max(newLevel, this.minAutoLevel);
  36558. }
  36559. this.levelController.startLevel = newLevel;
  36560. }
  36561. /**
  36562. * Whether level capping is enabled.
  36563. * Default value is set via `config.capLevelToPlayerSize`.
  36564. */
  36565. get capLevelToPlayerSize() {
  36566. return this.config.capLevelToPlayerSize;
  36567. }
  36568. /**
  36569. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  36570. */
  36571. set capLevelToPlayerSize(shouldStartCapping) {
  36572. const newCapLevelToPlayerSize = !!shouldStartCapping;
  36573. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  36574. if (newCapLevelToPlayerSize) {
  36575. this.capLevelController.startCapping();
  36576. } else {
  36577. this.capLevelController.stopCapping();
  36578. this.autoLevelCapping = -1;
  36579. this.streamController.nextLevelSwitch();
  36580. }
  36581. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  36582. }
  36583. }
  36584. /**
  36585. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  36586. */
  36587. get autoLevelCapping() {
  36588. return this._autoLevelCapping;
  36589. }
  36590. /**
  36591. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  36592. */
  36593. get bandwidthEstimate() {
  36594. const {
  36595. bwEstimator
  36596. } = this.abrController;
  36597. if (!bwEstimator) {
  36598. return NaN;
  36599. }
  36600. return bwEstimator.getEstimate();
  36601. }
  36602. set bandwidthEstimate(abrEwmaDefaultEstimate) {
  36603. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  36604. }
  36605. get abrEwmaDefaultEstimate() {
  36606. const {
  36607. bwEstimator
  36608. } = this.abrController;
  36609. if (!bwEstimator) {
  36610. return NaN;
  36611. }
  36612. return bwEstimator.defaultEstimate;
  36613. }
  36614. /**
  36615. * get time to first byte estimate
  36616. * @type {number}
  36617. */
  36618. get ttfbEstimate() {
  36619. const {
  36620. bwEstimator
  36621. } = this.abrController;
  36622. if (!bwEstimator) {
  36623. return NaN;
  36624. }
  36625. return bwEstimator.getEstimateTTFB();
  36626. }
  36627. /**
  36628. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  36629. */
  36630. set autoLevelCapping(newLevel) {
  36631. if (this._autoLevelCapping !== newLevel) {
  36632. this.logger.log(`set autoLevelCapping:${newLevel}`);
  36633. this._autoLevelCapping = newLevel;
  36634. this.levelController.checkMaxAutoUpdated();
  36635. }
  36636. }
  36637. get maxHdcpLevel() {
  36638. return this._maxHdcpLevel;
  36639. }
  36640. set maxHdcpLevel(value2) {
  36641. if (isHdcpLevel(value2) && this._maxHdcpLevel !== value2) {
  36642. this._maxHdcpLevel = value2;
  36643. this.levelController.checkMaxAutoUpdated();
  36644. }
  36645. }
  36646. /**
  36647. * True when automatic level selection enabled
  36648. */
  36649. get autoLevelEnabled() {
  36650. return this.levelController.manualLevel === -1;
  36651. }
  36652. /**
  36653. * Level set manually (if any)
  36654. */
  36655. get manualLevel() {
  36656. return this.levelController.manualLevel;
  36657. }
  36658. /**
  36659. * min level selectable in auto mode according to config.minAutoBitrate
  36660. */
  36661. get minAutoLevel() {
  36662. const {
  36663. levels,
  36664. config: {
  36665. minAutoBitrate
  36666. }
  36667. } = this;
  36668. if (!levels)
  36669. return 0;
  36670. const len = levels.length;
  36671. for (let i2 = 0; i2 < len; i2++) {
  36672. if (levels[i2].maxBitrate >= minAutoBitrate) {
  36673. return i2;
  36674. }
  36675. }
  36676. return 0;
  36677. }
  36678. /**
  36679. * max level selectable in auto mode according to autoLevelCapping
  36680. */
  36681. get maxAutoLevel() {
  36682. const {
  36683. levels,
  36684. autoLevelCapping,
  36685. maxHdcpLevel
  36686. } = this;
  36687. let maxAutoLevel;
  36688. if (autoLevelCapping === -1 && levels != null && levels.length) {
  36689. maxAutoLevel = levels.length - 1;
  36690. } else {
  36691. maxAutoLevel = autoLevelCapping;
  36692. }
  36693. if (maxHdcpLevel) {
  36694. for (let i2 = maxAutoLevel; i2--; ) {
  36695. const hdcpLevel = levels[i2].attrs["HDCP-LEVEL"];
  36696. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  36697. return i2;
  36698. }
  36699. }
  36700. }
  36701. return maxAutoLevel;
  36702. }
  36703. get firstAutoLevel() {
  36704. return this.abrController.firstAutoLevel;
  36705. }
  36706. /**
  36707. * next automatically selected quality level
  36708. */
  36709. get nextAutoLevel() {
  36710. return this.abrController.nextAutoLevel;
  36711. }
  36712. /**
  36713. * this setter is used to force next auto level.
  36714. * this is useful to force a switch down in auto mode:
  36715. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  36716. * forced value is valid for one fragment. upon successful frag loading at forced level,
  36717. * this value will be resetted to -1 by ABR controller.
  36718. */
  36719. set nextAutoLevel(nextLevel) {
  36720. this.abrController.nextAutoLevel = nextLevel;
  36721. }
  36722. /**
  36723. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  36724. */
  36725. get playingDate() {
  36726. return this.streamController.currentProgramDateTime;
  36727. }
  36728. get mainForwardBufferInfo() {
  36729. return this.streamController.getMainFwdBufferInfo();
  36730. }
  36731. get maxBufferLength() {
  36732. return this.streamController.maxBufferLength;
  36733. }
  36734. /**
  36735. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  36736. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  36737. */
  36738. setAudioOption(audioOption) {
  36739. var _this$audioTrackContr;
  36740. return ((_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption)) || null;
  36741. }
  36742. /**
  36743. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  36744. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  36745. */
  36746. setSubtitleOption(subtitleOption) {
  36747. var _this$subtitleTrackCo;
  36748. return ((_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption)) || null;
  36749. }
  36750. /**
  36751. * Get the complete list of audio tracks across all media groups
  36752. */
  36753. get allAudioTracks() {
  36754. const audioTrackController = this.audioTrackController;
  36755. return audioTrackController ? audioTrackController.allAudioTracks : [];
  36756. }
  36757. /**
  36758. * Get the list of selectable audio tracks
  36759. */
  36760. get audioTracks() {
  36761. const audioTrackController = this.audioTrackController;
  36762. return audioTrackController ? audioTrackController.audioTracks : [];
  36763. }
  36764. /**
  36765. * index of the selected audio track (index in audio track lists)
  36766. */
  36767. get audioTrack() {
  36768. const audioTrackController = this.audioTrackController;
  36769. return audioTrackController ? audioTrackController.audioTrack : -1;
  36770. }
  36771. /**
  36772. * selects an audio track, based on its index in audio track lists
  36773. */
  36774. set audioTrack(audioTrackId) {
  36775. const audioTrackController = this.audioTrackController;
  36776. if (audioTrackController) {
  36777. audioTrackController.audioTrack = audioTrackId;
  36778. }
  36779. }
  36780. /**
  36781. * get the complete list of subtitle tracks across all media groups
  36782. */
  36783. get allSubtitleTracks() {
  36784. const subtitleTrackController = this.subtitleTrackController;
  36785. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  36786. }
  36787. /**
  36788. * get alternate subtitle tracks list from playlist
  36789. */
  36790. get subtitleTracks() {
  36791. const subtitleTrackController = this.subtitleTrackController;
  36792. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  36793. }
  36794. /**
  36795. * index of the selected subtitle track (index in subtitle track lists)
  36796. */
  36797. get subtitleTrack() {
  36798. const subtitleTrackController = this.subtitleTrackController;
  36799. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  36800. }
  36801. get media() {
  36802. return this._media;
  36803. }
  36804. /**
  36805. * select an subtitle track, based on its index in subtitle track lists
  36806. */
  36807. set subtitleTrack(subtitleTrackId) {
  36808. const subtitleTrackController = this.subtitleTrackController;
  36809. if (subtitleTrackController) {
  36810. subtitleTrackController.subtitleTrack = subtitleTrackId;
  36811. }
  36812. }
  36813. /**
  36814. * Whether subtitle display is enabled or not
  36815. */
  36816. get subtitleDisplay() {
  36817. const subtitleTrackController = this.subtitleTrackController;
  36818. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  36819. }
  36820. /**
  36821. * Enable/disable subtitle display rendering
  36822. */
  36823. set subtitleDisplay(value2) {
  36824. const subtitleTrackController = this.subtitleTrackController;
  36825. if (subtitleTrackController) {
  36826. subtitleTrackController.subtitleDisplay = value2;
  36827. }
  36828. }
  36829. /**
  36830. * get mode for Low-Latency HLS loading
  36831. */
  36832. get lowLatencyMode() {
  36833. return this.config.lowLatencyMode;
  36834. }
  36835. /**
  36836. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  36837. */
  36838. set lowLatencyMode(mode) {
  36839. this.config.lowLatencyMode = mode;
  36840. }
  36841. /**
  36842. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  36843. * @returns null prior to loading live Playlist
  36844. */
  36845. get liveSyncPosition() {
  36846. return this.latencyController.liveSyncPosition;
  36847. }
  36848. /**
  36849. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  36850. * @returns 0 before first playlist is loaded
  36851. */
  36852. get latency() {
  36853. return this.latencyController.latency;
  36854. }
  36855. /**
  36856. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  36857. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  36858. * @returns 0 before first playlist is loaded
  36859. */
  36860. get maxLatency() {
  36861. return this.latencyController.maxLatency;
  36862. }
  36863. /**
  36864. * target distance from the edge as calculated by the latency controller
  36865. */
  36866. get targetLatency() {
  36867. return this.latencyController.targetLatency;
  36868. }
  36869. set targetLatency(latency) {
  36870. this.latencyController.targetLatency = latency;
  36871. }
  36872. /**
  36873. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  36874. */
  36875. get drift() {
  36876. return this.latencyController.drift;
  36877. }
  36878. /**
  36879. * set to true when startLoad is called before MANIFEST_PARSED event
  36880. */
  36881. get forceStartLoad() {
  36882. return this.streamController.forceStartLoad;
  36883. }
  36884. /**
  36885. * ContentSteering pathways getter
  36886. */
  36887. get pathways() {
  36888. return this.levelController.pathways;
  36889. }
  36890. /**
  36891. * ContentSteering pathwayPriority getter/setter
  36892. */
  36893. get pathwayPriority() {
  36894. return this.levelController.pathwayPriority;
  36895. }
  36896. set pathwayPriority(pathwayPriority) {
  36897. this.levelController.pathwayPriority = pathwayPriority;
  36898. }
  36899. /**
  36900. * returns true when all SourceBuffers are buffered to the end
  36901. */
  36902. get bufferedToEnd() {
  36903. var _this$bufferControlle;
  36904. return !!((_this$bufferControlle = this.bufferController) != null && _this$bufferControlle.bufferedToEnd);
  36905. }
  36906. /**
  36907. * returns Interstitials Program Manager
  36908. */
  36909. get interstitialsManager() {
  36910. var _this$interstitialsCo;
  36911. return ((_this$interstitialsCo = this.interstitialsController) == null ? void 0 : _this$interstitialsCo.interstitialsManager) || null;
  36912. }
  36913. /**
  36914. * returns mediaCapabilities.decodingInfo for a variant/rendition
  36915. */
  36916. getMediaDecodingInfo(level, audioTracks = this.allAudioTracks) {
  36917. const audioTracksByGroup = getAudioTracksByGroup(audioTracks);
  36918. return getMediaDecodingInfoPromise(level, audioTracksByGroup, navigator.mediaCapabilities);
  36919. }
  36920. }
  36921. Hls.defaultConfig = void 0;
  36922. var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
  36923. function getDefaultExportFromCjs(x) {
  36924. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
  36925. }
  36926. function getAugmentedNamespace(n2) {
  36927. if (n2.__esModule)
  36928. return n2;
  36929. var f2 = n2.default;
  36930. if (typeof f2 == "function") {
  36931. var a2 = function a3() {
  36932. if (this instanceof a3) {
  36933. return Reflect.construct(f2, arguments, this.constructor);
  36934. }
  36935. return f2.apply(this, arguments);
  36936. };
  36937. a2.prototype = f2.prototype;
  36938. } else
  36939. a2 = {};
  36940. Object.defineProperty(a2, "__esModule", { value: true });
  36941. Object.keys(n2).forEach(function(k) {
  36942. var d2 = Object.getOwnPropertyDescriptor(n2, k);
  36943. Object.defineProperty(a2, k, d2.get ? d2 : {
  36944. enumerable: true,
  36945. get: function() {
  36946. return n2[k];
  36947. }
  36948. });
  36949. });
  36950. return a2;
  36951. }
  36952. var cryptoJs = { exports: {} };
  36953. function commonjsRequire(path) {
  36954. 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.');
  36955. }
  36956. var core = { exports: {} };
  36957. const __viteBrowserExternal = new Proxy({}, {
  36958. get(_2, key) {
  36959. 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.`);
  36960. }
  36961. });
  36962. const __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  36963. __proto__: null,
  36964. default: __viteBrowserExternal
  36965. }, Symbol.toStringTag, { value: "Module" }));
  36966. const require$$0 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1);
  36967. var hasRequiredCore;
  36968. function requireCore() {
  36969. if (hasRequiredCore)
  36970. return core.exports;
  36971. hasRequiredCore = 1;
  36972. (function(module, exports) {
  36973. (function(root, factory) {
  36974. {
  36975. module.exports = factory();
  36976. }
  36977. })(commonjsGlobal, function() {
  36978. var CryptoJS2 = CryptoJS2 || function(Math2, undefined$1) {
  36979. var crypto;
  36980. if (typeof window !== "undefined" && $inject_window_crypto) {
  36981. crypto = $inject_window_crypto;
  36982. }
  36983. if (typeof self !== "undefined" && self.crypto) {
  36984. crypto = self.crypto;
  36985. }
  36986. if (typeof globalThis !== "undefined" && globalThis.crypto) {
  36987. crypto = globalThis.crypto;
  36988. }
  36989. if (!crypto && typeof window !== "undefined" && window.msCrypto) {
  36990. crypto = window.msCrypto;
  36991. }
  36992. if (!crypto && typeof commonjsGlobal !== "undefined" && commonjsGlobal.crypto) {
  36993. crypto = commonjsGlobal.crypto;
  36994. }
  36995. if (!crypto && typeof commonjsRequire === "function") {
  36996. try {
  36997. crypto = require$$0;
  36998. } catch (err) {
  36999. }
  37000. }
  37001. var cryptoSecureRandomInt = function() {
  37002. if (crypto) {
  37003. if (typeof crypto.getRandomValues === "function") {
  37004. try {
  37005. return crypto.getRandomValues(new Uint32Array(1))[0];
  37006. } catch (err) {
  37007. }
  37008. }
  37009. if (typeof crypto.randomBytes === "function") {
  37010. try {
  37011. return crypto.randomBytes(4).readInt32LE();
  37012. } catch (err) {
  37013. }
  37014. }
  37015. }
  37016. throw new Error("Native crypto module could not be used to get secure random number.");
  37017. };
  37018. var create2 = Object.create || /* @__PURE__ */ function() {
  37019. function F2() {
  37020. }
  37021. return function(obj) {
  37022. var subtype;
  37023. F2.prototype = obj;
  37024. subtype = new F2();
  37025. F2.prototype = null;
  37026. return subtype;
  37027. };
  37028. }();
  37029. var C2 = {};
  37030. var C_lib = C2.lib = {};
  37031. var Base = C_lib.Base = /* @__PURE__ */ function() {
  37032. return {
  37033. /**
  37034. * Creates a new object that inherits from this object.
  37035. *
  37036. * @param {Object} overrides Properties to copy into the new object.
  37037. *
  37038. * @return {Object} The new object.
  37039. *
  37040. * @static
  37041. *
  37042. * @example
  37043. *
  37044. * var MyType = CryptoJS.lib.Base.extend({
  37045. * field: 'value',
  37046. *
  37047. * method: function () {
  37048. * }
  37049. * });
  37050. */
  37051. extend: function(overrides) {
  37052. var subtype = create2(this);
  37053. if (overrides) {
  37054. subtype.mixIn(overrides);
  37055. }
  37056. if (!subtype.hasOwnProperty("init") || this.init === subtype.init) {
  37057. subtype.init = function() {
  37058. subtype.$super.init.apply(this, arguments);
  37059. };
  37060. }
  37061. subtype.init.prototype = subtype;
  37062. subtype.$super = this;
  37063. return subtype;
  37064. },
  37065. /**
  37066. * Extends this object and runs the init method.
  37067. * Arguments to create() will be passed to init().
  37068. *
  37069. * @return {Object} The new object.
  37070. *
  37071. * @static
  37072. *
  37073. * @example
  37074. *
  37075. * var instance = MyType.create();
  37076. */
  37077. create: function() {
  37078. var instance = this.extend();
  37079. instance.init.apply(instance, arguments);
  37080. return instance;
  37081. },
  37082. /**
  37083. * Initializes a newly created object.
  37084. * Override this method to add some logic when your objects are created.
  37085. *
  37086. * @example
  37087. *
  37088. * var MyType = CryptoJS.lib.Base.extend({
  37089. * init: function () {
  37090. * // ...
  37091. * }
  37092. * });
  37093. */
  37094. init: function() {
  37095. },
  37096. /**
  37097. * Copies properties into this object.
  37098. *
  37099. * @param {Object} properties The properties to mix in.
  37100. *
  37101. * @example
  37102. *
  37103. * MyType.mixIn({
  37104. * field: 'value'
  37105. * });
  37106. */
  37107. mixIn: function(properties) {
  37108. for (var propertyName in properties) {
  37109. if (properties.hasOwnProperty(propertyName)) {
  37110. this[propertyName] = properties[propertyName];
  37111. }
  37112. }
  37113. if (properties.hasOwnProperty("toString")) {
  37114. this.toString = properties.toString;
  37115. }
  37116. },
  37117. /**
  37118. * Creates a copy of this object.
  37119. *
  37120. * @return {Object} The clone.
  37121. *
  37122. * @example
  37123. *
  37124. * var clone = instance.clone();
  37125. */
  37126. clone: function() {
  37127. return this.init.prototype.extend(this);
  37128. }
  37129. };
  37130. }();
  37131. var WordArray = C_lib.WordArray = Base.extend({
  37132. /**
  37133. * Initializes a newly created word array.
  37134. *
  37135. * @param {Array} words (Optional) An array of 32-bit words.
  37136. * @param {number} sigBytes (Optional) The number of significant bytes in the words.
  37137. *
  37138. * @example
  37139. *
  37140. * var wordArray = CryptoJS.lib.WordArray.create();
  37141. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
  37142. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
  37143. */
  37144. init: function(words, sigBytes) {
  37145. words = this.words = words || [];
  37146. if (sigBytes != undefined$1) {
  37147. this.sigBytes = sigBytes;
  37148. } else {
  37149. this.sigBytes = words.length * 4;
  37150. }
  37151. },
  37152. /**
  37153. * Converts this word array to a string.
  37154. *
  37155. * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
  37156. *
  37157. * @return {string} The stringified word array.
  37158. *
  37159. * @example
  37160. *
  37161. * var string = wordArray + '';
  37162. * var string = wordArray.toString();
  37163. * var string = wordArray.toString(CryptoJS.enc.Utf8);
  37164. */
  37165. toString: function(encoder) {
  37166. return (encoder || Hex2).stringify(this);
  37167. },
  37168. /**
  37169. * Concatenates a word array to this word array.
  37170. *
  37171. * @param {WordArray} wordArray The word array to append.
  37172. *
  37173. * @return {WordArray} This word array.
  37174. *
  37175. * @example
  37176. *
  37177. * wordArray1.concat(wordArray2);
  37178. */
  37179. concat: function(wordArray) {
  37180. var thisWords = this.words;
  37181. var thatWords = wordArray.words;
  37182. var thisSigBytes = this.sigBytes;
  37183. var thatSigBytes = wordArray.sigBytes;
  37184. this.clamp();
  37185. if (thisSigBytes % 4) {
  37186. for (var i2 = 0; i2 < thatSigBytes; i2++) {
  37187. var thatByte = thatWords[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
  37188. thisWords[thisSigBytes + i2 >>> 2] |= thatByte << 24 - (thisSigBytes + i2) % 4 * 8;
  37189. }
  37190. } else {
  37191. for (var j2 = 0; j2 < thatSigBytes; j2 += 4) {
  37192. thisWords[thisSigBytes + j2 >>> 2] = thatWords[j2 >>> 2];
  37193. }
  37194. }
  37195. this.sigBytes += thatSigBytes;
  37196. return this;
  37197. },
  37198. /**
  37199. * Removes insignificant bits.
  37200. *
  37201. * @example
  37202. *
  37203. * wordArray.clamp();
  37204. */
  37205. clamp: function() {
  37206. var words = this.words;
  37207. var sigBytes = this.sigBytes;
  37208. words[sigBytes >>> 2] &= 4294967295 << 32 - sigBytes % 4 * 8;
  37209. words.length = Math2.ceil(sigBytes / 4);
  37210. },
  37211. /**
  37212. * Creates a copy of this word array.
  37213. *
  37214. * @return {WordArray} The clone.
  37215. *
  37216. * @example
  37217. *
  37218. * var clone = wordArray.clone();
  37219. */
  37220. clone: function() {
  37221. var clone2 = Base.clone.call(this);
  37222. clone2.words = this.words.slice(0);
  37223. return clone2;
  37224. },
  37225. /**
  37226. * Creates a word array filled with random bytes.
  37227. *
  37228. * @param {number} nBytes The number of random bytes to generate.
  37229. *
  37230. * @return {WordArray} The random word array.
  37231. *
  37232. * @static
  37233. *
  37234. * @example
  37235. *
  37236. * var wordArray = CryptoJS.lib.WordArray.random(16);
  37237. */
  37238. random: function(nBytes) {
  37239. var words = [];
  37240. for (var i2 = 0; i2 < nBytes; i2 += 4) {
  37241. words.push(cryptoSecureRandomInt());
  37242. }
  37243. return new WordArray.init(words, nBytes);
  37244. }
  37245. });
  37246. var C_enc = C2.enc = {};
  37247. var Hex2 = C_enc.Hex = {
  37248. /**
  37249. * Converts a word array to a hex string.
  37250. *
  37251. * @param {WordArray} wordArray The word array.
  37252. *
  37253. * @return {string} The hex string.
  37254. *
  37255. * @static
  37256. *
  37257. * @example
  37258. *
  37259. * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
  37260. */
  37261. stringify: function(wordArray) {
  37262. var words = wordArray.words;
  37263. var sigBytes = wordArray.sigBytes;
  37264. var hexChars = [];
  37265. for (var i2 = 0; i2 < sigBytes; i2++) {
  37266. var bite = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
  37267. hexChars.push((bite >>> 4).toString(16));
  37268. hexChars.push((bite & 15).toString(16));
  37269. }
  37270. return hexChars.join("");
  37271. },
  37272. /**
  37273. * Converts a hex string to a word array.
  37274. *
  37275. * @param {string} hexStr The hex string.
  37276. *
  37277. * @return {WordArray} The word array.
  37278. *
  37279. * @static
  37280. *
  37281. * @example
  37282. *
  37283. * var wordArray = CryptoJS.enc.Hex.parse(hexString);
  37284. */
  37285. parse: function(hexStr) {
  37286. var hexStrLength = hexStr.length;
  37287. var words = [];
  37288. for (var i2 = 0; i2 < hexStrLength; i2 += 2) {
  37289. words[i2 >>> 3] |= parseInt(hexStr.substr(i2, 2), 16) << 24 - i2 % 8 * 4;
  37290. }
  37291. return new WordArray.init(words, hexStrLength / 2);
  37292. }
  37293. };
  37294. var Latin1 = C_enc.Latin1 = {
  37295. /**
  37296. * Converts a word array to a Latin1 string.
  37297. *
  37298. * @param {WordArray} wordArray The word array.
  37299. *
  37300. * @return {string} The Latin1 string.
  37301. *
  37302. * @static
  37303. *
  37304. * @example
  37305. *
  37306. * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
  37307. */
  37308. stringify: function(wordArray) {
  37309. var words = wordArray.words;
  37310. var sigBytes = wordArray.sigBytes;
  37311. var latin1Chars = [];
  37312. for (var i2 = 0; i2 < sigBytes; i2++) {
  37313. var bite = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
  37314. latin1Chars.push(String.fromCharCode(bite));
  37315. }
  37316. return latin1Chars.join("");
  37317. },
  37318. /**
  37319. * Converts a Latin1 string to a word array.
  37320. *
  37321. * @param {string} latin1Str The Latin1 string.
  37322. *
  37323. * @return {WordArray} The word array.
  37324. *
  37325. * @static
  37326. *
  37327. * @example
  37328. *
  37329. * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
  37330. */
  37331. parse: function(latin1Str) {
  37332. var latin1StrLength = latin1Str.length;
  37333. var words = [];
  37334. for (var i2 = 0; i2 < latin1StrLength; i2++) {
  37335. words[i2 >>> 2] |= (latin1Str.charCodeAt(i2) & 255) << 24 - i2 % 4 * 8;
  37336. }
  37337. return new WordArray.init(words, latin1StrLength);
  37338. }
  37339. };
  37340. var Utf8 = C_enc.Utf8 = {
  37341. /**
  37342. * Converts a word array to a UTF-8 string.
  37343. *
  37344. * @param {WordArray} wordArray The word array.
  37345. *
  37346. * @return {string} The UTF-8 string.
  37347. *
  37348. * @static
  37349. *
  37350. * @example
  37351. *
  37352. * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
  37353. */
  37354. stringify: function(wordArray) {
  37355. try {
  37356. return decodeURIComponent(escape(Latin1.stringify(wordArray)));
  37357. } catch (e2) {
  37358. throw new Error("Malformed UTF-8 data");
  37359. }
  37360. },
  37361. /**
  37362. * Converts a UTF-8 string to a word array.
  37363. *
  37364. * @param {string} utf8Str The UTF-8 string.
  37365. *
  37366. * @return {WordArray} The word array.
  37367. *
  37368. * @static
  37369. *
  37370. * @example
  37371. *
  37372. * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
  37373. */
  37374. parse: function(utf8Str) {
  37375. return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
  37376. }
  37377. };
  37378. var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
  37379. /**
  37380. * Resets this block algorithm's data buffer to its initial state.
  37381. *
  37382. * @example
  37383. *
  37384. * bufferedBlockAlgorithm.reset();
  37385. */
  37386. reset: function() {
  37387. this._data = new WordArray.init();
  37388. this._nDataBytes = 0;
  37389. },
  37390. /**
  37391. * Adds new data to this block algorithm's buffer.
  37392. *
  37393. * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
  37394. *
  37395. * @example
  37396. *
  37397. * bufferedBlockAlgorithm._append('data');
  37398. * bufferedBlockAlgorithm._append(wordArray);
  37399. */
  37400. _append: function(data) {
  37401. if (typeof data == "string") {
  37402. data = Utf8.parse(data);
  37403. }
  37404. this._data.concat(data);
  37405. this._nDataBytes += data.sigBytes;
  37406. },
  37407. /**
  37408. * Processes available data blocks.
  37409. *
  37410. * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
  37411. *
  37412. * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
  37413. *
  37414. * @return {WordArray} The processed data.
  37415. *
  37416. * @example
  37417. *
  37418. * var processedData = bufferedBlockAlgorithm._process();
  37419. * var processedData = bufferedBlockAlgorithm._process(!!'flush');
  37420. */
  37421. _process: function(doFlush) {
  37422. var processedWords;
  37423. var data = this._data;
  37424. var dataWords = data.words;
  37425. var dataSigBytes = data.sigBytes;
  37426. var blockSize = this.blockSize;
  37427. var blockSizeBytes = blockSize * 4;
  37428. var nBlocksReady = dataSigBytes / blockSizeBytes;
  37429. if (doFlush) {
  37430. nBlocksReady = Math2.ceil(nBlocksReady);
  37431. } else {
  37432. nBlocksReady = Math2.max((nBlocksReady | 0) - this._minBufferSize, 0);
  37433. }
  37434. var nWordsReady = nBlocksReady * blockSize;
  37435. var nBytesReady = Math2.min(nWordsReady * 4, dataSigBytes);
  37436. if (nWordsReady) {
  37437. for (var offset = 0; offset < nWordsReady; offset += blockSize) {
  37438. this._doProcessBlock(dataWords, offset);
  37439. }
  37440. processedWords = dataWords.splice(0, nWordsReady);
  37441. data.sigBytes -= nBytesReady;
  37442. }
  37443. return new WordArray.init(processedWords, nBytesReady);
  37444. },
  37445. /**
  37446. * Creates a copy of this object.
  37447. *
  37448. * @return {Object} The clone.
  37449. *
  37450. * @example
  37451. *
  37452. * var clone = bufferedBlockAlgorithm.clone();
  37453. */
  37454. clone: function() {
  37455. var clone2 = Base.clone.call(this);
  37456. clone2._data = this._data.clone();
  37457. return clone2;
  37458. },
  37459. _minBufferSize: 0
  37460. });
  37461. C_lib.Hasher = BufferedBlockAlgorithm.extend({
  37462. /**
  37463. * Configuration options.
  37464. */
  37465. cfg: Base.extend(),
  37466. /**
  37467. * Initializes a newly created hasher.
  37468. *
  37469. * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
  37470. *
  37471. * @example
  37472. *
  37473. * var hasher = CryptoJS.algo.SHA256.create();
  37474. */
  37475. init: function(cfg) {
  37476. this.cfg = this.cfg.extend(cfg);
  37477. this.reset();
  37478. },
  37479. /**
  37480. * Resets this hasher to its initial state.
  37481. *
  37482. * @example
  37483. *
  37484. * hasher.reset();
  37485. */
  37486. reset: function() {
  37487. BufferedBlockAlgorithm.reset.call(this);
  37488. this._doReset();
  37489. },
  37490. /**
  37491. * Updates this hasher with a message.
  37492. *
  37493. * @param {WordArray|string} messageUpdate The message to append.
  37494. *
  37495. * @return {Hasher} This hasher.
  37496. *
  37497. * @example
  37498. *
  37499. * hasher.update('message');
  37500. * hasher.update(wordArray);
  37501. */
  37502. update: function(messageUpdate) {
  37503. this._append(messageUpdate);
  37504. this._process();
  37505. return this;
  37506. },
  37507. /**
  37508. * Finalizes the hash computation.
  37509. * Note that the finalize operation is effectively a destructive, read-once operation.
  37510. *
  37511. * @param {WordArray|string} messageUpdate (Optional) A final message update.
  37512. *
  37513. * @return {WordArray} The hash.
  37514. *
  37515. * @example
  37516. *
  37517. * var hash = hasher.finalize();
  37518. * var hash = hasher.finalize('message');
  37519. * var hash = hasher.finalize(wordArray);
  37520. */
  37521. finalize: function(messageUpdate) {
  37522. if (messageUpdate) {
  37523. this._append(messageUpdate);
  37524. }
  37525. var hash2 = this._doFinalize();
  37526. return hash2;
  37527. },
  37528. blockSize: 512 / 32,
  37529. /**
  37530. * Creates a shortcut function to a hasher's object interface.
  37531. *
  37532. * @param {Hasher} hasher The hasher to create a helper for.
  37533. *
  37534. * @return {Function} The shortcut function.
  37535. *
  37536. * @static
  37537. *
  37538. * @example
  37539. *
  37540. * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
  37541. */
  37542. _createHelper: function(hasher) {
  37543. return function(message, cfg) {
  37544. return new hasher.init(cfg).finalize(message);
  37545. };
  37546. },
  37547. /**
  37548. * Creates a shortcut function to the HMAC's object interface.
  37549. *
  37550. * @param {Hasher} hasher The hasher to use in this HMAC helper.
  37551. *
  37552. * @return {Function} The shortcut function.
  37553. *
  37554. * @static
  37555. *
  37556. * @example
  37557. *
  37558. * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
  37559. */
  37560. _createHmacHelper: function(hasher) {
  37561. return function(message, key) {
  37562. return new C_algo.HMAC.init(hasher, key).finalize(message);
  37563. };
  37564. }
  37565. });
  37566. var C_algo = C2.algo = {};
  37567. return C2;
  37568. }(Math);
  37569. return CryptoJS2;
  37570. });
  37571. })(core);
  37572. return core.exports;
  37573. }
  37574. var x64Core = { exports: {} };
  37575. var hasRequiredX64Core;
  37576. function requireX64Core() {
  37577. if (hasRequiredX64Core)
  37578. return x64Core.exports;
  37579. hasRequiredX64Core = 1;
  37580. (function(module, exports) {
  37581. (function(root, factory) {
  37582. {
  37583. module.exports = factory(requireCore());
  37584. }
  37585. })(commonjsGlobal, function(CryptoJS2) {
  37586. (function(undefined$1) {
  37587. var C2 = CryptoJS2;
  37588. var C_lib = C2.lib;
  37589. var Base = C_lib.Base;
  37590. var X32WordArray = C_lib.WordArray;
  37591. var C_x64 = C2.x64 = {};
  37592. C_x64.Word = Base.extend({
  37593. /**
  37594. * Initializes a newly created 64-bit word.
  37595. *
  37596. * @param {number} high The high 32 bits.
  37597. * @param {number} low The low 32 bits.
  37598. *
  37599. * @example
  37600. *
  37601. * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
  37602. */
  37603. init: function(high, low) {
  37604. this.high = high;
  37605. this.low = low;
  37606. }
  37607. /**
  37608. * Bitwise NOTs this word.
  37609. *
  37610. * @return {X64Word} A new x64-Word object after negating.
  37611. *
  37612. * @example
  37613. *
  37614. * var negated = x64Word.not();
  37615. */
  37616. // not: function () {
  37617. // var high = ~this.high;
  37618. // var low = ~this.low;
  37619. // return X64Word.create(high, low);
  37620. // },
  37621. /**
  37622. * Bitwise ANDs this word with the passed word.
  37623. *
  37624. * @param {X64Word} word The x64-Word to AND with this word.
  37625. *
  37626. * @return {X64Word} A new x64-Word object after ANDing.
  37627. *
  37628. * @example
  37629. *
  37630. * var anded = x64Word.and(anotherX64Word);
  37631. */
  37632. // and: function (word) {
  37633. // var high = this.high & word.high;
  37634. // var low = this.low & word.low;
  37635. // return X64Word.create(high, low);
  37636. // },
  37637. /**
  37638. * Bitwise ORs this word with the passed word.
  37639. *
  37640. * @param {X64Word} word The x64-Word to OR with this word.
  37641. *
  37642. * @return {X64Word} A new x64-Word object after ORing.
  37643. *
  37644. * @example
  37645. *
  37646. * var ored = x64Word.or(anotherX64Word);
  37647. */
  37648. // or: function (word) {
  37649. // var high = this.high | word.high;
  37650. // var low = this.low | word.low;
  37651. // return X64Word.create(high, low);
  37652. // },
  37653. /**
  37654. * Bitwise XORs this word with the passed word.
  37655. *
  37656. * @param {X64Word} word The x64-Word to XOR with this word.
  37657. *
  37658. * @return {X64Word} A new x64-Word object after XORing.
  37659. *
  37660. * @example
  37661. *
  37662. * var xored = x64Word.xor(anotherX64Word);
  37663. */
  37664. // xor: function (word) {
  37665. // var high = this.high ^ word.high;
  37666. // var low = this.low ^ word.low;
  37667. // return X64Word.create(high, low);
  37668. // },
  37669. /**
  37670. * Shifts this word n bits to the left.
  37671. *
  37672. * @param {number} n The number of bits to shift.
  37673. *
  37674. * @return {X64Word} A new x64-Word object after shifting.
  37675. *
  37676. * @example
  37677. *
  37678. * var shifted = x64Word.shiftL(25);
  37679. */
  37680. // shiftL: function (n) {
  37681. // if (n < 32) {
  37682. // var high = (this.high << n) | (this.low >>> (32 - n));
  37683. // var low = this.low << n;
  37684. // } else {
  37685. // var high = this.low << (n - 32);
  37686. // var low = 0;
  37687. // }
  37688. // return X64Word.create(high, low);
  37689. // },
  37690. /**
  37691. * Shifts this word n bits to the right.
  37692. *
  37693. * @param {number} n The number of bits to shift.
  37694. *
  37695. * @return {X64Word} A new x64-Word object after shifting.
  37696. *
  37697. * @example
  37698. *
  37699. * var shifted = x64Word.shiftR(7);
  37700. */
  37701. // shiftR: function (n) {
  37702. // if (n < 32) {
  37703. // var low = (this.low >>> n) | (this.high << (32 - n));
  37704. // var high = this.high >>> n;
  37705. // } else {
  37706. // var low = this.high >>> (n - 32);
  37707. // var high = 0;
  37708. // }
  37709. // return X64Word.create(high, low);
  37710. // },
  37711. /**
  37712. * Rotates this word n bits to the left.
  37713. *
  37714. * @param {number} n The number of bits to rotate.
  37715. *
  37716. * @return {X64Word} A new x64-Word object after rotating.
  37717. *
  37718. * @example
  37719. *
  37720. * var rotated = x64Word.rotL(25);
  37721. */
  37722. // rotL: function (n) {
  37723. // return this.shiftL(n).or(this.shiftR(64 - n));
  37724. // },
  37725. /**
  37726. * Rotates this word n bits to the right.
  37727. *
  37728. * @param {number} n The number of bits to rotate.
  37729. *
  37730. * @return {X64Word} A new x64-Word object after rotating.
  37731. *
  37732. * @example
  37733. *
  37734. * var rotated = x64Word.rotR(7);
  37735. */
  37736. // rotR: function (n) {
  37737. // return this.shiftR(n).or(this.shiftL(64 - n));
  37738. // },
  37739. /**
  37740. * Adds this word with the passed word.
  37741. *
  37742. * @param {X64Word} word The x64-Word to add with this word.
  37743. *
  37744. * @return {X64Word} A new x64-Word object after adding.
  37745. *
  37746. * @example
  37747. *
  37748. * var added = x64Word.add(anotherX64Word);
  37749. */
  37750. // add: function (word) {
  37751. // var low = (this.low + word.low) | 0;
  37752. // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
  37753. // var high = (this.high + word.high + carry) | 0;
  37754. // return X64Word.create(high, low);
  37755. // }
  37756. });
  37757. C_x64.WordArray = Base.extend({
  37758. /**
  37759. * Initializes a newly created word array.
  37760. *
  37761. * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
  37762. * @param {number} sigBytes (Optional) The number of significant bytes in the words.
  37763. *
  37764. * @example
  37765. *
  37766. * var wordArray = CryptoJS.x64.WordArray.create();
  37767. *
  37768. * var wordArray = CryptoJS.x64.WordArray.create([
  37769. * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
  37770. * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
  37771. * ]);
  37772. *
  37773. * var wordArray = CryptoJS.x64.WordArray.create([
  37774. * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
  37775. * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
  37776. * ], 10);
  37777. */
  37778. init: function(words, sigBytes) {
  37779. words = this.words = words || [];
  37780. if (sigBytes != undefined$1) {
  37781. this.sigBytes = sigBytes;
  37782. } else {
  37783. this.sigBytes = words.length * 8;
  37784. }
  37785. },
  37786. /**
  37787. * Converts this 64-bit word array to a 32-bit word array.
  37788. *
  37789. * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
  37790. *
  37791. * @example
  37792. *
  37793. * var x32WordArray = x64WordArray.toX32();
  37794. */
  37795. toX32: function() {
  37796. var x64Words = this.words;
  37797. var x64WordsLength = x64Words.length;
  37798. var x32Words = [];
  37799. for (var i2 = 0; i2 < x64WordsLength; i2++) {
  37800. var x64Word = x64Words[i2];
  37801. x32Words.push(x64Word.high);
  37802. x32Words.push(x64Word.low);
  37803. }
  37804. return X32WordArray.create(x32Words, this.sigBytes);
  37805. },
  37806. /**
  37807. * Creates a copy of this word array.
  37808. *
  37809. * @return {X64WordArray} The clone.
  37810. *
  37811. * @example
  37812. *
  37813. * var clone = x64WordArray.clone();
  37814. */
  37815. clone: function() {
  37816. var clone2 = Base.clone.call(this);
  37817. var words = clone2.words = this.words.slice(0);
  37818. var wordsLength = words.length;
  37819. for (var i2 = 0; i2 < wordsLength; i2++) {
  37820. words[i2] = words[i2].clone();
  37821. }
  37822. return clone2;
  37823. }
  37824. });
  37825. })();
  37826. return CryptoJS2;
  37827. });
  37828. })(x64Core);
  37829. return x64Core.exports;
  37830. }
  37831. var libTypedarrays = { exports: {} };
  37832. var hasRequiredLibTypedarrays;
  37833. function requireLibTypedarrays() {
  37834. if (hasRequiredLibTypedarrays)
  37835. return libTypedarrays.exports;
  37836. hasRequiredLibTypedarrays = 1;
  37837. (function(module, exports) {
  37838. (function(root, factory) {
  37839. {
  37840. module.exports = factory(requireCore());
  37841. }
  37842. })(commonjsGlobal, function(CryptoJS2) {
  37843. (function() {
  37844. if (typeof ArrayBuffer != "function") {
  37845. return;
  37846. }
  37847. var C2 = CryptoJS2;
  37848. var C_lib = C2.lib;
  37849. var WordArray = C_lib.WordArray;
  37850. var superInit = WordArray.init;
  37851. var subInit = WordArray.init = function(typedArray) {
  37852. if (typedArray instanceof ArrayBuffer) {
  37853. typedArray = new Uint8Array(typedArray);
  37854. }
  37855. 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) {
  37856. typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
  37857. }
  37858. if (typedArray instanceof Uint8Array) {
  37859. var typedArrayByteLength = typedArray.byteLength;
  37860. var words = [];
  37861. for (var i2 = 0; i2 < typedArrayByteLength; i2++) {
  37862. words[i2 >>> 2] |= typedArray[i2] << 24 - i2 % 4 * 8;
  37863. }
  37864. superInit.call(this, words, typedArrayByteLength);
  37865. } else {
  37866. superInit.apply(this, arguments);
  37867. }
  37868. };
  37869. subInit.prototype = WordArray;
  37870. })();
  37871. return CryptoJS2.lib.WordArray;
  37872. });
  37873. })(libTypedarrays);
  37874. return libTypedarrays.exports;
  37875. }
  37876. var encUtf16 = { exports: {} };
  37877. var hasRequiredEncUtf16;
  37878. function requireEncUtf16() {
  37879. if (hasRequiredEncUtf16)
  37880. return encUtf16.exports;
  37881. hasRequiredEncUtf16 = 1;
  37882. (function(module, exports) {
  37883. (function(root, factory) {
  37884. {
  37885. module.exports = factory(requireCore());
  37886. }
  37887. })(commonjsGlobal, function(CryptoJS2) {
  37888. (function() {
  37889. var C2 = CryptoJS2;
  37890. var C_lib = C2.lib;
  37891. var WordArray = C_lib.WordArray;
  37892. var C_enc = C2.enc;
  37893. C_enc.Utf16 = C_enc.Utf16BE = {
  37894. /**
  37895. * Converts a word array to a UTF-16 BE string.
  37896. *
  37897. * @param {WordArray} wordArray The word array.
  37898. *
  37899. * @return {string} The UTF-16 BE string.
  37900. *
  37901. * @static
  37902. *
  37903. * @example
  37904. *
  37905. * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
  37906. */
  37907. stringify: function(wordArray) {
  37908. var words = wordArray.words;
  37909. var sigBytes = wordArray.sigBytes;
  37910. var utf16Chars = [];
  37911. for (var i2 = 0; i2 < sigBytes; i2 += 2) {
  37912. var codePoint = words[i2 >>> 2] >>> 16 - i2 % 4 * 8 & 65535;
  37913. utf16Chars.push(String.fromCharCode(codePoint));
  37914. }
  37915. return utf16Chars.join("");
  37916. },
  37917. /**
  37918. * Converts a UTF-16 BE string to a word array.
  37919. *
  37920. * @param {string} utf16Str The UTF-16 BE string.
  37921. *
  37922. * @return {WordArray} The word array.
  37923. *
  37924. * @static
  37925. *
  37926. * @example
  37927. *
  37928. * var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
  37929. */
  37930. parse: function(utf16Str) {
  37931. var utf16StrLength = utf16Str.length;
  37932. var words = [];
  37933. for (var i2 = 0; i2 < utf16StrLength; i2++) {
  37934. words[i2 >>> 1] |= utf16Str.charCodeAt(i2) << 16 - i2 % 2 * 16;
  37935. }
  37936. return WordArray.create(words, utf16StrLength * 2);
  37937. }
  37938. };
  37939. C_enc.Utf16LE = {
  37940. /**
  37941. * Converts a word array to a UTF-16 LE string.
  37942. *
  37943. * @param {WordArray} wordArray The word array.
  37944. *
  37945. * @return {string} The UTF-16 LE string.
  37946. *
  37947. * @static
  37948. *
  37949. * @example
  37950. *
  37951. * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
  37952. */
  37953. stringify: function(wordArray) {
  37954. var words = wordArray.words;
  37955. var sigBytes = wordArray.sigBytes;
  37956. var utf16Chars = [];
  37957. for (var i2 = 0; i2 < sigBytes; i2 += 2) {
  37958. var codePoint = swapEndian(words[i2 >>> 2] >>> 16 - i2 % 4 * 8 & 65535);
  37959. utf16Chars.push(String.fromCharCode(codePoint));
  37960. }
  37961. return utf16Chars.join("");
  37962. },
  37963. /**
  37964. * Converts a UTF-16 LE string to a word array.
  37965. *
  37966. * @param {string} utf16Str The UTF-16 LE string.
  37967. *
  37968. * @return {WordArray} The word array.
  37969. *
  37970. * @static
  37971. *
  37972. * @example
  37973. *
  37974. * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
  37975. */
  37976. parse: function(utf16Str) {
  37977. var utf16StrLength = utf16Str.length;
  37978. var words = [];
  37979. for (var i2 = 0; i2 < utf16StrLength; i2++) {
  37980. words[i2 >>> 1] |= swapEndian(utf16Str.charCodeAt(i2) << 16 - i2 % 2 * 16);
  37981. }
  37982. return WordArray.create(words, utf16StrLength * 2);
  37983. }
  37984. };
  37985. function swapEndian(word) {
  37986. return word << 8 & 4278255360 | word >>> 8 & 16711935;
  37987. }
  37988. })();
  37989. return CryptoJS2.enc.Utf16;
  37990. });
  37991. })(encUtf16);
  37992. return encUtf16.exports;
  37993. }
  37994. var encBase64 = { exports: {} };
  37995. var hasRequiredEncBase64;
  37996. function requireEncBase64() {
  37997. if (hasRequiredEncBase64)
  37998. return encBase64.exports;
  37999. hasRequiredEncBase64 = 1;
  38000. (function(module, exports) {
  38001. (function(root, factory) {
  38002. {
  38003. module.exports = factory(requireCore());
  38004. }
  38005. })(commonjsGlobal, function(CryptoJS2) {
  38006. (function() {
  38007. var C2 = CryptoJS2;
  38008. var C_lib = C2.lib;
  38009. var WordArray = C_lib.WordArray;
  38010. var C_enc = C2.enc;
  38011. C_enc.Base64 = {
  38012. /**
  38013. * Converts a word array to a Base64 string.
  38014. *
  38015. * @param {WordArray} wordArray The word array.
  38016. *
  38017. * @return {string} The Base64 string.
  38018. *
  38019. * @static
  38020. *
  38021. * @example
  38022. *
  38023. * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
  38024. */
  38025. stringify: function(wordArray) {
  38026. var words = wordArray.words;
  38027. var sigBytes = wordArray.sigBytes;
  38028. var map = this._map;
  38029. wordArray.clamp();
  38030. var base64Chars = [];
  38031. for (var i2 = 0; i2 < sigBytes; i2 += 3) {
  38032. var byte1 = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
  38033. var byte2 = words[i2 + 1 >>> 2] >>> 24 - (i2 + 1) % 4 * 8 & 255;
  38034. var byte3 = words[i2 + 2 >>> 2] >>> 24 - (i2 + 2) % 4 * 8 & 255;
  38035. var triplet = byte1 << 16 | byte2 << 8 | byte3;
  38036. for (var j2 = 0; j2 < 4 && i2 + j2 * 0.75 < sigBytes; j2++) {
  38037. base64Chars.push(map.charAt(triplet >>> 6 * (3 - j2) & 63));
  38038. }
  38039. }
  38040. var paddingChar = map.charAt(64);
  38041. if (paddingChar) {
  38042. while (base64Chars.length % 4) {
  38043. base64Chars.push(paddingChar);
  38044. }
  38045. }
  38046. return base64Chars.join("");
  38047. },
  38048. /**
  38049. * Converts a Base64 string to a word array.
  38050. *
  38051. * @param {string} base64Str The Base64 string.
  38052. *
  38053. * @return {WordArray} The word array.
  38054. *
  38055. * @static
  38056. *
  38057. * @example
  38058. *
  38059. * var wordArray = CryptoJS.enc.Base64.parse(base64String);
  38060. */
  38061. parse: function(base64Str) {
  38062. var base64StrLength = base64Str.length;
  38063. var map = this._map;
  38064. var reverseMap = this._reverseMap;
  38065. if (!reverseMap) {
  38066. reverseMap = this._reverseMap = [];
  38067. for (var j2 = 0; j2 < map.length; j2++) {
  38068. reverseMap[map.charCodeAt(j2)] = j2;
  38069. }
  38070. }
  38071. var paddingChar = map.charAt(64);
  38072. if (paddingChar) {
  38073. var paddingIndex = base64Str.indexOf(paddingChar);
  38074. if (paddingIndex !== -1) {
  38075. base64StrLength = paddingIndex;
  38076. }
  38077. }
  38078. return parseLoop(base64Str, base64StrLength, reverseMap);
  38079. },
  38080. _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
  38081. };
  38082. function parseLoop(base64Str, base64StrLength, reverseMap) {
  38083. var words = [];
  38084. var nBytes = 0;
  38085. for (var i2 = 0; i2 < base64StrLength; i2++) {
  38086. if (i2 % 4) {
  38087. var bits1 = reverseMap[base64Str.charCodeAt(i2 - 1)] << i2 % 4 * 2;
  38088. var bits2 = reverseMap[base64Str.charCodeAt(i2)] >>> 6 - i2 % 4 * 2;
  38089. var bitsCombined = bits1 | bits2;
  38090. words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8;
  38091. nBytes++;
  38092. }
  38093. }
  38094. return WordArray.create(words, nBytes);
  38095. }
  38096. })();
  38097. return CryptoJS2.enc.Base64;
  38098. });
  38099. })(encBase64);
  38100. return encBase64.exports;
  38101. }
  38102. var encBase64url = { exports: {} };
  38103. var hasRequiredEncBase64url;
  38104. function requireEncBase64url() {
  38105. if (hasRequiredEncBase64url)
  38106. return encBase64url.exports;
  38107. hasRequiredEncBase64url = 1;
  38108. (function(module, exports) {
  38109. (function(root, factory) {
  38110. {
  38111. module.exports = factory(requireCore());
  38112. }
  38113. })(commonjsGlobal, function(CryptoJS2) {
  38114. (function() {
  38115. var C2 = CryptoJS2;
  38116. var C_lib = C2.lib;
  38117. var WordArray = C_lib.WordArray;
  38118. var C_enc = C2.enc;
  38119. C_enc.Base64url = {
  38120. /**
  38121. * Converts a word array to a Base64url string.
  38122. *
  38123. * @param {WordArray} wordArray The word array.
  38124. *
  38125. * @param {boolean} urlSafe Whether to use url safe
  38126. *
  38127. * @return {string} The Base64url string.
  38128. *
  38129. * @static
  38130. *
  38131. * @example
  38132. *
  38133. * var base64String = CryptoJS.enc.Base64url.stringify(wordArray);
  38134. */
  38135. stringify: function(wordArray, urlSafe) {
  38136. if (urlSafe === void 0) {
  38137. urlSafe = true;
  38138. }
  38139. var words = wordArray.words;
  38140. var sigBytes = wordArray.sigBytes;
  38141. var map = urlSafe ? this._safe_map : this._map;
  38142. wordArray.clamp();
  38143. var base64Chars = [];
  38144. for (var i2 = 0; i2 < sigBytes; i2 += 3) {
  38145. var byte1 = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
  38146. var byte2 = words[i2 + 1 >>> 2] >>> 24 - (i2 + 1) % 4 * 8 & 255;
  38147. var byte3 = words[i2 + 2 >>> 2] >>> 24 - (i2 + 2) % 4 * 8 & 255;
  38148. var triplet = byte1 << 16 | byte2 << 8 | byte3;
  38149. for (var j2 = 0; j2 < 4 && i2 + j2 * 0.75 < sigBytes; j2++) {
  38150. base64Chars.push(map.charAt(triplet >>> 6 * (3 - j2) & 63));
  38151. }
  38152. }
  38153. var paddingChar = map.charAt(64);
  38154. if (paddingChar) {
  38155. while (base64Chars.length % 4) {
  38156. base64Chars.push(paddingChar);
  38157. }
  38158. }
  38159. return base64Chars.join("");
  38160. },
  38161. /**
  38162. * Converts a Base64url string to a word array.
  38163. *
  38164. * @param {string} base64Str The Base64url string.
  38165. *
  38166. * @param {boolean} urlSafe Whether to use url safe
  38167. *
  38168. * @return {WordArray} The word array.
  38169. *
  38170. * @static
  38171. *
  38172. * @example
  38173. *
  38174. * var wordArray = CryptoJS.enc.Base64url.parse(base64String);
  38175. */
  38176. parse: function(base64Str, urlSafe) {
  38177. if (urlSafe === void 0) {
  38178. urlSafe = true;
  38179. }
  38180. var base64StrLength = base64Str.length;
  38181. var map = urlSafe ? this._safe_map : this._map;
  38182. var reverseMap = this._reverseMap;
  38183. if (!reverseMap) {
  38184. reverseMap = this._reverseMap = [];
  38185. for (var j2 = 0; j2 < map.length; j2++) {
  38186. reverseMap[map.charCodeAt(j2)] = j2;
  38187. }
  38188. }
  38189. var paddingChar = map.charAt(64);
  38190. if (paddingChar) {
  38191. var paddingIndex = base64Str.indexOf(paddingChar);
  38192. if (paddingIndex !== -1) {
  38193. base64StrLength = paddingIndex;
  38194. }
  38195. }
  38196. return parseLoop(base64Str, base64StrLength, reverseMap);
  38197. },
  38198. _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  38199. _safe_map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
  38200. };
  38201. function parseLoop(base64Str, base64StrLength, reverseMap) {
  38202. var words = [];
  38203. var nBytes = 0;
  38204. for (var i2 = 0; i2 < base64StrLength; i2++) {
  38205. if (i2 % 4) {
  38206. var bits1 = reverseMap[base64Str.charCodeAt(i2 - 1)] << i2 % 4 * 2;
  38207. var bits2 = reverseMap[base64Str.charCodeAt(i2)] >>> 6 - i2 % 4 * 2;
  38208. var bitsCombined = bits1 | bits2;
  38209. words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8;
  38210. nBytes++;
  38211. }
  38212. }
  38213. return WordArray.create(words, nBytes);
  38214. }
  38215. })();
  38216. return CryptoJS2.enc.Base64url;
  38217. });
  38218. })(encBase64url);
  38219. return encBase64url.exports;
  38220. }
  38221. var md5 = { exports: {} };
  38222. var hasRequiredMd5;
  38223. function requireMd5() {
  38224. if (hasRequiredMd5)
  38225. return md5.exports;
  38226. hasRequiredMd5 = 1;
  38227. (function(module, exports) {
  38228. (function(root, factory) {
  38229. {
  38230. module.exports = factory(requireCore());
  38231. }
  38232. })(commonjsGlobal, function(CryptoJS2) {
  38233. (function(Math2) {
  38234. var C2 = CryptoJS2;
  38235. var C_lib = C2.lib;
  38236. var WordArray = C_lib.WordArray;
  38237. var Hasher = C_lib.Hasher;
  38238. var C_algo = C2.algo;
  38239. var T2 = [];
  38240. (function() {
  38241. for (var i2 = 0; i2 < 64; i2++) {
  38242. T2[i2] = Math2.abs(Math2.sin(i2 + 1)) * 4294967296 | 0;
  38243. }
  38244. })();
  38245. var MD5 = C_algo.MD5 = Hasher.extend({
  38246. _doReset: function() {
  38247. this._hash = new WordArray.init([
  38248. 1732584193,
  38249. 4023233417,
  38250. 2562383102,
  38251. 271733878
  38252. ]);
  38253. },
  38254. _doProcessBlock: function(M2, offset) {
  38255. for (var i2 = 0; i2 < 16; i2++) {
  38256. var offset_i = offset + i2;
  38257. var M_offset_i = M2[offset_i];
  38258. M2[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 16711935 | (M_offset_i << 24 | M_offset_i >>> 8) & 4278255360;
  38259. }
  38260. var H2 = this._hash.words;
  38261. var M_offset_0 = M2[offset + 0];
  38262. var M_offset_1 = M2[offset + 1];
  38263. var M_offset_2 = M2[offset + 2];
  38264. var M_offset_3 = M2[offset + 3];
  38265. var M_offset_4 = M2[offset + 4];
  38266. var M_offset_5 = M2[offset + 5];
  38267. var M_offset_6 = M2[offset + 6];
  38268. var M_offset_7 = M2[offset + 7];
  38269. var M_offset_8 = M2[offset + 8];
  38270. var M_offset_9 = M2[offset + 9];
  38271. var M_offset_10 = M2[offset + 10];
  38272. var M_offset_11 = M2[offset + 11];
  38273. var M_offset_12 = M2[offset + 12];
  38274. var M_offset_13 = M2[offset + 13];
  38275. var M_offset_14 = M2[offset + 14];
  38276. var M_offset_15 = M2[offset + 15];
  38277. var a2 = H2[0];
  38278. var b2 = H2[1];
  38279. var c2 = H2[2];
  38280. var d2 = H2[3];
  38281. a2 = FF(a2, b2, c2, d2, M_offset_0, 7, T2[0]);
  38282. d2 = FF(d2, a2, b2, c2, M_offset_1, 12, T2[1]);
  38283. c2 = FF(c2, d2, a2, b2, M_offset_2, 17, T2[2]);
  38284. b2 = FF(b2, c2, d2, a2, M_offset_3, 22, T2[3]);
  38285. a2 = FF(a2, b2, c2, d2, M_offset_4, 7, T2[4]);
  38286. d2 = FF(d2, a2, b2, c2, M_offset_5, 12, T2[5]);
  38287. c2 = FF(c2, d2, a2, b2, M_offset_6, 17, T2[6]);
  38288. b2 = FF(b2, c2, d2, a2, M_offset_7, 22, T2[7]);
  38289. a2 = FF(a2, b2, c2, d2, M_offset_8, 7, T2[8]);
  38290. d2 = FF(d2, a2, b2, c2, M_offset_9, 12, T2[9]);
  38291. c2 = FF(c2, d2, a2, b2, M_offset_10, 17, T2[10]);
  38292. b2 = FF(b2, c2, d2, a2, M_offset_11, 22, T2[11]);
  38293. a2 = FF(a2, b2, c2, d2, M_offset_12, 7, T2[12]);
  38294. d2 = FF(d2, a2, b2, c2, M_offset_13, 12, T2[13]);
  38295. c2 = FF(c2, d2, a2, b2, M_offset_14, 17, T2[14]);
  38296. b2 = FF(b2, c2, d2, a2, M_offset_15, 22, T2[15]);
  38297. a2 = GG(a2, b2, c2, d2, M_offset_1, 5, T2[16]);
  38298. d2 = GG(d2, a2, b2, c2, M_offset_6, 9, T2[17]);
  38299. c2 = GG(c2, d2, a2, b2, M_offset_11, 14, T2[18]);
  38300. b2 = GG(b2, c2, d2, a2, M_offset_0, 20, T2[19]);
  38301. a2 = GG(a2, b2, c2, d2, M_offset_5, 5, T2[20]);
  38302. d2 = GG(d2, a2, b2, c2, M_offset_10, 9, T2[21]);
  38303. c2 = GG(c2, d2, a2, b2, M_offset_15, 14, T2[22]);
  38304. b2 = GG(b2, c2, d2, a2, M_offset_4, 20, T2[23]);
  38305. a2 = GG(a2, b2, c2, d2, M_offset_9, 5, T2[24]);
  38306. d2 = GG(d2, a2, b2, c2, M_offset_14, 9, T2[25]);
  38307. c2 = GG(c2, d2, a2, b2, M_offset_3, 14, T2[26]);
  38308. b2 = GG(b2, c2, d2, a2, M_offset_8, 20, T2[27]);
  38309. a2 = GG(a2, b2, c2, d2, M_offset_13, 5, T2[28]);
  38310. d2 = GG(d2, a2, b2, c2, M_offset_2, 9, T2[29]);
  38311. c2 = GG(c2, d2, a2, b2, M_offset_7, 14, T2[30]);
  38312. b2 = GG(b2, c2, d2, a2, M_offset_12, 20, T2[31]);
  38313. a2 = HH(a2, b2, c2, d2, M_offset_5, 4, T2[32]);
  38314. d2 = HH(d2, a2, b2, c2, M_offset_8, 11, T2[33]);
  38315. c2 = HH(c2, d2, a2, b2, M_offset_11, 16, T2[34]);
  38316. b2 = HH(b2, c2, d2, a2, M_offset_14, 23, T2[35]);
  38317. a2 = HH(a2, b2, c2, d2, M_offset_1, 4, T2[36]);
  38318. d2 = HH(d2, a2, b2, c2, M_offset_4, 11, T2[37]);
  38319. c2 = HH(c2, d2, a2, b2, M_offset_7, 16, T2[38]);
  38320. b2 = HH(b2, c2, d2, a2, M_offset_10, 23, T2[39]);
  38321. a2 = HH(a2, b2, c2, d2, M_offset_13, 4, T2[40]);
  38322. d2 = HH(d2, a2, b2, c2, M_offset_0, 11, T2[41]);
  38323. c2 = HH(c2, d2, a2, b2, M_offset_3, 16, T2[42]);
  38324. b2 = HH(b2, c2, d2, a2, M_offset_6, 23, T2[43]);
  38325. a2 = HH(a2, b2, c2, d2, M_offset_9, 4, T2[44]);
  38326. d2 = HH(d2, a2, b2, c2, M_offset_12, 11, T2[45]);
  38327. c2 = HH(c2, d2, a2, b2, M_offset_15, 16, T2[46]);
  38328. b2 = HH(b2, c2, d2, a2, M_offset_2, 23, T2[47]);
  38329. a2 = II(a2, b2, c2, d2, M_offset_0, 6, T2[48]);
  38330. d2 = II(d2, a2, b2, c2, M_offset_7, 10, T2[49]);
  38331. c2 = II(c2, d2, a2, b2, M_offset_14, 15, T2[50]);
  38332. b2 = II(b2, c2, d2, a2, M_offset_5, 21, T2[51]);
  38333. a2 = II(a2, b2, c2, d2, M_offset_12, 6, T2[52]);
  38334. d2 = II(d2, a2, b2, c2, M_offset_3, 10, T2[53]);
  38335. c2 = II(c2, d2, a2, b2, M_offset_10, 15, T2[54]);
  38336. b2 = II(b2, c2, d2, a2, M_offset_1, 21, T2[55]);
  38337. a2 = II(a2, b2, c2, d2, M_offset_8, 6, T2[56]);
  38338. d2 = II(d2, a2, b2, c2, M_offset_15, 10, T2[57]);
  38339. c2 = II(c2, d2, a2, b2, M_offset_6, 15, T2[58]);
  38340. b2 = II(b2, c2, d2, a2, M_offset_13, 21, T2[59]);
  38341. a2 = II(a2, b2, c2, d2, M_offset_4, 6, T2[60]);
  38342. d2 = II(d2, a2, b2, c2, M_offset_11, 10, T2[61]);
  38343. c2 = II(c2, d2, a2, b2, M_offset_2, 15, T2[62]);
  38344. b2 = II(b2, c2, d2, a2, M_offset_9, 21, T2[63]);
  38345. H2[0] = H2[0] + a2 | 0;
  38346. H2[1] = H2[1] + b2 | 0;
  38347. H2[2] = H2[2] + c2 | 0;
  38348. H2[3] = H2[3] + d2 | 0;
  38349. },
  38350. _doFinalize: function() {
  38351. var data = this._data;
  38352. var dataWords = data.words;
  38353. var nBitsTotal = this._nDataBytes * 8;
  38354. var nBitsLeft = data.sigBytes * 8;
  38355. dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  38356. var nBitsTotalH = Math2.floor(nBitsTotal / 4294967296);
  38357. var nBitsTotalL = nBitsTotal;
  38358. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = (nBitsTotalH << 8 | nBitsTotalH >>> 24) & 16711935 | (nBitsTotalH << 24 | nBitsTotalH >>> 8) & 4278255360;
  38359. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotalL << 8 | nBitsTotalL >>> 24) & 16711935 | (nBitsTotalL << 24 | nBitsTotalL >>> 8) & 4278255360;
  38360. data.sigBytes = (dataWords.length + 1) * 4;
  38361. this._process();
  38362. var hash2 = this._hash;
  38363. var H2 = hash2.words;
  38364. for (var i2 = 0; i2 < 4; i2++) {
  38365. var H_i = H2[i2];
  38366. H2[i2] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360;
  38367. }
  38368. return hash2;
  38369. },
  38370. clone: function() {
  38371. var clone2 = Hasher.clone.call(this);
  38372. clone2._hash = this._hash.clone();
  38373. return clone2;
  38374. }
  38375. });
  38376. function FF(a2, b2, c2, d2, x, s2, t2) {
  38377. var n2 = a2 + (b2 & c2 | ~b2 & d2) + x + t2;
  38378. return (n2 << s2 | n2 >>> 32 - s2) + b2;
  38379. }
  38380. function GG(a2, b2, c2, d2, x, s2, t2) {
  38381. var n2 = a2 + (b2 & d2 | c2 & ~d2) + x + t2;
  38382. return (n2 << s2 | n2 >>> 32 - s2) + b2;
  38383. }
  38384. function HH(a2, b2, c2, d2, x, s2, t2) {
  38385. var n2 = a2 + (b2 ^ c2 ^ d2) + x + t2;
  38386. return (n2 << s2 | n2 >>> 32 - s2) + b2;
  38387. }
  38388. function II(a2, b2, c2, d2, x, s2, t2) {
  38389. var n2 = a2 + (c2 ^ (b2 | ~d2)) + x + t2;
  38390. return (n2 << s2 | n2 >>> 32 - s2) + b2;
  38391. }
  38392. C2.MD5 = Hasher._createHelper(MD5);
  38393. C2.HmacMD5 = Hasher._createHmacHelper(MD5);
  38394. })(Math);
  38395. return CryptoJS2.MD5;
  38396. });
  38397. })(md5);
  38398. return md5.exports;
  38399. }
  38400. var sha1 = { exports: {} };
  38401. var hasRequiredSha1;
  38402. function requireSha1() {
  38403. if (hasRequiredSha1)
  38404. return sha1.exports;
  38405. hasRequiredSha1 = 1;
  38406. (function(module, exports) {
  38407. (function(root, factory) {
  38408. {
  38409. module.exports = factory(requireCore());
  38410. }
  38411. })(commonjsGlobal, function(CryptoJS2) {
  38412. (function() {
  38413. var C2 = CryptoJS2;
  38414. var C_lib = C2.lib;
  38415. var WordArray = C_lib.WordArray;
  38416. var Hasher = C_lib.Hasher;
  38417. var C_algo = C2.algo;
  38418. var W2 = [];
  38419. var SHA1 = C_algo.SHA1 = Hasher.extend({
  38420. _doReset: function() {
  38421. this._hash = new WordArray.init([
  38422. 1732584193,
  38423. 4023233417,
  38424. 2562383102,
  38425. 271733878,
  38426. 3285377520
  38427. ]);
  38428. },
  38429. _doProcessBlock: function(M2, offset) {
  38430. var H2 = this._hash.words;
  38431. var a2 = H2[0];
  38432. var b2 = H2[1];
  38433. var c2 = H2[2];
  38434. var d2 = H2[3];
  38435. var e2 = H2[4];
  38436. for (var i2 = 0; i2 < 80; i2++) {
  38437. if (i2 < 16) {
  38438. W2[i2] = M2[offset + i2] | 0;
  38439. } else {
  38440. var n2 = W2[i2 - 3] ^ W2[i2 - 8] ^ W2[i2 - 14] ^ W2[i2 - 16];
  38441. W2[i2] = n2 << 1 | n2 >>> 31;
  38442. }
  38443. var t2 = (a2 << 5 | a2 >>> 27) + e2 + W2[i2];
  38444. if (i2 < 20) {
  38445. t2 += (b2 & c2 | ~b2 & d2) + 1518500249;
  38446. } else if (i2 < 40) {
  38447. t2 += (b2 ^ c2 ^ d2) + 1859775393;
  38448. } else if (i2 < 60) {
  38449. t2 += (b2 & c2 | b2 & d2 | c2 & d2) - 1894007588;
  38450. } else {
  38451. t2 += (b2 ^ c2 ^ d2) - 899497514;
  38452. }
  38453. e2 = d2;
  38454. d2 = c2;
  38455. c2 = b2 << 30 | b2 >>> 2;
  38456. b2 = a2;
  38457. a2 = t2;
  38458. }
  38459. H2[0] = H2[0] + a2 | 0;
  38460. H2[1] = H2[1] + b2 | 0;
  38461. H2[2] = H2[2] + c2 | 0;
  38462. H2[3] = H2[3] + d2 | 0;
  38463. H2[4] = H2[4] + e2 | 0;
  38464. },
  38465. _doFinalize: function() {
  38466. var data = this._data;
  38467. var dataWords = data.words;
  38468. var nBitsTotal = this._nDataBytes * 8;
  38469. var nBitsLeft = data.sigBytes * 8;
  38470. dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  38471. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(nBitsTotal / 4294967296);
  38472. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
  38473. data.sigBytes = dataWords.length * 4;
  38474. this._process();
  38475. return this._hash;
  38476. },
  38477. clone: function() {
  38478. var clone2 = Hasher.clone.call(this);
  38479. clone2._hash = this._hash.clone();
  38480. return clone2;
  38481. }
  38482. });
  38483. C2.SHA1 = Hasher._createHelper(SHA1);
  38484. C2.HmacSHA1 = Hasher._createHmacHelper(SHA1);
  38485. })();
  38486. return CryptoJS2.SHA1;
  38487. });
  38488. })(sha1);
  38489. return sha1.exports;
  38490. }
  38491. var sha256 = { exports: {} };
  38492. var hasRequiredSha256;
  38493. function requireSha256() {
  38494. if (hasRequiredSha256)
  38495. return sha256.exports;
  38496. hasRequiredSha256 = 1;
  38497. (function(module, exports) {
  38498. (function(root, factory) {
  38499. {
  38500. module.exports = factory(requireCore());
  38501. }
  38502. })(commonjsGlobal, function(CryptoJS2) {
  38503. (function(Math2) {
  38504. var C2 = CryptoJS2;
  38505. var C_lib = C2.lib;
  38506. var WordArray = C_lib.WordArray;
  38507. var Hasher = C_lib.Hasher;
  38508. var C_algo = C2.algo;
  38509. var H2 = [];
  38510. var K2 = [];
  38511. (function() {
  38512. function isPrime(n3) {
  38513. var sqrtN = Math2.sqrt(n3);
  38514. for (var factor = 2; factor <= sqrtN; factor++) {
  38515. if (!(n3 % factor)) {
  38516. return false;
  38517. }
  38518. }
  38519. return true;
  38520. }
  38521. function getFractionalBits(n3) {
  38522. return (n3 - (n3 | 0)) * 4294967296 | 0;
  38523. }
  38524. var n2 = 2;
  38525. var nPrime = 0;
  38526. while (nPrime < 64) {
  38527. if (isPrime(n2)) {
  38528. if (nPrime < 8) {
  38529. H2[nPrime] = getFractionalBits(Math2.pow(n2, 1 / 2));
  38530. }
  38531. K2[nPrime] = getFractionalBits(Math2.pow(n2, 1 / 3));
  38532. nPrime++;
  38533. }
  38534. n2++;
  38535. }
  38536. })();
  38537. var W2 = [];
  38538. var SHA256 = C_algo.SHA256 = Hasher.extend({
  38539. _doReset: function() {
  38540. this._hash = new WordArray.init(H2.slice(0));
  38541. },
  38542. _doProcessBlock: function(M2, offset) {
  38543. var H3 = this._hash.words;
  38544. var a2 = H3[0];
  38545. var b2 = H3[1];
  38546. var c2 = H3[2];
  38547. var d2 = H3[3];
  38548. var e2 = H3[4];
  38549. var f2 = H3[5];
  38550. var g2 = H3[6];
  38551. var h2 = H3[7];
  38552. for (var i2 = 0; i2 < 64; i2++) {
  38553. if (i2 < 16) {
  38554. W2[i2] = M2[offset + i2] | 0;
  38555. } else {
  38556. var gamma0x = W2[i2 - 15];
  38557. var gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
  38558. var gamma1x = W2[i2 - 2];
  38559. var gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
  38560. W2[i2] = gamma0 + W2[i2 - 7] + gamma1 + W2[i2 - 16];
  38561. }
  38562. var ch = e2 & f2 ^ ~e2 & g2;
  38563. var maj = a2 & b2 ^ a2 & c2 ^ b2 & c2;
  38564. var sigma0 = (a2 << 30 | a2 >>> 2) ^ (a2 << 19 | a2 >>> 13) ^ (a2 << 10 | a2 >>> 22);
  38565. var sigma1 = (e2 << 26 | e2 >>> 6) ^ (e2 << 21 | e2 >>> 11) ^ (e2 << 7 | e2 >>> 25);
  38566. var t1 = h2 + sigma1 + ch + K2[i2] + W2[i2];
  38567. var t2 = sigma0 + maj;
  38568. h2 = g2;
  38569. g2 = f2;
  38570. f2 = e2;
  38571. e2 = d2 + t1 | 0;
  38572. d2 = c2;
  38573. c2 = b2;
  38574. b2 = a2;
  38575. a2 = t1 + t2 | 0;
  38576. }
  38577. H3[0] = H3[0] + a2 | 0;
  38578. H3[1] = H3[1] + b2 | 0;
  38579. H3[2] = H3[2] + c2 | 0;
  38580. H3[3] = H3[3] + d2 | 0;
  38581. H3[4] = H3[4] + e2 | 0;
  38582. H3[5] = H3[5] + f2 | 0;
  38583. H3[6] = H3[6] + g2 | 0;
  38584. H3[7] = H3[7] + h2 | 0;
  38585. },
  38586. _doFinalize: function() {
  38587. var data = this._data;
  38588. var dataWords = data.words;
  38589. var nBitsTotal = this._nDataBytes * 8;
  38590. var nBitsLeft = data.sigBytes * 8;
  38591. dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  38592. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math2.floor(nBitsTotal / 4294967296);
  38593. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
  38594. data.sigBytes = dataWords.length * 4;
  38595. this._process();
  38596. return this._hash;
  38597. },
  38598. clone: function() {
  38599. var clone2 = Hasher.clone.call(this);
  38600. clone2._hash = this._hash.clone();
  38601. return clone2;
  38602. }
  38603. });
  38604. C2.SHA256 = Hasher._createHelper(SHA256);
  38605. C2.HmacSHA256 = Hasher._createHmacHelper(SHA256);
  38606. })(Math);
  38607. return CryptoJS2.SHA256;
  38608. });
  38609. })(sha256);
  38610. return sha256.exports;
  38611. }
  38612. var sha224 = { exports: {} };
  38613. var hasRequiredSha224;
  38614. function requireSha224() {
  38615. if (hasRequiredSha224)
  38616. return sha224.exports;
  38617. hasRequiredSha224 = 1;
  38618. (function(module, exports) {
  38619. (function(root, factory, undef) {
  38620. {
  38621. module.exports = factory(requireCore(), requireSha256());
  38622. }
  38623. })(commonjsGlobal, function(CryptoJS2) {
  38624. (function() {
  38625. var C2 = CryptoJS2;
  38626. var C_lib = C2.lib;
  38627. var WordArray = C_lib.WordArray;
  38628. var C_algo = C2.algo;
  38629. var SHA256 = C_algo.SHA256;
  38630. var SHA224 = C_algo.SHA224 = SHA256.extend({
  38631. _doReset: function() {
  38632. this._hash = new WordArray.init([
  38633. 3238371032,
  38634. 914150663,
  38635. 812702999,
  38636. 4144912697,
  38637. 4290775857,
  38638. 1750603025,
  38639. 1694076839,
  38640. 3204075428
  38641. ]);
  38642. },
  38643. _doFinalize: function() {
  38644. var hash2 = SHA256._doFinalize.call(this);
  38645. hash2.sigBytes -= 4;
  38646. return hash2;
  38647. }
  38648. });
  38649. C2.SHA224 = SHA256._createHelper(SHA224);
  38650. C2.HmacSHA224 = SHA256._createHmacHelper(SHA224);
  38651. })();
  38652. return CryptoJS2.SHA224;
  38653. });
  38654. })(sha224);
  38655. return sha224.exports;
  38656. }
  38657. var sha512 = { exports: {} };
  38658. var hasRequiredSha512;
  38659. function requireSha512() {
  38660. if (hasRequiredSha512)
  38661. return sha512.exports;
  38662. hasRequiredSha512 = 1;
  38663. (function(module, exports) {
  38664. (function(root, factory, undef) {
  38665. {
  38666. module.exports = factory(requireCore(), requireX64Core());
  38667. }
  38668. })(commonjsGlobal, function(CryptoJS2) {
  38669. (function() {
  38670. var C2 = CryptoJS2;
  38671. var C_lib = C2.lib;
  38672. var Hasher = C_lib.Hasher;
  38673. var C_x64 = C2.x64;
  38674. var X64Word = C_x64.Word;
  38675. var X64WordArray = C_x64.WordArray;
  38676. var C_algo = C2.algo;
  38677. function X64Word_create() {
  38678. return X64Word.create.apply(X64Word, arguments);
  38679. }
  38680. var K2 = [
  38681. X64Word_create(1116352408, 3609767458),
  38682. X64Word_create(1899447441, 602891725),
  38683. X64Word_create(3049323471, 3964484399),
  38684. X64Word_create(3921009573, 2173295548),
  38685. X64Word_create(961987163, 4081628472),
  38686. X64Word_create(1508970993, 3053834265),
  38687. X64Word_create(2453635748, 2937671579),
  38688. X64Word_create(2870763221, 3664609560),
  38689. X64Word_create(3624381080, 2734883394),
  38690. X64Word_create(310598401, 1164996542),
  38691. X64Word_create(607225278, 1323610764),
  38692. X64Word_create(1426881987, 3590304994),
  38693. X64Word_create(1925078388, 4068182383),
  38694. X64Word_create(2162078206, 991336113),
  38695. X64Word_create(2614888103, 633803317),
  38696. X64Word_create(3248222580, 3479774868),
  38697. X64Word_create(3835390401, 2666613458),
  38698. X64Word_create(4022224774, 944711139),
  38699. X64Word_create(264347078, 2341262773),
  38700. X64Word_create(604807628, 2007800933),
  38701. X64Word_create(770255983, 1495990901),
  38702. X64Word_create(1249150122, 1856431235),
  38703. X64Word_create(1555081692, 3175218132),
  38704. X64Word_create(1996064986, 2198950837),
  38705. X64Word_create(2554220882, 3999719339),
  38706. X64Word_create(2821834349, 766784016),
  38707. X64Word_create(2952996808, 2566594879),
  38708. X64Word_create(3210313671, 3203337956),
  38709. X64Word_create(3336571891, 1034457026),
  38710. X64Word_create(3584528711, 2466948901),
  38711. X64Word_create(113926993, 3758326383),
  38712. X64Word_create(338241895, 168717936),
  38713. X64Word_create(666307205, 1188179964),
  38714. X64Word_create(773529912, 1546045734),
  38715. X64Word_create(1294757372, 1522805485),
  38716. X64Word_create(1396182291, 2643833823),
  38717. X64Word_create(1695183700, 2343527390),
  38718. X64Word_create(1986661051, 1014477480),
  38719. X64Word_create(2177026350, 1206759142),
  38720. X64Word_create(2456956037, 344077627),
  38721. X64Word_create(2730485921, 1290863460),
  38722. X64Word_create(2820302411, 3158454273),
  38723. X64Word_create(3259730800, 3505952657),
  38724. X64Word_create(3345764771, 106217008),
  38725. X64Word_create(3516065817, 3606008344),
  38726. X64Word_create(3600352804, 1432725776),
  38727. X64Word_create(4094571909, 1467031594),
  38728. X64Word_create(275423344, 851169720),
  38729. X64Word_create(430227734, 3100823752),
  38730. X64Word_create(506948616, 1363258195),
  38731. X64Word_create(659060556, 3750685593),
  38732. X64Word_create(883997877, 3785050280),
  38733. X64Word_create(958139571, 3318307427),
  38734. X64Word_create(1322822218, 3812723403),
  38735. X64Word_create(1537002063, 2003034995),
  38736. X64Word_create(1747873779, 3602036899),
  38737. X64Word_create(1955562222, 1575990012),
  38738. X64Word_create(2024104815, 1125592928),
  38739. X64Word_create(2227730452, 2716904306),
  38740. X64Word_create(2361852424, 442776044),
  38741. X64Word_create(2428436474, 593698344),
  38742. X64Word_create(2756734187, 3733110249),
  38743. X64Word_create(3204031479, 2999351573),
  38744. X64Word_create(3329325298, 3815920427),
  38745. X64Word_create(3391569614, 3928383900),
  38746. X64Word_create(3515267271, 566280711),
  38747. X64Word_create(3940187606, 3454069534),
  38748. X64Word_create(4118630271, 4000239992),
  38749. X64Word_create(116418474, 1914138554),
  38750. X64Word_create(174292421, 2731055270),
  38751. X64Word_create(289380356, 3203993006),
  38752. X64Word_create(460393269, 320620315),
  38753. X64Word_create(685471733, 587496836),
  38754. X64Word_create(852142971, 1086792851),
  38755. X64Word_create(1017036298, 365543100),
  38756. X64Word_create(1126000580, 2618297676),
  38757. X64Word_create(1288033470, 3409855158),
  38758. X64Word_create(1501505948, 4234509866),
  38759. X64Word_create(1607167915, 987167468),
  38760. X64Word_create(1816402316, 1246189591)
  38761. ];
  38762. var W2 = [];
  38763. (function() {
  38764. for (var i2 = 0; i2 < 80; i2++) {
  38765. W2[i2] = X64Word_create();
  38766. }
  38767. })();
  38768. var SHA512 = C_algo.SHA512 = Hasher.extend({
  38769. _doReset: function() {
  38770. this._hash = new X64WordArray.init([
  38771. new X64Word.init(1779033703, 4089235720),
  38772. new X64Word.init(3144134277, 2227873595),
  38773. new X64Word.init(1013904242, 4271175723),
  38774. new X64Word.init(2773480762, 1595750129),
  38775. new X64Word.init(1359893119, 2917565137),
  38776. new X64Word.init(2600822924, 725511199),
  38777. new X64Word.init(528734635, 4215389547),
  38778. new X64Word.init(1541459225, 327033209)
  38779. ]);
  38780. },
  38781. _doProcessBlock: function(M2, offset) {
  38782. var H2 = this._hash.words;
  38783. var H0 = H2[0];
  38784. var H1 = H2[1];
  38785. var H22 = H2[2];
  38786. var H3 = H2[3];
  38787. var H4 = H2[4];
  38788. var H5 = H2[5];
  38789. var H6 = H2[6];
  38790. var H7 = H2[7];
  38791. var H0h = H0.high;
  38792. var H0l = H0.low;
  38793. var H1h = H1.high;
  38794. var H1l = H1.low;
  38795. var H2h = H22.high;
  38796. var H2l = H22.low;
  38797. var H3h = H3.high;
  38798. var H3l = H3.low;
  38799. var H4h = H4.high;
  38800. var H4l = H4.low;
  38801. var H5h = H5.high;
  38802. var H5l = H5.low;
  38803. var H6h = H6.high;
  38804. var H6l = H6.low;
  38805. var H7h = H7.high;
  38806. var H7l = H7.low;
  38807. var ah = H0h;
  38808. var al = H0l;
  38809. var bh = H1h;
  38810. var bl = H1l;
  38811. var ch = H2h;
  38812. var cl = H2l;
  38813. var dh = H3h;
  38814. var dl = H3l;
  38815. var eh = H4h;
  38816. var el = H4l;
  38817. var fh = H5h;
  38818. var fl = H5l;
  38819. var gh = H6h;
  38820. var gl = H6l;
  38821. var hh = H7h;
  38822. var hl = H7l;
  38823. for (var i2 = 0; i2 < 80; i2++) {
  38824. var Wil;
  38825. var Wih;
  38826. var Wi = W2[i2];
  38827. if (i2 < 16) {
  38828. Wih = Wi.high = M2[offset + i2 * 2] | 0;
  38829. Wil = Wi.low = M2[offset + i2 * 2 + 1] | 0;
  38830. } else {
  38831. var gamma0x = W2[i2 - 15];
  38832. var gamma0xh = gamma0x.high;
  38833. var gamma0xl = gamma0x.low;
  38834. var gamma0h = (gamma0xh >>> 1 | gamma0xl << 31) ^ (gamma0xh >>> 8 | gamma0xl << 24) ^ gamma0xh >>> 7;
  38835. var gamma0l = (gamma0xl >>> 1 | gamma0xh << 31) ^ (gamma0xl >>> 8 | gamma0xh << 24) ^ (gamma0xl >>> 7 | gamma0xh << 25);
  38836. var gamma1x = W2[i2 - 2];
  38837. var gamma1xh = gamma1x.high;
  38838. var gamma1xl = gamma1x.low;
  38839. var gamma1h = (gamma1xh >>> 19 | gamma1xl << 13) ^ (gamma1xh << 3 | gamma1xl >>> 29) ^ gamma1xh >>> 6;
  38840. var gamma1l = (gamma1xl >>> 19 | gamma1xh << 13) ^ (gamma1xl << 3 | gamma1xh >>> 29) ^ (gamma1xl >>> 6 | gamma1xh << 26);
  38841. var Wi7 = W2[i2 - 7];
  38842. var Wi7h = Wi7.high;
  38843. var Wi7l = Wi7.low;
  38844. var Wi16 = W2[i2 - 16];
  38845. var Wi16h = Wi16.high;
  38846. var Wi16l = Wi16.low;
  38847. Wil = gamma0l + Wi7l;
  38848. Wih = gamma0h + Wi7h + (Wil >>> 0 < gamma0l >>> 0 ? 1 : 0);
  38849. Wil = Wil + gamma1l;
  38850. Wih = Wih + gamma1h + (Wil >>> 0 < gamma1l >>> 0 ? 1 : 0);
  38851. Wil = Wil + Wi16l;
  38852. Wih = Wih + Wi16h + (Wil >>> 0 < Wi16l >>> 0 ? 1 : 0);
  38853. Wi.high = Wih;
  38854. Wi.low = Wil;
  38855. }
  38856. var chh = eh & fh ^ ~eh & gh;
  38857. var chl = el & fl ^ ~el & gl;
  38858. var majh = ah & bh ^ ah & ch ^ bh & ch;
  38859. var majl = al & bl ^ al & cl ^ bl & cl;
  38860. var sigma0h = (ah >>> 28 | al << 4) ^ (ah << 30 | al >>> 2) ^ (ah << 25 | al >>> 7);
  38861. var sigma0l = (al >>> 28 | ah << 4) ^ (al << 30 | ah >>> 2) ^ (al << 25 | ah >>> 7);
  38862. var sigma1h = (eh >>> 14 | el << 18) ^ (eh >>> 18 | el << 14) ^ (eh << 23 | el >>> 9);
  38863. var sigma1l = (el >>> 14 | eh << 18) ^ (el >>> 18 | eh << 14) ^ (el << 23 | eh >>> 9);
  38864. var Ki = K2[i2];
  38865. var Kih = Ki.high;
  38866. var Kil = Ki.low;
  38867. var t1l = hl + sigma1l;
  38868. var t1h = hh + sigma1h + (t1l >>> 0 < hl >>> 0 ? 1 : 0);
  38869. var t1l = t1l + chl;
  38870. var t1h = t1h + chh + (t1l >>> 0 < chl >>> 0 ? 1 : 0);
  38871. var t1l = t1l + Kil;
  38872. var t1h = t1h + Kih + (t1l >>> 0 < Kil >>> 0 ? 1 : 0);
  38873. var t1l = t1l + Wil;
  38874. var t1h = t1h + Wih + (t1l >>> 0 < Wil >>> 0 ? 1 : 0);
  38875. var t2l = sigma0l + majl;
  38876. var t2h = sigma0h + majh + (t2l >>> 0 < sigma0l >>> 0 ? 1 : 0);
  38877. hh = gh;
  38878. hl = gl;
  38879. gh = fh;
  38880. gl = fl;
  38881. fh = eh;
  38882. fl = el;
  38883. el = dl + t1l | 0;
  38884. eh = dh + t1h + (el >>> 0 < dl >>> 0 ? 1 : 0) | 0;
  38885. dh = ch;
  38886. dl = cl;
  38887. ch = bh;
  38888. cl = bl;
  38889. bh = ah;
  38890. bl = al;
  38891. al = t1l + t2l | 0;
  38892. ah = t1h + t2h + (al >>> 0 < t1l >>> 0 ? 1 : 0) | 0;
  38893. }
  38894. H0l = H0.low = H0l + al;
  38895. H0.high = H0h + ah + (H0l >>> 0 < al >>> 0 ? 1 : 0);
  38896. H1l = H1.low = H1l + bl;
  38897. H1.high = H1h + bh + (H1l >>> 0 < bl >>> 0 ? 1 : 0);
  38898. H2l = H22.low = H2l + cl;
  38899. H22.high = H2h + ch + (H2l >>> 0 < cl >>> 0 ? 1 : 0);
  38900. H3l = H3.low = H3l + dl;
  38901. H3.high = H3h + dh + (H3l >>> 0 < dl >>> 0 ? 1 : 0);
  38902. H4l = H4.low = H4l + el;
  38903. H4.high = H4h + eh + (H4l >>> 0 < el >>> 0 ? 1 : 0);
  38904. H5l = H5.low = H5l + fl;
  38905. H5.high = H5h + fh + (H5l >>> 0 < fl >>> 0 ? 1 : 0);
  38906. H6l = H6.low = H6l + gl;
  38907. H6.high = H6h + gh + (H6l >>> 0 < gl >>> 0 ? 1 : 0);
  38908. H7l = H7.low = H7l + hl;
  38909. H7.high = H7h + hh + (H7l >>> 0 < hl >>> 0 ? 1 : 0);
  38910. },
  38911. _doFinalize: function() {
  38912. var data = this._data;
  38913. var dataWords = data.words;
  38914. var nBitsTotal = this._nDataBytes * 8;
  38915. var nBitsLeft = data.sigBytes * 8;
  38916. dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  38917. dataWords[(nBitsLeft + 128 >>> 10 << 5) + 30] = Math.floor(nBitsTotal / 4294967296);
  38918. dataWords[(nBitsLeft + 128 >>> 10 << 5) + 31] = nBitsTotal;
  38919. data.sigBytes = dataWords.length * 4;
  38920. this._process();
  38921. var hash2 = this._hash.toX32();
  38922. return hash2;
  38923. },
  38924. clone: function() {
  38925. var clone2 = Hasher.clone.call(this);
  38926. clone2._hash = this._hash.clone();
  38927. return clone2;
  38928. },
  38929. blockSize: 1024 / 32
  38930. });
  38931. C2.SHA512 = Hasher._createHelper(SHA512);
  38932. C2.HmacSHA512 = Hasher._createHmacHelper(SHA512);
  38933. })();
  38934. return CryptoJS2.SHA512;
  38935. });
  38936. })(sha512);
  38937. return sha512.exports;
  38938. }
  38939. var sha384 = { exports: {} };
  38940. var hasRequiredSha384;
  38941. function requireSha384() {
  38942. if (hasRequiredSha384)
  38943. return sha384.exports;
  38944. hasRequiredSha384 = 1;
  38945. (function(module, exports) {
  38946. (function(root, factory, undef) {
  38947. {
  38948. module.exports = factory(requireCore(), requireX64Core(), requireSha512());
  38949. }
  38950. })(commonjsGlobal, function(CryptoJS2) {
  38951. (function() {
  38952. var C2 = CryptoJS2;
  38953. var C_x64 = C2.x64;
  38954. var X64Word = C_x64.Word;
  38955. var X64WordArray = C_x64.WordArray;
  38956. var C_algo = C2.algo;
  38957. var SHA512 = C_algo.SHA512;
  38958. var SHA384 = C_algo.SHA384 = SHA512.extend({
  38959. _doReset: function() {
  38960. this._hash = new X64WordArray.init([
  38961. new X64Word.init(3418070365, 3238371032),
  38962. new X64Word.init(1654270250, 914150663),
  38963. new X64Word.init(2438529370, 812702999),
  38964. new X64Word.init(355462360, 4144912697),
  38965. new X64Word.init(1731405415, 4290775857),
  38966. new X64Word.init(2394180231, 1750603025),
  38967. new X64Word.init(3675008525, 1694076839),
  38968. new X64Word.init(1203062813, 3204075428)
  38969. ]);
  38970. },
  38971. _doFinalize: function() {
  38972. var hash2 = SHA512._doFinalize.call(this);
  38973. hash2.sigBytes -= 16;
  38974. return hash2;
  38975. }
  38976. });
  38977. C2.SHA384 = SHA512._createHelper(SHA384);
  38978. C2.HmacSHA384 = SHA512._createHmacHelper(SHA384);
  38979. })();
  38980. return CryptoJS2.SHA384;
  38981. });
  38982. })(sha384);
  38983. return sha384.exports;
  38984. }
  38985. var sha3 = { exports: {} };
  38986. var hasRequiredSha3;
  38987. function requireSha3() {
  38988. if (hasRequiredSha3)
  38989. return sha3.exports;
  38990. hasRequiredSha3 = 1;
  38991. (function(module, exports) {
  38992. (function(root, factory, undef) {
  38993. {
  38994. module.exports = factory(requireCore(), requireX64Core());
  38995. }
  38996. })(commonjsGlobal, function(CryptoJS2) {
  38997. (function(Math2) {
  38998. var C2 = CryptoJS2;
  38999. var C_lib = C2.lib;
  39000. var WordArray = C_lib.WordArray;
  39001. var Hasher = C_lib.Hasher;
  39002. var C_x64 = C2.x64;
  39003. var X64Word = C_x64.Word;
  39004. var C_algo = C2.algo;
  39005. var RHO_OFFSETS = [];
  39006. var PI_INDEXES = [];
  39007. var ROUND_CONSTANTS = [];
  39008. (function() {
  39009. var x = 1, y2 = 0;
  39010. for (var t2 = 0; t2 < 24; t2++) {
  39011. RHO_OFFSETS[x + 5 * y2] = (t2 + 1) * (t2 + 2) / 2 % 64;
  39012. var newX = y2 % 5;
  39013. var newY = (2 * x + 3 * y2) % 5;
  39014. x = newX;
  39015. y2 = newY;
  39016. }
  39017. for (var x = 0; x < 5; x++) {
  39018. for (var y2 = 0; y2 < 5; y2++) {
  39019. PI_INDEXES[x + 5 * y2] = y2 + (2 * x + 3 * y2) % 5 * 5;
  39020. }
  39021. }
  39022. var LFSR = 1;
  39023. for (var i2 = 0; i2 < 24; i2++) {
  39024. var roundConstantMsw = 0;
  39025. var roundConstantLsw = 0;
  39026. for (var j2 = 0; j2 < 7; j2++) {
  39027. if (LFSR & 1) {
  39028. var bitPosition = (1 << j2) - 1;
  39029. if (bitPosition < 32) {
  39030. roundConstantLsw ^= 1 << bitPosition;
  39031. } else {
  39032. roundConstantMsw ^= 1 << bitPosition - 32;
  39033. }
  39034. }
  39035. if (LFSR & 128) {
  39036. LFSR = LFSR << 1 ^ 113;
  39037. } else {
  39038. LFSR <<= 1;
  39039. }
  39040. }
  39041. ROUND_CONSTANTS[i2] = X64Word.create(roundConstantMsw, roundConstantLsw);
  39042. }
  39043. })();
  39044. var T2 = [];
  39045. (function() {
  39046. for (var i2 = 0; i2 < 25; i2++) {
  39047. T2[i2] = X64Word.create();
  39048. }
  39049. })();
  39050. var SHA3 = C_algo.SHA3 = Hasher.extend({
  39051. /**
  39052. * Configuration options.
  39053. *
  39054. * @property {number} outputLength
  39055. * The desired number of bits in the output hash.
  39056. * Only values permitted are: 224, 256, 384, 512.
  39057. * Default: 512
  39058. */
  39059. cfg: Hasher.cfg.extend({
  39060. outputLength: 512
  39061. }),
  39062. _doReset: function() {
  39063. var state = this._state = [];
  39064. for (var i2 = 0; i2 < 25; i2++) {
  39065. state[i2] = new X64Word.init();
  39066. }
  39067. this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
  39068. },
  39069. _doProcessBlock: function(M2, offset) {
  39070. var state = this._state;
  39071. var nBlockSizeLanes = this.blockSize / 2;
  39072. for (var i2 = 0; i2 < nBlockSizeLanes; i2++) {
  39073. var M2i = M2[offset + 2 * i2];
  39074. var M2i1 = M2[offset + 2 * i2 + 1];
  39075. M2i = (M2i << 8 | M2i >>> 24) & 16711935 | (M2i << 24 | M2i >>> 8) & 4278255360;
  39076. M2i1 = (M2i1 << 8 | M2i1 >>> 24) & 16711935 | (M2i1 << 24 | M2i1 >>> 8) & 4278255360;
  39077. var lane = state[i2];
  39078. lane.high ^= M2i1;
  39079. lane.low ^= M2i;
  39080. }
  39081. for (var round2 = 0; round2 < 24; round2++) {
  39082. for (var x = 0; x < 5; x++) {
  39083. var tMsw = 0, tLsw = 0;
  39084. for (var y2 = 0; y2 < 5; y2++) {
  39085. var lane = state[x + 5 * y2];
  39086. tMsw ^= lane.high;
  39087. tLsw ^= lane.low;
  39088. }
  39089. var Tx = T2[x];
  39090. Tx.high = tMsw;
  39091. Tx.low = tLsw;
  39092. }
  39093. for (var x = 0; x < 5; x++) {
  39094. var Tx4 = T2[(x + 4) % 5];
  39095. var Tx1 = T2[(x + 1) % 5];
  39096. var Tx1Msw = Tx1.high;
  39097. var Tx1Lsw = Tx1.low;
  39098. var tMsw = Tx4.high ^ (Tx1Msw << 1 | Tx1Lsw >>> 31);
  39099. var tLsw = Tx4.low ^ (Tx1Lsw << 1 | Tx1Msw >>> 31);
  39100. for (var y2 = 0; y2 < 5; y2++) {
  39101. var lane = state[x + 5 * y2];
  39102. lane.high ^= tMsw;
  39103. lane.low ^= tLsw;
  39104. }
  39105. }
  39106. for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
  39107. var tMsw;
  39108. var tLsw;
  39109. var lane = state[laneIndex];
  39110. var laneMsw = lane.high;
  39111. var laneLsw = lane.low;
  39112. var rhoOffset = RHO_OFFSETS[laneIndex];
  39113. if (rhoOffset < 32) {
  39114. tMsw = laneMsw << rhoOffset | laneLsw >>> 32 - rhoOffset;
  39115. tLsw = laneLsw << rhoOffset | laneMsw >>> 32 - rhoOffset;
  39116. } else {
  39117. tMsw = laneLsw << rhoOffset - 32 | laneMsw >>> 64 - rhoOffset;
  39118. tLsw = laneMsw << rhoOffset - 32 | laneLsw >>> 64 - rhoOffset;
  39119. }
  39120. var TPiLane = T2[PI_INDEXES[laneIndex]];
  39121. TPiLane.high = tMsw;
  39122. TPiLane.low = tLsw;
  39123. }
  39124. var T0 = T2[0];
  39125. var state0 = state[0];
  39126. T0.high = state0.high;
  39127. T0.low = state0.low;
  39128. for (var x = 0; x < 5; x++) {
  39129. for (var y2 = 0; y2 < 5; y2++) {
  39130. var laneIndex = x + 5 * y2;
  39131. var lane = state[laneIndex];
  39132. var TLane = T2[laneIndex];
  39133. var Tx1Lane = T2[(x + 1) % 5 + 5 * y2];
  39134. var Tx2Lane = T2[(x + 2) % 5 + 5 * y2];
  39135. lane.high = TLane.high ^ ~Tx1Lane.high & Tx2Lane.high;
  39136. lane.low = TLane.low ^ ~Tx1Lane.low & Tx2Lane.low;
  39137. }
  39138. }
  39139. var lane = state[0];
  39140. var roundConstant = ROUND_CONSTANTS[round2];
  39141. lane.high ^= roundConstant.high;
  39142. lane.low ^= roundConstant.low;
  39143. }
  39144. },
  39145. _doFinalize: function() {
  39146. var data = this._data;
  39147. var dataWords = data.words;
  39148. this._nDataBytes * 8;
  39149. var nBitsLeft = data.sigBytes * 8;
  39150. var blockSizeBits = this.blockSize * 32;
  39151. dataWords[nBitsLeft >>> 5] |= 1 << 24 - nBitsLeft % 32;
  39152. dataWords[(Math2.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits >>> 5) - 1] |= 128;
  39153. data.sigBytes = dataWords.length * 4;
  39154. this._process();
  39155. var state = this._state;
  39156. var outputLengthBytes = this.cfg.outputLength / 8;
  39157. var outputLengthLanes = outputLengthBytes / 8;
  39158. var hashWords = [];
  39159. for (var i2 = 0; i2 < outputLengthLanes; i2++) {
  39160. var lane = state[i2];
  39161. var laneMsw = lane.high;
  39162. var laneLsw = lane.low;
  39163. laneMsw = (laneMsw << 8 | laneMsw >>> 24) & 16711935 | (laneMsw << 24 | laneMsw >>> 8) & 4278255360;
  39164. laneLsw = (laneLsw << 8 | laneLsw >>> 24) & 16711935 | (laneLsw << 24 | laneLsw >>> 8) & 4278255360;
  39165. hashWords.push(laneLsw);
  39166. hashWords.push(laneMsw);
  39167. }
  39168. return new WordArray.init(hashWords, outputLengthBytes);
  39169. },
  39170. clone: function() {
  39171. var clone2 = Hasher.clone.call(this);
  39172. var state = clone2._state = this._state.slice(0);
  39173. for (var i2 = 0; i2 < 25; i2++) {
  39174. state[i2] = state[i2].clone();
  39175. }
  39176. return clone2;
  39177. }
  39178. });
  39179. C2.SHA3 = Hasher._createHelper(SHA3);
  39180. C2.HmacSHA3 = Hasher._createHmacHelper(SHA3);
  39181. })(Math);
  39182. return CryptoJS2.SHA3;
  39183. });
  39184. })(sha3);
  39185. return sha3.exports;
  39186. }
  39187. var ripemd160 = { exports: {} };
  39188. var hasRequiredRipemd160;
  39189. function requireRipemd160() {
  39190. if (hasRequiredRipemd160)
  39191. return ripemd160.exports;
  39192. hasRequiredRipemd160 = 1;
  39193. (function(module, exports) {
  39194. (function(root, factory) {
  39195. {
  39196. module.exports = factory(requireCore());
  39197. }
  39198. })(commonjsGlobal, function(CryptoJS2) {
  39199. /** @preserve
  39200. (c) 2012 by Cédric Mesnil. All rights reserved.
  39201. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  39202. - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  39203. - 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.
  39204. 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.
  39205. */
  39206. (function(Math2) {
  39207. var C2 = CryptoJS2;
  39208. var C_lib = C2.lib;
  39209. var WordArray = C_lib.WordArray;
  39210. var Hasher = C_lib.Hasher;
  39211. var C_algo = C2.algo;
  39212. var _zl = WordArray.create([
  39213. 0,
  39214. 1,
  39215. 2,
  39216. 3,
  39217. 4,
  39218. 5,
  39219. 6,
  39220. 7,
  39221. 8,
  39222. 9,
  39223. 10,
  39224. 11,
  39225. 12,
  39226. 13,
  39227. 14,
  39228. 15,
  39229. 7,
  39230. 4,
  39231. 13,
  39232. 1,
  39233. 10,
  39234. 6,
  39235. 15,
  39236. 3,
  39237. 12,
  39238. 0,
  39239. 9,
  39240. 5,
  39241. 2,
  39242. 14,
  39243. 11,
  39244. 8,
  39245. 3,
  39246. 10,
  39247. 14,
  39248. 4,
  39249. 9,
  39250. 15,
  39251. 8,
  39252. 1,
  39253. 2,
  39254. 7,
  39255. 0,
  39256. 6,
  39257. 13,
  39258. 11,
  39259. 5,
  39260. 12,
  39261. 1,
  39262. 9,
  39263. 11,
  39264. 10,
  39265. 0,
  39266. 8,
  39267. 12,
  39268. 4,
  39269. 13,
  39270. 3,
  39271. 7,
  39272. 15,
  39273. 14,
  39274. 5,
  39275. 6,
  39276. 2,
  39277. 4,
  39278. 0,
  39279. 5,
  39280. 9,
  39281. 7,
  39282. 12,
  39283. 2,
  39284. 10,
  39285. 14,
  39286. 1,
  39287. 3,
  39288. 8,
  39289. 11,
  39290. 6,
  39291. 15,
  39292. 13
  39293. ]);
  39294. var _zr = WordArray.create([
  39295. 5,
  39296. 14,
  39297. 7,
  39298. 0,
  39299. 9,
  39300. 2,
  39301. 11,
  39302. 4,
  39303. 13,
  39304. 6,
  39305. 15,
  39306. 8,
  39307. 1,
  39308. 10,
  39309. 3,
  39310. 12,
  39311. 6,
  39312. 11,
  39313. 3,
  39314. 7,
  39315. 0,
  39316. 13,
  39317. 5,
  39318. 10,
  39319. 14,
  39320. 15,
  39321. 8,
  39322. 12,
  39323. 4,
  39324. 9,
  39325. 1,
  39326. 2,
  39327. 15,
  39328. 5,
  39329. 1,
  39330. 3,
  39331. 7,
  39332. 14,
  39333. 6,
  39334. 9,
  39335. 11,
  39336. 8,
  39337. 12,
  39338. 2,
  39339. 10,
  39340. 0,
  39341. 4,
  39342. 13,
  39343. 8,
  39344. 6,
  39345. 4,
  39346. 1,
  39347. 3,
  39348. 11,
  39349. 15,
  39350. 0,
  39351. 5,
  39352. 12,
  39353. 2,
  39354. 13,
  39355. 9,
  39356. 7,
  39357. 10,
  39358. 14,
  39359. 12,
  39360. 15,
  39361. 10,
  39362. 4,
  39363. 1,
  39364. 5,
  39365. 8,
  39366. 7,
  39367. 6,
  39368. 2,
  39369. 13,
  39370. 14,
  39371. 0,
  39372. 3,
  39373. 9,
  39374. 11
  39375. ]);
  39376. var _sl = WordArray.create([
  39377. 11,
  39378. 14,
  39379. 15,
  39380. 12,
  39381. 5,
  39382. 8,
  39383. 7,
  39384. 9,
  39385. 11,
  39386. 13,
  39387. 14,
  39388. 15,
  39389. 6,
  39390. 7,
  39391. 9,
  39392. 8,
  39393. 7,
  39394. 6,
  39395. 8,
  39396. 13,
  39397. 11,
  39398. 9,
  39399. 7,
  39400. 15,
  39401. 7,
  39402. 12,
  39403. 15,
  39404. 9,
  39405. 11,
  39406. 7,
  39407. 13,
  39408. 12,
  39409. 11,
  39410. 13,
  39411. 6,
  39412. 7,
  39413. 14,
  39414. 9,
  39415. 13,
  39416. 15,
  39417. 14,
  39418. 8,
  39419. 13,
  39420. 6,
  39421. 5,
  39422. 12,
  39423. 7,
  39424. 5,
  39425. 11,
  39426. 12,
  39427. 14,
  39428. 15,
  39429. 14,
  39430. 15,
  39431. 9,
  39432. 8,
  39433. 9,
  39434. 14,
  39435. 5,
  39436. 6,
  39437. 8,
  39438. 6,
  39439. 5,
  39440. 12,
  39441. 9,
  39442. 15,
  39443. 5,
  39444. 11,
  39445. 6,
  39446. 8,
  39447. 13,
  39448. 12,
  39449. 5,
  39450. 12,
  39451. 13,
  39452. 14,
  39453. 11,
  39454. 8,
  39455. 5,
  39456. 6
  39457. ]);
  39458. var _sr = WordArray.create([
  39459. 8,
  39460. 9,
  39461. 9,
  39462. 11,
  39463. 13,
  39464. 15,
  39465. 15,
  39466. 5,
  39467. 7,
  39468. 7,
  39469. 8,
  39470. 11,
  39471. 14,
  39472. 14,
  39473. 12,
  39474. 6,
  39475. 9,
  39476. 13,
  39477. 15,
  39478. 7,
  39479. 12,
  39480. 8,
  39481. 9,
  39482. 11,
  39483. 7,
  39484. 7,
  39485. 12,
  39486. 7,
  39487. 6,
  39488. 15,
  39489. 13,
  39490. 11,
  39491. 9,
  39492. 7,
  39493. 15,
  39494. 11,
  39495. 8,
  39496. 6,
  39497. 6,
  39498. 14,
  39499. 12,
  39500. 13,
  39501. 5,
  39502. 14,
  39503. 13,
  39504. 13,
  39505. 7,
  39506. 5,
  39507. 15,
  39508. 5,
  39509. 8,
  39510. 11,
  39511. 14,
  39512. 14,
  39513. 6,
  39514. 14,
  39515. 6,
  39516. 9,
  39517. 12,
  39518. 9,
  39519. 12,
  39520. 5,
  39521. 15,
  39522. 8,
  39523. 8,
  39524. 5,
  39525. 12,
  39526. 9,
  39527. 12,
  39528. 5,
  39529. 14,
  39530. 6,
  39531. 8,
  39532. 13,
  39533. 6,
  39534. 5,
  39535. 15,
  39536. 13,
  39537. 11,
  39538. 11
  39539. ]);
  39540. var _hl = WordArray.create([0, 1518500249, 1859775393, 2400959708, 2840853838]);
  39541. var _hr = WordArray.create([1352829926, 1548603684, 1836072691, 2053994217, 0]);
  39542. var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
  39543. _doReset: function() {
  39544. this._hash = WordArray.create([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
  39545. },
  39546. _doProcessBlock: function(M2, offset) {
  39547. for (var i2 = 0; i2 < 16; i2++) {
  39548. var offset_i = offset + i2;
  39549. var M_offset_i = M2[offset_i];
  39550. M2[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 16711935 | (M_offset_i << 24 | M_offset_i >>> 8) & 4278255360;
  39551. }
  39552. var H2 = this._hash.words;
  39553. var hl = _hl.words;
  39554. var hr = _hr.words;
  39555. var zl = _zl.words;
  39556. var zr = _zr.words;
  39557. var sl = _sl.words;
  39558. var sr = _sr.words;
  39559. var al, bl, cl, dl, el;
  39560. var ar, br, cr, dr, er2;
  39561. ar = al = H2[0];
  39562. br = bl = H2[1];
  39563. cr = cl = H2[2];
  39564. dr = dl = H2[3];
  39565. er2 = el = H2[4];
  39566. var t2;
  39567. for (var i2 = 0; i2 < 80; i2 += 1) {
  39568. t2 = al + M2[offset + zl[i2]] | 0;
  39569. if (i2 < 16) {
  39570. t2 += f1(bl, cl, dl) + hl[0];
  39571. } else if (i2 < 32) {
  39572. t2 += f2(bl, cl, dl) + hl[1];
  39573. } else if (i2 < 48) {
  39574. t2 += f3(bl, cl, dl) + hl[2];
  39575. } else if (i2 < 64) {
  39576. t2 += f4(bl, cl, dl) + hl[3];
  39577. } else {
  39578. t2 += f5(bl, cl, dl) + hl[4];
  39579. }
  39580. t2 = t2 | 0;
  39581. t2 = rotl(t2, sl[i2]);
  39582. t2 = t2 + el | 0;
  39583. al = el;
  39584. el = dl;
  39585. dl = rotl(cl, 10);
  39586. cl = bl;
  39587. bl = t2;
  39588. t2 = ar + M2[offset + zr[i2]] | 0;
  39589. if (i2 < 16) {
  39590. t2 += f5(br, cr, dr) + hr[0];
  39591. } else if (i2 < 32) {
  39592. t2 += f4(br, cr, dr) + hr[1];
  39593. } else if (i2 < 48) {
  39594. t2 += f3(br, cr, dr) + hr[2];
  39595. } else if (i2 < 64) {
  39596. t2 += f2(br, cr, dr) + hr[3];
  39597. } else {
  39598. t2 += f1(br, cr, dr) + hr[4];
  39599. }
  39600. t2 = t2 | 0;
  39601. t2 = rotl(t2, sr[i2]);
  39602. t2 = t2 + er2 | 0;
  39603. ar = er2;
  39604. er2 = dr;
  39605. dr = rotl(cr, 10);
  39606. cr = br;
  39607. br = t2;
  39608. }
  39609. t2 = H2[1] + cl + dr | 0;
  39610. H2[1] = H2[2] + dl + er2 | 0;
  39611. H2[2] = H2[3] + el + ar | 0;
  39612. H2[3] = H2[4] + al + br | 0;
  39613. H2[4] = H2[0] + bl + cr | 0;
  39614. H2[0] = t2;
  39615. },
  39616. _doFinalize: function() {
  39617. var data = this._data;
  39618. var dataWords = data.words;
  39619. var nBitsTotal = this._nDataBytes * 8;
  39620. var nBitsLeft = data.sigBytes * 8;
  39621. dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  39622. dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotal << 8 | nBitsTotal >>> 24) & 16711935 | (nBitsTotal << 24 | nBitsTotal >>> 8) & 4278255360;
  39623. data.sigBytes = (dataWords.length + 1) * 4;
  39624. this._process();
  39625. var hash2 = this._hash;
  39626. var H2 = hash2.words;
  39627. for (var i2 = 0; i2 < 5; i2++) {
  39628. var H_i = H2[i2];
  39629. H2[i2] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360;
  39630. }
  39631. return hash2;
  39632. },
  39633. clone: function() {
  39634. var clone2 = Hasher.clone.call(this);
  39635. clone2._hash = this._hash.clone();
  39636. return clone2;
  39637. }
  39638. });
  39639. function f1(x, y2, z2) {
  39640. return x ^ y2 ^ z2;
  39641. }
  39642. function f2(x, y2, z2) {
  39643. return x & y2 | ~x & z2;
  39644. }
  39645. function f3(x, y2, z2) {
  39646. return (x | ~y2) ^ z2;
  39647. }
  39648. function f4(x, y2, z2) {
  39649. return x & z2 | y2 & ~z2;
  39650. }
  39651. function f5(x, y2, z2) {
  39652. return x ^ (y2 | ~z2);
  39653. }
  39654. function rotl(x, n2) {
  39655. return x << n2 | x >>> 32 - n2;
  39656. }
  39657. C2.RIPEMD160 = Hasher._createHelper(RIPEMD160);
  39658. C2.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
  39659. })();
  39660. return CryptoJS2.RIPEMD160;
  39661. });
  39662. })(ripemd160);
  39663. return ripemd160.exports;
  39664. }
  39665. var hmac = { exports: {} };
  39666. var hasRequiredHmac;
  39667. function requireHmac() {
  39668. if (hasRequiredHmac)
  39669. return hmac.exports;
  39670. hasRequiredHmac = 1;
  39671. (function(module, exports) {
  39672. (function(root, factory) {
  39673. {
  39674. module.exports = factory(requireCore());
  39675. }
  39676. })(commonjsGlobal, function(CryptoJS2) {
  39677. (function() {
  39678. var C2 = CryptoJS2;
  39679. var C_lib = C2.lib;
  39680. var Base = C_lib.Base;
  39681. var C_enc = C2.enc;
  39682. var Utf8 = C_enc.Utf8;
  39683. var C_algo = C2.algo;
  39684. C_algo.HMAC = Base.extend({
  39685. /**
  39686. * Initializes a newly created HMAC.
  39687. *
  39688. * @param {Hasher} hasher The hash algorithm to use.
  39689. * @param {WordArray|string} key The secret key.
  39690. *
  39691. * @example
  39692. *
  39693. * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
  39694. */
  39695. init: function(hasher, key) {
  39696. hasher = this._hasher = new hasher.init();
  39697. if (typeof key == "string") {
  39698. key = Utf8.parse(key);
  39699. }
  39700. var hasherBlockSize = hasher.blockSize;
  39701. var hasherBlockSizeBytes = hasherBlockSize * 4;
  39702. if (key.sigBytes > hasherBlockSizeBytes) {
  39703. key = hasher.finalize(key);
  39704. }
  39705. key.clamp();
  39706. var oKey = this._oKey = key.clone();
  39707. var iKey = this._iKey = key.clone();
  39708. var oKeyWords = oKey.words;
  39709. var iKeyWords = iKey.words;
  39710. for (var i2 = 0; i2 < hasherBlockSize; i2++) {
  39711. oKeyWords[i2] ^= 1549556828;
  39712. iKeyWords[i2] ^= 909522486;
  39713. }
  39714. oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
  39715. this.reset();
  39716. },
  39717. /**
  39718. * Resets this HMAC to its initial state.
  39719. *
  39720. * @example
  39721. *
  39722. * hmacHasher.reset();
  39723. */
  39724. reset: function() {
  39725. var hasher = this._hasher;
  39726. hasher.reset();
  39727. hasher.update(this._iKey);
  39728. },
  39729. /**
  39730. * Updates this HMAC with a message.
  39731. *
  39732. * @param {WordArray|string} messageUpdate The message to append.
  39733. *
  39734. * @return {HMAC} This HMAC instance.
  39735. *
  39736. * @example
  39737. *
  39738. * hmacHasher.update('message');
  39739. * hmacHasher.update(wordArray);
  39740. */
  39741. update: function(messageUpdate) {
  39742. this._hasher.update(messageUpdate);
  39743. return this;
  39744. },
  39745. /**
  39746. * Finalizes the HMAC computation.
  39747. * Note that the finalize operation is effectively a destructive, read-once operation.
  39748. *
  39749. * @param {WordArray|string} messageUpdate (Optional) A final message update.
  39750. *
  39751. * @return {WordArray} The HMAC.
  39752. *
  39753. * @example
  39754. *
  39755. * var hmac = hmacHasher.finalize();
  39756. * var hmac = hmacHasher.finalize('message');
  39757. * var hmac = hmacHasher.finalize(wordArray);
  39758. */
  39759. finalize: function(messageUpdate) {
  39760. var hasher = this._hasher;
  39761. var innerHash = hasher.finalize(messageUpdate);
  39762. hasher.reset();
  39763. var hmac2 = hasher.finalize(this._oKey.clone().concat(innerHash));
  39764. return hmac2;
  39765. }
  39766. });
  39767. })();
  39768. });
  39769. })(hmac);
  39770. return hmac.exports;
  39771. }
  39772. var pbkdf2 = { exports: {} };
  39773. var hasRequiredPbkdf2;
  39774. function requirePbkdf2() {
  39775. if (hasRequiredPbkdf2)
  39776. return pbkdf2.exports;
  39777. hasRequiredPbkdf2 = 1;
  39778. (function(module, exports) {
  39779. (function(root, factory, undef) {
  39780. {
  39781. module.exports = factory(requireCore(), requireSha256(), requireHmac());
  39782. }
  39783. })(commonjsGlobal, function(CryptoJS2) {
  39784. (function() {
  39785. var C2 = CryptoJS2;
  39786. var C_lib = C2.lib;
  39787. var Base = C_lib.Base;
  39788. var WordArray = C_lib.WordArray;
  39789. var C_algo = C2.algo;
  39790. var SHA256 = C_algo.SHA256;
  39791. var HMAC = C_algo.HMAC;
  39792. var PBKDF2 = C_algo.PBKDF2 = Base.extend({
  39793. /**
  39794. * Configuration options.
  39795. *
  39796. * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
  39797. * @property {Hasher} hasher The hasher to use. Default: SHA256
  39798. * @property {number} iterations The number of iterations to perform. Default: 250000
  39799. */
  39800. cfg: Base.extend({
  39801. keySize: 128 / 32,
  39802. hasher: SHA256,
  39803. iterations: 25e4
  39804. }),
  39805. /**
  39806. * Initializes a newly created key derivation function.
  39807. *
  39808. * @param {Object} cfg (Optional) The configuration options to use for the derivation.
  39809. *
  39810. * @example
  39811. *
  39812. * var kdf = CryptoJS.algo.PBKDF2.create();
  39813. * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
  39814. * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
  39815. */
  39816. init: function(cfg) {
  39817. this.cfg = this.cfg.extend(cfg);
  39818. },
  39819. /**
  39820. * Computes the Password-Based Key Derivation Function 2.
  39821. *
  39822. * @param {WordArray|string} password The password.
  39823. * @param {WordArray|string} salt A salt.
  39824. *
  39825. * @return {WordArray} The derived key.
  39826. *
  39827. * @example
  39828. *
  39829. * var key = kdf.compute(password, salt);
  39830. */
  39831. compute: function(password, salt) {
  39832. var cfg = this.cfg;
  39833. var hmac2 = HMAC.create(cfg.hasher, password);
  39834. var derivedKey = WordArray.create();
  39835. var blockIndex = WordArray.create([1]);
  39836. var derivedKeyWords = derivedKey.words;
  39837. var blockIndexWords = blockIndex.words;
  39838. var keySize = cfg.keySize;
  39839. var iterations = cfg.iterations;
  39840. while (derivedKeyWords.length < keySize) {
  39841. var block = hmac2.update(salt).finalize(blockIndex);
  39842. hmac2.reset();
  39843. var blockWords = block.words;
  39844. var blockWordsLength = blockWords.length;
  39845. var intermediate = block;
  39846. for (var i2 = 1; i2 < iterations; i2++) {
  39847. intermediate = hmac2.finalize(intermediate);
  39848. hmac2.reset();
  39849. var intermediateWords = intermediate.words;
  39850. for (var j2 = 0; j2 < blockWordsLength; j2++) {
  39851. blockWords[j2] ^= intermediateWords[j2];
  39852. }
  39853. }
  39854. derivedKey.concat(block);
  39855. blockIndexWords[0]++;
  39856. }
  39857. derivedKey.sigBytes = keySize * 4;
  39858. return derivedKey;
  39859. }
  39860. });
  39861. C2.PBKDF2 = function(password, salt, cfg) {
  39862. return PBKDF2.create(cfg).compute(password, salt);
  39863. };
  39864. })();
  39865. return CryptoJS2.PBKDF2;
  39866. });
  39867. })(pbkdf2);
  39868. return pbkdf2.exports;
  39869. }
  39870. var evpkdf = { exports: {} };
  39871. var hasRequiredEvpkdf;
  39872. function requireEvpkdf() {
  39873. if (hasRequiredEvpkdf)
  39874. return evpkdf.exports;
  39875. hasRequiredEvpkdf = 1;
  39876. (function(module, exports) {
  39877. (function(root, factory, undef) {
  39878. {
  39879. module.exports = factory(requireCore(), requireSha1(), requireHmac());
  39880. }
  39881. })(commonjsGlobal, function(CryptoJS2) {
  39882. (function() {
  39883. var C2 = CryptoJS2;
  39884. var C_lib = C2.lib;
  39885. var Base = C_lib.Base;
  39886. var WordArray = C_lib.WordArray;
  39887. var C_algo = C2.algo;
  39888. var MD5 = C_algo.MD5;
  39889. var EvpKDF = C_algo.EvpKDF = Base.extend({
  39890. /**
  39891. * Configuration options.
  39892. *
  39893. * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
  39894. * @property {Hasher} hasher The hash algorithm to use. Default: MD5
  39895. * @property {number} iterations The number of iterations to perform. Default: 1
  39896. */
  39897. cfg: Base.extend({
  39898. keySize: 128 / 32,
  39899. hasher: MD5,
  39900. iterations: 1
  39901. }),
  39902. /**
  39903. * Initializes a newly created key derivation function.
  39904. *
  39905. * @param {Object} cfg (Optional) The configuration options to use for the derivation.
  39906. *
  39907. * @example
  39908. *
  39909. * var kdf = CryptoJS.algo.EvpKDF.create();
  39910. * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
  39911. * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
  39912. */
  39913. init: function(cfg) {
  39914. this.cfg = this.cfg.extend(cfg);
  39915. },
  39916. /**
  39917. * Derives a key from a password.
  39918. *
  39919. * @param {WordArray|string} password The password.
  39920. * @param {WordArray|string} salt A salt.
  39921. *
  39922. * @return {WordArray} The derived key.
  39923. *
  39924. * @example
  39925. *
  39926. * var key = kdf.compute(password, salt);
  39927. */
  39928. compute: function(password, salt) {
  39929. var block;
  39930. var cfg = this.cfg;
  39931. var hasher = cfg.hasher.create();
  39932. var derivedKey = WordArray.create();
  39933. var derivedKeyWords = derivedKey.words;
  39934. var keySize = cfg.keySize;
  39935. var iterations = cfg.iterations;
  39936. while (derivedKeyWords.length < keySize) {
  39937. if (block) {
  39938. hasher.update(block);
  39939. }
  39940. block = hasher.update(password).finalize(salt);
  39941. hasher.reset();
  39942. for (var i2 = 1; i2 < iterations; i2++) {
  39943. block = hasher.finalize(block);
  39944. hasher.reset();
  39945. }
  39946. derivedKey.concat(block);
  39947. }
  39948. derivedKey.sigBytes = keySize * 4;
  39949. return derivedKey;
  39950. }
  39951. });
  39952. C2.EvpKDF = function(password, salt, cfg) {
  39953. return EvpKDF.create(cfg).compute(password, salt);
  39954. };
  39955. })();
  39956. return CryptoJS2.EvpKDF;
  39957. });
  39958. })(evpkdf);
  39959. return evpkdf.exports;
  39960. }
  39961. var cipherCore = { exports: {} };
  39962. var hasRequiredCipherCore;
  39963. function requireCipherCore() {
  39964. if (hasRequiredCipherCore)
  39965. return cipherCore.exports;
  39966. hasRequiredCipherCore = 1;
  39967. (function(module, exports) {
  39968. (function(root, factory, undef) {
  39969. {
  39970. module.exports = factory(requireCore(), requireEvpkdf());
  39971. }
  39972. })(commonjsGlobal, function(CryptoJS2) {
  39973. CryptoJS2.lib.Cipher || function(undefined$1) {
  39974. var C2 = CryptoJS2;
  39975. var C_lib = C2.lib;
  39976. var Base = C_lib.Base;
  39977. var WordArray = C_lib.WordArray;
  39978. var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
  39979. var C_enc = C2.enc;
  39980. C_enc.Utf8;
  39981. var Base64 = C_enc.Base64;
  39982. var C_algo = C2.algo;
  39983. var EvpKDF = C_algo.EvpKDF;
  39984. var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
  39985. /**
  39986. * Configuration options.
  39987. *
  39988. * @property {WordArray} iv The IV to use for this operation.
  39989. */
  39990. cfg: Base.extend(),
  39991. /**
  39992. * Creates this cipher in encryption mode.
  39993. *
  39994. * @param {WordArray} key The key.
  39995. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  39996. *
  39997. * @return {Cipher} A cipher instance.
  39998. *
  39999. * @static
  40000. *
  40001. * @example
  40002. *
  40003. * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
  40004. */
  40005. createEncryptor: function(key, cfg) {
  40006. return this.create(this._ENC_XFORM_MODE, key, cfg);
  40007. },
  40008. /**
  40009. * Creates this cipher in decryption mode.
  40010. *
  40011. * @param {WordArray} key The key.
  40012. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  40013. *
  40014. * @return {Cipher} A cipher instance.
  40015. *
  40016. * @static
  40017. *
  40018. * @example
  40019. *
  40020. * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
  40021. */
  40022. createDecryptor: function(key, cfg) {
  40023. return this.create(this._DEC_XFORM_MODE, key, cfg);
  40024. },
  40025. /**
  40026. * Initializes a newly created cipher.
  40027. *
  40028. * @param {number} xformMode Either the encryption or decryption transormation mode constant.
  40029. * @param {WordArray} key The key.
  40030. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  40031. *
  40032. * @example
  40033. *
  40034. * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
  40035. */
  40036. init: function(xformMode, key, cfg) {
  40037. this.cfg = this.cfg.extend(cfg);
  40038. this._xformMode = xformMode;
  40039. this._key = key;
  40040. this.reset();
  40041. },
  40042. /**
  40043. * Resets this cipher to its initial state.
  40044. *
  40045. * @example
  40046. *
  40047. * cipher.reset();
  40048. */
  40049. reset: function() {
  40050. BufferedBlockAlgorithm.reset.call(this);
  40051. this._doReset();
  40052. },
  40053. /**
  40054. * Adds data to be encrypted or decrypted.
  40055. *
  40056. * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
  40057. *
  40058. * @return {WordArray} The data after processing.
  40059. *
  40060. * @example
  40061. *
  40062. * var encrypted = cipher.process('data');
  40063. * var encrypted = cipher.process(wordArray);
  40064. */
  40065. process: function(dataUpdate) {
  40066. this._append(dataUpdate);
  40067. return this._process();
  40068. },
  40069. /**
  40070. * Finalizes the encryption or decryption process.
  40071. * Note that the finalize operation is effectively a destructive, read-once operation.
  40072. *
  40073. * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
  40074. *
  40075. * @return {WordArray} The data after final processing.
  40076. *
  40077. * @example
  40078. *
  40079. * var encrypted = cipher.finalize();
  40080. * var encrypted = cipher.finalize('data');
  40081. * var encrypted = cipher.finalize(wordArray);
  40082. */
  40083. finalize: function(dataUpdate) {
  40084. if (dataUpdate) {
  40085. this._append(dataUpdate);
  40086. }
  40087. var finalProcessedData = this._doFinalize();
  40088. return finalProcessedData;
  40089. },
  40090. keySize: 128 / 32,
  40091. ivSize: 128 / 32,
  40092. _ENC_XFORM_MODE: 1,
  40093. _DEC_XFORM_MODE: 2,
  40094. /**
  40095. * Creates shortcut functions to a cipher's object interface.
  40096. *
  40097. * @param {Cipher} cipher The cipher to create a helper for.
  40098. *
  40099. * @return {Object} An object with encrypt and decrypt shortcut functions.
  40100. *
  40101. * @static
  40102. *
  40103. * @example
  40104. *
  40105. * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
  40106. */
  40107. _createHelper: /* @__PURE__ */ function() {
  40108. function selectCipherStrategy(key) {
  40109. if (typeof key == "string") {
  40110. return PasswordBasedCipher;
  40111. } else {
  40112. return SerializableCipher;
  40113. }
  40114. }
  40115. return function(cipher) {
  40116. return {
  40117. encrypt: function(message, key, cfg) {
  40118. return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
  40119. },
  40120. decrypt: function(ciphertext, key, cfg) {
  40121. return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
  40122. }
  40123. };
  40124. };
  40125. }()
  40126. });
  40127. C_lib.StreamCipher = Cipher.extend({
  40128. _doFinalize: function() {
  40129. var finalProcessedBlocks = this._process(true);
  40130. return finalProcessedBlocks;
  40131. },
  40132. blockSize: 1
  40133. });
  40134. var C_mode = C2.mode = {};
  40135. var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
  40136. /**
  40137. * Creates this mode for encryption.
  40138. *
  40139. * @param {Cipher} cipher A block cipher instance.
  40140. * @param {Array} iv The IV words.
  40141. *
  40142. * @static
  40143. *
  40144. * @example
  40145. *
  40146. * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
  40147. */
  40148. createEncryptor: function(cipher, iv) {
  40149. return this.Encryptor.create(cipher, iv);
  40150. },
  40151. /**
  40152. * Creates this mode for decryption.
  40153. *
  40154. * @param {Cipher} cipher A block cipher instance.
  40155. * @param {Array} iv The IV words.
  40156. *
  40157. * @static
  40158. *
  40159. * @example
  40160. *
  40161. * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
  40162. */
  40163. createDecryptor: function(cipher, iv) {
  40164. return this.Decryptor.create(cipher, iv);
  40165. },
  40166. /**
  40167. * Initializes a newly created mode.
  40168. *
  40169. * @param {Cipher} cipher A block cipher instance.
  40170. * @param {Array} iv The IV words.
  40171. *
  40172. * @example
  40173. *
  40174. * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
  40175. */
  40176. init: function(cipher, iv) {
  40177. this._cipher = cipher;
  40178. this._iv = iv;
  40179. }
  40180. });
  40181. var CBC = C_mode.CBC = function() {
  40182. var CBC2 = BlockCipherMode.extend();
  40183. CBC2.Encryptor = CBC2.extend({
  40184. /**
  40185. * Processes the data block at offset.
  40186. *
  40187. * @param {Array} words The data words to operate on.
  40188. * @param {number} offset The offset where the block starts.
  40189. *
  40190. * @example
  40191. *
  40192. * mode.processBlock(data.words, offset);
  40193. */
  40194. processBlock: function(words, offset) {
  40195. var cipher = this._cipher;
  40196. var blockSize = cipher.blockSize;
  40197. xorBlock.call(this, words, offset, blockSize);
  40198. cipher.encryptBlock(words, offset);
  40199. this._prevBlock = words.slice(offset, offset + blockSize);
  40200. }
  40201. });
  40202. CBC2.Decryptor = CBC2.extend({
  40203. /**
  40204. * Processes the data block at offset.
  40205. *
  40206. * @param {Array} words The data words to operate on.
  40207. * @param {number} offset The offset where the block starts.
  40208. *
  40209. * @example
  40210. *
  40211. * mode.processBlock(data.words, offset);
  40212. */
  40213. processBlock: function(words, offset) {
  40214. var cipher = this._cipher;
  40215. var blockSize = cipher.blockSize;
  40216. var thisBlock = words.slice(offset, offset + blockSize);
  40217. cipher.decryptBlock(words, offset);
  40218. xorBlock.call(this, words, offset, blockSize);
  40219. this._prevBlock = thisBlock;
  40220. }
  40221. });
  40222. function xorBlock(words, offset, blockSize) {
  40223. var block;
  40224. var iv = this._iv;
  40225. if (iv) {
  40226. block = iv;
  40227. this._iv = undefined$1;
  40228. } else {
  40229. block = this._prevBlock;
  40230. }
  40231. for (var i2 = 0; i2 < blockSize; i2++) {
  40232. words[offset + i2] ^= block[i2];
  40233. }
  40234. }
  40235. return CBC2;
  40236. }();
  40237. var C_pad = C2.pad = {};
  40238. var Pkcs7 = C_pad.Pkcs7 = {
  40239. /**
  40240. * Pads data using the algorithm defined in PKCS #5/7.
  40241. *
  40242. * @param {WordArray} data The data to pad.
  40243. * @param {number} blockSize The multiple that the data should be padded to.
  40244. *
  40245. * @static
  40246. *
  40247. * @example
  40248. *
  40249. * CryptoJS.pad.Pkcs7.pad(wordArray, 4);
  40250. */
  40251. pad: function(data, blockSize) {
  40252. var blockSizeBytes = blockSize * 4;
  40253. var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
  40254. var paddingWord = nPaddingBytes << 24 | nPaddingBytes << 16 | nPaddingBytes << 8 | nPaddingBytes;
  40255. var paddingWords = [];
  40256. for (var i2 = 0; i2 < nPaddingBytes; i2 += 4) {
  40257. paddingWords.push(paddingWord);
  40258. }
  40259. var padding = WordArray.create(paddingWords, nPaddingBytes);
  40260. data.concat(padding);
  40261. },
  40262. /**
  40263. * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
  40264. *
  40265. * @param {WordArray} data The data to unpad.
  40266. *
  40267. * @static
  40268. *
  40269. * @example
  40270. *
  40271. * CryptoJS.pad.Pkcs7.unpad(wordArray);
  40272. */
  40273. unpad: function(data) {
  40274. var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255;
  40275. data.sigBytes -= nPaddingBytes;
  40276. }
  40277. };
  40278. C_lib.BlockCipher = Cipher.extend({
  40279. /**
  40280. * Configuration options.
  40281. *
  40282. * @property {Mode} mode The block mode to use. Default: CBC
  40283. * @property {Padding} padding The padding strategy to use. Default: Pkcs7
  40284. */
  40285. cfg: Cipher.cfg.extend({
  40286. mode: CBC,
  40287. padding: Pkcs7
  40288. }),
  40289. reset: function() {
  40290. var modeCreator;
  40291. Cipher.reset.call(this);
  40292. var cfg = this.cfg;
  40293. var iv = cfg.iv;
  40294. var mode = cfg.mode;
  40295. if (this._xformMode == this._ENC_XFORM_MODE) {
  40296. modeCreator = mode.createEncryptor;
  40297. } else {
  40298. modeCreator = mode.createDecryptor;
  40299. this._minBufferSize = 1;
  40300. }
  40301. if (this._mode && this._mode.__creator == modeCreator) {
  40302. this._mode.init(this, iv && iv.words);
  40303. } else {
  40304. this._mode = modeCreator.call(mode, this, iv && iv.words);
  40305. this._mode.__creator = modeCreator;
  40306. }
  40307. },
  40308. _doProcessBlock: function(words, offset) {
  40309. this._mode.processBlock(words, offset);
  40310. },
  40311. _doFinalize: function() {
  40312. var finalProcessedBlocks;
  40313. var padding = this.cfg.padding;
  40314. if (this._xformMode == this._ENC_XFORM_MODE) {
  40315. padding.pad(this._data, this.blockSize);
  40316. finalProcessedBlocks = this._process(true);
  40317. } else {
  40318. finalProcessedBlocks = this._process(true);
  40319. padding.unpad(finalProcessedBlocks);
  40320. }
  40321. return finalProcessedBlocks;
  40322. },
  40323. blockSize: 128 / 32
  40324. });
  40325. var CipherParams = C_lib.CipherParams = Base.extend({
  40326. /**
  40327. * Initializes a newly created cipher params object.
  40328. *
  40329. * @param {Object} cipherParams An object with any of the possible cipher parameters.
  40330. *
  40331. * @example
  40332. *
  40333. * var cipherParams = CryptoJS.lib.CipherParams.create({
  40334. * ciphertext: ciphertextWordArray,
  40335. * key: keyWordArray,
  40336. * iv: ivWordArray,
  40337. * salt: saltWordArray,
  40338. * algorithm: CryptoJS.algo.AES,
  40339. * mode: CryptoJS.mode.CBC,
  40340. * padding: CryptoJS.pad.PKCS7,
  40341. * blockSize: 4,
  40342. * formatter: CryptoJS.format.OpenSSL
  40343. * });
  40344. */
  40345. init: function(cipherParams) {
  40346. this.mixIn(cipherParams);
  40347. },
  40348. /**
  40349. * Converts this cipher params object to a string.
  40350. *
  40351. * @param {Format} formatter (Optional) The formatting strategy to use.
  40352. *
  40353. * @return {string} The stringified cipher params.
  40354. *
  40355. * @throws Error If neither the formatter nor the default formatter is set.
  40356. *
  40357. * @example
  40358. *
  40359. * var string = cipherParams + '';
  40360. * var string = cipherParams.toString();
  40361. * var string = cipherParams.toString(CryptoJS.format.OpenSSL);
  40362. */
  40363. toString: function(formatter) {
  40364. return (formatter || this.formatter).stringify(this);
  40365. }
  40366. });
  40367. var C_format = C2.format = {};
  40368. var OpenSSLFormatter = C_format.OpenSSL = {
  40369. /**
  40370. * Converts a cipher params object to an OpenSSL-compatible string.
  40371. *
  40372. * @param {CipherParams} cipherParams The cipher params object.
  40373. *
  40374. * @return {string} The OpenSSL-compatible string.
  40375. *
  40376. * @static
  40377. *
  40378. * @example
  40379. *
  40380. * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
  40381. */
  40382. stringify: function(cipherParams) {
  40383. var wordArray;
  40384. var ciphertext = cipherParams.ciphertext;
  40385. var salt = cipherParams.salt;
  40386. if (salt) {
  40387. wordArray = WordArray.create([1398893684, 1701076831]).concat(salt).concat(ciphertext);
  40388. } else {
  40389. wordArray = ciphertext;
  40390. }
  40391. return wordArray.toString(Base64);
  40392. },
  40393. /**
  40394. * Converts an OpenSSL-compatible string to a cipher params object.
  40395. *
  40396. * @param {string} openSSLStr The OpenSSL-compatible string.
  40397. *
  40398. * @return {CipherParams} The cipher params object.
  40399. *
  40400. * @static
  40401. *
  40402. * @example
  40403. *
  40404. * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
  40405. */
  40406. parse: function(openSSLStr) {
  40407. var salt;
  40408. var ciphertext = Base64.parse(openSSLStr);
  40409. var ciphertextWords = ciphertext.words;
  40410. if (ciphertextWords[0] == 1398893684 && ciphertextWords[1] == 1701076831) {
  40411. salt = WordArray.create(ciphertextWords.slice(2, 4));
  40412. ciphertextWords.splice(0, 4);
  40413. ciphertext.sigBytes -= 16;
  40414. }
  40415. return CipherParams.create({ ciphertext, salt });
  40416. }
  40417. };
  40418. var SerializableCipher = C_lib.SerializableCipher = Base.extend({
  40419. /**
  40420. * Configuration options.
  40421. *
  40422. * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
  40423. */
  40424. cfg: Base.extend({
  40425. format: OpenSSLFormatter
  40426. }),
  40427. /**
  40428. * Encrypts a message.
  40429. *
  40430. * @param {Cipher} cipher The cipher algorithm to use.
  40431. * @param {WordArray|string} message The message to encrypt.
  40432. * @param {WordArray} key The key.
  40433. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  40434. *
  40435. * @return {CipherParams} A cipher params object.
  40436. *
  40437. * @static
  40438. *
  40439. * @example
  40440. *
  40441. * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
  40442. * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
  40443. * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
  40444. */
  40445. encrypt: function(cipher, message, key, cfg) {
  40446. cfg = this.cfg.extend(cfg);
  40447. var encryptor = cipher.createEncryptor(key, cfg);
  40448. var ciphertext = encryptor.finalize(message);
  40449. var cipherCfg = encryptor.cfg;
  40450. return CipherParams.create({
  40451. ciphertext,
  40452. key,
  40453. iv: cipherCfg.iv,
  40454. algorithm: cipher,
  40455. mode: cipherCfg.mode,
  40456. padding: cipherCfg.padding,
  40457. blockSize: cipher.blockSize,
  40458. formatter: cfg.format
  40459. });
  40460. },
  40461. /**
  40462. * Decrypts serialized ciphertext.
  40463. *
  40464. * @param {Cipher} cipher The cipher algorithm to use.
  40465. * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
  40466. * @param {WordArray} key The key.
  40467. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  40468. *
  40469. * @return {WordArray} The plaintext.
  40470. *
  40471. * @static
  40472. *
  40473. * @example
  40474. *
  40475. * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
  40476. * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
  40477. */
  40478. decrypt: function(cipher, ciphertext, key, cfg) {
  40479. cfg = this.cfg.extend(cfg);
  40480. ciphertext = this._parse(ciphertext, cfg.format);
  40481. var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
  40482. return plaintext;
  40483. },
  40484. /**
  40485. * Converts serialized ciphertext to CipherParams,
  40486. * else assumed CipherParams already and returns ciphertext unchanged.
  40487. *
  40488. * @param {CipherParams|string} ciphertext The ciphertext.
  40489. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
  40490. *
  40491. * @return {CipherParams} The unserialized ciphertext.
  40492. *
  40493. * @static
  40494. *
  40495. * @example
  40496. *
  40497. * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
  40498. */
  40499. _parse: function(ciphertext, format2) {
  40500. if (typeof ciphertext == "string") {
  40501. return format2.parse(ciphertext, this);
  40502. } else {
  40503. return ciphertext;
  40504. }
  40505. }
  40506. });
  40507. var C_kdf = C2.kdf = {};
  40508. var OpenSSLKdf = C_kdf.OpenSSL = {
  40509. /**
  40510. * Derives a key and IV from a password.
  40511. *
  40512. * @param {string} password The password to derive from.
  40513. * @param {number} keySize The size in words of the key to generate.
  40514. * @param {number} ivSize The size in words of the IV to generate.
  40515. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
  40516. *
  40517. * @return {CipherParams} A cipher params object with the key, IV, and salt.
  40518. *
  40519. * @static
  40520. *
  40521. * @example
  40522. *
  40523. * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
  40524. * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
  40525. */
  40526. execute: function(password, keySize, ivSize, salt, hasher) {
  40527. if (!salt) {
  40528. salt = WordArray.random(64 / 8);
  40529. }
  40530. if (!hasher) {
  40531. var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
  40532. } else {
  40533. var key = EvpKDF.create({ keySize: keySize + ivSize, hasher }).compute(password, salt);
  40534. }
  40535. var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
  40536. key.sigBytes = keySize * 4;
  40537. return CipherParams.create({ key, iv, salt });
  40538. }
  40539. };
  40540. var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
  40541. /**
  40542. * Configuration options.
  40543. *
  40544. * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
  40545. */
  40546. cfg: SerializableCipher.cfg.extend({
  40547. kdf: OpenSSLKdf
  40548. }),
  40549. /**
  40550. * Encrypts a message using a password.
  40551. *
  40552. * @param {Cipher} cipher The cipher algorithm to use.
  40553. * @param {WordArray|string} message The message to encrypt.
  40554. * @param {string} password The password.
  40555. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  40556. *
  40557. * @return {CipherParams} A cipher params object.
  40558. *
  40559. * @static
  40560. *
  40561. * @example
  40562. *
  40563. * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
  40564. * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
  40565. */
  40566. encrypt: function(cipher, message, password, cfg) {
  40567. cfg = this.cfg.extend(cfg);
  40568. var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, cfg.salt, cfg.hasher);
  40569. cfg.iv = derivedParams.iv;
  40570. var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
  40571. ciphertext.mixIn(derivedParams);
  40572. return ciphertext;
  40573. },
  40574. /**
  40575. * Decrypts serialized ciphertext using a password.
  40576. *
  40577. * @param {Cipher} cipher The cipher algorithm to use.
  40578. * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
  40579. * @param {string} password The password.
  40580. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  40581. *
  40582. * @return {WordArray} The plaintext.
  40583. *
  40584. * @static
  40585. *
  40586. * @example
  40587. *
  40588. * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
  40589. * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
  40590. */
  40591. decrypt: function(cipher, ciphertext, password, cfg) {
  40592. cfg = this.cfg.extend(cfg);
  40593. ciphertext = this._parse(ciphertext, cfg.format);
  40594. var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt, cfg.hasher);
  40595. cfg.iv = derivedParams.iv;
  40596. var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
  40597. return plaintext;
  40598. }
  40599. });
  40600. }();
  40601. });
  40602. })(cipherCore);
  40603. return cipherCore.exports;
  40604. }
  40605. var modeCfb = { exports: {} };
  40606. var hasRequiredModeCfb;
  40607. function requireModeCfb() {
  40608. if (hasRequiredModeCfb)
  40609. return modeCfb.exports;
  40610. hasRequiredModeCfb = 1;
  40611. (function(module, exports) {
  40612. (function(root, factory, undef) {
  40613. {
  40614. module.exports = factory(requireCore(), requireCipherCore());
  40615. }
  40616. })(commonjsGlobal, function(CryptoJS2) {
  40617. CryptoJS2.mode.CFB = function() {
  40618. var CFB = CryptoJS2.lib.BlockCipherMode.extend();
  40619. CFB.Encryptor = CFB.extend({
  40620. processBlock: function(words, offset) {
  40621. var cipher = this._cipher;
  40622. var blockSize = cipher.blockSize;
  40623. generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
  40624. this._prevBlock = words.slice(offset, offset + blockSize);
  40625. }
  40626. });
  40627. CFB.Decryptor = CFB.extend({
  40628. processBlock: function(words, offset) {
  40629. var cipher = this._cipher;
  40630. var blockSize = cipher.blockSize;
  40631. var thisBlock = words.slice(offset, offset + blockSize);
  40632. generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
  40633. this._prevBlock = thisBlock;
  40634. }
  40635. });
  40636. function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
  40637. var keystream;
  40638. var iv = this._iv;
  40639. if (iv) {
  40640. keystream = iv.slice(0);
  40641. this._iv = void 0;
  40642. } else {
  40643. keystream = this._prevBlock;
  40644. }
  40645. cipher.encryptBlock(keystream, 0);
  40646. for (var i2 = 0; i2 < blockSize; i2++) {
  40647. words[offset + i2] ^= keystream[i2];
  40648. }
  40649. }
  40650. return CFB;
  40651. }();
  40652. return CryptoJS2.mode.CFB;
  40653. });
  40654. })(modeCfb);
  40655. return modeCfb.exports;
  40656. }
  40657. var modeCtr = { exports: {} };
  40658. var hasRequiredModeCtr;
  40659. function requireModeCtr() {
  40660. if (hasRequiredModeCtr)
  40661. return modeCtr.exports;
  40662. hasRequiredModeCtr = 1;
  40663. (function(module, exports) {
  40664. (function(root, factory, undef) {
  40665. {
  40666. module.exports = factory(requireCore(), requireCipherCore());
  40667. }
  40668. })(commonjsGlobal, function(CryptoJS2) {
  40669. CryptoJS2.mode.CTR = function() {
  40670. var CTR = CryptoJS2.lib.BlockCipherMode.extend();
  40671. var Encryptor = CTR.Encryptor = CTR.extend({
  40672. processBlock: function(words, offset) {
  40673. var cipher = this._cipher;
  40674. var blockSize = cipher.blockSize;
  40675. var iv = this._iv;
  40676. var counter = this._counter;
  40677. if (iv) {
  40678. counter = this._counter = iv.slice(0);
  40679. this._iv = void 0;
  40680. }
  40681. var keystream = counter.slice(0);
  40682. cipher.encryptBlock(keystream, 0);
  40683. counter[blockSize - 1] = counter[blockSize - 1] + 1 | 0;
  40684. for (var i2 = 0; i2 < blockSize; i2++) {
  40685. words[offset + i2] ^= keystream[i2];
  40686. }
  40687. }
  40688. });
  40689. CTR.Decryptor = Encryptor;
  40690. return CTR;
  40691. }();
  40692. return CryptoJS2.mode.CTR;
  40693. });
  40694. })(modeCtr);
  40695. return modeCtr.exports;
  40696. }
  40697. var modeCtrGladman = { exports: {} };
  40698. var hasRequiredModeCtrGladman;
  40699. function requireModeCtrGladman() {
  40700. if (hasRequiredModeCtrGladman)
  40701. return modeCtrGladman.exports;
  40702. hasRequiredModeCtrGladman = 1;
  40703. (function(module, exports) {
  40704. (function(root, factory, undef) {
  40705. {
  40706. module.exports = factory(requireCore(), requireCipherCore());
  40707. }
  40708. })(commonjsGlobal, function(CryptoJS2) {
  40709. /** @preserve
  40710. * Counter block mode compatible with Dr Brian Gladman fileenc.c
  40711. * derived from CryptoJS.mode.CTR
  40712. * Jan Hruby jhruby.web@gmail.com
  40713. */
  40714. CryptoJS2.mode.CTRGladman = function() {
  40715. var CTRGladman = CryptoJS2.lib.BlockCipherMode.extend();
  40716. function incWord(word) {
  40717. if ((word >> 24 & 255) === 255) {
  40718. var b1 = word >> 16 & 255;
  40719. var b2 = word >> 8 & 255;
  40720. var b3 = word & 255;
  40721. if (b1 === 255) {
  40722. b1 = 0;
  40723. if (b2 === 255) {
  40724. b2 = 0;
  40725. if (b3 === 255) {
  40726. b3 = 0;
  40727. } else {
  40728. ++b3;
  40729. }
  40730. } else {
  40731. ++b2;
  40732. }
  40733. } else {
  40734. ++b1;
  40735. }
  40736. word = 0;
  40737. word += b1 << 16;
  40738. word += b2 << 8;
  40739. word += b3;
  40740. } else {
  40741. word += 1 << 24;
  40742. }
  40743. return word;
  40744. }
  40745. function incCounter(counter) {
  40746. if ((counter[0] = incWord(counter[0])) === 0) {
  40747. counter[1] = incWord(counter[1]);
  40748. }
  40749. return counter;
  40750. }
  40751. var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
  40752. processBlock: function(words, offset) {
  40753. var cipher = this._cipher;
  40754. var blockSize = cipher.blockSize;
  40755. var iv = this._iv;
  40756. var counter = this._counter;
  40757. if (iv) {
  40758. counter = this._counter = iv.slice(0);
  40759. this._iv = void 0;
  40760. }
  40761. incCounter(counter);
  40762. var keystream = counter.slice(0);
  40763. cipher.encryptBlock(keystream, 0);
  40764. for (var i2 = 0; i2 < blockSize; i2++) {
  40765. words[offset + i2] ^= keystream[i2];
  40766. }
  40767. }
  40768. });
  40769. CTRGladman.Decryptor = Encryptor;
  40770. return CTRGladman;
  40771. }();
  40772. return CryptoJS2.mode.CTRGladman;
  40773. });
  40774. })(modeCtrGladman);
  40775. return modeCtrGladman.exports;
  40776. }
  40777. var modeOfb = { exports: {} };
  40778. var hasRequiredModeOfb;
  40779. function requireModeOfb() {
  40780. if (hasRequiredModeOfb)
  40781. return modeOfb.exports;
  40782. hasRequiredModeOfb = 1;
  40783. (function(module, exports) {
  40784. (function(root, factory, undef) {
  40785. {
  40786. module.exports = factory(requireCore(), requireCipherCore());
  40787. }
  40788. })(commonjsGlobal, function(CryptoJS2) {
  40789. CryptoJS2.mode.OFB = function() {
  40790. var OFB = CryptoJS2.lib.BlockCipherMode.extend();
  40791. var Encryptor = OFB.Encryptor = OFB.extend({
  40792. processBlock: function(words, offset) {
  40793. var cipher = this._cipher;
  40794. var blockSize = cipher.blockSize;
  40795. var iv = this._iv;
  40796. var keystream = this._keystream;
  40797. if (iv) {
  40798. keystream = this._keystream = iv.slice(0);
  40799. this._iv = void 0;
  40800. }
  40801. cipher.encryptBlock(keystream, 0);
  40802. for (var i2 = 0; i2 < blockSize; i2++) {
  40803. words[offset + i2] ^= keystream[i2];
  40804. }
  40805. }
  40806. });
  40807. OFB.Decryptor = Encryptor;
  40808. return OFB;
  40809. }();
  40810. return CryptoJS2.mode.OFB;
  40811. });
  40812. })(modeOfb);
  40813. return modeOfb.exports;
  40814. }
  40815. var modeEcb = { exports: {} };
  40816. var hasRequiredModeEcb;
  40817. function requireModeEcb() {
  40818. if (hasRequiredModeEcb)
  40819. return modeEcb.exports;
  40820. hasRequiredModeEcb = 1;
  40821. (function(module, exports) {
  40822. (function(root, factory, undef) {
  40823. {
  40824. module.exports = factory(requireCore(), requireCipherCore());
  40825. }
  40826. })(commonjsGlobal, function(CryptoJS2) {
  40827. CryptoJS2.mode.ECB = function() {
  40828. var ECB = CryptoJS2.lib.BlockCipherMode.extend();
  40829. ECB.Encryptor = ECB.extend({
  40830. processBlock: function(words, offset) {
  40831. this._cipher.encryptBlock(words, offset);
  40832. }
  40833. });
  40834. ECB.Decryptor = ECB.extend({
  40835. processBlock: function(words, offset) {
  40836. this._cipher.decryptBlock(words, offset);
  40837. }
  40838. });
  40839. return ECB;
  40840. }();
  40841. return CryptoJS2.mode.ECB;
  40842. });
  40843. })(modeEcb);
  40844. return modeEcb.exports;
  40845. }
  40846. var padAnsix923 = { exports: {} };
  40847. var hasRequiredPadAnsix923;
  40848. function requirePadAnsix923() {
  40849. if (hasRequiredPadAnsix923)
  40850. return padAnsix923.exports;
  40851. hasRequiredPadAnsix923 = 1;
  40852. (function(module, exports) {
  40853. (function(root, factory, undef) {
  40854. {
  40855. module.exports = factory(requireCore(), requireCipherCore());
  40856. }
  40857. })(commonjsGlobal, function(CryptoJS2) {
  40858. CryptoJS2.pad.AnsiX923 = {
  40859. pad: function(data, blockSize) {
  40860. var dataSigBytes = data.sigBytes;
  40861. var blockSizeBytes = blockSize * 4;
  40862. var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
  40863. var lastBytePos = dataSigBytes + nPaddingBytes - 1;
  40864. data.clamp();
  40865. data.words[lastBytePos >>> 2] |= nPaddingBytes << 24 - lastBytePos % 4 * 8;
  40866. data.sigBytes += nPaddingBytes;
  40867. },
  40868. unpad: function(data) {
  40869. var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255;
  40870. data.sigBytes -= nPaddingBytes;
  40871. }
  40872. };
  40873. return CryptoJS2.pad.Ansix923;
  40874. });
  40875. })(padAnsix923);
  40876. return padAnsix923.exports;
  40877. }
  40878. var padIso10126 = { exports: {} };
  40879. var hasRequiredPadIso10126;
  40880. function requirePadIso10126() {
  40881. if (hasRequiredPadIso10126)
  40882. return padIso10126.exports;
  40883. hasRequiredPadIso10126 = 1;
  40884. (function(module, exports) {
  40885. (function(root, factory, undef) {
  40886. {
  40887. module.exports = factory(requireCore(), requireCipherCore());
  40888. }
  40889. })(commonjsGlobal, function(CryptoJS2) {
  40890. CryptoJS2.pad.Iso10126 = {
  40891. pad: function(data, blockSize) {
  40892. var blockSizeBytes = blockSize * 4;
  40893. var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
  40894. data.concat(CryptoJS2.lib.WordArray.random(nPaddingBytes - 1)).concat(CryptoJS2.lib.WordArray.create([nPaddingBytes << 24], 1));
  40895. },
  40896. unpad: function(data) {
  40897. var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255;
  40898. data.sigBytes -= nPaddingBytes;
  40899. }
  40900. };
  40901. return CryptoJS2.pad.Iso10126;
  40902. });
  40903. })(padIso10126);
  40904. return padIso10126.exports;
  40905. }
  40906. var padIso97971 = { exports: {} };
  40907. var hasRequiredPadIso97971;
  40908. function requirePadIso97971() {
  40909. if (hasRequiredPadIso97971)
  40910. return padIso97971.exports;
  40911. hasRequiredPadIso97971 = 1;
  40912. (function(module, exports) {
  40913. (function(root, factory, undef) {
  40914. {
  40915. module.exports = factory(requireCore(), requireCipherCore());
  40916. }
  40917. })(commonjsGlobal, function(CryptoJS2) {
  40918. CryptoJS2.pad.Iso97971 = {
  40919. pad: function(data, blockSize) {
  40920. data.concat(CryptoJS2.lib.WordArray.create([2147483648], 1));
  40921. CryptoJS2.pad.ZeroPadding.pad(data, blockSize);
  40922. },
  40923. unpad: function(data) {
  40924. CryptoJS2.pad.ZeroPadding.unpad(data);
  40925. data.sigBytes--;
  40926. }
  40927. };
  40928. return CryptoJS2.pad.Iso97971;
  40929. });
  40930. })(padIso97971);
  40931. return padIso97971.exports;
  40932. }
  40933. var padZeropadding = { exports: {} };
  40934. var hasRequiredPadZeropadding;
  40935. function requirePadZeropadding() {
  40936. if (hasRequiredPadZeropadding)
  40937. return padZeropadding.exports;
  40938. hasRequiredPadZeropadding = 1;
  40939. (function(module, exports) {
  40940. (function(root, factory, undef) {
  40941. {
  40942. module.exports = factory(requireCore(), requireCipherCore());
  40943. }
  40944. })(commonjsGlobal, function(CryptoJS2) {
  40945. CryptoJS2.pad.ZeroPadding = {
  40946. pad: function(data, blockSize) {
  40947. var blockSizeBytes = blockSize * 4;
  40948. data.clamp();
  40949. data.sigBytes += blockSizeBytes - (data.sigBytes % blockSizeBytes || blockSizeBytes);
  40950. },
  40951. unpad: function(data) {
  40952. var dataWords = data.words;
  40953. var i2 = data.sigBytes - 1;
  40954. for (var i2 = data.sigBytes - 1; i2 >= 0; i2--) {
  40955. if (dataWords[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255) {
  40956. data.sigBytes = i2 + 1;
  40957. break;
  40958. }
  40959. }
  40960. }
  40961. };
  40962. return CryptoJS2.pad.ZeroPadding;
  40963. });
  40964. })(padZeropadding);
  40965. return padZeropadding.exports;
  40966. }
  40967. var padNopadding = { exports: {} };
  40968. var hasRequiredPadNopadding;
  40969. function requirePadNopadding() {
  40970. if (hasRequiredPadNopadding)
  40971. return padNopadding.exports;
  40972. hasRequiredPadNopadding = 1;
  40973. (function(module, exports) {
  40974. (function(root, factory, undef) {
  40975. {
  40976. module.exports = factory(requireCore(), requireCipherCore());
  40977. }
  40978. })(commonjsGlobal, function(CryptoJS2) {
  40979. CryptoJS2.pad.NoPadding = {
  40980. pad: function() {
  40981. },
  40982. unpad: function() {
  40983. }
  40984. };
  40985. return CryptoJS2.pad.NoPadding;
  40986. });
  40987. })(padNopadding);
  40988. return padNopadding.exports;
  40989. }
  40990. var formatHex = { exports: {} };
  40991. var hasRequiredFormatHex;
  40992. function requireFormatHex() {
  40993. if (hasRequiredFormatHex)
  40994. return formatHex.exports;
  40995. hasRequiredFormatHex = 1;
  40996. (function(module, exports) {
  40997. (function(root, factory, undef) {
  40998. {
  40999. module.exports = factory(requireCore(), requireCipherCore());
  41000. }
  41001. })(commonjsGlobal, function(CryptoJS2) {
  41002. (function(undefined$1) {
  41003. var C2 = CryptoJS2;
  41004. var C_lib = C2.lib;
  41005. var CipherParams = C_lib.CipherParams;
  41006. var C_enc = C2.enc;
  41007. var Hex2 = C_enc.Hex;
  41008. var C_format = C2.format;
  41009. C_format.Hex = {
  41010. /**
  41011. * Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
  41012. *
  41013. * @param {CipherParams} cipherParams The cipher params object.
  41014. *
  41015. * @return {string} The hexadecimally encoded string.
  41016. *
  41017. * @static
  41018. *
  41019. * @example
  41020. *
  41021. * var hexString = CryptoJS.format.Hex.stringify(cipherParams);
  41022. */
  41023. stringify: function(cipherParams) {
  41024. return cipherParams.ciphertext.toString(Hex2);
  41025. },
  41026. /**
  41027. * Converts a hexadecimally encoded ciphertext string to a cipher params object.
  41028. *
  41029. * @param {string} input The hexadecimally encoded string.
  41030. *
  41031. * @return {CipherParams} The cipher params object.
  41032. *
  41033. * @static
  41034. *
  41035. * @example
  41036. *
  41037. * var cipherParams = CryptoJS.format.Hex.parse(hexString);
  41038. */
  41039. parse: function(input) {
  41040. var ciphertext = Hex2.parse(input);
  41041. return CipherParams.create({ ciphertext });
  41042. }
  41043. };
  41044. })();
  41045. return CryptoJS2.format.Hex;
  41046. });
  41047. })(formatHex);
  41048. return formatHex.exports;
  41049. }
  41050. var aes = { exports: {} };
  41051. var hasRequiredAes;
  41052. function requireAes() {
  41053. if (hasRequiredAes)
  41054. return aes.exports;
  41055. hasRequiredAes = 1;
  41056. (function(module, exports) {
  41057. (function(root, factory, undef) {
  41058. {
  41059. module.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  41060. }
  41061. })(commonjsGlobal, function(CryptoJS2) {
  41062. (function() {
  41063. var C2 = CryptoJS2;
  41064. var C_lib = C2.lib;
  41065. var BlockCipher = C_lib.BlockCipher;
  41066. var C_algo = C2.algo;
  41067. var SBOX = [];
  41068. var INV_SBOX = [];
  41069. var SUB_MIX_0 = [];
  41070. var SUB_MIX_1 = [];
  41071. var SUB_MIX_2 = [];
  41072. var SUB_MIX_3 = [];
  41073. var INV_SUB_MIX_0 = [];
  41074. var INV_SUB_MIX_1 = [];
  41075. var INV_SUB_MIX_2 = [];
  41076. var INV_SUB_MIX_3 = [];
  41077. (function() {
  41078. var d2 = [];
  41079. for (var i2 = 0; i2 < 256; i2++) {
  41080. if (i2 < 128) {
  41081. d2[i2] = i2 << 1;
  41082. } else {
  41083. d2[i2] = i2 << 1 ^ 283;
  41084. }
  41085. }
  41086. var x = 0;
  41087. var xi = 0;
  41088. for (var i2 = 0; i2 < 256; i2++) {
  41089. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  41090. sx = sx >>> 8 ^ sx & 255 ^ 99;
  41091. SBOX[x] = sx;
  41092. INV_SBOX[sx] = x;
  41093. var x2 = d2[x];
  41094. var x4 = d2[x2];
  41095. var x8 = d2[x4];
  41096. var t2 = d2[sx] * 257 ^ sx * 16843008;
  41097. SUB_MIX_0[x] = t2 << 24 | t2 >>> 8;
  41098. SUB_MIX_1[x] = t2 << 16 | t2 >>> 16;
  41099. SUB_MIX_2[x] = t2 << 8 | t2 >>> 24;
  41100. SUB_MIX_3[x] = t2;
  41101. var t2 = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008;
  41102. INV_SUB_MIX_0[sx] = t2 << 24 | t2 >>> 8;
  41103. INV_SUB_MIX_1[sx] = t2 << 16 | t2 >>> 16;
  41104. INV_SUB_MIX_2[sx] = t2 << 8 | t2 >>> 24;
  41105. INV_SUB_MIX_3[sx] = t2;
  41106. if (!x) {
  41107. x = xi = 1;
  41108. } else {
  41109. x = x2 ^ d2[d2[d2[x8 ^ x2]]];
  41110. xi ^= d2[d2[xi]];
  41111. }
  41112. }
  41113. })();
  41114. var RCON = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
  41115. var AES = C_algo.AES = BlockCipher.extend({
  41116. _doReset: function() {
  41117. var t2;
  41118. if (this._nRounds && this._keyPriorReset === this._key) {
  41119. return;
  41120. }
  41121. var key = this._keyPriorReset = this._key;
  41122. var keyWords = key.words;
  41123. var keySize = key.sigBytes / 4;
  41124. var nRounds = this._nRounds = keySize + 6;
  41125. var ksRows = (nRounds + 1) * 4;
  41126. var keySchedule = this._keySchedule = [];
  41127. for (var ksRow = 0; ksRow < ksRows; ksRow++) {
  41128. if (ksRow < keySize) {
  41129. keySchedule[ksRow] = keyWords[ksRow];
  41130. } else {
  41131. t2 = keySchedule[ksRow - 1];
  41132. if (!(ksRow % keySize)) {
  41133. t2 = t2 << 8 | t2 >>> 24;
  41134. t2 = SBOX[t2 >>> 24] << 24 | SBOX[t2 >>> 16 & 255] << 16 | SBOX[t2 >>> 8 & 255] << 8 | SBOX[t2 & 255];
  41135. t2 ^= RCON[ksRow / keySize | 0] << 24;
  41136. } else if (keySize > 6 && ksRow % keySize == 4) {
  41137. t2 = SBOX[t2 >>> 24] << 24 | SBOX[t2 >>> 16 & 255] << 16 | SBOX[t2 >>> 8 & 255] << 8 | SBOX[t2 & 255];
  41138. }
  41139. keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t2;
  41140. }
  41141. }
  41142. var invKeySchedule = this._invKeySchedule = [];
  41143. for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  41144. var ksRow = ksRows - invKsRow;
  41145. if (invKsRow % 4) {
  41146. var t2 = keySchedule[ksRow];
  41147. } else {
  41148. var t2 = keySchedule[ksRow - 4];
  41149. }
  41150. if (invKsRow < 4 || ksRow <= 4) {
  41151. invKeySchedule[invKsRow] = t2;
  41152. } else {
  41153. 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]];
  41154. }
  41155. }
  41156. },
  41157. encryptBlock: function(M2, offset) {
  41158. this._doCryptBlock(M2, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
  41159. },
  41160. decryptBlock: function(M2, offset) {
  41161. var t2 = M2[offset + 1];
  41162. M2[offset + 1] = M2[offset + 3];
  41163. M2[offset + 3] = t2;
  41164. this._doCryptBlock(M2, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
  41165. var t2 = M2[offset + 1];
  41166. M2[offset + 1] = M2[offset + 3];
  41167. M2[offset + 3] = t2;
  41168. },
  41169. _doCryptBlock: function(M2, offset, keySchedule, SUB_MIX_02, SUB_MIX_12, SUB_MIX_22, SUB_MIX_32, SBOX2) {
  41170. var nRounds = this._nRounds;
  41171. var s0 = M2[offset] ^ keySchedule[0];
  41172. var s1 = M2[offset + 1] ^ keySchedule[1];
  41173. var s2 = M2[offset + 2] ^ keySchedule[2];
  41174. var s3 = M2[offset + 3] ^ keySchedule[3];
  41175. var ksRow = 4;
  41176. for (var round2 = 1; round2 < nRounds; round2++) {
  41177. 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++];
  41178. 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++];
  41179. 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++];
  41180. 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++];
  41181. s0 = t0;
  41182. s1 = t1;
  41183. s2 = t2;
  41184. s3 = t3;
  41185. }
  41186. var t0 = (SBOX2[s0 >>> 24] << 24 | SBOX2[s1 >>> 16 & 255] << 16 | SBOX2[s2 >>> 8 & 255] << 8 | SBOX2[s3 & 255]) ^ keySchedule[ksRow++];
  41187. var t1 = (SBOX2[s1 >>> 24] << 24 | SBOX2[s2 >>> 16 & 255] << 16 | SBOX2[s3 >>> 8 & 255] << 8 | SBOX2[s0 & 255]) ^ keySchedule[ksRow++];
  41188. var t2 = (SBOX2[s2 >>> 24] << 24 | SBOX2[s3 >>> 16 & 255] << 16 | SBOX2[s0 >>> 8 & 255] << 8 | SBOX2[s1 & 255]) ^ keySchedule[ksRow++];
  41189. var t3 = (SBOX2[s3 >>> 24] << 24 | SBOX2[s0 >>> 16 & 255] << 16 | SBOX2[s1 >>> 8 & 255] << 8 | SBOX2[s2 & 255]) ^ keySchedule[ksRow++];
  41190. M2[offset] = t0;
  41191. M2[offset + 1] = t1;
  41192. M2[offset + 2] = t2;
  41193. M2[offset + 3] = t3;
  41194. },
  41195. keySize: 256 / 32
  41196. });
  41197. C2.AES = BlockCipher._createHelper(AES);
  41198. })();
  41199. return CryptoJS2.AES;
  41200. });
  41201. })(aes);
  41202. return aes.exports;
  41203. }
  41204. var tripledes = { exports: {} };
  41205. var hasRequiredTripledes;
  41206. function requireTripledes() {
  41207. if (hasRequiredTripledes)
  41208. return tripledes.exports;
  41209. hasRequiredTripledes = 1;
  41210. (function(module, exports) {
  41211. (function(root, factory, undef) {
  41212. {
  41213. module.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  41214. }
  41215. })(commonjsGlobal, function(CryptoJS2) {
  41216. (function() {
  41217. var C2 = CryptoJS2;
  41218. var C_lib = C2.lib;
  41219. var WordArray = C_lib.WordArray;
  41220. var BlockCipher = C_lib.BlockCipher;
  41221. var C_algo = C2.algo;
  41222. var PC1 = [
  41223. 57,
  41224. 49,
  41225. 41,
  41226. 33,
  41227. 25,
  41228. 17,
  41229. 9,
  41230. 1,
  41231. 58,
  41232. 50,
  41233. 42,
  41234. 34,
  41235. 26,
  41236. 18,
  41237. 10,
  41238. 2,
  41239. 59,
  41240. 51,
  41241. 43,
  41242. 35,
  41243. 27,
  41244. 19,
  41245. 11,
  41246. 3,
  41247. 60,
  41248. 52,
  41249. 44,
  41250. 36,
  41251. 63,
  41252. 55,
  41253. 47,
  41254. 39,
  41255. 31,
  41256. 23,
  41257. 15,
  41258. 7,
  41259. 62,
  41260. 54,
  41261. 46,
  41262. 38,
  41263. 30,
  41264. 22,
  41265. 14,
  41266. 6,
  41267. 61,
  41268. 53,
  41269. 45,
  41270. 37,
  41271. 29,
  41272. 21,
  41273. 13,
  41274. 5,
  41275. 28,
  41276. 20,
  41277. 12,
  41278. 4
  41279. ];
  41280. var PC2 = [
  41281. 14,
  41282. 17,
  41283. 11,
  41284. 24,
  41285. 1,
  41286. 5,
  41287. 3,
  41288. 28,
  41289. 15,
  41290. 6,
  41291. 21,
  41292. 10,
  41293. 23,
  41294. 19,
  41295. 12,
  41296. 4,
  41297. 26,
  41298. 8,
  41299. 16,
  41300. 7,
  41301. 27,
  41302. 20,
  41303. 13,
  41304. 2,
  41305. 41,
  41306. 52,
  41307. 31,
  41308. 37,
  41309. 47,
  41310. 55,
  41311. 30,
  41312. 40,
  41313. 51,
  41314. 45,
  41315. 33,
  41316. 48,
  41317. 44,
  41318. 49,
  41319. 39,
  41320. 56,
  41321. 34,
  41322. 53,
  41323. 46,
  41324. 42,
  41325. 50,
  41326. 36,
  41327. 29,
  41328. 32
  41329. ];
  41330. var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
  41331. var SBOX_P = [
  41332. {
  41333. 0: 8421888,
  41334. 268435456: 32768,
  41335. 536870912: 8421378,
  41336. 805306368: 2,
  41337. 1073741824: 512,
  41338. 1342177280: 8421890,
  41339. 1610612736: 8389122,
  41340. 1879048192: 8388608,
  41341. 2147483648: 514,
  41342. 2415919104: 8389120,
  41343. 2684354560: 33280,
  41344. 2952790016: 8421376,
  41345. 3221225472: 32770,
  41346. 3489660928: 8388610,
  41347. 3758096384: 0,
  41348. 4026531840: 33282,
  41349. 134217728: 0,
  41350. 402653184: 8421890,
  41351. 671088640: 33282,
  41352. 939524096: 32768,
  41353. 1207959552: 8421888,
  41354. 1476395008: 512,
  41355. 1744830464: 8421378,
  41356. 2013265920: 2,
  41357. 2281701376: 8389120,
  41358. 2550136832: 33280,
  41359. 2818572288: 8421376,
  41360. 3087007744: 8389122,
  41361. 3355443200: 8388610,
  41362. 3623878656: 32770,
  41363. 3892314112: 514,
  41364. 4160749568: 8388608,
  41365. 1: 32768,
  41366. 268435457: 2,
  41367. 536870913: 8421888,
  41368. 805306369: 8388608,
  41369. 1073741825: 8421378,
  41370. 1342177281: 33280,
  41371. 1610612737: 512,
  41372. 1879048193: 8389122,
  41373. 2147483649: 8421890,
  41374. 2415919105: 8421376,
  41375. 2684354561: 8388610,
  41376. 2952790017: 33282,
  41377. 3221225473: 514,
  41378. 3489660929: 8389120,
  41379. 3758096385: 32770,
  41380. 4026531841: 0,
  41381. 134217729: 8421890,
  41382. 402653185: 8421376,
  41383. 671088641: 8388608,
  41384. 939524097: 512,
  41385. 1207959553: 32768,
  41386. 1476395009: 8388610,
  41387. 1744830465: 2,
  41388. 2013265921: 33282,
  41389. 2281701377: 32770,
  41390. 2550136833: 8389122,
  41391. 2818572289: 514,
  41392. 3087007745: 8421888,
  41393. 3355443201: 8389120,
  41394. 3623878657: 0,
  41395. 3892314113: 33280,
  41396. 4160749569: 8421378
  41397. },
  41398. {
  41399. 0: 1074282512,
  41400. 16777216: 16384,
  41401. 33554432: 524288,
  41402. 50331648: 1074266128,
  41403. 67108864: 1073741840,
  41404. 83886080: 1074282496,
  41405. 100663296: 1073758208,
  41406. 117440512: 16,
  41407. 134217728: 540672,
  41408. 150994944: 1073758224,
  41409. 167772160: 1073741824,
  41410. 184549376: 540688,
  41411. 201326592: 524304,
  41412. 218103808: 0,
  41413. 234881024: 16400,
  41414. 251658240: 1074266112,
  41415. 8388608: 1073758208,
  41416. 25165824: 540688,
  41417. 41943040: 16,
  41418. 58720256: 1073758224,
  41419. 75497472: 1074282512,
  41420. 92274688: 1073741824,
  41421. 109051904: 524288,
  41422. 125829120: 1074266128,
  41423. 142606336: 524304,
  41424. 159383552: 0,
  41425. 176160768: 16384,
  41426. 192937984: 1074266112,
  41427. 209715200: 1073741840,
  41428. 226492416: 540672,
  41429. 243269632: 1074282496,
  41430. 260046848: 16400,
  41431. 268435456: 0,
  41432. 285212672: 1074266128,
  41433. 301989888: 1073758224,
  41434. 318767104: 1074282496,
  41435. 335544320: 1074266112,
  41436. 352321536: 16,
  41437. 369098752: 540688,
  41438. 385875968: 16384,
  41439. 402653184: 16400,
  41440. 419430400: 524288,
  41441. 436207616: 524304,
  41442. 452984832: 1073741840,
  41443. 469762048: 540672,
  41444. 486539264: 1073758208,
  41445. 503316480: 1073741824,
  41446. 520093696: 1074282512,
  41447. 276824064: 540688,
  41448. 293601280: 524288,
  41449. 310378496: 1074266112,
  41450. 327155712: 16384,
  41451. 343932928: 1073758208,
  41452. 360710144: 1074282512,
  41453. 377487360: 16,
  41454. 394264576: 1073741824,
  41455. 411041792: 1074282496,
  41456. 427819008: 1073741840,
  41457. 444596224: 1073758224,
  41458. 461373440: 524304,
  41459. 478150656: 0,
  41460. 494927872: 16400,
  41461. 511705088: 1074266128,
  41462. 528482304: 540672
  41463. },
  41464. {
  41465. 0: 260,
  41466. 1048576: 0,
  41467. 2097152: 67109120,
  41468. 3145728: 65796,
  41469. 4194304: 65540,
  41470. 5242880: 67108868,
  41471. 6291456: 67174660,
  41472. 7340032: 67174400,
  41473. 8388608: 67108864,
  41474. 9437184: 67174656,
  41475. 10485760: 65792,
  41476. 11534336: 67174404,
  41477. 12582912: 67109124,
  41478. 13631488: 65536,
  41479. 14680064: 4,
  41480. 15728640: 256,
  41481. 524288: 67174656,
  41482. 1572864: 67174404,
  41483. 2621440: 0,
  41484. 3670016: 67109120,
  41485. 4718592: 67108868,
  41486. 5767168: 65536,
  41487. 6815744: 65540,
  41488. 7864320: 260,
  41489. 8912896: 4,
  41490. 9961472: 256,
  41491. 11010048: 67174400,
  41492. 12058624: 65796,
  41493. 13107200: 65792,
  41494. 14155776: 67109124,
  41495. 15204352: 67174660,
  41496. 16252928: 67108864,
  41497. 16777216: 67174656,
  41498. 17825792: 65540,
  41499. 18874368: 65536,
  41500. 19922944: 67109120,
  41501. 20971520: 256,
  41502. 22020096: 67174660,
  41503. 23068672: 67108868,
  41504. 24117248: 0,
  41505. 25165824: 67109124,
  41506. 26214400: 67108864,
  41507. 27262976: 4,
  41508. 28311552: 65792,
  41509. 29360128: 67174400,
  41510. 30408704: 260,
  41511. 31457280: 65796,
  41512. 32505856: 67174404,
  41513. 17301504: 67108864,
  41514. 18350080: 260,
  41515. 19398656: 67174656,
  41516. 20447232: 0,
  41517. 21495808: 65540,
  41518. 22544384: 67109120,
  41519. 23592960: 256,
  41520. 24641536: 67174404,
  41521. 25690112: 65536,
  41522. 26738688: 67174660,
  41523. 27787264: 65796,
  41524. 28835840: 67108868,
  41525. 29884416: 67109124,
  41526. 30932992: 67174400,
  41527. 31981568: 4,
  41528. 33030144: 65792
  41529. },
  41530. {
  41531. 0: 2151682048,
  41532. 65536: 2147487808,
  41533. 131072: 4198464,
  41534. 196608: 2151677952,
  41535. 262144: 0,
  41536. 327680: 4198400,
  41537. 393216: 2147483712,
  41538. 458752: 4194368,
  41539. 524288: 2147483648,
  41540. 589824: 4194304,
  41541. 655360: 64,
  41542. 720896: 2147487744,
  41543. 786432: 2151678016,
  41544. 851968: 4160,
  41545. 917504: 4096,
  41546. 983040: 2151682112,
  41547. 32768: 2147487808,
  41548. 98304: 64,
  41549. 163840: 2151678016,
  41550. 229376: 2147487744,
  41551. 294912: 4198400,
  41552. 360448: 2151682112,
  41553. 425984: 0,
  41554. 491520: 2151677952,
  41555. 557056: 4096,
  41556. 622592: 2151682048,
  41557. 688128: 4194304,
  41558. 753664: 4160,
  41559. 819200: 2147483648,
  41560. 884736: 4194368,
  41561. 950272: 4198464,
  41562. 1015808: 2147483712,
  41563. 1048576: 4194368,
  41564. 1114112: 4198400,
  41565. 1179648: 2147483712,
  41566. 1245184: 0,
  41567. 1310720: 4160,
  41568. 1376256: 2151678016,
  41569. 1441792: 2151682048,
  41570. 1507328: 2147487808,
  41571. 1572864: 2151682112,
  41572. 1638400: 2147483648,
  41573. 1703936: 2151677952,
  41574. 1769472: 4198464,
  41575. 1835008: 2147487744,
  41576. 1900544: 4194304,
  41577. 1966080: 64,
  41578. 2031616: 4096,
  41579. 1081344: 2151677952,
  41580. 1146880: 2151682112,
  41581. 1212416: 0,
  41582. 1277952: 4198400,
  41583. 1343488: 4194368,
  41584. 1409024: 2147483648,
  41585. 1474560: 2147487808,
  41586. 1540096: 64,
  41587. 1605632: 2147483712,
  41588. 1671168: 4096,
  41589. 1736704: 2147487744,
  41590. 1802240: 2151678016,
  41591. 1867776: 4160,
  41592. 1933312: 2151682048,
  41593. 1998848: 4194304,
  41594. 2064384: 4198464
  41595. },
  41596. {
  41597. 0: 128,
  41598. 4096: 17039360,
  41599. 8192: 262144,
  41600. 12288: 536870912,
  41601. 16384: 537133184,
  41602. 20480: 16777344,
  41603. 24576: 553648256,
  41604. 28672: 262272,
  41605. 32768: 16777216,
  41606. 36864: 537133056,
  41607. 40960: 536871040,
  41608. 45056: 553910400,
  41609. 49152: 553910272,
  41610. 53248: 0,
  41611. 57344: 17039488,
  41612. 61440: 553648128,
  41613. 2048: 17039488,
  41614. 6144: 553648256,
  41615. 10240: 128,
  41616. 14336: 17039360,
  41617. 18432: 262144,
  41618. 22528: 537133184,
  41619. 26624: 553910272,
  41620. 30720: 536870912,
  41621. 34816: 537133056,
  41622. 38912: 0,
  41623. 43008: 553910400,
  41624. 47104: 16777344,
  41625. 51200: 536871040,
  41626. 55296: 553648128,
  41627. 59392: 16777216,
  41628. 63488: 262272,
  41629. 65536: 262144,
  41630. 69632: 128,
  41631. 73728: 536870912,
  41632. 77824: 553648256,
  41633. 81920: 16777344,
  41634. 86016: 553910272,
  41635. 90112: 537133184,
  41636. 94208: 16777216,
  41637. 98304: 553910400,
  41638. 102400: 553648128,
  41639. 106496: 17039360,
  41640. 110592: 537133056,
  41641. 114688: 262272,
  41642. 118784: 536871040,
  41643. 122880: 0,
  41644. 126976: 17039488,
  41645. 67584: 553648256,
  41646. 71680: 16777216,
  41647. 75776: 17039360,
  41648. 79872: 537133184,
  41649. 83968: 536870912,
  41650. 88064: 17039488,
  41651. 92160: 128,
  41652. 96256: 553910272,
  41653. 100352: 262272,
  41654. 104448: 553910400,
  41655. 108544: 0,
  41656. 112640: 553648128,
  41657. 116736: 16777344,
  41658. 120832: 262144,
  41659. 124928: 537133056,
  41660. 129024: 536871040
  41661. },
  41662. {
  41663. 0: 268435464,
  41664. 256: 8192,
  41665. 512: 270532608,
  41666. 768: 270540808,
  41667. 1024: 268443648,
  41668. 1280: 2097152,
  41669. 1536: 2097160,
  41670. 1792: 268435456,
  41671. 2048: 0,
  41672. 2304: 268443656,
  41673. 2560: 2105344,
  41674. 2816: 8,
  41675. 3072: 270532616,
  41676. 3328: 2105352,
  41677. 3584: 8200,
  41678. 3840: 270540800,
  41679. 128: 270532608,
  41680. 384: 270540808,
  41681. 640: 8,
  41682. 896: 2097152,
  41683. 1152: 2105352,
  41684. 1408: 268435464,
  41685. 1664: 268443648,
  41686. 1920: 8200,
  41687. 2176: 2097160,
  41688. 2432: 8192,
  41689. 2688: 268443656,
  41690. 2944: 270532616,
  41691. 3200: 0,
  41692. 3456: 270540800,
  41693. 3712: 2105344,
  41694. 3968: 268435456,
  41695. 4096: 268443648,
  41696. 4352: 270532616,
  41697. 4608: 270540808,
  41698. 4864: 8200,
  41699. 5120: 2097152,
  41700. 5376: 268435456,
  41701. 5632: 268435464,
  41702. 5888: 2105344,
  41703. 6144: 2105352,
  41704. 6400: 0,
  41705. 6656: 8,
  41706. 6912: 270532608,
  41707. 7168: 8192,
  41708. 7424: 268443656,
  41709. 7680: 270540800,
  41710. 7936: 2097160,
  41711. 4224: 8,
  41712. 4480: 2105344,
  41713. 4736: 2097152,
  41714. 4992: 268435464,
  41715. 5248: 268443648,
  41716. 5504: 8200,
  41717. 5760: 270540808,
  41718. 6016: 270532608,
  41719. 6272: 270540800,
  41720. 6528: 270532616,
  41721. 6784: 8192,
  41722. 7040: 2105352,
  41723. 7296: 2097160,
  41724. 7552: 0,
  41725. 7808: 268435456,
  41726. 8064: 268443656
  41727. },
  41728. {
  41729. 0: 1048576,
  41730. 16: 33555457,
  41731. 32: 1024,
  41732. 48: 1049601,
  41733. 64: 34604033,
  41734. 80: 0,
  41735. 96: 1,
  41736. 112: 34603009,
  41737. 128: 33555456,
  41738. 144: 1048577,
  41739. 160: 33554433,
  41740. 176: 34604032,
  41741. 192: 34603008,
  41742. 208: 1025,
  41743. 224: 1049600,
  41744. 240: 33554432,
  41745. 8: 34603009,
  41746. 24: 0,
  41747. 40: 33555457,
  41748. 56: 34604032,
  41749. 72: 1048576,
  41750. 88: 33554433,
  41751. 104: 33554432,
  41752. 120: 1025,
  41753. 136: 1049601,
  41754. 152: 33555456,
  41755. 168: 34603008,
  41756. 184: 1048577,
  41757. 200: 1024,
  41758. 216: 34604033,
  41759. 232: 1,
  41760. 248: 1049600,
  41761. 256: 33554432,
  41762. 272: 1048576,
  41763. 288: 33555457,
  41764. 304: 34603009,
  41765. 320: 1048577,
  41766. 336: 33555456,
  41767. 352: 34604032,
  41768. 368: 1049601,
  41769. 384: 1025,
  41770. 400: 34604033,
  41771. 416: 1049600,
  41772. 432: 1,
  41773. 448: 0,
  41774. 464: 34603008,
  41775. 480: 33554433,
  41776. 496: 1024,
  41777. 264: 1049600,
  41778. 280: 33555457,
  41779. 296: 34603009,
  41780. 312: 1,
  41781. 328: 33554432,
  41782. 344: 1048576,
  41783. 360: 1025,
  41784. 376: 34604032,
  41785. 392: 33554433,
  41786. 408: 34603008,
  41787. 424: 0,
  41788. 440: 34604033,
  41789. 456: 1049601,
  41790. 472: 1024,
  41791. 488: 33555456,
  41792. 504: 1048577
  41793. },
  41794. {
  41795. 0: 134219808,
  41796. 1: 131072,
  41797. 2: 134217728,
  41798. 3: 32,
  41799. 4: 131104,
  41800. 5: 134350880,
  41801. 6: 134350848,
  41802. 7: 2048,
  41803. 8: 134348800,
  41804. 9: 134219776,
  41805. 10: 133120,
  41806. 11: 134348832,
  41807. 12: 2080,
  41808. 13: 0,
  41809. 14: 134217760,
  41810. 15: 133152,
  41811. 2147483648: 2048,
  41812. 2147483649: 134350880,
  41813. 2147483650: 134219808,
  41814. 2147483651: 134217728,
  41815. 2147483652: 134348800,
  41816. 2147483653: 133120,
  41817. 2147483654: 133152,
  41818. 2147483655: 32,
  41819. 2147483656: 134217760,
  41820. 2147483657: 2080,
  41821. 2147483658: 131104,
  41822. 2147483659: 134350848,
  41823. 2147483660: 0,
  41824. 2147483661: 134348832,
  41825. 2147483662: 134219776,
  41826. 2147483663: 131072,
  41827. 16: 133152,
  41828. 17: 134350848,
  41829. 18: 32,
  41830. 19: 2048,
  41831. 20: 134219776,
  41832. 21: 134217760,
  41833. 22: 134348832,
  41834. 23: 131072,
  41835. 24: 0,
  41836. 25: 131104,
  41837. 26: 134348800,
  41838. 27: 134219808,
  41839. 28: 134350880,
  41840. 29: 133120,
  41841. 30: 2080,
  41842. 31: 134217728,
  41843. 2147483664: 131072,
  41844. 2147483665: 2048,
  41845. 2147483666: 134348832,
  41846. 2147483667: 133152,
  41847. 2147483668: 32,
  41848. 2147483669: 134348800,
  41849. 2147483670: 134217728,
  41850. 2147483671: 134219808,
  41851. 2147483672: 134350880,
  41852. 2147483673: 134217760,
  41853. 2147483674: 134219776,
  41854. 2147483675: 0,
  41855. 2147483676: 133120,
  41856. 2147483677: 2080,
  41857. 2147483678: 131104,
  41858. 2147483679: 134350848
  41859. }
  41860. ];
  41861. var SBOX_MASK = [
  41862. 4160749569,
  41863. 528482304,
  41864. 33030144,
  41865. 2064384,
  41866. 129024,
  41867. 8064,
  41868. 504,
  41869. 2147483679
  41870. ];
  41871. var DES = C_algo.DES = BlockCipher.extend({
  41872. _doReset: function() {
  41873. var key = this._key;
  41874. var keyWords = key.words;
  41875. var keyBits = [];
  41876. for (var i2 = 0; i2 < 56; i2++) {
  41877. var keyBitPos = PC1[i2] - 1;
  41878. keyBits[i2] = keyWords[keyBitPos >>> 5] >>> 31 - keyBitPos % 32 & 1;
  41879. }
  41880. var subKeys = this._subKeys = [];
  41881. for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
  41882. var subKey = subKeys[nSubKey] = [];
  41883. var bitShift = BIT_SHIFTS[nSubKey];
  41884. for (var i2 = 0; i2 < 24; i2++) {
  41885. subKey[i2 / 6 | 0] |= keyBits[(PC2[i2] - 1 + bitShift) % 28] << 31 - i2 % 6;
  41886. subKey[4 + (i2 / 6 | 0)] |= keyBits[28 + (PC2[i2 + 24] - 1 + bitShift) % 28] << 31 - i2 % 6;
  41887. }
  41888. subKey[0] = subKey[0] << 1 | subKey[0] >>> 31;
  41889. for (var i2 = 1; i2 < 7; i2++) {
  41890. subKey[i2] = subKey[i2] >>> (i2 - 1) * 4 + 3;
  41891. }
  41892. subKey[7] = subKey[7] << 5 | subKey[7] >>> 27;
  41893. }
  41894. var invSubKeys = this._invSubKeys = [];
  41895. for (var i2 = 0; i2 < 16; i2++) {
  41896. invSubKeys[i2] = subKeys[15 - i2];
  41897. }
  41898. },
  41899. encryptBlock: function(M2, offset) {
  41900. this._doCryptBlock(M2, offset, this._subKeys);
  41901. },
  41902. decryptBlock: function(M2, offset) {
  41903. this._doCryptBlock(M2, offset, this._invSubKeys);
  41904. },
  41905. _doCryptBlock: function(M2, offset, subKeys) {
  41906. this._lBlock = M2[offset];
  41907. this._rBlock = M2[offset + 1];
  41908. exchangeLR.call(this, 4, 252645135);
  41909. exchangeLR.call(this, 16, 65535);
  41910. exchangeRL.call(this, 2, 858993459);
  41911. exchangeRL.call(this, 8, 16711935);
  41912. exchangeLR.call(this, 1, 1431655765);
  41913. for (var round2 = 0; round2 < 16; round2++) {
  41914. var subKey = subKeys[round2];
  41915. var lBlock = this._lBlock;
  41916. var rBlock = this._rBlock;
  41917. var f2 = 0;
  41918. for (var i2 = 0; i2 < 8; i2++) {
  41919. f2 |= SBOX_P[i2][((rBlock ^ subKey[i2]) & SBOX_MASK[i2]) >>> 0];
  41920. }
  41921. this._lBlock = rBlock;
  41922. this._rBlock = lBlock ^ f2;
  41923. }
  41924. var t2 = this._lBlock;
  41925. this._lBlock = this._rBlock;
  41926. this._rBlock = t2;
  41927. exchangeLR.call(this, 1, 1431655765);
  41928. exchangeRL.call(this, 8, 16711935);
  41929. exchangeRL.call(this, 2, 858993459);
  41930. exchangeLR.call(this, 16, 65535);
  41931. exchangeLR.call(this, 4, 252645135);
  41932. M2[offset] = this._lBlock;
  41933. M2[offset + 1] = this._rBlock;
  41934. },
  41935. keySize: 64 / 32,
  41936. ivSize: 64 / 32,
  41937. blockSize: 64 / 32
  41938. });
  41939. function exchangeLR(offset, mask) {
  41940. var t2 = (this._lBlock >>> offset ^ this._rBlock) & mask;
  41941. this._rBlock ^= t2;
  41942. this._lBlock ^= t2 << offset;
  41943. }
  41944. function exchangeRL(offset, mask) {
  41945. var t2 = (this._rBlock >>> offset ^ this._lBlock) & mask;
  41946. this._lBlock ^= t2;
  41947. this._rBlock ^= t2 << offset;
  41948. }
  41949. C2.DES = BlockCipher._createHelper(DES);
  41950. var TripleDES = C_algo.TripleDES = BlockCipher.extend({
  41951. _doReset: function() {
  41952. var key = this._key;
  41953. var keyWords = key.words;
  41954. if (keyWords.length !== 2 && keyWords.length !== 4 && keyWords.length < 6) {
  41955. throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");
  41956. }
  41957. var key1 = keyWords.slice(0, 2);
  41958. var key2 = keyWords.length < 4 ? keyWords.slice(0, 2) : keyWords.slice(2, 4);
  41959. var key3 = keyWords.length < 6 ? keyWords.slice(0, 2) : keyWords.slice(4, 6);
  41960. this._des1 = DES.createEncryptor(WordArray.create(key1));
  41961. this._des2 = DES.createEncryptor(WordArray.create(key2));
  41962. this._des3 = DES.createEncryptor(WordArray.create(key3));
  41963. },
  41964. encryptBlock: function(M2, offset) {
  41965. this._des1.encryptBlock(M2, offset);
  41966. this._des2.decryptBlock(M2, offset);
  41967. this._des3.encryptBlock(M2, offset);
  41968. },
  41969. decryptBlock: function(M2, offset) {
  41970. this._des3.decryptBlock(M2, offset);
  41971. this._des2.encryptBlock(M2, offset);
  41972. this._des1.decryptBlock(M2, offset);
  41973. },
  41974. keySize: 192 / 32,
  41975. ivSize: 64 / 32,
  41976. blockSize: 64 / 32
  41977. });
  41978. C2.TripleDES = BlockCipher._createHelper(TripleDES);
  41979. })();
  41980. return CryptoJS2.TripleDES;
  41981. });
  41982. })(tripledes);
  41983. return tripledes.exports;
  41984. }
  41985. var rc4 = { exports: {} };
  41986. var hasRequiredRc4;
  41987. function requireRc4() {
  41988. if (hasRequiredRc4)
  41989. return rc4.exports;
  41990. hasRequiredRc4 = 1;
  41991. (function(module, exports) {
  41992. (function(root, factory, undef) {
  41993. {
  41994. module.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  41995. }
  41996. })(commonjsGlobal, function(CryptoJS2) {
  41997. (function() {
  41998. var C2 = CryptoJS2;
  41999. var C_lib = C2.lib;
  42000. var StreamCipher = C_lib.StreamCipher;
  42001. var C_algo = C2.algo;
  42002. var RC4 = C_algo.RC4 = StreamCipher.extend({
  42003. _doReset: function() {
  42004. var key = this._key;
  42005. var keyWords = key.words;
  42006. var keySigBytes = key.sigBytes;
  42007. var S2 = this._S = [];
  42008. for (var i2 = 0; i2 < 256; i2++) {
  42009. S2[i2] = i2;
  42010. }
  42011. for (var i2 = 0, j2 = 0; i2 < 256; i2++) {
  42012. var keyByteIndex = i2 % keySigBytes;
  42013. var keyByte = keyWords[keyByteIndex >>> 2] >>> 24 - keyByteIndex % 4 * 8 & 255;
  42014. j2 = (j2 + S2[i2] + keyByte) % 256;
  42015. var t2 = S2[i2];
  42016. S2[i2] = S2[j2];
  42017. S2[j2] = t2;
  42018. }
  42019. this._i = this._j = 0;
  42020. },
  42021. _doProcessBlock: function(M2, offset) {
  42022. M2[offset] ^= generateKeystreamWord.call(this);
  42023. },
  42024. keySize: 256 / 32,
  42025. ivSize: 0
  42026. });
  42027. function generateKeystreamWord() {
  42028. var S2 = this._S;
  42029. var i2 = this._i;
  42030. var j2 = this._j;
  42031. var keystreamWord = 0;
  42032. for (var n2 = 0; n2 < 4; n2++) {
  42033. i2 = (i2 + 1) % 256;
  42034. j2 = (j2 + S2[i2]) % 256;
  42035. var t2 = S2[i2];
  42036. S2[i2] = S2[j2];
  42037. S2[j2] = t2;
  42038. keystreamWord |= S2[(S2[i2] + S2[j2]) % 256] << 24 - n2 * 8;
  42039. }
  42040. this._i = i2;
  42041. this._j = j2;
  42042. return keystreamWord;
  42043. }
  42044. C2.RC4 = StreamCipher._createHelper(RC4);
  42045. var RC4Drop = C_algo.RC4Drop = RC4.extend({
  42046. /**
  42047. * Configuration options.
  42048. *
  42049. * @property {number} drop The number of keystream words to drop. Default 192
  42050. */
  42051. cfg: RC4.cfg.extend({
  42052. drop: 192
  42053. }),
  42054. _doReset: function() {
  42055. RC4._doReset.call(this);
  42056. for (var i2 = this.cfg.drop; i2 > 0; i2--) {
  42057. generateKeystreamWord.call(this);
  42058. }
  42059. }
  42060. });
  42061. C2.RC4Drop = StreamCipher._createHelper(RC4Drop);
  42062. })();
  42063. return CryptoJS2.RC4;
  42064. });
  42065. })(rc4);
  42066. return rc4.exports;
  42067. }
  42068. var rabbit = { exports: {} };
  42069. var hasRequiredRabbit;
  42070. function requireRabbit() {
  42071. if (hasRequiredRabbit)
  42072. return rabbit.exports;
  42073. hasRequiredRabbit = 1;
  42074. (function(module, exports) {
  42075. (function(root, factory, undef) {
  42076. {
  42077. module.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  42078. }
  42079. })(commonjsGlobal, function(CryptoJS2) {
  42080. (function() {
  42081. var C2 = CryptoJS2;
  42082. var C_lib = C2.lib;
  42083. var StreamCipher = C_lib.StreamCipher;
  42084. var C_algo = C2.algo;
  42085. var S2 = [];
  42086. var C_ = [];
  42087. var G2 = [];
  42088. var Rabbit = C_algo.Rabbit = StreamCipher.extend({
  42089. _doReset: function() {
  42090. var K2 = this._key.words;
  42091. var iv = this.cfg.iv;
  42092. for (var i2 = 0; i2 < 4; i2++) {
  42093. K2[i2] = (K2[i2] << 8 | K2[i2] >>> 24) & 16711935 | (K2[i2] << 24 | K2[i2] >>> 8) & 4278255360;
  42094. }
  42095. var X2 = this._X = [
  42096. K2[0],
  42097. K2[3] << 16 | K2[2] >>> 16,
  42098. K2[1],
  42099. K2[0] << 16 | K2[3] >>> 16,
  42100. K2[2],
  42101. K2[1] << 16 | K2[0] >>> 16,
  42102. K2[3],
  42103. K2[2] << 16 | K2[1] >>> 16
  42104. ];
  42105. var C3 = this._C = [
  42106. K2[2] << 16 | K2[2] >>> 16,
  42107. K2[0] & 4294901760 | K2[1] & 65535,
  42108. K2[3] << 16 | K2[3] >>> 16,
  42109. K2[1] & 4294901760 | K2[2] & 65535,
  42110. K2[0] << 16 | K2[0] >>> 16,
  42111. K2[2] & 4294901760 | K2[3] & 65535,
  42112. K2[1] << 16 | K2[1] >>> 16,
  42113. K2[3] & 4294901760 | K2[0] & 65535
  42114. ];
  42115. this._b = 0;
  42116. for (var i2 = 0; i2 < 4; i2++) {
  42117. nextState.call(this);
  42118. }
  42119. for (var i2 = 0; i2 < 8; i2++) {
  42120. C3[i2] ^= X2[i2 + 4 & 7];
  42121. }
  42122. if (iv) {
  42123. var IV = iv.words;
  42124. var IV_0 = IV[0];
  42125. var IV_1 = IV[1];
  42126. var i0 = (IV_0 << 8 | IV_0 >>> 24) & 16711935 | (IV_0 << 24 | IV_0 >>> 8) & 4278255360;
  42127. var i22 = (IV_1 << 8 | IV_1 >>> 24) & 16711935 | (IV_1 << 24 | IV_1 >>> 8) & 4278255360;
  42128. var i1 = i0 >>> 16 | i22 & 4294901760;
  42129. var i3 = i22 << 16 | i0 & 65535;
  42130. C3[0] ^= i0;
  42131. C3[1] ^= i1;
  42132. C3[2] ^= i22;
  42133. C3[3] ^= i3;
  42134. C3[4] ^= i0;
  42135. C3[5] ^= i1;
  42136. C3[6] ^= i22;
  42137. C3[7] ^= i3;
  42138. for (var i2 = 0; i2 < 4; i2++) {
  42139. nextState.call(this);
  42140. }
  42141. }
  42142. },
  42143. _doProcessBlock: function(M2, offset) {
  42144. var X2 = this._X;
  42145. nextState.call(this);
  42146. S2[0] = X2[0] ^ X2[5] >>> 16 ^ X2[3] << 16;
  42147. S2[1] = X2[2] ^ X2[7] >>> 16 ^ X2[5] << 16;
  42148. S2[2] = X2[4] ^ X2[1] >>> 16 ^ X2[7] << 16;
  42149. S2[3] = X2[6] ^ X2[3] >>> 16 ^ X2[1] << 16;
  42150. for (var i2 = 0; i2 < 4; i2++) {
  42151. S2[i2] = (S2[i2] << 8 | S2[i2] >>> 24) & 16711935 | (S2[i2] << 24 | S2[i2] >>> 8) & 4278255360;
  42152. M2[offset + i2] ^= S2[i2];
  42153. }
  42154. },
  42155. blockSize: 128 / 32,
  42156. ivSize: 64 / 32
  42157. });
  42158. function nextState() {
  42159. var X2 = this._X;
  42160. var C3 = this._C;
  42161. for (var i2 = 0; i2 < 8; i2++) {
  42162. C_[i2] = C3[i2];
  42163. }
  42164. C3[0] = C3[0] + 1295307597 + this._b | 0;
  42165. C3[1] = C3[1] + 3545052371 + (C3[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0;
  42166. C3[2] = C3[2] + 886263092 + (C3[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0;
  42167. C3[3] = C3[3] + 1295307597 + (C3[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0;
  42168. C3[4] = C3[4] + 3545052371 + (C3[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0;
  42169. C3[5] = C3[5] + 886263092 + (C3[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0;
  42170. C3[6] = C3[6] + 1295307597 + (C3[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0;
  42171. C3[7] = C3[7] + 3545052371 + (C3[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0;
  42172. this._b = C3[7] >>> 0 < C_[7] >>> 0 ? 1 : 0;
  42173. for (var i2 = 0; i2 < 8; i2++) {
  42174. var gx = X2[i2] + C3[i2];
  42175. var ga = gx & 65535;
  42176. var gb = gx >>> 16;
  42177. var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb;
  42178. var gl = ((gx & 4294901760) * gx | 0) + ((gx & 65535) * gx | 0);
  42179. G2[i2] = gh ^ gl;
  42180. }
  42181. X2[0] = G2[0] + (G2[7] << 16 | G2[7] >>> 16) + (G2[6] << 16 | G2[6] >>> 16) | 0;
  42182. X2[1] = G2[1] + (G2[0] << 8 | G2[0] >>> 24) + G2[7] | 0;
  42183. X2[2] = G2[2] + (G2[1] << 16 | G2[1] >>> 16) + (G2[0] << 16 | G2[0] >>> 16) | 0;
  42184. X2[3] = G2[3] + (G2[2] << 8 | G2[2] >>> 24) + G2[1] | 0;
  42185. X2[4] = G2[4] + (G2[3] << 16 | G2[3] >>> 16) + (G2[2] << 16 | G2[2] >>> 16) | 0;
  42186. X2[5] = G2[5] + (G2[4] << 8 | G2[4] >>> 24) + G2[3] | 0;
  42187. X2[6] = G2[6] + (G2[5] << 16 | G2[5] >>> 16) + (G2[4] << 16 | G2[4] >>> 16) | 0;
  42188. X2[7] = G2[7] + (G2[6] << 8 | G2[6] >>> 24) + G2[5] | 0;
  42189. }
  42190. C2.Rabbit = StreamCipher._createHelper(Rabbit);
  42191. })();
  42192. return CryptoJS2.Rabbit;
  42193. });
  42194. })(rabbit);
  42195. return rabbit.exports;
  42196. }
  42197. var rabbitLegacy = { exports: {} };
  42198. var hasRequiredRabbitLegacy;
  42199. function requireRabbitLegacy() {
  42200. if (hasRequiredRabbitLegacy)
  42201. return rabbitLegacy.exports;
  42202. hasRequiredRabbitLegacy = 1;
  42203. (function(module, exports) {
  42204. (function(root, factory, undef) {
  42205. {
  42206. module.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  42207. }
  42208. })(commonjsGlobal, function(CryptoJS2) {
  42209. (function() {
  42210. var C2 = CryptoJS2;
  42211. var C_lib = C2.lib;
  42212. var StreamCipher = C_lib.StreamCipher;
  42213. var C_algo = C2.algo;
  42214. var S2 = [];
  42215. var C_ = [];
  42216. var G2 = [];
  42217. var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
  42218. _doReset: function() {
  42219. var K2 = this._key.words;
  42220. var iv = this.cfg.iv;
  42221. var X2 = this._X = [
  42222. K2[0],
  42223. K2[3] << 16 | K2[2] >>> 16,
  42224. K2[1],
  42225. K2[0] << 16 | K2[3] >>> 16,
  42226. K2[2],
  42227. K2[1] << 16 | K2[0] >>> 16,
  42228. K2[3],
  42229. K2[2] << 16 | K2[1] >>> 16
  42230. ];
  42231. var C3 = this._C = [
  42232. K2[2] << 16 | K2[2] >>> 16,
  42233. K2[0] & 4294901760 | K2[1] & 65535,
  42234. K2[3] << 16 | K2[3] >>> 16,
  42235. K2[1] & 4294901760 | K2[2] & 65535,
  42236. K2[0] << 16 | K2[0] >>> 16,
  42237. K2[2] & 4294901760 | K2[3] & 65535,
  42238. K2[1] << 16 | K2[1] >>> 16,
  42239. K2[3] & 4294901760 | K2[0] & 65535
  42240. ];
  42241. this._b = 0;
  42242. for (var i2 = 0; i2 < 4; i2++) {
  42243. nextState.call(this);
  42244. }
  42245. for (var i2 = 0; i2 < 8; i2++) {
  42246. C3[i2] ^= X2[i2 + 4 & 7];
  42247. }
  42248. if (iv) {
  42249. var IV = iv.words;
  42250. var IV_0 = IV[0];
  42251. var IV_1 = IV[1];
  42252. var i0 = (IV_0 << 8 | IV_0 >>> 24) & 16711935 | (IV_0 << 24 | IV_0 >>> 8) & 4278255360;
  42253. var i22 = (IV_1 << 8 | IV_1 >>> 24) & 16711935 | (IV_1 << 24 | IV_1 >>> 8) & 4278255360;
  42254. var i1 = i0 >>> 16 | i22 & 4294901760;
  42255. var i3 = i22 << 16 | i0 & 65535;
  42256. C3[0] ^= i0;
  42257. C3[1] ^= i1;
  42258. C3[2] ^= i22;
  42259. C3[3] ^= i3;
  42260. C3[4] ^= i0;
  42261. C3[5] ^= i1;
  42262. C3[6] ^= i22;
  42263. C3[7] ^= i3;
  42264. for (var i2 = 0; i2 < 4; i2++) {
  42265. nextState.call(this);
  42266. }
  42267. }
  42268. },
  42269. _doProcessBlock: function(M2, offset) {
  42270. var X2 = this._X;
  42271. nextState.call(this);
  42272. S2[0] = X2[0] ^ X2[5] >>> 16 ^ X2[3] << 16;
  42273. S2[1] = X2[2] ^ X2[7] >>> 16 ^ X2[5] << 16;
  42274. S2[2] = X2[4] ^ X2[1] >>> 16 ^ X2[7] << 16;
  42275. S2[3] = X2[6] ^ X2[3] >>> 16 ^ X2[1] << 16;
  42276. for (var i2 = 0; i2 < 4; i2++) {
  42277. S2[i2] = (S2[i2] << 8 | S2[i2] >>> 24) & 16711935 | (S2[i2] << 24 | S2[i2] >>> 8) & 4278255360;
  42278. M2[offset + i2] ^= S2[i2];
  42279. }
  42280. },
  42281. blockSize: 128 / 32,
  42282. ivSize: 64 / 32
  42283. });
  42284. function nextState() {
  42285. var X2 = this._X;
  42286. var C3 = this._C;
  42287. for (var i2 = 0; i2 < 8; i2++) {
  42288. C_[i2] = C3[i2];
  42289. }
  42290. C3[0] = C3[0] + 1295307597 + this._b | 0;
  42291. C3[1] = C3[1] + 3545052371 + (C3[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0;
  42292. C3[2] = C3[2] + 886263092 + (C3[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0;
  42293. C3[3] = C3[3] + 1295307597 + (C3[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0;
  42294. C3[4] = C3[4] + 3545052371 + (C3[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0;
  42295. C3[5] = C3[5] + 886263092 + (C3[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0;
  42296. C3[6] = C3[6] + 1295307597 + (C3[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0;
  42297. C3[7] = C3[7] + 3545052371 + (C3[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0;
  42298. this._b = C3[7] >>> 0 < C_[7] >>> 0 ? 1 : 0;
  42299. for (var i2 = 0; i2 < 8; i2++) {
  42300. var gx = X2[i2] + C3[i2];
  42301. var ga = gx & 65535;
  42302. var gb = gx >>> 16;
  42303. var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb;
  42304. var gl = ((gx & 4294901760) * gx | 0) + ((gx & 65535) * gx | 0);
  42305. G2[i2] = gh ^ gl;
  42306. }
  42307. X2[0] = G2[0] + (G2[7] << 16 | G2[7] >>> 16) + (G2[6] << 16 | G2[6] >>> 16) | 0;
  42308. X2[1] = G2[1] + (G2[0] << 8 | G2[0] >>> 24) + G2[7] | 0;
  42309. X2[2] = G2[2] + (G2[1] << 16 | G2[1] >>> 16) + (G2[0] << 16 | G2[0] >>> 16) | 0;
  42310. X2[3] = G2[3] + (G2[2] << 8 | G2[2] >>> 24) + G2[1] | 0;
  42311. X2[4] = G2[4] + (G2[3] << 16 | G2[3] >>> 16) + (G2[2] << 16 | G2[2] >>> 16) | 0;
  42312. X2[5] = G2[5] + (G2[4] << 8 | G2[4] >>> 24) + G2[3] | 0;
  42313. X2[6] = G2[6] + (G2[5] << 16 | G2[5] >>> 16) + (G2[4] << 16 | G2[4] >>> 16) | 0;
  42314. X2[7] = G2[7] + (G2[6] << 8 | G2[6] >>> 24) + G2[5] | 0;
  42315. }
  42316. C2.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
  42317. })();
  42318. return CryptoJS2.RabbitLegacy;
  42319. });
  42320. })(rabbitLegacy);
  42321. return rabbitLegacy.exports;
  42322. }
  42323. var blowfish = { exports: {} };
  42324. var hasRequiredBlowfish;
  42325. function requireBlowfish() {
  42326. if (hasRequiredBlowfish)
  42327. return blowfish.exports;
  42328. hasRequiredBlowfish = 1;
  42329. (function(module, exports) {
  42330. (function(root, factory, undef) {
  42331. {
  42332. module.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
  42333. }
  42334. })(commonjsGlobal, function(CryptoJS2) {
  42335. (function() {
  42336. var C2 = CryptoJS2;
  42337. var C_lib = C2.lib;
  42338. var BlockCipher = C_lib.BlockCipher;
  42339. var C_algo = C2.algo;
  42340. const N2 = 16;
  42341. const ORIG_P = [
  42342. 608135816,
  42343. 2242054355,
  42344. 320440878,
  42345. 57701188,
  42346. 2752067618,
  42347. 698298832,
  42348. 137296536,
  42349. 3964562569,
  42350. 1160258022,
  42351. 953160567,
  42352. 3193202383,
  42353. 887688300,
  42354. 3232508343,
  42355. 3380367581,
  42356. 1065670069,
  42357. 3041331479,
  42358. 2450970073,
  42359. 2306472731
  42360. ];
  42361. const ORIG_S = [
  42362. [
  42363. 3509652390,
  42364. 2564797868,
  42365. 805139163,
  42366. 3491422135,
  42367. 3101798381,
  42368. 1780907670,
  42369. 3128725573,
  42370. 4046225305,
  42371. 614570311,
  42372. 3012652279,
  42373. 134345442,
  42374. 2240740374,
  42375. 1667834072,
  42376. 1901547113,
  42377. 2757295779,
  42378. 4103290238,
  42379. 227898511,
  42380. 1921955416,
  42381. 1904987480,
  42382. 2182433518,
  42383. 2069144605,
  42384. 3260701109,
  42385. 2620446009,
  42386. 720527379,
  42387. 3318853667,
  42388. 677414384,
  42389. 3393288472,
  42390. 3101374703,
  42391. 2390351024,
  42392. 1614419982,
  42393. 1822297739,
  42394. 2954791486,
  42395. 3608508353,
  42396. 3174124327,
  42397. 2024746970,
  42398. 1432378464,
  42399. 3864339955,
  42400. 2857741204,
  42401. 1464375394,
  42402. 1676153920,
  42403. 1439316330,
  42404. 715854006,
  42405. 3033291828,
  42406. 289532110,
  42407. 2706671279,
  42408. 2087905683,
  42409. 3018724369,
  42410. 1668267050,
  42411. 732546397,
  42412. 1947742710,
  42413. 3462151702,
  42414. 2609353502,
  42415. 2950085171,
  42416. 1814351708,
  42417. 2050118529,
  42418. 680887927,
  42419. 999245976,
  42420. 1800124847,
  42421. 3300911131,
  42422. 1713906067,
  42423. 1641548236,
  42424. 4213287313,
  42425. 1216130144,
  42426. 1575780402,
  42427. 4018429277,
  42428. 3917837745,
  42429. 3693486850,
  42430. 3949271944,
  42431. 596196993,
  42432. 3549867205,
  42433. 258830323,
  42434. 2213823033,
  42435. 772490370,
  42436. 2760122372,
  42437. 1774776394,
  42438. 2652871518,
  42439. 566650946,
  42440. 4142492826,
  42441. 1728879713,
  42442. 2882767088,
  42443. 1783734482,
  42444. 3629395816,
  42445. 2517608232,
  42446. 2874225571,
  42447. 1861159788,
  42448. 326777828,
  42449. 3124490320,
  42450. 2130389656,
  42451. 2716951837,
  42452. 967770486,
  42453. 1724537150,
  42454. 2185432712,
  42455. 2364442137,
  42456. 1164943284,
  42457. 2105845187,
  42458. 998989502,
  42459. 3765401048,
  42460. 2244026483,
  42461. 1075463327,
  42462. 1455516326,
  42463. 1322494562,
  42464. 910128902,
  42465. 469688178,
  42466. 1117454909,
  42467. 936433444,
  42468. 3490320968,
  42469. 3675253459,
  42470. 1240580251,
  42471. 122909385,
  42472. 2157517691,
  42473. 634681816,
  42474. 4142456567,
  42475. 3825094682,
  42476. 3061402683,
  42477. 2540495037,
  42478. 79693498,
  42479. 3249098678,
  42480. 1084186820,
  42481. 1583128258,
  42482. 426386531,
  42483. 1761308591,
  42484. 1047286709,
  42485. 322548459,
  42486. 995290223,
  42487. 1845252383,
  42488. 2603652396,
  42489. 3431023940,
  42490. 2942221577,
  42491. 3202600964,
  42492. 3727903485,
  42493. 1712269319,
  42494. 422464435,
  42495. 3234572375,
  42496. 1170764815,
  42497. 3523960633,
  42498. 3117677531,
  42499. 1434042557,
  42500. 442511882,
  42501. 3600875718,
  42502. 1076654713,
  42503. 1738483198,
  42504. 4213154764,
  42505. 2393238008,
  42506. 3677496056,
  42507. 1014306527,
  42508. 4251020053,
  42509. 793779912,
  42510. 2902807211,
  42511. 842905082,
  42512. 4246964064,
  42513. 1395751752,
  42514. 1040244610,
  42515. 2656851899,
  42516. 3396308128,
  42517. 445077038,
  42518. 3742853595,
  42519. 3577915638,
  42520. 679411651,
  42521. 2892444358,
  42522. 2354009459,
  42523. 1767581616,
  42524. 3150600392,
  42525. 3791627101,
  42526. 3102740896,
  42527. 284835224,
  42528. 4246832056,
  42529. 1258075500,
  42530. 768725851,
  42531. 2589189241,
  42532. 3069724005,
  42533. 3532540348,
  42534. 1274779536,
  42535. 3789419226,
  42536. 2764799539,
  42537. 1660621633,
  42538. 3471099624,
  42539. 4011903706,
  42540. 913787905,
  42541. 3497959166,
  42542. 737222580,
  42543. 2514213453,
  42544. 2928710040,
  42545. 3937242737,
  42546. 1804850592,
  42547. 3499020752,
  42548. 2949064160,
  42549. 2386320175,
  42550. 2390070455,
  42551. 2415321851,
  42552. 4061277028,
  42553. 2290661394,
  42554. 2416832540,
  42555. 1336762016,
  42556. 1754252060,
  42557. 3520065937,
  42558. 3014181293,
  42559. 791618072,
  42560. 3188594551,
  42561. 3933548030,
  42562. 2332172193,
  42563. 3852520463,
  42564. 3043980520,
  42565. 413987798,
  42566. 3465142937,
  42567. 3030929376,
  42568. 4245938359,
  42569. 2093235073,
  42570. 3534596313,
  42571. 375366246,
  42572. 2157278981,
  42573. 2479649556,
  42574. 555357303,
  42575. 3870105701,
  42576. 2008414854,
  42577. 3344188149,
  42578. 4221384143,
  42579. 3956125452,
  42580. 2067696032,
  42581. 3594591187,
  42582. 2921233993,
  42583. 2428461,
  42584. 544322398,
  42585. 577241275,
  42586. 1471733935,
  42587. 610547355,
  42588. 4027169054,
  42589. 1432588573,
  42590. 1507829418,
  42591. 2025931657,
  42592. 3646575487,
  42593. 545086370,
  42594. 48609733,
  42595. 2200306550,
  42596. 1653985193,
  42597. 298326376,
  42598. 1316178497,
  42599. 3007786442,
  42600. 2064951626,
  42601. 458293330,
  42602. 2589141269,
  42603. 3591329599,
  42604. 3164325604,
  42605. 727753846,
  42606. 2179363840,
  42607. 146436021,
  42608. 1461446943,
  42609. 4069977195,
  42610. 705550613,
  42611. 3059967265,
  42612. 3887724982,
  42613. 4281599278,
  42614. 3313849956,
  42615. 1404054877,
  42616. 2845806497,
  42617. 146425753,
  42618. 1854211946
  42619. ],
  42620. [
  42621. 1266315497,
  42622. 3048417604,
  42623. 3681880366,
  42624. 3289982499,
  42625. 290971e4,
  42626. 1235738493,
  42627. 2632868024,
  42628. 2414719590,
  42629. 3970600049,
  42630. 1771706367,
  42631. 1449415276,
  42632. 3266420449,
  42633. 422970021,
  42634. 1963543593,
  42635. 2690192192,
  42636. 3826793022,
  42637. 1062508698,
  42638. 1531092325,
  42639. 1804592342,
  42640. 2583117782,
  42641. 2714934279,
  42642. 4024971509,
  42643. 1294809318,
  42644. 4028980673,
  42645. 1289560198,
  42646. 2221992742,
  42647. 1669523910,
  42648. 35572830,
  42649. 157838143,
  42650. 1052438473,
  42651. 1016535060,
  42652. 1802137761,
  42653. 1753167236,
  42654. 1386275462,
  42655. 3080475397,
  42656. 2857371447,
  42657. 1040679964,
  42658. 2145300060,
  42659. 2390574316,
  42660. 1461121720,
  42661. 2956646967,
  42662. 4031777805,
  42663. 4028374788,
  42664. 33600511,
  42665. 2920084762,
  42666. 1018524850,
  42667. 629373528,
  42668. 3691585981,
  42669. 3515945977,
  42670. 2091462646,
  42671. 2486323059,
  42672. 586499841,
  42673. 988145025,
  42674. 935516892,
  42675. 3367335476,
  42676. 2599673255,
  42677. 2839830854,
  42678. 265290510,
  42679. 3972581182,
  42680. 2759138881,
  42681. 3795373465,
  42682. 1005194799,
  42683. 847297441,
  42684. 406762289,
  42685. 1314163512,
  42686. 1332590856,
  42687. 1866599683,
  42688. 4127851711,
  42689. 750260880,
  42690. 613907577,
  42691. 1450815602,
  42692. 3165620655,
  42693. 3734664991,
  42694. 3650291728,
  42695. 3012275730,
  42696. 3704569646,
  42697. 1427272223,
  42698. 778793252,
  42699. 1343938022,
  42700. 2676280711,
  42701. 2052605720,
  42702. 1946737175,
  42703. 3164576444,
  42704. 3914038668,
  42705. 3967478842,
  42706. 3682934266,
  42707. 1661551462,
  42708. 3294938066,
  42709. 4011595847,
  42710. 840292616,
  42711. 3712170807,
  42712. 616741398,
  42713. 312560963,
  42714. 711312465,
  42715. 1351876610,
  42716. 322626781,
  42717. 1910503582,
  42718. 271666773,
  42719. 2175563734,
  42720. 1594956187,
  42721. 70604529,
  42722. 3617834859,
  42723. 1007753275,
  42724. 1495573769,
  42725. 4069517037,
  42726. 2549218298,
  42727. 2663038764,
  42728. 504708206,
  42729. 2263041392,
  42730. 3941167025,
  42731. 2249088522,
  42732. 1514023603,
  42733. 1998579484,
  42734. 1312622330,
  42735. 694541497,
  42736. 2582060303,
  42737. 2151582166,
  42738. 1382467621,
  42739. 776784248,
  42740. 2618340202,
  42741. 3323268794,
  42742. 2497899128,
  42743. 2784771155,
  42744. 503983604,
  42745. 4076293799,
  42746. 907881277,
  42747. 423175695,
  42748. 432175456,
  42749. 1378068232,
  42750. 4145222326,
  42751. 3954048622,
  42752. 3938656102,
  42753. 3820766613,
  42754. 2793130115,
  42755. 2977904593,
  42756. 26017576,
  42757. 3274890735,
  42758. 3194772133,
  42759. 1700274565,
  42760. 1756076034,
  42761. 4006520079,
  42762. 3677328699,
  42763. 720338349,
  42764. 1533947780,
  42765. 354530856,
  42766. 688349552,
  42767. 3973924725,
  42768. 1637815568,
  42769. 332179504,
  42770. 3949051286,
  42771. 53804574,
  42772. 2852348879,
  42773. 3044236432,
  42774. 1282449977,
  42775. 3583942155,
  42776. 3416972820,
  42777. 4006381244,
  42778. 1617046695,
  42779. 2628476075,
  42780. 3002303598,
  42781. 1686838959,
  42782. 431878346,
  42783. 2686675385,
  42784. 1700445008,
  42785. 1080580658,
  42786. 1009431731,
  42787. 832498133,
  42788. 3223435511,
  42789. 2605976345,
  42790. 2271191193,
  42791. 2516031870,
  42792. 1648197032,
  42793. 4164389018,
  42794. 2548247927,
  42795. 300782431,
  42796. 375919233,
  42797. 238389289,
  42798. 3353747414,
  42799. 2531188641,
  42800. 2019080857,
  42801. 1475708069,
  42802. 455242339,
  42803. 2609103871,
  42804. 448939670,
  42805. 3451063019,
  42806. 1395535956,
  42807. 2413381860,
  42808. 1841049896,
  42809. 1491858159,
  42810. 885456874,
  42811. 4264095073,
  42812. 4001119347,
  42813. 1565136089,
  42814. 3898914787,
  42815. 1108368660,
  42816. 540939232,
  42817. 1173283510,
  42818. 2745871338,
  42819. 3681308437,
  42820. 4207628240,
  42821. 3343053890,
  42822. 4016749493,
  42823. 1699691293,
  42824. 1103962373,
  42825. 3625875870,
  42826. 2256883143,
  42827. 3830138730,
  42828. 1031889488,
  42829. 3479347698,
  42830. 1535977030,
  42831. 4236805024,
  42832. 3251091107,
  42833. 2132092099,
  42834. 1774941330,
  42835. 1199868427,
  42836. 1452454533,
  42837. 157007616,
  42838. 2904115357,
  42839. 342012276,
  42840. 595725824,
  42841. 1480756522,
  42842. 206960106,
  42843. 497939518,
  42844. 591360097,
  42845. 863170706,
  42846. 2375253569,
  42847. 3596610801,
  42848. 1814182875,
  42849. 2094937945,
  42850. 3421402208,
  42851. 1082520231,
  42852. 3463918190,
  42853. 2785509508,
  42854. 435703966,
  42855. 3908032597,
  42856. 1641649973,
  42857. 2842273706,
  42858. 3305899714,
  42859. 1510255612,
  42860. 2148256476,
  42861. 2655287854,
  42862. 3276092548,
  42863. 4258621189,
  42864. 236887753,
  42865. 3681803219,
  42866. 274041037,
  42867. 1734335097,
  42868. 3815195456,
  42869. 3317970021,
  42870. 1899903192,
  42871. 1026095262,
  42872. 4050517792,
  42873. 356393447,
  42874. 2410691914,
  42875. 3873677099,
  42876. 3682840055
  42877. ],
  42878. [
  42879. 3913112168,
  42880. 2491498743,
  42881. 4132185628,
  42882. 2489919796,
  42883. 1091903735,
  42884. 1979897079,
  42885. 3170134830,
  42886. 3567386728,
  42887. 3557303409,
  42888. 857797738,
  42889. 1136121015,
  42890. 1342202287,
  42891. 507115054,
  42892. 2535736646,
  42893. 337727348,
  42894. 3213592640,
  42895. 1301675037,
  42896. 2528481711,
  42897. 1895095763,
  42898. 1721773893,
  42899. 3216771564,
  42900. 62756741,
  42901. 2142006736,
  42902. 835421444,
  42903. 2531993523,
  42904. 1442658625,
  42905. 3659876326,
  42906. 2882144922,
  42907. 676362277,
  42908. 1392781812,
  42909. 170690266,
  42910. 3921047035,
  42911. 1759253602,
  42912. 3611846912,
  42913. 1745797284,
  42914. 664899054,
  42915. 1329594018,
  42916. 3901205900,
  42917. 3045908486,
  42918. 2062866102,
  42919. 2865634940,
  42920. 3543621612,
  42921. 3464012697,
  42922. 1080764994,
  42923. 553557557,
  42924. 3656615353,
  42925. 3996768171,
  42926. 991055499,
  42927. 499776247,
  42928. 1265440854,
  42929. 648242737,
  42930. 3940784050,
  42931. 980351604,
  42932. 3713745714,
  42933. 1749149687,
  42934. 3396870395,
  42935. 4211799374,
  42936. 3640570775,
  42937. 1161844396,
  42938. 3125318951,
  42939. 1431517754,
  42940. 545492359,
  42941. 4268468663,
  42942. 3499529547,
  42943. 1437099964,
  42944. 2702547544,
  42945. 3433638243,
  42946. 2581715763,
  42947. 2787789398,
  42948. 1060185593,
  42949. 1593081372,
  42950. 2418618748,
  42951. 4260947970,
  42952. 69676912,
  42953. 2159744348,
  42954. 86519011,
  42955. 2512459080,
  42956. 3838209314,
  42957. 1220612927,
  42958. 3339683548,
  42959. 133810670,
  42960. 1090789135,
  42961. 1078426020,
  42962. 1569222167,
  42963. 845107691,
  42964. 3583754449,
  42965. 4072456591,
  42966. 1091646820,
  42967. 628848692,
  42968. 1613405280,
  42969. 3757631651,
  42970. 526609435,
  42971. 236106946,
  42972. 48312990,
  42973. 2942717905,
  42974. 3402727701,
  42975. 1797494240,
  42976. 859738849,
  42977. 992217954,
  42978. 4005476642,
  42979. 2243076622,
  42980. 3870952857,
  42981. 3732016268,
  42982. 765654824,
  42983. 3490871365,
  42984. 2511836413,
  42985. 1685915746,
  42986. 3888969200,
  42987. 1414112111,
  42988. 2273134842,
  42989. 3281911079,
  42990. 4080962846,
  42991. 172450625,
  42992. 2569994100,
  42993. 980381355,
  42994. 4109958455,
  42995. 2819808352,
  42996. 2716589560,
  42997. 2568741196,
  42998. 3681446669,
  42999. 3329971472,
  43000. 1835478071,
  43001. 660984891,
  43002. 3704678404,
  43003. 4045999559,
  43004. 3422617507,
  43005. 3040415634,
  43006. 1762651403,
  43007. 1719377915,
  43008. 3470491036,
  43009. 2693910283,
  43010. 3642056355,
  43011. 3138596744,
  43012. 1364962596,
  43013. 2073328063,
  43014. 1983633131,
  43015. 926494387,
  43016. 3423689081,
  43017. 2150032023,
  43018. 4096667949,
  43019. 1749200295,
  43020. 3328846651,
  43021. 309677260,
  43022. 2016342300,
  43023. 1779581495,
  43024. 3079819751,
  43025. 111262694,
  43026. 1274766160,
  43027. 443224088,
  43028. 298511866,
  43029. 1025883608,
  43030. 3806446537,
  43031. 1145181785,
  43032. 168956806,
  43033. 3641502830,
  43034. 3584813610,
  43035. 1689216846,
  43036. 3666258015,
  43037. 3200248200,
  43038. 1692713982,
  43039. 2646376535,
  43040. 4042768518,
  43041. 1618508792,
  43042. 1610833997,
  43043. 3523052358,
  43044. 4130873264,
  43045. 2001055236,
  43046. 3610705100,
  43047. 2202168115,
  43048. 4028541809,
  43049. 2961195399,
  43050. 1006657119,
  43051. 2006996926,
  43052. 3186142756,
  43053. 1430667929,
  43054. 3210227297,
  43055. 1314452623,
  43056. 4074634658,
  43057. 4101304120,
  43058. 2273951170,
  43059. 1399257539,
  43060. 3367210612,
  43061. 3027628629,
  43062. 1190975929,
  43063. 2062231137,
  43064. 2333990788,
  43065. 2221543033,
  43066. 2438960610,
  43067. 1181637006,
  43068. 548689776,
  43069. 2362791313,
  43070. 3372408396,
  43071. 3104550113,
  43072. 3145860560,
  43073. 296247880,
  43074. 1970579870,
  43075. 3078560182,
  43076. 3769228297,
  43077. 1714227617,
  43078. 3291629107,
  43079. 3898220290,
  43080. 166772364,
  43081. 1251581989,
  43082. 493813264,
  43083. 448347421,
  43084. 195405023,
  43085. 2709975567,
  43086. 677966185,
  43087. 3703036547,
  43088. 1463355134,
  43089. 2715995803,
  43090. 1338867538,
  43091. 1343315457,
  43092. 2802222074,
  43093. 2684532164,
  43094. 233230375,
  43095. 2599980071,
  43096. 2000651841,
  43097. 3277868038,
  43098. 1638401717,
  43099. 4028070440,
  43100. 3237316320,
  43101. 6314154,
  43102. 819756386,
  43103. 300326615,
  43104. 590932579,
  43105. 1405279636,
  43106. 3267499572,
  43107. 3150704214,
  43108. 2428286686,
  43109. 3959192993,
  43110. 3461946742,
  43111. 1862657033,
  43112. 1266418056,
  43113. 963775037,
  43114. 2089974820,
  43115. 2263052895,
  43116. 1917689273,
  43117. 448879540,
  43118. 3550394620,
  43119. 3981727096,
  43120. 150775221,
  43121. 3627908307,
  43122. 1303187396,
  43123. 508620638,
  43124. 2975983352,
  43125. 2726630617,
  43126. 1817252668,
  43127. 1876281319,
  43128. 1457606340,
  43129. 908771278,
  43130. 3720792119,
  43131. 3617206836,
  43132. 2455994898,
  43133. 1729034894,
  43134. 1080033504
  43135. ],
  43136. [
  43137. 976866871,
  43138. 3556439503,
  43139. 2881648439,
  43140. 1522871579,
  43141. 1555064734,
  43142. 1336096578,
  43143. 3548522304,
  43144. 2579274686,
  43145. 3574697629,
  43146. 3205460757,
  43147. 3593280638,
  43148. 3338716283,
  43149. 3079412587,
  43150. 564236357,
  43151. 2993598910,
  43152. 1781952180,
  43153. 1464380207,
  43154. 3163844217,
  43155. 3332601554,
  43156. 1699332808,
  43157. 1393555694,
  43158. 1183702653,
  43159. 3581086237,
  43160. 1288719814,
  43161. 691649499,
  43162. 2847557200,
  43163. 2895455976,
  43164. 3193889540,
  43165. 2717570544,
  43166. 1781354906,
  43167. 1676643554,
  43168. 2592534050,
  43169. 3230253752,
  43170. 1126444790,
  43171. 2770207658,
  43172. 2633158820,
  43173. 2210423226,
  43174. 2615765581,
  43175. 2414155088,
  43176. 3127139286,
  43177. 673620729,
  43178. 2805611233,
  43179. 1269405062,
  43180. 4015350505,
  43181. 3341807571,
  43182. 4149409754,
  43183. 1057255273,
  43184. 2012875353,
  43185. 2162469141,
  43186. 2276492801,
  43187. 2601117357,
  43188. 993977747,
  43189. 3918593370,
  43190. 2654263191,
  43191. 753973209,
  43192. 36408145,
  43193. 2530585658,
  43194. 25011837,
  43195. 3520020182,
  43196. 2088578344,
  43197. 530523599,
  43198. 2918365339,
  43199. 1524020338,
  43200. 1518925132,
  43201. 3760827505,
  43202. 3759777254,
  43203. 1202760957,
  43204. 3985898139,
  43205. 3906192525,
  43206. 674977740,
  43207. 4174734889,
  43208. 2031300136,
  43209. 2019492241,
  43210. 3983892565,
  43211. 4153806404,
  43212. 3822280332,
  43213. 352677332,
  43214. 2297720250,
  43215. 60907813,
  43216. 90501309,
  43217. 3286998549,
  43218. 1016092578,
  43219. 2535922412,
  43220. 2839152426,
  43221. 457141659,
  43222. 509813237,
  43223. 4120667899,
  43224. 652014361,
  43225. 1966332200,
  43226. 2975202805,
  43227. 55981186,
  43228. 2327461051,
  43229. 676427537,
  43230. 3255491064,
  43231. 2882294119,
  43232. 3433927263,
  43233. 1307055953,
  43234. 942726286,
  43235. 933058658,
  43236. 2468411793,
  43237. 3933900994,
  43238. 4215176142,
  43239. 1361170020,
  43240. 2001714738,
  43241. 2830558078,
  43242. 3274259782,
  43243. 1222529897,
  43244. 1679025792,
  43245. 2729314320,
  43246. 3714953764,
  43247. 1770335741,
  43248. 151462246,
  43249. 3013232138,
  43250. 1682292957,
  43251. 1483529935,
  43252. 471910574,
  43253. 1539241949,
  43254. 458788160,
  43255. 3436315007,
  43256. 1807016891,
  43257. 3718408830,
  43258. 978976581,
  43259. 1043663428,
  43260. 3165965781,
  43261. 1927990952,
  43262. 4200891579,
  43263. 2372276910,
  43264. 3208408903,
  43265. 3533431907,
  43266. 1412390302,
  43267. 2931980059,
  43268. 4132332400,
  43269. 1947078029,
  43270. 3881505623,
  43271. 4168226417,
  43272. 2941484381,
  43273. 1077988104,
  43274. 1320477388,
  43275. 886195818,
  43276. 18198404,
  43277. 3786409e3,
  43278. 2509781533,
  43279. 112762804,
  43280. 3463356488,
  43281. 1866414978,
  43282. 891333506,
  43283. 18488651,
  43284. 661792760,
  43285. 1628790961,
  43286. 3885187036,
  43287. 3141171499,
  43288. 876946877,
  43289. 2693282273,
  43290. 1372485963,
  43291. 791857591,
  43292. 2686433993,
  43293. 3759982718,
  43294. 3167212022,
  43295. 3472953795,
  43296. 2716379847,
  43297. 445679433,
  43298. 3561995674,
  43299. 3504004811,
  43300. 3574258232,
  43301. 54117162,
  43302. 3331405415,
  43303. 2381918588,
  43304. 3769707343,
  43305. 4154350007,
  43306. 1140177722,
  43307. 4074052095,
  43308. 668550556,
  43309. 3214352940,
  43310. 367459370,
  43311. 261225585,
  43312. 2610173221,
  43313. 4209349473,
  43314. 3468074219,
  43315. 3265815641,
  43316. 314222801,
  43317. 3066103646,
  43318. 3808782860,
  43319. 282218597,
  43320. 3406013506,
  43321. 3773591054,
  43322. 379116347,
  43323. 1285071038,
  43324. 846784868,
  43325. 2669647154,
  43326. 3771962079,
  43327. 3550491691,
  43328. 2305946142,
  43329. 453669953,
  43330. 1268987020,
  43331. 3317592352,
  43332. 3279303384,
  43333. 3744833421,
  43334. 2610507566,
  43335. 3859509063,
  43336. 266596637,
  43337. 3847019092,
  43338. 517658769,
  43339. 3462560207,
  43340. 3443424879,
  43341. 370717030,
  43342. 4247526661,
  43343. 2224018117,
  43344. 4143653529,
  43345. 4112773975,
  43346. 2788324899,
  43347. 2477274417,
  43348. 1456262402,
  43349. 2901442914,
  43350. 1517677493,
  43351. 1846949527,
  43352. 2295493580,
  43353. 3734397586,
  43354. 2176403920,
  43355. 1280348187,
  43356. 1908823572,
  43357. 3871786941,
  43358. 846861322,
  43359. 1172426758,
  43360. 3287448474,
  43361. 3383383037,
  43362. 1655181056,
  43363. 3139813346,
  43364. 901632758,
  43365. 1897031941,
  43366. 2986607138,
  43367. 3066810236,
  43368. 3447102507,
  43369. 1393639104,
  43370. 373351379,
  43371. 950779232,
  43372. 625454576,
  43373. 3124240540,
  43374. 4148612726,
  43375. 2007998917,
  43376. 544563296,
  43377. 2244738638,
  43378. 2330496472,
  43379. 2058025392,
  43380. 1291430526,
  43381. 424198748,
  43382. 50039436,
  43383. 29584100,
  43384. 3605783033,
  43385. 2429876329,
  43386. 2791104160,
  43387. 1057563949,
  43388. 3255363231,
  43389. 3075367218,
  43390. 3463963227,
  43391. 1469046755,
  43392. 985887462
  43393. ]
  43394. ];
  43395. var BLOWFISH_CTX = {
  43396. pbox: [],
  43397. sbox: []
  43398. };
  43399. function F2(ctx, x) {
  43400. let a2 = x >> 24 & 255;
  43401. let b2 = x >> 16 & 255;
  43402. let c2 = x >> 8 & 255;
  43403. let d2 = x & 255;
  43404. let y2 = ctx.sbox[0][a2] + ctx.sbox[1][b2];
  43405. y2 = y2 ^ ctx.sbox[2][c2];
  43406. y2 = y2 + ctx.sbox[3][d2];
  43407. return y2;
  43408. }
  43409. function BlowFish_Encrypt(ctx, left, right) {
  43410. let Xl = left;
  43411. let Xr = right;
  43412. let temp;
  43413. for (let i2 = 0; i2 < N2; ++i2) {
  43414. Xl = Xl ^ ctx.pbox[i2];
  43415. Xr = F2(ctx, Xl) ^ Xr;
  43416. temp = Xl;
  43417. Xl = Xr;
  43418. Xr = temp;
  43419. }
  43420. temp = Xl;
  43421. Xl = Xr;
  43422. Xr = temp;
  43423. Xr = Xr ^ ctx.pbox[N2];
  43424. Xl = Xl ^ ctx.pbox[N2 + 1];
  43425. return { left: Xl, right: Xr };
  43426. }
  43427. function BlowFish_Decrypt(ctx, left, right) {
  43428. let Xl = left;
  43429. let Xr = right;
  43430. let temp;
  43431. for (let i2 = N2 + 1; i2 > 1; --i2) {
  43432. Xl = Xl ^ ctx.pbox[i2];
  43433. Xr = F2(ctx, Xl) ^ Xr;
  43434. temp = Xl;
  43435. Xl = Xr;
  43436. Xr = temp;
  43437. }
  43438. temp = Xl;
  43439. Xl = Xr;
  43440. Xr = temp;
  43441. Xr = Xr ^ ctx.pbox[1];
  43442. Xl = Xl ^ ctx.pbox[0];
  43443. return { left: Xl, right: Xr };
  43444. }
  43445. function BlowFishInit(ctx, key, keysize) {
  43446. for (let Row2 = 0; Row2 < 4; Row2++) {
  43447. ctx.sbox[Row2] = [];
  43448. for (let Col2 = 0; Col2 < 256; Col2++) {
  43449. ctx.sbox[Row2][Col2] = ORIG_S[Row2][Col2];
  43450. }
  43451. }
  43452. let keyIndex = 0;
  43453. for (let index2 = 0; index2 < N2 + 2; index2++) {
  43454. ctx.pbox[index2] = ORIG_P[index2] ^ key[keyIndex];
  43455. keyIndex++;
  43456. if (keyIndex >= keysize) {
  43457. keyIndex = 0;
  43458. }
  43459. }
  43460. let Data1 = 0;
  43461. let Data2 = 0;
  43462. let res = 0;
  43463. for (let i2 = 0; i2 < N2 + 2; i2 += 2) {
  43464. res = BlowFish_Encrypt(ctx, Data1, Data2);
  43465. Data1 = res.left;
  43466. Data2 = res.right;
  43467. ctx.pbox[i2] = Data1;
  43468. ctx.pbox[i2 + 1] = Data2;
  43469. }
  43470. for (let i2 = 0; i2 < 4; i2++) {
  43471. for (let j2 = 0; j2 < 256; j2 += 2) {
  43472. res = BlowFish_Encrypt(ctx, Data1, Data2);
  43473. Data1 = res.left;
  43474. Data2 = res.right;
  43475. ctx.sbox[i2][j2] = Data1;
  43476. ctx.sbox[i2][j2 + 1] = Data2;
  43477. }
  43478. }
  43479. return true;
  43480. }
  43481. var Blowfish = C_algo.Blowfish = BlockCipher.extend({
  43482. _doReset: function() {
  43483. if (this._keyPriorReset === this._key) {
  43484. return;
  43485. }
  43486. var key = this._keyPriorReset = this._key;
  43487. var keyWords = key.words;
  43488. var keySize = key.sigBytes / 4;
  43489. BlowFishInit(BLOWFISH_CTX, keyWords, keySize);
  43490. },
  43491. encryptBlock: function(M2, offset) {
  43492. var res = BlowFish_Encrypt(BLOWFISH_CTX, M2[offset], M2[offset + 1]);
  43493. M2[offset] = res.left;
  43494. M2[offset + 1] = res.right;
  43495. },
  43496. decryptBlock: function(M2, offset) {
  43497. var res = BlowFish_Decrypt(BLOWFISH_CTX, M2[offset], M2[offset + 1]);
  43498. M2[offset] = res.left;
  43499. M2[offset + 1] = res.right;
  43500. },
  43501. blockSize: 64 / 32,
  43502. keySize: 128 / 32,
  43503. ivSize: 64 / 32
  43504. });
  43505. C2.Blowfish = BlockCipher._createHelper(Blowfish);
  43506. })();
  43507. return CryptoJS2.Blowfish;
  43508. });
  43509. })(blowfish);
  43510. return blowfish.exports;
  43511. }
  43512. (function(module, exports) {
  43513. (function(root, factory, undef) {
  43514. {
  43515. module.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());
  43516. }
  43517. })(commonjsGlobal, function(CryptoJS2) {
  43518. return CryptoJS2;
  43519. });
  43520. })(cryptoJs);
  43521. var cryptoJsExports = cryptoJs.exports;
  43522. const CryptoJS = /* @__PURE__ */ getDefaultExportFromCjs(cryptoJsExports);
  43523. let request$5 = new Request$1().http;
  43524. const api$3 = {
  43525. liveDataLike: (liveId) => `/app/live/liveData/like/${liveId}`,
  43526. // 点赞
  43527. collectStore: "/app/live/liveData/collectStore",
  43528. // 收藏/取消收藏
  43529. follow: (liveId) => `/app/live/liveData/follow/${liveId}`,
  43530. // 关注/取消关注
  43531. getRecentLiveViewers: (liveId) => `/app/live/liveData/getRecentLiveViewers/${liveId}`,
  43532. // 获取直播间用户(展示在线用户)
  43533. // checkSms: 'api/sms/checkSms',
  43534. getLive: (liveId) => `/app/live/${liveId}`,
  43535. // 获取直播间信息接口
  43536. getLiveViewData: (liveId) => `/app/live/liveData/getLiveViewData/${liveId}`,
  43537. // 直播间点赞、关注、在线人数数据
  43538. // 直播订单
  43539. liveStore: (liveId) => `/app/live/liveGoods/liveStore/${liveId}`,
  43540. // 店铺展示
  43541. liveGoodsDetail: (productId) => `/app/live/liveGoods/liveGoodsDetail/${productId}`,
  43542. // 商品详情
  43543. liveOrderUser: (liveId) => `/app/live/liveOrder/liveOrderUser/${liveId}`
  43544. // 正在购买
  43545. };
  43546. function liveDataLike(liveId, data = {}) {
  43547. return request$5(api$3.liveDataLike(liveId), data, "GET", "application/json;charset=UTF-8");
  43548. }
  43549. function collectStore(data) {
  43550. return request$5(api$3.collectStore, data, "GET", "application/json;charset=UTF-8");
  43551. }
  43552. function follow(liveId, data = {}) {
  43553. return request$5(api$3.follow(liveId), data, "GET", "application/json;charset=UTF-8");
  43554. }
  43555. function getRecentLiveViewers(liveId, data = {}) {
  43556. return request$5(api$3.getRecentLiveViewers(liveId), data, "GET", "application/json;charset=UTF-8");
  43557. }
  43558. function liveStore(liveId, data) {
  43559. return request$5(api$3.liveStore(liveId), data, "GET", "application/json;charset=UTF-8");
  43560. }
  43561. function liveGoodsDetail(productId, data) {
  43562. return request$5(api$3.liveGoodsDetail(productId), data, "GET", "application/json;charset=UTF-8");
  43563. }
  43564. function liveOrderUser(liveId, data = {}) {
  43565. return request$5(api$3.liveOrderUser(liveId), data, "GET", "application/json;charset=UTF-8");
  43566. }
  43567. function getLive(liveId, data = {}) {
  43568. return request$5(api$3.getLive(liveId), data, "GET", "application/json;charset=UTF-8");
  43569. }
  43570. function getLiveViewData(liveId, data = {}) {
  43571. return request$5(api$3.getLiveViewData(liveId), data, "GET", "application/json;charset=UTF-8");
  43572. }
  43573. let request$4 = new Request$1().http;
  43574. const api$2 = {
  43575. // 直播订单
  43576. liveOrderList: "/app/live/liveOrder/list",
  43577. // 订单列表
  43578. createliveOrder: "/app/live/liveOrder/create",
  43579. // 创建订单
  43580. updateConfirm: (orderId, type) => `/app/live/liveOrder/updateConfirm/${orderId}/${type} `,
  43581. // 取消/支付订单确认
  43582. updateLiveOrder: "/app/live/liveOrder/update",
  43583. // 取消/支付订单
  43584. liveOrderKey: "/app/live/liveOrder/confirm",
  43585. // 生成订单key
  43586. userAddr: (userId) => `/app/user/getUserAddr/${userId} `
  43587. // 获取用户收货地址
  43588. };
  43589. function createliveOrder(data) {
  43590. return request$4(api$2.createliveOrder, data, "POST", "application/json;charset=UTF-8");
  43591. }
  43592. function liveOrderKey(data = {}) {
  43593. return request$4(api$2.liveOrderKey, data, "POST", "application/json;charset=UTF-8");
  43594. }
  43595. function liveOrderList(data) {
  43596. return request$4(api$2.liveOrderList, data, "GET", "application/json;charset=UTF-8");
  43597. }
  43598. function userAddr(userId, data = {}) {
  43599. return request$4(api$2.userAddr(userId), data, "GET", "application/json;charset=UTF-8");
  43600. }
  43601. const _imports_0$a = "/static/images/live/return.png";
  43602. const _imports_1$6 = "/static/images/live/like.png";
  43603. const _imports_2$5 = "/static/images/live/shop.png";
  43604. const _imports_3$2 = "/static/images/live/share.png";
  43605. const _imports_4$1 = "/static/images/live/shopping.png";
  43606. const _imports_5 = "/static/images/shopping.png";
  43607. const _imports_6 = "/static/images/more-icon.png";
  43608. const _imports_7 = "/static/images/search.png";
  43609. const _imports_10 = "/static/images/collect.png";
  43610. const _imports_9 = "/static/images/order.png";
  43611. var wsUrl$1 = "ws://v56c9b8e.natappfree.cc/app/webSocket";
  43612. var pingpangTimes$1 = null;
  43613. var isSocketOpen$1 = false;
  43614. var socket$1 = null;
  43615. const _sfc_main$p = {
  43616. data() {
  43617. return {
  43618. boxHeight: 300,
  43619. //小黄车高度
  43620. isFollow: true,
  43621. liveViewData: {},
  43622. liveViewers: [],
  43623. //观众
  43624. likeName: 0,
  43625. hlsPlayer: null,
  43626. // HLS播放器实例,
  43627. livingUrl: "",
  43628. products: {},
  43629. store: {},
  43630. orderUser: {},
  43631. //正在购买
  43632. userType: 0,
  43633. timestamp: "",
  43634. liveId: null,
  43635. // userId: uni.getStorageSync("userInfo.userId"),
  43636. livedata: {},
  43637. codeimg: "",
  43638. placeholderText: "说点什么...",
  43639. isZoom: false,
  43640. //点赞按钮控制是否放大
  43641. userinfo: "",
  43642. //用户信息
  43643. // path: 'http://192.168.10.166/dev-api', //余红奇
  43644. path: "http://v56c9b8e.natappfree.cc",
  43645. //余红奇
  43646. // path: 'http://192.168.10.170/dev-api', //陈果
  43647. value: "",
  43648. talkdisabled: false,
  43649. //输入框是否禁用
  43650. autoplay: true,
  43651. //视频自动播放
  43652. showadd: false,
  43653. talklist: [],
  43654. scrollIntoView: "",
  43655. bufferRate: 0,
  43656. //视频缓冲时间
  43657. playDuration: 0,
  43658. //视频播放时间
  43659. videoContext: "",
  43660. thistime: uni.$u.timeFormat(/* @__PURE__ */ new Date(), "yyyy-mm-dd hh:MM:ss"),
  43661. upDown: true,
  43662. //是否视频显示隐藏
  43663. isLongPress: false,
  43664. // 是否长按
  43665. timeout: null,
  43666. // 计时器
  43667. showWelcomeMessage: false,
  43668. isSubmit: false,
  43669. messageContent: "",
  43670. showziliao: false,
  43671. isScreen: true,
  43672. showAnswer: false,
  43673. //展示答题
  43674. Answerlistall: {},
  43675. //所有题目
  43676. answerlist: {},
  43677. //当前题目
  43678. answerfrist: 0,
  43679. //当前选择
  43680. checkboxValue: [],
  43681. //多选数据
  43682. checkboxFormValue: "",
  43683. //多选数据
  43684. allAnswerLists: [],
  43685. // 新增:存储所有题目列表
  43686. showAnswerred: false,
  43687. //展示红包答题
  43688. answerbtn: false,
  43689. //答题按钮弹窗
  43690. redallAnswerLists: [],
  43691. //储存所有红包答题列表
  43692. redanswerAll: [],
  43693. //红包当前题目
  43694. redanswerList: [],
  43695. //红包答题列表
  43696. redanswertips: [],
  43697. //红包答题提示
  43698. shopping: false,
  43699. //小黄车弹窗
  43700. scrollTop: 0,
  43701. //弹幕
  43702. old: {
  43703. scrollTop: 0
  43704. },
  43705. liveData: {}
  43706. //直播间点赞、关注、在线人数数据
  43707. // shopList: [{
  43708. // title: '史士昊老师四神汤健脾消食疗法',
  43709. // details: '看它来喘口气,小小震撼,',
  43710. // people: '45708 '
  43711. // },{
  43712. // title: '史士昊老师四神汤健脾消食疗法',
  43713. // details: '看它来喘口气,小小震撼,',
  43714. // people: '45708 '
  43715. // }],
  43716. // chatList: [{
  43717. // lable: '达人',
  43718. // name: '锅巴',
  43719. // txt: '中医调节身体确实'
  43720. // },
  43721. // {
  43722. // lable: '',
  43723. // name: '从芯开始',
  43724. // txt: '来了'
  43725. // }
  43726. // {
  43727. // lable: '',
  43728. // name: '北京的帅小伙:',
  43729. // txt: '来了来了,上茶'
  43730. // },
  43731. // {
  43732. // lable: '',
  43733. // name: '萍萍',
  43734. // txt: '来了'
  43735. // }
  43736. // ]
  43737. };
  43738. },
  43739. onLoad(options) {
  43740. if (options.liveId) {
  43741. this.liveId = options.liveId;
  43742. formatAppLog("log", "at pages/home/living.vue:503", "接收到的liveId:", this.liveId);
  43743. }
  43744. },
  43745. computed: {
  43746. filteredViewers() {
  43747. return this.liveViewers.slice(0, 3);
  43748. }
  43749. },
  43750. // computed: {
  43751. // userId() {
  43752. // return this.$store.state.user.userId
  43753. // }
  43754. // },
  43755. mounted() {
  43756. this.getliveViewData();
  43757. this.intervalId = setInterval(() => {
  43758. this.getliveViewData();
  43759. }, 60 * 1e3);
  43760. this.getLiveinformation();
  43761. this.getliveOrder();
  43762. this.getliveStore();
  43763. this.getliveUser();
  43764. this.initTime();
  43765. this.initSocket();
  43766. var that = this;
  43767. uni.$on("initSocket", () => {
  43768. that.initSocket();
  43769. });
  43770. uni.$on("sendMsg", (item) => {
  43771. that.sendMsg(item);
  43772. });
  43773. uni.$on("closeWebSocket", () => {
  43774. that.closeWebSocket();
  43775. });
  43776. this.getEWechatSdk();
  43777. this.getliving();
  43778. this.gettalklist();
  43779. this.userinfo = JSON.parse(uni.getStorageSync("userInfo"));
  43780. },
  43781. onReady: function(res) {
  43782. this.videoContext = uni.createVideoContext("myVideo");
  43783. },
  43784. onUnload() {
  43785. if (this.hlsPlayer) {
  43786. this.hlsPlayer.destroy();
  43787. this.hlsPlayer = null;
  43788. }
  43789. },
  43790. methods: {
  43791. // 去订单列表
  43792. goOrderList() {
  43793. uni.navigateTo({
  43794. url: "/pages_shop/order"
  43795. });
  43796. },
  43797. // 初始化HLS播放器
  43798. initHlsPlayer() {
  43799. if (Hls.isSupported() && this.livingUrl) {
  43800. const video2 = document.getElementById("myVideo");
  43801. if (video2) {
  43802. this.hlsPlayer = new Hls();
  43803. this.hlsPlayer.loadSource(this.livingUrl);
  43804. this.hlsPlayer.attachMedia(video2);
  43805. this.hlsPlayer.on(Hls.Events.MANIFEST_PARSED, () => {
  43806. video2.play();
  43807. });
  43808. }
  43809. }
  43810. },
  43811. // 视频错误处理
  43812. videoError(e2) {
  43813. formatAppLog("error", "at pages/home/living.vue:587", "视频播放错误:", e2.detail.errMsg);
  43814. if (this.livingUrl) {
  43815. setTimeout(() => {
  43816. this.videoContext.play();
  43817. }, 2e3);
  43818. }
  43819. },
  43820. getliving() {
  43821. const param = {
  43822. id: this.liveId
  43823. };
  43824. getlive(param).then((res) => {
  43825. if (res.code == 200) {
  43826. this.livedata = res.data;
  43827. this.codeimg = res.data.qwQrCode;
  43828. this.livingUrl = res.data.livingUrl;
  43829. if (this.livingUrl && this.livingUrl.indexOf(".m3u8") > -1) {
  43830. this.$nextTick(() => {
  43831. if (this.videoContext) {
  43832. this.videoContext.play();
  43833. }
  43834. });
  43835. } else {
  43836. if (this.livedata.status == 1) {
  43837. this.autoplay = true;
  43838. this.videoContext.seek(this.livedata.nowDuration);
  43839. } else {
  43840. this.autoplay = false;
  43841. this.placeholderText = "直播开始才能发言讨论";
  43842. this.talkdisabled = true;
  43843. }
  43844. }
  43845. } else {
  43846. uni.showToast({
  43847. title: res.msg,
  43848. icon: "none",
  43849. duration: 2e3
  43850. });
  43851. }
  43852. });
  43853. },
  43854. maskString(str, maskChar = "*") {
  43855. if (!str)
  43856. return "";
  43857. const strVal = String(str);
  43858. return strVal.split("").map((char, index2) => index2 === 0 ? char : maskChar).join("");
  43859. },
  43860. getPureDecimal(num, precision = 6) {
  43861. const decimalPart = Math.abs(num).toFixed(precision).split(".")[1];
  43862. return (decimalPart == null ? void 0 : decimalPart.replace(/0+$/, "")) || "";
  43863. },
  43864. // 返回上一个页面并关闭WebSocket
  43865. goBack() {
  43866. uni.navigateBack();
  43867. closeWebSocket();
  43868. },
  43869. // // 收藏商品
  43870. // collectProducts(){
  43871. // },
  43872. //直播间点赞、关注、在线人数数据
  43873. getliveViewData() {
  43874. getLiveViewData(this.liveId).then(
  43875. (res) => {
  43876. if (res.code == 200) {
  43877. this.liveViewData = res;
  43878. } else {
  43879. uni.showToast({
  43880. title: res.msg,
  43881. icon: "none"
  43882. });
  43883. }
  43884. },
  43885. (rej) => {
  43886. }
  43887. );
  43888. },
  43889. //正在购买
  43890. getliveOrder() {
  43891. liveOrderUser(this.liveId).then(
  43892. (res) => {
  43893. if (res.code == 200) {
  43894. formatAppLog("log", "at pages/home/living.vue:682", "正在购买>>>>", res);
  43895. this.orderUser = res;
  43896. } else {
  43897. uni.showToast({
  43898. title: res.msg,
  43899. icon: "none"
  43900. });
  43901. }
  43902. },
  43903. (rej) => {
  43904. }
  43905. );
  43906. },
  43907. //小黄车 店铺展示
  43908. getliveStore() {
  43909. let data = {
  43910. pageSize: 10,
  43911. page: 1
  43912. };
  43913. liveStore(this.liveId, data).then(
  43914. (res) => {
  43915. if (res.code == 200) {
  43916. formatAppLog("log", "at pages/home/living.vue:703", "小黄车 店铺展示>>>>", res);
  43917. this.products = res.data;
  43918. } else {
  43919. uni.showToast({
  43920. title: res.msg,
  43921. icon: "none"
  43922. });
  43923. }
  43924. },
  43925. (rej) => {
  43926. }
  43927. );
  43928. },
  43929. // 获取直播间信息接口
  43930. getLiveinformation() {
  43931. getLive(this.liveId).then(
  43932. (res) => {
  43933. if (res.code == 200) {
  43934. formatAppLog("log", "at pages/home/living.vue:720", "获取直播间信息接口>>>>", res);
  43935. this.livingUrl = res.livingUrl;
  43936. } else {
  43937. uni.showToast({
  43938. title: res.msg,
  43939. icon: "none"
  43940. });
  43941. }
  43942. },
  43943. (rej) => {
  43944. }
  43945. );
  43946. },
  43947. // 获取直播间用户
  43948. getliveUser() {
  43949. getRecentLiveViewers(this.liveId).then(
  43950. (res) => {
  43951. if (res.code == 200) {
  43952. formatAppLog("log", "at pages/home/living.vue:738", "获取直播间用户>>>>", res);
  43953. this.liveViewers = res.recentLiveViewers;
  43954. } else {
  43955. uni.showToast({
  43956. title: res.msg,
  43957. icon: "none"
  43958. });
  43959. }
  43960. },
  43961. (rej) => {
  43962. }
  43963. );
  43964. },
  43965. // 点赞
  43966. onLike() {
  43967. liveDataLike(this.liveId).then(
  43968. (res) => {
  43969. if (res.code == 200) {
  43970. if (typeof res.msg === "number" || typeof res.msg === "string" && /^\d+$/.test(res.msg.trim())) {
  43971. this.liveData++;
  43972. } else {
  43973. uni.showToast({
  43974. title: res.msg,
  43975. icon: "none"
  43976. });
  43977. }
  43978. } else {
  43979. uni.showToast({
  43980. title: res.msg,
  43981. icon: "none"
  43982. });
  43983. }
  43984. },
  43985. (rej) => {
  43986. }
  43987. );
  43988. },
  43989. // 去购买,跳商品详情
  43990. goShop(item) {
  43991. formatAppLog("log", "at pages/home/living.vue:779", "去购买,跳商品详情", item);
  43992. uni.navigateTo({
  43993. url: "/pages_shop/goods?productId=" + item + "&liveId=" + this.liveId
  43994. });
  43995. },
  43996. // 收藏
  43997. onCollect(item) {
  43998. formatAppLog("log", "at pages/home/living.vue:787", "item>>>", item.productId);
  43999. uni.setStorageSync("storeId", storeId);
  44000. let data = {
  44001. liveId: this.liveId,
  44002. productId: item.productId,
  44003. storeId: this.store.storeId
  44004. };
  44005. collectStore(data).then(
  44006. (res) => {
  44007. if (res.code == 200) {
  44008. formatAppLog("log", "at pages/home/living.vue:796", "收藏lcollectStore>>>>", res);
  44009. } else {
  44010. uni.showToast({
  44011. title: res.msg,
  44012. icon: "none"
  44013. });
  44014. }
  44015. },
  44016. (rej) => {
  44017. }
  44018. );
  44019. },
  44020. // 关注
  44021. onFollow() {
  44022. follow(this.liveId).then(
  44023. (res) => {
  44024. this.isFollow = !this.isFollow;
  44025. uni.showToast({
  44026. title: res.msg,
  44027. icon: "none"
  44028. });
  44029. },
  44030. (rej) => {
  44031. }
  44032. );
  44033. },
  44034. initTime() {
  44035. const now2 = /* @__PURE__ */ new Date();
  44036. this.timestamp = now2.getTime();
  44037. },
  44038. // initWebSocket() {
  44039. // const liveWS = new LiveWS('ws://your-server.com', 123, 456);
  44040. // // 从 URL 中解析 timestamp
  44041. // const urlParams = new URL(liveWS.url).searchParams;
  44042. // this.timestamp = urlParams.get('timestamp');
  44043. // // __f__('log','at pages/home/living.vue:831','Timestamp:', timestamp);
  44044. // },
  44045. // 弹幕滚动
  44046. lowerChat: function(e2) {
  44047. formatAppLog("log", "at pages/home/living.vue:836", e2);
  44048. },
  44049. scroll: function(e2) {
  44050. formatAppLog("log", "at pages/home/living.vue:839", e2);
  44051. this.old.scrollTop = e2.detail.scrollTop;
  44052. },
  44053. loadmore() {
  44054. },
  44055. // 弹幕
  44056. scrollchat() {
  44057. },
  44058. noredanswer() {
  44059. if (this.Answerlistall > 0) {
  44060. this.showAnswer = !this.this.showAnswer;
  44061. } else {
  44062. uni.showToast({
  44063. title: "暂无题目",
  44064. icon: "none"
  44065. });
  44066. }
  44067. },
  44068. redbagAnswer() {
  44069. this.showAnswerred = !this.showAnswerred;
  44070. this.answerbtn = !this.answerbtn;
  44071. },
  44072. submitAnswers() {
  44073. if (this.isSubmit)
  44074. return;
  44075. this.isSubmit = true;
  44076. const data = {
  44077. questionId: this.answerlist.id,
  44078. answer: this.checkboxFormValue
  44079. };
  44080. submitAnswer(data).then((res) => {
  44081. if (res.code == 200) {
  44082. uni.showToast({
  44083. title: res.msg,
  44084. icon: "none"
  44085. });
  44086. }
  44087. if (this.answerfrist < this.Answerlistall - 1) {
  44088. this.answerfrist++;
  44089. this.answerlist = this.allAnswerLists[this.answerfrist];
  44090. this.answerlist.content = JSON.parse(this.answerlist.content);
  44091. } else {
  44092. uni.showToast({
  44093. title: "已是最后一题",
  44094. icon: "none"
  44095. });
  44096. this.showAnswer = false;
  44097. }
  44098. this.checkboxValue = [];
  44099. this.checkboxFormValue = "";
  44100. uni.showToast({
  44101. title: res.msg,
  44102. icon: "none"
  44103. });
  44104. }).finally((e2) => {
  44105. this.isSubmit = false;
  44106. });
  44107. },
  44108. handleCheckboxSelect(value2) {
  44109. const index2 = this.checkboxValue.indexOf(value2);
  44110. formatAppLog("log", "at pages/home/living.vue:912", value2);
  44111. if (this.answerlist.type == 1) {
  44112. this.checkboxValue = [value2];
  44113. this.checkboxFormValue = this.checkboxValue.join(",");
  44114. this.submitAnswers();
  44115. formatAppLog("log", "at pages/home/living.vue:924", this.checkboxValue);
  44116. } else if (this.answerlist.type == 2) {
  44117. if (index2 > -1) {
  44118. this.checkboxValue.splice(index2, 1);
  44119. this.checkboxFormValue = this.checkboxValue.join(",");
  44120. } else {
  44121. this.checkboxValue.push(value2);
  44122. this.checkboxFormValue = this.checkboxValue.join(",");
  44123. }
  44124. formatAppLog("log", "at pages/home/living.vue:933", this.checkboxFormValue);
  44125. }
  44126. },
  44127. getAnswerlists() {
  44128. formatAppLog("log", "at pages/home/living.vue:937", 123);
  44129. const data = {
  44130. liveId: this.liveId
  44131. };
  44132. getAnswerlist(data).then((res) => {
  44133. if (res.code == 200) {
  44134. if (res.data.length > 0) {
  44135. this.allAnswerLists = res.data;
  44136. this.Answerlistall = res.data.length;
  44137. if (this.allAnswerLists.length > 0) {
  44138. this.answerlist = this.allAnswerLists[0];
  44139. this.answerlist.content = JSON.parse(this.allAnswerLists[0].content);
  44140. }
  44141. this.showAnswer = true;
  44142. } else {
  44143. this.showAnswer = false;
  44144. }
  44145. }
  44146. });
  44147. },
  44148. gettalklist() {
  44149. const param = {
  44150. id: this.liveId
  44151. };
  44152. gettextlist(param).then((res) => {
  44153. if (res.code == 200) {
  44154. this.talklist = res.data;
  44155. this.$nextTick(() => {
  44156. this.scrollIntoView = `list_${this.talklist.length - 1}`;
  44157. });
  44158. }
  44159. });
  44160. },
  44161. open() {
  44162. },
  44163. close() {
  44164. this.showadd = !this.showadd;
  44165. },
  44166. closes() {
  44167. this.showziliao = !this.showziliao;
  44168. },
  44169. closest() {
  44170. this.showAnswer = !this.showAnswer;
  44171. },
  44172. closestred() {
  44173. this.showAnswerred = !this.showAnswerred;
  44174. },
  44175. closeanswer() {
  44176. this.answerbtn = !this.answerbtn;
  44177. },
  44178. // 关闭小黄车
  44179. closeshop() {
  44180. this.shopping = !this.shopping;
  44181. },
  44182. longPress() {
  44183. this.timeout = setTimeout(() => {
  44184. this.isLongPress = true;
  44185. uni.saveImageToPhotosAlbum({
  44186. filePath: this.livedata.qwQrCode,
  44187. // 图片的本地路径或网络路径
  44188. success: () => {
  44189. uni.showToast({
  44190. title: "保存成功"
  44191. });
  44192. },
  44193. fail: () => {
  44194. uni.showToast({
  44195. title: "",
  44196. icon: "none"
  44197. });
  44198. }
  44199. });
  44200. }, 500);
  44201. },
  44202. cancelLongPress() {
  44203. clearTimeout(this.timeout);
  44204. this.isLongPress = false;
  44205. },
  44206. // 触摸开始
  44207. handleTouchStart() {
  44208. this.isZoom = true;
  44209. },
  44210. // 触摸结束
  44211. handleTouchEnd() {
  44212. this.isZoom = false;
  44213. },
  44214. getliving() {
  44215. const param = {
  44216. id: this.liveId
  44217. };
  44218. getlive(param).then((res) => {
  44219. if (res.code == 200) {
  44220. this.livedata = res.data;
  44221. this.codeimg = res.data.qwQrCode;
  44222. if (this.livedata.status == 1) {
  44223. this.autoplay = true;
  44224. this.videoContext.seek(this.livedata.nowDuration);
  44225. } else {
  44226. this.autoplay = false;
  44227. this.placeholderText = "直播开始才能发言讨论";
  44228. this.talkdisabled = true;
  44229. }
  44230. formatAppLog("log", "at pages/home/living.vue:1043", this.autoplay);
  44231. } else {
  44232. uni.showToast({
  44233. title: res.msg,
  44234. icon: "none",
  44235. duration: 2e3
  44236. });
  44237. }
  44238. });
  44239. },
  44240. getEWechatSdk() {
  44241. },
  44242. closeWebSocket() {
  44243. if (socket$1 != null) {
  44244. uni.closeSocket();
  44245. }
  44246. clearInterval(pingpangTimes$1);
  44247. },
  44248. reConnect() {
  44249. var that = this;
  44250. try {
  44251. uni.closeSocket();
  44252. } catch (e2) {
  44253. }
  44254. setTimeout(function() {
  44255. that.initSocket();
  44256. }, 1e4);
  44257. },
  44258. initSocket() {
  44259. this.userinfo = JSON.parse(uni.getStorageSync("userInfo"));
  44260. let signature = CryptoJS.HmacSHA256(
  44261. CryptoJS.enc.Utf8.parse(this.liveId.toString() + this.userinfo.userId + this.userType + this.timestamp),
  44262. CryptoJS.enc.Utf8.parse(this.timestamp)
  44263. ).toString(CryptoJS.enc.Hex);
  44264. var that = this;
  44265. socket$1 = uni.connectSocket({
  44266. // url: wsUrl+"?userId=40486&liveId=2",
  44267. // url: wsUrl + "?userId=" + this.userid + "&liveId=" +
  44268. // this.liveId+"&AppToken="+'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI0IiwiaWF0IjoxNzQwNzIxMDQ1LCJleHAiOjE3NDEzMjU4NDV9.PgS83JTMSJgVFD6vGAhUsEPbS6Az4yMyX8wVug61TZNTB3092CtvANo-AB9ZG4NdSBLgLrf4litM3vvTk-FK0g',
  44269. //
  44270. // url: wsUrl + "?userId=" + this.userId + "&liveId=" + this.liveId + "&AppToken=" + uni
  44271. // .getStorageSync('AppToken'),
  44272. url: wsUrl$1 + "?userId=" + this.userinfo.userId + "&liveId=" + this.liveId + "&userType=" + this.userType + "&timestamp=" + this.timestamp + "&signature=" + signature,
  44273. multiple: true,
  44274. success: (res) => {
  44275. clearInterval(pingpangTimes$1);
  44276. uni.onSocketMessage((res2) => {
  44277. if (res2.data.code == 500) {
  44278. uni.showToast({
  44279. title: res2.data.msg,
  44280. icon: "none",
  44281. duration: 2e3
  44282. });
  44283. }
  44284. const redata = JSON.parse(res2.data);
  44285. formatAppLog("log", "at pages/home/living.vue:1124", "WebSocket拿到的东西", redata);
  44286. this.talklist.push(redata.data);
  44287. this.$nextTick(() => {
  44288. this.scrollIntoView = `list_${this.talklist.length - 1}`;
  44289. });
  44290. if (redata.cmd == "deleteId") {
  44291. uni.$emit("deleteId");
  44292. } else if (redata.cmd == "init") {
  44293. uni.$emit("init", redata.data);
  44294. } else if (redata.cmd == "reload") {
  44295. uni.$emit("reload");
  44296. } else if (redata.data.cmd == "sendRedPacketQuestion") {
  44297. const list = JSON.parse(redata.data.data);
  44298. this.redanswerAll = [...this.redanswerAll, ...list];
  44299. if (this.redanswerAll[1].randomAmount !== null) {
  44300. this.redanswertips = JSON.parse(this.redanswerAll[0].randomAmount);
  44301. }
  44302. formatAppLog("log", "at pages/home/living.vue:1141", this.redanswertips);
  44303. formatAppLog("log", "at pages/home/living.vue:1142", this.redanswerAll);
  44304. } else if (redata.data.cmd == "entry") {
  44305. this.showWelcomeMessage = true;
  44306. uni.$emit("entry", redata.data);
  44307. }
  44308. });
  44309. },
  44310. error: (res) => {
  44311. uni.$emit("websocket", 0);
  44312. formatAppLog("log", "at pages/home/living.vue:1156", res);
  44313. }
  44314. });
  44315. uni.onSocketOpen(() => {
  44316. isSocketOpen$1 = true;
  44317. formatAppLog("log", "at pages/home/living.vue:1162", "WebSocket连接已打开!!");
  44318. uni.showToast({
  44319. title: "插件已打开",
  44320. icon: "none"
  44321. });
  44322. });
  44323. uni.onSocketClose(() => {
  44324. isSocketOpen$1 = false;
  44325. clearInterval(pingpangTimes$1);
  44326. formatAppLog("log", "at pages/home/living.vue:1173", "WebSocket连接已关闭!");
  44327. uni.showToast({
  44328. title: "插件离线",
  44329. icon: "none"
  44330. });
  44331. that.reConnect();
  44332. });
  44333. uni.onSocketError(() => {
  44334. isSocketOpen$1 = false;
  44335. clearInterval(pingpangTimes$1);
  44336. formatAppLog("log", "at pages/home/living.vue:1186", "WebSocket连接打开失败");
  44337. uni.showToast({
  44338. title: "插件离线",
  44339. icon: "none"
  44340. });
  44341. uni.showModal({
  44342. content: "聊天连接失败是否重新尝试连接",
  44343. success() {
  44344. that.reConnect();
  44345. }
  44346. });
  44347. });
  44348. },
  44349. sendMsg() {
  44350. if (isSocketOpen$1) {
  44351. const data = {
  44352. liveId: this.liveId,
  44353. userId: this.userinfo.userId,
  44354. userType: 0,
  44355. cmd: "sendMsg",
  44356. msg: this.value,
  44357. nickName: this.userinfo.nickName,
  44358. avatar: this.userinfo.avatar
  44359. };
  44360. if (this.value == "") {
  44361. uni.showToast({
  44362. title: "不能发送空消息",
  44363. icon: "none"
  44364. });
  44365. } else {
  44366. socket$1.send({
  44367. data: JSON.stringify(data),
  44368. success: () => {
  44369. formatAppLog("log", "at pages/home/living.vue:1223", "发送成功");
  44370. this.value = "";
  44371. },
  44372. fail: () => {
  44373. formatAppLog("log", "at pages/home/living.vue:1227", "发送失败");
  44374. }
  44375. });
  44376. }
  44377. }
  44378. }
  44379. }
  44380. };
  44381. function _sfc_render$o(_ctx, _cache, $props, $setup, $data, $options) {
  44382. const _component_u_avatar = resolveEasycom(vue.resolveDynamicComponent("u-avatar"), __easycom_1$1);
  44383. const _component_u_input = resolveEasycom(vue.resolveDynamicComponent("u-input"), __easycom_2$1);
  44384. const _component_u_icon = resolveEasycom(vue.resolveDynamicComponent("u-icon"), __easycom_0$4);
  44385. const _component_u_popup = resolveEasycom(vue.resolveDynamicComponent("u-popup"), __easycom_1$4);
  44386. return vue.openBlock(), vue.createElementBlock("view", { class: "container" }, [
  44387. vue.createCommentVNode(' <view class="popup-video " v-if="!autoplay">\r\n <view class="fs36 bold" v-if="livedata.status==1">——直播还未开始——</view>\r\n <view class="fs36 bold" v-if="livedata.status==3">——直播已经结束——</view>\r\n <view class="fs28 mtb20">了解更多,点击下方联系老师</view>\r\n <view class="more" @click="showadd=!showadd">联系老师</view>\r\n </view> '),
  44388. vue.createCommentVNode(` <image :src="livedata.liveImgUrl" \r
  44389. :class="livedata.status!=2?'background-images':'background-image'"></image> `),
  44390. vue.createElementVNode("view", { class: "blackbg" }),
  44391. vue.createElementVNode("view", { class: "content" }, [
  44392. vue.createCommentVNode(" 页面内容 "),
  44393. vue.createElementVNode("view", {
  44394. style: { "position": "fixed", "top": "0", "z-index": "5" },
  44395. class: "content-top"
  44396. }, [
  44397. vue.createElementVNode("view", { class: "u-flex-y-center" }, [
  44398. vue.createElementVNode("image", {
  44399. onClick: _cache[0] || (_cache[0] = (...args) => $options.goBack && $options.goBack(...args)),
  44400. style: { "width": "60rpx", "height": "64rpx", "margin-right": "26rpx" },
  44401. src: _imports_0$a
  44402. }),
  44403. vue.createElementVNode("view", {
  44404. class: "align-center",
  44405. style: { "padding": "6rpx 4rpx", "height": "64rpx", "background": "rgba(0,0,0,0.5)", "border-radius": "32rpx" }
  44406. }, [
  44407. vue.createVNode(_component_u_avatar, {
  44408. src: $data.livedata.liveImgUrl,
  44409. size: "32"
  44410. }, null, 8, ["src"]),
  44411. vue.createElementVNode("view", {
  44412. class: "colorf",
  44413. style: { "margin-left": "8rpx" }
  44414. }, [
  44415. vue.createElementVNode(
  44416. "view",
  44417. null,
  44418. vue.toDisplayString($data.livedata.liveName ? $data.livedata.liveName : "芳华未来"),
  44419. 1
  44420. /* TEXT */
  44421. ),
  44422. vue.createElementVNode(
  44423. "view",
  44424. { style: { "font-size": "16rpx" } },
  44425. vue.toDisplayString($data.liveViewData.follow || $data.liveViewData.follow === 0 ? $data.liveViewData.follow : 0) + "位粉丝 ",
  44426. 1
  44427. /* TEXT */
  44428. )
  44429. ]),
  44430. $data.isFollow ? (vue.openBlock(), vue.createElementBlock("view", {
  44431. key: 0,
  44432. onClick: _cache[1] || (_cache[1] = (...args) => $options.onFollow && $options.onFollow(...args)),
  44433. class: "follow-btn ml20"
  44434. }, "关注")) : (vue.openBlock(), vue.createElementBlock("view", {
  44435. key: 1,
  44436. onClick: _cache[2] || (_cache[2] = (...args) => $options.onFollow && $options.onFollow(...args)),
  44437. class: "follow-btn ml20"
  44438. }, "已关注"))
  44439. ])
  44440. ]),
  44441. vue.createElementVNode("view", { class: "u-flex-end align-center" }, [
  44442. (vue.openBlock(true), vue.createElementBlock(
  44443. vue.Fragment,
  44444. null,
  44445. vue.renderList($options.filteredViewers, (item, index2) => {
  44446. return vue.openBlock(), vue.createElementBlock("image", {
  44447. class: "w52 h52 mr4",
  44448. key: index2,
  44449. style: { "border-radius": "26rpx" },
  44450. src: item.avatar
  44451. }, null, 8, ["src"]);
  44452. }),
  44453. 128
  44454. /* KEYED_FRAGMENT */
  44455. )),
  44456. vue.createElementVNode(
  44457. "view",
  44458. { class: "sum" },
  44459. vue.toDisplayString($data.liveViewData.online),
  44460. 1
  44461. /* TEXT */
  44462. )
  44463. ])
  44464. ]),
  44465. vue.createCommentVNode(" 右边的 "),
  44466. vue.createElementVNode("view", { class: "side-group" }, [
  44467. vue.createElementVNode("view", { class: "side-item" }, [
  44468. vue.createElementVNode("image", {
  44469. onClick: _cache[3] || (_cache[3] = ($event) => $options.onLike()),
  44470. src: _imports_1$6
  44471. }),
  44472. vue.createElementVNode(
  44473. "view",
  44474. null,
  44475. vue.toDisplayString($data.liveViewData.like),
  44476. 1
  44477. /* TEXT */
  44478. ),
  44479. vue.createCommentVNode(" <view>{{liveData likeName}}</view> ")
  44480. ]),
  44481. vue.createElementVNode("view", { class: "side-item" }, [
  44482. vue.createElementVNode("image", { src: _imports_2$5 }),
  44483. vue.createElementVNode("view", null, "店铺")
  44484. ]),
  44485. vue.createElementVNode("view", { class: "side-item" }, [
  44486. vue.createElementVNode("image", { src: _imports_3$2 }),
  44487. vue.createElementVNode("view", null, "分享")
  44488. ])
  44489. ]),
  44490. vue.createElementVNode("view", { class: "shop-prompt u-flex-y-center" }, [
  44491. vue.createElementVNode("image", {
  44492. class: "w32 h32 mr8",
  44493. src: _imports_4$1
  44494. }),
  44495. vue.createElementVNode(
  44496. "text",
  44497. null,
  44498. vue.toDisplayString($data.orderUser.userName ? $options.maskString($data.orderUser.userName) : "") + " 等 " + vue.toDisplayString($data.orderUser.count || 0) + " 人正在去购买",
  44499. 1
  44500. /* TEXT */
  44501. )
  44502. ]),
  44503. vue.createCommentVNode(` <view class="videolist " style="margin: auto 0">\r
  44504. <view class="vedio" :style="{height:isScreen?'100vh':''}">\r
  44505. <video id="myVideo" class="videotop" :src="livingUrl" :autoplay="autoplay" :controls='false'\r
  44506. vslide-gesture-in-fullscreen='true' :show-center-play-btn="false"></video>\r
  44507. </view>\r
  44508. </view> `),
  44509. vue.createCommentVNode(" object-fit:fill; "),
  44510. vue.createElementVNode("view", {
  44511. class: "videolist",
  44512. style: { "margin": "auto 0" }
  44513. }, [
  44514. vue.createElementVNode(
  44515. "view",
  44516. {
  44517. class: "vedio",
  44518. style: vue.normalizeStyle({ height: $data.isScreen ? "100vh" : "" })
  44519. },
  44520. [
  44521. vue.createCommentVNode(" 修改video组件以支持HLS "),
  44522. vue.createElementVNode("video", {
  44523. id: "myVideo",
  44524. class: "videotop",
  44525. src: $data.livingUrl,
  44526. autoplay: $data.autoplay,
  44527. controls: false,
  44528. "custom-cache": false,
  44529. "enable-progress-gesture": false,
  44530. "vslide-gesture-in-fullscreen": "true",
  44531. "show-center-play-btn": false,
  44532. "http-cache": false,
  44533. onError: _cache[4] || (_cache[4] = (...args) => $options.videoError && $options.videoError(...args))
  44534. }, null, 40, ["src", "autoplay"])
  44535. ],
  44536. 4
  44537. /* STYLE */
  44538. )
  44539. ]),
  44540. vue.createElementVNode("view", {
  44541. class: "pb40 mt90",
  44542. style: { "position": "fixed", "bottom": "0" }
  44543. }, [
  44544. vue.createElementVNode("view", { class: "w100 h300 mt20" }, [
  44545. vue.createElementVNode("scroll-view", {
  44546. "scroll-y": "true",
  44547. class: "talk p20 scrolly flex-1 column",
  44548. style: { "width": "calc(100% - 40rpx)", "height": "calc(100% - 40rpx)" },
  44549. "scroll-into-view": $data.scrollIntoView
  44550. }, [
  44551. vue.createElementVNode("view", null, [
  44552. (vue.openBlock(true), vue.createElementBlock(
  44553. vue.Fragment,
  44554. null,
  44555. vue.renderList($data.talklist, (item, index2) => {
  44556. return vue.withDirectives((vue.openBlock(), vue.createElementBlock("view", {
  44557. class: "list justify-start",
  44558. key: item.index,
  44559. id: `list_${index2}`
  44560. }, [
  44561. vue.createElementVNode("view", { class: "talk-list ml16 justify-start" }, [
  44562. vue.createElementVNode("view", { class: "fs24" }, [
  44563. vue.createElementVNode(
  44564. "text",
  44565. { class: "fs24 colorf" },
  44566. vue.toDisplayString(item.msg) + "直播间" + vue.toDisplayString($data.messageContent),
  44567. 1
  44568. /* TEXT */
  44569. )
  44570. ])
  44571. ])
  44572. ], 8, ["id"])), [
  44573. [vue.vShow, item.cmd == "announcement"]
  44574. ]);
  44575. }),
  44576. 128
  44577. /* KEYED_FRAGMENT */
  44578. ))
  44579. ]),
  44580. vue.createCommentVNode(" 弹幕 "),
  44581. vue.createCommentVNode(' <u-list class="chat-list" height="184" @scrolltolower="scrollchat">\r\n <u-list-item class="chat-item" v-for="(item,index) in chatList" :key="index">\r\n <view class="chat-lable u-flex-y-center mr8" v-if="item.lable">\r\n <image class="w24 h24 mr8" src="@/static/images/live/diamond.png"></image>\r\n <text>{{item.lable}}</text>\r\n </view>\r\n <text style="color: #FFDA73;white-space: nowrap;" class=" mr8">{{item.name}}:</text>\r\n <text style="flex: 1;min-width: 0;word-break: break-word;">{{item.txt}}</text>\r\n </u-list-item>\r\n </u-list> '),
  44582. (vue.openBlock(true), vue.createElementBlock(
  44583. vue.Fragment,
  44584. null,
  44585. vue.renderList($data.talklist, (item, index2) => {
  44586. return vue.withDirectives((vue.openBlock(), vue.createElementBlock("view", {
  44587. class: "list justify-start",
  44588. key: item.index,
  44589. id: `list_${index2}`
  44590. }, [
  44591. vue.createElementVNode("view", { class: "talk-list ml16 justify-start" }, [
  44592. vue.createElementVNode("view", { class: "fs24" }, [
  44593. vue.createCommentVNode(` <text style="color: #3fc69b;transform: scale(0.8);display: inline-block; "v-if="item.userId==userinfo.userId&&item.cmd=='sendMsg'">我</text> `),
  44594. vue.createCommentVNode(' <text style="color: #c84e1e;transform: scale(0.8);display: inline-block;" v-if="item.userType==1">[ 管理员 ]</text> '),
  44595. vue.createElementVNode(
  44596. "text",
  44597. { style: { "color": "#FFDA73" } },
  44598. vue.toDisplayString(item.nickName) + ":",
  44599. 1
  44600. /* TEXT */
  44601. ),
  44602. vue.createElementVNode(
  44603. "text",
  44604. { class: "fs24 colorf" },
  44605. vue.toDisplayString(item.msg),
  44606. 1
  44607. /* TEXT */
  44608. )
  44609. ])
  44610. ])
  44611. ], 8, ["id"])), [
  44612. [vue.vShow, item.cmd == "sendMsg"]
  44613. ]);
  44614. }),
  44615. 128
  44616. /* KEYED_FRAGMENT */
  44617. )),
  44618. vue.createCommentVNode(` <view class="list justify-start" v-for="(item,index) in talklist" :key="item.index"\r
  44619. :id="\`list_\${index}\`" v-show="item.cmd=='sendMsg'">\r
  44620. \r
  44621. <view class="talk-list ml16 justify-start">\r
  44622. <view class="fs24">\r
  44623. <text style="color: #3fc69b;transform: scale(0.8);display: inline-block; "\r
  44624. v-if="item.userId==userinfo.userId&&item.cmd=='sendMsg'">我</text>\r
  44625. <text style="color: #c84e1e;transform: scale(0.8);display: inline-block;" v-if="item.userType==1">\r
  44626. [ 管理员 ]</text>\r
  44627. <text style="color: #FFDA73;">{{item.nickName}}:</text>\r
  44628. <text class='fs24 colorf'>{{item.msg}}</text>\r
  44629. </view>\r
  44630. </view>\r
  44631. </view> `),
  44632. $data.showWelcomeMessage ? (vue.openBlock(), vue.createElementBlock("view", {
  44633. key: 0,
  44634. class: "welcome-message"
  44635. }, [
  44636. (vue.openBlock(true), vue.createElementBlock(
  44637. vue.Fragment,
  44638. null,
  44639. vue.renderList($data.talklist, (item, index2) => {
  44640. return vue.withDirectives((vue.openBlock(), vue.createElementBlock("view", {
  44641. class: "list justify-start",
  44642. key: item.index,
  44643. id: `list_${index2}`
  44644. }, [
  44645. vue.createElementVNode("view", { class: "talk-list ml16 justify-start" }, [
  44646. vue.createElementVNode("view", { class: "fs24" }, [
  44647. vue.createElementVNode(
  44648. "text",
  44649. { style: { "color": "#ff89d6" } },
  44650. vue.toDisplayString(item.nickName),
  44651. 1
  44652. /* TEXT */
  44653. ),
  44654. vue.createElementVNode(
  44655. "text",
  44656. { class: "fs24 colorf" },
  44657. vue.toDisplayString(item.msg) + "直播间" + vue.toDisplayString($data.messageContent),
  44658. 1
  44659. /* TEXT */
  44660. )
  44661. ])
  44662. ])
  44663. ], 8, ["id"])), [
  44664. [vue.vShow, item.cmd == "entry" || item.cmd == "out"]
  44665. ]);
  44666. }),
  44667. 128
  44668. /* KEYED_FRAGMENT */
  44669. ))
  44670. ])) : vue.createCommentVNode("v-if", true)
  44671. ], 8, ["scroll-into-view"])
  44672. ]),
  44673. vue.createElementVNode("view", { class: "justify-between p24" }, [
  44674. vue.createElementVNode("view", {
  44675. class: "u-flex-y-center",
  44676. style: { "background": "rgba(255,255,255,0.2)", "padding": "18rpx 14rpx 18rpx 32rpx", "width": "526rpx", "box-sizing": "border-box", "border-radius": "36rpx" }
  44677. }, [
  44678. vue.createVNode(_component_u_input, {
  44679. placeholder: $data.placeholderText,
  44680. border: "none",
  44681. customStyle: "font-size:24rpx;",
  44682. modelValue: $data.value,
  44683. "onUpdate:modelValue": _cache[5] || (_cache[5] = ($event) => $data.value = $event),
  44684. shape: "circle",
  44685. color: "#fff",
  44686. placeholderStyle: "color:#e7e7e7",
  44687. class: "ml20",
  44688. onKeydown: vue.withKeys($options.sendMsg, ["enter"]),
  44689. onConfirm: $options.sendMsg
  44690. }, null, 8, ["placeholder", "modelValue", "onKeydown", "onConfirm"]),
  44691. vue.createCommentVNode(' <image @click="sendMsg" class="w44 h44" src="@/static/images/live/like.png"></image> ')
  44692. ]),
  44693. vue.createCommentVNode(" :disabled='talkdisabled' ></u-input> "),
  44694. vue.createCommentVNode(' <view @click="sendMsg" class="colorf center ml10 fs24">发送</view> '),
  44695. vue.createElementVNode("view", { class: "justify-between mr30 align-center" }, [
  44696. vue.createCommentVNode(' <view class="icon-bg ml20" @click="answerbtn=!answerbtn">\r\n <image src="/static/images/redbag.png" class="w40 h40"></image>\r\n </view> '),
  44697. vue.createElementVNode("view", {
  44698. class: "icon-bg ml20",
  44699. onClick: _cache[6] || (_cache[6] = ($event) => $data.shopping = !$data.shopping)
  44700. }, [
  44701. vue.createElementVNode("image", {
  44702. src: _imports_5,
  44703. class: "w48 h48"
  44704. })
  44705. ]),
  44706. vue.createElementVNode("view", {
  44707. class: "icon-bg ml20",
  44708. onClick: _cache[7] || (_cache[7] = ($event) => $data.showziliao = !$data.showziliao)
  44709. }, [
  44710. vue.createElementVNode("image", {
  44711. src: _imports_6,
  44712. class: "w48 h48"
  44713. })
  44714. ]),
  44715. vue.createCommentVNode(` <view class="icon-bg ml20" :class="{ 'zoom-button-active': isZoom }"\r
  44716. @touchstart="handleTouchStart" @touchend="handleTouchEnd">\r
  44717. <image src="/static/images/dianzan.png" class="w40 h40"></image>\r
  44718. </view> `)
  44719. ])
  44720. ])
  44721. ])
  44722. ]),
  44723. vue.createCommentVNode(` <u-popup :show="showadd" @close="close" @open="open" round='20rpx' bgColor='#fffee1'>\r
  44724. <view class="addchat p20">\r
  44725. <view class="u-flex-row-reverse u-flex">\r
  44726. <u-icon name="close" size="18" @click="showadd=!showadd"></u-icon>\r
  44727. </view>\r
  44728. <view class="column align-center">\r
  44729. <view class="fs36" style="color: #ff5c03;">扫码添加助教老师</view>\r
  44730. <view class="fs28 color6">扫码添加助教老师</view>\r
  44731. <view class="p10 mt40" style="border: #ff5c03 solid 2rpx;">\r
  44732. <image :src="codeimg" class="wh180" @touchstart="longPress" @touchend="cancelLongPress">\r
  44733. </image>\r
  44734. </view>\r
  44735. <view class="color6 mt20">长按识别二维码</view>\r
  44736. </view>\r
  44737. </view>\r
  44738. </u-popup> `),
  44739. vue.createVNode(_component_u_popup, {
  44740. show: $data.showziliao,
  44741. onClose: $options.closes,
  44742. round: "20",
  44743. bgColor: "#fffee1"
  44744. }, {
  44745. default: vue.withCtx(() => [
  44746. vue.createElementVNode("view", {
  44747. class: "addchat p20 bgf",
  44748. style: { "border-radius": "20rpx" }
  44749. }, [
  44750. vue.createElementVNode("view", { class: "u-flex-row-reverse u-flex" }, [
  44751. vue.createVNode(_component_u_icon, {
  44752. name: "close",
  44753. size: "18",
  44754. onClick: _cache[8] || (_cache[8] = ($event) => $data.showziliao = !$data.showziliao)
  44755. })
  44756. ]),
  44757. vue.createElementVNode("view", { class: "column align-center h400" }, [
  44758. vue.createElementVNode("view", {
  44759. class: "fs36",
  44760. style: { "color": "#ff5c03" }
  44761. }, "资料"),
  44762. vue.createElementVNode("view", {
  44763. innerHTML: $data.livedata.liveDesc
  44764. }, null, 8, ["innerHTML"])
  44765. ])
  44766. ])
  44767. ]),
  44768. _: 1
  44769. /* STABLE */
  44770. }, 8, ["show", "onClose"]),
  44771. vue.createCommentVNode(" 抽奖 "),
  44772. vue.createCommentVNode(` <u-popup :show="answerbtn" @close="closeanswer" round='40rpx' bgColor='#fff'>\r
  44773. <view class=" p20 bgf" style="border-radius: 40rpx;height: fit-content;">\r
  44774. <view class="u-flex-row-reverse u-flex">\r
  44775. <u-icon name="close" size="18" @click="answerbtn=!answerbtn"></u-icon>\r
  44776. </view>\r
  44777. <view class="column align-center h400">\r
  44778. <view class="fs36 " style="color: #000000;font-weight: bold;">答题获取红包/积分奖励</view>\r
  44779. <view class="answerpop" @click="noredanswer">\r
  44780. <view class="color6 w350 fs24">\r
  44781. 边玩边学,解锁你的知识巅峰!\r
  44782. </view>\r
  44783. <view class="answera">答题挑战</view>\r
  44784. </view>\r
  44785. <view class="answerpop">\r
  44786. \r
  44787. <view class="color6 fs24" v-if='redanswertips&&redanswertips.length>0'>\r
  44788. 🔥 <text style="color: #ff5c03;" class="fs30 bold">{{redanswertips[1].probability}}</text>\r
  44789. %用户首抽得\r
  44790. <text style="color: #ff5c03;" class="fs40 bold">{{redanswertips[1].maxAmount}}</text>元\r
  44791. </view>\r
  44792. <view v-else class="color6 w350 fs24">\r
  44793. 随机奖励\r
  44794. </view>\r
  44795. <view class="answera" @click="redbagAnswer">\r
  44796. <image src="/static/images/baganswer.png"></image>\r
  44797. <view> 获得红包</view>\r
  44798. </view>\r
  44799. </view>\r
  44800. </view>\r
  44801. </view>\r
  44802. </u-popup> `),
  44803. vue.createCommentVNode(` <u-popup :show="showAnswer" @close="closest" round='40' bgColor='#fffee1' mode="center">\r
  44804. <view class="answerbox p20 bgf">\r
  44805. <view class="u-flex-row-reverse u-flex">\r
  44806. <u-icon name="close" size="18" @click="closest"></u-icon>\r
  44807. </view>\r
  44808. <view class="column align-center ">\r
  44809. <view v-if="answerlist.type==1" style="width: 100%;">\r
  44810. <view class="mb40" style="text-align: center;">\r
  44811. <text class="color9 fs24">(单选)</text>{{answerlist.title}}\r
  44812. </view>\r
  44813. <view v-for="(item,index) in answerlist.content" :key="index"\r
  44814. :class=" checkboxValue[0]== item.label?'answeract itemanswer':'itemanswer' "\r
  44815. @click="handleCheckboxSelect(item.label)">{{item.label}}. {{item.content}}</view>\r
  44816. </view>\r
  44817. <view v-if="answerlist.type==2" style="width: 100%;">\r
  44818. <view class="mb40 " style="text-align: center;">\r
  44819. <text class="color9 fs24">(多选)</text>{{answerlist.title}}\r
  44820. </view>\r
  44821. <view v-for="(item,index) in answerlist.content" :key="index"\r
  44822. :class=" checkboxValue.includes(item.label)?'answeract itemanswer':'itemanswer' "\r
  44823. @click="handleCheckboxSelect(item.label)">{{item.label}}. {{item.content}}</view>\r
  44824. <view class=" submitbtn" @click="submitAnswers">确认</view>\r
  44825. </view>\r
  44826. <view class="fs24 mtb20 " style="color: #717171;">\r
  44827. {{answerfrist+1}}/{{Answerlistall}}\r
  44828. </view>\r
  44829. </view>\r
  44830. </view>\r
  44831. </u-popup> `),
  44832. vue.createCommentVNode(` <u-popup :show="showAnswerred" @close="closestred" round='40' bgColor='#fffee1' mode="center">\r
  44833. <view class="answerbox p20 bgf">\r
  44834. <view class="u-flex-row-reverse u-flex">\r
  44835. <u-icon name="close" size="18" @click="closestred"></u-icon>\r
  44836. </view>\r
  44837. <view class="column align-center ">\r
  44838. <view v-if="answerlist.type==1" style="width: 100%;">\r
  44839. <view class="mb40" style="text-align: center;">\r
  44840. <text class="color9 fs24">(单选)</text>{{answerlist.title}}\r
  44841. </view>\r
  44842. <view v-for="(item,index) in answerlist.content" :key="index"\r
  44843. :class=" checkboxValue[0]== item.label?'answeract itemanswer':'itemanswer' "\r
  44844. @click="handleCheckboxSelect(item.label)">{{item.label}}. {{item.content}}</view>\r
  44845. </view>\r
  44846. <view v-if="answerlist.type==2" style="width: 100%;">\r
  44847. <view class="mb40 " style="text-align: center;">\r
  44848. <text class="color9 fs24">(多选)</text>{{answerlist.title}}\r
  44849. </view>\r
  44850. <view v-for="(item,index) in answerlist.content" :key="index"\r
  44851. :class=" checkboxValue.includes(item.label)?'answeract itemanswer':'itemanswer' "\r
  44852. @click="handleCheckboxSelect(item.label)">{{item.label}}. {{item.content}}</view>\r
  44853. <view class=" submitbtn" @click="submitAnswers">确认</view>\r
  44854. </view>\r
  44855. <view class="fs24 mtb20 " style="color: #717171;">\r
  44856. {{answerfrist+1}}/{{Answerlistall}}\r
  44857. </view>\r
  44858. </view>\r
  44859. </view>\r
  44860. </u-popup> `),
  44861. vue.createCommentVNode(" 小黄车弹窗 "),
  44862. vue.createVNode(_component_u_popup, {
  44863. show: $data.shopping,
  44864. onClose: $options.closeshop,
  44865. onOpen: $options.open,
  44866. round: "20rpx",
  44867. bgColor: "#f3f5f9"
  44868. }, {
  44869. default: vue.withCtx(() => [
  44870. vue.createElementVNode("view", { class: "shoppop" }, [
  44871. vue.createElementVNode("view", { class: "shoppop-top" }, [
  44872. vue.createVNode(_component_u_avatar, {
  44873. src: $data.livedata.liveImgUrl,
  44874. size: "36",
  44875. class: "ml16"
  44876. }, null, 8, ["src"]),
  44877. vue.createElementVNode("view", { class: "search-input u-flex-y-center" }, [
  44878. vue.createElementVNode("image", {
  44879. style: { "width": "24rpx", "height": "24rpx", "margin-right": "16rpx" },
  44880. src: _imports_7
  44881. }),
  44882. vue.createElementVNode("input", { placeholder: "搜索商品或序号" })
  44883. ]),
  44884. vue.createElementVNode("view", {
  44885. class: "t-c search-top",
  44886. style: { "margin-right": "48rpx" },
  44887. onClick: _cache[9] || (_cache[9] = (...args) => $options.onCollect && $options.onCollect(...args))
  44888. }, [
  44889. vue.createElementVNode("image", {
  44890. style: { "width": "32rpx", "height": "32rpx" },
  44891. src: _imports_10
  44892. }),
  44893. vue.createElementVNode("view", null, "收藏")
  44894. ]),
  44895. vue.createElementVNode("view", {
  44896. class: "t-c search-top",
  44897. onClick: _cache[10] || (_cache[10] = (...args) => $options.goOrderList && $options.goOrderList(...args))
  44898. }, [
  44899. vue.createElementVNode("image", {
  44900. style: { "width": "32rpx", "height": "32rpx" },
  44901. src: _imports_9
  44902. }),
  44903. vue.createElementVNode("view", null, "订单")
  44904. ])
  44905. ]),
  44906. vue.createElementVNode(
  44907. "scroll-view",
  44908. {
  44909. "scroll-y": "",
  44910. class: "shop-list",
  44911. style: vue.normalizeStyle({ height: $data.boxHeight + "px" })
  44912. },
  44913. [
  44914. (vue.openBlock(true), vue.createElementBlock(
  44915. vue.Fragment,
  44916. null,
  44917. vue.renderList($data.products, (item, index2) => {
  44918. return vue.openBlock(), vue.createElementBlock("view", {
  44919. class: "list-item",
  44920. key: index2
  44921. }, [
  44922. vue.createElementVNode("view", { class: "goods-img" }, [
  44923. vue.createElementVNode("image", {
  44924. src: item.imgUrl,
  44925. mode: "widthFix"
  44926. }, null, 8, ["src"]),
  44927. vue.createElementVNode(
  44928. "view",
  44929. { class: "goods-label" },
  44930. vue.toDisplayString(index2 + 1),
  44931. 1
  44932. /* TEXT */
  44933. )
  44934. ]),
  44935. vue.createElementVNode("view", { class: "goods-right" }, [
  44936. vue.createElementVNode(
  44937. "view",
  44938. { class: "goods-title" },
  44939. vue.toDisplayString(item.productName),
  44940. 1
  44941. /* TEXT */
  44942. ),
  44943. vue.createElementVNode(
  44944. "view",
  44945. { class: "goods-details" },
  44946. vue.toDisplayString(item.productIntroduce),
  44947. 1
  44948. /* TEXT */
  44949. ),
  44950. vue.createElementVNode(
  44951. "view",
  44952. { class: "goods-people" },
  44953. vue.toDisplayString(item.sales) + " 人已购",
  44954. 1
  44955. /* TEXT */
  44956. ),
  44957. vue.createElementVNode("view", { class: "goods-shop" }, [
  44958. vue.createElementVNode("text", { class: "nummber" }, [
  44959. vue.createElementVNode("text", { style: { "font-size": "20rpx", "font-weight": "600" } }, "¥"),
  44960. vue.createElementVNode(
  44961. "text",
  44962. { style: { "font-size": "36rpx", "font-weight": "bold" } },
  44963. vue.toDisplayString(Math.trunc(item.price)),
  44964. 1
  44965. /* TEXT */
  44966. ),
  44967. vue.createTextVNode(
  44968. "." + vue.toDisplayString($options.getPureDecimal(item.price) ? $options.getPureDecimal(item.price) : "00") + "/日",
  44969. 1
  44970. /* TEXT */
  44971. )
  44972. ]),
  44973. vue.createElementVNode("view", { class: "btn-group u-flex-y-center" }, [
  44974. vue.createElementVNode("view", { class: "collect-btn" }, [
  44975. vue.createElementVNode("image", {
  44976. onClick: ($event) => $options.onCollect(item),
  44977. style: { "width": "32rpx", "height": "32rpx" },
  44978. src: _imports_10
  44979. }, null, 8, ["onClick"])
  44980. ]),
  44981. item.status == 1 ? (vue.openBlock(), vue.createElementBlock("view", {
  44982. key: 0,
  44983. class: "shop-btn",
  44984. onClick: ($event) => $options.goShop(item.productId)
  44985. }, "去购买 ", 8, ["onClick"])) : item.status == 0 ? (vue.openBlock(), vue.createElementBlock("view", {
  44986. key: 1,
  44987. onClick: ($event) => $options.goShop(item.productId),
  44988. class: "shop-btn"
  44989. }, " 已下架", 8, ["onClick"])) : vue.createCommentVNode("v-if", true)
  44990. ])
  44991. ])
  44992. ])
  44993. ]);
  44994. }),
  44995. 128
  44996. /* KEYED_FRAGMENT */
  44997. ))
  44998. ],
  44999. 4
  45000. /* STYLE */
  45001. )
  45002. ])
  45003. ]),
  45004. _: 1
  45005. /* STABLE */
  45006. }, 8, ["show", "onClose", "onOpen"])
  45007. ]);
  45008. }
  45009. const PagesHomeLiving = /* @__PURE__ */ _export_sfc(_sfc_main$p, [["render", _sfc_render$o], ["__scopeId", "data-v-471975a0"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages/home/living.vue"]]);
  45010. const _sfc_main$o = {};
  45011. function _sfc_render$n(_ctx, _cache) {
  45012. return vue.openBlock(), vue.createElementBlock("view", { class: "column" });
  45013. }
  45014. const PagesUserIndex = /* @__PURE__ */ _export_sfc(_sfc_main$o, [["render", _sfc_render$n], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages/user/index.vue"]]);
  45015. let request$3 = new Request$1().http;
  45016. function liveList(data) {
  45017. return request$3("/app/live/liveList", data, "GET", "application/json;charset=UTF-8");
  45018. }
  45019. const _sfc_main$n = {
  45020. data() {
  45021. return {
  45022. list: null,
  45023. liveId: null
  45024. };
  45025. },
  45026. onLoad(option) {
  45027. this.getList();
  45028. },
  45029. methods: {
  45030. goLive(item) {
  45031. this.liveId = item.liveId;
  45032. formatAppLog("log", "at pages/list/index.vue:36", "要传的liveId", this.liveId);
  45033. uni.navigateTo({
  45034. url: "/pages/home/living?liveId=" + this.liveId
  45035. // url: `/pages/home/living?liveId=${encodeURIComponent(JSON.stringify(liveId))}`
  45036. });
  45037. },
  45038. getList() {
  45039. const data = {
  45040. page: 1,
  45041. page_size: 10
  45042. };
  45043. uni.showLoading({
  45044. title: "处理中..."
  45045. });
  45046. liveList(data).then((res) => {
  45047. if (res.code == 200) {
  45048. this.list = res.rows;
  45049. formatAppLog("log", "at pages/list/index.vue:54", "list>>", this.list);
  45050. } else {
  45051. uni.showToast({
  45052. title: res.msg,
  45053. icon: "none"
  45054. });
  45055. }
  45056. }).catch((rej) => {
  45057. formatAppLog("log", "at pages/list/index.vue:63", "请求失败:", JSON.stringify(rej));
  45058. }).finally(() => {
  45059. uni.hideLoading();
  45060. });
  45061. }
  45062. }
  45063. };
  45064. function _sfc_render$m(_ctx, _cache, $props, $setup, $data, $options) {
  45065. return vue.openBlock(), vue.createElementBlock("view", { class: "content" }, [
  45066. vue.createElementVNode("view", { class: "list" }, [
  45067. (vue.openBlock(true), vue.createElementBlock(
  45068. vue.Fragment,
  45069. null,
  45070. vue.renderList($data.list, (item, index2) => {
  45071. return vue.openBlock(), vue.createElementBlock("view", {
  45072. class: "list-item",
  45073. onClick: ($event) => $options.goLive(item),
  45074. key: index2
  45075. }, [
  45076. vue.createElementVNode("image", {
  45077. src: item.liveImgUrl
  45078. }, null, 8, ["src"]),
  45079. vue.createElementVNode("view", { class: "info" }, [
  45080. vue.createElementVNode(
  45081. "text",
  45082. null,
  45083. vue.toDisplayString(item.liveName),
  45084. 1
  45085. /* TEXT */
  45086. )
  45087. ])
  45088. ], 8, ["onClick"]);
  45089. }),
  45090. 128
  45091. /* KEYED_FRAGMENT */
  45092. ))
  45093. ])
  45094. ]);
  45095. }
  45096. const PagesListIndex = /* @__PURE__ */ _export_sfc(_sfc_main$n, [["render", _sfc_render$m], ["__scopeId", "data-v-7bd28468"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages/list/index.vue"]]);
  45097. const props$4 = {
  45098. props: {
  45099. // 是否显示圆点
  45100. isDot: {
  45101. type: Boolean,
  45102. default: () => props$f.badge.isDot
  45103. },
  45104. // 显示的内容
  45105. value: {
  45106. type: [Number, String],
  45107. default: () => props$f.badge.value
  45108. },
  45109. // 显示的内容
  45110. modelValue: {
  45111. type: [Number, String],
  45112. default: () => props$f.badge.modelValue
  45113. },
  45114. // 是否显示
  45115. show: {
  45116. type: Boolean,
  45117. default: () => props$f.badge.show
  45118. },
  45119. // 最大值,超过最大值会显示 '{max}+'
  45120. max: {
  45121. type: [Number, String],
  45122. default: () => props$f.badge.max
  45123. },
  45124. // 主题类型,error|warning|success|primary
  45125. type: {
  45126. type: String,
  45127. default: () => props$f.badge.type
  45128. },
  45129. // 当数值为 0 时,是否展示 Badge
  45130. showZero: {
  45131. type: Boolean,
  45132. default: () => props$f.badge.showZero
  45133. },
  45134. // 背景颜色,优先级比type高,如设置,type参数会失效
  45135. bgColor: {
  45136. type: [String, null],
  45137. default: () => props$f.badge.bgColor
  45138. },
  45139. // 字体颜色
  45140. color: {
  45141. type: [String, null],
  45142. default: () => props$f.badge.color
  45143. },
  45144. // 徽标形状,circle-四角均为圆角,horn-左下角为直角
  45145. shape: {
  45146. type: String,
  45147. default: () => props$f.badge.shape
  45148. },
  45149. // 设置数字的显示方式,overflow|ellipsis|limit
  45150. // overflow会根据max字段判断,超出显示`${max}+`
  45151. // ellipsis会根据max判断,超出显示`${max}...`
  45152. // limit会依据1000作为判断条件,超出1000,显示`${value/1000}K`,比如2.2k、3.34w,最多保留2位小数
  45153. numberType: {
  45154. type: String,
  45155. default: () => props$f.badge.numberType
  45156. },
  45157. // 设置badge的位置偏移,格式为 [x, y],也即设置的为top和right的值,absolute为true时有效
  45158. offset: {
  45159. type: Array,
  45160. default: () => props$f.badge.offset
  45161. },
  45162. // 是否反转背景和字体颜色
  45163. inverted: {
  45164. type: Boolean,
  45165. default: () => props$f.badge.inverted
  45166. },
  45167. // 是否绝对定位
  45168. absolute: {
  45169. type: Boolean,
  45170. default: () => props$f.badge.absolute
  45171. }
  45172. }
  45173. };
  45174. const _sfc_main$m = {
  45175. name: "u-badge",
  45176. mixins: [mpMixin, props$4, mixin$1],
  45177. computed: {
  45178. // 是否将badge中心与父组件右上角重合
  45179. boxStyle() {
  45180. let style = {};
  45181. return style;
  45182. },
  45183. // 整个组件的样式
  45184. badgeStyle() {
  45185. const style = {};
  45186. if (this.color) {
  45187. style.color = this.color;
  45188. }
  45189. if (this.bgColor && !this.inverted) {
  45190. style.backgroundColor = this.bgColor;
  45191. }
  45192. if (this.absolute) {
  45193. style.position = "absolute";
  45194. if (this.offset.length) {
  45195. const top = this.offset[0];
  45196. const right = this.offset[1] || top;
  45197. style.top = addUnit(top);
  45198. style.right = addUnit(right);
  45199. }
  45200. }
  45201. return style;
  45202. },
  45203. showValue() {
  45204. switch (this.numberType) {
  45205. case "overflow":
  45206. return Number(this.value) > Number(this.max) ? this.max + "+" : this.value;
  45207. case "ellipsis":
  45208. return Number(this.value) > Number(this.max) ? "..." : this.value;
  45209. case "limit":
  45210. return Number(this.value) > 999 ? Number(this.value) >= 9999 ? Math.floor(this.value / 1e4 * 100) / 100 + "w" : Math.floor(this.value / 1e3 * 100) / 100 + "k" : this.value;
  45211. default:
  45212. return Number(this.value);
  45213. }
  45214. }
  45215. },
  45216. methods: {
  45217. addStyle
  45218. }
  45219. };
  45220. function _sfc_render$l(_ctx, _cache, $props, $setup, $data, $options) {
  45221. return _ctx.show && ((Number(_ctx.value) === 0 ? _ctx.showZero : true) || _ctx.isDot) ? (vue.openBlock(), vue.createElementBlock(
  45222. "text",
  45223. {
  45224. key: 0,
  45225. class: vue.normalizeClass([[_ctx.isDot ? "u-badge--dot" : "u-badge--not-dot", _ctx.inverted && "u-badge--inverted", _ctx.shape === "horn" && "u-badge--horn", `u-badge--${_ctx.type}${_ctx.inverted ? "--inverted" : ""}`], "u-badge"]),
  45226. style: vue.normalizeStyle([$options.addStyle(_ctx.customStyle), $options.badgeStyle])
  45227. },
  45228. vue.toDisplayString(_ctx.isDot ? "" : $options.showValue),
  45229. 7
  45230. /* TEXT, CLASS, STYLE */
  45231. )) : vue.createCommentVNode("v-if", true);
  45232. }
  45233. const __easycom_0$2 = /* @__PURE__ */ _export_sfc(_sfc_main$m, [["render", _sfc_render$l], ["__scopeId", "data-v-06cca9b7"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-badge/u-badge.vue"]]);
  45234. const props$3 = {
  45235. props: {
  45236. // 滑块的移动过渡时间,单位ms
  45237. duration: {
  45238. type: Number,
  45239. default: () => props$f.tabs.duration
  45240. },
  45241. // tabs标签数组
  45242. list: {
  45243. type: Array,
  45244. default: () => props$f.tabs.list
  45245. },
  45246. // 滑块颜色
  45247. lineColor: {
  45248. type: String,
  45249. default: () => props$f.tabs.lineColor
  45250. },
  45251. // 菜单选择中时的样式
  45252. activeStyle: {
  45253. type: [String, Object],
  45254. default: () => props$f.tabs.activeStyle
  45255. },
  45256. // 菜单非选中时的样式
  45257. inactiveStyle: {
  45258. type: [String, Object],
  45259. default: () => props$f.tabs.inactiveStyle
  45260. },
  45261. // 滑块长度
  45262. lineWidth: {
  45263. type: [String, Number],
  45264. default: () => props$f.tabs.lineWidth
  45265. },
  45266. // 滑块高度
  45267. lineHeight: {
  45268. type: [String, Number],
  45269. default: () => props$f.tabs.lineHeight
  45270. },
  45271. // 滑块背景显示大小,当滑块背景设置为图片时使用
  45272. lineBgSize: {
  45273. type: String,
  45274. default: () => props$f.tabs.lineBgSize
  45275. },
  45276. // 菜单item的样式
  45277. itemStyle: {
  45278. type: [String, Object],
  45279. default: () => props$f.tabs.itemStyle
  45280. },
  45281. // 菜单是否可滚动
  45282. scrollable: {
  45283. type: Boolean,
  45284. default: () => props$f.tabs.scrollable
  45285. },
  45286. // 当前选中标签的索引
  45287. current: {
  45288. type: [Number, String],
  45289. default: () => props$f.tabs.current
  45290. },
  45291. // 默认读取的键名
  45292. keyName: {
  45293. type: String,
  45294. default: () => props$f.tabs.keyName
  45295. }
  45296. }
  45297. };
  45298. const _sfc_main$l = {
  45299. name: "u-tabs",
  45300. mixins: [mpMixin, mixin$1, props$3],
  45301. data() {
  45302. return {
  45303. firstTime: true,
  45304. scrollLeft: 0,
  45305. scrollViewWidth: 0,
  45306. lineOffsetLeft: 0,
  45307. tabsRect: {
  45308. left: 0
  45309. },
  45310. innerCurrent: 0,
  45311. moving: false
  45312. };
  45313. },
  45314. watch: {
  45315. current: {
  45316. immediate: true,
  45317. handler(newValue, oldValue) {
  45318. if (newValue !== this.innerCurrent) {
  45319. this.innerCurrent = newValue;
  45320. this.$nextTick(() => {
  45321. this.resize();
  45322. });
  45323. }
  45324. }
  45325. },
  45326. // list变化时,重新渲染list各项信息
  45327. list() {
  45328. this.$nextTick(() => {
  45329. this.resize();
  45330. });
  45331. }
  45332. },
  45333. computed: {
  45334. textStyle() {
  45335. return (index2) => {
  45336. const style = {};
  45337. const customeStyle = index2 === this.innerCurrent ? addStyle(this.activeStyle) : uni.$u.addStyle(
  45338. this.inactiveStyle
  45339. );
  45340. if (this.list[index2].disabled) {
  45341. style.color = "#c8c9cc";
  45342. }
  45343. return deepMerge$1(customeStyle, style);
  45344. };
  45345. },
  45346. propsBadge() {
  45347. return props$f.badge;
  45348. }
  45349. },
  45350. async mounted() {
  45351. this.init();
  45352. },
  45353. emits: ["click", "change"],
  45354. methods: {
  45355. addStyle,
  45356. addUnit,
  45357. setLineLeft() {
  45358. const tabItem = this.list[this.innerCurrent];
  45359. if (!tabItem) {
  45360. return;
  45361. }
  45362. let lineOffsetLeft = this.list.slice(0, this.innerCurrent).reduce((total, curr) => total + curr.rect.width, 0);
  45363. const lineWidth = getPx(this.lineWidth);
  45364. this.lineOffsetLeft = lineOffsetLeft + (tabItem.rect.width - lineWidth) / 2;
  45365. if (this.firstTime) {
  45366. setTimeout(() => {
  45367. this.firstTime = false;
  45368. }, 10);
  45369. }
  45370. },
  45371. // nvue下设置滑块的位置
  45372. animation(x, duration = 0) {
  45373. },
  45374. // 点击某一个标签
  45375. clickHandler(item, index2) {
  45376. this.$emit("click", {
  45377. ...item,
  45378. index: index2
  45379. });
  45380. if (item.disabled)
  45381. return;
  45382. this.innerCurrent = index2;
  45383. this.resize();
  45384. this.$emit("change", {
  45385. ...item,
  45386. index: index2
  45387. });
  45388. },
  45389. init() {
  45390. sleep().then(() => {
  45391. this.resize();
  45392. });
  45393. },
  45394. setScrollLeft() {
  45395. const tabRect = this.list[this.innerCurrent];
  45396. const offsetLeft = this.list.slice(0, this.innerCurrent).reduce((total, curr) => {
  45397. return total + curr.rect.width;
  45398. }, 0);
  45399. const windowWidth = sys().windowWidth;
  45400. let scrollLeft = offsetLeft - (this.tabsRect.width - tabRect.rect.width) / 2 - (windowWidth - this.tabsRect.right) / 2 + this.tabsRect.left / 2;
  45401. scrollLeft = Math.min(scrollLeft, this.scrollViewWidth - this.tabsRect.width);
  45402. this.scrollLeft = Math.max(0, scrollLeft);
  45403. },
  45404. // 获取所有标签的尺寸
  45405. resize() {
  45406. if (this.list.length === 0) {
  45407. return;
  45408. }
  45409. Promise.all([this.getTabsRect(), this.getAllItemRect()]).then(([tabsRect, itemRect = []]) => {
  45410. this.tabsRect = tabsRect;
  45411. this.scrollViewWidth = 0;
  45412. itemRect.map((item, index2) => {
  45413. this.scrollViewWidth += item.width;
  45414. this.list[index2].rect = item;
  45415. });
  45416. this.setLineLeft();
  45417. this.setScrollLeft();
  45418. });
  45419. },
  45420. // 获取导航菜单的尺寸
  45421. getTabsRect() {
  45422. return new Promise((resolve) => {
  45423. this.queryRect("u-tabs__wrapper__scroll-view").then((size) => resolve(size));
  45424. });
  45425. },
  45426. // 获取所有标签的尺寸
  45427. getAllItemRect() {
  45428. return new Promise((resolve) => {
  45429. const promiseAllArr = this.list.map((item, index2) => this.queryRect(
  45430. `u-tabs__wrapper__nav__item-${index2}`,
  45431. true
  45432. ));
  45433. Promise.all(promiseAllArr).then((sizes) => resolve(sizes));
  45434. });
  45435. },
  45436. // 获取各个标签的尺寸
  45437. queryRect(el, item) {
  45438. return new Promise((resolve) => {
  45439. this.$uGetRect(`.${el}`).then((size) => {
  45440. resolve(size);
  45441. });
  45442. });
  45443. }
  45444. }
  45445. };
  45446. function _sfc_render$k(_ctx, _cache, $props, $setup, $data, $options) {
  45447. const _component_u_badge = resolveEasycom(vue.resolveDynamicComponent("u-badge"), __easycom_0$2);
  45448. return vue.openBlock(), vue.createElementBlock("view", { class: "u-tabs" }, [
  45449. vue.createElementVNode("view", { class: "u-tabs__wrapper" }, [
  45450. vue.renderSlot(_ctx.$slots, "left", {}, void 0, true),
  45451. vue.createElementVNode("view", { class: "u-tabs__wrapper__scroll-view-wrapper" }, [
  45452. vue.createElementVNode("scroll-view", {
  45453. "scroll-x": _ctx.scrollable,
  45454. "scroll-left": $data.scrollLeft,
  45455. "scroll-with-animation": "",
  45456. class: "u-tabs__wrapper__scroll-view",
  45457. "show-scrollbar": false,
  45458. ref: "u-tabs__wrapper__scroll-view"
  45459. }, [
  45460. vue.createElementVNode(
  45461. "view",
  45462. {
  45463. class: "u-tabs__wrapper__nav",
  45464. ref: "u-tabs__wrapper__nav"
  45465. },
  45466. [
  45467. (vue.openBlock(true), vue.createElementBlock(
  45468. vue.Fragment,
  45469. null,
  45470. vue.renderList(_ctx.list, (item, index2) => {
  45471. return vue.openBlock(), vue.createElementBlock("view", {
  45472. class: vue.normalizeClass(["u-tabs__wrapper__nav__item", [`u-tabs__wrapper__nav__item-${index2}`, item.disabled && "u-tabs__wrapper__nav__item--disabled"]]),
  45473. key: index2,
  45474. onClick: ($event) => $options.clickHandler(item, index2),
  45475. ref_for: true,
  45476. ref: `u-tabs__wrapper__nav__item-${index2}`,
  45477. style: vue.normalizeStyle([$options.addStyle(_ctx.itemStyle), { flex: _ctx.scrollable ? "" : 1 }])
  45478. }, [
  45479. vue.createElementVNode(
  45480. "text",
  45481. {
  45482. class: vue.normalizeClass([[item.disabled && "u-tabs__wrapper__nav__item__text--disabled"], "u-tabs__wrapper__nav__item__text"]),
  45483. style: vue.normalizeStyle([$options.textStyle(index2)])
  45484. },
  45485. vue.toDisplayString(item[_ctx.keyName]),
  45486. 7
  45487. /* TEXT, CLASS, STYLE */
  45488. ),
  45489. vue.createVNode(_component_u_badge, {
  45490. show: !!(item.badge && (item.badge.show || item.badge.isDot || item.badge.value)),
  45491. isDot: item.badge && item.badge.isDot || $options.propsBadge.isDot,
  45492. value: item.badge && item.badge.value || $options.propsBadge.value,
  45493. max: item.badge && item.badge.max || $options.propsBadge.max,
  45494. type: item.badge && item.badge.type || $options.propsBadge.type,
  45495. showZero: item.badge && item.badge.showZero || $options.propsBadge.showZero,
  45496. bgColor: item.badge && item.badge.bgColor || $options.propsBadge.bgColor,
  45497. color: item.badge && item.badge.color || $options.propsBadge.color,
  45498. shape: item.badge && item.badge.shape || $options.propsBadge.shape,
  45499. numberType: item.badge && item.badge.numberType || $options.propsBadge.numberType,
  45500. inverted: item.badge && item.badge.inverted || $options.propsBadge.inverted,
  45501. customStyle: "margin-left: 4px;"
  45502. }, null, 8, ["show", "isDot", "value", "max", "type", "showZero", "bgColor", "color", "shape", "numberType", "inverted"])
  45503. ], 14, ["onClick"]);
  45504. }),
  45505. 128
  45506. /* KEYED_FRAGMENT */
  45507. )),
  45508. vue.createElementVNode(
  45509. "view",
  45510. {
  45511. class: "u-tabs__wrapper__nav__line",
  45512. ref: "u-tabs__wrapper__nav__line",
  45513. style: vue.normalizeStyle([{
  45514. width: $options.addUnit(_ctx.lineWidth),
  45515. transform: `translate(${$data.lineOffsetLeft}px)`,
  45516. transitionDuration: `${$data.firstTime ? 0 : _ctx.duration}ms`,
  45517. height: $options.addUnit(_ctx.lineHeight),
  45518. background: _ctx.lineColor,
  45519. backgroundSize: _ctx.lineBgSize
  45520. }])
  45521. },
  45522. null,
  45523. 4
  45524. /* STYLE */
  45525. )
  45526. ],
  45527. 512
  45528. /* NEED_PATCH */
  45529. )
  45530. ], 8, ["scroll-x", "scroll-left"])
  45531. ]),
  45532. vue.renderSlot(_ctx.$slots, "right", {}, void 0, true)
  45533. ])
  45534. ]);
  45535. }
  45536. const __easycom_0$1 = /* @__PURE__ */ _export_sfc(_sfc_main$l, [["render", _sfc_render$k], ["__scopeId", "data-v-02b0c54f"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-tabs/u-tabs.vue"]]);
  45537. const _imports_0$9 = "/static/images/top.png";
  45538. const _imports_1$5 = "/static/images/up-down.png";
  45539. const _imports_2$4 = "/static/images/wechat.png";
  45540. var wsUrl = "ws://192.168.10.170:7114/app/webSocket";
  45541. var pingpangTimes = null;
  45542. var isSocketOpen = false;
  45543. var socket = null;
  45544. const _sfc_main$k = {
  45545. data() {
  45546. return {
  45547. icon: "公告:",
  45548. icon2: "广播:",
  45549. text1: "组件功能丰富多端兼容让您快速集成开箱即用",
  45550. text2: "丰富多端兼容让您快速集成开箱即用",
  45551. srcAvatar: "",
  45552. acttab: 0,
  45553. value: "",
  45554. talkdisabled: false,
  45555. //是否禁用
  45556. placeholderText: "请输入内容",
  45557. showadd: false,
  45558. autoplay: true,
  45559. //自动播放
  45560. userinfo: "",
  45561. //用户信息
  45562. path: "http://192.168.10.170/dev-api",
  45563. livedata: {},
  45564. bufferRate: 0,
  45565. // 缓冲时间
  45566. playDuration: 0,
  45567. //视频播放时间
  45568. videoContext: "",
  45569. thistime: uni.$u.timeFormat(/* @__PURE__ */ new Date(), "yyyy-mm-dd hh:MM:ss"),
  45570. codeimg: "",
  45571. userid: "4",
  45572. liveId: "5",
  45573. upDown: true,
  45574. //是否视频显示隐藏
  45575. isLongPress: false,
  45576. // 是否长按
  45577. timeout: null,
  45578. // 计时器
  45579. list1: [
  45580. {
  45581. name: "讨论"
  45582. },
  45583. // {
  45584. // name: '问答'
  45585. // },
  45586. {
  45587. name: "资料"
  45588. }
  45589. ],
  45590. talklist: [],
  45591. scrollIntoView: "",
  45592. showWelcomeMessage: false,
  45593. messageContent: ""
  45594. };
  45595. },
  45596. mounted() {
  45597. this.initSocket();
  45598. var that = this;
  45599. uni.$on("initSocket", () => {
  45600. that.initSocket();
  45601. });
  45602. uni.$on("sendMsg", (item) => {
  45603. that.sendMsg(item);
  45604. });
  45605. uni.$on("closeWebSocket", () => {
  45606. that.closeWebSocket();
  45607. });
  45608. this.getEWechatSdk();
  45609. this.userinfo = JSON.parse(uni.getStorageSync("userInfo"));
  45610. this.getliving();
  45611. this.gettalklist();
  45612. },
  45613. onReady: function(res) {
  45614. this.videoContext = uni.createVideoContext("myVideo");
  45615. },
  45616. onLoad() {
  45617. },
  45618. methods: {
  45619. gettalklist() {
  45620. const param = {
  45621. id: this.liveId
  45622. };
  45623. gettextlist(param).then((res) => {
  45624. if (res.code == 200) {
  45625. this.talklist = res.data;
  45626. this.$nextTick(() => {
  45627. this.scrollIntoView = `list_${this.talklist.length - 1}`;
  45628. });
  45629. }
  45630. });
  45631. },
  45632. longPress() {
  45633. this.timeout = setTimeout(() => {
  45634. this.isLongPress = true;
  45635. uni.saveImageToPhotosAlbum({
  45636. filePath: this.livedata.qwQrCode,
  45637. // 图片的本地路径或网络路径
  45638. success: () => {
  45639. uni.showToast({
  45640. title: "保存成功"
  45641. });
  45642. },
  45643. fail: () => {
  45644. uni.showToast({
  45645. title: "保存失败",
  45646. icon: "none"
  45647. });
  45648. }
  45649. });
  45650. }, 500);
  45651. },
  45652. cancelLongPress() {
  45653. clearTimeout(this.timeout);
  45654. this.isLongPress = false;
  45655. },
  45656. getliving() {
  45657. this.gettalklist();
  45658. const param = {
  45659. id: this.liveId
  45660. };
  45661. getlive(param).then((res) => {
  45662. if (res.code == 200) {
  45663. this.livedata = res.data;
  45664. this.codeimg = res.data.qwQrCode;
  45665. if (this.livedata.status == 2) {
  45666. this.autoplay = true;
  45667. this.videoContext.seek(this.livedata.nowDuration);
  45668. } else {
  45669. this.autoplay = false;
  45670. this.placeholderText = "直播开始才能发言讨论";
  45671. this.talkdisabled = true;
  45672. }
  45673. } else {
  45674. uni.showToast({
  45675. title: res.msg,
  45676. icon: "none",
  45677. duration: 2e3
  45678. });
  45679. }
  45680. });
  45681. },
  45682. addwechat() {
  45683. this.showadd = !this.showadd;
  45684. },
  45685. open() {
  45686. },
  45687. close() {
  45688. this.showadd = !this.showadd;
  45689. },
  45690. tabClick(e2) {
  45691. this.acttab = e2.index;
  45692. if (e2.index == 0) {
  45693. this.$nextTick(() => {
  45694. this.gettalklist();
  45695. });
  45696. }
  45697. },
  45698. getEWechatSdk() {
  45699. let eWechatSdk = "";
  45700. if (/(Android)/i.test(navigator.userAgent)) {
  45701. eWechatSdk = "jWeixin";
  45702. } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
  45703. eWechatSdk = "wx";
  45704. } else {
  45705. eWechatSdk = "jWeixin";
  45706. }
  45707. uni.setStorageSync("wxSdk", eWechatSdk);
  45708. },
  45709. closeWebSocket() {
  45710. if (socket != null) {
  45711. uni.closeSocket();
  45712. }
  45713. clearInterval(pingpangTimes);
  45714. },
  45715. reConnect() {
  45716. var that = this;
  45717. try {
  45718. uni.closeSocket();
  45719. } catch (e2) {
  45720. }
  45721. setTimeout(function() {
  45722. that.initSocket();
  45723. }, 1e4);
  45724. },
  45725. initSocket() {
  45726. var that = this;
  45727. socket = uni.connectSocket({
  45728. // url: wsUrl+"?userId=40486&liveId=2",
  45729. // url: wsUrl + "?userId=" + this.userid + "&liveId=" +
  45730. // this.liveId+"&AppToken="+'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI0IiwiaWF0IjoxNzQwNzIxMDQ1LCJleHAiOjE3NDEzMjU4NDV9.PgS83JTMSJgVFD6vGAhUsEPbS6Az4yMyX8wVug61TZNTB3092CtvANo-AB9ZG4NdSBLgLrf4litM3vvTk-FK0g',
  45731. url: wsUrl + "?userId=666&liveId=777&AppToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI2NjYiLCJpYXQiOjE3NTE4NzQ0NzEsImV4cCI6MTc4MzQxMDQ3MX0.3uxTTb0qXygmaY9ItovMclxJCNhNEi6kFEqmfLGg4lP2PYzCPODsVjW4PjXNu6EYsl5eYyESltHWcwBnaNkilQ&signature=ff21bfb41ddd5f2e31d6f5bf32ec565aab9c518614d139fa26727468ce701237&userType=0&timestamp=666",
  45732. multiple: true,
  45733. success: (res) => {
  45734. clearInterval(pingpangTimes);
  45735. uni.onSocketMessage((res2) => {
  45736. const redata = JSON.parse(res2.data);
  45737. this.talklist.push(redata.data);
  45738. this.$nextTick(() => {
  45739. this.scrollIntoView = `list_${this.talklist.length - 1}`;
  45740. });
  45741. if (redata.cmd == "deleteId") {
  45742. uni.$emit("deleteId");
  45743. } else if (redata.cmd == "init") {
  45744. uni.$emit("init", redata.data);
  45745. } else if (redata.cmd == "reload") {
  45746. uni.$emit("reload");
  45747. } else if (redata.cmd == "sendStatus") {
  45748. uni.$emit("sendStatus", redata.data);
  45749. } else if (redata.data.cmd == "entry") {
  45750. this.showWelcomeMessage = true;
  45751. uni.$emit("entry", redata.data);
  45752. formatAppLog("log", "at pages/home/live.vue:341", redata.data);
  45753. }
  45754. });
  45755. },
  45756. error: (res) => {
  45757. uni.$emit("websocket", 0);
  45758. }
  45759. });
  45760. uni.onSocketOpen(() => {
  45761. isSocketOpen = true;
  45762. formatAppLog("log", "at pages/home/live.vue:354", "WebSocket连接已打开!!");
  45763. uni.showToast({
  45764. title: "插件已打开",
  45765. icon: "none"
  45766. });
  45767. });
  45768. uni.onSocketClose(() => {
  45769. isSocketOpen = false;
  45770. clearInterval(pingpangTimes);
  45771. formatAppLog("log", "at pages/home/live.vue:365", "WebSocket连接已关闭!");
  45772. uni.showToast({
  45773. title: "插件离线",
  45774. icon: "none"
  45775. });
  45776. that.reConnect();
  45777. });
  45778. uni.onSocketError(() => {
  45779. isSocketOpen = false;
  45780. clearInterval(pingpangTimes);
  45781. formatAppLog("log", "at pages/home/live.vue:378", "WebSocket连接打开失败");
  45782. uni.showToast({
  45783. title: "插件离线",
  45784. icon: "none"
  45785. });
  45786. uni.showModal({
  45787. content: "聊天连接失败是否重新尝试连接",
  45788. success() {
  45789. that.reConnect();
  45790. }
  45791. });
  45792. });
  45793. },
  45794. sendMsg() {
  45795. if (isSocketOpen) {
  45796. const data = {
  45797. liveId: this.livedata.liveId,
  45798. userId: this.userinfo.userId,
  45799. userType: 0,
  45800. cmd: "sendMsg",
  45801. msg: this.value,
  45802. nickName: this.userinfo.nickName,
  45803. avatar: this.userinfo.avatar
  45804. };
  45805. if (this.value == "") {
  45806. uni.showToast({
  45807. title: "不能发送空消息",
  45808. icon: "none"
  45809. });
  45810. } else {
  45811. socket.send({
  45812. data: JSON.stringify(data),
  45813. success: () => {
  45814. formatAppLog("log", "at pages/home/live.vue:414", "发送成功");
  45815. this.value = "";
  45816. },
  45817. fail: () => {
  45818. formatAppLog("log", "at pages/home/live.vue:418", "发送失败");
  45819. }
  45820. });
  45821. }
  45822. }
  45823. }
  45824. }
  45825. };
  45826. function _sfc_render$j(_ctx, _cache, $props, $setup, $data, $options) {
  45827. const _component_u_tabs = resolveEasycom(vue.resolveDynamicComponent("u-tabs"), __easycom_0$1);
  45828. const _component_u_avatar = resolveEasycom(vue.resolveDynamicComponent("u-avatar"), __easycom_1$1);
  45829. const _component_u_input = resolveEasycom(vue.resolveDynamicComponent("u-input"), __easycom_2$1);
  45830. const _component_u_icon = resolveEasycom(vue.resolveDynamicComponent("u-icon"), __easycom_0$4);
  45831. const _component_u_popup = resolveEasycom(vue.resolveDynamicComponent("u-popup"), __easycom_1$4);
  45832. return vue.openBlock(), vue.createElementBlock("view", { class: "live column flex-1" }, [
  45833. $data.upDown ? (vue.openBlock(), vue.createElementBlock("view", {
  45834. key: 0,
  45835. class: "videolist"
  45836. }, [
  45837. vue.createElementVNode("view", { class: "vedio" }, [
  45838. vue.createCommentVNode(` <view class="p20 textscll">\r
  45839. <u-notice-bar :icon="icon" :text="text1" mode="closable" bgColor='rgba(0,0,0,0.7)' color='#fff'\r
  45840. style="border-radius: 10rpx;"></u-notice-bar>\r
  45841. </view> `),
  45842. vue.createElementVNode("video", {
  45843. id: "myVideo",
  45844. class: "videotop",
  45845. src: $data.path + $data.livedata.videoUrl,
  45846. autoplay: $data.autoplay,
  45847. controls: false,
  45848. poster: $data.livedata.liveImgUrl,
  45849. "vslide-gesture-in-fullscreen": "true",
  45850. "show-center-play-btn": false
  45851. }, null, 8, ["src", "autoplay", "poster"])
  45852. ]),
  45853. !$data.autoplay ? (vue.openBlock(), vue.createElementBlock("view", {
  45854. key: 0,
  45855. class: "popup-video"
  45856. }, [
  45857. $data.livedata.status == 1 ? (vue.openBlock(), vue.createElementBlock("view", {
  45858. key: 0,
  45859. class: "fs36 bold"
  45860. }, "——直播还未开始——")) : vue.createCommentVNode("v-if", true),
  45861. $data.livedata.status == 3 ? (vue.openBlock(), vue.createElementBlock("view", {
  45862. key: 1,
  45863. class: "fs36 bold"
  45864. }, "——直播已经结束——")) : vue.createCommentVNode("v-if", true),
  45865. vue.createElementVNode("view", { class: "fs28 mtb20" }, "了解更多,点击下方联系老师"),
  45866. vue.createElementVNode("view", {
  45867. class: "more",
  45868. onClick: _cache[0] || (_cache[0] = ($event) => $data.showadd = !$data.showadd)
  45869. }, "联系老师")
  45870. ])) : vue.createCommentVNode("v-if", true)
  45871. ])) : vue.createCommentVNode("v-if", true),
  45872. vue.createElementVNode("view", {
  45873. class: "justify-between align-center bgf",
  45874. style: { "border-bottom": "#dedede solid 2rpx" }
  45875. }, [
  45876. vue.createVNode(_component_u_tabs, {
  45877. list: $data.list1,
  45878. onClick: $options.tabClick,
  45879. inactiveStyle: "color:#888",
  45880. itemStyle: "width:120rpx;height: 80rpx;"
  45881. }, null, 8, ["list", "onClick"]),
  45882. vue.createElementVNode("view", { class: "justify-around flex-1 align-center" }, [
  45883. vue.createElementVNode("view", {
  45884. class: "reflash",
  45885. onClick: _cache[1] || (_cache[1] = ($event) => $options.getliving())
  45886. }, "刷新"),
  45887. vue.withDirectives(vue.createElementVNode(
  45888. "image",
  45889. {
  45890. src: _imports_0$9,
  45891. class: "wh48",
  45892. onClick: _cache[2] || (_cache[2] = ($event) => $data.upDown = !$data.upDown)
  45893. },
  45894. null,
  45895. 512
  45896. /* NEED_PATCH */
  45897. ), [
  45898. [vue.vShow, $data.upDown]
  45899. ]),
  45900. vue.withDirectives(vue.createElementVNode(
  45901. "image",
  45902. {
  45903. src: _imports_1$5,
  45904. class: "wh48",
  45905. onClick: _cache[3] || (_cache[3] = ($event) => $data.upDown = !$data.upDown)
  45906. },
  45907. null,
  45908. 512
  45909. /* NEED_PATCH */
  45910. ), [
  45911. [vue.vShow, !$data.upDown]
  45912. ])
  45913. ])
  45914. ]),
  45915. $data.acttab == 0 ? (vue.openBlock(), vue.createElementBlock("view", {
  45916. key: 1,
  45917. class: "talkbox column flex-1 hidden",
  45918. style: { "height": "100%" }
  45919. }, [
  45920. vue.createCommentVNode(` <u-notice-bar :icon="icon2" :text="text2" mode="closable" bgColor='rgba(254,253,235)' color='#FF5C03'\r
  45921. style=" height: 30rpx;line-height: 40rpx;"></u-notice-bar> `),
  45922. vue.createElementVNode("scroll-view", {
  45923. "scroll-y": "true",
  45924. class: "talk p20 scrolly flex-1 column",
  45925. style: { "width": "calc(100% - 40rpx)", "height": "calc(100% - 40rpx)" },
  45926. "scroll-into-view": $data.scrollIntoView
  45927. }, [
  45928. (vue.openBlock(true), vue.createElementBlock(
  45929. vue.Fragment,
  45930. null,
  45931. vue.renderList($data.talklist, (item, index2) => {
  45932. return vue.withDirectives((vue.openBlock(), vue.createElementBlock("view", {
  45933. class: "list justify-start",
  45934. key: item.index,
  45935. id: `list_${index2}`
  45936. }, [
  45937. vue.createVNode(_component_u_avatar, {
  45938. src: item.avatar,
  45939. size: "30"
  45940. }, null, 8, ["src"]),
  45941. vue.createElementVNode("view", { class: "ml16" }, [
  45942. vue.createElementVNode("view", { class: "fs24" }, [
  45943. item.userId == $data.userinfo.userId && item.cmd == "sendMsg" ? (vue.openBlock(), vue.createElementBlock("text", {
  45944. key: 0,
  45945. style: { "color": "#3fc69b", "transform": "scale(0.8)", "display": "inline-block" }
  45946. }, "[ 我 ]")) : vue.createCommentVNode("v-if", true),
  45947. item.userType == 1 ? (vue.openBlock(), vue.createElementBlock("text", {
  45948. key: 1,
  45949. style: { "color": "#c84e1e", "transform": "scale(0.8)", "display": "inline-block" }
  45950. }, " [ 管理员 ]")) : vue.createCommentVNode("v-if", true),
  45951. vue.createElementVNode(
  45952. "text",
  45953. null,
  45954. vue.toDisplayString(item.nickName),
  45955. 1
  45956. /* TEXT */
  45957. )
  45958. ]),
  45959. vue.createElementVNode("view", { class: "talktext bgf p20 mt12" }, [
  45960. vue.createElementVNode(
  45961. "view",
  45962. { class: "fs24" },
  45963. vue.toDisplayString(item.msg),
  45964. 1
  45965. /* TEXT */
  45966. )
  45967. ])
  45968. ])
  45969. ], 8, ["id"])), [
  45970. [vue.vShow, item.cmd == "sendMsg"]
  45971. ]);
  45972. }),
  45973. 128
  45974. /* KEYED_FRAGMENT */
  45975. )),
  45976. $data.showWelcomeMessage ? (vue.openBlock(), vue.createElementBlock("view", {
  45977. key: 0,
  45978. class: "welcome-message"
  45979. }, [
  45980. (vue.openBlock(true), vue.createElementBlock(
  45981. vue.Fragment,
  45982. null,
  45983. vue.renderList($data.talklist, (item, index2) => {
  45984. return vue.withDirectives((vue.openBlock(), vue.createElementBlock("view", {
  45985. class: "list justify-start",
  45986. key: item.index,
  45987. id: `list_${index2}`
  45988. }, [
  45989. vue.createElementVNode("view", { class: "ml16" }, [
  45990. vue.createElementVNode("view", { class: "fs24" }, [
  45991. item.userType == 1 ? (vue.openBlock(), vue.createElementBlock("text", {
  45992. key: 0,
  45993. style: { "color": "#c84e1e", "transform": "scale(0.8)", "display": "inline-block" }
  45994. }, " [ 管理员 ]")) : vue.createCommentVNode("v-if", true)
  45995. ]),
  45996. vue.createElementVNode("view", { class: "talktext bgf p20 mt12 justify-start" }, [
  45997. vue.createElementVNode(
  45998. "text",
  45999. {
  46000. style: { "color": "#9e5584" },
  46001. class: "fs24"
  46002. },
  46003. vue.toDisplayString(item.nickName),
  46004. 1
  46005. /* TEXT */
  46006. ),
  46007. vue.createElementVNode(
  46008. "view",
  46009. { class: "fs24 flex-1" },
  46010. vue.toDisplayString(item.msg) + "直播间",
  46011. 1
  46012. /* TEXT */
  46013. )
  46014. ])
  46015. ])
  46016. ], 8, ["id"])), [
  46017. [vue.vShow, item.cmd == "entry" || item.cmd == "out"]
  46018. ]);
  46019. }),
  46020. 128
  46021. /* KEYED_FRAGMENT */
  46022. ))
  46023. ])) : vue.createCommentVNode("v-if", true)
  46024. ], 8, ["scroll-into-view"]),
  46025. vue.createElementVNode("view", { class: "pb90 mb20" }),
  46026. vue.createElementVNode("view", { class: "bot_talk bgf" }, [
  46027. vue.createVNode(_component_u_input, {
  46028. placeholder: $data.placeholderText,
  46029. border: "none",
  46030. customStyle: "background:#f1f7f7;padding:12rpx;padding-left:40rpx",
  46031. modelValue: $data.value,
  46032. "onUpdate:modelValue": _cache[4] || (_cache[4] = ($event) => $data.value = $event),
  46033. shape: "circle"
  46034. }, null, 8, ["placeholder", "modelValue"]),
  46035. vue.createCommentVNode(" :disabled='talkdisabled'></u-input> "),
  46036. vue.createElementVNode("view", {
  46037. class: "sent ml20",
  46038. onClick: _cache[5] || (_cache[5] = (...args) => $options.sendMsg && $options.sendMsg(...args))
  46039. }, "发送")
  46040. ])
  46041. ])) : vue.createCommentVNode("v-if", true),
  46042. vue.createCommentVNode(' <view class="answerbox" v-if="acttab==1">\r\n 问答\r\n </view> '),
  46043. $data.acttab == 1 ? (vue.openBlock(), vue.createElementBlock("view", {
  46044. key: 2,
  46045. class: "informationbox"
  46046. }, [
  46047. vue.createElementVNode("view", { class: "p20 bgf m20 radius20" }, [
  46048. vue.createElementVNode("view", {
  46049. innerHTML: $data.livedata.liveDesc
  46050. }, null, 8, ["innerHTML"]),
  46051. vue.withDirectives(vue.createElementVNode(
  46052. "view",
  46053. null,
  46054. "暂无资料",
  46055. 512
  46056. /* NEED_PATCH */
  46057. ), [
  46058. [vue.vShow, !$data.livedata.liveDesc]
  46059. ])
  46060. ])
  46061. ])) : vue.createCommentVNode("v-if", true),
  46062. vue.createElementVNode("view", {
  46063. class: "invite-member",
  46064. onClick: _cache[6] || (_cache[6] = (...args) => $options.addwechat && $options.addwechat(...args))
  46065. }, [
  46066. vue.createElementVNode("image", {
  46067. src: _imports_2$4,
  46068. class: "wh80 weimg"
  46069. }),
  46070. vue.createElementVNode("view", { class: "addwe" }, "加微信")
  46071. ]),
  46072. vue.createElementVNode("view", { class: "" }, [
  46073. vue.createVNode(_component_u_popup, {
  46074. show: $data.showadd,
  46075. onClose: $options.close,
  46076. onOpen: $options.open,
  46077. round: "20rpx",
  46078. bgColor: "#fffee1"
  46079. }, {
  46080. default: vue.withCtx(() => [
  46081. vue.createElementVNode("view", { class: "addchat p20" }, [
  46082. vue.createElementVNode("view", { class: "u-flex-row-reverse u-flex" }, [
  46083. vue.createVNode(_component_u_icon, {
  46084. name: "close",
  46085. size: "18",
  46086. onClick: _cache[7] || (_cache[7] = ($event) => $data.showadd = !$data.showadd)
  46087. })
  46088. ]),
  46089. vue.createElementVNode("view", { class: "column align-center" }, [
  46090. vue.createElementVNode("view", {
  46091. class: "fs36",
  46092. style: { "color": "#ff5c03" }
  46093. }, "扫码添加助教老师"),
  46094. vue.createElementVNode("view", { class: "fs28 color6" }, "扫码添加助教老师"),
  46095. vue.createElementVNode("view", {
  46096. class: "p10 mt40",
  46097. style: { "border": "#ff5c03 solid 2rpx" }
  46098. }, [
  46099. vue.createElementVNode("image", {
  46100. src: $data.codeimg,
  46101. class: "wh180",
  46102. onTouchstart: _cache[8] || (_cache[8] = (...args) => $options.longPress && $options.longPress(...args)),
  46103. onTouchend: _cache[9] || (_cache[9] = (...args) => $options.cancelLongPress && $options.cancelLongPress(...args))
  46104. }, null, 40, ["src"])
  46105. ]),
  46106. vue.createElementVNode("view", { class: "color6 mt20" }, "长按识别二维码")
  46107. ])
  46108. ])
  46109. ]),
  46110. _: 1
  46111. /* STABLE */
  46112. }, 8, ["show", "onClose", "onOpen"])
  46113. ])
  46114. ]);
  46115. }
  46116. const PagesHomeLive = /* @__PURE__ */ _export_sfc(_sfc_main$k, [["render", _sfc_render$j], ["__scopeId", "data-v-81fcd0c9"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages/home/live.vue"]]);
  46117. const _sfc_main$j = {
  46118. data() {
  46119. return {};
  46120. },
  46121. methods: {}
  46122. };
  46123. function _sfc_render$i(_ctx, _cache, $props, $setup, $data, $options) {
  46124. return vue.openBlock(), vue.createElementBlock("view");
  46125. }
  46126. const PagesGamesIndex = /* @__PURE__ */ _export_sfc(_sfc_main$j, [["render", _sfc_render$i], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages/games/index.vue"]]);
  46127. const custom = {
  46128. "^u--(.*)": "@/uni_modules/uview-plus/components/u-$1/u-$1.vue",
  46129. "^up-(.*)": "@/uni_modules/uview-plus/components/u-$1/u-$1.vue",
  46130. "^u-([^-].*)": "@/uni_modules/uview-plus/components/u-$1/u-$1.vue"
  46131. };
  46132. const pages = [
  46133. {
  46134. path: "pages/home/index",
  46135. style: {
  46136. navigationBarTitleText: "",
  46137. enablePullDownRefresh: false
  46138. }
  46139. },
  46140. {
  46141. path: "pages/home/living",
  46142. style: {
  46143. navigationBarTitleText: "",
  46144. navigationBarTextStyle: "black",
  46145. enablePullDownRefresh: false,
  46146. navigationStyle: "custom",
  46147. "app-plus": {
  46148. bounce: "none"
  46149. }
  46150. }
  46151. },
  46152. {
  46153. path: "pages/user/index",
  46154. style: {
  46155. navigationBarTitleText: "",
  46156. navigationBarTextStyle: "black",
  46157. enablePullDownRefresh: false,
  46158. navigationStyle: "custom",
  46159. "app-plus": {
  46160. bounce: "none"
  46161. }
  46162. }
  46163. },
  46164. {
  46165. path: "pages/list/index",
  46166. style: {
  46167. navigationBarTitleText: "直播列表",
  46168. navigationBarTextStyle: "black",
  46169. "app-plus": {
  46170. bounce: "none"
  46171. }
  46172. }
  46173. },
  46174. {
  46175. path: "pages/home/live",
  46176. style: {
  46177. navigationBarTitleText: "",
  46178. navigationBarTextStyle: "black",
  46179. enablePullDownRefresh: false,
  46180. navigationStyle: "custom",
  46181. "app-plus": {
  46182. bounce: "none"
  46183. }
  46184. }
  46185. },
  46186. {
  46187. path: "pages/games/index",
  46188. style: {
  46189. navigationBarTitleText: "",
  46190. navigationBarTextStyle: "black",
  46191. enablePullDownRefresh: false,
  46192. navigationStyle: "custom",
  46193. "app-plus": {
  46194. bounce: "none"
  46195. }
  46196. }
  46197. },
  46198. {
  46199. path: "pages/login/login",
  46200. style: {
  46201. navigationBarTitleText: "",
  46202. navigationBarTextStyle: "black",
  46203. enablePullDownRefresh: false,
  46204. navigationStyle: "custom",
  46205. "app-plus": {
  46206. bounce: "none"
  46207. }
  46208. }
  46209. }
  46210. ];
  46211. const subPackages = [
  46212. {
  46213. root: "pages_shop",
  46214. pages: [
  46215. {
  46216. path: "cart",
  46217. style: {
  46218. navigationBarTitleText: "药膳食疗",
  46219. "app-plus": {
  46220. titleNView: false
  46221. }
  46222. }
  46223. },
  46224. {
  46225. path: "goods",
  46226. style: {
  46227. navigationBarTitleText: "商品详情",
  46228. enablePullDownRefresh: false
  46229. }
  46230. },
  46231. {
  46232. path: "store",
  46233. style: {
  46234. navigationBarTitleText: "店铺详情",
  46235. enablePullDownRefresh: false
  46236. }
  46237. },
  46238. {
  46239. path: "order",
  46240. style: {
  46241. navigationBarTitleText: "我的订单",
  46242. navigationBarTextStyle: "black",
  46243. "app-plus": {
  46244. bounce: "none"
  46245. }
  46246. }
  46247. },
  46248. {
  46249. path: "confirmCreateOrder",
  46250. style: {
  46251. navigationBarTitleText: "确认订单",
  46252. navigationBarTextStyle: "black",
  46253. "app-plus": {
  46254. bounce: "none"
  46255. }
  46256. }
  46257. },
  46258. {
  46259. path: "paymentOrder",
  46260. style: {
  46261. navigationBarTitleText: "支付订单",
  46262. navigationBarTextStyle: "black",
  46263. "app-plus": {
  46264. bounce: "none"
  46265. }
  46266. }
  46267. },
  46268. {
  46269. path: "confirmPackageOrder",
  46270. style: {
  46271. navigationBarTitleText: "确认支付",
  46272. navigationBarTextStyle: "black",
  46273. "app-plus": {
  46274. bounce: "none"
  46275. }
  46276. }
  46277. },
  46278. {
  46279. path: "success",
  46280. style: {
  46281. navigationBarTitleText: "支付成功",
  46282. navigationBarTextStyle: "black",
  46283. "app-plus": {
  46284. bounce: "none"
  46285. }
  46286. }
  46287. }
  46288. ]
  46289. },
  46290. {
  46291. root: "pages_user",
  46292. pages: [
  46293. {
  46294. path: "address",
  46295. style: {
  46296. navigationBarTitleText: "收货地址",
  46297. "app-plus": {
  46298. titleNView: false
  46299. }
  46300. }
  46301. },
  46302. {
  46303. path: "addAddress",
  46304. style: {
  46305. navigationBarTitleText: "新建收货地址",
  46306. navigationBarTextStyle: "black",
  46307. "app-plus": {
  46308. bounce: "none"
  46309. }
  46310. }
  46311. }
  46312. ]
  46313. }
  46314. ];
  46315. const globalStyle = {
  46316. navigationBarTextStyle: "black",
  46317. navigationBarTitleText: "【S直播】",
  46318. navigationBarBackgroundColor: "#f5f5f5",
  46319. backgroundColor: "#f7f8fa"
  46320. };
  46321. const uniIdRouter = {};
  46322. const tabBar = {
  46323. color: "#AEAEAE",
  46324. selectedColor: "#000000",
  46325. fontSize: "12px",
  46326. borderStyle: "black",
  46327. backgroundColor: "#fff",
  46328. list: [
  46329. {
  46330. pagePath: "pages/list/index",
  46331. iconPath: "/static/tabBar/query.png",
  46332. selectedIconPath: "/static/tabBar/query_active.png",
  46333. text: "列表"
  46334. },
  46335. {
  46336. pagePath: "pages/games/index",
  46337. iconPath: "/static/tabBar/pulverize.png",
  46338. selectedIconPath: "/static/tabBar/pulverize_active.png",
  46339. text: "合同粉碎"
  46340. },
  46341. {
  46342. pagePath: "pages/user/index",
  46343. iconPath: "/static/tabBar/user.png",
  46344. selectedIconPath: "/static/tabBar/user_active.png",
  46345. text: "我的"
  46346. }
  46347. ]
  46348. };
  46349. const e = {
  46350. custom,
  46351. pages,
  46352. subPackages,
  46353. globalStyle,
  46354. uniIdRouter,
  46355. tabBar
  46356. };
  46357. var define_process_env_UNI_SECURE_NETWORK_CONFIG_default = [];
  46358. function t(e2) {
  46359. return e2 && e2.__esModule && Object.prototype.hasOwnProperty.call(e2, "default") ? e2.default : e2;
  46360. }
  46361. function n(e2, t2, n2) {
  46362. return e2(n2 = { path: t2, exports: {}, require: function(e3, t3) {
  46363. return function() {
  46364. throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");
  46365. }(null == t3 && n2.path);
  46366. } }, n2.exports), n2.exports;
  46367. }
  46368. var s = n(function(e2, t2) {
  46369. var n2;
  46370. e2.exports = (n2 = n2 || function(e3, t3) {
  46371. var n3 = Object.create || /* @__PURE__ */ function() {
  46372. function e4() {
  46373. }
  46374. return function(t4) {
  46375. var n4;
  46376. return e4.prototype = t4, n4 = new e4(), e4.prototype = null, n4;
  46377. };
  46378. }(), s2 = {}, r2 = s2.lib = {}, i2 = r2.Base = { extend: function(e4) {
  46379. var t4 = n3(this);
  46380. return e4 && t4.mixIn(e4), t4.hasOwnProperty("init") && this.init !== t4.init || (t4.init = function() {
  46381. t4.$super.init.apply(this, arguments);
  46382. }), t4.init.prototype = t4, t4.$super = this, t4;
  46383. }, create: function() {
  46384. var e4 = this.extend();
  46385. return e4.init.apply(e4, arguments), e4;
  46386. }, init: function() {
  46387. }, mixIn: function(e4) {
  46388. for (var t4 in e4)
  46389. e4.hasOwnProperty(t4) && (this[t4] = e4[t4]);
  46390. e4.hasOwnProperty("toString") && (this.toString = e4.toString);
  46391. }, clone: function() {
  46392. return this.init.prototype.extend(this);
  46393. } }, o2 = r2.WordArray = i2.extend({ init: function(e4, n4) {
  46394. e4 = this.words = e4 || [], this.sigBytes = n4 != t3 ? n4 : 4 * e4.length;
  46395. }, toString: function(e4) {
  46396. return (e4 || c2).stringify(this);
  46397. }, concat: function(e4) {
  46398. var t4 = this.words, n4 = e4.words, s3 = this.sigBytes, r3 = e4.sigBytes;
  46399. if (this.clamp(), s3 % 4)
  46400. for (var i3 = 0; i3 < r3; i3++) {
  46401. var o3 = n4[i3 >>> 2] >>> 24 - i3 % 4 * 8 & 255;
  46402. t4[s3 + i3 >>> 2] |= o3 << 24 - (s3 + i3) % 4 * 8;
  46403. }
  46404. else
  46405. for (i3 = 0; i3 < r3; i3 += 4)
  46406. t4[s3 + i3 >>> 2] = n4[i3 >>> 2];
  46407. return this.sigBytes += r3, this;
  46408. }, clamp: function() {
  46409. var t4 = this.words, n4 = this.sigBytes;
  46410. t4[n4 >>> 2] &= 4294967295 << 32 - n4 % 4 * 8, t4.length = e3.ceil(n4 / 4);
  46411. }, clone: function() {
  46412. var e4 = i2.clone.call(this);
  46413. return e4.words = this.words.slice(0), e4;
  46414. }, random: function(t4) {
  46415. for (var n4, s3 = [], r3 = function(t5) {
  46416. var n5 = 987654321, s4 = 4294967295;
  46417. return function() {
  46418. var r4 = ((n5 = 36969 * (65535 & n5) + (n5 >> 16) & s4) << 16) + (t5 = 18e3 * (65535 & t5) + (t5 >> 16) & s4) & s4;
  46419. return r4 /= 4294967296, (r4 += 0.5) * (e3.random() > 0.5 ? 1 : -1);
  46420. };
  46421. }, i3 = 0; i3 < t4; i3 += 4) {
  46422. var a3 = r3(4294967296 * (n4 || e3.random()));
  46423. n4 = 987654071 * a3(), s3.push(4294967296 * a3() | 0);
  46424. }
  46425. return new o2.init(s3, t4);
  46426. } }), a2 = s2.enc = {}, c2 = a2.Hex = { stringify: function(e4) {
  46427. for (var t4 = e4.words, n4 = e4.sigBytes, s3 = [], r3 = 0; r3 < n4; r3++) {
  46428. var i3 = t4[r3 >>> 2] >>> 24 - r3 % 4 * 8 & 255;
  46429. s3.push((i3 >>> 4).toString(16)), s3.push((15 & i3).toString(16));
  46430. }
  46431. return s3.join("");
  46432. }, parse: function(e4) {
  46433. for (var t4 = e4.length, n4 = [], s3 = 0; s3 < t4; s3 += 2)
  46434. n4[s3 >>> 3] |= parseInt(e4.substr(s3, 2), 16) << 24 - s3 % 8 * 4;
  46435. return new o2.init(n4, t4 / 2);
  46436. } }, u2 = a2.Latin1 = { stringify: function(e4) {
  46437. for (var t4 = e4.words, n4 = e4.sigBytes, s3 = [], r3 = 0; r3 < n4; r3++) {
  46438. var i3 = t4[r3 >>> 2] >>> 24 - r3 % 4 * 8 & 255;
  46439. s3.push(String.fromCharCode(i3));
  46440. }
  46441. return s3.join("");
  46442. }, parse: function(e4) {
  46443. for (var t4 = e4.length, n4 = [], s3 = 0; s3 < t4; s3++)
  46444. n4[s3 >>> 2] |= (255 & e4.charCodeAt(s3)) << 24 - s3 % 4 * 8;
  46445. return new o2.init(n4, t4);
  46446. } }, h2 = a2.Utf8 = { stringify: function(e4) {
  46447. try {
  46448. return decodeURIComponent(escape(u2.stringify(e4)));
  46449. } catch (e5) {
  46450. throw new Error("Malformed UTF-8 data");
  46451. }
  46452. }, parse: function(e4) {
  46453. return u2.parse(unescape(encodeURIComponent(e4)));
  46454. } }, l2 = r2.BufferedBlockAlgorithm = i2.extend({ reset: function() {
  46455. this._data = new o2.init(), this._nDataBytes = 0;
  46456. }, _append: function(e4) {
  46457. "string" == typeof e4 && (e4 = h2.parse(e4)), this._data.concat(e4), this._nDataBytes += e4.sigBytes;
  46458. }, _process: function(t4) {
  46459. 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);
  46460. if (c3) {
  46461. for (var h3 = 0; h3 < c3; h3 += i3)
  46462. this._doProcessBlock(s3, h3);
  46463. var l3 = s3.splice(0, c3);
  46464. n4.sigBytes -= u3;
  46465. }
  46466. return new o2.init(l3, u3);
  46467. }, clone: function() {
  46468. var e4 = i2.clone.call(this);
  46469. return e4._data = this._data.clone(), e4;
  46470. }, _minBufferSize: 0 });
  46471. r2.Hasher = l2.extend({ cfg: i2.extend(), init: function(e4) {
  46472. this.cfg = this.cfg.extend(e4), this.reset();
  46473. }, reset: function() {
  46474. l2.reset.call(this), this._doReset();
  46475. }, update: function(e4) {
  46476. return this._append(e4), this._process(), this;
  46477. }, finalize: function(e4) {
  46478. return e4 && this._append(e4), this._doFinalize();
  46479. }, blockSize: 16, _createHelper: function(e4) {
  46480. return function(t4, n4) {
  46481. return new e4.init(n4).finalize(t4);
  46482. };
  46483. }, _createHmacHelper: function(e4) {
  46484. return function(t4, n4) {
  46485. return new d2.HMAC.init(e4, n4).finalize(t4);
  46486. };
  46487. } });
  46488. var d2 = s2.algo = {};
  46489. return s2;
  46490. }(Math), n2);
  46491. }), r = s, i = (n(function(e2, t2) {
  46492. var n2;
  46493. e2.exports = (n2 = r, function(e3) {
  46494. var t3 = n2, s2 = t3.lib, r2 = s2.WordArray, i2 = s2.Hasher, o2 = t3.algo, a2 = [];
  46495. !function() {
  46496. for (var t4 = 0; t4 < 64; t4++)
  46497. a2[t4] = 4294967296 * e3.abs(e3.sin(t4 + 1)) | 0;
  46498. }();
  46499. var c2 = o2.MD5 = i2.extend({ _doReset: function() {
  46500. this._hash = new r2.init([1732584193, 4023233417, 2562383102, 271733878]);
  46501. }, _doProcessBlock: function(e4, t4) {
  46502. for (var n3 = 0; n3 < 16; n3++) {
  46503. var s3 = t4 + n3, r3 = e4[s3];
  46504. e4[s3] = 16711935 & (r3 << 8 | r3 >>> 24) | 4278255360 & (r3 << 24 | r3 >>> 8);
  46505. }
  46506. 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];
  46507. 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;
  46508. }, _doFinalize: function() {
  46509. var t4 = this._data, n3 = t4.words, s3 = 8 * this._nDataBytes, r3 = 8 * t4.sigBytes;
  46510. n3[r3 >>> 5] |= 128 << 24 - r3 % 32;
  46511. var i3 = e3.floor(s3 / 4294967296), o3 = s3;
  46512. 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();
  46513. for (var a3 = this._hash, c3 = a3.words, u3 = 0; u3 < 4; u3++) {
  46514. var h3 = c3[u3];
  46515. c3[u3] = 16711935 & (h3 << 8 | h3 >>> 24) | 4278255360 & (h3 << 24 | h3 >>> 8);
  46516. }
  46517. return a3;
  46518. }, clone: function() {
  46519. var e4 = i2.clone.call(this);
  46520. return e4._hash = this._hash.clone(), e4;
  46521. } });
  46522. function u2(e4, t4, n3, s3, r3, i3, o3) {
  46523. var a3 = e4 + (t4 & n3 | ~t4 & s3) + r3 + o3;
  46524. return (a3 << i3 | a3 >>> 32 - i3) + t4;
  46525. }
  46526. function h2(e4, t4, n3, s3, r3, i3, o3) {
  46527. var a3 = e4 + (t4 & s3 | n3 & ~s3) + r3 + o3;
  46528. return (a3 << i3 | a3 >>> 32 - i3) + t4;
  46529. }
  46530. function l2(e4, t4, n3, s3, r3, i3, o3) {
  46531. var a3 = e4 + (t4 ^ n3 ^ s3) + r3 + o3;
  46532. return (a3 << i3 | a3 >>> 32 - i3) + t4;
  46533. }
  46534. function d2(e4, t4, n3, s3, r3, i3, o3) {
  46535. var a3 = e4 + (n3 ^ (t4 | ~s3)) + r3 + o3;
  46536. return (a3 << i3 | a3 >>> 32 - i3) + t4;
  46537. }
  46538. t3.MD5 = i2._createHelper(c2), t3.HmacMD5 = i2._createHmacHelper(c2);
  46539. }(Math), n2.MD5);
  46540. }), n(function(e2, t2) {
  46541. var n2;
  46542. e2.exports = (n2 = r, void function() {
  46543. var e3 = n2, t3 = e3.lib.Base, s2 = e3.enc.Utf8;
  46544. e3.algo.HMAC = t3.extend({ init: function(e4, t4) {
  46545. e4 = this._hasher = new e4.init(), "string" == typeof t4 && (t4 = s2.parse(t4));
  46546. var n3 = e4.blockSize, r2 = 4 * n3;
  46547. t4.sigBytes > r2 && (t4 = e4.finalize(t4)), t4.clamp();
  46548. for (var i2 = this._oKey = t4.clone(), o2 = this._iKey = t4.clone(), a2 = i2.words, c2 = o2.words, u2 = 0; u2 < n3; u2++)
  46549. a2[u2] ^= 1549556828, c2[u2] ^= 909522486;
  46550. i2.sigBytes = o2.sigBytes = r2, this.reset();
  46551. }, reset: function() {
  46552. var e4 = this._hasher;
  46553. e4.reset(), e4.update(this._iKey);
  46554. }, update: function(e4) {
  46555. return this._hasher.update(e4), this;
  46556. }, finalize: function(e4) {
  46557. var t4 = this._hasher, n3 = t4.finalize(e4);
  46558. return t4.reset(), t4.finalize(this._oKey.clone().concat(n3));
  46559. } });
  46560. }());
  46561. }), n(function(e2, t2) {
  46562. e2.exports = r.HmacMD5;
  46563. })), o = n(function(e2, t2) {
  46564. e2.exports = r.enc.Utf8;
  46565. }), a = n(function(e2, t2) {
  46566. var n2;
  46567. e2.exports = (n2 = r, function() {
  46568. var e3 = n2, t3 = e3.lib.WordArray;
  46569. function s2(e4, n3, s3) {
  46570. for (var r2 = [], i2 = 0, o2 = 0; o2 < n3; o2++)
  46571. if (o2 % 4) {
  46572. var a2 = s3[e4.charCodeAt(o2 - 1)] << o2 % 4 * 2, c2 = s3[e4.charCodeAt(o2)] >>> 6 - o2 % 4 * 2;
  46573. r2[i2 >>> 2] |= (a2 | c2) << 24 - i2 % 4 * 8, i2++;
  46574. }
  46575. return t3.create(r2, i2);
  46576. }
  46577. e3.enc.Base64 = { stringify: function(e4) {
  46578. var t4 = e4.words, n3 = e4.sigBytes, s3 = this._map;
  46579. e4.clamp();
  46580. for (var r2 = [], i2 = 0; i2 < n3; i2 += 3)
  46581. 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++)
  46582. r2.push(s3.charAt(o2 >>> 6 * (3 - a2) & 63));
  46583. var c2 = s3.charAt(64);
  46584. if (c2)
  46585. for (; r2.length % 4; )
  46586. r2.push(c2);
  46587. return r2.join("");
  46588. }, parse: function(e4) {
  46589. var t4 = e4.length, n3 = this._map, r2 = this._reverseMap;
  46590. if (!r2) {
  46591. r2 = this._reverseMap = [];
  46592. for (var i2 = 0; i2 < n3.length; i2++)
  46593. r2[n3.charCodeAt(i2)] = i2;
  46594. }
  46595. var o2 = n3.charAt(64);
  46596. if (o2) {
  46597. var a2 = e4.indexOf(o2);
  46598. -1 !== a2 && (t4 = a2);
  46599. }
  46600. return s2(e4, t4, r2);
  46601. }, _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" };
  46602. }(), n2.enc.Base64);
  46603. });
  46604. 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";
  46605. function g(e2) {
  46606. return Object.prototype.toString.call(e2).slice(8, -1).toLowerCase();
  46607. }
  46608. function m(e2) {
  46609. return "object" === g(e2);
  46610. }
  46611. function y(e2) {
  46612. return "function" == typeof e2;
  46613. }
  46614. function _(e2) {
  46615. return function() {
  46616. try {
  46617. return e2.apply(e2, arguments);
  46618. } catch (e3) {
  46619. console.error(e3);
  46620. }
  46621. };
  46622. }
  46623. const w = "REJECTED", I = "NOT_PENDING";
  46624. class v {
  46625. constructor({ createPromise: e2, retryRule: t2 = w } = {}) {
  46626. this.createPromise = e2, this.status = null, this.promise = null, this.retryRule = t2;
  46627. }
  46628. get needRetry() {
  46629. if (!this.status)
  46630. return true;
  46631. switch (this.retryRule) {
  46632. case w:
  46633. return this.status === f;
  46634. case I:
  46635. return this.status !== d;
  46636. }
  46637. }
  46638. exec() {
  46639. 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;
  46640. }
  46641. }
  46642. class S {
  46643. constructor() {
  46644. this._callback = {};
  46645. }
  46646. addListener(e2, t2) {
  46647. this._callback[e2] || (this._callback[e2] = []), this._callback[e2].push(t2);
  46648. }
  46649. on(e2, t2) {
  46650. return this.addListener(e2, t2);
  46651. }
  46652. removeListener(e2, t2) {
  46653. if (!t2)
  46654. throw new Error('The "listener" argument must be of type function. Received undefined');
  46655. const n2 = this._callback[e2];
  46656. if (!n2)
  46657. return;
  46658. const s2 = function(e3, t3) {
  46659. for (let n3 = e3.length - 1; n3 >= 0; n3--)
  46660. if (e3[n3] === t3)
  46661. return n3;
  46662. return -1;
  46663. }(n2, t2);
  46664. n2.splice(s2, 1);
  46665. }
  46666. off(e2, t2) {
  46667. return this.removeListener(e2, t2);
  46668. }
  46669. removeAllListener(e2) {
  46670. delete this._callback[e2];
  46671. }
  46672. emit(e2, ...t2) {
  46673. const n2 = this._callback[e2];
  46674. if (n2)
  46675. for (let e3 = 0; e3 < n2.length; e3++)
  46676. n2[e3](...t2);
  46677. }
  46678. }
  46679. function T(e2) {
  46680. return e2 && "string" == typeof e2 ? JSON.parse(e2) : e2;
  46681. }
  46682. const b = true, E = "app", A = T(define_process_env_UNI_SECURE_NETWORK_CONFIG_default), P = E, C = T(""), O = T("[]") || [];
  46683. let N = "";
  46684. try {
  46685. N = "__UNI__90F7D71";
  46686. } catch (e2) {
  46687. }
  46688. let R, L = {};
  46689. function U(e2, t2 = {}) {
  46690. var n2, s2;
  46691. return n2 = L, s2 = e2, Object.prototype.hasOwnProperty.call(n2, s2) || (L[e2] = t2), L[e2];
  46692. }
  46693. function D() {
  46694. return R || (R = function() {
  46695. if ("undefined" != typeof globalThis)
  46696. return globalThis;
  46697. if ("undefined" != typeof self)
  46698. return self;
  46699. if ("undefined" != typeof window)
  46700. return window;
  46701. function e2() {
  46702. return this;
  46703. }
  46704. return void 0 !== e2() ? e2() : new Function("return this")();
  46705. }(), R);
  46706. }
  46707. L = uni._globalUniCloudObj ? uni._globalUniCloudObj : uni._globalUniCloudObj = {};
  46708. const M = ["invoke", "success", "fail", "complete"], q = U("_globalUniCloudInterceptor");
  46709. function F(e2, t2) {
  46710. q[e2] || (q[e2] = {}), m(t2) && Object.keys(t2).forEach((n2) => {
  46711. M.indexOf(n2) > -1 && function(e3, t3, n3) {
  46712. let s2 = q[e3][t3];
  46713. s2 || (s2 = q[e3][t3] = []), -1 === s2.indexOf(n3) && y(n3) && s2.push(n3);
  46714. }(e2, n2, t2[n2]);
  46715. });
  46716. }
  46717. function K(e2, t2) {
  46718. q[e2] || (q[e2] = {}), m(t2) ? Object.keys(t2).forEach((n2) => {
  46719. M.indexOf(n2) > -1 && function(e3, t3, n3) {
  46720. const s2 = q[e3][t3];
  46721. if (!s2)
  46722. return;
  46723. const r2 = s2.indexOf(n3);
  46724. r2 > -1 && s2.splice(r2, 1);
  46725. }(e2, n2, t2[n2]);
  46726. }) : delete q[e2];
  46727. }
  46728. function j(e2, t2) {
  46729. return e2 && 0 !== e2.length ? e2.reduce((e3, n2) => e3.then(() => n2(t2)), Promise.resolve()) : Promise.resolve();
  46730. }
  46731. function $(e2, t2) {
  46732. return q[e2] && q[e2][t2] || [];
  46733. }
  46734. function B(e2) {
  46735. F("callObject", e2);
  46736. }
  46737. const W = U("_globalUniCloudListener"), H = { RESPONSE: "response", NEED_LOGIN: "needLogin", REFRESH_TOKEN: "refreshToken" }, J = { CLIENT_DB: "clientdb", CLOUD_FUNCTION: "cloudfunction", CLOUD_OBJECT: "cloudobject" };
  46738. function z(e2) {
  46739. return W[e2] || (W[e2] = []), W[e2];
  46740. }
  46741. function V(e2, t2) {
  46742. const n2 = z(e2);
  46743. n2.includes(t2) || n2.push(t2);
  46744. }
  46745. function G(e2, t2) {
  46746. const n2 = z(e2), s2 = n2.indexOf(t2);
  46747. -1 !== s2 && n2.splice(s2, 1);
  46748. }
  46749. function Y(e2, t2) {
  46750. const n2 = z(e2);
  46751. for (let e3 = 0; e3 < n2.length; e3++) {
  46752. (0, n2[e3])(t2);
  46753. }
  46754. }
  46755. let Q, X = false;
  46756. function Z() {
  46757. return Q || (Q = new Promise((e2) => {
  46758. X && e2(), function t2() {
  46759. if ("function" == typeof getCurrentPages) {
  46760. const t3 = getCurrentPages();
  46761. t3 && t3[0] && (X = true, e2());
  46762. }
  46763. X || setTimeout(() => {
  46764. t2();
  46765. }, 30);
  46766. }();
  46767. }), Q);
  46768. }
  46769. function ee(e2) {
  46770. const t2 = {};
  46771. for (const n2 in e2) {
  46772. const s2 = e2[n2];
  46773. y(s2) && (t2[n2] = _(s2));
  46774. }
  46775. return t2;
  46776. }
  46777. class te extends Error {
  46778. constructor(e2) {
  46779. const t2 = e2.message || e2.errMsg || "unknown system error";
  46780. 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;
  46781. }
  46782. toJson(e2 = 0) {
  46783. if (!(e2 >= 10))
  46784. return e2++, { errCode: this.errCode, errMsg: this.errMsg, errSubject: this.errSubject, cause: this.cause && this.cause.toJson ? this.cause.toJson(e2) : this.cause };
  46785. }
  46786. }
  46787. var ne = { request: (e2) => uni.request(e2), uploadFile: (e2) => uni.uploadFile(e2), setStorageSync: (e2, t2) => uni.setStorageSync(e2, t2), getStorageSync: (e2) => uni.getStorageSync(e2), removeStorageSync: (e2) => uni.removeStorageSync(e2), clearStorageSync: () => uni.clearStorageSync(), connectSocket: (e2) => uni.connectSocket(e2) };
  46788. function se(e2) {
  46789. return e2 && se(e2.__v_raw) || e2;
  46790. }
  46791. function re() {
  46792. return { token: ne.getStorageSync(c) || ne.getStorageSync(h), tokenExpired: ne.getStorageSync(u) };
  46793. }
  46794. function ie({ token: e2, tokenExpired: t2 } = {}) {
  46795. e2 && ne.setStorageSync(c, e2), t2 && ne.setStorageSync(u, t2);
  46796. }
  46797. let oe, ae;
  46798. function ce() {
  46799. return oe || (oe = uni.getSystemInfoSync()), oe;
  46800. }
  46801. function ue() {
  46802. let e2, t2;
  46803. try {
  46804. if (uni.getLaunchOptionsSync) {
  46805. if (uni.getLaunchOptionsSync.toString().indexOf("not yet implemented") > -1)
  46806. return;
  46807. const { scene: n2, channel: s2 } = uni.getLaunchOptionsSync();
  46808. e2 = s2, t2 = n2;
  46809. }
  46810. } catch (e3) {
  46811. }
  46812. return { channel: e2, scene: t2 };
  46813. }
  46814. let he = {};
  46815. function le() {
  46816. const e2 = uni.getLocale && uni.getLocale() || "en";
  46817. if (ae)
  46818. return { ...he, ...ae, locale: e2, LOCALE: e2 };
  46819. 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"];
  46820. for (const e3 in t2)
  46821. Object.hasOwnProperty.call(t2, e3) && -1 === o2.indexOf(e3) && delete t2[e3];
  46822. return ae = { PLATFORM: r2, OS: s2, APPID: i2, DEVICEID: n2, ...ue(), ...t2 }, { ...he, ...ae, locale: e2, LOCALE: e2 };
  46823. }
  46824. var de = { sign: function(e2, t2) {
  46825. let n2 = "";
  46826. return Object.keys(e2).sort().forEach(function(t3) {
  46827. e2[t3] && (n2 = n2 + "&" + t3 + "=" + e2[t3]);
  46828. }), n2 = n2.slice(1), i(n2, t2).toString();
  46829. }, wrappedRequest: function(e2, t2) {
  46830. return new Promise((n2, s2) => {
  46831. t2(Object.assign(e2, { complete(e3) {
  46832. e3 || (e3 = {});
  46833. const t3 = e3.data && e3.data.header && e3.data.header["x-serverless-request-id"] || e3.header && e3.header["request-id"];
  46834. if (!e3.statusCode || e3.statusCode >= 400) {
  46835. 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";
  46836. return s2(new te({ code: n3, message: r3, requestId: t3 }));
  46837. }
  46838. const r2 = e3.data;
  46839. if (r2.error)
  46840. return s2(new te({ code: r2.error.code, message: r2.error.message, requestId: t3 }));
  46841. r2.result = r2.data, r2.requestId = t3, delete r2.data, n2(r2);
  46842. } }));
  46843. });
  46844. }, toBase64: function(e2) {
  46845. return a.stringify(o.parse(e2));
  46846. } };
  46847. var pe = class {
  46848. constructor(e2) {
  46849. ["spaceId", "clientSecret"].forEach((t2) => {
  46850. if (!Object.prototype.hasOwnProperty.call(e2, t2))
  46851. throw new Error(`${t2} required`);
  46852. }), 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) => {
  46853. if (!e3.result || !e3.result.accessToken)
  46854. throw new te({ code: "AUTH_FAILED", message: "获取accessToken失败" });
  46855. this.setAccessToken(e3.result.accessToken);
  46856. }), retryRule: I });
  46857. }
  46858. get hasAccessToken() {
  46859. return !!this.accessToken;
  46860. }
  46861. setAccessToken(e2) {
  46862. this.accessToken = e2;
  46863. }
  46864. requestWrapped(e2) {
  46865. return de.wrappedRequest(e2, this.adapter.request);
  46866. }
  46867. requestAuth(e2) {
  46868. return this.requestWrapped(e2);
  46869. }
  46870. request(e2, t2) {
  46871. return Promise.resolve().then(() => this.hasAccessToken ? t2 ? this.requestWrapped(e2) : this.requestWrapped(e2).catch((t3) => new Promise((e3, n2) => {
  46872. !t3 || "GATEWAY_INVALID_TOKEN" !== t3.code && "InvalidParameter.InvalidToken" !== t3.code ? n2(t3) : e3();
  46873. }).then(() => this.getAccessToken()).then(() => {
  46874. const t4 = this.rebuildRequest(e2);
  46875. return this.request(t4, true);
  46876. })) : this.getAccessToken().then(() => {
  46877. const t3 = this.rebuildRequest(e2);
  46878. return this.request(t3, true);
  46879. }));
  46880. }
  46881. rebuildRequest(e2) {
  46882. const t2 = Object.assign({}, e2);
  46883. 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;
  46884. }
  46885. setupRequest(e2, t2) {
  46886. const n2 = Object.assign({}, e2, { spaceId: this.config.spaceId, timestamp: Date.now() }), s2 = { "Content-Type": "application/json" };
  46887. 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 };
  46888. }
  46889. getAccessToken() {
  46890. return this._getAccessTokenPromiseHub.exec();
  46891. }
  46892. async authorize() {
  46893. await this.getAccessToken();
  46894. }
  46895. callFunction(e2) {
  46896. const t2 = { method: "serverless.function.runtime.invoke", params: JSON.stringify({ functionTarget: e2.name, functionArgs: e2.data || {} }) };
  46897. return this.request({ ...this.setupRequest(t2), timeout: e2.timeout });
  46898. }
  46899. getOSSUploadOptionsFromPath(e2) {
  46900. const t2 = { method: "serverless.file.resource.generateProximalSign", params: JSON.stringify(e2) };
  46901. return this.request(this.setupRequest(t2));
  46902. }
  46903. uploadFileToOSS({ url: e2, formData: t2, name: n2, filePath: s2, fileType: r2, onUploadProgress: i2 }) {
  46904. return new Promise((o2, a2) => {
  46905. const c2 = this.adapter.uploadFile({ url: e2, formData: t2, name: n2, filePath: s2, fileType: r2, header: { "X-OSS-server-side-encrpytion": "AES256" }, success(e3) {
  46906. e3 && e3.statusCode < 400 ? o2(e3) : a2(new te({ code: "UPLOAD_FAILED", message: "文件上传失败" }));
  46907. }, fail(e3) {
  46908. a2(new te({ code: e3.code || "UPLOAD_FAILED", message: e3.message || e3.errMsg || "文件上传失败" }));
  46909. } });
  46910. "function" == typeof i2 && c2 && "function" == typeof c2.onProgressUpdate && c2.onProgressUpdate((e3) => {
  46911. i2({ loaded: e3.totalBytesSent, total: e3.totalBytesExpectedToSend });
  46912. });
  46913. });
  46914. }
  46915. reportOSSUpload(e2) {
  46916. const t2 = { method: "serverless.file.resource.report", params: JSON.stringify(e2) };
  46917. return this.request(this.setupRequest(t2));
  46918. }
  46919. async uploadFile({ filePath: e2, cloudPath: t2, fileType: n2 = "image", cloudPathAsRealPath: s2 = false, onUploadProgress: r2, config: i2 }) {
  46920. if ("string" !== g(t2))
  46921. throw new te({ code: "INVALID_PARAM", message: "cloudPath必须为字符串类型" });
  46922. if (!(t2 = t2.trim()))
  46923. throw new te({ code: "INVALID_PARAM", message: "cloudPath不可为空" });
  46924. if (/:\/\//.test(t2))
  46925. throw new te({ code: "INVALID_PARAM", message: "cloudPath不合法" });
  46926. const o2 = i2 && i2.envType || this.config.envType;
  46927. if (s2 && ("/" !== t2[0] && (t2 = "/" + t2), t2.indexOf("\\") > -1))
  46928. throw new te({ code: "INVALID_PARAM", message: "使用cloudPath作为路径时,cloudPath不可包含“\\”" });
  46929. 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 };
  46930. if (u2 && (_2["x-oss-security-token"] = u2), y2) {
  46931. const e3 = JSON.stringify({ callbackUrl: y2, callbackBody: JSON.stringify({ fileId: f2, spaceId: this.config.spaceId }), callbackBodyType: "application/json" });
  46932. _2.callback = de.toBase64(e3);
  46933. }
  46934. const w2 = { url: "https://" + a2.host, formData: _2, fileName: "file", name: "file", filePath: e2, fileType: n2 };
  46935. if (await this.uploadFileToOSS(Object.assign({}, w2, { onUploadProgress: r2 })), y2)
  46936. return { success: true, filePath: e2, fileID: c2 };
  46937. if ((await this.reportOSSUpload({ id: f2 })).success)
  46938. return { success: true, filePath: e2, fileID: c2 };
  46939. throw new te({ code: "UPLOAD_FAILED", message: "文件上传失败" });
  46940. }
  46941. getTempFileURL({ fileList: e2 } = {}) {
  46942. return new Promise((t2, n2) => {
  46943. Array.isArray(e2) && 0 !== e2.length || n2(new te({ code: "INVALID_PARAM", message: "fileList的元素必须是非空的字符串" })), this.getFileInfo({ fileList: e2 }).then((n3) => {
  46944. t2({ fileList: e2.map((e3, t3) => {
  46945. const s2 = n3.fileList[t3];
  46946. return { fileID: e3, tempFileURL: s2 && s2.url || e3 };
  46947. }) });
  46948. });
  46949. });
  46950. }
  46951. async getFileInfo({ fileList: e2 } = {}) {
  46952. if (!Array.isArray(e2) || 0 === e2.length)
  46953. throw new te({ code: "INVALID_PARAM", message: "fileList的元素必须是非空的字符串" });
  46954. const t2 = { method: "serverless.file.resource.info", params: JSON.stringify({ id: e2.map((e3) => e3.split("?")[0]).join(",") }) };
  46955. return { fileList: (await this.request(this.setupRequest(t2))).result };
  46956. }
  46957. };
  46958. var fe = { init(e2) {
  46959. const t2 = new pe(e2), n2 = { signInAnonymously: function() {
  46960. return t2.authorize();
  46961. }, getLoginState: function() {
  46962. return Promise.resolve(false);
  46963. } };
  46964. return t2.auth = function() {
  46965. return n2;
  46966. }, t2.customAuth = t2.auth, t2;
  46967. } };
  46968. const ge = "undefined" != typeof location && "http:" === location.protocol ? "http:" : "https:";
  46969. var me;
  46970. !function(e2) {
  46971. e2.local = "local", e2.none = "none", e2.session = "session";
  46972. }(me || (me = {}));
  46973. var ye = function() {
  46974. }, _e = n(function(e2, t2) {
  46975. var n2;
  46976. e2.exports = (n2 = r, function(e3) {
  46977. var t3 = n2, s2 = t3.lib, r2 = s2.WordArray, i2 = s2.Hasher, o2 = t3.algo, a2 = [], c2 = [];
  46978. !function() {
  46979. function t4(t5) {
  46980. for (var n4 = e3.sqrt(t5), s4 = 2; s4 <= n4; s4++)
  46981. if (!(t5 % s4))
  46982. return false;
  46983. return true;
  46984. }
  46985. function n3(e4) {
  46986. return 4294967296 * (e4 - (0 | e4)) | 0;
  46987. }
  46988. for (var s3 = 2, r3 = 0; r3 < 64; )
  46989. t4(s3) && (r3 < 8 && (a2[r3] = n3(e3.pow(s3, 0.5))), c2[r3] = n3(e3.pow(s3, 1 / 3)), r3++), s3++;
  46990. }();
  46991. var u2 = [], h2 = o2.SHA256 = i2.extend({ _doReset: function() {
  46992. this._hash = new r2.init(a2.slice(0));
  46993. }, _doProcessBlock: function(e4, t4) {
  46994. 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++) {
  46995. if (p2 < 16)
  46996. u2[p2] = 0 | e4[t4 + p2];
  46997. else {
  46998. 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;
  46999. u2[p2] = g2 + u2[p2 - 7] + y2 + u2[p2 - 16];
  47000. }
  47001. 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];
  47002. d2 = l2, l2 = h3, h3 = a3, a3 = o3 + I2 | 0, o3 = i3, i3 = r3, r3 = s3, s3 = I2 + (w2 + _2) | 0;
  47003. }
  47004. 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;
  47005. }, _doFinalize: function() {
  47006. var t4 = this._data, n3 = t4.words, s3 = 8 * this._nDataBytes, r3 = 8 * t4.sigBytes;
  47007. 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;
  47008. }, clone: function() {
  47009. var e4 = i2.clone.call(this);
  47010. return e4._hash = this._hash.clone(), e4;
  47011. } });
  47012. t3.SHA256 = i2._createHelper(h2), t3.HmacSHA256 = i2._createHmacHelper(h2);
  47013. }(Math), n2.SHA256);
  47014. }), we = _e, Ie = n(function(e2, t2) {
  47015. e2.exports = r.HmacSHA256;
  47016. });
  47017. const ve = () => {
  47018. let e2;
  47019. if (!Promise) {
  47020. e2 = () => {
  47021. }, e2.promise = {};
  47022. const t3 = () => {
  47023. throw new te({ message: 'Your Node runtime does support ES6 Promises. Set "global.Promise" to your preferred implementation of promises.' });
  47024. };
  47025. return Object.defineProperty(e2.promise, "then", { get: t3 }), Object.defineProperty(e2.promise, "catch", { get: t3 }), e2;
  47026. }
  47027. const t2 = new Promise((t3, n2) => {
  47028. e2 = (e3, s2) => e3 ? n2(e3) : t3(s2);
  47029. });
  47030. return e2.promise = t2, e2;
  47031. };
  47032. function Se(e2) {
  47033. return void 0 === e2;
  47034. }
  47035. function Te(e2) {
  47036. return "[object Null]" === Object.prototype.toString.call(e2);
  47037. }
  47038. function be(e2 = "") {
  47039. return e2.replace(/([\s\S]+)\s+(请前往云开发AI小助手查看问题:.*)/, "$1");
  47040. }
  47041. function Ee(e2 = 32) {
  47042. const t2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  47043. let n2 = "";
  47044. for (let s2 = 0; s2 < e2; s2++)
  47045. n2 += t2.charAt(Math.floor(62 * Math.random()));
  47046. return n2;
  47047. }
  47048. var ke;
  47049. function Ae(e2) {
  47050. const t2 = (n2 = e2, "[object Array]" === Object.prototype.toString.call(n2) ? e2 : [e2]);
  47051. var n2;
  47052. for (const e3 of t2) {
  47053. const { isMatch: t3, genAdapter: n3, runtime: s2 } = e3;
  47054. if (t3())
  47055. return { adapter: n3(), runtime: s2 };
  47056. }
  47057. }
  47058. !function(e2) {
  47059. e2.WEB = "web", e2.WX_MP = "wx_mp";
  47060. }(ke || (ke = {}));
  47061. const Pe = { adapter: null, runtime: void 0 }, Ce = ["anonymousUuidKey"];
  47062. class Oe extends ye {
  47063. constructor() {
  47064. super(), Pe.adapter.root.tcbObject || (Pe.adapter.root.tcbObject = {});
  47065. }
  47066. setItem(e2, t2) {
  47067. Pe.adapter.root.tcbObject[e2] = t2;
  47068. }
  47069. getItem(e2) {
  47070. return Pe.adapter.root.tcbObject[e2];
  47071. }
  47072. removeItem(e2) {
  47073. delete Pe.adapter.root.tcbObject[e2];
  47074. }
  47075. clear() {
  47076. delete Pe.adapter.root.tcbObject;
  47077. }
  47078. }
  47079. function xe(e2, t2) {
  47080. switch (e2) {
  47081. case "local":
  47082. return t2.localStorage || new Oe();
  47083. case "none":
  47084. return new Oe();
  47085. default:
  47086. return t2.sessionStorage || new Oe();
  47087. }
  47088. }
  47089. class Ne {
  47090. constructor(e2) {
  47091. if (!this._storage) {
  47092. this._persistence = Pe.adapter.primaryStorage || e2.persistence, this._storage = xe(this._persistence, Pe.adapter);
  47093. 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}`;
  47094. this.keys = { accessTokenKey: t2, accessTokenExpireKey: n2, refreshTokenKey: s2, anonymousUuidKey: r2, loginTypeKey: i2, userInfoKey: c2, deviceIdKey: o2, tokenTypeKey: a2 };
  47095. }
  47096. }
  47097. updatePersistence(e2) {
  47098. if (e2 === this._persistence)
  47099. return;
  47100. const t2 = "local" === this._persistence;
  47101. this._persistence = e2;
  47102. const n2 = xe(e2, Pe.adapter);
  47103. for (const e3 in this.keys) {
  47104. const s2 = this.keys[e3];
  47105. if (t2 && Ce.includes(e3))
  47106. continue;
  47107. const r2 = this._storage.getItem(s2);
  47108. Se(r2) || Te(r2) || (n2.setItem(s2, r2), this._storage.removeItem(s2));
  47109. }
  47110. this._storage = n2;
  47111. }
  47112. setStore(e2, t2, n2) {
  47113. if (!this._storage)
  47114. return;
  47115. const s2 = { version: n2 || "localCachev1", content: t2 }, r2 = JSON.stringify(s2);
  47116. try {
  47117. this._storage.setItem(e2, r2);
  47118. } catch (e3) {
  47119. throw e3;
  47120. }
  47121. }
  47122. getStore(e2, t2) {
  47123. try {
  47124. if (!this._storage)
  47125. return;
  47126. } catch (e3) {
  47127. return "";
  47128. }
  47129. t2 = t2 || "localCachev1";
  47130. const n2 = this._storage.getItem(e2);
  47131. if (!n2)
  47132. return "";
  47133. if (n2.indexOf(t2) >= 0) {
  47134. return JSON.parse(n2).content;
  47135. }
  47136. return "";
  47137. }
  47138. removeStore(e2) {
  47139. this._storage.removeItem(e2);
  47140. }
  47141. }
  47142. const Re = {}, Le = {};
  47143. function Ue(e2) {
  47144. return Re[e2];
  47145. }
  47146. class De {
  47147. constructor(e2, t2) {
  47148. this.data = t2 || null, this.name = e2;
  47149. }
  47150. }
  47151. class Me extends De {
  47152. constructor(e2, t2) {
  47153. super("error", { error: e2, data: t2 }), this.error = e2;
  47154. }
  47155. }
  47156. const qe = new class {
  47157. constructor() {
  47158. this._listeners = {};
  47159. }
  47160. on(e2, t2) {
  47161. return function(e3, t3, n2) {
  47162. n2[e3] = n2[e3] || [], n2[e3].push(t3);
  47163. }(e2, t2, this._listeners), this;
  47164. }
  47165. off(e2, t2) {
  47166. return function(e3, t3, n2) {
  47167. if (n2 && n2[e3]) {
  47168. const s2 = n2[e3].indexOf(t3);
  47169. -1 !== s2 && n2[e3].splice(s2, 1);
  47170. }
  47171. }(e2, t2, this._listeners), this;
  47172. }
  47173. fire(e2, t2) {
  47174. if (e2 instanceof Me)
  47175. return console.error(e2.error), this;
  47176. const n2 = "string" == typeof e2 ? new De(e2, t2 || {}) : e2;
  47177. const s2 = n2.name;
  47178. if (this._listens(s2)) {
  47179. n2.target = this;
  47180. const e3 = this._listeners[s2] ? [...this._listeners[s2]] : [];
  47181. for (const t3 of e3)
  47182. t3.call(this, n2);
  47183. }
  47184. return this;
  47185. }
  47186. _listens(e2) {
  47187. return this._listeners[e2] && this._listeners[e2].length > 0;
  47188. }
  47189. }();
  47190. function Fe(e2, t2) {
  47191. qe.on(e2, t2);
  47192. }
  47193. function Ke(e2, t2 = {}) {
  47194. qe.fire(e2, t2);
  47195. }
  47196. function je(e2, t2) {
  47197. qe.off(e2, t2);
  47198. }
  47199. const $e = "loginStateChanged", Be = "loginStateExpire", We = "loginTypeChanged", He = "anonymousConverted", Je = "refreshAccessToken";
  47200. var ze;
  47201. !function(e2) {
  47202. 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";
  47203. }(ze || (ze = {}));
  47204. class Ve {
  47205. constructor() {
  47206. this._fnPromiseMap = /* @__PURE__ */ new Map();
  47207. }
  47208. async run(e2, t2) {
  47209. let n2 = this._fnPromiseMap.get(e2);
  47210. return n2 || (n2 = new Promise(async (n3, s2) => {
  47211. try {
  47212. await this._runIdlePromise();
  47213. const e3 = t2();
  47214. n3(await e3);
  47215. } catch (e3) {
  47216. s2(e3);
  47217. } finally {
  47218. this._fnPromiseMap.delete(e2);
  47219. }
  47220. }), this._fnPromiseMap.set(e2, n2)), n2;
  47221. }
  47222. _runIdlePromise() {
  47223. return Promise.resolve();
  47224. }
  47225. }
  47226. class Ge {
  47227. constructor(e2) {
  47228. 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"] });
  47229. }
  47230. _getDeviceId() {
  47231. if (this._deviceID)
  47232. return this._deviceID;
  47233. const { deviceIdKey: e2 } = this._cache.keys;
  47234. let t2 = this._cache.getStore(e2);
  47235. return "string" == typeof t2 && t2.length >= 16 && t2.length <= 48 || (t2 = Ee(), this._cache.setStore(e2, t2)), this._deviceID = t2, t2;
  47236. }
  47237. async _request(e2, t2, n2 = {}) {
  47238. const s2 = { "x-request-id": Ee(), "x-device-id": this._getDeviceId() };
  47239. if (n2.withAccessToken) {
  47240. const { tokenTypeKey: e3 } = this._cache.keys, t3 = await this.getAccessToken(), n3 = this._cache.getStore(e3);
  47241. s2.authorization = `${n3} ${t3}`;
  47242. }
  47243. return this._reqClass["get" === n2.method ? "get" : "post"]({ url: `${this._baseURL}${e2}`, data: t2, headers: s2 });
  47244. }
  47245. async _fetchAccessToken() {
  47246. const { loginTypeKey: e2, accessTokenKey: t2, accessTokenExpireKey: n2, tokenTypeKey: s2 } = this._cache.keys, r2 = this._cache.getStore(e2);
  47247. if (r2 && r2 !== ze.ANONYMOUS)
  47248. throw new te({ code: "INVALID_OPERATION", message: "非匿名登录不支持刷新 access token" });
  47249. 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;
  47250. return this._cache.setStore(s2, c2), this._cache.setStore(t2, o2), this._cache.setStore(n2, Date.now() + 1e3 * a2), o2;
  47251. }
  47252. isAccessTokenExpired(e2, t2) {
  47253. let n2 = true;
  47254. return e2 && t2 && (n2 = t2 < Date.now()), n2;
  47255. }
  47256. async getAccessToken() {
  47257. const { accessTokenKey: e2, accessTokenExpireKey: t2 } = this._cache.keys, n2 = this._cache.getStore(e2), s2 = this._cache.getStore(t2);
  47258. return this.isAccessTokenExpired(n2, s2) ? this._fetchAccessToken() : n2;
  47259. }
  47260. async refreshAccessToken() {
  47261. const { accessTokenKey: e2, accessTokenExpireKey: t2, loginTypeKey: n2 } = this._cache.keys;
  47262. return this._cache.removeStore(e2), this._cache.removeStore(t2), this._cache.setStore(n2, ze.ANONYMOUS), this.getAccessToken();
  47263. }
  47264. async getUserInfo() {
  47265. return this._singlePromise.run("getUserInfo", async () => (await this._request("/auth/v1/user/me", {}, { withAccessToken: true, method: "get" })).data);
  47266. }
  47267. }
  47268. 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" };
  47269. function Xe(e2, t2, n2) {
  47270. const s2 = e2[t2];
  47271. e2[t2] = function(t3) {
  47272. const r2 = {}, i2 = {};
  47273. n2.forEach((n3) => {
  47274. const { data: s3, headers: o3 } = n3.call(e2, t3);
  47275. Object.assign(r2, s3), Object.assign(i2, o3);
  47276. });
  47277. const o2 = t3.data;
  47278. return o2 && (() => {
  47279. var e3;
  47280. if (e3 = o2, "[object FormData]" !== Object.prototype.toString.call(e3))
  47281. t3.data = { ...o2, ...r2 };
  47282. else
  47283. for (const e4 in r2)
  47284. o2.append(e4, r2[e4]);
  47285. })(), t3.headers = { ...t3.headers || {}, ...i2 }, s2.call(e2, t3);
  47286. };
  47287. }
  47288. function Ze() {
  47289. const e2 = Math.random().toString(16).slice(2);
  47290. return { data: { seqId: e2 }, headers: { ...Qe, "x-seqid": e2 } };
  47291. }
  47292. class et {
  47293. constructor(e2 = {}) {
  47294. var t2;
  47295. 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]);
  47296. }
  47297. async post(e2) {
  47298. return await this._reqClass.post(e2);
  47299. }
  47300. async upload(e2) {
  47301. return await this._reqClass.upload(e2);
  47302. }
  47303. async download(e2) {
  47304. return await this._reqClass.download(e2);
  47305. }
  47306. async refreshAccessToken() {
  47307. let e2, t2;
  47308. this._refreshAccessTokenPromise || (this._refreshAccessTokenPromise = this._refreshAccessToken());
  47309. try {
  47310. e2 = await this._refreshAccessTokenPromise;
  47311. } catch (e3) {
  47312. t2 = e3;
  47313. }
  47314. if (this._refreshAccessTokenPromise = null, this._shouldRefreshAccessTokenHook = null, t2)
  47315. throw t2;
  47316. return e2;
  47317. }
  47318. async _refreshAccessToken() {
  47319. const { accessTokenKey: e2, accessTokenExpireKey: t2, refreshTokenKey: n2, loginTypeKey: s2, anonymousUuidKey: r2 } = this._cache.keys;
  47320. this._cache.removeStore(e2), this._cache.removeStore(t2);
  47321. let i2 = this._cache.getStore(n2);
  47322. if (!i2)
  47323. throw new te({ message: "未登录CloudBase" });
  47324. const o2 = { refresh_token: i2 }, a2 = await this.request("auth.fetchAccessTokenWithRefreshToken", o2);
  47325. if (a2.data.code) {
  47326. const { code: e3 } = a2.data;
  47327. if ("SIGN_PARAM_INVALID" === e3 || "REFRESH_TOKEN_EXPIRED" === e3 || "INVALID_REFRESH_TOKEN" === e3) {
  47328. if (this._cache.getStore(s2) === ze.ANONYMOUS && "INVALID_REFRESH_TOKEN" === e3) {
  47329. const e4 = this._cache.getStore(r2), t3 = this._cache.getStore(n2), s3 = await this.send("auth.signInAnonymously", { anonymous_uuid: e4, refresh_token: t3 });
  47330. return this.setRefreshToken(s3.refresh_token), this._refreshAccessToken();
  47331. }
  47332. Ke(Be), this._cache.removeStore(n2);
  47333. }
  47334. throw new te({ code: a2.data.code, message: `刷新access token失败:${a2.data.code}` });
  47335. }
  47336. if (a2.data.access_token)
  47337. 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 };
  47338. a2.data.refresh_token && (this._cache.removeStore(n2), this._cache.setStore(n2, a2.data.refresh_token), this._refreshAccessToken());
  47339. }
  47340. async getAccessToken() {
  47341. const { accessTokenKey: e2, accessTokenExpireKey: t2, refreshTokenKey: n2 } = this._cache.keys;
  47342. if (!this._cache.getStore(n2))
  47343. throw new te({ message: "refresh token不存在,登录状态异常" });
  47344. let s2 = this._cache.getStore(e2), r2 = this._cache.getStore(t2), i2 = true;
  47345. return this._shouldRefreshAccessTokenHook && !await this._shouldRefreshAccessTokenHook(s2, r2) && (i2 = false), (!s2 || !r2 || r2 < Date.now()) && i2 ? this.refreshAccessToken() : { accessToken: s2, accessTokenExpire: r2 };
  47346. }
  47347. async request(e2, t2, n2) {
  47348. const s2 = `x-tcb-trace_${this.config.env}`;
  47349. let r2 = "application/x-www-form-urlencoded";
  47350. const i2 = { action: e2, env: this.config.env, dataVersion: "2019-08-16", ...t2 };
  47351. let o2;
  47352. if (-1 === Ye.indexOf(e2) && (this._cache.keys, i2.access_token = await this.oauth.getAccessToken()), "storage.uploadFile" === e2) {
  47353. o2 = new FormData();
  47354. for (let e3 in o2)
  47355. o2.hasOwnProperty(e3) && void 0 !== o2[e3] && o2.append(e3, i2[e3]);
  47356. r2 = "multipart/form-data";
  47357. } else {
  47358. r2 = "application/json", o2 = {};
  47359. for (let e3 in i2)
  47360. void 0 !== i2[e3] && (o2[e3] = i2[e3]);
  47361. }
  47362. let a2 = { headers: { "content-type": r2 } };
  47363. n2 && n2.timeout && (a2.timeout = n2.timeout), n2 && n2.onUploadProgress && (a2.onUploadProgress = n2.onUploadProgress);
  47364. const c2 = this._localCache.getStore(s2);
  47365. c2 && (a2.headers["X-TCB-Trace"] = c2);
  47366. const { parse: u2, inQuery: h2, search: l2 } = t2;
  47367. let d2 = { env: this.config.env };
  47368. u2 && (d2.parse = true), h2 && (d2 = { ...h2, ...d2 });
  47369. let p2 = function(e3, t3, n3 = {}) {
  47370. const s3 = /\?/.test(t3);
  47371. let r3 = "";
  47372. for (let e4 in n3)
  47373. "" === r3 ? !s3 && (t3 += "?") : r3 += "&", r3 += `${e4}=${encodeURIComponent(n3[e4])}`;
  47374. return /^http(s)?\:\/\//.test(t3 += r3) ? t3 : `${e3}${t3}`;
  47375. }(ge, "//tcb-api.tencentcloudapi.com/web", d2);
  47376. l2 && (p2 += l2);
  47377. const f2 = await this.post({ url: p2, data: o2, ...a2 }), g2 = f2.header && f2.header["x-tcb-trace"];
  47378. if (g2 && this._localCache.setStore(s2, g2), 200 !== Number(f2.status) && 200 !== Number(f2.statusCode) || !f2.data)
  47379. throw new te({ code: "NETWORK_ERROR", message: "network request error" });
  47380. return f2;
  47381. }
  47382. async send(e2, t2 = {}, n2 = {}) {
  47383. const s2 = await this.request(e2, t2, { ...n2, onUploadProgress: t2.onUploadProgress });
  47384. if (("ACCESS_TOKEN_DISABLED" === s2.data.code || "ACCESS_TOKEN_EXPIRED" === s2.data.code) && -1 === Ye.indexOf(e2)) {
  47385. await this.oauth.refreshAccessToken();
  47386. const s3 = await this.request(e2, t2, { ...n2, onUploadProgress: t2.onUploadProgress });
  47387. if (s3.data.code)
  47388. throw new te({ code: s3.data.code, message: be(s3.data.message) });
  47389. return s3.data;
  47390. }
  47391. if (s2.data.code)
  47392. throw new te({ code: s2.data.code, message: be(s2.data.message) });
  47393. return s2.data;
  47394. }
  47395. setRefreshToken(e2) {
  47396. const { accessTokenKey: t2, accessTokenExpireKey: n2, refreshTokenKey: s2 } = this._cache.keys;
  47397. this._cache.removeStore(t2), this._cache.removeStore(n2), this._cache.setStore(s2, e2);
  47398. }
  47399. }
  47400. const tt = {};
  47401. function nt(e2) {
  47402. return tt[e2];
  47403. }
  47404. class st {
  47405. constructor(e2) {
  47406. this.config = e2, this._cache = Ue(e2.env), this._request = nt(e2.env);
  47407. }
  47408. setRefreshToken(e2) {
  47409. const { accessTokenKey: t2, accessTokenExpireKey: n2, refreshTokenKey: s2 } = this._cache.keys;
  47410. this._cache.removeStore(t2), this._cache.removeStore(n2), this._cache.setStore(s2, e2);
  47411. }
  47412. setAccessToken(e2, t2) {
  47413. const { accessTokenKey: n2, accessTokenExpireKey: s2 } = this._cache.keys;
  47414. this._cache.setStore(n2, e2), this._cache.setStore(s2, t2);
  47415. }
  47416. async refreshUserInfo() {
  47417. const { data: e2 } = await this._request.send("auth.getUserInfo", {});
  47418. return this.setLocalUserInfo(e2), e2;
  47419. }
  47420. setLocalUserInfo(e2) {
  47421. const { userInfoKey: t2 } = this._cache.keys;
  47422. this._cache.setStore(t2, e2);
  47423. }
  47424. }
  47425. class rt {
  47426. constructor(e2) {
  47427. if (!e2)
  47428. throw new te({ code: "PARAM_ERROR", message: "envId is not defined" });
  47429. this._envId = e2, this._cache = Ue(this._envId), this._request = nt(this._envId), this.setUserInfo();
  47430. }
  47431. linkWithTicket(e2) {
  47432. if ("string" != typeof e2)
  47433. throw new te({ code: "PARAM_ERROR", message: "ticket must be string" });
  47434. return this._request.send("auth.linkWithTicket", { ticket: e2 });
  47435. }
  47436. linkWithRedirect(e2) {
  47437. e2.signInWithRedirect();
  47438. }
  47439. updatePassword(e2, t2) {
  47440. return this._request.send("auth.updatePassword", { oldPassword: t2, newPassword: e2 });
  47441. }
  47442. updateEmail(e2) {
  47443. return this._request.send("auth.updateEmail", { newEmail: e2 });
  47444. }
  47445. updateUsername(e2) {
  47446. if ("string" != typeof e2)
  47447. throw new te({ code: "PARAM_ERROR", message: "username must be a string" });
  47448. return this._request.send("auth.updateUsername", { username: e2 });
  47449. }
  47450. async getLinkedUidList() {
  47451. const { data: e2 } = await this._request.send("auth.getLinkedUidList", {});
  47452. let t2 = false;
  47453. const { users: n2 } = e2;
  47454. return n2.forEach((e3) => {
  47455. e3.wxOpenId && e3.wxPublicId && (t2 = true);
  47456. }), { users: n2, hasPrimaryUid: t2 };
  47457. }
  47458. setPrimaryUid(e2) {
  47459. return this._request.send("auth.setPrimaryUid", { uid: e2 });
  47460. }
  47461. unlink(e2) {
  47462. return this._request.send("auth.unlink", { platform: e2 });
  47463. }
  47464. async update(e2) {
  47465. 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 });
  47466. this.setLocalUserInfo(a2);
  47467. }
  47468. async refresh() {
  47469. const e2 = await this._request.oauth.getUserInfo();
  47470. return this.setLocalUserInfo(e2), e2;
  47471. }
  47472. setUserInfo() {
  47473. const { userInfoKey: e2 } = this._cache.keys, t2 = this._cache.getStore(e2);
  47474. ["uid", "loginType", "openid", "wxOpenId", "wxPublicId", "unionId", "qqMiniOpenId", "email", "hasPassword", "customUserId", "nickName", "gender", "avatarUrl"].forEach((e3) => {
  47475. this[e3] = t2[e3];
  47476. }), this.location = { country: t2.country, province: t2.province, city: t2.city };
  47477. }
  47478. setLocalUserInfo(e2) {
  47479. const { userInfoKey: t2 } = this._cache.keys;
  47480. this._cache.setStore(t2, e2), this.setUserInfo();
  47481. }
  47482. }
  47483. class it {
  47484. constructor(e2) {
  47485. if (!e2)
  47486. throw new te({ code: "PARAM_ERROR", message: "envId is not defined" });
  47487. this._cache = Ue(e2);
  47488. 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);
  47489. this.credential = { refreshToken: r2, accessToken: i2, accessTokenExpire: o2 }, this.user = new rt(e2);
  47490. }
  47491. get isAnonymousAuth() {
  47492. return this.loginType === ze.ANONYMOUS;
  47493. }
  47494. get isCustomAuth() {
  47495. return this.loginType === ze.CUSTOM;
  47496. }
  47497. get isWeixinAuth() {
  47498. return this.loginType === ze.WECHAT || this.loginType === ze.WECHAT_OPEN || this.loginType === ze.WECHAT_PUBLIC;
  47499. }
  47500. get loginType() {
  47501. return this._cache.getStore(this._cache.keys.loginTypeKey);
  47502. }
  47503. }
  47504. class ot extends st {
  47505. async signIn() {
  47506. this._cache.updatePersistence("local"), await this._request.oauth.getAccessToken(), Ke($e), Ke(We, { env: this.config.env, loginType: ze.ANONYMOUS, persistence: "local" });
  47507. const e2 = new it(this.config.env);
  47508. return await e2.user.refresh(), e2;
  47509. }
  47510. async linkAndRetrieveDataWithTicket(e2) {
  47511. 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 });
  47512. if (i2.refresh_token)
  47513. 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 } };
  47514. throw new te({ message: "匿名转化失败" });
  47515. }
  47516. _setAnonymousUUID(e2) {
  47517. const { anonymousUuidKey: t2, loginTypeKey: n2 } = this._cache.keys;
  47518. this._cache.removeStore(t2), this._cache.setStore(t2, e2), this._cache.setStore(n2, ze.ANONYMOUS);
  47519. }
  47520. _clearAnonymousUUID() {
  47521. this._cache.removeStore(this._cache.keys.anonymousUuidKey);
  47522. }
  47523. }
  47524. class at extends st {
  47525. async signIn(e2) {
  47526. if ("string" != typeof e2)
  47527. throw new te({ code: "PARAM_ERROR", message: "ticket must be a string" });
  47528. const { refreshTokenKey: t2 } = this._cache.keys, n2 = await this._request.send("auth.signInWithTicket", { ticket: e2, refresh_token: this._cache.getStore(t2) || "" });
  47529. if (n2.refresh_token)
  47530. 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);
  47531. throw new te({ message: "自定义登录失败" });
  47532. }
  47533. }
  47534. class ct extends st {
  47535. async signIn(e2, t2) {
  47536. if ("string" != typeof e2)
  47537. throw new te({ code: "PARAM_ERROR", message: "email must be a string" });
  47538. 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;
  47539. if (r2)
  47540. 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);
  47541. throw s2.code ? new te({ code: s2.code, message: `邮箱登录失败: ${s2.message}` }) : new te({ message: "邮箱登录失败" });
  47542. }
  47543. async activate(e2) {
  47544. return this._request.send("auth.activateEndUserMail", { token: e2 });
  47545. }
  47546. async resetPasswordWithToken(e2, t2) {
  47547. return this._request.send("auth.resetPasswordWithToken", { token: e2, newPassword: t2 });
  47548. }
  47549. }
  47550. class ut extends st {
  47551. async signIn(e2, t2) {
  47552. if ("string" != typeof e2)
  47553. throw new te({ code: "PARAM_ERROR", message: "username must be a string" });
  47554. "string" != typeof t2 && (t2 = "", console.warn("password is empty"));
  47555. 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;
  47556. if (r2)
  47557. 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);
  47558. throw s2.code ? new te({ code: s2.code, message: `用户名密码登录失败: ${s2.message}` }) : new te({ message: "用户名密码登录失败" });
  47559. }
  47560. }
  47561. class ht {
  47562. constructor(e2) {
  47563. 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);
  47564. }
  47565. get currentUser() {
  47566. const e2 = this.hasLoginState();
  47567. return e2 && e2.user || null;
  47568. }
  47569. get loginType() {
  47570. return this._cache.getStore(this._cache.keys.loginTypeKey);
  47571. }
  47572. anonymousAuthProvider() {
  47573. return new ot(this.config);
  47574. }
  47575. customAuthProvider() {
  47576. return new at(this.config);
  47577. }
  47578. emailAuthProvider() {
  47579. return new ct(this.config);
  47580. }
  47581. usernameAuthProvider() {
  47582. return new ut(this.config);
  47583. }
  47584. async signInAnonymously() {
  47585. return new ot(this.config).signIn();
  47586. }
  47587. async signInWithEmailAndPassword(e2, t2) {
  47588. return new ct(this.config).signIn(e2, t2);
  47589. }
  47590. signInWithUsernameAndPassword(e2, t2) {
  47591. return new ut(this.config).signIn(e2, t2);
  47592. }
  47593. async linkAndRetrieveDataWithTicket(e2) {
  47594. this._anonymousAuthProvider || (this._anonymousAuthProvider = new ot(this.config)), Fe(He, this._onAnonymousConverted);
  47595. return await this._anonymousAuthProvider.linkAndRetrieveDataWithTicket(e2);
  47596. }
  47597. async signOut() {
  47598. if (this.loginType === ze.ANONYMOUS)
  47599. throw new te({ message: "匿名用户不支持登出操作" });
  47600. const { refreshTokenKey: e2, accessTokenKey: t2, accessTokenExpireKey: n2 } = this._cache.keys, s2 = this._cache.getStore(e2);
  47601. if (!s2)
  47602. return;
  47603. const r2 = await this._request.send("auth.logout", { refresh_token: s2 });
  47604. 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;
  47605. }
  47606. async signUpWithEmailAndPassword(e2, t2) {
  47607. return this._request.send("auth.signUpWithEmailAndPassword", { email: e2, password: t2 });
  47608. }
  47609. async sendPasswordResetEmail(e2) {
  47610. return this._request.send("auth.sendPasswordResetEmail", { email: e2 });
  47611. }
  47612. onLoginStateChanged(e2) {
  47613. Fe($e, () => {
  47614. const t3 = this.hasLoginState();
  47615. e2.call(this, t3);
  47616. });
  47617. const t2 = this.hasLoginState();
  47618. e2.call(this, t2);
  47619. }
  47620. onLoginStateExpired(e2) {
  47621. Fe(Be, e2.bind(this));
  47622. }
  47623. onAccessTokenRefreshed(e2) {
  47624. Fe(Je, e2.bind(this));
  47625. }
  47626. onAnonymousConverted(e2) {
  47627. Fe(He, e2.bind(this));
  47628. }
  47629. onLoginTypeChanged(e2) {
  47630. Fe(We, () => {
  47631. const t2 = this.hasLoginState();
  47632. e2.call(this, t2);
  47633. });
  47634. }
  47635. async getAccessToken() {
  47636. return { accessToken: (await this._request.getAccessToken()).accessToken, env: this.config.env };
  47637. }
  47638. hasLoginState() {
  47639. const { accessTokenKey: e2, accessTokenExpireKey: t2 } = this._cache.keys, n2 = this._cache.getStore(e2), s2 = this._cache.getStore(t2);
  47640. return this._request.oauth.isAccessTokenExpired(n2, s2) ? null : new it(this.config.env);
  47641. }
  47642. async isUsernameRegistered(e2) {
  47643. if ("string" != typeof e2)
  47644. throw new te({ code: "PARAM_ERROR", message: "username must be a string" });
  47645. const { data: t2 } = await this._request.send("auth.isUsernameRegistered", { username: e2 });
  47646. return t2 && t2.isRegistered;
  47647. }
  47648. getLoginState() {
  47649. return Promise.resolve(this.hasLoginState());
  47650. }
  47651. async signInWithTicket(e2) {
  47652. return new at(this.config).signIn(e2);
  47653. }
  47654. shouldRefreshAccessToken(e2) {
  47655. this._request._shouldRefreshAccessTokenHook = e2.bind(this);
  47656. }
  47657. getUserInfo() {
  47658. return this._request.send("auth.getUserInfo", {}).then((e2) => e2.code ? e2 : { ...e2.data, requestId: e2.seqId });
  47659. }
  47660. getAuthHeader() {
  47661. const { refreshTokenKey: e2, accessTokenKey: t2 } = this._cache.keys, n2 = this._cache.getStore(e2);
  47662. return { "x-cloudbase-credentials": this._cache.getStore(t2) + "/@@/" + n2 };
  47663. }
  47664. _onAnonymousConverted(e2) {
  47665. const { env: t2 } = e2.data;
  47666. t2 === this.config.env && this._cache.updatePersistence(this.config.persistence);
  47667. }
  47668. _onLoginTypeChanged(e2) {
  47669. const { loginType: t2, persistence: n2, env: s2 } = e2.data;
  47670. s2 === this.config.env && (this._cache.updatePersistence(n2), this._cache.setStore(this._cache.keys.loginTypeKey, t2));
  47671. }
  47672. }
  47673. const lt = function(e2, t2) {
  47674. t2 = t2 || ve();
  47675. const n2 = nt(this.config.env), { cloudPath: s2, filePath: r2, onUploadProgress: i2, fileType: o2 = "image" } = e2;
  47676. return n2.send("storage.getUploadMetadata", { path: s2 }).then((e3) => {
  47677. 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 };
  47678. n2.upload({ url: a2, data: p2, file: r2, name: s2, fileType: o2, onUploadProgress: i2 }).then((e4) => {
  47679. 201 === e4.statusCode ? t2(null, { fileID: h2, requestId: d2 }) : t2(new te({ code: "STORAGE_REQUEST_FAIL", message: `STORAGE_REQUEST_FAIL: ${e4.data}` }));
  47680. }).catch((e4) => {
  47681. t2(e4);
  47682. });
  47683. }).catch((e3) => {
  47684. t2(e3);
  47685. }), t2.promise;
  47686. }, dt = function(e2, t2) {
  47687. t2 = t2 || ve();
  47688. const n2 = nt(this.config.env), { cloudPath: s2 } = e2;
  47689. return n2.send("storage.getUploadMetadata", { path: s2 }).then((e3) => {
  47690. t2(null, e3);
  47691. }).catch((e3) => {
  47692. t2(e3);
  47693. }), t2.promise;
  47694. }, pt = function({ fileList: e2 }, t2) {
  47695. if (t2 = t2 || ve(), !e2 || !Array.isArray(e2))
  47696. return { code: "INVALID_PARAM", message: "fileList必须是非空的数组" };
  47697. for (let t3 of e2)
  47698. if (!t3 || "string" != typeof t3)
  47699. return { code: "INVALID_PARAM", message: "fileList的元素必须是非空的字符串" };
  47700. const n2 = { fileid_list: e2 };
  47701. return nt(this.config.env).send("storage.batchDeleteFile", n2).then((e3) => {
  47702. e3.code ? t2(null, e3) : t2(null, { fileList: e3.data.delete_list, requestId: e3.requestId });
  47703. }).catch((e3) => {
  47704. t2(e3);
  47705. }), t2.promise;
  47706. }, ft = function({ fileList: e2 }, t2) {
  47707. t2 = t2 || ve(), e2 && Array.isArray(e2) || t2(null, { code: "INVALID_PARAM", message: "fileList必须是非空的数组" });
  47708. let n2 = [];
  47709. for (let s3 of e2)
  47710. "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的元素必须是字符串" });
  47711. const s2 = { file_list: n2 };
  47712. return nt(this.config.env).send("storage.batchGetDownloadUrl", s2).then((e3) => {
  47713. e3.code ? t2(null, e3) : t2(null, { fileList: e3.data.download_list, requestId: e3.requestId });
  47714. }).catch((e3) => {
  47715. t2(e3);
  47716. }), t2.promise;
  47717. }, gt = async function({ fileID: e2 }, t2) {
  47718. const n2 = (await ft.call(this, { fileList: [{ fileID: e2, maxAge: 600 }] })).fileList[0];
  47719. if ("SUCCESS" !== n2.code)
  47720. return t2 ? t2(n2) : new Promise((e3) => {
  47721. e3(n2);
  47722. });
  47723. const s2 = nt(this.config.env);
  47724. let r2 = n2.download_url;
  47725. if (r2 = encodeURI(r2), !t2)
  47726. return s2.download({ url: r2 });
  47727. t2(await s2.download({ url: r2 }));
  47728. }, mt = function({ name: e2, data: t2, query: n2, parse: s2, search: r2, timeout: i2 }, o2) {
  47729. const a2 = o2 || ve();
  47730. let c2;
  47731. try {
  47732. c2 = t2 ? JSON.stringify(t2) : "";
  47733. } catch (e3) {
  47734. return Promise.reject(e3);
  47735. }
  47736. if (!e2)
  47737. return Promise.reject(new te({ code: "PARAM_ERROR", message: "函数名不能为空" }));
  47738. const u2 = { inQuery: n2, parse: s2, search: r2, function_name: e2, request_data: c2 };
  47739. return nt(this.config.env).send("functions.invokeFunction", u2, { timeout: i2 }).then((e3) => {
  47740. if (e3.code)
  47741. a2(null, e3);
  47742. else {
  47743. let t3 = e3.data.response_data;
  47744. if (s2)
  47745. a2(null, { result: t3, requestId: e3.requestId });
  47746. else
  47747. try {
  47748. t3 = JSON.parse(e3.data.response_data), a2(null, { result: t3, requestId: e3.requestId });
  47749. } catch (e4) {
  47750. a2(new te({ message: "response data must be json" }));
  47751. }
  47752. }
  47753. return a2.promise;
  47754. }).catch((e3) => {
  47755. a2(e3);
  47756. }), a2.promise;
  47757. }, yt = { timeout: 15e3, persistence: "session" }, _t = 6e5, wt = {};
  47758. class It {
  47759. constructor(e2) {
  47760. this.config = e2 || this.config, this.authObj = void 0;
  47761. }
  47762. init(e2) {
  47763. switch (Pe.adapter || (this.requestClient = new Pe.adapter.reqClass({ timeout: e2.timeout || 5e3, timeoutMsg: `请求在${(e2.timeout || 5e3) / 1e3}s内未完成,已中断` })), this.config = { ...yt, ...e2 }, true) {
  47764. case this.config.timeout > _t:
  47765. console.warn("timeout大于可配置上限[10分钟],已重置为上限数值"), this.config.timeout = _t;
  47766. break;
  47767. case this.config.timeout < 100:
  47768. console.warn("timeout小于可配置下限[100ms],已重置为下限数值"), this.config.timeout = 100;
  47769. }
  47770. return new It(this.config);
  47771. }
  47772. auth({ persistence: e2 } = {}) {
  47773. if (this.authObj)
  47774. return this.authObj;
  47775. const t2 = e2 || Pe.adapter.primaryStorage || yt.persistence;
  47776. var n2;
  47777. return t2 !== this.config.persistence && (this.config.persistence = t2), function(e3) {
  47778. const { env: t3 } = e3;
  47779. Re[t3] = new Ne(e3), Le[t3] = new Ne({ ...e3, persistence: "local" });
  47780. }(this.config), n2 = this.config, tt[n2.env] = new et(n2), this.authObj = new ht(this.config), this.authObj;
  47781. }
  47782. on(e2, t2) {
  47783. return Fe.apply(this, [e2, t2]);
  47784. }
  47785. off(e2, t2) {
  47786. return je.apply(this, [e2, t2]);
  47787. }
  47788. callFunction(e2, t2) {
  47789. return mt.apply(this, [e2, t2]);
  47790. }
  47791. deleteFile(e2, t2) {
  47792. return pt.apply(this, [e2, t2]);
  47793. }
  47794. getTempFileURL(e2, t2) {
  47795. return ft.apply(this, [e2, t2]);
  47796. }
  47797. downloadFile(e2, t2) {
  47798. return gt.apply(this, [e2, t2]);
  47799. }
  47800. uploadFile(e2, t2) {
  47801. return lt.apply(this, [e2, t2]);
  47802. }
  47803. getUploadMetadata(e2, t2) {
  47804. return dt.apply(this, [e2, t2]);
  47805. }
  47806. registerExtension(e2) {
  47807. wt[e2.name] = e2;
  47808. }
  47809. async invokeExtension(e2, t2) {
  47810. const n2 = wt[e2];
  47811. if (!n2)
  47812. throw new te({ message: `扩展${e2} 必须先注册` });
  47813. return await n2.invoke(t2, this);
  47814. }
  47815. useAdapters(e2) {
  47816. const { adapter: t2, runtime: n2 } = Ae(e2) || {};
  47817. t2 && (Pe.adapter = t2), n2 && (Pe.runtime = n2);
  47818. }
  47819. }
  47820. var vt = new It();
  47821. function St(e2, t2, n2) {
  47822. void 0 === n2 && (n2 = {});
  47823. var s2 = /\?/.test(t2), r2 = "";
  47824. for (var i2 in n2)
  47825. "" === r2 ? !s2 && (t2 += "?") : r2 += "&", r2 += i2 + "=" + encodeURIComponent(n2[i2]);
  47826. return /^http(s)?:\/\//.test(t2 += r2) ? t2 : "" + e2 + t2;
  47827. }
  47828. class Tt {
  47829. get(e2) {
  47830. const { url: t2, data: n2, headers: s2, timeout: r2 } = e2;
  47831. return new Promise((e3, i2) => {
  47832. ne.request({ url: St("https:", t2), data: n2, method: "GET", header: s2, timeout: r2, success(t3) {
  47833. e3(t3);
  47834. }, fail(e4) {
  47835. i2(e4);
  47836. } });
  47837. });
  47838. }
  47839. post(e2) {
  47840. const { url: t2, data: n2, headers: s2, timeout: r2 } = e2;
  47841. return new Promise((e3, i2) => {
  47842. ne.request({ url: St("https:", t2), data: n2, method: "POST", header: s2, timeout: r2, success(t3) {
  47843. e3(t3);
  47844. }, fail(e4) {
  47845. i2(e4);
  47846. } });
  47847. });
  47848. }
  47849. upload(e2) {
  47850. return new Promise((t2, n2) => {
  47851. 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) {
  47852. const n3 = { statusCode: e3.statusCode, data: e3.data || {} };
  47853. 200 === e3.statusCode && i2.success_action_status && (n3.statusCode = parseInt(i2.success_action_status, 10)), t2(n3);
  47854. }, fail(e3) {
  47855. n2(new Error(e3.errMsg || "uploadFile:fail"));
  47856. } });
  47857. "function" == typeof e2.onUploadProgress && c2 && "function" == typeof c2.onProgressUpdate && c2.onProgressUpdate((t3) => {
  47858. e2.onUploadProgress({ loaded: t3.totalBytesSent, total: t3.totalBytesExpectedToSend });
  47859. });
  47860. });
  47861. }
  47862. }
  47863. const bt = { setItem(e2, t2) {
  47864. ne.setStorageSync(e2, t2);
  47865. }, getItem: (e2) => ne.getStorageSync(e2), removeItem(e2) {
  47866. ne.removeStorageSync(e2);
  47867. }, clear() {
  47868. ne.clearStorageSync();
  47869. } };
  47870. var Et = { genAdapter: function() {
  47871. return { root: {}, reqClass: Tt, localStorage: bt, primaryStorage: "local" };
  47872. }, isMatch: function() {
  47873. return true;
  47874. }, runtime: "uni_app" };
  47875. vt.useAdapters(Et);
  47876. const kt = vt, At = kt.init;
  47877. kt.init = function(e2) {
  47878. e2.env = e2.spaceId;
  47879. const t2 = At.call(this, e2);
  47880. t2.config.provider = "tencent", t2.config.spaceId = e2.spaceId;
  47881. const n2 = t2.auth;
  47882. return t2.auth = function(e3) {
  47883. const t3 = n2.call(this, e3);
  47884. return ["linkAndRetrieveDataWithTicket", "signInAnonymously", "signOut", "getAccessToken", "getLoginState", "signInWithTicket", "getUserInfo"].forEach((e4) => {
  47885. var n3;
  47886. t3[e4] = (n3 = t3[e4], function(e5) {
  47887. e5 = e5 || {};
  47888. const { success: t4, fail: s2, complete: r2 } = ee(e5);
  47889. if (!(t4 || s2 || r2))
  47890. return n3.call(this, e5);
  47891. n3.call(this, e5).then((e6) => {
  47892. t4 && t4(e6), r2 && r2(e6);
  47893. }, (e6) => {
  47894. s2 && s2(e6), r2 && r2(e6);
  47895. });
  47896. }).bind(t3);
  47897. }), t3;
  47898. }, t2.customAuth = t2.auth, t2;
  47899. };
  47900. var Pt = kt;
  47901. async function Ct(e2, t2) {
  47902. const n2 = `http://${e2}:${t2}/system/ping`;
  47903. try {
  47904. const e3 = await (s2 = { url: n2, timeout: 500 }, new Promise((e4, t3) => {
  47905. ne.request({ ...s2, success(t4) {
  47906. e4(t4);
  47907. }, fail(e5) {
  47908. t3(e5);
  47909. } });
  47910. }));
  47911. return !(!e3.data || 0 !== e3.data.code);
  47912. } catch (e3) {
  47913. return false;
  47914. }
  47915. var s2;
  47916. }
  47917. async function Ot(e2, t2) {
  47918. let n2;
  47919. for (let s2 = 0; s2 < e2.length; s2++) {
  47920. const r2 = e2[s2];
  47921. if (await Ct(r2, t2)) {
  47922. n2 = r2;
  47923. break;
  47924. }
  47925. }
  47926. return { address: n2, port: t2 };
  47927. }
  47928. 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" };
  47929. var Nt = class {
  47930. constructor(e2) {
  47931. if (["spaceId", "clientSecret"].forEach((t2) => {
  47932. if (!Object.prototype.hasOwnProperty.call(e2, t2))
  47933. throw new Error(`${t2} required`);
  47934. }), !e2.endpoint)
  47935. throw new Error("集群空间未配置ApiEndpoint,配置后需要重新关联服务空间后生效");
  47936. 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;
  47937. }
  47938. async request(e2, t2 = true) {
  47939. const n2 = t2;
  47940. return e2 = n2 ? await this.setupLocalRequest(e2) : this.setupRequest(e2), Promise.resolve().then(() => n2 ? this.requestLocal(e2) : de.wrappedRequest(e2, this.adapter.request));
  47941. }
  47942. requestLocal(e2) {
  47943. return new Promise((t2, n2) => {
  47944. this.adapter.request(Object.assign(e2, { complete(e3) {
  47945. if (e3 || (e3 = {}), !e3.statusCode || e3.statusCode >= 400) {
  47946. const t3 = e3.data && e3.data.code || "SYS_ERR", s2 = e3.data && e3.data.message || "request:fail";
  47947. return n2(new te({ code: t3, message: s2 }));
  47948. }
  47949. t2({ success: true, result: e3.data });
  47950. } }));
  47951. });
  47952. }
  47953. setupRequest(e2) {
  47954. const t2 = Object.assign({}, e2, { spaceId: this.config.spaceId, timestamp: Date.now() }), n2 = { "Content-Type": "application/json" };
  47955. n2["x-serverless-sign"] = de.sign(t2, this.config.clientSecret);
  47956. const s2 = le();
  47957. n2["x-client-info"] = encodeURIComponent(JSON.stringify(s2));
  47958. const { token: r2 } = re();
  47959. return n2["x-client-token"] = r2, { url: this.config.requestUrl, method: "POST", data: t2, dataType: "json", header: JSON.parse(JSON.stringify(n2)) };
  47960. }
  47961. async setupLocalRequest(e2) {
  47962. 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);
  47963. return { url: `http://${o2}:${i2}/${xt[e2.method]}`, method: "POST", data: s2, dataType: "json", header: JSON.parse(JSON.stringify({ "Content-Type": "application/json" })) };
  47964. }
  47965. callFunction(e2) {
  47966. const t2 = { method: "serverless.function.runtime.invoke", params: JSON.stringify({ functionTarget: e2.name, functionArgs: e2.data || {} }) };
  47967. return this.request(t2, false);
  47968. }
  47969. getUploadFileOptions(e2) {
  47970. const t2 = { method: "serverless.file.resource.generateProximalSign", params: JSON.stringify(e2) };
  47971. return this.request(t2);
  47972. }
  47973. reportUploadFile(e2) {
  47974. const t2 = { method: "serverless.file.resource.report", params: JSON.stringify(e2) };
  47975. return this.request(t2);
  47976. }
  47977. uploadFile({ filePath: e2, cloudPath: t2, fileType: n2 = "image", onUploadProgress: s2 }) {
  47978. if (!t2)
  47979. throw new te({ code: "CLOUDPATH_REQUIRED", message: "cloudPath不可为空" });
  47980. let r2;
  47981. return this.getUploadFileOptions({ cloudPath: t2 }).then((t3) => {
  47982. const { url: i2, formData: o2, name: a2 } = t3.result;
  47983. return r2 = t3.result.fileUrl, new Promise((t4, r3) => {
  47984. const c2 = this.adapter.uploadFile({ url: i2, formData: o2, name: a2, filePath: e2, fileType: n2, success(e3) {
  47985. e3 && e3.statusCode < 400 ? t4(e3) : r3(new te({ code: "UPLOAD_FAILED", message: "文件上传失败" }));
  47986. }, fail(e3) {
  47987. r3(new te({ code: e3.code || "UPLOAD_FAILED", message: e3.message || e3.errMsg || "文件上传失败" }));
  47988. } });
  47989. "function" == typeof s2 && c2 && "function" == typeof c2.onProgressUpdate && c2.onProgressUpdate((e3) => {
  47990. s2({ loaded: e3.totalBytesSent, total: e3.totalBytesExpectedToSend });
  47991. });
  47992. });
  47993. }).then(() => this.reportUploadFile({ cloudPath: t2 })).then((t3) => new Promise((n3, s3) => {
  47994. t3.success ? n3({ success: true, filePath: e2, fileID: r2 }) : s3(new te({ code: "UPLOAD_FAILED", message: "文件上传失败" }));
  47995. }));
  47996. }
  47997. deleteFile({ fileList: e2 }) {
  47998. const t2 = { method: "serverless.file.resource.delete", params: JSON.stringify({ fileList: e2 }) };
  47999. return this.request(t2).then((e3) => {
  48000. if (e3.success)
  48001. return e3.result;
  48002. throw new te({ code: "DELETE_FILE_FAILED", message: "删除文件失败" });
  48003. });
  48004. }
  48005. getTempFileURL({ fileList: e2, maxAge: t2 } = {}) {
  48006. if (!Array.isArray(e2) || 0 === e2.length)
  48007. throw new te({ code: "INVALID_PARAM", message: "fileList的元素必须是非空的字符串" });
  48008. const n2 = { method: "serverless.file.resource.getTempFileURL", params: JSON.stringify({ fileList: e2, maxAge: t2 }) };
  48009. return this.request(n2).then((e3) => {
  48010. if (e3.success)
  48011. return { fileList: e3.result.fileList.map((e4) => ({ fileID: e4.fileID, tempFileURL: e4.tempFileURL })) };
  48012. throw new te({ code: "GET_TEMP_FILE_URL_FAILED", message: "获取临时文件链接失败" });
  48013. });
  48014. }
  48015. };
  48016. var Rt = { init(e2) {
  48017. const t2 = new Nt(e2), n2 = { signInAnonymously: function() {
  48018. return Promise.resolve();
  48019. }, getLoginState: function() {
  48020. return Promise.resolve(false);
  48021. } };
  48022. return t2.auth = function() {
  48023. return n2;
  48024. }, t2.customAuth = t2.auth, t2;
  48025. } }, Lt = n(function(e2, t2) {
  48026. e2.exports = r.enc.Hex;
  48027. });
  48028. function Ut() {
  48029. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(e2) {
  48030. var t2 = 16 * Math.random() | 0;
  48031. return ("x" === e2 ? t2 : 3 & t2 | 8).toString(16);
  48032. });
  48033. }
  48034. function Dt(e2 = "", t2 = {}) {
  48035. 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) {
  48036. const t3 = "HMAC-SHA256", n3 = e3.signedHeaders.join(";"), s3 = e3.signedHeaders.map((t4) => `${t4.toLowerCase()}:${e3.headers[t4]}
  48037. `).join(""), r3 = we(e3.body).toString(Lt), i3 = `${e3.method.toUpperCase()}
  48038. ${e3.path}
  48039. ${e3.query}
  48040. ${s3}
  48041. ${n3}
  48042. ${r3}
  48043. `, o3 = we(i3).toString(Lt), a3 = `${t3}
  48044. ${e3.timestamp}
  48045. ${o3}
  48046. `, c3 = Ie(a3, e3.secretKey).toString(Lt);
  48047. return `${t3} Credential=${e3.secretId}, SignedHeaders=${n3}, Signature=${c3}`;
  48048. }({ path: d2, query: p2, method: r2, headers: h2, timestamp: c2, body: JSON.stringify(n2), secretId: a2.accessKey, secretKey: a2.secretKey, signedHeaders: l2.sort() });
  48049. return { url: `${a2.endpoint}${e2}`, headers: Object.assign({}, h2, { Authorization: f2 }) };
  48050. }
  48051. function Mt({ url: e2, data: t2, method: n2 = "POST", headers: s2 = {}, timeout: r2 }) {
  48052. return new Promise((i2, o2) => {
  48053. ne.request({ url: e2, method: n2, data: "object" == typeof t2 ? JSON.stringify(t2) : t2, header: s2, dataType: "json", timeout: r2, complete: (e3 = {}) => {
  48054. const t3 = s2["x-trace-id"] || "";
  48055. if (!e3.statusCode || e3.statusCode >= 400) {
  48056. const { message: n3, errMsg: s3, trace_id: r3 } = e3.data || {};
  48057. return o2(new te({ code: "SYS_ERR", message: n3 || s3 || "request:fail", requestId: r3 || t3 }));
  48058. }
  48059. i2({ status: e3.statusCode, data: e3.data, headers: e3.header, requestId: t3 });
  48060. } });
  48061. });
  48062. }
  48063. function qt(e2, t2) {
  48064. 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 });
  48065. return Mt({ url: i2, data: s2, method: r2, headers: o2 }).then((e3) => {
  48066. const t3 = e3.data || {};
  48067. if (!t3.success)
  48068. throw new te({ code: e3.errCode, message: e3.errMsg, requestId: e3.requestId });
  48069. return t3.data || {};
  48070. }).catch((e3) => {
  48071. throw new te({ code: e3.errCode, message: e3.errMsg, requestId: e3.requestId });
  48072. });
  48073. }
  48074. function Ft(e2 = "") {
  48075. const t2 = e2.trim().replace(/^cloud:\/\//, ""), n2 = t2.indexOf("/");
  48076. if (n2 <= 0)
  48077. throw new te({ code: "INVALID_PARAM", message: "fileID不合法" });
  48078. const s2 = t2.substring(0, n2), r2 = t2.substring(n2 + 1);
  48079. return s2 !== this.config.spaceId && console.warn("file ".concat(e2, " does not belong to env ").concat(this.config.spaceId)), r2;
  48080. }
  48081. function Kt(e2 = "") {
  48082. return "cloud://".concat(this.config.spaceId, "/").concat(e2.replace(/^\/+/, ""));
  48083. }
  48084. class jt {
  48085. constructor(e2) {
  48086. this.config = e2;
  48087. }
  48088. signedURL(e2, t2 = {}) {
  48089. 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) {
  48090. return r2[e3] ? "".concat(e3, "=").concat(r2[e3]) : null;
  48091. }).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("&");
  48092. return `${this.config.wsEndpoint}${n2}?${c2}&signature=${a2}`;
  48093. }
  48094. }
  48095. var $t = class {
  48096. constructor(e2) {
  48097. if (["spaceId", "spaceAppId", "accessKey", "secretKey"].forEach((t2) => {
  48098. if (!Object.prototype.hasOwnProperty.call(e2, t2))
  48099. throw new Error(`${t2} required`);
  48100. }), e2.endpoint) {
  48101. if ("string" != typeof e2.endpoint)
  48102. throw new Error("endpoint must be string");
  48103. if (!/^https:\/\//.test(e2.endpoint))
  48104. throw new Error("endpoint must start with https://");
  48105. e2.endpoint = e2.endpoint.replace(/\/$/, "");
  48106. }
  48107. 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);
  48108. }
  48109. callFunction(e2) {
  48110. return function(e3, t2) {
  48111. const { name: n2, data: s2, async: r2 = false, timeout: i2 } = e3, o2 = "POST", a2 = { "x-to-function-name": n2 };
  48112. r2 && (a2["x-function-invoke-type"] = "async");
  48113. const { url: c2, headers: u2 } = Dt("/functions/invokeFunction", { functionName: n2, data: s2, method: o2, headers: a2, signHeaderKeys: ["x-to-function-name"], config: t2 });
  48114. return Mt({ url: c2, data: s2, method: o2, headers: u2, timeout: i2 }).then((e4) => {
  48115. let t3 = 0;
  48116. if (r2) {
  48117. const n3 = e4.data || {};
  48118. t3 = "200" === n3.errCode ? 0 : n3.errCode, e4.data = n3.data || {}, e4.errMsg = n3.errMsg;
  48119. }
  48120. if (0 !== t3)
  48121. throw new te({ code: t3, message: e4.errMsg, requestId: e4.requestId });
  48122. return { errCode: t3, success: 0 === t3, requestId: e4.requestId, result: e4.data };
  48123. }).catch((e4) => {
  48124. throw new te({ code: e4.errCode, message: e4.errMsg, requestId: e4.requestId });
  48125. });
  48126. }(e2, this.config);
  48127. }
  48128. uploadFileToOSS({ url: e2, filePath: t2, fileType: n2, formData: s2, onUploadProgress: r2 }) {
  48129. return new Promise((i2, o2) => {
  48130. const a2 = ne.uploadFile({ url: e2, filePath: t2, fileType: n2, formData: s2, name: "file", success(e3) {
  48131. e3 && e3.statusCode < 400 ? i2(e3) : o2(new te({ code: "UPLOAD_FAILED", message: "文件上传失败" }));
  48132. }, fail(e3) {
  48133. o2(new te({ code: e3.code || "UPLOAD_FAILED", message: e3.message || e3.errMsg || "文件上传失败" }));
  48134. } });
  48135. "function" == typeof r2 && a2 && "function" == typeof a2.onProgressUpdate && a2.onProgressUpdate((e3) => {
  48136. r2({ loaded: e3.totalBytesSent, total: e3.totalBytesExpectedToSend });
  48137. });
  48138. });
  48139. }
  48140. async uploadFile({ filePath: e2, cloudPath: t2 = "", fileType: n2 = "image", onUploadProgress: s2 }) {
  48141. if ("string" !== g(t2))
  48142. throw new te({ code: "INVALID_PARAM", message: "cloudPath必须为字符串类型" });
  48143. if (!(t2 = t2.trim()))
  48144. throw new te({ code: "INVALID_PARAM", message: "cloudPath不可为空" });
  48145. if (/:\/\//.test(t2))
  48146. throw new te({ code: "INVALID_PARAM", message: "cloudPath不合法" });
  48147. 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), {});
  48148. return this.uploadFileToOSS({ url: o2, filePath: e2, fileType: n2, formData: c2, onUploadProgress: s2 }).then(() => ({ fileID: i2 }));
  48149. }
  48150. async getTempFileURL({ fileList: e2 }) {
  48151. return new Promise((t2, n2) => {
  48152. (!e2 || e2.length < 0) && t2({ code: "INVALID_PARAM", message: "fileList不能为空数组" }), e2.length > 50 && t2({ code: "INVALID_PARAM", message: "fileList数组长度不能超过50" });
  48153. const s2 = [];
  48154. for (const n3 of e2) {
  48155. let e3;
  48156. "string" !== g(n3) && t2({ code: "INVALID_PARAM", message: "fileList的元素必须是非空的字符串" });
  48157. try {
  48158. e3 = Ft.call(this, n3);
  48159. } catch (t3) {
  48160. console.warn(t3.errCode, t3.errMsg), e3 = n3;
  48161. }
  48162. s2.push({ file_id: e3, expire: 600 });
  48163. }
  48164. qt({ path: "/?download_url", data: { file_list: s2 }, method: "POST" }, this.config).then((e3) => {
  48165. const { file_list: n3 = [] } = e3;
  48166. t2({ fileList: n3.map((e4) => ({ fileID: Kt.call(this, e4.file_id), tempFileURL: e4.download_url })) });
  48167. }).catch((e3) => n2(e3));
  48168. });
  48169. }
  48170. async connectWebSocket(e2) {
  48171. const { name: t2, query: n2 } = e2;
  48172. return ne.connectSocket({ url: this._websocket.signedURL(t2, n2), complete: () => {
  48173. } });
  48174. }
  48175. };
  48176. var Bt = { init: (e2) => {
  48177. e2.provider = "alipay";
  48178. const t2 = new $t(e2);
  48179. return t2.auth = function() {
  48180. return { signInAnonymously: function() {
  48181. return Promise.resolve();
  48182. }, getLoginState: function() {
  48183. return Promise.resolve(true);
  48184. } };
  48185. }, t2;
  48186. } };
  48187. function Wt({ data: e2 }) {
  48188. let t2;
  48189. t2 = le();
  48190. const n2 = JSON.parse(JSON.stringify(e2 || {}));
  48191. if (Object.assign(n2, { clientInfo: t2 }), !n2.uniIdToken) {
  48192. const { token: e3 } = re();
  48193. e3 && (n2.uniIdToken = e3);
  48194. }
  48195. return n2;
  48196. }
  48197. async function Ht(e2 = {}) {
  48198. await this.__dev__.initLocalNetwork();
  48199. 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}`;
  48200. return new Promise((t3, n3) => {
  48201. ne.request({ method: "POST", url: i2, data: { name: e2.name, platform: P, provider: s2, spaceId: r2 }, timeout: 3e3, success(e3) {
  48202. t3(e3);
  48203. }, fail() {
  48204. t3({ data: { code: "NETWORK_ERROR", message: "连接本地调试服务失败,请检查客户端是否和主机在同一局域网下,自动切换为已部署的云函数。" } });
  48205. } });
  48206. }).then(({ data: e3 } = {}) => {
  48207. const { code: t3, message: n3 } = e3 || {};
  48208. return { code: 0 === t3 ? 0 : t3 || "SYS_ERR", message: n3 || "SYS_ERR" };
  48209. }).then(({ code: t3, message: n3 }) => {
  48210. if (0 !== t3) {
  48211. switch (t3) {
  48212. case "MODULE_ENCRYPTED":
  48213. console.error(`此云函数(${e2.name})依赖加密公共模块不可本地调试,自动切换为云端已部署的云函数`);
  48214. break;
  48215. case "FUNCTION_ENCRYPTED":
  48216. console.error(`此云函数(${e2.name})已加密不可本地调试,自动切换为云端已部署的云函数`);
  48217. break;
  48218. case "ACTION_ENCRYPTED":
  48219. console.error(n3 || "需要访问加密的uni-clientDB-action,自动切换为云端环境");
  48220. break;
  48221. case "NETWORK_ERROR":
  48222. console.error(n3 || "连接本地调试服务失败,请检查客户端是否和主机在同一局域网下");
  48223. break;
  48224. case "SWITCH_TO_CLOUD":
  48225. break;
  48226. default: {
  48227. const e3 = `检测本地调试服务出现错误:${n3},请检查网络环境或重启客户端再试`;
  48228. throw console.error(e3), new Error(e3);
  48229. }
  48230. }
  48231. return this._callCloudFunction(e2);
  48232. }
  48233. return new Promise((t4, n4) => {
  48234. const r3 = Wt.call(this, { data: e2.data });
  48235. 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) {
  48236. n4(new te({ code: e3.code || e3.errCode || "SYS_ERR", message: e3.message || e3.errMsg || "request:fail" }));
  48237. } });
  48238. });
  48239. });
  48240. }
  48241. const Jt = [{ rule: /fc_function_not_found|FUNCTION_NOT_FOUND/, content: ",云函数[{functionName}]在云端不存在,请检查此云函数名称是否正确以及该云函数是否已上传到服务空间", mode: "append" }];
  48242. var zt = /[\\^$.*+?()[\]{}|]/g, Vt = RegExp(zt.source);
  48243. function Gt(e2, t2, n2) {
  48244. return e2.replace(new RegExp((s2 = t2) && Vt.test(s2) ? s2.replace(zt, "\\$&") : s2, "g"), n2);
  48245. var s2;
  48246. }
  48247. 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" } };
  48248. function nn(e2) {
  48249. const { errSubject: t2, subject: n2, errCode: s2, errMsg: r2, code: i2, message: o2, cause: a2 } = e2 || {};
  48250. return new te({ subject: t2 || n2 || Zt, code: s2 || i2 || en.SYSTEM_ERROR.code, message: r2 || o2, cause: a2 });
  48251. }
  48252. let Kn;
  48253. function Hn({ secretType: e2 } = {}) {
  48254. return e2 === Yt.REQUEST || e2 === Yt.RESPONSE || e2 === Yt.BOTH;
  48255. }
  48256. function Jn({ name: e2, data: t2 = {} } = {}) {
  48257. return "DCloud-clientDB" === e2 && "encryption" === t2.redirectTo && "getAppClientKey" === t2.action;
  48258. }
  48259. function zn({ provider: e2, spaceId: t2, functionName: n2 } = {}) {
  48260. const { appId: s2, uniPlatform: r2, osName: i2 } = ce();
  48261. let o2 = r2;
  48262. "app" === r2 && (o2 = i2);
  48263. const a2 = function({ provider: e3, spaceId: t3 } = {}) {
  48264. const n3 = A;
  48265. if (!n3)
  48266. return {};
  48267. e3 = /* @__PURE__ */ function(e4) {
  48268. return "tencent" === e4 ? "tcb" : e4;
  48269. }(e3);
  48270. const s3 = n3.find((n4) => n4.provider === e3 && n4.spaceId === t3);
  48271. return s3 && s3.config;
  48272. }({ provider: e2, spaceId: t2 });
  48273. if (!a2 || !a2.accessControl || !a2.accessControl.enable)
  48274. return false;
  48275. const c2 = a2.accessControl.function || {}, u2 = Object.keys(c2);
  48276. if (0 === u2.length)
  48277. return true;
  48278. const h2 = function(e3, t3) {
  48279. let n3, s3, r3;
  48280. for (let i3 = 0; i3 < e3.length; i3++) {
  48281. const o3 = e3[i3];
  48282. o3 !== t3 ? "*" !== o3 ? o3.split(",").map((e4) => e4.trim()).indexOf(t3) > -1 && (s3 = o3) : r3 = o3 : n3 = o3;
  48283. }
  48284. return n3 || s3 || r3;
  48285. }(u2, n2);
  48286. if (!h2)
  48287. return false;
  48288. if ((c2[h2] || []).find((e3 = {}) => e3.appId === s2 && (e3.platform || "").toLowerCase() === o2.toLowerCase()))
  48289. return true;
  48290. throw console.error(`此应用[appId: ${s2}, platform: ${o2}]不在云端配置的允许访问的应用列表内,参考:https://uniapp.dcloud.net.cn/uniCloud/secure-network.html#verify-client`), nn(en.APP_INFO_INVALID);
  48291. }
  48292. function Vn({ functionName: e2, result: t2, logPvd: n2 }) {
  48293. if (this.__dev__.debugLog && t2 && t2.requestId) {
  48294. const s2 = JSON.stringify({ spaceId: this.config.spaceId, functionName: e2, requestId: t2.requestId });
  48295. console.log(`[${n2}-request]${s2}[/${n2}-request]`);
  48296. }
  48297. }
  48298. function Gn(e2) {
  48299. const t2 = e2.callFunction, n2 = function(n3) {
  48300. const s2 = n3.name;
  48301. n3.data = Wt.call(e2, { data: n3.data });
  48302. const r2 = { aliyun: "aliyun", tencent: "tcb", tcb: "tcb", alipay: "alipay", dcloud: "dcloud" }[this.config.provider], i2 = Hn(n3), o2 = Jn(n3), a2 = i2 || o2;
  48303. 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 = [] } = {}) {
  48304. for (let s3 = 0; s3 < n4.length; s3++) {
  48305. const { rule: r3, content: i3, mode: o3 } = n4[s3], a3 = e4.match(r3);
  48306. if (!a3)
  48307. continue;
  48308. let c2 = i3;
  48309. for (let e5 = 1; e5 < a3.length; e5++)
  48310. c2 = Gt(c2, `{$${e5}}`, a3[e5]);
  48311. for (const e5 in t3)
  48312. c2 = Gt(c2, `{${e5}}`, t3[e5]);
  48313. return "replace" === o3 ? c2 : e4 + c2;
  48314. }
  48315. return e4;
  48316. }({ message: `[${n3.name}]: ${e3.message}`, formatter: Jt, extraInfo: { functionName: s2 } })), Promise.reject(e3)));
  48317. };
  48318. e2.callFunction = function(t3) {
  48319. const { provider: s2, spaceId: r2 } = e2.config, i2 = t3.name;
  48320. let o2, a2;
  48321. 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))
  48322. a2 = n2.call(e2, t3);
  48323. else if (Hn(t3)) {
  48324. a2 = new Kn({ secretType: t3.secretType, uniCloudIns: e2 }).wrapEncryptDataCallFunction(n2.bind(e2))(t3);
  48325. } else if (zn({ provider: s2, spaceId: r2, functionName: i2 })) {
  48326. a2 = new Kn({ secretType: t3.secretType, uniCloudIns: e2 }).wrapVerifyClientCallFunction(n2.bind(e2))(t3);
  48327. } else
  48328. a2 = o2(t3);
  48329. return Object.defineProperty(a2, "result", { get: () => (console.warn("当前返回结果为Promise类型,不可直接访问其result属性,详情请参考:https://uniapp.dcloud.net.cn/uniCloud/faq?id=promise"), {}) }), a2.then((e3) => e3);
  48330. };
  48331. }
  48332. Kn = class {
  48333. constructor() {
  48334. throw nn({ message: `Platform ${P} is not enabled, please check whether secure network module is enabled in your manifest.json` });
  48335. }
  48336. };
  48337. const Yn = Symbol("CLIENT_DB_INTERNAL");
  48338. function Qn(e2, t2) {
  48339. return e2.then = "DoNotReturnProxyWithAFunctionNamedThen", e2._internalType = Yn, e2.inspect = null, e2.__v_raw = void 0, new Proxy(e2, { get(e3, n2, s2) {
  48340. if ("_uniClient" === n2)
  48341. return null;
  48342. if ("symbol" == typeof n2)
  48343. return e3[n2];
  48344. if (n2 in e3 || "string" != typeof n2) {
  48345. const t3 = e3[n2];
  48346. return "function" == typeof t3 ? t3.bind(e3) : t3;
  48347. }
  48348. return t2.get(e3, n2, s2);
  48349. } });
  48350. }
  48351. function Xn(e2) {
  48352. return { on: (t2, n2) => {
  48353. e2[t2] = e2[t2] || [], e2[t2].indexOf(n2) > -1 || e2[t2].push(n2);
  48354. }, off: (t2, n2) => {
  48355. e2[t2] = e2[t2] || [];
  48356. const s2 = e2[t2].indexOf(n2);
  48357. -1 !== s2 && e2[t2].splice(s2, 1);
  48358. } };
  48359. }
  48360. const Zn = ["db.Geo", "db.command", "command.aggregate"];
  48361. function es(e2, t2) {
  48362. return Zn.indexOf(`${e2}.${t2}`) > -1;
  48363. }
  48364. function ts(e2) {
  48365. switch (g(e2 = se(e2))) {
  48366. case "array":
  48367. return e2.map((e3) => ts(e3));
  48368. case "object":
  48369. return e2._internalType === Yn || Object.keys(e2).forEach((t2) => {
  48370. e2[t2] = ts(e2[t2]);
  48371. }), e2;
  48372. case "regexp":
  48373. return { $regexp: { source: e2.source, flags: e2.flags } };
  48374. case "date":
  48375. return { $date: e2.toISOString() };
  48376. default:
  48377. return e2;
  48378. }
  48379. }
  48380. function ns(e2) {
  48381. return e2 && e2.content && e2.content.$method;
  48382. }
  48383. class ss {
  48384. constructor(e2, t2, n2) {
  48385. this.content = e2, this.prevStage = t2 || null, this.udb = null, this._database = n2;
  48386. }
  48387. toJSON() {
  48388. let e2 = this;
  48389. const t2 = [e2.content];
  48390. for (; e2.prevStage; )
  48391. e2 = e2.prevStage, t2.push(e2.content);
  48392. return { $db: t2.reverse().map((e3) => ({ $method: e3.$method, $param: ts(e3.$param) })) };
  48393. }
  48394. toString() {
  48395. return JSON.stringify(this.toJSON());
  48396. }
  48397. getAction() {
  48398. const e2 = this.toJSON().$db.find((e3) => "action" === e3.$method);
  48399. return e2 && e2.$param && e2.$param[0];
  48400. }
  48401. getCommand() {
  48402. return { $db: this.toJSON().$db.filter((e2) => "action" !== e2.$method) };
  48403. }
  48404. get isAggregate() {
  48405. let e2 = this;
  48406. for (; e2; ) {
  48407. const t2 = ns(e2), n2 = ns(e2.prevStage);
  48408. if ("aggregate" === t2 && "collection" === n2 || "pipeline" === t2)
  48409. return true;
  48410. e2 = e2.prevStage;
  48411. }
  48412. return false;
  48413. }
  48414. get isCommand() {
  48415. let e2 = this;
  48416. for (; e2; ) {
  48417. if ("command" === ns(e2))
  48418. return true;
  48419. e2 = e2.prevStage;
  48420. }
  48421. return false;
  48422. }
  48423. get isAggregateCommand() {
  48424. let e2 = this;
  48425. for (; e2; ) {
  48426. const t2 = ns(e2), n2 = ns(e2.prevStage);
  48427. if ("aggregate" === t2 && "command" === n2)
  48428. return true;
  48429. e2 = e2.prevStage;
  48430. }
  48431. return false;
  48432. }
  48433. getNextStageFn(e2) {
  48434. const t2 = this;
  48435. return function() {
  48436. return rs({ $method: e2, $param: ts(Array.from(arguments)) }, t2, t2._database);
  48437. };
  48438. }
  48439. get count() {
  48440. return this.isAggregate ? this.getNextStageFn("count") : function() {
  48441. return this._send("count", Array.from(arguments));
  48442. };
  48443. }
  48444. get remove() {
  48445. return this.isCommand ? this.getNextStageFn("remove") : function() {
  48446. return this._send("remove", Array.from(arguments));
  48447. };
  48448. }
  48449. get() {
  48450. return this._send("get", Array.from(arguments));
  48451. }
  48452. get add() {
  48453. return this.isCommand ? this.getNextStageFn("add") : function() {
  48454. return this._send("add", Array.from(arguments));
  48455. };
  48456. }
  48457. update() {
  48458. return this._send("update", Array.from(arguments));
  48459. }
  48460. end() {
  48461. return this._send("end", Array.from(arguments));
  48462. }
  48463. get set() {
  48464. return this.isCommand ? this.getNextStageFn("set") : function() {
  48465. throw new Error("JQL禁止使用set方法");
  48466. };
  48467. }
  48468. _send(e2, t2) {
  48469. const n2 = this.getAction(), s2 = this.getCommand();
  48470. if (s2.$db.push({ $method: e2, $param: ts(t2) }), b) {
  48471. const e3 = s2.$db.find((e4) => "collection" === e4.$method), t3 = e3 && e3.$param;
  48472. 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- 如果主表数据量很小请忽略此信息,项目发行时不会出现此提示。");
  48473. }
  48474. return this._database._callCloudFunction({ action: n2, command: s2 });
  48475. }
  48476. }
  48477. function rs(e2, t2, n2) {
  48478. return Qn(new ss(e2, t2, n2), { get(e3, t3) {
  48479. let s2 = "db";
  48480. return e3 && e3.content && (s2 = e3.content.$method), es(s2, t3) ? rs({ $method: t3 }, e3, n2) : function() {
  48481. return rs({ $method: t3, $param: ts(Array.from(arguments)) }, e3, n2);
  48482. };
  48483. } });
  48484. }
  48485. function is({ path: e2, method: t2 }) {
  48486. return class {
  48487. constructor() {
  48488. this.param = Array.from(arguments);
  48489. }
  48490. toJSON() {
  48491. return { $newDb: [...e2.map((e3) => ({ $method: e3 })), { $method: t2, $param: this.param }] };
  48492. }
  48493. toString() {
  48494. return JSON.stringify(this.toJSON());
  48495. }
  48496. };
  48497. }
  48498. class os {
  48499. constructor({ uniClient: e2 = {}, isJQL: t2 = false } = {}) {
  48500. 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" });
  48501. }
  48502. getCloudEnv(e2) {
  48503. if ("string" != typeof e2 || !e2.trim())
  48504. throw new Error("getCloudEnv参数错误");
  48505. return { $env: e2.replace("$cloudEnv_", "") };
  48506. }
  48507. _callback(e2, t2) {
  48508. const n2 = this._dbCallBacks;
  48509. n2[e2] && n2[e2].forEach((e3) => {
  48510. e3(...t2);
  48511. });
  48512. }
  48513. _callbackAuth(e2, t2) {
  48514. const n2 = this._authCallBacks;
  48515. n2[e2] && n2[e2].forEach((e3) => {
  48516. e3(...t2);
  48517. });
  48518. }
  48519. multiSend() {
  48520. const e2 = Array.from(arguments), t2 = e2.map((e3) => {
  48521. const t3 = e3.getAction(), n2 = e3.getCommand();
  48522. if ("getTemp" !== n2.$db[n2.$db.length - 1].$method)
  48523. throw new Error("multiSend只支持子命令内使用getTemp");
  48524. return { action: t3, command: n2 };
  48525. });
  48526. return this._callCloudFunction({ multiCommand: t2, queryList: e2 });
  48527. }
  48528. }
  48529. function as(e2, t2 = {}) {
  48530. return Qn(new e2(t2), { get: (e3, t3) => es("db", t3) ? rs({ $method: t3 }, null, e3) : function() {
  48531. return rs({ $method: t3, $param: ts(Array.from(arguments)) }, null, e3);
  48532. } });
  48533. }
  48534. class cs extends os {
  48535. _parseResult(e2) {
  48536. return this._isJQL ? e2.result : e2;
  48537. }
  48538. _callCloudFunction({ action: e2, command: t2, multiCommand: n2, queryList: s2 }) {
  48539. function r2(e3, t3) {
  48540. if (n2 && s2)
  48541. for (let n3 = 0; n3 < s2.length; n3++) {
  48542. const r3 = s2[n3];
  48543. r3.udb && "function" == typeof r3.udb.setResult && (t3 ? r3.udb.setResult(t3) : r3.udb.setResult(e3.result.dataList[n3]));
  48544. }
  48545. }
  48546. const i2 = this, o2 = this._isJQL ? "databaseForJQL" : "database";
  48547. function a2(e3) {
  48548. 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)));
  48549. }
  48550. const c2 = j($(o2, "invoke")), u2 = this._uniClient;
  48551. return c2.then(() => u2.callFunction({ name: "DCloud-clientDB", type: l.CLIENT_DB, data: { action: e2, command: t2, multiCommand: n2 } })).then((e3) => {
  48552. const { code: t3, message: n3, token: s3, tokenExpired: c3, systemInfo: u3 = [] } = e3.result;
  48553. if (u3)
  48554. for (let e4 = 0; e4 < u3.length; e4++) {
  48555. const { level: t4, message: n4, detail: s4 } = u3[e4];
  48556. let r3 = "[System Info]" + n4;
  48557. s4 && (r3 = `${r3}
  48558. 详细信息:${s4}`), (console["warn" === t4 ? "error" : t4] || console.log)(r3);
  48559. }
  48560. if (t3) {
  48561. return a2(new te({ code: t3, message: n3, requestId: e3.requestId }));
  48562. }
  48563. 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 }));
  48564. const h2 = [{ prop: "affectedDocs", tips: "affectedDocs不再推荐使用,请使用inserted/deleted/updated/data.length替代" }, { prop: "code", tips: "code不再推荐使用,请使用errCode替代" }, { prop: "message", tips: "message不再推荐使用,请使用errMsg替代" }];
  48565. for (let t4 = 0; t4 < h2.length; t4++) {
  48566. const { prop: n4, tips: s4 } = h2[t4];
  48567. if (n4 in e3.result) {
  48568. const t5 = e3.result[n4];
  48569. Object.defineProperty(e3.result, n4, { get: () => (console.warn(s4), t5) });
  48570. }
  48571. }
  48572. return function(e4) {
  48573. return j($(o2, "success"), e4).then(() => j($(o2, "complete"), e4)).then(() => {
  48574. r2(e4, null);
  48575. const t4 = i2._parseResult(e4);
  48576. return Y(H.RESPONSE, { type: J.CLIENT_DB, content: t4 }), Promise.resolve(t4);
  48577. });
  48578. }(e3);
  48579. }, (e3) => {
  48580. /fc_function_not_found|FUNCTION_NOT_FOUND/g.test(e3.message) && console.warn("clientDB未初始化,请在web控制台保存一次schema以开启clientDB");
  48581. return a2(new te({ code: e3.code || "SYSTEM_ERROR", message: e3.message, requestId: e3.requestId }));
  48582. });
  48583. }
  48584. }
  48585. 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: "用户未登录或登录状态过期,自动跳转登录页面" };
  48586. function fs(e2, t2) {
  48587. let n2 = "";
  48588. return n2 = e2 ? `${e2}/${t2}` : t2, n2.replace(/^\//, "");
  48589. }
  48590. function gs(e2 = [], t2 = "") {
  48591. const n2 = [], s2 = [];
  48592. return e2.forEach((e3) => {
  48593. true === e3.needLogin ? n2.push(fs(t2, e3.path)) : false === e3.needLogin && s2.push(fs(t2, e3.path));
  48594. }), { needLoginPage: n2, notNeedLoginPage: s2 };
  48595. }
  48596. function ms(e2) {
  48597. return e2.split("?")[0].replace(/^\//, "");
  48598. }
  48599. function ys() {
  48600. return function(e2) {
  48601. let t2 = e2 && e2.$page && e2.$page.fullPath;
  48602. return t2 ? ("/" !== t2.charAt(0) && (t2 = "/" + t2), t2) : "";
  48603. }(function() {
  48604. const e2 = getCurrentPages();
  48605. return e2[e2.length - 1];
  48606. }());
  48607. }
  48608. function _s() {
  48609. return ms(ys());
  48610. }
  48611. function ws(e2 = "", t2 = {}) {
  48612. if (!e2)
  48613. return false;
  48614. if (!(t2 && t2.list && t2.list.length))
  48615. return false;
  48616. const n2 = t2.list, s2 = ms(e2);
  48617. return n2.some((e3) => e3.pagePath === s2);
  48618. }
  48619. const Is = !!e.uniIdRouter;
  48620. const { loginPage: vs, routerNeedLogin: Ss, resToLogin: Ts, needLoginPage: bs, notNeedLoginPage: Es, loginPageInTabBar: ks } = function({ pages: t2 = [], subPackages: n2 = [], uniIdRouter: s2 = {}, tabBar: r2 = {} } = e) {
  48621. const { loginPage: i2, needLogin: o2 = [], resToLogin: a2 = true } = s2, { needLoginPage: c2, notNeedLoginPage: u2 } = gs(t2), { needLoginPage: h2, notNeedLoginPage: l2 } = function(e2 = []) {
  48622. const t3 = [], n3 = [];
  48623. return e2.forEach((e3) => {
  48624. const { root: s3, pages: r3 = [] } = e3, { needLoginPage: i3, notNeedLoginPage: o3 } = gs(r3, s3);
  48625. t3.push(...i3), n3.push(...o3);
  48626. }), { needLoginPage: t3, notNeedLoginPage: n3 };
  48627. }(n2);
  48628. return { loginPage: i2, routerNeedLogin: o2, resToLogin: a2, needLoginPage: [...c2, ...h2], notNeedLoginPage: [...u2, ...l2], loginPageInTabBar: ws(i2, r2) };
  48629. }();
  48630. if (bs.indexOf(vs) > -1)
  48631. throw new Error(`Login page [${vs}] should not be "needLogin", please check your pages.json`);
  48632. function As(e2) {
  48633. const t2 = _s();
  48634. if ("/" === e2.charAt(0))
  48635. return e2;
  48636. const [n2, s2] = e2.split("?"), r2 = n2.replace(/^\//, "").split("/"), i2 = t2.split("/");
  48637. i2.pop();
  48638. for (let e3 = 0; e3 < r2.length; e3++) {
  48639. const t3 = r2[e3];
  48640. ".." === t3 ? i2.pop() : "." !== t3 && i2.push(t3);
  48641. }
  48642. return "" === i2[0] && i2.shift(), "/" + i2.join("/") + (s2 ? "?" + s2 : "");
  48643. }
  48644. function Ps(e2) {
  48645. const t2 = ms(As(e2));
  48646. return !(Es.indexOf(t2) > -1) && (bs.indexOf(t2) > -1 || Ss.some((t3) => function(e3, t4) {
  48647. return new RegExp(t4).test(e3);
  48648. }(e2, t3)));
  48649. }
  48650. function Cs({ redirect: e2 }) {
  48651. const t2 = ms(e2), n2 = ms(vs);
  48652. return _s() !== n2 && t2 !== n2;
  48653. }
  48654. function Os({ api: e2, redirect: t2 } = {}) {
  48655. if (!t2 || !Cs({ redirect: t2 }))
  48656. return;
  48657. const n2 = function(e3, t3) {
  48658. return "/" !== e3.charAt(0) && (e3 = "/" + e3), t3 ? e3.indexOf("?") > -1 ? e3 + `&uniIdRedirectUrl=${encodeURIComponent(t3)}` : e3 + `?uniIdRedirectUrl=${encodeURIComponent(t3)}` : e3;
  48659. }(vs, t2);
  48660. ks ? "navigateTo" !== e2 && "redirectTo" !== e2 || (e2 = "switchTab") : "switchTab" === e2 && (e2 = "navigateTo");
  48661. const s2 = { navigateTo: uni.navigateTo, redirectTo: uni.redirectTo, switchTab: uni.switchTab, reLaunch: uni.reLaunch };
  48662. setTimeout(() => {
  48663. s2[e2]({ url: n2 });
  48664. }, 0);
  48665. }
  48666. function xs({ url: e2 } = {}) {
  48667. const t2 = { abortLoginPageJump: false, autoToLoginPage: false }, n2 = function() {
  48668. const { token: e3, tokenExpired: t3 } = re();
  48669. let n3;
  48670. if (e3) {
  48671. if (t3 < Date.now()) {
  48672. const e4 = "uni-id-token-expired";
  48673. n3 = { errCode: e4, errMsg: ps[e4] };
  48674. }
  48675. } else {
  48676. const e4 = "uni-id-check-token-failed";
  48677. n3 = { errCode: e4, errMsg: ps[e4] };
  48678. }
  48679. return n3;
  48680. }();
  48681. if (Ps(e2) && n2) {
  48682. n2.uniIdRedirectUrl = e2;
  48683. if (z(H.NEED_LOGIN).length > 0)
  48684. return setTimeout(() => {
  48685. Y(H.NEED_LOGIN, n2);
  48686. }, 0), t2.abortLoginPageJump = true, t2;
  48687. t2.autoToLoginPage = true;
  48688. }
  48689. return t2;
  48690. }
  48691. function Ns() {
  48692. !function() {
  48693. const e3 = ys(), { abortLoginPageJump: t2, autoToLoginPage: n2 } = xs({ url: e3 });
  48694. t2 || n2 && Os({ api: "redirectTo", redirect: e3 });
  48695. }();
  48696. const e2 = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
  48697. for (let t2 = 0; t2 < e2.length; t2++) {
  48698. const n2 = e2[t2];
  48699. uni.addInterceptor(n2, { invoke(e3) {
  48700. const { abortLoginPageJump: t3, autoToLoginPage: s2 } = xs({ url: e3.url });
  48701. return t3 ? e3 : s2 ? (Os({ api: n2, redirect: As(e3.url) }), false) : e3;
  48702. } });
  48703. }
  48704. }
  48705. function Rs() {
  48706. this.onResponse((e2) => {
  48707. const { type: t2, content: n2 } = e2;
  48708. let s2 = false;
  48709. switch (t2) {
  48710. case "cloudobject":
  48711. s2 = function(e3) {
  48712. if ("object" != typeof e3)
  48713. return false;
  48714. const { errCode: t3 } = e3 || {};
  48715. return t3 in ps;
  48716. }(n2);
  48717. break;
  48718. case "clientdb":
  48719. s2 = function(e3) {
  48720. if ("object" != typeof e3)
  48721. return false;
  48722. const { errCode: t3 } = e3 || {};
  48723. return t3 in ls;
  48724. }(n2);
  48725. }
  48726. s2 && function(e3 = {}) {
  48727. const t3 = z(H.NEED_LOGIN);
  48728. Z().then(() => {
  48729. const n3 = ys();
  48730. if (n3 && Cs({ redirect: n3 }))
  48731. return t3.length > 0 ? Y(H.NEED_LOGIN, Object.assign({ uniIdRedirectUrl: n3 }, e3)) : void (vs && Os({ api: "navigateTo", redirect: n3 }));
  48732. });
  48733. }(n2);
  48734. });
  48735. }
  48736. function Ls(e2) {
  48737. !function(e3) {
  48738. e3.onResponse = function(e4) {
  48739. V(H.RESPONSE, e4);
  48740. }, e3.offResponse = function(e4) {
  48741. G(H.RESPONSE, e4);
  48742. };
  48743. }(e2), function(e3) {
  48744. e3.onNeedLogin = function(e4) {
  48745. V(H.NEED_LOGIN, e4);
  48746. }, e3.offNeedLogin = function(e4) {
  48747. G(H.NEED_LOGIN, e4);
  48748. }, Is && (U(Qt).needLoginInit || (U(Qt).needLoginInit = true, Z().then(() => {
  48749. Ns.call(e3);
  48750. }), Ts && Rs.call(e3)));
  48751. }(e2), function(e3) {
  48752. e3.onRefreshToken = function(e4) {
  48753. V(H.REFRESH_TOKEN, e4);
  48754. }, e3.offRefreshToken = function(e4) {
  48755. G(H.REFRESH_TOKEN, e4);
  48756. };
  48757. }(e2);
  48758. }
  48759. let Us;
  48760. const Ds = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", Ms = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/;
  48761. function qs() {
  48762. const e2 = re().token || "", t2 = e2.split(".");
  48763. if (!e2 || 3 !== t2.length)
  48764. return { uid: null, role: [], permission: [], tokenExpired: 0 };
  48765. let n2;
  48766. try {
  48767. n2 = JSON.parse((s2 = t2[1], decodeURIComponent(Us(s2).split("").map(function(e3) {
  48768. return "%" + ("00" + e3.charCodeAt(0).toString(16)).slice(-2);
  48769. }).join(""))));
  48770. } catch (e3) {
  48771. throw new Error("获取当前用户信息出错,详细错误信息为:" + e3.message);
  48772. }
  48773. var s2;
  48774. return n2.tokenExpired = 1e3 * n2.exp, delete n2.exp, delete n2.iat, n2;
  48775. }
  48776. Us = "function" != typeof atob ? function(e2) {
  48777. if (e2 = String(e2).replace(/[\t\n\f\r ]+/g, ""), !Ms.test(e2))
  48778. throw new Error("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
  48779. var t2;
  48780. e2 += "==".slice(2 - (3 & e2.length));
  48781. for (var n2, s2, r2 = "", i2 = 0; i2 < e2.length; )
  48782. 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);
  48783. return r2;
  48784. } : atob;
  48785. var Fs = n(function(e2, t2) {
  48786. Object.defineProperty(t2, "__esModule", { value: true });
  48787. const n2 = "chooseAndUploadFile:ok", s2 = "chooseAndUploadFile:fail";
  48788. function r2(e3, t3) {
  48789. return e3.tempFiles.forEach((e4, n3) => {
  48790. 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("."));
  48791. }), e3.tempFilePaths || (e3.tempFilePaths = e3.tempFiles.map((e4) => e4.path)), e3;
  48792. }
  48793. function i2(e3, t3, { onChooseFile: s3, onUploadProgress: r3 }) {
  48794. return t3.then((e4) => {
  48795. if (s3) {
  48796. const t4 = s3(e4);
  48797. if (void 0 !== t4)
  48798. return Promise.resolve(t4).then((t5) => void 0 === t5 ? e4 : t5);
  48799. }
  48800. return e4;
  48801. }).then((t4) => false === t4 ? { errMsg: n2, tempFilePaths: [], tempFiles: [] } : function(e4, t5, s4 = 5, r4) {
  48802. (t5 = Object.assign({}, t5)).errMsg = n2;
  48803. const i3 = t5.tempFiles, o2 = i3.length;
  48804. let a2 = 0;
  48805. return new Promise((n3) => {
  48806. for (; a2 < s4; )
  48807. c2();
  48808. function c2() {
  48809. const s5 = a2++;
  48810. if (s5 >= o2)
  48811. return void (!i3.find((e5) => !e5.url && !e5.errMsg) && n3(t5));
  48812. const u2 = i3[s5];
  48813. e4.uploadFile({ provider: u2.provider, filePath: u2.path, cloudPath: u2.cloudPath, fileType: u2.fileType, cloudPathAsRealPath: u2.cloudPathAsRealPath, onUploadProgress(e5) {
  48814. e5.index = s5, e5.tempFile = u2, e5.tempFilePath = u2.path, r4 && r4(e5);
  48815. } }).then((e5) => {
  48816. u2.url = e5.fileID, s5 < o2 && c2();
  48817. }).catch((e5) => {
  48818. u2.errMsg = e5.errMsg || e5.message, s5 < o2 && c2();
  48819. });
  48820. }
  48821. });
  48822. }(e3, t4, 5, r3));
  48823. }
  48824. t2.initChooseAndUploadFile = function(e3) {
  48825. return function(t3 = { type: "all" }) {
  48826. return "image" === t3.type ? i2(e3, function(e4) {
  48827. const { count: t4, sizeType: n3, sourceType: i3 = ["album", "camera"], extension: o2 } = e4;
  48828. return new Promise((e5, a2) => {
  48829. uni.chooseImage({ count: t4, sizeType: n3, sourceType: i3, extension: o2, success(t5) {
  48830. e5(r2(t5, "image"));
  48831. }, fail(e6) {
  48832. a2({ errMsg: e6.errMsg.replace("chooseImage:fail", s2) });
  48833. } });
  48834. });
  48835. }(t3), t3) : "video" === t3.type ? i2(e3, function(e4) {
  48836. const { camera: t4, compressed: n3, maxDuration: i3, sourceType: o2 = ["album", "camera"], extension: a2 } = e4;
  48837. return new Promise((e5, c2) => {
  48838. uni.chooseVideo({ camera: t4, compressed: n3, maxDuration: i3, sourceType: o2, extension: a2, success(t5) {
  48839. const { tempFilePath: n4, duration: s3, size: i4, height: o3, width: a3 } = t5;
  48840. 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"));
  48841. }, fail(e6) {
  48842. c2({ errMsg: e6.errMsg.replace("chooseVideo:fail", s2) });
  48843. } });
  48844. });
  48845. }(t3), t3) : i2(e3, function(e4) {
  48846. const { count: t4, extension: n3 } = e4;
  48847. return new Promise((e5, i3) => {
  48848. let o2 = uni.chooseFile;
  48849. if ("undefined" != typeof wx && "function" == typeof wx.chooseMessageFile && (o2 = wx.chooseMessageFile), "function" != typeof o2)
  48850. return i3({ errMsg: s2 + " 请指定 type 类型,该平台仅支持选择 image 或 video。" });
  48851. o2({ type: "all", count: t4, extension: n3, success(t5) {
  48852. e5(r2(t5));
  48853. }, fail(e6) {
  48854. i3({ errMsg: e6.errMsg.replace("chooseFile:fail", s2) });
  48855. } });
  48856. });
  48857. }(t3), t3);
  48858. };
  48859. };
  48860. }), Ks = t(Fs);
  48861. const js = { auto: "auto", onready: "onready", manual: "manual" };
  48862. function $s(e2) {
  48863. 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() {
  48864. this.mixinDatacomPage = { current: this.pageCurrent, size: this.pageSize, count: 0 }, this.$watch(() => {
  48865. var e3 = [];
  48866. return ["pageCurrent", "pageSize", "localdata", "collection", "action", "field", "orderby", "where", "getont", "getcount", "gettree", "groupby", "groupField", "distinct"].forEach((t2) => {
  48867. e3.push(this[t2]);
  48868. }), e3;
  48869. }, (e3, t2) => {
  48870. if (this.loadtime === js.manual)
  48871. return;
  48872. let n2 = false;
  48873. const s2 = [];
  48874. for (let r2 = 2; r2 < e3.length; r2++)
  48875. e3[r2] !== t2[r2] && (s2.push(e3[r2]), n2 = true);
  48876. e3[0] !== t2[0] && (this.mixinDatacomPage.current = this.pageCurrent), this.mixinDatacomPage.size = this.pageSize, this.onMixinDatacomPropsChange(n2, s2);
  48877. });
  48878. }, methods: { onMixinDatacomPropsChange(e3, t2) {
  48879. }, mixinDatacomEasyGet({ getone: e3 = false, success: t2, fail: n2 } = {}) {
  48880. this.mixinDatacomLoading || (this.mixinDatacomLoading = true, this.mixinDatacomErrorMessage = "", this.mixinDatacomError = null, this.mixinDatacomGet().then((n3) => {
  48881. this.mixinDatacomLoading = false;
  48882. const { data: s2, count: r2 } = n3.result;
  48883. this.getcount && (this.mixinDatacomPage.count = r2), this.mixinDatacomHasMore = s2.length < this.pageSize;
  48884. const i2 = e3 ? s2.length ? s2[0] : void 0 : s2;
  48885. this.mixinDatacomResData = i2, t2 && t2(i2);
  48886. }).catch((e4) => {
  48887. this.mixinDatacomLoading = false, this.mixinDatacomErrorMessage = e4, this.mixinDatacomError = e4, n2 && n2(e4);
  48888. }));
  48889. }, mixinDatacomGet(t2 = {}) {
  48890. let n2;
  48891. t2 = t2 || {}, n2 = "undefined" != typeof __uniX && __uniX ? e2.databaseForJQL(this.spaceInfo) : e2.database(this.spaceInfo);
  48892. const s2 = t2.action || this.action;
  48893. s2 && (n2 = n2.action(s2));
  48894. const r2 = t2.collection || this.collection;
  48895. n2 = Array.isArray(r2) ? n2.collection(...r2) : n2.collection(r2);
  48896. const i2 = t2.where || this.where;
  48897. i2 && Object.keys(i2).length && (n2 = n2.where(i2));
  48898. const o2 = t2.field || this.field;
  48899. o2 && (n2 = n2.field(o2));
  48900. const a2 = t2.foreignKey || this.foreignKey;
  48901. a2 && (n2 = n2.foreignKey(a2));
  48902. const c2 = t2.groupby || this.groupby;
  48903. c2 && (n2 = n2.groupBy(c2));
  48904. const u2 = t2.groupField || this.groupField;
  48905. u2 && (n2 = n2.groupField(u2));
  48906. true === (void 0 !== t2.distinct ? t2.distinct : this.distinct) && (n2 = n2.distinct());
  48907. const h2 = t2.orderby || this.orderby;
  48908. h2 && (n2 = n2.orderBy(h2));
  48909. 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 };
  48910. return f2 && (m2.getTree = y2), g2 && (m2.getTreePath = y2), n2 = n2.skip(d2 * (l2 - 1)).limit(d2).get(m2), n2;
  48911. } } };
  48912. }
  48913. function Bs(e2) {
  48914. return function(t2, n2 = {}) {
  48915. n2 = function(e3, t3 = {}) {
  48916. 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;
  48917. }({ customUI: false, loadingOptions: { title: "加载中...", mask: true }, errorOptions: { type: "modal", retry: false } }, n2);
  48918. const { customUI: s2, loadingOptions: r2, errorOptions: i2, parseSystemError: o2 } = n2, a2 = !s2;
  48919. return new Proxy({}, { get(s3, c2) {
  48920. switch (c2) {
  48921. case "toString":
  48922. return "[object UniCloudObject]";
  48923. case "toJSON":
  48924. return {};
  48925. }
  48926. return function({ fn: e3, interceptorName: t3, getCallbackArgs: n3 } = {}) {
  48927. return async function(...s4) {
  48928. const r3 = n3 ? n3({ params: s4 }) : {};
  48929. let i3, o3;
  48930. try {
  48931. return await j($(t3, "invoke"), { ...r3 }), i3 = await e3(...s4), await j($(t3, "success"), { ...r3, result: i3 }), i3;
  48932. } catch (e4) {
  48933. throw o3 = e4, await j($(t3, "fail"), { ...r3, error: o3 }), o3;
  48934. } finally {
  48935. await j($(t3, "complete"), o3 ? { ...r3, error: o3 } : { ...r3, result: i3 });
  48936. }
  48937. };
  48938. }({ fn: async function s4(...u2) {
  48939. let h2;
  48940. a2 && uni.showLoading({ title: r2.title, mask: r2.mask });
  48941. const d2 = { name: t2, type: l.OBJECT, data: { method: c2, params: u2 } };
  48942. "object" == typeof n2.secretMethods && function(e3, t3) {
  48943. const n3 = t3.data.method, s5 = e3.secretMethods || {}, r3 = s5[n3] || s5["*"];
  48944. r3 && (t3.secretType = r3);
  48945. }(n2, d2);
  48946. let p2 = false;
  48947. try {
  48948. h2 = await e2.callFunction(d2);
  48949. } catch (e3) {
  48950. p2 = true, h2 = { result: new te(e3) };
  48951. }
  48952. const { errSubject: f2, errCode: g2, errMsg: m2, newToken: y2 } = h2.result || {};
  48953. if (a2 && uni.hideLoading(), y2 && y2.token && y2.tokenExpired && (ie(y2), Y(H.REFRESH_TOKEN, { ...y2 })), g2) {
  48954. let e3 = m2;
  48955. if (p2 && o2) {
  48956. e3 = (await o2({ objectName: t2, methodName: c2, params: u2, errSubject: f2, errCode: g2, errMsg: m2 })).errMsg || m2;
  48957. }
  48958. if (a2)
  48959. if ("toast" === i2.type)
  48960. uni.showToast({ title: e3, icon: "none" });
  48961. else {
  48962. if ("modal" !== i2.type)
  48963. throw new Error(`Invalid errorOptions.type: ${i2.type}`);
  48964. {
  48965. const { confirm: t3 } = await async function({ title: e4, content: t4, showCancel: n4, cancelText: s5, confirmText: r3 } = {}) {
  48966. return new Promise((i3, o3) => {
  48967. uni.showModal({ title: e4, content: t4, showCancel: n4, cancelText: s5, confirmText: r3, success(e5) {
  48968. i3(e5);
  48969. }, fail() {
  48970. i3({ confirm: false, cancel: true });
  48971. } });
  48972. });
  48973. }({ title: "提示", content: e3, showCancel: i2.retry, cancelText: "取消", confirmText: i2.retry ? "重试" : "确定" });
  48974. if (i2.retry && t3)
  48975. return s4(...u2);
  48976. }
  48977. }
  48978. const n3 = new te({ subject: f2, code: g2, message: m2, requestId: h2.requestId });
  48979. throw n3.detail = h2.result, Y(H.RESPONSE, { type: J.CLOUD_OBJECT, content: n3 }), n3;
  48980. }
  48981. return Y(H.RESPONSE, { type: J.CLOUD_OBJECT, content: h2.result }), h2.result;
  48982. }, interceptorName: "callObject", getCallbackArgs: function({ params: e3 } = {}) {
  48983. return { objectName: t2, methodName: c2, params: e3 };
  48984. } });
  48985. } });
  48986. };
  48987. }
  48988. function Ws(e2) {
  48989. return U(Xt.replace("{spaceId}", e2.config.spaceId));
  48990. }
  48991. async function Hs({ openid: e2, callLoginByWeixin: t2 = false } = {}) {
  48992. Ws(this);
  48993. throw new Error(`[SecureNetwork] API \`initSecureNetworkByWeixin\` is not supported on platform \`${P}\``);
  48994. }
  48995. async function Js(e2) {
  48996. const t2 = Ws(this);
  48997. return t2.initPromise || (t2.initPromise = Hs.call(this, e2).then((e3) => e3).catch((e3) => {
  48998. throw delete t2.initPromise, e3;
  48999. })), t2.initPromise;
  49000. }
  49001. function zs(e2) {
  49002. return function({ openid: t2, callLoginByWeixin: n2 = false } = {}) {
  49003. return Js.call(e2, { openid: t2, callLoginByWeixin: n2 });
  49004. };
  49005. }
  49006. function Vs(e2) {
  49007. !function(e3) {
  49008. he = e3;
  49009. }(e2);
  49010. }
  49011. function Gs(e2) {
  49012. const n2 = { getAppBaseInfo: uni.getSystemInfo, getPushClientId: uni.getPushClientId };
  49013. return function(s2) {
  49014. return new Promise((r2, i2) => {
  49015. n2[e2]({ ...s2, success(e3) {
  49016. r2(e3);
  49017. }, fail(e3) {
  49018. i2(e3);
  49019. } });
  49020. });
  49021. };
  49022. }
  49023. class Ys extends S {
  49024. constructor() {
  49025. super(), this._uniPushMessageCallback = this._receivePushMessage.bind(this), this._currentMessageId = -1, this._payloadQueue = [];
  49026. }
  49027. init() {
  49028. return Promise.all([Gs("getAppBaseInfo")(), Gs("getPushClientId")()]).then(([{ appId: e2 } = {}, { cid: t2 } = {}] = []) => {
  49029. if (!e2)
  49030. throw new Error("Invalid appId, please check the manifest.json file");
  49031. if (!t2)
  49032. throw new Error("Invalid push client id");
  49033. this._appId = e2, this._pushClientId = t2, this._seqId = Date.now() + "-" + Math.floor(9e5 * Math.random() + 1e5), this.emit("open"), this._initMessageListener();
  49034. }, (e2) => {
  49035. throw this.emit("error", e2), this.close(), e2;
  49036. });
  49037. }
  49038. async open() {
  49039. return this.init();
  49040. }
  49041. _isUniCloudSSE(e2) {
  49042. if ("receive" !== e2.type)
  49043. return false;
  49044. const t2 = e2 && e2.data && e2.data.payload;
  49045. return !(!t2 || "UNI_CLOUD_SSE" !== t2.channel || t2.seqId !== this._seqId);
  49046. }
  49047. _receivePushMessage(e2) {
  49048. if (!this._isUniCloudSSE(e2))
  49049. return;
  49050. const t2 = e2 && e2.data && e2.data.payload, { action: n2, messageId: s2, message: r2 } = t2;
  49051. this._payloadQueue.push({ action: n2, messageId: s2, message: r2 }), this._consumMessage();
  49052. }
  49053. _consumMessage() {
  49054. for (; ; ) {
  49055. const e2 = this._payloadQueue.find((e3) => e3.messageId === this._currentMessageId + 1);
  49056. if (!e2)
  49057. break;
  49058. this._currentMessageId++, this._parseMessagePayload(e2);
  49059. }
  49060. }
  49061. _parseMessagePayload(e2) {
  49062. const { action: t2, messageId: n2, message: s2 } = e2;
  49063. "end" === t2 ? this._end({ messageId: n2, message: s2 }) : "message" === t2 && this._appendMessage({ messageId: n2, message: s2 });
  49064. }
  49065. _appendMessage({ messageId: e2, message: t2 } = {}) {
  49066. this.emit("message", t2);
  49067. }
  49068. _end({ messageId: e2, message: t2 } = {}) {
  49069. this.emit("end", t2), this.close();
  49070. }
  49071. _initMessageListener() {
  49072. uni.onPushMessage(this._uniPushMessageCallback);
  49073. }
  49074. _destroy() {
  49075. uni.offPushMessage(this._uniPushMessageCallback);
  49076. }
  49077. toJSON() {
  49078. return { appId: this._appId, pushClientId: this._pushClientId, seqId: this._seqId };
  49079. }
  49080. close() {
  49081. this._destroy(), this.emit("close");
  49082. }
  49083. }
  49084. async function Qs(e2) {
  49085. {
  49086. const { osName: e3, osVersion: t3 } = ce();
  49087. "ios" === e3 && function(e4) {
  49088. if (!e4 || "string" != typeof e4)
  49089. return 0;
  49090. const t4 = e4.match(/^(\d+)./);
  49091. return t4 && t4[1] ? parseInt(t4[1]) : 0;
  49092. }(t3) >= 14 && console.warn("iOS 14及以上版本连接uniCloud本地调试服务需要允许客户端查找并连接到本地网络上的设备(仅开发期间需要,发行后不需要)");
  49093. }
  49094. const t2 = e2.__dev__;
  49095. if (!t2.debugInfo)
  49096. return;
  49097. const { address: n2, servePort: s2 } = t2.debugInfo, { address: r2 } = await Ot(n2, s2);
  49098. if (r2)
  49099. return t2.localAddress = r2, void (t2.localPort = s2);
  49100. const i2 = console["error"];
  49101. let o2 = "";
  49102. 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)
  49103. throw new Error(o2);
  49104. i2(o2);
  49105. }
  49106. function Xs(e2) {
  49107. e2._initPromiseHub || (e2._initPromiseHub = new v({ createPromise: function() {
  49108. let t2 = Promise.resolve();
  49109. var n2;
  49110. n2 = 1, t2 = new Promise((e3) => {
  49111. setTimeout(() => {
  49112. e3();
  49113. }, n2);
  49114. });
  49115. const s2 = e2.auth();
  49116. return t2.then(() => s2.getLoginState()).then((e3) => e3 ? Promise.resolve() : s2.signInAnonymously());
  49117. } }));
  49118. }
  49119. const Zs = { tcb: Pt, tencent: Pt, aliyun: fe, private: Rt, dcloud: Rt, alipay: Bt };
  49120. let er = new class {
  49121. init(e2) {
  49122. let t2 = {};
  49123. const n2 = Zs[e2.provider];
  49124. if (!n2)
  49125. throw new Error("未提供正确的provider参数");
  49126. t2 = n2.init(e2), function(e3) {
  49127. const t3 = {};
  49128. e3.__dev__ = t3, t3.debugLog = "app" === P;
  49129. const n3 = C;
  49130. n3 && !n3.code && (t3.debugInfo = n3);
  49131. const s2 = new v({ createPromise: function() {
  49132. return Qs(e3);
  49133. } });
  49134. t3.initLocalNetwork = function() {
  49135. return s2.exec();
  49136. };
  49137. }(t2), Xs(t2), Gn(t2), function(e3) {
  49138. const t3 = e3.uploadFile;
  49139. e3.uploadFile = function(e4) {
  49140. return t3.call(this, e4);
  49141. };
  49142. }(t2), function(e3) {
  49143. e3.database = function(t3) {
  49144. if (t3 && Object.keys(t3).length > 0)
  49145. return e3.init(t3).database();
  49146. if (this._database)
  49147. return this._database;
  49148. const n3 = as(cs, { uniClient: e3 });
  49149. return this._database = n3, n3;
  49150. }, e3.databaseForJQL = function(t3) {
  49151. if (t3 && Object.keys(t3).length > 0)
  49152. return e3.init(t3).databaseForJQL();
  49153. if (this._databaseForJQL)
  49154. return this._databaseForJQL;
  49155. const n3 = as(cs, { uniClient: e3, isJQL: true });
  49156. return this._databaseForJQL = n3, n3;
  49157. };
  49158. }(t2), function(e3) {
  49159. e3.getCurrentUserInfo = qs, e3.chooseAndUploadFile = Ks.initChooseAndUploadFile(e3), Object.assign(e3, { get mixinDatacom() {
  49160. return $s(e3);
  49161. } }), e3.SSEChannel = Ys, e3.initSecureNetworkByWeixin = zs(e3), e3.setCustomClientInfo = Vs, e3.importObject = Bs(e3);
  49162. }(t2);
  49163. return ["callFunction", "uploadFile", "deleteFile", "getTempFileURL", "downloadFile", "chooseAndUploadFile"].forEach((e3) => {
  49164. if (!t2[e3])
  49165. return;
  49166. const n3 = t2[e3];
  49167. t2[e3] = function() {
  49168. return n3.apply(t2, Array.from(arguments));
  49169. }, t2[e3] = (/* @__PURE__ */ function(e4, t3) {
  49170. return function(n4) {
  49171. let s2 = false;
  49172. if ("callFunction" === t3) {
  49173. const e5 = n4 && n4.type || l.DEFAULT;
  49174. s2 = e5 !== l.DEFAULT;
  49175. }
  49176. const r2 = "callFunction" === t3 && !s2, i2 = this._initPromiseHub.exec();
  49177. n4 = n4 || {};
  49178. 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))));
  49179. if (!(o2 || a2 || c2))
  49180. return u2;
  49181. u2.then((e5) => {
  49182. o2 && o2(e5), c2 && c2(e5), r2 && Y(H.RESPONSE, { type: J.CLOUD_FUNCTION, content: e5 });
  49183. }, (e5) => {
  49184. a2 && a2(e5), c2 && c2(e5), r2 && Y(H.RESPONSE, { type: J.CLOUD_FUNCTION, content: e5 });
  49185. });
  49186. };
  49187. }(t2[e3], e3)).bind(t2);
  49188. }), t2.init = this.init, t2;
  49189. }
  49190. }();
  49191. (() => {
  49192. const e2 = O;
  49193. let t2 = {};
  49194. if (e2 && 1 === e2.length)
  49195. t2 = e2[0], er = er.init(t2), er._isDefault = true;
  49196. else {
  49197. const t3 = ["auth", "callFunction", "uploadFile", "deleteFile", "getTempFileURL", "downloadFile"], n2 = ["database", "getCurrentUserInfo", "importObject"];
  49198. let s2;
  49199. s2 = e2 && e2.length > 0 ? "应用有多个服务空间,请通过uniCloud.init方法指定要使用的服务空间" : "应用未关联服务空间,请在uniCloud目录右键关联服务空间", [...t3, ...n2].forEach((e3) => {
  49200. er[e3] = function() {
  49201. if (console.error(s2), -1 === n2.indexOf(e3))
  49202. return Promise.reject(new te({ code: "SYS_ERR", message: s2 }));
  49203. console.error(s2);
  49204. };
  49205. });
  49206. }
  49207. if (Object.assign(er, { get mixinDatacom() {
  49208. return $s(er);
  49209. } }), Ls(er), er.addInterceptor = F, er.removeInterceptor = K, er.interceptObject = B, uni.__uniCloud = er, "app" === P) {
  49210. const e3 = D();
  49211. e3.uniCloud = er, e3.UniCloudError = te;
  49212. }
  49213. })();
  49214. var tr = er;
  49215. function getDevtoolsGlobalHook() {
  49216. return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
  49217. }
  49218. function getTarget() {
  49219. return typeof navigator !== "undefined" && typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
  49220. }
  49221. const isProxyAvailable = typeof Proxy === "function";
  49222. const HOOK_SETUP = "devtools-plugin:setup";
  49223. const HOOK_PLUGIN_SETTINGS_SET = "plugin:settings:set";
  49224. class ApiProxy {
  49225. constructor(plugin, hook) {
  49226. this.target = null;
  49227. this.targetQueue = [];
  49228. this.onQueue = [];
  49229. this.plugin = plugin;
  49230. this.hook = hook;
  49231. const defaultSettings = {};
  49232. if (plugin.settings) {
  49233. for (const id in plugin.settings) {
  49234. const item = plugin.settings[id];
  49235. defaultSettings[id] = item.defaultValue;
  49236. }
  49237. }
  49238. const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
  49239. let currentSettings = { ...defaultSettings };
  49240. try {
  49241. const raw = localStorage.getItem(localSettingsSaveId);
  49242. const data = JSON.parse(raw);
  49243. Object.assign(currentSettings, data);
  49244. } catch (e2) {
  49245. }
  49246. this.fallbacks = {
  49247. getSettings() {
  49248. return currentSettings;
  49249. },
  49250. setSettings(value2) {
  49251. try {
  49252. localStorage.setItem(localSettingsSaveId, JSON.stringify(value2));
  49253. } catch (e2) {
  49254. }
  49255. currentSettings = value2;
  49256. }
  49257. };
  49258. hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value2) => {
  49259. if (pluginId === this.plugin.id) {
  49260. this.fallbacks.setSettings(value2);
  49261. }
  49262. });
  49263. this.proxiedOn = new Proxy({}, {
  49264. get: (_target, prop) => {
  49265. if (this.target) {
  49266. return this.target.on[prop];
  49267. } else {
  49268. return (...args) => {
  49269. this.onQueue.push({
  49270. method: prop,
  49271. args
  49272. });
  49273. };
  49274. }
  49275. }
  49276. });
  49277. this.proxiedTarget = new Proxy({}, {
  49278. get: (_target, prop) => {
  49279. if (this.target) {
  49280. return this.target[prop];
  49281. } else if (prop === "on") {
  49282. return this.proxiedOn;
  49283. } else if (Object.keys(this.fallbacks).includes(prop)) {
  49284. return (...args) => {
  49285. this.targetQueue.push({
  49286. method: prop,
  49287. args,
  49288. resolve: () => {
  49289. }
  49290. });
  49291. return this.fallbacks[prop](...args);
  49292. };
  49293. } else {
  49294. return (...args) => {
  49295. return new Promise((resolve) => {
  49296. this.targetQueue.push({
  49297. method: prop,
  49298. args,
  49299. resolve
  49300. });
  49301. });
  49302. };
  49303. }
  49304. }
  49305. });
  49306. }
  49307. async setRealTarget(target) {
  49308. this.target = target;
  49309. for (const item of this.onQueue) {
  49310. this.target.on[item.method](...item.args);
  49311. }
  49312. for (const item of this.targetQueue) {
  49313. item.resolve(await this.target[item.method](...item.args));
  49314. }
  49315. }
  49316. }
  49317. function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
  49318. const target = getTarget();
  49319. const hook = getDevtoolsGlobalHook();
  49320. const enableProxy = isProxyAvailable && pluginDescriptor.enableEarlyProxy;
  49321. if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
  49322. hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
  49323. } else {
  49324. const proxy = enableProxy ? new ApiProxy(pluginDescriptor, hook) : null;
  49325. const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
  49326. list.push({
  49327. pluginDescriptor,
  49328. setupFn,
  49329. proxy
  49330. });
  49331. if (proxy)
  49332. setupFn(proxy.proxiedTarget);
  49333. }
  49334. }
  49335. /*!
  49336. * vuex v4.1.0
  49337. * (c) 2022 Evan You
  49338. * @license MIT
  49339. */
  49340. var storeKey = "store";
  49341. function useStore(key) {
  49342. if (key === void 0)
  49343. key = null;
  49344. return vue.inject(key !== null ? key : storeKey);
  49345. }
  49346. function forEachValue(obj, fn) {
  49347. Object.keys(obj).forEach(function(key) {
  49348. return fn(obj[key], key);
  49349. });
  49350. }
  49351. function isObject$1(obj) {
  49352. return obj !== null && typeof obj === "object";
  49353. }
  49354. function isPromise(val) {
  49355. return val && typeof val.then === "function";
  49356. }
  49357. function assert(condition, msg) {
  49358. if (!condition) {
  49359. throw new Error("[vuex] " + msg);
  49360. }
  49361. }
  49362. function partial(fn, arg) {
  49363. return function() {
  49364. return fn(arg);
  49365. };
  49366. }
  49367. function genericSubscribe(fn, subs, options) {
  49368. if (subs.indexOf(fn) < 0) {
  49369. options && options.prepend ? subs.unshift(fn) : subs.push(fn);
  49370. }
  49371. return function() {
  49372. var i2 = subs.indexOf(fn);
  49373. if (i2 > -1) {
  49374. subs.splice(i2, 1);
  49375. }
  49376. };
  49377. }
  49378. function resetStore(store2, hot) {
  49379. store2._actions = /* @__PURE__ */ Object.create(null);
  49380. store2._mutations = /* @__PURE__ */ Object.create(null);
  49381. store2._wrappedGetters = /* @__PURE__ */ Object.create(null);
  49382. store2._modulesNamespaceMap = /* @__PURE__ */ Object.create(null);
  49383. var state = store2.state;
  49384. installModule(store2, state, [], store2._modules.root, true);
  49385. resetStoreState(store2, state, hot);
  49386. }
  49387. function resetStoreState(store2, state, hot) {
  49388. var oldState = store2._state;
  49389. var oldScope = store2._scope;
  49390. store2.getters = {};
  49391. store2._makeLocalGettersCache = /* @__PURE__ */ Object.create(null);
  49392. var wrappedGetters = store2._wrappedGetters;
  49393. var computedObj = {};
  49394. var computedCache = {};
  49395. var scope = vue.effectScope(true);
  49396. scope.run(function() {
  49397. forEachValue(wrappedGetters, function(fn, key) {
  49398. computedObj[key] = partial(fn, store2);
  49399. computedCache[key] = vue.computed(function() {
  49400. return computedObj[key]();
  49401. });
  49402. Object.defineProperty(store2.getters, key, {
  49403. get: function() {
  49404. return computedCache[key].value;
  49405. },
  49406. enumerable: true
  49407. // for local getters
  49408. });
  49409. });
  49410. });
  49411. store2._state = vue.reactive({
  49412. data: state
  49413. });
  49414. store2._scope = scope;
  49415. if (store2.strict) {
  49416. enableStrictMode(store2);
  49417. }
  49418. if (oldState) {
  49419. if (hot) {
  49420. store2._withCommit(function() {
  49421. oldState.data = null;
  49422. });
  49423. }
  49424. }
  49425. if (oldScope) {
  49426. oldScope.stop();
  49427. }
  49428. }
  49429. function installModule(store2, rootState, path, module, hot) {
  49430. var isRoot = !path.length;
  49431. var namespace = store2._modules.getNamespace(path);
  49432. if (module.namespaced) {
  49433. if (store2._modulesNamespaceMap[namespace] && true) {
  49434. console.error("[vuex] duplicate namespace " + namespace + " for the namespaced module " + path.join("/"));
  49435. }
  49436. store2._modulesNamespaceMap[namespace] = module;
  49437. }
  49438. if (!isRoot && !hot) {
  49439. var parentState = getNestedState(rootState, path.slice(0, -1));
  49440. var moduleName = path[path.length - 1];
  49441. store2._withCommit(function() {
  49442. {
  49443. if (moduleName in parentState) {
  49444. console.warn(
  49445. '[vuex] state field "' + moduleName + '" was overridden by a module with the same name at "' + path.join(".") + '"'
  49446. );
  49447. }
  49448. }
  49449. parentState[moduleName] = module.state;
  49450. });
  49451. }
  49452. var local = module.context = makeLocalContext(store2, namespace, path);
  49453. module.forEachMutation(function(mutation, key) {
  49454. var namespacedType = namespace + key;
  49455. registerMutation(store2, namespacedType, mutation, local);
  49456. });
  49457. module.forEachAction(function(action, key) {
  49458. var type = action.root ? key : namespace + key;
  49459. var handler = action.handler || action;
  49460. registerAction(store2, type, handler, local);
  49461. });
  49462. module.forEachGetter(function(getter, key) {
  49463. var namespacedType = namespace + key;
  49464. registerGetter(store2, namespacedType, getter, local);
  49465. });
  49466. module.forEachChild(function(child, key) {
  49467. installModule(store2, rootState, path.concat(key), child, hot);
  49468. });
  49469. }
  49470. function makeLocalContext(store2, namespace, path) {
  49471. var noNamespace = namespace === "";
  49472. var local = {
  49473. dispatch: noNamespace ? store2.dispatch : function(_type, _payload, _options) {
  49474. var args = unifyObjectStyle(_type, _payload, _options);
  49475. var payload = args.payload;
  49476. var options = args.options;
  49477. var type = args.type;
  49478. if (!options || !options.root) {
  49479. type = namespace + type;
  49480. if (!store2._actions[type]) {
  49481. console.error("[vuex] unknown local action type: " + args.type + ", global type: " + type);
  49482. return;
  49483. }
  49484. }
  49485. return store2.dispatch(type, payload);
  49486. },
  49487. commit: noNamespace ? store2.commit : function(_type, _payload, _options) {
  49488. var args = unifyObjectStyle(_type, _payload, _options);
  49489. var payload = args.payload;
  49490. var options = args.options;
  49491. var type = args.type;
  49492. if (!options || !options.root) {
  49493. type = namespace + type;
  49494. if (!store2._mutations[type]) {
  49495. console.error("[vuex] unknown local mutation type: " + args.type + ", global type: " + type);
  49496. return;
  49497. }
  49498. }
  49499. store2.commit(type, payload, options);
  49500. }
  49501. };
  49502. Object.defineProperties(local, {
  49503. getters: {
  49504. get: noNamespace ? function() {
  49505. return store2.getters;
  49506. } : function() {
  49507. return makeLocalGetters(store2, namespace);
  49508. }
  49509. },
  49510. state: {
  49511. get: function() {
  49512. return getNestedState(store2.state, path);
  49513. }
  49514. }
  49515. });
  49516. return local;
  49517. }
  49518. function makeLocalGetters(store2, namespace) {
  49519. if (!store2._makeLocalGettersCache[namespace]) {
  49520. var gettersProxy = {};
  49521. var splitPos = namespace.length;
  49522. Object.keys(store2.getters).forEach(function(type) {
  49523. if (type.slice(0, splitPos) !== namespace) {
  49524. return;
  49525. }
  49526. var localType = type.slice(splitPos);
  49527. Object.defineProperty(gettersProxy, localType, {
  49528. get: function() {
  49529. return store2.getters[type];
  49530. },
  49531. enumerable: true
  49532. });
  49533. });
  49534. store2._makeLocalGettersCache[namespace] = gettersProxy;
  49535. }
  49536. return store2._makeLocalGettersCache[namespace];
  49537. }
  49538. function registerMutation(store2, type, handler, local) {
  49539. var entry = store2._mutations[type] || (store2._mutations[type] = []);
  49540. entry.push(function wrappedMutationHandler(payload) {
  49541. handler.call(store2, local.state, payload);
  49542. });
  49543. }
  49544. function registerAction(store2, type, handler, local) {
  49545. var entry = store2._actions[type] || (store2._actions[type] = []);
  49546. entry.push(function wrappedActionHandler(payload) {
  49547. var res = handler.call(store2, {
  49548. dispatch: local.dispatch,
  49549. commit: local.commit,
  49550. getters: local.getters,
  49551. state: local.state,
  49552. rootGetters: store2.getters,
  49553. rootState: store2.state
  49554. }, payload);
  49555. if (!isPromise(res)) {
  49556. res = Promise.resolve(res);
  49557. }
  49558. if (store2._devtoolHook) {
  49559. return res.catch(function(err) {
  49560. store2._devtoolHook.emit("vuex:error", err);
  49561. throw err;
  49562. });
  49563. } else {
  49564. return res;
  49565. }
  49566. });
  49567. }
  49568. function registerGetter(store2, type, rawGetter, local) {
  49569. if (store2._wrappedGetters[type]) {
  49570. {
  49571. console.error("[vuex] duplicate getter key: " + type);
  49572. }
  49573. return;
  49574. }
  49575. store2._wrappedGetters[type] = function wrappedGetter(store22) {
  49576. return rawGetter(
  49577. local.state,
  49578. // local state
  49579. local.getters,
  49580. // local getters
  49581. store22.state,
  49582. // root state
  49583. store22.getters
  49584. // root getters
  49585. );
  49586. };
  49587. }
  49588. function enableStrictMode(store2) {
  49589. vue.watch(function() {
  49590. return store2._state.data;
  49591. }, function() {
  49592. {
  49593. assert(store2._committing, "do not mutate vuex store state outside mutation handlers.");
  49594. }
  49595. }, { deep: true, flush: "sync" });
  49596. }
  49597. function getNestedState(state, path) {
  49598. return path.reduce(function(state2, key) {
  49599. return state2[key];
  49600. }, state);
  49601. }
  49602. function unifyObjectStyle(type, payload, options) {
  49603. if (isObject$1(type) && type.type) {
  49604. options = payload;
  49605. payload = type;
  49606. type = type.type;
  49607. }
  49608. {
  49609. assert(typeof type === "string", "expects string as the type, but found " + typeof type + ".");
  49610. }
  49611. return { type, payload, options };
  49612. }
  49613. var LABEL_VUEX_BINDINGS = "vuex bindings";
  49614. var MUTATIONS_LAYER_ID = "vuex:mutations";
  49615. var ACTIONS_LAYER_ID = "vuex:actions";
  49616. var INSPECTOR_ID = "vuex";
  49617. var actionId = 0;
  49618. function addDevtools(app2, store2) {
  49619. setupDevtoolsPlugin(
  49620. {
  49621. id: "org.vuejs.vuex",
  49622. app: app2,
  49623. label: "Vuex",
  49624. homepage: "https://next.vuex.vuejs.org/",
  49625. logo: "https://vuejs.org/images/icons/favicon-96x96.png",
  49626. packageName: "vuex",
  49627. componentStateTypes: [LABEL_VUEX_BINDINGS]
  49628. },
  49629. function(api2) {
  49630. api2.addTimelineLayer({
  49631. id: MUTATIONS_LAYER_ID,
  49632. label: "Vuex Mutations",
  49633. color: COLOR_LIME_500
  49634. });
  49635. api2.addTimelineLayer({
  49636. id: ACTIONS_LAYER_ID,
  49637. label: "Vuex Actions",
  49638. color: COLOR_LIME_500
  49639. });
  49640. api2.addInspector({
  49641. id: INSPECTOR_ID,
  49642. label: "Vuex",
  49643. icon: "storage",
  49644. treeFilterPlaceholder: "Filter stores..."
  49645. });
  49646. api2.on.getInspectorTree(function(payload) {
  49647. if (payload.app === app2 && payload.inspectorId === INSPECTOR_ID) {
  49648. if (payload.filter) {
  49649. var nodes = [];
  49650. flattenStoreForInspectorTree(nodes, store2._modules.root, payload.filter, "");
  49651. payload.rootNodes = nodes;
  49652. } else {
  49653. payload.rootNodes = [
  49654. formatStoreForInspectorTree(store2._modules.root, "")
  49655. ];
  49656. }
  49657. }
  49658. });
  49659. api2.on.getInspectorState(function(payload) {
  49660. if (payload.app === app2 && payload.inspectorId === INSPECTOR_ID) {
  49661. var modulePath = payload.nodeId;
  49662. makeLocalGetters(store2, modulePath);
  49663. payload.state = formatStoreForInspectorState(
  49664. getStoreModule(store2._modules, modulePath),
  49665. modulePath === "root" ? store2.getters : store2._makeLocalGettersCache,
  49666. modulePath
  49667. );
  49668. }
  49669. });
  49670. api2.on.editInspectorState(function(payload) {
  49671. if (payload.app === app2 && payload.inspectorId === INSPECTOR_ID) {
  49672. var modulePath = payload.nodeId;
  49673. var path = payload.path;
  49674. if (modulePath !== "root") {
  49675. path = modulePath.split("/").filter(Boolean).concat(path);
  49676. }
  49677. store2._withCommit(function() {
  49678. payload.set(store2._state.data, path, payload.state.value);
  49679. });
  49680. }
  49681. });
  49682. store2.subscribe(function(mutation, state) {
  49683. var data = {};
  49684. if (mutation.payload) {
  49685. data.payload = mutation.payload;
  49686. }
  49687. data.state = state;
  49688. api2.notifyComponentUpdate();
  49689. api2.sendInspectorTree(INSPECTOR_ID);
  49690. api2.sendInspectorState(INSPECTOR_ID);
  49691. api2.addTimelineEvent({
  49692. layerId: MUTATIONS_LAYER_ID,
  49693. event: {
  49694. time: Date.now(),
  49695. title: mutation.type,
  49696. data
  49697. }
  49698. });
  49699. });
  49700. store2.subscribeAction({
  49701. before: function(action, state) {
  49702. var data = {};
  49703. if (action.payload) {
  49704. data.payload = action.payload;
  49705. }
  49706. action._id = actionId++;
  49707. action._time = Date.now();
  49708. data.state = state;
  49709. api2.addTimelineEvent({
  49710. layerId: ACTIONS_LAYER_ID,
  49711. event: {
  49712. time: action._time,
  49713. title: action.type,
  49714. groupId: action._id,
  49715. subtitle: "start",
  49716. data
  49717. }
  49718. });
  49719. },
  49720. after: function(action, state) {
  49721. var data = {};
  49722. var duration = Date.now() - action._time;
  49723. data.duration = {
  49724. _custom: {
  49725. type: "duration",
  49726. display: duration + "ms",
  49727. tooltip: "Action duration",
  49728. value: duration
  49729. }
  49730. };
  49731. if (action.payload) {
  49732. data.payload = action.payload;
  49733. }
  49734. data.state = state;
  49735. api2.addTimelineEvent({
  49736. layerId: ACTIONS_LAYER_ID,
  49737. event: {
  49738. time: Date.now(),
  49739. title: action.type,
  49740. groupId: action._id,
  49741. subtitle: "end",
  49742. data
  49743. }
  49744. });
  49745. }
  49746. });
  49747. }
  49748. );
  49749. }
  49750. var COLOR_LIME_500 = 8702998;
  49751. var COLOR_DARK = 6710886;
  49752. var COLOR_WHITE = 16777215;
  49753. var TAG_NAMESPACED = {
  49754. label: "namespaced",
  49755. textColor: COLOR_WHITE,
  49756. backgroundColor: COLOR_DARK
  49757. };
  49758. function extractNameFromPath(path) {
  49759. return path && path !== "root" ? path.split("/").slice(-2, -1)[0] : "Root";
  49760. }
  49761. function formatStoreForInspectorTree(module, path) {
  49762. return {
  49763. id: path || "root",
  49764. // all modules end with a `/`, we want the last segment only
  49765. // cart/ -> cart
  49766. // nested/cart/ -> cart
  49767. label: extractNameFromPath(path),
  49768. tags: module.namespaced ? [TAG_NAMESPACED] : [],
  49769. children: Object.keys(module._children).map(
  49770. function(moduleName) {
  49771. return formatStoreForInspectorTree(
  49772. module._children[moduleName],
  49773. path + moduleName + "/"
  49774. );
  49775. }
  49776. )
  49777. };
  49778. }
  49779. function flattenStoreForInspectorTree(result, module, filter, path) {
  49780. if (path.includes(filter)) {
  49781. result.push({
  49782. id: path || "root",
  49783. label: path.endsWith("/") ? path.slice(0, path.length - 1) : path || "Root",
  49784. tags: module.namespaced ? [TAG_NAMESPACED] : []
  49785. });
  49786. }
  49787. Object.keys(module._children).forEach(function(moduleName) {
  49788. flattenStoreForInspectorTree(result, module._children[moduleName], filter, path + moduleName + "/");
  49789. });
  49790. }
  49791. function formatStoreForInspectorState(module, getters2, path) {
  49792. getters2 = path === "root" ? getters2 : getters2[path];
  49793. var gettersKeys = Object.keys(getters2);
  49794. var storeState = {
  49795. state: Object.keys(module.state).map(function(key) {
  49796. return {
  49797. key,
  49798. editable: true,
  49799. value: module.state[key]
  49800. };
  49801. })
  49802. };
  49803. if (gettersKeys.length) {
  49804. var tree = transformPathsToObjectTree(getters2);
  49805. storeState.getters = Object.keys(tree).map(function(key) {
  49806. return {
  49807. key: key.endsWith("/") ? extractNameFromPath(key) : key,
  49808. editable: false,
  49809. value: canThrow(function() {
  49810. return tree[key];
  49811. })
  49812. };
  49813. });
  49814. }
  49815. return storeState;
  49816. }
  49817. function transformPathsToObjectTree(getters2) {
  49818. var result = {};
  49819. Object.keys(getters2).forEach(function(key) {
  49820. var path = key.split("/");
  49821. if (path.length > 1) {
  49822. var target = result;
  49823. var leafKey = path.pop();
  49824. path.forEach(function(p2) {
  49825. if (!target[p2]) {
  49826. target[p2] = {
  49827. _custom: {
  49828. value: {},
  49829. display: p2,
  49830. tooltip: "Module",
  49831. abstract: true
  49832. }
  49833. };
  49834. }
  49835. target = target[p2]._custom.value;
  49836. });
  49837. target[leafKey] = canThrow(function() {
  49838. return getters2[key];
  49839. });
  49840. } else {
  49841. result[key] = canThrow(function() {
  49842. return getters2[key];
  49843. });
  49844. }
  49845. });
  49846. return result;
  49847. }
  49848. function getStoreModule(moduleMap, path) {
  49849. var names = path.split("/").filter(function(n2) {
  49850. return n2;
  49851. });
  49852. return names.reduce(
  49853. function(module, moduleName, i2) {
  49854. var child = module[moduleName];
  49855. if (!child) {
  49856. throw new Error('Missing module "' + moduleName + '" for path "' + path + '".');
  49857. }
  49858. return i2 === names.length - 1 ? child : child._children;
  49859. },
  49860. path === "root" ? moduleMap : moduleMap.root._children
  49861. );
  49862. }
  49863. function canThrow(cb) {
  49864. try {
  49865. return cb();
  49866. } catch (e2) {
  49867. return e2;
  49868. }
  49869. }
  49870. var Module = function Module2(rawModule, runtime) {
  49871. this.runtime = runtime;
  49872. this._children = /* @__PURE__ */ Object.create(null);
  49873. this._rawModule = rawModule;
  49874. var rawState = rawModule.state;
  49875. this.state = (typeof rawState === "function" ? rawState() : rawState) || {};
  49876. };
  49877. var prototypeAccessors$1 = { namespaced: { configurable: true } };
  49878. prototypeAccessors$1.namespaced.get = function() {
  49879. return !!this._rawModule.namespaced;
  49880. };
  49881. Module.prototype.addChild = function addChild(key, module) {
  49882. this._children[key] = module;
  49883. };
  49884. Module.prototype.removeChild = function removeChild(key) {
  49885. delete this._children[key];
  49886. };
  49887. Module.prototype.getChild = function getChild(key) {
  49888. return this._children[key];
  49889. };
  49890. Module.prototype.hasChild = function hasChild(key) {
  49891. return key in this._children;
  49892. };
  49893. Module.prototype.update = function update(rawModule) {
  49894. this._rawModule.namespaced = rawModule.namespaced;
  49895. if (rawModule.actions) {
  49896. this._rawModule.actions = rawModule.actions;
  49897. }
  49898. if (rawModule.mutations) {
  49899. this._rawModule.mutations = rawModule.mutations;
  49900. }
  49901. if (rawModule.getters) {
  49902. this._rawModule.getters = rawModule.getters;
  49903. }
  49904. };
  49905. Module.prototype.forEachChild = function forEachChild(fn) {
  49906. forEachValue(this._children, fn);
  49907. };
  49908. Module.prototype.forEachGetter = function forEachGetter(fn) {
  49909. if (this._rawModule.getters) {
  49910. forEachValue(this._rawModule.getters, fn);
  49911. }
  49912. };
  49913. Module.prototype.forEachAction = function forEachAction(fn) {
  49914. if (this._rawModule.actions) {
  49915. forEachValue(this._rawModule.actions, fn);
  49916. }
  49917. };
  49918. Module.prototype.forEachMutation = function forEachMutation(fn) {
  49919. if (this._rawModule.mutations) {
  49920. forEachValue(this._rawModule.mutations, fn);
  49921. }
  49922. };
  49923. Object.defineProperties(Module.prototype, prototypeAccessors$1);
  49924. var ModuleCollection = function ModuleCollection2(rawRootModule) {
  49925. this.register([], rawRootModule, false);
  49926. };
  49927. ModuleCollection.prototype.get = function get(path) {
  49928. return path.reduce(function(module, key) {
  49929. return module.getChild(key);
  49930. }, this.root);
  49931. };
  49932. ModuleCollection.prototype.getNamespace = function getNamespace(path) {
  49933. var module = this.root;
  49934. return path.reduce(function(namespace, key) {
  49935. module = module.getChild(key);
  49936. return namespace + (module.namespaced ? key + "/" : "");
  49937. }, "");
  49938. };
  49939. ModuleCollection.prototype.update = function update$1(rawRootModule) {
  49940. update2([], this.root, rawRootModule);
  49941. };
  49942. ModuleCollection.prototype.register = function register(path, rawModule, runtime) {
  49943. var this$1$1 = this;
  49944. if (runtime === void 0)
  49945. runtime = true;
  49946. {
  49947. assertRawModule(path, rawModule);
  49948. }
  49949. var newModule = new Module(rawModule, runtime);
  49950. if (path.length === 0) {
  49951. this.root = newModule;
  49952. } else {
  49953. var parent = this.get(path.slice(0, -1));
  49954. parent.addChild(path[path.length - 1], newModule);
  49955. }
  49956. if (rawModule.modules) {
  49957. forEachValue(rawModule.modules, function(rawChildModule, key) {
  49958. this$1$1.register(path.concat(key), rawChildModule, runtime);
  49959. });
  49960. }
  49961. };
  49962. ModuleCollection.prototype.unregister = function unregister(path) {
  49963. var parent = this.get(path.slice(0, -1));
  49964. var key = path[path.length - 1];
  49965. var child = parent.getChild(key);
  49966. if (!child) {
  49967. {
  49968. console.warn(
  49969. "[vuex] trying to unregister module '" + key + "', which is not registered"
  49970. );
  49971. }
  49972. return;
  49973. }
  49974. if (!child.runtime) {
  49975. return;
  49976. }
  49977. parent.removeChild(key);
  49978. };
  49979. ModuleCollection.prototype.isRegistered = function isRegistered(path) {
  49980. var parent = this.get(path.slice(0, -1));
  49981. var key = path[path.length - 1];
  49982. if (parent) {
  49983. return parent.hasChild(key);
  49984. }
  49985. return false;
  49986. };
  49987. function update2(path, targetModule, newModule) {
  49988. {
  49989. assertRawModule(path, newModule);
  49990. }
  49991. targetModule.update(newModule);
  49992. if (newModule.modules) {
  49993. for (var key in newModule.modules) {
  49994. if (!targetModule.getChild(key)) {
  49995. {
  49996. console.warn(
  49997. "[vuex] trying to add a new module '" + key + "' on hot reloading, manual reload is needed"
  49998. );
  49999. }
  50000. return;
  50001. }
  50002. update2(
  50003. path.concat(key),
  50004. targetModule.getChild(key),
  50005. newModule.modules[key]
  50006. );
  50007. }
  50008. }
  50009. }
  50010. var functionAssert = {
  50011. assert: function(value2) {
  50012. return typeof value2 === "function";
  50013. },
  50014. expected: "function"
  50015. };
  50016. var objectAssert = {
  50017. assert: function(value2) {
  50018. return typeof value2 === "function" || typeof value2 === "object" && typeof value2.handler === "function";
  50019. },
  50020. expected: 'function or object with "handler" function'
  50021. };
  50022. var assertTypes = {
  50023. getters: functionAssert,
  50024. mutations: functionAssert,
  50025. actions: objectAssert
  50026. };
  50027. function assertRawModule(path, rawModule) {
  50028. Object.keys(assertTypes).forEach(function(key) {
  50029. if (!rawModule[key]) {
  50030. return;
  50031. }
  50032. var assertOptions = assertTypes[key];
  50033. forEachValue(rawModule[key], function(value2, type) {
  50034. assert(
  50035. assertOptions.assert(value2),
  50036. makeAssertionMessage(path, key, type, value2, assertOptions.expected)
  50037. );
  50038. });
  50039. });
  50040. }
  50041. function makeAssertionMessage(path, key, type, value2, expected) {
  50042. var buf = key + " should be " + expected + ' but "' + key + "." + type + '"';
  50043. if (path.length > 0) {
  50044. buf += ' in module "' + path.join(".") + '"';
  50045. }
  50046. buf += " is " + JSON.stringify(value2) + ".";
  50047. return buf;
  50048. }
  50049. function createStore(options) {
  50050. return new Store(options);
  50051. }
  50052. var Store = function Store2(options) {
  50053. var this$1$1 = this;
  50054. if (options === void 0)
  50055. options = {};
  50056. {
  50057. assert(typeof Promise !== "undefined", "vuex requires a Promise polyfill in this browser.");
  50058. assert(this instanceof Store2, "store must be called with the new operator.");
  50059. }
  50060. var plugins = options.plugins;
  50061. if (plugins === void 0)
  50062. plugins = [];
  50063. var strict = options.strict;
  50064. if (strict === void 0)
  50065. strict = false;
  50066. var devtools = options.devtools;
  50067. this._committing = false;
  50068. this._actions = /* @__PURE__ */ Object.create(null);
  50069. this._actionSubscribers = [];
  50070. this._mutations = /* @__PURE__ */ Object.create(null);
  50071. this._wrappedGetters = /* @__PURE__ */ Object.create(null);
  50072. this._modules = new ModuleCollection(options);
  50073. this._modulesNamespaceMap = /* @__PURE__ */ Object.create(null);
  50074. this._subscribers = [];
  50075. this._makeLocalGettersCache = /* @__PURE__ */ Object.create(null);
  50076. this._scope = null;
  50077. this._devtools = devtools;
  50078. var store2 = this;
  50079. var ref = this;
  50080. var dispatch2 = ref.dispatch;
  50081. var commit2 = ref.commit;
  50082. this.dispatch = function boundDispatch(type, payload) {
  50083. return dispatch2.call(store2, type, payload);
  50084. };
  50085. this.commit = function boundCommit(type, payload, options2) {
  50086. return commit2.call(store2, type, payload, options2);
  50087. };
  50088. this.strict = strict;
  50089. var state = this._modules.root.state;
  50090. installModule(this, state, [], this._modules.root);
  50091. resetStoreState(this, state);
  50092. plugins.forEach(function(plugin) {
  50093. return plugin(this$1$1);
  50094. });
  50095. };
  50096. var prototypeAccessors = { state: { configurable: true } };
  50097. Store.prototype.install = function install2(app2, injectKey) {
  50098. app2.provide(injectKey || storeKey, this);
  50099. app2.config.globalProperties.$store = this;
  50100. var useDevtools = this._devtools !== void 0 ? this._devtools : true;
  50101. if (useDevtools) {
  50102. addDevtools(app2, this);
  50103. }
  50104. };
  50105. prototypeAccessors.state.get = function() {
  50106. return this._state.data;
  50107. };
  50108. prototypeAccessors.state.set = function(v2) {
  50109. {
  50110. assert(false, "use store.replaceState() to explicit replace store state.");
  50111. }
  50112. };
  50113. Store.prototype.commit = function commit(_type, _payload, _options) {
  50114. var this$1$1 = this;
  50115. var ref = unifyObjectStyle(_type, _payload, _options);
  50116. var type = ref.type;
  50117. var payload = ref.payload;
  50118. var options = ref.options;
  50119. var mutation = { type, payload };
  50120. var entry = this._mutations[type];
  50121. if (!entry) {
  50122. {
  50123. console.error("[vuex] unknown mutation type: " + type);
  50124. }
  50125. return;
  50126. }
  50127. this._withCommit(function() {
  50128. entry.forEach(function commitIterator(handler) {
  50129. handler(payload);
  50130. });
  50131. });
  50132. this._subscribers.slice().forEach(function(sub) {
  50133. return sub(mutation, this$1$1.state);
  50134. });
  50135. if (options && options.silent) {
  50136. console.warn(
  50137. "[vuex] mutation type: " + type + ". Silent option has been removed. Use the filter functionality in the vue-devtools"
  50138. );
  50139. }
  50140. };
  50141. Store.prototype.dispatch = function dispatch(_type, _payload) {
  50142. var this$1$1 = this;
  50143. var ref = unifyObjectStyle(_type, _payload);
  50144. var type = ref.type;
  50145. var payload = ref.payload;
  50146. var action = { type, payload };
  50147. var entry = this._actions[type];
  50148. if (!entry) {
  50149. {
  50150. console.error("[vuex] unknown action type: " + type);
  50151. }
  50152. return;
  50153. }
  50154. try {
  50155. this._actionSubscribers.slice().filter(function(sub) {
  50156. return sub.before;
  50157. }).forEach(function(sub) {
  50158. return sub.before(action, this$1$1.state);
  50159. });
  50160. } catch (e2) {
  50161. {
  50162. console.warn("[vuex] error in before action subscribers: ");
  50163. console.error(e2);
  50164. }
  50165. }
  50166. var result = entry.length > 1 ? Promise.all(entry.map(function(handler) {
  50167. return handler(payload);
  50168. })) : entry[0](payload);
  50169. return new Promise(function(resolve, reject) {
  50170. result.then(function(res) {
  50171. try {
  50172. this$1$1._actionSubscribers.filter(function(sub) {
  50173. return sub.after;
  50174. }).forEach(function(sub) {
  50175. return sub.after(action, this$1$1.state);
  50176. });
  50177. } catch (e2) {
  50178. {
  50179. console.warn("[vuex] error in after action subscribers: ");
  50180. console.error(e2);
  50181. }
  50182. }
  50183. resolve(res);
  50184. }, function(error2) {
  50185. try {
  50186. this$1$1._actionSubscribers.filter(function(sub) {
  50187. return sub.error;
  50188. }).forEach(function(sub) {
  50189. return sub.error(action, this$1$1.state, error2);
  50190. });
  50191. } catch (e2) {
  50192. {
  50193. console.warn("[vuex] error in error action subscribers: ");
  50194. console.error(e2);
  50195. }
  50196. }
  50197. reject(error2);
  50198. });
  50199. });
  50200. };
  50201. Store.prototype.subscribe = function subscribe(fn, options) {
  50202. return genericSubscribe(fn, this._subscribers, options);
  50203. };
  50204. Store.prototype.subscribeAction = function subscribeAction(fn, options) {
  50205. var subs = typeof fn === "function" ? { before: fn } : fn;
  50206. return genericSubscribe(subs, this._actionSubscribers, options);
  50207. };
  50208. Store.prototype.watch = function watch$1(getter, cb, options) {
  50209. var this$1$1 = this;
  50210. {
  50211. assert(typeof getter === "function", "store.watch only accepts a function.");
  50212. }
  50213. return vue.watch(function() {
  50214. return getter(this$1$1.state, this$1$1.getters);
  50215. }, cb, Object.assign({}, options));
  50216. };
  50217. Store.prototype.replaceState = function replaceState(state) {
  50218. var this$1$1 = this;
  50219. this._withCommit(function() {
  50220. this$1$1._state.data = state;
  50221. });
  50222. };
  50223. Store.prototype.registerModule = function registerModule(path, rawModule, options) {
  50224. if (options === void 0)
  50225. options = {};
  50226. if (typeof path === "string") {
  50227. path = [path];
  50228. }
  50229. {
  50230. assert(Array.isArray(path), "module path must be a string or an Array.");
  50231. assert(path.length > 0, "cannot register the root module by using registerModule.");
  50232. }
  50233. this._modules.register(path, rawModule);
  50234. installModule(this, this.state, path, this._modules.get(path), options.preserveState);
  50235. resetStoreState(this, this.state);
  50236. };
  50237. Store.prototype.unregisterModule = function unregisterModule(path) {
  50238. var this$1$1 = this;
  50239. if (typeof path === "string") {
  50240. path = [path];
  50241. }
  50242. {
  50243. assert(Array.isArray(path), "module path must be a string or an Array.");
  50244. }
  50245. this._modules.unregister(path);
  50246. this._withCommit(function() {
  50247. var parentState = getNestedState(this$1$1.state, path.slice(0, -1));
  50248. delete parentState[path[path.length - 1]];
  50249. });
  50250. resetStore(this);
  50251. };
  50252. Store.prototype.hasModule = function hasModule(path) {
  50253. if (typeof path === "string") {
  50254. path = [path];
  50255. }
  50256. {
  50257. assert(Array.isArray(path), "module path must be a string or an Array.");
  50258. }
  50259. return this._modules.isRegistered(path);
  50260. };
  50261. Store.prototype.hotUpdate = function hotUpdate(newOptions) {
  50262. this._modules.update(newOptions);
  50263. resetStore(this, true);
  50264. };
  50265. Store.prototype._withCommit = function _withCommit(fn) {
  50266. var committing = this._committing;
  50267. this._committing = true;
  50268. fn();
  50269. this._committing = committing;
  50270. };
  50271. Object.defineProperties(Store.prototype, prototypeAccessors);
  50272. const ACCESS_TOKEN = "AccessToken";
  50273. const USER_ID = "userId";
  50274. const USER_INFO = "userInfo";
  50275. const postfix = "_expiry";
  50276. const storage = {
  50277. /**
  50278. * 设置缓存
  50279. * @param {[type]} k [键名]
  50280. * @param {[type]} v [键值]
  50281. * @param {[type]} t [时间、单位秒]
  50282. */
  50283. set(k, v2, t2) {
  50284. uni.setStorageSync(k, v2);
  50285. const seconds = parseInt(t2);
  50286. if (seconds > 0) {
  50287. let timestamp = Date.parse(/* @__PURE__ */ new Date());
  50288. timestamp = timestamp / 1e3 + seconds;
  50289. uni.setStorageSync(k + postfix, timestamp + "");
  50290. } else {
  50291. uni.removeStorageSync(k + postfix);
  50292. }
  50293. },
  50294. /**
  50295. * 获取缓存
  50296. * @param {[type]} k [键名]
  50297. * @param {[type]} def [获取为空时默认]
  50298. */
  50299. get(k, def) {
  50300. const deadtime = parseInt(uni.getStorageSync(k + postfix));
  50301. if (deadtime) {
  50302. if (parseInt(deadtime) < Date.parse(/* @__PURE__ */ new Date()) / 1e3) {
  50303. if (def) {
  50304. return def;
  50305. } else {
  50306. return false;
  50307. }
  50308. }
  50309. }
  50310. const res = uni.getStorageSync(k);
  50311. if (res) {
  50312. return res;
  50313. }
  50314. if (def == void 0 || def == "") {
  50315. def = false;
  50316. }
  50317. return def;
  50318. },
  50319. /**
  50320. * 删除指定缓存
  50321. * @param {Object} k
  50322. */
  50323. remove(k) {
  50324. uni.removeStorageSync(k);
  50325. uni.removeStorageSync(k + postfix);
  50326. },
  50327. /**
  50328. * 清理所有缓存
  50329. * @return {[type]} [description]
  50330. */
  50331. clear() {
  50332. uni.clearStorageSync();
  50333. }
  50334. };
  50335. const app = {
  50336. state: {
  50337. // 当前终端平台
  50338. platform: ""
  50339. },
  50340. mutations: {
  50341. SET_PLATFORM: (state, value2) => {
  50342. state.platform = value2;
  50343. }
  50344. },
  50345. actions: {}
  50346. };
  50347. const urlEncode = (obj = {}) => {
  50348. const result = [];
  50349. for (const key in obj) {
  50350. const item = obj[key];
  50351. if (!item) {
  50352. continue;
  50353. }
  50354. if (isArray$1(item)) {
  50355. item.forEach((val) => {
  50356. result.push(key + "=" + val);
  50357. });
  50358. } else {
  50359. result.push(key + "=" + item);
  50360. }
  50361. }
  50362. return result.join("&");
  50363. };
  50364. const inArray = (search, array2) => {
  50365. for (var i2 in array2) {
  50366. if (array2[i2] == search)
  50367. return true;
  50368. }
  50369. return false;
  50370. };
  50371. const isArray$1 = (array2) => {
  50372. return Object.prototype.toString.call(array2) === "[object Array]";
  50373. };
  50374. const getTabBarLinks = () => {
  50375. const tabBarLinks = [
  50376. "pages/home/index",
  50377. "pages/camp/index",
  50378. "pages/games/index",
  50379. "pages/user/index"
  50380. ];
  50381. return tabBarLinks;
  50382. };
  50383. const navTo = (url2, query = {}, modo = "navigateTo") => {
  50384. if (!url2 || url2.length == 0) {
  50385. return false;
  50386. }
  50387. if (inArray(url2, getTabBarLinks())) {
  50388. uni.switchTab({
  50389. url: `/${url2}`
  50390. });
  50391. return true;
  50392. }
  50393. const queryStr = query ? "?" + urlEncode(query) : "";
  50394. modo === "navigateTo" && uni.navigateTo({
  50395. url: `/${url2}${queryStr}`
  50396. });
  50397. modo === "redirectTo" && uni.redirectTo({
  50398. url: `/${url2}${queryStr}`
  50399. });
  50400. return true;
  50401. };
  50402. const loginSuccess = (commit, {
  50403. token,
  50404. id,
  50405. userInfo
  50406. }) => {
  50407. const expiryTime = 30 * 86400 * 3;
  50408. storage.set(USER_ID, id, expiryTime);
  50409. storage.set(ACCESS_TOKEN, token, expiryTime);
  50410. commit("SET_TOKEN", token);
  50411. commit("SET_USER_ID", id);
  50412. commit("SET_USER_INFO", userInfo);
  50413. };
  50414. const user = {
  50415. state: {
  50416. // 用户认证token
  50417. token: uni.getStorageSync(ACCESS_TOKEN),
  50418. // 用户ID
  50419. userId: uni.getStorageSync(USER_ID),
  50420. userInfo: uni.getStorageSync(USER_INFO),
  50421. parent_id: null
  50422. },
  50423. mutations: {
  50424. SET_TOKEN: (state, value2) => {
  50425. state.token = value2;
  50426. },
  50427. SET_USER_ID: (state, value2) => {
  50428. state.userId = value2;
  50429. },
  50430. SET_USER_INFO: (state, value2) => {
  50431. state.userInfo = value2;
  50432. },
  50433. M_PARENT_ID: (state, value2) => {
  50434. state.parent_id = value2;
  50435. }
  50436. },
  50437. actions: {
  50438. // 用户登录(普通登录: 输入手机号和验证码)
  50439. async LoginWX({
  50440. commit
  50441. }, data) {
  50442. const result = await userLoginWX(data);
  50443. if (result) {
  50444. if (result.data.token) {
  50445. loginSuccess(commit, {
  50446. token: result.data.token,
  50447. id: result.data.id,
  50448. userInfo: {}
  50449. });
  50450. return Promise.resolve(result);
  50451. } else {
  50452. return Promise.resolve(result);
  50453. }
  50454. }
  50455. },
  50456. // 用户登录(普通登录: 输入手机号和验证码)
  50457. async LoginApp({
  50458. commit
  50459. }, data) {
  50460. const result = await userLloginApp(data);
  50461. if (result) {
  50462. loginSuccess(commit, {
  50463. token: result.data.token,
  50464. id: result.data.id
  50465. });
  50466. return Promise.resolve(result);
  50467. } else {
  50468. return Promise.resolve(result);
  50469. }
  50470. },
  50471. // H5登陆
  50472. async LoginH5({
  50473. commit
  50474. }, data) {
  50475. const result = await userLoginH5(data);
  50476. if (result) {
  50477. if (result.data.token) {
  50478. loginSuccess(commit, {
  50479. token: result.data.token,
  50480. id: result.data.id
  50481. });
  50482. return Promise.resolve(result);
  50483. } else {
  50484. return Promise.resolve(result);
  50485. }
  50486. }
  50487. },
  50488. // 退出登录
  50489. async Logout({
  50490. commit
  50491. }, data) {
  50492. const store2 = this;
  50493. if (store2.getters.userId > 0) {
  50494. storage.remove(USER_ID);
  50495. storage.remove(ACCESS_TOKEN);
  50496. storage.remove(USER_INFO);
  50497. commit("SET_TOKEN", "");
  50498. commit("SET_USER_ID", null);
  50499. commit("SET_USER_INFO", null);
  50500. navTo("pages/home/index", {});
  50501. return Promise.resolve({
  50502. result: true
  50503. });
  50504. }
  50505. }
  50506. }
  50507. };
  50508. const cate = {
  50509. state: {
  50510. // 当前终端平台
  50511. cate_history: uni.getStorageSync("cate_history") ? uni.getStorageSync("cate_history") : []
  50512. },
  50513. mutations: {
  50514. SET_CATE_HISTORY: (state, value2) => {
  50515. state.cate_history = value2;
  50516. uni.setStorageSync("cate_history", state.cate_history);
  50517. }
  50518. },
  50519. actions: {}
  50520. };
  50521. const getters = {
  50522. token: (state) => state.user.token,
  50523. userId: (state) => state.user.userId,
  50524. platform: (state) => state.app.platform,
  50525. userInfo: (state) => state.user.userInfo
  50526. };
  50527. const store = createStore({
  50528. modules: {
  50529. app,
  50530. user,
  50531. cate
  50532. },
  50533. getters
  50534. });
  50535. const mergeConfig$2 = (_this, options) => {
  50536. let urlType = /^(http|https):\/\//.test(options.url);
  50537. let config2 = Object.assign({
  50538. timeout: _this.timeout
  50539. }, _this.config, options);
  50540. if (options.method == "FILE") {
  50541. config2.url = urlType ? options.url : _this.fileUrl + options.url;
  50542. } else {
  50543. config2.url = urlType ? options.url : _this.baseUrl + options.url;
  50544. }
  50545. if (options.header) {
  50546. config2.header = Object.assign({}, _this.header, options.header);
  50547. } else {
  50548. config2.header = Object.assign({}, _this.header);
  50549. }
  50550. return config2;
  50551. };
  50552. const dispatchRequest$1 = (requestInfo) => {
  50553. return new Promise((resolve, reject) => {
  50554. let requestAbort = true;
  50555. let requestData = {
  50556. url: requestInfo.url,
  50557. header: requestInfo.header,
  50558. //加入请求头
  50559. success: (res) => {
  50560. requestAbort = false;
  50561. resolve(res);
  50562. },
  50563. fail: (err) => {
  50564. requestAbort = false;
  50565. if (err.errMsg == "request:fail abort") {
  50566. reject({
  50567. errMsg: "请求超时,请重新尝试",
  50568. statusCode: 0
  50569. });
  50570. } else {
  50571. reject(err);
  50572. }
  50573. }
  50574. };
  50575. if (requestInfo.method) {
  50576. requestData.method = requestInfo.method;
  50577. }
  50578. if (requestInfo.data) {
  50579. requestData.data = requestInfo.data;
  50580. }
  50581. if (requestInfo.dataType) {
  50582. requestData.dataType = requestInfo.dataType;
  50583. }
  50584. let requestTask = uni.request(requestData);
  50585. setTimeout(() => {
  50586. if (requestAbort) {
  50587. requestTask.abort();
  50588. }
  50589. }, requestInfo.timeout);
  50590. });
  50591. };
  50592. const jsonpRequest = (requestInfo) => {
  50593. return new Promise((resolve, reject) => {
  50594. let dataStr = "";
  50595. Object.keys(requestInfo.data).forEach((key) => {
  50596. dataStr += key + "=" + requestInfo.data[key] + "&";
  50597. });
  50598. if (dataStr !== "") {
  50599. dataStr = dataStr.substr(0, dataStr.lastIndexOf("&"));
  50600. }
  50601. requestInfo.url = requestInfo.url + "?" + dataStr;
  50602. });
  50603. };
  50604. const getPlatform = () => {
  50605. const platform2 = "app";
  50606. return platform2;
  50607. };
  50608. const platfrom = getPlatform();
  50609. let request$2 = class request {
  50610. constructor(options) {
  50611. this.baseUrl = options.baseUrl || "";
  50612. this.fileUrl = options.fileUrl || "";
  50613. this.timeout = options.timeout || 6e3;
  50614. this.defaultUploadUrl = options.defaultUploadUrl || "";
  50615. this.header = options.header || {};
  50616. this.config = options.config || {
  50617. isPrompt: true,
  50618. load: true,
  50619. isFactory: false,
  50620. resend: 0
  50621. };
  50622. }
  50623. // post请求
  50624. post(url2 = "", data = {}, options = {}) {
  50625. return this.request({
  50626. method: "POST",
  50627. data,
  50628. url: url2,
  50629. ...options
  50630. });
  50631. }
  50632. // get请求
  50633. get(url2 = "", data = {}, options = {}) {
  50634. return this.request({
  50635. method: "GET",
  50636. data,
  50637. url: url2,
  50638. ...options
  50639. });
  50640. }
  50641. // put请求
  50642. put(url2 = "", data = {}, options = {}) {
  50643. return this.request({
  50644. method: "PUT",
  50645. data,
  50646. url: url2,
  50647. ...options
  50648. });
  50649. }
  50650. // delete请求
  50651. delete(url2 = "", data = {}, options = {}) {
  50652. return this.request({
  50653. method: "DELETE",
  50654. data,
  50655. url: url2,
  50656. ...options
  50657. });
  50658. }
  50659. // jsonp请求(只限于H5使用)
  50660. jsonp(url2 = "", data = {}, options = {}) {
  50661. return this.request({
  50662. method: "JSONP",
  50663. data,
  50664. url: url2,
  50665. ...options
  50666. });
  50667. }
  50668. // 接口请求方法
  50669. async request(data) {
  50670. let requestInfo, runRequestStart = false;
  50671. try {
  50672. if (!data.url) {
  50673. throw {
  50674. errMsg: "【request】缺失数据url",
  50675. statusCode: 0
  50676. };
  50677. }
  50678. requestInfo = mergeConfig$2(this, data);
  50679. runRequestStart = true;
  50680. if (this.requestStart) {
  50681. let requestStart = this.requestStart(requestInfo);
  50682. if (typeof requestStart == "object") {
  50683. let changekeys = ["data", "header", "isPrompt", "load", "isFactory"];
  50684. changekeys.forEach((key) => {
  50685. requestInfo[key] = requestStart[key];
  50686. });
  50687. } else {
  50688. throw {
  50689. errMsg: "【request】请求开始拦截器未通过",
  50690. statusCode: 0,
  50691. formData: requestInfo.data,
  50692. method: requestInfo.method,
  50693. header: requestInfo.header,
  50694. url: requestInfo.url
  50695. };
  50696. }
  50697. }
  50698. let requestResult = {};
  50699. if (requestInfo.method == "JSONP") {
  50700. requestResult = await jsonpRequest(requestInfo);
  50701. } else {
  50702. requestResult = await dispatchRequest$1(requestInfo);
  50703. }
  50704. if (requestInfo.isFactory && this.dataFactory) {
  50705. let result = await this.dataFactory({
  50706. ...requestInfo,
  50707. response: requestResult.data
  50708. });
  50709. return result ? Promise.resolve(result) : null;
  50710. } else {
  50711. return Promise.resolve(requestResult);
  50712. }
  50713. } catch (err) {
  50714. this.requestError && this.requestError(err);
  50715. return Promise.reject(err);
  50716. } finally {
  50717. if (runRequestStart) {
  50718. this.requestEnd && this.requestEnd(requestInfo);
  50719. }
  50720. }
  50721. }
  50722. };
  50723. const qiniuUploader = /* @__PURE__ */ function() {
  50724. var config2 = {
  50725. qiniuRegion: "",
  50726. qiniuImageURLPrefix: "",
  50727. qiniuUploadToken: "",
  50728. qiniuUploadTokenURL: "",
  50729. qiniuUploadTokenFunction: null,
  50730. qiniuShouldUseQiniuFileName: false
  50731. };
  50732. function init(options) {
  50733. config2 = {
  50734. qiniuRegion: "",
  50735. qiniuImageURLPrefix: "",
  50736. qiniuUploadToken: "",
  50737. qiniuUploadTokenURL: "",
  50738. qiniuUploadTokenFunction: null,
  50739. qiniuShouldUseQiniuFileName: false
  50740. };
  50741. updateConfigWithOptions(options);
  50742. }
  50743. function updateConfigWithOptions(options) {
  50744. if (options.region) {
  50745. config2.qiniuRegion = options.region;
  50746. } else {
  50747. formatAppLog("error", "at utils/request/upload/qiniuUploader.js:30", "qiniu uploader need your bucket region");
  50748. }
  50749. if (options.uptoken) {
  50750. config2.qiniuUploadToken = options.uptoken;
  50751. } else if (options.uptokenURL) {
  50752. config2.qiniuUploadTokenURL = options.uptokenURL;
  50753. } else if (options.uptokenFunc) {
  50754. config2.qiniuUploadTokenFunction = options.uptokenFunc;
  50755. }
  50756. if (options.domain) {
  50757. config2.qiniuImageURLPrefix = options.domain;
  50758. }
  50759. config2.qiniuShouldUseQiniuFileName = options.shouldUseQiniuFileName;
  50760. }
  50761. function upload(filePath, success, fail, options, progress, cancelTask) {
  50762. if (null == filePath) {
  50763. formatAppLog("error", "at utils/request/upload/qiniuUploader.js:47", "qiniu uploader need filePath to upload");
  50764. return;
  50765. }
  50766. if (options) {
  50767. updateConfigWithOptions(options);
  50768. }
  50769. if (config2.qiniuUploadToken) {
  50770. doUpload(filePath, success, fail, options, progress, cancelTask);
  50771. } else if (config2.qiniuUploadTokenURL) {
  50772. getQiniuToken(function() {
  50773. doUpload(filePath, success, fail, options, progress, cancelTask);
  50774. });
  50775. } else if (config2.qiniuUploadTokenFunction) {
  50776. config2.qiniuUploadToken = config2.qiniuUploadTokenFunction();
  50777. if (null == config2.qiniuUploadToken && config2.qiniuUploadToken.length > 0) {
  50778. formatAppLog("error", "at utils/request/upload/qiniuUploader.js:62", "qiniu UploadTokenFunction result is null, please check the return value");
  50779. return;
  50780. }
  50781. doUpload(filePath, success, fail, options, progress, cancelTask);
  50782. } else {
  50783. formatAppLog("error", "at utils/request/upload/qiniuUploader.js:67", "qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]");
  50784. return;
  50785. }
  50786. }
  50787. function doUpload(filePath, success, fail, options, progress, cancelTask) {
  50788. if (null == config2.qiniuUploadToken && config2.qiniuUploadToken.length > 0) {
  50789. formatAppLog("error", "at utils/request/upload/qiniuUploader.js:74", "qiniu UploadToken is null, please check the init config or networking");
  50790. return;
  50791. }
  50792. var url2 = uploadURLFromRegionCode(config2.qiniuRegion);
  50793. var fileName = filePath.split("//")[1];
  50794. if (options && options.key) {
  50795. fileName = options.key;
  50796. }
  50797. var formData = {
  50798. "token": config2.qiniuUploadToken
  50799. };
  50800. if (!config2.qiniuShouldUseQiniuFileName) {
  50801. formData["key"] = fileName;
  50802. }
  50803. var uploadTask = wx.uploadFile({
  50804. url: url2,
  50805. filePath,
  50806. name: "file",
  50807. formData,
  50808. success: function(res) {
  50809. var dataString = res.data;
  50810. if (res.data.hasOwnProperty("type") && res.data.type === "Buffer") {
  50811. dataString = String.fromCharCode.apply(null, res.data.data);
  50812. }
  50813. try {
  50814. var dataObject = JSON.parse(dataString);
  50815. var imageUrl = config2.qiniuImageURLPrefix + "/" + dataObject.key;
  50816. dataObject.imageURL = imageUrl;
  50817. if (success) {
  50818. success(dataObject);
  50819. }
  50820. } catch (e2) {
  50821. formatAppLog("log", "at utils/request/upload/qiniuUploader.js:107", "parse JSON failed, origin String is: " + dataString);
  50822. if (fail) {
  50823. fail(e2);
  50824. }
  50825. }
  50826. },
  50827. fail: function(error2) {
  50828. formatAppLog("error", "at utils/request/upload/qiniuUploader.js:114", error2);
  50829. if (fail) {
  50830. fail(error2);
  50831. }
  50832. }
  50833. });
  50834. uploadTask.onProgressUpdate((res) => {
  50835. progress && progress(res);
  50836. });
  50837. cancelTask && cancelTask(() => {
  50838. uploadTask.abort();
  50839. });
  50840. }
  50841. function getQiniuToken(callback) {
  50842. wx.request({
  50843. url: config2.qiniuUploadTokenURL,
  50844. success: function(res) {
  50845. var token = res.data.uptoken;
  50846. if (token && token.length > 0) {
  50847. config2.qiniuUploadToken = token;
  50848. if (callback) {
  50849. callback();
  50850. }
  50851. } else {
  50852. formatAppLog("error", "at utils/request/upload/qiniuUploader.js:141", "qiniuUploader cannot get your token, please check the uptokenURL or server");
  50853. }
  50854. },
  50855. fail: function(error2) {
  50856. formatAppLog("error", "at utils/request/upload/qiniuUploader.js:145", "qiniu UploadToken is null, please check the init config or networking: " + error2);
  50857. }
  50858. });
  50859. }
  50860. function uploadURLFromRegionCode(code2) {
  50861. var uploadURL = null;
  50862. switch (code2) {
  50863. case "ECN":
  50864. uploadURL = "https://up.qbox.me";
  50865. break;
  50866. case "NCN":
  50867. uploadURL = "https://up-z1.qbox.me";
  50868. break;
  50869. case "SCN":
  50870. uploadURL = "https://up-z2.qbox.me";
  50871. break;
  50872. case "NA":
  50873. uploadURL = "https://up-na0.qbox.me";
  50874. break;
  50875. case "ASG":
  50876. uploadURL = "https://up-as0.qbox.me";
  50877. break;
  50878. default:
  50879. formatAppLog("error", "at utils/request/upload/qiniuUploader.js:169", "please make the region is with one of [ECN, SCN, NCN, NA, ASG]");
  50880. }
  50881. return uploadURL;
  50882. }
  50883. return {
  50884. init,
  50885. upload
  50886. };
  50887. }();
  50888. const randomChar = function(l2, url2 = "") {
  50889. const x = "0123456789qwertyuioplkjhgfdsazxcvbnm";
  50890. let tmp = "";
  50891. let time = /* @__PURE__ */ new Date();
  50892. for (let i2 = 0; i2 < l2; i2++) {
  50893. tmp += x.charAt(Math.ceil(Math.random() * 1e8) % x.length);
  50894. }
  50895. return "file/" + url2 + time.getTime() + tmp;
  50896. };
  50897. const chooseImage = function(data) {
  50898. return new Promise((resolve, reject) => {
  50899. uni.chooseImage({
  50900. count: data.count || 9,
  50901. //默认9
  50902. sizeType: data.sizeType || ["original", "compressed"],
  50903. //可以指定是原图还是压缩图,默认二者都有
  50904. sourceType: data.sourceType || ["album", "camera"],
  50905. //从相册选择
  50906. success: function(res) {
  50907. resolve(res.tempFiles);
  50908. },
  50909. fail: (err) => {
  50910. reject({
  50911. errMsg: err.errMsg,
  50912. errCode: err.errCode,
  50913. statusCode: 0
  50914. });
  50915. }
  50916. });
  50917. });
  50918. };
  50919. const chooseVideo = function(data) {
  50920. return new Promise((resolve, reject) => {
  50921. uni.chooseVideo({
  50922. sourceType: data.sourceType || ["album", "camera"],
  50923. //从相册选择
  50924. compressed: data.compressed || false,
  50925. //是否压缩所选的视频源文件,默认值为 true,需要压缩。
  50926. maxDuration: data.maxDuration || 60,
  50927. //拍摄视频最长拍摄时间,单位秒。最长支持 60 秒。
  50928. camera: data.camera || "back",
  50929. //'front'、'back',默认'back'
  50930. success: function(res) {
  50931. let files = [{
  50932. path: res.tempFilePath
  50933. }];
  50934. files[0].duration = res.duration;
  50935. files[0].size = res.size;
  50936. files[0].height = res.height;
  50937. files[0].width = res.width;
  50938. resolve(files);
  50939. },
  50940. fail: (err) => {
  50941. reject({
  50942. errMsg: err.errMsg,
  50943. errCode: err.errCode,
  50944. statusCode: 0
  50945. });
  50946. }
  50947. });
  50948. });
  50949. };
  50950. const qiniuUpload = function(requestInfo, getQnToken) {
  50951. return new Promise((resolve, reject) => {
  50952. if (Array.isArray(requestInfo.files)) {
  50953. let len = requestInfo.files.length;
  50954. let fileList = new Array();
  50955. if (getQnToken) {
  50956. getQnToken((qnRes) => {
  50957. let prefixLen = qnRes.visitPrefix.length;
  50958. if (qnRes.visitPrefix.charAt(prefixLen - 1) == "/") {
  50959. qnRes.visitPrefix = qnRes.visitPrefix.substring(0, prefixLen - 1);
  50960. }
  50961. uploadFile(0);
  50962. function uploadFile(i2) {
  50963. let item = requestInfo.files[i2];
  50964. let updateUrl = randomChar(10, qnRes.folderPath);
  50965. let fileData = {
  50966. fileIndex: i2,
  50967. files: requestInfo.files,
  50968. ...item
  50969. };
  50970. if (item.name) {
  50971. fileData.name = item.name;
  50972. let nameArr = item.name.split(".");
  50973. updateUrl += "." + nameArr[nameArr.length - 1];
  50974. }
  50975. qiniuUploader.upload(item.path || item, (res) => {
  50976. fileData.url = res.imageURL;
  50977. requestInfo.onEachUpdate && requestInfo.onEachUpdate({
  50978. url: res.imageURL,
  50979. ...fileData
  50980. });
  50981. fileList.push(res.imageURL);
  50982. if (len - 1 > i2) {
  50983. uploadFile(i2 + 1);
  50984. } else {
  50985. resolve(fileList);
  50986. }
  50987. }, (error2) => {
  50988. reject(error2);
  50989. }, {
  50990. region: qnRes.region || "SCN",
  50991. //地区
  50992. domain: qnRes.visitPrefix,
  50993. // bucket 域名,下载资源时用到。
  50994. key: updateUrl,
  50995. uptoken: qnRes.token,
  50996. // 由其他程序生成七牛 uptoken
  50997. uptokenURL: "UpTokenURL.com/uptoken"
  50998. // 上传地址
  50999. }, (res) => {
  51000. formatAppLog("log", "at utils/request/upload/utils.js:127", requestInfo);
  51001. requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({}, fileData, res));
  51002. });
  51003. }
  51004. });
  51005. } else {
  51006. reject({
  51007. errMsg: "请添加七牛云回调方法:getQnToken",
  51008. statusCode: 0
  51009. });
  51010. }
  51011. } else {
  51012. reject({
  51013. errMsg: "files 必须是数组类型",
  51014. statusCode: 0
  51015. });
  51016. }
  51017. });
  51018. };
  51019. const urlUpload = function(requestInfo, dataFactory) {
  51020. return new Promise((resolve, reject) => {
  51021. if (requestInfo.header["Content-Type"]) {
  51022. delete requestInfo.header["Content-Type"];
  51023. }
  51024. if (requestInfo.header["content-type"]) {
  51025. delete requestInfo.header["content-type"];
  51026. }
  51027. if (Array.isArray(requestInfo.files)) {
  51028. let fileUpload2 = function(i2) {
  51029. let item = requestInfo.files[i2];
  51030. let fileData = {
  51031. fileIndex: i2,
  51032. files: requestInfo.files,
  51033. ...item
  51034. };
  51035. let config2 = {
  51036. url: requestInfo.url,
  51037. filePath: item.path,
  51038. header: requestInfo.header,
  51039. //加入请求头
  51040. name: requestInfo.name || "file",
  51041. success: (response) => {
  51042. if (requestInfo.isFactory && dataFactory) {
  51043. dataFactory({
  51044. ...requestInfo,
  51045. response
  51046. }).then((data) => {
  51047. fileList.push(data);
  51048. requestInfo.onEachUpdate && requestInfo.onEachUpdate({
  51049. data,
  51050. ...fileData
  51051. });
  51052. if (len <= i2) {
  51053. resolve(fileList);
  51054. } else {
  51055. fileUpload2(i2 + 1);
  51056. }
  51057. }, (err) => {
  51058. reject(err);
  51059. });
  51060. } else {
  51061. requestInfo.onEachUpdate && requestInfo.onEachUpdate({
  51062. data: response,
  51063. ...fileData
  51064. });
  51065. fileList.push(response);
  51066. if (len <= i2) {
  51067. resolve(fileList);
  51068. } else {
  51069. fileUpload2(i2 + 1);
  51070. }
  51071. }
  51072. },
  51073. fail: (err) => {
  51074. reject(err);
  51075. }
  51076. };
  51077. if (requestInfo.data) {
  51078. config2.formData = requestInfo.data;
  51079. }
  51080. const uploadTask = uni.uploadFile(config2);
  51081. uploadTask.onProgressUpdate((res) => {
  51082. requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({}, fileData, res));
  51083. });
  51084. };
  51085. const len = requestInfo.files.length - 1;
  51086. let fileList = new Array();
  51087. fileUpload2(0);
  51088. } else {
  51089. reject({
  51090. errMsg: "files 必须是数组类型",
  51091. statusCode: 0
  51092. });
  51093. }
  51094. });
  51095. };
  51096. class fileUpload extends request$2 {
  51097. constructor(props2) {
  51098. super(props2);
  51099. }
  51100. async ossImagUpload(options = {}) {
  51101. try {
  51102. const files = await chooseImage(options);
  51103. const data = [];
  51104. for (let item of files) {
  51105. let params = {
  51106. size: item.size,
  51107. model: "image"
  51108. };
  51109. if (item.name) {
  51110. params.name = item.name;
  51111. params.path = item.path;
  51112. } else if (item.path) {
  51113. if (item.path.indexOf("/") > -1) {
  51114. let names = item.path.split("/");
  51115. params.name = names[names.length - 1];
  51116. }
  51117. params.path = item.path;
  51118. }
  51119. options.onSelectComplete && options.onSelectComplete(files);
  51120. data.push(params);
  51121. }
  51122. return Promise.resolve(data);
  51123. } catch (err) {
  51124. return Promise.reject(err);
  51125. }
  51126. }
  51127. async ossVideoUpload(options = {}) {
  51128. let files;
  51129. try {
  51130. files = await chooseVideo(options);
  51131. let file = files[0];
  51132. let params = {
  51133. size: file.size,
  51134. model: "video"
  51135. };
  51136. if (file.name) {
  51137. params.name = file.name;
  51138. params.path = file.path;
  51139. } else if (file.path) {
  51140. if (file.path.indexOf("/") > -1) {
  51141. let names = file.path.split("/");
  51142. params.name = names[names.length - 1];
  51143. }
  51144. params.path = file.path;
  51145. }
  51146. options.onSelectComplete && options.onSelectComplete(files);
  51147. return Promise.resolve(params);
  51148. } catch (err) {
  51149. return Promise.reject(err);
  51150. }
  51151. }
  51152. //七牛云上传图片
  51153. async qnImgUpload(options = {}) {
  51154. let files;
  51155. try {
  51156. files = await chooseImage(options);
  51157. options.onSelectComplete && options.onSelectComplete(files);
  51158. } catch (err) {
  51159. this.requestError && this.requestError(err);
  51160. return Promise.reject(err);
  51161. }
  51162. if (files) {
  51163. return this.qnFileUpload({
  51164. ...options,
  51165. files
  51166. });
  51167. }
  51168. }
  51169. //七牛云上传视频
  51170. async qnVideoUpload(options = {}) {
  51171. let files;
  51172. try {
  51173. files = await chooseVideo(options);
  51174. options.onSelectComplete && options.onSelectComplete(files);
  51175. } catch (err) {
  51176. this.requestError && this.requestError(err);
  51177. return Promise.reject(err);
  51178. }
  51179. if (files) {
  51180. return this.qnFileUpload({
  51181. ...options,
  51182. files
  51183. });
  51184. }
  51185. }
  51186. //七牛云文件上传(支持多张上传)
  51187. async qnFileUpload(options = {}) {
  51188. let requestInfo;
  51189. try {
  51190. requestInfo = {
  51191. ...this.config,
  51192. ...options,
  51193. header: {},
  51194. method: "FILE"
  51195. };
  51196. if (this.requestStart) {
  51197. let requestStart = this.requestStart(requestInfo);
  51198. if (typeof requestStart == "object") {
  51199. let changekeys = ["load", "files"];
  51200. changekeys.forEach((key) => {
  51201. requestInfo[key] = requestStart[key];
  51202. });
  51203. } else {
  51204. throw {
  51205. errMsg: "【request】请求开始拦截器未通过",
  51206. statusCode: 0,
  51207. data: requestInfo.data,
  51208. method: requestInfo.method,
  51209. header: requestInfo.header,
  51210. url: requestInfo.url
  51211. };
  51212. }
  51213. }
  51214. let requestResult = await qiniuUpload(requestInfo, this.getQnToken);
  51215. return Promise.resolve(requestResult);
  51216. } catch (err) {
  51217. this.requestError && this.requestError(err);
  51218. return Promise.reject(err);
  51219. } finally {
  51220. this.requestEnd && this.requestEnd(requestInfo);
  51221. }
  51222. }
  51223. //本地服务器图片上传
  51224. async urlImgUpload() {
  51225. let options = {};
  51226. if (arguments[0]) {
  51227. if (typeof arguments[0] == "string") {
  51228. options.url = arguments[0];
  51229. } else if (typeof arguments[0] == "object") {
  51230. options = Object.assign(options, arguments[0]);
  51231. }
  51232. }
  51233. if (arguments[1] && typeof arguments[1] == "object") {
  51234. options = Object.assign(options, arguments[1]);
  51235. }
  51236. try {
  51237. options.files = await chooseImage(options);
  51238. options.onSelectComplete && options.onSelectComplete(options.files);
  51239. } catch (err) {
  51240. this.requestError && this.requestError(err);
  51241. return Promise.reject(err);
  51242. }
  51243. if (options.files) {
  51244. return this.urlFileUpload(options);
  51245. }
  51246. }
  51247. //本地服务器上传视频
  51248. async urlVideoUpload() {
  51249. let options = {};
  51250. if (arguments[0]) {
  51251. if (typeof arguments[0] == "string") {
  51252. options.url = arguments[0];
  51253. } else if (typeof arguments[0] == "object") {
  51254. options = Object.assign(options, arguments[0]);
  51255. }
  51256. }
  51257. if (arguments[1] && typeof arguments[1] == "object") {
  51258. options = Object.assign(options, arguments[1]);
  51259. }
  51260. try {
  51261. options.files = await chooseVideo(options);
  51262. options.onSelectComplete && options.onSelectComplete(options.files);
  51263. } catch (err) {
  51264. this.requestError && this.requestError(err);
  51265. return Promise.reject(err);
  51266. }
  51267. if (options.files) {
  51268. return this.urlFileUpload(options);
  51269. }
  51270. }
  51271. //本地服务器文件上传方法
  51272. async urlFileUpload() {
  51273. let requestInfo = {
  51274. method: "FILE"
  51275. };
  51276. if (arguments[0]) {
  51277. if (typeof arguments[0] == "string") {
  51278. requestInfo.url = arguments[0];
  51279. } else if (typeof arguments[0] == "object") {
  51280. requestInfo = Object.assign(requestInfo, arguments[0]);
  51281. }
  51282. }
  51283. if (arguments[1] && typeof arguments[1] == "object") {
  51284. requestInfo = Object.assign(requestInfo, arguments[1]);
  51285. }
  51286. if (!requestInfo.url && this.defaultUploadUrl) {
  51287. requestInfo.url = this.defaultUploadUrl;
  51288. }
  51289. let runRequestStart = false;
  51290. try {
  51291. if (!requestInfo.url) {
  51292. throw {
  51293. errMsg: "【request】文件上传缺失数据url",
  51294. statusCode: 0,
  51295. data: requestInfo.data,
  51296. method: requestInfo.method,
  51297. header: requestInfo.header,
  51298. url: requestInfo.url
  51299. };
  51300. }
  51301. requestInfo = mergeConfig$2(this, requestInfo);
  51302. runRequestStart = true;
  51303. if (this.requestStart) {
  51304. let requestStart = this.requestStart(requestInfo);
  51305. if (typeof requestStart == "object") {
  51306. let changekeys = ["data", "header", "isPrompt", "load", "isFactory", "files"];
  51307. changekeys.forEach((key) => {
  51308. requestInfo[key] = requestStart[key];
  51309. });
  51310. } else {
  51311. throw {
  51312. errMsg: "【request】请求开始拦截器未通过",
  51313. statusCode: 0,
  51314. data: requestInfo.data,
  51315. method: requestInfo.method,
  51316. header: requestInfo.header,
  51317. url: requestInfo.url
  51318. };
  51319. }
  51320. }
  51321. let requestResult = await urlUpload(requestInfo, this.dataFactory);
  51322. return Promise.resolve(requestResult);
  51323. } catch (err) {
  51324. this.requestError && this.requestError(err);
  51325. return Promise.reject(err);
  51326. } finally {
  51327. if (runRequestStart) {
  51328. this.requestEnd && this.requestEnd(requestInfo);
  51329. }
  51330. }
  51331. }
  51332. }
  51333. const developUrl = "http://v56c9b8e.natappfree.cc/";
  51334. const defaultConfig = {
  51335. // 系统名称
  51336. name: "签约",
  51337. apiUrl: developUrl
  51338. };
  51339. const mergeConfig$1 = Object.assign({}, defaultConfig);
  51340. const config = {
  51341. // 获取全部配置
  51342. all() {
  51343. return mergeConfig$1;
  51344. },
  51345. // 获取指定配置
  51346. get(key, def = void 0) {
  51347. if (mergeConfig$1.hasOwnProperty(key)) {
  51348. return mergeConfig$1[key];
  51349. }
  51350. formatAppLog("error", "at core/config/index.js:21", `检测到不存在的配置项: ${key}`);
  51351. return def;
  51352. },
  51353. getResource(imgName) {
  51354. return `${mergeConfig$1.apiUrl}images/${imgName}`;
  51355. }
  51356. };
  51357. const apiUrl = config.get("apiUrl");
  51358. const $http = new fileUpload({
  51359. // 接口请求地址
  51360. baseUrl: apiUrl,
  51361. // 服务器本地上传文件地址
  51362. fileUrl: apiUrl,
  51363. // 服务器上传图片默认url
  51364. defaultUploadUrl: "upload/image",
  51365. // 设置请求头(如果使用报错跨域问题,可能是content-type请求类型和后台那边设置的不一致)
  51366. header: {
  51367. "content-type": "application/json;charset=utf-8"
  51368. },
  51369. // 请求超时时间, 单位ms(默认15000)
  51370. timeout: 15e3,
  51371. // 默认配置(可不写)
  51372. config: {
  51373. // 是否自动提示错误
  51374. isPrompt: true,
  51375. // 是否显示加载动画
  51376. load: true,
  51377. // 是否使用数据工厂
  51378. isFactory: true
  51379. }
  51380. });
  51381. let requestNum = 0;
  51382. $http.requestStart = (options) => {
  51383. if (options.load) {
  51384. if (requestNum <= 0) {
  51385. uni.showLoading({
  51386. title: "加载中",
  51387. mask: true
  51388. });
  51389. }
  51390. requestNum += 1;
  51391. }
  51392. if (options.method == "FILE" && options.maxSize) {
  51393. const maxSize = options.maxSize;
  51394. for (let item of options.files) {
  51395. if (item.size > maxSize) {
  51396. setTimeout(() => {
  51397. uni.showToast({
  51398. title: "图片过大,请重新上传",
  51399. icon: "none"
  51400. });
  51401. });
  51402. return false;
  51403. }
  51404. }
  51405. }
  51406. options.header["api-name"] = store.getters.platform;
  51407. options.header["token"] = store.getters.token;
  51408. return options;
  51409. };
  51410. $http.requestEnd = (options) => {
  51411. if (options.load) {
  51412. if (requestNum > 0) {
  51413. uni.hideLoading();
  51414. }
  51415. }
  51416. };
  51417. $http.dataFactory = async (res) => {
  51418. requestNum -= 1;
  51419. if (requestNum <= 0) {
  51420. uni.hideLoading();
  51421. }
  51422. const httpData = res.response;
  51423. if (httpData.code === 0) {
  51424. uni.showToast({
  51425. title: httpData.msg,
  51426. icon: "none",
  51427. duration: 2500
  51428. });
  51429. return false;
  51430. } else if (httpData.code == 401) {
  51431. store.dispatch("Logout");
  51432. uni.showToast({
  51433. title: "登录状态错误或已失效",
  51434. icon: "none",
  51435. duration: 2500
  51436. });
  51437. return false;
  51438. } else if (httpData.code === 200) {
  51439. return Promise.resolve(httpData);
  51440. } else {
  51441. uni.showToast({
  51442. title: "服务端错误",
  51443. icon: "none",
  51444. duration: 2500
  51445. });
  51446. return false;
  51447. }
  51448. };
  51449. $http.requestError = (e2) => {
  51450. if (e2.statusCode === 0) {
  51451. throw e2;
  51452. } else {
  51453. setTimeout(() => showRequestError(e2), 10);
  51454. }
  51455. };
  51456. const showRequestError = (e2) => {
  51457. let errMsg = `网络请求出错:${e2.errMsg}`;
  51458. if (e2.errMsg === "request:fail") {
  51459. errMsg = "网络请求错误,请检查您的网络是否正常!";
  51460. }
  51461. uni.showToast({
  51462. title: errMsg,
  51463. icon: "none",
  51464. duration: 3500
  51465. });
  51466. };
  51467. const request$1 = $http;
  51468. const api$1 = {
  51469. userLoginWX: "api/login/login",
  51470. userLloginApp: "api/login/loginApp",
  51471. userLoginH5: "api/login/loginH5",
  51472. doSmsSend: "api/sms/send",
  51473. checkSms: "api/sms/checkSms",
  51474. resetPassword: "api/login/resetPassword",
  51475. // 我写的登录
  51476. loginByApp: "app/user/loginByApp",
  51477. captchaImage: "captchaImage"
  51478. };
  51479. function userLoginWX(data) {
  51480. return request$1.post(api$1.userLoginWX, data);
  51481. }
  51482. function userLloginApp(data) {
  51483. return request$1.post(api$1.userLloginApp, data);
  51484. }
  51485. function userLoginH5(data) {
  51486. return request$1.post(api$1.userLoginH5, data);
  51487. }
  51488. function loginByApp(data) {
  51489. return request$1.post(api$1.loginByApp, data);
  51490. }
  51491. function captchaImage(data) {
  51492. return request$1.get(api$1.captchaImage);
  51493. }
  51494. const _imports_0$8 = "/static/image/login/apple.png";
  51495. const _sfc_main$i = {
  51496. data() {
  51497. return {
  51498. userName: "",
  51499. password: "",
  51500. registrationID: "",
  51501. unionid: "",
  51502. userPhone: "",
  51503. loginType: 0,
  51504. isApp: false,
  51505. agree: false,
  51506. isAgreePrivacy: false,
  51507. isIos: false,
  51508. from: "",
  51509. source: "",
  51510. appleKey: "",
  51511. code: {
  51512. img: "",
  51513. uuid: ""
  51514. }
  51515. };
  51516. },
  51517. onLoad(option) {
  51518. this.isIos = plus.os.name == "iOS";
  51519. this.from = option.from || "";
  51520. let that = this;
  51521. uni.$on("getRegistrationID", function(data) {
  51522. that.registrationID = data;
  51523. });
  51524. this.isApp = true;
  51525. this.source = plus.runtime.channel || "app";
  51526. },
  51527. onShow() {
  51528. this.isAgreePrivacy = this.isIos ? true : plus.runtime.isAgreePrivacy();
  51529. if (plus.runtime.isAgreePrivacy()) {
  51530. this.getRegistrationID();
  51531. }
  51532. },
  51533. onUnload() {
  51534. uni.$off("getRegistrationID");
  51535. },
  51536. mounted() {
  51537. },
  51538. methods: {
  51539. initUniverify() {
  51540. const callback = (res) => {
  51541. univerifyManager.getCheckBoxState({
  51542. success(res2) {
  51543. if (res2.state) {
  51544. univerifyManager.close();
  51545. }
  51546. }
  51547. });
  51548. };
  51549. univerifyManager.onButtonsClick(callback);
  51550. univerifyManager.offButtonsClick(callback);
  51551. },
  51552. verificationCode() {
  51553. captchaImage().then((res) => {
  51554. if (res.code == 200) {
  51555. this.code.img = res.img;
  51556. this.code.uuid = res.uuid;
  51557. formatAppLog("log", "at pages/login/login.vue:152", "qqq", res);
  51558. }
  51559. });
  51560. },
  51561. login() {
  51562. formatAppLog("log", "at pages/login/login.vue:201", "dianl");
  51563. var data = {
  51564. // jpushId:this.registrationID,
  51565. phone: this.userName,
  51566. // password: this.password,
  51567. // code:this.code,
  51568. loginType: 3
  51569. // source: this.source
  51570. };
  51571. loginByApp(data).then(
  51572. (res) => {
  51573. formatAppLog("log", "at pages/login/login.vue:215", res, "444");
  51574. uni.hideLoading();
  51575. if (res.code == 200) {
  51576. formatAppLog("log", "at pages/login/login.vue:219", "token", res.token);
  51577. uni.setStorageSync("userInfo", JSON.stringify(res.user));
  51578. uni.setStorageSync("AppToken", res.token);
  51579. uni.switchTab({
  51580. url: "/pages/list/index"
  51581. });
  51582. } else {
  51583. uni.showToast({
  51584. title: res.msg,
  51585. icon: "none"
  51586. });
  51587. }
  51588. },
  51589. (rej) => {
  51590. formatAppLog("log", "at pages/login/login.vue:253", "qxj rej:" + JSON.stringify(rej));
  51591. }
  51592. );
  51593. },
  51594. quickAppleLogin() {
  51595. let that = this;
  51596. if (!this.agree) {
  51597. uni.showToast({
  51598. title: "请同意相关协议",
  51599. icon: "none"
  51600. });
  51601. return;
  51602. }
  51603. uni.getProvider({
  51604. service: "oauth",
  51605. success: function(res) {
  51606. if (res.provider.indexOf("apple")) {
  51607. uni.login({
  51608. provider: "apple",
  51609. success: function(loginRes) {
  51610. that.appleKey = loginRes.authResult.openid;
  51611. that.loginByAppleAct(loginRes.authResult);
  51612. },
  51613. fail: function(err) {
  51614. formatAppLog("log", "at pages/login/login.vue:279", err);
  51615. }
  51616. });
  51617. }
  51618. }
  51619. });
  51620. },
  51621. async loginByAppleAct(authResult) {
  51622. let loginDevice = "";
  51623. if (plus.runtime.isAgreePrivacy()) {
  51624. const info = await uni.getPushClientId();
  51625. uni.setStorageSync("registrationID", info.cid);
  51626. this.registrationID = info.cid;
  51627. let devinfo = await uni.getDeviceInfo();
  51628. if (devinfo != null) {
  51629. loginDevice += devinfo.deviceBrand ? devinfo.deviceBrand : "";
  51630. loginDevice += devinfo.deviceModel ? " " + devinfo.deviceModel : "";
  51631. loginDevice += devinfo.system ? " " + devinfo.system : "";
  51632. }
  51633. }
  51634. const params = {
  51635. loginDevice,
  51636. jpushId: this.registrationID,
  51637. source: this.source,
  51638. appleKey: authResult.openid
  51639. };
  51640. uni.showLoading({
  51641. title: "登陆中"
  51642. });
  51643. loginByApple(params).then((res) => {
  51644. uni.hideLoading();
  51645. if (res.user != null) {
  51646. uni.hideLoading();
  51647. uni.setStorageSync("AppToken", res.token);
  51648. uni.setStorageSync("userInfo", JSON.stringify(res.user));
  51649. uni.closeAuthView();
  51650. uni.$emit("refreshIM");
  51651. uni.$emit("showHealthButler");
  51652. uni.$emit("refreshUserInfo", {});
  51653. this.goPage();
  51654. } else {
  51655. if (res.isNew) {
  51656. this.bindMobile("apple");
  51657. }
  51658. }
  51659. }).catch(() => {
  51660. uni.hideLoading();
  51661. });
  51662. },
  51663. loginWeixin() {
  51664. if (!this.agree) {
  51665. uni.showToast({
  51666. title: "请同意相关协议",
  51667. icon: "none"
  51668. });
  51669. return;
  51670. }
  51671. uni.login({
  51672. provider: "weixin",
  51673. onlyAuthorize: true,
  51674. success: async (res) => {
  51675. uni.showLoading({
  51676. title: "处理中..."
  51677. });
  51678. const params = {
  51679. code: res.code,
  51680. jpushId: this.registrationID,
  51681. source: this.source
  51682. };
  51683. this.loginByWeChatAct(params);
  51684. },
  51685. fail: (err) => {
  51686. formatAppLog("log", "at pages/login/login.vue:355", "qxj loginWeixin fail:", JSON.stringify(err));
  51687. if (err.code == 1e3) {
  51688. uni.showModal({
  51689. title: "登录失败",
  51690. content: `${err.errMsg}
  51691. ,错误码:${err.code}`,
  51692. confirmText: "开通指南",
  51693. cancelText: "确定",
  51694. success: (res) => {
  51695. if (res.confirm) {
  51696. setTimeout(() => {
  51697. plus.runtime.openWeb(
  51698. "https://ask.dcloud.net.cn/article/37965"
  51699. );
  51700. }, 500);
  51701. }
  51702. }
  51703. });
  51704. return;
  51705. }
  51706. if (err.code == "30005") {
  51707. uni.showModal({
  51708. showCancel: false,
  51709. title: "预登录失败",
  51710. content: err.errMsg
  51711. });
  51712. return;
  51713. }
  51714. if (err.code != "30003") {
  51715. uni.showModal({
  51716. showCancel: false,
  51717. title: "登录失败",
  51718. content: JSON.stringify(err)
  51719. });
  51720. }
  51721. },
  51722. complete: () => {
  51723. }
  51724. });
  51725. },
  51726. goToRegister() {
  51727. this.$navTo("./register");
  51728. },
  51729. goToFindPass() {
  51730. this.$navTo("./findpass");
  51731. },
  51732. doUniverify(authResult) {
  51733. tr.callFunction({
  51734. name: "loginByMobile",
  51735. // 你的云函数名称
  51736. data: {
  51737. access_token: authResult.access_token,
  51738. // 客户端一键登录接口返回的access_token
  51739. openid: authResult.openid
  51740. // 客户端一键登录接口返回的openid
  51741. }
  51742. }).then((res) => {
  51743. uni.closeAuthView();
  51744. if (res.result.errCode == 0) {
  51745. this.userName = res.result.phoneNumber;
  51746. } else {
  51747. uni.showToast({
  51748. title: res.result.message,
  51749. icon: "none"
  51750. });
  51751. }
  51752. }).catch((err) => {
  51753. formatAppLog("error", "at pages/login/login.vue:425", "调用云函数失败:", err);
  51754. formatAppLog("error", "at pages/login/login.vue:427", "错误信息:", err.errMsg);
  51755. });
  51756. },
  51757. loginByWeChatAct(params) {
  51758. loginByWeChat(params).then(
  51759. (res) => {
  51760. if (res.code == 200) {
  51761. if (res.user != null) {
  51762. uni.hideLoading();
  51763. uni.setStorageSync("AppToken", res.token);
  51764. uni.setStorageSync("userInfo", JSON.stringify(res.user));
  51765. uni.closeAuthView();
  51766. uni.$emit("refreshIM");
  51767. uni.$emit("showHealthButler");
  51768. uni.$emit("refreshUserInfo", {});
  51769. this.goPage();
  51770. } else {
  51771. this.unionid = res.unionid;
  51772. if (res.isNew) {
  51773. this.bindMobile();
  51774. }
  51775. }
  51776. } else {
  51777. uni.hideLoading();
  51778. uni.showToast({
  51779. title: res.msg,
  51780. icon: "none"
  51781. });
  51782. }
  51783. },
  51784. (rej) => {
  51785. }
  51786. );
  51787. },
  51788. bindMobile(type) {
  51789. uni.login({
  51790. provider: "univerify",
  51791. univerifyStyle: {
  51792. // 自定义登录框样式
  51793. fullScreen: false,
  51794. authButton: {
  51795. "title": "绑定手机号",
  51796. "normalColor": "#FF5C03",
  51797. "highlightColor": "#FF5C03"
  51798. },
  51799. privacyTerms: {
  51800. "defaultCheckBoxState": true,
  51801. // 条款勾选框初始状态 默认值: true
  51802. "isCenterHint": false,
  51803. //未勾选服务条款时点击登录按钮的提示是否居中显示 默认值: false (3.7.13+ 版本支持)
  51804. "uncheckedImage": "",
  51805. // 可选 条款勾选框未选中状态图片(仅支持本地图片 建议尺寸 24x24px)(3.2.0+ 版本支持)
  51806. "checkedImage": "",
  51807. // 可选 条款勾选框选中状态图片(仅支持本地图片 建议尺寸24x24px)(3.2.0+ 版本支持)
  51808. "checkBoxSize": 18,
  51809. // 可选 条款勾选框大小
  51810. "textColor": "#BBBBBB",
  51811. // 文字颜色 默认值:#BBBBBB
  51812. "termsColor": "#FF5C03",
  51813. // 协议文字颜色 默认值: #5496E3
  51814. "prefix": "我已阅读并同意",
  51815. // 条款前的文案 默认值:“我已阅读并同意”
  51816. "suffix": "并使用本机号码登录",
  51817. // 条款后的文案 默认值:“并使用本机号码登录”
  51818. "privacyItems": [
  51819. // 自定义协议条款,最大支持2个,需要同时设置url和title. 否则不生效
  51820. ]
  51821. }
  51822. },
  51823. success(res) {
  51824. formatAppLog("log", "at pages/login/login.vue:489", "qxj univerify login:" + JSON.stringify(res.authResult));
  51825. if (type == "apple") {
  51826. this.loginByUniverify(res.authResult, 3);
  51827. } else {
  51828. this.loginByUniverify(res.authResult, 1);
  51829. }
  51830. },
  51831. fail(res) {
  51832. uni.hideLoading();
  51833. uni.showToast({
  51834. title: "一键登录失败请检查网络和SIM卡是否可用",
  51835. icon: "none",
  51836. position: "bottom"
  51837. });
  51838. uni.navigateTo({
  51839. url: "/pages/auth/login"
  51840. });
  51841. formatAppLog("log", "at pages/login/login.vue:511", "qxj failRes:" + JSON.stringify(res));
  51842. }
  51843. });
  51844. },
  51845. loginByUniverify(authResult, type) {
  51846. tr.callFunction({
  51847. name: "loginByMobile",
  51848. // 你的云函数名称
  51849. data: {
  51850. access_token: authResult.access_token,
  51851. // 客户端一键登录接口返回的access_token
  51852. openid: authResult.openid
  51853. // 客户端一键登录接口返回的openid
  51854. }
  51855. }).then((res) => {
  51856. formatAppLog("log", "at pages/login/login.vue:532", "qxj doUniverify:", JSON.stringify(res));
  51857. if (res.result.errCode == 0) {
  51858. userPhone = res.result.phoneNumber;
  51859. if (type == 3) {
  51860. this.setPhoneAct(3, userPhone, this.unionid);
  51861. } else {
  51862. this.setPhoneAct(1, userPhone, this.unionid);
  51863. }
  51864. } else {
  51865. uni.showToast({
  51866. title: res.result.message,
  51867. icon: "none"
  51868. });
  51869. }
  51870. }).catch((err) => {
  51871. formatAppLog("error", "at pages/login/login.vue:549", "调用云函数失败:", err);
  51872. formatAppLog("error", "at pages/login/login.vue:551", "错误信息:", err.errMsg);
  51873. });
  51874. },
  51875. setPhoneAct(type, phone, unionId) {
  51876. let params = {
  51877. phone,
  51878. unionId
  51879. };
  51880. if (type == 3) {
  51881. params = {
  51882. phone,
  51883. unionId,
  51884. appleKey: this.appleKey
  51885. };
  51886. }
  51887. setPhone(params).then(
  51888. (res) => {
  51889. uni.hideLoading();
  51890. if (res.code == 200) {
  51891. uni.setStorageSync("AppToken", res.token);
  51892. uni.setStorageSync("userInfo", JSON.stringify(res.user));
  51893. uni.closeAuthView();
  51894. uni.$emit("refreshIM");
  51895. this.goPage();
  51896. } else {
  51897. uni.showToast({
  51898. title: res.msg,
  51899. icon: "none"
  51900. });
  51901. uni.closeAuthView();
  51902. }
  51903. },
  51904. (rej) => {
  51905. }
  51906. );
  51907. },
  51908. getRegistrationID() {
  51909. this.registrationID = uni.getStorageSync("registrationID");
  51910. if (this.registrationID == null || this.registrationID == "") {
  51911. uni.getPushClientId({
  51912. success: (res) => {
  51913. uni.setStorageSync("registrationID", res.cid);
  51914. this.registrationID = res.cid;
  51915. }
  51916. });
  51917. }
  51918. },
  51919. goBack() {
  51920. formatAppLog("log", "at pages/login/login.vue:600", "qxj goBack");
  51921. uni.$emit("showHealthButler");
  51922. uni.redirectTo({
  51923. url: "/pages/auth/loginIndex"
  51924. });
  51925. },
  51926. handleAgree() {
  51927. this.agree = !this.agree;
  51928. if (this.isIos) {
  51929. if (this.agree) {
  51930. plus.runtime.agreePrivacy();
  51931. this.getRegistrationID();
  51932. } else {
  51933. plus.runtime.disagreePrivacy();
  51934. }
  51935. }
  51936. },
  51937. goToWeb(index2) {
  51938. uni.setStorageSync("url", index2 == 0 ? "https://userapp.his.cdwjyyh.com/web/userAgreement" : "https://userapp.his.cdwjyyh.com/web/privacyPolicy");
  51939. uni.navigateTo({
  51940. url: "/pages/index/h5"
  51941. });
  51942. },
  51943. goPage() {
  51944. let pages2 = getCurrentPages();
  51945. pages2[pages2.length - 1];
  51946. let openUrl = uni.getStorageSync("openUrl");
  51947. if (openUrl) {
  51948. uni.navigateTo({
  51949. url: openUrl,
  51950. success: function(res) {
  51951. uni.removeStorageSync("openUrl");
  51952. }
  51953. });
  51954. } else {
  51955. uni.reLaunch({
  51956. url: "../course/index",
  51957. animationType: "none",
  51958. animationDuration: 2e3
  51959. });
  51960. return;
  51961. }
  51962. this.$updateMsgDot();
  51963. this.$setSource();
  51964. }
  51965. }
  51966. };
  51967. function _sfc_render$h(_ctx, _cache, $props, $setup, $data, $options) {
  51968. return vue.openBlock(), vue.createElementBlock("view", null, [
  51969. vue.createElementVNode("view", { class: "content x-c" }, [
  51970. vue.createCommentVNode(' <image class="backImg" @tap="goBack()" src="../../static/images/icon_close.png"></image> '),
  51971. vue.createElementVNode("view", { class: "pageTop x-c" }, [
  51972. vue.createElementVNode("view", { class: "head x-c" }, " 登录即可体验完整功能 "),
  51973. vue.createElementVNode("view", { class: "loginBox" }, [
  51974. vue.createElementVNode("view", { class: "login-item" }, [
  51975. vue.createElementVNode("view", { class: "input-account" }, [
  51976. vue.withDirectives(vue.createElementVNode(
  51977. "input",
  51978. {
  51979. "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => $data.userName = $event),
  51980. placeholder: "手机号登录",
  51981. type: "number"
  51982. },
  51983. null,
  51984. 512
  51985. /* NEED_PATCH */
  51986. ), [
  51987. [vue.vModelText, $data.userName]
  51988. ])
  51989. ]),
  51990. vue.createElementVNode("view", { class: "line" })
  51991. ]),
  51992. vue.createElementVNode("view", { class: "login-item" }, [
  51993. vue.createElementVNode("view", { class: "input-pwd" }, [
  51994. vue.withDirectives(vue.createElementVNode(
  51995. "input",
  51996. {
  51997. "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => $data.password = $event),
  51998. placeholder: "请输入密码",
  51999. type: "password"
  52000. },
  52001. null,
  52002. 512
  52003. /* NEED_PATCH */
  52004. ), [
  52005. [vue.vModelText, $data.password]
  52006. ])
  52007. ]),
  52008. vue.createElementVNode("view", { class: "line" })
  52009. ]),
  52010. vue.createElementVNode("view", { class: "btns" }, [
  52011. vue.createElementVNode("view", {
  52012. class: "login-btn",
  52013. onClick: _cache[2] || (_cache[2] = (...args) => $options.login && $options.login(...args))
  52014. }, "登录")
  52015. ]),
  52016. vue.createCommentVNode(' <view class="btns">\r\n <view class="login-btn" @click="verificationCode">验证码</view>\r\n </view> '),
  52017. vue.createElementVNode("view", { class: "reg-box x-bc" }, [
  52018. vue.createElementVNode("view", {
  52019. class: "reg-btn",
  52020. onClick: _cache[3] || (_cache[3] = ($event) => $options.goToRegister())
  52021. }, "注册账号"),
  52022. vue.createCommentVNode(' <view class="reg-btn" @click="goToFindPass()">忘记密码</view> ')
  52023. ])
  52024. ])
  52025. ]),
  52026. $data.isApp && $data.isAgreePrivacy ? (vue.openBlock(), vue.createElementBlock("view", {
  52027. key: 0,
  52028. class: "pageBottom"
  52029. }, [
  52030. vue.createElementVNode("view", { class: "tips y-f" }, " — 快捷登录 — "),
  52031. vue.createElementVNode("view", { class: "menu x-ac" }, [
  52032. vue.createCommentVNode(' <view @tap="loginWeixin" ><image src="/static/image/login/weixin.png"></image></view> '),
  52033. $data.isIos ? (vue.openBlock(), vue.createElementBlock("view", {
  52034. key: 0,
  52035. onClick: _cache[4] || (_cache[4] = (...args) => $options.quickAppleLogin && $options.quickAppleLogin(...args))
  52036. }, [
  52037. vue.createElementVNode("image", { src: _imports_0$8 })
  52038. ])) : vue.createCommentVNode("v-if", true),
  52039. vue.createCommentVNode(' <view><image src="/static/image/login/qq.png"></image></view>\r\n <view><image src="/static/image/login/weibo.png"></image></view> ')
  52040. ])
  52041. ])) : vue.createCommentVNode("v-if", true),
  52042. vue.createElementVNode("view", { class: "checkbox" }, [
  52043. vue.createElementVNode("view", {
  52044. class: "checkbox-icon",
  52045. onClick: _cache[5] || (_cache[5] = (...args) => $options.handleAgree && $options.handleAgree(...args))
  52046. }, [
  52047. vue.createCommentVNode(' <image src="../../static/image/login/radio_default.png" v-show="!agree"></image>\r\n <image src="../../static/image/login/radio_choose.png" v-show="agree"></image>\r\n ')
  52048. ]),
  52049. vue.createElementVNode("view", null, [
  52050. vue.createTextVNode("我已阅读并同意"),
  52051. vue.createElementVNode("text", {
  52052. onClick: _cache[6] || (_cache[6] = ($event) => $options.goToWeb(0))
  52053. }, "《用户协议》"),
  52054. vue.createElementVNode("text", {
  52055. onClick: _cache[7] || (_cache[7] = ($event) => $options.goToWeb(1))
  52056. }, "《隐私政策》"),
  52057. vue.createTextVNode(" 并使用本机号码登录")
  52058. ])
  52059. ])
  52060. ])
  52061. ]);
  52062. }
  52063. const PagesLoginLogin = /* @__PURE__ */ _export_sfc(_sfc_main$i, [["render", _sfc_render$h], ["__scopeId", "data-v-e4e4508d"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages/login/login.vue"]]);
  52064. const _sfc_main$h = {
  52065. name: "Loading",
  52066. props: {
  52067. loaded: Boolean,
  52068. loading: Boolean
  52069. }
  52070. };
  52071. function _sfc_render$g(_ctx, _cache, $props, $setup, $data, $options) {
  52072. return $props.loading || !$props.loaded ? (vue.openBlock(), vue.createElementBlock("view", {
  52073. key: 0,
  52074. class: "Loads acea-row row-center-wrapper",
  52075. style: { "margin-top": "20rpx" }
  52076. }, [
  52077. $props.loading ? (vue.openBlock(), vue.createElementBlock(
  52078. vue.Fragment,
  52079. { key: 0 },
  52080. [
  52081. vue.createElementVNode("view", { class: "iconfont icon-jiazai loading acea-row row-center-wrapper" }),
  52082. vue.createTextVNode(" 正在加载中 ")
  52083. ],
  52084. 64
  52085. /* STABLE_FRAGMENT */
  52086. )) : vue.createCommentVNode("v-if", true),
  52087. !$props.loading ? (vue.openBlock(), vue.createElementBlock(
  52088. vue.Fragment,
  52089. { key: 1 },
  52090. [
  52091. vue.createTextVNode(" 上拉加载更多 ")
  52092. ],
  52093. 64
  52094. /* STABLE_FRAGMENT */
  52095. )) : vue.createCommentVNode("v-if", true)
  52096. ])) : vue.createCommentVNode("v-if", true);
  52097. }
  52098. const Loading = /* @__PURE__ */ _export_sfc(_sfc_main$h, [["render", _sfc_render$g], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/components/Loading.vue"]]);
  52099. const _imports_0$7 = "/static/images/like.png";
  52100. const _sfc_main$g = {
  52101. components: { Loading },
  52102. name: "likeProduct",
  52103. data() {
  52104. return {
  52105. page: {
  52106. page: 1,
  52107. pageSize: 10
  52108. },
  52109. total: 0,
  52110. list: [],
  52111. loaded: false,
  52112. loading: false
  52113. };
  52114. },
  52115. created() {
  52116. },
  52117. mounted() {
  52118. this.getGoodsProducts();
  52119. },
  52120. methods: {
  52121. getGoodsProducts() {
  52122. formatAppLog("log", "at pages_shop/components/likeProduct.vue:54", 1);
  52123. var that = this;
  52124. if (that.loaded == true || that.loading == true)
  52125. return;
  52126. that.loading = true;
  52127. uni.showLoading({
  52128. title: "加载中..."
  52129. });
  52130. getGoodsProducts(that.page).then(
  52131. (res) => {
  52132. if (res.code == 200) {
  52133. that.total = res.data.total;
  52134. that.list.push.apply(that.list, res.data.list);
  52135. that.loading = false;
  52136. that.loaded = that.list.length < that.total ? false : true;
  52137. that.page.page = that.page.page + 1;
  52138. uni.hideLoading();
  52139. }
  52140. },
  52141. (err) => {
  52142. uni.hideLoading();
  52143. uni.showToast({
  52144. title: err.msg,
  52145. icon: "none",
  52146. duration: 2e3
  52147. });
  52148. }
  52149. );
  52150. },
  52151. showProduct(item) {
  52152. uni.navigateTo({
  52153. url: "/pages/shopping/productDetails?productId=" + item.productId
  52154. });
  52155. }
  52156. }
  52157. };
  52158. function _sfc_render$f(_ctx, _cache, $props, $setup, $data, $options) {
  52159. const _component_Loading = vue.resolveComponent("Loading");
  52160. return vue.openBlock(), vue.createElementBlock("view", null, [
  52161. vue.createElementVNode("view", { class: "like-title" }, [
  52162. vue.createElementVNode("image", {
  52163. src: _imports_0$7,
  52164. mode: ""
  52165. }),
  52166. vue.createElementVNode("text", { class: "text" }, "猜你喜欢")
  52167. ]),
  52168. vue.createElementVNode("view", { class: "like-list" }, [
  52169. (vue.openBlock(true), vue.createElementBlock(
  52170. vue.Fragment,
  52171. null,
  52172. vue.renderList($data.list, (item, index2) => {
  52173. return vue.openBlock(), vue.createElementBlock("view", {
  52174. class: "item",
  52175. key: index2,
  52176. onClick: ($event) => $options.showProduct(item)
  52177. }, [
  52178. vue.createElementVNode("view", { class: "img-box" }, [
  52179. vue.createElementVNode("image", {
  52180. src: item.image,
  52181. mode: ""
  52182. }, null, 8, ["src"])
  52183. ]),
  52184. vue.createElementVNode("view", { class: "info-box" }, [
  52185. vue.createElementVNode(
  52186. "view",
  52187. { class: "title ellipsis2" },
  52188. vue.toDisplayString(item.productName),
  52189. 1
  52190. /* TEXT */
  52191. ),
  52192. vue.createElementVNode("view", { class: "price-box" }, [
  52193. vue.createElementVNode("view", { class: "now" }, [
  52194. vue.createElementVNode("text", { class: "unit" }, "¥"),
  52195. vue.createElementVNode(
  52196. "text",
  52197. { class: "num" },
  52198. vue.toDisplayString(item.price.toFixed(2)),
  52199. 1
  52200. /* TEXT */
  52201. )
  52202. ]),
  52203. vue.createElementVNode(
  52204. "view",
  52205. { class: "old" },
  52206. "¥" + vue.toDisplayString(item.otPrice.toFixed(2)),
  52207. 1
  52208. /* TEXT */
  52209. )
  52210. ])
  52211. ])
  52212. ], 8, ["onClick"]);
  52213. }),
  52214. 128
  52215. /* KEYED_FRAGMENT */
  52216. ))
  52217. ]),
  52218. vue.createVNode(_component_Loading, {
  52219. loaded: $data.loaded,
  52220. loading: $data.loading
  52221. }, null, 8, ["loaded", "loading"])
  52222. ]);
  52223. }
  52224. const likeProduct = /* @__PURE__ */ _export_sfc(_sfc_main$g, [["render", _sfc_render$f], ["__scopeId", "data-v-68f2157a"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages_shop/components/likeProduct.vue"]]);
  52225. const _imports_0$6 = "/static/images/jian.png";
  52226. const _imports_1$4 = "/static/images/jian2.png";
  52227. const _imports_2$3 = "/static/images/add.png";
  52228. const _imports_2$2 = "/static/images/no_data.png";
  52229. const _sfc_main$f = {
  52230. components: {
  52231. likeProduct
  52232. },
  52233. data() {
  52234. return {
  52235. totalMoney: 0,
  52236. carts: [],
  52237. checkAll: false
  52238. };
  52239. },
  52240. onLoad() {
  52241. },
  52242. onShow() {
  52243. this.getCarts();
  52244. },
  52245. onReachBottom() {
  52246. },
  52247. methods: {
  52248. delCart() {
  52249. var selectCarts = this.carts.flatMap((item) => item.list.filter((listItem) => listItem.checked === true)).map((el) => el.id);
  52250. if (selectCarts.length == 0) {
  52251. uni.showToast({
  52252. icon: "none",
  52253. title: "请选择商品删除"
  52254. });
  52255. return;
  52256. }
  52257. let data = { ids: selectCarts };
  52258. delCart(data).then(
  52259. (res) => {
  52260. if (res.code == 200) {
  52261. uni.showToast({
  52262. icon: "success",
  52263. title: "操作成功"
  52264. });
  52265. this.getCarts();
  52266. } else {
  52267. uni.showToast({
  52268. icon: "none",
  52269. title: res.msg
  52270. });
  52271. }
  52272. },
  52273. (rej) => {
  52274. }
  52275. );
  52276. formatAppLog("log", "at pages_shop/cart.vue:133", selectCarts);
  52277. },
  52278. computedMoney() {
  52279. var money = 0;
  52280. this.carts.forEach((item, index2, arr) => {
  52281. item.list.forEach((it2) => {
  52282. if (it2.checked) {
  52283. money += it2.price * it2.cartNum;
  52284. }
  52285. });
  52286. });
  52287. formatAppLog("log", "at pages_shop/cart.vue:145", money);
  52288. this.totalMoney = money;
  52289. },
  52290. handleCheckAll() {
  52291. this.checkAll = !this.checkAll;
  52292. var that = this;
  52293. this.carts.forEach((item, index2, arr) => {
  52294. item.checked = that.checkAll;
  52295. item.list.forEach((it2) => {
  52296. it2.checked = that.checkAll;
  52297. });
  52298. });
  52299. this.computedMoney();
  52300. },
  52301. checkShopChange(item) {
  52302. item.checked = !item.checked;
  52303. item.list.forEach((it2) => {
  52304. it2.checked = item.checked;
  52305. });
  52306. this.computedMoney();
  52307. },
  52308. checkChange(item, shop) {
  52309. item.checked = !item.checked;
  52310. shop.checked = shop.list.every((it2) => it2.checked == true);
  52311. this.computedMoney();
  52312. },
  52313. changeNum(e2, item) {
  52314. item.cartNum = e2.detail.value.replace(/\D/g, "");
  52315. if (item.cartNum <= 1) {
  52316. uni.showToast({
  52317. title: "已经是底线啦!",
  52318. icon: "none",
  52319. duration: 2e3
  52320. });
  52321. return;
  52322. }
  52323. if (item.cartNum < 1) {
  52324. item.cartNum = 1;
  52325. }
  52326. if (item.cartNum >= item.stock) {
  52327. item.cartNum = item.stock;
  52328. }
  52329. this.changeCartNum(item);
  52330. },
  52331. changeCartNum(item) {
  52332. let data = { number: item.cartNum, id: item.id };
  52333. cartNum(data).then(
  52334. (res) => {
  52335. if (res.code == 200) {
  52336. uni.showToast({
  52337. icon: "none",
  52338. title: "操作成功"
  52339. });
  52340. this.computedMoney();
  52341. } else {
  52342. uni.showToast({
  52343. icon: "none",
  52344. title: res.msg
  52345. });
  52346. }
  52347. },
  52348. (rej) => {
  52349. }
  52350. );
  52351. },
  52352. getCarts() {
  52353. getCarts().then(
  52354. (res) => {
  52355. if (res.code == 200) {
  52356. this.carts = res.carts;
  52357. this.carts.forEach((item) => {
  52358. item.checked = false;
  52359. item.list.forEach((it2) => {
  52360. it2.checked = false;
  52361. });
  52362. });
  52363. this.computedMoney();
  52364. } else {
  52365. uni.showToast({
  52366. icon: "none",
  52367. title: "请求失败"
  52368. });
  52369. }
  52370. },
  52371. (rej) => {
  52372. }
  52373. );
  52374. },
  52375. // 购物车减法
  52376. delNum(item) {
  52377. if (item.cartNum <= 1) {
  52378. uni.showToast({
  52379. title: "已经是底线啦!",
  52380. icon: "none",
  52381. duration: 2e3
  52382. });
  52383. return;
  52384. }
  52385. item.cartNum--;
  52386. if (item.cartNum < 1) {
  52387. item.cartNum = 1;
  52388. }
  52389. this.changeCartNum(item);
  52390. },
  52391. // 购物车加法
  52392. addNum(item) {
  52393. formatAppLog("log", "at pages_shop/cart.vue:252", item);
  52394. item.cartNum++;
  52395. if (item.cartNum >= item.stock) {
  52396. item.cartNum = item.stock;
  52397. }
  52398. this.changeCartNum(item);
  52399. },
  52400. // 结算
  52401. submit() {
  52402. let selectCarts = this.carts.filter((item) => item.list.some((listItem) => listItem.checked === true)).map((item) => ({
  52403. storeId: item.list[0].storeId || "",
  52404. data: {
  52405. type: "cart",
  52406. cartIds: item.list.filter((it2) => it2.checked == true).map((it2) => it2.id).join(",")
  52407. }
  52408. }));
  52409. if (selectCarts.length == 0) {
  52410. uni.showToast({
  52411. icon: "none",
  52412. title: "请选择商品"
  52413. });
  52414. return;
  52415. }
  52416. uni.navigateTo({
  52417. url: "./confirmOrder?type=cart&confirmParam=" + encodeURIComponent(JSON.stringify(selectCarts))
  52418. });
  52419. },
  52420. showProduct(item) {
  52421. uni.navigateTo({
  52422. url: "../shopping/productDetails?productId=" + item.productId
  52423. });
  52424. }
  52425. }
  52426. };
  52427. function _sfc_render$e(_ctx, _cache, $props, $setup, $data, $options) {
  52428. const _component_likeProduct = vue.resolveComponent("likeProduct");
  52429. return vue.openBlock(), vue.createElementBlock("view", { class: "content" }, [
  52430. vue.createCommentVNode(" 商品列表 "),
  52431. (vue.openBlock(true), vue.createElementBlock(
  52432. vue.Fragment,
  52433. null,
  52434. vue.renderList($data.carts, (shop, idx) => {
  52435. return vue.openBlock(), vue.createElementBlock("view", {
  52436. class: "shopbox",
  52437. key: idx
  52438. }, [
  52439. shop.storeName && shop.storeName != "null" ? (vue.openBlock(), vue.createElementBlock("view", {
  52440. key: 0,
  52441. class: "shopbox-name"
  52442. }, [
  52443. vue.createElementVNode("label", { style: { "margin-right": "30upx" } }, [
  52444. vue.createElementVNode("checkbox", {
  52445. value: shop.checked,
  52446. checked: shop.checked,
  52447. onClick: ($event) => $options.checkShopChange(shop)
  52448. }, null, 8, ["value", "checked", "onClick"])
  52449. ]),
  52450. vue.createElementVNode(
  52451. "text",
  52452. null,
  52453. vue.toDisplayString(shop.storeName),
  52454. 1
  52455. /* TEXT */
  52456. )
  52457. ])) : vue.createCommentVNode("v-if", true),
  52458. vue.createElementVNode("view", { class: "goods-list" }, [
  52459. (vue.openBlock(true), vue.createElementBlock(
  52460. vue.Fragment,
  52461. null,
  52462. vue.renderList(shop.list, (item, index2) => {
  52463. return vue.openBlock(), vue.createElementBlock("view", {
  52464. class: "item",
  52465. key: index2
  52466. }, [
  52467. vue.createElementVNode("label", { style: { "margin-right": "30upx" } }, [
  52468. vue.createElementVNode("checkbox", {
  52469. value: item.checked,
  52470. checked: item.checked,
  52471. onClick: ($event) => $options.checkChange(item, shop)
  52472. }, null, 8, ["value", "checked", "onClick"])
  52473. ]),
  52474. vue.createElementVNode("image", {
  52475. class: "goods-img",
  52476. src: item.productAttrImage == null || item.productAttrImage == "" ? item.productImage : item.productAttrImage,
  52477. mode: "aspectFit"
  52478. }, null, 8, ["src"]),
  52479. vue.createElementVNode("view", { class: "info-box" }, [
  52480. vue.createElementVNode("view", null, [
  52481. vue.createElementVNode("view", { class: "title-box" }, [
  52482. vue.createElementVNode(
  52483. "view",
  52484. { class: "tag" },
  52485. vue.toDisplayString(_ctx.utils.getDictLabelName("storeProductType", item.productType)),
  52486. 1
  52487. /* TEXT */
  52488. ),
  52489. vue.createElementVNode(
  52490. "view",
  52491. { class: "title ellipsis" },
  52492. vue.toDisplayString(item.productName),
  52493. 1
  52494. /* TEXT */
  52495. )
  52496. ]),
  52497. vue.createElementVNode(
  52498. "view",
  52499. { class: "intro ellipsis" },
  52500. vue.toDisplayString(item.productAttrName),
  52501. 1
  52502. /* TEXT */
  52503. )
  52504. ]),
  52505. vue.createElementVNode("view", { class: "price-num" }, [
  52506. vue.createElementVNode("view", { class: "price" }, [
  52507. vue.createElementVNode("text", { class: "unit" }, "¥"),
  52508. vue.createElementVNode(
  52509. "text",
  52510. { class: "text" },
  52511. vue.toDisplayString(item.price),
  52512. 1
  52513. /* TEXT */
  52514. )
  52515. ]),
  52516. vue.createElementVNode("view", { class: "num-box" }, [
  52517. vue.createElementVNode("view", {
  52518. class: "img-box",
  52519. onClick: ($event) => $options.delNum(item)
  52520. }, [
  52521. item.cartNum <= 1 ? (vue.openBlock(), vue.createElementBlock("image", {
  52522. key: 0,
  52523. src: _imports_0$6,
  52524. mode: ""
  52525. })) : (vue.openBlock(), vue.createElementBlock("image", {
  52526. key: 1,
  52527. src: _imports_1$4,
  52528. mode: ""
  52529. }))
  52530. ], 8, ["onClick"]),
  52531. vue.createElementVNode("input", {
  52532. type: "number",
  52533. onChange: ($event) => $options.changeNum($event, item),
  52534. value: item.cartNum
  52535. }, null, 40, ["onChange", "value"]),
  52536. vue.createElementVNode("view", {
  52537. class: "img-box",
  52538. onClick: ($event) => $options.addNum(item)
  52539. }, [
  52540. vue.createElementVNode("image", {
  52541. src: _imports_2$3,
  52542. mode: ""
  52543. })
  52544. ], 8, ["onClick"])
  52545. ])
  52546. ])
  52547. ])
  52548. ]);
  52549. }),
  52550. 128
  52551. /* KEYED_FRAGMENT */
  52552. ))
  52553. ])
  52554. ]);
  52555. }),
  52556. 128
  52557. /* KEYED_FRAGMENT */
  52558. )),
  52559. $data.carts.length == 0 ? (vue.openBlock(), vue.createElementBlock("view", {
  52560. key: 0,
  52561. class: "no-data-box"
  52562. }, [
  52563. vue.createElementVNode("image", {
  52564. src: _imports_2$2,
  52565. mode: "aspectFit"
  52566. }),
  52567. vue.createElementVNode("view", { class: "empty-title" }, "暂无数据")
  52568. ])) : vue.createCommentVNode("v-if", true),
  52569. vue.createCommentVNode(" 猜你喜欢 "),
  52570. vue.createElementVNode("view", { class: "like-product" }, [
  52571. vue.createVNode(
  52572. _component_likeProduct,
  52573. { ref: "product" },
  52574. null,
  52575. 512
  52576. /* NEED_PATCH */
  52577. )
  52578. ]),
  52579. vue.createCommentVNode(" 底部按钮 "),
  52580. vue.createElementVNode("view", { class: "btn-foot" }, [
  52581. vue.createElementVNode("view", { class: "left" }, [
  52582. vue.createElementVNode("label", null, [
  52583. vue.createElementVNode("checkbox", {
  52584. checked: $data.checkAll,
  52585. onClick: _cache[0] || (_cache[0] = ($event) => $options.handleCheckAll())
  52586. }, null, 8, ["checked"])
  52587. ]),
  52588. vue.createElementVNode("text", { class: "text" }, "全选"),
  52589. vue.createElementVNode("text", {
  52590. class: "text",
  52591. onClick: _cache[1] || (_cache[1] = ($event) => $options.delCart())
  52592. }, "删除")
  52593. ]),
  52594. vue.createElementVNode("view", { class: "right" }, [
  52595. vue.createElementVNode("view", { class: "total" }, [
  52596. vue.createElementVNode("text", { class: "label" }, "合计:"),
  52597. vue.createElementVNode("view", { class: "price" }, [
  52598. vue.createElementVNode("text", { class: "unit" }, "¥"),
  52599. vue.createElementVNode(
  52600. "text",
  52601. { class: "num" },
  52602. vue.toDisplayString($data.totalMoney.toFixed(2)),
  52603. 1
  52604. /* TEXT */
  52605. )
  52606. ])
  52607. ]),
  52608. vue.createElementVNode("view", {
  52609. class: "btn",
  52610. onClick: _cache[2] || (_cache[2] = (...args) => $options.submit && $options.submit(...args))
  52611. }, "结算")
  52612. ])
  52613. ])
  52614. ]);
  52615. }
  52616. const PagesShopCart = /* @__PURE__ */ _export_sfc(_sfc_main$f, [["render", _sfc_render$e], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages_shop/cart.vue"]]);
  52617. const props$2 = {
  52618. props: {
  52619. // 步进器标识符,在change回调返回
  52620. name: {
  52621. type: [String, Number],
  52622. default: () => props$f.numberBox.name
  52623. },
  52624. // 用于双向绑定的值,初始化时设置设为默认min值(最小值)
  52625. modelValue: {
  52626. type: [String, Number],
  52627. default: () => props$f.numberBox.value
  52628. },
  52629. // 最小值
  52630. min: {
  52631. type: [String, Number],
  52632. default: () => props$f.numberBox.min
  52633. },
  52634. // 最大值
  52635. max: {
  52636. type: [String, Number],
  52637. default: () => props$f.numberBox.max
  52638. },
  52639. // 加减的步长,可为小数
  52640. step: {
  52641. type: [String, Number],
  52642. default: () => props$f.numberBox.step
  52643. },
  52644. // 是否只允许输入整数
  52645. integer: {
  52646. type: Boolean,
  52647. default: () => props$f.numberBox.integer
  52648. },
  52649. // 是否禁用,包括输入框,加减按钮
  52650. disabled: {
  52651. type: Boolean,
  52652. default: () => props$f.numberBox.disabled
  52653. },
  52654. // 是否禁用输入框
  52655. disabledInput: {
  52656. type: Boolean,
  52657. default: () => props$f.numberBox.disabledInput
  52658. },
  52659. // 是否开启异步变更,开启后需要手动控制输入值
  52660. asyncChange: {
  52661. type: Boolean,
  52662. default: () => props$f.numberBox.asyncChange
  52663. },
  52664. // 输入框宽度,单位为px
  52665. inputWidth: {
  52666. type: [String, Number],
  52667. default: () => props$f.numberBox.inputWidth
  52668. },
  52669. // 是否显示减少按钮
  52670. showMinus: {
  52671. type: Boolean,
  52672. default: () => props$f.numberBox.showMinus
  52673. },
  52674. // 是否显示增加按钮
  52675. showPlus: {
  52676. type: Boolean,
  52677. default: () => props$f.numberBox.showPlus
  52678. },
  52679. // 显示的小数位数
  52680. decimalLength: {
  52681. type: [String, Number, null],
  52682. default: () => props$f.numberBox.decimalLength
  52683. },
  52684. // 是否开启长按加减手势
  52685. longPress: {
  52686. type: Boolean,
  52687. default: () => props$f.numberBox.longPress
  52688. },
  52689. // 输入框文字和加减按钮图标的颜色
  52690. color: {
  52691. type: String,
  52692. default: () => props$f.numberBox.color
  52693. },
  52694. // 按钮大小,宽高等于此值,单位px,输入框高度和此值保持一致
  52695. buttonSize: {
  52696. type: [String, Number],
  52697. default: () => props$f.numberBox.buttonSize
  52698. },
  52699. // 输入框和按钮的背景颜色
  52700. bgColor: {
  52701. type: String,
  52702. default: () => props$f.numberBox.bgColor
  52703. },
  52704. // 指定光标于键盘的距离,避免键盘遮挡输入框,单位px
  52705. cursorSpacing: {
  52706. type: [String, Number],
  52707. default: () => props$f.numberBox.cursorSpacing
  52708. },
  52709. // 是否禁用增加按钮
  52710. disablePlus: {
  52711. type: Boolean,
  52712. default: () => props$f.numberBox.disablePlus
  52713. },
  52714. // 是否禁用减少按钮
  52715. disableMinus: {
  52716. type: Boolean,
  52717. default: () => props$f.numberBox.disableMinus
  52718. },
  52719. // 加减按钮图标的样式
  52720. iconStyle: {
  52721. type: [Object, String],
  52722. default: () => props$f.numberBox.iconStyle
  52723. }
  52724. }
  52725. };
  52726. const _sfc_main$e = {
  52727. name: "u-number-box",
  52728. mixins: [mpMixin, mixin$1, props$2],
  52729. data() {
  52730. return {
  52731. // 输入框实际操作的值
  52732. currentValue: "",
  52733. // 定时器
  52734. longPressTimer: null
  52735. };
  52736. },
  52737. watch: {
  52738. // 多个值之间,只要一个值发生变化,都要重新检查check()函数
  52739. watchChange(n2) {
  52740. this.check();
  52741. },
  52742. // 监听v-mode的变化,重新初始化内部的值
  52743. modelValue: {
  52744. handler: function(newV, oldV) {
  52745. if (newV !== this.currentValue) {
  52746. this.currentValue = this.format(this.modelValue);
  52747. }
  52748. },
  52749. immediate: true
  52750. }
  52751. },
  52752. computed: {
  52753. getCursorSpacing() {
  52754. return getPx(this.cursorSpacing);
  52755. },
  52756. // 按钮的样式
  52757. buttonStyle() {
  52758. return (type) => {
  52759. const style = {
  52760. backgroundColor: this.bgColor,
  52761. height: addUnit(this.buttonSize),
  52762. color: this.color
  52763. };
  52764. if (this.isDisabled(type)) {
  52765. style.backgroundColor = "#f7f8fa";
  52766. }
  52767. return style;
  52768. };
  52769. },
  52770. // 输入框的样式
  52771. inputStyle() {
  52772. this.disabled || this.disabledInput;
  52773. const style = {
  52774. color: this.color,
  52775. backgroundColor: this.bgColor,
  52776. height: addUnit(this.buttonSize),
  52777. width: addUnit(this.inputWidth)
  52778. };
  52779. return style;
  52780. },
  52781. // 用于监听多个值发生变化
  52782. watchChange() {
  52783. return [this.integer, this.decimalLength, this.min, this.max];
  52784. },
  52785. isDisabled() {
  52786. return (type) => {
  52787. if (type === "plus") {
  52788. return this.disabled || this.disablePlus || this.currentValue >= this.max;
  52789. }
  52790. return this.disabled || this.disableMinus || this.currentValue <= this.min;
  52791. };
  52792. }
  52793. },
  52794. mounted() {
  52795. this.init();
  52796. },
  52797. emits: ["update:modelValue", "focus", "blur", "overlimit", "change", "plus", "minus"],
  52798. methods: {
  52799. init() {
  52800. this.currentValue = this.format(this.modelValue);
  52801. },
  52802. // 格式化整理数据,限制范围
  52803. format(value2) {
  52804. value2 = this.filter(value2);
  52805. value2 = value2 === "" ? 0 : +value2;
  52806. value2 = Math.max(Math.min(this.max, value2), this.min);
  52807. if (this.decimalLength !== null) {
  52808. value2 = value2.toFixed(this.decimalLength);
  52809. }
  52810. return value2;
  52811. },
  52812. // 过滤非法的字符
  52813. filter(value2) {
  52814. value2 = String(value2).replace(/[^0-9.-]/g, "");
  52815. if (this.integer && value2.indexOf(".") !== -1) {
  52816. value2 = value2.split(".")[0];
  52817. }
  52818. return value2;
  52819. },
  52820. check() {
  52821. const val = this.format(this.currentValue);
  52822. if (val !== this.currentValue) {
  52823. this.currentValue = val;
  52824. }
  52825. },
  52826. // 判断是否出于禁止操作状态
  52827. // isDisabled(type) {
  52828. // if (type === 'plus') {
  52829. // // 在点击增加按钮情况下,判断整体的disabled,是否单独禁用增加按钮,以及当前值是否大于最大的允许值
  52830. // return (
  52831. // this.disabled ||
  52832. // this.disablePlus ||
  52833. // this.currentValue >= this.max
  52834. // )
  52835. // }
  52836. // // 点击减少按钮同理
  52837. // return (
  52838. // this.disabled ||
  52839. // this.disableMinus ||
  52840. // this.currentValue <= this.min
  52841. // )
  52842. // },
  52843. // 输入框活动焦点
  52844. onFocus(event) {
  52845. this.$emit("focus", {
  52846. ...event.detail,
  52847. name: this.name
  52848. });
  52849. },
  52850. // 输入框失去焦点
  52851. onBlur(event) {
  52852. this.format(event.detail.value);
  52853. this.$emit(
  52854. "blur",
  52855. {
  52856. ...event.detail,
  52857. name: this.name
  52858. }
  52859. );
  52860. },
  52861. // 输入框值发生变化
  52862. onInput(e2) {
  52863. const {
  52864. value: value2 = ""
  52865. } = e2.detail || {};
  52866. if (value2 === "")
  52867. return;
  52868. let formatted = this.filter(value2);
  52869. if (this.decimalLength !== null && formatted.indexOf(".") !== -1) {
  52870. const pair = formatted.split(".");
  52871. formatted = `${pair[0]}.${pair[1].slice(0, this.decimalLength)}`;
  52872. }
  52873. formatted = this.format(formatted);
  52874. this.emitChange(formatted);
  52875. },
  52876. // 发出change事件
  52877. emitChange(value2) {
  52878. if (!this.asyncChange) {
  52879. this.$nextTick(() => {
  52880. this.$emit("update:modelValue", value2);
  52881. this.currentValue = value2;
  52882. this.$forceUpdate();
  52883. });
  52884. }
  52885. this.$emit("change", {
  52886. value: value2,
  52887. name: this.name
  52888. });
  52889. },
  52890. onChange() {
  52891. const {
  52892. type
  52893. } = this;
  52894. if (this.isDisabled(type)) {
  52895. return this.$emit("overlimit", type);
  52896. }
  52897. const diff = type === "minus" ? -this.step : +this.step;
  52898. const value2 = this.format(this.add(+this.currentValue, diff));
  52899. this.emitChange(value2);
  52900. this.$emit(type);
  52901. },
  52902. // 对值扩大后进行四舍五入,再除以扩大因子,避免出现浮点数操作的精度问题
  52903. add(num1, num2) {
  52904. const cardinal = Math.pow(10, 10);
  52905. return Math.round((num1 + num2) * cardinal) / cardinal;
  52906. },
  52907. // 点击加减按钮
  52908. clickHandler(type) {
  52909. this.type = type;
  52910. this.onChange();
  52911. },
  52912. longPressStep() {
  52913. this.clearTimeout();
  52914. this.longPressTimer = setTimeout(() => {
  52915. this.onChange();
  52916. this.longPressStep();
  52917. }, 250);
  52918. },
  52919. onTouchStart(type) {
  52920. if (!this.longPress)
  52921. return;
  52922. this.clearTimeout();
  52923. this.type = type;
  52924. this.longPressTimer = setTimeout(() => {
  52925. this.onChange();
  52926. this.longPressStep();
  52927. }, 600);
  52928. },
  52929. // 触摸结束,清除定时器,停止长按加减
  52930. onTouchEnd() {
  52931. if (!this.longPress)
  52932. return;
  52933. this.clearTimeout();
  52934. },
  52935. // 清除定时器
  52936. clearTimeout() {
  52937. clearTimeout(this.longPressTimer);
  52938. this.longPressTimer = null;
  52939. }
  52940. }
  52941. };
  52942. function _sfc_render$d(_ctx, _cache, $props, $setup, $data, $options) {
  52943. const _component_u_icon = resolveEasycom(vue.resolveDynamicComponent("u-icon"), __easycom_0$4);
  52944. return vue.openBlock(), vue.createElementBlock("view", { class: "u-number-box" }, [
  52945. _ctx.showMinus && _ctx.$slots.minus ? (vue.openBlock(), vue.createElementBlock(
  52946. "view",
  52947. {
  52948. key: 0,
  52949. class: "u-number-box__slot cursor-pointer",
  52950. onClick: _cache[0] || (_cache[0] = vue.withModifiers(($event) => $options.clickHandler("minus"), ["stop"])),
  52951. onTouchstart: _cache[1] || (_cache[1] = ($event) => $options.onTouchStart("minus")),
  52952. onTouchend: _cache[2] || (_cache[2] = vue.withModifiers((...args) => $options.clearTimeout && $options.clearTimeout(...args), ["stop"]))
  52953. },
  52954. [
  52955. vue.renderSlot(_ctx.$slots, "minus", {}, void 0, true)
  52956. ],
  52957. 32
  52958. /* NEED_HYDRATION */
  52959. )) : _ctx.showMinus ? (vue.openBlock(), vue.createElementBlock(
  52960. "view",
  52961. {
  52962. key: 1,
  52963. class: vue.normalizeClass(["u-number-box__minus cursor-pointer", { "u-number-box__minus--disabled": $options.isDisabled("minus") }]),
  52964. onClick: _cache[3] || (_cache[3] = vue.withModifiers(($event) => $options.clickHandler("minus"), ["stop"])),
  52965. onTouchstart: _cache[4] || (_cache[4] = ($event) => $options.onTouchStart("minus")),
  52966. onTouchend: _cache[5] || (_cache[5] = vue.withModifiers((...args) => $options.clearTimeout && $options.clearTimeout(...args), ["stop"])),
  52967. "hover-class": "u-number-box__minus--hover",
  52968. "hover-stay-time": "150",
  52969. style: vue.normalizeStyle([$options.buttonStyle("minus")])
  52970. },
  52971. [
  52972. vue.createVNode(_component_u_icon, {
  52973. name: "minus",
  52974. color: $options.isDisabled("minus") ? "#c8c9cc" : "#323233",
  52975. size: "15",
  52976. bold: "",
  52977. customStyle: _ctx.iconStyle
  52978. }, null, 8, ["color", "customStyle"])
  52979. ],
  52980. 38
  52981. /* CLASS, STYLE, NEED_HYDRATION */
  52982. )) : vue.createCommentVNode("v-if", true),
  52983. vue.renderSlot(_ctx.$slots, "input", {}, () => [
  52984. vue.withDirectives(vue.createElementVNode("input", {
  52985. disabled: _ctx.disabledInput || _ctx.disabled,
  52986. "cursor-spacing": $options.getCursorSpacing,
  52987. class: vue.normalizeClass([{ "u-number-box__input--disabled": _ctx.disabled || _ctx.disabledInput }, "u-number-box__input"]),
  52988. "onUpdate:modelValue": _cache[6] || (_cache[6] = ($event) => $data.currentValue = $event),
  52989. onBlur: _cache[7] || (_cache[7] = (...args) => $options.onBlur && $options.onBlur(...args)),
  52990. onFocus: _cache[8] || (_cache[8] = (...args) => $options.onFocus && $options.onFocus(...args)),
  52991. onInput: _cache[9] || (_cache[9] = (...args) => $options.onInput && $options.onInput(...args)),
  52992. type: "number",
  52993. style: vue.normalizeStyle([$options.inputStyle])
  52994. }, null, 46, ["disabled", "cursor-spacing"]), [
  52995. [vue.vModelText, $data.currentValue]
  52996. ])
  52997. ], true),
  52998. _ctx.showPlus && _ctx.$slots.plus ? (vue.openBlock(), vue.createElementBlock(
  52999. "view",
  53000. {
  53001. key: 2,
  53002. class: "u-number-box__slot cursor-pointer",
  53003. onClick: _cache[10] || (_cache[10] = vue.withModifiers(($event) => $options.clickHandler("plus"), ["stop"])),
  53004. onTouchstart: _cache[11] || (_cache[11] = ($event) => $options.onTouchStart("plus")),
  53005. onTouchend: _cache[12] || (_cache[12] = vue.withModifiers((...args) => $options.clearTimeout && $options.clearTimeout(...args), ["stop"]))
  53006. },
  53007. [
  53008. vue.renderSlot(_ctx.$slots, "plus", {}, void 0, true)
  53009. ],
  53010. 32
  53011. /* NEED_HYDRATION */
  53012. )) : _ctx.showPlus ? (vue.openBlock(), vue.createElementBlock(
  53013. "view",
  53014. {
  53015. key: 3,
  53016. class: vue.normalizeClass(["u-number-box__plus cursor-pointer", { "u-number-box__minus--disabled": $options.isDisabled("plus") }]),
  53017. onClick: _cache[13] || (_cache[13] = vue.withModifiers(($event) => $options.clickHandler("plus"), ["stop"])),
  53018. onTouchstart: _cache[14] || (_cache[14] = ($event) => $options.onTouchStart("plus")),
  53019. onTouchend: _cache[15] || (_cache[15] = vue.withModifiers((...args) => $options.clearTimeout && $options.clearTimeout(...args), ["stop"])),
  53020. "hover-class": "u-number-box__plus--hover",
  53021. "hover-stay-time": "150",
  53022. style: vue.normalizeStyle([$options.buttonStyle("plus")])
  53023. },
  53024. [
  53025. vue.createVNode(_component_u_icon, {
  53026. name: "plus",
  53027. color: $options.isDisabled("plus") ? "#c8c9cc" : "#323233",
  53028. size: "15",
  53029. bold: "",
  53030. customStyle: _ctx.iconStyle
  53031. }, null, 8, ["color", "customStyle"])
  53032. ],
  53033. 38
  53034. /* CLASS, STYLE, NEED_HYDRATION */
  53035. )) : vue.createCommentVNode("v-if", true)
  53036. ]);
  53037. }
  53038. const __easycom_2 = /* @__PURE__ */ _export_sfc(_sfc_main$e, [["render", _sfc_render$d], ["__scopeId", "data-v-eb6f6237"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-number-box/u-number-box.vue"]]);
  53039. const _sfc_main$d = {
  53040. props: {
  53041. title: {
  53042. //标题
  53043. type: String,
  53044. default: ""
  53045. },
  53046. fontweight: {
  53047. type: [String, Number],
  53048. default: "normal"
  53049. },
  53050. visible: {
  53051. //隐藏显示标识
  53052. type: Boolean,
  53053. default: false
  53054. },
  53055. maxHeight: {
  53056. //内容区域最大高度
  53057. type: [String, Number],
  53058. default: "75%"
  53059. },
  53060. radius: {
  53061. //顶部圆角
  53062. type: [String, Number],
  53063. default: "0"
  53064. },
  53065. animaTime: {
  53066. //弹窗动画时间
  53067. type: Number,
  53068. default: 0.2
  53069. },
  53070. bottom: {
  53071. //离底部距离
  53072. type: [String, Number],
  53073. default: 0
  53074. },
  53075. bgColor: {
  53076. type: [String],
  53077. default: "#ffffff"
  53078. },
  53079. zindex: {
  53080. type: [String, Number],
  53081. default: 1e3
  53082. },
  53083. maskZindex: {
  53084. type: [String, Number],
  53085. default: 999
  53086. },
  53087. always: {
  53088. //是否每次打开都重新计算内容高度
  53089. type: Boolean,
  53090. default: false
  53091. }
  53092. },
  53093. data() {
  53094. return {
  53095. show: false,
  53096. height: 0,
  53097. PopHeight: 0,
  53098. cotMaxHeight: "",
  53099. isAnimaStart: false,
  53100. rpxRate: "",
  53101. cotRadius: 0
  53102. // closeIcon: iconClose
  53103. };
  53104. },
  53105. watch: {
  53106. visible(newval) {
  53107. this.isAnimaStart = true;
  53108. setTimeout(() => {
  53109. this.isAnimaStart = false;
  53110. }, this.animaTime * 1e3);
  53111. if (newval && this.height === 0) {
  53112. if (this.PopHeight === 0 || this.always) {
  53113. this.setContViewHeight();
  53114. } else {
  53115. this.height = this.PopHeight;
  53116. }
  53117. this.$emit("open");
  53118. } else {
  53119. this.height = 0;
  53120. }
  53121. this.show = newval;
  53122. },
  53123. maxHeight: {
  53124. handler(newval) {
  53125. this.cotMaxHeight = this.unitCheck(newval);
  53126. },
  53127. immediate: true
  53128. },
  53129. radius: {
  53130. handler(newval) {
  53131. this.cotRadius = this.unitCheck(newval);
  53132. },
  53133. immediate: true
  53134. }
  53135. },
  53136. created() {
  53137. this.rpxRate = this.getRpxRate();
  53138. },
  53139. mounted() {
  53140. this.$nextTick(() => {
  53141. });
  53142. },
  53143. methods: {
  53144. onClose() {
  53145. this.$emit("update:visible", false);
  53146. this.$emit("close");
  53147. },
  53148. //触底
  53149. onScrollToLower(e2) {
  53150. this.$emit("reachBottom");
  53151. },
  53152. getRpxRate() {
  53153. let res = uni.getSystemInfoSync();
  53154. let width = res.windowWidth;
  53155. let rate = 750 / width;
  53156. return rate;
  53157. },
  53158. unitCheck(value2) {
  53159. const val = String(value2);
  53160. if (!val.includes("px") && !val.includes("%")) {
  53161. return `${val}rpx`;
  53162. }
  53163. return val;
  53164. },
  53165. preventTouch(el) {
  53166. el.addEventListener("touchmove", function(e2) {
  53167. e2.stopPropagation();
  53168. }, {
  53169. passive: false
  53170. });
  53171. },
  53172. setBodyOverFlow(val) {
  53173. document.body.style.overflow = val;
  53174. },
  53175. //设置内容区域高度
  53176. async setContViewHeight() {
  53177. let data = await this.computeHeight();
  53178. this.height = data.height + (this.title ? 100 / parseFloat(this.rpxRate) : 0);
  53179. this.PopHeight = this.height;
  53180. },
  53181. //计算内容区域高度
  53182. computeHeight() {
  53183. return new Promise((resolve) => {
  53184. this.$nextTick(() => {
  53185. const query = uni.createSelectorQuery().in(this);
  53186. query.select("#popup_content").boundingClientRect((data) => {
  53187. resolve(data);
  53188. }).exec();
  53189. });
  53190. });
  53191. }
  53192. }
  53193. };
  53194. function _sfc_render$c(_ctx, _cache, $props, $setup, $data, $options) {
  53195. return vue.openBlock(), vue.createElementBlock(
  53196. "view",
  53197. {
  53198. class: vue.normalizeClass(["popup", { "popup-show": $data.show }]),
  53199. onMousewheel: _cache[6] || (_cache[6] = vue.withModifiers(() => {
  53200. }, ["prevent", "stop"])),
  53201. onTouchmove: _cache[7] || (_cache[7] = vue.withModifiers(() => {
  53202. }, ["stop", "prevent"])),
  53203. style: vue.normalizeStyle({ "z-index": $props.zindex })
  53204. },
  53205. [
  53206. vue.withDirectives(vue.createElementVNode(
  53207. "view",
  53208. {
  53209. class: "mask",
  53210. style: vue.normalizeStyle({ "z-index": $props.maskZindex, bottom: $props.bottom + "rpx" }),
  53211. onClick: _cache[0] || (_cache[0] = vue.withModifiers((...args) => $options.onClose && $options.onClose(...args), ["stop"])),
  53212. onTouchmove: _cache[1] || (_cache[1] = vue.withModifiers(() => {
  53213. }, ["prevent", "stop"]))
  53214. },
  53215. null,
  53216. 36
  53217. /* STYLE, NEED_HYDRATION */
  53218. ), [
  53219. [vue.vShow, $data.show]
  53220. ]),
  53221. vue.createElementVNode(
  53222. "view",
  53223. {
  53224. class: vue.normalizeClass(["content", { show: $data.show }]),
  53225. onClick: _cache[4] || (_cache[4] = vue.withModifiers(() => {
  53226. }, ["stop"])),
  53227. onTouchmove: _cache[5] || (_cache[5] = vue.withModifiers(() => {
  53228. }, ["prevent", "stop"])),
  53229. style: vue.normalizeStyle({
  53230. "background-color": $props.bgColor,
  53231. height: `${$data.height}px`,
  53232. maxHeight: $data.show ? $data.cotMaxHeight : 0,
  53233. "border-top-right-radius": $data.cotRadius,
  53234. "border-top-left-radius": $data.cotRadius,
  53235. transition: `all ${$props.animaTime}s ease-in`,
  53236. bottom: $props.bottom + "rpx",
  53237. "z-index": $props.zindex
  53238. })
  53239. },
  53240. [
  53241. vue.withDirectives(vue.createElementVNode(
  53242. "view",
  53243. {
  53244. id: "title-bar",
  53245. class: "title-bar"
  53246. },
  53247. [
  53248. vue.createElementVNode(
  53249. "view",
  53250. {
  53251. class: "title",
  53252. style: vue.normalizeStyle({ fontWeight: $props.fontweight })
  53253. },
  53254. vue.toDisplayString($props.title),
  53255. 5
  53256. /* TEXT, STYLE */
  53257. ),
  53258. vue.createElementVNode("view", {
  53259. class: "close-wrap",
  53260. onClick: _cache[2] || (_cache[2] = vue.withModifiers((...args) => $options.onClose && $options.onClose(...args), ["stop"]))
  53261. }, [
  53262. vue.createCommentVNode(' <image class="close-icon" :src="closeIcon" mode="widthFix"></image> '),
  53263. vue.createElementVNode("image", {
  53264. class: "close-icon",
  53265. src: "",
  53266. mode: "widthFix"
  53267. })
  53268. ])
  53269. ],
  53270. 512
  53271. /* NEED_PATCH */
  53272. ), [
  53273. [vue.vShow, $props.title]
  53274. ]),
  53275. vue.createElementVNode("view", { class: "scroll-wrap" }, [
  53276. vue.createElementVNode(
  53277. "scroll-view",
  53278. {
  53279. class: vue.normalizeClass({ "scroll-view": $data.isAnimaStart }),
  53280. "scroll-y": "true",
  53281. style: { "height": "100%" },
  53282. onScrolltolower: _cache[3] || (_cache[3] = (...args) => $options.onScrollToLower && $options.onScrollToLower(...args))
  53283. },
  53284. [
  53285. vue.createElementVNode("view", {
  53286. id: "popup_content",
  53287. class: "popup_content"
  53288. }, [
  53289. vue.renderSlot(_ctx.$slots, "default", {}, void 0, true)
  53290. ])
  53291. ],
  53292. 34
  53293. /* CLASS, NEED_HYDRATION */
  53294. )
  53295. ])
  53296. ],
  53297. 38
  53298. /* CLASS, STYLE, NEED_HYDRATION */
  53299. )
  53300. ],
  53301. 38
  53302. /* CLASS, STYLE, NEED_HYDRATION */
  53303. );
  53304. }
  53305. const popupBottom = /* @__PURE__ */ _export_sfc(_sfc_main$d, [["render", _sfc_render$c], ["__scopeId", "data-v-4fac7f82"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/components/px-popup-bottom/px-popup-bottom.vue"]]);
  53306. const _imports_0$5 = "/static/images/googs_service.png";
  53307. const _imports_1$3 = "/static/images/right_arrow.png";
  53308. const _imports_2$1 = "/static/images/googs1.png";
  53309. const _imports_3$1 = "/static/images/googs2.png";
  53310. const _imports_4 = "/static/images/googs3.png";
  53311. const _sfc_main$c = {
  53312. components: {
  53313. popupBottom
  53314. },
  53315. data() {
  53316. return {
  53317. totalNum: 1,
  53318. orderKey: null,
  53319. type: null,
  53320. liveOrderList: [],
  53321. //下订单的 不在这个页面
  53322. liveId: null,
  53323. // storeId:uni.setStorageSync("storeId"),
  53324. serviceList: ["免邮发货", "药师服务", "隐私保护"],
  53325. editShow: false,
  53326. productId: null,
  53327. goosDetail: {},
  53328. //商品详情
  53329. loadding: true,
  53330. buyText: "立即购买",
  53331. showStorePicker: false,
  53332. goodsNum: 0,
  53333. //商品选择数量
  53334. productValueSelect: {
  53335. price: 0,
  53336. serviceFee: 0
  53337. },
  53338. attrs: [],
  53339. values: [],
  53340. stores: [],
  53341. storeNames: [],
  53342. storeIdx: 0,
  53343. storeName: "",
  53344. product: {
  53345. price: 0,
  53346. otPrice: 0
  53347. },
  53348. showModal: false,
  53349. // 当前轮播的图片
  53350. activeBanner: 1,
  53351. // 购物车数量
  53352. cartCount: 0,
  53353. // 规格弹窗
  53354. specVisible: false,
  53355. // 规格数量
  53356. specNum: 1,
  53357. config: null,
  53358. showServiceFee: false,
  53359. selectVal: "",
  53360. // 链接带的storeId
  53361. urlStoreId: void 0,
  53362. // 所选规格门店店铺价格
  53363. storePriceList: [],
  53364. // 所选店铺
  53365. storeSelectInfo: {},
  53366. // 保存选的规格
  53367. choseSpecSubIndex: 0,
  53368. choseSpecIndex: 0
  53369. };
  53370. },
  53371. onLoad(options) {
  53372. if (options.productId) {
  53373. this.productId = options.productId;
  53374. formatAppLog("log", "at pages_shop/goods.vue:354", "接收到的productId:", this.productId);
  53375. }
  53376. this.liveId = options.liveId;
  53377. },
  53378. mounted() {
  53379. this.getliveGoods();
  53380. var userInfo = uni.getStorageSync("userInfo");
  53381. formatAppLog("log", "at pages_shop/goods.vue:372", "之前的数据在这里", userInfo);
  53382. },
  53383. onShow() {
  53384. },
  53385. methods: {
  53386. // 获得key
  53387. getKey() {
  53388. liveOrderKey().then(
  53389. (res) => {
  53390. if (res.code == 200) {
  53391. formatAppLog("log", "at pages_shop/goods.vue:383", "下订单的key>>>>", res);
  53392. this.orderKey = res.orderKey;
  53393. formatAppLog("log", "at pages_shop/goods.vue:385", "key>>>>", this.orderKey);
  53394. uni.navigateTo({
  53395. url: "/pages_shop/confirmCreateOrder?orderKey=" + this.orderKey + "&liveId=" + this.liveId + "&productId=" + this.productId + "&totalNum=" + this.totalNum + "&price=" + this.goosDetail.price
  53396. });
  53397. } else {
  53398. uni.showToast({
  53399. title: res.msg,
  53400. icon: "none"
  53401. });
  53402. }
  53403. },
  53404. (rej) => {
  53405. }
  53406. );
  53407. },
  53408. // 点击取消/支付订单
  53409. operateOrder(type) {
  53410. let orderId = this.liveOrderList;
  53411. formatAppLog("log", "at pages_shop/goods.vue:406", "orderId>>", orderId);
  53412. },
  53413. // 选择商品数量
  53414. goodsNumChange(e2) {
  53415. formatAppLog("log", "at pages_shop/goods.vue:423", "当前选择商品数量为: " + e2.value);
  53416. this.totalNum = e2.value;
  53417. },
  53418. // 提交
  53419. submit() {
  53420. this.specVisible = false;
  53421. this.getKey();
  53422. },
  53423. // 加入购物车
  53424. addCart(type) {
  53425. this.type = type;
  53426. this.specVisible = true;
  53427. },
  53428. // addCart(type) {
  53429. // this.utils.isLogin().then(res => {
  53430. // if(res){
  53431. // this.type=type;
  53432. // this.specVisible = true
  53433. // }
  53434. // });
  53435. // },
  53436. openEditMoney() {
  53437. this.editShow = true;
  53438. },
  53439. //商品详情
  53440. getliveGoods() {
  53441. liveGoodsDetail(this.productId).then(
  53442. (res) => {
  53443. if (res.code == 200) {
  53444. formatAppLog("log", "at pages_shop/goods.vue:459", "小黄车 商品详情>>>>", res);
  53445. this.goosDetail = res.data;
  53446. } else {
  53447. uni.showToast({
  53448. title: res.msg,
  53449. icon: "none"
  53450. });
  53451. }
  53452. },
  53453. (rej) => {
  53454. formatAppLog("log", "at pages_shop/goods.vue:470", "qxj rej:" + JSON.stringify(rej));
  53455. }
  53456. );
  53457. }
  53458. }
  53459. };
  53460. function _sfc_render$b(_ctx, _cache, $props, $setup, $data, $options) {
  53461. const _component_uni_badge = vue.resolveComponent("uni-badge");
  53462. const _component_u_icon = resolveEasycom(vue.resolveDynamicComponent("u-icon"), __easycom_0$4);
  53463. const _component_u_popup = resolveEasycom(vue.resolveDynamicComponent("u-popup"), __easycom_1$4);
  53464. const _component_u_number_box = resolveEasycom(vue.resolveDynamicComponent("u-number-box"), __easycom_2);
  53465. const _component_popupBottom = vue.resolveComponent("popupBottom");
  53466. return vue.openBlock(), vue.createElementBlock("view", { class: "" }, [
  53467. vue.createElementVNode("view", { class: "content" }, [
  53468. vue.createCommentVNode(' <view class="share-box centerV ">\r\n <image class="w48 h48 " src="" mode=""></image>\r\n <text class="color-text mt8 weight-500 fs20">微信分享</text>\r\n </view> '),
  53469. vue.createCommentVNode(" 商品轮播图片 "),
  53470. vue.createCommentVNode(' <view class="shop-banner" @click="showImg()">\r\n 商品轮播图\r\n <swiper class="swiper" :indicator-dots="false" :circular="true" :autoplay="true" :interval="3000"\r\n :duration="1000" indicator-color="rgba(255, 255, 255, 0.6)" indicator-active-color="#ffffff" @change="">\r\n <swiper-item class="swiper-item" v-for="(item,index) in banner" :key="index">\r\n <image :src="item" mode="aspectFill"></image>\r\n <view class="cf-box" v-if="product.productType==2">\r\n <view class="title">处方药</view>\r\n <view class="subTitle">请在医师指导下使用</view>\r\n </view>\r\n </swiper-item>\r\n </swiper>\r\n \r\n 底部遮罩\r\n <view class="banner-mask"></view>\r\n 数量\r\n <view class="num-box"><text class="weight-500">{{ activeBanner }}</text>/{{ banner.length }}</view>\r\n </view> '),
  53471. vue.createElementVNode("view", { class: "shop-banner" }, [
  53472. vue.createElementVNode("view", { class: "swiper" }, [
  53473. vue.createElementVNode("view", { class: "swiper-item" }, [
  53474. vue.createElementVNode("image", {
  53475. src: $data.goosDetail.imgUrl,
  53476. mode: "aspectFill"
  53477. }, null, 8, ["src"]),
  53478. $data.product.productType == 2 ? (vue.openBlock(), vue.createElementBlock("view", {
  53479. key: 0,
  53480. class: "cf-box"
  53481. }, [
  53482. vue.createElementVNode("view", { class: "title" }, "处方药"),
  53483. vue.createElementVNode("view", { class: "subTitle" }, "请在医师指导下使用")
  53484. ])) : vue.createCommentVNode("v-if", true)
  53485. ])
  53486. ])
  53487. ]),
  53488. vue.createCommentVNode(" 详细信息 "),
  53489. vue.createElementVNode("view", { class: "det-info" }, [
  53490. vue.createElementVNode("view", { class: "price-box" }, [
  53491. vue.createElementVNode("view", { class: "price" }, [
  53492. vue.createElementVNode("text", { class: "label" }, "会员价"),
  53493. vue.createElementVNode("text", { class: "unit" }, "¥"),
  53494. vue.createElementVNode(
  53495. "text",
  53496. { class: "num" },
  53497. vue.toDisplayString($data.goosDetail.price),
  53498. 1
  53499. /* TEXT */
  53500. ),
  53501. vue.createElementVNode("text", { class: "fs24 color-text2" }, "零售价"),
  53502. vue.createElementVNode(
  53503. "text",
  53504. { class: "old" },
  53505. "¥" + vue.toDisplayString($data.goosDetail.otPrice),
  53506. 1
  53507. /* TEXT */
  53508. )
  53509. ]),
  53510. vue.createElementVNode(
  53511. "text",
  53512. { class: "fs24 color-text2" },
  53513. "月售" + vue.toDisplayString($data.goosDetail.sales) + "件",
  53514. 1
  53515. /* TEXT */
  53516. )
  53517. ]),
  53518. vue.createCommentVNode(' <view class="name-box">\r\n <view class="tag"></view>\r\n {{product.productName}}\r\n </view> '),
  53519. vue.createCommentVNode(` <view class="intro" v-if="product.productInfo!=null" v-html="product.productInfo.replace(/\\n/g,'<br>')"> `)
  53520. ])
  53521. ]),
  53522. vue.createElementVNode("view", { class: "guige" }, [
  53523. vue.createElementVNode("view", { class: "guige-gg" }, [
  53524. vue.createElementVNode("text", { class: "gg-text" }, "规格"),
  53525. vue.createElementVNode("text", { class: "gg-text2" }, "云南白药气雾剂 85g+30g *1 、说明书*1")
  53526. ]),
  53527. vue.createElementVNode("view", { class: "safe-box" }, [
  53528. vue.createElementVNode("text", { class: "text" }, "服务"),
  53529. vue.createElementVNode("view", { class: "box" }, [
  53530. (vue.openBlock(true), vue.createElementBlock(
  53531. vue.Fragment,
  53532. null,
  53533. vue.renderList($data.serviceList, (item, index2) => {
  53534. return vue.openBlock(), vue.createElementBlock("view", { key: index2 }, [
  53535. vue.createElementVNode("image", {
  53536. src: _imports_0$5,
  53537. mode: ""
  53538. }),
  53539. vue.createElementVNode(
  53540. "text",
  53541. null,
  53542. vue.toDisplayString(item),
  53543. 1
  53544. /* TEXT */
  53545. )
  53546. ]);
  53547. }),
  53548. 128
  53549. /* KEYED_FRAGMENT */
  53550. )),
  53551. vue.createElementVNode("view", {
  53552. onClick: _cache[0] || (_cache[0] = ($event) => $options.openEditMoney())
  53553. }, [
  53554. vue.createElementVNode("image", {
  53555. class: "w48 h48",
  53556. src: _imports_1$3
  53557. })
  53558. ])
  53559. ])
  53560. ]),
  53561. vue.createCommentVNode(" 点击服务,出现弹窗"),
  53562. $data.editShow ? (vue.openBlock(), vue.createElementBlock("view", {
  53563. key: 0,
  53564. class: "popup-box"
  53565. }, [
  53566. vue.createElementVNode("view", {
  53567. class: "info-mask",
  53568. onClick: _cache[1] || (_cache[1] = ($event) => _ctx.cancelEditMoney())
  53569. }),
  53570. vue.createElementVNode("view", { class: "info-form" }, [
  53571. vue.createElementVNode("view", { class: "top" }, [
  53572. vue.createElementVNode("view", { class: "title" }, "服务"),
  53573. vue.createElementVNode("view", {
  53574. class: "close",
  53575. onClick: _cache[2] || (_cache[2] = ($event) => _ctx.cancelEditMoney())
  53576. }, [
  53577. vue.createElementVNode("image", {
  53578. class: "w48 h48",
  53579. src: "",
  53580. mode: ""
  53581. })
  53582. ])
  53583. ]),
  53584. vue.createElementVNode("view", { class: "line" }),
  53585. vue.createElementVNode("view", { class: "form-box" }, [
  53586. vue.createElementVNode("view", { class: "form-item2" }, [
  53587. vue.createElementVNode("view", { class: "form-item-box" }, [
  53588. vue.createElementVNode("image", {
  53589. class: "w28 h28",
  53590. src: "",
  53591. mode: ""
  53592. }),
  53593. vue.createElementVNode("text", null, "免邮发货")
  53594. ]),
  53595. vue.createElementVNode("view", { class: "form-content" }, " 订单支付成功后48小时内发货,若未在48小时内发货,平台审核后消费者将会收到至少3元无门槛红包(特殊商品及不可抗力因素除外) ")
  53596. ]),
  53597. vue.createElementVNode("view", { class: "form-item2" }, [
  53598. vue.createElementVNode("view", { class: "form-item-box" }, [
  53599. vue.createElementVNode("image", {
  53600. class: "w28 h28",
  53601. src: "",
  53602. mode: ""
  53603. }),
  53604. vue.createElementVNode("text", null, "药师服务")
  53605. ]),
  53606. vue.createElementVNode("view", { class: "form-content" }, " 用药关怀认证药师,24小时专业用药咨询 ")
  53607. ]),
  53608. vue.createElementVNode("view", { class: "form-item2" }, [
  53609. vue.createElementVNode("view", { class: "form-item-box" }, [
  53610. vue.createElementVNode("image", {
  53611. class: "w28 h28",
  53612. src: "",
  53613. mode: ""
  53614. }),
  53615. vue.createElementVNode("text", null, "隐私保护")
  53616. ]),
  53617. vue.createElementVNode("view", { class: "form-content" }, " 除患者本人或其授权的代理人外,其他人员未经允许不得随意查阅患者的医疗记录 ")
  53618. ])
  53619. ]),
  53620. vue.createElementVNode("view", { class: "btns" }, [
  53621. vue.createElementVNode("view", {
  53622. class: "sub-btn",
  53623. onClick: _cache[3] || (_cache[3] = ($event) => _ctx.cancelEditMoney())
  53624. }, "确定")
  53625. ])
  53626. ])
  53627. ])) : vue.createCommentVNode("v-if", true)
  53628. ]),
  53629. vue.createCommentVNode(" 购买人数、库存 "),
  53630. vue.createElementVNode("view", { class: "shop-box" }, [
  53631. vue.createElementVNode("view", {
  53632. class: "",
  53633. style: { "flex": "1", "overflow": "hidden", "display": "flex", "justify-content": "space-between", "align-items": "center" }
  53634. }, [
  53635. vue.createCommentVNode(" 店铺图片logo "),
  53636. vue.createCommentVNode(' <view class="logo">\r\n <image src="" mode="aspectFill"></image>\r\n </view> '),
  53637. vue.createElementVNode("view", { class: "txtBox" }, [
  53638. vue.createElementVNode("view", { class: "name" }, "南泉达路店"),
  53639. vue.createElementVNode(
  53640. "view",
  53641. { class: "desc" },
  53642. "24小时营业 · 月售" + vue.toDisplayString() + " · 支持预订",
  53643. 1
  53644. /* TEXT */
  53645. )
  53646. ])
  53647. ]),
  53648. vue.createCommentVNode(` <button class="goShop"\r
  53649. @click="navgetTo('/pages_shop/store?storeId='+productValueSelect.storeId)">进店</button> `)
  53650. ]),
  53651. vue.createCommentVNode(" 图文详情 "),
  53652. vue.createElementVNode("view", { class: "det-box" }, [
  53653. vue.createElementVNode("view", { class: "title" }, "药品详情"),
  53654. vue.createElementVNode("view", { class: "det-title" }, [
  53655. vue.createElementVNode("view", { class: "tt" }, "说明书"),
  53656. vue.createElementVNode("view", { class: "det-right" }, [
  53657. vue.createElementVNode("text", null, "查看详情"),
  53658. vue.createElementVNode("image", {
  53659. class: "w48 h48",
  53660. src: ""
  53661. })
  53662. ])
  53663. ]),
  53664. vue.createElementVNode("view", { class: "det-table" }, [
  53665. vue.createElementVNode("view", { class: "row" }, [
  53666. vue.createElementVNode("text", { class: "cell cell-1" }, "通用名称"),
  53667. vue.createElementVNode("text", { class: "cell cell-2" }, "云南白药气雾剂")
  53668. ]),
  53669. vue.createElementVNode("view", { class: "row" }, [
  53670. vue.createElementVNode("text", { class: "cell cell-1" }, "成份"),
  53671. vue.createElementVNode("text", { class: "cell cell-2" }, "国家保密方,本品含草乌(制)、雪上一枝蒿(制),其余成份略。")
  53672. ]),
  53673. vue.createElementVNode("view", { class: "row" }, [
  53674. vue.createElementVNode("text", { class: "cell cell-1" }, "性状"),
  53675. vue.createElementVNode("text", { class: "cell cell-2" }, "云南白药气雾剂为非定量阀门气雾剂,在耐压容器中的药液为淡黄...")
  53676. ])
  53677. ]),
  53678. vue.createElementVNode("view", { class: "inner" }, [
  53679. vue.createElementVNode("view", {
  53680. innerHTML: $data.product.description,
  53681. style: { "font-size": "0" }
  53682. }, null, 8, ["innerHTML"])
  53683. ])
  53684. ]),
  53685. vue.createCommentVNode(" 底部按钮 "),
  53686. vue.createElementVNode("view", { class: "btn-foot" }, [
  53687. vue.createElementVNode("view", { class: "menu-box" }, [
  53688. vue.createElementVNode("view", { class: "item" }, [
  53689. vue.createElementVNode("image", {
  53690. src: _imports_2$1,
  53691. mode: ""
  53692. }),
  53693. vue.createElementVNode("text", { class: "label" }, "首页")
  53694. ]),
  53695. vue.createElementVNode("view", {
  53696. class: "item",
  53697. style: { "position": "relative" }
  53698. }, [
  53699. vue.createElementVNode("image", {
  53700. src: _imports_3$1,
  53701. mode: ""
  53702. }),
  53703. vue.createElementVNode("text", { class: "label" }, "咨询"),
  53704. vue.createElementVNode("button", {
  53705. class: "contact-btn",
  53706. "open-type": "contact"
  53707. })
  53708. ]),
  53709. vue.createElementVNode("view", {
  53710. class: "item",
  53711. onClick: _cache[4] || (_cache[4] = ($event) => _ctx.navgetTo("./cart"))
  53712. }, [
  53713. vue.createVNode(_component_uni_badge, {
  53714. size: "small",
  53715. text: $data.cartCount,
  53716. absolute: "rightTop",
  53717. type: "error"
  53718. }, {
  53719. default: vue.withCtx(() => [
  53720. vue.createElementVNode("image", {
  53721. src: _imports_4,
  53722. mode: ""
  53723. })
  53724. ]),
  53725. _: 1
  53726. /* STABLE */
  53727. }, 8, ["text"]),
  53728. vue.createElementVNode("text", { class: "label" }, "购物车")
  53729. ])
  53730. ]),
  53731. vue.createElementVNode("view", { class: "btn-box" }, [
  53732. vue.createElementVNode("view", {
  53733. class: "btn cart",
  53734. onClick: _cache[5] || (_cache[5] = ($event) => $options.addCart("cart"))
  53735. }, "加入购物车"),
  53736. vue.createElementVNode(
  53737. "view",
  53738. {
  53739. class: "btn buy",
  53740. onClick: _cache[6] || (_cache[6] = ($event) => $options.addCart("buy"))
  53741. },
  53742. vue.toDisplayString($data.buyText),
  53743. 1
  53744. /* TEXT */
  53745. )
  53746. ])
  53747. ]),
  53748. vue.createCommentVNode(" 选择药品规格弹窗 "),
  53749. vue.createVNode(_component_popupBottom, {
  53750. ref: "popup",
  53751. visible: $data.specVisible,
  53752. title: " ",
  53753. radius: "32",
  53754. maxHeight: "800"
  53755. }, {
  53756. default: vue.withCtx(() => {
  53757. var _a;
  53758. return [
  53759. vue.createElementVNode("view", { class: "product-spec" }, [
  53760. vue.createElementVNode("view", { class: "pro-info" }, [
  53761. vue.createElementVNode("view", { class: "img-box" }, [
  53762. vue.createElementVNode("image", {
  53763. src: ((_a = $data.goosDetail) == null ? void 0 : _a.imgUrl) || _ctx.$img.img,
  53764. mode: "aspectFill"
  53765. }, null, 8, ["src"])
  53766. ]),
  53767. vue.createElementVNode("view", { class: "info-text" }, [
  53768. vue.createElementVNode(
  53769. "view",
  53770. { class: "info-title" },
  53771. vue.toDisplayString($data.goosDetail.productName),
  53772. 1
  53773. /* TEXT */
  53774. ),
  53775. vue.createElementVNode("view", { class: "price" }, [
  53776. vue.createElementVNode("view", { class: "label" }, "会员价"),
  53777. vue.createElementVNode("text", { class: "unit" }, "¥"),
  53778. vue.createElementVNode(
  53779. "text",
  53780. { class: "num" },
  53781. vue.toDisplayString($data.goosDetail.price ? $data.goosDetail.price.toFixed(2) : "0.00"),
  53782. 1
  53783. /* TEXT */
  53784. )
  53785. ]),
  53786. vue.createElementVNode("view", { class: "desc-box" }, [
  53787. vue.createElementVNode(
  53788. "text",
  53789. { class: "text" },
  53790. "月售" + vue.toDisplayString($data.goosDetail.sales) + "件",
  53791. 1
  53792. /* TEXT */
  53793. )
  53794. ])
  53795. ])
  53796. ]),
  53797. vue.createCommentVNode(" 选择健康管理师 "),
  53798. vue.createCommentVNode(` <view class="tech-pBox" style="margin-top: 20rpx;">\r
  53799. <view class="label">选择健康管理师</view>\r
  53800. <view v-for="(item,index) in storePriceList.slice(0,2)" :key="index"\r
  53801. :class="productValueSelect.storeId == item.storeId ? 'item hover':'item'"\r
  53802. @click="storeChange(item,index)">\r
  53803. \r
  53804. <image mode="aspectFill"\r
  53805. :src="productValueSelect.image==null||productValueSelect.image==''?product.image:productValueSelect.image">\r
  53806. </image>\r
  53807. <view class="tech-right">\r
  53808. <view class="tech-right-top">\r
  53809. <text class="title-1">秦宇</text>\r
  53810. <text class="title-2">健康管理师/执业药师</text>\r
  53811. </view>\r
  53812. <view class="tech-right-bottom">{{item.storeName}}</view>\r
  53813. </view>\r
  53814. </view>\r
  53815. </view> `),
  53816. vue.createVNode(_component_u_popup, {
  53817. show: $data.showStorePicker,
  53818. round: 16,
  53819. mode: "bottom"
  53820. }, {
  53821. default: vue.withCtx(() => [
  53822. vue.createElementVNode("view", { class: "storepopup" }, [
  53823. vue.createElementVNode("view", { class: "storepopup-title" }, [
  53824. vue.createTextVNode(" 选择店铺 "),
  53825. vue.createElementVNode("image", {
  53826. class: "close-icon",
  53827. src: "",
  53828. mode: "widthFix"
  53829. })
  53830. ]),
  53831. vue.createElementVNode("scroll-view", {
  53832. class: "shop-pBox storepopup-box",
  53833. "scroll-y": "true"
  53834. }, [
  53835. (vue.openBlock(true), vue.createElementBlock(
  53836. vue.Fragment,
  53837. null,
  53838. vue.renderList($data.storePriceList, (item, index2) => {
  53839. return vue.openBlock(), vue.createElementBlock("view", {
  53840. key: index2,
  53841. class: vue.normalizeClass($data.productValueSelect.storeId == item.storeId ? "item hover" : "item"),
  53842. onClick: ($event) => _ctx.pickerStore(item, index2)
  53843. }, [
  53844. vue.createElementVNode("view", { class: "top x-bc" }, [
  53845. vue.createElementVNode("view", { class: "price" }, [
  53846. vue.createElementVNode("text", { class: "strong" }, "¥"),
  53847. vue.createTextVNode(
  53848. vue.toDisplayString(item.price.toFixed(2)),
  53849. 1
  53850. /* TEXT */
  53851. )
  53852. ]),
  53853. vue.createElementVNode(
  53854. "view",
  53855. { class: "num" },
  53856. "销售" + vue.toDisplayString(_ctx.utils.formatSalesNum(item.sales)),
  53857. 1
  53858. /* TEXT */
  53859. )
  53860. ]),
  53861. vue.createElementVNode("view", { class: "bot x-bc shop-pBox-name" }, [
  53862. vue.createElementVNode(
  53863. "view",
  53864. { class: "name" },
  53865. vue.toDisplayString(item.storeName),
  53866. 1
  53867. /* TEXT */
  53868. ),
  53869. vue.createVNode(_component_u_icon, {
  53870. name: "arrow-right",
  53871. color: "#000",
  53872. size: "14"
  53873. })
  53874. ])
  53875. ], 10, ["onClick"]);
  53876. }),
  53877. 128
  53878. /* KEYED_FRAGMENT */
  53879. ))
  53880. ])
  53881. ])
  53882. ]),
  53883. _: 1
  53884. /* STABLE */
  53885. }, 8, ["show"]),
  53886. vue.createCommentVNode(` <view class="spec-box">\r
  53887. <view v-for="(item,index) in attrs">\r
  53888. <view class="title">{{item.attrName}}</view>\r
  53889. <view class="spec-list">\r
  53890. <view v-for="(subItem,subindex) in item.values" :key="subindex"\r
  53891. :class="subindex==item.index?'item active':'item'">\r
  53892. {{ subItem }}\r
  53893. </view>\r
  53894. </view>\r
  53895. </view>\r
  53896. </view> `),
  53897. vue.createElementVNode("view", { class: "price-num" }, [
  53898. vue.createElementVNode("view", { class: "label" }, "数量"),
  53899. vue.createVNode(_component_u_number_box, {
  53900. bgColor: "#ececec",
  53901. modelValue: $data.goodsNum,
  53902. "onUpdate:modelValue": _cache[7] || (_cache[7] = ($event) => $data.goodsNum = $event),
  53903. onChange: $options.goodsNumChange
  53904. }, null, 8, ["modelValue", "onChange"])
  53905. ]),
  53906. vue.createElementVNode("view", {
  53907. class: "sub-btn",
  53908. onClick: _cache[8] || (_cache[8] = (...args) => $options.submit && $options.submit(...args))
  53909. }, "确定")
  53910. ])
  53911. ];
  53912. }),
  53913. _: 1
  53914. /* STABLE */
  53915. }, 8, ["visible"]),
  53916. vue.createCommentVNode(' <view class="loadding" v-if="loadding==true">\r\n <image src=""></image>\r\n <text class="text">加载中...</text>\r\n </view> '),
  53917. vue.createCommentVNode(' <u-modal :show="showModal" title="温馨提示" content="处方药须凭处方在药师指导下购买和使用" @confirm="hideModal()"></u-modal> '),
  53918. vue.createCommentVNode(' <view>\r\n <view @click="operateOrder(0)" style="background-color: aqua; padding: 100rpx;">取消</view>\r\n <view @click="operateOrder(1)" style="background-color: #ff0004;padding: 150rpx;">确认</view>\r\n </view> ')
  53919. ]);
  53920. }
  53921. const PagesShopGoods = /* @__PURE__ */ _export_sfc(_sfc_main$c, [["render", _sfc_render$b], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages_shop/goods.vue"]]);
  53922. const props$1 = {
  53923. props: {
  53924. // 图片地址
  53925. src: {
  53926. type: String,
  53927. default: () => props$f.image.src
  53928. },
  53929. // 裁剪模式
  53930. mode: {
  53931. type: String,
  53932. default: () => props$f.image.mode
  53933. },
  53934. // 宽度,单位任意
  53935. width: {
  53936. type: [String, Number],
  53937. default: () => props$f.image.width
  53938. },
  53939. // 高度,单位任意
  53940. height: {
  53941. type: [String, Number],
  53942. default: () => props$f.image.height
  53943. },
  53944. // 图片形状,circle-圆形,square-方形
  53945. shape: {
  53946. type: String,
  53947. default: () => props$f.image.shape
  53948. },
  53949. // 圆角,单位任意
  53950. radius: {
  53951. type: [String, Number],
  53952. default: () => props$f.image.radius
  53953. },
  53954. // 是否懒加载,微信小程序、App、百度小程序、字节跳动小程序
  53955. lazyLoad: {
  53956. type: Boolean,
  53957. default: () => props$f.image.lazyLoad
  53958. },
  53959. // 开启长按图片显示识别微信小程序码菜单
  53960. showMenuByLongpress: {
  53961. type: Boolean,
  53962. default: () => props$f.image.showMenuByLongpress
  53963. },
  53964. // 加载中的图标,或者小图片
  53965. loadingIcon: {
  53966. type: String,
  53967. default: () => props$f.image.loadingIcon
  53968. },
  53969. // 加载失败的图标,或者小图片
  53970. errorIcon: {
  53971. type: String,
  53972. default: () => props$f.image.errorIcon
  53973. },
  53974. // 是否显示加载中的图标或者自定义的slot
  53975. showLoading: {
  53976. type: Boolean,
  53977. default: () => props$f.image.showLoading
  53978. },
  53979. // 是否显示加载错误的图标或者自定义的slot
  53980. showError: {
  53981. type: Boolean,
  53982. default: () => props$f.image.showError
  53983. },
  53984. // 是否需要淡入效果
  53985. fade: {
  53986. type: Boolean,
  53987. default: () => props$f.image.fade
  53988. },
  53989. // 只支持网络资源,只对微信小程序有效
  53990. webp: {
  53991. type: Boolean,
  53992. default: () => props$f.image.webp
  53993. },
  53994. // 过渡时间,单位ms
  53995. duration: {
  53996. type: [String, Number],
  53997. default: () => props$f.image.duration
  53998. },
  53999. // 背景颜色,用于深色页面加载图片时,为了和背景色融合
  54000. bgColor: {
  54001. type: String,
  54002. default: () => props$f.image.bgColor
  54003. }
  54004. }
  54005. };
  54006. const _sfc_main$b = {
  54007. name: "u-image",
  54008. mixins: [mpMixin, mixin$1, props$1],
  54009. data() {
  54010. return {
  54011. // 图片是否加载错误,如果是,则显示错误占位图
  54012. isError: false,
  54013. // 初始化组件时,默认为加载中状态
  54014. loading: true,
  54015. // 不透明度,为了实现淡入淡出的效果
  54016. opacity: 1,
  54017. // 过渡时间,因为props的值无法修改,故需要一个中间值
  54018. durationTime: this.duration,
  54019. // 图片加载完成时,去掉背景颜色,因为如果是png图片,就会显示灰色的背景
  54020. backgroundStyle: {},
  54021. // 用于fade模式的控制组件显示与否
  54022. show: false
  54023. };
  54024. },
  54025. watch: {
  54026. src: {
  54027. immediate: true,
  54028. handler(n2) {
  54029. if (!n2) {
  54030. this.isError = true;
  54031. } else {
  54032. this.isError = false;
  54033. this.loading = true;
  54034. }
  54035. }
  54036. }
  54037. },
  54038. computed: {
  54039. wrapStyle() {
  54040. let style = {};
  54041. style.width = addUnit(this.width);
  54042. style.height = addUnit(this.height);
  54043. style.borderRadius = this.shape == "circle" ? "10000px" : addUnit(this.radius);
  54044. style.overflow = this.radius > 0 ? "hidden" : "visible";
  54045. return deepMerge$1(style, addStyle(this.customStyle));
  54046. }
  54047. },
  54048. mounted() {
  54049. this.show = true;
  54050. },
  54051. emits: ["click", "error", "load"],
  54052. methods: {
  54053. addUnit,
  54054. // 点击图片
  54055. onClick() {
  54056. this.$emit("click");
  54057. },
  54058. // 图片加载失败
  54059. onErrorHandler(err) {
  54060. this.loading = false;
  54061. this.isError = true;
  54062. this.$emit("error", err);
  54063. },
  54064. // 图片加载完成,标记loading结束
  54065. onLoadHandler(event) {
  54066. this.loading = false;
  54067. this.isError = false;
  54068. this.$emit("load", event);
  54069. this.removeBgColor();
  54070. },
  54071. // 移除图片的背景色
  54072. removeBgColor() {
  54073. this.backgroundStyle = {
  54074. backgroundColor: "transparent"
  54075. };
  54076. }
  54077. }
  54078. };
  54079. function _sfc_render$a(_ctx, _cache, $props, $setup, $data, $options) {
  54080. const _component_u_icon = resolveEasycom(vue.resolveDynamicComponent("u-icon"), __easycom_0$4);
  54081. const _component_u_transition = resolveEasycom(vue.resolveDynamicComponent("u-transition"), __easycom_1$6);
  54082. return vue.openBlock(), vue.createBlock(_component_u_transition, {
  54083. mode: "fade",
  54084. show: $data.show,
  54085. duration: _ctx.fade ? 1e3 : 0
  54086. }, {
  54087. default: vue.withCtx(() => [
  54088. vue.createElementVNode(
  54089. "view",
  54090. {
  54091. class: "u-image",
  54092. onClick: _cache[2] || (_cache[2] = (...args) => $options.onClick && $options.onClick(...args)),
  54093. style: vue.normalizeStyle([$options.wrapStyle, $data.backgroundStyle])
  54094. },
  54095. [
  54096. !$data.isError ? (vue.openBlock(), vue.createElementBlock("image", {
  54097. key: 0,
  54098. src: _ctx.src,
  54099. mode: _ctx.mode,
  54100. onError: _cache[0] || (_cache[0] = (...args) => $options.onErrorHandler && $options.onErrorHandler(...args)),
  54101. onLoad: _cache[1] || (_cache[1] = (...args) => $options.onLoadHandler && $options.onLoadHandler(...args)),
  54102. "show-menu-by-longpress": _ctx.showMenuByLongpress,
  54103. "lazy-load": _ctx.lazyLoad,
  54104. class: "u-image__image",
  54105. style: vue.normalizeStyle({
  54106. borderRadius: _ctx.shape == "circle" ? "10000px" : $options.addUnit(_ctx.radius),
  54107. width: $options.addUnit(_ctx.width),
  54108. height: $options.addUnit(_ctx.height)
  54109. })
  54110. }, null, 44, ["src", "mode", "show-menu-by-longpress", "lazy-load"])) : vue.createCommentVNode("v-if", true),
  54111. _ctx.showLoading && $data.loading ? (vue.openBlock(), vue.createElementBlock(
  54112. "view",
  54113. {
  54114. key: 1,
  54115. class: "u-image__loading",
  54116. style: vue.normalizeStyle({
  54117. borderRadius: _ctx.shape == "circle" ? "50%" : $options.addUnit(_ctx.radius),
  54118. backgroundColor: this.bgColor,
  54119. width: $options.addUnit(_ctx.width),
  54120. height: $options.addUnit(_ctx.height)
  54121. })
  54122. },
  54123. [
  54124. vue.renderSlot(_ctx.$slots, "loading", {}, () => [
  54125. vue.createVNode(_component_u_icon, {
  54126. name: _ctx.loadingIcon,
  54127. width: _ctx.width,
  54128. height: _ctx.height
  54129. }, null, 8, ["name", "width", "height"])
  54130. ], true)
  54131. ],
  54132. 4
  54133. /* STYLE */
  54134. )) : vue.createCommentVNode("v-if", true),
  54135. _ctx.showError && $data.isError && !$data.loading ? (vue.openBlock(), vue.createElementBlock(
  54136. "view",
  54137. {
  54138. key: 2,
  54139. class: "u-image__error",
  54140. style: vue.normalizeStyle({
  54141. borderRadius: _ctx.shape == "circle" ? "50%" : $options.addUnit(_ctx.radius),
  54142. width: $options.addUnit(_ctx.width),
  54143. height: $options.addUnit(_ctx.height)
  54144. })
  54145. },
  54146. [
  54147. vue.renderSlot(_ctx.$slots, "error", {}, () => [
  54148. vue.createVNode(_component_u_icon, {
  54149. name: _ctx.errorIcon,
  54150. width: _ctx.width,
  54151. height: _ctx.height
  54152. }, null, 8, ["name", "width", "height"])
  54153. ], true)
  54154. ],
  54155. 4
  54156. /* STYLE */
  54157. )) : vue.createCommentVNode("v-if", true)
  54158. ],
  54159. 4
  54160. /* STYLE */
  54161. )
  54162. ]),
  54163. _: 3
  54164. /* FORWARDED */
  54165. }, 8, ["show", "duration"]);
  54166. }
  54167. const __easycom_1 = /* @__PURE__ */ _export_sfc(_sfc_main$b, [["render", _sfc_render$a], ["__scopeId", "data-v-abebd402"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-image/u-image.vue"]]);
  54168. const props = {
  54169. props: {
  54170. // 吸顶容器到顶部某个距离的时候,进行吸顶,在H5平台,NavigationBar为44px
  54171. offsetTop: {
  54172. type: [String, Number],
  54173. default: () => props$f.sticky.offsetTop
  54174. },
  54175. // 自定义导航栏的高度
  54176. customNavHeight: {
  54177. type: [String, Number],
  54178. default: () => props$f.sticky.customNavHeight
  54179. },
  54180. // 是否开启吸顶功能
  54181. disabled: {
  54182. type: Boolean,
  54183. default: () => props$f.sticky.disabled
  54184. },
  54185. // 吸顶区域的背景颜色
  54186. bgColor: {
  54187. type: String,
  54188. default: () => props$f.sticky.bgColor
  54189. },
  54190. // z-index值
  54191. zIndex: {
  54192. type: [String, Number],
  54193. default: () => props$f.sticky.zIndex
  54194. },
  54195. // 列表中的索引值
  54196. index: {
  54197. type: [String, Number],
  54198. default: () => props$f.sticky.index
  54199. }
  54200. }
  54201. };
  54202. const zIndex = {
  54203. toast: 10090,
  54204. noNetwork: 10080,
  54205. // popup包含popup,actionsheet,keyboard,picker的值
  54206. popup: 10075,
  54207. mask: 10070,
  54208. navbar: 980,
  54209. topTips: 975,
  54210. sticky: 970,
  54211. indexListSticky: 965
  54212. };
  54213. const _sfc_main$a = {
  54214. name: "u-sticky",
  54215. mixins: [mpMixin, mixin$1, props],
  54216. data() {
  54217. return {
  54218. cssSticky: false,
  54219. // 是否使用css的sticky实现
  54220. stickyTop: 0,
  54221. // 吸顶的top值,因为可能受自定义导航栏影响,最终的吸顶值非offsetTop值
  54222. elId: guid(),
  54223. left: 0,
  54224. // js模式时,吸顶的内容因为处于postition: fixed模式,为了和原来保持一致的样式,需要记录并重新设置它的left,height,width属性
  54225. width: "auto",
  54226. height: "auto",
  54227. fixed: false
  54228. // js模式时,是否处于吸顶模式
  54229. };
  54230. },
  54231. computed: {
  54232. style() {
  54233. const style = {};
  54234. if (!this.disabled) {
  54235. if (this.cssSticky) {
  54236. style.position = "sticky";
  54237. style.zIndex = this.uZindex;
  54238. style.top = addUnit(this.stickyTop);
  54239. } else {
  54240. style.height = this.fixed ? this.height + "px" : "auto";
  54241. }
  54242. } else {
  54243. style.position = "static";
  54244. }
  54245. style.backgroundColor = this.bgColor;
  54246. return deepMerge$1(addStyle(this.customStyle), style);
  54247. },
  54248. // 吸顶内容的样式
  54249. stickyContent() {
  54250. const style = {};
  54251. if (!this.cssSticky) {
  54252. style.position = this.fixed ? "fixed" : "static";
  54253. style.top = this.stickyTop + "px";
  54254. style.left = this.left + "px";
  54255. style.width = this.width == "auto" ? "auto" : this.width + "px";
  54256. style.zIndex = this.uZindex;
  54257. }
  54258. return style;
  54259. },
  54260. uZindex() {
  54261. return this.zIndex ? this.zIndex : zIndex.sticky;
  54262. }
  54263. },
  54264. mounted() {
  54265. this.init();
  54266. },
  54267. methods: {
  54268. init() {
  54269. this.getStickyTop();
  54270. this.checkSupportCssSticky();
  54271. if (!this.cssSticky) {
  54272. !this.disabled && this.initObserveContent();
  54273. }
  54274. },
  54275. initObserveContent() {
  54276. this.$uGetRect("#" + this.elId).then((res) => {
  54277. this.height = res.height;
  54278. this.left = res.left;
  54279. this.width = res.width;
  54280. this.$nextTick(() => {
  54281. this.observeContent();
  54282. });
  54283. });
  54284. },
  54285. observeContent() {
  54286. this.disconnectObserver("contentObserver");
  54287. const contentObserver = uni.createIntersectionObserver({
  54288. // 检测的区间范围
  54289. thresholds: [0.95, 0.98, 1]
  54290. });
  54291. contentObserver.relativeToViewport({
  54292. top: -this.stickyTop
  54293. });
  54294. contentObserver.observe(`#${this.elId}`, (res) => {
  54295. this.setFixed(res.boundingClientRect.top);
  54296. });
  54297. this.contentObserver = contentObserver;
  54298. },
  54299. setFixed(top) {
  54300. const fixed = top <= this.stickyTop;
  54301. this.fixed = fixed;
  54302. },
  54303. disconnectObserver(observerName) {
  54304. const observer = this[observerName];
  54305. observer && observer.disconnect();
  54306. },
  54307. getStickyTop() {
  54308. this.stickyTop = getPx(this.offsetTop) + getPx(this.customNavHeight);
  54309. },
  54310. async checkSupportCssSticky() {
  54311. if (os$1() === "android" && Number(sys().system) > 8) {
  54312. this.cssSticky = true;
  54313. }
  54314. this.cssSticky = await this.checkComputedStyle();
  54315. if (os$1() === "ios") {
  54316. this.cssSticky = true;
  54317. }
  54318. },
  54319. // 在APP和微信小程序上,通过uni.createSelectorQuery可以判断是否支持css sticky
  54320. checkComputedStyle() {
  54321. return new Promise((resolve) => {
  54322. uni.createSelectorQuery().in(this).select(".u-sticky").fields({
  54323. computedStyle: ["position"]
  54324. }).exec((e2) => {
  54325. resolve("sticky" === e2[0].position);
  54326. });
  54327. });
  54328. },
  54329. // H5通过创建元素的形式嗅探是否支持css sticky
  54330. // 判断浏览器是否支持sticky属性
  54331. checkCssStickyForH5() {
  54332. }
  54333. },
  54334. beforeUnmount() {
  54335. this.disconnectObserver("contentObserver");
  54336. }
  54337. };
  54338. function _sfc_render$9(_ctx, _cache, $props, $setup, $data, $options) {
  54339. return vue.openBlock(), vue.createElementBlock("view", {
  54340. class: "u-sticky",
  54341. id: $data.elId,
  54342. style: vue.normalizeStyle([$options.style])
  54343. }, [
  54344. vue.createElementVNode(
  54345. "view",
  54346. {
  54347. style: vue.normalizeStyle([$options.stickyContent]),
  54348. class: "u-sticky__content"
  54349. },
  54350. [
  54351. vue.renderSlot(_ctx.$slots, "default", {}, void 0, true)
  54352. ],
  54353. 4
  54354. /* STYLE */
  54355. )
  54356. ], 12, ["id"]);
  54357. }
  54358. const __easycom_3 = /* @__PURE__ */ _export_sfc(_sfc_main$a, [["render", _sfc_render$9], ["__scopeId", "data-v-8b303089"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/uni_modules/uview-plus/components/u-sticky/u-sticky.vue"]]);
  54359. const _sfc_main$9 = {
  54360. data() {
  54361. return {
  54362. statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
  54363. // 右侧的胶囊距离右侧屏幕距离-px
  54364. menuRight: uni.getStorageSync("menuInfo").menuRight,
  54365. // 右侧的胶囊宽度-px
  54366. menuWidth: uni.getStorageSync("menuInfo").menuWidth,
  54367. opacity: 0,
  54368. opacityTxt: 0,
  54369. storeId: "",
  54370. tabbar: [{
  54371. name: "商品"
  54372. }, {
  54373. name: "商家"
  54374. }],
  54375. current: 0,
  54376. storeInfo: {},
  54377. logoUrl: "/static/images/adfd21c004854c9b8997d371d7a0ce8c.jpg",
  54378. // 商家资质图片
  54379. licenseImagesList: ["/static/images/sjzz.jpg"],
  54380. divHeight: "0px",
  54381. allCates: [],
  54382. cates: [],
  54383. subCates: [],
  54384. // 选中药品分类
  54385. cateSelect: 0,
  54386. // 轮播图
  54387. advs: [],
  54388. // 'company'表示销售管理的进来的
  54389. from: ""
  54390. };
  54391. },
  54392. onLoad(option) {
  54393. this.storeId = option.storeId || "";
  54394. this.from = option.from || "";
  54395. if (this.storeId) {
  54396. this.getStoreInfo();
  54397. this.getProductCate();
  54398. } else {
  54399. uni.showToast({
  54400. title: "storeId不存在~",
  54401. icon: "none"
  54402. });
  54403. }
  54404. },
  54405. onShow() {
  54406. this.divHeight = `calc(100vh - 44px - 88rpx - ${this.statusBarHeight}px)`;
  54407. this.getAdv();
  54408. },
  54409. onPageScroll(e2) {
  54410. if (e2.scrollTop <= 44) {
  54411. this.opacityTxt = 0;
  54412. this.opacity = e2.scrollTop > this.statusBarHeight ? 0.6 : 0;
  54413. } else if (e2.scrollTop > 50) {
  54414. this.opacity = 1;
  54415. this.opacityTxt = 1;
  54416. }
  54417. },
  54418. methods: {
  54419. rightClick() {
  54420. uni.navigateBack();
  54421. },
  54422. clickTab(item) {
  54423. this.current = item.index;
  54424. },
  54425. // 预览图片
  54426. previewImage(index2) {
  54427. uni.previewImage({
  54428. current: index2,
  54429. urls: this.licenseImagesList
  54430. });
  54431. },
  54432. getStoreInfo() {
  54433. getStoreById({ storeId: this.storeId }).then(
  54434. (res) => {
  54435. if (res.code == 200) {
  54436. this.storeInfo = res.data || {};
  54437. } else {
  54438. uni.showToast({
  54439. icon: "none",
  54440. title: res.msg
  54441. });
  54442. }
  54443. },
  54444. (rej) => {
  54445. }
  54446. );
  54447. },
  54448. toSearch() {
  54449. if (this.from == "company") {
  54450. uni.navigateTo({
  54451. url: "/pages_company/order/productList?storeId=" + this.storeId || ""
  54452. });
  54453. } else {
  54454. uni.navigateTo({
  54455. url: "/pages/home/productSearch?storeId=" + this.storeId || ""
  54456. });
  54457. }
  54458. },
  54459. handleAdvClick(item) {
  54460. if (item.showType == 1) {
  54461. uni.setStorageSync("url", item.advUrl);
  54462. uni.navigateTo({
  54463. url: "/pages/home/h5?storeId=" + this.storeId || ""
  54464. });
  54465. } else if (item.showType == 2) {
  54466. uni.navigateTo({
  54467. url: item.advUrl
  54468. });
  54469. } else if (item.showType == 3) {
  54470. uni.setStorageSync("content", item.content);
  54471. uni.navigateTo({
  54472. url: "/pages/home/content?storeId=" + this.storeId || ""
  54473. });
  54474. }
  54475. },
  54476. getAdv() {
  54477. let data = { advType: 2 };
  54478. getAdv(data).then(
  54479. (res) => {
  54480. if (res.code == 200) {
  54481. this.advs = res.data;
  54482. }
  54483. },
  54484. (rej) => {
  54485. }
  54486. );
  54487. },
  54488. getProductCate() {
  54489. let data = {};
  54490. getProductCate(data).then(
  54491. (res) => {
  54492. if (res.code == 200) {
  54493. this.allCates = res.data;
  54494. this.cates = this.allCates.filter(function(item) {
  54495. return item.pid == 0;
  54496. });
  54497. if (this.cates != null && this.cates.length > 0) {
  54498. this.cateSelect = this.cates[0].cateId;
  54499. this.getSubCate();
  54500. }
  54501. } else {
  54502. uni.showToast({
  54503. icon: "none",
  54504. title: "请求失败"
  54505. });
  54506. }
  54507. },
  54508. (rej) => {
  54509. }
  54510. );
  54511. },
  54512. // 药品分类选择
  54513. choseCate(item) {
  54514. this.cateSelect = item.cateId;
  54515. this.getSubCate();
  54516. },
  54517. getSubCate() {
  54518. var that = this;
  54519. this.subCates = this.allCates.filter(function(item) {
  54520. return item.pid == that.cateSelect;
  54521. });
  54522. },
  54523. // 查看药品详情
  54524. showProductList(item) {
  54525. uni.navigateTo({
  54526. url: "/pages/shopping/productList?cateId=" + item.cateId + "&pid=" + item.pid + "&storeId=" + this.storeId + "&from=" + this.from
  54527. });
  54528. }
  54529. }
  54530. };
  54531. function _sfc_render$8(_ctx, _cache, $props, $setup, $data, $options) {
  54532. const _component_u_icon = resolveEasycom(vue.resolveDynamicComponent("u-icon"), __easycom_0$4);
  54533. const _component_u_image = resolveEasycom(vue.resolveDynamicComponent("u-image"), __easycom_1);
  54534. const _component_u_tabs = resolveEasycom(vue.resolveDynamicComponent("u-tabs"), __easycom_0$1);
  54535. const _component_u_sticky = resolveEasycom(vue.resolveDynamicComponent("u-sticky"), __easycom_3);
  54536. return vue.withDirectives((vue.openBlock(), vue.createElementBlock(
  54537. "view",
  54538. { class: "content" },
  54539. [
  54540. vue.createElementVNode(
  54541. "view",
  54542. {
  54543. class: "uni-nav-bar",
  54544. style: vue.normalizeStyle({ backgroundColor: `rgba(255,255,255,${$data.opacity})` })
  54545. },
  54546. [
  54547. vue.createElementVNode(
  54548. "view",
  54549. {
  54550. style: vue.normalizeStyle({ height: $data.statusBarHeight + "px", width: "100%" })
  54551. },
  54552. null,
  54553. 4
  54554. /* STYLE */
  54555. ),
  54556. vue.createElementVNode("view", { class: "uni-nav-barbox" }, [
  54557. vue.createElementVNode("view", { class: "uni-nav-back" }, [
  54558. vue.createVNode(_component_u_icon, {
  54559. name: "arrow-left",
  54560. color: "#333",
  54561. size: "20",
  54562. onClick: $options.rightClick
  54563. }, null, 8, ["onClick"])
  54564. ]),
  54565. vue.createElementVNode(
  54566. "view",
  54567. {
  54568. class: "uni-nav-title",
  54569. style: vue.normalizeStyle({ opacity: 1, width: `calc(100vw - 100rpx - ${$data.menuRight} - ${$data.menuWidth})` })
  54570. },
  54571. [
  54572. vue.createCommentVNode(" {{storeInfo.storeName}} "),
  54573. vue.createElementVNode(
  54574. "view",
  54575. {
  54576. class: "inputbox",
  54577. style: vue.normalizeStyle({ background: $data.opacity >= 0.6 ? "#f7f7f7" : "#fff" }),
  54578. onClick: _cache[0] || (_cache[0] = (...args) => $options.toSearch && $options.toSearch(...args))
  54579. },
  54580. [
  54581. vue.createCommentVNode(' <image class="icon-search" src="../../static/images/search.png" mode=""></image> '),
  54582. vue.createElementVNode("view", null, "搜索店内药品")
  54583. ],
  54584. 4
  54585. /* STYLE */
  54586. )
  54587. ],
  54588. 4
  54589. /* STYLE */
  54590. )
  54591. ])
  54592. ],
  54593. 4
  54594. /* STYLE */
  54595. ),
  54596. vue.createCommentVNode(' <image class="bg" src="../../static/images/chu_query.png" mode="widthFix"></image> '),
  54597. vue.createElementVNode("view", { class: "content-body" }, [
  54598. vue.withDirectives(vue.createElementVNode(
  54599. "view",
  54600. { class: "store-head" },
  54601. [
  54602. vue.createElementVNode("view", { class: "store-head-top" }, [
  54603. vue.createElementVNode("view", { class: "store-head-logo" }, [
  54604. vue.createVNode(_component_u_image, {
  54605. shape: "square",
  54606. src: $data.storeInfo.logoUrl || $data.logoUrl,
  54607. width: "100rpx",
  54608. height: "100rpx",
  54609. radius: "6"
  54610. }, null, 8, ["src"])
  54611. ]),
  54612. vue.createElementVNode(
  54613. "view",
  54614. { class: "store-head-name" },
  54615. vue.toDisplayString($data.storeInfo.storeName || ""),
  54616. 1
  54617. /* TEXT */
  54618. )
  54619. ]),
  54620. vue.createElementVNode("view", { class: "store-head-desc" }, [
  54621. vue.createElementVNode(
  54622. "view",
  54623. null,
  54624. "销售" + vue.toDisplayString(_ctx.utils.formatSalesNum($data.storeInfo.salesCount)),
  54625. 1
  54626. /* TEXT */
  54627. ),
  54628. vue.createElementVNode("view", null, "24小时营业"),
  54629. vue.createElementVNode("view", null, "支持预订")
  54630. ])
  54631. ],
  54632. 512
  54633. /* NEED_PATCH */
  54634. ), [
  54635. [vue.vShow, $data.storeInfo.storeName]
  54636. ]),
  54637. vue.createElementVNode("view", { class: "storebox" }, [
  54638. vue.createVNode(_component_u_sticky, {
  54639. bgColor: "#fff",
  54640. "offset-top": $data.statusBarHeight + 44
  54641. }, {
  54642. default: vue.withCtx(() => [
  54643. vue.createVNode(_component_u_tabs, {
  54644. list: $data.tabbar,
  54645. current: $data.current,
  54646. onClick: $options.clickTab,
  54647. class: "u-tabs"
  54648. }, null, 8, ["list", "current", "onClick"])
  54649. ]),
  54650. _: 1
  54651. /* STABLE */
  54652. }, 8, ["offset-top"]),
  54653. vue.createCommentVNode(" 商品 "),
  54654. vue.createElementVNode(
  54655. "view",
  54656. {
  54657. style: vue.normalizeStyle({ height: $data.divHeight, display: $data.current == 0 ? "flex" : "none" }),
  54658. class: "medic-box"
  54659. },
  54660. [
  54661. vue.createElementVNode("view", { class: "cate-list" }, [
  54662. (vue.openBlock(true), vue.createElementBlock(
  54663. vue.Fragment,
  54664. null,
  54665. vue.renderList($data.cates, (item, index2) => {
  54666. return vue.openBlock(), vue.createElementBlock("view", {
  54667. key: index2,
  54668. class: vue.normalizeClass($data.cateSelect == item.cateId ? "item active" : "item"),
  54669. onClick: ($event) => $options.choseCate(item)
  54670. }, vue.toDisplayString(item.cateName), 11, ["onClick"]);
  54671. }),
  54672. 128
  54673. /* KEYED_FRAGMENT */
  54674. ))
  54675. ]),
  54676. vue.createElementVNode("view", { class: "medic" }, [
  54677. vue.createCommentVNode(" 轮播图 "),
  54678. vue.createElementVNode("view", { class: "banner-box" }, [
  54679. vue.createElementVNode("swiper", {
  54680. class: "swiper",
  54681. "indicator-dots": true,
  54682. circular: true,
  54683. autoplay: true,
  54684. interval: 3e3,
  54685. duration: 1e3,
  54686. "indicator-color": "rgba(255, 255, 255, 0.6)",
  54687. "indicator-active-color": "#ffffff"
  54688. }, [
  54689. (vue.openBlock(true), vue.createElementBlock(
  54690. vue.Fragment,
  54691. null,
  54692. vue.renderList($data.advs, (item, index2) => {
  54693. return vue.openBlock(), vue.createElementBlock("swiper-item", {
  54694. class: "swiper-item",
  54695. key: index2,
  54696. onClick: ($event) => $options.handleAdvClick(item)
  54697. }, [
  54698. vue.createElementVNode("image", {
  54699. src: item.imageUrl,
  54700. mode: ""
  54701. }, null, 8, ["src"])
  54702. ], 8, ["onClick"]);
  54703. }),
  54704. 128
  54705. /* KEYED_FRAGMENT */
  54706. ))
  54707. ])
  54708. ]),
  54709. vue.createCommentVNode(" 药品列表 "),
  54710. vue.createElementVNode("view", { class: "medic-list" }, [
  54711. vue.createCommentVNode(' <view class="item" v-for="(item,index) in subCates" :key="index">\r\n <view class="title">{{item.cateName}}</view> '),
  54712. vue.createElementVNode("view", { class: "inner-list" }, [
  54713. (vue.openBlock(true), vue.createElementBlock(
  54714. vue.Fragment,
  54715. null,
  54716. vue.renderList($data.subCates, (subItem, index2) => {
  54717. return vue.openBlock(), vue.createElementBlock("view", {
  54718. class: "definite",
  54719. onClick: ($event) => $options.showProductList(subItem)
  54720. }, [
  54721. vue.createElementVNode("view", { class: "img-box" }, [
  54722. vue.createElementVNode("image", {
  54723. src: subItem.pic,
  54724. mode: "aspectFit"
  54725. }, null, 8, ["src"])
  54726. ]),
  54727. vue.createElementVNode(
  54728. "view",
  54729. { class: "name ellipsis" },
  54730. vue.toDisplayString(subItem.cateName),
  54731. 1
  54732. /* TEXT */
  54733. )
  54734. ], 8, ["onClick"]);
  54735. }),
  54736. 256
  54737. /* UNKEYED_FRAGMENT */
  54738. ))
  54739. ]),
  54740. vue.createCommentVNode(" </view> ")
  54741. ])
  54742. ])
  54743. ],
  54744. 4
  54745. /* STYLE */
  54746. ),
  54747. vue.createCommentVNode(" 商家信息 "),
  54748. vue.withDirectives(vue.createElementVNode(
  54749. "view",
  54750. {
  54751. class: "storebox-info",
  54752. style: vue.normalizeStyle({ height: $data.divHeight })
  54753. },
  54754. [
  54755. vue.createElementVNode("view", { class: "storebox-map" }, [
  54756. vue.createVNode(_component_u_icon, {
  54757. name: "map",
  54758. color: "#ccc",
  54759. size: "18"
  54760. }),
  54761. vue.createElementVNode(
  54762. "view",
  54763. { style: { "margin-left": "10rpx" } },
  54764. vue.toDisplayString($data.storeInfo.address || "--"),
  54765. 1
  54766. /* TEXT */
  54767. )
  54768. ]),
  54769. $data.storeInfo.phone ? (vue.openBlock(), vue.createElementBlock("view", {
  54770. key: 0,
  54771. class: "storebox-map"
  54772. }, [
  54773. vue.createVNode(_component_u_icon, {
  54774. name: "phone",
  54775. color: "#ccc",
  54776. size: "18"
  54777. }),
  54778. vue.createElementVNode(
  54779. "view",
  54780. { style: { "margin-left": "10rpx" } },
  54781. vue.toDisplayString($data.storeInfo.phone || "--"),
  54782. 1
  54783. /* TEXT */
  54784. )
  54785. ])) : vue.createCommentVNode("v-if", true),
  54786. $data.storeInfo.descs ? (vue.openBlock(), vue.createElementBlock("view", {
  54787. key: 1,
  54788. class: "storebox-qualifications"
  54789. }, [
  54790. vue.createVNode(_component_u_icon, {
  54791. name: "volume",
  54792. color: "#ccc",
  54793. size: "18"
  54794. }),
  54795. vue.createElementVNode(
  54796. "view",
  54797. { style: { "margin-left": "10rpx" } },
  54798. vue.toDisplayString($data.storeInfo.descs || "--"),
  54799. 1
  54800. /* TEXT */
  54801. )
  54802. ])) : vue.createCommentVNode("v-if", true),
  54803. vue.createElementVNode("view", { class: "storebox-qualifications" }, [
  54804. vue.createVNode(_component_u_icon, {
  54805. name: "file-text",
  54806. color: "#ccc",
  54807. size: "18"
  54808. }),
  54809. vue.createElementVNode("view", { style: { "margin-left": "10rpx" } }, "商家资质")
  54810. ]),
  54811. vue.createElementVNode("view", { class: "qualifications" }, [
  54812. (vue.openBlock(true), vue.createElementBlock(
  54813. vue.Fragment,
  54814. null,
  54815. vue.renderList($data.licenseImagesList, (img, i2) => {
  54816. return vue.openBlock(), vue.createElementBlock("view", { key: i2 }, [
  54817. vue.createVNode(_component_u_image, {
  54818. shape: "square",
  54819. lazyLoad: "",
  54820. src: img,
  54821. width: "100%",
  54822. mode: "widthFix",
  54823. radius: "6",
  54824. onClick: ($event) => $options.previewImage(i2)
  54825. }, null, 8, ["src", "onClick"])
  54826. ]);
  54827. }),
  54828. 128
  54829. /* KEYED_FRAGMENT */
  54830. ))
  54831. ])
  54832. ],
  54833. 4
  54834. /* STYLE */
  54835. ), [
  54836. [vue.vShow, $data.current == 1]
  54837. ])
  54838. ])
  54839. ])
  54840. ],
  54841. 512
  54842. /* NEED_PATCH */
  54843. )), [
  54844. [vue.vShow, $data.storeId]
  54845. ]);
  54846. }
  54847. const PagesShopStore = /* @__PURE__ */ _export_sfc(_sfc_main$9, [["render", _sfc_render$8], ["__scopeId", "data-v-dd5fc6f3"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages_shop/store.vue"]]);
  54848. const _imports_0$4 = "/static/images/a.jpg";
  54849. const _sfc_main$8 = {
  54850. data() {
  54851. return {
  54852. orderList: [],
  54853. tabList: [{
  54854. name: "全部"
  54855. }, {
  54856. name: "待付款"
  54857. }, {
  54858. name: "已付款"
  54859. }]
  54860. };
  54861. },
  54862. mounted() {
  54863. this.getliveOrderList();
  54864. },
  54865. methods: {
  54866. tabsClick(item) {
  54867. formatAppLog("log", "at pages_shop/order.vue:65", "item", item);
  54868. },
  54869. // 订单列表
  54870. getliveOrderList() {
  54871. let data = {
  54872. pageSize: 10,
  54873. page: 1
  54874. };
  54875. liveOrderList(data).then(
  54876. (res) => {
  54877. if (res.code == 200) {
  54878. formatAppLog("log", "at pages_shop/order.vue:76", "订单列表数据>>>>", res);
  54879. this.orderList = res.rows;
  54880. } else {
  54881. uni.showToast({
  54882. title: res.msg,
  54883. icon: "none"
  54884. });
  54885. }
  54886. },
  54887. (rej) => {
  54888. formatAppLog("log", "at pages_shop/order.vue:86", "rej:" + JSON.stringify(rej));
  54889. }
  54890. );
  54891. }
  54892. }
  54893. };
  54894. function _sfc_render$7(_ctx, _cache, $props, $setup, $data, $options) {
  54895. const _component_u_tabs = resolveEasycom(vue.resolveDynamicComponent("u-tabs"), __easycom_0$1);
  54896. return vue.openBlock(), vue.createElementBlock("view", null, [
  54897. vue.createElementVNode("view", { class: "" }),
  54898. vue.createElementVNode("view", { class: "content" }, [
  54899. vue.createVNode(_component_u_tabs, {
  54900. class: "tabs",
  54901. itemStyle: "width:33%;height:100rpx;",
  54902. list: $data.tabList,
  54903. onClick: $options.tabsClick,
  54904. lineColor: "#FF5C03"
  54905. }, null, 8, ["list", "onClick"]),
  54906. vue.createElementVNode("view", { class: "order-list" }, [
  54907. (vue.openBlock(true), vue.createElementBlock(
  54908. vue.Fragment,
  54909. null,
  54910. vue.renderList($data.orderList, (item, index2) => {
  54911. return vue.openBlock(), vue.createElementBlock("view", {
  54912. class: "order-item",
  54913. key: index2
  54914. }, [
  54915. vue.createElementVNode("view", { class: "order-num" }, [
  54916. vue.createCommentVNode(" {{item.}} "),
  54917. vue.createElementVNode(
  54918. "text",
  54919. null,
  54920. "订单号:" + vue.toDisplayString(item.orderCode),
  54921. 1
  54922. /* TEXT */
  54923. ),
  54924. item.status == -1 ? (vue.openBlock(), vue.createElementBlock("text", { key: 0 }, "申请退款")) : item.status == -2 ? (vue.openBlock(), vue.createElementBlock("text", { key: 1 }, "退货成功")) : item.status == 1 ? (vue.openBlock(), vue.createElementBlock("text", { key: 2 }, "待支付")) : item.status == 2 ? (vue.openBlock(), vue.createElementBlock("text", { key: 3 }, "待发货")) : item.status == 3 ? (vue.openBlock(), vue.createElementBlock("text", { key: 4 }, "待收货")) : item.status == 4 ? (vue.openBlock(), vue.createElementBlock("text", { key: 5 }, "待评价")) : item.status == 5 ? (vue.openBlock(), vue.createElementBlock("text", { key: 6 }, "已完成")) : vue.createCommentVNode("v-if", true)
  54925. ]),
  54926. vue.createElementVNode("view", { class: "order-main" }, [
  54927. vue.createElementVNode("view", { class: "img-box" }, [
  54928. vue.createElementVNode("image", { src: _imports_0$4 })
  54929. ]),
  54930. vue.createElementVNode("view", { class: "order-text" }, [
  54931. vue.createElementVNode(
  54932. "view",
  54933. { class: "title" },
  54934. vue.toDisplayString(item.orderName),
  54935. 1
  54936. /* TEXT */
  54937. ),
  54938. vue.createElementVNode("view", { class: "txt" }, "适用于乏力、头晕等人群,通过问诊可明确诊断给予专业性指导意见。"),
  54939. vue.createElementVNode("view", { class: "num" }, [
  54940. vue.createElementVNode("text", null, "45708 人已购"),
  54941. vue.createElementVNode(
  54942. "text",
  54943. { class: "grey" },
  54944. "x" + vue.toDisplayString(item.totalNum),
  54945. 1
  54946. /* TEXT */
  54947. )
  54948. ])
  54949. ])
  54950. ]),
  54951. vue.createElementVNode("view", { class: "order-money" }, [
  54952. vue.createElementVNode("text", { class: "title" }, "订单金额:"),
  54953. vue.createElementVNode("text", { class: "num" }, [
  54954. vue.createTextVNode("¥"),
  54955. vue.createElementVNode(
  54956. "text",
  54957. { class: "bold" },
  54958. vue.toDisplayString(item.totalPrice),
  54959. 1
  54960. /* TEXT */
  54961. ),
  54962. vue.createTextVNode(".00")
  54963. ])
  54964. ])
  54965. ]);
  54966. }),
  54967. 128
  54968. /* KEYED_FRAGMENT */
  54969. ))
  54970. ])
  54971. ])
  54972. ]);
  54973. }
  54974. const PagesShopOrder = /* @__PURE__ */ _export_sfc(_sfc_main$8, [["render", _sfc_render$7], ["__scopeId", "data-v-11bfd2e6"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages_shop/order.vue"]]);
  54975. const _sfc_main$7 = {
  54976. name: "EvanSwitch",
  54977. props: {
  54978. value: {
  54979. type: [String, Number, Boolean],
  54980. default: false
  54981. },
  54982. activeColor: {
  54983. type: String,
  54984. default: "#108ee9"
  54985. },
  54986. inactiveColor: {
  54987. type: String,
  54988. default: "#fff"
  54989. },
  54990. size: {
  54991. type: Number,
  54992. default: 30
  54993. },
  54994. disabled: {
  54995. type: Boolean,
  54996. default: false
  54997. },
  54998. activeValue: {
  54999. type: [String, Number, Boolean],
  55000. default: true
  55001. },
  55002. inactiveValue: {
  55003. type: [String, Number, Boolean],
  55004. default: false
  55005. },
  55006. beforeChange: {
  55007. type: Function,
  55008. default: null
  55009. },
  55010. extraData: null,
  55011. contextLevel: {
  55012. type: Number,
  55013. default: 1
  55014. }
  55015. },
  55016. computed: {
  55017. switchHeight() {
  55018. return this.size + "px";
  55019. }
  55020. },
  55021. watch: {
  55022. value: {
  55023. immediate: true,
  55024. handler(value2) {
  55025. this.currentValue = value2;
  55026. }
  55027. }
  55028. },
  55029. data() {
  55030. return {
  55031. currentValue: false
  55032. };
  55033. },
  55034. methods: {
  55035. toggle() {
  55036. if (!this.disabled) {
  55037. if (this.beforeChange && typeof this.beforeChange === "function") {
  55038. let context = this;
  55039. for (let i2 = 0; i2 < this.contextLevel; i2++) {
  55040. context = context.$options.parent;
  55041. }
  55042. const result = this.beforeChange(
  55043. this.currentValue === this.activeValue ? this.inactiveValue : this.activeValue,
  55044. this.extraData,
  55045. context
  55046. );
  55047. if (typeof result === "object") {
  55048. result.then(() => {
  55049. this.toggleValue();
  55050. }).catch(() => {
  55051. });
  55052. } else if (typeof result === "boolean" && result) {
  55053. this.toggleValue();
  55054. }
  55055. } else {
  55056. this.toggleValue();
  55057. }
  55058. }
  55059. },
  55060. toggleValue() {
  55061. this.currentValue = this.currentValue === this.activeValue ? this.inactiveValue : this.activeValue;
  55062. this.$emit("input", this.currentValue);
  55063. this.$emit("change", this.currentValue);
  55064. }
  55065. }
  55066. };
  55067. function _sfc_render$6(_ctx, _cache, $props, $setup, $data, $options) {
  55068. return vue.openBlock(), vue.createElementBlock(
  55069. vue.Fragment,
  55070. null,
  55071. [
  55072. vue.createCommentVNode(` <view @click="toggle" class="evan-switch" :class="{'evan-switch--disabled':disabled}" :style="{width:2*size+'px',height:switchHeight,borderRadius:size+'px',backgroundColor:currentValue===activeValue?activeColor:inactiveColor}">\r
  55073. <view class="evan-switch__circle" :style="{width:size+'px',height:size+'px',transform:currentValue===activeValue?\`translateX(\${size}px)\`:\`translateX(0)\`}"></view>\r
  55074. </view> `),
  55075. vue.createElementVNode(
  55076. "view",
  55077. {
  55078. onClick: _cache[0] || (_cache[0] = (...args) => $options.toggle && $options.toggle(...args)),
  55079. class: vue.normalizeClass(["evan-switch", { "evan-switch--disabled": $props.disabled }]),
  55080. style: vue.normalizeStyle({ backgroundColor: $data.currentValue === $props.activeValue ? $props.activeColor : $props.inactiveColor })
  55081. },
  55082. [
  55083. vue.createElementVNode(
  55084. "view",
  55085. {
  55086. class: "evan-switch__circle",
  55087. style: vue.normalizeStyle({ transform: $data.currentValue === $props.activeValue ? `translateX(${29}px)` : `translateX(0)` })
  55088. },
  55089. null,
  55090. 4
  55091. /* STYLE */
  55092. )
  55093. ],
  55094. 6
  55095. /* CLASS, STYLE */
  55096. )
  55097. ],
  55098. 2112
  55099. /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
  55100. );
  55101. }
  55102. const __easycom_0 = /* @__PURE__ */ _export_sfc(_sfc_main$7, [["render", _sfc_render$6], ["__scopeId", "data-v-687346f1"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/components/evan-switch/evan-switch.vue"]]);
  55103. const _imports_0$3 = "/static/images/arrow_gray.png";
  55104. const _imports_2 = "/static/images/coupon1.png";
  55105. const _imports_3 = "/static/images/coupon2.png";
  55106. const _sfc_main$6 = {
  55107. components: {
  55108. EvanSwitch: __easycom_0,
  55109. popupBottom
  55110. },
  55111. data() {
  55112. return {
  55113. totalNum: null,
  55114. orderKey: null,
  55115. price: null,
  55116. liveId: null,
  55117. orderList: [],
  55118. userInfo: null,
  55119. userAddrLiat: [],
  55120. //用户地址
  55121. temps: [],
  55122. couponUserId: null,
  55123. couponText: "请选择",
  55124. couponsList: [],
  55125. couponVisible: false,
  55126. priceAll: {
  55127. payPrice: 0,
  55128. totalPostage: 0,
  55129. usedIntegral: 0,
  55130. totalPrice: 0
  55131. },
  55132. address: null,
  55133. carts: [],
  55134. checked: false,
  55135. type: null,
  55136. cartIds: null,
  55137. // form:{
  55138. // useIntegral:0,
  55139. // orderKey:null,
  55140. // addressId:null,
  55141. // mark:null,
  55142. // companyId:null,
  55143. // companyUserId:null,
  55144. // createOrderKey:null,
  55145. // },
  55146. confirmParam: []
  55147. };
  55148. },
  55149. computed: {
  55150. priceSum() {
  55151. return this.price * this.totalNum;
  55152. }
  55153. },
  55154. onLoad(options) {
  55155. formatAppLog("log", "at pages_shop/confirmCreateOrder.vue:242", "确认订单", options);
  55156. this.orderKey = options.orderKey;
  55157. this.liveId = options.liveId;
  55158. this.productId = options.productId;
  55159. this.totalNum = Number(options.totalNum);
  55160. this.price = Number(options.price);
  55161. },
  55162. mounted() {
  55163. this.getUserAddr();
  55164. },
  55165. methods: {
  55166. // 获取用户收货地址
  55167. getUserAddr() {
  55168. this.userInfo = JSON.parse(uni.getStorageSync("userInfo"));
  55169. userAddr(this.userInfo.userId).then(
  55170. (res) => {
  55171. if (res.code == 200) {
  55172. formatAppLog("log", "at pages_shop/confirmCreateOrder.vue:272", "用户收货地址>>>>", res);
  55173. this.userAddrLiat = res;
  55174. } else {
  55175. uni.showToast({
  55176. title: res.msg,
  55177. icon: "none"
  55178. });
  55179. }
  55180. },
  55181. (rej) => {
  55182. }
  55183. );
  55184. },
  55185. // 创建订单
  55186. createLiveOrder() {
  55187. let data = {
  55188. liveId: this.liveId,
  55189. orderKey: this.orderKey,
  55190. // storeId:this.storeId,,
  55191. userName: "没名字",
  55192. userPhone: "1234568",
  55193. userAddress: "随便住",
  55194. // cartId:"5",
  55195. productId: this.productId,
  55196. totalNum: this.totalNum
  55197. // totalPrice:999,
  55198. // remark:"随便备注",
  55199. };
  55200. return createliveOrder(data).then((res) => {
  55201. if (res.code == 200) {
  55202. this.orderList = res.order;
  55203. return res.order;
  55204. } else {
  55205. uni.showToast({
  55206. title: res.msg,
  55207. icon: "none"
  55208. });
  55209. throw new Error(res.msg);
  55210. }
  55211. });
  55212. },
  55213. getWeixinOrderTemps: function() {
  55214. getWeixinOrderTemps().then(
  55215. (res) => {
  55216. if (res.code == 200) {
  55217. this.temps = res.temp;
  55218. }
  55219. },
  55220. (rej) => {
  55221. }
  55222. );
  55223. },
  55224. couponSelect(item) {
  55225. this.couponText = "-¥" + item.couponPrice.toFixed(2);
  55226. this.couponUserId = item.id;
  55227. this.couponVisible = false;
  55228. this.computed();
  55229. },
  55230. openCoupon() {
  55231. let that = this;
  55232. var data = {
  55233. couponType: 2,
  55234. useMinPrice: this.price.payPrice
  55235. };
  55236. getMyEnableCouponList(data).then((res) => {
  55237. this.couponVisible = true;
  55238. that.couponsList = res.data;
  55239. });
  55240. },
  55241. integralChange(e2) {
  55242. this.form.useIntegral = e2 ? 1 : 0;
  55243. this.computed();
  55244. },
  55245. confirm(item) {
  55246. confirm(this.confirmParam).then(
  55247. (res) => {
  55248. if (res.code == 200) {
  55249. this.carts = res.carts.map((item2) => ({
  55250. ...item2,
  55251. markinfo: ""
  55252. }));
  55253. this.form.orderKey = res.orderKeys;
  55254. if (res.address != null) {
  55255. this.form.addressId = res.address.id;
  55256. this.address = res.address;
  55257. }
  55258. this.computed();
  55259. } else {
  55260. uni.showToast({
  55261. icon: "none",
  55262. title: res.msg
  55263. });
  55264. }
  55265. },
  55266. (rej) => {
  55267. }
  55268. );
  55269. },
  55270. computed(item) {
  55271. let data = {
  55272. createOrderKey: this.form.createOrderKey,
  55273. couponUserId: this.couponUserId,
  55274. orderKeys: this.form.orderKey,
  55275. addressId: this.form.addressId,
  55276. useIntegral: this.form.useIntegral
  55277. };
  55278. computed(data).then(
  55279. (res) => {
  55280. if (res.code == 200) {
  55281. this.price = res.data && res.data.length > 0 ? res.data : [];
  55282. this.priceAll = res.data && res.data.length > 0 ? res.data[res.data.length - 1] : {
  55283. payPrice: 0,
  55284. totalPostage: 0,
  55285. usedIntegral: 0,
  55286. totalPrice: 0
  55287. };
  55288. } else {
  55289. if (res.code == 501) {
  55290. uni.showToast({
  55291. icon: "none",
  55292. title: res.msg
  55293. });
  55294. setTimeout(function() {
  55295. uni.navigateBack({
  55296. delta: 1
  55297. });
  55298. }, 500);
  55299. return;
  55300. } else {
  55301. uni.showToast({
  55302. icon: "none",
  55303. title: res.msg
  55304. });
  55305. }
  55306. }
  55307. },
  55308. (rej) => {
  55309. }
  55310. );
  55311. },
  55312. // 提交订单
  55313. async submitOrder() {
  55314. try {
  55315. const orderList = await this.createLiveOrder();
  55316. const orderListStr = encodeURIComponent(JSON.stringify(orderList));
  55317. uni.navigateTo({
  55318. url: `/pages_shop/paymentOrder?orderList=${orderListStr}`
  55319. });
  55320. } catch (error2) {
  55321. formatAppLog("error", "at pages_shop/confirmCreateOrder.vue:425", "订单创建失败:", error2);
  55322. uni.showToast({ title: "提交失败", icon: "none" });
  55323. }
  55324. },
  55325. createOrder() {
  55326. const mark = this.carts.map((item) => item.markinfo);
  55327. var data = null;
  55328. var tuiUserId = uni.getStorageSync("tuiUserId");
  55329. uni.showLoading({
  55330. title: "正在处理中..."
  55331. });
  55332. if (tuiUserId != null && tuiUserId != void 0 && tuiUserId > 0) {
  55333. data = {
  55334. createOrderKey: this.form.createOrderKey,
  55335. orderCreateType: 3,
  55336. tuiUserId,
  55337. companyId: this.form.companyId,
  55338. companyUserId: this.form.companyUserId,
  55339. couponUserId: this.couponUserId,
  55340. mark,
  55341. orderKeys: this.form.orderKey,
  55342. addressId: this.form.addressId,
  55343. useIntegral: this.form.useIntegral,
  55344. payType: 1
  55345. };
  55346. } else {
  55347. data = {
  55348. createOrderKey: this.form.createOrderKey,
  55349. orderCreateType: 3,
  55350. companyId: this.form.companyId,
  55351. companyUserId: this.form.companyUserId,
  55352. couponUserId: this.couponUserId,
  55353. mark,
  55354. orderKeys: this.form.orderKey,
  55355. addressId: this.form.addressId,
  55356. useIntegral: this.form.useIntegral,
  55357. payType: 1
  55358. };
  55359. }
  55360. create(data).then(
  55361. (res) => {
  55362. uni.hideLoading();
  55363. if (!res.code && res.code !== 0) {
  55364. uni.hideLoading();
  55365. if (res.some((item) => item.order.isPrescribe) == 1) {
  55366. setTimeout(function() {
  55367. let orderIds = res.filter((item) => item.order.isPrescribe == 1).map((it2) => it2.order.id);
  55368. orderIds = orderIds.join(",");
  55369. uni.redirectTo({
  55370. url: "prescribe?orderId=" + orderIds + "&combinationOrderId=" + encodeURIComponent(res[0].order.combinationOrderId)
  55371. });
  55372. }, 200);
  55373. } else {
  55374. setTimeout(function() {
  55375. uni.redirectTo({
  55376. url: "./paymentOrder?combinationOrderId=" + encodeURIComponent(
  55377. res[0].order.combinationOrderId
  55378. )
  55379. });
  55380. }, 200);
  55381. }
  55382. return;
  55383. } else {
  55384. if (res.code == 501) {
  55385. uni.showToast({
  55386. icon: "none",
  55387. title: res.msg
  55388. });
  55389. setTimeout(function() {
  55390. uni.navigateBack({
  55391. delta: 1
  55392. });
  55393. }, 200);
  55394. return;
  55395. } else {
  55396. uni.showToast({
  55397. icon: "none",
  55398. title: res.msg
  55399. });
  55400. }
  55401. }
  55402. },
  55403. (rej) => {
  55404. }
  55405. );
  55406. },
  55407. openAddress() {
  55408. uni.navigateTo({
  55409. url: "/pages_user/address"
  55410. });
  55411. }
  55412. }
  55413. };
  55414. function _sfc_render$5(_ctx, _cache, $props, $setup, $data, $options) {
  55415. var _a, _b, _c;
  55416. const _component_popupBottom = vue.resolveComponent("popupBottom");
  55417. return vue.openBlock(), vue.createElementBlock("view", null, [
  55418. vue.createElementVNode("view", { class: "inner-box" }, [
  55419. vue.createCommentVNode(" 收货人 "),
  55420. $data.address == null ? (vue.openBlock(), vue.createElementBlock("view", {
  55421. key: 0,
  55422. class: "address-box",
  55423. onClick: _cache[0] || (_cache[0] = ($event) => $options.openAddress())
  55424. }, [
  55425. vue.createElementVNode("view", { class: "left" }, [
  55426. vue.createElementVNode("view", { class: "name-box" }, [
  55427. vue.createElementVNode("text", { class: "text name" }, "添加收货地址")
  55428. ])
  55429. ]),
  55430. vue.createElementVNode("view", { class: "arrow-box" }, [
  55431. vue.createElementVNode("image", {
  55432. src: _imports_0$3,
  55433. mode: ""
  55434. })
  55435. ])
  55436. ])) : vue.createCommentVNode("v-if", true),
  55437. $data.address != null ? (vue.openBlock(), vue.createElementBlock("view", {
  55438. key: 1,
  55439. class: "address-box",
  55440. onClick: _cache[1] || (_cache[1] = ($event) => $options.openAddress())
  55441. }, [
  55442. vue.createElementVNode("view", { class: "left" }, [
  55443. vue.createElementVNode("view", { class: "name-box" }, [
  55444. vue.createElementVNode(
  55445. "text",
  55446. { class: "text name" },
  55447. vue.toDisplayString($data.address.realName),
  55448. 1
  55449. /* TEXT */
  55450. ),
  55451. $data.address.phone != null ? (vue.openBlock(), vue.createElementBlock(
  55452. "text",
  55453. {
  55454. key: 0,
  55455. class: "text"
  55456. },
  55457. vue.toDisplayString(_ctx.utils.parsePhone($data.address.phone)),
  55458. 1
  55459. /* TEXT */
  55460. )) : vue.createCommentVNode("v-if", true)
  55461. ]),
  55462. vue.createElementVNode(
  55463. "view",
  55464. { class: "address" },
  55465. vue.toDisplayString($data.address.province) + vue.toDisplayString($data.address.city) + vue.toDisplayString($data.address.district) + vue.toDisplayString($data.address.detail),
  55466. 1
  55467. /* TEXT */
  55468. )
  55469. ]),
  55470. vue.createElementVNode("view", { class: "arrow-box" }, [
  55471. vue.createElementVNode("image", {
  55472. src: _imports_0$3,
  55473. mode: ""
  55474. })
  55475. ])
  55476. ])) : vue.createCommentVNode("v-if", true),
  55477. vue.createCommentVNode(" 药品列表 "),
  55478. (vue.openBlock(true), vue.createElementBlock(
  55479. vue.Fragment,
  55480. null,
  55481. vue.renderList($data.carts, (shop, idx) => {
  55482. return vue.openBlock(), vue.createElementBlock("view", {
  55483. class: "shopbox",
  55484. key: idx
  55485. }, [
  55486. shop.storeName && shop.storeName != "null" ? (vue.openBlock(), vue.createElementBlock("view", {
  55487. key: 0,
  55488. class: "shopbox-name"
  55489. }, [
  55490. vue.createElementVNode(
  55491. "text",
  55492. null,
  55493. vue.toDisplayString(shop.storeName),
  55494. 1
  55495. /* TEXT */
  55496. )
  55497. ])) : vue.createCommentVNode("v-if", true),
  55498. vue.createElementVNode("view", { class: "goods-list" }, [
  55499. (vue.openBlock(true), vue.createElementBlock(
  55500. vue.Fragment,
  55501. null,
  55502. vue.renderList(shop.list, (item, index2) => {
  55503. var _a2;
  55504. return vue.openBlock(), vue.createElementBlock("view", {
  55505. key: index2,
  55506. class: "item"
  55507. }, [
  55508. vue.createElementVNode("view", { class: "img-box" }, [
  55509. vue.createElementVNode("image", {
  55510. src: item.productAttrImage ? item.productAttrImage : item.productImage,
  55511. mode: "aspectFill"
  55512. }, null, 8, ["src"])
  55513. ]),
  55514. vue.createElementVNode("view", { class: "info-box" }, [
  55515. vue.createElementVNode("view", null, [
  55516. vue.createElementVNode("view", { class: "name-box ellipsis2" }, [
  55517. vue.createElementVNode(
  55518. "view",
  55519. { class: "tag" },
  55520. vue.toDisplayString(_ctx.utils.getDictLabelName("storeProductType", item.productType)),
  55521. 1
  55522. /* TEXT */
  55523. ),
  55524. vue.createTextVNode(
  55525. vue.toDisplayString(item.productName),
  55526. 1
  55527. /* TEXT */
  55528. )
  55529. ]),
  55530. vue.createElementVNode(
  55531. "view",
  55532. { class: "spec ellipsis2" },
  55533. vue.toDisplayString(item.productAttrName),
  55534. 1
  55535. /* TEXT */
  55536. )
  55537. ]),
  55538. vue.createElementVNode("view", { class: "price-num" }, [
  55539. vue.createElementVNode("view", { class: "price" }, [
  55540. vue.createElementVNode("text", { class: "unit" }, "¥"),
  55541. vue.createElementVNode(
  55542. "text",
  55543. { class: "num" },
  55544. vue.toDisplayString((_a2 = item.price) == null ? void 0 : _a2.toFixed(2)),
  55545. 1
  55546. /* TEXT */
  55547. )
  55548. ]),
  55549. vue.createElementVNode(
  55550. "view",
  55551. { class: "num" },
  55552. "x" + vue.toDisplayString(item.cartNum),
  55553. 1
  55554. /* TEXT */
  55555. )
  55556. ])
  55557. ])
  55558. ]);
  55559. }),
  55560. 128
  55561. /* KEYED_FRAGMENT */
  55562. )),
  55563. vue.createCommentVNode(" 运费 "),
  55564. vue.createElementVNode("view", { class: "points" }, [
  55565. vue.createElementVNode("view", { class: "left" }, [
  55566. vue.createElementVNode("text", { class: "text" }, "运费")
  55567. ]),
  55568. $data.price && $data.price.length > 0 ? (vue.openBlock(), vue.createElementBlock("view", {
  55569. key: 0,
  55570. class: "right"
  55571. }, [
  55572. vue.createElementVNode(
  55573. "text",
  55574. { class: "text" },
  55575. vue.toDisplayString($data.price[idx].payPostage == null || $data.price[idx].payPostage == 0 ? "免运费" : $data.price[idx].payPostage.toFixed(2)),
  55576. 1
  55577. /* TEXT */
  55578. )
  55579. ])) : vue.createCommentVNode("v-if", true)
  55580. ]),
  55581. vue.createCommentVNode(" 备注 "),
  55582. vue.createElementVNode("view", { class: "points" }, [
  55583. vue.createElementVNode("view", { class: "left" }, [
  55584. vue.createElementVNode("text", { class: "text" }, "备注")
  55585. ]),
  55586. vue.createElementVNode("view", { class: "remarks" }, [
  55587. vue.withDirectives(vue.createElementVNode("input", {
  55588. type: "text",
  55589. "onUpdate:modelValue": ($event) => shop.markinfo = $event,
  55590. placeholder: "备注留言(选填)",
  55591. "placeholder-class": "input"
  55592. }, null, 8, ["onUpdate:modelValue"]), [
  55593. [vue.vModelText, shop.markinfo]
  55594. ])
  55595. ])
  55596. ])
  55597. ])
  55598. ]);
  55599. }),
  55600. 128
  55601. /* KEYED_FRAGMENT */
  55602. )),
  55603. vue.createCommentVNode(" 积分 "),
  55604. vue.createElementVNode("view", { class: "price-info" }, [
  55605. vue.createElementVNode("view", { class: "price-info-title" }, "价格明细"),
  55606. vue.createElementVNode("view", { class: "points" }, [
  55607. vue.createElementVNode("view", { class: "left" }, [
  55608. vue.createElementVNode("text", { class: "text" }, "商品总价")
  55609. ]),
  55610. vue.createElementVNode("view", {
  55611. class: "right",
  55612. style: { "align-items": "baseline" }
  55613. }, [
  55614. vue.createElementVNode("text", { class: "price-info-unit" }, "¥"),
  55615. vue.createElementVNode(
  55616. "text",
  55617. { class: "price-info-num" },
  55618. vue.toDisplayString((_a = $data.price) == null ? void 0 : _a.toFixed(2)),
  55619. 1
  55620. /* TEXT */
  55621. )
  55622. ])
  55623. ]),
  55624. vue.createCommentVNode(' <view class="points">\r\n <view class="left">\r\n <image src="/static/images/points.png" mode=""></image>\r\n <text class="text">可用积分</text>\r\n </view>\r\n <view class="right">\r\n <text class="text">{{priceAll.usedIntegral}}积分</text>\r\n <evan-switch @change="integralChange" v-model="checked" activeColor="#0bb3f2"\r\n inactiveColor="rgba(0, 0, 0, 0.1)"></evan-switch>\r\n </view>\r\n </view> '),
  55625. vue.createCommentVNode(' <view class="points" @click="openCoupon()">\r\n <view class="left">\r\n <text class="text">优惠券</text>\r\n </view>\r\n <view class="right">\r\n <text class="text">{{couponText}}</text>\r\n <image src="/static/images/arrow4.png" mode=""></image>\r\n </view>\r\n </view> '),
  55626. vue.createElementVNode("view", { class: "points" }, [
  55627. vue.createElementVNode("view", { class: "left" }, [
  55628. vue.createElementVNode("text", { class: "text" }, "合计")
  55629. ]),
  55630. vue.createElementVNode("view", {
  55631. class: "right",
  55632. style: { "align-items": "baseline" }
  55633. }, [
  55634. vue.createElementVNode("text", { class: "price-info-unit" }, "¥"),
  55635. vue.createElementVNode(
  55636. "text",
  55637. { class: "price-info-num" },
  55638. vue.toDisplayString((_b = $options.priceSum) == null ? void 0 : _b.toFixed(2)),
  55639. 1
  55640. /* TEXT */
  55641. )
  55642. ])
  55643. ])
  55644. ]),
  55645. vue.createCommentVNode(` <view class="points">\r
  55646. <view class="left">\r
  55647. <text class="text">运费</text>\r
  55648. </view>\r
  55649. <view class="right">\r
  55650. <text class="text">{{price.payPostage==null||price.payPostage==0?'免运费':price.payPostage.toFixed(2)}}</text>\r
  55651. </view>\r
  55652. </view> `),
  55653. vue.createCommentVNode(" 备注 "),
  55654. vue.createCommentVNode(' <view class="remarks">\r\n <input type="text" v-model="form.mark" placeholder="备注留言(选填)" placeholder-class="input" />\r\n </view> ')
  55655. ]),
  55656. vue.createCommentVNode(" 底部按钮 "),
  55657. vue.createElementVNode("view", { class: "btn-foot" }, [
  55658. vue.createElementVNode("view", { class: "right" }, [
  55659. vue.createElementVNode("view", { class: "total" }, [
  55660. vue.createElementVNode("text", { class: "label" }, "合计:"),
  55661. vue.createElementVNode("view", { class: "price" }, [
  55662. vue.createElementVNode("text", { class: "unit" }, "¥"),
  55663. vue.createElementVNode(
  55664. "text",
  55665. { class: "num" },
  55666. vue.toDisplayString((_c = $options.priceSum) == null ? void 0 : _c.toFixed(2)),
  55667. 1
  55668. /* TEXT */
  55669. )
  55670. ])
  55671. ]),
  55672. vue.createElementVNode("view", {
  55673. class: "btn",
  55674. onClick: _cache[2] || (_cache[2] = (...args) => $options.submitOrder && $options.submitOrder(...args))
  55675. }, "提交订单")
  55676. ])
  55677. ]),
  55678. vue.createVNode(_component_popupBottom, {
  55679. ref: "popup",
  55680. visible: $data.couponVisible,
  55681. title: " ",
  55682. bgColor: "#f5f5f5",
  55683. radius: "30",
  55684. maxHeight: "60%"
  55685. }, {
  55686. default: vue.withCtx(() => [
  55687. vue.createElementVNode("view", {
  55688. class: "coupon",
  55689. style: { "height": "650rpx" }
  55690. }, [
  55691. $data.couponsList.length > 0 ? (vue.openBlock(), vue.createElementBlock("div", {
  55692. key: 0,
  55693. class: "coupon-list"
  55694. }, [
  55695. (vue.openBlock(true), vue.createElementBlock(
  55696. vue.Fragment,
  55697. null,
  55698. vue.renderList($data.couponsList, (item, index2) => {
  55699. return vue.openBlock(), vue.createElementBlock("div", {
  55700. class: "item acea-row row-center-wrapper",
  55701. key: index2
  55702. }, [
  55703. vue.createElementVNode("div", { class: "money" }, [
  55704. item.status == 0 ? (vue.openBlock(), vue.createElementBlock("image", {
  55705. key: 0,
  55706. class: "img",
  55707. src: _imports_2,
  55708. mode: "widthFix"
  55709. })) : vue.createCommentVNode("v-if", true),
  55710. item.status != 0 ? (vue.openBlock(), vue.createElementBlock("image", {
  55711. key: 1,
  55712. class: "img",
  55713. src: _imports_3,
  55714. mode: "widthFix"
  55715. })) : vue.createCommentVNode("v-if", true),
  55716. vue.createElementVNode("div", { style: { "z-index": "999" } }, [
  55717. vue.createTextVNode(" ¥"),
  55718. vue.createElementVNode(
  55719. "span",
  55720. { class: "num" },
  55721. vue.toDisplayString(item.couponPrice),
  55722. 1
  55723. /* TEXT */
  55724. )
  55725. ]),
  55726. vue.createElementVNode(
  55727. "div",
  55728. { class: "pic-num" },
  55729. "满" + vue.toDisplayString(item.useMinPrice) + "元可用",
  55730. 1
  55731. /* TEXT */
  55732. )
  55733. ]),
  55734. vue.createElementVNode("div", { class: "text" }, [
  55735. vue.createElementVNode(
  55736. "div",
  55737. { class: "condition line1" },
  55738. vue.toDisplayString(item.couponTitle),
  55739. 1
  55740. /* TEXT */
  55741. ),
  55742. vue.createElementVNode("div", { class: "data acea-row row-between-wrapper" }, [
  55743. vue.createElementVNode(
  55744. "div",
  55745. null,
  55746. vue.toDisplayString(item.limitTime) + "到期",
  55747. 1
  55748. /* TEXT */
  55749. ),
  55750. vue.createElementVNode("div", {
  55751. class: "bnt bg-color-red",
  55752. onClick: ($event) => $options.couponSelect(item)
  55753. }, "选择", 8, ["onClick"])
  55754. ])
  55755. ])
  55756. ]);
  55757. }),
  55758. 128
  55759. /* KEYED_FRAGMENT */
  55760. ))
  55761. ])) : vue.createCommentVNode("v-if", true),
  55762. $data.couponsList.length == 0 ? (vue.openBlock(), vue.createElementBlock("view", {
  55763. key: 1,
  55764. class: "no-data-box"
  55765. }, [
  55766. vue.createElementVNode("image", {
  55767. src: _imports_2$2,
  55768. mode: "aspectFit"
  55769. }),
  55770. vue.createElementVNode("view", { class: "empty-title" }, "暂无数据")
  55771. ])) : vue.createCommentVNode("v-if", true)
  55772. ])
  55773. ]),
  55774. _: 1
  55775. /* STABLE */
  55776. }, 8, ["visible"])
  55777. ]);
  55778. }
  55779. const PagesShopConfirmCreateOrder = /* @__PURE__ */ _export_sfc(_sfc_main$6, [["render", _sfc_render$5], ["__scopeId", "data-v-5fa01107"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages_shop/confirmCreateOrder.vue"]]);
  55780. var dayjs_min = { exports: {} };
  55781. (function(module, exports) {
  55782. !function(t2, e2) {
  55783. module.exports = e2();
  55784. }(commonjsGlobal, function() {
  55785. 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) {
  55786. var e3 = ["th", "st", "nd", "rd"], n3 = t3 % 100;
  55787. return "[" + t3 + (e3[(n3 - 20) % 10] || e3[n3] || e3[0]) + "]";
  55788. } }, m2 = function(t3, e3, n3) {
  55789. var r3 = String(t3);
  55790. return !r3 || r3.length >= e3 ? t3 : "" + Array(e3 + 1 - r3.length).join(n3) + t3;
  55791. }, v2 = { s: m2, z: function(t3) {
  55792. var e3 = -t3.utcOffset(), n3 = Math.abs(e3), r3 = Math.floor(n3 / 60), i3 = n3 % 60;
  55793. return (e3 <= 0 ? "+" : "-") + m2(r3, 2, "0") + ":" + m2(i3, 2, "0");
  55794. }, m: function t3(e3, n3) {
  55795. if (e3.date() < n3.date())
  55796. return -t3(n3, e3);
  55797. 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);
  55798. return +(-(r3 + (n3 - i3) / (s3 ? i3 - u3 : u3 - i3)) || 0);
  55799. }, a: function(t3) {
  55800. return t3 < 0 ? Math.ceil(t3) || 0 : Math.floor(t3);
  55801. }, p: function(t3) {
  55802. 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$/, "");
  55803. }, u: function(t3) {
  55804. return void 0 === t3;
  55805. } }, g2 = "en", D2 = {};
  55806. D2[g2] = M2;
  55807. var p2 = "$isDayjsObject", S2 = function(t3) {
  55808. return t3 instanceof _2 || !(!t3 || !t3[p2]);
  55809. }, w2 = function t3(e3, n3, r3) {
  55810. var i3;
  55811. if (!e3)
  55812. return g2;
  55813. if ("string" == typeof e3) {
  55814. var s3 = e3.toLowerCase();
  55815. D2[s3] && (i3 = s3), n3 && (D2[s3] = n3, i3 = s3);
  55816. var u3 = e3.split("-");
  55817. if (!i3 && u3.length > 1)
  55818. return t3(u3[0]);
  55819. } else {
  55820. var a3 = e3.name;
  55821. D2[a3] = e3, i3 = a3;
  55822. }
  55823. return !r3 && i3 && (g2 = i3), i3 || !r3 && g2;
  55824. }, O2 = function(t3, e3) {
  55825. if (S2(t3))
  55826. return t3.clone();
  55827. var n3 = "object" == typeof e3 ? e3 : {};
  55828. return n3.date = t3, n3.args = arguments, new _2(n3);
  55829. }, b2 = v2;
  55830. b2.l = w2, b2.i = S2, b2.w = function(t3, e3) {
  55831. return O2(t3, { locale: e3.$L, utc: e3.$u, x: e3.$x, $offset: e3.$offset });
  55832. };
  55833. var _2 = function() {
  55834. function M3(t3) {
  55835. this.$L = w2(t3.locale, null, true), this.parse(t3), this.$x = this.$x || t3.x || {}, this[p2] = true;
  55836. }
  55837. var m3 = M3.prototype;
  55838. return m3.parse = function(t3) {
  55839. this.$d = function(t4) {
  55840. var e3 = t4.date, n3 = t4.utc;
  55841. if (null === e3)
  55842. return /* @__PURE__ */ new Date(NaN);
  55843. if (b2.u(e3))
  55844. return /* @__PURE__ */ new Date();
  55845. if (e3 instanceof Date)
  55846. return new Date(e3);
  55847. if ("string" == typeof e3 && !/Z$/i.test(e3)) {
  55848. var r3 = e3.match($2);
  55849. if (r3) {
  55850. var i3 = r3[2] - 1 || 0, s3 = (r3[7] || "0").substring(0, 3);
  55851. 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);
  55852. }
  55853. }
  55854. return new Date(e3);
  55855. }(t3), this.init();
  55856. }, m3.init = function() {
  55857. var t3 = this.$d;
  55858. 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();
  55859. }, m3.$utils = function() {
  55860. return b2;
  55861. }, m3.isValid = function() {
  55862. return !(this.$d.toString() === l2);
  55863. }, m3.isSame = function(t3, e3) {
  55864. var n3 = O2(t3);
  55865. return this.startOf(e3) <= n3 && n3 <= this.endOf(e3);
  55866. }, m3.isAfter = function(t3, e3) {
  55867. return O2(t3) < this.startOf(e3);
  55868. }, m3.isBefore = function(t3, e3) {
  55869. return this.endOf(e3) < O2(t3);
  55870. }, m3.$g = function(t3, e3, n3) {
  55871. return b2.u(t3) ? this[e3] : this.set(n3, t3);
  55872. }, m3.unix = function() {
  55873. return Math.floor(this.valueOf() / 1e3);
  55874. }, m3.valueOf = function() {
  55875. return this.$d.getTime();
  55876. }, m3.startOf = function(t3, e3) {
  55877. var n3 = this, r3 = !!b2.u(e3) || e3, f3 = b2.p(t3), l3 = function(t4, e4) {
  55878. var i3 = b2.w(n3.$u ? Date.UTC(n3.$y, e4, t4) : new Date(n3.$y, e4, t4), n3);
  55879. return r3 ? i3 : i3.endOf(a2);
  55880. }, $3 = function(t4, e4) {
  55881. return b2.w(n3.toDate()[t4].apply(n3.toDate("s"), (r3 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e4)), n3);
  55882. }, y3 = this.$W, M4 = this.$M, m4 = this.$D, v3 = "set" + (this.$u ? "UTC" : "");
  55883. switch (f3) {
  55884. case h2:
  55885. return r3 ? l3(1, 0) : l3(31, 11);
  55886. case c2:
  55887. return r3 ? l3(1, M4) : l3(0, M4 + 1);
  55888. case o2:
  55889. var g3 = this.$locale().weekStart || 0, D3 = (y3 < g3 ? y3 + 7 : y3) - g3;
  55890. return l3(r3 ? m4 - D3 : m4 + (6 - D3), M4);
  55891. case a2:
  55892. case d2:
  55893. return $3(v3 + "Hours", 0);
  55894. case u2:
  55895. return $3(v3 + "Minutes", 1);
  55896. case s2:
  55897. return $3(v3 + "Seconds", 2);
  55898. case i2:
  55899. return $3(v3 + "Milliseconds", 3);
  55900. default:
  55901. return this.clone();
  55902. }
  55903. }, m3.endOf = function(t3) {
  55904. return this.startOf(t3, false);
  55905. }, m3.$set = function(t3, e3) {
  55906. 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;
  55907. if (o3 === c2 || o3 === h2) {
  55908. var y3 = this.clone().set(d2, 1);
  55909. y3.$d[l3]($3), y3.init(), this.$d = y3.set(d2, Math.min(this.$D, y3.daysInMonth())).$d;
  55910. } else
  55911. l3 && this.$d[l3]($3);
  55912. return this.init(), this;
  55913. }, m3.set = function(t3, e3) {
  55914. return this.clone().$set(t3, e3);
  55915. }, m3.get = function(t3) {
  55916. return this[b2.p(t3)]();
  55917. }, m3.add = function(r3, f3) {
  55918. var d3, l3 = this;
  55919. r3 = Number(r3);
  55920. var $3 = b2.p(f3), y3 = function(t3) {
  55921. var e3 = O2(l3);
  55922. return b2.w(e3.date(e3.date() + Math.round(t3 * r3)), l3);
  55923. };
  55924. if ($3 === c2)
  55925. return this.set(c2, this.$M + r3);
  55926. if ($3 === h2)
  55927. return this.set(h2, this.$y + r3);
  55928. if ($3 === a2)
  55929. return y3(1);
  55930. if ($3 === o2)
  55931. return y3(7);
  55932. var M4 = (d3 = {}, d3[s2] = e2, d3[u2] = n2, d3[i2] = t2, d3)[$3] || 1, m4 = this.$d.getTime() + r3 * M4;
  55933. return b2.w(m4, this);
  55934. }, m3.subtract = function(t3, e3) {
  55935. return this.add(-1 * t3, e3);
  55936. }, m3.format = function(t3) {
  55937. var e3 = this, n3 = this.$locale();
  55938. if (!this.isValid())
  55939. return n3.invalidDate || l2;
  55940. 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) {
  55941. return t4 && (t4[n4] || t4(e3, r3)) || i4[n4].slice(0, s4);
  55942. }, d3 = function(t4) {
  55943. return b2.s(s3 % 12 || 12, t4, "0");
  55944. }, $3 = f3 || function(t4, e4, n4) {
  55945. var r4 = t4 < 12 ? "AM" : "PM";
  55946. return n4 ? r4.toLowerCase() : r4;
  55947. };
  55948. return r3.replace(y2, function(t4, r4) {
  55949. return r4 || function(t5) {
  55950. switch (t5) {
  55951. case "YY":
  55952. return String(e3.$y).slice(-2);
  55953. case "YYYY":
  55954. return b2.s(e3.$y, 4, "0");
  55955. case "M":
  55956. return a3 + 1;
  55957. case "MM":
  55958. return b2.s(a3 + 1, 2, "0");
  55959. case "MMM":
  55960. return h3(n3.monthsShort, a3, c3, 3);
  55961. case "MMMM":
  55962. return h3(c3, a3);
  55963. case "D":
  55964. return e3.$D;
  55965. case "DD":
  55966. return b2.s(e3.$D, 2, "0");
  55967. case "d":
  55968. return String(e3.$W);
  55969. case "dd":
  55970. return h3(n3.weekdaysMin, e3.$W, o3, 2);
  55971. case "ddd":
  55972. return h3(n3.weekdaysShort, e3.$W, o3, 3);
  55973. case "dddd":
  55974. return o3[e3.$W];
  55975. case "H":
  55976. return String(s3);
  55977. case "HH":
  55978. return b2.s(s3, 2, "0");
  55979. case "h":
  55980. return d3(1);
  55981. case "hh":
  55982. return d3(2);
  55983. case "a":
  55984. return $3(s3, u3, true);
  55985. case "A":
  55986. return $3(s3, u3, false);
  55987. case "m":
  55988. return String(u3);
  55989. case "mm":
  55990. return b2.s(u3, 2, "0");
  55991. case "s":
  55992. return String(e3.$s);
  55993. case "ss":
  55994. return b2.s(e3.$s, 2, "0");
  55995. case "SSS":
  55996. return b2.s(e3.$ms, 3, "0");
  55997. case "Z":
  55998. return i3;
  55999. }
  56000. return null;
  56001. }(t4) || i3.replace(":", "");
  56002. });
  56003. }, m3.utcOffset = function() {
  56004. return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
  56005. }, m3.diff = function(r3, d3, l3) {
  56006. var $3, y3 = this, M4 = b2.p(d3), m4 = O2(r3), v3 = (m4.utcOffset() - this.utcOffset()) * e2, g3 = this - m4, D3 = function() {
  56007. return b2.m(y3, m4);
  56008. };
  56009. switch (M4) {
  56010. case h2:
  56011. $3 = D3() / 12;
  56012. break;
  56013. case c2:
  56014. $3 = D3();
  56015. break;
  56016. case f2:
  56017. $3 = D3() / 3;
  56018. break;
  56019. case o2:
  56020. $3 = (g3 - v3) / 6048e5;
  56021. break;
  56022. case a2:
  56023. $3 = (g3 - v3) / 864e5;
  56024. break;
  56025. case u2:
  56026. $3 = g3 / n2;
  56027. break;
  56028. case s2:
  56029. $3 = g3 / e2;
  56030. break;
  56031. case i2:
  56032. $3 = g3 / t2;
  56033. break;
  56034. default:
  56035. $3 = g3;
  56036. }
  56037. return l3 ? $3 : b2.a($3);
  56038. }, m3.daysInMonth = function() {
  56039. return this.endOf(c2).$D;
  56040. }, m3.$locale = function() {
  56041. return D2[this.$L];
  56042. }, m3.locale = function(t3, e3) {
  56043. if (!t3)
  56044. return this.$L;
  56045. var n3 = this.clone(), r3 = w2(t3, e3, true);
  56046. return r3 && (n3.$L = r3), n3;
  56047. }, m3.clone = function() {
  56048. return b2.w(this.$d, this);
  56049. }, m3.toDate = function() {
  56050. return new Date(this.valueOf());
  56051. }, m3.toJSON = function() {
  56052. return this.isValid() ? this.toISOString() : null;
  56053. }, m3.toISOString = function() {
  56054. return this.$d.toISOString();
  56055. }, m3.toString = function() {
  56056. return this.$d.toUTCString();
  56057. }, M3;
  56058. }(), k = _2.prototype;
  56059. return O2.prototype = k, [["$ms", r2], ["$s", i2], ["$m", s2], ["$H", u2], ["$W", a2], ["$M", c2], ["$y", h2], ["$D", d2]].forEach(function(t3) {
  56060. k[t3[1]] = function(e3) {
  56061. return this.$g(e3, t3[0], t3[1]);
  56062. };
  56063. }), O2.extend = function(t3, e3) {
  56064. return t3.$i || (t3(e3, _2, O2), t3.$i = true), O2;
  56065. }, O2.locale = w2, O2.isDayjs = S2, O2.unix = function(t3) {
  56066. return O2(1e3 * t3);
  56067. }, O2.en = D2[g2], O2.Ls = D2, O2.p = {}, O2;
  56068. });
  56069. })(dayjs_min);
  56070. var dayjs_minExports = dayjs_min.exports;
  56071. const dayjs = /* @__PURE__ */ getDefaultExportFromCjs(dayjs_minExports);
  56072. let request = new Request$1().http;
  56073. const api = {
  56074. // 支付
  56075. zfbPayment: "/app/live/liveOrder/aliPayment"
  56076. // 支付宝付款
  56077. // updateConfirm: (orderId, type) => `/app/live/liveOrder/updateConfirm/${orderId}/${type} `, // 取消/支付订单确认
  56078. };
  56079. function zfbPayment(data) {
  56080. return request(api.zfbPayment, data, "POST", "application/json;charset=UTF-8");
  56081. }
  56082. const _imports_0$2 = "/static/images/wecha_pay.png";
  56083. const _imports_1$2 = "/static/images/zfb.png";
  56084. const _sfc_main$5 = {
  56085. data() {
  56086. return {
  56087. payType: 2,
  56088. order: null,
  56089. // formattedDate: '',
  56090. orderId: null,
  56091. payDelivery: 0,
  56092. payMoney: 0,
  56093. config: null,
  56094. payType: 1,
  56095. // payLimitTime: null,
  56096. user: null,
  56097. combinationOrderId: "",
  56098. // 需要开处方的订单id
  56099. prescribeOrder: ""
  56100. };
  56101. },
  56102. computed: {
  56103. formattedDate() {
  56104. var _a;
  56105. return ((_a = this.order) == null ? void 0 : _a.createTime) ? dayjs(this.order.createTime).format("YYYY-MM-DD HH:mm:ss") : "";
  56106. },
  56107. payLimitTime() {
  56108. var _a;
  56109. return ((_a = this.order) == null ? void 0 : _a.updateTime) ? dayjs(this.order.updateTime).format("YYYY-MM-DD HH:mm:ss") : "";
  56110. }
  56111. },
  56112. onLoad(options) {
  56113. formatAppLog("log", "at pages_shop/paymentOrder.vue:210", "支付订单是>>", options);
  56114. if (options.orderList) {
  56115. try {
  56116. const decoded = decodeURIComponent(options.orderList);
  56117. this.order = JSON.parse(decoded) || {};
  56118. } catch (e2) {
  56119. formatAppLog("error", "at pages_shop/paymentOrder.vue:220", "参数解析失败:", e2);
  56120. this.order = {};
  56121. }
  56122. }
  56123. },
  56124. //发送给朋友
  56125. onShareAppMessage(res) {
  56126. const combinationOrderId = this.combinationOrderId ? `&combinationOrderId=${encodeURIComponent(this.combinationOrderId)}` : "";
  56127. return {
  56128. title: "帮TA支付",
  56129. path: "/pages_user/user/otherPaymentOrder?orderId=" + this.orderId + combinationOrderId,
  56130. imageUrl: "/static/images/logo.png"
  56131. //分享图标,路径可以是本地文件路径、代码包文件路径或者网络图片路径.支持PNG及JPG。显示图片长宽比是 5:4
  56132. };
  56133. },
  56134. methods: {
  56135. // 选微信支付或者支付宝支付
  56136. handlePayTypeChange(e2) {
  56137. this.payType = e2.detail.value;
  56138. formatAppLog("log", "at pages_shop/paymentOrder.vue:256", "当前选中:", this.payType);
  56139. if (this.payType === 1) {
  56140. this.doWechatPay();
  56141. } else if (this.payType === 2) {
  56142. this.doAlipay();
  56143. }
  56144. },
  56145. payOrder() {
  56146. if (this.payType == 2) {
  56147. this.doAlipay();
  56148. } else {
  56149. uni.showToast({
  56150. title: "暂时没有开通微信支付",
  56151. icon: "none"
  56152. });
  56153. }
  56154. },
  56155. // 支付
  56156. doAlipay() {
  56157. var data = {
  56158. orderId: this.order.orderId
  56159. };
  56160. formatAppLog("log", "at pages_shop/paymentOrder.vue:279", "orderId>>", this.order.orderId);
  56161. let that = this;
  56162. const tzCashier = requireNativePlugin("TZBank-Cashier");
  56163. uni.showLoading();
  56164. zfbPayment(data).then(
  56165. (res) => {
  56166. formatAppLog("log", "at pages_shop/paymentOrder.vue:287", "支付开始", res);
  56167. uni.hideLoading();
  56168. if (res.code == 200) {
  56169. formatAppLog("log", "at pages_shop/paymentOrder.vue:290", "支付在这里", res);
  56170. if (res.type == "tz") {
  56171. const match = res.data.body.url.match(/[\?&]businessCstNo=([^&]+)/);
  56172. const businessCstNo = match ? match[1] : null;
  56173. formatAppLog("log", "at pages_shop/paymentOrder.vue:295", "qxj tzCashier:" + tzCashier + " businessCstNo:" + businessCstNo);
  56174. tzCashier.pay({
  56175. env: 0,
  56176. wxMiniProgramType: 0,
  56177. // wxAppId: 'wx703c4bd07bbd1695',
  56178. wxAppId: "wx9ea36eecd281bcd3",
  56179. wxUniversalLink: "https://yjf.runtzh.com/",
  56180. orderFlowNo: res.data.body.orderFlowNo,
  56181. businessCstNo,
  56182. platMerCstNo: res.data.body.platMerCstNo
  56183. }, (res2) => {
  56184. uni.$emit("closePrivilege", {});
  56185. that.showPayTips = true;
  56186. });
  56187. } else if (res.type == "hf") {
  56188. if (uni.getSystemInfoSync().platform == "android") {
  56189. var alipayScheme = "alipays://platformapi/startApp?&saId=10000007&qrcode=" + res.data.qr_code;
  56190. } else {
  56191. var alipayScheme = "alipay://platformapi/startApp?&saId=10000007&qrcode=" + res.data.qr_code;
  56192. }
  56193. plus.runtime.openURL(alipayScheme, function(error2) {
  56194. });
  56195. uni.$emit("closePrivilege", {});
  56196. that.showPayTips = true;
  56197. }
  56198. } else {
  56199. uni.showToast({
  56200. title: res.msg,
  56201. icon: "none"
  56202. });
  56203. }
  56204. },
  56205. (rej) => {
  56206. }
  56207. );
  56208. },
  56209. getUserInfo() {
  56210. getUserInfo().then(
  56211. (res) => {
  56212. if (res.code == 200) {
  56213. if (res.user != null) {
  56214. this.user = res.user;
  56215. }
  56216. } else {
  56217. uni.showToast({
  56218. icon: "none",
  56219. title: "请求失败"
  56220. });
  56221. }
  56222. },
  56223. (rej) => {
  56224. }
  56225. );
  56226. },
  56227. getStoreConfig() {
  56228. getStoreConfig().then(
  56229. (res) => {
  56230. if (res.code == 200) {
  56231. this.config = res.data;
  56232. formatAppLog("log", "at pages_shop/paymentOrder.vue:374", this.config);
  56233. }
  56234. },
  56235. (rej) => {
  56236. }
  56237. );
  56238. },
  56239. payTypeChange(e2) {
  56240. if (this.combinationOrderId) {
  56241. this.editPayTypeByCombinationId(e2.detail.value);
  56242. } else {
  56243. this.editPayType(e2.detail.value);
  56244. }
  56245. },
  56246. copyOrderSn(text) {
  56247. uni.setClipboardData({
  56248. data: text,
  56249. success: () => {
  56250. uni.showToast({
  56251. title: "内容已成功复制到剪切板",
  56252. icon: "none"
  56253. });
  56254. }
  56255. });
  56256. },
  56257. // getStoreOrderById(){
  56258. // var data = {orderId:this.orderId};
  56259. // var that=this;
  56260. // uni.showLoading();
  56261. // getStoreOrderById(data).then(
  56262. // res => {
  56263. // if(res.code==200){
  56264. // __f__('log','at pages_shop/paymentOrder.vue:406',res);
  56265. // uni.hideLoading();
  56266. // that.order=res.order;
  56267. // that.order.orderCodes = that.order.orderCode ? [that.order.orderCode]:[]
  56268. // that.orderCode = that.order.orderCode
  56269. // that.payLimitTime=res.payLimitTime;
  56270. // //套餐订单处理
  56271. // if(res.productPackage!=null){
  56272. // this.payType=res.productPackage.payType;
  56273. // __f__('log','at pages_shop/paymentOrder.vue:415',this.payType)
  56274. // if(this.order.payType==4){
  56275. // this.order.payType=1;
  56276. // }
  56277. // }
  56278. // this.editPayType(this.order.payType)
  56279. // }else{
  56280. // uni.showToast({
  56281. // icon:'none',
  56282. // title: res.msg,
  56283. // });
  56284. // }
  56285. // },
  56286. // rej => {}
  56287. // );
  56288. // },
  56289. editPayType(payType) {
  56290. var data = {
  56291. orderId: this.orderId,
  56292. payType
  56293. };
  56294. var that = this;
  56295. uni.showLoading();
  56296. editPayType(data).then(
  56297. (res) => {
  56298. if (res.code == 200) {
  56299. formatAppLog("log", "at pages_shop/paymentOrder.vue:443", res);
  56300. uni.hideLoading();
  56301. that.order = res.order;
  56302. that.order.orderCodes = that.order.orderCode ? [that.order.orderCode] : [];
  56303. that.orderCode = that.order.orderCode;
  56304. this.payMoney = this.order.payMoney;
  56305. this.payDelivery = this.order.payDelivery;
  56306. } else {
  56307. uni.showToast({
  56308. icon: "none",
  56309. title: res.msg
  56310. });
  56311. }
  56312. },
  56313. (rej) => {
  56314. }
  56315. );
  56316. },
  56317. // getStoreOrderByCombinationId() {
  56318. // var data = {combinationId:this.combinationOrderId};
  56319. // var that=this;
  56320. // uni.showLoading();
  56321. // getStoreOrderByCombinationId(data).then(
  56322. // res => {
  56323. // if(res.code==200){
  56324. // __f__('log','at pages_shop/paymentOrder.vue:469',res);
  56325. // uni.hideLoading();
  56326. // that.order=res.order;
  56327. // that.orderCode = res.order.orderCodes ? res.order.orderCodes.join(',') : "";
  56328. // that.payLimitTime=res.payLimitTime;
  56329. // //套餐订单处理
  56330. // if(res.productPackage!=null){
  56331. // this.payType=res.productPackage.payType;
  56332. // __f__('log','at pages_shop/paymentOrder.vue:477',this.payType)
  56333. // if(this.order.payType==4){
  56334. // this.order.payType=1;
  56335. // }
  56336. // }
  56337. // that.prescribeOrder = res.prescribeOrder;
  56338. // this.editPayTypeByCombinationId(this.order.payType)
  56339. // }else{
  56340. // uni.showToast({
  56341. // icon:'none',
  56342. // title: res.msg,
  56343. // });
  56344. // }
  56345. // },
  56346. // rej => {}
  56347. // );
  56348. // },
  56349. // editPayTypeByCombinationId(payType){
  56350. // var data = {combinationOrderId:this.combinationOrderId,payType:payType};
  56351. // var that=this;
  56352. // uni.showLoading();
  56353. // editPayTypeByCombinationId(data).then(
  56354. // res => {
  56355. // if(res.code==200){
  56356. // __f__('log','at pages_shop/paymentOrder.vue:502',res);
  56357. // uni.hideLoading();
  56358. // that.order=res.order;
  56359. // that.orderCode = res.order.orderCodes ? res.order.orderCodes.join(',') : "";
  56360. // //this.payType=this.order.payType
  56361. // this.payMoney=this.order.payMoney;
  56362. // this.payDelivery=this.order.payDelivery;
  56363. // that.prescribeOrder = res.prescribeOrder;
  56364. // }else{
  56365. // uni.showToast({
  56366. // icon:'none',
  56367. // title: res.msg,
  56368. // });
  56369. // }
  56370. // },
  56371. // rej => {}
  56372. // );
  56373. // },
  56374. otherPayOrder() {
  56375. uni.navigateTo({
  56376. url: "/pages_user/user/otherPaymentOrder?combinationOrderId=" + encodeURIComponent(this.combinationOrderId)
  56377. });
  56378. },
  56379. // payOrder() {
  56380. // if (this.combinationOrderId) {
  56381. // let data = {
  56382. // combinationOrderId: this.combinationOrderId,
  56383. // payType: this.order.payType
  56384. // };
  56385. // let that = this;
  56386. // uni.showLoading();
  56387. // payByCombinationId(data).then(
  56388. // res => {
  56389. // if (res.code == 200) {
  56390. // this.payfun(res)
  56391. // } else {
  56392. // uni.showToast({
  56393. // icon: 'none',
  56394. // title: res.msg,
  56395. // });
  56396. // }
  56397. // },
  56398. // rej => {}
  56399. // );
  56400. // } else {
  56401. // let data = {
  56402. // orderId: this.order.id,
  56403. // payType: this.order.payType
  56404. // };
  56405. // let that = this;
  56406. // uni.showLoading();
  56407. // pay(data).then(
  56408. // res => {
  56409. // if (res.code == 200) {
  56410. // this.payfun(res)
  56411. // } else {
  56412. // uni.showToast({
  56413. // icon: 'none',
  56414. // title: res.msg,
  56415. // });
  56416. // }
  56417. // },
  56418. // rej => {}
  56419. // );
  56420. // }
  56421. // },
  56422. payfun(res) {
  56423. const that = this;
  56424. formatAppLog("log", "at pages_shop/paymentOrder.vue:576", res.result);
  56425. if (res.payType == 1 || res.payType == 2) {
  56426. uni.requestPayment({
  56427. provider: "wxpay",
  56428. timeStamp: res.result.timeStamp,
  56429. nonceStr: res.result.nonceStr,
  56430. // package: res.result.packageValue,
  56431. package: res.result.packageStr,
  56432. signType: res.result.signType,
  56433. paySign: res.result.paySign,
  56434. success: function(res2) {
  56435. uni.hideLoading();
  56436. uni.redirectTo({
  56437. url: "success?order=" + JSON.stringify(that.order)
  56438. });
  56439. },
  56440. fail: function(err) {
  56441. uni.showToast({
  56442. icon: "none",
  56443. title: "fail:" + JSON.stringify(err)
  56444. });
  56445. formatAppLog("log", "at pages_shop/paymentOrder.vue:597", "fail:" + JSON.stringify(err));
  56446. uni.hideLoading();
  56447. }
  56448. });
  56449. } else if (res.payType == 3) {
  56450. uni.hideLoading();
  56451. if (that.order.isPrescribe) {
  56452. uni.redirectTo({
  56453. url: "prescribe?orderId=" + that.prescribeOrder + "&combinationOrderId=" + encodeURIComponent(that.order.combinationOrderId)
  56454. });
  56455. } else {
  56456. uni.redirectTo({
  56457. url: "success?order=" + JSON.stringify(that.order)
  56458. });
  56459. }
  56460. }
  56461. }
  56462. }
  56463. };
  56464. function _sfc_render$4(_ctx, _cache, $props, $setup, $data, $options) {
  56465. var _a;
  56466. return vue.openBlock(), vue.createElementBlock("view", { class: "content" }, [
  56467. vue.createElementVNode("view", { class: "inner" }, [
  56468. vue.createCommentVNode(" 时间、价格 "),
  56469. vue.createElementVNode("view", { class: "time-price" }, [
  56470. vue.createElementVNode(
  56471. "text",
  56472. { class: "time" },
  56473. "请在" + vue.toDisplayString($options.payLimitTime) + "前完成支付",
  56474. 1
  56475. /* TEXT */
  56476. ),
  56477. vue.createElementVNode("view", { class: "price-box" }, [
  56478. vue.createElementVNode("text", { class: "unit" }, "¥"),
  56479. vue.createElementVNode(
  56480. "text",
  56481. { class: "num" },
  56482. vue.toDisplayString($data.order ? (Number($data.order.totalPrice) || 0).toFixed(2) : "0.00"),
  56483. 1
  56484. /* TEXT */
  56485. )
  56486. ]),
  56487. vue.createCommentVNode(' <text class="desc" v-if="payType==2">代收金额{{payDelivery.toFixed(2)}},请您在收到快递后支付尾款给快递人员。</text>\r\n <text class="desc" v-if="payType==3">货到付款金额{{payDelivery.toFixed(2)}},请您在收到快递后支付给快递人员。</text> ')
  56488. ]),
  56489. vue.createCommentVNode(" 支付方式 "),
  56490. vue.createElementVNode("view", { class: "pay-type" }, [
  56491. vue.createElementVNode("view", { class: "title" }, "支付方式"),
  56492. vue.createCommentVNode(" 改价订单只能选择微信支付和物流代收 "),
  56493. vue.createCommentVNode(` <radio-group @change="payTypeChange" v-if="order.isEditMoney!=null&&order.isEditMoney==1">\r
  56494. <view class="item" >\r
  56495. <view class="left" >\r
  56496. <image src="/static/images/wecha_pay.png" mode=""></image>\r
  56497. <text class="text">微信支付</text>\r
  56498. </view>\r
  56499. <label>\r
  56500. <radio :value="1" :checked="order.payType=='1'" />\r
  56501. </label>\r
  56502. </view>\r
  56503. <view class="item" >\r
  56504. <view class="left">\r
  56505. <image src="/static/images/pay_de.png" mode=""></image>\r
  56506. <text class="text">物流代收</text>\r
  56507. </view>\r
  56508. <label>\r
  56509. <radio :value="2" :checked="order.payType=='2'" />\r
  56510. </label>\r
  56511. </view>\r
  56512. </radio-group> `),
  56513. vue.createCommentVNode(` <radio-group @change="payTypeChange" v-else-if="order.orderCreateType!=null&& order.orderCreateType==3">\r
  56514. <view class="item" >\r
  56515. <view class="left" >\r
  56516. <image src="/static/images/wecha_pay.png" mode=""></image>\r
  56517. <text class="text">微信支付</text>\r
  56518. </view>\r
  56519. <label>\r
  56520. <radio :value="1" :checked="order.payType=='1'" />\r
  56521. </label>\r
  56522. </view>\r
  56523. <view class="item" >\r
  56524. <view class="left">\r
  56525. <image src="/static/images/pay_de.png" mode=""></image>\r
  56526. <text class="text">物流代收</text>\r
  56527. </view>\r
  56528. <label>\r
  56529. <radio :value="2" :checked="order.payType=='2'" />\r
  56530. </label>\r
  56531. </view>\r
  56532. <view class="item" v-if="user!=null&&user.level==1 ">\r
  56533. <view class="left">\r
  56534. <image src="/static/images/pay_1.png" mode=""></image>\r
  56535. <text class="text">货到付款</text>\r
  56536. </view>\r
  56537. <label>\r
  56538. <radio :value="3" :checked="order.payType=='3'" />\r
  56539. </label>\r
  56540. </view>\r
  56541. </radio-group>\r
  56542. <radio-group @change="payTypeChange" v-else-if="order.orderCreateType!=null&& order.orderCreateType==2">\r
  56543. <view class="item" v-if="payType==1||payType==4" >\r
  56544. <view class="left" >\r
  56545. <image src="/static/images/wecha_pay.png" mode=""></image>\r
  56546. <text class="text">微信支付</text>\r
  56547. </view>\r
  56548. <label>\r
  56549. <radio :value="1" :checked="order.payType=='1'" />\r
  56550. </label>\r
  56551. </view>\r
  56552. <view class="item" v-if="payType==2||payType==4">\r
  56553. <view class="left" >\r
  56554. <image src="/static/images/pay_de.png" mode=""></image>\r
  56555. <text class="text">物流代收</text>\r
  56556. </view>\r
  56557. <label>\r
  56558. <radio :value="2" :checked="order.payType=='2'" />\r
  56559. </label>\r
  56560. </view>\r
  56561. <view class="item" v-if="user!=null&&user.level==1 ">\r
  56562. <view class="left">\r
  56563. <image src="/static/images/pay_1.png" mode=""></image>\r
  56564. <text class="text">货到付款</text>\r
  56565. </view>\r
  56566. <label>\r
  56567. <radio :value="3" :checked="order.payType=='3'" />\r
  56568. </label>\r
  56569. </view>\r
  56570. </radio-group> `),
  56571. vue.createCommentVNode(' <radio-group @change="payTypeChange" v-else-if="order.orderCreateType!=null&&(order.orderCreateType==1)">\r\n <view class="item" >\r\n <view class="left" >\r\n <image src="/static/images/wecha_pay.png" mode=""></image>\r\n <text class="text">微信支付</text>\r\n </view>\r\n <label>\r\n <radio :value="1" checked />\r\n </label>\r\n </view>\r\n </radio-group> '),
  56572. vue.createElementVNode(
  56573. "radio-group",
  56574. {
  56575. onChange: _cache[0] || (_cache[0] = (...args) => $options.handlePayTypeChange && $options.handlePayTypeChange(...args))
  56576. },
  56577. [
  56578. vue.createElementVNode("view", { class: "item" }, [
  56579. vue.createElementVNode("view", { class: "left" }, [
  56580. vue.createElementVNode("image", {
  56581. src: _imports_0$2,
  56582. mode: ""
  56583. }),
  56584. vue.createElementVNode("text", { class: "text" }, "微信支付")
  56585. ]),
  56586. vue.createElementVNode("label", null, [
  56587. vue.createElementVNode("radio", {
  56588. value: 1,
  56589. checked: $data.payType === 1
  56590. }, null, 8, ["checked"])
  56591. ])
  56592. ]),
  56593. vue.createElementVNode("view", { class: "item" }, [
  56594. vue.createElementVNode("view", { class: "left" }, [
  56595. vue.createElementVNode("image", {
  56596. src: _imports_1$2,
  56597. mode: ""
  56598. }),
  56599. vue.createElementVNode("text", { class: "text" }, "支付宝")
  56600. ]),
  56601. vue.createElementVNode("label", null, [
  56602. vue.createElementVNode("radio", {
  56603. value: 2,
  56604. checked: $data.payType === 2
  56605. }, null, 8, ["checked"])
  56606. ])
  56607. ])
  56608. ],
  56609. 32
  56610. /* NEED_HYDRATION */
  56611. )
  56612. ]),
  56613. vue.createCommentVNode(" 订单详情查看 "),
  56614. vue.createElementVNode("view", { class: "order-info" }, [
  56615. vue.createElementVNode("view", { class: "title" }, "订单信息"),
  56616. vue.createElementVNode("view", { class: "item" }, [
  56617. vue.createElementVNode("text", { class: "label" }, "订单编号"),
  56618. vue.createElementVNode("view", { class: "sn-box" }, [
  56619. vue.createElementVNode("view", null, [
  56620. vue.createElementVNode(
  56621. "view",
  56622. { class: "text" },
  56623. vue.toDisplayString((_a = $data.order) == null ? void 0 : _a.orderCode),
  56624. 1
  56625. /* TEXT */
  56626. )
  56627. ]),
  56628. vue.createElementVNode("view", {
  56629. class: "copy-btn",
  56630. onClick: _cache[1] || (_cache[1] = ($event) => $options.copyOrderSn(_ctx.orderCode))
  56631. }, "复制")
  56632. ])
  56633. ]),
  56634. vue.createElementVNode("view", { class: "item" }, [
  56635. vue.createElementVNode("text", { class: "label" }, "下单时间"),
  56636. vue.createElementVNode(
  56637. "text",
  56638. { class: "text" },
  56639. vue.toDisplayString($options.formattedDate),
  56640. 1
  56641. /* TEXT */
  56642. )
  56643. ]),
  56644. vue.createElementVNode("view", { class: "item" }, [
  56645. vue.createElementVNode("text", { class: "label" }, "订单金额"),
  56646. $data.order != null ? (vue.openBlock(), vue.createElementBlock(
  56647. "text",
  56648. {
  56649. key: 0,
  56650. class: "text"
  56651. },
  56652. vue.toDisplayString($data.order ? (Number($data.order.totalPrice) || 0).toFixed(2) : "0.00"),
  56653. 1
  56654. /* TEXT */
  56655. )) : vue.createCommentVNode("v-if", true)
  56656. ]),
  56657. vue.createCommentVNode(' <view class="item">\r\n <text class="label">支付方式</text>\r\n <text class="text">微信支付</text>\r\n </view> ')
  56658. ])
  56659. ]),
  56660. vue.createElementVNode("view", { class: "btn-box" }, [
  56661. vue.createElementVNode("view", {
  56662. class: "btn",
  56663. onClick: _cache[2] || (_cache[2] = ($event) => $options.payOrder())
  56664. }, "去支付"),
  56665. vue.createCommentVNode(' <view class="other-btn">\r\n 亲友代付\r\n <button class="share" data-name="shareBtn" open-type="share">分享</button>\r\n </view> ')
  56666. ])
  56667. ]);
  56668. }
  56669. const PagesShopPaymentOrder = /* @__PURE__ */ _export_sfc(_sfc_main$5, [["render", _sfc_render$4], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages_shop/paymentOrder.vue"]]);
  56670. const _imports_1$1 = "/static/images/arrow4.png";
  56671. const _sfc_main$4 = {
  56672. components: {
  56673. EvanSwitch: __easycom_0,
  56674. popupBottom
  56675. },
  56676. data() {
  56677. return {
  56678. liveId: null,
  56679. temps: [],
  56680. totalMoney: 0,
  56681. couponUserId: null,
  56682. couponText: "请选择",
  56683. couponsList: [],
  56684. couponVisible: false,
  56685. companyUserId: null,
  56686. packageId: null,
  56687. address: null,
  56688. package: {},
  56689. // checked: false,
  56690. // type:null,
  56691. // cartIds:null,
  56692. form: {
  56693. // useIntegral:0,
  56694. orderKey: null,
  56695. addressId: null,
  56696. mark: null
  56697. }
  56698. };
  56699. },
  56700. onLoad(option) {
  56701. },
  56702. onShow() {
  56703. },
  56704. methods: {
  56705. getWeixinTemps: function() {
  56706. getWeixinTemps().then(
  56707. (res) => {
  56708. if (res.code == 200) {
  56709. this.temps = res.temp;
  56710. }
  56711. },
  56712. (rej) => {
  56713. }
  56714. );
  56715. },
  56716. couponSelect(item) {
  56717. this.couponText = "-¥" + item.couponPrice.toFixed(2);
  56718. this.couponUserId = item.id;
  56719. this.couponVisible = false;
  56720. this.computedPackageOrder();
  56721. },
  56722. openCoupon() {
  56723. let that = this;
  56724. var data = { packageCateId: this.package.cateId, couponType: 1, useMinPrice: this.totalMoney };
  56725. getMyEnableCouponList(data).then((res) => {
  56726. this.couponVisible = true;
  56727. that.couponsList = res.data;
  56728. });
  56729. },
  56730. confirmPackageOrder() {
  56731. let data = { packageId: this.packageId, couponUserId: this.couponUserId };
  56732. confirmPackageOrder(data).then(
  56733. (res) => {
  56734. if (res.code == 200) {
  56735. this.form.orderKey = res.orderKey;
  56736. this.address = res.address;
  56737. this.package = res.package;
  56738. if (res.address != null) {
  56739. this.form.addressId = res.address.id;
  56740. }
  56741. this.totalMoney = res.totalMoney;
  56742. } else {
  56743. uni.showToast({
  56744. icon: "none",
  56745. title: res.msg
  56746. });
  56747. }
  56748. },
  56749. (rej) => {
  56750. }
  56751. );
  56752. },
  56753. computedPackageOrder() {
  56754. let data = { packageId: this.packageId, couponUserId: this.couponUserId };
  56755. computedPackageOrder(data).then(
  56756. (res) => {
  56757. if (res.code == 200) {
  56758. this.totalMoney = res.totalMoney;
  56759. } else {
  56760. uni.showToast({
  56761. icon: "none",
  56762. title: res.msg
  56763. });
  56764. }
  56765. },
  56766. (rej) => {
  56767. }
  56768. );
  56769. },
  56770. // 提交订单
  56771. submitOrder() {
  56772. var that = this;
  56773. if (this.form.orderKey == null) {
  56774. uni.showToast({
  56775. icon: "none",
  56776. title: "订单KEY不存在"
  56777. });
  56778. return;
  56779. }
  56780. if (this.form.addressId == null) {
  56781. uni.showToast({
  56782. icon: "none",
  56783. title: "收货地址不能为空"
  56784. });
  56785. return;
  56786. }
  56787. uni.requestSubscribeMessage({
  56788. tmplIds: this.temps,
  56789. success(res) {
  56790. that.createPackageOrder();
  56791. },
  56792. fail(res) {
  56793. that.createPackageOrder();
  56794. }
  56795. });
  56796. },
  56797. createPackageOrder() {
  56798. uni.showLoading({
  56799. title: "正在处理中..."
  56800. });
  56801. let data = { couponUserId: this.couponUserId, mark: this.form.mark, orderKey: this.form.orderKey, addressId: this.form.addressId, packageId: this.packageId, companyUserId: this.companyUserId };
  56802. createPackageOrder(data).then(
  56803. (res) => {
  56804. uni.hideLoading();
  56805. if (res.code == 200) {
  56806. if (res.order.isPrescribe == 1) {
  56807. setTimeout(function() {
  56808. uni.redirectTo({
  56809. url: "prescribe?orderId=" + res.order.id
  56810. });
  56811. }, 200);
  56812. } else {
  56813. setTimeout(function() {
  56814. uni.redirectTo({
  56815. url: "./paymentOrder?orderId=" + res.order.id
  56816. });
  56817. }, 200);
  56818. }
  56819. return;
  56820. } else {
  56821. if (res.code == 501) {
  56822. uni.showToast({
  56823. icon: "none",
  56824. title: res.msg
  56825. });
  56826. setTimeout(function() {
  56827. uni.navigateBack({
  56828. delta: 1
  56829. });
  56830. }, 200);
  56831. return;
  56832. } else {
  56833. uni.showToast({
  56834. icon: "none",
  56835. title: res.msg
  56836. });
  56837. }
  56838. }
  56839. },
  56840. (rej) => {
  56841. }
  56842. );
  56843. },
  56844. openAddress() {
  56845. uni.navigateTo({
  56846. url: "/pages_user/user/address"
  56847. });
  56848. }
  56849. }
  56850. };
  56851. function _sfc_render$3(_ctx, _cache, $props, $setup, $data, $options) {
  56852. const _component_popupBottom = vue.resolveComponent("popupBottom");
  56853. return vue.openBlock(), vue.createElementBlock("view", null, [
  56854. vue.createElementVNode("view", { class: "inner-box" }, [
  56855. vue.createCommentVNode(" 收货人 "),
  56856. $data.address == null ? (vue.openBlock(), vue.createElementBlock("view", {
  56857. key: 0,
  56858. class: "address-box",
  56859. onClick: _cache[0] || (_cache[0] = ($event) => $options.openAddress())
  56860. }, [
  56861. vue.createElementVNode("view", { class: "left" }, [
  56862. vue.createElementVNode("view", { class: "name-box" }, [
  56863. vue.createElementVNode("text", { class: "text name" }, "添加收货地址")
  56864. ])
  56865. ]),
  56866. vue.createElementVNode("view", { class: "arrow-box" }, [
  56867. vue.createElementVNode("image", {
  56868. src: _imports_0$3,
  56869. mode: ""
  56870. })
  56871. ])
  56872. ])) : vue.createCommentVNode("v-if", true),
  56873. $data.address != null ? (vue.openBlock(), vue.createElementBlock("view", {
  56874. key: 1,
  56875. class: "address-box",
  56876. onClick: _cache[1] || (_cache[1] = ($event) => $options.openAddress())
  56877. }, [
  56878. vue.createElementVNode("view", { class: "left" }, [
  56879. vue.createElementVNode("view", { class: "name-box" }, [
  56880. vue.createElementVNode(
  56881. "text",
  56882. { class: "text name" },
  56883. vue.toDisplayString($data.address.realName),
  56884. 1
  56885. /* TEXT */
  56886. ),
  56887. $data.address.phone != null ? (vue.openBlock(), vue.createElementBlock(
  56888. "text",
  56889. {
  56890. key: 0,
  56891. class: "text"
  56892. },
  56893. vue.toDisplayString(_ctx.utils.parsePhone($data.address.phone)),
  56894. 1
  56895. /* TEXT */
  56896. )) : vue.createCommentVNode("v-if", true)
  56897. ]),
  56898. vue.createElementVNode(
  56899. "view",
  56900. { class: "address" },
  56901. vue.toDisplayString($data.address.province) + vue.toDisplayString($data.address.city) + vue.toDisplayString($data.address.district) + vue.toDisplayString($data.address.detail),
  56902. 1
  56903. /* TEXT */
  56904. )
  56905. ]),
  56906. vue.createElementVNode("view", { class: "arrow-box" }, [
  56907. vue.createElementVNode("image", {
  56908. src: _imports_0$3,
  56909. mode: ""
  56910. })
  56911. ])
  56912. ])) : vue.createCommentVNode("v-if", true),
  56913. vue.createCommentVNode(" 药品列表 "),
  56914. vue.createElementVNode("view", { class: "goods-list" }, [
  56915. vue.createElementVNode("view", { class: "item" }, [
  56916. vue.createElementVNode("view", { class: "img-box" }, [
  56917. vue.createElementVNode("image", {
  56918. src: $data.package.imgUrl,
  56919. mode: "aspectFill"
  56920. }, null, 8, ["src"])
  56921. ]),
  56922. vue.createElementVNode("view", { class: "info-box" }, [
  56923. vue.createElementVNode("view", null, [
  56924. vue.createElementVNode(
  56925. "view",
  56926. { class: "name-box ellipsis2" },
  56927. vue.toDisplayString($data.package.title),
  56928. 1
  56929. /* TEXT */
  56930. ),
  56931. vue.createElementVNode(
  56932. "view",
  56933. { class: "spec ellipsis2" },
  56934. vue.toDisplayString($data.package.descs),
  56935. 1
  56936. /* TEXT */
  56937. )
  56938. ]),
  56939. vue.createElementVNode("view", { class: "price-num" }, [
  56940. vue.createElementVNode("view", { class: "price" }, [
  56941. vue.createElementVNode("text", { class: "unit" }, "¥"),
  56942. $data.package.payMoney != null ? (vue.openBlock(), vue.createElementBlock(
  56943. "text",
  56944. {
  56945. key: 0,
  56946. class: "num"
  56947. },
  56948. vue.toDisplayString($data.package.payMoney.toFixed(2)),
  56949. 1
  56950. /* TEXT */
  56951. )) : vue.createCommentVNode("v-if", true)
  56952. ])
  56953. ])
  56954. ])
  56955. ]),
  56956. vue.createCommentVNode(" 小计 "),
  56957. vue.createElementVNode("view", { class: "sub-total" }, [
  56958. vue.createElementVNode("text", { class: "label" }, "合计:"),
  56959. vue.createElementVNode("view", { class: "price" }, [
  56960. vue.createElementVNode("text", { class: "unit" }, "¥"),
  56961. $data.package.payMoney != null ? (vue.openBlock(), vue.createElementBlock(
  56962. "text",
  56963. {
  56964. key: 0,
  56965. class: "num"
  56966. },
  56967. vue.toDisplayString($data.package.payMoney.toFixed(2)),
  56968. 1
  56969. /* TEXT */
  56970. )) : vue.createCommentVNode("v-if", true)
  56971. ])
  56972. ])
  56973. ]),
  56974. vue.createElementVNode("view", {
  56975. class: "points",
  56976. onClick: _cache[2] || (_cache[2] = ($event) => $options.openCoupon())
  56977. }, [
  56978. vue.createElementVNode("view", { class: "left" }, [
  56979. vue.createElementVNode("text", { class: "text" }, "优惠券")
  56980. ]),
  56981. vue.createElementVNode("view", { class: "right" }, [
  56982. vue.createElementVNode(
  56983. "text",
  56984. { class: "text" },
  56985. vue.toDisplayString($data.couponText),
  56986. 1
  56987. /* TEXT */
  56988. ),
  56989. vue.createElementVNode("image", {
  56990. src: _imports_1$1,
  56991. mode: ""
  56992. })
  56993. ])
  56994. ]),
  56995. vue.createCommentVNode(" 备注 "),
  56996. vue.createElementVNode("view", { class: "remarks" }, [
  56997. vue.withDirectives(vue.createElementVNode(
  56998. "input",
  56999. {
  57000. type: "text",
  57001. "onUpdate:modelValue": _cache[3] || (_cache[3] = ($event) => $data.form.mark = $event),
  57002. placeholder: "备注留言(选填)",
  57003. "placeholder-class": "input"
  57004. },
  57005. null,
  57006. 512
  57007. /* NEED_PATCH */
  57008. ), [
  57009. [vue.vModelText, $data.form.mark]
  57010. ])
  57011. ])
  57012. ]),
  57013. vue.createCommentVNode(" 底部按钮 "),
  57014. vue.createElementVNode("view", { class: "btn-foot" }, [
  57015. vue.createElementVNode("view", { class: "right" }, [
  57016. vue.createElementVNode("view", { class: "total" }, [
  57017. vue.createElementVNode("text", { class: "label" }, "应付金额:"),
  57018. vue.createElementVNode("view", { class: "price" }, [
  57019. vue.createElementVNode("text", { class: "unit" }, "¥"),
  57020. $data.totalMoney != null ? (vue.openBlock(), vue.createElementBlock(
  57021. "text",
  57022. {
  57023. key: 0,
  57024. class: "num"
  57025. },
  57026. vue.toDisplayString($data.totalMoney.toFixed(2)),
  57027. 1
  57028. /* TEXT */
  57029. )) : vue.createCommentVNode("v-if", true)
  57030. ])
  57031. ]),
  57032. vue.createElementVNode("view", {
  57033. class: "btn",
  57034. onClick: _cache[4] || (_cache[4] = (...args) => $options.submitOrder && $options.submitOrder(...args))
  57035. }, "提交订单")
  57036. ])
  57037. ]),
  57038. vue.createVNode(_component_popupBottom, {
  57039. ref: "popup",
  57040. visible: $data.couponVisible,
  57041. title: " ",
  57042. bgColor: "#f5f5f5",
  57043. radius: "30",
  57044. maxHeight: "60%"
  57045. }, {
  57046. default: vue.withCtx(() => [
  57047. vue.createElementVNode("view", {
  57048. class: "coupon",
  57049. style: { "height": "650rpx" }
  57050. }, [
  57051. $data.couponsList.length > 0 ? (vue.openBlock(), vue.createElementBlock("div", {
  57052. key: 0,
  57053. class: "coupon-list"
  57054. }, [
  57055. (vue.openBlock(true), vue.createElementBlock(
  57056. vue.Fragment,
  57057. null,
  57058. vue.renderList($data.couponsList, (item, index2) => {
  57059. return vue.openBlock(), vue.createElementBlock("div", {
  57060. class: "item acea-row row-center-wrapper",
  57061. key: index2
  57062. }, [
  57063. vue.createElementVNode("div", { class: "money" }, [
  57064. item.status == 0 ? (vue.openBlock(), vue.createElementBlock("image", {
  57065. key: 0,
  57066. class: "img",
  57067. src: _imports_2,
  57068. mode: "widthFix"
  57069. })) : vue.createCommentVNode("v-if", true),
  57070. item.status != 0 ? (vue.openBlock(), vue.createElementBlock("image", {
  57071. key: 1,
  57072. class: "img",
  57073. src: _imports_3,
  57074. mode: "widthFix"
  57075. })) : vue.createCommentVNode("v-if", true),
  57076. vue.createElementVNode("div", { style: { "z-index": "999" } }, [
  57077. vue.createTextVNode(" ¥"),
  57078. vue.createElementVNode(
  57079. "span",
  57080. { class: "num" },
  57081. vue.toDisplayString(item.couponPrice),
  57082. 1
  57083. /* TEXT */
  57084. )
  57085. ]),
  57086. vue.createElementVNode(
  57087. "div",
  57088. { class: "pic-num" },
  57089. "满" + vue.toDisplayString(item.useMinPrice) + "元可用",
  57090. 1
  57091. /* TEXT */
  57092. )
  57093. ]),
  57094. vue.createElementVNode("div", { class: "text" }, [
  57095. vue.createElementVNode(
  57096. "div",
  57097. { class: "condition line1" },
  57098. vue.toDisplayString(item.couponTitle),
  57099. 1
  57100. /* TEXT */
  57101. ),
  57102. vue.createElementVNode("div", { class: "data acea-row row-between-wrapper" }, [
  57103. vue.createElementVNode(
  57104. "div",
  57105. null,
  57106. vue.toDisplayString(item.limitTime) + "到期",
  57107. 1
  57108. /* TEXT */
  57109. ),
  57110. vue.createElementVNode("div", {
  57111. class: "bnt bg-color-red",
  57112. onClick: ($event) => $options.couponSelect(item)
  57113. }, "选择", 8, ["onClick"])
  57114. ])
  57115. ])
  57116. ]);
  57117. }),
  57118. 128
  57119. /* KEYED_FRAGMENT */
  57120. ))
  57121. ])) : vue.createCommentVNode("v-if", true),
  57122. $data.couponsList.length == 0 ? (vue.openBlock(), vue.createElementBlock("view", {
  57123. key: 1,
  57124. class: "no-data-box"
  57125. }, [
  57126. vue.createElementVNode("image", {
  57127. src: _imports_2$2,
  57128. mode: "aspectFit"
  57129. }),
  57130. vue.createElementVNode("view", { class: "empty-title" }, "暂无数据")
  57131. ])) : vue.createCommentVNode("v-if", true)
  57132. ])
  57133. ]),
  57134. _: 1
  57135. /* STABLE */
  57136. }, 8, ["visible"])
  57137. ]);
  57138. }
  57139. const PagesShopConfirmPackageOrder = /* @__PURE__ */ _export_sfc(_sfc_main$4, [["render", _sfc_render$3], ["__scopeId", "data-v-365fa217"], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages_shop/confirmPackageOrder.vue"]]);
  57140. const _imports_0$1 = "/static/images/success.png";
  57141. const _sfc_main$3 = {
  57142. data() {
  57143. return {
  57144. order: null,
  57145. orderCode: "",
  57146. ids: []
  57147. };
  57148. },
  57149. onLoad(option) {
  57150. this.order = JSON.parse(decodeURIComponent(option.order));
  57151. this.orderCode = this.order && this.order.orderCodes ? this.order.orderCodes.join(",") : this.order.orderCode || "";
  57152. this.ids = this.order && this.order.ids ? this.order.ids : this.order.id ? [this.order.id] : [];
  57153. },
  57154. methods: {
  57155. copyOrderSn(text) {
  57156. uni.setClipboardData({
  57157. data: text,
  57158. success: () => {
  57159. uni.showToast({
  57160. title: "内容已成功复制到剪切板",
  57161. icon: "none"
  57162. });
  57163. }
  57164. });
  57165. },
  57166. goOrderDetails(id) {
  57167. if (this.ids && this.ids.length > 1) {
  57168. uni.navigateTo({
  57169. url: "/pages_user/user/storeOrder?status="
  57170. });
  57171. } else {
  57172. uni.redirectTo({
  57173. url: "/pages_user/user/storeOrderDetail?id=" + this.ids[0]
  57174. });
  57175. }
  57176. }
  57177. }
  57178. };
  57179. function _sfc_render$2(_ctx, _cache, $props, $setup, $data, $options) {
  57180. return vue.openBlock(), vue.createElementBlock("view", { class: "content" }, [
  57181. vue.createElementVNode("view", { class: "inner" }, [
  57182. vue.createElementVNode("view", { class: "top" }, [
  57183. vue.createElementVNode("text", { class: "title" }, "支付成功"),
  57184. vue.createElementVNode("image", {
  57185. class: "icon",
  57186. src: _imports_0$1
  57187. }),
  57188. vue.createElementVNode("view", { class: "btn-box" }, [
  57189. vue.createElementVNode("view", {
  57190. class: "btn cancel",
  57191. onClick: _cache[0] || (_cache[0] = ($event) => $options.goOrderDetails($data.order.id))
  57192. }, " 查看订单")
  57193. ])
  57194. ]),
  57195. vue.createCommentVNode(" 订单详情查看 "),
  57196. vue.createElementVNode("view", { class: "order-info" }, [
  57197. vue.createElementVNode("view", { class: "title" }, "订单信息"),
  57198. vue.createElementVNode("view", { class: "item" }, [
  57199. vue.createElementVNode("text", { class: "label" }, "订单编号"),
  57200. vue.createElementVNode("view", { class: "sn-box" }, [
  57201. vue.createElementVNode("view", null, [
  57202. (vue.openBlock(true), vue.createElementBlock(
  57203. vue.Fragment,
  57204. null,
  57205. vue.renderList($data.order.orderCodes, (item) => {
  57206. return vue.openBlock(), vue.createElementBlock(
  57207. "view",
  57208. {
  57209. class: "text",
  57210. key: item
  57211. },
  57212. vue.toDisplayString(item),
  57213. 1
  57214. /* TEXT */
  57215. );
  57216. }),
  57217. 128
  57218. /* KEYED_FRAGMENT */
  57219. ))
  57220. ]),
  57221. vue.createElementVNode("view", {
  57222. class: "copy-btn",
  57223. onClick: _cache[1] || (_cache[1] = ($event) => $options.copyOrderSn($data.orderCode))
  57224. }, "复制")
  57225. ])
  57226. ]),
  57227. vue.createElementVNode("view", { class: "item" }, [
  57228. vue.createElementVNode("text", { class: "label" }, "下单时间"),
  57229. vue.createElementVNode(
  57230. "text",
  57231. { class: "text" },
  57232. vue.toDisplayString($data.order.createTime),
  57233. 1
  57234. /* TEXT */
  57235. )
  57236. ])
  57237. ])
  57238. ])
  57239. ]);
  57240. }
  57241. const PagesShopSuccess = /* @__PURE__ */ _export_sfc(_sfc_main$3, [["render", _sfc_render$2], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages_shop/success.vue"]]);
  57242. const _imports_0 = "/static/images/del1.png";
  57243. const _imports_1 = "/static/images/edit.png";
  57244. const _sfc_main$2 = {
  57245. data() {
  57246. return {
  57247. address: []
  57248. };
  57249. },
  57250. onLoad() {
  57251. this.getAddressList();
  57252. uni.$on("refreshAddress", () => {
  57253. this.getAddressList();
  57254. });
  57255. },
  57256. methods: {
  57257. selectAddress(item) {
  57258. uni.$emit("updateAddress", item);
  57259. uni.navigateBack({
  57260. delta: 1
  57261. });
  57262. },
  57263. editAddress(item) {
  57264. uni.navigateTo({
  57265. url: "./addAddress?type=edit&id=" + item.id
  57266. });
  57267. },
  57268. delAllAddress(item) {
  57269. uni.showModal({
  57270. title: "提示",
  57271. content: "确认删除所有地址吗?",
  57272. showCancel: true,
  57273. cancelText: "取消",
  57274. confirmText: "确定",
  57275. success: (res) => {
  57276. if (res.confirm) {
  57277. var data = {};
  57278. delAllAddress(data).then(
  57279. (res2) => {
  57280. if (res2.code == 200) {
  57281. uni.showToast({
  57282. icon: "success",
  57283. title: "操作成功"
  57284. });
  57285. this.getAddressList();
  57286. } else {
  57287. uni.showToast({
  57288. icon: "none",
  57289. title: "请求失败"
  57290. });
  57291. }
  57292. },
  57293. (rej) => {
  57294. }
  57295. );
  57296. }
  57297. }
  57298. });
  57299. },
  57300. delAddress(item) {
  57301. uni.showModal({
  57302. title: "提示",
  57303. content: "确认删除此地址吗?",
  57304. showCancel: true,
  57305. cancelText: "取消",
  57306. confirmText: "确定",
  57307. success: (res) => {
  57308. if (res.confirm) {
  57309. var data = { id: item.id };
  57310. delAddress(data).then(
  57311. (res2) => {
  57312. if (res2.code == 200) {
  57313. uni.showToast({
  57314. icon: "success",
  57315. title: "操作成功"
  57316. });
  57317. this.getAddressList();
  57318. } else {
  57319. uni.showToast({
  57320. icon: "none",
  57321. title: "请求失败"
  57322. });
  57323. }
  57324. },
  57325. (rej) => {
  57326. }
  57327. );
  57328. }
  57329. }
  57330. });
  57331. },
  57332. getAddressList() {
  57333. uni.showLoading({
  57334. title: "正在加载中"
  57335. });
  57336. getAddressList().then(
  57337. (res) => {
  57338. uni.hideLoading();
  57339. if (res.code == 200) {
  57340. this.address = res.data;
  57341. } else {
  57342. uni.showToast({
  57343. icon: "none",
  57344. title: "请求失败"
  57345. });
  57346. }
  57347. },
  57348. (rej) => {
  57349. }
  57350. );
  57351. },
  57352. // 新建收货地址
  57353. addAdress() {
  57354. uni.navigateTo({
  57355. url: "./addAddress?type=add"
  57356. });
  57357. }
  57358. }
  57359. };
  57360. function _sfc_render$1(_ctx, _cache, $props, $setup, $data, $options) {
  57361. return vue.openBlock(), vue.createElementBlock("view", { class: "content" }, [
  57362. vue.createElementVNode("view", { class: "inner" }, [
  57363. vue.createElementVNode("view", { class: "top" }, [
  57364. vue.createElementVNode("view", {
  57365. class: "del",
  57366. onClick: _cache[0] || (_cache[0] = (...args) => $options.delAllAddress && $options.delAllAddress(...args))
  57367. }, "清空地址")
  57368. ]),
  57369. (vue.openBlock(true), vue.createElementBlock(
  57370. vue.Fragment,
  57371. null,
  57372. vue.renderList($data.address, (item, index2) => {
  57373. return vue.openBlock(), vue.createElementBlock("view", {
  57374. key: index2,
  57375. class: "address-item"
  57376. }, [
  57377. vue.createElementVNode("view", {
  57378. class: "info",
  57379. onClick: ($event) => $options.selectAddress(item)
  57380. }, [
  57381. vue.createElementVNode("view", { class: "title" }, [
  57382. item.isDefault == 1 ? (vue.openBlock(), vue.createElementBlock("view", {
  57383. key: 0,
  57384. class: "tag"
  57385. }, "默认")) : vue.createCommentVNode("v-if", true),
  57386. vue.createTextVNode(
  57387. " " + vue.toDisplayString(item.province) + vue.toDisplayString(item.city) + vue.toDisplayString(item.district) + vue.toDisplayString(item.detail),
  57388. 1
  57389. /* TEXT */
  57390. )
  57391. ]),
  57392. vue.createElementVNode("view", { class: "name-phone" }, [
  57393. vue.createElementVNode(
  57394. "text",
  57395. { class: "text" },
  57396. vue.toDisplayString(item.realName),
  57397. 1
  57398. /* TEXT */
  57399. ),
  57400. vue.createElementVNode(
  57401. "text",
  57402. { class: "text" },
  57403. vue.toDisplayString(_ctx.utils.parsePhone(item.phone)),
  57404. 1
  57405. /* TEXT */
  57406. )
  57407. ])
  57408. ], 8, ["onClick"]),
  57409. vue.createElementVNode("view", { class: "operat-box" }, [
  57410. vue.createElementVNode("image", {
  57411. src: _imports_0,
  57412. mode: "",
  57413. onClick: ($event) => $options.delAddress(item)
  57414. }, null, 8, ["onClick"]),
  57415. vue.createElementVNode("image", {
  57416. src: _imports_1,
  57417. mode: "",
  57418. onClick: ($event) => $options.editAddress(item)
  57419. }, null, 8, ["onClick"])
  57420. ])
  57421. ]);
  57422. }),
  57423. 128
  57424. /* KEYED_FRAGMENT */
  57425. )),
  57426. $data.address.length == 0 ? (vue.openBlock(), vue.createElementBlock("view", {
  57427. key: 0,
  57428. class: "no-data-box",
  57429. onClick: _cache[1] || (_cache[1] = ($event) => $options.getAddressList())
  57430. }, [
  57431. vue.createElementVNode("image", {
  57432. src: _imports_2$2,
  57433. mode: "aspectFit"
  57434. }),
  57435. vue.createElementVNode("view", { class: "empty-title" }, "暂无数据")
  57436. ])) : vue.createCommentVNode("v-if", true)
  57437. ]),
  57438. vue.createElementVNode("view", { class: "btn-box" }, [
  57439. vue.createElementVNode("view", {
  57440. class: "sub-btn",
  57441. onClick: _cache[2] || (_cache[2] = (...args) => $options.addAdress && $options.addAdress(...args))
  57442. }, "新建收货地址")
  57443. ])
  57444. ]);
  57445. }
  57446. const PagesUserAddress = /* @__PURE__ */ _export_sfc(_sfc_main$2, [["render", _sfc_render$1], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages_user/address.vue"]]);
  57447. const _sfc_main$1 = {
  57448. components: {
  57449. EvanSwitch: __easycom_0
  57450. },
  57451. data() {
  57452. return {
  57453. content: null,
  57454. type: null,
  57455. id: null,
  57456. isDefault: false,
  57457. addressList: [[], [], []],
  57458. multiIndex: [0, 0, 0],
  57459. address: [],
  57460. form: {
  57461. realName: null,
  57462. phone: null,
  57463. detail: null,
  57464. address: null,
  57465. isDefault: 0
  57466. }
  57467. };
  57468. },
  57469. onLoad(option) {
  57470. this.type = option.type;
  57471. if (this.type == "edit") {
  57472. uni.setNavigationBarTitle({
  57473. title: "修改收货地址"
  57474. });
  57475. this.id = option.id;
  57476. this.getAddressById();
  57477. } else {
  57478. uni.setNavigationBarTitle({
  57479. title: "新增收货地址"
  57480. });
  57481. }
  57482. this.getCitys();
  57483. },
  57484. methods: {
  57485. parseAddress() {
  57486. if (this.content == null || this.content == "") {
  57487. uni.showToast({ icon: "none", title: "请输入地址信息" });
  57488. return;
  57489. }
  57490. var data = { content: this.content };
  57491. parseAddress(data).then(
  57492. (res) => {
  57493. if (res.code == 200) {
  57494. this.form.realName = res.data.name;
  57495. this.form.phone = res.data.mobile;
  57496. this.form.address = res.data.provinceName + res.data.cityName + res.data.expAreaName;
  57497. this.form.province = res.data.provinceName;
  57498. this.form.city = res.data.cityName;
  57499. this.form.district = res.data.expAreaName;
  57500. this.form.detail = res.data.streetName + res.data.address;
  57501. } else {
  57502. uni.showToast({
  57503. icon: "none",
  57504. title: res.msg
  57505. });
  57506. }
  57507. },
  57508. (rej) => {
  57509. }
  57510. );
  57511. },
  57512. getAddressById() {
  57513. var data = { id: this.id };
  57514. getAddressById(data).then(
  57515. (res) => {
  57516. if (res.code == 200) {
  57517. this.form = res.data;
  57518. this.isDefault = this.form.isDefault == 1 ? true : false;
  57519. this.form.address = this.form.province + this.form.city + this.form.district;
  57520. } else {
  57521. uni.showToast({
  57522. icon: "none",
  57523. title: res.msg
  57524. });
  57525. }
  57526. },
  57527. (rej) => {
  57528. }
  57529. );
  57530. },
  57531. submit() {
  57532. if (this.type == "add") {
  57533. this.addAddress();
  57534. } else if (this.type == "edit") {
  57535. this.editAddress();
  57536. }
  57537. },
  57538. editAddress() {
  57539. this.form.isDefault = this.isDefault ? 1 : 0;
  57540. editAddress(this.form).then(
  57541. (res) => {
  57542. if (res.code == 200) {
  57543. uni.showToast({
  57544. icon: "success",
  57545. title: "操作成功"
  57546. });
  57547. setTimeout(function() {
  57548. uni.$emit("refreshAddress");
  57549. uni.navigateBack({
  57550. delta: 1
  57551. });
  57552. }, 500);
  57553. } else {
  57554. uni.showToast({
  57555. icon: "none",
  57556. title: res.msg
  57557. });
  57558. }
  57559. },
  57560. (rej) => {
  57561. }
  57562. );
  57563. },
  57564. addAddress() {
  57565. this.form.isDefault = this.isDefault ? 1 : 0;
  57566. addAddress(this.form).then(
  57567. (res) => {
  57568. if (res.code == 200) {
  57569. uni.showToast({
  57570. icon: "success",
  57571. title: "操作成功"
  57572. });
  57573. setTimeout(function() {
  57574. uni.$emit("refreshAddress");
  57575. uni.navigateBack({
  57576. delta: 1
  57577. });
  57578. }, 500);
  57579. } else {
  57580. uni.showToast({
  57581. icon: "none",
  57582. title: res.msg
  57583. });
  57584. }
  57585. },
  57586. (rej) => {
  57587. }
  57588. );
  57589. },
  57590. // 地区选择
  57591. pickerChange(e2) {
  57592. this.multiIndex = e2.detail.value;
  57593. this.form.address = this.addressList[0][this.multiIndex[0]].n + this.addressList[1][this.multiIndex[1]].n + this.addressList[2][this.multiIndex[2]].n;
  57594. this.form.province = this.addressList[0][this.multiIndex[0]].n;
  57595. this.form.city = this.addressList[1][this.multiIndex[1]].n;
  57596. this.form.district = this.addressList[2][this.multiIndex[2]].n;
  57597. this.form.cityId = this.addressList[1][this.multiIndex[1]].v;
  57598. },
  57599. pickerColumnchange(e2) {
  57600. if (e2.detail.column === 0) {
  57601. this.multiIndex[0] = e2.detail.value;
  57602. this.addressList[1] = this.address[this.multiIndex[0]].c;
  57603. this.addressList[2] = this.address[this.multiIndex[0]].c[0].c;
  57604. this.multiIndex.splice(1, 1, 0);
  57605. this.multiIndex.splice(2, 1, 0);
  57606. }
  57607. if (e2.detail.column === 1) {
  57608. this.multiIndex[1] = e2.detail.value;
  57609. this.addressList[2] = this.address[this.multiIndex[0]].c[this.multiIndex[1]].c;
  57610. this.multiIndex.splice(2, 1, 0);
  57611. }
  57612. if (e2.detail.column === 2) {
  57613. this.multiIndex[2] = e2.detail.value;
  57614. }
  57615. },
  57616. getCitys() {
  57617. getCitys().then(
  57618. (res) => {
  57619. if (res.code == 200) {
  57620. this.address = res.data;
  57621. for (var i2 = 0; i2 < this.address.length; i2++) {
  57622. this.addressList[0].push(this.address[i2]);
  57623. }
  57624. for (var i2 = 0; i2 < this.address[0].c.length; i2++) {
  57625. this.addressList[1].push(this.address[0].c[i2]);
  57626. }
  57627. for (var i2 = 0; i2 < this.address[0].c[0].c.length; i2++) {
  57628. this.addressList[2].push(this.address[0].c[0].c[i2]);
  57629. }
  57630. } else {
  57631. uni.showToast({
  57632. icon: "none",
  57633. title: "请求失败"
  57634. });
  57635. }
  57636. },
  57637. (rej) => {
  57638. }
  57639. );
  57640. }
  57641. }
  57642. };
  57643. function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  57644. const _component_evan_switch = resolveEasycom(vue.resolveDynamicComponent("evan-switch"), __easycom_0);
  57645. return vue.openBlock(), vue.createElementBlock("view", { class: "content" }, [
  57646. vue.createElementVNode("view", { class: "inner" }, [
  57647. vue.createElementVNode("view", { class: "address-box" }, [
  57648. vue.withDirectives(vue.createElementVNode(
  57649. "textarea",
  57650. {
  57651. class: "textarea",
  57652. "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => $data.content = $event),
  57653. placeholder: "请粘贴或输入文本,点击'识别'自动识别姓名、电话、地址,格式:深圳市龙岗区坂田街道长坑路西2巷2号202 黄大大 18888888888"
  57654. },
  57655. null,
  57656. 512
  57657. /* NEED_PATCH */
  57658. ), [
  57659. [vue.vModelText, $data.content]
  57660. ]),
  57661. vue.createElementVNode("view", { class: "btns" }, [
  57662. vue.createElementVNode("view", {
  57663. class: "btn parse",
  57664. onClick: _cache[1] || (_cache[1] = ($event) => $options.parseAddress())
  57665. }, "识别")
  57666. ])
  57667. ]),
  57668. vue.createElementVNode("view", { class: "form-box" }, [
  57669. vue.createElementVNode("view", { class: "form-item" }, [
  57670. vue.createElementVNode("text", { class: "label" }, "联系人"),
  57671. vue.withDirectives(vue.createElementVNode(
  57672. "input",
  57673. {
  57674. type: "text",
  57675. "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => $data.form.realName = $event),
  57676. maxlength: "10",
  57677. placeholder: "姓名",
  57678. class: "form-input"
  57679. },
  57680. null,
  57681. 512
  57682. /* NEED_PATCH */
  57683. ), [
  57684. [vue.vModelText, $data.form.realName]
  57685. ])
  57686. ]),
  57687. vue.createElementVNode("view", { class: "form-item" }, [
  57688. vue.createElementVNode("text", { class: "label" }, "手机号"),
  57689. vue.withDirectives(vue.createElementVNode(
  57690. "input",
  57691. {
  57692. type: "number",
  57693. "onUpdate:modelValue": _cache[3] || (_cache[3] = ($event) => $data.form.phone = $event),
  57694. maxlength: "11",
  57695. placeholder: "手机号",
  57696. class: "form-input"
  57697. },
  57698. null,
  57699. 512
  57700. /* NEED_PATCH */
  57701. ), [
  57702. [vue.vModelText, $data.form.phone]
  57703. ])
  57704. ]),
  57705. vue.createElementVNode("view", { class: "form-item" }, [
  57706. vue.createElementVNode("text", { class: "label" }, "所在地区"),
  57707. vue.createElementVNode("picker", {
  57708. value: $data.multiIndex,
  57709. class: "birth-picker",
  57710. mode: "multiSelector",
  57711. "range-key": "n",
  57712. range: $data.addressList,
  57713. onChange: _cache[5] || (_cache[5] = (...args) => $options.pickerChange && $options.pickerChange(...args)),
  57714. onColumnchange: _cache[6] || (_cache[6] = (...args) => $options.pickerColumnchange && $options.pickerColumnchange(...args))
  57715. }, [
  57716. vue.createElementVNode("view", { class: "right-box" }, [
  57717. vue.createElementVNode("view", { class: "input-box" }, [
  57718. vue.withDirectives(vue.createElementVNode(
  57719. "input",
  57720. {
  57721. type: "text",
  57722. "onUpdate:modelValue": _cache[4] || (_cache[4] = ($event) => $data.form.address = $event),
  57723. placeholder: "请选择",
  57724. class: "form-input",
  57725. disabled: "disabled"
  57726. },
  57727. null,
  57728. 512
  57729. /* NEED_PATCH */
  57730. ), [
  57731. [vue.vModelText, $data.form.address]
  57732. ])
  57733. ]),
  57734. vue.createElementVNode("image", {
  57735. class: "arrow",
  57736. src: _imports_0$3,
  57737. mode: ""
  57738. })
  57739. ])
  57740. ], 40, ["value", "range"])
  57741. ]),
  57742. vue.createElementVNode("view", { class: "form-item" }, [
  57743. vue.createElementVNode("text", { class: "label" }, "详细地址"),
  57744. vue.withDirectives(vue.createElementVNode(
  57745. "textarea",
  57746. {
  57747. class: "form-textarea",
  57748. "onUpdate:modelValue": _cache[7] || (_cache[7] = ($event) => $data.form.detail = $event),
  57749. placeholder: "请输入详细地址"
  57750. },
  57751. null,
  57752. 512
  57753. /* NEED_PATCH */
  57754. ), [
  57755. [vue.vModelText, $data.form.detail]
  57756. ])
  57757. ])
  57758. ]),
  57759. vue.createCommentVNode(" 设为默认地址 "),
  57760. vue.createElementVNode("view", { class: "setting-box" }, [
  57761. vue.createElementVNode("text", { class: "label" }, "设为默认地址"),
  57762. vue.createVNode(_component_evan_switch, {
  57763. modelValue: $data.isDefault,
  57764. "onUpdate:modelValue": _cache[8] || (_cache[8] = ($event) => $data.isDefault = $event),
  57765. activeColor: "#0bb3f2",
  57766. inactiveColor: "rgba(0, 0, 0, 0.1)"
  57767. }, null, 8, ["modelValue"])
  57768. ])
  57769. ]),
  57770. vue.createElementVNode("view", { class: "btn-box" }, [
  57771. vue.createElementVNode("view", {
  57772. class: "sub-btn",
  57773. onClick: _cache[9] || (_cache[9] = ($event) => $options.submit())
  57774. }, "保存地址")
  57775. ])
  57776. ]);
  57777. }
  57778. const PagesUserAddAddress = /* @__PURE__ */ _export_sfc(_sfc_main$1, [["render", _sfc_render], ["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/pages_user/addAddress.vue"]]);
  57779. __definePage("pages/home/index", PagesHomeIndex);
  57780. __definePage("pages/home/living", PagesHomeLiving);
  57781. __definePage("pages/user/index", PagesUserIndex);
  57782. __definePage("pages/list/index", PagesListIndex);
  57783. __definePage("pages/home/live", PagesHomeLive);
  57784. __definePage("pages/games/index", PagesGamesIndex);
  57785. __definePage("pages/login/login", PagesLoginLogin);
  57786. __definePage("pages_shop/cart", PagesShopCart);
  57787. __definePage("pages_shop/goods", PagesShopGoods);
  57788. __definePage("pages_shop/store", PagesShopStore);
  57789. __definePage("pages_shop/order", PagesShopOrder);
  57790. __definePage("pages_shop/confirmCreateOrder", PagesShopConfirmCreateOrder);
  57791. __definePage("pages_shop/paymentOrder", PagesShopPaymentOrder);
  57792. __definePage("pages_shop/confirmPackageOrder", PagesShopConfirmPackageOrder);
  57793. __definePage("pages_shop/success", PagesShopSuccess);
  57794. __definePage("pages_user/address", PagesUserAddress);
  57795. __definePage("pages_user/addAddress", PagesUserAddAddress);
  57796. const _sfc_main = {
  57797. onLaunch: function(options) {
  57798. const store2 = useStore();
  57799. let parent_id;
  57800. if (options.query && options.query.scene) {
  57801. parent_id = decodeURIComponent(options.query.scene).split("=")[1];
  57802. } else if (options.query && options.query.parent_id) {
  57803. parent_id = options.query.parent_id;
  57804. }
  57805. storage.set("PARENT_ID", parent_id, 30 * 86400 * 3);
  57806. store2.commit("M_PARENT_ID", parent_id);
  57807. },
  57808. onShow: function() {
  57809. formatAppLog("log", "at App.vue:25", "App Show");
  57810. },
  57811. onLoad() {
  57812. formatAppLog("log", "at App.vue:29", "App Load");
  57813. },
  57814. onHide: function() {
  57815. formatAppLog("log", "at App.vue:32", "App Hide");
  57816. },
  57817. methods: {
  57818. /**
  57819. * 小程序主动更新
  57820. */
  57821. updateManager() {
  57822. const updateManager = uni.getUpdateManager();
  57823. updateManager.onCheckForUpdate((res) => {
  57824. });
  57825. updateManager.onUpdateReady(() => {
  57826. uni.showModal({
  57827. title: "更新提示",
  57828. content: "新版本已经准备好,即将重启应用",
  57829. showCancel: false,
  57830. success(res) {
  57831. if (res.confirm) {
  57832. updateManager.applyUpdate();
  57833. }
  57834. }
  57835. });
  57836. });
  57837. updateManager.onUpdateFailed(() => {
  57838. uni.showModal({
  57839. title: "更新提示",
  57840. content: "新版本下载失败",
  57841. showCancel: false
  57842. });
  57843. });
  57844. }
  57845. }
  57846. };
  57847. const App = /* @__PURE__ */ _export_sfc(_sfc_main, [["__file", "C:/Users/Administrator/Desktop/项目/直播/liveH5-v3/App.vue"]]);
  57848. const { toString } = Object.prototype;
  57849. function isArray(val) {
  57850. return toString.call(val) === "[object Array]";
  57851. }
  57852. function isObject(val) {
  57853. return val !== null && typeof val === "object";
  57854. }
  57855. function isDate(val) {
  57856. return toString.call(val) === "[object Date]";
  57857. }
  57858. function isURLSearchParams(val) {
  57859. return typeof URLSearchParams !== "undefined" && val instanceof URLSearchParams;
  57860. }
  57861. function forEach(obj, fn) {
  57862. if (obj === null || typeof obj === "undefined") {
  57863. return;
  57864. }
  57865. if (typeof obj !== "object") {
  57866. obj = [obj];
  57867. }
  57868. if (isArray(obj)) {
  57869. for (let i2 = 0, l2 = obj.length; i2 < l2; i2++) {
  57870. fn.call(null, obj[i2], i2, obj);
  57871. }
  57872. } else {
  57873. for (const key in obj) {
  57874. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  57875. fn.call(null, obj[key], key, obj);
  57876. }
  57877. }
  57878. }
  57879. }
  57880. function isPlainObject(obj) {
  57881. return Object.prototype.toString.call(obj) === "[object Object]";
  57882. }
  57883. function deepMerge() {
  57884. const result = {};
  57885. function assignValue(val, key) {
  57886. if (typeof result[key] === "object" && typeof val === "object") {
  57887. result[key] = deepMerge(result[key], val);
  57888. } else if (typeof val === "object") {
  57889. result[key] = deepMerge({}, val);
  57890. } else {
  57891. result[key] = val;
  57892. }
  57893. }
  57894. for (let i2 = 0, l2 = arguments.length; i2 < l2; i2++) {
  57895. forEach(arguments[i2], assignValue);
  57896. }
  57897. return result;
  57898. }
  57899. function isUndefined(val) {
  57900. return typeof val === "undefined";
  57901. }
  57902. function encode(val) {
  57903. return encodeURIComponent(val).replace(/%40/gi, "@").replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
  57904. }
  57905. function buildURL(url2, params) {
  57906. if (!params) {
  57907. return url2;
  57908. }
  57909. let serializedParams;
  57910. if (isURLSearchParams(params)) {
  57911. serializedParams = params.toString();
  57912. } else {
  57913. const parts = [];
  57914. forEach(params, (val, key) => {
  57915. if (val === null || typeof val === "undefined") {
  57916. return;
  57917. }
  57918. if (isArray(val)) {
  57919. key = `${key}[]`;
  57920. } else {
  57921. val = [val];
  57922. }
  57923. forEach(val, (v2) => {
  57924. if (isDate(v2)) {
  57925. v2 = v2.toISOString();
  57926. } else if (isObject(v2)) {
  57927. v2 = JSON.stringify(v2);
  57928. }
  57929. parts.push(`${encode(key)}=${encode(v2)}`);
  57930. });
  57931. });
  57932. serializedParams = parts.join("&");
  57933. }
  57934. if (serializedParams) {
  57935. const hashmarkIndex = url2.indexOf("#");
  57936. if (hashmarkIndex !== -1) {
  57937. url2 = url2.slice(0, hashmarkIndex);
  57938. }
  57939. url2 += (url2.indexOf("?") === -1 ? "?" : "&") + serializedParams;
  57940. }
  57941. return url2;
  57942. }
  57943. function isAbsoluteURL(url2) {
  57944. return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url2);
  57945. }
  57946. function combineURLs(baseURL, relativeURL) {
  57947. return relativeURL ? `${baseURL.replace(/\/+$/, "")}/${relativeURL.replace(/^\/+/, "")}` : baseURL;
  57948. }
  57949. function buildFullPath(baseURL, requestedURL) {
  57950. if (baseURL && !isAbsoluteURL(requestedURL)) {
  57951. return combineURLs(baseURL, requestedURL);
  57952. }
  57953. return requestedURL;
  57954. }
  57955. function settle(resolve, reject, response) {
  57956. const { validateStatus } = response.config;
  57957. const status2 = response.statusCode;
  57958. if (status2 && (!validateStatus || validateStatus(status2))) {
  57959. resolve(response);
  57960. } else {
  57961. reject(response);
  57962. }
  57963. }
  57964. const mergeKeys$1 = (keys, config2) => {
  57965. const config3 = {};
  57966. keys.forEach((prop) => {
  57967. if (!isUndefined(config2[prop])) {
  57968. config3[prop] = config2[prop];
  57969. }
  57970. });
  57971. return config3;
  57972. };
  57973. const adapter = (config2) => new Promise((resolve, reject) => {
  57974. const fullPath = buildURL(buildFullPath(config2.baseURL, config2.url), config2.params);
  57975. const _config = {
  57976. url: fullPath,
  57977. header: config2.header,
  57978. complete: (response) => {
  57979. config2.fullPath = fullPath;
  57980. response.config = config2;
  57981. try {
  57982. if (typeof response.data === "string") {
  57983. response.data = JSON.parse(response.data);
  57984. }
  57985. } catch (e2) {
  57986. }
  57987. settle(resolve, reject, response);
  57988. }
  57989. };
  57990. let requestTask;
  57991. if (config2.method === "UPLOAD") {
  57992. delete _config.header["content-type"];
  57993. delete _config.header["Content-Type"];
  57994. const otherConfig = {
  57995. filePath: config2.filePath,
  57996. name: config2.name
  57997. };
  57998. const optionalKeys = [
  57999. "files",
  58000. "timeout",
  58001. "formData"
  58002. ];
  58003. requestTask = uni.uploadFile({ ..._config, ...otherConfig, ...mergeKeys$1(optionalKeys, config2) });
  58004. } else if (config2.method === "DOWNLOAD") {
  58005. if (!isUndefined(config2.timeout)) {
  58006. _config.timeout = config2.timeout;
  58007. }
  58008. requestTask = uni.downloadFile(_config);
  58009. } else {
  58010. const optionalKeys = [
  58011. "data",
  58012. "method",
  58013. "timeout",
  58014. "dataType",
  58015. "responseType",
  58016. "sslVerify",
  58017. "firstIpv4"
  58018. ];
  58019. requestTask = uni.request({ ..._config, ...mergeKeys$1(optionalKeys, config2) });
  58020. }
  58021. if (config2.getTask) {
  58022. config2.getTask(requestTask, config2);
  58023. }
  58024. });
  58025. const dispatchRequest = (config2) => adapter(config2);
  58026. function InterceptorManager() {
  58027. this.handlers = [];
  58028. }
  58029. InterceptorManager.prototype.use = function use(fulfilled, rejected) {
  58030. this.handlers.push({
  58031. fulfilled,
  58032. rejected
  58033. });
  58034. return this.handlers.length - 1;
  58035. };
  58036. InterceptorManager.prototype.eject = function eject(id) {
  58037. if (this.handlers[id]) {
  58038. this.handlers[id] = null;
  58039. }
  58040. };
  58041. InterceptorManager.prototype.forEach = function forEach2(fn) {
  58042. this.handlers.forEach((h2) => {
  58043. if (h2 !== null) {
  58044. fn(h2);
  58045. }
  58046. });
  58047. };
  58048. const mergeKeys = (keys, globalsConfig, config2) => {
  58049. const config3 = {};
  58050. keys.forEach((prop) => {
  58051. if (!isUndefined(config2[prop])) {
  58052. config3[prop] = config2[prop];
  58053. } else if (!isUndefined(globalsConfig[prop])) {
  58054. config3[prop] = globalsConfig[prop];
  58055. }
  58056. });
  58057. return config3;
  58058. };
  58059. const mergeConfig = (globalsConfig, config2 = {}) => {
  58060. const method = config2.method || globalsConfig.method || "GET";
  58061. let config3 = {
  58062. baseURL: globalsConfig.baseURL || "",
  58063. method,
  58064. url: config2.url || "",
  58065. params: config2.params || {},
  58066. custom: { ...globalsConfig.custom || {}, ...config2.custom || {} },
  58067. header: deepMerge(globalsConfig.header || {}, config2.header || {})
  58068. };
  58069. const defaultToConfig2Keys = ["getTask", "validateStatus"];
  58070. config3 = { ...config3, ...mergeKeys(defaultToConfig2Keys, globalsConfig, config2) };
  58071. if (method === "DOWNLOAD") {
  58072. if (!isUndefined(config2.timeout)) {
  58073. config3.timeout = config2.timeout;
  58074. } else if (!isUndefined(globalsConfig.timeout)) {
  58075. config3.timeout = globalsConfig.timeout;
  58076. }
  58077. } else if (method === "UPLOAD") {
  58078. delete config3.header["content-type"];
  58079. delete config3.header["Content-Type"];
  58080. const uploadKeys = [
  58081. "files",
  58082. "filePath",
  58083. "name",
  58084. "timeout",
  58085. "formData"
  58086. ];
  58087. uploadKeys.forEach((prop) => {
  58088. if (!isUndefined(config2[prop])) {
  58089. config3[prop] = config2[prop];
  58090. }
  58091. });
  58092. if (isUndefined(config3.timeout) && !isUndefined(globalsConfig.timeout)) {
  58093. config3.timeout = globalsConfig.timeout;
  58094. }
  58095. } else {
  58096. const defaultsKeys = [
  58097. "data",
  58098. "timeout",
  58099. "dataType",
  58100. "responseType",
  58101. "sslVerify",
  58102. "firstIpv4"
  58103. ];
  58104. config3 = { ...config3, ...mergeKeys(defaultsKeys, globalsConfig, config2) };
  58105. }
  58106. return config3;
  58107. };
  58108. const defaults = {
  58109. baseURL: "",
  58110. header: {},
  58111. method: "GET",
  58112. dataType: "json",
  58113. responseType: "text",
  58114. custom: {},
  58115. timeout: 6e4,
  58116. sslVerify: true,
  58117. firstIpv4: false,
  58118. validateStatus: function validateStatus(status2) {
  58119. return status2 >= 200 && status2 < 300;
  58120. }
  58121. };
  58122. var clone = function() {
  58123. function _instanceof(obj, type) {
  58124. return type != null && obj instanceof type;
  58125. }
  58126. var nativeMap;
  58127. try {
  58128. nativeMap = Map;
  58129. } catch (_2) {
  58130. nativeMap = function() {
  58131. };
  58132. }
  58133. var nativeSet;
  58134. try {
  58135. nativeSet = Set;
  58136. } catch (_2) {
  58137. nativeSet = function() {
  58138. };
  58139. }
  58140. var nativePromise;
  58141. try {
  58142. nativePromise = Promise;
  58143. } catch (_2) {
  58144. nativePromise = function() {
  58145. };
  58146. }
  58147. function clone2(parent, circular, depth, prototype, includeNonEnumerable) {
  58148. if (typeof circular === "object") {
  58149. depth = circular.depth;
  58150. prototype = circular.prototype;
  58151. includeNonEnumerable = circular.includeNonEnumerable;
  58152. circular = circular.circular;
  58153. }
  58154. var allParents = [];
  58155. var allChildren = [];
  58156. var useBuffer = typeof Buffer != "undefined";
  58157. if (typeof circular == "undefined")
  58158. circular = true;
  58159. if (typeof depth == "undefined")
  58160. depth = Infinity;
  58161. function _clone(parent2, depth2) {
  58162. if (parent2 === null)
  58163. return null;
  58164. if (depth2 === 0)
  58165. return parent2;
  58166. var child;
  58167. var proto;
  58168. if (typeof parent2 != "object") {
  58169. return parent2;
  58170. }
  58171. if (_instanceof(parent2, nativeMap)) {
  58172. child = new nativeMap();
  58173. } else if (_instanceof(parent2, nativeSet)) {
  58174. child = new nativeSet();
  58175. } else if (_instanceof(parent2, nativePromise)) {
  58176. child = new nativePromise(function(resolve, reject) {
  58177. parent2.then(function(value2) {
  58178. resolve(_clone(value2, depth2 - 1));
  58179. }, function(err) {
  58180. reject(_clone(err, depth2 - 1));
  58181. });
  58182. });
  58183. } else if (clone2.__isArray(parent2)) {
  58184. child = [];
  58185. } else if (clone2.__isRegExp(parent2)) {
  58186. child = new RegExp(parent2.source, __getRegExpFlags(parent2));
  58187. if (parent2.lastIndex)
  58188. child.lastIndex = parent2.lastIndex;
  58189. } else if (clone2.__isDate(parent2)) {
  58190. child = new Date(parent2.getTime());
  58191. } else if (useBuffer && Buffer.isBuffer(parent2)) {
  58192. if (Buffer.from) {
  58193. child = Buffer.from(parent2);
  58194. } else {
  58195. child = new Buffer(parent2.length);
  58196. parent2.copy(child);
  58197. }
  58198. return child;
  58199. } else if (_instanceof(parent2, Error)) {
  58200. child = Object.create(parent2);
  58201. } else {
  58202. if (typeof prototype == "undefined") {
  58203. proto = Object.getPrototypeOf(parent2);
  58204. child = Object.create(proto);
  58205. } else {
  58206. child = Object.create(prototype);
  58207. proto = prototype;
  58208. }
  58209. }
  58210. if (circular) {
  58211. var index2 = allParents.indexOf(parent2);
  58212. if (index2 != -1) {
  58213. return allChildren[index2];
  58214. }
  58215. allParents.push(parent2);
  58216. allChildren.push(child);
  58217. }
  58218. if (_instanceof(parent2, nativeMap)) {
  58219. parent2.forEach(function(value2, key) {
  58220. var keyChild = _clone(key, depth2 - 1);
  58221. var valueChild = _clone(value2, depth2 - 1);
  58222. child.set(keyChild, valueChild);
  58223. });
  58224. }
  58225. if (_instanceof(parent2, nativeSet)) {
  58226. parent2.forEach(function(value2) {
  58227. var entryChild = _clone(value2, depth2 - 1);
  58228. child.add(entryChild);
  58229. });
  58230. }
  58231. for (var i2 in parent2) {
  58232. var attrs = Object.getOwnPropertyDescriptor(parent2, i2);
  58233. if (attrs) {
  58234. child[i2] = _clone(parent2[i2], depth2 - 1);
  58235. }
  58236. try {
  58237. var objProperty = Object.getOwnPropertyDescriptor(parent2, i2);
  58238. if (objProperty.set === "undefined") {
  58239. continue;
  58240. }
  58241. child[i2] = _clone(parent2[i2], depth2 - 1);
  58242. } catch (e2) {
  58243. if (e2 instanceof TypeError) {
  58244. continue;
  58245. } else if (e2 instanceof ReferenceError) {
  58246. continue;
  58247. }
  58248. }
  58249. }
  58250. if (Object.getOwnPropertySymbols) {
  58251. var symbols = Object.getOwnPropertySymbols(parent2);
  58252. for (var i2 = 0; i2 < symbols.length; i2++) {
  58253. var symbol = symbols[i2];
  58254. var descriptor = Object.getOwnPropertyDescriptor(parent2, symbol);
  58255. if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
  58256. continue;
  58257. }
  58258. child[symbol] = _clone(parent2[symbol], depth2 - 1);
  58259. Object.defineProperty(child, symbol, descriptor);
  58260. }
  58261. }
  58262. if (includeNonEnumerable) {
  58263. var allPropertyNames = Object.getOwnPropertyNames(parent2);
  58264. for (var i2 = 0; i2 < allPropertyNames.length; i2++) {
  58265. var propertyName = allPropertyNames[i2];
  58266. var descriptor = Object.getOwnPropertyDescriptor(parent2, propertyName);
  58267. if (descriptor && descriptor.enumerable) {
  58268. continue;
  58269. }
  58270. child[propertyName] = _clone(parent2[propertyName], depth2 - 1);
  58271. Object.defineProperty(child, propertyName, descriptor);
  58272. }
  58273. }
  58274. return child;
  58275. }
  58276. return _clone(parent, depth);
  58277. }
  58278. clone2.clonePrototype = function clonePrototype(parent) {
  58279. if (parent === null)
  58280. return null;
  58281. var c2 = function() {
  58282. };
  58283. c2.prototype = parent;
  58284. return new c2();
  58285. };
  58286. function __objToStr(o2) {
  58287. return Object.prototype.toString.call(o2);
  58288. }
  58289. clone2.__objToStr = __objToStr;
  58290. function __isDate(o2) {
  58291. return typeof o2 === "object" && __objToStr(o2) === "[object Date]";
  58292. }
  58293. clone2.__isDate = __isDate;
  58294. function __isArray(o2) {
  58295. return typeof o2 === "object" && __objToStr(o2) === "[object Array]";
  58296. }
  58297. clone2.__isArray = __isArray;
  58298. function __isRegExp(o2) {
  58299. return typeof o2 === "object" && __objToStr(o2) === "[object RegExp]";
  58300. }
  58301. clone2.__isRegExp = __isRegExp;
  58302. function __getRegExpFlags(re2) {
  58303. var flags = "";
  58304. if (re2.global)
  58305. flags += "g";
  58306. if (re2.ignoreCase)
  58307. flags += "i";
  58308. if (re2.multiline)
  58309. flags += "m";
  58310. return flags;
  58311. }
  58312. clone2.__getRegExpFlags = __getRegExpFlags;
  58313. return clone2;
  58314. }();
  58315. class Request {
  58316. /**
  58317. * @param {Object} arg - 全局配置
  58318. * @param {String} arg.baseURL - 全局根路径
  58319. * @param {Object} arg.header - 全局header
  58320. * @param {String} arg.method = [GET|POST|PUT|DELETE|CONNECT|HEAD|OPTIONS|TRACE] - 全局默认请求方式
  58321. * @param {String} arg.dataType = [json] - 全局默认的dataType
  58322. * @param {String} arg.responseType = [text|arraybuffer] - 全局默认的responseType。支付宝小程序不支持
  58323. * @param {Object} arg.custom - 全局默认的自定义参数
  58324. * @param {Number} arg.timeout - 全局默认的超时时间,单位 ms。默认60000。H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)、微信小程序(2.10.0)、支付宝小程序
  58325. * @param {Boolean} arg.sslVerify - 全局默认的是否验证 ssl 证书。默认true.仅App安卓端支持(HBuilderX 2.3.3+)
  58326. * @param {Boolean} arg.withCredentials - 全局默认的跨域请求时是否携带凭证(cookies)。默认false。仅H5支持(HBuilderX 2.6.15+)
  58327. * @param {Boolean} arg.firstIpv4 - 全DNS解析时优先使用ipv4。默认false。仅 App-Android 支持 (HBuilderX 2.8.0+)
  58328. * @param {Function(statusCode):Boolean} arg.validateStatus - 全局默认的自定义验证器。默认statusCode >= 200 && statusCode < 300
  58329. */
  58330. constructor(arg = {}) {
  58331. if (!isPlainObject(arg)) {
  58332. arg = {};
  58333. formatAppLog("warn", "at uni_modules/uview-plus/libs/luch-request/core/Request.js:39", "设置全局参数必须接收一个Object");
  58334. }
  58335. this.config = clone({ ...defaults, ...arg });
  58336. this.interceptors = {
  58337. request: new InterceptorManager(),
  58338. response: new InterceptorManager()
  58339. };
  58340. }
  58341. /**
  58342. * @Function
  58343. * @param {Request~setConfigCallback} f - 设置全局默认配置
  58344. */
  58345. setConfig(f2) {
  58346. this.config = f2(this.config);
  58347. }
  58348. middleware(config2) {
  58349. config2 = mergeConfig(this.config, config2);
  58350. const chain = [dispatchRequest, void 0];
  58351. let promise2 = Promise.resolve(config2);
  58352. this.interceptors.request.forEach((interceptor) => {
  58353. chain.unshift(interceptor.fulfilled, interceptor.rejected);
  58354. });
  58355. this.interceptors.response.forEach((interceptor) => {
  58356. chain.push(interceptor.fulfilled, interceptor.rejected);
  58357. });
  58358. while (chain.length) {
  58359. promise2 = promise2.then(chain.shift(), chain.shift());
  58360. }
  58361. return promise2;
  58362. }
  58363. /**
  58364. * @Function
  58365. * @param {Object} config - 请求配置项
  58366. * @prop {String} options.url - 请求路径
  58367. * @prop {Object} options.data - 请求参数
  58368. * @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] - 响应的数据类型
  58369. * @prop {Object} [options.dataType = config.dataType] - 如果设为 json,会尝试对返回的数据做一次 JSON.parse
  58370. * @prop {Object} [options.header = config.header] - 请求header
  58371. * @prop {Object} [options.method = config.method] - 请求方法
  58372. * @returns {Promise<unknown>}
  58373. */
  58374. request(config2 = {}) {
  58375. return this.middleware(config2);
  58376. }
  58377. get(url2, options = {}) {
  58378. return this.middleware({
  58379. url: url2,
  58380. method: "GET",
  58381. ...options
  58382. });
  58383. }
  58384. post(url2, data, options = {}) {
  58385. return this.middleware({
  58386. url: url2,
  58387. data,
  58388. method: "POST",
  58389. ...options
  58390. });
  58391. }
  58392. put(url2, data, options = {}) {
  58393. return this.middleware({
  58394. url: url2,
  58395. data,
  58396. method: "PUT",
  58397. ...options
  58398. });
  58399. }
  58400. delete(url2, data, options = {}) {
  58401. return this.middleware({
  58402. url: url2,
  58403. data,
  58404. method: "DELETE",
  58405. ...options
  58406. });
  58407. }
  58408. options(url2, data, options = {}) {
  58409. return this.middleware({
  58410. url: url2,
  58411. data,
  58412. method: "OPTIONS",
  58413. ...options
  58414. });
  58415. }
  58416. upload(url2, config2 = {}) {
  58417. config2.url = url2;
  58418. config2.method = "UPLOAD";
  58419. return this.middleware(config2);
  58420. }
  58421. download(url2, config2 = {}) {
  58422. config2.url = url2;
  58423. config2.method = "DOWNLOAD";
  58424. return this.middleware(config2);
  58425. }
  58426. }
  58427. function colorGradient(startColor = "rgb(0, 0, 0)", endColor = "rgb(255, 255, 255)", step = 10) {
  58428. const startRGB = hexToRgb(startColor, false);
  58429. const startR = startRGB[0];
  58430. const startG = startRGB[1];
  58431. const startB = startRGB[2];
  58432. const endRGB = hexToRgb(endColor, false);
  58433. const endR = endRGB[0];
  58434. const endG = endRGB[1];
  58435. const endB = endRGB[2];
  58436. const sR = (endR - startR) / step;
  58437. const sG = (endG - startG) / step;
  58438. const sB = (endB - startB) / step;
  58439. const colorArr = [];
  58440. for (let i2 = 0; i2 < step; i2++) {
  58441. let hex = rgbToHex(`rgb(${Math.round(sR * i2 + startR)},${Math.round(sG * i2 + startG)},${Math.round(sB * i2 + startB)})`);
  58442. if (i2 === 0)
  58443. hex = rgbToHex(startColor);
  58444. if (i2 === step - 1)
  58445. hex = rgbToHex(endColor);
  58446. colorArr.push(hex);
  58447. }
  58448. return colorArr;
  58449. }
  58450. function hexToRgb(sColor, str = true) {
  58451. const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  58452. sColor = String(sColor).toLowerCase();
  58453. if (sColor && reg.test(sColor)) {
  58454. if (sColor.length === 4) {
  58455. let sColorNew = "#";
  58456. for (let i2 = 1; i2 < 4; i2 += 1) {
  58457. sColorNew += sColor.slice(i2, i2 + 1).concat(sColor.slice(i2, i2 + 1));
  58458. }
  58459. sColor = sColorNew;
  58460. }
  58461. const sColorChange = [];
  58462. for (let i2 = 1; i2 < 7; i2 += 2) {
  58463. sColorChange.push(parseInt(`0x${sColor.slice(i2, i2 + 2)}`));
  58464. }
  58465. if (!str) {
  58466. return sColorChange;
  58467. }
  58468. return `rgb(${sColorChange[0]},${sColorChange[1]},${sColorChange[2]})`;
  58469. }
  58470. if (/^(rgb|RGB)/.test(sColor)) {
  58471. const arr = sColor.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
  58472. return arr.map((val) => Number(val));
  58473. }
  58474. return sColor;
  58475. }
  58476. function rgbToHex(rgb) {
  58477. const _this = rgb;
  58478. const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  58479. if (/^(rgb|RGB)/.test(_this)) {
  58480. const aColor = _this.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
  58481. let strHex = "#";
  58482. for (let i2 = 0; i2 < aColor.length; i2++) {
  58483. let hex = Number(aColor[i2]).toString(16);
  58484. hex = String(hex).length == 1 ? `${0}${hex}` : hex;
  58485. if (hex === "0") {
  58486. hex += hex;
  58487. }
  58488. strHex += hex;
  58489. }
  58490. if (strHex.length !== 7) {
  58491. strHex = _this;
  58492. }
  58493. return strHex;
  58494. }
  58495. if (reg.test(_this)) {
  58496. const aNum = _this.replace(/#/, "").split("");
  58497. if (aNum.length === 6) {
  58498. return _this;
  58499. }
  58500. if (aNum.length === 3) {
  58501. let numHex = "#";
  58502. for (let i2 = 0; i2 < aNum.length; i2 += 1) {
  58503. numHex += aNum[i2] + aNum[i2];
  58504. }
  58505. return numHex;
  58506. }
  58507. } else {
  58508. return _this;
  58509. }
  58510. }
  58511. function colorToRgba(color2, alpha) {
  58512. color2 = rgbToHex(color2);
  58513. const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  58514. let sColor = String(color2).toLowerCase();
  58515. if (sColor && reg.test(sColor)) {
  58516. if (sColor.length === 4) {
  58517. let sColorNew = "#";
  58518. for (let i2 = 1; i2 < 4; i2 += 1) {
  58519. sColorNew += sColor.slice(i2, i2 + 1).concat(sColor.slice(i2, i2 + 1));
  58520. }
  58521. sColor = sColorNew;
  58522. }
  58523. const sColorChange = [];
  58524. for (let i2 = 1; i2 < 7; i2 += 2) {
  58525. sColorChange.push(parseInt(`0x${sColor.slice(i2, i2 + 2)}`));
  58526. }
  58527. return `rgba(${sColorChange.join(",")},${alpha})`;
  58528. }
  58529. return sColor;
  58530. }
  58531. const colorGradient$1 = {
  58532. colorGradient,
  58533. hexToRgb,
  58534. rgbToHex,
  58535. colorToRgba
  58536. };
  58537. let timeout = null;
  58538. function debounce(func2, wait = 500, immediate = false) {
  58539. if (timeout !== null)
  58540. clearTimeout(timeout);
  58541. if (immediate) {
  58542. const callNow = !timeout;
  58543. timeout = setTimeout(() => {
  58544. timeout = null;
  58545. }, wait);
  58546. if (callNow)
  58547. typeof func2 === "function" && func2();
  58548. } else {
  58549. timeout = setTimeout(() => {
  58550. typeof func2 === "function" && func2();
  58551. }, wait);
  58552. }
  58553. }
  58554. let flag;
  58555. function throttle(func2, wait = 500, immediate = true) {
  58556. if (immediate) {
  58557. if (!flag) {
  58558. flag = true;
  58559. typeof func2 === "function" && func2();
  58560. setTimeout(() => {
  58561. flag = false;
  58562. }, wait);
  58563. }
  58564. } else if (!flag) {
  58565. flag = true;
  58566. setTimeout(() => {
  58567. flag = false;
  58568. typeof func2 === "function" && func2();
  58569. }, wait);
  58570. }
  58571. }
  58572. let platform = "none";
  58573. platform = "vue3";
  58574. platform = "plus";
  58575. const platform$1 = platform;
  58576. const http = new Request();
  58577. let themeType = ["primary", "success", "error", "warning", "info"];
  58578. function setConfig(configs) {
  58579. index.shallowMerge(config$1, configs.config || {});
  58580. index.shallowMerge(props$f, configs.props || {});
  58581. index.shallowMerge(color, configs.color || {});
  58582. index.shallowMerge(zIndex, configs.zIndex || {});
  58583. }
  58584. index.setConfig = setConfig;
  58585. const $u = {
  58586. route,
  58587. date: index.timeFormat,
  58588. // 另名date
  58589. colorGradient: colorGradient$1.colorGradient,
  58590. hexToRgb: colorGradient$1.hexToRgb,
  58591. rgbToHex: colorGradient$1.rgbToHex,
  58592. colorToRgba: colorGradient$1.colorToRgba,
  58593. test,
  58594. type: themeType,
  58595. http,
  58596. config: config$1,
  58597. // uview-plus配置信息相关,比如版本号
  58598. zIndex,
  58599. debounce,
  58600. throttle,
  58601. mixin: mixin$1,
  58602. mpMixin,
  58603. props: props$f,
  58604. ...index,
  58605. color,
  58606. platform: platform$1
  58607. };
  58608. uni.$u = $u;
  58609. const install = (Vue2) => {
  58610. Vue2.config.globalProperties.$u = $u;
  58611. Vue2.mixin(mixin$1);
  58612. };
  58613. const uviewPlus = {
  58614. install
  58615. };
  58616. function Initializer() {
  58617. store.commit("SET_PLATFORM", platfrom);
  58618. store.commit("SET_TOKEN", storage.get(ACCESS_TOKEN));
  58619. store.commit("SET_USER_ID", storage.get(USER_ID));
  58620. }
  58621. const share = {
  58622. data() {
  58623. return {
  58624. share: {
  58625. // 转发的标题 (默认标题)
  58626. title: config.get("name"),
  58627. // 默认是当前页面,必须是以‘/’开头的完整路径
  58628. path: `/pages/home/index`,
  58629. //自定义图片路径,可以是本地文件路径、代码包文件路径或者网络图片路径,
  58630. //支持PNG及JPG,不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
  58631. imageUrl: config.getResource("logo.png")
  58632. }
  58633. };
  58634. },
  58635. // 发送给朋友
  58636. onShareAppMessage(res) {
  58637. let shareInfo = uni.getStorageSync("shareInfo");
  58638. return {
  58639. title: shareInfo.title || this.share.title,
  58640. imageUrl: shareInfo.imgUrl || this.share.imageUrl,
  58641. path: shareInfo.path || this.share.path
  58642. };
  58643. },
  58644. //分享到朋友圈
  58645. onShareTimeline(res) {
  58646. let shareInfo = uni.getStorageSync("shareInfo");
  58647. return {
  58648. title: shareInfo.title || this.share.title,
  58649. imageUrl: shareInfo.imgUrl || this.share.imageUrl,
  58650. path: shareInfo.path || this.share.path
  58651. };
  58652. }
  58653. };
  58654. const mixin = {
  58655. data() {
  58656. return {
  58657. platform: platfrom
  58658. };
  58659. },
  58660. computed: {}
  58661. };
  58662. function createApp() {
  58663. const app2 = vue.createVueApp(App);
  58664. app2.use(uviewPlus).use(store);
  58665. app2.config.productionTip = false;
  58666. app2.config.globalProperties.$img = {
  58667. img: "/static/images/img.png",
  58668. // 默认图片
  58669. logo: "/static/images/logo.png"
  58670. // 其他公共图片
  58671. };
  58672. app2.mixin(share).mixin(mixin);
  58673. return {
  58674. app: app2,
  58675. created: Initializer
  58676. };
  58677. }
  58678. const { app: __app__, Vuex: __Vuex__, Pinia: __Pinia__ } = createApp();
  58679. uni.Vuex = __Vuex__;
  58680. uni.Pinia = __Pinia__;
  58681. __app__.provide("__globalStyles", __uniConfig.styles);
  58682. __app__._component.mpType = "app";
  58683. __app__._component.render = () => {
  58684. };
  58685. __app__.mount("#app");
  58686. })(Vue);