adapter.min.js 190 KB

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