adapter.js 170 KB

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