rtcEngine.min.js 268 KB

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