ZLMRTCClient.js 258 KB

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