ZLMRTCClient.js 266 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222
  1. var ZLMRTCClient = (function (exports) {
  2. 'use strict';
  3. const Events$1 = {
  4. WEBRTC_NOT_SUPPORT: 'WEBRTC_NOT_SUPPORT',
  5. WEBRTC_ICE_CANDIDATE_ERROR: 'WEBRTC_ICE_CANDIDATE_ERROR',
  6. WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED: 'WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED',
  7. WEBRTC_ON_REMOTE_STREAMS: 'WEBRTC_ON_REMOTE_STREAMS',
  8. WEBRTC_ON_LOCAL_STREAM: 'WEBRTC_ON_LOCAL_STREAM',
  9. WEBRTC_ON_CONNECTION_STATE_CHANGE: 'WEBRTC_ON_CONNECTION_STATE_CHANGE',
  10. WEBRTC_ON_DATA_CHANNEL_OPEN: 'WEBRTC_ON_DATA_CHANNEL_OPEN',
  11. WEBRTC_ON_DATA_CHANNEL_CLOSE: 'WEBRTC_ON_DATA_CHANNEL_CLOSE',
  12. WEBRTC_ON_DATA_CHANNEL_ERR: 'WEBRTC_ON_DATA_CHANNEL_ERR',
  13. WEBRTC_ON_DATA_CHANNEL_MSG: 'WEBRTC_ON_DATA_CHANNEL_MSG',
  14. CAPTURE_STREAM_FAILED: 'CAPTURE_STREAM_FAILED'
  15. };
  16. const VERSION$1 = '1.0.1';
  17. const BUILD_DATE = 'Mon Mar 27 2023 19:11:59 GMT+0800 (China Standard Time)';
  18. // Copyright (C) <2018> Intel Corporation
  19. //
  20. // SPDX-License-Identifier: Apache-2.0
  21. // eslint-disable-next-line require-jsdoc
  22. function isFirefox() {
  23. return window.navigator.userAgent.match('Firefox') !== null;
  24. }
  25. // eslint-disable-next-line require-jsdoc
  26. function isChrome() {
  27. return window.navigator.userAgent.match('Chrome') !== null;
  28. }
  29. // eslint-disable-next-line require-jsdoc
  30. function isEdge() {
  31. return window.navigator.userAgent.match(/Edge\/(\d+).(\d+)$/) !== null;
  32. }
  33. // Copyright (C) <2018> Intel Corporation
  34. /**
  35. * @class AudioSourceInfo
  36. * @classDesc Source info about an audio track. Values: 'mic', 'screen-cast', 'file', 'mixed'.
  37. * @memberOf Owt.Base
  38. * @readonly
  39. * @enum {string}
  40. */
  41. const AudioSourceInfo = {
  42. MIC: 'mic',
  43. SCREENCAST: 'screen-cast',
  44. FILE: 'file',
  45. MIXED: 'mixed'
  46. };
  47. /**
  48. * @class VideoSourceInfo
  49. * @classDesc Source info about a video track. Values: 'camera', 'screen-cast', 'file', 'mixed'.
  50. * @memberOf Owt.Base
  51. * @readonly
  52. * @enum {string}
  53. */
  54. const VideoSourceInfo = {
  55. CAMERA: 'camera',
  56. SCREENCAST: 'screen-cast',
  57. FILE: 'file',
  58. MIXED: 'mixed'
  59. };
  60. /**
  61. * @class TrackKind
  62. * @classDesc Kind of a track. Values: 'audio' for audio track, 'video' for video track, 'av' for both audio and video tracks.
  63. * @memberOf Owt.Base
  64. * @readonly
  65. * @enum {string}
  66. */
  67. const TrackKind = {
  68. /**
  69. * Audio tracks.
  70. * @type string
  71. */
  72. AUDIO: 'audio',
  73. /**
  74. * Video tracks.
  75. * @type string
  76. */
  77. VIDEO: 'video',
  78. /**
  79. * Both audio and video tracks.
  80. * @type string
  81. */
  82. AUDIO_AND_VIDEO: 'av'
  83. };
  84. /**
  85. * @class Resolution
  86. * @memberOf Owt.Base
  87. * @classDesc The Resolution defines the size of a rectangle.
  88. * @constructor
  89. * @param {number} width
  90. * @param {number} height
  91. */
  92. class Resolution {
  93. // eslint-disable-next-line require-jsdoc
  94. constructor(width, height) {
  95. /**
  96. * @member {number} width
  97. * @instance
  98. * @memberof Owt.Base.Resolution
  99. */
  100. this.width = width;
  101. /**
  102. * @member {number} height
  103. * @instance
  104. * @memberof Owt.Base.Resolution
  105. */
  106. this.height = height;
  107. }
  108. }
  109. /*
  110. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  111. *
  112. * Use of this source code is governed by a BSD-style license
  113. * that can be found in the LICENSE file in the root of the source
  114. * tree.
  115. */
  116. let logDisabled_ = true;
  117. let deprecationWarnings_ = true;
  118. /**
  119. * Extract browser version out of the provided user agent string.
  120. *
  121. * @param {!string} uastring userAgent string.
  122. * @param {!string} expr Regular expression used as match criteria.
  123. * @param {!number} pos position in the version string to be returned.
  124. * @return {!number} browser version.
  125. */
  126. function extractVersion(uastring, expr, pos) {
  127. const match = uastring.match(expr);
  128. return match && match.length >= pos && parseInt(match[pos], 10);
  129. }
  130. // Wraps the peerconnection event eventNameToWrap in a function
  131. // which returns the modified event object (or false to prevent
  132. // the event).
  133. function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {
  134. if (!window.RTCPeerConnection) {
  135. return;
  136. }
  137. const proto = window.RTCPeerConnection.prototype;
  138. const nativeAddEventListener = proto.addEventListener;
  139. proto.addEventListener = function(nativeEventName, cb) {
  140. if (nativeEventName !== eventNameToWrap) {
  141. return nativeAddEventListener.apply(this, arguments);
  142. }
  143. const wrappedCallback = (e) => {
  144. const modifiedEvent = wrapper(e);
  145. if (modifiedEvent) {
  146. if (cb.handleEvent) {
  147. cb.handleEvent(modifiedEvent);
  148. } else {
  149. cb(modifiedEvent);
  150. }
  151. }
  152. };
  153. this._eventMap = this._eventMap || {};
  154. if (!this._eventMap[eventNameToWrap]) {
  155. this._eventMap[eventNameToWrap] = new Map();
  156. }
  157. this._eventMap[eventNameToWrap].set(cb, wrappedCallback);
  158. return nativeAddEventListener.apply(this, [nativeEventName,
  159. wrappedCallback]);
  160. };
  161. const nativeRemoveEventListener = proto.removeEventListener;
  162. proto.removeEventListener = function(nativeEventName, cb) {
  163. if (nativeEventName !== eventNameToWrap || !this._eventMap
  164. || !this._eventMap[eventNameToWrap]) {
  165. return nativeRemoveEventListener.apply(this, arguments);
  166. }
  167. if (!this._eventMap[eventNameToWrap].has(cb)) {
  168. return nativeRemoveEventListener.apply(this, arguments);
  169. }
  170. const unwrappedCb = this._eventMap[eventNameToWrap].get(cb);
  171. this._eventMap[eventNameToWrap].delete(cb);
  172. if (this._eventMap[eventNameToWrap].size === 0) {
  173. delete this._eventMap[eventNameToWrap];
  174. }
  175. if (Object.keys(this._eventMap).length === 0) {
  176. delete this._eventMap;
  177. }
  178. return nativeRemoveEventListener.apply(this, [nativeEventName,
  179. unwrappedCb]);
  180. };
  181. Object.defineProperty(proto, 'on' + eventNameToWrap, {
  182. get() {
  183. return this['_on' + eventNameToWrap];
  184. },
  185. set(cb) {
  186. if (this['_on' + eventNameToWrap]) {
  187. this.removeEventListener(eventNameToWrap,
  188. this['_on' + eventNameToWrap]);
  189. delete this['_on' + eventNameToWrap];
  190. }
  191. if (cb) {
  192. this.addEventListener(eventNameToWrap,
  193. this['_on' + eventNameToWrap] = cb);
  194. }
  195. },
  196. enumerable: true,
  197. configurable: true
  198. });
  199. }
  200. function disableLog(bool) {
  201. if (typeof bool !== 'boolean') {
  202. return new Error('Argument type: ' + typeof bool +
  203. '. Please use a boolean.');
  204. }
  205. logDisabled_ = bool;
  206. return (bool) ? 'adapter.js logging disabled' :
  207. 'adapter.js logging enabled';
  208. }
  209. /**
  210. * Disable or enable deprecation warnings
  211. * @param {!boolean} bool set to true to disable warnings.
  212. */
  213. function disableWarnings(bool) {
  214. if (typeof bool !== 'boolean') {
  215. return new Error('Argument type: ' + typeof bool +
  216. '. Please use a boolean.');
  217. }
  218. deprecationWarnings_ = !bool;
  219. return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
  220. }
  221. function log$1() {
  222. if (typeof window === 'object') {
  223. if (logDisabled_) {
  224. return;
  225. }
  226. if (typeof console !== 'undefined' && typeof console.log === 'function') {
  227. console.log.apply(console, arguments);
  228. }
  229. }
  230. }
  231. /**
  232. * Shows a deprecation warning suggesting the modern and spec-compatible API.
  233. */
  234. function deprecated(oldMethod, newMethod) {
  235. if (!deprecationWarnings_) {
  236. return;
  237. }
  238. console.warn(oldMethod + ' is deprecated, please use ' + newMethod +
  239. ' instead.');
  240. }
  241. /**
  242. * Browser detector.
  243. *
  244. * @return {object} result containing browser and version
  245. * properties.
  246. */
  247. function detectBrowser(window) {
  248. // Returned result object.
  249. const result = {browser: null, version: null};
  250. // Fail early if it's not a browser
  251. if (typeof window === 'undefined' || !window.navigator) {
  252. result.browser = 'Not a browser.';
  253. return result;
  254. }
  255. const {navigator} = window;
  256. if (navigator.mozGetUserMedia) { // Firefox.
  257. result.browser = 'firefox';
  258. result.version = extractVersion(navigator.userAgent,
  259. /Firefox\/(\d+)\./, 1);
  260. } else if (navigator.webkitGetUserMedia ||
  261. (window.isSecureContext === false && window.webkitRTCPeerConnection &&
  262. !window.RTCIceGatherer)) {
  263. // Chrome, Chromium, Webview, Opera.
  264. // Version matches Chrome/WebRTC version.
  265. // Chrome 74 removed webkitGetUserMedia on http as well so we need the
  266. // more complicated fallback to webkitRTCPeerConnection.
  267. result.browser = 'chrome';
  268. result.version = extractVersion(navigator.userAgent,
  269. /Chrom(e|ium)\/(\d+)\./, 2);
  270. } else if (navigator.mediaDevices &&
  271. navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { // Edge.
  272. result.browser = 'edge';
  273. result.version = extractVersion(navigator.userAgent,
  274. /Edge\/(\d+).(\d+)$/, 2);
  275. } else if (window.RTCPeerConnection &&
  276. navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) { // Safari.
  277. result.browser = 'safari';
  278. result.version = extractVersion(navigator.userAgent,
  279. /AppleWebKit\/(\d+)\./, 1);
  280. result.supportsUnifiedPlan = window.RTCRtpTransceiver &&
  281. 'currentDirection' in window.RTCRtpTransceiver.prototype;
  282. } else { // Default fallthrough: not supported.
  283. result.browser = 'Not a supported browser.';
  284. return result;
  285. }
  286. return result;
  287. }
  288. /**
  289. * Checks if something is an object.
  290. *
  291. * @param {*} val The something you want to check.
  292. * @return true if val is an object, false otherwise.
  293. */
  294. function isObject$1(val) {
  295. return Object.prototype.toString.call(val) === '[object Object]';
  296. }
  297. /**
  298. * Remove all empty objects and undefined values
  299. * from a nested object -- an enhanced and vanilla version
  300. * of Lodash's `compact`.
  301. */
  302. function compactObject(data) {
  303. if (!isObject$1(data)) {
  304. return data;
  305. }
  306. return Object.keys(data).reduce(function(accumulator, key) {
  307. const isObj = isObject$1(data[key]);
  308. const value = isObj ? compactObject(data[key]) : data[key];
  309. const isEmptyObject = isObj && !Object.keys(value).length;
  310. if (value === undefined || isEmptyObject) {
  311. return accumulator;
  312. }
  313. return Object.assign(accumulator, {[key]: value});
  314. }, {});
  315. }
  316. /* iterates the stats graph recursively. */
  317. function walkStats(stats, base, resultSet) {
  318. if (!base || resultSet.has(base.id)) {
  319. return;
  320. }
  321. resultSet.set(base.id, base);
  322. Object.keys(base).forEach(name => {
  323. if (name.endsWith('Id')) {
  324. walkStats(stats, stats.get(base[name]), resultSet);
  325. } else if (name.endsWith('Ids')) {
  326. base[name].forEach(id => {
  327. walkStats(stats, stats.get(id), resultSet);
  328. });
  329. }
  330. });
  331. }
  332. /* filter getStats for a sender/receiver track. */
  333. function filterStats(result, track, outbound) {
  334. const streamStatsType = outbound ? 'outbound-rtp' : 'inbound-rtp';
  335. const filteredResult = new Map();
  336. if (track === null) {
  337. return filteredResult;
  338. }
  339. const trackStats = [];
  340. result.forEach(value => {
  341. if (value.type === 'track' &&
  342. value.trackIdentifier === track.id) {
  343. trackStats.push(value);
  344. }
  345. });
  346. trackStats.forEach(trackStat => {
  347. result.forEach(stats => {
  348. if (stats.type === streamStatsType && stats.trackId === trackStat.id) {
  349. walkStats(result, stats, filteredResult);
  350. }
  351. });
  352. });
  353. return filteredResult;
  354. }
  355. /*
  356. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  357. *
  358. * Use of this source code is governed by a BSD-style license
  359. * that can be found in the LICENSE file in the root of the source
  360. * tree.
  361. */
  362. const logging = log$1;
  363. function shimGetUserMedia$3(window, browserDetails) {
  364. const navigator = window && window.navigator;
  365. if (!navigator.mediaDevices) {
  366. return;
  367. }
  368. const constraintsToChrome_ = function(c) {
  369. if (typeof c !== 'object' || c.mandatory || c.optional) {
  370. return c;
  371. }
  372. const cc = {};
  373. Object.keys(c).forEach(key => {
  374. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  375. return;
  376. }
  377. const r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
  378. if (r.exact !== undefined && typeof r.exact === 'number') {
  379. r.min = r.max = r.exact;
  380. }
  381. const oldname_ = function(prefix, name) {
  382. if (prefix) {
  383. return prefix + name.charAt(0).toUpperCase() + name.slice(1);
  384. }
  385. return (name === 'deviceId') ? 'sourceId' : name;
  386. };
  387. if (r.ideal !== undefined) {
  388. cc.optional = cc.optional || [];
  389. let oc = {};
  390. if (typeof r.ideal === 'number') {
  391. oc[oldname_('min', key)] = r.ideal;
  392. cc.optional.push(oc);
  393. oc = {};
  394. oc[oldname_('max', key)] = r.ideal;
  395. cc.optional.push(oc);
  396. } else {
  397. oc[oldname_('', key)] = r.ideal;
  398. cc.optional.push(oc);
  399. }
  400. }
  401. if (r.exact !== undefined && typeof r.exact !== 'number') {
  402. cc.mandatory = cc.mandatory || {};
  403. cc.mandatory[oldname_('', key)] = r.exact;
  404. } else {
  405. ['min', 'max'].forEach(mix => {
  406. if (r[mix] !== undefined) {
  407. cc.mandatory = cc.mandatory || {};
  408. cc.mandatory[oldname_(mix, key)] = r[mix];
  409. }
  410. });
  411. }
  412. });
  413. if (c.advanced) {
  414. cc.optional = (cc.optional || []).concat(c.advanced);
  415. }
  416. return cc;
  417. };
  418. const shimConstraints_ = function(constraints, func) {
  419. if (browserDetails.version >= 61) {
  420. return func(constraints);
  421. }
  422. constraints = JSON.parse(JSON.stringify(constraints));
  423. if (constraints && typeof constraints.audio === 'object') {
  424. const remap = function(obj, a, b) {
  425. if (a in obj && !(b in obj)) {
  426. obj[b] = obj[a];
  427. delete obj[a];
  428. }
  429. };
  430. constraints = JSON.parse(JSON.stringify(constraints));
  431. remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
  432. remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
  433. constraints.audio = constraintsToChrome_(constraints.audio);
  434. }
  435. if (constraints && typeof constraints.video === 'object') {
  436. // Shim facingMode for mobile & surface pro.
  437. let face = constraints.video.facingMode;
  438. face = face && ((typeof face === 'object') ? face : {ideal: face});
  439. const getSupportedFacingModeLies = browserDetails.version < 66;
  440. if ((face && (face.exact === 'user' || face.exact === 'environment' ||
  441. face.ideal === 'user' || face.ideal === 'environment')) &&
  442. !(navigator.mediaDevices.getSupportedConstraints &&
  443. navigator.mediaDevices.getSupportedConstraints().facingMode &&
  444. !getSupportedFacingModeLies)) {
  445. delete constraints.video.facingMode;
  446. let matches;
  447. if (face.exact === 'environment' || face.ideal === 'environment') {
  448. matches = ['back', 'rear'];
  449. } else if (face.exact === 'user' || face.ideal === 'user') {
  450. matches = ['front'];
  451. }
  452. if (matches) {
  453. // Look for matches in label, or use last cam for back (typical).
  454. return navigator.mediaDevices.enumerateDevices()
  455. .then(devices => {
  456. devices = devices.filter(d => d.kind === 'videoinput');
  457. let dev = devices.find(d => matches.some(match =>
  458. d.label.toLowerCase().includes(match)));
  459. if (!dev && devices.length && matches.includes('back')) {
  460. dev = devices[devices.length - 1]; // more likely the back cam
  461. }
  462. if (dev) {
  463. constraints.video.deviceId = face.exact ? {exact: dev.deviceId} :
  464. {ideal: dev.deviceId};
  465. }
  466. constraints.video = constraintsToChrome_(constraints.video);
  467. logging('chrome: ' + JSON.stringify(constraints));
  468. return func(constraints);
  469. });
  470. }
  471. }
  472. constraints.video = constraintsToChrome_(constraints.video);
  473. }
  474. logging('chrome: ' + JSON.stringify(constraints));
  475. return func(constraints);
  476. };
  477. const shimError_ = function(e) {
  478. if (browserDetails.version >= 64) {
  479. return e;
  480. }
  481. return {
  482. name: {
  483. PermissionDeniedError: 'NotAllowedError',
  484. PermissionDismissedError: 'NotAllowedError',
  485. InvalidStateError: 'NotAllowedError',
  486. DevicesNotFoundError: 'NotFoundError',
  487. ConstraintNotSatisfiedError: 'OverconstrainedError',
  488. TrackStartError: 'NotReadableError',
  489. MediaDeviceFailedDueToShutdown: 'NotAllowedError',
  490. MediaDeviceKillSwitchOn: 'NotAllowedError',
  491. TabCaptureError: 'AbortError',
  492. ScreenCaptureError: 'AbortError',
  493. DeviceCaptureError: 'AbortError'
  494. }[e.name] || e.name,
  495. message: e.message,
  496. constraint: e.constraint || e.constraintName,
  497. toString() {
  498. return this.name + (this.message && ': ') + this.message;
  499. }
  500. };
  501. };
  502. const getUserMedia_ = function(constraints, onSuccess, onError) {
  503. shimConstraints_(constraints, c => {
  504. navigator.webkitGetUserMedia(c, onSuccess, e => {
  505. if (onError) {
  506. onError(shimError_(e));
  507. }
  508. });
  509. });
  510. };
  511. navigator.getUserMedia = getUserMedia_.bind(navigator);
  512. // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
  513. // function which returns a Promise, it does not accept spec-style
  514. // constraints.
  515. if (navigator.mediaDevices.getUserMedia) {
  516. const origGetUserMedia = navigator.mediaDevices.getUserMedia.
  517. bind(navigator.mediaDevices);
  518. navigator.mediaDevices.getUserMedia = function(cs) {
  519. return shimConstraints_(cs, c => origGetUserMedia(c).then(stream => {
  520. if (c.audio && !stream.getAudioTracks().length ||
  521. c.video && !stream.getVideoTracks().length) {
  522. stream.getTracks().forEach(track => {
  523. track.stop();
  524. });
  525. throw new DOMException('', 'NotFoundError');
  526. }
  527. return stream;
  528. }, e => Promise.reject(shimError_(e))));
  529. };
  530. }
  531. }
  532. /*
  533. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  534. *
  535. * Use of this source code is governed by a BSD-style license
  536. * that can be found in the LICENSE file in the root of the source
  537. * tree.
  538. */
  539. function shimGetDisplayMedia$2(window, getSourceId) {
  540. if (window.navigator.mediaDevices &&
  541. 'getDisplayMedia' in window.navigator.mediaDevices) {
  542. return;
  543. }
  544. if (!(window.navigator.mediaDevices)) {
  545. return;
  546. }
  547. // getSourceId is a function that returns a promise resolving with
  548. // the sourceId of the screen/window/tab to be shared.
  549. if (typeof getSourceId !== 'function') {
  550. console.error('shimGetDisplayMedia: getSourceId argument is not ' +
  551. 'a function');
  552. return;
  553. }
  554. window.navigator.mediaDevices.getDisplayMedia =
  555. function getDisplayMedia(constraints) {
  556. return getSourceId(constraints)
  557. .then(sourceId => {
  558. const widthSpecified = constraints.video && constraints.video.width;
  559. const heightSpecified = constraints.video &&
  560. constraints.video.height;
  561. const frameRateSpecified = constraints.video &&
  562. constraints.video.frameRate;
  563. constraints.video = {
  564. mandatory: {
  565. chromeMediaSource: 'desktop',
  566. chromeMediaSourceId: sourceId,
  567. maxFrameRate: frameRateSpecified || 3
  568. }
  569. };
  570. if (widthSpecified) {
  571. constraints.video.mandatory.maxWidth = widthSpecified;
  572. }
  573. if (heightSpecified) {
  574. constraints.video.mandatory.maxHeight = heightSpecified;
  575. }
  576. return window.navigator.mediaDevices.getUserMedia(constraints);
  577. });
  578. };
  579. }
  580. /*
  581. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  582. *
  583. * Use of this source code is governed by a BSD-style license
  584. * that can be found in the LICENSE file in the root of the source
  585. * tree.
  586. */
  587. function shimMediaStream(window) {
  588. window.MediaStream = window.MediaStream || window.webkitMediaStream;
  589. }
  590. function shimOnTrack$1(window) {
  591. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  592. window.RTCPeerConnection.prototype)) {
  593. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  594. get() {
  595. return this._ontrack;
  596. },
  597. set(f) {
  598. if (this._ontrack) {
  599. this.removeEventListener('track', this._ontrack);
  600. }
  601. this.addEventListener('track', this._ontrack = f);
  602. },
  603. enumerable: true,
  604. configurable: true
  605. });
  606. const origSetRemoteDescription =
  607. window.RTCPeerConnection.prototype.setRemoteDescription;
  608. window.RTCPeerConnection.prototype.setRemoteDescription =
  609. function setRemoteDescription() {
  610. if (!this._ontrackpoly) {
  611. this._ontrackpoly = (e) => {
  612. // onaddstream does not fire when a track is added to an existing
  613. // stream. But stream.onaddtrack is implemented so we use that.
  614. e.stream.addEventListener('addtrack', te => {
  615. let receiver;
  616. if (window.RTCPeerConnection.prototype.getReceivers) {
  617. receiver = this.getReceivers()
  618. .find(r => r.track && r.track.id === te.track.id);
  619. } else {
  620. receiver = {track: te.track};
  621. }
  622. const event = new Event('track');
  623. event.track = te.track;
  624. event.receiver = receiver;
  625. event.transceiver = {receiver};
  626. event.streams = [e.stream];
  627. this.dispatchEvent(event);
  628. });
  629. e.stream.getTracks().forEach(track => {
  630. let receiver;
  631. if (window.RTCPeerConnection.prototype.getReceivers) {
  632. receiver = this.getReceivers()
  633. .find(r => r.track && r.track.id === track.id);
  634. } else {
  635. receiver = {track};
  636. }
  637. const event = new Event('track');
  638. event.track = track;
  639. event.receiver = receiver;
  640. event.transceiver = {receiver};
  641. event.streams = [e.stream];
  642. this.dispatchEvent(event);
  643. });
  644. };
  645. this.addEventListener('addstream', this._ontrackpoly);
  646. }
  647. return origSetRemoteDescription.apply(this, arguments);
  648. };
  649. } else {
  650. // even if RTCRtpTransceiver is in window, it is only used and
  651. // emitted in unified-plan. Unfortunately this means we need
  652. // to unconditionally wrap the event.
  653. wrapPeerConnectionEvent(window, 'track', e => {
  654. if (!e.transceiver) {
  655. Object.defineProperty(e, 'transceiver',
  656. {value: {receiver: e.receiver}});
  657. }
  658. return e;
  659. });
  660. }
  661. }
  662. function shimGetSendersWithDtmf(window) {
  663. // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.
  664. if (typeof window === 'object' && window.RTCPeerConnection &&
  665. !('getSenders' in window.RTCPeerConnection.prototype) &&
  666. 'createDTMFSender' in window.RTCPeerConnection.prototype) {
  667. const shimSenderWithDtmf = function(pc, track) {
  668. return {
  669. track,
  670. get dtmf() {
  671. if (this._dtmf === undefined) {
  672. if (track.kind === 'audio') {
  673. this._dtmf = pc.createDTMFSender(track);
  674. } else {
  675. this._dtmf = null;
  676. }
  677. }
  678. return this._dtmf;
  679. },
  680. _pc: pc
  681. };
  682. };
  683. // augment addTrack when getSenders is not available.
  684. if (!window.RTCPeerConnection.prototype.getSenders) {
  685. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  686. this._senders = this._senders || [];
  687. return this._senders.slice(); // return a copy of the internal state.
  688. };
  689. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  690. window.RTCPeerConnection.prototype.addTrack =
  691. function addTrack(track, stream) {
  692. let sender = origAddTrack.apply(this, arguments);
  693. if (!sender) {
  694. sender = shimSenderWithDtmf(this, track);
  695. this._senders.push(sender);
  696. }
  697. return sender;
  698. };
  699. const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  700. window.RTCPeerConnection.prototype.removeTrack =
  701. function removeTrack(sender) {
  702. origRemoveTrack.apply(this, arguments);
  703. const idx = this._senders.indexOf(sender);
  704. if (idx !== -1) {
  705. this._senders.splice(idx, 1);
  706. }
  707. };
  708. }
  709. const origAddStream = window.RTCPeerConnection.prototype.addStream;
  710. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  711. this._senders = this._senders || [];
  712. origAddStream.apply(this, [stream]);
  713. stream.getTracks().forEach(track => {
  714. this._senders.push(shimSenderWithDtmf(this, track));
  715. });
  716. };
  717. const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  718. window.RTCPeerConnection.prototype.removeStream =
  719. function removeStream(stream) {
  720. this._senders = this._senders || [];
  721. origRemoveStream.apply(this, [stream]);
  722. stream.getTracks().forEach(track => {
  723. const sender = this._senders.find(s => s.track === track);
  724. if (sender) { // remove sender
  725. this._senders.splice(this._senders.indexOf(sender), 1);
  726. }
  727. });
  728. };
  729. } else if (typeof window === 'object' && window.RTCPeerConnection &&
  730. 'getSenders' in window.RTCPeerConnection.prototype &&
  731. 'createDTMFSender' in window.RTCPeerConnection.prototype &&
  732. window.RTCRtpSender &&
  733. !('dtmf' in window.RTCRtpSender.prototype)) {
  734. const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  735. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  736. const senders = origGetSenders.apply(this, []);
  737. senders.forEach(sender => sender._pc = this);
  738. return senders;
  739. };
  740. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  741. get() {
  742. if (this._dtmf === undefined) {
  743. if (this.track.kind === 'audio') {
  744. this._dtmf = this._pc.createDTMFSender(this.track);
  745. } else {
  746. this._dtmf = null;
  747. }
  748. }
  749. return this._dtmf;
  750. }
  751. });
  752. }
  753. }
  754. function shimGetStats(window) {
  755. if (!window.RTCPeerConnection) {
  756. return;
  757. }
  758. const origGetStats = window.RTCPeerConnection.prototype.getStats;
  759. window.RTCPeerConnection.prototype.getStats = function getStats() {
  760. const [selector, onSucc, onErr] = arguments;
  761. // If selector is a function then we are in the old style stats so just
  762. // pass back the original getStats format to avoid breaking old users.
  763. if (arguments.length > 0 && typeof selector === 'function') {
  764. return origGetStats.apply(this, arguments);
  765. }
  766. // When spec-style getStats is supported, return those when called with
  767. // either no arguments or the selector argument is null.
  768. if (origGetStats.length === 0 && (arguments.length === 0 ||
  769. typeof selector !== 'function')) {
  770. return origGetStats.apply(this, []);
  771. }
  772. const fixChromeStats_ = function(response) {
  773. const standardReport = {};
  774. const reports = response.result();
  775. reports.forEach(report => {
  776. const standardStats = {
  777. id: report.id,
  778. timestamp: report.timestamp,
  779. type: {
  780. localcandidate: 'local-candidate',
  781. remotecandidate: 'remote-candidate'
  782. }[report.type] || report.type
  783. };
  784. report.names().forEach(name => {
  785. standardStats[name] = report.stat(name);
  786. });
  787. standardReport[standardStats.id] = standardStats;
  788. });
  789. return standardReport;
  790. };
  791. // shim getStats with maplike support
  792. const makeMapStats = function(stats) {
  793. return new Map(Object.keys(stats).map(key => [key, stats[key]]));
  794. };
  795. if (arguments.length >= 2) {
  796. const successCallbackWrapper_ = function(response) {
  797. onSucc(makeMapStats(fixChromeStats_(response)));
  798. };
  799. return origGetStats.apply(this, [successCallbackWrapper_,
  800. selector]);
  801. }
  802. // promise-support
  803. return new Promise((resolve, reject) => {
  804. origGetStats.apply(this, [
  805. function(response) {
  806. resolve(makeMapStats(fixChromeStats_(response)));
  807. }, reject]);
  808. }).then(onSucc, onErr);
  809. };
  810. }
  811. function shimSenderReceiverGetStats(window) {
  812. if (!(typeof window === 'object' && window.RTCPeerConnection &&
  813. window.RTCRtpSender && window.RTCRtpReceiver)) {
  814. return;
  815. }
  816. // shim sender stats.
  817. if (!('getStats' in window.RTCRtpSender.prototype)) {
  818. const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  819. if (origGetSenders) {
  820. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  821. const senders = origGetSenders.apply(this, []);
  822. senders.forEach(sender => sender._pc = this);
  823. return senders;
  824. };
  825. }
  826. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  827. if (origAddTrack) {
  828. window.RTCPeerConnection.prototype.addTrack = function addTrack() {
  829. const sender = origAddTrack.apply(this, arguments);
  830. sender._pc = this;
  831. return sender;
  832. };
  833. }
  834. window.RTCRtpSender.prototype.getStats = function getStats() {
  835. const sender = this;
  836. return this._pc.getStats().then(result =>
  837. /* Note: this will include stats of all senders that
  838. * send a track with the same id as sender.track as
  839. * it is not possible to identify the RTCRtpSender.
  840. */
  841. filterStats(result, sender.track, true));
  842. };
  843. }
  844. // shim receiver stats.
  845. if (!('getStats' in window.RTCRtpReceiver.prototype)) {
  846. const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
  847. if (origGetReceivers) {
  848. window.RTCPeerConnection.prototype.getReceivers =
  849. function getReceivers() {
  850. const receivers = origGetReceivers.apply(this, []);
  851. receivers.forEach(receiver => receiver._pc = this);
  852. return receivers;
  853. };
  854. }
  855. wrapPeerConnectionEvent(window, 'track', e => {
  856. e.receiver._pc = e.srcElement;
  857. return e;
  858. });
  859. window.RTCRtpReceiver.prototype.getStats = function getStats() {
  860. const receiver = this;
  861. return this._pc.getStats().then(result =>
  862. filterStats(result, receiver.track, false));
  863. };
  864. }
  865. if (!('getStats' in window.RTCRtpSender.prototype &&
  866. 'getStats' in window.RTCRtpReceiver.prototype)) {
  867. return;
  868. }
  869. // shim RTCPeerConnection.getStats(track).
  870. const origGetStats = window.RTCPeerConnection.prototype.getStats;
  871. window.RTCPeerConnection.prototype.getStats = function getStats() {
  872. if (arguments.length > 0 &&
  873. arguments[0] instanceof window.MediaStreamTrack) {
  874. const track = arguments[0];
  875. let sender;
  876. let receiver;
  877. let err;
  878. this.getSenders().forEach(s => {
  879. if (s.track === track) {
  880. if (sender) {
  881. err = true;
  882. } else {
  883. sender = s;
  884. }
  885. }
  886. });
  887. this.getReceivers().forEach(r => {
  888. if (r.track === track) {
  889. if (receiver) {
  890. err = true;
  891. } else {
  892. receiver = r;
  893. }
  894. }
  895. return r.track === track;
  896. });
  897. if (err || (sender && receiver)) {
  898. return Promise.reject(new DOMException(
  899. 'There are more than one sender or receiver for the track.',
  900. 'InvalidAccessError'));
  901. } else if (sender) {
  902. return sender.getStats();
  903. } else if (receiver) {
  904. return receiver.getStats();
  905. }
  906. return Promise.reject(new DOMException(
  907. 'There is no sender or receiver for the track.',
  908. 'InvalidAccessError'));
  909. }
  910. return origGetStats.apply(this, arguments);
  911. };
  912. }
  913. function shimAddTrackRemoveTrackWithNative(window) {
  914. // shim addTrack/removeTrack with native variants in order to make
  915. // the interactions with legacy getLocalStreams behave as in other browsers.
  916. // Keeps a mapping stream.id => [stream, rtpsenders...]
  917. window.RTCPeerConnection.prototype.getLocalStreams =
  918. function getLocalStreams() {
  919. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  920. return Object.keys(this._shimmedLocalStreams)
  921. .map(streamId => this._shimmedLocalStreams[streamId][0]);
  922. };
  923. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  924. window.RTCPeerConnection.prototype.addTrack =
  925. function addTrack(track, stream) {
  926. if (!stream) {
  927. return origAddTrack.apply(this, arguments);
  928. }
  929. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  930. const sender = origAddTrack.apply(this, arguments);
  931. if (!this._shimmedLocalStreams[stream.id]) {
  932. this._shimmedLocalStreams[stream.id] = [stream, sender];
  933. } else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) {
  934. this._shimmedLocalStreams[stream.id].push(sender);
  935. }
  936. return sender;
  937. };
  938. const origAddStream = window.RTCPeerConnection.prototype.addStream;
  939. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  940. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  941. stream.getTracks().forEach(track => {
  942. const alreadyExists = this.getSenders().find(s => s.track === track);
  943. if (alreadyExists) {
  944. throw new DOMException('Track already exists.',
  945. 'InvalidAccessError');
  946. }
  947. });
  948. const existingSenders = this.getSenders();
  949. origAddStream.apply(this, arguments);
  950. const newSenders = this.getSenders()
  951. .filter(newSender => existingSenders.indexOf(newSender) === -1);
  952. this._shimmedLocalStreams[stream.id] = [stream].concat(newSenders);
  953. };
  954. const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  955. window.RTCPeerConnection.prototype.removeStream =
  956. function removeStream(stream) {
  957. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  958. delete this._shimmedLocalStreams[stream.id];
  959. return origRemoveStream.apply(this, arguments);
  960. };
  961. const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  962. window.RTCPeerConnection.prototype.removeTrack =
  963. function removeTrack(sender) {
  964. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  965. if (sender) {
  966. Object.keys(this._shimmedLocalStreams).forEach(streamId => {
  967. const idx = this._shimmedLocalStreams[streamId].indexOf(sender);
  968. if (idx !== -1) {
  969. this._shimmedLocalStreams[streamId].splice(idx, 1);
  970. }
  971. if (this._shimmedLocalStreams[streamId].length === 1) {
  972. delete this._shimmedLocalStreams[streamId];
  973. }
  974. });
  975. }
  976. return origRemoveTrack.apply(this, arguments);
  977. };
  978. }
  979. function shimAddTrackRemoveTrack(window, browserDetails) {
  980. if (!window.RTCPeerConnection) {
  981. return;
  982. }
  983. // shim addTrack and removeTrack.
  984. if (window.RTCPeerConnection.prototype.addTrack &&
  985. browserDetails.version >= 65) {
  986. return shimAddTrackRemoveTrackWithNative(window);
  987. }
  988. // also shim pc.getLocalStreams when addTrack is shimmed
  989. // to return the original streams.
  990. const origGetLocalStreams = window.RTCPeerConnection.prototype
  991. .getLocalStreams;
  992. window.RTCPeerConnection.prototype.getLocalStreams =
  993. function getLocalStreams() {
  994. const nativeStreams = origGetLocalStreams.apply(this);
  995. this._reverseStreams = this._reverseStreams || {};
  996. return nativeStreams.map(stream => this._reverseStreams[stream.id]);
  997. };
  998. const origAddStream = window.RTCPeerConnection.prototype.addStream;
  999. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  1000. this._streams = this._streams || {};
  1001. this._reverseStreams = this._reverseStreams || {};
  1002. stream.getTracks().forEach(track => {
  1003. const alreadyExists = this.getSenders().find(s => s.track === track);
  1004. if (alreadyExists) {
  1005. throw new DOMException('Track already exists.',
  1006. 'InvalidAccessError');
  1007. }
  1008. });
  1009. // Add identity mapping for consistency with addTrack.
  1010. // Unless this is being used with a stream from addTrack.
  1011. if (!this._reverseStreams[stream.id]) {
  1012. const newStream = new window.MediaStream(stream.getTracks());
  1013. this._streams[stream.id] = newStream;
  1014. this._reverseStreams[newStream.id] = stream;
  1015. stream = newStream;
  1016. }
  1017. origAddStream.apply(this, [stream]);
  1018. };
  1019. const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  1020. window.RTCPeerConnection.prototype.removeStream =
  1021. function removeStream(stream) {
  1022. this._streams = this._streams || {};
  1023. this._reverseStreams = this._reverseStreams || {};
  1024. origRemoveStream.apply(this, [(this._streams[stream.id] || stream)]);
  1025. delete this._reverseStreams[(this._streams[stream.id] ?
  1026. this._streams[stream.id].id : stream.id)];
  1027. delete this._streams[stream.id];
  1028. };
  1029. window.RTCPeerConnection.prototype.addTrack =
  1030. function addTrack(track, stream) {
  1031. if (this.signalingState === 'closed') {
  1032. throw new DOMException(
  1033. 'The RTCPeerConnection\'s signalingState is \'closed\'.',
  1034. 'InvalidStateError');
  1035. }
  1036. const streams = [].slice.call(arguments, 1);
  1037. if (streams.length !== 1 ||
  1038. !streams[0].getTracks().find(t => t === track)) {
  1039. // this is not fully correct but all we can manage without
  1040. // [[associated MediaStreams]] internal slot.
  1041. throw new DOMException(
  1042. 'The adapter.js addTrack polyfill only supports a single ' +
  1043. ' stream which is associated with the specified track.',
  1044. 'NotSupportedError');
  1045. }
  1046. const alreadyExists = this.getSenders().find(s => s.track === track);
  1047. if (alreadyExists) {
  1048. throw new DOMException('Track already exists.',
  1049. 'InvalidAccessError');
  1050. }
  1051. this._streams = this._streams || {};
  1052. this._reverseStreams = this._reverseStreams || {};
  1053. const oldStream = this._streams[stream.id];
  1054. if (oldStream) {
  1055. // this is using odd Chrome behaviour, use with caution:
  1056. // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
  1057. // Note: we rely on the high-level addTrack/dtmf shim to
  1058. // create the sender with a dtmf sender.
  1059. oldStream.addTrack(track);
  1060. // Trigger ONN async.
  1061. Promise.resolve().then(() => {
  1062. this.dispatchEvent(new Event('negotiationneeded'));
  1063. });
  1064. } else {
  1065. const newStream = new window.MediaStream([track]);
  1066. this._streams[stream.id] = newStream;
  1067. this._reverseStreams[newStream.id] = stream;
  1068. this.addStream(newStream);
  1069. }
  1070. return this.getSenders().find(s => s.track === track);
  1071. };
  1072. // replace the internal stream id with the external one and
  1073. // vice versa.
  1074. function replaceInternalStreamId(pc, description) {
  1075. let sdp = description.sdp;
  1076. Object.keys(pc._reverseStreams || []).forEach(internalId => {
  1077. const externalStream = pc._reverseStreams[internalId];
  1078. const internalStream = pc._streams[externalStream.id];
  1079. sdp = sdp.replace(new RegExp(internalStream.id, 'g'),
  1080. externalStream.id);
  1081. });
  1082. return new RTCSessionDescription({
  1083. type: description.type,
  1084. sdp
  1085. });
  1086. }
  1087. function replaceExternalStreamId(pc, description) {
  1088. let sdp = description.sdp;
  1089. Object.keys(pc._reverseStreams || []).forEach(internalId => {
  1090. const externalStream = pc._reverseStreams[internalId];
  1091. const internalStream = pc._streams[externalStream.id];
  1092. sdp = sdp.replace(new RegExp(externalStream.id, 'g'),
  1093. internalStream.id);
  1094. });
  1095. return new RTCSessionDescription({
  1096. type: description.type,
  1097. sdp
  1098. });
  1099. }
  1100. ['createOffer', 'createAnswer'].forEach(function(method) {
  1101. const nativeMethod = window.RTCPeerConnection.prototype[method];
  1102. const methodObj = {[method]() {
  1103. const args = arguments;
  1104. const isLegacyCall = arguments.length &&
  1105. typeof arguments[0] === 'function';
  1106. if (isLegacyCall) {
  1107. return nativeMethod.apply(this, [
  1108. (description) => {
  1109. const desc = replaceInternalStreamId(this, description);
  1110. args[0].apply(null, [desc]);
  1111. },
  1112. (err) => {
  1113. if (args[1]) {
  1114. args[1].apply(null, err);
  1115. }
  1116. }, arguments[2]
  1117. ]);
  1118. }
  1119. return nativeMethod.apply(this, arguments)
  1120. .then(description => replaceInternalStreamId(this, description));
  1121. }};
  1122. window.RTCPeerConnection.prototype[method] = methodObj[method];
  1123. });
  1124. const origSetLocalDescription =
  1125. window.RTCPeerConnection.prototype.setLocalDescription;
  1126. window.RTCPeerConnection.prototype.setLocalDescription =
  1127. function setLocalDescription() {
  1128. if (!arguments.length || !arguments[0].type) {
  1129. return origSetLocalDescription.apply(this, arguments);
  1130. }
  1131. arguments[0] = replaceExternalStreamId(this, arguments[0]);
  1132. return origSetLocalDescription.apply(this, arguments);
  1133. };
  1134. // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier
  1135. const origLocalDescription = Object.getOwnPropertyDescriptor(
  1136. window.RTCPeerConnection.prototype, 'localDescription');
  1137. Object.defineProperty(window.RTCPeerConnection.prototype,
  1138. 'localDescription', {
  1139. get() {
  1140. const description = origLocalDescription.get.apply(this);
  1141. if (description.type === '') {
  1142. return description;
  1143. }
  1144. return replaceInternalStreamId(this, description);
  1145. }
  1146. });
  1147. window.RTCPeerConnection.prototype.removeTrack =
  1148. function removeTrack(sender) {
  1149. if (this.signalingState === 'closed') {
  1150. throw new DOMException(
  1151. 'The RTCPeerConnection\'s signalingState is \'closed\'.',
  1152. 'InvalidStateError');
  1153. }
  1154. // We can not yet check for sender instanceof RTCRtpSender
  1155. // since we shim RTPSender. So we check if sender._pc is set.
  1156. if (!sender._pc) {
  1157. throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' +
  1158. 'does not implement interface RTCRtpSender.', 'TypeError');
  1159. }
  1160. const isLocal = sender._pc === this;
  1161. if (!isLocal) {
  1162. throw new DOMException('Sender was not created by this connection.',
  1163. 'InvalidAccessError');
  1164. }
  1165. // Search for the native stream the senders track belongs to.
  1166. this._streams = this._streams || {};
  1167. let stream;
  1168. Object.keys(this._streams).forEach(streamid => {
  1169. const hasTrack = this._streams[streamid].getTracks()
  1170. .find(track => sender.track === track);
  1171. if (hasTrack) {
  1172. stream = this._streams[streamid];
  1173. }
  1174. });
  1175. if (stream) {
  1176. if (stream.getTracks().length === 1) {
  1177. // if this is the last track of the stream, remove the stream. This
  1178. // takes care of any shimmed _senders.
  1179. this.removeStream(this._reverseStreams[stream.id]);
  1180. } else {
  1181. // relying on the same odd chrome behaviour as above.
  1182. stream.removeTrack(sender.track);
  1183. }
  1184. this.dispatchEvent(new Event('negotiationneeded'));
  1185. }
  1186. };
  1187. }
  1188. function shimPeerConnection$2(window, browserDetails) {
  1189. if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) {
  1190. // very basic support for old versions.
  1191. window.RTCPeerConnection = window.webkitRTCPeerConnection;
  1192. }
  1193. if (!window.RTCPeerConnection) {
  1194. return;
  1195. }
  1196. // shim implicit creation of RTCSessionDescription/RTCIceCandidate
  1197. if (browserDetails.version < 53) {
  1198. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  1199. .forEach(function(method) {
  1200. const nativeMethod = window.RTCPeerConnection.prototype[method];
  1201. const methodObj = {[method]() {
  1202. arguments[0] = new ((method === 'addIceCandidate') ?
  1203. window.RTCIceCandidate :
  1204. window.RTCSessionDescription)(arguments[0]);
  1205. return nativeMethod.apply(this, arguments);
  1206. }};
  1207. window.RTCPeerConnection.prototype[method] = methodObj[method];
  1208. });
  1209. }
  1210. }
  1211. // Attempt to fix ONN in plan-b mode.
  1212. function fixNegotiationNeeded(window, browserDetails) {
  1213. wrapPeerConnectionEvent(window, 'negotiationneeded', e => {
  1214. const pc = e.target;
  1215. if (browserDetails.version < 72 || (pc.getConfiguration &&
  1216. pc.getConfiguration().sdpSemantics === 'plan-b')) {
  1217. if (pc.signalingState !== 'stable') {
  1218. return;
  1219. }
  1220. }
  1221. return e;
  1222. });
  1223. }
  1224. var chromeShim = /*#__PURE__*/Object.freeze({
  1225. __proto__: null,
  1226. shimMediaStream: shimMediaStream,
  1227. shimOnTrack: shimOnTrack$1,
  1228. shimGetSendersWithDtmf: shimGetSendersWithDtmf,
  1229. shimGetStats: shimGetStats,
  1230. shimSenderReceiverGetStats: shimSenderReceiverGetStats,
  1231. shimAddTrackRemoveTrackWithNative: shimAddTrackRemoveTrackWithNative,
  1232. shimAddTrackRemoveTrack: shimAddTrackRemoveTrack,
  1233. shimPeerConnection: shimPeerConnection$2,
  1234. fixNegotiationNeeded: fixNegotiationNeeded,
  1235. shimGetUserMedia: shimGetUserMedia$3,
  1236. shimGetDisplayMedia: shimGetDisplayMedia$2
  1237. });
  1238. /*
  1239. * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
  1240. *
  1241. * Use of this source code is governed by a BSD-style license
  1242. * that can be found in the LICENSE file in the root of the source
  1243. * tree.
  1244. */
  1245. // Edge does not like
  1246. // 1) stun: filtered after 14393 unless ?transport=udp is present
  1247. // 2) turn: that does not have all of turn:host:port?transport=udp
  1248. // 3) turn: with ipv6 addresses
  1249. // 4) turn: occurring muliple times
  1250. function filterIceServers$1(iceServers, edgeVersion) {
  1251. let hasTurn = false;
  1252. iceServers = JSON.parse(JSON.stringify(iceServers));
  1253. return iceServers.filter(server => {
  1254. if (server && (server.urls || server.url)) {
  1255. let urls = server.urls || server.url;
  1256. if (server.url && !server.urls) {
  1257. deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  1258. }
  1259. const isString = typeof urls === 'string';
  1260. if (isString) {
  1261. urls = [urls];
  1262. }
  1263. urls = urls.filter(url => {
  1264. // filter STUN unconditionally.
  1265. if (url.indexOf('stun:') === 0) {
  1266. return false;
  1267. }
  1268. const validTurn = url.startsWith('turn') &&
  1269. !url.startsWith('turn:[') &&
  1270. url.includes('transport=udp');
  1271. if (validTurn && !hasTurn) {
  1272. hasTurn = true;
  1273. return true;
  1274. }
  1275. return validTurn && !hasTurn;
  1276. });
  1277. delete server.url;
  1278. server.urls = isString ? urls[0] : urls;
  1279. return !!urls.length;
  1280. }
  1281. });
  1282. }
  1283. function createCommonjsModule(fn) {
  1284. var module = { exports: {} };
  1285. return fn(module, module.exports), module.exports;
  1286. }
  1287. /* eslint-env node */
  1288. var sdp = createCommonjsModule(function (module) {
  1289. // SDP helpers.
  1290. var SDPUtils = {};
  1291. // Generate an alphanumeric identifier for cname or mids.
  1292. // TODO: use UUIDs instead? https://gist.github.com/jed/982883
  1293. SDPUtils.generateIdentifier = function() {
  1294. return Math.random().toString(36).substr(2, 10);
  1295. };
  1296. // The RTCP CNAME used by all peerconnections from the same JS.
  1297. SDPUtils.localCName = SDPUtils.generateIdentifier();
  1298. // Splits SDP into lines, dealing with both CRLF and LF.
  1299. SDPUtils.splitLines = function(blob) {
  1300. return blob.trim().split('\n').map(function(line) {
  1301. return line.trim();
  1302. });
  1303. };
  1304. // Splits SDP into sessionpart and mediasections. Ensures CRLF.
  1305. SDPUtils.splitSections = function(blob) {
  1306. var parts = blob.split('\nm=');
  1307. return parts.map(function(part, index) {
  1308. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  1309. });
  1310. };
  1311. // returns the session description.
  1312. SDPUtils.getDescription = function(blob) {
  1313. var sections = SDPUtils.splitSections(blob);
  1314. return sections && sections[0];
  1315. };
  1316. // returns the individual media sections.
  1317. SDPUtils.getMediaSections = function(blob) {
  1318. var sections = SDPUtils.splitSections(blob);
  1319. sections.shift();
  1320. return sections;
  1321. };
  1322. // Returns lines that start with a certain prefix.
  1323. SDPUtils.matchPrefix = function(blob, prefix) {
  1324. return SDPUtils.splitLines(blob).filter(function(line) {
  1325. return line.indexOf(prefix) === 0;
  1326. });
  1327. };
  1328. // Parses an ICE candidate line. Sample input:
  1329. // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
  1330. // rport 55996"
  1331. SDPUtils.parseCandidate = function(line) {
  1332. var parts;
  1333. // Parse both variants.
  1334. if (line.indexOf('a=candidate:') === 0) {
  1335. parts = line.substring(12).split(' ');
  1336. } else {
  1337. parts = line.substring(10).split(' ');
  1338. }
  1339. var candidate = {
  1340. foundation: parts[0],
  1341. component: parseInt(parts[1], 10),
  1342. protocol: parts[2].toLowerCase(),
  1343. priority: parseInt(parts[3], 10),
  1344. ip: parts[4],
  1345. address: parts[4], // address is an alias for ip.
  1346. port: parseInt(parts[5], 10),
  1347. // skip parts[6] == 'typ'
  1348. type: parts[7]
  1349. };
  1350. for (var i = 8; i < parts.length; i += 2) {
  1351. switch (parts[i]) {
  1352. case 'raddr':
  1353. candidate.relatedAddress = parts[i + 1];
  1354. break;
  1355. case 'rport':
  1356. candidate.relatedPort = parseInt(parts[i + 1], 10);
  1357. break;
  1358. case 'tcptype':
  1359. candidate.tcpType = parts[i + 1];
  1360. break;
  1361. case 'ufrag':
  1362. candidate.ufrag = parts[i + 1]; // for backward compability.
  1363. candidate.usernameFragment = parts[i + 1];
  1364. break;
  1365. default: // extension handling, in particular ufrag
  1366. candidate[parts[i]] = parts[i + 1];
  1367. break;
  1368. }
  1369. }
  1370. return candidate;
  1371. };
  1372. // Translates a candidate object into SDP candidate attribute.
  1373. SDPUtils.writeCandidate = function(candidate) {
  1374. var sdp = [];
  1375. sdp.push(candidate.foundation);
  1376. sdp.push(candidate.component);
  1377. sdp.push(candidate.protocol.toUpperCase());
  1378. sdp.push(candidate.priority);
  1379. sdp.push(candidate.address || candidate.ip);
  1380. sdp.push(candidate.port);
  1381. var type = candidate.type;
  1382. sdp.push('typ');
  1383. sdp.push(type);
  1384. if (type !== 'host' && candidate.relatedAddress &&
  1385. candidate.relatedPort) {
  1386. sdp.push('raddr');
  1387. sdp.push(candidate.relatedAddress);
  1388. sdp.push('rport');
  1389. sdp.push(candidate.relatedPort);
  1390. }
  1391. if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
  1392. sdp.push('tcptype');
  1393. sdp.push(candidate.tcpType);
  1394. }
  1395. if (candidate.usernameFragment || candidate.ufrag) {
  1396. sdp.push('ufrag');
  1397. sdp.push(candidate.usernameFragment || candidate.ufrag);
  1398. }
  1399. return 'candidate:' + sdp.join(' ');
  1400. };
  1401. // Parses an ice-options line, returns an array of option tags.
  1402. // a=ice-options:foo bar
  1403. SDPUtils.parseIceOptions = function(line) {
  1404. return line.substr(14).split(' ');
  1405. };
  1406. // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
  1407. // a=rtpmap:111 opus/48000/2
  1408. SDPUtils.parseRtpMap = function(line) {
  1409. var parts = line.substr(9).split(' ');
  1410. var parsed = {
  1411. payloadType: parseInt(parts.shift(), 10) // was: id
  1412. };
  1413. parts = parts[0].split('/');
  1414. parsed.name = parts[0];
  1415. parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
  1416. parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
  1417. // legacy alias, got renamed back to channels in ORTC.
  1418. parsed.numChannels = parsed.channels;
  1419. return parsed;
  1420. };
  1421. // Generate an a=rtpmap line from RTCRtpCodecCapability or
  1422. // RTCRtpCodecParameters.
  1423. SDPUtils.writeRtpMap = function(codec) {
  1424. var pt = codec.payloadType;
  1425. if (codec.preferredPayloadType !== undefined) {
  1426. pt = codec.preferredPayloadType;
  1427. }
  1428. var channels = codec.channels || codec.numChannels || 1;
  1429. return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
  1430. (channels !== 1 ? '/' + channels : '') + '\r\n';
  1431. };
  1432. // Parses an a=extmap line (headerextension from RFC 5285). Sample input:
  1433. // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  1434. // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
  1435. SDPUtils.parseExtmap = function(line) {
  1436. var parts = line.substr(9).split(' ');
  1437. return {
  1438. id: parseInt(parts[0], 10),
  1439. direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
  1440. uri: parts[1]
  1441. };
  1442. };
  1443. // Generates a=extmap line from RTCRtpHeaderExtensionParameters or
  1444. // RTCRtpHeaderExtension.
  1445. SDPUtils.writeExtmap = function(headerExtension) {
  1446. return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
  1447. (headerExtension.direction && headerExtension.direction !== 'sendrecv'
  1448. ? '/' + headerExtension.direction
  1449. : '') +
  1450. ' ' + headerExtension.uri + '\r\n';
  1451. };
  1452. // Parses an ftmp line, returns dictionary. Sample input:
  1453. // a=fmtp:96 vbr=on;cng=on
  1454. // Also deals with vbr=on; cng=on
  1455. SDPUtils.parseFmtp = function(line) {
  1456. var parsed = {};
  1457. var kv;
  1458. var parts = line.substr(line.indexOf(' ') + 1).split(';');
  1459. for (var j = 0; j < parts.length; j++) {
  1460. kv = parts[j].trim().split('=');
  1461. parsed[kv[0].trim()] = kv[1];
  1462. }
  1463. return parsed;
  1464. };
  1465. // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
  1466. SDPUtils.writeFmtp = function(codec) {
  1467. var line = '';
  1468. var pt = codec.payloadType;
  1469. if (codec.preferredPayloadType !== undefined) {
  1470. pt = codec.preferredPayloadType;
  1471. }
  1472. if (codec.parameters && Object.keys(codec.parameters).length) {
  1473. var params = [];
  1474. Object.keys(codec.parameters).forEach(function(param) {
  1475. if (codec.parameters[param]) {
  1476. params.push(param + '=' + codec.parameters[param]);
  1477. } else {
  1478. params.push(param);
  1479. }
  1480. });
  1481. line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
  1482. }
  1483. return line;
  1484. };
  1485. // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
  1486. // a=rtcp-fb:98 nack rpsi
  1487. SDPUtils.parseRtcpFb = function(line) {
  1488. var parts = line.substr(line.indexOf(' ') + 1).split(' ');
  1489. return {
  1490. type: parts.shift(),
  1491. parameter: parts.join(' ')
  1492. };
  1493. };
  1494. // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
  1495. SDPUtils.writeRtcpFb = function(codec) {
  1496. var lines = '';
  1497. var pt = codec.payloadType;
  1498. if (codec.preferredPayloadType !== undefined) {
  1499. pt = codec.preferredPayloadType;
  1500. }
  1501. if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
  1502. // FIXME: special handling for trr-int?
  1503. codec.rtcpFeedback.forEach(function(fb) {
  1504. lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
  1505. (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
  1506. '\r\n';
  1507. });
  1508. }
  1509. return lines;
  1510. };
  1511. // Parses an RFC 5576 ssrc media attribute. Sample input:
  1512. // a=ssrc:3735928559 cname:something
  1513. SDPUtils.parseSsrcMedia = function(line) {
  1514. var sp = line.indexOf(' ');
  1515. var parts = {
  1516. ssrc: parseInt(line.substr(7, sp - 7), 10)
  1517. };
  1518. var colon = line.indexOf(':', sp);
  1519. if (colon > -1) {
  1520. parts.attribute = line.substr(sp + 1, colon - sp - 1);
  1521. parts.value = line.substr(colon + 1);
  1522. } else {
  1523. parts.attribute = line.substr(sp + 1);
  1524. }
  1525. return parts;
  1526. };
  1527. SDPUtils.parseSsrcGroup = function(line) {
  1528. var parts = line.substr(13).split(' ');
  1529. return {
  1530. semantics: parts.shift(),
  1531. ssrcs: parts.map(function(ssrc) {
  1532. return parseInt(ssrc, 10);
  1533. })
  1534. };
  1535. };
  1536. // Extracts the MID (RFC 5888) from a media section.
  1537. // returns the MID or undefined if no mid line was found.
  1538. SDPUtils.getMid = function(mediaSection) {
  1539. var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
  1540. if (mid) {
  1541. return mid.substr(6);
  1542. }
  1543. };
  1544. SDPUtils.parseFingerprint = function(line) {
  1545. var parts = line.substr(14).split(' ');
  1546. return {
  1547. algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.
  1548. value: parts[1]
  1549. };
  1550. };
  1551. // Extracts DTLS parameters from SDP media section or sessionpart.
  1552. // FIXME: for consistency with other functions this should only
  1553. // get the fingerprint line as input. See also getIceParameters.
  1554. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
  1555. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
  1556. 'a=fingerprint:');
  1557. // Note: a=setup line is ignored since we use the 'auto' role.
  1558. // Note2: 'algorithm' is not case sensitive except in Edge.
  1559. return {
  1560. role: 'auto',
  1561. fingerprints: lines.map(SDPUtils.parseFingerprint)
  1562. };
  1563. };
  1564. // Serializes DTLS parameters to SDP.
  1565. SDPUtils.writeDtlsParameters = function(params, setupType) {
  1566. var sdp = 'a=setup:' + setupType + '\r\n';
  1567. params.fingerprints.forEach(function(fp) {
  1568. sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
  1569. });
  1570. return sdp;
  1571. };
  1572. // Parses a=crypto lines into
  1573. // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#dictionary-rtcsrtpsdesparameters-members
  1574. SDPUtils.parseCryptoLine = function(line) {
  1575. var parts = line.substr(9).split(' ');
  1576. return {
  1577. tag: parseInt(parts[0], 10),
  1578. cryptoSuite: parts[1],
  1579. keyParams: parts[2],
  1580. sessionParams: parts.slice(3),
  1581. };
  1582. };
  1583. SDPUtils.writeCryptoLine = function(parameters) {
  1584. return 'a=crypto:' + parameters.tag + ' ' +
  1585. parameters.cryptoSuite + ' ' +
  1586. (typeof parameters.keyParams === 'object'
  1587. ? SDPUtils.writeCryptoKeyParams(parameters.keyParams)
  1588. : parameters.keyParams) +
  1589. (parameters.sessionParams ? ' ' + parameters.sessionParams.join(' ') : '') +
  1590. '\r\n';
  1591. };
  1592. // Parses the crypto key parameters into
  1593. // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#rtcsrtpkeyparam*
  1594. SDPUtils.parseCryptoKeyParams = function(keyParams) {
  1595. if (keyParams.indexOf('inline:') !== 0) {
  1596. return null;
  1597. }
  1598. var parts = keyParams.substr(7).split('|');
  1599. return {
  1600. keyMethod: 'inline',
  1601. keySalt: parts[0],
  1602. lifeTime: parts[1],
  1603. mkiValue: parts[2] ? parts[2].split(':')[0] : undefined,
  1604. mkiLength: parts[2] ? parts[2].split(':')[1] : undefined,
  1605. };
  1606. };
  1607. SDPUtils.writeCryptoKeyParams = function(keyParams) {
  1608. return keyParams.keyMethod + ':'
  1609. + keyParams.keySalt +
  1610. (keyParams.lifeTime ? '|' + keyParams.lifeTime : '') +
  1611. (keyParams.mkiValue && keyParams.mkiLength
  1612. ? '|' + keyParams.mkiValue + ':' + keyParams.mkiLength
  1613. : '');
  1614. };
  1615. // Extracts all SDES paramters.
  1616. SDPUtils.getCryptoParameters = function(mediaSection, sessionpart) {
  1617. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
  1618. 'a=crypto:');
  1619. return lines.map(SDPUtils.parseCryptoLine);
  1620. };
  1621. // Parses ICE information from SDP media section or sessionpart.
  1622. // FIXME: for consistency with other functions this should only
  1623. // get the ice-ufrag and ice-pwd lines as input.
  1624. SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
  1625. var ufrag = SDPUtils.matchPrefix(mediaSection + sessionpart,
  1626. 'a=ice-ufrag:')[0];
  1627. var pwd = SDPUtils.matchPrefix(mediaSection + sessionpart,
  1628. 'a=ice-pwd:')[0];
  1629. if (!(ufrag && pwd)) {
  1630. return null;
  1631. }
  1632. return {
  1633. usernameFragment: ufrag.substr(12),
  1634. password: pwd.substr(10),
  1635. };
  1636. };
  1637. // Serializes ICE parameters to SDP.
  1638. SDPUtils.writeIceParameters = function(params) {
  1639. return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
  1640. 'a=ice-pwd:' + params.password + '\r\n';
  1641. };
  1642. // Parses the SDP media section and returns RTCRtpParameters.
  1643. SDPUtils.parseRtpParameters = function(mediaSection) {
  1644. var description = {
  1645. codecs: [],
  1646. headerExtensions: [],
  1647. fecMechanisms: [],
  1648. rtcp: []
  1649. };
  1650. var lines = SDPUtils.splitLines(mediaSection);
  1651. var mline = lines[0].split(' ');
  1652. for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
  1653. var pt = mline[i];
  1654. var rtpmapline = SDPUtils.matchPrefix(
  1655. mediaSection, 'a=rtpmap:' + pt + ' ')[0];
  1656. if (rtpmapline) {
  1657. var codec = SDPUtils.parseRtpMap(rtpmapline);
  1658. var fmtps = SDPUtils.matchPrefix(
  1659. mediaSection, 'a=fmtp:' + pt + ' ');
  1660. // Only the first a=fmtp:<pt> is considered.
  1661. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
  1662. codec.rtcpFeedback = SDPUtils.matchPrefix(
  1663. mediaSection, 'a=rtcp-fb:' + pt + ' ')
  1664. .map(SDPUtils.parseRtcpFb);
  1665. description.codecs.push(codec);
  1666. // parse FEC mechanisms from rtpmap lines.
  1667. switch (codec.name.toUpperCase()) {
  1668. case 'RED':
  1669. case 'ULPFEC':
  1670. description.fecMechanisms.push(codec.name.toUpperCase());
  1671. break;
  1672. }
  1673. }
  1674. }
  1675. SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
  1676. description.headerExtensions.push(SDPUtils.parseExtmap(line));
  1677. });
  1678. // FIXME: parse rtcp.
  1679. return description;
  1680. };
  1681. // Generates parts of the SDP media section describing the capabilities /
  1682. // parameters.
  1683. SDPUtils.writeRtpDescription = function(kind, caps) {
  1684. var sdp = '';
  1685. // Build the mline.
  1686. sdp += 'm=' + kind + ' ';
  1687. sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
  1688. sdp += ' UDP/TLS/RTP/SAVPF ';
  1689. sdp += caps.codecs.map(function(codec) {
  1690. if (codec.preferredPayloadType !== undefined) {
  1691. return codec.preferredPayloadType;
  1692. }
  1693. return codec.payloadType;
  1694. }).join(' ') + '\r\n';
  1695. sdp += 'c=IN IP4 0.0.0.0\r\n';
  1696. sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
  1697. // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
  1698. caps.codecs.forEach(function(codec) {
  1699. sdp += SDPUtils.writeRtpMap(codec);
  1700. sdp += SDPUtils.writeFmtp(codec);
  1701. sdp += SDPUtils.writeRtcpFb(codec);
  1702. });
  1703. var maxptime = 0;
  1704. caps.codecs.forEach(function(codec) {
  1705. if (codec.maxptime > maxptime) {
  1706. maxptime = codec.maxptime;
  1707. }
  1708. });
  1709. if (maxptime > 0) {
  1710. sdp += 'a=maxptime:' + maxptime + '\r\n';
  1711. }
  1712. sdp += 'a=rtcp-mux\r\n';
  1713. if (caps.headerExtensions) {
  1714. caps.headerExtensions.forEach(function(extension) {
  1715. sdp += SDPUtils.writeExtmap(extension);
  1716. });
  1717. }
  1718. // FIXME: write fecMechanisms.
  1719. return sdp;
  1720. };
  1721. // Parses the SDP media section and returns an array of
  1722. // RTCRtpEncodingParameters.
  1723. SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
  1724. var encodingParameters = [];
  1725. var description = SDPUtils.parseRtpParameters(mediaSection);
  1726. var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
  1727. var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
  1728. // filter a=ssrc:... cname:, ignore PlanB-msid
  1729. var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  1730. .map(function(line) {
  1731. return SDPUtils.parseSsrcMedia(line);
  1732. })
  1733. .filter(function(parts) {
  1734. return parts.attribute === 'cname';
  1735. });
  1736. var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
  1737. var secondarySsrc;
  1738. var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
  1739. .map(function(line) {
  1740. var parts = line.substr(17).split(' ');
  1741. return parts.map(function(part) {
  1742. return parseInt(part, 10);
  1743. });
  1744. });
  1745. if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
  1746. secondarySsrc = flows[0][1];
  1747. }
  1748. description.codecs.forEach(function(codec) {
  1749. if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
  1750. var encParam = {
  1751. ssrc: primarySsrc,
  1752. codecPayloadType: parseInt(codec.parameters.apt, 10)
  1753. };
  1754. if (primarySsrc && secondarySsrc) {
  1755. encParam.rtx = {ssrc: secondarySsrc};
  1756. }
  1757. encodingParameters.push(encParam);
  1758. if (hasRed) {
  1759. encParam = JSON.parse(JSON.stringify(encParam));
  1760. encParam.fec = {
  1761. ssrc: primarySsrc,
  1762. mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
  1763. };
  1764. encodingParameters.push(encParam);
  1765. }
  1766. }
  1767. });
  1768. if (encodingParameters.length === 0 && primarySsrc) {
  1769. encodingParameters.push({
  1770. ssrc: primarySsrc
  1771. });
  1772. }
  1773. // we support both b=AS and b=TIAS but interpret AS as TIAS.
  1774. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
  1775. if (bandwidth.length) {
  1776. if (bandwidth[0].indexOf('b=TIAS:') === 0) {
  1777. bandwidth = parseInt(bandwidth[0].substr(7), 10);
  1778. } else if (bandwidth[0].indexOf('b=AS:') === 0) {
  1779. // use formula from JSEP to convert b=AS to TIAS value.
  1780. bandwidth = parseInt(bandwidth[0].substr(5), 10) * 1000 * 0.95
  1781. - (50 * 40 * 8);
  1782. } else {
  1783. bandwidth = undefined;
  1784. }
  1785. encodingParameters.forEach(function(params) {
  1786. params.maxBitrate = bandwidth;
  1787. });
  1788. }
  1789. return encodingParameters;
  1790. };
  1791. // parses http://draft.ortc.org/#rtcrtcpparameters*
  1792. SDPUtils.parseRtcpParameters = function(mediaSection) {
  1793. var rtcpParameters = {};
  1794. // Gets the first SSRC. Note tha with RTX there might be multiple
  1795. // SSRCs.
  1796. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  1797. .map(function(line) {
  1798. return SDPUtils.parseSsrcMedia(line);
  1799. })
  1800. .filter(function(obj) {
  1801. return obj.attribute === 'cname';
  1802. })[0];
  1803. if (remoteSsrc) {
  1804. rtcpParameters.cname = remoteSsrc.value;
  1805. rtcpParameters.ssrc = remoteSsrc.ssrc;
  1806. }
  1807. // Edge uses the compound attribute instead of reducedSize
  1808. // compound is !reducedSize
  1809. var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
  1810. rtcpParameters.reducedSize = rsize.length > 0;
  1811. rtcpParameters.compound = rsize.length === 0;
  1812. // parses the rtcp-mux attrіbute.
  1813. // Note that Edge does not support unmuxed RTCP.
  1814. var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
  1815. rtcpParameters.mux = mux.length > 0;
  1816. return rtcpParameters;
  1817. };
  1818. // parses either a=msid: or a=ssrc:... msid lines and returns
  1819. // the id of the MediaStream and MediaStreamTrack.
  1820. SDPUtils.parseMsid = function(mediaSection) {
  1821. var parts;
  1822. var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
  1823. if (spec.length === 1) {
  1824. parts = spec[0].substr(7).split(' ');
  1825. return {stream: parts[0], track: parts[1]};
  1826. }
  1827. var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  1828. .map(function(line) {
  1829. return SDPUtils.parseSsrcMedia(line);
  1830. })
  1831. .filter(function(msidParts) {
  1832. return msidParts.attribute === 'msid';
  1833. });
  1834. if (planB.length > 0) {
  1835. parts = planB[0].value.split(' ');
  1836. return {stream: parts[0], track: parts[1]};
  1837. }
  1838. };
  1839. // SCTP
  1840. // parses draft-ietf-mmusic-sctp-sdp-26 first and falls back
  1841. // to draft-ietf-mmusic-sctp-sdp-05
  1842. SDPUtils.parseSctpDescription = function(mediaSection) {
  1843. var mline = SDPUtils.parseMLine(mediaSection);
  1844. var maxSizeLine = SDPUtils.matchPrefix(mediaSection, 'a=max-message-size:');
  1845. var maxMessageSize;
  1846. if (maxSizeLine.length > 0) {
  1847. maxMessageSize = parseInt(maxSizeLine[0].substr(19), 10);
  1848. }
  1849. if (isNaN(maxMessageSize)) {
  1850. maxMessageSize = 65536;
  1851. }
  1852. var sctpPort = SDPUtils.matchPrefix(mediaSection, 'a=sctp-port:');
  1853. if (sctpPort.length > 0) {
  1854. return {
  1855. port: parseInt(sctpPort[0].substr(12), 10),
  1856. protocol: mline.fmt,
  1857. maxMessageSize: maxMessageSize
  1858. };
  1859. }
  1860. var sctpMapLines = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:');
  1861. if (sctpMapLines.length > 0) {
  1862. var parts = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:')[0]
  1863. .substr(10)
  1864. .split(' ');
  1865. return {
  1866. port: parseInt(parts[0], 10),
  1867. protocol: parts[1],
  1868. maxMessageSize: maxMessageSize
  1869. };
  1870. }
  1871. };
  1872. // SCTP
  1873. // outputs the draft-ietf-mmusic-sctp-sdp-26 version that all browsers
  1874. // support by now receiving in this format, unless we originally parsed
  1875. // as the draft-ietf-mmusic-sctp-sdp-05 format (indicated by the m-line
  1876. // protocol of DTLS/SCTP -- without UDP/ or TCP/)
  1877. SDPUtils.writeSctpDescription = function(media, sctp) {
  1878. var output = [];
  1879. if (media.protocol !== 'DTLS/SCTP') {
  1880. output = [
  1881. 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.protocol + '\r\n',
  1882. 'c=IN IP4 0.0.0.0\r\n',
  1883. 'a=sctp-port:' + sctp.port + '\r\n'
  1884. ];
  1885. } else {
  1886. output = [
  1887. 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.port + '\r\n',
  1888. 'c=IN IP4 0.0.0.0\r\n',
  1889. 'a=sctpmap:' + sctp.port + ' ' + sctp.protocol + ' 65535\r\n'
  1890. ];
  1891. }
  1892. if (sctp.maxMessageSize !== undefined) {
  1893. output.push('a=max-message-size:' + sctp.maxMessageSize + '\r\n');
  1894. }
  1895. return output.join('');
  1896. };
  1897. // Generate a session ID for SDP.
  1898. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
  1899. // recommends using a cryptographically random +ve 64-bit value
  1900. // but right now this should be acceptable and within the right range
  1901. SDPUtils.generateSessionId = function() {
  1902. return Math.random().toString().substr(2, 21);
  1903. };
  1904. // Write boilder plate for start of SDP
  1905. // sessId argument is optional - if not supplied it will
  1906. // be generated randomly
  1907. // sessVersion is optional and defaults to 2
  1908. // sessUser is optional and defaults to 'thisisadapterortc'
  1909. SDPUtils.writeSessionBoilerplate = function(sessId, sessVer, sessUser) {
  1910. var sessionId;
  1911. var version = sessVer !== undefined ? sessVer : 2;
  1912. if (sessId) {
  1913. sessionId = sessId;
  1914. } else {
  1915. sessionId = SDPUtils.generateSessionId();
  1916. }
  1917. var user = sessUser || 'thisisadapterortc';
  1918. // FIXME: sess-id should be an NTP timestamp.
  1919. return 'v=0\r\n' +
  1920. 'o=' + user + ' ' + sessionId + ' ' + version +
  1921. ' IN IP4 127.0.0.1\r\n' +
  1922. 's=-\r\n' +
  1923. 't=0 0\r\n';
  1924. };
  1925. SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
  1926. var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
  1927. // Map ICE parameters (ufrag, pwd) to SDP.
  1928. sdp += SDPUtils.writeIceParameters(
  1929. transceiver.iceGatherer.getLocalParameters());
  1930. // Map DTLS parameters to SDP.
  1931. sdp += SDPUtils.writeDtlsParameters(
  1932. transceiver.dtlsTransport.getLocalParameters(),
  1933. type === 'offer' ? 'actpass' : 'active');
  1934. sdp += 'a=mid:' + transceiver.mid + '\r\n';
  1935. if (transceiver.direction) {
  1936. sdp += 'a=' + transceiver.direction + '\r\n';
  1937. } else if (transceiver.rtpSender && transceiver.rtpReceiver) {
  1938. sdp += 'a=sendrecv\r\n';
  1939. } else if (transceiver.rtpSender) {
  1940. sdp += 'a=sendonly\r\n';
  1941. } else if (transceiver.rtpReceiver) {
  1942. sdp += 'a=recvonly\r\n';
  1943. } else {
  1944. sdp += 'a=inactive\r\n';
  1945. }
  1946. if (transceiver.rtpSender) {
  1947. // spec.
  1948. var msid = 'msid:' + stream.id + ' ' +
  1949. transceiver.rtpSender.track.id + '\r\n';
  1950. sdp += 'a=' + msid;
  1951. // for Chrome.
  1952. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  1953. ' ' + msid;
  1954. if (transceiver.sendEncodingParameters[0].rtx) {
  1955. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  1956. ' ' + msid;
  1957. sdp += 'a=ssrc-group:FID ' +
  1958. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  1959. transceiver.sendEncodingParameters[0].rtx.ssrc +
  1960. '\r\n';
  1961. }
  1962. }
  1963. // FIXME: this should be written by writeRtpDescription.
  1964. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  1965. ' cname:' + SDPUtils.localCName + '\r\n';
  1966. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  1967. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  1968. ' cname:' + SDPUtils.localCName + '\r\n';
  1969. }
  1970. return sdp;
  1971. };
  1972. // Gets the direction from the mediaSection or the sessionpart.
  1973. SDPUtils.getDirection = function(mediaSection, sessionpart) {
  1974. // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
  1975. var lines = SDPUtils.splitLines(mediaSection);
  1976. for (var i = 0; i < lines.length; i++) {
  1977. switch (lines[i]) {
  1978. case 'a=sendrecv':
  1979. case 'a=sendonly':
  1980. case 'a=recvonly':
  1981. case 'a=inactive':
  1982. return lines[i].substr(2);
  1983. // FIXME: What should happen here?
  1984. }
  1985. }
  1986. if (sessionpart) {
  1987. return SDPUtils.getDirection(sessionpart);
  1988. }
  1989. return 'sendrecv';
  1990. };
  1991. SDPUtils.getKind = function(mediaSection) {
  1992. var lines = SDPUtils.splitLines(mediaSection);
  1993. var mline = lines[0].split(' ');
  1994. return mline[0].substr(2);
  1995. };
  1996. SDPUtils.isRejected = function(mediaSection) {
  1997. return mediaSection.split(' ', 2)[1] === '0';
  1998. };
  1999. SDPUtils.parseMLine = function(mediaSection) {
  2000. var lines = SDPUtils.splitLines(mediaSection);
  2001. var parts = lines[0].substr(2).split(' ');
  2002. return {
  2003. kind: parts[0],
  2004. port: parseInt(parts[1], 10),
  2005. protocol: parts[2],
  2006. fmt: parts.slice(3).join(' ')
  2007. };
  2008. };
  2009. SDPUtils.parseOLine = function(mediaSection) {
  2010. var line = SDPUtils.matchPrefix(mediaSection, 'o=')[0];
  2011. var parts = line.substr(2).split(' ');
  2012. return {
  2013. username: parts[0],
  2014. sessionId: parts[1],
  2015. sessionVersion: parseInt(parts[2], 10),
  2016. netType: parts[3],
  2017. addressType: parts[4],
  2018. address: parts[5]
  2019. };
  2020. };
  2021. // a very naive interpretation of a valid SDP.
  2022. SDPUtils.isValidSDP = function(blob) {
  2023. if (typeof blob !== 'string' || blob.length === 0) {
  2024. return false;
  2025. }
  2026. var lines = SDPUtils.splitLines(blob);
  2027. for (var i = 0; i < lines.length; i++) {
  2028. if (lines[i].length < 2 || lines[i].charAt(1) !== '=') {
  2029. return false;
  2030. }
  2031. // TODO: check the modifier a bit more.
  2032. }
  2033. return true;
  2034. };
  2035. // Expose public methods.
  2036. {
  2037. module.exports = SDPUtils;
  2038. }
  2039. });
  2040. /*
  2041. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  2042. *
  2043. * Use of this source code is governed by a BSD-style license
  2044. * that can be found in the LICENSE file in the root of the source
  2045. * tree.
  2046. */
  2047. function fixStatsType(stat) {
  2048. return {
  2049. inboundrtp: 'inbound-rtp',
  2050. outboundrtp: 'outbound-rtp',
  2051. candidatepair: 'candidate-pair',
  2052. localcandidate: 'local-candidate',
  2053. remotecandidate: 'remote-candidate'
  2054. }[stat.type] || stat.type;
  2055. }
  2056. function writeMediaSection(transceiver, caps, type, stream, dtlsRole) {
  2057. var sdp$1 = sdp.writeRtpDescription(transceiver.kind, caps);
  2058. // Map ICE parameters (ufrag, pwd) to SDP.
  2059. sdp$1 += sdp.writeIceParameters(
  2060. transceiver.iceGatherer.getLocalParameters());
  2061. // Map DTLS parameters to SDP.
  2062. sdp$1 += sdp.writeDtlsParameters(
  2063. transceiver.dtlsTransport.getLocalParameters(),
  2064. type === 'offer' ? 'actpass' : dtlsRole || 'active');
  2065. sdp$1 += 'a=mid:' + transceiver.mid + '\r\n';
  2066. if (transceiver.rtpSender && transceiver.rtpReceiver) {
  2067. sdp$1 += 'a=sendrecv\r\n';
  2068. } else if (transceiver.rtpSender) {
  2069. sdp$1 += 'a=sendonly\r\n';
  2070. } else if (transceiver.rtpReceiver) {
  2071. sdp$1 += 'a=recvonly\r\n';
  2072. } else {
  2073. sdp$1 += 'a=inactive\r\n';
  2074. }
  2075. if (transceiver.rtpSender) {
  2076. var trackId = transceiver.rtpSender._initialTrackId ||
  2077. transceiver.rtpSender.track.id;
  2078. transceiver.rtpSender._initialTrackId = trackId;
  2079. // spec.
  2080. var msid = 'msid:' + (stream ? stream.id : '-') + ' ' +
  2081. trackId + '\r\n';
  2082. sdp$1 += 'a=' + msid;
  2083. // for Chrome. Legacy should no longer be required.
  2084. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2085. ' ' + msid;
  2086. // RTX
  2087. if (transceiver.sendEncodingParameters[0].rtx) {
  2088. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2089. ' ' + msid;
  2090. sdp$1 += 'a=ssrc-group:FID ' +
  2091. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  2092. transceiver.sendEncodingParameters[0].rtx.ssrc +
  2093. '\r\n';
  2094. }
  2095. }
  2096. // FIXME: this should be written by writeRtpDescription.
  2097. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2098. ' cname:' + sdp.localCName + '\r\n';
  2099. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  2100. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2101. ' cname:' + sdp.localCName + '\r\n';
  2102. }
  2103. return sdp$1;
  2104. }
  2105. // Edge does not like
  2106. // 1) stun: filtered after 14393 unless ?transport=udp is present
  2107. // 2) turn: that does not have all of turn:host:port?transport=udp
  2108. // 3) turn: with ipv6 addresses
  2109. // 4) turn: occurring muliple times
  2110. function filterIceServers(iceServers, edgeVersion) {
  2111. var hasTurn = false;
  2112. iceServers = JSON.parse(JSON.stringify(iceServers));
  2113. return iceServers.filter(function(server) {
  2114. if (server && (server.urls || server.url)) {
  2115. var urls = server.urls || server.url;
  2116. if (server.url && !server.urls) {
  2117. console.warn('RTCIceServer.url is deprecated! Use urls instead.');
  2118. }
  2119. var isString = typeof urls === 'string';
  2120. if (isString) {
  2121. urls = [urls];
  2122. }
  2123. urls = urls.filter(function(url) {
  2124. var validTurn = url.indexOf('turn:') === 0 &&
  2125. url.indexOf('transport=udp') !== -1 &&
  2126. url.indexOf('turn:[') === -1 &&
  2127. !hasTurn;
  2128. if (validTurn) {
  2129. hasTurn = true;
  2130. return true;
  2131. }
  2132. return url.indexOf('stun:') === 0 && edgeVersion >= 14393 &&
  2133. url.indexOf('?transport=udp') === -1;
  2134. });
  2135. delete server.url;
  2136. server.urls = isString ? urls[0] : urls;
  2137. return !!urls.length;
  2138. }
  2139. });
  2140. }
  2141. // Determines the intersection of local and remote capabilities.
  2142. function getCommonCapabilities(localCapabilities, remoteCapabilities) {
  2143. var commonCapabilities = {
  2144. codecs: [],
  2145. headerExtensions: [],
  2146. fecMechanisms: []
  2147. };
  2148. var findCodecByPayloadType = function(pt, codecs) {
  2149. pt = parseInt(pt, 10);
  2150. for (var i = 0; i < codecs.length; i++) {
  2151. if (codecs[i].payloadType === pt ||
  2152. codecs[i].preferredPayloadType === pt) {
  2153. return codecs[i];
  2154. }
  2155. }
  2156. };
  2157. var rtxCapabilityMatches = function(lRtx, rRtx, lCodecs, rCodecs) {
  2158. var lCodec = findCodecByPayloadType(lRtx.parameters.apt, lCodecs);
  2159. var rCodec = findCodecByPayloadType(rRtx.parameters.apt, rCodecs);
  2160. return lCodec && rCodec &&
  2161. lCodec.name.toLowerCase() === rCodec.name.toLowerCase();
  2162. };
  2163. localCapabilities.codecs.forEach(function(lCodec) {
  2164. for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
  2165. var rCodec = remoteCapabilities.codecs[i];
  2166. if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
  2167. lCodec.clockRate === rCodec.clockRate) {
  2168. if (lCodec.name.toLowerCase() === 'rtx' &&
  2169. lCodec.parameters && rCodec.parameters.apt) {
  2170. // for RTX we need to find the local rtx that has a apt
  2171. // which points to the same local codec as the remote one.
  2172. if (!rtxCapabilityMatches(lCodec, rCodec,
  2173. localCapabilities.codecs, remoteCapabilities.codecs)) {
  2174. continue;
  2175. }
  2176. }
  2177. rCodec = JSON.parse(JSON.stringify(rCodec)); // deepcopy
  2178. // number of channels is the highest common number of channels
  2179. rCodec.numChannels = Math.min(lCodec.numChannels,
  2180. rCodec.numChannels);
  2181. // push rCodec so we reply with offerer payload type
  2182. commonCapabilities.codecs.push(rCodec);
  2183. // determine common feedback mechanisms
  2184. rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
  2185. for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
  2186. if (lCodec.rtcpFeedback[j].type === fb.type &&
  2187. lCodec.rtcpFeedback[j].parameter === fb.parameter) {
  2188. return true;
  2189. }
  2190. }
  2191. return false;
  2192. });
  2193. // FIXME: also need to determine .parameters
  2194. // see https://github.com/openpeer/ortc/issues/569
  2195. break;
  2196. }
  2197. }
  2198. });
  2199. localCapabilities.headerExtensions.forEach(function(lHeaderExtension) {
  2200. for (var i = 0; i < remoteCapabilities.headerExtensions.length;
  2201. i++) {
  2202. var rHeaderExtension = remoteCapabilities.headerExtensions[i];
  2203. if (lHeaderExtension.uri === rHeaderExtension.uri) {
  2204. commonCapabilities.headerExtensions.push(rHeaderExtension);
  2205. break;
  2206. }
  2207. }
  2208. });
  2209. // FIXME: fecMechanisms
  2210. return commonCapabilities;
  2211. }
  2212. // is action=setLocalDescription with type allowed in signalingState
  2213. function isActionAllowedInSignalingState(action, type, signalingState) {
  2214. return {
  2215. offer: {
  2216. setLocalDescription: ['stable', 'have-local-offer'],
  2217. setRemoteDescription: ['stable', 'have-remote-offer']
  2218. },
  2219. answer: {
  2220. setLocalDescription: ['have-remote-offer', 'have-local-pranswer'],
  2221. setRemoteDescription: ['have-local-offer', 'have-remote-pranswer']
  2222. }
  2223. }[type][action].indexOf(signalingState) !== -1;
  2224. }
  2225. function maybeAddCandidate(iceTransport, candidate) {
  2226. // Edge's internal representation adds some fields therefore
  2227. // not all fieldѕ are taken into account.
  2228. var alreadyAdded = iceTransport.getRemoteCandidates()
  2229. .find(function(remoteCandidate) {
  2230. return candidate.foundation === remoteCandidate.foundation &&
  2231. candidate.ip === remoteCandidate.ip &&
  2232. candidate.port === remoteCandidate.port &&
  2233. candidate.priority === remoteCandidate.priority &&
  2234. candidate.protocol === remoteCandidate.protocol &&
  2235. candidate.type === remoteCandidate.type;
  2236. });
  2237. if (!alreadyAdded) {
  2238. iceTransport.addRemoteCandidate(candidate);
  2239. }
  2240. return !alreadyAdded;
  2241. }
  2242. function makeError(name, description) {
  2243. var e = new Error(description);
  2244. e.name = name;
  2245. // legacy error codes from https://heycam.github.io/webidl/#idl-DOMException-error-names
  2246. e.code = {
  2247. NotSupportedError: 9,
  2248. InvalidStateError: 11,
  2249. InvalidAccessError: 15,
  2250. TypeError: undefined,
  2251. OperationError: undefined
  2252. }[name];
  2253. return e;
  2254. }
  2255. var rtcpeerconnection = function(window, edgeVersion) {
  2256. // https://w3c.github.io/mediacapture-main/#mediastream
  2257. // Helper function to add the track to the stream and
  2258. // dispatch the event ourselves.
  2259. function addTrackToStreamAndFireEvent(track, stream) {
  2260. stream.addTrack(track);
  2261. stream.dispatchEvent(new window.MediaStreamTrackEvent('addtrack',
  2262. {track: track}));
  2263. }
  2264. function removeTrackFromStreamAndFireEvent(track, stream) {
  2265. stream.removeTrack(track);
  2266. stream.dispatchEvent(new window.MediaStreamTrackEvent('removetrack',
  2267. {track: track}));
  2268. }
  2269. function fireAddTrack(pc, track, receiver, streams) {
  2270. var trackEvent = new Event('track');
  2271. trackEvent.track = track;
  2272. trackEvent.receiver = receiver;
  2273. trackEvent.transceiver = {receiver: receiver};
  2274. trackEvent.streams = streams;
  2275. window.setTimeout(function() {
  2276. pc._dispatchEvent('track', trackEvent);
  2277. });
  2278. }
  2279. var RTCPeerConnection = function(config) {
  2280. var pc = this;
  2281. var _eventTarget = document.createDocumentFragment();
  2282. ['addEventListener', 'removeEventListener', 'dispatchEvent']
  2283. .forEach(function(method) {
  2284. pc[method] = _eventTarget[method].bind(_eventTarget);
  2285. });
  2286. this.canTrickleIceCandidates = null;
  2287. this.needNegotiation = false;
  2288. this.localStreams = [];
  2289. this.remoteStreams = [];
  2290. this._localDescription = null;
  2291. this._remoteDescription = null;
  2292. this.signalingState = 'stable';
  2293. this.iceConnectionState = 'new';
  2294. this.connectionState = 'new';
  2295. this.iceGatheringState = 'new';
  2296. config = JSON.parse(JSON.stringify(config || {}));
  2297. this.usingBundle = config.bundlePolicy === 'max-bundle';
  2298. if (config.rtcpMuxPolicy === 'negotiate') {
  2299. throw(makeError('NotSupportedError',
  2300. 'rtcpMuxPolicy \'negotiate\' is not supported'));
  2301. } else if (!config.rtcpMuxPolicy) {
  2302. config.rtcpMuxPolicy = 'require';
  2303. }
  2304. switch (config.iceTransportPolicy) {
  2305. case 'all':
  2306. case 'relay':
  2307. break;
  2308. default:
  2309. config.iceTransportPolicy = 'all';
  2310. break;
  2311. }
  2312. switch (config.bundlePolicy) {
  2313. case 'balanced':
  2314. case 'max-compat':
  2315. case 'max-bundle':
  2316. break;
  2317. default:
  2318. config.bundlePolicy = 'balanced';
  2319. break;
  2320. }
  2321. config.iceServers = filterIceServers(config.iceServers || [], edgeVersion);
  2322. this._iceGatherers = [];
  2323. if (config.iceCandidatePoolSize) {
  2324. for (var i = config.iceCandidatePoolSize; i > 0; i--) {
  2325. this._iceGatherers.push(new window.RTCIceGatherer({
  2326. iceServers: config.iceServers,
  2327. gatherPolicy: config.iceTransportPolicy
  2328. }));
  2329. }
  2330. } else {
  2331. config.iceCandidatePoolSize = 0;
  2332. }
  2333. this._config = config;
  2334. // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
  2335. // everything that is needed to describe a SDP m-line.
  2336. this.transceivers = [];
  2337. this._sdpSessionId = sdp.generateSessionId();
  2338. this._sdpSessionVersion = 0;
  2339. this._dtlsRole = undefined; // role for a=setup to use in answers.
  2340. this._isClosed = false;
  2341. };
  2342. Object.defineProperty(RTCPeerConnection.prototype, 'localDescription', {
  2343. configurable: true,
  2344. get: function() {
  2345. return this._localDescription;
  2346. }
  2347. });
  2348. Object.defineProperty(RTCPeerConnection.prototype, 'remoteDescription', {
  2349. configurable: true,
  2350. get: function() {
  2351. return this._remoteDescription;
  2352. }
  2353. });
  2354. // set up event handlers on prototype
  2355. RTCPeerConnection.prototype.onicecandidate = null;
  2356. RTCPeerConnection.prototype.onaddstream = null;
  2357. RTCPeerConnection.prototype.ontrack = null;
  2358. RTCPeerConnection.prototype.onremovestream = null;
  2359. RTCPeerConnection.prototype.onsignalingstatechange = null;
  2360. RTCPeerConnection.prototype.oniceconnectionstatechange = null;
  2361. RTCPeerConnection.prototype.onconnectionstatechange = null;
  2362. RTCPeerConnection.prototype.onicegatheringstatechange = null;
  2363. RTCPeerConnection.prototype.onnegotiationneeded = null;
  2364. RTCPeerConnection.prototype.ondatachannel = null;
  2365. RTCPeerConnection.prototype._dispatchEvent = function(name, event) {
  2366. if (this._isClosed) {
  2367. return;
  2368. }
  2369. this.dispatchEvent(event);
  2370. if (typeof this['on' + name] === 'function') {
  2371. this['on' + name](event);
  2372. }
  2373. };
  2374. RTCPeerConnection.prototype._emitGatheringStateChange = function() {
  2375. var event = new Event('icegatheringstatechange');
  2376. this._dispatchEvent('icegatheringstatechange', event);
  2377. };
  2378. RTCPeerConnection.prototype.getConfiguration = function() {
  2379. return this._config;
  2380. };
  2381. RTCPeerConnection.prototype.getLocalStreams = function() {
  2382. return this.localStreams;
  2383. };
  2384. RTCPeerConnection.prototype.getRemoteStreams = function() {
  2385. return this.remoteStreams;
  2386. };
  2387. // internal helper to create a transceiver object.
  2388. // (which is not yet the same as the WebRTC 1.0 transceiver)
  2389. RTCPeerConnection.prototype._createTransceiver = function(kind, doNotAdd) {
  2390. var hasBundleTransport = this.transceivers.length > 0;
  2391. var transceiver = {
  2392. track: null,
  2393. iceGatherer: null,
  2394. iceTransport: null,
  2395. dtlsTransport: null,
  2396. localCapabilities: null,
  2397. remoteCapabilities: null,
  2398. rtpSender: null,
  2399. rtpReceiver: null,
  2400. kind: kind,
  2401. mid: null,
  2402. sendEncodingParameters: null,
  2403. recvEncodingParameters: null,
  2404. stream: null,
  2405. associatedRemoteMediaStreams: [],
  2406. wantReceive: true
  2407. };
  2408. if (this.usingBundle && hasBundleTransport) {
  2409. transceiver.iceTransport = this.transceivers[0].iceTransport;
  2410. transceiver.dtlsTransport = this.transceivers[0].dtlsTransport;
  2411. } else {
  2412. var transports = this._createIceAndDtlsTransports();
  2413. transceiver.iceTransport = transports.iceTransport;
  2414. transceiver.dtlsTransport = transports.dtlsTransport;
  2415. }
  2416. if (!doNotAdd) {
  2417. this.transceivers.push(transceiver);
  2418. }
  2419. return transceiver;
  2420. };
  2421. RTCPeerConnection.prototype.addTrack = function(track, stream) {
  2422. if (this._isClosed) {
  2423. throw makeError('InvalidStateError',
  2424. 'Attempted to call addTrack on a closed peerconnection.');
  2425. }
  2426. var alreadyExists = this.transceivers.find(function(s) {
  2427. return s.track === track;
  2428. });
  2429. if (alreadyExists) {
  2430. throw makeError('InvalidAccessError', 'Track already exists.');
  2431. }
  2432. var transceiver;
  2433. for (var i = 0; i < this.transceivers.length; i++) {
  2434. if (!this.transceivers[i].track &&
  2435. this.transceivers[i].kind === track.kind) {
  2436. transceiver = this.transceivers[i];
  2437. }
  2438. }
  2439. if (!transceiver) {
  2440. transceiver = this._createTransceiver(track.kind);
  2441. }
  2442. this._maybeFireNegotiationNeeded();
  2443. if (this.localStreams.indexOf(stream) === -1) {
  2444. this.localStreams.push(stream);
  2445. }
  2446. transceiver.track = track;
  2447. transceiver.stream = stream;
  2448. transceiver.rtpSender = new window.RTCRtpSender(track,
  2449. transceiver.dtlsTransport);
  2450. return transceiver.rtpSender;
  2451. };
  2452. RTCPeerConnection.prototype.addStream = function(stream) {
  2453. var pc = this;
  2454. if (edgeVersion >= 15025) {
  2455. stream.getTracks().forEach(function(track) {
  2456. pc.addTrack(track, stream);
  2457. });
  2458. } else {
  2459. // Clone is necessary for local demos mostly, attaching directly
  2460. // to two different senders does not work (build 10547).
  2461. // Fixed in 15025 (or earlier)
  2462. var clonedStream = stream.clone();
  2463. stream.getTracks().forEach(function(track, idx) {
  2464. var clonedTrack = clonedStream.getTracks()[idx];
  2465. track.addEventListener('enabled', function(event) {
  2466. clonedTrack.enabled = event.enabled;
  2467. });
  2468. });
  2469. clonedStream.getTracks().forEach(function(track) {
  2470. pc.addTrack(track, clonedStream);
  2471. });
  2472. }
  2473. };
  2474. RTCPeerConnection.prototype.removeTrack = function(sender) {
  2475. if (this._isClosed) {
  2476. throw makeError('InvalidStateError',
  2477. 'Attempted to call removeTrack on a closed peerconnection.');
  2478. }
  2479. if (!(sender instanceof window.RTCRtpSender)) {
  2480. throw new TypeError('Argument 1 of RTCPeerConnection.removeTrack ' +
  2481. 'does not implement interface RTCRtpSender.');
  2482. }
  2483. var transceiver = this.transceivers.find(function(t) {
  2484. return t.rtpSender === sender;
  2485. });
  2486. if (!transceiver) {
  2487. throw makeError('InvalidAccessError',
  2488. 'Sender was not created by this connection.');
  2489. }
  2490. var stream = transceiver.stream;
  2491. transceiver.rtpSender.stop();
  2492. transceiver.rtpSender = null;
  2493. transceiver.track = null;
  2494. transceiver.stream = null;
  2495. // remove the stream from the set of local streams
  2496. var localStreams = this.transceivers.map(function(t) {
  2497. return t.stream;
  2498. });
  2499. if (localStreams.indexOf(stream) === -1 &&
  2500. this.localStreams.indexOf(stream) > -1) {
  2501. this.localStreams.splice(this.localStreams.indexOf(stream), 1);
  2502. }
  2503. this._maybeFireNegotiationNeeded();
  2504. };
  2505. RTCPeerConnection.prototype.removeStream = function(stream) {
  2506. var pc = this;
  2507. stream.getTracks().forEach(function(track) {
  2508. var sender = pc.getSenders().find(function(s) {
  2509. return s.track === track;
  2510. });
  2511. if (sender) {
  2512. pc.removeTrack(sender);
  2513. }
  2514. });
  2515. };
  2516. RTCPeerConnection.prototype.getSenders = function() {
  2517. return this.transceivers.filter(function(transceiver) {
  2518. return !!transceiver.rtpSender;
  2519. })
  2520. .map(function(transceiver) {
  2521. return transceiver.rtpSender;
  2522. });
  2523. };
  2524. RTCPeerConnection.prototype.getReceivers = function() {
  2525. return this.transceivers.filter(function(transceiver) {
  2526. return !!transceiver.rtpReceiver;
  2527. })
  2528. .map(function(transceiver) {
  2529. return transceiver.rtpReceiver;
  2530. });
  2531. };
  2532. RTCPeerConnection.prototype._createIceGatherer = function(sdpMLineIndex,
  2533. usingBundle) {
  2534. var pc = this;
  2535. if (usingBundle && sdpMLineIndex > 0) {
  2536. return this.transceivers[0].iceGatherer;
  2537. } else if (this._iceGatherers.length) {
  2538. return this._iceGatherers.shift();
  2539. }
  2540. var iceGatherer = new window.RTCIceGatherer({
  2541. iceServers: this._config.iceServers,
  2542. gatherPolicy: this._config.iceTransportPolicy
  2543. });
  2544. Object.defineProperty(iceGatherer, 'state',
  2545. {value: 'new', writable: true}
  2546. );
  2547. this.transceivers[sdpMLineIndex].bufferedCandidateEvents = [];
  2548. this.transceivers[sdpMLineIndex].bufferCandidates = function(event) {
  2549. var end = !event.candidate || Object.keys(event.candidate).length === 0;
  2550. // polyfill since RTCIceGatherer.state is not implemented in
  2551. // Edge 10547 yet.
  2552. iceGatherer.state = end ? 'completed' : 'gathering';
  2553. if (pc.transceivers[sdpMLineIndex].bufferedCandidateEvents !== null) {
  2554. pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event);
  2555. }
  2556. };
  2557. iceGatherer.addEventListener('localcandidate',
  2558. this.transceivers[sdpMLineIndex].bufferCandidates);
  2559. return iceGatherer;
  2560. };
  2561. // start gathering from an RTCIceGatherer.
  2562. RTCPeerConnection.prototype._gather = function(mid, sdpMLineIndex) {
  2563. var pc = this;
  2564. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  2565. if (iceGatherer.onlocalcandidate) {
  2566. return;
  2567. }
  2568. var bufferedCandidateEvents =
  2569. this.transceivers[sdpMLineIndex].bufferedCandidateEvents;
  2570. this.transceivers[sdpMLineIndex].bufferedCandidateEvents = null;
  2571. iceGatherer.removeEventListener('localcandidate',
  2572. this.transceivers[sdpMLineIndex].bufferCandidates);
  2573. iceGatherer.onlocalcandidate = function(evt) {
  2574. if (pc.usingBundle && sdpMLineIndex > 0) {
  2575. // if we know that we use bundle we can drop candidates with
  2576. // ѕdpMLineIndex > 0. If we don't do this then our state gets
  2577. // confused since we dispose the extra ice gatherer.
  2578. return;
  2579. }
  2580. var event = new Event('icecandidate');
  2581. event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex};
  2582. var cand = evt.candidate;
  2583. // Edge emits an empty object for RTCIceCandidateComplete‥
  2584. var end = !cand || Object.keys(cand).length === 0;
  2585. if (end) {
  2586. // polyfill since RTCIceGatherer.state is not implemented in
  2587. // Edge 10547 yet.
  2588. if (iceGatherer.state === 'new' || iceGatherer.state === 'gathering') {
  2589. iceGatherer.state = 'completed';
  2590. }
  2591. } else {
  2592. if (iceGatherer.state === 'new') {
  2593. iceGatherer.state = 'gathering';
  2594. }
  2595. // RTCIceCandidate doesn't have a component, needs to be added
  2596. cand.component = 1;
  2597. // also the usernameFragment. TODO: update SDP to take both variants.
  2598. cand.ufrag = iceGatherer.getLocalParameters().usernameFragment;
  2599. var serializedCandidate = sdp.writeCandidate(cand);
  2600. event.candidate = Object.assign(event.candidate,
  2601. sdp.parseCandidate(serializedCandidate));
  2602. event.candidate.candidate = serializedCandidate;
  2603. event.candidate.toJSON = function() {
  2604. return {
  2605. candidate: event.candidate.candidate,
  2606. sdpMid: event.candidate.sdpMid,
  2607. sdpMLineIndex: event.candidate.sdpMLineIndex,
  2608. usernameFragment: event.candidate.usernameFragment
  2609. };
  2610. };
  2611. }
  2612. // update local description.
  2613. var sections = sdp.getMediaSections(pc._localDescription.sdp);
  2614. if (!end) {
  2615. sections[event.candidate.sdpMLineIndex] +=
  2616. 'a=' + event.candidate.candidate + '\r\n';
  2617. } else {
  2618. sections[event.candidate.sdpMLineIndex] +=
  2619. 'a=end-of-candidates\r\n';
  2620. }
  2621. pc._localDescription.sdp =
  2622. sdp.getDescription(pc._localDescription.sdp) +
  2623. sections.join('');
  2624. var complete = pc.transceivers.every(function(transceiver) {
  2625. return transceiver.iceGatherer &&
  2626. transceiver.iceGatherer.state === 'completed';
  2627. });
  2628. if (pc.iceGatheringState !== 'gathering') {
  2629. pc.iceGatheringState = 'gathering';
  2630. pc._emitGatheringStateChange();
  2631. }
  2632. // Emit candidate. Also emit null candidate when all gatherers are
  2633. // complete.
  2634. if (!end) {
  2635. pc._dispatchEvent('icecandidate', event);
  2636. }
  2637. if (complete) {
  2638. pc._dispatchEvent('icecandidate', new Event('icecandidate'));
  2639. pc.iceGatheringState = 'complete';
  2640. pc._emitGatheringStateChange();
  2641. }
  2642. };
  2643. // emit already gathered candidates.
  2644. window.setTimeout(function() {
  2645. bufferedCandidateEvents.forEach(function(e) {
  2646. iceGatherer.onlocalcandidate(e);
  2647. });
  2648. }, 0);
  2649. };
  2650. // Create ICE transport and DTLS transport.
  2651. RTCPeerConnection.prototype._createIceAndDtlsTransports = function() {
  2652. var pc = this;
  2653. var iceTransport = new window.RTCIceTransport(null);
  2654. iceTransport.onicestatechange = function() {
  2655. pc._updateIceConnectionState();
  2656. pc._updateConnectionState();
  2657. };
  2658. var dtlsTransport = new window.RTCDtlsTransport(iceTransport);
  2659. dtlsTransport.ondtlsstatechange = function() {
  2660. pc._updateConnectionState();
  2661. };
  2662. dtlsTransport.onerror = function() {
  2663. // onerror does not set state to failed by itself.
  2664. Object.defineProperty(dtlsTransport, 'state',
  2665. {value: 'failed', writable: true});
  2666. pc._updateConnectionState();
  2667. };
  2668. return {
  2669. iceTransport: iceTransport,
  2670. dtlsTransport: dtlsTransport
  2671. };
  2672. };
  2673. // Destroy ICE gatherer, ICE transport and DTLS transport.
  2674. // Without triggering the callbacks.
  2675. RTCPeerConnection.prototype._disposeIceAndDtlsTransports = function(
  2676. sdpMLineIndex) {
  2677. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  2678. if (iceGatherer) {
  2679. delete iceGatherer.onlocalcandidate;
  2680. delete this.transceivers[sdpMLineIndex].iceGatherer;
  2681. }
  2682. var iceTransport = this.transceivers[sdpMLineIndex].iceTransport;
  2683. if (iceTransport) {
  2684. delete iceTransport.onicestatechange;
  2685. delete this.transceivers[sdpMLineIndex].iceTransport;
  2686. }
  2687. var dtlsTransport = this.transceivers[sdpMLineIndex].dtlsTransport;
  2688. if (dtlsTransport) {
  2689. delete dtlsTransport.ondtlsstatechange;
  2690. delete dtlsTransport.onerror;
  2691. delete this.transceivers[sdpMLineIndex].dtlsTransport;
  2692. }
  2693. };
  2694. // Start the RTP Sender and Receiver for a transceiver.
  2695. RTCPeerConnection.prototype._transceive = function(transceiver,
  2696. send, recv) {
  2697. var params = getCommonCapabilities(transceiver.localCapabilities,
  2698. transceiver.remoteCapabilities);
  2699. if (send && transceiver.rtpSender) {
  2700. params.encodings = transceiver.sendEncodingParameters;
  2701. params.rtcp = {
  2702. cname: sdp.localCName,
  2703. compound: transceiver.rtcpParameters.compound
  2704. };
  2705. if (transceiver.recvEncodingParameters.length) {
  2706. params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
  2707. }
  2708. transceiver.rtpSender.send(params);
  2709. }
  2710. if (recv && transceiver.rtpReceiver && params.codecs.length > 0) {
  2711. // remove RTX field in Edge 14942
  2712. if (transceiver.kind === 'video'
  2713. && transceiver.recvEncodingParameters
  2714. && edgeVersion < 15019) {
  2715. transceiver.recvEncodingParameters.forEach(function(p) {
  2716. delete p.rtx;
  2717. });
  2718. }
  2719. if (transceiver.recvEncodingParameters.length) {
  2720. params.encodings = transceiver.recvEncodingParameters;
  2721. } else {
  2722. params.encodings = [{}];
  2723. }
  2724. params.rtcp = {
  2725. compound: transceiver.rtcpParameters.compound
  2726. };
  2727. if (transceiver.rtcpParameters.cname) {
  2728. params.rtcp.cname = transceiver.rtcpParameters.cname;
  2729. }
  2730. if (transceiver.sendEncodingParameters.length) {
  2731. params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
  2732. }
  2733. transceiver.rtpReceiver.receive(params);
  2734. }
  2735. };
  2736. RTCPeerConnection.prototype.setLocalDescription = function(description) {
  2737. var pc = this;
  2738. // Note: pranswer is not supported.
  2739. if (['offer', 'answer'].indexOf(description.type) === -1) {
  2740. return Promise.reject(makeError('TypeError',
  2741. 'Unsupported type "' + description.type + '"'));
  2742. }
  2743. if (!isActionAllowedInSignalingState('setLocalDescription',
  2744. description.type, pc.signalingState) || pc._isClosed) {
  2745. return Promise.reject(makeError('InvalidStateError',
  2746. 'Can not set local ' + description.type +
  2747. ' in state ' + pc.signalingState));
  2748. }
  2749. var sections;
  2750. var sessionpart;
  2751. if (description.type === 'offer') {
  2752. // VERY limited support for SDP munging. Limited to:
  2753. // * changing the order of codecs
  2754. sections = sdp.splitSections(description.sdp);
  2755. sessionpart = sections.shift();
  2756. sections.forEach(function(mediaSection, sdpMLineIndex) {
  2757. var caps = sdp.parseRtpParameters(mediaSection);
  2758. pc.transceivers[sdpMLineIndex].localCapabilities = caps;
  2759. });
  2760. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  2761. pc._gather(transceiver.mid, sdpMLineIndex);
  2762. });
  2763. } else if (description.type === 'answer') {
  2764. sections = sdp.splitSections(pc._remoteDescription.sdp);
  2765. sessionpart = sections.shift();
  2766. var isIceLite = sdp.matchPrefix(sessionpart,
  2767. 'a=ice-lite').length > 0;
  2768. sections.forEach(function(mediaSection, sdpMLineIndex) {
  2769. var transceiver = pc.transceivers[sdpMLineIndex];
  2770. var iceGatherer = transceiver.iceGatherer;
  2771. var iceTransport = transceiver.iceTransport;
  2772. var dtlsTransport = transceiver.dtlsTransport;
  2773. var localCapabilities = transceiver.localCapabilities;
  2774. var remoteCapabilities = transceiver.remoteCapabilities;
  2775. // treat bundle-only as not-rejected.
  2776. var rejected = sdp.isRejected(mediaSection) &&
  2777. sdp.matchPrefix(mediaSection, 'a=bundle-only').length === 0;
  2778. if (!rejected && !transceiver.rejected) {
  2779. var remoteIceParameters = sdp.getIceParameters(
  2780. mediaSection, sessionpart);
  2781. var remoteDtlsParameters = sdp.getDtlsParameters(
  2782. mediaSection, sessionpart);
  2783. if (isIceLite) {
  2784. remoteDtlsParameters.role = 'server';
  2785. }
  2786. if (!pc.usingBundle || sdpMLineIndex === 0) {
  2787. pc._gather(transceiver.mid, sdpMLineIndex);
  2788. if (iceTransport.state === 'new') {
  2789. iceTransport.start(iceGatherer, remoteIceParameters,
  2790. isIceLite ? 'controlling' : 'controlled');
  2791. }
  2792. if (dtlsTransport.state === 'new') {
  2793. dtlsTransport.start(remoteDtlsParameters);
  2794. }
  2795. }
  2796. // Calculate intersection of capabilities.
  2797. var params = getCommonCapabilities(localCapabilities,
  2798. remoteCapabilities);
  2799. // Start the RTCRtpSender. The RTCRtpReceiver for this
  2800. // transceiver has already been started in setRemoteDescription.
  2801. pc._transceive(transceiver,
  2802. params.codecs.length > 0,
  2803. false);
  2804. }
  2805. });
  2806. }
  2807. pc._localDescription = {
  2808. type: description.type,
  2809. sdp: description.sdp
  2810. };
  2811. if (description.type === 'offer') {
  2812. pc._updateSignalingState('have-local-offer');
  2813. } else {
  2814. pc._updateSignalingState('stable');
  2815. }
  2816. return Promise.resolve();
  2817. };
  2818. RTCPeerConnection.prototype.setRemoteDescription = function(description) {
  2819. var pc = this;
  2820. // Note: pranswer is not supported.
  2821. if (['offer', 'answer'].indexOf(description.type) === -1) {
  2822. return Promise.reject(makeError('TypeError',
  2823. 'Unsupported type "' + description.type + '"'));
  2824. }
  2825. if (!isActionAllowedInSignalingState('setRemoteDescription',
  2826. description.type, pc.signalingState) || pc._isClosed) {
  2827. return Promise.reject(makeError('InvalidStateError',
  2828. 'Can not set remote ' + description.type +
  2829. ' in state ' + pc.signalingState));
  2830. }
  2831. var streams = {};
  2832. pc.remoteStreams.forEach(function(stream) {
  2833. streams[stream.id] = stream;
  2834. });
  2835. var receiverList = [];
  2836. var sections = sdp.splitSections(description.sdp);
  2837. var sessionpart = sections.shift();
  2838. var isIceLite = sdp.matchPrefix(sessionpart,
  2839. 'a=ice-lite').length > 0;
  2840. var usingBundle = sdp.matchPrefix(sessionpart,
  2841. 'a=group:BUNDLE ').length > 0;
  2842. pc.usingBundle = usingBundle;
  2843. var iceOptions = sdp.matchPrefix(sessionpart,
  2844. 'a=ice-options:')[0];
  2845. if (iceOptions) {
  2846. pc.canTrickleIceCandidates = iceOptions.substr(14).split(' ')
  2847. .indexOf('trickle') >= 0;
  2848. } else {
  2849. pc.canTrickleIceCandidates = false;
  2850. }
  2851. sections.forEach(function(mediaSection, sdpMLineIndex) {
  2852. var lines = sdp.splitLines(mediaSection);
  2853. var kind = sdp.getKind(mediaSection);
  2854. // treat bundle-only as not-rejected.
  2855. var rejected = sdp.isRejected(mediaSection) &&
  2856. sdp.matchPrefix(mediaSection, 'a=bundle-only').length === 0;
  2857. var protocol = lines[0].substr(2).split(' ')[2];
  2858. var direction = sdp.getDirection(mediaSection, sessionpart);
  2859. var remoteMsid = sdp.parseMsid(mediaSection);
  2860. var mid = sdp.getMid(mediaSection) || sdp.generateIdentifier();
  2861. // Reject datachannels which are not implemented yet.
  2862. if (rejected || (kind === 'application' && (protocol === 'DTLS/SCTP' ||
  2863. protocol === 'UDP/DTLS/SCTP'))) {
  2864. // TODO: this is dangerous in the case where a non-rejected m-line
  2865. // becomes rejected.
  2866. pc.transceivers[sdpMLineIndex] = {
  2867. mid: mid,
  2868. kind: kind,
  2869. protocol: protocol,
  2870. rejected: true
  2871. };
  2872. return;
  2873. }
  2874. if (!rejected && pc.transceivers[sdpMLineIndex] &&
  2875. pc.transceivers[sdpMLineIndex].rejected) {
  2876. // recycle a rejected transceiver.
  2877. pc.transceivers[sdpMLineIndex] = pc._createTransceiver(kind, true);
  2878. }
  2879. var transceiver;
  2880. var iceGatherer;
  2881. var iceTransport;
  2882. var dtlsTransport;
  2883. var rtpReceiver;
  2884. var sendEncodingParameters;
  2885. var recvEncodingParameters;
  2886. var localCapabilities;
  2887. var track;
  2888. // FIXME: ensure the mediaSection has rtcp-mux set.
  2889. var remoteCapabilities = sdp.parseRtpParameters(mediaSection);
  2890. var remoteIceParameters;
  2891. var remoteDtlsParameters;
  2892. if (!rejected) {
  2893. remoteIceParameters = sdp.getIceParameters(mediaSection,
  2894. sessionpart);
  2895. remoteDtlsParameters = sdp.getDtlsParameters(mediaSection,
  2896. sessionpart);
  2897. remoteDtlsParameters.role = 'client';
  2898. }
  2899. recvEncodingParameters =
  2900. sdp.parseRtpEncodingParameters(mediaSection);
  2901. var rtcpParameters = sdp.parseRtcpParameters(mediaSection);
  2902. var isComplete = sdp.matchPrefix(mediaSection,
  2903. 'a=end-of-candidates', sessionpart).length > 0;
  2904. var cands = sdp.matchPrefix(mediaSection, 'a=candidate:')
  2905. .map(function(cand) {
  2906. return sdp.parseCandidate(cand);
  2907. })
  2908. .filter(function(cand) {
  2909. return cand.component === 1;
  2910. });
  2911. // Check if we can use BUNDLE and dispose transports.
  2912. if ((description.type === 'offer' || description.type === 'answer') &&
  2913. !rejected && usingBundle && sdpMLineIndex > 0 &&
  2914. pc.transceivers[sdpMLineIndex]) {
  2915. pc._disposeIceAndDtlsTransports(sdpMLineIndex);
  2916. pc.transceivers[sdpMLineIndex].iceGatherer =
  2917. pc.transceivers[0].iceGatherer;
  2918. pc.transceivers[sdpMLineIndex].iceTransport =
  2919. pc.transceivers[0].iceTransport;
  2920. pc.transceivers[sdpMLineIndex].dtlsTransport =
  2921. pc.transceivers[0].dtlsTransport;
  2922. if (pc.transceivers[sdpMLineIndex].rtpSender) {
  2923. pc.transceivers[sdpMLineIndex].rtpSender.setTransport(
  2924. pc.transceivers[0].dtlsTransport);
  2925. }
  2926. if (pc.transceivers[sdpMLineIndex].rtpReceiver) {
  2927. pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(
  2928. pc.transceivers[0].dtlsTransport);
  2929. }
  2930. }
  2931. if (description.type === 'offer' && !rejected) {
  2932. transceiver = pc.transceivers[sdpMLineIndex] ||
  2933. pc._createTransceiver(kind);
  2934. transceiver.mid = mid;
  2935. if (!transceiver.iceGatherer) {
  2936. transceiver.iceGatherer = pc._createIceGatherer(sdpMLineIndex,
  2937. usingBundle);
  2938. }
  2939. if (cands.length && transceiver.iceTransport.state === 'new') {
  2940. if (isComplete && (!usingBundle || sdpMLineIndex === 0)) {
  2941. transceiver.iceTransport.setRemoteCandidates(cands);
  2942. } else {
  2943. cands.forEach(function(candidate) {
  2944. maybeAddCandidate(transceiver.iceTransport, candidate);
  2945. });
  2946. }
  2947. }
  2948. localCapabilities = window.RTCRtpReceiver.getCapabilities(kind);
  2949. // filter RTX until additional stuff needed for RTX is implemented
  2950. // in adapter.js
  2951. if (edgeVersion < 15019) {
  2952. localCapabilities.codecs = localCapabilities.codecs.filter(
  2953. function(codec) {
  2954. return codec.name !== 'rtx';
  2955. });
  2956. }
  2957. sendEncodingParameters = transceiver.sendEncodingParameters || [{
  2958. ssrc: (2 * sdpMLineIndex + 2) * 1001
  2959. }];
  2960. // TODO: rewrite to use http://w3c.github.io/webrtc-pc/#set-associated-remote-streams
  2961. var isNewTrack = false;
  2962. if (direction === 'sendrecv' || direction === 'sendonly') {
  2963. isNewTrack = !transceiver.rtpReceiver;
  2964. rtpReceiver = transceiver.rtpReceiver ||
  2965. new window.RTCRtpReceiver(transceiver.dtlsTransport, kind);
  2966. if (isNewTrack) {
  2967. var stream;
  2968. track = rtpReceiver.track;
  2969. // FIXME: does not work with Plan B.
  2970. if (remoteMsid && remoteMsid.stream === '-') ; else if (remoteMsid) {
  2971. if (!streams[remoteMsid.stream]) {
  2972. streams[remoteMsid.stream] = new window.MediaStream();
  2973. Object.defineProperty(streams[remoteMsid.stream], 'id', {
  2974. get: function() {
  2975. return remoteMsid.stream;
  2976. }
  2977. });
  2978. }
  2979. Object.defineProperty(track, 'id', {
  2980. get: function() {
  2981. return remoteMsid.track;
  2982. }
  2983. });
  2984. stream = streams[remoteMsid.stream];
  2985. } else {
  2986. if (!streams.default) {
  2987. streams.default = new window.MediaStream();
  2988. }
  2989. stream = streams.default;
  2990. }
  2991. if (stream) {
  2992. addTrackToStreamAndFireEvent(track, stream);
  2993. transceiver.associatedRemoteMediaStreams.push(stream);
  2994. }
  2995. receiverList.push([track, rtpReceiver, stream]);
  2996. }
  2997. } else if (transceiver.rtpReceiver && transceiver.rtpReceiver.track) {
  2998. transceiver.associatedRemoteMediaStreams.forEach(function(s) {
  2999. var nativeTrack = s.getTracks().find(function(t) {
  3000. return t.id === transceiver.rtpReceiver.track.id;
  3001. });
  3002. if (nativeTrack) {
  3003. removeTrackFromStreamAndFireEvent(nativeTrack, s);
  3004. }
  3005. });
  3006. transceiver.associatedRemoteMediaStreams = [];
  3007. }
  3008. transceiver.localCapabilities = localCapabilities;
  3009. transceiver.remoteCapabilities = remoteCapabilities;
  3010. transceiver.rtpReceiver = rtpReceiver;
  3011. transceiver.rtcpParameters = rtcpParameters;
  3012. transceiver.sendEncodingParameters = sendEncodingParameters;
  3013. transceiver.recvEncodingParameters = recvEncodingParameters;
  3014. // Start the RTCRtpReceiver now. The RTPSender is started in
  3015. // setLocalDescription.
  3016. pc._transceive(pc.transceivers[sdpMLineIndex],
  3017. false,
  3018. isNewTrack);
  3019. } else if (description.type === 'answer' && !rejected) {
  3020. transceiver = pc.transceivers[sdpMLineIndex];
  3021. iceGatherer = transceiver.iceGatherer;
  3022. iceTransport = transceiver.iceTransport;
  3023. dtlsTransport = transceiver.dtlsTransport;
  3024. rtpReceiver = transceiver.rtpReceiver;
  3025. sendEncodingParameters = transceiver.sendEncodingParameters;
  3026. localCapabilities = transceiver.localCapabilities;
  3027. pc.transceivers[sdpMLineIndex].recvEncodingParameters =
  3028. recvEncodingParameters;
  3029. pc.transceivers[sdpMLineIndex].remoteCapabilities =
  3030. remoteCapabilities;
  3031. pc.transceivers[sdpMLineIndex].rtcpParameters = rtcpParameters;
  3032. if (cands.length && iceTransport.state === 'new') {
  3033. if ((isIceLite || isComplete) &&
  3034. (!usingBundle || sdpMLineIndex === 0)) {
  3035. iceTransport.setRemoteCandidates(cands);
  3036. } else {
  3037. cands.forEach(function(candidate) {
  3038. maybeAddCandidate(transceiver.iceTransport, candidate);
  3039. });
  3040. }
  3041. }
  3042. if (!usingBundle || sdpMLineIndex === 0) {
  3043. if (iceTransport.state === 'new') {
  3044. iceTransport.start(iceGatherer, remoteIceParameters,
  3045. 'controlling');
  3046. }
  3047. if (dtlsTransport.state === 'new') {
  3048. dtlsTransport.start(remoteDtlsParameters);
  3049. }
  3050. }
  3051. // If the offer contained RTX but the answer did not,
  3052. // remove RTX from sendEncodingParameters.
  3053. var commonCapabilities = getCommonCapabilities(
  3054. transceiver.localCapabilities,
  3055. transceiver.remoteCapabilities);
  3056. var hasRtx = commonCapabilities.codecs.filter(function(c) {
  3057. return c.name.toLowerCase() === 'rtx';
  3058. }).length;
  3059. if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
  3060. delete transceiver.sendEncodingParameters[0].rtx;
  3061. }
  3062. pc._transceive(transceiver,
  3063. direction === 'sendrecv' || direction === 'recvonly',
  3064. direction === 'sendrecv' || direction === 'sendonly');
  3065. // TODO: rewrite to use http://w3c.github.io/webrtc-pc/#set-associated-remote-streams
  3066. if (rtpReceiver &&
  3067. (direction === 'sendrecv' || direction === 'sendonly')) {
  3068. track = rtpReceiver.track;
  3069. if (remoteMsid) {
  3070. if (!streams[remoteMsid.stream]) {
  3071. streams[remoteMsid.stream] = new window.MediaStream();
  3072. }
  3073. addTrackToStreamAndFireEvent(track, streams[remoteMsid.stream]);
  3074. receiverList.push([track, rtpReceiver, streams[remoteMsid.stream]]);
  3075. } else {
  3076. if (!streams.default) {
  3077. streams.default = new window.MediaStream();
  3078. }
  3079. addTrackToStreamAndFireEvent(track, streams.default);
  3080. receiverList.push([track, rtpReceiver, streams.default]);
  3081. }
  3082. } else {
  3083. // FIXME: actually the receiver should be created later.
  3084. delete transceiver.rtpReceiver;
  3085. }
  3086. }
  3087. });
  3088. if (pc._dtlsRole === undefined) {
  3089. pc._dtlsRole = description.type === 'offer' ? 'active' : 'passive';
  3090. }
  3091. pc._remoteDescription = {
  3092. type: description.type,
  3093. sdp: description.sdp
  3094. };
  3095. if (description.type === 'offer') {
  3096. pc._updateSignalingState('have-remote-offer');
  3097. } else {
  3098. pc._updateSignalingState('stable');
  3099. }
  3100. Object.keys(streams).forEach(function(sid) {
  3101. var stream = streams[sid];
  3102. if (stream.getTracks().length) {
  3103. if (pc.remoteStreams.indexOf(stream) === -1) {
  3104. pc.remoteStreams.push(stream);
  3105. var event = new Event('addstream');
  3106. event.stream = stream;
  3107. window.setTimeout(function() {
  3108. pc._dispatchEvent('addstream', event);
  3109. });
  3110. }
  3111. receiverList.forEach(function(item) {
  3112. var track = item[0];
  3113. var receiver = item[1];
  3114. if (stream.id !== item[2].id) {
  3115. return;
  3116. }
  3117. fireAddTrack(pc, track, receiver, [stream]);
  3118. });
  3119. }
  3120. });
  3121. receiverList.forEach(function(item) {
  3122. if (item[2]) {
  3123. return;
  3124. }
  3125. fireAddTrack(pc, item[0], item[1], []);
  3126. });
  3127. // check whether addIceCandidate({}) was called within four seconds after
  3128. // setRemoteDescription.
  3129. window.setTimeout(function() {
  3130. if (!(pc && pc.transceivers)) {
  3131. return;
  3132. }
  3133. pc.transceivers.forEach(function(transceiver) {
  3134. if (transceiver.iceTransport &&
  3135. transceiver.iceTransport.state === 'new' &&
  3136. transceiver.iceTransport.getRemoteCandidates().length > 0) {
  3137. console.warn('Timeout for addRemoteCandidate. Consider sending ' +
  3138. 'an end-of-candidates notification');
  3139. transceiver.iceTransport.addRemoteCandidate({});
  3140. }
  3141. });
  3142. }, 4000);
  3143. return Promise.resolve();
  3144. };
  3145. RTCPeerConnection.prototype.close = function() {
  3146. this.transceivers.forEach(function(transceiver) {
  3147. /* not yet
  3148. if (transceiver.iceGatherer) {
  3149. transceiver.iceGatherer.close();
  3150. }
  3151. */
  3152. if (transceiver.iceTransport) {
  3153. transceiver.iceTransport.stop();
  3154. }
  3155. if (transceiver.dtlsTransport) {
  3156. transceiver.dtlsTransport.stop();
  3157. }
  3158. if (transceiver.rtpSender) {
  3159. transceiver.rtpSender.stop();
  3160. }
  3161. if (transceiver.rtpReceiver) {
  3162. transceiver.rtpReceiver.stop();
  3163. }
  3164. });
  3165. // FIXME: clean up tracks, local streams, remote streams, etc
  3166. this._isClosed = true;
  3167. this._updateSignalingState('closed');
  3168. };
  3169. // Update the signaling state.
  3170. RTCPeerConnection.prototype._updateSignalingState = function(newState) {
  3171. this.signalingState = newState;
  3172. var event = new Event('signalingstatechange');
  3173. this._dispatchEvent('signalingstatechange', event);
  3174. };
  3175. // Determine whether to fire the negotiationneeded event.
  3176. RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() {
  3177. var pc = this;
  3178. if (this.signalingState !== 'stable' || this.needNegotiation === true) {
  3179. return;
  3180. }
  3181. this.needNegotiation = true;
  3182. window.setTimeout(function() {
  3183. if (pc.needNegotiation) {
  3184. pc.needNegotiation = false;
  3185. var event = new Event('negotiationneeded');
  3186. pc._dispatchEvent('negotiationneeded', event);
  3187. }
  3188. }, 0);
  3189. };
  3190. // Update the ice connection state.
  3191. RTCPeerConnection.prototype._updateIceConnectionState = function() {
  3192. var newState;
  3193. var states = {
  3194. 'new': 0,
  3195. closed: 0,
  3196. checking: 0,
  3197. connected: 0,
  3198. completed: 0,
  3199. disconnected: 0,
  3200. failed: 0
  3201. };
  3202. this.transceivers.forEach(function(transceiver) {
  3203. if (transceiver.iceTransport && !transceiver.rejected) {
  3204. states[transceiver.iceTransport.state]++;
  3205. }
  3206. });
  3207. newState = 'new';
  3208. if (states.failed > 0) {
  3209. newState = 'failed';
  3210. } else if (states.checking > 0) {
  3211. newState = 'checking';
  3212. } else if (states.disconnected > 0) {
  3213. newState = 'disconnected';
  3214. } else if (states.new > 0) {
  3215. newState = 'new';
  3216. } else if (states.connected > 0) {
  3217. newState = 'connected';
  3218. } else if (states.completed > 0) {
  3219. newState = 'completed';
  3220. }
  3221. if (newState !== this.iceConnectionState) {
  3222. this.iceConnectionState = newState;
  3223. var event = new Event('iceconnectionstatechange');
  3224. this._dispatchEvent('iceconnectionstatechange', event);
  3225. }
  3226. };
  3227. // Update the connection state.
  3228. RTCPeerConnection.prototype._updateConnectionState = function() {
  3229. var newState;
  3230. var states = {
  3231. 'new': 0,
  3232. closed: 0,
  3233. connecting: 0,
  3234. connected: 0,
  3235. completed: 0,
  3236. disconnected: 0,
  3237. failed: 0
  3238. };
  3239. this.transceivers.forEach(function(transceiver) {
  3240. if (transceiver.iceTransport && transceiver.dtlsTransport &&
  3241. !transceiver.rejected) {
  3242. states[transceiver.iceTransport.state]++;
  3243. states[transceiver.dtlsTransport.state]++;
  3244. }
  3245. });
  3246. // ICETransport.completed and connected are the same for this purpose.
  3247. states.connected += states.completed;
  3248. newState = 'new';
  3249. if (states.failed > 0) {
  3250. newState = 'failed';
  3251. } else if (states.connecting > 0) {
  3252. newState = 'connecting';
  3253. } else if (states.disconnected > 0) {
  3254. newState = 'disconnected';
  3255. } else if (states.new > 0) {
  3256. newState = 'new';
  3257. } else if (states.connected > 0) {
  3258. newState = 'connected';
  3259. }
  3260. if (newState !== this.connectionState) {
  3261. this.connectionState = newState;
  3262. var event = new Event('connectionstatechange');
  3263. this._dispatchEvent('connectionstatechange', event);
  3264. }
  3265. };
  3266. RTCPeerConnection.prototype.createOffer = function() {
  3267. var pc = this;
  3268. if (pc._isClosed) {
  3269. return Promise.reject(makeError('InvalidStateError',
  3270. 'Can not call createOffer after close'));
  3271. }
  3272. var numAudioTracks = pc.transceivers.filter(function(t) {
  3273. return t.kind === 'audio';
  3274. }).length;
  3275. var numVideoTracks = pc.transceivers.filter(function(t) {
  3276. return t.kind === 'video';
  3277. }).length;
  3278. // Determine number of audio and video tracks we need to send/recv.
  3279. var offerOptions = arguments[0];
  3280. if (offerOptions) {
  3281. // Reject Chrome legacy constraints.
  3282. if (offerOptions.mandatory || offerOptions.optional) {
  3283. throw new TypeError(
  3284. 'Legacy mandatory/optional constraints not supported.');
  3285. }
  3286. if (offerOptions.offerToReceiveAudio !== undefined) {
  3287. if (offerOptions.offerToReceiveAudio === true) {
  3288. numAudioTracks = 1;
  3289. } else if (offerOptions.offerToReceiveAudio === false) {
  3290. numAudioTracks = 0;
  3291. } else {
  3292. numAudioTracks = offerOptions.offerToReceiveAudio;
  3293. }
  3294. }
  3295. if (offerOptions.offerToReceiveVideo !== undefined) {
  3296. if (offerOptions.offerToReceiveVideo === true) {
  3297. numVideoTracks = 1;
  3298. } else if (offerOptions.offerToReceiveVideo === false) {
  3299. numVideoTracks = 0;
  3300. } else {
  3301. numVideoTracks = offerOptions.offerToReceiveVideo;
  3302. }
  3303. }
  3304. }
  3305. pc.transceivers.forEach(function(transceiver) {
  3306. if (transceiver.kind === 'audio') {
  3307. numAudioTracks--;
  3308. if (numAudioTracks < 0) {
  3309. transceiver.wantReceive = false;
  3310. }
  3311. } else if (transceiver.kind === 'video') {
  3312. numVideoTracks--;
  3313. if (numVideoTracks < 0) {
  3314. transceiver.wantReceive = false;
  3315. }
  3316. }
  3317. });
  3318. // Create M-lines for recvonly streams.
  3319. while (numAudioTracks > 0 || numVideoTracks > 0) {
  3320. if (numAudioTracks > 0) {
  3321. pc._createTransceiver('audio');
  3322. numAudioTracks--;
  3323. }
  3324. if (numVideoTracks > 0) {
  3325. pc._createTransceiver('video');
  3326. numVideoTracks--;
  3327. }
  3328. }
  3329. var sdp$1 = sdp.writeSessionBoilerplate(pc._sdpSessionId,
  3330. pc._sdpSessionVersion++);
  3331. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3332. // For each track, create an ice gatherer, ice transport,
  3333. // dtls transport, potentially rtpsender and rtpreceiver.
  3334. var track = transceiver.track;
  3335. var kind = transceiver.kind;
  3336. var mid = transceiver.mid || sdp.generateIdentifier();
  3337. transceiver.mid = mid;
  3338. if (!transceiver.iceGatherer) {
  3339. transceiver.iceGatherer = pc._createIceGatherer(sdpMLineIndex,
  3340. pc.usingBundle);
  3341. }
  3342. var localCapabilities = window.RTCRtpSender.getCapabilities(kind);
  3343. // filter RTX until additional stuff needed for RTX is implemented
  3344. // in adapter.js
  3345. if (edgeVersion < 15019) {
  3346. localCapabilities.codecs = localCapabilities.codecs.filter(
  3347. function(codec) {
  3348. return codec.name !== 'rtx';
  3349. });
  3350. }
  3351. localCapabilities.codecs.forEach(function(codec) {
  3352. // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
  3353. // by adding level-asymmetry-allowed=1
  3354. if (codec.name === 'H264' &&
  3355. codec.parameters['level-asymmetry-allowed'] === undefined) {
  3356. codec.parameters['level-asymmetry-allowed'] = '1';
  3357. }
  3358. // for subsequent offers, we might have to re-use the payload
  3359. // type of the last offer.
  3360. if (transceiver.remoteCapabilities &&
  3361. transceiver.remoteCapabilities.codecs) {
  3362. transceiver.remoteCapabilities.codecs.forEach(function(remoteCodec) {
  3363. if (codec.name.toLowerCase() === remoteCodec.name.toLowerCase() &&
  3364. codec.clockRate === remoteCodec.clockRate) {
  3365. codec.preferredPayloadType = remoteCodec.payloadType;
  3366. }
  3367. });
  3368. }
  3369. });
  3370. localCapabilities.headerExtensions.forEach(function(hdrExt) {
  3371. var remoteExtensions = transceiver.remoteCapabilities &&
  3372. transceiver.remoteCapabilities.headerExtensions || [];
  3373. remoteExtensions.forEach(function(rHdrExt) {
  3374. if (hdrExt.uri === rHdrExt.uri) {
  3375. hdrExt.id = rHdrExt.id;
  3376. }
  3377. });
  3378. });
  3379. // generate an ssrc now, to be used later in rtpSender.send
  3380. var sendEncodingParameters = transceiver.sendEncodingParameters || [{
  3381. ssrc: (2 * sdpMLineIndex + 1) * 1001
  3382. }];
  3383. if (track) {
  3384. // add RTX
  3385. if (edgeVersion >= 15019 && kind === 'video' &&
  3386. !sendEncodingParameters[0].rtx) {
  3387. sendEncodingParameters[0].rtx = {
  3388. ssrc: sendEncodingParameters[0].ssrc + 1
  3389. };
  3390. }
  3391. }
  3392. if (transceiver.wantReceive) {
  3393. transceiver.rtpReceiver = new window.RTCRtpReceiver(
  3394. transceiver.dtlsTransport, kind);
  3395. }
  3396. transceiver.localCapabilities = localCapabilities;
  3397. transceiver.sendEncodingParameters = sendEncodingParameters;
  3398. });
  3399. // always offer BUNDLE and dispose on return if not supported.
  3400. if (pc._config.bundlePolicy !== 'max-compat') {
  3401. sdp$1 += 'a=group:BUNDLE ' + pc.transceivers.map(function(t) {
  3402. return t.mid;
  3403. }).join(' ') + '\r\n';
  3404. }
  3405. sdp$1 += 'a=ice-options:trickle\r\n';
  3406. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3407. sdp$1 += writeMediaSection(transceiver, transceiver.localCapabilities,
  3408. 'offer', transceiver.stream, pc._dtlsRole);
  3409. sdp$1 += 'a=rtcp-rsize\r\n';
  3410. if (transceiver.iceGatherer && pc.iceGatheringState !== 'new' &&
  3411. (sdpMLineIndex === 0 || !pc.usingBundle)) {
  3412. transceiver.iceGatherer.getLocalCandidates().forEach(function(cand) {
  3413. cand.component = 1;
  3414. sdp$1 += 'a=' + sdp.writeCandidate(cand) + '\r\n';
  3415. });
  3416. if (transceiver.iceGatherer.state === 'completed') {
  3417. sdp$1 += 'a=end-of-candidates\r\n';
  3418. }
  3419. }
  3420. });
  3421. var desc = new window.RTCSessionDescription({
  3422. type: 'offer',
  3423. sdp: sdp$1
  3424. });
  3425. return Promise.resolve(desc);
  3426. };
  3427. RTCPeerConnection.prototype.createAnswer = function() {
  3428. var pc = this;
  3429. if (pc._isClosed) {
  3430. return Promise.reject(makeError('InvalidStateError',
  3431. 'Can not call createAnswer after close'));
  3432. }
  3433. if (!(pc.signalingState === 'have-remote-offer' ||
  3434. pc.signalingState === 'have-local-pranswer')) {
  3435. return Promise.reject(makeError('InvalidStateError',
  3436. 'Can not call createAnswer in signalingState ' + pc.signalingState));
  3437. }
  3438. var sdp$1 = sdp.writeSessionBoilerplate(pc._sdpSessionId,
  3439. pc._sdpSessionVersion++);
  3440. if (pc.usingBundle) {
  3441. sdp$1 += 'a=group:BUNDLE ' + pc.transceivers.map(function(t) {
  3442. return t.mid;
  3443. }).join(' ') + '\r\n';
  3444. }
  3445. sdp$1 += 'a=ice-options:trickle\r\n';
  3446. var mediaSectionsInOffer = sdp.getMediaSections(
  3447. pc._remoteDescription.sdp).length;
  3448. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3449. if (sdpMLineIndex + 1 > mediaSectionsInOffer) {
  3450. return;
  3451. }
  3452. if (transceiver.rejected) {
  3453. if (transceiver.kind === 'application') {
  3454. if (transceiver.protocol === 'DTLS/SCTP') { // legacy fmt
  3455. sdp$1 += 'm=application 0 DTLS/SCTP 5000\r\n';
  3456. } else {
  3457. sdp$1 += 'm=application 0 ' + transceiver.protocol +
  3458. ' webrtc-datachannel\r\n';
  3459. }
  3460. } else if (transceiver.kind === 'audio') {
  3461. sdp$1 += 'm=audio 0 UDP/TLS/RTP/SAVPF 0\r\n' +
  3462. 'a=rtpmap:0 PCMU/8000\r\n';
  3463. } else if (transceiver.kind === 'video') {
  3464. sdp$1 += 'm=video 0 UDP/TLS/RTP/SAVPF 120\r\n' +
  3465. 'a=rtpmap:120 VP8/90000\r\n';
  3466. }
  3467. sdp$1 += 'c=IN IP4 0.0.0.0\r\n' +
  3468. 'a=inactive\r\n' +
  3469. 'a=mid:' + transceiver.mid + '\r\n';
  3470. return;
  3471. }
  3472. // FIXME: look at direction.
  3473. if (transceiver.stream) {
  3474. var localTrack;
  3475. if (transceiver.kind === 'audio') {
  3476. localTrack = transceiver.stream.getAudioTracks()[0];
  3477. } else if (transceiver.kind === 'video') {
  3478. localTrack = transceiver.stream.getVideoTracks()[0];
  3479. }
  3480. if (localTrack) {
  3481. // add RTX
  3482. if (edgeVersion >= 15019 && transceiver.kind === 'video' &&
  3483. !transceiver.sendEncodingParameters[0].rtx) {
  3484. transceiver.sendEncodingParameters[0].rtx = {
  3485. ssrc: transceiver.sendEncodingParameters[0].ssrc + 1
  3486. };
  3487. }
  3488. }
  3489. }
  3490. // Calculate intersection of capabilities.
  3491. var commonCapabilities = getCommonCapabilities(
  3492. transceiver.localCapabilities,
  3493. transceiver.remoteCapabilities);
  3494. var hasRtx = commonCapabilities.codecs.filter(function(c) {
  3495. return c.name.toLowerCase() === 'rtx';
  3496. }).length;
  3497. if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
  3498. delete transceiver.sendEncodingParameters[0].rtx;
  3499. }
  3500. sdp$1 += writeMediaSection(transceiver, commonCapabilities,
  3501. 'answer', transceiver.stream, pc._dtlsRole);
  3502. if (transceiver.rtcpParameters &&
  3503. transceiver.rtcpParameters.reducedSize) {
  3504. sdp$1 += 'a=rtcp-rsize\r\n';
  3505. }
  3506. });
  3507. var desc = new window.RTCSessionDescription({
  3508. type: 'answer',
  3509. sdp: sdp$1
  3510. });
  3511. return Promise.resolve(desc);
  3512. };
  3513. RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
  3514. var pc = this;
  3515. var sections;
  3516. if (candidate && !(candidate.sdpMLineIndex !== undefined ||
  3517. candidate.sdpMid)) {
  3518. return Promise.reject(new TypeError('sdpMLineIndex or sdpMid required'));
  3519. }
  3520. // TODO: needs to go into ops queue.
  3521. return new Promise(function(resolve, reject) {
  3522. if (!pc._remoteDescription) {
  3523. return reject(makeError('InvalidStateError',
  3524. 'Can not add ICE candidate without a remote description'));
  3525. } else if (!candidate || candidate.candidate === '') {
  3526. for (var j = 0; j < pc.transceivers.length; j++) {
  3527. if (pc.transceivers[j].rejected) {
  3528. continue;
  3529. }
  3530. pc.transceivers[j].iceTransport.addRemoteCandidate({});
  3531. sections = sdp.getMediaSections(pc._remoteDescription.sdp);
  3532. sections[j] += 'a=end-of-candidates\r\n';
  3533. pc._remoteDescription.sdp =
  3534. sdp.getDescription(pc._remoteDescription.sdp) +
  3535. sections.join('');
  3536. if (pc.usingBundle) {
  3537. break;
  3538. }
  3539. }
  3540. } else {
  3541. var sdpMLineIndex = candidate.sdpMLineIndex;
  3542. if (candidate.sdpMid) {
  3543. for (var i = 0; i < pc.transceivers.length; i++) {
  3544. if (pc.transceivers[i].mid === candidate.sdpMid) {
  3545. sdpMLineIndex = i;
  3546. break;
  3547. }
  3548. }
  3549. }
  3550. var transceiver = pc.transceivers[sdpMLineIndex];
  3551. if (transceiver) {
  3552. if (transceiver.rejected) {
  3553. return resolve();
  3554. }
  3555. var cand = Object.keys(candidate.candidate).length > 0 ?
  3556. sdp.parseCandidate(candidate.candidate) : {};
  3557. // Ignore Chrome's invalid candidates since Edge does not like them.
  3558. if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
  3559. return resolve();
  3560. }
  3561. // Ignore RTCP candidates, we assume RTCP-MUX.
  3562. if (cand.component && cand.component !== 1) {
  3563. return resolve();
  3564. }
  3565. // when using bundle, avoid adding candidates to the wrong
  3566. // ice transport. And avoid adding candidates added in the SDP.
  3567. if (sdpMLineIndex === 0 || (sdpMLineIndex > 0 &&
  3568. transceiver.iceTransport !== pc.transceivers[0].iceTransport)) {
  3569. if (!maybeAddCandidate(transceiver.iceTransport, cand)) {
  3570. return reject(makeError('OperationError',
  3571. 'Can not add ICE candidate'));
  3572. }
  3573. }
  3574. // update the remoteDescription.
  3575. var candidateString = candidate.candidate.trim();
  3576. if (candidateString.indexOf('a=') === 0) {
  3577. candidateString = candidateString.substr(2);
  3578. }
  3579. sections = sdp.getMediaSections(pc._remoteDescription.sdp);
  3580. sections[sdpMLineIndex] += 'a=' +
  3581. (cand.type ? candidateString : 'end-of-candidates')
  3582. + '\r\n';
  3583. pc._remoteDescription.sdp =
  3584. sdp.getDescription(pc._remoteDescription.sdp) +
  3585. sections.join('');
  3586. } else {
  3587. return reject(makeError('OperationError',
  3588. 'Can not add ICE candidate'));
  3589. }
  3590. }
  3591. resolve();
  3592. });
  3593. };
  3594. RTCPeerConnection.prototype.getStats = function(selector) {
  3595. if (selector && selector instanceof window.MediaStreamTrack) {
  3596. var senderOrReceiver = null;
  3597. this.transceivers.forEach(function(transceiver) {
  3598. if (transceiver.rtpSender &&
  3599. transceiver.rtpSender.track === selector) {
  3600. senderOrReceiver = transceiver.rtpSender;
  3601. } else if (transceiver.rtpReceiver &&
  3602. transceiver.rtpReceiver.track === selector) {
  3603. senderOrReceiver = transceiver.rtpReceiver;
  3604. }
  3605. });
  3606. if (!senderOrReceiver) {
  3607. throw makeError('InvalidAccessError', 'Invalid selector.');
  3608. }
  3609. return senderOrReceiver.getStats();
  3610. }
  3611. var promises = [];
  3612. this.transceivers.forEach(function(transceiver) {
  3613. ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
  3614. 'dtlsTransport'].forEach(function(method) {
  3615. if (transceiver[method]) {
  3616. promises.push(transceiver[method].getStats());
  3617. }
  3618. });
  3619. });
  3620. return Promise.all(promises).then(function(allStats) {
  3621. var results = new Map();
  3622. allStats.forEach(function(stats) {
  3623. stats.forEach(function(stat) {
  3624. results.set(stat.id, stat);
  3625. });
  3626. });
  3627. return results;
  3628. });
  3629. };
  3630. // fix low-level stat names and return Map instead of object.
  3631. var ortcObjects = ['RTCRtpSender', 'RTCRtpReceiver', 'RTCIceGatherer',
  3632. 'RTCIceTransport', 'RTCDtlsTransport'];
  3633. ortcObjects.forEach(function(ortcObjectName) {
  3634. var obj = window[ortcObjectName];
  3635. if (obj && obj.prototype && obj.prototype.getStats) {
  3636. var nativeGetstats = obj.prototype.getStats;
  3637. obj.prototype.getStats = function() {
  3638. return nativeGetstats.apply(this)
  3639. .then(function(nativeStats) {
  3640. var mapStats = new Map();
  3641. Object.keys(nativeStats).forEach(function(id) {
  3642. nativeStats[id].type = fixStatsType(nativeStats[id]);
  3643. mapStats.set(id, nativeStats[id]);
  3644. });
  3645. return mapStats;
  3646. });
  3647. };
  3648. }
  3649. });
  3650. // legacy callback shims. Should be moved to adapter.js some days.
  3651. var methods = ['createOffer', 'createAnswer'];
  3652. methods.forEach(function(method) {
  3653. var nativeMethod = RTCPeerConnection.prototype[method];
  3654. RTCPeerConnection.prototype[method] = function() {
  3655. var args = arguments;
  3656. if (typeof args[0] === 'function' ||
  3657. typeof args[1] === 'function') { // legacy
  3658. return nativeMethod.apply(this, [arguments[2]])
  3659. .then(function(description) {
  3660. if (typeof args[0] === 'function') {
  3661. args[0].apply(null, [description]);
  3662. }
  3663. }, function(error) {
  3664. if (typeof args[1] === 'function') {
  3665. args[1].apply(null, [error]);
  3666. }
  3667. });
  3668. }
  3669. return nativeMethod.apply(this, arguments);
  3670. };
  3671. });
  3672. methods = ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'];
  3673. methods.forEach(function(method) {
  3674. var nativeMethod = RTCPeerConnection.prototype[method];
  3675. RTCPeerConnection.prototype[method] = function() {
  3676. var args = arguments;
  3677. if (typeof args[1] === 'function' ||
  3678. typeof args[2] === 'function') { // legacy
  3679. return nativeMethod.apply(this, arguments)
  3680. .then(function() {
  3681. if (typeof args[1] === 'function') {
  3682. args[1].apply(null);
  3683. }
  3684. }, function(error) {
  3685. if (typeof args[2] === 'function') {
  3686. args[2].apply(null, [error]);
  3687. }
  3688. });
  3689. }
  3690. return nativeMethod.apply(this, arguments);
  3691. };
  3692. });
  3693. // getStats is special. It doesn't have a spec legacy method yet we support
  3694. // getStats(something, cb) without error callbacks.
  3695. ['getStats'].forEach(function(method) {
  3696. var nativeMethod = RTCPeerConnection.prototype[method];
  3697. RTCPeerConnection.prototype[method] = function() {
  3698. var args = arguments;
  3699. if (typeof args[1] === 'function') {
  3700. return nativeMethod.apply(this, arguments)
  3701. .then(function() {
  3702. if (typeof args[1] === 'function') {
  3703. args[1].apply(null);
  3704. }
  3705. });
  3706. }
  3707. return nativeMethod.apply(this, arguments);
  3708. };
  3709. });
  3710. return RTCPeerConnection;
  3711. };
  3712. /*
  3713. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3714. *
  3715. * Use of this source code is governed by a BSD-style license
  3716. * that can be found in the LICENSE file in the root of the source
  3717. * tree.
  3718. */
  3719. function shimGetUserMedia$2(window) {
  3720. const navigator = window && window.navigator;
  3721. const shimError_ = function(e) {
  3722. return {
  3723. name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name,
  3724. message: e.message,
  3725. constraint: e.constraint,
  3726. toString() {
  3727. return this.name;
  3728. }
  3729. };
  3730. };
  3731. // getUserMedia error shim.
  3732. const origGetUserMedia = navigator.mediaDevices.getUserMedia.
  3733. bind(navigator.mediaDevices);
  3734. navigator.mediaDevices.getUserMedia = function(c) {
  3735. return origGetUserMedia(c).catch(e => Promise.reject(shimError_(e)));
  3736. };
  3737. }
  3738. /*
  3739. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  3740. *
  3741. * Use of this source code is governed by a BSD-style license
  3742. * that can be found in the LICENSE file in the root of the source
  3743. * tree.
  3744. */
  3745. function shimGetDisplayMedia$1(window) {
  3746. if (!('getDisplayMedia' in window.navigator)) {
  3747. return;
  3748. }
  3749. if (!(window.navigator.mediaDevices)) {
  3750. return;
  3751. }
  3752. if (window.navigator.mediaDevices &&
  3753. 'getDisplayMedia' in window.navigator.mediaDevices) {
  3754. return;
  3755. }
  3756. window.navigator.mediaDevices.getDisplayMedia =
  3757. window.navigator.getDisplayMedia.bind(window.navigator);
  3758. }
  3759. /*
  3760. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3761. *
  3762. * Use of this source code is governed by a BSD-style license
  3763. * that can be found in the LICENSE file in the root of the source
  3764. * tree.
  3765. */
  3766. function shimPeerConnection$1(window, browserDetails) {
  3767. if (window.RTCIceGatherer) {
  3768. if (!window.RTCIceCandidate) {
  3769. window.RTCIceCandidate = function RTCIceCandidate(args) {
  3770. return args;
  3771. };
  3772. }
  3773. if (!window.RTCSessionDescription) {
  3774. window.RTCSessionDescription = function RTCSessionDescription(args) {
  3775. return args;
  3776. };
  3777. }
  3778. // this adds an additional event listener to MediaStrackTrack that signals
  3779. // when a tracks enabled property was changed. Workaround for a bug in
  3780. // addStream, see below. No longer required in 15025+
  3781. if (browserDetails.version < 15025) {
  3782. const origMSTEnabled = Object.getOwnPropertyDescriptor(
  3783. window.MediaStreamTrack.prototype, 'enabled');
  3784. Object.defineProperty(window.MediaStreamTrack.prototype, 'enabled', {
  3785. set(value) {
  3786. origMSTEnabled.set.call(this, value);
  3787. const ev = new Event('enabled');
  3788. ev.enabled = value;
  3789. this.dispatchEvent(ev);
  3790. }
  3791. });
  3792. }
  3793. }
  3794. // ORTC defines the DTMF sender a bit different.
  3795. // https://github.com/w3c/ortc/issues/714
  3796. if (window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
  3797. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  3798. get() {
  3799. if (this._dtmf === undefined) {
  3800. if (this.track.kind === 'audio') {
  3801. this._dtmf = new window.RTCDtmfSender(this);
  3802. } else if (this.track.kind === 'video') {
  3803. this._dtmf = null;
  3804. }
  3805. }
  3806. return this._dtmf;
  3807. }
  3808. });
  3809. }
  3810. // Edge currently only implements the RTCDtmfSender, not the
  3811. // RTCDTMFSender alias. See http://draft.ortc.org/#rtcdtmfsender2*
  3812. if (window.RTCDtmfSender && !window.RTCDTMFSender) {
  3813. window.RTCDTMFSender = window.RTCDtmfSender;
  3814. }
  3815. const RTCPeerConnectionShim = rtcpeerconnection(window,
  3816. browserDetails.version);
  3817. window.RTCPeerConnection = function RTCPeerConnection(config) {
  3818. if (config && config.iceServers) {
  3819. config.iceServers = filterIceServers$1(config.iceServers,
  3820. browserDetails.version);
  3821. log$1('ICE servers after filtering:', config.iceServers);
  3822. }
  3823. return new RTCPeerConnectionShim(config);
  3824. };
  3825. window.RTCPeerConnection.prototype = RTCPeerConnectionShim.prototype;
  3826. }
  3827. function shimReplaceTrack(window) {
  3828. // ORTC has replaceTrack -- https://github.com/w3c/ortc/issues/614
  3829. if (window.RTCRtpSender &&
  3830. !('replaceTrack' in window.RTCRtpSender.prototype)) {
  3831. window.RTCRtpSender.prototype.replaceTrack =
  3832. window.RTCRtpSender.prototype.setTrack;
  3833. }
  3834. }
  3835. var edgeShim = /*#__PURE__*/Object.freeze({
  3836. __proto__: null,
  3837. shimPeerConnection: shimPeerConnection$1,
  3838. shimReplaceTrack: shimReplaceTrack,
  3839. shimGetUserMedia: shimGetUserMedia$2,
  3840. shimGetDisplayMedia: shimGetDisplayMedia$1
  3841. });
  3842. /*
  3843. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3844. *
  3845. * Use of this source code is governed by a BSD-style license
  3846. * that can be found in the LICENSE file in the root of the source
  3847. * tree.
  3848. */
  3849. function shimGetUserMedia$1(window, browserDetails) {
  3850. const navigator = window && window.navigator;
  3851. const MediaStreamTrack = window && window.MediaStreamTrack;
  3852. navigator.getUserMedia = function(constraints, onSuccess, onError) {
  3853. // Replace Firefox 44+'s deprecation warning with unprefixed version.
  3854. deprecated('navigator.getUserMedia',
  3855. 'navigator.mediaDevices.getUserMedia');
  3856. navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
  3857. };
  3858. if (!(browserDetails.version > 55 &&
  3859. 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
  3860. const remap = function(obj, a, b) {
  3861. if (a in obj && !(b in obj)) {
  3862. obj[b] = obj[a];
  3863. delete obj[a];
  3864. }
  3865. };
  3866. const nativeGetUserMedia = navigator.mediaDevices.getUserMedia.
  3867. bind(navigator.mediaDevices);
  3868. navigator.mediaDevices.getUserMedia = function(c) {
  3869. if (typeof c === 'object' && typeof c.audio === 'object') {
  3870. c = JSON.parse(JSON.stringify(c));
  3871. remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
  3872. remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
  3873. }
  3874. return nativeGetUserMedia(c);
  3875. };
  3876. if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
  3877. const nativeGetSettings = MediaStreamTrack.prototype.getSettings;
  3878. MediaStreamTrack.prototype.getSettings = function() {
  3879. const obj = nativeGetSettings.apply(this, arguments);
  3880. remap(obj, 'mozAutoGainControl', 'autoGainControl');
  3881. remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
  3882. return obj;
  3883. };
  3884. }
  3885. if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
  3886. const nativeApplyConstraints =
  3887. MediaStreamTrack.prototype.applyConstraints;
  3888. MediaStreamTrack.prototype.applyConstraints = function(c) {
  3889. if (this.kind === 'audio' && typeof c === 'object') {
  3890. c = JSON.parse(JSON.stringify(c));
  3891. remap(c, 'autoGainControl', 'mozAutoGainControl');
  3892. remap(c, 'noiseSuppression', 'mozNoiseSuppression');
  3893. }
  3894. return nativeApplyConstraints.apply(this, [c]);
  3895. };
  3896. }
  3897. }
  3898. }
  3899. /*
  3900. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  3901. *
  3902. * Use of this source code is governed by a BSD-style license
  3903. * that can be found in the LICENSE file in the root of the source
  3904. * tree.
  3905. */
  3906. function shimGetDisplayMedia(window, preferredMediaSource) {
  3907. if (window.navigator.mediaDevices &&
  3908. 'getDisplayMedia' in window.navigator.mediaDevices) {
  3909. return;
  3910. }
  3911. if (!(window.navigator.mediaDevices)) {
  3912. return;
  3913. }
  3914. window.navigator.mediaDevices.getDisplayMedia =
  3915. function getDisplayMedia(constraints) {
  3916. if (!(constraints && constraints.video)) {
  3917. const err = new DOMException('getDisplayMedia without video ' +
  3918. 'constraints is undefined');
  3919. err.name = 'NotFoundError';
  3920. // from https://heycam.github.io/webidl/#idl-DOMException-error-names
  3921. err.code = 8;
  3922. return Promise.reject(err);
  3923. }
  3924. if (constraints.video === true) {
  3925. constraints.video = {mediaSource: preferredMediaSource};
  3926. } else {
  3927. constraints.video.mediaSource = preferredMediaSource;
  3928. }
  3929. return window.navigator.mediaDevices.getUserMedia(constraints);
  3930. };
  3931. }
  3932. /*
  3933. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3934. *
  3935. * Use of this source code is governed by a BSD-style license
  3936. * that can be found in the LICENSE file in the root of the source
  3937. * tree.
  3938. */
  3939. function shimOnTrack(window) {
  3940. if (typeof window === 'object' && window.RTCTrackEvent &&
  3941. ('receiver' in window.RTCTrackEvent.prototype) &&
  3942. !('transceiver' in window.RTCTrackEvent.prototype)) {
  3943. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  3944. get() {
  3945. return {receiver: this.receiver};
  3946. }
  3947. });
  3948. }
  3949. }
  3950. function shimPeerConnection(window, browserDetails) {
  3951. if (typeof window !== 'object' ||
  3952. !(window.RTCPeerConnection || window.mozRTCPeerConnection)) {
  3953. return; // probably media.peerconnection.enabled=false in about:config
  3954. }
  3955. if (!window.RTCPeerConnection && window.mozRTCPeerConnection) {
  3956. // very basic support for old versions.
  3957. window.RTCPeerConnection = window.mozRTCPeerConnection;
  3958. }
  3959. if (browserDetails.version < 53) {
  3960. // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
  3961. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  3962. .forEach(function(method) {
  3963. const nativeMethod = window.RTCPeerConnection.prototype[method];
  3964. const methodObj = {[method]() {
  3965. arguments[0] = new ((method === 'addIceCandidate') ?
  3966. window.RTCIceCandidate :
  3967. window.RTCSessionDescription)(arguments[0]);
  3968. return nativeMethod.apply(this, arguments);
  3969. }};
  3970. window.RTCPeerConnection.prototype[method] = methodObj[method];
  3971. });
  3972. }
  3973. const modernStatsTypes = {
  3974. inboundrtp: 'inbound-rtp',
  3975. outboundrtp: 'outbound-rtp',
  3976. candidatepair: 'candidate-pair',
  3977. localcandidate: 'local-candidate',
  3978. remotecandidate: 'remote-candidate'
  3979. };
  3980. const nativeGetStats = window.RTCPeerConnection.prototype.getStats;
  3981. window.RTCPeerConnection.prototype.getStats = function getStats() {
  3982. const [selector, onSucc, onErr] = arguments;
  3983. return nativeGetStats.apply(this, [selector || null])
  3984. .then(stats => {
  3985. if (browserDetails.version < 53 && !onSucc) {
  3986. // Shim only promise getStats with spec-hyphens in type names
  3987. // Leave callback version alone; misc old uses of forEach before Map
  3988. try {
  3989. stats.forEach(stat => {
  3990. stat.type = modernStatsTypes[stat.type] || stat.type;
  3991. });
  3992. } catch (e) {
  3993. if (e.name !== 'TypeError') {
  3994. throw e;
  3995. }
  3996. // Avoid TypeError: "type" is read-only, in old versions. 34-43ish
  3997. stats.forEach((stat, i) => {
  3998. stats.set(i, Object.assign({}, stat, {
  3999. type: modernStatsTypes[stat.type] || stat.type
  4000. }));
  4001. });
  4002. }
  4003. }
  4004. return stats;
  4005. })
  4006. .then(onSucc, onErr);
  4007. };
  4008. }
  4009. function shimSenderGetStats(window) {
  4010. if (!(typeof window === 'object' && window.RTCPeerConnection &&
  4011. window.RTCRtpSender)) {
  4012. return;
  4013. }
  4014. if (window.RTCRtpSender && 'getStats' in window.RTCRtpSender.prototype) {
  4015. return;
  4016. }
  4017. const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  4018. if (origGetSenders) {
  4019. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  4020. const senders = origGetSenders.apply(this, []);
  4021. senders.forEach(sender => sender._pc = this);
  4022. return senders;
  4023. };
  4024. }
  4025. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  4026. if (origAddTrack) {
  4027. window.RTCPeerConnection.prototype.addTrack = function addTrack() {
  4028. const sender = origAddTrack.apply(this, arguments);
  4029. sender._pc = this;
  4030. return sender;
  4031. };
  4032. }
  4033. window.RTCRtpSender.prototype.getStats = function getStats() {
  4034. return this.track ? this._pc.getStats(this.track) :
  4035. Promise.resolve(new Map());
  4036. };
  4037. }
  4038. function shimReceiverGetStats(window) {
  4039. if (!(typeof window === 'object' && window.RTCPeerConnection &&
  4040. window.RTCRtpSender)) {
  4041. return;
  4042. }
  4043. if (window.RTCRtpSender && 'getStats' in window.RTCRtpReceiver.prototype) {
  4044. return;
  4045. }
  4046. const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
  4047. if (origGetReceivers) {
  4048. window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {
  4049. const receivers = origGetReceivers.apply(this, []);
  4050. receivers.forEach(receiver => receiver._pc = this);
  4051. return receivers;
  4052. };
  4053. }
  4054. wrapPeerConnectionEvent(window, 'track', e => {
  4055. e.receiver._pc = e.srcElement;
  4056. return e;
  4057. });
  4058. window.RTCRtpReceiver.prototype.getStats = function getStats() {
  4059. return this._pc.getStats(this.track);
  4060. };
  4061. }
  4062. function shimRemoveStream(window) {
  4063. if (!window.RTCPeerConnection ||
  4064. 'removeStream' in window.RTCPeerConnection.prototype) {
  4065. return;
  4066. }
  4067. window.RTCPeerConnection.prototype.removeStream =
  4068. function removeStream(stream) {
  4069. deprecated('removeStream', 'removeTrack');
  4070. this.getSenders().forEach(sender => {
  4071. if (sender.track && stream.getTracks().includes(sender.track)) {
  4072. this.removeTrack(sender);
  4073. }
  4074. });
  4075. };
  4076. }
  4077. function shimRTCDataChannel(window) {
  4078. // rename DataChannel to RTCDataChannel (native fix in FF60):
  4079. // https://bugzilla.mozilla.org/show_bug.cgi?id=1173851
  4080. if (window.DataChannel && !window.RTCDataChannel) {
  4081. window.RTCDataChannel = window.DataChannel;
  4082. }
  4083. }
  4084. function shimAddTransceiver(window) {
  4085. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  4086. // Firefox ignores the init sendEncodings options passed to addTransceiver
  4087. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  4088. if (!(typeof window === 'object' && window.RTCPeerConnection)) {
  4089. return;
  4090. }
  4091. const origAddTransceiver = window.RTCPeerConnection.prototype.addTransceiver;
  4092. if (origAddTransceiver) {
  4093. window.RTCPeerConnection.prototype.addTransceiver =
  4094. function addTransceiver() {
  4095. this.setParametersPromises = [];
  4096. const initParameters = arguments[1];
  4097. const shouldPerformCheck = initParameters &&
  4098. 'sendEncodings' in initParameters;
  4099. if (shouldPerformCheck) {
  4100. // If sendEncodings params are provided, validate grammar
  4101. initParameters.sendEncodings.forEach((encodingParam) => {
  4102. if ('rid' in encodingParam) {
  4103. const ridRegex = /^[a-z0-9]{0,16}$/i;
  4104. if (!ridRegex.test(encodingParam.rid)) {
  4105. throw new TypeError('Invalid RID value provided.');
  4106. }
  4107. }
  4108. if ('scaleResolutionDownBy' in encodingParam) {
  4109. if (!(parseFloat(encodingParam.scaleResolutionDownBy) >= 1.0)) {
  4110. throw new RangeError('scale_resolution_down_by must be >= 1.0');
  4111. }
  4112. }
  4113. if ('maxFramerate' in encodingParam) {
  4114. if (!(parseFloat(encodingParam.maxFramerate) >= 0)) {
  4115. throw new RangeError('max_framerate must be >= 0.0');
  4116. }
  4117. }
  4118. });
  4119. }
  4120. const transceiver = origAddTransceiver.apply(this, arguments);
  4121. if (shouldPerformCheck) {
  4122. // Check if the init options were applied. If not we do this in an
  4123. // asynchronous way and save the promise reference in a global object.
  4124. // This is an ugly hack, but at the same time is way more robust than
  4125. // checking the sender parameters before and after the createOffer
  4126. // Also note that after the createoffer we are not 100% sure that
  4127. // the params were asynchronously applied so we might miss the
  4128. // opportunity to recreate offer.
  4129. const {sender} = transceiver;
  4130. const params = sender.getParameters();
  4131. if (!('encodings' in params) ||
  4132. // Avoid being fooled by patched getParameters() below.
  4133. (params.encodings.length === 1 &&
  4134. Object.keys(params.encodings[0]).length === 0)) {
  4135. params.encodings = initParameters.sendEncodings;
  4136. sender.sendEncodings = initParameters.sendEncodings;
  4137. this.setParametersPromises.push(sender.setParameters(params)
  4138. .then(() => {
  4139. delete sender.sendEncodings;
  4140. }).catch(() => {
  4141. delete sender.sendEncodings;
  4142. })
  4143. );
  4144. }
  4145. }
  4146. return transceiver;
  4147. };
  4148. }
  4149. }
  4150. function shimGetParameters(window) {
  4151. if (!(typeof window === 'object' && window.RTCRtpSender)) {
  4152. return;
  4153. }
  4154. const origGetParameters = window.RTCRtpSender.prototype.getParameters;
  4155. if (origGetParameters) {
  4156. window.RTCRtpSender.prototype.getParameters =
  4157. function getParameters() {
  4158. const params = origGetParameters.apply(this, arguments);
  4159. if (!('encodings' in params)) {
  4160. params.encodings = [].concat(this.sendEncodings || [{}]);
  4161. }
  4162. return params;
  4163. };
  4164. }
  4165. }
  4166. function shimCreateOffer(window) {
  4167. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  4168. // Firefox ignores the init sendEncodings options passed to addTransceiver
  4169. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  4170. if (!(typeof window === 'object' && window.RTCPeerConnection)) {
  4171. return;
  4172. }
  4173. const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
  4174. window.RTCPeerConnection.prototype.createOffer = function createOffer() {
  4175. if (this.setParametersPromises && this.setParametersPromises.length) {
  4176. return Promise.all(this.setParametersPromises)
  4177. .then(() => {
  4178. return origCreateOffer.apply(this, arguments);
  4179. })
  4180. .finally(() => {
  4181. this.setParametersPromises = [];
  4182. });
  4183. }
  4184. return origCreateOffer.apply(this, arguments);
  4185. };
  4186. }
  4187. function shimCreateAnswer(window) {
  4188. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  4189. // Firefox ignores the init sendEncodings options passed to addTransceiver
  4190. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  4191. if (!(typeof window === 'object' && window.RTCPeerConnection)) {
  4192. return;
  4193. }
  4194. const origCreateAnswer = window.RTCPeerConnection.prototype.createAnswer;
  4195. window.RTCPeerConnection.prototype.createAnswer = function createAnswer() {
  4196. if (this.setParametersPromises && this.setParametersPromises.length) {
  4197. return Promise.all(this.setParametersPromises)
  4198. .then(() => {
  4199. return origCreateAnswer.apply(this, arguments);
  4200. })
  4201. .finally(() => {
  4202. this.setParametersPromises = [];
  4203. });
  4204. }
  4205. return origCreateAnswer.apply(this, arguments);
  4206. };
  4207. }
  4208. var firefoxShim = /*#__PURE__*/Object.freeze({
  4209. __proto__: null,
  4210. shimOnTrack: shimOnTrack,
  4211. shimPeerConnection: shimPeerConnection,
  4212. shimSenderGetStats: shimSenderGetStats,
  4213. shimReceiverGetStats: shimReceiverGetStats,
  4214. shimRemoveStream: shimRemoveStream,
  4215. shimRTCDataChannel: shimRTCDataChannel,
  4216. shimAddTransceiver: shimAddTransceiver,
  4217. shimGetParameters: shimGetParameters,
  4218. shimCreateOffer: shimCreateOffer,
  4219. shimCreateAnswer: shimCreateAnswer,
  4220. shimGetUserMedia: shimGetUserMedia$1,
  4221. shimGetDisplayMedia: shimGetDisplayMedia
  4222. });
  4223. /*
  4224. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4225. *
  4226. * Use of this source code is governed by a BSD-style license
  4227. * that can be found in the LICENSE file in the root of the source
  4228. * tree.
  4229. */
  4230. function shimLocalStreamsAPI(window) {
  4231. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4232. return;
  4233. }
  4234. if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {
  4235. window.RTCPeerConnection.prototype.getLocalStreams =
  4236. function getLocalStreams() {
  4237. if (!this._localStreams) {
  4238. this._localStreams = [];
  4239. }
  4240. return this._localStreams;
  4241. };
  4242. }
  4243. if (!('addStream' in window.RTCPeerConnection.prototype)) {
  4244. const _addTrack = window.RTCPeerConnection.prototype.addTrack;
  4245. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  4246. if (!this._localStreams) {
  4247. this._localStreams = [];
  4248. }
  4249. if (!this._localStreams.includes(stream)) {
  4250. this._localStreams.push(stream);
  4251. }
  4252. // Try to emulate Chrome's behaviour of adding in audio-video order.
  4253. // Safari orders by track id.
  4254. stream.getAudioTracks().forEach(track => _addTrack.call(this, track,
  4255. stream));
  4256. stream.getVideoTracks().forEach(track => _addTrack.call(this, track,
  4257. stream));
  4258. };
  4259. window.RTCPeerConnection.prototype.addTrack =
  4260. function addTrack(track, ...streams) {
  4261. if (streams) {
  4262. streams.forEach((stream) => {
  4263. if (!this._localStreams) {
  4264. this._localStreams = [stream];
  4265. } else if (!this._localStreams.includes(stream)) {
  4266. this._localStreams.push(stream);
  4267. }
  4268. });
  4269. }
  4270. return _addTrack.apply(this, arguments);
  4271. };
  4272. }
  4273. if (!('removeStream' in window.RTCPeerConnection.prototype)) {
  4274. window.RTCPeerConnection.prototype.removeStream =
  4275. function removeStream(stream) {
  4276. if (!this._localStreams) {
  4277. this._localStreams = [];
  4278. }
  4279. const index = this._localStreams.indexOf(stream);
  4280. if (index === -1) {
  4281. return;
  4282. }
  4283. this._localStreams.splice(index, 1);
  4284. const tracks = stream.getTracks();
  4285. this.getSenders().forEach(sender => {
  4286. if (tracks.includes(sender.track)) {
  4287. this.removeTrack(sender);
  4288. }
  4289. });
  4290. };
  4291. }
  4292. }
  4293. function shimRemoteStreamsAPI(window) {
  4294. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4295. return;
  4296. }
  4297. if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {
  4298. window.RTCPeerConnection.prototype.getRemoteStreams =
  4299. function getRemoteStreams() {
  4300. return this._remoteStreams ? this._remoteStreams : [];
  4301. };
  4302. }
  4303. if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
  4304. Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
  4305. get() {
  4306. return this._onaddstream;
  4307. },
  4308. set(f) {
  4309. if (this._onaddstream) {
  4310. this.removeEventListener('addstream', this._onaddstream);
  4311. this.removeEventListener('track', this._onaddstreampoly);
  4312. }
  4313. this.addEventListener('addstream', this._onaddstream = f);
  4314. this.addEventListener('track', this._onaddstreampoly = (e) => {
  4315. e.streams.forEach(stream => {
  4316. if (!this._remoteStreams) {
  4317. this._remoteStreams = [];
  4318. }
  4319. if (this._remoteStreams.includes(stream)) {
  4320. return;
  4321. }
  4322. this._remoteStreams.push(stream);
  4323. const event = new Event('addstream');
  4324. event.stream = stream;
  4325. this.dispatchEvent(event);
  4326. });
  4327. });
  4328. }
  4329. });
  4330. const origSetRemoteDescription =
  4331. window.RTCPeerConnection.prototype.setRemoteDescription;
  4332. window.RTCPeerConnection.prototype.setRemoteDescription =
  4333. function setRemoteDescription() {
  4334. const pc = this;
  4335. if (!this._onaddstreampoly) {
  4336. this.addEventListener('track', this._onaddstreampoly = function(e) {
  4337. e.streams.forEach(stream => {
  4338. if (!pc._remoteStreams) {
  4339. pc._remoteStreams = [];
  4340. }
  4341. if (pc._remoteStreams.indexOf(stream) >= 0) {
  4342. return;
  4343. }
  4344. pc._remoteStreams.push(stream);
  4345. const event = new Event('addstream');
  4346. event.stream = stream;
  4347. pc.dispatchEvent(event);
  4348. });
  4349. });
  4350. }
  4351. return origSetRemoteDescription.apply(pc, arguments);
  4352. };
  4353. }
  4354. }
  4355. function shimCallbacksAPI(window) {
  4356. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4357. return;
  4358. }
  4359. const prototype = window.RTCPeerConnection.prototype;
  4360. const origCreateOffer = prototype.createOffer;
  4361. const origCreateAnswer = prototype.createAnswer;
  4362. const setLocalDescription = prototype.setLocalDescription;
  4363. const setRemoteDescription = prototype.setRemoteDescription;
  4364. const addIceCandidate = prototype.addIceCandidate;
  4365. prototype.createOffer =
  4366. function createOffer(successCallback, failureCallback) {
  4367. const options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  4368. const promise = origCreateOffer.apply(this, [options]);
  4369. if (!failureCallback) {
  4370. return promise;
  4371. }
  4372. promise.then(successCallback, failureCallback);
  4373. return Promise.resolve();
  4374. };
  4375. prototype.createAnswer =
  4376. function createAnswer(successCallback, failureCallback) {
  4377. const options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  4378. const promise = origCreateAnswer.apply(this, [options]);
  4379. if (!failureCallback) {
  4380. return promise;
  4381. }
  4382. promise.then(successCallback, failureCallback);
  4383. return Promise.resolve();
  4384. };
  4385. let withCallback = function(description, successCallback, failureCallback) {
  4386. const promise = setLocalDescription.apply(this, [description]);
  4387. if (!failureCallback) {
  4388. return promise;
  4389. }
  4390. promise.then(successCallback, failureCallback);
  4391. return Promise.resolve();
  4392. };
  4393. prototype.setLocalDescription = withCallback;
  4394. withCallback = function(description, successCallback, failureCallback) {
  4395. const promise = setRemoteDescription.apply(this, [description]);
  4396. if (!failureCallback) {
  4397. return promise;
  4398. }
  4399. promise.then(successCallback, failureCallback);
  4400. return Promise.resolve();
  4401. };
  4402. prototype.setRemoteDescription = withCallback;
  4403. withCallback = function(candidate, successCallback, failureCallback) {
  4404. const promise = addIceCandidate.apply(this, [candidate]);
  4405. if (!failureCallback) {
  4406. return promise;
  4407. }
  4408. promise.then(successCallback, failureCallback);
  4409. return Promise.resolve();
  4410. };
  4411. prototype.addIceCandidate = withCallback;
  4412. }
  4413. function shimGetUserMedia(window) {
  4414. const navigator = window && window.navigator;
  4415. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  4416. // shim not needed in Safari 12.1
  4417. const mediaDevices = navigator.mediaDevices;
  4418. const _getUserMedia = mediaDevices.getUserMedia.bind(mediaDevices);
  4419. navigator.mediaDevices.getUserMedia = (constraints) => {
  4420. return _getUserMedia(shimConstraints(constraints));
  4421. };
  4422. }
  4423. if (!navigator.getUserMedia && navigator.mediaDevices &&
  4424. navigator.mediaDevices.getUserMedia) {
  4425. navigator.getUserMedia = function getUserMedia(constraints, cb, errcb) {
  4426. navigator.mediaDevices.getUserMedia(constraints)
  4427. .then(cb, errcb);
  4428. }.bind(navigator);
  4429. }
  4430. }
  4431. function shimConstraints(constraints) {
  4432. if (constraints && constraints.video !== undefined) {
  4433. return Object.assign({},
  4434. constraints,
  4435. {video: compactObject(constraints.video)}
  4436. );
  4437. }
  4438. return constraints;
  4439. }
  4440. function shimRTCIceServerUrls(window) {
  4441. if (!window.RTCPeerConnection) {
  4442. return;
  4443. }
  4444. // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
  4445. const OrigPeerConnection = window.RTCPeerConnection;
  4446. window.RTCPeerConnection =
  4447. function RTCPeerConnection(pcConfig, pcConstraints) {
  4448. if (pcConfig && pcConfig.iceServers) {
  4449. const newIceServers = [];
  4450. for (let i = 0; i < pcConfig.iceServers.length; i++) {
  4451. let server = pcConfig.iceServers[i];
  4452. if (!server.hasOwnProperty('urls') &&
  4453. server.hasOwnProperty('url')) {
  4454. deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  4455. server = JSON.parse(JSON.stringify(server));
  4456. server.urls = server.url;
  4457. delete server.url;
  4458. newIceServers.push(server);
  4459. } else {
  4460. newIceServers.push(pcConfig.iceServers[i]);
  4461. }
  4462. }
  4463. pcConfig.iceServers = newIceServers;
  4464. }
  4465. return new OrigPeerConnection(pcConfig, pcConstraints);
  4466. };
  4467. window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
  4468. // wrap static methods. Currently just generateCertificate.
  4469. if ('generateCertificate' in OrigPeerConnection) {
  4470. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  4471. get() {
  4472. return OrigPeerConnection.generateCertificate;
  4473. }
  4474. });
  4475. }
  4476. }
  4477. function shimTrackEventTransceiver(window) {
  4478. // Add event.transceiver member over deprecated event.receiver
  4479. if (typeof window === 'object' && window.RTCTrackEvent &&
  4480. 'receiver' in window.RTCTrackEvent.prototype &&
  4481. !('transceiver' in window.RTCTrackEvent.prototype)) {
  4482. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  4483. get() {
  4484. return {receiver: this.receiver};
  4485. }
  4486. });
  4487. }
  4488. }
  4489. function shimCreateOfferLegacy(window) {
  4490. const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
  4491. window.RTCPeerConnection.prototype.createOffer =
  4492. function createOffer(offerOptions) {
  4493. if (offerOptions) {
  4494. if (typeof offerOptions.offerToReceiveAudio !== 'undefined') {
  4495. // support bit values
  4496. offerOptions.offerToReceiveAudio =
  4497. !!offerOptions.offerToReceiveAudio;
  4498. }
  4499. const audioTransceiver = this.getTransceivers().find(transceiver =>
  4500. transceiver.receiver.track.kind === 'audio');
  4501. if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {
  4502. if (audioTransceiver.direction === 'sendrecv') {
  4503. if (audioTransceiver.setDirection) {
  4504. audioTransceiver.setDirection('sendonly');
  4505. } else {
  4506. audioTransceiver.direction = 'sendonly';
  4507. }
  4508. } else if (audioTransceiver.direction === 'recvonly') {
  4509. if (audioTransceiver.setDirection) {
  4510. audioTransceiver.setDirection('inactive');
  4511. } else {
  4512. audioTransceiver.direction = 'inactive';
  4513. }
  4514. }
  4515. } else if (offerOptions.offerToReceiveAudio === true &&
  4516. !audioTransceiver) {
  4517. this.addTransceiver('audio');
  4518. }
  4519. if (typeof offerOptions.offerToReceiveVideo !== 'undefined') {
  4520. // support bit values
  4521. offerOptions.offerToReceiveVideo =
  4522. !!offerOptions.offerToReceiveVideo;
  4523. }
  4524. const videoTransceiver = this.getTransceivers().find(transceiver =>
  4525. transceiver.receiver.track.kind === 'video');
  4526. if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {
  4527. if (videoTransceiver.direction === 'sendrecv') {
  4528. if (videoTransceiver.setDirection) {
  4529. videoTransceiver.setDirection('sendonly');
  4530. } else {
  4531. videoTransceiver.direction = 'sendonly';
  4532. }
  4533. } else if (videoTransceiver.direction === 'recvonly') {
  4534. if (videoTransceiver.setDirection) {
  4535. videoTransceiver.setDirection('inactive');
  4536. } else {
  4537. videoTransceiver.direction = 'inactive';
  4538. }
  4539. }
  4540. } else if (offerOptions.offerToReceiveVideo === true &&
  4541. !videoTransceiver) {
  4542. this.addTransceiver('video');
  4543. }
  4544. }
  4545. return origCreateOffer.apply(this, arguments);
  4546. };
  4547. }
  4548. function shimAudioContext(window) {
  4549. if (typeof window !== 'object' || window.AudioContext) {
  4550. return;
  4551. }
  4552. window.AudioContext = window.webkitAudioContext;
  4553. }
  4554. var safariShim = /*#__PURE__*/Object.freeze({
  4555. __proto__: null,
  4556. shimLocalStreamsAPI: shimLocalStreamsAPI,
  4557. shimRemoteStreamsAPI: shimRemoteStreamsAPI,
  4558. shimCallbacksAPI: shimCallbacksAPI,
  4559. shimGetUserMedia: shimGetUserMedia,
  4560. shimConstraints: shimConstraints,
  4561. shimRTCIceServerUrls: shimRTCIceServerUrls,
  4562. shimTrackEventTransceiver: shimTrackEventTransceiver,
  4563. shimCreateOfferLegacy: shimCreateOfferLegacy,
  4564. shimAudioContext: shimAudioContext
  4565. });
  4566. /*
  4567. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  4568. *
  4569. * Use of this source code is governed by a BSD-style license
  4570. * that can be found in the LICENSE file in the root of the source
  4571. * tree.
  4572. */
  4573. function shimRTCIceCandidate(window) {
  4574. // foundation is arbitrarily chosen as an indicator for full support for
  4575. // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
  4576. if (!window.RTCIceCandidate || (window.RTCIceCandidate && 'foundation' in
  4577. window.RTCIceCandidate.prototype)) {
  4578. return;
  4579. }
  4580. const NativeRTCIceCandidate = window.RTCIceCandidate;
  4581. window.RTCIceCandidate = function RTCIceCandidate(args) {
  4582. // Remove the a= which shouldn't be part of the candidate string.
  4583. if (typeof args === 'object' && args.candidate &&
  4584. args.candidate.indexOf('a=') === 0) {
  4585. args = JSON.parse(JSON.stringify(args));
  4586. args.candidate = args.candidate.substr(2);
  4587. }
  4588. if (args.candidate && args.candidate.length) {
  4589. // Augment the native candidate with the parsed fields.
  4590. const nativeCandidate = new NativeRTCIceCandidate(args);
  4591. const parsedCandidate = sdp.parseCandidate(args.candidate);
  4592. const augmentedCandidate = Object.assign(nativeCandidate,
  4593. parsedCandidate);
  4594. // Add a serializer that does not serialize the extra attributes.
  4595. augmentedCandidate.toJSON = function toJSON() {
  4596. return {
  4597. candidate: augmentedCandidate.candidate,
  4598. sdpMid: augmentedCandidate.sdpMid,
  4599. sdpMLineIndex: augmentedCandidate.sdpMLineIndex,
  4600. usernameFragment: augmentedCandidate.usernameFragment,
  4601. };
  4602. };
  4603. return augmentedCandidate;
  4604. }
  4605. return new NativeRTCIceCandidate(args);
  4606. };
  4607. window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype;
  4608. // Hook up the augmented candidate in onicecandidate and
  4609. // addEventListener('icecandidate', ...)
  4610. wrapPeerConnectionEvent(window, 'icecandidate', e => {
  4611. if (e.candidate) {
  4612. Object.defineProperty(e, 'candidate', {
  4613. value: new window.RTCIceCandidate(e.candidate),
  4614. writable: 'false'
  4615. });
  4616. }
  4617. return e;
  4618. });
  4619. }
  4620. function shimMaxMessageSize(window, browserDetails) {
  4621. if (!window.RTCPeerConnection) {
  4622. return;
  4623. }
  4624. if (!('sctp' in window.RTCPeerConnection.prototype)) {
  4625. Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', {
  4626. get() {
  4627. return typeof this._sctp === 'undefined' ? null : this._sctp;
  4628. }
  4629. });
  4630. }
  4631. const sctpInDescription = function(description) {
  4632. if (!description || !description.sdp) {
  4633. return false;
  4634. }
  4635. const sections = sdp.splitSections(description.sdp);
  4636. sections.shift();
  4637. return sections.some(mediaSection => {
  4638. const mLine = sdp.parseMLine(mediaSection);
  4639. return mLine && mLine.kind === 'application'
  4640. && mLine.protocol.indexOf('SCTP') !== -1;
  4641. });
  4642. };
  4643. const getRemoteFirefoxVersion = function(description) {
  4644. // TODO: Is there a better solution for detecting Firefox?
  4645. const match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
  4646. if (match === null || match.length < 2) {
  4647. return -1;
  4648. }
  4649. const version = parseInt(match[1], 10);
  4650. // Test for NaN (yes, this is ugly)
  4651. return version !== version ? -1 : version;
  4652. };
  4653. const getCanSendMaxMessageSize = function(remoteIsFirefox) {
  4654. // Every implementation we know can send at least 64 KiB.
  4655. // Note: Although Chrome is technically able to send up to 256 KiB, the
  4656. // data does not reach the other peer reliably.
  4657. // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419
  4658. let canSendMaxMessageSize = 65536;
  4659. if (browserDetails.browser === 'firefox') {
  4660. if (browserDetails.version < 57) {
  4661. if (remoteIsFirefox === -1) {
  4662. // FF < 57 will send in 16 KiB chunks using the deprecated PPID
  4663. // fragmentation.
  4664. canSendMaxMessageSize = 16384;
  4665. } else {
  4666. // However, other FF (and RAWRTC) can reassemble PPID-fragmented
  4667. // messages. Thus, supporting ~2 GiB when sending.
  4668. canSendMaxMessageSize = 2147483637;
  4669. }
  4670. } else if (browserDetails.version < 60) {
  4671. // Currently, all FF >= 57 will reset the remote maximum message size
  4672. // to the default value when a data channel is created at a later
  4673. // stage. :(
  4674. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  4675. canSendMaxMessageSize =
  4676. browserDetails.version === 57 ? 65535 : 65536;
  4677. } else {
  4678. // FF >= 60 supports sending ~2 GiB
  4679. canSendMaxMessageSize = 2147483637;
  4680. }
  4681. }
  4682. return canSendMaxMessageSize;
  4683. };
  4684. const getMaxMessageSize = function(description, remoteIsFirefox) {
  4685. // Note: 65536 bytes is the default value from the SDP spec. Also,
  4686. // every implementation we know supports receiving 65536 bytes.
  4687. let maxMessageSize = 65536;
  4688. // FF 57 has a slightly incorrect default remote max message size, so
  4689. // we need to adjust it here to avoid a failure when sending.
  4690. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697
  4691. if (browserDetails.browser === 'firefox'
  4692. && browserDetails.version === 57) {
  4693. maxMessageSize = 65535;
  4694. }
  4695. const match = sdp.matchPrefix(description.sdp,
  4696. 'a=max-message-size:');
  4697. if (match.length > 0) {
  4698. maxMessageSize = parseInt(match[0].substr(19), 10);
  4699. } else if (browserDetails.browser === 'firefox' &&
  4700. remoteIsFirefox !== -1) {
  4701. // If the maximum message size is not present in the remote SDP and
  4702. // both local and remote are Firefox, the remote peer can receive
  4703. // ~2 GiB.
  4704. maxMessageSize = 2147483637;
  4705. }
  4706. return maxMessageSize;
  4707. };
  4708. const origSetRemoteDescription =
  4709. window.RTCPeerConnection.prototype.setRemoteDescription;
  4710. window.RTCPeerConnection.prototype.setRemoteDescription =
  4711. function setRemoteDescription() {
  4712. this._sctp = null;
  4713. // Chrome decided to not expose .sctp in plan-b mode.
  4714. // As usual, adapter.js has to do an 'ugly worakaround'
  4715. // to cover up the mess.
  4716. if (browserDetails.browser === 'chrome' && browserDetails.version >= 76) {
  4717. const {sdpSemantics} = this.getConfiguration();
  4718. if (sdpSemantics === 'plan-b') {
  4719. Object.defineProperty(this, 'sctp', {
  4720. get() {
  4721. return typeof this._sctp === 'undefined' ? null : this._sctp;
  4722. },
  4723. enumerable: true,
  4724. configurable: true,
  4725. });
  4726. }
  4727. }
  4728. if (sctpInDescription(arguments[0])) {
  4729. // Check if the remote is FF.
  4730. const isFirefox = getRemoteFirefoxVersion(arguments[0]);
  4731. // Get the maximum message size the local peer is capable of sending
  4732. const canSendMMS = getCanSendMaxMessageSize(isFirefox);
  4733. // Get the maximum message size of the remote peer.
  4734. const remoteMMS = getMaxMessageSize(arguments[0], isFirefox);
  4735. // Determine final maximum message size
  4736. let maxMessageSize;
  4737. if (canSendMMS === 0 && remoteMMS === 0) {
  4738. maxMessageSize = Number.POSITIVE_INFINITY;
  4739. } else if (canSendMMS === 0 || remoteMMS === 0) {
  4740. maxMessageSize = Math.max(canSendMMS, remoteMMS);
  4741. } else {
  4742. maxMessageSize = Math.min(canSendMMS, remoteMMS);
  4743. }
  4744. // Create a dummy RTCSctpTransport object and the 'maxMessageSize'
  4745. // attribute.
  4746. const sctp = {};
  4747. Object.defineProperty(sctp, 'maxMessageSize', {
  4748. get() {
  4749. return maxMessageSize;
  4750. }
  4751. });
  4752. this._sctp = sctp;
  4753. }
  4754. return origSetRemoteDescription.apply(this, arguments);
  4755. };
  4756. }
  4757. function shimSendThrowTypeError(window) {
  4758. if (!(window.RTCPeerConnection &&
  4759. 'createDataChannel' in window.RTCPeerConnection.prototype)) {
  4760. return;
  4761. }
  4762. // Note: Although Firefox >= 57 has a native implementation, the maximum
  4763. // message size can be reset for all data channels at a later stage.
  4764. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  4765. function wrapDcSend(dc, pc) {
  4766. const origDataChannelSend = dc.send;
  4767. dc.send = function send() {
  4768. const data = arguments[0];
  4769. const length = data.length || data.size || data.byteLength;
  4770. if (dc.readyState === 'open' &&
  4771. pc.sctp && length > pc.sctp.maxMessageSize) {
  4772. throw new TypeError('Message too large (can send a maximum of ' +
  4773. pc.sctp.maxMessageSize + ' bytes)');
  4774. }
  4775. return origDataChannelSend.apply(dc, arguments);
  4776. };
  4777. }
  4778. const origCreateDataChannel =
  4779. window.RTCPeerConnection.prototype.createDataChannel;
  4780. window.RTCPeerConnection.prototype.createDataChannel =
  4781. function createDataChannel() {
  4782. const dataChannel = origCreateDataChannel.apply(this, arguments);
  4783. wrapDcSend(dataChannel, this);
  4784. return dataChannel;
  4785. };
  4786. wrapPeerConnectionEvent(window, 'datachannel', e => {
  4787. wrapDcSend(e.channel, e.target);
  4788. return e;
  4789. });
  4790. }
  4791. /* shims RTCConnectionState by pretending it is the same as iceConnectionState.
  4792. * See https://bugs.chromium.org/p/webrtc/issues/detail?id=6145#c12
  4793. * for why this is a valid hack in Chrome. In Firefox it is slightly incorrect
  4794. * since DTLS failures would be hidden. See
  4795. * https://bugzilla.mozilla.org/show_bug.cgi?id=1265827
  4796. * for the Firefox tracking bug.
  4797. */
  4798. function shimConnectionState(window) {
  4799. if (!window.RTCPeerConnection ||
  4800. 'connectionState' in window.RTCPeerConnection.prototype) {
  4801. return;
  4802. }
  4803. const proto = window.RTCPeerConnection.prototype;
  4804. Object.defineProperty(proto, 'connectionState', {
  4805. get() {
  4806. return {
  4807. completed: 'connected',
  4808. checking: 'connecting'
  4809. }[this.iceConnectionState] || this.iceConnectionState;
  4810. },
  4811. enumerable: true,
  4812. configurable: true
  4813. });
  4814. Object.defineProperty(proto, 'onconnectionstatechange', {
  4815. get() {
  4816. return this._onconnectionstatechange || null;
  4817. },
  4818. set(cb) {
  4819. if (this._onconnectionstatechange) {
  4820. this.removeEventListener('connectionstatechange',
  4821. this._onconnectionstatechange);
  4822. delete this._onconnectionstatechange;
  4823. }
  4824. if (cb) {
  4825. this.addEventListener('connectionstatechange',
  4826. this._onconnectionstatechange = cb);
  4827. }
  4828. },
  4829. enumerable: true,
  4830. configurable: true
  4831. });
  4832. ['setLocalDescription', 'setRemoteDescription'].forEach((method) => {
  4833. const origMethod = proto[method];
  4834. proto[method] = function() {
  4835. if (!this._connectionstatechangepoly) {
  4836. this._connectionstatechangepoly = e => {
  4837. const pc = e.target;
  4838. if (pc._lastConnectionState !== pc.connectionState) {
  4839. pc._lastConnectionState = pc.connectionState;
  4840. const newEvent = new Event('connectionstatechange', e);
  4841. pc.dispatchEvent(newEvent);
  4842. }
  4843. return e;
  4844. };
  4845. this.addEventListener('iceconnectionstatechange',
  4846. this._connectionstatechangepoly);
  4847. }
  4848. return origMethod.apply(this, arguments);
  4849. };
  4850. });
  4851. }
  4852. function removeExtmapAllowMixed(window, browserDetails) {
  4853. /* remove a=extmap-allow-mixed for webrtc.org < M71 */
  4854. if (!window.RTCPeerConnection) {
  4855. return;
  4856. }
  4857. if (browserDetails.browser === 'chrome' && browserDetails.version >= 71) {
  4858. return;
  4859. }
  4860. if (browserDetails.browser === 'safari' && browserDetails.version >= 605) {
  4861. return;
  4862. }
  4863. const nativeSRD = window.RTCPeerConnection.prototype.setRemoteDescription;
  4864. window.RTCPeerConnection.prototype.setRemoteDescription =
  4865. function setRemoteDescription(desc) {
  4866. if (desc && desc.sdp && desc.sdp.indexOf('\na=extmap-allow-mixed') !== -1) {
  4867. const sdp = desc.sdp.split('\n').filter((line) => {
  4868. return line.trim() !== 'a=extmap-allow-mixed';
  4869. }).join('\n');
  4870. // Safari enforces read-only-ness of RTCSessionDescription fields.
  4871. if (window.RTCSessionDescription &&
  4872. desc instanceof window.RTCSessionDescription) {
  4873. arguments[0] = new window.RTCSessionDescription({
  4874. type: desc.type,
  4875. sdp,
  4876. });
  4877. } else {
  4878. desc.sdp = sdp;
  4879. }
  4880. }
  4881. return nativeSRD.apply(this, arguments);
  4882. };
  4883. }
  4884. function shimAddIceCandidateNullOrEmpty(window, browserDetails) {
  4885. // Support for addIceCandidate(null or undefined)
  4886. // as well as addIceCandidate({candidate: "", ...})
  4887. // https://bugs.chromium.org/p/chromium/issues/detail?id=978582
  4888. // Note: must be called before other polyfills which change the signature.
  4889. if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {
  4890. return;
  4891. }
  4892. const nativeAddIceCandidate =
  4893. window.RTCPeerConnection.prototype.addIceCandidate;
  4894. if (!nativeAddIceCandidate || nativeAddIceCandidate.length === 0) {
  4895. return;
  4896. }
  4897. window.RTCPeerConnection.prototype.addIceCandidate =
  4898. function addIceCandidate() {
  4899. if (!arguments[0]) {
  4900. if (arguments[1]) {
  4901. arguments[1].apply(null);
  4902. }
  4903. return Promise.resolve();
  4904. }
  4905. // Firefox 68+ emits and processes {candidate: "", ...}, ignore
  4906. // in older versions.
  4907. // Native support for ignoring exists for Chrome M77+.
  4908. // Safari ignores as well, exact version unknown but works in the same
  4909. // version that also ignores addIceCandidate(null).
  4910. if (((browserDetails.browser === 'chrome' && browserDetails.version < 78)
  4911. || (browserDetails.browser === 'firefox'
  4912. && browserDetails.version < 68)
  4913. || (browserDetails.browser === 'safari'))
  4914. && arguments[0] && arguments[0].candidate === '') {
  4915. return Promise.resolve();
  4916. }
  4917. return nativeAddIceCandidate.apply(this, arguments);
  4918. };
  4919. }
  4920. var commonShim = /*#__PURE__*/Object.freeze({
  4921. __proto__: null,
  4922. shimRTCIceCandidate: shimRTCIceCandidate,
  4923. shimMaxMessageSize: shimMaxMessageSize,
  4924. shimSendThrowTypeError: shimSendThrowTypeError,
  4925. shimConnectionState: shimConnectionState,
  4926. removeExtmapAllowMixed: removeExtmapAllowMixed,
  4927. shimAddIceCandidateNullOrEmpty: shimAddIceCandidateNullOrEmpty
  4928. });
  4929. /*
  4930. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4931. *
  4932. * Use of this source code is governed by a BSD-style license
  4933. * that can be found in the LICENSE file in the root of the source
  4934. * tree.
  4935. */
  4936. // Shimming starts here.
  4937. function adapterFactory({window} = {}, options = {
  4938. shimChrome: true,
  4939. shimFirefox: true,
  4940. shimEdge: true,
  4941. shimSafari: true,
  4942. }) {
  4943. // Utils.
  4944. const logging = log$1;
  4945. const browserDetails = detectBrowser(window);
  4946. const adapter = {
  4947. browserDetails,
  4948. commonShim,
  4949. extractVersion: extractVersion,
  4950. disableLog: disableLog,
  4951. disableWarnings: disableWarnings
  4952. };
  4953. // Shim browser if found.
  4954. switch (browserDetails.browser) {
  4955. case 'chrome':
  4956. if (!chromeShim || !shimPeerConnection$2 ||
  4957. !options.shimChrome) {
  4958. logging('Chrome shim is not included in this adapter release.');
  4959. return adapter;
  4960. }
  4961. if (browserDetails.version === null) {
  4962. logging('Chrome shim can not determine version, not shimming.');
  4963. return adapter;
  4964. }
  4965. logging('adapter.js shimming chrome.');
  4966. // Export to the adapter global object visible in the browser.
  4967. adapter.browserShim = chromeShim;
  4968. // Must be called before shimPeerConnection.
  4969. shimAddIceCandidateNullOrEmpty(window, browserDetails);
  4970. shimGetUserMedia$3(window, browserDetails);
  4971. shimMediaStream(window);
  4972. shimPeerConnection$2(window, browserDetails);
  4973. shimOnTrack$1(window);
  4974. shimAddTrackRemoveTrack(window, browserDetails);
  4975. shimGetSendersWithDtmf(window);
  4976. shimGetStats(window);
  4977. shimSenderReceiverGetStats(window);
  4978. fixNegotiationNeeded(window, browserDetails);
  4979. shimRTCIceCandidate(window);
  4980. shimConnectionState(window);
  4981. shimMaxMessageSize(window, browserDetails);
  4982. shimSendThrowTypeError(window);
  4983. removeExtmapAllowMixed(window, browserDetails);
  4984. break;
  4985. case 'firefox':
  4986. if (!firefoxShim || !shimPeerConnection ||
  4987. !options.shimFirefox) {
  4988. logging('Firefox shim is not included in this adapter release.');
  4989. return adapter;
  4990. }
  4991. logging('adapter.js shimming firefox.');
  4992. // Export to the adapter global object visible in the browser.
  4993. adapter.browserShim = firefoxShim;
  4994. // Must be called before shimPeerConnection.
  4995. shimAddIceCandidateNullOrEmpty(window, browserDetails);
  4996. shimGetUserMedia$1(window, browserDetails);
  4997. shimPeerConnection(window, browserDetails);
  4998. shimOnTrack(window);
  4999. shimRemoveStream(window);
  5000. shimSenderGetStats(window);
  5001. shimReceiverGetStats(window);
  5002. shimRTCDataChannel(window);
  5003. shimAddTransceiver(window);
  5004. shimGetParameters(window);
  5005. shimCreateOffer(window);
  5006. shimCreateAnswer(window);
  5007. shimRTCIceCandidate(window);
  5008. shimConnectionState(window);
  5009. shimMaxMessageSize(window, browserDetails);
  5010. shimSendThrowTypeError(window);
  5011. break;
  5012. case 'edge':
  5013. if (!edgeShim || !shimPeerConnection$1 || !options.shimEdge) {
  5014. logging('MS edge shim is not included in this adapter release.');
  5015. return adapter;
  5016. }
  5017. logging('adapter.js shimming edge.');
  5018. // Export to the adapter global object visible in the browser.
  5019. adapter.browserShim = edgeShim;
  5020. shimGetUserMedia$2(window);
  5021. shimGetDisplayMedia$1(window);
  5022. shimPeerConnection$1(window, browserDetails);
  5023. shimReplaceTrack(window);
  5024. // the edge shim implements the full RTCIceCandidate object.
  5025. shimMaxMessageSize(window, browserDetails);
  5026. shimSendThrowTypeError(window);
  5027. break;
  5028. case 'safari':
  5029. if (!safariShim || !options.shimSafari) {
  5030. logging('Safari shim is not included in this adapter release.');
  5031. return adapter;
  5032. }
  5033. logging('adapter.js shimming safari.');
  5034. // Export to the adapter global object visible in the browser.
  5035. adapter.browserShim = safariShim;
  5036. // Must be called before shimCallbackAPI.
  5037. shimAddIceCandidateNullOrEmpty(window, browserDetails);
  5038. shimRTCIceServerUrls(window);
  5039. shimCreateOfferLegacy(window);
  5040. shimCallbacksAPI(window);
  5041. shimLocalStreamsAPI(window);
  5042. shimRemoteStreamsAPI(window);
  5043. shimTrackEventTransceiver(window);
  5044. shimGetUserMedia(window);
  5045. shimAudioContext(window);
  5046. shimRTCIceCandidate(window);
  5047. shimMaxMessageSize(window, browserDetails);
  5048. shimSendThrowTypeError(window);
  5049. removeExtmapAllowMixed(window, browserDetails);
  5050. break;
  5051. default:
  5052. logging('Unsupported browser!');
  5053. break;
  5054. }
  5055. return adapter;
  5056. }
  5057. /*
  5058. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  5059. *
  5060. * Use of this source code is governed by a BSD-style license
  5061. * that can be found in the LICENSE file in the root of the source
  5062. * tree.
  5063. */
  5064. adapterFactory({window: typeof window === 'undefined' ? undefined : window});
  5065. /**
  5066. * @class AudioTrackConstraints
  5067. * @classDesc Constraints for creating an audio MediaStreamTrack.
  5068. * @memberof Owt.Base
  5069. * @constructor
  5070. * @param {Owt.Base.AudioSourceInfo} source Source info of this audio track.
  5071. */
  5072. class AudioTrackConstraints {
  5073. // eslint-disable-next-line require-jsdoc
  5074. constructor(source) {
  5075. if (!Object.values(AudioSourceInfo).some(v => v === source)) {
  5076. throw new TypeError('Invalid source.');
  5077. }
  5078. /**
  5079. * @member {string} source
  5080. * @memberof Owt.Base.AudioTrackConstraints
  5081. * @desc Values could be "mic", "screen-cast", "file" or "mixed".
  5082. * @instance
  5083. */
  5084. this.source = source;
  5085. /**
  5086. * @member {string} deviceId
  5087. * @memberof Owt.Base.AudioTrackConstraints
  5088. * @desc Do not provide deviceId if source is not "mic".
  5089. * @instance
  5090. * @see https://w3c.github.io/mediacapture-main/#def-constraint-deviceId
  5091. */
  5092. this.deviceId = undefined;
  5093. }
  5094. }
  5095. /**
  5096. * @class VideoTrackConstraints
  5097. * @classDesc Constraints for creating a video MediaStreamTrack.
  5098. * @memberof Owt.Base
  5099. * @constructor
  5100. * @param {Owt.Base.VideoSourceInfo} source Source info of this video track.
  5101. */
  5102. class VideoTrackConstraints {
  5103. // eslint-disable-next-line require-jsdoc
  5104. constructor(source) {
  5105. if (!Object.values(VideoSourceInfo).some(v => v === source)) {
  5106. throw new TypeError('Invalid source.');
  5107. }
  5108. /**
  5109. * @member {string} source
  5110. * @memberof Owt.Base.VideoTrackConstraints
  5111. * @desc Values could be "camera", "screen-cast", "file" or "mixed".
  5112. * @instance
  5113. */
  5114. this.source = source;
  5115. /**
  5116. * @member {string} deviceId
  5117. * @memberof Owt.Base.VideoTrackConstraints
  5118. * @desc Do not provide deviceId if source is not "camera".
  5119. * @instance
  5120. * @see https://w3c.github.io/mediacapture-main/#def-constraint-deviceId
  5121. */
  5122. this.deviceId = undefined;
  5123. /**
  5124. * @member {Owt.Base.Resolution} resolution
  5125. * @memberof Owt.Base.VideoTrackConstraints
  5126. * @instance
  5127. */
  5128. this.resolution = undefined;
  5129. /**
  5130. * @member {number} frameRate
  5131. * @memberof Owt.Base.VideoTrackConstraints
  5132. * @instance
  5133. */
  5134. this.frameRate = undefined;
  5135. }
  5136. }
  5137. /**
  5138. * @class StreamConstraints
  5139. * @classDesc Constraints for creating a MediaStream from screen mic and camera.
  5140. * @memberof Owt.Base
  5141. * @constructor
  5142. * @param {?Owt.Base.AudioTrackConstraints} audioConstraints
  5143. * @param {?Owt.Base.VideoTrackConstraints} videoConstraints
  5144. */
  5145. class StreamConstraints {
  5146. // eslint-disable-next-line require-jsdoc
  5147. constructor(audioConstraints = false, videoConstraints = false) {
  5148. /**
  5149. * @member {Owt.Base.MediaStreamTrackDeviceConstraintsForAudio} audio
  5150. * @memberof Owt.Base.MediaStreamDeviceConstraints
  5151. * @instance
  5152. */
  5153. this.audio = audioConstraints;
  5154. /**
  5155. * @member {Owt.Base.MediaStreamTrackDeviceConstraintsForVideo} Video
  5156. * @memberof Owt.Base.MediaStreamDeviceConstraints
  5157. * @instance
  5158. */
  5159. this.video = videoConstraints;
  5160. }
  5161. }
  5162. // eslint-disable-next-line require-jsdoc
  5163. function isVideoConstrainsForScreenCast(constraints) {
  5164. return typeof constraints.video === 'object' && constraints.video.source === VideoSourceInfo.SCREENCAST;
  5165. }
  5166. /**
  5167. * @class MediaStreamFactory
  5168. * @classDesc A factory to create MediaStream. You can also create MediaStream by yourself.
  5169. * @memberof Owt.Base
  5170. */
  5171. class MediaStreamFactory {
  5172. /**
  5173. * @function createMediaStream
  5174. * @static
  5175. * @desc Create a MediaStream with given constraints. If you want to create a MediaStream for screen cast, please make sure both audio and video's source are "screen-cast".
  5176. * @memberof Owt.Base.MediaStreamFactory
  5177. * @return {Promise<MediaStream, Error>} Return a promise that is resolved when stream is successfully created, or rejected if one of the following error happened:
  5178. * - One or more parameters cannot be satisfied.
  5179. * - Specified device is busy.
  5180. * - Cannot obtain necessary permission or operation is canceled by user.
  5181. * - Video source is screen cast, while audio source is not.
  5182. * - Audio source is screen cast, while video source is disabled.
  5183. * @param {Owt.Base.StreamConstraints} constraints
  5184. */
  5185. static createMediaStream(constraints) {
  5186. if (typeof constraints !== 'object' || !constraints.audio && !constraints.video) {
  5187. return Promise.reject(new TypeError('Invalid constrains'));
  5188. }
  5189. if (!isVideoConstrainsForScreenCast(constraints) && typeof constraints.audio === 'object' && constraints.audio.source === AudioSourceInfo.SCREENCAST) {
  5190. return Promise.reject(new TypeError('Cannot share screen without video.'));
  5191. }
  5192. if (isVideoConstrainsForScreenCast(constraints) && !isChrome() && !isFirefox()) {
  5193. return Promise.reject(new TypeError('Screen sharing only supports Chrome and Firefox.'));
  5194. }
  5195. if (isVideoConstrainsForScreenCast(constraints) && typeof constraints.audio === 'object' && constraints.audio.source !== AudioSourceInfo.SCREENCAST) {
  5196. return Promise.reject(new TypeError('Cannot capture video from screen cast while capture audio from' + ' other source.'));
  5197. }
  5198. // Check and convert constraints.
  5199. if (!constraints.audio && !constraints.video) {
  5200. return Promise.reject(new TypeError('At least one of audio and video must be requested.'));
  5201. }
  5202. const mediaConstraints = Object.create({});
  5203. if (typeof constraints.audio === 'object' && constraints.audio.source === AudioSourceInfo.MIC) {
  5204. mediaConstraints.audio = Object.create({});
  5205. if (isEdge()) {
  5206. mediaConstraints.audio.deviceId = constraints.audio.deviceId;
  5207. } else {
  5208. mediaConstraints.audio.deviceId = {
  5209. exact: constraints.audio.deviceId
  5210. };
  5211. }
  5212. } else {
  5213. if (constraints.audio.source === AudioSourceInfo.SCREENCAST) {
  5214. mediaConstraints.audio = true;
  5215. } else {
  5216. mediaConstraints.audio = constraints.audio;
  5217. }
  5218. }
  5219. if (typeof constraints.video === 'object') {
  5220. mediaConstraints.video = Object.create({});
  5221. if (typeof constraints.video.frameRate === 'number') {
  5222. mediaConstraints.video.frameRate = constraints.video.frameRate;
  5223. }
  5224. if (constraints.video.resolution && constraints.video.resolution.width && constraints.video.resolution.height) {
  5225. if (constraints.video.source === VideoSourceInfo.SCREENCAST) {
  5226. mediaConstraints.video.width = constraints.video.resolution.width;
  5227. mediaConstraints.video.height = constraints.video.resolution.height;
  5228. } else {
  5229. mediaConstraints.video.width = Object.create({});
  5230. mediaConstraints.video.width.exact = constraints.video.resolution.width;
  5231. mediaConstraints.video.height = Object.create({});
  5232. mediaConstraints.video.height.exact = constraints.video.resolution.height;
  5233. }
  5234. }
  5235. if (typeof constraints.video.deviceId === 'string') {
  5236. mediaConstraints.video.deviceId = {
  5237. exact: constraints.video.deviceId
  5238. };
  5239. }
  5240. if (isFirefox() && constraints.video.source === VideoSourceInfo.SCREENCAST) {
  5241. mediaConstraints.video.mediaSource = 'screen';
  5242. }
  5243. } else {
  5244. mediaConstraints.video = constraints.video;
  5245. }
  5246. if (isVideoConstrainsForScreenCast(constraints)) {
  5247. return navigator.mediaDevices.getDisplayMedia(mediaConstraints);
  5248. } else {
  5249. return navigator.mediaDevices.getUserMedia(mediaConstraints);
  5250. }
  5251. }
  5252. }
  5253. // Copyright (C) <2018> Intel Corporation
  5254. var media = /*#__PURE__*/Object.freeze({
  5255. __proto__: null,
  5256. AudioTrackConstraints: AudioTrackConstraints,
  5257. VideoTrackConstraints: VideoTrackConstraints,
  5258. StreamConstraints: StreamConstraints,
  5259. MediaStreamFactory: MediaStreamFactory,
  5260. AudioSourceInfo: AudioSourceInfo,
  5261. VideoSourceInfo: VideoSourceInfo,
  5262. TrackKind: TrackKind,
  5263. Resolution: Resolution
  5264. });
  5265. let logger;
  5266. let errorLogger;
  5267. function setLogger() {
  5268. /*eslint-disable */
  5269. logger = console.log;
  5270. errorLogger = console.error;
  5271. /*eslint-enable */
  5272. }
  5273. function log(message, ...optionalParams) {
  5274. if (logger) {
  5275. logger(message, ...optionalParams);
  5276. }
  5277. }
  5278. function error(message, ...optionalParams) {
  5279. if (errorLogger) {
  5280. errorLogger(message, ...optionalParams);
  5281. }
  5282. }
  5283. class Event$1 {
  5284. constructor(type) {
  5285. this.listener = {};
  5286. this.type = type | '';
  5287. }
  5288. on(event, fn) {
  5289. if (!this.listener[event]) {
  5290. this.listener[event] = [];
  5291. }
  5292. this.listener[event].push(fn);
  5293. return true;
  5294. }
  5295. off(event, fn) {
  5296. if (this.listener[event]) {
  5297. var index = this.listener[event].indexOf(fn);
  5298. if (index > -1) {
  5299. this.listener[event].splice(index, 1);
  5300. }
  5301. return true;
  5302. }
  5303. return false;
  5304. }
  5305. offAll() {
  5306. this.listener = {};
  5307. }
  5308. dispatch(event, data) {
  5309. if (this.listener[event]) {
  5310. this.listener[event].map(each => {
  5311. each.apply(null, [data]);
  5312. });
  5313. return true;
  5314. }
  5315. return false;
  5316. }
  5317. }
  5318. var bind = function bind(fn, thisArg) {
  5319. return function wrap() {
  5320. var args = new Array(arguments.length);
  5321. for (var i = 0; i < args.length; i++) {
  5322. args[i] = arguments[i];
  5323. }
  5324. return fn.apply(thisArg, args);
  5325. };
  5326. };
  5327. // utils is a library of generic helper functions non-specific to axios
  5328. var toString = Object.prototype.toString;
  5329. // eslint-disable-next-line func-names
  5330. var kindOf = (function(cache) {
  5331. // eslint-disable-next-line func-names
  5332. return function(thing) {
  5333. var str = toString.call(thing);
  5334. return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
  5335. };
  5336. })(Object.create(null));
  5337. function kindOfTest(type) {
  5338. type = type.toLowerCase();
  5339. return function isKindOf(thing) {
  5340. return kindOf(thing) === type;
  5341. };
  5342. }
  5343. /**
  5344. * Determine if a value is an Array
  5345. *
  5346. * @param {Object} val The value to test
  5347. * @returns {boolean} True if value is an Array, otherwise false
  5348. */
  5349. function isArray(val) {
  5350. return Array.isArray(val);
  5351. }
  5352. /**
  5353. * Determine if a value is undefined
  5354. *
  5355. * @param {Object} val The value to test
  5356. * @returns {boolean} True if the value is undefined, otherwise false
  5357. */
  5358. function isUndefined(val) {
  5359. return typeof val === 'undefined';
  5360. }
  5361. /**
  5362. * Determine if a value is a Buffer
  5363. *
  5364. * @param {Object} val The value to test
  5365. * @returns {boolean} True if value is a Buffer, otherwise false
  5366. */
  5367. function isBuffer(val) {
  5368. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
  5369. && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
  5370. }
  5371. /**
  5372. * Determine if a value is an ArrayBuffer
  5373. *
  5374. * @function
  5375. * @param {Object} val The value to test
  5376. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  5377. */
  5378. var isArrayBuffer = kindOfTest('ArrayBuffer');
  5379. /**
  5380. * Determine if a value is a view on an ArrayBuffer
  5381. *
  5382. * @param {Object} val The value to test
  5383. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  5384. */
  5385. function isArrayBufferView(val) {
  5386. var result;
  5387. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  5388. result = ArrayBuffer.isView(val);
  5389. } else {
  5390. result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
  5391. }
  5392. return result;
  5393. }
  5394. /**
  5395. * Determine if a value is a String
  5396. *
  5397. * @param {Object} val The value to test
  5398. * @returns {boolean} True if value is a String, otherwise false
  5399. */
  5400. function isString(val) {
  5401. return typeof val === 'string';
  5402. }
  5403. /**
  5404. * Determine if a value is a Number
  5405. *
  5406. * @param {Object} val The value to test
  5407. * @returns {boolean} True if value is a Number, otherwise false
  5408. */
  5409. function isNumber(val) {
  5410. return typeof val === 'number';
  5411. }
  5412. /**
  5413. * Determine if a value is an Object
  5414. *
  5415. * @param {Object} val The value to test
  5416. * @returns {boolean} True if value is an Object, otherwise false
  5417. */
  5418. function isObject(val) {
  5419. return val !== null && typeof val === 'object';
  5420. }
  5421. /**
  5422. * Determine if a value is a plain Object
  5423. *
  5424. * @param {Object} val The value to test
  5425. * @return {boolean} True if value is a plain Object, otherwise false
  5426. */
  5427. function isPlainObject(val) {
  5428. if (kindOf(val) !== 'object') {
  5429. return false;
  5430. }
  5431. var prototype = Object.getPrototypeOf(val);
  5432. return prototype === null || prototype === Object.prototype;
  5433. }
  5434. /**
  5435. * Determine if a value is a Date
  5436. *
  5437. * @function
  5438. * @param {Object} val The value to test
  5439. * @returns {boolean} True if value is a Date, otherwise false
  5440. */
  5441. var isDate = kindOfTest('Date');
  5442. /**
  5443. * Determine if a value is a File
  5444. *
  5445. * @function
  5446. * @param {Object} val The value to test
  5447. * @returns {boolean} True if value is a File, otherwise false
  5448. */
  5449. var isFile = kindOfTest('File');
  5450. /**
  5451. * Determine if a value is a Blob
  5452. *
  5453. * @function
  5454. * @param {Object} val The value to test
  5455. * @returns {boolean} True if value is a Blob, otherwise false
  5456. */
  5457. var isBlob = kindOfTest('Blob');
  5458. /**
  5459. * Determine if a value is a FileList
  5460. *
  5461. * @function
  5462. * @param {Object} val The value to test
  5463. * @returns {boolean} True if value is a File, otherwise false
  5464. */
  5465. var isFileList = kindOfTest('FileList');
  5466. /**
  5467. * Determine if a value is a Function
  5468. *
  5469. * @param {Object} val The value to test
  5470. * @returns {boolean} True if value is a Function, otherwise false
  5471. */
  5472. function isFunction(val) {
  5473. return toString.call(val) === '[object Function]';
  5474. }
  5475. /**
  5476. * Determine if a value is a Stream
  5477. *
  5478. * @param {Object} val The value to test
  5479. * @returns {boolean} True if value is a Stream, otherwise false
  5480. */
  5481. function isStream(val) {
  5482. return isObject(val) && isFunction(val.pipe);
  5483. }
  5484. /**
  5485. * Determine if a value is a FormData
  5486. *
  5487. * @param {Object} thing The value to test
  5488. * @returns {boolean} True if value is an FormData, otherwise false
  5489. */
  5490. function isFormData(thing) {
  5491. var pattern = '[object FormData]';
  5492. return thing && (
  5493. (typeof FormData === 'function' && thing instanceof FormData) ||
  5494. toString.call(thing) === pattern ||
  5495. (isFunction(thing.toString) && thing.toString() === pattern)
  5496. );
  5497. }
  5498. /**
  5499. * Determine if a value is a URLSearchParams object
  5500. * @function
  5501. * @param {Object} val The value to test
  5502. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  5503. */
  5504. var isURLSearchParams = kindOfTest('URLSearchParams');
  5505. /**
  5506. * Trim excess whitespace off the beginning and end of a string
  5507. *
  5508. * @param {String} str The String to trim
  5509. * @returns {String} The String freed of excess whitespace
  5510. */
  5511. function trim(str) {
  5512. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  5513. }
  5514. /**
  5515. * Determine if we're running in a standard browser environment
  5516. *
  5517. * This allows axios to run in a web worker, and react-native.
  5518. * Both environments support XMLHttpRequest, but not fully standard globals.
  5519. *
  5520. * web workers:
  5521. * typeof window -> undefined
  5522. * typeof document -> undefined
  5523. *
  5524. * react-native:
  5525. * navigator.product -> 'ReactNative'
  5526. * nativescript
  5527. * navigator.product -> 'NativeScript' or 'NS'
  5528. */
  5529. function isStandardBrowserEnv() {
  5530. if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
  5531. navigator.product === 'NativeScript' ||
  5532. navigator.product === 'NS')) {
  5533. return false;
  5534. }
  5535. return (
  5536. typeof window !== 'undefined' &&
  5537. typeof document !== 'undefined'
  5538. );
  5539. }
  5540. /**
  5541. * Iterate over an Array or an Object invoking a function for each item.
  5542. *
  5543. * If `obj` is an Array callback will be called passing
  5544. * the value, index, and complete array for each item.
  5545. *
  5546. * If 'obj' is an Object callback will be called passing
  5547. * the value, key, and complete object for each property.
  5548. *
  5549. * @param {Object|Array} obj The object to iterate
  5550. * @param {Function} fn The callback to invoke for each item
  5551. */
  5552. function forEach(obj, fn) {
  5553. // Don't bother if no value provided
  5554. if (obj === null || typeof obj === 'undefined') {
  5555. return;
  5556. }
  5557. // Force an array if not already something iterable
  5558. if (typeof obj !== 'object') {
  5559. /*eslint no-param-reassign:0*/
  5560. obj = [obj];
  5561. }
  5562. if (isArray(obj)) {
  5563. // Iterate over array values
  5564. for (var i = 0, l = obj.length; i < l; i++) {
  5565. fn.call(null, obj[i], i, obj);
  5566. }
  5567. } else {
  5568. // Iterate over object keys
  5569. for (var key in obj) {
  5570. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  5571. fn.call(null, obj[key], key, obj);
  5572. }
  5573. }
  5574. }
  5575. }
  5576. /**
  5577. * Accepts varargs expecting each argument to be an object, then
  5578. * immutably merges the properties of each object and returns result.
  5579. *
  5580. * When multiple objects contain the same key the later object in
  5581. * the arguments list will take precedence.
  5582. *
  5583. * Example:
  5584. *
  5585. * ```js
  5586. * var result = merge({foo: 123}, {foo: 456});
  5587. * console.log(result.foo); // outputs 456
  5588. * ```
  5589. *
  5590. * @param {Object} obj1 Object to merge
  5591. * @returns {Object} Result of all merge properties
  5592. */
  5593. function merge(/* obj1, obj2, obj3, ... */) {
  5594. var result = {};
  5595. function assignValue(val, key) {
  5596. if (isPlainObject(result[key]) && isPlainObject(val)) {
  5597. result[key] = merge(result[key], val);
  5598. } else if (isPlainObject(val)) {
  5599. result[key] = merge({}, val);
  5600. } else if (isArray(val)) {
  5601. result[key] = val.slice();
  5602. } else {
  5603. result[key] = val;
  5604. }
  5605. }
  5606. for (var i = 0, l = arguments.length; i < l; i++) {
  5607. forEach(arguments[i], assignValue);
  5608. }
  5609. return result;
  5610. }
  5611. /**
  5612. * Extends object a by mutably adding to it the properties of object b.
  5613. *
  5614. * @param {Object} a The object to be extended
  5615. * @param {Object} b The object to copy properties from
  5616. * @param {Object} thisArg The object to bind function to
  5617. * @return {Object} The resulting value of object a
  5618. */
  5619. function extend(a, b, thisArg) {
  5620. forEach(b, function assignValue(val, key) {
  5621. if (thisArg && typeof val === 'function') {
  5622. a[key] = bind(val, thisArg);
  5623. } else {
  5624. a[key] = val;
  5625. }
  5626. });
  5627. return a;
  5628. }
  5629. /**
  5630. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  5631. *
  5632. * @param {string} content with BOM
  5633. * @return {string} content value without BOM
  5634. */
  5635. function stripBOM(content) {
  5636. if (content.charCodeAt(0) === 0xFEFF) {
  5637. content = content.slice(1);
  5638. }
  5639. return content;
  5640. }
  5641. /**
  5642. * Inherit the prototype methods from one constructor into another
  5643. * @param {function} constructor
  5644. * @param {function} superConstructor
  5645. * @param {object} [props]
  5646. * @param {object} [descriptors]
  5647. */
  5648. function inherits(constructor, superConstructor, props, descriptors) {
  5649. constructor.prototype = Object.create(superConstructor.prototype, descriptors);
  5650. constructor.prototype.constructor = constructor;
  5651. props && Object.assign(constructor.prototype, props);
  5652. }
  5653. /**
  5654. * Resolve object with deep prototype chain to a flat object
  5655. * @param {Object} sourceObj source object
  5656. * @param {Object} [destObj]
  5657. * @param {Function} [filter]
  5658. * @returns {Object}
  5659. */
  5660. function toFlatObject(sourceObj, destObj, filter) {
  5661. var props;
  5662. var i;
  5663. var prop;
  5664. var merged = {};
  5665. destObj = destObj || {};
  5666. do {
  5667. props = Object.getOwnPropertyNames(sourceObj);
  5668. i = props.length;
  5669. while (i-- > 0) {
  5670. prop = props[i];
  5671. if (!merged[prop]) {
  5672. destObj[prop] = sourceObj[prop];
  5673. merged[prop] = true;
  5674. }
  5675. }
  5676. sourceObj = Object.getPrototypeOf(sourceObj);
  5677. } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
  5678. return destObj;
  5679. }
  5680. /*
  5681. * determines whether a string ends with the characters of a specified string
  5682. * @param {String} str
  5683. * @param {String} searchString
  5684. * @param {Number} [position= 0]
  5685. * @returns {boolean}
  5686. */
  5687. function endsWith(str, searchString, position) {
  5688. str = String(str);
  5689. if (position === undefined || position > str.length) {
  5690. position = str.length;
  5691. }
  5692. position -= searchString.length;
  5693. var lastIndex = str.indexOf(searchString, position);
  5694. return lastIndex !== -1 && lastIndex === position;
  5695. }
  5696. /**
  5697. * Returns new array from array like object
  5698. * @param {*} [thing]
  5699. * @returns {Array}
  5700. */
  5701. function toArray(thing) {
  5702. if (!thing) return null;
  5703. var i = thing.length;
  5704. if (isUndefined(i)) return null;
  5705. var arr = new Array(i);
  5706. while (i-- > 0) {
  5707. arr[i] = thing[i];
  5708. }
  5709. return arr;
  5710. }
  5711. // eslint-disable-next-line func-names
  5712. var isTypedArray = (function(TypedArray) {
  5713. // eslint-disable-next-line func-names
  5714. return function(thing) {
  5715. return TypedArray && thing instanceof TypedArray;
  5716. };
  5717. })(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
  5718. var utils = {
  5719. isArray: isArray,
  5720. isArrayBuffer: isArrayBuffer,
  5721. isBuffer: isBuffer,
  5722. isFormData: isFormData,
  5723. isArrayBufferView: isArrayBufferView,
  5724. isString: isString,
  5725. isNumber: isNumber,
  5726. isObject: isObject,
  5727. isPlainObject: isPlainObject,
  5728. isUndefined: isUndefined,
  5729. isDate: isDate,
  5730. isFile: isFile,
  5731. isBlob: isBlob,
  5732. isFunction: isFunction,
  5733. isStream: isStream,
  5734. isURLSearchParams: isURLSearchParams,
  5735. isStandardBrowserEnv: isStandardBrowserEnv,
  5736. forEach: forEach,
  5737. merge: merge,
  5738. extend: extend,
  5739. trim: trim,
  5740. stripBOM: stripBOM,
  5741. inherits: inherits,
  5742. toFlatObject: toFlatObject,
  5743. kindOf: kindOf,
  5744. kindOfTest: kindOfTest,
  5745. endsWith: endsWith,
  5746. toArray: toArray,
  5747. isTypedArray: isTypedArray,
  5748. isFileList: isFileList
  5749. };
  5750. function encode(val) {
  5751. return encodeURIComponent(val).
  5752. replace(/%3A/gi, ':').
  5753. replace(/%24/g, '$').
  5754. replace(/%2C/gi, ',').
  5755. replace(/%20/g, '+').
  5756. replace(/%5B/gi, '[').
  5757. replace(/%5D/gi, ']');
  5758. }
  5759. /**
  5760. * Build a URL by appending params to the end
  5761. *
  5762. * @param {string} url The base of the url (e.g., http://www.google.com)
  5763. * @param {object} [params] The params to be appended
  5764. * @returns {string} The formatted url
  5765. */
  5766. var buildURL = function buildURL(url, params, paramsSerializer) {
  5767. /*eslint no-param-reassign:0*/
  5768. if (!params) {
  5769. return url;
  5770. }
  5771. var serializedParams;
  5772. if (paramsSerializer) {
  5773. serializedParams = paramsSerializer(params);
  5774. } else if (utils.isURLSearchParams(params)) {
  5775. serializedParams = params.toString();
  5776. } else {
  5777. var parts = [];
  5778. utils.forEach(params, function serialize(val, key) {
  5779. if (val === null || typeof val === 'undefined') {
  5780. return;
  5781. }
  5782. if (utils.isArray(val)) {
  5783. key = key + '[]';
  5784. } else {
  5785. val = [val];
  5786. }
  5787. utils.forEach(val, function parseValue(v) {
  5788. if (utils.isDate(v)) {
  5789. v = v.toISOString();
  5790. } else if (utils.isObject(v)) {
  5791. v = JSON.stringify(v);
  5792. }
  5793. parts.push(encode(key) + '=' + encode(v));
  5794. });
  5795. });
  5796. serializedParams = parts.join('&');
  5797. }
  5798. if (serializedParams) {
  5799. var hashmarkIndex = url.indexOf('#');
  5800. if (hashmarkIndex !== -1) {
  5801. url = url.slice(0, hashmarkIndex);
  5802. }
  5803. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  5804. }
  5805. return url;
  5806. };
  5807. function InterceptorManager() {
  5808. this.handlers = [];
  5809. }
  5810. /**
  5811. * Add a new interceptor to the stack
  5812. *
  5813. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  5814. * @param {Function} rejected The function to handle `reject` for a `Promise`
  5815. *
  5816. * @return {Number} An ID used to remove interceptor later
  5817. */
  5818. InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
  5819. this.handlers.push({
  5820. fulfilled: fulfilled,
  5821. rejected: rejected,
  5822. synchronous: options ? options.synchronous : false,
  5823. runWhen: options ? options.runWhen : null
  5824. });
  5825. return this.handlers.length - 1;
  5826. };
  5827. /**
  5828. * Remove an interceptor from the stack
  5829. *
  5830. * @param {Number} id The ID that was returned by `use`
  5831. */
  5832. InterceptorManager.prototype.eject = function eject(id) {
  5833. if (this.handlers[id]) {
  5834. this.handlers[id] = null;
  5835. }
  5836. };
  5837. /**
  5838. * Iterate over all the registered interceptors
  5839. *
  5840. * This method is particularly useful for skipping over any
  5841. * interceptors that may have become `null` calling `eject`.
  5842. *
  5843. * @param {Function} fn The function to call for each interceptor
  5844. */
  5845. InterceptorManager.prototype.forEach = function forEach(fn) {
  5846. utils.forEach(this.handlers, function forEachHandler(h) {
  5847. if (h !== null) {
  5848. fn(h);
  5849. }
  5850. });
  5851. };
  5852. var InterceptorManager_1 = InterceptorManager;
  5853. var normalizeHeaderName = function normalizeHeaderName(headers, normalizedName) {
  5854. utils.forEach(headers, function processHeader(value, name) {
  5855. if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
  5856. headers[normalizedName] = value;
  5857. delete headers[name];
  5858. }
  5859. });
  5860. };
  5861. /**
  5862. * Create an Error with the specified message, config, error code, request and response.
  5863. *
  5864. * @param {string} message The error message.
  5865. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  5866. * @param {Object} [config] The config.
  5867. * @param {Object} [request] The request.
  5868. * @param {Object} [response] The response.
  5869. * @returns {Error} The created error.
  5870. */
  5871. function AxiosError(message, code, config, request, response) {
  5872. Error.call(this);
  5873. this.message = message;
  5874. this.name = 'AxiosError';
  5875. code && (this.code = code);
  5876. config && (this.config = config);
  5877. request && (this.request = request);
  5878. response && (this.response = response);
  5879. }
  5880. utils.inherits(AxiosError, Error, {
  5881. toJSON: function toJSON() {
  5882. return {
  5883. // Standard
  5884. message: this.message,
  5885. name: this.name,
  5886. // Microsoft
  5887. description: this.description,
  5888. number: this.number,
  5889. // Mozilla
  5890. fileName: this.fileName,
  5891. lineNumber: this.lineNumber,
  5892. columnNumber: this.columnNumber,
  5893. stack: this.stack,
  5894. // Axios
  5895. config: this.config,
  5896. code: this.code,
  5897. status: this.response && this.response.status ? this.response.status : null
  5898. };
  5899. }
  5900. });
  5901. var prototype = AxiosError.prototype;
  5902. var descriptors = {};
  5903. [
  5904. 'ERR_BAD_OPTION_VALUE',
  5905. 'ERR_BAD_OPTION',
  5906. 'ECONNABORTED',
  5907. 'ETIMEDOUT',
  5908. 'ERR_NETWORK',
  5909. 'ERR_FR_TOO_MANY_REDIRECTS',
  5910. 'ERR_DEPRECATED',
  5911. 'ERR_BAD_RESPONSE',
  5912. 'ERR_BAD_REQUEST',
  5913. 'ERR_CANCELED'
  5914. // eslint-disable-next-line func-names
  5915. ].forEach(function(code) {
  5916. descriptors[code] = {value: code};
  5917. });
  5918. Object.defineProperties(AxiosError, descriptors);
  5919. Object.defineProperty(prototype, 'isAxiosError', {value: true});
  5920. // eslint-disable-next-line func-names
  5921. AxiosError.from = function(error, code, config, request, response, customProps) {
  5922. var axiosError = Object.create(prototype);
  5923. utils.toFlatObject(error, axiosError, function filter(obj) {
  5924. return obj !== Error.prototype;
  5925. });
  5926. AxiosError.call(axiosError, error.message, code, config, request, response);
  5927. axiosError.name = error.name;
  5928. customProps && Object.assign(axiosError, customProps);
  5929. return axiosError;
  5930. };
  5931. var AxiosError_1 = AxiosError;
  5932. var transitional = {
  5933. silentJSONParsing: true,
  5934. forcedJSONParsing: true,
  5935. clarifyTimeoutError: false
  5936. };
  5937. /**
  5938. * Convert a data object to FormData
  5939. * @param {Object} obj
  5940. * @param {?Object} [formData]
  5941. * @returns {Object}
  5942. **/
  5943. function toFormData(obj, formData) {
  5944. // eslint-disable-next-line no-param-reassign
  5945. formData = formData || new FormData();
  5946. var stack = [];
  5947. function convertValue(value) {
  5948. if (value === null) return '';
  5949. if (utils.isDate(value)) {
  5950. return value.toISOString();
  5951. }
  5952. if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
  5953. return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
  5954. }
  5955. return value;
  5956. }
  5957. function build(data, parentKey) {
  5958. if (utils.isPlainObject(data) || utils.isArray(data)) {
  5959. if (stack.indexOf(data) !== -1) {
  5960. throw Error('Circular reference detected in ' + parentKey);
  5961. }
  5962. stack.push(data);
  5963. utils.forEach(data, function each(value, key) {
  5964. if (utils.isUndefined(value)) return;
  5965. var fullKey = parentKey ? parentKey + '.' + key : key;
  5966. var arr;
  5967. if (value && !parentKey && typeof value === 'object') {
  5968. if (utils.endsWith(key, '{}')) {
  5969. // eslint-disable-next-line no-param-reassign
  5970. value = JSON.stringify(value);
  5971. } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) {
  5972. // eslint-disable-next-line func-names
  5973. arr.forEach(function(el) {
  5974. !utils.isUndefined(el) && formData.append(fullKey, convertValue(el));
  5975. });
  5976. return;
  5977. }
  5978. }
  5979. build(value, fullKey);
  5980. });
  5981. stack.pop();
  5982. } else {
  5983. formData.append(parentKey, convertValue(data));
  5984. }
  5985. }
  5986. build(obj);
  5987. return formData;
  5988. }
  5989. var toFormData_1 = toFormData;
  5990. /**
  5991. * Resolve or reject a Promise based on response status.
  5992. *
  5993. * @param {Function} resolve A function that resolves the promise.
  5994. * @param {Function} reject A function that rejects the promise.
  5995. * @param {object} response The response.
  5996. */
  5997. var settle = function settle(resolve, reject, response) {
  5998. var validateStatus = response.config.validateStatus;
  5999. if (!response.status || !validateStatus || validateStatus(response.status)) {
  6000. resolve(response);
  6001. } else {
  6002. reject(new AxiosError_1(
  6003. 'Request failed with status code ' + response.status,
  6004. [AxiosError_1.ERR_BAD_REQUEST, AxiosError_1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
  6005. response.config,
  6006. response.request,
  6007. response
  6008. ));
  6009. }
  6010. };
  6011. var cookies = (
  6012. utils.isStandardBrowserEnv() ?
  6013. // Standard browser envs support document.cookie
  6014. (function standardBrowserEnv() {
  6015. return {
  6016. write: function write(name, value, expires, path, domain, secure) {
  6017. var cookie = [];
  6018. cookie.push(name + '=' + encodeURIComponent(value));
  6019. if (utils.isNumber(expires)) {
  6020. cookie.push('expires=' + new Date(expires).toGMTString());
  6021. }
  6022. if (utils.isString(path)) {
  6023. cookie.push('path=' + path);
  6024. }
  6025. if (utils.isString(domain)) {
  6026. cookie.push('domain=' + domain);
  6027. }
  6028. if (secure === true) {
  6029. cookie.push('secure');
  6030. }
  6031. document.cookie = cookie.join('; ');
  6032. },
  6033. read: function read(name) {
  6034. var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
  6035. return (match ? decodeURIComponent(match[3]) : null);
  6036. },
  6037. remove: function remove(name) {
  6038. this.write(name, '', Date.now() - 86400000);
  6039. }
  6040. };
  6041. })() :
  6042. // Non standard browser env (web workers, react-native) lack needed support.
  6043. (function nonStandardBrowserEnv() {
  6044. return {
  6045. write: function write() {},
  6046. read: function read() { return null; },
  6047. remove: function remove() {}
  6048. };
  6049. })()
  6050. );
  6051. /**
  6052. * Determines whether the specified URL is absolute
  6053. *
  6054. * @param {string} url The URL to test
  6055. * @returns {boolean} True if the specified URL is absolute, otherwise false
  6056. */
  6057. var isAbsoluteURL = function isAbsoluteURL(url) {
  6058. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  6059. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  6060. // by any combination of letters, digits, plus, period, or hyphen.
  6061. return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
  6062. };
  6063. /**
  6064. * Creates a new URL by combining the specified URLs
  6065. *
  6066. * @param {string} baseURL The base URL
  6067. * @param {string} relativeURL The relative URL
  6068. * @returns {string} The combined URL
  6069. */
  6070. var combineURLs = function combineURLs(baseURL, relativeURL) {
  6071. return relativeURL
  6072. ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
  6073. : baseURL;
  6074. };
  6075. /**
  6076. * Creates a new URL by combining the baseURL with the requestedURL,
  6077. * only when the requestedURL is not already an absolute URL.
  6078. * If the requestURL is absolute, this function returns the requestedURL untouched.
  6079. *
  6080. * @param {string} baseURL The base URL
  6081. * @param {string} requestedURL Absolute or relative URL to combine
  6082. * @returns {string} The combined full path
  6083. */
  6084. var buildFullPath = function buildFullPath(baseURL, requestedURL) {
  6085. if (baseURL && !isAbsoluteURL(requestedURL)) {
  6086. return combineURLs(baseURL, requestedURL);
  6087. }
  6088. return requestedURL;
  6089. };
  6090. // Headers whose duplicates are ignored by node
  6091. // c.f. https://nodejs.org/api/http.html#http_message_headers
  6092. var ignoreDuplicateOf = [
  6093. 'age', 'authorization', 'content-length', 'content-type', 'etag',
  6094. 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  6095. 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  6096. 'referer', 'retry-after', 'user-agent'
  6097. ];
  6098. /**
  6099. * Parse headers into an object
  6100. *
  6101. * ```
  6102. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  6103. * Content-Type: application/json
  6104. * Connection: keep-alive
  6105. * Transfer-Encoding: chunked
  6106. * ```
  6107. *
  6108. * @param {String} headers Headers needing to be parsed
  6109. * @returns {Object} Headers parsed into an object
  6110. */
  6111. var parseHeaders = function parseHeaders(headers) {
  6112. var parsed = {};
  6113. var key;
  6114. var val;
  6115. var i;
  6116. if (!headers) { return parsed; }
  6117. utils.forEach(headers.split('\n'), function parser(line) {
  6118. i = line.indexOf(':');
  6119. key = utils.trim(line.substr(0, i)).toLowerCase();
  6120. val = utils.trim(line.substr(i + 1));
  6121. if (key) {
  6122. if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
  6123. return;
  6124. }
  6125. if (key === 'set-cookie') {
  6126. parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
  6127. } else {
  6128. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  6129. }
  6130. }
  6131. });
  6132. return parsed;
  6133. };
  6134. var isURLSameOrigin = (
  6135. utils.isStandardBrowserEnv() ?
  6136. // Standard browser envs have full support of the APIs needed to test
  6137. // whether the request URL is of the same origin as current location.
  6138. (function standardBrowserEnv() {
  6139. var msie = /(msie|trident)/i.test(navigator.userAgent);
  6140. var urlParsingNode = document.createElement('a');
  6141. var originURL;
  6142. /**
  6143. * Parse a URL to discover it's components
  6144. *
  6145. * @param {String} url The URL to be parsed
  6146. * @returns {Object}
  6147. */
  6148. function resolveURL(url) {
  6149. var href = url;
  6150. if (msie) {
  6151. // IE needs attribute set twice to normalize properties
  6152. urlParsingNode.setAttribute('href', href);
  6153. href = urlParsingNode.href;
  6154. }
  6155. urlParsingNode.setAttribute('href', href);
  6156. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  6157. return {
  6158. href: urlParsingNode.href,
  6159. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  6160. host: urlParsingNode.host,
  6161. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  6162. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  6163. hostname: urlParsingNode.hostname,
  6164. port: urlParsingNode.port,
  6165. pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
  6166. urlParsingNode.pathname :
  6167. '/' + urlParsingNode.pathname
  6168. };
  6169. }
  6170. originURL = resolveURL(window.location.href);
  6171. /**
  6172. * Determine if a URL shares the same origin as the current location
  6173. *
  6174. * @param {String} requestURL The URL to test
  6175. * @returns {boolean} True if URL shares the same origin, otherwise false
  6176. */
  6177. return function isURLSameOrigin(requestURL) {
  6178. var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
  6179. return (parsed.protocol === originURL.protocol &&
  6180. parsed.host === originURL.host);
  6181. };
  6182. })() :
  6183. // Non standard browser envs (web workers, react-native) lack needed support.
  6184. (function nonStandardBrowserEnv() {
  6185. return function isURLSameOrigin() {
  6186. return true;
  6187. };
  6188. })()
  6189. );
  6190. /**
  6191. * A `CanceledError` is an object that is thrown when an operation is canceled.
  6192. *
  6193. * @class
  6194. * @param {string=} message The message.
  6195. */
  6196. function CanceledError(message) {
  6197. // eslint-disable-next-line no-eq-null,eqeqeq
  6198. AxiosError_1.call(this, message == null ? 'canceled' : message, AxiosError_1.ERR_CANCELED);
  6199. this.name = 'CanceledError';
  6200. }
  6201. utils.inherits(CanceledError, AxiosError_1, {
  6202. __CANCEL__: true
  6203. });
  6204. var CanceledError_1 = CanceledError;
  6205. var parseProtocol = function parseProtocol(url) {
  6206. var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
  6207. return match && match[1] || '';
  6208. };
  6209. var xhr = function xhrAdapter(config) {
  6210. return new Promise(function dispatchXhrRequest(resolve, reject) {
  6211. var requestData = config.data;
  6212. var requestHeaders = config.headers;
  6213. var responseType = config.responseType;
  6214. var onCanceled;
  6215. function done() {
  6216. if (config.cancelToken) {
  6217. config.cancelToken.unsubscribe(onCanceled);
  6218. }
  6219. if (config.signal) {
  6220. config.signal.removeEventListener('abort', onCanceled);
  6221. }
  6222. }
  6223. if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
  6224. delete requestHeaders['Content-Type']; // Let the browser set it
  6225. }
  6226. var request = new XMLHttpRequest();
  6227. // HTTP basic authentication
  6228. if (config.auth) {
  6229. var username = config.auth.username || '';
  6230. var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
  6231. requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
  6232. }
  6233. var fullPath = buildFullPath(config.baseURL, config.url);
  6234. request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
  6235. // Set the request timeout in MS
  6236. request.timeout = config.timeout;
  6237. function onloadend() {
  6238. if (!request) {
  6239. return;
  6240. }
  6241. // Prepare the response
  6242. var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
  6243. var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
  6244. request.responseText : request.response;
  6245. var response = {
  6246. data: responseData,
  6247. status: request.status,
  6248. statusText: request.statusText,
  6249. headers: responseHeaders,
  6250. config: config,
  6251. request: request
  6252. };
  6253. settle(function _resolve(value) {
  6254. resolve(value);
  6255. done();
  6256. }, function _reject(err) {
  6257. reject(err);
  6258. done();
  6259. }, response);
  6260. // Clean up request
  6261. request = null;
  6262. }
  6263. if ('onloadend' in request) {
  6264. // Use onloadend if available
  6265. request.onloadend = onloadend;
  6266. } else {
  6267. // Listen for ready state to emulate onloadend
  6268. request.onreadystatechange = function handleLoad() {
  6269. if (!request || request.readyState !== 4) {
  6270. return;
  6271. }
  6272. // The request errored out and we didn't get a response, this will be
  6273. // handled by onerror instead
  6274. // With one exception: request that using file: protocol, most browsers
  6275. // will return status as 0 even though it's a successful request
  6276. if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
  6277. return;
  6278. }
  6279. // readystate handler is calling before onerror or ontimeout handlers,
  6280. // so we should call onloadend on the next 'tick'
  6281. setTimeout(onloadend);
  6282. };
  6283. }
  6284. // Handle browser request cancellation (as opposed to a manual cancellation)
  6285. request.onabort = function handleAbort() {
  6286. if (!request) {
  6287. return;
  6288. }
  6289. reject(new AxiosError_1('Request aborted', AxiosError_1.ECONNABORTED, config, request));
  6290. // Clean up request
  6291. request = null;
  6292. };
  6293. // Handle low level network errors
  6294. request.onerror = function handleError() {
  6295. // Real errors are hidden from us by the browser
  6296. // onerror should only fire if it's a network error
  6297. reject(new AxiosError_1('Network Error', AxiosError_1.ERR_NETWORK, config, request, request));
  6298. // Clean up request
  6299. request = null;
  6300. };
  6301. // Handle timeout
  6302. request.ontimeout = function handleTimeout() {
  6303. var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
  6304. var transitional$1 = config.transitional || transitional;
  6305. if (config.timeoutErrorMessage) {
  6306. timeoutErrorMessage = config.timeoutErrorMessage;
  6307. }
  6308. reject(new AxiosError_1(
  6309. timeoutErrorMessage,
  6310. transitional$1.clarifyTimeoutError ? AxiosError_1.ETIMEDOUT : AxiosError_1.ECONNABORTED,
  6311. config,
  6312. request));
  6313. // Clean up request
  6314. request = null;
  6315. };
  6316. // Add xsrf header
  6317. // This is only done if running in a standard browser environment.
  6318. // Specifically not if we're in a web worker, or react-native.
  6319. if (utils.isStandardBrowserEnv()) {
  6320. // Add xsrf header
  6321. var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
  6322. cookies.read(config.xsrfCookieName) :
  6323. undefined;
  6324. if (xsrfValue) {
  6325. requestHeaders[config.xsrfHeaderName] = xsrfValue;
  6326. }
  6327. }
  6328. // Add headers to the request
  6329. if ('setRequestHeader' in request) {
  6330. utils.forEach(requestHeaders, function setRequestHeader(val, key) {
  6331. if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
  6332. // Remove Content-Type if data is undefined
  6333. delete requestHeaders[key];
  6334. } else {
  6335. // Otherwise add header to the request
  6336. request.setRequestHeader(key, val);
  6337. }
  6338. });
  6339. }
  6340. // Add withCredentials to request if needed
  6341. if (!utils.isUndefined(config.withCredentials)) {
  6342. request.withCredentials = !!config.withCredentials;
  6343. }
  6344. // Add responseType to request if needed
  6345. if (responseType && responseType !== 'json') {
  6346. request.responseType = config.responseType;
  6347. }
  6348. // Handle progress if needed
  6349. if (typeof config.onDownloadProgress === 'function') {
  6350. request.addEventListener('progress', config.onDownloadProgress);
  6351. }
  6352. // Not all browsers support upload events
  6353. if (typeof config.onUploadProgress === 'function' && request.upload) {
  6354. request.upload.addEventListener('progress', config.onUploadProgress);
  6355. }
  6356. if (config.cancelToken || config.signal) {
  6357. // Handle cancellation
  6358. // eslint-disable-next-line func-names
  6359. onCanceled = function(cancel) {
  6360. if (!request) {
  6361. return;
  6362. }
  6363. reject(!cancel || (cancel && cancel.type) ? new CanceledError_1() : cancel);
  6364. request.abort();
  6365. request = null;
  6366. };
  6367. config.cancelToken && config.cancelToken.subscribe(onCanceled);
  6368. if (config.signal) {
  6369. config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
  6370. }
  6371. }
  6372. if (!requestData) {
  6373. requestData = null;
  6374. }
  6375. var protocol = parseProtocol(fullPath);
  6376. if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) {
  6377. reject(new AxiosError_1('Unsupported protocol ' + protocol + ':', AxiosError_1.ERR_BAD_REQUEST, config));
  6378. return;
  6379. }
  6380. // Send the request
  6381. request.send(requestData);
  6382. });
  6383. };
  6384. // eslint-disable-next-line strict
  6385. var _null = null;
  6386. var DEFAULT_CONTENT_TYPE = {
  6387. 'Content-Type': 'application/x-www-form-urlencoded'
  6388. };
  6389. function setContentTypeIfUnset(headers, value) {
  6390. if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
  6391. headers['Content-Type'] = value;
  6392. }
  6393. }
  6394. function getDefaultAdapter() {
  6395. var adapter;
  6396. if (typeof XMLHttpRequest !== 'undefined') {
  6397. // For browsers use XHR adapter
  6398. adapter = xhr;
  6399. } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
  6400. // For node use HTTP adapter
  6401. adapter = xhr;
  6402. }
  6403. return adapter;
  6404. }
  6405. function stringifySafely(rawValue, parser, encoder) {
  6406. if (utils.isString(rawValue)) {
  6407. try {
  6408. (parser || JSON.parse)(rawValue);
  6409. return utils.trim(rawValue);
  6410. } catch (e) {
  6411. if (e.name !== 'SyntaxError') {
  6412. throw e;
  6413. }
  6414. }
  6415. }
  6416. return (encoder || JSON.stringify)(rawValue);
  6417. }
  6418. var defaults = {
  6419. transitional: transitional,
  6420. adapter: getDefaultAdapter(),
  6421. transformRequest: [function transformRequest(data, headers) {
  6422. normalizeHeaderName(headers, 'Accept');
  6423. normalizeHeaderName(headers, 'Content-Type');
  6424. if (utils.isFormData(data) ||
  6425. utils.isArrayBuffer(data) ||
  6426. utils.isBuffer(data) ||
  6427. utils.isStream(data) ||
  6428. utils.isFile(data) ||
  6429. utils.isBlob(data)
  6430. ) {
  6431. return data;
  6432. }
  6433. if (utils.isArrayBufferView(data)) {
  6434. return data.buffer;
  6435. }
  6436. if (utils.isURLSearchParams(data)) {
  6437. setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
  6438. return data.toString();
  6439. }
  6440. var isObjectPayload = utils.isObject(data);
  6441. var contentType = headers && headers['Content-Type'];
  6442. var isFileList;
  6443. if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) {
  6444. var _FormData = this.env && this.env.FormData;
  6445. return toFormData_1(isFileList ? {'files[]': data} : data, _FormData && new _FormData());
  6446. } else if (isObjectPayload || contentType === 'application/json') {
  6447. setContentTypeIfUnset(headers, 'application/json');
  6448. return stringifySafely(data);
  6449. }
  6450. return data;
  6451. }],
  6452. transformResponse: [function transformResponse(data) {
  6453. var transitional = this.transitional || defaults.transitional;
  6454. var silentJSONParsing = transitional && transitional.silentJSONParsing;
  6455. var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
  6456. var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
  6457. if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
  6458. try {
  6459. return JSON.parse(data);
  6460. } catch (e) {
  6461. if (strictJSONParsing) {
  6462. if (e.name === 'SyntaxError') {
  6463. throw AxiosError_1.from(e, AxiosError_1.ERR_BAD_RESPONSE, this, null, this.response);
  6464. }
  6465. throw e;
  6466. }
  6467. }
  6468. }
  6469. return data;
  6470. }],
  6471. /**
  6472. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  6473. * timeout is not created.
  6474. */
  6475. timeout: 0,
  6476. xsrfCookieName: 'XSRF-TOKEN',
  6477. xsrfHeaderName: 'X-XSRF-TOKEN',
  6478. maxContentLength: -1,
  6479. maxBodyLength: -1,
  6480. env: {
  6481. FormData: _null
  6482. },
  6483. validateStatus: function validateStatus(status) {
  6484. return status >= 200 && status < 300;
  6485. },
  6486. headers: {
  6487. common: {
  6488. 'Accept': 'application/json, text/plain, */*'
  6489. }
  6490. }
  6491. };
  6492. utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
  6493. defaults.headers[method] = {};
  6494. });
  6495. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  6496. defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
  6497. });
  6498. var defaults_1 = defaults;
  6499. /**
  6500. * Transform the data for a request or a response
  6501. *
  6502. * @param {Object|String} data The data to be transformed
  6503. * @param {Array} headers The headers for the request or response
  6504. * @param {Array|Function} fns A single function or Array of functions
  6505. * @returns {*} The resulting transformed data
  6506. */
  6507. var transformData = function transformData(data, headers, fns) {
  6508. var context = this || defaults_1;
  6509. /*eslint no-param-reassign:0*/
  6510. utils.forEach(fns, function transform(fn) {
  6511. data = fn.call(context, data, headers);
  6512. });
  6513. return data;
  6514. };
  6515. var isCancel = function isCancel(value) {
  6516. return !!(value && value.__CANCEL__);
  6517. };
  6518. /**
  6519. * Throws a `CanceledError` if cancellation has been requested.
  6520. */
  6521. function throwIfCancellationRequested(config) {
  6522. if (config.cancelToken) {
  6523. config.cancelToken.throwIfRequested();
  6524. }
  6525. if (config.signal && config.signal.aborted) {
  6526. throw new CanceledError_1();
  6527. }
  6528. }
  6529. /**
  6530. * Dispatch a request to the server using the configured adapter.
  6531. *
  6532. * @param {object} config The config that is to be used for the request
  6533. * @returns {Promise} The Promise to be fulfilled
  6534. */
  6535. var dispatchRequest = function dispatchRequest(config) {
  6536. throwIfCancellationRequested(config);
  6537. // Ensure headers exist
  6538. config.headers = config.headers || {};
  6539. // Transform request data
  6540. config.data = transformData.call(
  6541. config,
  6542. config.data,
  6543. config.headers,
  6544. config.transformRequest
  6545. );
  6546. // Flatten headers
  6547. config.headers = utils.merge(
  6548. config.headers.common || {},
  6549. config.headers[config.method] || {},
  6550. config.headers
  6551. );
  6552. utils.forEach(
  6553. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  6554. function cleanHeaderConfig(method) {
  6555. delete config.headers[method];
  6556. }
  6557. );
  6558. var adapter = config.adapter || defaults_1.adapter;
  6559. return adapter(config).then(function onAdapterResolution(response) {
  6560. throwIfCancellationRequested(config);
  6561. // Transform response data
  6562. response.data = transformData.call(
  6563. config,
  6564. response.data,
  6565. response.headers,
  6566. config.transformResponse
  6567. );
  6568. return response;
  6569. }, function onAdapterRejection(reason) {
  6570. if (!isCancel(reason)) {
  6571. throwIfCancellationRequested(config);
  6572. // Transform response data
  6573. if (reason && reason.response) {
  6574. reason.response.data = transformData.call(
  6575. config,
  6576. reason.response.data,
  6577. reason.response.headers,
  6578. config.transformResponse
  6579. );
  6580. }
  6581. }
  6582. return Promise.reject(reason);
  6583. });
  6584. };
  6585. /**
  6586. * Config-specific merge-function which creates a new config-object
  6587. * by merging two configuration objects together.
  6588. *
  6589. * @param {Object} config1
  6590. * @param {Object} config2
  6591. * @returns {Object} New object resulting from merging config2 to config1
  6592. */
  6593. var mergeConfig = function mergeConfig(config1, config2) {
  6594. // eslint-disable-next-line no-param-reassign
  6595. config2 = config2 || {};
  6596. var config = {};
  6597. function getMergedValue(target, source) {
  6598. if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
  6599. return utils.merge(target, source);
  6600. } else if (utils.isPlainObject(source)) {
  6601. return utils.merge({}, source);
  6602. } else if (utils.isArray(source)) {
  6603. return source.slice();
  6604. }
  6605. return source;
  6606. }
  6607. // eslint-disable-next-line consistent-return
  6608. function mergeDeepProperties(prop) {
  6609. if (!utils.isUndefined(config2[prop])) {
  6610. return getMergedValue(config1[prop], config2[prop]);
  6611. } else if (!utils.isUndefined(config1[prop])) {
  6612. return getMergedValue(undefined, config1[prop]);
  6613. }
  6614. }
  6615. // eslint-disable-next-line consistent-return
  6616. function valueFromConfig2(prop) {
  6617. if (!utils.isUndefined(config2[prop])) {
  6618. return getMergedValue(undefined, config2[prop]);
  6619. }
  6620. }
  6621. // eslint-disable-next-line consistent-return
  6622. function defaultToConfig2(prop) {
  6623. if (!utils.isUndefined(config2[prop])) {
  6624. return getMergedValue(undefined, config2[prop]);
  6625. } else if (!utils.isUndefined(config1[prop])) {
  6626. return getMergedValue(undefined, config1[prop]);
  6627. }
  6628. }
  6629. // eslint-disable-next-line consistent-return
  6630. function mergeDirectKeys(prop) {
  6631. if (prop in config2) {
  6632. return getMergedValue(config1[prop], config2[prop]);
  6633. } else if (prop in config1) {
  6634. return getMergedValue(undefined, config1[prop]);
  6635. }
  6636. }
  6637. var mergeMap = {
  6638. 'url': valueFromConfig2,
  6639. 'method': valueFromConfig2,
  6640. 'data': valueFromConfig2,
  6641. 'baseURL': defaultToConfig2,
  6642. 'transformRequest': defaultToConfig2,
  6643. 'transformResponse': defaultToConfig2,
  6644. 'paramsSerializer': defaultToConfig2,
  6645. 'timeout': defaultToConfig2,
  6646. 'timeoutMessage': defaultToConfig2,
  6647. 'withCredentials': defaultToConfig2,
  6648. 'adapter': defaultToConfig2,
  6649. 'responseType': defaultToConfig2,
  6650. 'xsrfCookieName': defaultToConfig2,
  6651. 'xsrfHeaderName': defaultToConfig2,
  6652. 'onUploadProgress': defaultToConfig2,
  6653. 'onDownloadProgress': defaultToConfig2,
  6654. 'decompress': defaultToConfig2,
  6655. 'maxContentLength': defaultToConfig2,
  6656. 'maxBodyLength': defaultToConfig2,
  6657. 'beforeRedirect': defaultToConfig2,
  6658. 'transport': defaultToConfig2,
  6659. 'httpAgent': defaultToConfig2,
  6660. 'httpsAgent': defaultToConfig2,
  6661. 'cancelToken': defaultToConfig2,
  6662. 'socketPath': defaultToConfig2,
  6663. 'responseEncoding': defaultToConfig2,
  6664. 'validateStatus': mergeDirectKeys
  6665. };
  6666. utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
  6667. var merge = mergeMap[prop] || mergeDeepProperties;
  6668. var configValue = merge(prop);
  6669. (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
  6670. });
  6671. return config;
  6672. };
  6673. var data = {
  6674. "version": "0.27.2"
  6675. };
  6676. var VERSION = data.version;
  6677. var validators$1 = {};
  6678. // eslint-disable-next-line func-names
  6679. ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
  6680. validators$1[type] = function validator(thing) {
  6681. return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
  6682. };
  6683. });
  6684. var deprecatedWarnings = {};
  6685. /**
  6686. * Transitional option validator
  6687. * @param {function|boolean?} validator - set to false if the transitional option has been removed
  6688. * @param {string?} version - deprecated version / removed since version
  6689. * @param {string?} message - some message with additional info
  6690. * @returns {function}
  6691. */
  6692. validators$1.transitional = function transitional(validator, version, message) {
  6693. function formatMessage(opt, desc) {
  6694. return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
  6695. }
  6696. // eslint-disable-next-line func-names
  6697. return function(value, opt, opts) {
  6698. if (validator === false) {
  6699. throw new AxiosError_1(
  6700. formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
  6701. AxiosError_1.ERR_DEPRECATED
  6702. );
  6703. }
  6704. if (version && !deprecatedWarnings[opt]) {
  6705. deprecatedWarnings[opt] = true;
  6706. // eslint-disable-next-line no-console
  6707. console.warn(
  6708. formatMessage(
  6709. opt,
  6710. ' has been deprecated since v' + version + ' and will be removed in the near future'
  6711. )
  6712. );
  6713. }
  6714. return validator ? validator(value, opt, opts) : true;
  6715. };
  6716. };
  6717. /**
  6718. * Assert object's properties type
  6719. * @param {object} options
  6720. * @param {object} schema
  6721. * @param {boolean?} allowUnknown
  6722. */
  6723. function assertOptions(options, schema, allowUnknown) {
  6724. if (typeof options !== 'object') {
  6725. throw new AxiosError_1('options must be an object', AxiosError_1.ERR_BAD_OPTION_VALUE);
  6726. }
  6727. var keys = Object.keys(options);
  6728. var i = keys.length;
  6729. while (i-- > 0) {
  6730. var opt = keys[i];
  6731. var validator = schema[opt];
  6732. if (validator) {
  6733. var value = options[opt];
  6734. var result = value === undefined || validator(value, opt, options);
  6735. if (result !== true) {
  6736. throw new AxiosError_1('option ' + opt + ' must be ' + result, AxiosError_1.ERR_BAD_OPTION_VALUE);
  6737. }
  6738. continue;
  6739. }
  6740. if (allowUnknown !== true) {
  6741. throw new AxiosError_1('Unknown option ' + opt, AxiosError_1.ERR_BAD_OPTION);
  6742. }
  6743. }
  6744. }
  6745. var validator = {
  6746. assertOptions: assertOptions,
  6747. validators: validators$1
  6748. };
  6749. var validators = validator.validators;
  6750. /**
  6751. * Create a new instance of Axios
  6752. *
  6753. * @param {Object} instanceConfig The default config for the instance
  6754. */
  6755. function Axios(instanceConfig) {
  6756. this.defaults = instanceConfig;
  6757. this.interceptors = {
  6758. request: new InterceptorManager_1(),
  6759. response: new InterceptorManager_1()
  6760. };
  6761. }
  6762. /**
  6763. * Dispatch a request
  6764. *
  6765. * @param {Object} config The config specific for this request (merged with this.defaults)
  6766. */
  6767. Axios.prototype.request = function request(configOrUrl, config) {
  6768. /*eslint no-param-reassign:0*/
  6769. // Allow for axios('example/url'[, config]) a la fetch API
  6770. if (typeof configOrUrl === 'string') {
  6771. config = config || {};
  6772. config.url = configOrUrl;
  6773. } else {
  6774. config = configOrUrl || {};
  6775. }
  6776. config = mergeConfig(this.defaults, config);
  6777. // Set config.method
  6778. if (config.method) {
  6779. config.method = config.method.toLowerCase();
  6780. } else if (this.defaults.method) {
  6781. config.method = this.defaults.method.toLowerCase();
  6782. } else {
  6783. config.method = 'get';
  6784. }
  6785. var transitional = config.transitional;
  6786. if (transitional !== undefined) {
  6787. validator.assertOptions(transitional, {
  6788. silentJSONParsing: validators.transitional(validators.boolean),
  6789. forcedJSONParsing: validators.transitional(validators.boolean),
  6790. clarifyTimeoutError: validators.transitional(validators.boolean)
  6791. }, false);
  6792. }
  6793. // filter out skipped interceptors
  6794. var requestInterceptorChain = [];
  6795. var synchronousRequestInterceptors = true;
  6796. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  6797. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  6798. return;
  6799. }
  6800. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  6801. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  6802. });
  6803. var responseInterceptorChain = [];
  6804. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  6805. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  6806. });
  6807. var promise;
  6808. if (!synchronousRequestInterceptors) {
  6809. var chain = [dispatchRequest, undefined];
  6810. Array.prototype.unshift.apply(chain, requestInterceptorChain);
  6811. chain = chain.concat(responseInterceptorChain);
  6812. promise = Promise.resolve(config);
  6813. while (chain.length) {
  6814. promise = promise.then(chain.shift(), chain.shift());
  6815. }
  6816. return promise;
  6817. }
  6818. var newConfig = config;
  6819. while (requestInterceptorChain.length) {
  6820. var onFulfilled = requestInterceptorChain.shift();
  6821. var onRejected = requestInterceptorChain.shift();
  6822. try {
  6823. newConfig = onFulfilled(newConfig);
  6824. } catch (error) {
  6825. onRejected(error);
  6826. break;
  6827. }
  6828. }
  6829. try {
  6830. promise = dispatchRequest(newConfig);
  6831. } catch (error) {
  6832. return Promise.reject(error);
  6833. }
  6834. while (responseInterceptorChain.length) {
  6835. promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
  6836. }
  6837. return promise;
  6838. };
  6839. Axios.prototype.getUri = function getUri(config) {
  6840. config = mergeConfig(this.defaults, config);
  6841. var fullPath = buildFullPath(config.baseURL, config.url);
  6842. return buildURL(fullPath, config.params, config.paramsSerializer);
  6843. };
  6844. // Provide aliases for supported request methods
  6845. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  6846. /*eslint func-names:0*/
  6847. Axios.prototype[method] = function(url, config) {
  6848. return this.request(mergeConfig(config || {}, {
  6849. method: method,
  6850. url: url,
  6851. data: (config || {}).data
  6852. }));
  6853. };
  6854. });
  6855. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  6856. /*eslint func-names:0*/
  6857. function generateHTTPMethod(isForm) {
  6858. return function httpMethod(url, data, config) {
  6859. return this.request(mergeConfig(config || {}, {
  6860. method: method,
  6861. headers: isForm ? {
  6862. 'Content-Type': 'multipart/form-data'
  6863. } : {},
  6864. url: url,
  6865. data: data
  6866. }));
  6867. };
  6868. }
  6869. Axios.prototype[method] = generateHTTPMethod();
  6870. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  6871. });
  6872. var Axios_1 = Axios;
  6873. /**
  6874. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  6875. *
  6876. * @class
  6877. * @param {Function} executor The executor function.
  6878. */
  6879. function CancelToken(executor) {
  6880. if (typeof executor !== 'function') {
  6881. throw new TypeError('executor must be a function.');
  6882. }
  6883. var resolvePromise;
  6884. this.promise = new Promise(function promiseExecutor(resolve) {
  6885. resolvePromise = resolve;
  6886. });
  6887. var token = this;
  6888. // eslint-disable-next-line func-names
  6889. this.promise.then(function(cancel) {
  6890. if (!token._listeners) return;
  6891. var i;
  6892. var l = token._listeners.length;
  6893. for (i = 0; i < l; i++) {
  6894. token._listeners[i](cancel);
  6895. }
  6896. token._listeners = null;
  6897. });
  6898. // eslint-disable-next-line func-names
  6899. this.promise.then = function(onfulfilled) {
  6900. var _resolve;
  6901. // eslint-disable-next-line func-names
  6902. var promise = new Promise(function(resolve) {
  6903. token.subscribe(resolve);
  6904. _resolve = resolve;
  6905. }).then(onfulfilled);
  6906. promise.cancel = function reject() {
  6907. token.unsubscribe(_resolve);
  6908. };
  6909. return promise;
  6910. };
  6911. executor(function cancel(message) {
  6912. if (token.reason) {
  6913. // Cancellation has already been requested
  6914. return;
  6915. }
  6916. token.reason = new CanceledError_1(message);
  6917. resolvePromise(token.reason);
  6918. });
  6919. }
  6920. /**
  6921. * Throws a `CanceledError` if cancellation has been requested.
  6922. */
  6923. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  6924. if (this.reason) {
  6925. throw this.reason;
  6926. }
  6927. };
  6928. /**
  6929. * Subscribe to the cancel signal
  6930. */
  6931. CancelToken.prototype.subscribe = function subscribe(listener) {
  6932. if (this.reason) {
  6933. listener(this.reason);
  6934. return;
  6935. }
  6936. if (this._listeners) {
  6937. this._listeners.push(listener);
  6938. } else {
  6939. this._listeners = [listener];
  6940. }
  6941. };
  6942. /**
  6943. * Unsubscribe from the cancel signal
  6944. */
  6945. CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
  6946. if (!this._listeners) {
  6947. return;
  6948. }
  6949. var index = this._listeners.indexOf(listener);
  6950. if (index !== -1) {
  6951. this._listeners.splice(index, 1);
  6952. }
  6953. };
  6954. /**
  6955. * Returns an object that contains a new `CancelToken` and a function that, when called,
  6956. * cancels the `CancelToken`.
  6957. */
  6958. CancelToken.source = function source() {
  6959. var cancel;
  6960. var token = new CancelToken(function executor(c) {
  6961. cancel = c;
  6962. });
  6963. return {
  6964. token: token,
  6965. cancel: cancel
  6966. };
  6967. };
  6968. var CancelToken_1 = CancelToken;
  6969. /**
  6970. * Syntactic sugar for invoking a function and expanding an array for arguments.
  6971. *
  6972. * Common use case would be to use `Function.prototype.apply`.
  6973. *
  6974. * ```js
  6975. * function f(x, y, z) {}
  6976. * var args = [1, 2, 3];
  6977. * f.apply(null, args);
  6978. * ```
  6979. *
  6980. * With `spread` this example can be re-written.
  6981. *
  6982. * ```js
  6983. * spread(function(x, y, z) {})([1, 2, 3]);
  6984. * ```
  6985. *
  6986. * @param {Function} callback
  6987. * @returns {Function}
  6988. */
  6989. var spread = function spread(callback) {
  6990. return function wrap(arr) {
  6991. return callback.apply(null, arr);
  6992. };
  6993. };
  6994. /**
  6995. * Determines whether the payload is an error thrown by Axios
  6996. *
  6997. * @param {*} payload The value to test
  6998. * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
  6999. */
  7000. var isAxiosError = function isAxiosError(payload) {
  7001. return utils.isObject(payload) && (payload.isAxiosError === true);
  7002. };
  7003. /**
  7004. * Create an instance of Axios
  7005. *
  7006. * @param {Object} defaultConfig The default config for the instance
  7007. * @return {Axios} A new instance of Axios
  7008. */
  7009. function createInstance(defaultConfig) {
  7010. var context = new Axios_1(defaultConfig);
  7011. var instance = bind(Axios_1.prototype.request, context);
  7012. // Copy axios.prototype to instance
  7013. utils.extend(instance, Axios_1.prototype, context);
  7014. // Copy context to instance
  7015. utils.extend(instance, context);
  7016. // Factory for creating new instances
  7017. instance.create = function create(instanceConfig) {
  7018. return createInstance(mergeConfig(defaultConfig, instanceConfig));
  7019. };
  7020. return instance;
  7021. }
  7022. // Create the default instance to be exported
  7023. var axios$1 = createInstance(defaults_1);
  7024. // Expose Axios class to allow class inheritance
  7025. axios$1.Axios = Axios_1;
  7026. // Expose Cancel & CancelToken
  7027. axios$1.CanceledError = CanceledError_1;
  7028. axios$1.CancelToken = CancelToken_1;
  7029. axios$1.isCancel = isCancel;
  7030. axios$1.VERSION = data.version;
  7031. axios$1.toFormData = toFormData_1;
  7032. // Expose AxiosError class
  7033. axios$1.AxiosError = AxiosError_1;
  7034. // alias for CanceledError for backward compatibility
  7035. axios$1.Cancel = axios$1.CanceledError;
  7036. // Expose all/spread
  7037. axios$1.all = function all(promises) {
  7038. return Promise.all(promises);
  7039. };
  7040. axios$1.spread = spread;
  7041. // Expose isAxiosError
  7042. axios$1.isAxiosError = isAxiosError;
  7043. var axios_1 = axios$1;
  7044. // Allow use of default import syntax in TypeScript
  7045. var _default = axios$1;
  7046. axios_1.default = _default;
  7047. var axios = axios_1;
  7048. class RTCEndpoint extends Event$1 {
  7049. constructor(options) {
  7050. super('RTCPusherPlayer');
  7051. this.TAG = '[RTCPusherPlayer]';
  7052. let defaults = {
  7053. element: '',
  7054. // html video element
  7055. debug: false,
  7056. // if output debug log
  7057. zlmsdpUrl: '',
  7058. simulcast: false,
  7059. useCamera: true,
  7060. audioEnable: true,
  7061. videoEnable: true,
  7062. recvOnly: false,
  7063. resolution: {
  7064. w: 0,
  7065. h: 0
  7066. },
  7067. usedatachannel: false
  7068. };
  7069. this.options = Object.assign({}, defaults, options);
  7070. if (this.options.debug) {
  7071. setLogger();
  7072. }
  7073. this.e = {
  7074. onicecandidate: this._onIceCandidate.bind(this),
  7075. ontrack: this._onTrack.bind(this),
  7076. onicecandidateerror: this._onIceCandidateError.bind(this),
  7077. onconnectionstatechange: this._onconnectionstatechange.bind(this),
  7078. ondatachannelopen: this._onDataChannelOpen.bind(this),
  7079. ondatachannelmsg: this._onDataChannelMsg.bind(this),
  7080. ondatachannelerr: this._onDataChannelErr.bind(this),
  7081. ondatachannelclose: this._onDataChannelClose.bind(this)
  7082. };
  7083. this._remoteStream = null;
  7084. this._localStream = null;
  7085. this._tracks = [];
  7086. this.pc = new RTCPeerConnection(null);
  7087. this.pc.onicecandidate = this.e.onicecandidate;
  7088. this.pc.onicecandidateerror = this.e.onicecandidateerror;
  7089. this.pc.ontrack = this.e.ontrack;
  7090. this.pc.onconnectionstatechange = this.e.onconnectionstatechange;
  7091. this.datachannel = null;
  7092. if (this.options.usedatachannel) {
  7093. this.datachannel = this.pc.createDataChannel('chat');
  7094. this.datachannel.onclose = this.e.ondatachannelclose;
  7095. this.datachannel.onerror = this.e.ondatachannelerr;
  7096. this.datachannel.onmessage = this.e.ondatachannelmsg;
  7097. this.datachannel.onopen = this.e.ondatachannelopen;
  7098. }
  7099. if (!this.options.recvOnly && (this.options.audioEnable || this.options.videoEnable)) this.start();else this.receive();
  7100. }
  7101. receive() {
  7102. //debug.error(this.TAG,'this not implement');
  7103. const AudioTransceiverInit = {
  7104. direction: 'recvonly',
  7105. sendEncodings: []
  7106. };
  7107. const VideoTransceiverInit = {
  7108. direction: 'recvonly',
  7109. sendEncodings: []
  7110. };
  7111. if (this.options.videoEnable) {
  7112. this.pc.addTransceiver('video', VideoTransceiverInit);
  7113. }
  7114. if (this.options.audioEnable) {
  7115. this.pc.addTransceiver('audio', AudioTransceiverInit);
  7116. }
  7117. this.pc.createOffer().then(desc => {
  7118. log(this.TAG, 'offer:', desc.sdp);
  7119. this.pc.setLocalDescription(desc).then(() => {
  7120. axios({
  7121. method: 'post',
  7122. url: this.options.zlmsdpUrl,
  7123. responseType: 'json',
  7124. data: desc.sdp,
  7125. headers: {
  7126. 'Content-Type': 'text/plain;charset=utf-8'
  7127. }
  7128. }).then(response => {
  7129. let ret = response.data; //JSON.parse(response.data);
  7130. if (ret.code != 0) {
  7131. // mean failed for offer/anwser exchange
  7132. this.dispatch(Events$1.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, ret);
  7133. return;
  7134. }
  7135. let anwser = {};
  7136. anwser.sdp = ret.sdp;
  7137. anwser.type = 'answer';
  7138. log(this.TAG, 'answer:', ret.sdp);
  7139. this.pc.setRemoteDescription(anwser).then(() => {
  7140. log(this.TAG, 'set remote sucess');
  7141. }).catch(e => {
  7142. error(this.TAG, e);
  7143. });
  7144. });
  7145. });
  7146. }).catch(e => {
  7147. error(this.TAG, e);
  7148. });
  7149. }
  7150. start() {
  7151. let videoConstraints = false;
  7152. let audioConstraints = false;
  7153. if (this.options.useCamera) {
  7154. if (this.options.videoEnable) videoConstraints = new VideoTrackConstraints(VideoSourceInfo.CAMERA);
  7155. if (this.options.audioEnable) audioConstraints = new AudioTrackConstraints(AudioSourceInfo.MIC);
  7156. } else {
  7157. if (this.options.videoEnable) {
  7158. videoConstraints = new VideoTrackConstraints(VideoSourceInfo.SCREENCAST);
  7159. if (this.options.audioEnable) audioConstraints = new AudioTrackConstraints(AudioSourceInfo.SCREENCAST);
  7160. } else {
  7161. if (this.options.audioEnable) audioConstraints = new AudioTrackConstraints(AudioSourceInfo.MIC);else {
  7162. // error shared display media not only audio
  7163. error(this.TAG, 'error paramter');
  7164. }
  7165. }
  7166. }
  7167. if (this.options.resolution.w != 0 && this.options.resolution.h != 0 && typeof videoConstraints == 'object') {
  7168. videoConstraints.resolution = new Resolution(this.options.resolution.w, this.options.resolution.h);
  7169. }
  7170. MediaStreamFactory.createMediaStream(new StreamConstraints(audioConstraints, videoConstraints)).then(stream => {
  7171. this._localStream = stream;
  7172. this.dispatch(Events$1.WEBRTC_ON_LOCAL_STREAM, stream);
  7173. const AudioTransceiverInit = {
  7174. direction: 'sendrecv',
  7175. sendEncodings: []
  7176. };
  7177. const VideoTransceiverInit = {
  7178. direction: 'sendrecv',
  7179. sendEncodings: []
  7180. };
  7181. if (this.options.simulcast && stream.getVideoTracks().length > 0) {
  7182. VideoTransceiverInit.sendEncodings = [{
  7183. rid: 'h',
  7184. active: true,
  7185. maxBitrate: 1000000
  7186. }, {
  7187. rid: 'm',
  7188. active: true,
  7189. maxBitrate: 500000,
  7190. scaleResolutionDownBy: 2
  7191. }, {
  7192. rid: 'l',
  7193. active: true,
  7194. maxBitrate: 200000,
  7195. scaleResolutionDownBy: 4
  7196. }];
  7197. }
  7198. if (this.options.audioEnable) {
  7199. if (stream.getAudioTracks().length > 0) {
  7200. this.pc.addTransceiver(stream.getAudioTracks()[0], AudioTransceiverInit);
  7201. } else {
  7202. AudioTransceiverInit.direction = 'recvonly';
  7203. this.pc.addTransceiver('audio', AudioTransceiverInit);
  7204. }
  7205. }
  7206. if (this.options.videoEnable) {
  7207. if (stream.getVideoTracks().length > 0) {
  7208. this.pc.addTransceiver(stream.getVideoTracks()[0], VideoTransceiverInit);
  7209. } else {
  7210. VideoTransceiverInit.direction = 'recvonly';
  7211. this.pc.addTransceiver('video', VideoTransceiverInit);
  7212. }
  7213. }
  7214. /*
  7215. stream.getTracks().forEach((track,idx)=>{
  7216. debug.log(this.TAG,track);
  7217. this.pc.addTrack(track);
  7218. });
  7219. */
  7220. this.pc.createOffer().then(desc => {
  7221. log(this.TAG, 'offer:', desc.sdp);
  7222. this.pc.setLocalDescription(desc).then(() => {
  7223. axios({
  7224. method: 'post',
  7225. url: this.options.zlmsdpUrl,
  7226. responseType: 'json',
  7227. data: desc.sdp,
  7228. headers: {
  7229. 'Content-Type': 'text/plain;charset=utf-8'
  7230. }
  7231. }).then(response => {
  7232. let ret = response.data; //JSON.parse(response.data);
  7233. if (ret.code != 0) {
  7234. // mean failed for offer/anwser exchange
  7235. this.dispatch(Events$1.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, ret);
  7236. return;
  7237. }
  7238. let anwser = {};
  7239. anwser.sdp = ret.sdp;
  7240. anwser.type = 'answer';
  7241. log(this.TAG, 'answer:', ret.sdp);
  7242. this.pc.setRemoteDescription(anwser).then(() => {
  7243. log(this.TAG, 'set remote sucess');
  7244. }).catch(e => {
  7245. error(this.TAG, e);
  7246. });
  7247. });
  7248. });
  7249. }).catch(e => {
  7250. error(this.TAG, e);
  7251. });
  7252. }).catch(e => {
  7253. this.dispatch(Events$1.CAPTURE_STREAM_FAILED);
  7254. //debug.error(this.TAG,e);
  7255. });
  7256. //const offerOptions = {};
  7257. /*
  7258. if (typeof this.pc.addTransceiver === 'function') {
  7259. // |direction| seems not working on Safari.
  7260. this.pc.addTransceiver('audio', { direction: 'recvonly' });
  7261. this.pc.addTransceiver('video', { direction: 'recvonly' });
  7262. } else {
  7263. offerOptions.offerToReceiveAudio = true;
  7264. offerOptions.offerToReceiveVideo = true;
  7265. }
  7266. */
  7267. }
  7268. _onIceCandidate(event) {
  7269. if (event.candidate) {
  7270. log(this.TAG, 'Remote ICE candidate: \n ' + event.candidate.candidate);
  7271. // Send the candidate to the remote peer
  7272. }
  7273. }
  7274. _onTrack(event) {
  7275. this._tracks.push(event.track);
  7276. if (this.options.element && event.streams && event.streams.length > 0) {
  7277. this.options.element.srcObject = event.streams[0];
  7278. this._remoteStream = event.streams[0];
  7279. this.dispatch(Events$1.WEBRTC_ON_REMOTE_STREAMS, event);
  7280. } else {
  7281. if (this.pc.getReceivers().length == this._tracks.length) {
  7282. log(this.TAG, 'play remote stream ');
  7283. this._remoteStream = new MediaStream(this._tracks);
  7284. this.options.element.srcObject = this._remoteStream;
  7285. } else {
  7286. error(this.TAG, 'wait stream track finish');
  7287. }
  7288. }
  7289. }
  7290. _onIceCandidateError(event) {
  7291. this.dispatch(Events$1.WEBRTC_ICE_CANDIDATE_ERROR, event);
  7292. }
  7293. _onconnectionstatechange(event) {
  7294. this.dispatch(Events$1.WEBRTC_ON_CONNECTION_STATE_CHANGE, this.pc.connectionState);
  7295. }
  7296. _onDataChannelOpen(event) {
  7297. log(this.TAG, 'ondatachannel open:', event);
  7298. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_OPEN, event);
  7299. }
  7300. _onDataChannelMsg(event) {
  7301. log(this.TAG, 'ondatachannel msg:', event);
  7302. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_MSG, event);
  7303. }
  7304. _onDataChannelErr(event) {
  7305. log(this.TAG, 'ondatachannel err:', event);
  7306. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_ERR, event);
  7307. }
  7308. _onDataChannelClose(event) {
  7309. log(this.TAG, 'ondatachannel close:', event);
  7310. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_CLOSE, event);
  7311. }
  7312. sendMsg(data) {
  7313. if (this.datachannel != null) {
  7314. this.datachannel.send(data);
  7315. } else {
  7316. error(this.TAG, 'data channel is null');
  7317. }
  7318. }
  7319. closeDataChannel() {
  7320. if (this.datachannel) {
  7321. this.datachannel.close();
  7322. this.datachannel = null;
  7323. }
  7324. }
  7325. close() {
  7326. this.closeDataChannel();
  7327. if (this.pc) {
  7328. this.pc.close();
  7329. this.pc = null;
  7330. }
  7331. if (this.options) {
  7332. this.options = null;
  7333. }
  7334. if (this._localStream) {
  7335. this._localStream.getTracks().forEach((track, idx) => {
  7336. track.stop();
  7337. });
  7338. }
  7339. if (this._remoteStream) {
  7340. this._remoteStream.getTracks().forEach((track, idx) => {
  7341. track.stop();
  7342. });
  7343. }
  7344. this._tracks.forEach((track, idx) => {
  7345. track.stop();
  7346. });
  7347. this._tracks = [];
  7348. }
  7349. get remoteStream() {
  7350. return this._remoteStream;
  7351. }
  7352. get localStream() {
  7353. return this._localStream;
  7354. }
  7355. }
  7356. const quickScan = [{
  7357. 'label': '4K(UHD)',
  7358. 'width': 3840,
  7359. 'height': 2160
  7360. }, {
  7361. 'label': '1080p(FHD)',
  7362. 'width': 1920,
  7363. 'height': 1080
  7364. }, {
  7365. 'label': 'UXGA',
  7366. 'width': 1600,
  7367. 'height': 1200,
  7368. 'ratio': '4:3'
  7369. }, {
  7370. 'label': '720p(HD)',
  7371. 'width': 1280,
  7372. 'height': 720
  7373. }, {
  7374. 'label': 'SVGA',
  7375. 'width': 800,
  7376. 'height': 600
  7377. }, {
  7378. 'label': 'VGA',
  7379. 'width': 640,
  7380. 'height': 480
  7381. }, {
  7382. 'label': '360p(nHD)',
  7383. 'width': 640,
  7384. 'height': 360
  7385. }, {
  7386. 'label': 'CIF',
  7387. 'width': 352,
  7388. 'height': 288
  7389. }, {
  7390. 'label': 'QVGA',
  7391. 'width': 320,
  7392. 'height': 240
  7393. }, {
  7394. 'label': 'QCIF',
  7395. 'width': 176,
  7396. 'height': 144
  7397. }, {
  7398. 'label': 'QQVGA',
  7399. 'width': 160,
  7400. 'height': 120
  7401. }];
  7402. function GetSupportCameraResolutions$1() {
  7403. return new Promise(function (resolve, reject) {
  7404. let resolutions = [];
  7405. let ok = 0;
  7406. let err = 0;
  7407. for (let i = 0; i < quickScan.length; ++i) {
  7408. let videoConstraints = new VideoTrackConstraints(VideoSourceInfo.CAMERA);
  7409. videoConstraints.resolution = new Resolution(quickScan[i].width, quickScan[i].height);
  7410. MediaStreamFactory.createMediaStream(new StreamConstraints(false, videoConstraints)).then(stream => {
  7411. resolutions.push(quickScan[i]);
  7412. ok++;
  7413. if (ok + err == quickScan.length) {
  7414. resolve(resolutions);
  7415. }
  7416. }).catch(e => {
  7417. err++;
  7418. if (ok + err == quickScan.length) {
  7419. resolve(resolutions);
  7420. }
  7421. });
  7422. }
  7423. });
  7424. }
  7425. function GetAllScanResolution$1() {
  7426. return quickScan;
  7427. }
  7428. function isSupportResolution$1(w, h) {
  7429. return new Promise(function (resolve, reject) {
  7430. let videoConstraints = new VideoTrackConstraints(VideoSourceInfo.CAMERA);
  7431. videoConstraints.resolution = new Resolution(w, h);
  7432. MediaStreamFactory.createMediaStream(new StreamConstraints(false, videoConstraints)).then(stream => {
  7433. resolve();
  7434. }).catch(e => {
  7435. reject(e);
  7436. });
  7437. });
  7438. }
  7439. console.log('build date:', BUILD_DATE);
  7440. console.log('version:', VERSION$1);
  7441. const Events = Events$1;
  7442. const Media = media;
  7443. const Endpoint = RTCEndpoint;
  7444. const GetSupportCameraResolutions = GetSupportCameraResolutions$1;
  7445. const GetAllScanResolution = GetAllScanResolution$1;
  7446. const isSupportResolution = isSupportResolution$1;
  7447. exports.Endpoint = Endpoint;
  7448. exports.Events = Events;
  7449. exports.GetAllScanResolution = GetAllScanResolution;
  7450. exports.GetSupportCameraResolutions = GetSupportCameraResolutions;
  7451. exports.Media = Media;
  7452. exports.isSupportResolution = isSupportResolution;
  7453. Object.defineProperty(exports, '__esModule', { value: true });
  7454. return exports;
  7455. })({});
  7456. //# sourceMappingURL=ZLMRTCClient.js.map