adapter.js 191 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.adapter = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /*
  3. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by a BSD-style license
  6. * that can be found in the LICENSE file in the root of the source
  7. * tree.
  8. */
  9. /* eslint-env node */
  10. 'use strict';
  11. var SDPUtils = require('sdp');
  12. function writeMediaSection(transceiver, caps, type, stream, dtlsRole) {
  13. var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
  14. // Map ICE parameters (ufrag, pwd) to SDP.
  15. sdp += SDPUtils.writeIceParameters(
  16. transceiver.iceGatherer.getLocalParameters());
  17. // Map DTLS parameters to SDP.
  18. sdp += SDPUtils.writeDtlsParameters(
  19. transceiver.dtlsTransport.getLocalParameters(),
  20. type === 'offer' ? 'actpass' : dtlsRole || 'active');
  21. sdp += 'a=mid:' + transceiver.mid + '\r\n';
  22. if (transceiver.direction) {
  23. sdp += 'a=' + transceiver.direction + '\r\n';
  24. } else if (transceiver.rtpSender && transceiver.rtpReceiver) {
  25. sdp += 'a=sendrecv\r\n';
  26. } else if (transceiver.rtpSender) {
  27. sdp += 'a=sendonly\r\n';
  28. } else if (transceiver.rtpReceiver) {
  29. sdp += 'a=recvonly\r\n';
  30. } else {
  31. sdp += 'a=inactive\r\n';
  32. }
  33. if (transceiver.rtpSender) {
  34. // spec.
  35. var msid = 'msid:' + stream.id + ' ' +
  36. transceiver.rtpSender.track.id + '\r\n';
  37. sdp += 'a=' + msid;
  38. // for Chrome.
  39. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  40. ' ' + msid;
  41. if (transceiver.sendEncodingParameters[0].rtx) {
  42. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  43. ' ' + msid;
  44. sdp += 'a=ssrc-group:FID ' +
  45. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  46. transceiver.sendEncodingParameters[0].rtx.ssrc +
  47. '\r\n';
  48. }
  49. }
  50. // FIXME: this should be written by writeRtpDescription.
  51. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  52. ' cname:' + SDPUtils.localCName + '\r\n';
  53. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  54. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  55. ' cname:' + SDPUtils.localCName + '\r\n';
  56. }
  57. return sdp;
  58. }
  59. // Edge does not like
  60. // 1) stun: filtered after 14393 unless ?transport=udp is present
  61. // 2) turn: that does not have all of turn:host:port?transport=udp
  62. // 3) turn: with ipv6 addresses
  63. // 4) turn: occurring muliple times
  64. function filterIceServers(iceServers, edgeVersion) {
  65. var hasTurn = false;
  66. iceServers = JSON.parse(JSON.stringify(iceServers));
  67. return iceServers.filter(function(server) {
  68. if (server && (server.urls || server.url)) {
  69. var urls = server.urls || server.url;
  70. if (server.url && !server.urls) {
  71. console.warn('RTCIceServer.url is deprecated! Use urls instead.');
  72. }
  73. var isString = typeof urls === 'string';
  74. if (isString) {
  75. urls = [urls];
  76. }
  77. urls = urls.filter(function(url) {
  78. var validTurn = url.indexOf('turn:') === 0 &&
  79. url.indexOf('transport=udp') !== -1 &&
  80. url.indexOf('turn:[') === -1 &&
  81. !hasTurn;
  82. if (validTurn) {
  83. hasTurn = true;
  84. return true;
  85. }
  86. return url.indexOf('stun:') === 0 && edgeVersion >= 14393 &&
  87. url.indexOf('?transport=udp') === -1;
  88. });
  89. delete server.url;
  90. server.urls = isString ? urls[0] : urls;
  91. return !!urls.length;
  92. }
  93. return false;
  94. });
  95. }
  96. // Determines the intersection of local and remote capabilities.
  97. function getCommonCapabilities(localCapabilities, remoteCapabilities) {
  98. var commonCapabilities = {
  99. codecs: [],
  100. headerExtensions: [],
  101. fecMechanisms: []
  102. };
  103. var findCodecByPayloadType = function(pt, codecs) {
  104. pt = parseInt(pt, 10);
  105. for (var i = 0; i < codecs.length; i++) {
  106. if (codecs[i].payloadType === pt ||
  107. codecs[i].preferredPayloadType === pt) {
  108. return codecs[i];
  109. }
  110. }
  111. };
  112. var rtxCapabilityMatches = function(lRtx, rRtx, lCodecs, rCodecs) {
  113. var lCodec = findCodecByPayloadType(lRtx.parameters.apt, lCodecs);
  114. var rCodec = findCodecByPayloadType(rRtx.parameters.apt, rCodecs);
  115. return lCodec && rCodec &&
  116. lCodec.name.toLowerCase() === rCodec.name.toLowerCase();
  117. };
  118. localCapabilities.codecs.forEach(function(lCodec) {
  119. for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
  120. var rCodec = remoteCapabilities.codecs[i];
  121. if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
  122. lCodec.clockRate === rCodec.clockRate) {
  123. if (lCodec.name.toLowerCase() === 'rtx' &&
  124. lCodec.parameters && rCodec.parameters.apt) {
  125. // for RTX we need to find the local rtx that has a apt
  126. // which points to the same local codec as the remote one.
  127. if (!rtxCapabilityMatches(lCodec, rCodec,
  128. localCapabilities.codecs, remoteCapabilities.codecs)) {
  129. continue;
  130. }
  131. }
  132. rCodec = JSON.parse(JSON.stringify(rCodec)); // deepcopy
  133. // number of channels is the highest common number of channels
  134. rCodec.numChannels = Math.min(lCodec.numChannels,
  135. rCodec.numChannels);
  136. // push rCodec so we reply with offerer payload type
  137. commonCapabilities.codecs.push(rCodec);
  138. // determine common feedback mechanisms
  139. rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
  140. for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
  141. if (lCodec.rtcpFeedback[j].type === fb.type &&
  142. lCodec.rtcpFeedback[j].parameter === fb.parameter) {
  143. return true;
  144. }
  145. }
  146. return false;
  147. });
  148. // FIXME: also need to determine .parameters
  149. // see https://github.com/openpeer/ortc/issues/569
  150. break;
  151. }
  152. }
  153. });
  154. localCapabilities.headerExtensions.forEach(function(lHeaderExtension) {
  155. for (var i = 0; i < remoteCapabilities.headerExtensions.length;
  156. i++) {
  157. var rHeaderExtension = remoteCapabilities.headerExtensions[i];
  158. if (lHeaderExtension.uri === rHeaderExtension.uri) {
  159. commonCapabilities.headerExtensions.push(rHeaderExtension);
  160. break;
  161. }
  162. }
  163. });
  164. // FIXME: fecMechanisms
  165. return commonCapabilities;
  166. }
  167. // is action=setLocalDescription with type allowed in signalingState
  168. function isActionAllowedInSignalingState(action, type, signalingState) {
  169. return {
  170. offer: {
  171. setLocalDescription: ['stable', 'have-local-offer'],
  172. setRemoteDescription: ['stable', 'have-remote-offer']
  173. },
  174. answer: {
  175. setLocalDescription: ['have-remote-offer', 'have-local-pranswer'],
  176. setRemoteDescription: ['have-local-offer', 'have-remote-pranswer']
  177. }
  178. }[type][action].indexOf(signalingState) !== -1;
  179. }
  180. function maybeAddCandidate(iceTransport, candidate) {
  181. // Edge's internal representation adds some fields therefore
  182. // not all fieldѕ are taken into account.
  183. var alreadyAdded = iceTransport.getRemoteCandidates()
  184. .find(function(remoteCandidate) {
  185. return candidate.foundation === remoteCandidate.foundation &&
  186. candidate.ip === remoteCandidate.ip &&
  187. candidate.port === remoteCandidate.port &&
  188. candidate.priority === remoteCandidate.priority &&
  189. candidate.protocol === remoteCandidate.protocol &&
  190. candidate.type === remoteCandidate.type;
  191. });
  192. if (!alreadyAdded) {
  193. iceTransport.addRemoteCandidate(candidate);
  194. }
  195. return !alreadyAdded;
  196. }
  197. module.exports = function(window, edgeVersion) {
  198. var RTCPeerConnection = function(config) {
  199. var self = this;
  200. var _eventTarget = document.createDocumentFragment();
  201. ['addEventListener', 'removeEventListener', 'dispatchEvent']
  202. .forEach(function(method) {
  203. self[method] = _eventTarget[method].bind(_eventTarget);
  204. });
  205. this.onicecandidate = null;
  206. this.onaddstream = null;
  207. this.ontrack = null;
  208. this.onremovestream = null;
  209. this.onsignalingstatechange = null;
  210. this.oniceconnectionstatechange = null;
  211. this.onicegatheringstatechange = null;
  212. this.onnegotiationneeded = null;
  213. this.ondatachannel = null;
  214. this.canTrickleIceCandidates = null;
  215. this.needNegotiation = false;
  216. this.localStreams = [];
  217. this.remoteStreams = [];
  218. this.localDescription = null;
  219. this.remoteDescription = null;
  220. this.signalingState = 'stable';
  221. this.iceConnectionState = 'new';
  222. this.iceGatheringState = 'new';
  223. config = JSON.parse(JSON.stringify(config || {}));
  224. this.usingBundle = config.bundlePolicy === 'max-bundle';
  225. if (config.rtcpMuxPolicy === 'negotiate') {
  226. var e = new Error('rtcpMuxPolicy \'negotiate\' is not supported');
  227. e.name = 'NotSupportedError';
  228. throw(e);
  229. } else if (!config.rtcpMuxPolicy) {
  230. config.rtcpMuxPolicy = 'require';
  231. }
  232. switch (config.iceTransportPolicy) {
  233. case 'all':
  234. case 'relay':
  235. break;
  236. default:
  237. config.iceTransportPolicy = 'all';
  238. break;
  239. }
  240. switch (config.bundlePolicy) {
  241. case 'balanced':
  242. case 'max-compat':
  243. case 'max-bundle':
  244. break;
  245. default:
  246. config.bundlePolicy = 'balanced';
  247. break;
  248. }
  249. config.iceServers = filterIceServers(config.iceServers || [], edgeVersion);
  250. this._iceGatherers = [];
  251. if (config.iceCandidatePoolSize) {
  252. for (var i = config.iceCandidatePoolSize; i > 0; i--) {
  253. this._iceGatherers = new window.RTCIceGatherer({
  254. iceServers: config.iceServers,
  255. gatherPolicy: config.iceTransportPolicy
  256. });
  257. }
  258. } else {
  259. config.iceCandidatePoolSize = 0;
  260. }
  261. this._config = config;
  262. // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
  263. // everything that is needed to describe a SDP m-line.
  264. this.transceivers = [];
  265. this._sdpSessionId = SDPUtils.generateSessionId();
  266. this._sdpSessionVersion = 0;
  267. this._dtlsRole = undefined; // role for a=setup to use in answers.
  268. };
  269. RTCPeerConnection.prototype._emitGatheringStateChange = function() {
  270. var event = new Event('icegatheringstatechange');
  271. this.dispatchEvent(event);
  272. if (typeof this.onicegatheringstatechange === 'function') {
  273. this.onicegatheringstatechange(event);
  274. }
  275. };
  276. RTCPeerConnection.prototype.getConfiguration = function() {
  277. return this._config;
  278. };
  279. RTCPeerConnection.prototype.getLocalStreams = function() {
  280. return this.localStreams;
  281. };
  282. RTCPeerConnection.prototype.getRemoteStreams = function() {
  283. return this.remoteStreams;
  284. };
  285. // internal helper to create a transceiver object.
  286. // (whih is not yet the same as the WebRTC 1.0 transceiver)
  287. RTCPeerConnection.prototype._createTransceiver = function(kind) {
  288. var hasBundleTransport = this.transceivers.length > 0;
  289. var transceiver = {
  290. track: null,
  291. iceGatherer: null,
  292. iceTransport: null,
  293. dtlsTransport: null,
  294. localCapabilities: null,
  295. remoteCapabilities: null,
  296. rtpSender: null,
  297. rtpReceiver: null,
  298. kind: kind,
  299. mid: null,
  300. sendEncodingParameters: null,
  301. recvEncodingParameters: null,
  302. stream: null,
  303. wantReceive: true
  304. };
  305. if (this.usingBundle && hasBundleTransport) {
  306. transceiver.iceTransport = this.transceivers[0].iceTransport;
  307. transceiver.dtlsTransport = this.transceivers[0].dtlsTransport;
  308. } else {
  309. var transports = this._createIceAndDtlsTransports();
  310. transceiver.iceTransport = transports.iceTransport;
  311. transceiver.dtlsTransport = transports.dtlsTransport;
  312. }
  313. this.transceivers.push(transceiver);
  314. return transceiver;
  315. };
  316. RTCPeerConnection.prototype.addTrack = function(track, stream) {
  317. var transceiver;
  318. for (var i = 0; i < this.transceivers.length; i++) {
  319. if (!this.transceivers[i].track &&
  320. this.transceivers[i].kind === track.kind) {
  321. transceiver = this.transceivers[i];
  322. }
  323. }
  324. if (!transceiver) {
  325. transceiver = this._createTransceiver(track.kind);
  326. }
  327. this._maybeFireNegotiationNeeded();
  328. if (this.localStreams.indexOf(stream) === -1) {
  329. this.localStreams.push(stream);
  330. }
  331. transceiver.track = track;
  332. transceiver.stream = stream;
  333. transceiver.rtpSender = new window.RTCRtpSender(track,
  334. transceiver.dtlsTransport);
  335. return transceiver.rtpSender;
  336. };
  337. RTCPeerConnection.prototype.addStream = function(stream) {
  338. var self = this;
  339. if (edgeVersion >= 15025) {
  340. stream.getTracks().forEach(function(track) {
  341. self.addTrack(track, stream);
  342. });
  343. } else {
  344. // Clone is necessary for local demos mostly, attaching directly
  345. // to two different senders does not work (build 10547).
  346. // Fixed in 15025 (or earlier)
  347. var clonedStream = stream.clone();
  348. stream.getTracks().forEach(function(track, idx) {
  349. var clonedTrack = clonedStream.getTracks()[idx];
  350. track.addEventListener('enabled', function(event) {
  351. clonedTrack.enabled = event.enabled;
  352. });
  353. });
  354. clonedStream.getTracks().forEach(function(track) {
  355. self.addTrack(track, clonedStream);
  356. });
  357. }
  358. };
  359. RTCPeerConnection.prototype.removeStream = function(stream) {
  360. var idx = this.localStreams.indexOf(stream);
  361. if (idx > -1) {
  362. this.localStreams.splice(idx, 1);
  363. this._maybeFireNegotiationNeeded();
  364. }
  365. };
  366. RTCPeerConnection.prototype.getSenders = function() {
  367. return this.transceivers.filter(function(transceiver) {
  368. return !!transceiver.rtpSender;
  369. })
  370. .map(function(transceiver) {
  371. return transceiver.rtpSender;
  372. });
  373. };
  374. RTCPeerConnection.prototype.getReceivers = function() {
  375. return this.transceivers.filter(function(transceiver) {
  376. return !!transceiver.rtpReceiver;
  377. })
  378. .map(function(transceiver) {
  379. return transceiver.rtpReceiver;
  380. });
  381. };
  382. RTCPeerConnection.prototype._createIceGatherer = function(sdpMLineIndex,
  383. usingBundle) {
  384. var self = this;
  385. if (usingBundle && sdpMLineIndex > 0) {
  386. return this.transceivers[0].iceGatherer;
  387. } else if (this._iceGatherers.length) {
  388. return this._iceGatherers.shift();
  389. }
  390. var iceGatherer = new window.RTCIceGatherer({
  391. iceServers: this._config.iceServers,
  392. gatherPolicy: this._config.iceTransportPolicy
  393. });
  394. Object.defineProperty(iceGatherer, 'state',
  395. {value: 'new', writable: true}
  396. );
  397. this.transceivers[sdpMLineIndex].candidates = [];
  398. this.transceivers[sdpMLineIndex].bufferCandidates = function(event) {
  399. var end = !event.candidate || Object.keys(event.candidate).length === 0;
  400. // polyfill since RTCIceGatherer.state is not implemented in
  401. // Edge 10547 yet.
  402. iceGatherer.state = end ? 'completed' : 'gathering';
  403. if (self.transceivers[sdpMLineIndex].candidates !== null) {
  404. self.transceivers[sdpMLineIndex].candidates.push(event.candidate);
  405. }
  406. };
  407. iceGatherer.addEventListener('localcandidate',
  408. this.transceivers[sdpMLineIndex].bufferCandidates);
  409. return iceGatherer;
  410. };
  411. // start gathering from an RTCIceGatherer.
  412. RTCPeerConnection.prototype._gather = function(mid, sdpMLineIndex) {
  413. var self = this;
  414. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  415. if (iceGatherer.onlocalcandidate) {
  416. return;
  417. }
  418. var candidates = this.transceivers[sdpMLineIndex].candidates;
  419. this.transceivers[sdpMLineIndex].candidates = null;
  420. iceGatherer.removeEventListener('localcandidate',
  421. this.transceivers[sdpMLineIndex].bufferCandidates);
  422. iceGatherer.onlocalcandidate = function(evt) {
  423. if (self.usingBundle && sdpMLineIndex > 0) {
  424. // if we know that we use bundle we can drop candidates with
  425. // ѕdpMLineIndex > 0. If we don't do this then our state gets
  426. // confused since we dispose the extra ice gatherer.
  427. return;
  428. }
  429. var event = new Event('icecandidate');
  430. event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex};
  431. var cand = evt.candidate;
  432. // Edge emits an empty object for RTCIceCandidateComplete‥
  433. var end = !cand || Object.keys(cand).length === 0;
  434. if (end) {
  435. // polyfill since RTCIceGatherer.state is not implemented in
  436. // Edge 10547 yet.
  437. if (iceGatherer.state === 'new' || iceGatherer.state === 'gathering') {
  438. iceGatherer.state = 'completed';
  439. }
  440. } else {
  441. if (iceGatherer.state === 'new') {
  442. iceGatherer.state = 'gathering';
  443. }
  444. // RTCIceCandidate doesn't have a component, needs to be added
  445. cand.component = 1;
  446. event.candidate.candidate = SDPUtils.writeCandidate(cand);
  447. }
  448. // update local description.
  449. var sections = SDPUtils.splitSections(self.localDescription.sdp);
  450. if (!end) {
  451. sections[event.candidate.sdpMLineIndex + 1] +=
  452. 'a=' + event.candidate.candidate + '\r\n';
  453. } else {
  454. sections[event.candidate.sdpMLineIndex + 1] +=
  455. 'a=end-of-candidates\r\n';
  456. }
  457. self.localDescription.sdp = sections.join('');
  458. var complete = self.transceivers.every(function(transceiver) {
  459. return transceiver.iceGatherer &&
  460. transceiver.iceGatherer.state === 'completed';
  461. });
  462. if (self.iceGatheringState !== 'gathering') {
  463. self.iceGatheringState = 'gathering';
  464. self._emitGatheringStateChange();
  465. }
  466. // Emit candidate. Also emit null candidate when all gatherers are
  467. // complete.
  468. if (!end) {
  469. self.dispatchEvent(event);
  470. if (typeof self.onicecandidate === 'function') {
  471. self.onicecandidate(event);
  472. }
  473. }
  474. if (complete) {
  475. self.dispatchEvent(new Event('icecandidate'));
  476. if (typeof self.onicecandidate === 'function') {
  477. self.onicecandidate(new Event('icecandidate'));
  478. }
  479. self.iceGatheringState = 'complete';
  480. self._emitGatheringStateChange();
  481. }
  482. };
  483. // emit already gathered candidates.
  484. window.setTimeout(function() {
  485. candidates.forEach(function(candidate) {
  486. var e = new Event('RTCIceGatherEvent');
  487. e.candidate = candidate;
  488. iceGatherer.onlocalcandidate(e);
  489. });
  490. }, 0);
  491. };
  492. // Create ICE transport and DTLS transport.
  493. RTCPeerConnection.prototype._createIceAndDtlsTransports = function() {
  494. var self = this;
  495. var iceTransport = new window.RTCIceTransport(null);
  496. iceTransport.onicestatechange = function() {
  497. self._updateConnectionState();
  498. };
  499. var dtlsTransport = new window.RTCDtlsTransport(iceTransport);
  500. dtlsTransport.ondtlsstatechange = function() {
  501. self._updateConnectionState();
  502. };
  503. dtlsTransport.onerror = function() {
  504. // onerror does not set state to failed by itself.
  505. Object.defineProperty(dtlsTransport, 'state',
  506. {value: 'failed', writable: true});
  507. self._updateConnectionState();
  508. };
  509. return {
  510. iceTransport: iceTransport,
  511. dtlsTransport: dtlsTransport
  512. };
  513. };
  514. // Destroy ICE gatherer, ICE transport and DTLS transport.
  515. // Without triggering the callbacks.
  516. RTCPeerConnection.prototype._disposeIceAndDtlsTransports = function(
  517. sdpMLineIndex) {
  518. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  519. if (iceGatherer) {
  520. delete iceGatherer.onlocalcandidate;
  521. delete this.transceivers[sdpMLineIndex].iceGatherer;
  522. }
  523. var iceTransport = this.transceivers[sdpMLineIndex].iceTransport;
  524. if (iceTransport) {
  525. delete iceTransport.onicestatechange;
  526. delete this.transceivers[sdpMLineIndex].iceTransport;
  527. }
  528. var dtlsTransport = this.transceivers[sdpMLineIndex].dtlsTransport;
  529. if (dtlsTransport) {
  530. delete dtlsTransport.ondtlsstatechange;
  531. delete dtlsTransport.onerror;
  532. delete this.transceivers[sdpMLineIndex].dtlsTransport;
  533. }
  534. };
  535. // Start the RTP Sender and Receiver for a transceiver.
  536. RTCPeerConnection.prototype._transceive = function(transceiver,
  537. send, recv) {
  538. var params = getCommonCapabilities(transceiver.localCapabilities,
  539. transceiver.remoteCapabilities);
  540. if (send && transceiver.rtpSender) {
  541. params.encodings = transceiver.sendEncodingParameters;
  542. params.rtcp = {
  543. cname: SDPUtils.localCName,
  544. compound: transceiver.rtcpParameters.compound
  545. };
  546. if (transceiver.recvEncodingParameters.length) {
  547. params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
  548. }
  549. transceiver.rtpSender.send(params);
  550. }
  551. if (recv && transceiver.rtpReceiver && params.codecs.length > 0) {
  552. // remove RTX field in Edge 14942
  553. if (transceiver.kind === 'video'
  554. && transceiver.recvEncodingParameters
  555. && edgeVersion < 15019) {
  556. transceiver.recvEncodingParameters.forEach(function(p) {
  557. delete p.rtx;
  558. });
  559. }
  560. params.encodings = transceiver.recvEncodingParameters;
  561. params.rtcp = {
  562. cname: transceiver.rtcpParameters.cname,
  563. compound: transceiver.rtcpParameters.compound
  564. };
  565. if (transceiver.sendEncodingParameters.length) {
  566. params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
  567. }
  568. transceiver.rtpReceiver.receive(params);
  569. }
  570. };
  571. RTCPeerConnection.prototype.setLocalDescription = function(description) {
  572. var self = this;
  573. var args = arguments;
  574. if (!isActionAllowedInSignalingState('setLocalDescription',
  575. description.type, this.signalingState)) {
  576. return new Promise(function(resolve, reject) {
  577. var e = new Error('Can not set local ' + description.type +
  578. ' in state ' + self.signalingState);
  579. e.name = 'InvalidStateError';
  580. if (args.length > 2 && typeof args[2] === 'function') {
  581. args[2].apply(null, [e]);
  582. }
  583. reject(e);
  584. });
  585. }
  586. var sections;
  587. var sessionpart;
  588. if (description.type === 'offer') {
  589. // VERY limited support for SDP munging. Limited to:
  590. // * changing the order of codecs
  591. sections = SDPUtils.splitSections(description.sdp);
  592. sessionpart = sections.shift();
  593. sections.forEach(function(mediaSection, sdpMLineIndex) {
  594. var caps = SDPUtils.parseRtpParameters(mediaSection);
  595. self.transceivers[sdpMLineIndex].localCapabilities = caps;
  596. });
  597. this.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  598. self._gather(transceiver.mid, sdpMLineIndex);
  599. });
  600. } else if (description.type === 'answer') {
  601. sections = SDPUtils.splitSections(self.remoteDescription.sdp);
  602. sessionpart = sections.shift();
  603. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  604. 'a=ice-lite').length > 0;
  605. sections.forEach(function(mediaSection, sdpMLineIndex) {
  606. var transceiver = self.transceivers[sdpMLineIndex];
  607. var iceGatherer = transceiver.iceGatherer;
  608. var iceTransport = transceiver.iceTransport;
  609. var dtlsTransport = transceiver.dtlsTransport;
  610. var localCapabilities = transceiver.localCapabilities;
  611. var remoteCapabilities = transceiver.remoteCapabilities;
  612. // treat bundle-only as not-rejected.
  613. var rejected = SDPUtils.isRejected(mediaSection) &&
  614. !SDPUtils.matchPrefix(mediaSection, 'a=bundle-only').length === 1;
  615. if (!rejected && !transceiver.isDatachannel) {
  616. var remoteIceParameters = SDPUtils.getIceParameters(
  617. mediaSection, sessionpart);
  618. var remoteDtlsParameters = SDPUtils.getDtlsParameters(
  619. mediaSection, sessionpart);
  620. if (isIceLite) {
  621. remoteDtlsParameters.role = 'server';
  622. }
  623. if (!self.usingBundle || sdpMLineIndex === 0) {
  624. self._gather(transceiver.mid, sdpMLineIndex);
  625. if (iceTransport.state === 'new') {
  626. iceTransport.start(iceGatherer, remoteIceParameters,
  627. isIceLite ? 'controlling' : 'controlled');
  628. }
  629. if (dtlsTransport.state === 'new') {
  630. dtlsTransport.start(remoteDtlsParameters);
  631. }
  632. }
  633. // Calculate intersection of capabilities.
  634. var params = getCommonCapabilities(localCapabilities,
  635. remoteCapabilities);
  636. // Start the RTCRtpSender. The RTCRtpReceiver for this
  637. // transceiver has already been started in setRemoteDescription.
  638. self._transceive(transceiver,
  639. params.codecs.length > 0,
  640. false);
  641. }
  642. });
  643. }
  644. this.localDescription = {
  645. type: description.type,
  646. sdp: description.sdp
  647. };
  648. switch (description.type) {
  649. case 'offer':
  650. this._updateSignalingState('have-local-offer');
  651. break;
  652. case 'answer':
  653. this._updateSignalingState('stable');
  654. break;
  655. default:
  656. throw new TypeError('unsupported type "' + description.type +
  657. '"');
  658. }
  659. // If a success callback was provided, emit ICE candidates after it
  660. // has been executed. Otherwise, emit callback after the Promise is
  661. // resolved.
  662. var cb = arguments.length > 1 && typeof arguments[1] === 'function' &&
  663. arguments[1];
  664. return new Promise(function(resolve) {
  665. if (cb) {
  666. cb.apply(null);
  667. }
  668. resolve();
  669. });
  670. };
  671. RTCPeerConnection.prototype.setRemoteDescription = function(description) {
  672. var self = this;
  673. var args = arguments;
  674. if (!isActionAllowedInSignalingState('setRemoteDescription',
  675. description.type, this.signalingState)) {
  676. return new Promise(function(resolve, reject) {
  677. var e = new Error('Can not set remote ' + description.type +
  678. ' in state ' + self.signalingState);
  679. e.name = 'InvalidStateError';
  680. if (args.length > 2 && typeof args[2] === 'function') {
  681. args[2].apply(null, [e]);
  682. }
  683. reject(e);
  684. });
  685. }
  686. var streams = {};
  687. this.remoteStreams.forEach(function(stream) {
  688. streams[stream.id] = stream;
  689. });
  690. var receiverList = [];
  691. var sections = SDPUtils.splitSections(description.sdp);
  692. var sessionpart = sections.shift();
  693. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  694. 'a=ice-lite').length > 0;
  695. var usingBundle = SDPUtils.matchPrefix(sessionpart,
  696. 'a=group:BUNDLE ').length > 0;
  697. this.usingBundle = usingBundle;
  698. var iceOptions = SDPUtils.matchPrefix(sessionpart,
  699. 'a=ice-options:')[0];
  700. if (iceOptions) {
  701. this.canTrickleIceCandidates = iceOptions.substr(14).split(' ')
  702. .indexOf('trickle') >= 0;
  703. } else {
  704. this.canTrickleIceCandidates = false;
  705. }
  706. sections.forEach(function(mediaSection, sdpMLineIndex) {
  707. var lines = SDPUtils.splitLines(mediaSection);
  708. var kind = SDPUtils.getKind(mediaSection);
  709. // treat bundle-only as not-rejected.
  710. var rejected = SDPUtils.isRejected(mediaSection) &&
  711. !SDPUtils.matchPrefix(mediaSection, 'a=bundle-only').length === 1;
  712. var protocol = lines[0].substr(2).split(' ')[2];
  713. var direction = SDPUtils.getDirection(mediaSection, sessionpart);
  714. var remoteMsid = SDPUtils.parseMsid(mediaSection);
  715. var mid = SDPUtils.getMid(mediaSection) || SDPUtils.generateIdentifier();
  716. // Reject datachannels which are not implemented yet.
  717. if (kind === 'application' && protocol === 'DTLS/SCTP') {
  718. self.transceivers[sdpMLineIndex] = {
  719. mid: mid,
  720. isDatachannel: true
  721. };
  722. return;
  723. }
  724. var transceiver;
  725. var iceGatherer;
  726. var iceTransport;
  727. var dtlsTransport;
  728. var rtpReceiver;
  729. var sendEncodingParameters;
  730. var recvEncodingParameters;
  731. var localCapabilities;
  732. var track;
  733. // FIXME: ensure the mediaSection has rtcp-mux set.
  734. var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection);
  735. var remoteIceParameters;
  736. var remoteDtlsParameters;
  737. if (!rejected) {
  738. remoteIceParameters = SDPUtils.getIceParameters(mediaSection,
  739. sessionpart);
  740. remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection,
  741. sessionpart);
  742. remoteDtlsParameters.role = 'client';
  743. }
  744. recvEncodingParameters =
  745. SDPUtils.parseRtpEncodingParameters(mediaSection);
  746. var rtcpParameters = SDPUtils.parseRtcpParameters(mediaSection);
  747. var isComplete = SDPUtils.matchPrefix(mediaSection,
  748. 'a=end-of-candidates', sessionpart).length > 0;
  749. var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
  750. .map(function(cand) {
  751. return SDPUtils.parseCandidate(cand);
  752. })
  753. .filter(function(cand) {
  754. return cand.component === 1;
  755. });
  756. // Check if we can use BUNDLE and dispose transports.
  757. if ((description.type === 'offer' || description.type === 'answer') &&
  758. !rejected && usingBundle && sdpMLineIndex > 0 &&
  759. self.transceivers[sdpMLineIndex]) {
  760. self._disposeIceAndDtlsTransports(sdpMLineIndex);
  761. self.transceivers[sdpMLineIndex].iceGatherer =
  762. self.transceivers[0].iceGatherer;
  763. self.transceivers[sdpMLineIndex].iceTransport =
  764. self.transceivers[0].iceTransport;
  765. self.transceivers[sdpMLineIndex].dtlsTransport =
  766. self.transceivers[0].dtlsTransport;
  767. if (self.transceivers[sdpMLineIndex].rtpSender) {
  768. self.transceivers[sdpMLineIndex].rtpSender.setTransport(
  769. self.transceivers[0].dtlsTransport);
  770. }
  771. if (self.transceivers[sdpMLineIndex].rtpReceiver) {
  772. self.transceivers[sdpMLineIndex].rtpReceiver.setTransport(
  773. self.transceivers[0].dtlsTransport);
  774. }
  775. }
  776. if (description.type === 'offer' && !rejected) {
  777. transceiver = self.transceivers[sdpMLineIndex] ||
  778. self._createTransceiver(kind);
  779. transceiver.mid = mid;
  780. if (!transceiver.iceGatherer) {
  781. transceiver.iceGatherer = self._createIceGatherer(sdpMLineIndex,
  782. usingBundle);
  783. }
  784. if (cands.length && transceiver.iceTransport.state === 'new') {
  785. if (isComplete && (!usingBundle || sdpMLineIndex === 0)) {
  786. transceiver.iceTransport.setRemoteCandidates(cands);
  787. } else {
  788. cands.forEach(function(candidate) {
  789. maybeAddCandidate(transceiver.iceTransport, candidate);
  790. });
  791. }
  792. }
  793. localCapabilities = window.RTCRtpReceiver.getCapabilities(kind);
  794. // filter RTX until additional stuff needed for RTX is implemented
  795. // in adapter.js
  796. if (edgeVersion < 15019) {
  797. localCapabilities.codecs = localCapabilities.codecs.filter(
  798. function(codec) {
  799. return codec.name !== 'rtx';
  800. });
  801. }
  802. sendEncodingParameters = transceiver.sendEncodingParameters || [{
  803. ssrc: (2 * sdpMLineIndex + 2) * 1001
  804. }];
  805. var isNewTrack = false;
  806. if (direction === 'sendrecv' || direction === 'sendonly') {
  807. isNewTrack = !transceiver.rtpReceiver;
  808. rtpReceiver = transceiver.rtpReceiver ||
  809. new window.RTCRtpReceiver(transceiver.dtlsTransport, kind);
  810. if (isNewTrack) {
  811. var stream;
  812. track = rtpReceiver.track;
  813. // FIXME: does not work with Plan B.
  814. if (remoteMsid) {
  815. if (!streams[remoteMsid.stream]) {
  816. streams[remoteMsid.stream] = new window.MediaStream();
  817. Object.defineProperty(streams[remoteMsid.stream], 'id', {
  818. get: function() {
  819. return remoteMsid.stream;
  820. }
  821. });
  822. }
  823. Object.defineProperty(track, 'id', {
  824. get: function() {
  825. return remoteMsid.track;
  826. }
  827. });
  828. stream = streams[remoteMsid.stream];
  829. } else {
  830. if (!streams["default"]) {
  831. streams["default"] = new window.MediaStream();
  832. }
  833. stream = streams["default"];
  834. }
  835. stream.addTrack(track);
  836. receiverList.push([track, rtpReceiver, stream]);
  837. }
  838. }
  839. transceiver.localCapabilities = localCapabilities;
  840. transceiver.remoteCapabilities = remoteCapabilities;
  841. transceiver.rtpReceiver = rtpReceiver;
  842. transceiver.rtcpParameters = rtcpParameters;
  843. transceiver.sendEncodingParameters = sendEncodingParameters;
  844. transceiver.recvEncodingParameters = recvEncodingParameters;
  845. // Start the RTCRtpReceiver now. The RTPSender is started in
  846. // setLocalDescription.
  847. self._transceive(self.transceivers[sdpMLineIndex],
  848. false,
  849. isNewTrack);
  850. } else if (description.type === 'answer' && !rejected) {
  851. transceiver = self.transceivers[sdpMLineIndex];
  852. iceGatherer = transceiver.iceGatherer;
  853. iceTransport = transceiver.iceTransport;
  854. dtlsTransport = transceiver.dtlsTransport;
  855. rtpReceiver = transceiver.rtpReceiver;
  856. sendEncodingParameters = transceiver.sendEncodingParameters;
  857. localCapabilities = transceiver.localCapabilities;
  858. self.transceivers[sdpMLineIndex].recvEncodingParameters =
  859. recvEncodingParameters;
  860. self.transceivers[sdpMLineIndex].remoteCapabilities =
  861. remoteCapabilities;
  862. self.transceivers[sdpMLineIndex].rtcpParameters = rtcpParameters;
  863. if (cands.length && iceTransport.state === 'new') {
  864. if ((isIceLite || isComplete) &&
  865. (!usingBundle || sdpMLineIndex === 0)) {
  866. iceTransport.setRemoteCandidates(cands);
  867. } else {
  868. cands.forEach(function(candidate) {
  869. maybeAddCandidate(transceiver.iceTransport, candidate);
  870. });
  871. }
  872. }
  873. if (!usingBundle || sdpMLineIndex === 0) {
  874. if (iceTransport.state === 'new') {
  875. iceTransport.start(iceGatherer, remoteIceParameters,
  876. 'controlling');
  877. }
  878. if (dtlsTransport.state === 'new') {
  879. dtlsTransport.start(remoteDtlsParameters);
  880. }
  881. }
  882. self._transceive(transceiver,
  883. direction === 'sendrecv' || direction === 'recvonly',
  884. direction === 'sendrecv' || direction === 'sendonly');
  885. if (rtpReceiver &&
  886. (direction === 'sendrecv' || direction === 'sendonly')) {
  887. track = rtpReceiver.track;
  888. if (remoteMsid) {
  889. if (!streams[remoteMsid.stream]) {
  890. streams[remoteMsid.stream] = new window.MediaStream();
  891. }
  892. streams[remoteMsid.stream].addTrack(track);
  893. receiverList.push([track, rtpReceiver, streams[remoteMsid.stream]]);
  894. } else {
  895. if (!streams["default"]) {
  896. streams["default"] = new window.MediaStream();
  897. }
  898. streams["default"].addTrack(track);
  899. receiverList.push([track, rtpReceiver, streams["default"]]);
  900. }
  901. } else {
  902. // FIXME: actually the receiver should be created later.
  903. delete transceiver.rtpReceiver;
  904. }
  905. }
  906. });
  907. if (this._dtlsRole === undefined) {
  908. this._dtlsRole = description.type === 'offer' ? 'active' : 'passive';
  909. }
  910. this.remoteDescription = {
  911. type: description.type,
  912. sdp: description.sdp
  913. };
  914. switch (description.type) {
  915. case 'offer':
  916. this._updateSignalingState('have-remote-offer');
  917. break;
  918. case 'answer':
  919. this._updateSignalingState('stable');
  920. break;
  921. default:
  922. throw new TypeError('unsupported type "' + description.type +
  923. '"');
  924. }
  925. Object.keys(streams).forEach(function(sid) {
  926. var stream = streams[sid];
  927. if (stream.getTracks().length) {
  928. if (self.remoteStreams.indexOf(stream) === -1) {
  929. self.remoteStreams.push(stream);
  930. var event = new Event('addstream');
  931. event.stream = stream;
  932. window.setTimeout(function() {
  933. self.dispatchEvent(event);
  934. if (typeof self.onaddstream === 'function') {
  935. self.onaddstream(event);
  936. }
  937. });
  938. }
  939. receiverList.forEach(function(item) {
  940. var track = item[0];
  941. var receiver = item[1];
  942. if (stream.id !== item[2].id) {
  943. return;
  944. }
  945. var trackEvent = new Event('track');
  946. trackEvent.track = track;
  947. trackEvent.receiver = receiver;
  948. trackEvent.transceiver = {receiver: receiver};
  949. trackEvent.streams = [stream];
  950. window.setTimeout(function() {
  951. self.dispatchEvent(trackEvent);
  952. if (typeof self.ontrack === 'function') {
  953. self.ontrack(trackEvent);
  954. }
  955. });
  956. });
  957. }
  958. });
  959. // check whether addIceCandidate({}) was called within four seconds after
  960. // setRemoteDescription.
  961. window.setTimeout(function() {
  962. if (!(self && self.transceivers)) {
  963. return;
  964. }
  965. self.transceivers.forEach(function(transceiver) {
  966. if (transceiver.iceTransport &&
  967. transceiver.iceTransport.state === 'new' &&
  968. transceiver.iceTransport.getRemoteCandidates().length > 0) {
  969. console.warn('Timeout for addRemoteCandidate. Consider sending ' +
  970. 'an end-of-candidates notification');
  971. transceiver.iceTransport.addRemoteCandidate({});
  972. }
  973. });
  974. }, 4000);
  975. return new Promise(function(resolve) {
  976. if (args.length > 1 && typeof args[1] === 'function') {
  977. args[1].apply(null);
  978. }
  979. resolve();
  980. });
  981. };
  982. RTCPeerConnection.prototype.close = function() {
  983. this.transceivers.forEach(function(transceiver) {
  984. /* not yet
  985. if (transceiver.iceGatherer) {
  986. transceiver.iceGatherer.close();
  987. }
  988. */
  989. if (transceiver.iceTransport) {
  990. transceiver.iceTransport.stop();
  991. }
  992. if (transceiver.dtlsTransport) {
  993. transceiver.dtlsTransport.stop();
  994. }
  995. if (transceiver.rtpSender) {
  996. transceiver.rtpSender.stop();
  997. }
  998. if (transceiver.rtpReceiver) {
  999. transceiver.rtpReceiver.stop();
  1000. }
  1001. });
  1002. // FIXME: clean up tracks, local streams, remote streams, etc
  1003. this._updateSignalingState('closed');
  1004. };
  1005. // Update the signaling state.
  1006. RTCPeerConnection.prototype._updateSignalingState = function(newState) {
  1007. this.signalingState = newState;
  1008. var event = new Event('signalingstatechange');
  1009. this.dispatchEvent(event);
  1010. if (typeof this.onsignalingstatechange === 'function') {
  1011. this.onsignalingstatechange(event);
  1012. }
  1013. };
  1014. // Determine whether to fire the negotiationneeded event.
  1015. RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() {
  1016. var self = this;
  1017. if (this.signalingState !== 'stable' || this.needNegotiation === true) {
  1018. return;
  1019. }
  1020. this.needNegotiation = true;
  1021. window.setTimeout(function() {
  1022. if (self.needNegotiation === false) {
  1023. return;
  1024. }
  1025. self.needNegotiation = false;
  1026. var event = new Event('negotiationneeded');
  1027. self.dispatchEvent(event);
  1028. if (typeof self.onnegotiationneeded === 'function') {
  1029. self.onnegotiationneeded(event);
  1030. }
  1031. }, 0);
  1032. };
  1033. // Update the connection state.
  1034. RTCPeerConnection.prototype._updateConnectionState = function() {
  1035. var newState;
  1036. var states = {
  1037. 'new': 0,
  1038. closed: 0,
  1039. connecting: 0,
  1040. checking: 0,
  1041. connected: 0,
  1042. completed: 0,
  1043. disconnected: 0,
  1044. failed: 0
  1045. };
  1046. this.transceivers.forEach(function(transceiver) {
  1047. states[transceiver.iceTransport.state]++;
  1048. states[transceiver.dtlsTransport.state]++;
  1049. });
  1050. // ICETransport.completed and connected are the same for this purpose.
  1051. states.connected += states.completed;
  1052. newState = 'new';
  1053. if (states.failed > 0) {
  1054. newState = 'failed';
  1055. } else if (states.connecting > 0 || states.checking > 0) {
  1056. newState = 'connecting';
  1057. } else if (states.disconnected > 0) {
  1058. newState = 'disconnected';
  1059. } else if (states['new'] > 0) {
  1060. newState = 'new';
  1061. } else if (states.connected > 0 || states.completed > 0) {
  1062. newState = 'connected';
  1063. }
  1064. if (newState !== this.iceConnectionState) {
  1065. this.iceConnectionState = newState;
  1066. var event = new Event('iceconnectionstatechange');
  1067. this.dispatchEvent(event);
  1068. if (typeof this.oniceconnectionstatechange === 'function') {
  1069. this.oniceconnectionstatechange(event);
  1070. }
  1071. }
  1072. };
  1073. RTCPeerConnection.prototype.createOffer = function() {
  1074. var self = this;
  1075. var args = arguments;
  1076. var offerOptions;
  1077. if (arguments.length === 1 && typeof arguments[0] !== 'function') {
  1078. offerOptions = arguments[0];
  1079. } else if (arguments.length === 3) {
  1080. offerOptions = arguments[2];
  1081. }
  1082. var numAudioTracks = this.transceivers.filter(function(t) {
  1083. return t.kind === 'audio';
  1084. }).length;
  1085. var numVideoTracks = this.transceivers.filter(function(t) {
  1086. return t.kind === 'video';
  1087. }).length;
  1088. // Determine number of audio and video tracks we need to send/recv.
  1089. if (offerOptions) {
  1090. // Reject Chrome legacy constraints.
  1091. if (offerOptions.mandatory || offerOptions.optional) {
  1092. throw new TypeError(
  1093. 'Legacy mandatory/optional constraints not supported.');
  1094. }
  1095. if (offerOptions.offerToReceiveAudio !== undefined) {
  1096. if (offerOptions.offerToReceiveAudio === true) {
  1097. numAudioTracks = 1;
  1098. } else if (offerOptions.offerToReceiveAudio === false) {
  1099. numAudioTracks = 0;
  1100. } else {
  1101. numAudioTracks = offerOptions.offerToReceiveAudio;
  1102. }
  1103. }
  1104. if (offerOptions.offerToReceiveVideo !== undefined) {
  1105. if (offerOptions.offerToReceiveVideo === true) {
  1106. numVideoTracks = 1;
  1107. } else if (offerOptions.offerToReceiveVideo === false) {
  1108. numVideoTracks = 0;
  1109. } else {
  1110. numVideoTracks = offerOptions.offerToReceiveVideo;
  1111. }
  1112. }
  1113. }
  1114. this.transceivers.forEach(function(transceiver) {
  1115. if (transceiver.kind === 'audio') {
  1116. numAudioTracks--;
  1117. if (numAudioTracks < 0) {
  1118. transceiver.wantReceive = false;
  1119. }
  1120. } else if (transceiver.kind === 'video') {
  1121. numVideoTracks--;
  1122. if (numVideoTracks < 0) {
  1123. transceiver.wantReceive = false;
  1124. }
  1125. }
  1126. });
  1127. // Create M-lines for recvonly streams.
  1128. while (numAudioTracks > 0 || numVideoTracks > 0) {
  1129. if (numAudioTracks > 0) {
  1130. this._createTransceiver('audio');
  1131. numAudioTracks--;
  1132. }
  1133. if (numVideoTracks > 0) {
  1134. this._createTransceiver('video');
  1135. numVideoTracks--;
  1136. }
  1137. }
  1138. var sdp = SDPUtils.writeSessionBoilerplate(this._sdpSessionId,
  1139. this._sdpSessionVersion++);
  1140. this.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  1141. // For each track, create an ice gatherer, ice transport,
  1142. // dtls transport, potentially rtpsender and rtpreceiver.
  1143. var track = transceiver.track;
  1144. var kind = transceiver.kind;
  1145. var mid = SDPUtils.generateIdentifier();
  1146. transceiver.mid = mid;
  1147. if (!transceiver.iceGatherer) {
  1148. transceiver.iceGatherer = self._createIceGatherer(sdpMLineIndex,
  1149. self.usingBundle);
  1150. }
  1151. var localCapabilities = window.RTCRtpSender.getCapabilities(kind);
  1152. // filter RTX until additional stuff needed for RTX is implemented
  1153. // in adapter.js
  1154. if (edgeVersion < 15019) {
  1155. localCapabilities.codecs = localCapabilities.codecs.filter(
  1156. function(codec) {
  1157. return codec.name !== 'rtx';
  1158. });
  1159. }
  1160. localCapabilities.codecs.forEach(function(codec) {
  1161. // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
  1162. // by adding level-asymmetry-allowed=1
  1163. if (codec.name === 'H264' &&
  1164. codec.parameters['level-asymmetry-allowed'] === undefined) {
  1165. codec.parameters['level-asymmetry-allowed'] = '1';
  1166. }
  1167. });
  1168. // generate an ssrc now, to be used later in rtpSender.send
  1169. var sendEncodingParameters = transceiver.sendEncodingParameters || [{
  1170. ssrc: (2 * sdpMLineIndex + 1) * 1001
  1171. }];
  1172. if (track) {
  1173. // add RTX
  1174. if (edgeVersion >= 15019 && kind === 'video' &&
  1175. !sendEncodingParameters[0].rtx) {
  1176. sendEncodingParameters[0].rtx = {
  1177. ssrc: sendEncodingParameters[0].ssrc + 1
  1178. };
  1179. }
  1180. }
  1181. if (transceiver.wantReceive) {
  1182. transceiver.rtpReceiver = new window.RTCRtpReceiver(
  1183. transceiver.dtlsTransport, kind);
  1184. }
  1185. transceiver.localCapabilities = localCapabilities;
  1186. transceiver.sendEncodingParameters = sendEncodingParameters;
  1187. });
  1188. // always offer BUNDLE and dispose on return if not supported.
  1189. if (this._config.bundlePolicy !== 'max-compat') {
  1190. sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) {
  1191. return t.mid;
  1192. }).join(' ') + '\r\n';
  1193. }
  1194. sdp += 'a=ice-options:trickle\r\n';
  1195. this.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  1196. sdp += writeMediaSection(transceiver, transceiver.localCapabilities,
  1197. 'offer', transceiver.stream, self._dtlsRole);
  1198. sdp += 'a=rtcp-rsize\r\n';
  1199. if (transceiver.iceGatherer && self.iceGatheringState !== 'new' &&
  1200. (sdpMLineIndex === 0 || !self.usingBundle)) {
  1201. transceiver.iceGatherer.getLocalCandidates().forEach(function(cand) {
  1202. cand.component = 1;
  1203. sdp += 'a=' + SDPUtils.writeCandidate(cand) + '\r\n';
  1204. });
  1205. if (transceiver.iceGatherer.state === 'completed') {
  1206. sdp += 'a=end-of-candidates\r\n';
  1207. }
  1208. }
  1209. });
  1210. var desc = new window.RTCSessionDescription({
  1211. type: 'offer',
  1212. sdp: sdp
  1213. });
  1214. return new Promise(function(resolve) {
  1215. if (args.length > 0 && typeof args[0] === 'function') {
  1216. args[0].apply(null, [desc]);
  1217. resolve();
  1218. return;
  1219. }
  1220. resolve(desc);
  1221. });
  1222. };
  1223. RTCPeerConnection.prototype.createAnswer = function() {
  1224. var self = this;
  1225. var args = arguments;
  1226. var sdp = SDPUtils.writeSessionBoilerplate(this._sdpSessionId,
  1227. this._sdpSessionVersion++);
  1228. if (this.usingBundle) {
  1229. sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) {
  1230. return t.mid;
  1231. }).join(' ') + '\r\n';
  1232. }
  1233. var mediaSectionsInOffer = SDPUtils.splitSections(
  1234. this.remoteDescription.sdp).length - 1;
  1235. this.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  1236. if (sdpMLineIndex + 1 > mediaSectionsInOffer) {
  1237. return;
  1238. }
  1239. if (transceiver.isDatachannel) {
  1240. sdp += 'm=application 0 DTLS/SCTP 5000\r\n' +
  1241. 'c=IN IP4 0.0.0.0\r\n' +
  1242. 'a=mid:' + transceiver.mid + '\r\n';
  1243. return;
  1244. }
  1245. // FIXME: look at direction.
  1246. if (transceiver.stream) {
  1247. var localTrack;
  1248. if (transceiver.kind === 'audio') {
  1249. localTrack = transceiver.stream.getAudioTracks()[0];
  1250. } else if (transceiver.kind === 'video') {
  1251. localTrack = transceiver.stream.getVideoTracks()[0];
  1252. }
  1253. if (localTrack) {
  1254. // add RTX
  1255. if (edgeVersion >= 15019 && transceiver.kind === 'video' &&
  1256. !transceiver.sendEncodingParameters[0].rtx) {
  1257. transceiver.sendEncodingParameters[0].rtx = {
  1258. ssrc: transceiver.sendEncodingParameters[0].ssrc + 1
  1259. };
  1260. }
  1261. }
  1262. }
  1263. // Calculate intersection of capabilities.
  1264. var commonCapabilities = getCommonCapabilities(
  1265. transceiver.localCapabilities,
  1266. transceiver.remoteCapabilities);
  1267. var hasRtx = commonCapabilities.codecs.filter(function(c) {
  1268. return c.name.toLowerCase() === 'rtx';
  1269. }).length;
  1270. if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
  1271. delete transceiver.sendEncodingParameters[0].rtx;
  1272. }
  1273. sdp += writeMediaSection(transceiver, commonCapabilities,
  1274. 'answer', transceiver.stream, self._dtlsRole);
  1275. if (transceiver.rtcpParameters &&
  1276. transceiver.rtcpParameters.reducedSize) {
  1277. sdp += 'a=rtcp-rsize\r\n';
  1278. }
  1279. });
  1280. var desc = new window.RTCSessionDescription({
  1281. type: 'answer',
  1282. sdp: sdp
  1283. });
  1284. return new Promise(function(resolve) {
  1285. if (args.length > 0 && typeof args[0] === 'function') {
  1286. args[0].apply(null, [desc]);
  1287. resolve();
  1288. return;
  1289. }
  1290. resolve(desc);
  1291. });
  1292. };
  1293. RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
  1294. var err;
  1295. var sections;
  1296. if (!candidate || candidate.candidate === '') {
  1297. for (var j = 0; j < this.transceivers.length; j++) {
  1298. if (this.transceivers[j].isDatachannel) {
  1299. continue;
  1300. }
  1301. this.transceivers[j].iceTransport.addRemoteCandidate({});
  1302. sections = SDPUtils.splitSections(this.remoteDescription.sdp);
  1303. sections[j + 1] += 'a=end-of-candidates\r\n';
  1304. this.remoteDescription.sdp = sections.join('');
  1305. if (this.usingBundle) {
  1306. break;
  1307. }
  1308. }
  1309. } else if (!(candidate.sdpMLineIndex !== undefined || candidate.sdpMid)) {
  1310. throw new TypeError('sdpMLineIndex or sdpMid required');
  1311. } else if (!this.remoteDescription) {
  1312. err = new Error('Can not add ICE candidate without ' +
  1313. 'a remote description');
  1314. err.name = 'InvalidStateError';
  1315. } else {
  1316. var sdpMLineIndex = candidate.sdpMLineIndex;
  1317. if (candidate.sdpMid) {
  1318. for (var i = 0; i < this.transceivers.length; i++) {
  1319. if (this.transceivers[i].mid === candidate.sdpMid) {
  1320. sdpMLineIndex = i;
  1321. break;
  1322. }
  1323. }
  1324. }
  1325. var transceiver = this.transceivers[sdpMLineIndex];
  1326. if (transceiver) {
  1327. if (transceiver.isDatachannel) {
  1328. return Promise.resolve();
  1329. }
  1330. var cand = Object.keys(candidate.candidate).length > 0 ?
  1331. SDPUtils.parseCandidate(candidate.candidate) : {};
  1332. // Ignore Chrome's invalid candidates since Edge does not like them.
  1333. if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
  1334. return Promise.resolve();
  1335. }
  1336. // Ignore RTCP candidates, we assume RTCP-MUX.
  1337. if (cand.component && cand.component !== 1) {
  1338. return Promise.resolve();
  1339. }
  1340. // when using bundle, avoid adding candidates to the wrong
  1341. // ice transport. And avoid adding candidates added in the SDP.
  1342. if (sdpMLineIndex === 0 || (sdpMLineIndex > 0 &&
  1343. transceiver.iceTransport !== this.transceivers[0].iceTransport)) {
  1344. if (!maybeAddCandidate(transceiver.iceTransport, cand)) {
  1345. err = new Error('Can not add ICE candidate');
  1346. err.name = 'OperationError';
  1347. }
  1348. }
  1349. if (!err) {
  1350. // update the remoteDescription.
  1351. var candidateString = candidate.candidate.trim();
  1352. if (candidateString.indexOf('a=') === 0) {
  1353. candidateString = candidateString.substr(2);
  1354. }
  1355. sections = SDPUtils.splitSections(this.remoteDescription.sdp);
  1356. sections[sdpMLineIndex + 1] += 'a=' +
  1357. (cand.type ? candidateString : 'end-of-candidates')
  1358. + '\r\n';
  1359. this.remoteDescription.sdp = sections.join('');
  1360. }
  1361. } else {
  1362. err = new Error('Can not add ICE candidate');
  1363. err.name = 'OperationError';
  1364. }
  1365. }
  1366. var args = arguments;
  1367. return new Promise(function(resolve, reject) {
  1368. if (err) {
  1369. if (args.length > 2 && typeof args[2] === 'function') {
  1370. args[2].apply(null, [err]);
  1371. }
  1372. reject(err);
  1373. } else {
  1374. if (args.length > 1 && typeof args[1] === 'function') {
  1375. args[1].apply(null);
  1376. }
  1377. resolve();
  1378. }
  1379. });
  1380. };
  1381. RTCPeerConnection.prototype.getStats = function() {
  1382. var promises = [];
  1383. this.transceivers.forEach(function(transceiver) {
  1384. ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
  1385. 'dtlsTransport'].forEach(function(method) {
  1386. if (transceiver[method]) {
  1387. promises.push(transceiver[method].getStats());
  1388. }
  1389. });
  1390. });
  1391. var cb = arguments.length > 1 && typeof arguments[1] === 'function' &&
  1392. arguments[1];
  1393. var fixStatsType = function(stat) {
  1394. return {
  1395. inboundrtp: 'inbound-rtp',
  1396. outboundrtp: 'outbound-rtp',
  1397. candidatepair: 'candidate-pair',
  1398. localcandidate: 'local-candidate',
  1399. remotecandidate: 'remote-candidate'
  1400. }[stat.type] || stat.type;
  1401. };
  1402. return new Promise(function(resolve) {
  1403. // shim getStats with maplike support
  1404. var results = new Map();
  1405. Promise.all(promises).then(function(res) {
  1406. res.forEach(function(result) {
  1407. Object.keys(result).forEach(function(id) {
  1408. result[id].type = fixStatsType(result[id]);
  1409. results.set(id, result[id]);
  1410. });
  1411. });
  1412. if (cb) {
  1413. cb.apply(null, results);
  1414. }
  1415. resolve(results);
  1416. });
  1417. });
  1418. };
  1419. return RTCPeerConnection;
  1420. };
  1421. },{"sdp":2}],2:[function(require,module,exports){
  1422. /* eslint-env node */
  1423. 'use strict';
  1424. // SDP helpers.
  1425. var SDPUtils = {};
  1426. // Generate an alphanumeric identifier for cname or mids.
  1427. // TODO: use UUIDs instead? https://gist.github.com/jed/982883
  1428. SDPUtils.generateIdentifier = function() {
  1429. return Math.random().toString(36).substr(2, 10);
  1430. };
  1431. // The RTCP CNAME used by all peerconnections from the same JS.
  1432. SDPUtils.localCName = SDPUtils.generateIdentifier();
  1433. // Splits SDP into lines, dealing with both CRLF and LF.
  1434. SDPUtils.splitLines = function(blob) {
  1435. return blob.trim().split('\n').map(function(line) {
  1436. return line.trim();
  1437. });
  1438. };
  1439. // Splits SDP into sessionpart and mediasections. Ensures CRLF.
  1440. SDPUtils.splitSections = function(blob) {
  1441. var parts = blob.split('\nm=');
  1442. return parts.map(function(part, index) {
  1443. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  1444. });
  1445. };
  1446. // Returns lines that start with a certain prefix.
  1447. SDPUtils.matchPrefix = function(blob, prefix) {
  1448. return SDPUtils.splitLines(blob).filter(function(line) {
  1449. return line.indexOf(prefix) === 0;
  1450. });
  1451. };
  1452. // Parses an ICE candidate line. Sample input:
  1453. // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
  1454. // rport 55996"
  1455. SDPUtils.parseCandidate = function(line) {
  1456. var parts;
  1457. // Parse both variants.
  1458. if (line.indexOf('a=candidate:') === 0) {
  1459. parts = line.substring(12).split(' ');
  1460. } else {
  1461. parts = line.substring(10).split(' ');
  1462. }
  1463. var candidate = {
  1464. foundation: parts[0],
  1465. component: parseInt(parts[1], 10),
  1466. protocol: parts[2].toLowerCase(),
  1467. priority: parseInt(parts[3], 10),
  1468. ip: parts[4],
  1469. port: parseInt(parts[5], 10),
  1470. // skip parts[6] == 'typ'
  1471. type: parts[7]
  1472. };
  1473. for (var i = 8; i < parts.length; i += 2) {
  1474. switch (parts[i]) {
  1475. case 'raddr':
  1476. candidate.relatedAddress = parts[i + 1];
  1477. break;
  1478. case 'rport':
  1479. candidate.relatedPort = parseInt(parts[i + 1], 10);
  1480. break;
  1481. case 'tcptype':
  1482. candidate.tcpType = parts[i + 1];
  1483. break;
  1484. case 'ufrag':
  1485. candidate.ufrag = parts[i + 1]; // for backward compability.
  1486. candidate.usernameFragment = parts[i + 1];
  1487. break;
  1488. default: // extension handling, in particular ufrag
  1489. candidate[parts[i]] = parts[i + 1];
  1490. break;
  1491. }
  1492. }
  1493. return candidate;
  1494. };
  1495. // Translates a candidate object into SDP candidate attribute.
  1496. SDPUtils.writeCandidate = function(candidate) {
  1497. var sdp = [];
  1498. sdp.push(candidate.foundation);
  1499. sdp.push(candidate.component);
  1500. sdp.push(candidate.protocol.toUpperCase());
  1501. sdp.push(candidate.priority);
  1502. sdp.push(candidate.ip);
  1503. sdp.push(candidate.port);
  1504. var type = candidate.type;
  1505. sdp.push('typ');
  1506. sdp.push(type);
  1507. if (type !== 'host' && candidate.relatedAddress &&
  1508. candidate.relatedPort) {
  1509. sdp.push('raddr');
  1510. sdp.push(candidate.relatedAddress); // was: relAddr
  1511. sdp.push('rport');
  1512. sdp.push(candidate.relatedPort); // was: relPort
  1513. }
  1514. if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
  1515. sdp.push('tcptype');
  1516. sdp.push(candidate.tcpType);
  1517. }
  1518. if (candidate.ufrag) {
  1519. sdp.push('ufrag');
  1520. sdp.push(candidate.ufrag);
  1521. }
  1522. return 'candidate:' + sdp.join(' ');
  1523. };
  1524. // Parses an ice-options line, returns an array of option tags.
  1525. // a=ice-options:foo bar
  1526. SDPUtils.parseIceOptions = function(line) {
  1527. return line.substr(14).split(' ');
  1528. }
  1529. // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
  1530. // a=rtpmap:111 opus/48000/2
  1531. SDPUtils.parseRtpMap = function(line) {
  1532. var parts = line.substr(9).split(' ');
  1533. var parsed = {
  1534. payloadType: parseInt(parts.shift(), 10) // was: id
  1535. };
  1536. parts = parts[0].split('/');
  1537. parsed.name = parts[0];
  1538. parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
  1539. // was: channels
  1540. parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
  1541. return parsed;
  1542. };
  1543. // Generate an a=rtpmap line from RTCRtpCodecCapability or
  1544. // RTCRtpCodecParameters.
  1545. SDPUtils.writeRtpMap = function(codec) {
  1546. var pt = codec.payloadType;
  1547. if (codec.preferredPayloadType !== undefined) {
  1548. pt = codec.preferredPayloadType;
  1549. }
  1550. return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
  1551. (codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n';
  1552. };
  1553. // Parses an a=extmap line (headerextension from RFC 5285). Sample input:
  1554. // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  1555. // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
  1556. SDPUtils.parseExtmap = function(line) {
  1557. var parts = line.substr(9).split(' ');
  1558. return {
  1559. id: parseInt(parts[0], 10),
  1560. direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
  1561. uri: parts[1]
  1562. };
  1563. };
  1564. // Generates a=extmap line from RTCRtpHeaderExtensionParameters or
  1565. // RTCRtpHeaderExtension.
  1566. SDPUtils.writeExtmap = function(headerExtension) {
  1567. return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
  1568. (headerExtension.direction && headerExtension.direction !== 'sendrecv'
  1569. ? '/' + headerExtension.direction
  1570. : '') +
  1571. ' ' + headerExtension.uri + '\r\n';
  1572. };
  1573. // Parses an ftmp line, returns dictionary. Sample input:
  1574. // a=fmtp:96 vbr=on;cng=on
  1575. // Also deals with vbr=on; cng=on
  1576. SDPUtils.parseFmtp = function(line) {
  1577. var parsed = {};
  1578. var kv;
  1579. var parts = line.substr(line.indexOf(' ') + 1).split(';');
  1580. for (var j = 0; j < parts.length; j++) {
  1581. kv = parts[j].trim().split('=');
  1582. parsed[kv[0].trim()] = kv[1];
  1583. }
  1584. return parsed;
  1585. };
  1586. // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
  1587. SDPUtils.writeFmtp = function(codec) {
  1588. var line = '';
  1589. var pt = codec.payloadType;
  1590. if (codec.preferredPayloadType !== undefined) {
  1591. pt = codec.preferredPayloadType;
  1592. }
  1593. if (codec.parameters && Object.keys(codec.parameters).length) {
  1594. var params = [];
  1595. Object.keys(codec.parameters).forEach(function(param) {
  1596. params.push(param + '=' + codec.parameters[param]);
  1597. });
  1598. line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
  1599. }
  1600. return line;
  1601. };
  1602. // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
  1603. // a=rtcp-fb:98 nack rpsi
  1604. SDPUtils.parseRtcpFb = function(line) {
  1605. var parts = line.substr(line.indexOf(' ') + 1).split(' ');
  1606. return {
  1607. type: parts.shift(),
  1608. parameter: parts.join(' ')
  1609. };
  1610. };
  1611. // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
  1612. SDPUtils.writeRtcpFb = function(codec) {
  1613. var lines = '';
  1614. var pt = codec.payloadType;
  1615. if (codec.preferredPayloadType !== undefined) {
  1616. pt = codec.preferredPayloadType;
  1617. }
  1618. if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
  1619. // FIXME: special handling for trr-int?
  1620. codec.rtcpFeedback.forEach(function(fb) {
  1621. lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
  1622. (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
  1623. '\r\n';
  1624. });
  1625. }
  1626. return lines;
  1627. };
  1628. // Parses an RFC 5576 ssrc media attribute. Sample input:
  1629. // a=ssrc:3735928559 cname:something
  1630. SDPUtils.parseSsrcMedia = function(line) {
  1631. var sp = line.indexOf(' ');
  1632. var parts = {
  1633. ssrc: parseInt(line.substr(7, sp - 7), 10)
  1634. };
  1635. var colon = line.indexOf(':', sp);
  1636. if (colon > -1) {
  1637. parts.attribute = line.substr(sp + 1, colon - sp - 1);
  1638. parts.value = line.substr(colon + 1);
  1639. } else {
  1640. parts.attribute = line.substr(sp + 1);
  1641. }
  1642. return parts;
  1643. };
  1644. // Extracts the MID (RFC 5888) from a media section.
  1645. // returns the MID or undefined if no mid line was found.
  1646. SDPUtils.getMid = function(mediaSection) {
  1647. var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
  1648. if (mid) {
  1649. return mid.substr(6);
  1650. }
  1651. }
  1652. SDPUtils.parseFingerprint = function(line) {
  1653. var parts = line.substr(14).split(' ');
  1654. return {
  1655. algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.
  1656. value: parts[1]
  1657. };
  1658. };
  1659. // Extracts DTLS parameters from SDP media section or sessionpart.
  1660. // FIXME: for consistency with other functions this should only
  1661. // get the fingerprint line as input. See also getIceParameters.
  1662. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
  1663. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
  1664. 'a=fingerprint:');
  1665. // Note: a=setup line is ignored since we use the 'auto' role.
  1666. // Note2: 'algorithm' is not case sensitive except in Edge.
  1667. return {
  1668. role: 'auto',
  1669. fingerprints: lines.map(SDPUtils.parseFingerprint)
  1670. };
  1671. };
  1672. // Serializes DTLS parameters to SDP.
  1673. SDPUtils.writeDtlsParameters = function(params, setupType) {
  1674. var sdp = 'a=setup:' + setupType + '\r\n';
  1675. params.fingerprints.forEach(function(fp) {
  1676. sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
  1677. });
  1678. return sdp;
  1679. };
  1680. // Parses ICE information from SDP media section or sessionpart.
  1681. // FIXME: for consistency with other functions this should only
  1682. // get the ice-ufrag and ice-pwd lines as input.
  1683. SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
  1684. var lines = SDPUtils.splitLines(mediaSection);
  1685. // Search in session part, too.
  1686. lines = lines.concat(SDPUtils.splitLines(sessionpart));
  1687. var iceParameters = {
  1688. usernameFragment: lines.filter(function(line) {
  1689. return line.indexOf('a=ice-ufrag:') === 0;
  1690. })[0].substr(12),
  1691. password: lines.filter(function(line) {
  1692. return line.indexOf('a=ice-pwd:') === 0;
  1693. })[0].substr(10)
  1694. };
  1695. return iceParameters;
  1696. };
  1697. // Serializes ICE parameters to SDP.
  1698. SDPUtils.writeIceParameters = function(params) {
  1699. return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
  1700. 'a=ice-pwd:' + params.password + '\r\n';
  1701. };
  1702. // Parses the SDP media section and returns RTCRtpParameters.
  1703. SDPUtils.parseRtpParameters = function(mediaSection) {
  1704. var description = {
  1705. codecs: [],
  1706. headerExtensions: [],
  1707. fecMechanisms: [],
  1708. rtcp: []
  1709. };
  1710. var lines = SDPUtils.splitLines(mediaSection);
  1711. var mline = lines[0].split(' ');
  1712. for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
  1713. var pt = mline[i];
  1714. var rtpmapline = SDPUtils.matchPrefix(
  1715. mediaSection, 'a=rtpmap:' + pt + ' ')[0];
  1716. if (rtpmapline) {
  1717. var codec = SDPUtils.parseRtpMap(rtpmapline);
  1718. var fmtps = SDPUtils.matchPrefix(
  1719. mediaSection, 'a=fmtp:' + pt + ' ');
  1720. // Only the first a=fmtp:<pt> is considered.
  1721. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
  1722. codec.rtcpFeedback = SDPUtils.matchPrefix(
  1723. mediaSection, 'a=rtcp-fb:' + pt + ' ')
  1724. .map(SDPUtils.parseRtcpFb);
  1725. description.codecs.push(codec);
  1726. // parse FEC mechanisms from rtpmap lines.
  1727. switch (codec.name.toUpperCase()) {
  1728. case 'RED':
  1729. case 'ULPFEC':
  1730. description.fecMechanisms.push(codec.name.toUpperCase());
  1731. break;
  1732. default: // only RED and ULPFEC are recognized as FEC mechanisms.
  1733. break;
  1734. }
  1735. }
  1736. }
  1737. SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
  1738. description.headerExtensions.push(SDPUtils.parseExtmap(line));
  1739. });
  1740. // FIXME: parse rtcp.
  1741. return description;
  1742. };
  1743. // Generates parts of the SDP media section describing the capabilities /
  1744. // parameters.
  1745. SDPUtils.writeRtpDescription = function(kind, caps) {
  1746. var sdp = '';
  1747. // Build the mline.
  1748. sdp += 'm=' + kind + ' ';
  1749. sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
  1750. sdp += ' UDP/TLS/RTP/SAVPF ';
  1751. sdp += caps.codecs.map(function(codec) {
  1752. if (codec.preferredPayloadType !== undefined) {
  1753. return codec.preferredPayloadType;
  1754. }
  1755. return codec.payloadType;
  1756. }).join(' ') + '\r\n';
  1757. sdp += 'c=IN IP4 0.0.0.0\r\n';
  1758. sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
  1759. // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
  1760. caps.codecs.forEach(function(codec) {
  1761. sdp += SDPUtils.writeRtpMap(codec);
  1762. sdp += SDPUtils.writeFmtp(codec);
  1763. sdp += SDPUtils.writeRtcpFb(codec);
  1764. });
  1765. var maxptime = 0;
  1766. caps.codecs.forEach(function(codec) {
  1767. if (codec.maxptime > maxptime) {
  1768. maxptime = codec.maxptime;
  1769. }
  1770. });
  1771. if (maxptime > 0) {
  1772. sdp += 'a=maxptime:' + maxptime + '\r\n';
  1773. }
  1774. sdp += 'a=rtcp-mux\r\n';
  1775. caps.headerExtensions.forEach(function(extension) {
  1776. sdp += SDPUtils.writeExtmap(extension);
  1777. });
  1778. // FIXME: write fecMechanisms.
  1779. return sdp;
  1780. };
  1781. // Parses the SDP media section and returns an array of
  1782. // RTCRtpEncodingParameters.
  1783. SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
  1784. var encodingParameters = [];
  1785. var description = SDPUtils.parseRtpParameters(mediaSection);
  1786. var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
  1787. var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
  1788. // filter a=ssrc:... cname:, ignore PlanB-msid
  1789. var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  1790. .map(function(line) {
  1791. return SDPUtils.parseSsrcMedia(line);
  1792. })
  1793. .filter(function(parts) {
  1794. return parts.attribute === 'cname';
  1795. });
  1796. var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
  1797. var secondarySsrc;
  1798. var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
  1799. .map(function(line) {
  1800. var parts = line.split(' ');
  1801. parts.shift();
  1802. return parts.map(function(part) {
  1803. return parseInt(part, 10);
  1804. });
  1805. });
  1806. if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
  1807. secondarySsrc = flows[0][1];
  1808. }
  1809. description.codecs.forEach(function(codec) {
  1810. if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
  1811. var encParam = {
  1812. ssrc: primarySsrc,
  1813. codecPayloadType: parseInt(codec.parameters.apt, 10),
  1814. rtx: {
  1815. ssrc: secondarySsrc
  1816. }
  1817. };
  1818. encodingParameters.push(encParam);
  1819. if (hasRed) {
  1820. encParam = JSON.parse(JSON.stringify(encParam));
  1821. encParam.fec = {
  1822. ssrc: secondarySsrc,
  1823. mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
  1824. };
  1825. encodingParameters.push(encParam);
  1826. }
  1827. }
  1828. });
  1829. if (encodingParameters.length === 0 && primarySsrc) {
  1830. encodingParameters.push({
  1831. ssrc: primarySsrc
  1832. });
  1833. }
  1834. // we support both b=AS and b=TIAS but interpret AS as TIAS.
  1835. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
  1836. if (bandwidth.length) {
  1837. if (bandwidth[0].indexOf('b=TIAS:') === 0) {
  1838. bandwidth = parseInt(bandwidth[0].substr(7), 10);
  1839. } else if (bandwidth[0].indexOf('b=AS:') === 0) {
  1840. // use formula from JSEP to convert b=AS to TIAS value.
  1841. bandwidth = parseInt(bandwidth[0].substr(5), 10) * 1000 * 0.95
  1842. - (50 * 40 * 8);
  1843. } else {
  1844. bandwidth = undefined;
  1845. }
  1846. encodingParameters.forEach(function(params) {
  1847. params.maxBitrate = bandwidth;
  1848. });
  1849. }
  1850. return encodingParameters;
  1851. };
  1852. // parses http://draft.ortc.org/#rtcrtcpparameters*
  1853. SDPUtils.parseRtcpParameters = function(mediaSection) {
  1854. var rtcpParameters = {};
  1855. var cname;
  1856. // Gets the first SSRC. Note that with RTX there might be multiple
  1857. // SSRCs.
  1858. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  1859. .map(function(line) {
  1860. return SDPUtils.parseSsrcMedia(line);
  1861. })
  1862. .filter(function(obj) {
  1863. return obj.attribute === 'cname';
  1864. })[0];
  1865. if (remoteSsrc) {
  1866. rtcpParameters.cname = remoteSsrc.value;
  1867. rtcpParameters.ssrc = remoteSsrc.ssrc;
  1868. }
  1869. // Edge uses the compound attribute instead of reducedSize
  1870. // compound is !reducedSize
  1871. var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
  1872. rtcpParameters.reducedSize = rsize.length > 0;
  1873. rtcpParameters.compound = rsize.length === 0;
  1874. // parses the rtcp-mux attrіbute.
  1875. // Note that Edge does not support unmuxed RTCP.
  1876. var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
  1877. rtcpParameters.mux = mux.length > 0;
  1878. return rtcpParameters;
  1879. };
  1880. // parses either a=msid: or a=ssrc:... msid lines and returns
  1881. // the id of the MediaStream and MediaStreamTrack.
  1882. SDPUtils.parseMsid = function(mediaSection) {
  1883. var parts;
  1884. var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
  1885. if (spec.length === 1) {
  1886. parts = spec[0].substr(7).split(' ');
  1887. return {stream: parts[0], track: parts[1]};
  1888. }
  1889. var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  1890. .map(function(line) {
  1891. return SDPUtils.parseSsrcMedia(line);
  1892. })
  1893. .filter(function(parts) {
  1894. return parts.attribute === 'msid';
  1895. });
  1896. if (planB.length > 0) {
  1897. parts = planB[0].value.split(' ');
  1898. return {stream: parts[0], track: parts[1]};
  1899. }
  1900. };
  1901. // Generate a session ID for SDP.
  1902. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
  1903. // recommends using a cryptographically random +ve 64-bit value
  1904. // but right now this should be acceptable and within the right range
  1905. SDPUtils.generateSessionId = function() {
  1906. return Math.random().toString().substr(2, 21);
  1907. };
  1908. // Write boilder plate for start of SDP
  1909. // sessId argument is optional - if not supplied it will
  1910. // be generated randomly
  1911. // sessVersion is optional and defaults to 2
  1912. SDPUtils.writeSessionBoilerplate = function(sessId, sessVer) {
  1913. var sessionId;
  1914. var version = sessVer !== undefined ? sessVer : 2;
  1915. if (sessId) {
  1916. sessionId = sessId;
  1917. } else {
  1918. sessionId = SDPUtils.generateSessionId();
  1919. }
  1920. // FIXME: sess-id should be an NTP timestamp.
  1921. return 'v=0\r\n' +
  1922. 'o=thisisadapterortc ' + sessionId + ' ' + version + ' IN IP4 127.0.0.1\r\n' +
  1923. 's=-\r\n' +
  1924. 't=0 0\r\n';
  1925. };
  1926. SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
  1927. var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
  1928. // Map ICE parameters (ufrag, pwd) to SDP.
  1929. sdp += SDPUtils.writeIceParameters(
  1930. transceiver.iceGatherer.getLocalParameters());
  1931. // Map DTLS parameters to SDP.
  1932. sdp += SDPUtils.writeDtlsParameters(
  1933. transceiver.dtlsTransport.getLocalParameters(),
  1934. type === 'offer' ? 'actpass' : 'active');
  1935. sdp += 'a=mid:' + transceiver.mid + '\r\n';
  1936. if (transceiver.direction) {
  1937. sdp += 'a=' + transceiver.direction + '\r\n';
  1938. } else if (transceiver.rtpSender && transceiver.rtpReceiver) {
  1939. sdp += 'a=sendrecv\r\n';
  1940. } else if (transceiver.rtpSender) {
  1941. sdp += 'a=sendonly\r\n';
  1942. } else if (transceiver.rtpReceiver) {
  1943. sdp += 'a=recvonly\r\n';
  1944. } else {
  1945. sdp += 'a=inactive\r\n';
  1946. }
  1947. if (transceiver.rtpSender) {
  1948. // spec.
  1949. var msid = 'msid:' + stream.id + ' ' +
  1950. transceiver.rtpSender.track.id + '\r\n';
  1951. sdp += 'a=' + msid;
  1952. // for Chrome.
  1953. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  1954. ' ' + msid;
  1955. if (transceiver.sendEncodingParameters[0].rtx) {
  1956. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  1957. ' ' + msid;
  1958. sdp += 'a=ssrc-group:FID ' +
  1959. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  1960. transceiver.sendEncodingParameters[0].rtx.ssrc +
  1961. '\r\n';
  1962. }
  1963. }
  1964. // FIXME: this should be written by writeRtpDescription.
  1965. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  1966. ' cname:' + SDPUtils.localCName + '\r\n';
  1967. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  1968. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  1969. ' cname:' + SDPUtils.localCName + '\r\n';
  1970. }
  1971. return sdp;
  1972. };
  1973. // Gets the direction from the mediaSection or the sessionpart.
  1974. SDPUtils.getDirection = function(mediaSection, sessionpart) {
  1975. // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
  1976. var lines = SDPUtils.splitLines(mediaSection);
  1977. for (var i = 0; i < lines.length; i++) {
  1978. switch (lines[i]) {
  1979. case 'a=sendrecv':
  1980. case 'a=sendonly':
  1981. case 'a=recvonly':
  1982. case 'a=inactive':
  1983. return lines[i].substr(2);
  1984. default:
  1985. // FIXME: What should happen here?
  1986. }
  1987. }
  1988. if (sessionpart) {
  1989. return SDPUtils.getDirection(sessionpart);
  1990. }
  1991. return 'sendrecv';
  1992. };
  1993. SDPUtils.getKind = function(mediaSection) {
  1994. var lines = SDPUtils.splitLines(mediaSection);
  1995. var mline = lines[0].split(' ');
  1996. return mline[0].substr(2);
  1997. };
  1998. SDPUtils.isRejected = function(mediaSection) {
  1999. return mediaSection.split(' ', 2)[1] === '0';
  2000. };
  2001. SDPUtils.parseMLine = function(mediaSection) {
  2002. var lines = SDPUtils.splitLines(mediaSection);
  2003. var mline = lines[0].split(' ');
  2004. return {
  2005. kind: mline[0].substr(2),
  2006. port: parseInt(mline[1], 10),
  2007. protocol: mline[2],
  2008. fmt: mline.slice(3).join(' ')
  2009. };
  2010. };
  2011. // Expose public methods.
  2012. if (typeof module === 'object') {
  2013. module.exports = SDPUtils;
  2014. }
  2015. },{}],3:[function(require,module,exports){
  2016. (function (global){
  2017. /*
  2018. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  2019. *
  2020. * Use of this source code is governed by a BSD-style license
  2021. * that can be found in the LICENSE file in the root of the source
  2022. * tree.
  2023. */
  2024. /* eslint-env node */
  2025. 'use strict';
  2026. var adapterFactory = require('./adapter_factory.js');
  2027. module.exports = adapterFactory({window: global.window});
  2028. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2029. },{"./adapter_factory.js":4}],4:[function(require,module,exports){
  2030. /*
  2031. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  2032. *
  2033. * Use of this source code is governed by a BSD-style license
  2034. * that can be found in the LICENSE file in the root of the source
  2035. * tree.
  2036. */
  2037. /* eslint-env node */
  2038. 'use strict';
  2039. var utils = require('./utils');
  2040. // Shimming starts here.
  2041. module.exports = function(dependencies, opts) {
  2042. var window = dependencies && dependencies.window;
  2043. var options = {
  2044. shimChrome: true,
  2045. shimFirefox: true,
  2046. shimEdge: true,
  2047. shimSafari: true,
  2048. };
  2049. for (var key in opts) {
  2050. if (hasOwnProperty.call(opts, key)) {
  2051. options[key] = opts[key];
  2052. }
  2053. }
  2054. // Utils.
  2055. var logging = utils.log;
  2056. var browserDetails = utils.detectBrowser(window);
  2057. // Export to the adapter global object visible in the browser.
  2058. var adapter = {
  2059. browserDetails: browserDetails,
  2060. extractVersion: utils.extractVersion,
  2061. disableLog: utils.disableLog,
  2062. disableWarnings: utils.disableWarnings
  2063. };
  2064. // Uncomment the line below if you want logging to occur, including logging
  2065. // for the switch statement below. Can also be turned on in the browser via
  2066. // adapter.disableLog(false), but then logging from the switch statement below
  2067. // will not appear.
  2068. // require('./utils').disableLog(false);
  2069. // Browser shims.
  2070. var chromeShim = require('./chrome/chrome_shim') || null;
  2071. var edgeShim = require('./edge/edge_shim') || null;
  2072. var firefoxShim = require('./firefox/firefox_shim') || null;
  2073. var safariShim = require('./safari/safari_shim') || null;
  2074. var commonShim = require('./common_shim') || null;
  2075. // Shim browser if found.
  2076. switch (browserDetails.browser) {
  2077. case 'chrome':
  2078. if (!chromeShim || !chromeShim.shimPeerConnection ||
  2079. !options.shimChrome) {
  2080. logging('Chrome shim is not included in this adapter release.');
  2081. return adapter;
  2082. }
  2083. logging('adapter.js shimming chrome.');
  2084. // Export to the adapter global object visible in the browser.
  2085. adapter.browserShim = chromeShim;
  2086. commonShim.shimCreateObjectURL(window);
  2087. chromeShim.shimGetUserMedia(window);
  2088. chromeShim.shimMediaStream(window);
  2089. chromeShim.shimSourceObject(window);
  2090. chromeShim.shimPeerConnection(window);
  2091. chromeShim.shimOnTrack(window);
  2092. chromeShim.shimAddTrackRemoveTrack(window);
  2093. chromeShim.shimGetSendersWithDtmf(window);
  2094. commonShim.shimRTCIceCandidate(window);
  2095. break;
  2096. case 'firefox':
  2097. if (!firefoxShim || !firefoxShim.shimPeerConnection ||
  2098. !options.shimFirefox) {
  2099. logging('Firefox shim is not included in this adapter release.');
  2100. return adapter;
  2101. }
  2102. logging('adapter.js shimming firefox.');
  2103. // Export to the adapter global object visible in the browser.
  2104. adapter.browserShim = firefoxShim;
  2105. commonShim.shimCreateObjectURL(window);
  2106. firefoxShim.shimGetUserMedia(window);
  2107. firefoxShim.shimSourceObject(window);
  2108. firefoxShim.shimPeerConnection(window);
  2109. firefoxShim.shimOnTrack(window);
  2110. firefoxShim.shimRemoveStream(window);
  2111. commonShim.shimRTCIceCandidate(window);
  2112. break;
  2113. case 'edge':
  2114. if (!edgeShim || !edgeShim.shimPeerConnection || !options.shimEdge) {
  2115. logging('MS edge shim is not included in this adapter release.');
  2116. return adapter;
  2117. }
  2118. logging('adapter.js shimming edge.');
  2119. // Export to the adapter global object visible in the browser.
  2120. adapter.browserShim = edgeShim;
  2121. commonShim.shimCreateObjectURL(window);
  2122. edgeShim.shimGetUserMedia(window);
  2123. edgeShim.shimPeerConnection(window);
  2124. edgeShim.shimReplaceTrack(window);
  2125. // the edge shim implements the full RTCIceCandidate object.
  2126. break;
  2127. case 'safari':
  2128. if (!safariShim || !options.shimSafari) {
  2129. logging('Safari shim is not included in this adapter release.');
  2130. return adapter;
  2131. }
  2132. logging('adapter.js shimming safari.');
  2133. // Export to the adapter global object visible in the browser.
  2134. adapter.browserShim = safariShim;
  2135. commonShim.shimCreateObjectURL(window);
  2136. safariShim.shimRTCIceServerUrls(window);
  2137. safariShim.shimCallbacksAPI(window);
  2138. safariShim.shimLocalStreamsAPI(window);
  2139. safariShim.shimRemoteStreamsAPI(window);
  2140. safariShim.shimTrackEventTransceiver(window);
  2141. safariShim.shimGetUserMedia(window);
  2142. safariShim.shimCreateOfferLegacy(window);
  2143. commonShim.shimRTCIceCandidate(window);
  2144. break;
  2145. default:
  2146. logging('Unsupported browser!');
  2147. break;
  2148. }
  2149. return adapter;
  2150. };
  2151. },{"./chrome/chrome_shim":5,"./common_shim":7,"./edge/edge_shim":8,"./firefox/firefox_shim":10,"./safari/safari_shim":12,"./utils":13}],5:[function(require,module,exports){
  2152. /*
  2153. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  2154. *
  2155. * Use of this source code is governed by a BSD-style license
  2156. * that can be found in the LICENSE file in the root of the source
  2157. * tree.
  2158. */
  2159. /* eslint-env node */
  2160. 'use strict';
  2161. var utils = require('../utils.js');
  2162. var logging = utils.log;
  2163. var chromeShim = {
  2164. shimMediaStream: function(window) {
  2165. window.MediaStream = window.MediaStream || window.webkitMediaStream;
  2166. },
  2167. shimOnTrack: function(window) {
  2168. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  2169. window.RTCPeerConnection.prototype)) {
  2170. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  2171. get: function() {
  2172. return this._ontrack;
  2173. },
  2174. set: function(f) {
  2175. if (this._ontrack) {
  2176. this.removeEventListener('track', this._ontrack);
  2177. }
  2178. this.addEventListener('track', this._ontrack = f);
  2179. }
  2180. });
  2181. var origSetRemoteDescription =
  2182. window.RTCPeerConnection.prototype.setRemoteDescription;
  2183. window.RTCPeerConnection.prototype.setRemoteDescription = function() {
  2184. var pc = this;
  2185. if (!pc._ontrackpoly) {
  2186. pc._ontrackpoly = function(e) {
  2187. // onaddstream does not fire when a track is added to an existing
  2188. // stream. But stream.onaddtrack is implemented so we use that.
  2189. e.stream.addEventListener('addtrack', function(te) {
  2190. var receiver;
  2191. if (window.RTCPeerConnection.prototype.getReceivers) {
  2192. receiver = pc.getReceivers().find(function(r) {
  2193. return r.track && r.track.id === te.track.id;
  2194. });
  2195. } else {
  2196. receiver = {track: te.track};
  2197. }
  2198. var event = new Event('track');
  2199. event.track = te.track;
  2200. event.receiver = receiver;
  2201. event.transceiver = {receiver: receiver};
  2202. event.streams = [e.stream];
  2203. pc.dispatchEvent(event);
  2204. });
  2205. e.stream.getTracks().forEach(function(track) {
  2206. var receiver;
  2207. if (window.RTCPeerConnection.prototype.getReceivers) {
  2208. receiver = pc.getReceivers().find(function(r) {
  2209. return r.track && r.track.id === track.id;
  2210. });
  2211. } else {
  2212. receiver = {track: track};
  2213. }
  2214. var event = new Event('track');
  2215. event.track = track;
  2216. event.receiver = receiver;
  2217. event.transceiver = {receiver: receiver};
  2218. event.streams = [e.stream];
  2219. pc.dispatchEvent(event);
  2220. });
  2221. };
  2222. pc.addEventListener('addstream', pc._ontrackpoly);
  2223. }
  2224. return origSetRemoteDescription.apply(pc, arguments);
  2225. };
  2226. }
  2227. },
  2228. shimGetSendersWithDtmf: function(window) {
  2229. // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.
  2230. if (typeof window === 'object' && window.RTCPeerConnection &&
  2231. !('getSenders' in window.RTCPeerConnection.prototype) &&
  2232. 'createDTMFSender' in window.RTCPeerConnection.prototype) {
  2233. var shimSenderWithDtmf = function(pc, track) {
  2234. return {
  2235. track: track,
  2236. 'dtmf': function() {
  2237. if (this._dtmf === undefined) {
  2238. if (track.kind === 'audio') {
  2239. this._dtmf = pc.createDTMFSender(track);
  2240. } else {
  2241. this._dtmf = null;
  2242. }
  2243. }
  2244. return this._dtmf;
  2245. },
  2246. // get dtmf() {
  2247. // if (this._dtmf === undefined) {
  2248. // if (track.kind === 'audio') {
  2249. // this._dtmf = pc.createDTMFSender(track);
  2250. // } else {
  2251. // this._dtmf = null;
  2252. // }
  2253. // }
  2254. // return this._dtmf;
  2255. // },
  2256. _pc: pc
  2257. };
  2258. };
  2259. // augment addTrack when getSenders is not available.
  2260. if (!window.RTCPeerConnection.prototype.getSenders) {
  2261. window.RTCPeerConnection.prototype.getSenders = function() {
  2262. this._senders = this._senders || [];
  2263. return this._senders.slice(); // return a copy of the internal state.
  2264. };
  2265. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  2266. window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
  2267. var pc = this;
  2268. var sender = origAddTrack.apply(pc, arguments);
  2269. if (!sender) {
  2270. sender = shimSenderWithDtmf(pc, track);
  2271. pc._senders.push(sender);
  2272. }
  2273. return sender;
  2274. };
  2275. var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  2276. window.RTCPeerConnection.prototype.removeTrack = function(sender) {
  2277. var pc = this;
  2278. origRemoveTrack.apply(pc, arguments);
  2279. var idx = pc._senders.indexOf(sender);
  2280. if (idx !== -1) {
  2281. pc._senders.splice(idx, 1);
  2282. }
  2283. };
  2284. }
  2285. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  2286. window.RTCPeerConnection.prototype.addStream = function(stream) {
  2287. var pc = this;
  2288. pc._senders = pc._senders || [];
  2289. origAddStream.apply(pc, [stream]);
  2290. stream.getTracks().forEach(function(track) {
  2291. pc._senders.push(shimSenderWithDtmf(pc, track));
  2292. });
  2293. };
  2294. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  2295. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  2296. var pc = this;
  2297. pc._senders = pc._senders || [];
  2298. origRemoveStream.apply(pc, [stream]);
  2299. stream.getTracks().forEach(function(track) {
  2300. var sender = pc._senders.find(function(s) {
  2301. return s.track === track;
  2302. });
  2303. if (sender) {
  2304. pc._senders.splice(pc._senders.indexOf(sender), 1); // remove sender
  2305. }
  2306. });
  2307. };
  2308. } else if (typeof window === 'object' && window.RTCPeerConnection &&
  2309. 'getSenders' in window.RTCPeerConnection.prototype &&
  2310. 'createDTMFSender' in window.RTCPeerConnection.prototype &&
  2311. window.RTCRtpSender &&
  2312. !('dtmf' in window.RTCRtpSender.prototype)) {
  2313. var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  2314. window.RTCPeerConnection.prototype.getSenders = function() {
  2315. var pc = this;
  2316. var senders = origGetSenders.apply(pc, []);
  2317. senders.forEach(function(sender) {
  2318. sender._pc = pc;
  2319. });
  2320. return senders;
  2321. };
  2322. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  2323. get: function() {
  2324. if (this._dtmf === undefined) {
  2325. if (this.track.kind === 'audio') {
  2326. this._dtmf = this._pc.createDTMFSender(this.track);
  2327. } else {
  2328. this._dtmf = null;
  2329. }
  2330. }
  2331. return this._dtmf;
  2332. }
  2333. });
  2334. }
  2335. },
  2336. shimSourceObject: function(window) {
  2337. var URL = window && window.URL;
  2338. if (typeof window === 'object') {
  2339. if (window.HTMLMediaElement &&
  2340. !('srcObject' in window.HTMLMediaElement.prototype)) {
  2341. // Shim the srcObject property, once, when HTMLMediaElement is found.
  2342. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
  2343. get: function() {
  2344. return this._srcObject;
  2345. },
  2346. set: function(stream) {
  2347. var self = this;
  2348. // Use _srcObject as a private property for this shim
  2349. this._srcObject = stream;
  2350. if (this.src) {
  2351. URL.revokeObjectURL(this.src);
  2352. }
  2353. if (!stream) {
  2354. this.src = '';
  2355. return undefined;
  2356. }
  2357. this.src = URL.createObjectURL(stream);
  2358. // We need to recreate the blob url when a track is added or
  2359. // removed. Doing it manually since we want to avoid a recursion.
  2360. stream.addEventListener('addtrack', function() {
  2361. if (self.src) {
  2362. URL.revokeObjectURL(self.src);
  2363. }
  2364. self.src = URL.createObjectURL(stream);
  2365. });
  2366. stream.addEventListener('removetrack', function() {
  2367. if (self.src) {
  2368. URL.revokeObjectURL(self.src);
  2369. }
  2370. self.src = URL.createObjectURL(stream);
  2371. });
  2372. }
  2373. });
  2374. }
  2375. }
  2376. },
  2377. shimAddTrackRemoveTrack: function(window) {
  2378. var browserDetails = utils.detectBrowser(window);
  2379. // shim addTrack and removeTrack.
  2380. if (window.RTCPeerConnection.prototype.addTrack &&
  2381. browserDetails.version >= 64) {
  2382. return;
  2383. }
  2384. // also shim pc.getLocalStreams when addTrack is shimmed
  2385. // to return the original streams.
  2386. var origGetLocalStreams = window.RTCPeerConnection.prototype
  2387. .getLocalStreams;
  2388. window.RTCPeerConnection.prototype.getLocalStreams = function() {
  2389. var self = this;
  2390. var nativeStreams = origGetLocalStreams.apply(this);
  2391. self._reverseStreams = self._reverseStreams || {};
  2392. return nativeStreams.map(function(stream) {
  2393. return self._reverseStreams[stream.id];
  2394. });
  2395. };
  2396. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  2397. window.RTCPeerConnection.prototype.addStream = function(stream) {
  2398. var pc = this;
  2399. pc._streams = pc._streams || {};
  2400. pc._reverseStreams = pc._reverseStreams || {};
  2401. stream.getTracks().forEach(function(track) {
  2402. var alreadyExists = pc.getSenders().find(function(s) {
  2403. return s.track === track;
  2404. });
  2405. if (alreadyExists) {
  2406. throw new DOMException('Track already exists.',
  2407. 'InvalidAccessError');
  2408. }
  2409. });
  2410. // Add identity mapping for consistency with addTrack.
  2411. // Unless this is being used with a stream from addTrack.
  2412. if (!pc._reverseStreams[stream.id]) {
  2413. var newStream = new window.MediaStream(stream.getTracks());
  2414. pc._streams[stream.id] = newStream;
  2415. pc._reverseStreams[newStream.id] = stream;
  2416. stream = newStream;
  2417. }
  2418. origAddStream.apply(pc, [stream]);
  2419. };
  2420. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  2421. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  2422. var pc = this;
  2423. pc._streams = pc._streams || {};
  2424. pc._reverseStreams = pc._reverseStreams || {};
  2425. origRemoveStream.apply(pc, [(pc._streams[stream.id] || stream)]);
  2426. delete pc._reverseStreams[(pc._streams[stream.id] ?
  2427. pc._streams[stream.id].id : stream.id)];
  2428. delete pc._streams[stream.id];
  2429. };
  2430. window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
  2431. var pc = this;
  2432. if (pc.signalingState === 'closed') {
  2433. throw new DOMException(
  2434. 'The RTCPeerConnection\'s signalingState is \'closed\'.',
  2435. 'InvalidStateError');
  2436. }
  2437. var streams = [].slice.call(arguments, 1);
  2438. if (streams.length !== 1 ||
  2439. !streams[0].getTracks().find(function(t) {
  2440. return t === track;
  2441. })) {
  2442. // this is not fully correct but all we can manage without
  2443. // [[associated MediaStreams]] internal slot.
  2444. throw new DOMException(
  2445. 'The adapter.js addTrack polyfill only supports a single ' +
  2446. ' stream which is associated with the specified track.',
  2447. 'NotSupportedError');
  2448. }
  2449. var alreadyExists = pc.getSenders().find(function(s) {
  2450. return s.track === track;
  2451. });
  2452. if (alreadyExists) {
  2453. throw new DOMException('Track already exists.',
  2454. 'InvalidAccessError');
  2455. }
  2456. pc._streams = pc._streams || {};
  2457. pc._reverseStreams = pc._reverseStreams || {};
  2458. var oldStream = pc._streams[stream.id];
  2459. if (oldStream) {
  2460. // this is using odd Chrome behaviour, use with caution:
  2461. // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
  2462. // Note: we rely on the high-level addTrack/dtmf shim to
  2463. // create the sender with a dtmf sender.
  2464. oldStream.addTrack(track);
  2465. // Trigger ONN async.
  2466. Promise.resolve().then(function() {
  2467. pc.dispatchEvent(new Event('negotiationneeded'));
  2468. });
  2469. } else {
  2470. var newStream = new window.MediaStream([track]);
  2471. pc._streams[stream.id] = newStream;
  2472. pc._reverseStreams[newStream.id] = stream;
  2473. pc.addStream(newStream);
  2474. }
  2475. return pc.getSenders().find(function(s) {
  2476. return s.track === track;
  2477. });
  2478. };
  2479. // replace the internal stream id with the external one and
  2480. // vice versa.
  2481. function replaceInternalStreamId(pc, description) {
  2482. var sdp = description.sdp;
  2483. Object.keys(pc._reverseStreams || []).forEach(function(internalId) {
  2484. var externalStream = pc._reverseStreams[internalId];
  2485. var internalStream = pc._streams[externalStream.id];
  2486. sdp = sdp.replace(new RegExp(internalStream.id, 'g'),
  2487. externalStream.id);
  2488. });
  2489. return new RTCSessionDescription({
  2490. type: description.type,
  2491. sdp: sdp
  2492. });
  2493. }
  2494. function replaceExternalStreamId(pc, description) {
  2495. var sdp = description.sdp;
  2496. Object.keys(pc._reverseStreams || []).forEach(function(internalId) {
  2497. var externalStream = pc._reverseStreams[internalId];
  2498. var internalStream = pc._streams[externalStream.id];
  2499. sdp = sdp.replace(new RegExp(externalStream.id, 'g'),
  2500. internalStream.id);
  2501. });
  2502. return new RTCSessionDescription({
  2503. type: description.type,
  2504. sdp: sdp
  2505. });
  2506. }
  2507. ['createOffer', 'createAnswer'].forEach(function(method) {
  2508. var nativeMethod = window.RTCPeerConnection.prototype[method];
  2509. window.RTCPeerConnection.prototype[method] = function() {
  2510. var pc = this;
  2511. var args = arguments;
  2512. var isLegacyCall = arguments.length &&
  2513. typeof arguments[0] === 'function';
  2514. if (isLegacyCall) {
  2515. return nativeMethod.apply(pc, [
  2516. function(description) {
  2517. var desc = replaceInternalStreamId(pc, description);
  2518. args[0].apply(null, [desc]);
  2519. },
  2520. function(err) {
  2521. if (args[1]) {
  2522. args[1].apply(null, err);
  2523. }
  2524. }, arguments[2]
  2525. ]);
  2526. }
  2527. return nativeMethod.apply(pc, arguments)
  2528. .then(function(description) {
  2529. return replaceInternalStreamId(pc, description);
  2530. });
  2531. };
  2532. });
  2533. var origSetLocalDescription =
  2534. window.RTCPeerConnection.prototype.setLocalDescription;
  2535. window.RTCPeerConnection.prototype.setLocalDescription = function() {
  2536. var pc = this;
  2537. if (!arguments.length || !arguments[0].type) {
  2538. return origSetLocalDescription.apply(pc, arguments);
  2539. }
  2540. arguments[0] = replaceExternalStreamId(pc, arguments[0]);
  2541. return origSetLocalDescription.apply(pc, arguments);
  2542. };
  2543. // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier
  2544. var origLocalDescription = Object.getOwnPropertyDescriptor(
  2545. window.RTCPeerConnection.prototype, 'localDescription');
  2546. Object.defineProperty(window.RTCPeerConnection.prototype,
  2547. 'localDescription', {
  2548. get: function() {
  2549. var pc = this;
  2550. var description = origLocalDescription.get.apply(this);
  2551. if (description.type === '') {
  2552. return description;
  2553. }
  2554. return replaceInternalStreamId(pc, description);
  2555. }
  2556. });
  2557. window.RTCPeerConnection.prototype.removeTrack = function(sender) {
  2558. var pc = this;
  2559. if (pc.signalingState === 'closed') {
  2560. throw new DOMException(
  2561. 'The RTCPeerConnection\'s signalingState is \'closed\'.',
  2562. 'InvalidStateError');
  2563. }
  2564. // We can not yet check for sender instanceof RTCRtpSender
  2565. // since we shim RTPSender. So we check if sender._pc is set.
  2566. if (!sender._pc) {
  2567. throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' +
  2568. 'does not implement interface RTCRtpSender.', 'TypeError');
  2569. }
  2570. var isLocal = sender._pc === pc;
  2571. if (!isLocal) {
  2572. throw new DOMException('Sender was not created by this connection.',
  2573. 'InvalidAccessError');
  2574. }
  2575. // Search for the native stream the senders track belongs to.
  2576. pc._streams = pc._streams || {};
  2577. var stream;
  2578. Object.keys(pc._streams).forEach(function(streamid) {
  2579. var hasTrack = pc._streams[streamid].getTracks().find(function(track) {
  2580. return sender.track === track;
  2581. });
  2582. if (hasTrack) {
  2583. stream = pc._streams[streamid];
  2584. }
  2585. });
  2586. if (stream) {
  2587. if (stream.getTracks().length === 1) {
  2588. // if this is the last track of the stream, remove the stream. This
  2589. // takes care of any shimmed _senders.
  2590. pc.removeStream(pc._reverseStreams[stream.id]);
  2591. } else {
  2592. // relying on the same odd chrome behaviour as above.
  2593. stream.removeTrack(sender.track);
  2594. }
  2595. pc.dispatchEvent(new Event('negotiationneeded'));
  2596. }
  2597. };
  2598. },
  2599. shimPeerConnection: function(window) {
  2600. var browserDetails = utils.detectBrowser(window);
  2601. // The RTCPeerConnection object.
  2602. if (!window.RTCPeerConnection) {
  2603. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  2604. // Translate iceTransportPolicy to iceTransports,
  2605. // see https://code.google.com/p/webrtc/issues/detail?id=4869
  2606. // this was fixed in M56 along with unprefixing RTCPeerConnection.
  2607. logging('PeerConnection');
  2608. if (pcConfig && pcConfig.iceTransportPolicy) {
  2609. pcConfig.iceTransports = pcConfig.iceTransportPolicy;
  2610. }
  2611. return new window.webkitRTCPeerConnection(pcConfig, pcConstraints);
  2612. };
  2613. window.RTCPeerConnection.prototype =
  2614. window.webkitRTCPeerConnection.prototype;
  2615. // wrap static methods. Currently just generateCertificate.
  2616. if (window.webkitRTCPeerConnection.generateCertificate) {
  2617. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  2618. get: function() {
  2619. return window.webkitRTCPeerConnection.generateCertificate;
  2620. }
  2621. });
  2622. }
  2623. } else {
  2624. // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
  2625. var OrigPeerConnection = window.RTCPeerConnection;
  2626. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  2627. if (pcConfig && pcConfig.iceServers) {
  2628. var newIceServers = [];
  2629. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2630. var server = pcConfig.iceServers[i];
  2631. if (!server.hasOwnProperty('urls') &&
  2632. server.hasOwnProperty('url')) {
  2633. utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  2634. server = JSON.parse(JSON.stringify(server));
  2635. server.urls = server.url;
  2636. newIceServers.push(server);
  2637. } else {
  2638. newIceServers.push(pcConfig.iceServers[i]);
  2639. }
  2640. }
  2641. pcConfig.iceServers = newIceServers;
  2642. }
  2643. return new OrigPeerConnection(pcConfig, pcConstraints);
  2644. };
  2645. window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
  2646. // wrap static methods. Currently just generateCertificate.
  2647. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  2648. get: function() {
  2649. return OrigPeerConnection.generateCertificate;
  2650. }
  2651. });
  2652. }
  2653. var origGetStats = window.RTCPeerConnection.prototype.getStats;
  2654. window.RTCPeerConnection.prototype.getStats = function(selector,
  2655. successCallback, errorCallback) {
  2656. var self = this;
  2657. var args = arguments;
  2658. // If selector is a function then we are in the old style stats so just
  2659. // pass back the original getStats format to avoid breaking old users.
  2660. if (arguments.length > 0 && typeof selector === 'function') {
  2661. return origGetStats.apply(this, arguments);
  2662. }
  2663. // When spec-style getStats is supported, return those when called with
  2664. // either no arguments or the selector argument is null.
  2665. if (origGetStats.length === 0 && (arguments.length === 0 ||
  2666. typeof arguments[0] !== 'function')) {
  2667. return origGetStats.apply(this, []);
  2668. }
  2669. var fixChromeStats_ = function(response) {
  2670. var standardReport = {};
  2671. var reports = response.result();
  2672. reports.forEach(function(report) {
  2673. var standardStats = {
  2674. id: report.id,
  2675. timestamp: report.timestamp,
  2676. type: {
  2677. localcandidate: 'local-candidate',
  2678. remotecandidate: 'remote-candidate'
  2679. }[report.type] || report.type
  2680. };
  2681. report.names().forEach(function(name) {
  2682. standardStats[name] = report.stat(name);
  2683. });
  2684. standardReport[standardStats.id] = standardStats;
  2685. });
  2686. return standardReport;
  2687. };
  2688. // shim getStats with maplike support
  2689. var makeMapStats = function(stats) {
  2690. return new Map(Object.keys(stats).map(function(key) {
  2691. return [key, stats[key]];
  2692. }));
  2693. };
  2694. if (arguments.length >= 2) {
  2695. var successCallbackWrapper_ = function(response) {
  2696. args[1](makeMapStats(fixChromeStats_(response)));
  2697. };
  2698. return origGetStats.apply(this, [successCallbackWrapper_,
  2699. arguments[0]]);
  2700. }
  2701. // promise-support
  2702. return new Promise(function(resolve, reject) {
  2703. origGetStats.apply(self, [
  2704. function(response) {
  2705. resolve(makeMapStats(fixChromeStats_(response)));
  2706. }, reject]);
  2707. }).then(successCallback, errorCallback);
  2708. };
  2709. // add promise support -- natively available in Chrome 51
  2710. if (browserDetails.version < 51) {
  2711. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  2712. .forEach(function(method) {
  2713. var nativeMethod = window.RTCPeerConnection.prototype[method];
  2714. window.RTCPeerConnection.prototype[method] = function() {
  2715. var args = arguments;
  2716. var self = this;
  2717. var promise = new Promise(function(resolve, reject) {
  2718. nativeMethod.apply(self, [args[0], resolve, reject]);
  2719. });
  2720. if (args.length < 2) {
  2721. return promise;
  2722. }
  2723. return promise.then(function() {
  2724. args[1].apply(null, []);
  2725. },
  2726. function(err) {
  2727. if (args.length >= 3) {
  2728. args[2].apply(null, [err]);
  2729. }
  2730. });
  2731. };
  2732. });
  2733. }
  2734. // promise support for createOffer and createAnswer. Available (without
  2735. // bugs) since M52: crbug/619289
  2736. if (browserDetails.version < 52) {
  2737. ['createOffer', 'createAnswer'].forEach(function(method) {
  2738. var nativeMethod = window.RTCPeerConnection.prototype[method];
  2739. window.RTCPeerConnection.prototype[method] = function() {
  2740. var self = this;
  2741. if (arguments.length < 1 || (arguments.length === 1 &&
  2742. typeof arguments[0] === 'object')) {
  2743. var opts = arguments.length === 1 ? arguments[0] : undefined;
  2744. return new Promise(function(resolve, reject) {
  2745. nativeMethod.apply(self, [resolve, reject, opts]);
  2746. });
  2747. }
  2748. return nativeMethod.apply(this, arguments);
  2749. };
  2750. });
  2751. }
  2752. // shim implicit creation of RTCSessionDescription/RTCIceCandidate
  2753. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  2754. .forEach(function(method) {
  2755. var nativeMethod = window.RTCPeerConnection.prototype[method];
  2756. window.RTCPeerConnection.prototype[method] = function() {
  2757. arguments[0] = new ((method === 'addIceCandidate') ?
  2758. window.RTCIceCandidate :
  2759. window.RTCSessionDescription)(arguments[0]);
  2760. return nativeMethod.apply(this, arguments);
  2761. };
  2762. });
  2763. // support for addIceCandidate(null or undefined)
  2764. var nativeAddIceCandidate =
  2765. window.RTCPeerConnection.prototype.addIceCandidate;
  2766. window.RTCPeerConnection.prototype.addIceCandidate = function() {
  2767. if (!arguments[0]) {
  2768. if (arguments[1]) {
  2769. arguments[1].apply(null);
  2770. }
  2771. return Promise.resolve();
  2772. }
  2773. return nativeAddIceCandidate.apply(this, arguments);
  2774. };
  2775. }
  2776. };
  2777. // Expose public methods.
  2778. module.exports = {
  2779. shimMediaStream: chromeShim.shimMediaStream,
  2780. shimOnTrack: chromeShim.shimOnTrack,
  2781. shimAddTrackRemoveTrack: chromeShim.shimAddTrackRemoveTrack,
  2782. shimGetSendersWithDtmf: chromeShim.shimGetSendersWithDtmf,
  2783. shimSourceObject: chromeShim.shimSourceObject,
  2784. shimPeerConnection: chromeShim.shimPeerConnection,
  2785. shimGetUserMedia: require('./getusermedia')
  2786. };
  2787. },{"../utils.js":13,"./getusermedia":6}],6:[function(require,module,exports){
  2788. /*
  2789. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  2790. *
  2791. * Use of this source code is governed by a BSD-style license
  2792. * that can be found in the LICENSE file in the root of the source
  2793. * tree.
  2794. */
  2795. /* eslint-env node */
  2796. 'use strict';
  2797. var utils = require('../utils.js');
  2798. var logging = utils.log;
  2799. // Expose public methods.
  2800. module.exports = function(window) {
  2801. var browserDetails = utils.detectBrowser(window);
  2802. var navigator = window && window.navigator;
  2803. var constraintsToChrome_ = function(c) {
  2804. if (typeof c !== 'object' || c.mandatory || c.optional) {
  2805. return c;
  2806. }
  2807. var cc = {};
  2808. Object.keys(c).forEach(function(key) {
  2809. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  2810. return;
  2811. }
  2812. var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
  2813. if (r.exact !== undefined && typeof r.exact === 'number') {
  2814. r.min = r.max = r.exact;
  2815. }
  2816. var oldname_ = function(prefix, name) {
  2817. if (prefix) {
  2818. return prefix + name.charAt(0).toUpperCase() + name.slice(1);
  2819. }
  2820. return (name === 'deviceId') ? 'sourceId' : name;
  2821. };
  2822. if (r.ideal !== undefined) {
  2823. cc.optional = cc.optional || [];
  2824. var oc = {};
  2825. if (typeof r.ideal === 'number') {
  2826. oc[oldname_('min', key)] = r.ideal;
  2827. cc.optional.push(oc);
  2828. oc = {};
  2829. oc[oldname_('max', key)] = r.ideal;
  2830. cc.optional.push(oc);
  2831. } else {
  2832. oc[oldname_('', key)] = r.ideal;
  2833. cc.optional.push(oc);
  2834. }
  2835. }
  2836. if (r.exact !== undefined && typeof r.exact !== 'number') {
  2837. cc.mandatory = cc.mandatory || {};
  2838. cc.mandatory[oldname_('', key)] = r.exact;
  2839. } else {
  2840. ['min', 'max'].forEach(function(mix) {
  2841. if (r[mix] !== undefined) {
  2842. cc.mandatory = cc.mandatory || {};
  2843. cc.mandatory[oldname_(mix, key)] = r[mix];
  2844. }
  2845. });
  2846. }
  2847. });
  2848. if (c.advanced) {
  2849. cc.optional = (cc.optional || []).concat(c.advanced);
  2850. }
  2851. return cc;
  2852. };
  2853. var shimConstraints_ = function(constraints, func) {
  2854. if (browserDetails.version >= 61) {
  2855. return func(constraints);
  2856. }
  2857. constraints = JSON.parse(JSON.stringify(constraints));
  2858. if (constraints && typeof constraints.audio === 'object') {
  2859. var remap = function(obj, a, b) {
  2860. if (a in obj && !(b in obj)) {
  2861. obj[b] = obj[a];
  2862. delete obj[a];
  2863. }
  2864. };
  2865. constraints = JSON.parse(JSON.stringify(constraints));
  2866. remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
  2867. remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
  2868. constraints.audio = constraintsToChrome_(constraints.audio);
  2869. }
  2870. if (constraints && typeof constraints.video === 'object') {
  2871. // Shim facingMode for mobile & surface pro.
  2872. var face = constraints.video.facingMode;
  2873. face = face && ((typeof face === 'object') ? face : {ideal: face});
  2874. var getSupportedFacingModeLies = browserDetails.version < 66;
  2875. if ((face && (face.exact === 'user' || face.exact === 'environment' ||
  2876. face.ideal === 'user' || face.ideal === 'environment')) &&
  2877. !(navigator.mediaDevices.getSupportedConstraints &&
  2878. navigator.mediaDevices.getSupportedConstraints().facingMode &&
  2879. !getSupportedFacingModeLies)) {
  2880. delete constraints.video.facingMode;
  2881. var matches;
  2882. if (face.exact === 'environment' || face.ideal === 'environment') {
  2883. matches = ['back', 'rear'];
  2884. } else if (face.exact === 'user' || face.ideal === 'user') {
  2885. matches = ['front'];
  2886. }
  2887. if (matches) {
  2888. // Look for matches in label, or use last cam for back (typical).
  2889. return navigator.mediaDevices.enumerateDevices()
  2890. .then(function(devices) {
  2891. devices = devices.filter(function(d) {
  2892. return d.kind === 'videoinput';
  2893. });
  2894. var dev = devices.find(function(d) {
  2895. return matches.some(function(match) {
  2896. return d.label.toLowerCase().indexOf(match) !== -1;
  2897. });
  2898. });
  2899. if (!dev && devices.length && matches.indexOf('back') !== -1) {
  2900. dev = devices[devices.length - 1]; // more likely the back cam
  2901. }
  2902. if (dev) {
  2903. constraints.video.deviceId = face.exact ? {exact: dev.deviceId} :
  2904. {ideal: dev.deviceId};
  2905. }
  2906. constraints.video = constraintsToChrome_(constraints.video);
  2907. logging('chrome: ' + JSON.stringify(constraints));
  2908. return func(constraints);
  2909. });
  2910. }
  2911. }
  2912. constraints.video = constraintsToChrome_(constraints.video);
  2913. }
  2914. logging('chrome: ' + JSON.stringify(constraints));
  2915. return func(constraints);
  2916. };
  2917. var shimError_ = function(e) {
  2918. return {
  2919. name: {
  2920. PermissionDeniedError: 'NotAllowedError',
  2921. InvalidStateError: 'NotReadableError',
  2922. DevicesNotFoundError: 'NotFoundError',
  2923. ConstraintNotSatisfiedError: 'OverconstrainedError',
  2924. TrackStartError: 'NotReadableError',
  2925. MediaDeviceFailedDueToShutdown: 'NotReadableError',
  2926. MediaDeviceKillSwitchOn: 'NotReadableError'
  2927. }[e.name] || e.name,
  2928. message: e.message,
  2929. constraint: e.constraintName,
  2930. toString: function() {
  2931. return this.name + (this.message && ': ') + this.message;
  2932. }
  2933. };
  2934. };
  2935. var getUserMedia_ = function(constraints, onSuccess, onError) {
  2936. shimConstraints_(constraints, function(c) {
  2937. navigator.webkitGetUserMedia(c, onSuccess, function(e) {
  2938. if (onError) {
  2939. onError(shimError_(e));
  2940. }
  2941. });
  2942. });
  2943. };
  2944. navigator.getUserMedia = getUserMedia_;
  2945. // Returns the result of getUserMedia as a Promise.
  2946. var getUserMediaPromise_ = function(constraints) {
  2947. return new Promise(function(resolve, reject) {
  2948. navigator.getUserMedia(constraints, resolve, reject);
  2949. });
  2950. };
  2951. if (!navigator.mediaDevices) {
  2952. navigator.mediaDevices = {
  2953. getUserMedia: getUserMediaPromise_,
  2954. enumerateDevices: function() {
  2955. return new Promise(function(resolve) {
  2956. var kinds = {audio: 'audioinput', video: 'videoinput'};
  2957. return window.MediaStreamTrack.getSources(function(devices) {
  2958. resolve(devices.map(function(device) {
  2959. return {label: device.label,
  2960. kind: kinds[device.kind],
  2961. deviceId: device.id,
  2962. groupId: ''};
  2963. }));
  2964. });
  2965. });
  2966. },
  2967. getSupportedConstraints: function() {
  2968. return {
  2969. deviceId: true, echoCancellation: true, facingMode: true,
  2970. frameRate: true, height: true, width: true
  2971. };
  2972. }
  2973. };
  2974. }
  2975. // A shim for getUserMedia method on the mediaDevices object.
  2976. // TODO(KaptenJansson) remove once implemented in Chrome stable.
  2977. if (!navigator.mediaDevices.getUserMedia) {
  2978. navigator.mediaDevices.getUserMedia = function(constraints) {
  2979. return getUserMediaPromise_(constraints);
  2980. };
  2981. } else {
  2982. // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
  2983. // function which returns a Promise, it does not accept spec-style
  2984. // constraints.
  2985. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  2986. bind(navigator.mediaDevices);
  2987. navigator.mediaDevices.getUserMedia = function(cs) {
  2988. return shimConstraints_(cs, function(c) {
  2989. return origGetUserMedia(c).then(function(stream) {
  2990. if (c.audio && !stream.getAudioTracks().length ||
  2991. c.video && !stream.getVideoTracks().length) {
  2992. stream.getTracks().forEach(function(track) {
  2993. track.stop();
  2994. });
  2995. throw new DOMException('', 'NotFoundError');
  2996. }
  2997. return stream;
  2998. }, function(e) {
  2999. return Promise.reject(shimError_(e));
  3000. });
  3001. });
  3002. };
  3003. }
  3004. // Dummy devicechange event methods.
  3005. // TODO(KaptenJansson) remove once implemented in Chrome stable.
  3006. if (typeof navigator.mediaDevices.addEventListener === 'undefined') {
  3007. navigator.mediaDevices.addEventListener = function() {
  3008. logging('Dummy mediaDevices.addEventListener called.');
  3009. };
  3010. }
  3011. if (typeof navigator.mediaDevices.removeEventListener === 'undefined') {
  3012. navigator.mediaDevices.removeEventListener = function() {
  3013. logging('Dummy mediaDevices.removeEventListener called.');
  3014. };
  3015. }
  3016. };
  3017. },{"../utils.js":13}],7:[function(require,module,exports){
  3018. /*
  3019. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  3020. *
  3021. * Use of this source code is governed by a BSD-style license
  3022. * that can be found in the LICENSE file in the root of the source
  3023. * tree.
  3024. */
  3025. /* eslint-env node */
  3026. 'use strict';
  3027. var SDPUtils = require('sdp');
  3028. var utils = require('./utils');
  3029. // Wraps the peerconnection event eventNameToWrap in a function
  3030. // which returns the modified event object.
  3031. function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {
  3032. if (!window.RTCPeerConnection) {
  3033. return;
  3034. }
  3035. var proto = window.RTCPeerConnection.prototype;
  3036. var nativeAddEventListener = proto.addEventListener;
  3037. proto.addEventListener = function(nativeEventName, cb) {
  3038. if (nativeEventName !== eventNameToWrap) {
  3039. return nativeAddEventListener.apply(this, arguments);
  3040. }
  3041. var wrappedCallback = function(e) {
  3042. cb(wrapper(e));
  3043. };
  3044. this._eventMap = this._eventMap || {};
  3045. this._eventMap[cb] = wrappedCallback;
  3046. return nativeAddEventListener.apply(this, [nativeEventName,
  3047. wrappedCallback]);
  3048. };
  3049. var nativeRemoveEventListener = proto.removeEventListener;
  3050. proto.removeEventListener = function(nativeEventName, cb) {
  3051. if (nativeEventName !== eventNameToWrap || !this._eventMap
  3052. || !this._eventMap[cb]) {
  3053. return nativeRemoveEventListener.apply(this, arguments);
  3054. }
  3055. var unwrappedCb = this._eventMap[cb];
  3056. delete this._eventMap[cb];
  3057. return nativeRemoveEventListener.apply(this, [nativeEventName,
  3058. unwrappedCb]);
  3059. };
  3060. Object.defineProperty(proto, 'on' + eventNameToWrap, {
  3061. get: function() {
  3062. return this['_on' + eventNameToWrap];
  3063. },
  3064. set: function(cb) {
  3065. if (this['_on' + eventNameToWrap]) {
  3066. this.removeEventListener(eventNameToWrap,
  3067. this['_on' + eventNameToWrap]);
  3068. delete this['_on' + eventNameToWrap];
  3069. }
  3070. if (cb) {
  3071. this.addEventListener(eventNameToWrap,
  3072. this['_on' + eventNameToWrap] = cb);
  3073. }
  3074. }
  3075. });
  3076. }
  3077. module.exports = {
  3078. shimRTCIceCandidate: function(window) {
  3079. // foundation is arbitrarily chosen as an indicator for full support for
  3080. // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
  3081. if (window.RTCIceCandidate && 'foundation' in
  3082. window.RTCIceCandidate.prototype) {
  3083. return;
  3084. }
  3085. var NativeRTCIceCandidate = window.RTCIceCandidate;
  3086. window.RTCIceCandidate = function(args) {
  3087. // Remove the a= which shouldn't be part of the candidate string.
  3088. if (typeof args === 'object' && args.candidate &&
  3089. args.candidate.indexOf('a=') === 0) {
  3090. args = JSON.parse(JSON.stringify(args));
  3091. args.candidate = args.candidate.substr(2);
  3092. }
  3093. // Augment the native candidate with the parsed fields.
  3094. var nativeCandidate = new NativeRTCIceCandidate(args);
  3095. var parsedCandidate = SDPUtils.parseCandidate(args.candidate);
  3096. var augmentedCandidate = Object.assign(nativeCandidate,
  3097. parsedCandidate);
  3098. // Add a serializer that does not serialize the extra attributes.
  3099. augmentedCandidate.toJSON = function() {
  3100. return {
  3101. candidate: augmentedCandidate.candidate,
  3102. sdpMid: augmentedCandidate.sdpMid,
  3103. sdpMLineIndex: augmentedCandidate.sdpMLineIndex,
  3104. usernameFragment: augmentedCandidate.usernameFragment,
  3105. };
  3106. };
  3107. return augmentedCandidate;
  3108. };
  3109. // Hook up the augmented candidate in onicecandidate and
  3110. // addEventListener('icecandidate', ...)
  3111. wrapPeerConnectionEvent(window, 'icecandidate', function(e) {
  3112. if (e.candidate) {
  3113. Object.defineProperty(e, 'candidate', {
  3114. value: new window.RTCIceCandidate(e.candidate),
  3115. writable: 'false'
  3116. });
  3117. }
  3118. return e;
  3119. });
  3120. },
  3121. // shimCreateObjectURL must be called before shimSourceObject to avoid loop.
  3122. shimCreateObjectURL: function(window) {
  3123. var URL = window && window.URL;
  3124. if (!(typeof window === 'object' && window.HTMLMediaElement &&
  3125. 'srcObject' in window.HTMLMediaElement.prototype &&
  3126. URL.createObjectURL && URL.revokeObjectURL)) {
  3127. // Only shim CreateObjectURL using srcObject if srcObject exists.
  3128. return undefined;
  3129. }
  3130. var nativeCreateObjectURL = URL.createObjectURL.bind(URL);
  3131. var nativeRevokeObjectURL = URL.revokeObjectURL.bind(URL);
  3132. var streams = new Map(), newId = 0;
  3133. URL.createObjectURL = function(stream) {
  3134. if ('getTracks' in stream) {
  3135. var url = 'polyblob:' + (++newId);
  3136. streams.set(url, stream);
  3137. utils.deprecated('URL.createObjectURL(stream)',
  3138. 'elem.srcObject = stream');
  3139. return url;
  3140. }
  3141. return nativeCreateObjectURL(stream);
  3142. };
  3143. URL.revokeObjectURL = function(url) {
  3144. nativeRevokeObjectURL(url);
  3145. streams['delete'](url);
  3146. };
  3147. var dsc = Object.getOwnPropertyDescriptor(window.HTMLMediaElement.prototype,
  3148. 'src');
  3149. Object.defineProperty(window.HTMLMediaElement.prototype, 'src', {
  3150. get: function() {
  3151. return dsc.get.apply(this);
  3152. },
  3153. set: function(url) {
  3154. this.srcObject = streams.get(url) || null;
  3155. return dsc.set.apply(this, [url]);
  3156. }
  3157. });
  3158. var nativeSetAttribute = window.HTMLMediaElement.prototype.setAttribute;
  3159. window.HTMLMediaElement.prototype.setAttribute = function() {
  3160. if (arguments.length === 2 &&
  3161. ('' + arguments[0]).toLowerCase() === 'src') {
  3162. this.srcObject = streams.get(arguments[1]) || null;
  3163. }
  3164. return nativeSetAttribute.apply(this, arguments);
  3165. };
  3166. }
  3167. };
  3168. },{"./utils":13,"sdp":2}],8:[function(require,module,exports){
  3169. /*
  3170. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3171. *
  3172. * Use of this source code is governed by a BSD-style license
  3173. * that can be found in the LICENSE file in the root of the source
  3174. * tree.
  3175. */
  3176. /* eslint-env node */
  3177. 'use strict';
  3178. var utils = require('../utils');
  3179. var shimRTCPeerConnection = require('rtcpeerconnection-shim');
  3180. module.exports = {
  3181. shimGetUserMedia: require('./getusermedia'),
  3182. shimPeerConnection: function(window) {
  3183. var browserDetails = utils.detectBrowser(window);
  3184. if (window.RTCIceGatherer) {
  3185. // ORTC defines an RTCIceCandidate object but no constructor.
  3186. // Not implemented in Edge.
  3187. if (!window.RTCIceCandidate) {
  3188. window.RTCIceCandidate = function(args) {
  3189. return args;
  3190. };
  3191. }
  3192. // ORTC does not have a session description object but
  3193. // other browsers (i.e. Chrome) that will support both PC and ORTC
  3194. // in the future might have this defined already.
  3195. if (!window.RTCSessionDescription) {
  3196. window.RTCSessionDescription = function(args) {
  3197. return args;
  3198. };
  3199. }
  3200. // this adds an additional event listener to MediaStrackTrack that signals
  3201. // when a tracks enabled property was changed. Workaround for a bug in
  3202. // addStream, see below. No longer required in 15025+
  3203. if (browserDetails.version < 15025) {
  3204. var origMSTEnabled = Object.getOwnPropertyDescriptor(
  3205. window.MediaStreamTrack.prototype, 'enabled');
  3206. Object.defineProperty(window.MediaStreamTrack.prototype, 'enabled', {
  3207. set: function(value) {
  3208. origMSTEnabled.set.call(this, value);
  3209. var ev = new Event('enabled');
  3210. ev.enabled = value;
  3211. this.dispatchEvent(ev);
  3212. }
  3213. });
  3214. }
  3215. }
  3216. // ORTC defines the DTMF sender a bit different.
  3217. // https://github.com/w3c/ortc/issues/714
  3218. if (window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
  3219. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  3220. get: function() {
  3221. if (this._dtmf === undefined) {
  3222. if (this.track.kind === 'audio') {
  3223. this._dtmf = new window.RTCDtmfSender(this);
  3224. } else if (this.track.kind === 'video') {
  3225. this._dtmf = null;
  3226. }
  3227. }
  3228. return this._dtmf;
  3229. }
  3230. });
  3231. }
  3232. window.RTCPeerConnection =
  3233. shimRTCPeerConnection(window, browserDetails.version);
  3234. },
  3235. shimReplaceTrack: function(window) {
  3236. // ORTC has replaceTrack -- https://github.com/w3c/ortc/issues/614
  3237. if (window.RTCRtpSender &&
  3238. !('replaceTrack' in window.RTCRtpSender.prototype)) {
  3239. window.RTCRtpSender.prototype.replaceTrack =
  3240. window.RTCRtpSender.prototype.setTrack;
  3241. }
  3242. }
  3243. };
  3244. },{"../utils":13,"./getusermedia":9,"rtcpeerconnection-shim":1}],9:[function(require,module,exports){
  3245. /*
  3246. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3247. *
  3248. * Use of this source code is governed by a BSD-style license
  3249. * that can be found in the LICENSE file in the root of the source
  3250. * tree.
  3251. */
  3252. /* eslint-env node */
  3253. 'use strict';
  3254. // Expose public methods.
  3255. module.exports = function(window) {
  3256. var navigator = window && window.navigator;
  3257. var shimError_ = function(e) {
  3258. return {
  3259. name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name,
  3260. message: e.message,
  3261. constraint: e.constraint,
  3262. toString: function() {
  3263. return this.name;
  3264. }
  3265. };
  3266. };
  3267. // getUserMedia error shim.
  3268. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  3269. bind(navigator.mediaDevices);
  3270. navigator.mediaDevices.getUserMedia = function(c) {
  3271. return origGetUserMedia(c).catch(function(e) {
  3272. return Promise.reject(shimError_(e));
  3273. });
  3274. };
  3275. };
  3276. },{}],10:[function(require,module,exports){
  3277. /*
  3278. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3279. *
  3280. * Use of this source code is governed by a BSD-style license
  3281. * that can be found in the LICENSE file in the root of the source
  3282. * tree.
  3283. */
  3284. /* eslint-env node */
  3285. 'use strict';
  3286. var utils = require('../utils');
  3287. var firefoxShim = {
  3288. shimOnTrack: function(window) {
  3289. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  3290. window.RTCPeerConnection.prototype)) {
  3291. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  3292. get: function() {
  3293. return this._ontrack;
  3294. },
  3295. set: function(f) {
  3296. if (this._ontrack) {
  3297. this.removeEventListener('track', this._ontrack);
  3298. this.removeEventListener('addstream', this._ontrackpoly);
  3299. }
  3300. this.addEventListener('track', this._ontrack = f);
  3301. this.addEventListener('addstream', this._ontrackpoly = function(e) {
  3302. e.stream.getTracks().forEach(function(track) {
  3303. var event = new Event('track');
  3304. event.track = track;
  3305. event.receiver = {track: track};
  3306. event.transceiver = {receiver: event.receiver};
  3307. event.streams = [e.stream];
  3308. this.dispatchEvent(event);
  3309. }.bind(this));
  3310. }.bind(this));
  3311. }
  3312. });
  3313. }
  3314. if (typeof window === 'object' && window.RTCTrackEvent &&
  3315. ('receiver' in window.RTCTrackEvent.prototype) &&
  3316. !('transceiver' in window.RTCTrackEvent.prototype)) {
  3317. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  3318. get: function() {
  3319. return {receiver: this.receiver};
  3320. }
  3321. });
  3322. }
  3323. },
  3324. shimSourceObject: function(window) {
  3325. // Firefox has supported mozSrcObject since FF22, unprefixed in 42.
  3326. if (typeof window === 'object') {
  3327. if (window.HTMLMediaElement &&
  3328. !('srcObject' in window.HTMLMediaElement.prototype)) {
  3329. // Shim the srcObject property, once, when HTMLMediaElement is found.
  3330. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
  3331. get: function() {
  3332. return this.mozSrcObject;
  3333. },
  3334. set: function(stream) {
  3335. this.mozSrcObject = stream;
  3336. }
  3337. });
  3338. }
  3339. }
  3340. },
  3341. shimPeerConnection: function(window) {
  3342. var browserDetails = utils.detectBrowser(window);
  3343. if (typeof window !== 'object' || !(window.RTCPeerConnection ||
  3344. window.mozRTCPeerConnection)) {
  3345. return; // probably media.peerconnection.enabled=false in about:config
  3346. }
  3347. // The RTCPeerConnection object.
  3348. if (!window.RTCPeerConnection) {
  3349. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  3350. if (browserDetails.version < 38) {
  3351. // .urls is not supported in FF < 38.
  3352. // create RTCIceServers with a single url.
  3353. if (pcConfig && pcConfig.iceServers) {
  3354. var newIceServers = [];
  3355. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3356. var server = pcConfig.iceServers[i];
  3357. if (server.hasOwnProperty('urls')) {
  3358. for (var j = 0; j < server.urls.length; j++) {
  3359. var newServer = {
  3360. url: server.urls[j]
  3361. };
  3362. if (server.urls[j].indexOf('turn') === 0) {
  3363. newServer.username = server.username;
  3364. newServer.credential = server.credential;
  3365. }
  3366. newIceServers.push(newServer);
  3367. }
  3368. } else {
  3369. newIceServers.push(pcConfig.iceServers[i]);
  3370. }
  3371. }
  3372. pcConfig.iceServers = newIceServers;
  3373. }
  3374. }
  3375. return new window.mozRTCPeerConnection(pcConfig, pcConstraints);
  3376. };
  3377. window.RTCPeerConnection.prototype =
  3378. window.mozRTCPeerConnection.prototype;
  3379. // wrap static methods. Currently just generateCertificate.
  3380. if (window.mozRTCPeerConnection.generateCertificate) {
  3381. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  3382. get: function() {
  3383. return window.mozRTCPeerConnection.generateCertificate;
  3384. }
  3385. });
  3386. }
  3387. window.RTCSessionDescription = window.mozRTCSessionDescription;
  3388. window.RTCIceCandidate = window.mozRTCIceCandidate;
  3389. }
  3390. // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
  3391. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  3392. .forEach(function(method) {
  3393. var nativeMethod = window.RTCPeerConnection.prototype[method];
  3394. window.RTCPeerConnection.prototype[method] = function() {
  3395. arguments[0] = new ((method === 'addIceCandidate') ?
  3396. window.RTCIceCandidate :
  3397. window.RTCSessionDescription)(arguments[0]);
  3398. return nativeMethod.apply(this, arguments);
  3399. };
  3400. });
  3401. // support for addIceCandidate(null or undefined)
  3402. var nativeAddIceCandidate =
  3403. window.RTCPeerConnection.prototype.addIceCandidate;
  3404. window.RTCPeerConnection.prototype.addIceCandidate = function() {
  3405. if (!arguments[0]) {
  3406. if (arguments[1]) {
  3407. arguments[1].apply(null);
  3408. }
  3409. return Promise.resolve();
  3410. }
  3411. return nativeAddIceCandidate.apply(this, arguments);
  3412. };
  3413. // shim getStats with maplike support
  3414. var makeMapStats = function(stats) {
  3415. var map = new Map();
  3416. Object.keys(stats).forEach(function(key) {
  3417. map.set(key, stats[key]);
  3418. map[key] = stats[key];
  3419. });
  3420. return map;
  3421. };
  3422. var modernStatsTypes = {
  3423. inboundrtp: 'inbound-rtp',
  3424. outboundrtp: 'outbound-rtp',
  3425. candidatepair: 'candidate-pair',
  3426. localcandidate: 'local-candidate',
  3427. remotecandidate: 'remote-candidate'
  3428. };
  3429. var nativeGetStats = window.RTCPeerConnection.prototype.getStats;
  3430. window.RTCPeerConnection.prototype.getStats = function(
  3431. selector,
  3432. onSucc,
  3433. onErr
  3434. ) {
  3435. return nativeGetStats.apply(this, [selector || null])
  3436. .then(function(stats) {
  3437. if (browserDetails.version < 48) {
  3438. stats = makeMapStats(stats);
  3439. }
  3440. if (browserDetails.version < 53 && !onSucc) {
  3441. // Shim only promise getStats with spec-hyphens in type names
  3442. // Leave callback version alone; misc old uses of forEach before Map
  3443. try {
  3444. stats.forEach(function(stat) {
  3445. stat.type = modernStatsTypes[stat.type] || stat.type;
  3446. });
  3447. } catch (e) {
  3448. if (e.name !== 'TypeError') {
  3449. throw e;
  3450. }
  3451. // Avoid TypeError: "type" is read-only, in old versions. 34-43ish
  3452. stats.forEach(function(stat, i) {
  3453. stats.set(i, Object.assign({}, stat, {
  3454. type: modernStatsTypes[stat.type] || stat.type
  3455. }));
  3456. });
  3457. }
  3458. }
  3459. return stats;
  3460. })
  3461. .then(onSucc, onErr);
  3462. };
  3463. },
  3464. shimRemoveStream: function(window) {
  3465. if (!window.RTCPeerConnection ||
  3466. 'removeStream' in window.RTCPeerConnection.prototype) {
  3467. return;
  3468. }
  3469. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  3470. var pc = this;
  3471. utils.deprecated('removeStream', 'removeTrack');
  3472. this.getSenders().forEach(function(sender) {
  3473. if (sender.track && stream.getTracks().indexOf(sender.track) !== -1) {
  3474. pc.removeTrack(sender);
  3475. }
  3476. });
  3477. };
  3478. }
  3479. };
  3480. // Expose public methods.
  3481. module.exports = {
  3482. shimOnTrack: firefoxShim.shimOnTrack,
  3483. shimSourceObject: firefoxShim.shimSourceObject,
  3484. shimPeerConnection: firefoxShim.shimPeerConnection,
  3485. shimRemoveStream: firefoxShim.shimRemoveStream,
  3486. shimGetUserMedia: require('./getusermedia')
  3487. };
  3488. },{"../utils":13,"./getusermedia":11}],11:[function(require,module,exports){
  3489. /*
  3490. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3491. *
  3492. * Use of this source code is governed by a BSD-style license
  3493. * that can be found in the LICENSE file in the root of the source
  3494. * tree.
  3495. */
  3496. /* eslint-env node */
  3497. 'use strict';
  3498. var utils = require('../utils');
  3499. var logging = utils.log;
  3500. // Expose public methods.
  3501. module.exports = function(window) {
  3502. var browserDetails = utils.detectBrowser(window);
  3503. var navigator = window && window.navigator;
  3504. var MediaStreamTrack = window && window.MediaStreamTrack;
  3505. var shimError_ = function(e) {
  3506. return {
  3507. name: {
  3508. InternalError: 'NotReadableError',
  3509. NotSupportedError: 'TypeError',
  3510. PermissionDeniedError: 'NotAllowedError',
  3511. SecurityError: 'NotAllowedError'
  3512. }[e.name] || e.name,
  3513. message: {
  3514. 'The operation is insecure.': 'The request is not allowed by the ' +
  3515. 'user agent or the platform in the current context.'
  3516. }[e.message] || e.message,
  3517. constraint: e.constraint,
  3518. toString: function() {
  3519. return this.name + (this.message && ': ') + this.message;
  3520. }
  3521. };
  3522. };
  3523. // getUserMedia constraints shim.
  3524. var getUserMedia_ = function(constraints, onSuccess, onError) {
  3525. var constraintsToFF37_ = function(c) {
  3526. if (typeof c !== 'object' || c.require) {
  3527. return c;
  3528. }
  3529. var require = [];
  3530. Object.keys(c).forEach(function(key) {
  3531. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  3532. return;
  3533. }
  3534. var r = c[key] = (typeof c[key] === 'object') ?
  3535. c[key] : {ideal: c[key]};
  3536. if (r.min !== undefined ||
  3537. r.max !== undefined || r.exact !== undefined) {
  3538. require.push(key);
  3539. }
  3540. if (r.exact !== undefined) {
  3541. if (typeof r.exact === 'number') {
  3542. r. min = r.max = r.exact;
  3543. } else {
  3544. c[key] = r.exact;
  3545. }
  3546. delete r.exact;
  3547. }
  3548. if (r.ideal !== undefined) {
  3549. c.advanced = c.advanced || [];
  3550. var oc = {};
  3551. if (typeof r.ideal === 'number') {
  3552. oc[key] = {min: r.ideal, max: r.ideal};
  3553. } else {
  3554. oc[key] = r.ideal;
  3555. }
  3556. c.advanced.push(oc);
  3557. delete r.ideal;
  3558. if (!Object.keys(r).length) {
  3559. delete c[key];
  3560. }
  3561. }
  3562. });
  3563. if (require.length) {
  3564. c.require = require;
  3565. }
  3566. return c;
  3567. };
  3568. constraints = JSON.parse(JSON.stringify(constraints));
  3569. if (browserDetails.version < 38) {
  3570. logging('spec: ' + JSON.stringify(constraints));
  3571. if (constraints.audio) {
  3572. constraints.audio = constraintsToFF37_(constraints.audio);
  3573. }
  3574. if (constraints.video) {
  3575. constraints.video = constraintsToFF37_(constraints.video);
  3576. }
  3577. logging('ff37: ' + JSON.stringify(constraints));
  3578. }
  3579. return navigator.mozGetUserMedia(constraints, onSuccess, function(e) {
  3580. onError(shimError_(e));
  3581. });
  3582. };
  3583. // Returns the result of getUserMedia as a Promise.
  3584. var getUserMediaPromise_ = function(constraints) {
  3585. return new Promise(function(resolve, reject) {
  3586. getUserMedia_(constraints, resolve, reject);
  3587. });
  3588. };
  3589. // Shim for mediaDevices on older versions.
  3590. if (!navigator.mediaDevices) {
  3591. navigator.mediaDevices = {getUserMedia: getUserMediaPromise_,
  3592. addEventListener: function() { },
  3593. removeEventListener: function() { }
  3594. };
  3595. }
  3596. navigator.mediaDevices.enumerateDevices =
  3597. navigator.mediaDevices.enumerateDevices || function() {
  3598. return new Promise(function(resolve) {
  3599. var infos = [
  3600. {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
  3601. {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
  3602. ];
  3603. resolve(infos);
  3604. });
  3605. };
  3606. if (browserDetails.version < 41) {
  3607. // Work around http://bugzil.la/1169665
  3608. var orgEnumerateDevices =
  3609. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
  3610. navigator.mediaDevices.enumerateDevices = function() {
  3611. return orgEnumerateDevices().then(undefined, function(e) {
  3612. if (e.name === 'NotFoundError') {
  3613. return [];
  3614. }
  3615. throw e;
  3616. });
  3617. };
  3618. }
  3619. if (browserDetails.version < 49) {
  3620. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  3621. bind(navigator.mediaDevices);
  3622. navigator.mediaDevices.getUserMedia = function(c) {
  3623. return origGetUserMedia(c).then(function(stream) {
  3624. // Work around https://bugzil.la/802326
  3625. if (c.audio && !stream.getAudioTracks().length ||
  3626. c.video && !stream.getVideoTracks().length) {
  3627. stream.getTracks().forEach(function(track) {
  3628. track.stop();
  3629. });
  3630. throw new DOMException('The object can not be found here.',
  3631. 'NotFoundError');
  3632. }
  3633. return stream;
  3634. }, function(e) {
  3635. return Promise.reject(shimError_(e));
  3636. });
  3637. };
  3638. }
  3639. if (!(browserDetails.version > 55 &&
  3640. 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
  3641. var remap = function(obj, a, b) {
  3642. if (a in obj && !(b in obj)) {
  3643. obj[b] = obj[a];
  3644. delete obj[a];
  3645. }
  3646. };
  3647. var nativeGetUserMedia = navigator.mediaDevices.getUserMedia.
  3648. bind(navigator.mediaDevices);
  3649. navigator.mediaDevices.getUserMedia = function(c) {
  3650. if (typeof c === 'object' && typeof c.audio === 'object') {
  3651. c = JSON.parse(JSON.stringify(c));
  3652. remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
  3653. remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
  3654. }
  3655. return nativeGetUserMedia(c);
  3656. };
  3657. if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
  3658. var nativeGetSettings = MediaStreamTrack.prototype.getSettings;
  3659. MediaStreamTrack.prototype.getSettings = function() {
  3660. var obj = nativeGetSettings.apply(this, arguments);
  3661. remap(obj, 'mozAutoGainControl', 'autoGainControl');
  3662. remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
  3663. return obj;
  3664. };
  3665. }
  3666. if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
  3667. var nativeApplyConstraints = MediaStreamTrack.prototype.applyConstraints;
  3668. MediaStreamTrack.prototype.applyConstraints = function(c) {
  3669. if (this.kind === 'audio' && typeof c === 'object') {
  3670. c = JSON.parse(JSON.stringify(c));
  3671. remap(c, 'autoGainControl', 'mozAutoGainControl');
  3672. remap(c, 'noiseSuppression', 'mozNoiseSuppression');
  3673. }
  3674. return nativeApplyConstraints.apply(this, [c]);
  3675. };
  3676. }
  3677. }
  3678. navigator.getUserMedia = function(constraints, onSuccess, onError) {
  3679. if (browserDetails.version < 44) {
  3680. return getUserMedia_(constraints, onSuccess, onError);
  3681. }
  3682. // Replace Firefox 44+'s deprecation warning with unprefixed version.
  3683. utils.deprecated('navigator.getUserMedia',
  3684. 'navigator.mediaDevices.getUserMedia');
  3685. navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
  3686. };
  3687. };
  3688. },{"../utils":13}],12:[function(require,module,exports){
  3689. /*
  3690. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3691. *
  3692. * Use of this source code is governed by a BSD-style license
  3693. * that can be found in the LICENSE file in the root of the source
  3694. * tree.
  3695. */
  3696. 'use strict';
  3697. var utils = require('../utils');
  3698. var safariShim = {
  3699. // TODO: DrAlex, should be here, double check against LayoutTests
  3700. // TODO: once the back-end for the mac port is done, add.
  3701. // TODO: check for webkitGTK+
  3702. // shimPeerConnection: function() { },
  3703. shimLocalStreamsAPI: function(window) {
  3704. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  3705. return;
  3706. }
  3707. if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {
  3708. window.RTCPeerConnection.prototype.getLocalStreams = function() {
  3709. if (!this._localStreams) {
  3710. this._localStreams = [];
  3711. }
  3712. return this._localStreams;
  3713. };
  3714. }
  3715. if (!('getStreamById' in window.RTCPeerConnection.prototype)) {
  3716. window.RTCPeerConnection.prototype.getStreamById = function(id) {
  3717. var result = null;
  3718. if (this._localStreams) {
  3719. this._localStreams.forEach(function(stream) {
  3720. if (stream.id === id) {
  3721. result = stream;
  3722. }
  3723. });
  3724. }
  3725. if (this._remoteStreams) {
  3726. this._remoteStreams.forEach(function(stream) {
  3727. if (stream.id === id) {
  3728. result = stream;
  3729. }
  3730. });
  3731. }
  3732. return result;
  3733. };
  3734. }
  3735. if (!('addStream' in window.RTCPeerConnection.prototype)) {
  3736. var _addTrack = window.RTCPeerConnection.prototype.addTrack;
  3737. window.RTCPeerConnection.prototype.addStream = function(stream) {
  3738. if (!this._localStreams) {
  3739. this._localStreams = [];
  3740. }
  3741. if (this._localStreams.indexOf(stream) === -1) {
  3742. this._localStreams.push(stream);
  3743. }
  3744. var self = this;
  3745. stream.getTracks().forEach(function(track) {
  3746. _addTrack.call(self, track, stream);
  3747. });
  3748. };
  3749. window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
  3750. if (stream) {
  3751. if (!this._localStreams) {
  3752. this._localStreams = [stream];
  3753. } else if (this._localStreams.indexOf(stream) === -1) {
  3754. this._localStreams.push(stream);
  3755. }
  3756. }
  3757. return _addTrack.call(this, track, stream);
  3758. };
  3759. }
  3760. if (!('removeStream' in window.RTCPeerConnection.prototype)) {
  3761. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  3762. if (!this._localStreams) {
  3763. this._localStreams = [];
  3764. }
  3765. var index = this._localStreams.indexOf(stream);
  3766. if (index === -1) {
  3767. return;
  3768. }
  3769. this._localStreams.splice(index, 1);
  3770. var self = this;
  3771. var tracks = stream.getTracks();
  3772. this.getSenders().forEach(function(sender) {
  3773. if (tracks.indexOf(sender.track) !== -1) {
  3774. self.removeTrack(sender);
  3775. }
  3776. });
  3777. };
  3778. }
  3779. },
  3780. shimRemoteStreamsAPI: function(window) {
  3781. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  3782. return;
  3783. }
  3784. if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {
  3785. window.RTCPeerConnection.prototype.getRemoteStreams = function() {
  3786. return this._remoteStreams ? this._remoteStreams : [];
  3787. };
  3788. }
  3789. if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
  3790. Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
  3791. get: function() {
  3792. return this._onaddstream;
  3793. },
  3794. set: function(f) {
  3795. if (this._onaddstream) {
  3796. this.removeEventListener('addstream', this._onaddstream);
  3797. this.removeEventListener('track', this._onaddstreampoly);
  3798. }
  3799. this.addEventListener('addstream', this._onaddstream = f);
  3800. this.addEventListener('track', this._onaddstreampoly = function(e) {
  3801. var stream = e.streams[0];
  3802. if (!this._remoteStreams) {
  3803. this._remoteStreams = [];
  3804. }
  3805. if (this._remoteStreams.indexOf(stream) >= 0) {
  3806. return;
  3807. }
  3808. this._remoteStreams.push(stream);
  3809. var event = new Event('addstream');
  3810. event.stream = e.streams[0];
  3811. this.dispatchEvent(event);
  3812. }.bind(this));
  3813. }
  3814. });
  3815. }
  3816. },
  3817. shimCallbacksAPI: function(window) {
  3818. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  3819. return;
  3820. }
  3821. var prototype = window.RTCPeerConnection.prototype;
  3822. var createOffer = prototype.createOffer;
  3823. var createAnswer = prototype.createAnswer;
  3824. var setLocalDescription = prototype.setLocalDescription;
  3825. var setRemoteDescription = prototype.setRemoteDescription;
  3826. var addIceCandidate = prototype.addIceCandidate;
  3827. prototype.createOffer = function(successCallback, failureCallback) {
  3828. var options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  3829. var promise = createOffer.apply(this, [options]);
  3830. if (!failureCallback) {
  3831. return promise;
  3832. }
  3833. promise.then(successCallback, failureCallback);
  3834. return Promise.resolve();
  3835. };
  3836. prototype.createAnswer = function(successCallback, failureCallback) {
  3837. var options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  3838. var promise = createAnswer.apply(this, [options]);
  3839. if (!failureCallback) {
  3840. return promise;
  3841. }
  3842. promise.then(successCallback, failureCallback);
  3843. return Promise.resolve();
  3844. };
  3845. var withCallback = function(description, successCallback, failureCallback) {
  3846. var promise = setLocalDescription.apply(this, [description]);
  3847. if (!failureCallback) {
  3848. return promise;
  3849. }
  3850. promise.then(successCallback, failureCallback);
  3851. return Promise.resolve();
  3852. };
  3853. prototype.setLocalDescription = withCallback;
  3854. withCallback = function(description, successCallback, failureCallback) {
  3855. var promise = setRemoteDescription.apply(this, [description]);
  3856. if (!failureCallback) {
  3857. return promise;
  3858. }
  3859. promise.then(successCallback, failureCallback);
  3860. return Promise.resolve();
  3861. };
  3862. prototype.setRemoteDescription = withCallback;
  3863. withCallback = function(candidate, successCallback, failureCallback) {
  3864. var promise = addIceCandidate.apply(this, [candidate]);
  3865. if (!failureCallback) {
  3866. return promise;
  3867. }
  3868. promise.then(successCallback, failureCallback);
  3869. return Promise.resolve();
  3870. };
  3871. prototype.addIceCandidate = withCallback;
  3872. },
  3873. shimGetUserMedia: function(window) {
  3874. var navigator = window && window.navigator;
  3875. if (!navigator.getUserMedia) {
  3876. if (navigator.webkitGetUserMedia) {
  3877. navigator.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3878. } else if (navigator.mediaDevices &&
  3879. navigator.mediaDevices.getUserMedia) {
  3880. navigator.getUserMedia = function(constraints, cb, errcb) {
  3881. navigator.mediaDevices.getUserMedia(constraints)
  3882. .then(cb, errcb);
  3883. }.bind(navigator);
  3884. }
  3885. }
  3886. },
  3887. shimRTCIceServerUrls: function(window) {
  3888. // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
  3889. var OrigPeerConnection = window.RTCPeerConnection;
  3890. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  3891. if (pcConfig && pcConfig.iceServers) {
  3892. var newIceServers = [];
  3893. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3894. var server = pcConfig.iceServers[i];
  3895. if (!server.hasOwnProperty('urls') &&
  3896. server.hasOwnProperty('url')) {
  3897. utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  3898. server = JSON.parse(JSON.stringify(server));
  3899. server.urls = server.url;
  3900. delete server.url;
  3901. newIceServers.push(server);
  3902. } else {
  3903. newIceServers.push(pcConfig.iceServers[i]);
  3904. }
  3905. }
  3906. pcConfig.iceServers = newIceServers;
  3907. }
  3908. return new OrigPeerConnection(pcConfig, pcConstraints);
  3909. };
  3910. window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
  3911. // wrap static methods. Currently just generateCertificate.
  3912. if ('generateCertificate' in window.RTCPeerConnection) {
  3913. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  3914. get: function() {
  3915. return OrigPeerConnection.generateCertificate;
  3916. }
  3917. });
  3918. }
  3919. },
  3920. shimTrackEventTransceiver: function(window) {
  3921. // Add event.transceiver member over deprecated event.receiver
  3922. if (typeof window === 'object' && window.RTCPeerConnection &&
  3923. ('receiver' in window.RTCTrackEvent.prototype) &&
  3924. // can't check 'transceiver' in window.RTCTrackEvent.prototype, as it is
  3925. // defined for some reason even when window.RTCTransceiver is not.
  3926. !window.RTCTransceiver) {
  3927. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  3928. get: function() {
  3929. return {receiver: this.receiver};
  3930. }
  3931. });
  3932. }
  3933. },
  3934. shimCreateOfferLegacy: function(window) {
  3935. var origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
  3936. window.RTCPeerConnection.prototype.createOffer = function(offerOptions) {
  3937. var pc = this;
  3938. if (offerOptions) {
  3939. var audioTransceiver = pc.getTransceivers().find(function(transceiver) {
  3940. return transceiver.sender.track &&
  3941. transceiver.sender.track.kind === 'audio';
  3942. });
  3943. if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {
  3944. if (audioTransceiver.direction === 'sendrecv') {
  3945. audioTransceiver.setDirection('sendonly');
  3946. } else if (audioTransceiver.direction === 'recvonly') {
  3947. audioTransceiver.setDirection('inactive');
  3948. }
  3949. } else if (offerOptions.offerToReceiveAudio === true &&
  3950. !audioTransceiver) {
  3951. pc.addTransceiver('audio');
  3952. }
  3953. var videoTransceiver = pc.getTransceivers().find(function(transceiver) {
  3954. return transceiver.sender.track &&
  3955. transceiver.sender.track.kind === 'video';
  3956. });
  3957. if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {
  3958. if (videoTransceiver.direction === 'sendrecv') {
  3959. videoTransceiver.setDirection('sendonly');
  3960. } else if (videoTransceiver.direction === 'recvonly') {
  3961. videoTransceiver.setDirection('inactive');
  3962. }
  3963. } else if (offerOptions.offerToReceiveVideo === true &&
  3964. !videoTransceiver) {
  3965. pc.addTransceiver('video');
  3966. }
  3967. }
  3968. return origCreateOffer.apply(pc, arguments);
  3969. };
  3970. }
  3971. };
  3972. // Expose public methods.
  3973. module.exports = {
  3974. shimCallbacksAPI: safariShim.shimCallbacksAPI,
  3975. shimLocalStreamsAPI: safariShim.shimLocalStreamsAPI,
  3976. shimRemoteStreamsAPI: safariShim.shimRemoteStreamsAPI,
  3977. shimGetUserMedia: safariShim.shimGetUserMedia,
  3978. shimRTCIceServerUrls: safariShim.shimRTCIceServerUrls,
  3979. shimTrackEventTransceiver: safariShim.shimTrackEventTransceiver,
  3980. shimCreateOfferLegacy: safariShim.shimCreateOfferLegacy
  3981. // TODO
  3982. // shimPeerConnection: safariShim.shimPeerConnection
  3983. };
  3984. },{"../utils":13}],13:[function(require,module,exports){
  3985. /*
  3986. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3987. *
  3988. * Use of this source code is governed by a BSD-style license
  3989. * that can be found in the LICENSE file in the root of the source
  3990. * tree.
  3991. */
  3992. /* eslint-env node */
  3993. 'use strict';
  3994. var logDisabled_ = true;
  3995. var deprecationWarnings_ = true;
  3996. // Utility methods.
  3997. var utils = {
  3998. disableLog: function(bool) {
  3999. if (typeof bool !== 'boolean') {
  4000. return new Error('Argument type: ' + typeof bool +
  4001. '. Please use a boolean.');
  4002. }
  4003. logDisabled_ = bool;
  4004. return (bool) ? 'adapter.js logging disabled' :
  4005. 'adapter.js logging enabled';
  4006. },
  4007. /**
  4008. * Disable or enable deprecation warnings
  4009. * @param {!boolean} bool set to true to disable warnings.
  4010. */
  4011. disableWarnings: function(bool) {
  4012. if (typeof bool !== 'boolean') {
  4013. return new Error('Argument type: ' + typeof bool +
  4014. '. Please use a boolean.');
  4015. }
  4016. deprecationWarnings_ = !bool;
  4017. return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
  4018. },
  4019. log: function() {
  4020. if (typeof window === 'object') {
  4021. if (logDisabled_) {
  4022. return;
  4023. }
  4024. if (typeof console !== 'undefined' && typeof console.log === 'function') {
  4025. console.log.apply(console, arguments);
  4026. }
  4027. }
  4028. },
  4029. /**
  4030. * Shows a deprecation warning suggesting the modern and spec-compatible API.
  4031. */
  4032. deprecated: function(oldMethod, newMethod) {
  4033. if (!deprecationWarnings_) {
  4034. return;
  4035. }
  4036. console.warn(oldMethod + ' is deprecated, please use ' + newMethod +
  4037. ' instead.');
  4038. },
  4039. /**
  4040. * Extract browser version out of the provided user agent string.
  4041. *
  4042. * @param {!string} uastring userAgent string.
  4043. * @param {!string} expr Regular expression used as match criteria.
  4044. * @param {!number} pos position in the version string to be returned.
  4045. * @return {!number} browser version.
  4046. */
  4047. extractVersion: function(uastring, expr, pos) {
  4048. var match = uastring.match(expr);
  4049. return match && match.length >= pos && parseInt(match[pos], 10);
  4050. },
  4051. /**
  4052. * Browser detector.
  4053. *
  4054. * @return {object} result containing browser and version
  4055. * properties.
  4056. */
  4057. detectBrowser: function(window) {
  4058. var navigator = window && window.navigator;
  4059. // Returned result object.
  4060. var result = {};
  4061. result.browser = null;
  4062. result.version = null;
  4063. // Fail early if it's not a browser
  4064. if (typeof window === 'undefined' || !window.navigator) {
  4065. result.browser = 'Not a browser.';
  4066. return result;
  4067. }
  4068. // Firefox.
  4069. if (navigator.mozGetUserMedia) {
  4070. result.browser = 'firefox';
  4071. result.version = this.extractVersion(navigator.userAgent,
  4072. /Firefox\/(\d+)\./, 1);
  4073. } else if (navigator.webkitGetUserMedia) {
  4074. // Chrome, Chromium, Webview, Opera, all use the chrome shim for now
  4075. if (window.webkitRTCPeerConnection) {
  4076. result.browser = 'chrome';
  4077. result.version = this.extractVersion(navigator.userAgent,
  4078. /Chrom(e|ium)\/(\d+)\./, 2);
  4079. } else { // Safari (in an unpublished version) or unknown webkit-based.
  4080. if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) {
  4081. result.browser = 'safari';
  4082. result.version = this.extractVersion(navigator.userAgent,
  4083. /AppleWebKit\/(\d+)\./, 1);
  4084. } else { // unknown webkit-based browser.
  4085. result.browser = 'Unsupported webkit-based browser ' +
  4086. 'with GUM support but no WebRTC support.';
  4087. return result;
  4088. }
  4089. }
  4090. } else if (navigator.mediaDevices &&
  4091. navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { // Edge.
  4092. result.browser = 'edge';
  4093. result.version = this.extractVersion(navigator.userAgent,
  4094. /Edge\/(\d+).(\d+)$/, 2);
  4095. } else if (navigator.mediaDevices &&
  4096. navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) {
  4097. // Safari, with webkitGetUserMedia removed.
  4098. result.browser = 'safari';
  4099. result.version = this.extractVersion(navigator.userAgent,
  4100. /AppleWebKit\/(\d+)\./, 1);
  4101. } else { // Default fallthrough: not supported.
  4102. result.browser = 'Not a supported browser.';
  4103. return result;
  4104. }
  4105. return result;
  4106. },
  4107. };
  4108. // Export.
  4109. module.exports = {
  4110. log: utils.log,
  4111. deprecated: utils.deprecated,
  4112. disableLog: utils.disableLog,
  4113. disableWarnings: utils.disableWarnings,
  4114. extractVersion: utils.extractVersion,
  4115. shimCreateObjectURL: utils.shimCreateObjectURL,
  4116. detectBrowser: utils.detectBrowser.bind(utils)
  4117. };
  4118. },{}]},{},[3])(3)
  4119. });