adapter.min.js 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514
  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(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. /*
  3. * Copyright (c) 2016 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 _adapter_factory = require('./adapter_factory.js');
  12. var adapter = (0, _adapter_factory.adapterFactory)({ window: typeof window === 'undefined' ? undefined : window });
  13. module.exports = adapter; // this is the difference from adapter_core.
  14. },{"./adapter_factory.js":2}],2:[function(require,module,exports){
  15. 'use strict';
  16. Object.defineProperty(exports, "__esModule", {
  17. value: true
  18. });
  19. exports.adapterFactory = adapterFactory;
  20. var _utils = require('./utils');
  21. var utils = _interopRequireWildcard(_utils);
  22. var _chrome_shim = require('./chrome/chrome_shim');
  23. var chromeShim = _interopRequireWildcard(_chrome_shim);
  24. var _firefox_shim = require('./firefox/firefox_shim');
  25. var firefoxShim = _interopRequireWildcard(_firefox_shim);
  26. var _safari_shim = require('./safari/safari_shim');
  27. var safariShim = _interopRequireWildcard(_safari_shim);
  28. var _common_shim = require('./common_shim');
  29. var commonShim = _interopRequireWildcard(_common_shim);
  30. var _sdp = require('sdp');
  31. var sdp = _interopRequireWildcard(_sdp);
  32. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  33. // Shimming starts here.
  34. /*
  35. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  36. *
  37. * Use of this source code is governed by a BSD-style license
  38. * that can be found in the LICENSE file in the root of the source
  39. * tree.
  40. */
  41. function adapterFactory() {
  42. var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  43. window = _ref.window;
  44. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
  45. shimChrome: true,
  46. shimFirefox: true,
  47. shimSafari: true
  48. };
  49. // Utils.
  50. var logging = utils.log;
  51. var browserDetails = utils.detectBrowser(window);
  52. var adapter = {
  53. browserDetails: browserDetails,
  54. commonShim: commonShim,
  55. extractVersion: utils.extractVersion,
  56. disableLog: utils.disableLog,
  57. disableWarnings: utils.disableWarnings,
  58. // Expose sdp as a convenience. For production apps include directly.
  59. sdp: sdp
  60. };
  61. // Shim browser if found.
  62. switch (browserDetails.browser) {
  63. case 'chrome':
  64. if (!chromeShim || !chromeShim.shimPeerConnection || !options.shimChrome) {
  65. logging('Chrome shim is not included in this adapter release.');
  66. return adapter;
  67. }
  68. if (browserDetails.version === null) {
  69. logging('Chrome shim can not determine version, not shimming.');
  70. return adapter;
  71. }
  72. logging('adapter.js shimming chrome.');
  73. // Export to the adapter global object visible in the browser.
  74. adapter.browserShim = chromeShim;
  75. // Must be called before shimPeerConnection.
  76. commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);
  77. commonShim.shimParameterlessSetLocalDescription(window, browserDetails);
  78. chromeShim.shimGetUserMedia(window, browserDetails);
  79. chromeShim.shimMediaStream(window, browserDetails);
  80. chromeShim.shimPeerConnection(window, browserDetails);
  81. chromeShim.shimOnTrack(window, browserDetails);
  82. chromeShim.shimAddTrackRemoveTrack(window, browserDetails);
  83. chromeShim.shimGetSendersWithDtmf(window, browserDetails);
  84. chromeShim.shimGetStats(window, browserDetails);
  85. chromeShim.shimSenderReceiverGetStats(window, browserDetails);
  86. chromeShim.fixNegotiationNeeded(window, browserDetails);
  87. commonShim.shimRTCIceCandidate(window, browserDetails);
  88. commonShim.shimRTCIceCandidateRelayProtocol(window, browserDetails);
  89. commonShim.shimConnectionState(window, browserDetails);
  90. commonShim.shimMaxMessageSize(window, browserDetails);
  91. commonShim.shimSendThrowTypeError(window, browserDetails);
  92. commonShim.removeExtmapAllowMixed(window, browserDetails);
  93. break;
  94. case 'firefox':
  95. if (!firefoxShim || !firefoxShim.shimPeerConnection || !options.shimFirefox) {
  96. logging('Firefox shim is not included in this adapter release.');
  97. return adapter;
  98. }
  99. logging('adapter.js shimming firefox.');
  100. // Export to the adapter global object visible in the browser.
  101. adapter.browserShim = firefoxShim;
  102. // Must be called before shimPeerConnection.
  103. commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);
  104. commonShim.shimParameterlessSetLocalDescription(window, browserDetails);
  105. firefoxShim.shimGetUserMedia(window, browserDetails);
  106. firefoxShim.shimPeerConnection(window, browserDetails);
  107. firefoxShim.shimOnTrack(window, browserDetails);
  108. firefoxShim.shimRemoveStream(window, browserDetails);
  109. firefoxShim.shimSenderGetStats(window, browserDetails);
  110. firefoxShim.shimReceiverGetStats(window, browserDetails);
  111. firefoxShim.shimRTCDataChannel(window, browserDetails);
  112. firefoxShim.shimAddTransceiver(window, browserDetails);
  113. firefoxShim.shimGetParameters(window, browserDetails);
  114. firefoxShim.shimCreateOffer(window, browserDetails);
  115. firefoxShim.shimCreateAnswer(window, browserDetails);
  116. commonShim.shimRTCIceCandidate(window, browserDetails);
  117. commonShim.shimConnectionState(window, browserDetails);
  118. commonShim.shimMaxMessageSize(window, browserDetails);
  119. commonShim.shimSendThrowTypeError(window, browserDetails);
  120. break;
  121. case 'safari':
  122. if (!safariShim || !options.shimSafari) {
  123. logging('Safari shim is not included in this adapter release.');
  124. return adapter;
  125. }
  126. logging('adapter.js shimming safari.');
  127. // Export to the adapter global object visible in the browser.
  128. adapter.browserShim = safariShim;
  129. // Must be called before shimCallbackAPI.
  130. commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);
  131. commonShim.shimParameterlessSetLocalDescription(window, browserDetails);
  132. safariShim.shimRTCIceServerUrls(window, browserDetails);
  133. safariShim.shimCreateOfferLegacy(window, browserDetails);
  134. safariShim.shimCallbacksAPI(window, browserDetails);
  135. safariShim.shimLocalStreamsAPI(window, browserDetails);
  136. safariShim.shimRemoteStreamsAPI(window, browserDetails);
  137. safariShim.shimTrackEventTransceiver(window, browserDetails);
  138. safariShim.shimGetUserMedia(window, browserDetails);
  139. safariShim.shimAudioContext(window, browserDetails);
  140. commonShim.shimRTCIceCandidate(window, browserDetails);
  141. commonShim.shimRTCIceCandidateRelayProtocol(window, browserDetails);
  142. commonShim.shimMaxMessageSize(window, browserDetails);
  143. commonShim.shimSendThrowTypeError(window, browserDetails);
  144. commonShim.removeExtmapAllowMixed(window, browserDetails);
  145. break;
  146. default:
  147. logging('Unsupported browser!');
  148. break;
  149. }
  150. return adapter;
  151. }
  152. // Browser shims.
  153. },{"./chrome/chrome_shim":3,"./common_shim":6,"./firefox/firefox_shim":7,"./safari/safari_shim":10,"./utils":11,"sdp":12}],3:[function(require,module,exports){
  154. /*
  155. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  156. *
  157. * Use of this source code is governed by a BSD-style license
  158. * that can be found in the LICENSE file in the root of the source
  159. * tree.
  160. */
  161. /* eslint-env node */
  162. 'use strict';
  163. Object.defineProperty(exports, "__esModule", {
  164. value: true
  165. });
  166. exports.shimGetDisplayMedia = exports.shimGetUserMedia = undefined;
  167. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  168. var _getusermedia = require('./getusermedia');
  169. Object.defineProperty(exports, 'shimGetUserMedia', {
  170. enumerable: true,
  171. get: function get() {
  172. return _getusermedia.shimGetUserMedia;
  173. }
  174. });
  175. var _getdisplaymedia = require('./getdisplaymedia');
  176. Object.defineProperty(exports, 'shimGetDisplayMedia', {
  177. enumerable: true,
  178. get: function get() {
  179. return _getdisplaymedia.shimGetDisplayMedia;
  180. }
  181. });
  182. exports.shimMediaStream = shimMediaStream;
  183. exports.shimOnTrack = shimOnTrack;
  184. exports.shimGetSendersWithDtmf = shimGetSendersWithDtmf;
  185. exports.shimGetStats = shimGetStats;
  186. exports.shimSenderReceiverGetStats = shimSenderReceiverGetStats;
  187. exports.shimAddTrackRemoveTrackWithNative = shimAddTrackRemoveTrackWithNative;
  188. exports.shimAddTrackRemoveTrack = shimAddTrackRemoveTrack;
  189. exports.shimPeerConnection = shimPeerConnection;
  190. exports.fixNegotiationNeeded = fixNegotiationNeeded;
  191. var _utils = require('../utils.js');
  192. var utils = _interopRequireWildcard(_utils);
  193. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  194. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  195. function shimMediaStream(window) {
  196. window.MediaStream = window.MediaStream || window.webkitMediaStream;
  197. }
  198. function shimOnTrack(window) {
  199. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) {
  200. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  201. get: function get() {
  202. return this._ontrack;
  203. },
  204. set: function set(f) {
  205. if (this._ontrack) {
  206. this.removeEventListener('track', this._ontrack);
  207. }
  208. this.addEventListener('track', this._ontrack = f);
  209. },
  210. enumerable: true,
  211. configurable: true
  212. });
  213. var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
  214. window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
  215. var _this = this;
  216. if (!this._ontrackpoly) {
  217. this._ontrackpoly = function (e) {
  218. // onaddstream does not fire when a track is added to an existing
  219. // stream. But stream.onaddtrack is implemented so we use that.
  220. e.stream.addEventListener('addtrack', function (te) {
  221. var receiver = void 0;
  222. if (window.RTCPeerConnection.prototype.getReceivers) {
  223. receiver = _this.getReceivers().find(function (r) {
  224. return r.track && r.track.id === te.track.id;
  225. });
  226. } else {
  227. receiver = { track: te.track };
  228. }
  229. var event = new Event('track');
  230. event.track = te.track;
  231. event.receiver = receiver;
  232. event.transceiver = { receiver: receiver };
  233. event.streams = [e.stream];
  234. _this.dispatchEvent(event);
  235. });
  236. e.stream.getTracks().forEach(function (track) {
  237. var receiver = void 0;
  238. if (window.RTCPeerConnection.prototype.getReceivers) {
  239. receiver = _this.getReceivers().find(function (r) {
  240. return r.track && r.track.id === track.id;
  241. });
  242. } else {
  243. receiver = { track: track };
  244. }
  245. var event = new Event('track');
  246. event.track = track;
  247. event.receiver = receiver;
  248. event.transceiver = { receiver: receiver };
  249. event.streams = [e.stream];
  250. _this.dispatchEvent(event);
  251. });
  252. };
  253. this.addEventListener('addstream', this._ontrackpoly);
  254. }
  255. return origSetRemoteDescription.apply(this, arguments);
  256. };
  257. } else {
  258. // even if RTCRtpTransceiver is in window, it is only used and
  259. // emitted in unified-plan. Unfortunately this means we need
  260. // to unconditionally wrap the event.
  261. utils.wrapPeerConnectionEvent(window, 'track', function (e) {
  262. if (!e.transceiver) {
  263. Object.defineProperty(e, 'transceiver', { value: { receiver: e.receiver } });
  264. }
  265. return e;
  266. });
  267. }
  268. }
  269. function shimGetSendersWithDtmf(window) {
  270. // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.
  271. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && !('getSenders' in window.RTCPeerConnection.prototype) && 'createDTMFSender' in window.RTCPeerConnection.prototype) {
  272. var shimSenderWithDtmf = function shimSenderWithDtmf(pc, track) {
  273. return {
  274. track: track,
  275. get dtmf() {
  276. if (this._dtmf === undefined) {
  277. if (track.kind === 'audio') {
  278. this._dtmf = pc.createDTMFSender(track);
  279. } else {
  280. this._dtmf = null;
  281. }
  282. }
  283. return this._dtmf;
  284. },
  285. _pc: pc
  286. };
  287. };
  288. // augment addTrack when getSenders is not available.
  289. if (!window.RTCPeerConnection.prototype.getSenders) {
  290. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  291. this._senders = this._senders || [];
  292. return this._senders.slice(); // return a copy of the internal state.
  293. };
  294. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  295. window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
  296. var sender = origAddTrack.apply(this, arguments);
  297. if (!sender) {
  298. sender = shimSenderWithDtmf(this, track);
  299. this._senders.push(sender);
  300. }
  301. return sender;
  302. };
  303. var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  304. window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
  305. origRemoveTrack.apply(this, arguments);
  306. var idx = this._senders.indexOf(sender);
  307. if (idx !== -1) {
  308. this._senders.splice(idx, 1);
  309. }
  310. };
  311. }
  312. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  313. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  314. var _this2 = this;
  315. this._senders = this._senders || [];
  316. origAddStream.apply(this, [stream]);
  317. stream.getTracks().forEach(function (track) {
  318. _this2._senders.push(shimSenderWithDtmf(_this2, track));
  319. });
  320. };
  321. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  322. window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
  323. var _this3 = this;
  324. this._senders = this._senders || [];
  325. origRemoveStream.apply(this, [stream]);
  326. stream.getTracks().forEach(function (track) {
  327. var sender = _this3._senders.find(function (s) {
  328. return s.track === track;
  329. });
  330. if (sender) {
  331. // remove sender
  332. _this3._senders.splice(_this3._senders.indexOf(sender), 1);
  333. }
  334. });
  335. };
  336. } else if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && 'getSenders' in window.RTCPeerConnection.prototype && 'createDTMFSender' in window.RTCPeerConnection.prototype && window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
  337. var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  338. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  339. var _this4 = this;
  340. var senders = origGetSenders.apply(this, []);
  341. senders.forEach(function (sender) {
  342. return sender._pc = _this4;
  343. });
  344. return senders;
  345. };
  346. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  347. get: function get() {
  348. if (this._dtmf === undefined) {
  349. if (this.track.kind === 'audio') {
  350. this._dtmf = this._pc.createDTMFSender(this.track);
  351. } else {
  352. this._dtmf = null;
  353. }
  354. }
  355. return this._dtmf;
  356. }
  357. });
  358. }
  359. }
  360. function shimGetStats(window) {
  361. if (!window.RTCPeerConnection) {
  362. return;
  363. }
  364. var origGetStats = window.RTCPeerConnection.prototype.getStats;
  365. window.RTCPeerConnection.prototype.getStats = function getStats() {
  366. var _this5 = this;
  367. var _arguments = Array.prototype.slice.call(arguments),
  368. selector = _arguments[0],
  369. onSucc = _arguments[1],
  370. onErr = _arguments[2];
  371. // If selector is a function then we are in the old style stats so just
  372. // pass back the original getStats format to avoid breaking old users.
  373. if (arguments.length > 0 && typeof selector === 'function') {
  374. return origGetStats.apply(this, arguments);
  375. }
  376. // When spec-style getStats is supported, return those when called with
  377. // either no arguments or the selector argument is null.
  378. if (origGetStats.length === 0 && (arguments.length === 0 || typeof selector !== 'function')) {
  379. return origGetStats.apply(this, []);
  380. }
  381. var fixChromeStats_ = function fixChromeStats_(response) {
  382. var standardReport = {};
  383. var reports = response.result();
  384. reports.forEach(function (report) {
  385. var standardStats = {
  386. id: report.id,
  387. timestamp: report.timestamp,
  388. type: {
  389. localcandidate: 'local-candidate',
  390. remotecandidate: 'remote-candidate'
  391. }[report.type] || report.type
  392. };
  393. report.names().forEach(function (name) {
  394. standardStats[name] = report.stat(name);
  395. });
  396. standardReport[standardStats.id] = standardStats;
  397. });
  398. return standardReport;
  399. };
  400. // shim getStats with maplike support
  401. var makeMapStats = function makeMapStats(stats) {
  402. return new Map(Object.keys(stats).map(function (key) {
  403. return [key, stats[key]];
  404. }));
  405. };
  406. if (arguments.length >= 2) {
  407. var successCallbackWrapper_ = function successCallbackWrapper_(response) {
  408. onSucc(makeMapStats(fixChromeStats_(response)));
  409. };
  410. return origGetStats.apply(this, [successCallbackWrapper_, selector]);
  411. }
  412. // promise-support
  413. return new Promise(function (resolve, reject) {
  414. origGetStats.apply(_this5, [function (response) {
  415. resolve(makeMapStats(fixChromeStats_(response)));
  416. }, reject]);
  417. }).then(onSucc, onErr);
  418. };
  419. }
  420. function shimSenderReceiverGetStats(window) {
  421. if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && window.RTCRtpSender && window.RTCRtpReceiver)) {
  422. return;
  423. }
  424. // shim sender stats.
  425. if (!('getStats' in window.RTCRtpSender.prototype)) {
  426. var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  427. if (origGetSenders) {
  428. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  429. var _this6 = this;
  430. var senders = origGetSenders.apply(this, []);
  431. senders.forEach(function (sender) {
  432. return sender._pc = _this6;
  433. });
  434. return senders;
  435. };
  436. }
  437. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  438. if (origAddTrack) {
  439. window.RTCPeerConnection.prototype.addTrack = function addTrack() {
  440. var sender = origAddTrack.apply(this, arguments);
  441. sender._pc = this;
  442. return sender;
  443. };
  444. }
  445. window.RTCRtpSender.prototype.getStats = function getStats() {
  446. var sender = this;
  447. return this._pc.getStats().then(function (result) {
  448. return (
  449. /* Note: this will include stats of all senders that
  450. * send a track with the same id as sender.track as
  451. * it is not possible to identify the RTCRtpSender.
  452. */
  453. utils.filterStats(result, sender.track, true)
  454. );
  455. });
  456. };
  457. }
  458. // shim receiver stats.
  459. if (!('getStats' in window.RTCRtpReceiver.prototype)) {
  460. var origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
  461. if (origGetReceivers) {
  462. window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {
  463. var _this7 = this;
  464. var receivers = origGetReceivers.apply(this, []);
  465. receivers.forEach(function (receiver) {
  466. return receiver._pc = _this7;
  467. });
  468. return receivers;
  469. };
  470. }
  471. utils.wrapPeerConnectionEvent(window, 'track', function (e) {
  472. e.receiver._pc = e.srcElement;
  473. return e;
  474. });
  475. window.RTCRtpReceiver.prototype.getStats = function getStats() {
  476. var receiver = this;
  477. return this._pc.getStats().then(function (result) {
  478. return utils.filterStats(result, receiver.track, false);
  479. });
  480. };
  481. }
  482. if (!('getStats' in window.RTCRtpSender.prototype && 'getStats' in window.RTCRtpReceiver.prototype)) {
  483. return;
  484. }
  485. // shim RTCPeerConnection.getStats(track).
  486. var origGetStats = window.RTCPeerConnection.prototype.getStats;
  487. window.RTCPeerConnection.prototype.getStats = function getStats() {
  488. if (arguments.length > 0 && arguments[0] instanceof window.MediaStreamTrack) {
  489. var track = arguments[0];
  490. var sender = void 0;
  491. var receiver = void 0;
  492. var err = void 0;
  493. this.getSenders().forEach(function (s) {
  494. if (s.track === track) {
  495. if (sender) {
  496. err = true;
  497. } else {
  498. sender = s;
  499. }
  500. }
  501. });
  502. this.getReceivers().forEach(function (r) {
  503. if (r.track === track) {
  504. if (receiver) {
  505. err = true;
  506. } else {
  507. receiver = r;
  508. }
  509. }
  510. return r.track === track;
  511. });
  512. if (err || sender && receiver) {
  513. return Promise.reject(new DOMException('There are more than one sender or receiver for the track.', 'InvalidAccessError'));
  514. } else if (sender) {
  515. return sender.getStats();
  516. } else if (receiver) {
  517. return receiver.getStats();
  518. }
  519. return Promise.reject(new DOMException('There is no sender or receiver for the track.', 'InvalidAccessError'));
  520. }
  521. return origGetStats.apply(this, arguments);
  522. };
  523. }
  524. function shimAddTrackRemoveTrackWithNative(window) {
  525. // shim addTrack/removeTrack with native variants in order to make
  526. // the interactions with legacy getLocalStreams behave as in other browsers.
  527. // Keeps a mapping stream.id => [stream, rtpsenders...]
  528. window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
  529. var _this8 = this;
  530. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  531. return Object.keys(this._shimmedLocalStreams).map(function (streamId) {
  532. return _this8._shimmedLocalStreams[streamId][0];
  533. });
  534. };
  535. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  536. window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
  537. if (!stream) {
  538. return origAddTrack.apply(this, arguments);
  539. }
  540. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  541. var sender = origAddTrack.apply(this, arguments);
  542. if (!this._shimmedLocalStreams[stream.id]) {
  543. this._shimmedLocalStreams[stream.id] = [stream, sender];
  544. } else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) {
  545. this._shimmedLocalStreams[stream.id].push(sender);
  546. }
  547. return sender;
  548. };
  549. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  550. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  551. var _this9 = this;
  552. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  553. stream.getTracks().forEach(function (track) {
  554. var alreadyExists = _this9.getSenders().find(function (s) {
  555. return s.track === track;
  556. });
  557. if (alreadyExists) {
  558. throw new DOMException('Track already exists.', 'InvalidAccessError');
  559. }
  560. });
  561. var existingSenders = this.getSenders();
  562. origAddStream.apply(this, arguments);
  563. var newSenders = this.getSenders().filter(function (newSender) {
  564. return existingSenders.indexOf(newSender) === -1;
  565. });
  566. this._shimmedLocalStreams[stream.id] = [stream].concat(newSenders);
  567. };
  568. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  569. window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
  570. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  571. delete this._shimmedLocalStreams[stream.id];
  572. return origRemoveStream.apply(this, arguments);
  573. };
  574. var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  575. window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
  576. var _this10 = this;
  577. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  578. if (sender) {
  579. Object.keys(this._shimmedLocalStreams).forEach(function (streamId) {
  580. var idx = _this10._shimmedLocalStreams[streamId].indexOf(sender);
  581. if (idx !== -1) {
  582. _this10._shimmedLocalStreams[streamId].splice(idx, 1);
  583. }
  584. if (_this10._shimmedLocalStreams[streamId].length === 1) {
  585. delete _this10._shimmedLocalStreams[streamId];
  586. }
  587. });
  588. }
  589. return origRemoveTrack.apply(this, arguments);
  590. };
  591. }
  592. function shimAddTrackRemoveTrack(window, browserDetails) {
  593. if (!window.RTCPeerConnection) {
  594. return;
  595. }
  596. // shim addTrack and removeTrack.
  597. if (window.RTCPeerConnection.prototype.addTrack && browserDetails.version >= 65) {
  598. return shimAddTrackRemoveTrackWithNative(window);
  599. }
  600. // also shim pc.getLocalStreams when addTrack is shimmed
  601. // to return the original streams.
  602. var origGetLocalStreams = window.RTCPeerConnection.prototype.getLocalStreams;
  603. window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
  604. var _this11 = this;
  605. var nativeStreams = origGetLocalStreams.apply(this);
  606. this._reverseStreams = this._reverseStreams || {};
  607. return nativeStreams.map(function (stream) {
  608. return _this11._reverseStreams[stream.id];
  609. });
  610. };
  611. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  612. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  613. var _this12 = this;
  614. this._streams = this._streams || {};
  615. this._reverseStreams = this._reverseStreams || {};
  616. stream.getTracks().forEach(function (track) {
  617. var alreadyExists = _this12.getSenders().find(function (s) {
  618. return s.track === track;
  619. });
  620. if (alreadyExists) {
  621. throw new DOMException('Track already exists.', 'InvalidAccessError');
  622. }
  623. });
  624. // Add identity mapping for consistency with addTrack.
  625. // Unless this is being used with a stream from addTrack.
  626. if (!this._reverseStreams[stream.id]) {
  627. var newStream = new window.MediaStream(stream.getTracks());
  628. this._streams[stream.id] = newStream;
  629. this._reverseStreams[newStream.id] = stream;
  630. stream = newStream;
  631. }
  632. origAddStream.apply(this, [stream]);
  633. };
  634. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  635. window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
  636. this._streams = this._streams || {};
  637. this._reverseStreams = this._reverseStreams || {};
  638. origRemoveStream.apply(this, [this._streams[stream.id] || stream]);
  639. delete this._reverseStreams[this._streams[stream.id] ? this._streams[stream.id].id : stream.id];
  640. delete this._streams[stream.id];
  641. };
  642. window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
  643. var _this13 = this;
  644. if (this.signalingState === 'closed') {
  645. throw new DOMException('The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError');
  646. }
  647. var streams = [].slice.call(arguments, 1);
  648. if (streams.length !== 1 || !streams[0].getTracks().find(function (t) {
  649. return t === track;
  650. })) {
  651. // this is not fully correct but all we can manage without
  652. // [[associated MediaStreams]] internal slot.
  653. throw new DOMException('The adapter.js addTrack polyfill only supports a single ' + ' stream which is associated with the specified track.', 'NotSupportedError');
  654. }
  655. var alreadyExists = this.getSenders().find(function (s) {
  656. return s.track === track;
  657. });
  658. if (alreadyExists) {
  659. throw new DOMException('Track already exists.', 'InvalidAccessError');
  660. }
  661. this._streams = this._streams || {};
  662. this._reverseStreams = this._reverseStreams || {};
  663. var oldStream = this._streams[stream.id];
  664. if (oldStream) {
  665. // this is using odd Chrome behaviour, use with caution:
  666. // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
  667. // Note: we rely on the high-level addTrack/dtmf shim to
  668. // create the sender with a dtmf sender.
  669. oldStream.addTrack(track);
  670. // Trigger ONN async.
  671. Promise.resolve().then(function () {
  672. _this13.dispatchEvent(new Event('negotiationneeded'));
  673. });
  674. } else {
  675. var newStream = new window.MediaStream([track]);
  676. this._streams[stream.id] = newStream;
  677. this._reverseStreams[newStream.id] = stream;
  678. this.addStream(newStream);
  679. }
  680. return this.getSenders().find(function (s) {
  681. return s.track === track;
  682. });
  683. };
  684. // replace the internal stream id with the external one and
  685. // vice versa.
  686. function replaceInternalStreamId(pc, description) {
  687. var sdp = description.sdp;
  688. Object.keys(pc._reverseStreams || []).forEach(function (internalId) {
  689. var externalStream = pc._reverseStreams[internalId];
  690. var internalStream = pc._streams[externalStream.id];
  691. sdp = sdp.replace(new RegExp(internalStream.id, 'g'), externalStream.id);
  692. });
  693. return new RTCSessionDescription({
  694. type: description.type,
  695. sdp: sdp
  696. });
  697. }
  698. function replaceExternalStreamId(pc, description) {
  699. var sdp = description.sdp;
  700. Object.keys(pc._reverseStreams || []).forEach(function (internalId) {
  701. var externalStream = pc._reverseStreams[internalId];
  702. var internalStream = pc._streams[externalStream.id];
  703. sdp = sdp.replace(new RegExp(externalStream.id, 'g'), internalStream.id);
  704. });
  705. return new RTCSessionDescription({
  706. type: description.type,
  707. sdp: sdp
  708. });
  709. }
  710. ['createOffer', 'createAnswer'].forEach(function (method) {
  711. var nativeMethod = window.RTCPeerConnection.prototype[method];
  712. var methodObj = _defineProperty({}, method, function () {
  713. var _this14 = this;
  714. var args = arguments;
  715. var isLegacyCall = arguments.length && typeof arguments[0] === 'function';
  716. if (isLegacyCall) {
  717. return nativeMethod.apply(this, [function (description) {
  718. var desc = replaceInternalStreamId(_this14, description);
  719. args[0].apply(null, [desc]);
  720. }, function (err) {
  721. if (args[1]) {
  722. args[1].apply(null, err);
  723. }
  724. }, arguments[2]]);
  725. }
  726. return nativeMethod.apply(this, arguments).then(function (description) {
  727. return replaceInternalStreamId(_this14, description);
  728. });
  729. });
  730. window.RTCPeerConnection.prototype[method] = methodObj[method];
  731. });
  732. var origSetLocalDescription = window.RTCPeerConnection.prototype.setLocalDescription;
  733. window.RTCPeerConnection.prototype.setLocalDescription = function setLocalDescription() {
  734. if (!arguments.length || !arguments[0].type) {
  735. return origSetLocalDescription.apply(this, arguments);
  736. }
  737. arguments[0] = replaceExternalStreamId(this, arguments[0]);
  738. return origSetLocalDescription.apply(this, arguments);
  739. };
  740. // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier
  741. var origLocalDescription = Object.getOwnPropertyDescriptor(window.RTCPeerConnection.prototype, 'localDescription');
  742. Object.defineProperty(window.RTCPeerConnection.prototype, 'localDescription', {
  743. get: function get() {
  744. var description = origLocalDescription.get.apply(this);
  745. if (description.type === '') {
  746. return description;
  747. }
  748. return replaceInternalStreamId(this, description);
  749. }
  750. });
  751. window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
  752. var _this15 = this;
  753. if (this.signalingState === 'closed') {
  754. throw new DOMException('The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError');
  755. }
  756. // We can not yet check for sender instanceof RTCRtpSender
  757. // since we shim RTPSender. So we check if sender._pc is set.
  758. if (!sender._pc) {
  759. throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' + 'does not implement interface RTCRtpSender.', 'TypeError');
  760. }
  761. var isLocal = sender._pc === this;
  762. if (!isLocal) {
  763. throw new DOMException('Sender was not created by this connection.', 'InvalidAccessError');
  764. }
  765. // Search for the native stream the senders track belongs to.
  766. this._streams = this._streams || {};
  767. var stream = void 0;
  768. Object.keys(this._streams).forEach(function (streamid) {
  769. var hasTrack = _this15._streams[streamid].getTracks().find(function (track) {
  770. return sender.track === track;
  771. });
  772. if (hasTrack) {
  773. stream = _this15._streams[streamid];
  774. }
  775. });
  776. if (stream) {
  777. if (stream.getTracks().length === 1) {
  778. // if this is the last track of the stream, remove the stream. This
  779. // takes care of any shimmed _senders.
  780. this.removeStream(this._reverseStreams[stream.id]);
  781. } else {
  782. // relying on the same odd chrome behaviour as above.
  783. stream.removeTrack(sender.track);
  784. }
  785. this.dispatchEvent(new Event('negotiationneeded'));
  786. }
  787. };
  788. }
  789. function shimPeerConnection(window, browserDetails) {
  790. if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) {
  791. // very basic support for old versions.
  792. window.RTCPeerConnection = window.webkitRTCPeerConnection;
  793. }
  794. if (!window.RTCPeerConnection) {
  795. return;
  796. }
  797. // shim implicit creation of RTCSessionDescription/RTCIceCandidate
  798. if (browserDetails.version < 53) {
  799. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'].forEach(function (method) {
  800. var nativeMethod = window.RTCPeerConnection.prototype[method];
  801. var methodObj = _defineProperty({}, method, function () {
  802. arguments[0] = new (method === 'addIceCandidate' ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]);
  803. return nativeMethod.apply(this, arguments);
  804. });
  805. window.RTCPeerConnection.prototype[method] = methodObj[method];
  806. });
  807. }
  808. }
  809. // Attempt to fix ONN in plan-b mode.
  810. function fixNegotiationNeeded(window, browserDetails) {
  811. utils.wrapPeerConnectionEvent(window, 'negotiationneeded', function (e) {
  812. var pc = e.target;
  813. if (browserDetails.version < 72 || pc.getConfiguration && pc.getConfiguration().sdpSemantics === 'plan-b') {
  814. if (pc.signalingState !== 'stable') {
  815. return;
  816. }
  817. }
  818. return e;
  819. });
  820. }
  821. },{"../utils.js":11,"./getdisplaymedia":4,"./getusermedia":5}],4:[function(require,module,exports){
  822. /*
  823. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  824. *
  825. * Use of this source code is governed by a BSD-style license
  826. * that can be found in the LICENSE file in the root of the source
  827. * tree.
  828. */
  829. /* eslint-env node */
  830. 'use strict';
  831. Object.defineProperty(exports, "__esModule", {
  832. value: true
  833. });
  834. exports.shimGetDisplayMedia = shimGetDisplayMedia;
  835. function shimGetDisplayMedia(window, getSourceId) {
  836. if (window.navigator.mediaDevices && 'getDisplayMedia' in window.navigator.mediaDevices) {
  837. return;
  838. }
  839. if (!window.navigator.mediaDevices) {
  840. return;
  841. }
  842. // getSourceId is a function that returns a promise resolving with
  843. // the sourceId of the screen/window/tab to be shared.
  844. if (typeof getSourceId !== 'function') {
  845. console.error('shimGetDisplayMedia: getSourceId argument is not ' + 'a function');
  846. return;
  847. }
  848. window.navigator.mediaDevices.getDisplayMedia = function getDisplayMedia(constraints) {
  849. return getSourceId(constraints).then(function (sourceId) {
  850. var widthSpecified = constraints.video && constraints.video.width;
  851. var heightSpecified = constraints.video && constraints.video.height;
  852. var frameRateSpecified = constraints.video && constraints.video.frameRate;
  853. constraints.video = {
  854. mandatory: {
  855. chromeMediaSource: 'desktop',
  856. chromeMediaSourceId: sourceId,
  857. maxFrameRate: frameRateSpecified || 3
  858. }
  859. };
  860. if (widthSpecified) {
  861. constraints.video.mandatory.maxWidth = widthSpecified;
  862. }
  863. if (heightSpecified) {
  864. constraints.video.mandatory.maxHeight = heightSpecified;
  865. }
  866. return window.navigator.mediaDevices.getUserMedia(constraints);
  867. });
  868. };
  869. }
  870. },{}],5:[function(require,module,exports){
  871. /*
  872. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  873. *
  874. * Use of this source code is governed by a BSD-style license
  875. * that can be found in the LICENSE file in the root of the source
  876. * tree.
  877. */
  878. /* eslint-env node */
  879. 'use strict';
  880. Object.defineProperty(exports, "__esModule", {
  881. value: true
  882. });
  883. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  884. exports.shimGetUserMedia = shimGetUserMedia;
  885. var _utils = require('../utils.js');
  886. var utils = _interopRequireWildcard(_utils);
  887. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  888. var logging = utils.log;
  889. function shimGetUserMedia(window, browserDetails) {
  890. var navigator = window && window.navigator;
  891. if (!navigator.mediaDevices) {
  892. return;
  893. }
  894. var constraintsToChrome_ = function constraintsToChrome_(c) {
  895. if ((typeof c === 'undefined' ? 'undefined' : _typeof(c)) !== 'object' || c.mandatory || c.optional) {
  896. return c;
  897. }
  898. var cc = {};
  899. Object.keys(c).forEach(function (key) {
  900. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  901. return;
  902. }
  903. var r = _typeof(c[key]) === 'object' ? c[key] : { ideal: c[key] };
  904. if (r.exact !== undefined && typeof r.exact === 'number') {
  905. r.min = r.max = r.exact;
  906. }
  907. var oldname_ = function oldname_(prefix, name) {
  908. if (prefix) {
  909. return prefix + name.charAt(0).toUpperCase() + name.slice(1);
  910. }
  911. return name === 'deviceId' ? 'sourceId' : name;
  912. };
  913. if (r.ideal !== undefined) {
  914. cc.optional = cc.optional || [];
  915. var oc = {};
  916. if (typeof r.ideal === 'number') {
  917. oc[oldname_('min', key)] = r.ideal;
  918. cc.optional.push(oc);
  919. oc = {};
  920. oc[oldname_('max', key)] = r.ideal;
  921. cc.optional.push(oc);
  922. } else {
  923. oc[oldname_('', key)] = r.ideal;
  924. cc.optional.push(oc);
  925. }
  926. }
  927. if (r.exact !== undefined && typeof r.exact !== 'number') {
  928. cc.mandatory = cc.mandatory || {};
  929. cc.mandatory[oldname_('', key)] = r.exact;
  930. } else {
  931. ['min', 'max'].forEach(function (mix) {
  932. if (r[mix] !== undefined) {
  933. cc.mandatory = cc.mandatory || {};
  934. cc.mandatory[oldname_(mix, key)] = r[mix];
  935. }
  936. });
  937. }
  938. });
  939. if (c.advanced) {
  940. cc.optional = (cc.optional || []).concat(c.advanced);
  941. }
  942. return cc;
  943. };
  944. var shimConstraints_ = function shimConstraints_(constraints, func) {
  945. if (browserDetails.version >= 61) {
  946. return func(constraints);
  947. }
  948. constraints = JSON.parse(JSON.stringify(constraints));
  949. if (constraints && _typeof(constraints.audio) === 'object') {
  950. var remap = function remap(obj, a, b) {
  951. if (a in obj && !(b in obj)) {
  952. obj[b] = obj[a];
  953. delete obj[a];
  954. }
  955. };
  956. constraints = JSON.parse(JSON.stringify(constraints));
  957. remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
  958. remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
  959. constraints.audio = constraintsToChrome_(constraints.audio);
  960. }
  961. if (constraints && _typeof(constraints.video) === 'object') {
  962. // Shim facingMode for mobile & surface pro.
  963. var face = constraints.video.facingMode;
  964. face = face && ((typeof face === 'undefined' ? 'undefined' : _typeof(face)) === 'object' ? face : { ideal: face });
  965. var getSupportedFacingModeLies = browserDetails.version < 66;
  966. if (face && (face.exact === 'user' || face.exact === 'environment' || face.ideal === 'user' || face.ideal === 'environment') && !(navigator.mediaDevices.getSupportedConstraints && navigator.mediaDevices.getSupportedConstraints().facingMode && !getSupportedFacingModeLies)) {
  967. delete constraints.video.facingMode;
  968. var matches = void 0;
  969. if (face.exact === 'environment' || face.ideal === 'environment') {
  970. matches = ['back', 'rear'];
  971. } else if (face.exact === 'user' || face.ideal === 'user') {
  972. matches = ['front'];
  973. }
  974. if (matches) {
  975. // Look for matches in label, or use last cam for back (typical).
  976. return navigator.mediaDevices.enumerateDevices().then(function (devices) {
  977. devices = devices.filter(function (d) {
  978. return d.kind === 'videoinput';
  979. });
  980. var dev = devices.find(function (d) {
  981. return matches.some(function (match) {
  982. return d.label.toLowerCase().includes(match);
  983. });
  984. });
  985. if (!dev && devices.length && matches.includes('back')) {
  986. dev = devices[devices.length - 1]; // more likely the back cam
  987. }
  988. if (dev) {
  989. constraints.video.deviceId = face.exact ? { exact: dev.deviceId } : { ideal: dev.deviceId };
  990. }
  991. constraints.video = constraintsToChrome_(constraints.video);
  992. logging('chrome: ' + JSON.stringify(constraints));
  993. return func(constraints);
  994. });
  995. }
  996. }
  997. constraints.video = constraintsToChrome_(constraints.video);
  998. }
  999. logging('chrome: ' + JSON.stringify(constraints));
  1000. return func(constraints);
  1001. };
  1002. var shimError_ = function shimError_(e) {
  1003. if (browserDetails.version >= 64) {
  1004. return e;
  1005. }
  1006. return {
  1007. name: {
  1008. PermissionDeniedError: 'NotAllowedError',
  1009. PermissionDismissedError: 'NotAllowedError',
  1010. InvalidStateError: 'NotAllowedError',
  1011. DevicesNotFoundError: 'NotFoundError',
  1012. ConstraintNotSatisfiedError: 'OverconstrainedError',
  1013. TrackStartError: 'NotReadableError',
  1014. MediaDeviceFailedDueToShutdown: 'NotAllowedError',
  1015. MediaDeviceKillSwitchOn: 'NotAllowedError',
  1016. TabCaptureError: 'AbortError',
  1017. ScreenCaptureError: 'AbortError',
  1018. DeviceCaptureError: 'AbortError'
  1019. }[e.name] || e.name,
  1020. message: e.message,
  1021. constraint: e.constraint || e.constraintName,
  1022. toString: function toString() {
  1023. return this.name + (this.message && ': ') + this.message;
  1024. }
  1025. };
  1026. };
  1027. var getUserMedia_ = function getUserMedia_(constraints, onSuccess, onError) {
  1028. shimConstraints_(constraints, function (c) {
  1029. navigator.webkitGetUserMedia(c, onSuccess, function (e) {
  1030. if (onError) {
  1031. onError(shimError_(e));
  1032. }
  1033. });
  1034. });
  1035. };
  1036. navigator.getUserMedia = getUserMedia_.bind(navigator);
  1037. // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
  1038. // function which returns a Promise, it does not accept spec-style
  1039. // constraints.
  1040. if (navigator.mediaDevices.getUserMedia) {
  1041. var origGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
  1042. navigator.mediaDevices.getUserMedia = function (cs) {
  1043. return shimConstraints_(cs, function (c) {
  1044. return origGetUserMedia(c).then(function (stream) {
  1045. if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) {
  1046. stream.getTracks().forEach(function (track) {
  1047. track.stop();
  1048. });
  1049. throw new DOMException('', 'NotFoundError');
  1050. }
  1051. return stream;
  1052. }, function (e) {
  1053. return Promise.reject(shimError_(e));
  1054. });
  1055. });
  1056. };
  1057. }
  1058. }
  1059. },{"../utils.js":11}],6:[function(require,module,exports){
  1060. /*
  1061. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  1062. *
  1063. * Use of this source code is governed by a BSD-style license
  1064. * that can be found in the LICENSE file in the root of the source
  1065. * tree.
  1066. */
  1067. /* eslint-env node */
  1068. 'use strict';
  1069. Object.defineProperty(exports, "__esModule", {
  1070. value: true
  1071. });
  1072. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  1073. exports.shimRTCIceCandidate = shimRTCIceCandidate;
  1074. exports.shimRTCIceCandidateRelayProtocol = shimRTCIceCandidateRelayProtocol;
  1075. exports.shimMaxMessageSize = shimMaxMessageSize;
  1076. exports.shimSendThrowTypeError = shimSendThrowTypeError;
  1077. exports.shimConnectionState = shimConnectionState;
  1078. exports.removeExtmapAllowMixed = removeExtmapAllowMixed;
  1079. exports.shimAddIceCandidateNullOrEmpty = shimAddIceCandidateNullOrEmpty;
  1080. exports.shimParameterlessSetLocalDescription = shimParameterlessSetLocalDescription;
  1081. var _sdp = require('sdp');
  1082. var _sdp2 = _interopRequireDefault(_sdp);
  1083. var _utils = require('./utils');
  1084. var utils = _interopRequireWildcard(_utils);
  1085. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  1086. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1087. function shimRTCIceCandidate(window) {
  1088. // foundation is arbitrarily chosen as an indicator for full support for
  1089. // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
  1090. if (!window.RTCIceCandidate || window.RTCIceCandidate && 'foundation' in window.RTCIceCandidate.prototype) {
  1091. return;
  1092. }
  1093. var NativeRTCIceCandidate = window.RTCIceCandidate;
  1094. window.RTCIceCandidate = function RTCIceCandidate(args) {
  1095. // Remove the a= which shouldn't be part of the candidate string.
  1096. if ((typeof args === 'undefined' ? 'undefined' : _typeof(args)) === 'object' && args.candidate && args.candidate.indexOf('a=') === 0) {
  1097. args = JSON.parse(JSON.stringify(args));
  1098. args.candidate = args.candidate.substr(2);
  1099. }
  1100. if (args.candidate && args.candidate.length) {
  1101. // Augment the native candidate with the parsed fields.
  1102. var nativeCandidate = new NativeRTCIceCandidate(args);
  1103. var parsedCandidate = _sdp2.default.parseCandidate(args.candidate);
  1104. var augmentedCandidate = Object.assign(nativeCandidate, parsedCandidate);
  1105. // Add a serializer that does not serialize the extra attributes.
  1106. augmentedCandidate.toJSON = function toJSON() {
  1107. return {
  1108. candidate: augmentedCandidate.candidate,
  1109. sdpMid: augmentedCandidate.sdpMid,
  1110. sdpMLineIndex: augmentedCandidate.sdpMLineIndex,
  1111. usernameFragment: augmentedCandidate.usernameFragment
  1112. };
  1113. };
  1114. return augmentedCandidate;
  1115. }
  1116. return new NativeRTCIceCandidate(args);
  1117. };
  1118. window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype;
  1119. // Hook up the augmented candidate in onicecandidate and
  1120. // addEventListener('icecandidate', ...)
  1121. utils.wrapPeerConnectionEvent(window, 'icecandidate', function (e) {
  1122. if (e.candidate) {
  1123. Object.defineProperty(e, 'candidate', {
  1124. value: new window.RTCIceCandidate(e.candidate),
  1125. writable: 'false'
  1126. });
  1127. }
  1128. return e;
  1129. });
  1130. }
  1131. function shimRTCIceCandidateRelayProtocol(window) {
  1132. if (!window.RTCIceCandidate || window.RTCIceCandidate && 'relayProtocol' in window.RTCIceCandidate.prototype) {
  1133. return;
  1134. }
  1135. // Hook up the augmented candidate in onicecandidate and
  1136. // addEventListener('icecandidate', ...)
  1137. utils.wrapPeerConnectionEvent(window, 'icecandidate', function (e) {
  1138. if (e.candidate) {
  1139. var parsedCandidate = _sdp2.default.parseCandidate(e.candidate.candidate);
  1140. if (parsedCandidate.type === 'relay') {
  1141. // This is a libwebrtc-specific mapping of local type preference
  1142. // to relayProtocol.
  1143. e.candidate.relayProtocol = {
  1144. 0: 'tls',
  1145. 1: 'tcp',
  1146. 2: 'udp'
  1147. }[parsedCandidate.priority >> 24];
  1148. }
  1149. }
  1150. return e;
  1151. });
  1152. }
  1153. function shimMaxMessageSize(window, browserDetails) {
  1154. if (!window.RTCPeerConnection) {
  1155. return;
  1156. }
  1157. if (!('sctp' in window.RTCPeerConnection.prototype)) {
  1158. Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', {
  1159. get: function get() {
  1160. return typeof this._sctp === 'undefined' ? null : this._sctp;
  1161. }
  1162. });
  1163. }
  1164. var sctpInDescription = function sctpInDescription(description) {
  1165. if (!description || !description.sdp) {
  1166. return false;
  1167. }
  1168. var sections = _sdp2.default.splitSections(description.sdp);
  1169. sections.shift();
  1170. return sections.some(function (mediaSection) {
  1171. var mLine = _sdp2.default.parseMLine(mediaSection);
  1172. return mLine && mLine.kind === 'application' && mLine.protocol.indexOf('SCTP') !== -1;
  1173. });
  1174. };
  1175. var getRemoteFirefoxVersion = function getRemoteFirefoxVersion(description) {
  1176. // TODO: Is there a better solution for detecting Firefox?
  1177. var match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
  1178. if (match === null || match.length < 2) {
  1179. return -1;
  1180. }
  1181. var version = parseInt(match[1], 10);
  1182. // Test for NaN (yes, this is ugly)
  1183. return version !== version ? -1 : version;
  1184. };
  1185. var getCanSendMaxMessageSize = function getCanSendMaxMessageSize(remoteIsFirefox) {
  1186. // Every implementation we know can send at least 64 KiB.
  1187. // Note: Although Chrome is technically able to send up to 256 KiB, the
  1188. // data does not reach the other peer reliably.
  1189. // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419
  1190. var canSendMaxMessageSize = 65536;
  1191. if (browserDetails.browser === 'firefox') {
  1192. if (browserDetails.version < 57) {
  1193. if (remoteIsFirefox === -1) {
  1194. // FF < 57 will send in 16 KiB chunks using the deprecated PPID
  1195. // fragmentation.
  1196. canSendMaxMessageSize = 16384;
  1197. } else {
  1198. // However, other FF (and RAWRTC) can reassemble PPID-fragmented
  1199. // messages. Thus, supporting ~2 GiB when sending.
  1200. canSendMaxMessageSize = 2147483637;
  1201. }
  1202. } else if (browserDetails.version < 60) {
  1203. // Currently, all FF >= 57 will reset the remote maximum message size
  1204. // to the default value when a data channel is created at a later
  1205. // stage. :(
  1206. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  1207. canSendMaxMessageSize = browserDetails.version === 57 ? 65535 : 65536;
  1208. } else {
  1209. // FF >= 60 supports sending ~2 GiB
  1210. canSendMaxMessageSize = 2147483637;
  1211. }
  1212. }
  1213. return canSendMaxMessageSize;
  1214. };
  1215. var getMaxMessageSize = function getMaxMessageSize(description, remoteIsFirefox) {
  1216. // Note: 65536 bytes is the default value from the SDP spec. Also,
  1217. // every implementation we know supports receiving 65536 bytes.
  1218. var maxMessageSize = 65536;
  1219. // FF 57 has a slightly incorrect default remote max message size, so
  1220. // we need to adjust it here to avoid a failure when sending.
  1221. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697
  1222. if (browserDetails.browser === 'firefox' && browserDetails.version === 57) {
  1223. maxMessageSize = 65535;
  1224. }
  1225. var match = _sdp2.default.matchPrefix(description.sdp, 'a=max-message-size:');
  1226. if (match.length > 0) {
  1227. maxMessageSize = parseInt(match[0].substr(19), 10);
  1228. } else if (browserDetails.browser === 'firefox' && remoteIsFirefox !== -1) {
  1229. // If the maximum message size is not present in the remote SDP and
  1230. // both local and remote are Firefox, the remote peer can receive
  1231. // ~2 GiB.
  1232. maxMessageSize = 2147483637;
  1233. }
  1234. return maxMessageSize;
  1235. };
  1236. var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
  1237. window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
  1238. this._sctp = null;
  1239. // Chrome decided to not expose .sctp in plan-b mode.
  1240. // As usual, adapter.js has to do an 'ugly worakaround'
  1241. // to cover up the mess.
  1242. if (browserDetails.browser === 'chrome' && browserDetails.version >= 76) {
  1243. var _getConfiguration = this.getConfiguration(),
  1244. sdpSemantics = _getConfiguration.sdpSemantics;
  1245. if (sdpSemantics === 'plan-b') {
  1246. Object.defineProperty(this, 'sctp', {
  1247. get: function get() {
  1248. return typeof this._sctp === 'undefined' ? null : this._sctp;
  1249. },
  1250. enumerable: true,
  1251. configurable: true
  1252. });
  1253. }
  1254. }
  1255. if (sctpInDescription(arguments[0])) {
  1256. // Check if the remote is FF.
  1257. var isFirefox = getRemoteFirefoxVersion(arguments[0]);
  1258. // Get the maximum message size the local peer is capable of sending
  1259. var canSendMMS = getCanSendMaxMessageSize(isFirefox);
  1260. // Get the maximum message size of the remote peer.
  1261. var remoteMMS = getMaxMessageSize(arguments[0], isFirefox);
  1262. // Determine final maximum message size
  1263. var maxMessageSize = void 0;
  1264. if (canSendMMS === 0 && remoteMMS === 0) {
  1265. maxMessageSize = Number.POSITIVE_INFINITY;
  1266. } else if (canSendMMS === 0 || remoteMMS === 0) {
  1267. maxMessageSize = Math.max(canSendMMS, remoteMMS);
  1268. } else {
  1269. maxMessageSize = Math.min(canSendMMS, remoteMMS);
  1270. }
  1271. // Create a dummy RTCSctpTransport object and the 'maxMessageSize'
  1272. // attribute.
  1273. var sctp = {};
  1274. Object.defineProperty(sctp, 'maxMessageSize', {
  1275. get: function get() {
  1276. return maxMessageSize;
  1277. }
  1278. });
  1279. this._sctp = sctp;
  1280. }
  1281. return origSetRemoteDescription.apply(this, arguments);
  1282. };
  1283. }
  1284. function shimSendThrowTypeError(window) {
  1285. if (!(window.RTCPeerConnection && 'createDataChannel' in window.RTCPeerConnection.prototype)) {
  1286. return;
  1287. }
  1288. // Note: Although Firefox >= 57 has a native implementation, the maximum
  1289. // message size can be reset for all data channels at a later stage.
  1290. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  1291. function wrapDcSend(dc, pc) {
  1292. var origDataChannelSend = dc.send;
  1293. dc.send = function send() {
  1294. var data = arguments[0];
  1295. var length = data.length || data.size || data.byteLength;
  1296. if (dc.readyState === 'open' && pc.sctp && length > pc.sctp.maxMessageSize) {
  1297. throw new TypeError('Message too large (can send a maximum of ' + pc.sctp.maxMessageSize + ' bytes)');
  1298. }
  1299. return origDataChannelSend.apply(dc, arguments);
  1300. };
  1301. }
  1302. var origCreateDataChannel = window.RTCPeerConnection.prototype.createDataChannel;
  1303. window.RTCPeerConnection.prototype.createDataChannel = function createDataChannel() {
  1304. var dataChannel = origCreateDataChannel.apply(this, arguments);
  1305. wrapDcSend(dataChannel, this);
  1306. return dataChannel;
  1307. };
  1308. utils.wrapPeerConnectionEvent(window, 'datachannel', function (e) {
  1309. wrapDcSend(e.channel, e.target);
  1310. return e;
  1311. });
  1312. }
  1313. /* shims RTCConnectionState by pretending it is the same as iceConnectionState.
  1314. * See https://bugs.chromium.org/p/webrtc/issues/detail?id=6145#c12
  1315. * for why this is a valid hack in Chrome. In Firefox it is slightly incorrect
  1316. * since DTLS failures would be hidden. See
  1317. * https://bugzilla.mozilla.org/show_bug.cgi?id=1265827
  1318. * for the Firefox tracking bug.
  1319. */
  1320. function shimConnectionState(window) {
  1321. if (!window.RTCPeerConnection || 'connectionState' in window.RTCPeerConnection.prototype) {
  1322. return;
  1323. }
  1324. var proto = window.RTCPeerConnection.prototype;
  1325. Object.defineProperty(proto, 'connectionState', {
  1326. get: function get() {
  1327. return {
  1328. completed: 'connected',
  1329. checking: 'connecting'
  1330. }[this.iceConnectionState] || this.iceConnectionState;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(proto, 'onconnectionstatechange', {
  1336. get: function get() {
  1337. return this._onconnectionstatechange || null;
  1338. },
  1339. set: function set(cb) {
  1340. if (this._onconnectionstatechange) {
  1341. this.removeEventListener('connectionstatechange', this._onconnectionstatechange);
  1342. delete this._onconnectionstatechange;
  1343. }
  1344. if (cb) {
  1345. this.addEventListener('connectionstatechange', this._onconnectionstatechange = cb);
  1346. }
  1347. },
  1348. enumerable: true,
  1349. configurable: true
  1350. });
  1351. ['setLocalDescription', 'setRemoteDescription'].forEach(function (method) {
  1352. var origMethod = proto[method];
  1353. proto[method] = function () {
  1354. if (!this._connectionstatechangepoly) {
  1355. this._connectionstatechangepoly = function (e) {
  1356. var pc = e.target;
  1357. if (pc._lastConnectionState !== pc.connectionState) {
  1358. pc._lastConnectionState = pc.connectionState;
  1359. var newEvent = new Event('connectionstatechange', e);
  1360. pc.dispatchEvent(newEvent);
  1361. }
  1362. return e;
  1363. };
  1364. this.addEventListener('iceconnectionstatechange', this._connectionstatechangepoly);
  1365. }
  1366. return origMethod.apply(this, arguments);
  1367. };
  1368. });
  1369. }
  1370. function removeExtmapAllowMixed(window, browserDetails) {
  1371. /* remove a=extmap-allow-mixed for webrtc.org < M71 */
  1372. if (!window.RTCPeerConnection) {
  1373. return;
  1374. }
  1375. if (browserDetails.browser === 'chrome' && browserDetails.version >= 71) {
  1376. return;
  1377. }
  1378. if (browserDetails.browser === 'safari' && browserDetails.version >= 605) {
  1379. return;
  1380. }
  1381. var nativeSRD = window.RTCPeerConnection.prototype.setRemoteDescription;
  1382. window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription(desc) {
  1383. if (desc && desc.sdp && desc.sdp.indexOf('\na=extmap-allow-mixed') !== -1) {
  1384. var sdp = desc.sdp.split('\n').filter(function (line) {
  1385. return line.trim() !== 'a=extmap-allow-mixed';
  1386. }).join('\n');
  1387. // Safari enforces read-only-ness of RTCSessionDescription fields.
  1388. if (window.RTCSessionDescription && desc instanceof window.RTCSessionDescription) {
  1389. arguments[0] = new window.RTCSessionDescription({
  1390. type: desc.type,
  1391. sdp: sdp
  1392. });
  1393. } else {
  1394. desc.sdp = sdp;
  1395. }
  1396. }
  1397. return nativeSRD.apply(this, arguments);
  1398. };
  1399. }
  1400. function shimAddIceCandidateNullOrEmpty(window, browserDetails) {
  1401. // Support for addIceCandidate(null or undefined)
  1402. // as well as addIceCandidate({candidate: "", ...})
  1403. // https://bugs.chromium.org/p/chromium/issues/detail?id=978582
  1404. // Note: must be called before other polyfills which change the signature.
  1405. if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {
  1406. return;
  1407. }
  1408. var nativeAddIceCandidate = window.RTCPeerConnection.prototype.addIceCandidate;
  1409. if (!nativeAddIceCandidate || nativeAddIceCandidate.length === 0) {
  1410. return;
  1411. }
  1412. window.RTCPeerConnection.prototype.addIceCandidate = function addIceCandidate() {
  1413. if (!arguments[0]) {
  1414. if (arguments[1]) {
  1415. arguments[1].apply(null);
  1416. }
  1417. return Promise.resolve();
  1418. }
  1419. // Firefox 68+ emits and processes {candidate: "", ...}, ignore
  1420. // in older versions.
  1421. // Native support for ignoring exists for Chrome M77+.
  1422. // Safari ignores as well, exact version unknown but works in the same
  1423. // version that also ignores addIceCandidate(null).
  1424. if ((browserDetails.browser === 'chrome' && browserDetails.version < 78 || browserDetails.browser === 'firefox' && browserDetails.version < 68 || browserDetails.browser === 'safari') && arguments[0] && arguments[0].candidate === '') {
  1425. return Promise.resolve();
  1426. }
  1427. return nativeAddIceCandidate.apply(this, arguments);
  1428. };
  1429. }
  1430. // Note: Make sure to call this ahead of APIs that modify
  1431. // setLocalDescription.length
  1432. function shimParameterlessSetLocalDescription(window, browserDetails) {
  1433. if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {
  1434. return;
  1435. }
  1436. var nativeSetLocalDescription = window.RTCPeerConnection.prototype.setLocalDescription;
  1437. if (!nativeSetLocalDescription || nativeSetLocalDescription.length === 0) {
  1438. return;
  1439. }
  1440. window.RTCPeerConnection.prototype.setLocalDescription = function setLocalDescription() {
  1441. var _this = this;
  1442. var desc = arguments[0] || {};
  1443. if ((typeof desc === 'undefined' ? 'undefined' : _typeof(desc)) !== 'object' || desc.type && desc.sdp) {
  1444. return nativeSetLocalDescription.apply(this, arguments);
  1445. }
  1446. // The remaining steps should technically happen when SLD comes off the
  1447. // RTCPeerConnection's operations chain (not ahead of going on it), but
  1448. // this is too difficult to shim. Instead, this shim only covers the
  1449. // common case where the operations chain is empty. This is imperfect, but
  1450. // should cover many cases. Rationale: Even if we can't reduce the glare
  1451. // window to zero on imperfect implementations, there's value in tapping
  1452. // into the perfect negotiation pattern that several browsers support.
  1453. desc = { type: desc.type, sdp: desc.sdp };
  1454. if (!desc.type) {
  1455. switch (this.signalingState) {
  1456. case 'stable':
  1457. case 'have-local-offer':
  1458. case 'have-remote-pranswer':
  1459. desc.type = 'offer';
  1460. break;
  1461. default:
  1462. desc.type = 'answer';
  1463. break;
  1464. }
  1465. }
  1466. if (desc.sdp || desc.type !== 'offer' && desc.type !== 'answer') {
  1467. return nativeSetLocalDescription.apply(this, [desc]);
  1468. }
  1469. var func = desc.type === 'offer' ? this.createOffer : this.createAnswer;
  1470. return func.apply(this).then(function (d) {
  1471. return nativeSetLocalDescription.apply(_this, [d]);
  1472. });
  1473. };
  1474. }
  1475. },{"./utils":11,"sdp":12}],7:[function(require,module,exports){
  1476. /*
  1477. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1478. *
  1479. * Use of this source code is governed by a BSD-style license
  1480. * that can be found in the LICENSE file in the root of the source
  1481. * tree.
  1482. */
  1483. /* eslint-env node */
  1484. 'use strict';
  1485. Object.defineProperty(exports, "__esModule", {
  1486. value: true
  1487. });
  1488. exports.shimGetDisplayMedia = exports.shimGetUserMedia = undefined;
  1489. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  1490. var _getusermedia = require('./getusermedia');
  1491. Object.defineProperty(exports, 'shimGetUserMedia', {
  1492. enumerable: true,
  1493. get: function get() {
  1494. return _getusermedia.shimGetUserMedia;
  1495. }
  1496. });
  1497. var _getdisplaymedia = require('./getdisplaymedia');
  1498. Object.defineProperty(exports, 'shimGetDisplayMedia', {
  1499. enumerable: true,
  1500. get: function get() {
  1501. return _getdisplaymedia.shimGetDisplayMedia;
  1502. }
  1503. });
  1504. exports.shimOnTrack = shimOnTrack;
  1505. exports.shimPeerConnection = shimPeerConnection;
  1506. exports.shimSenderGetStats = shimSenderGetStats;
  1507. exports.shimReceiverGetStats = shimReceiverGetStats;
  1508. exports.shimRemoveStream = shimRemoveStream;
  1509. exports.shimRTCDataChannel = shimRTCDataChannel;
  1510. exports.shimAddTransceiver = shimAddTransceiver;
  1511. exports.shimGetParameters = shimGetParameters;
  1512. exports.shimCreateOffer = shimCreateOffer;
  1513. exports.shimCreateAnswer = shimCreateAnswer;
  1514. var _utils = require('../utils');
  1515. var utils = _interopRequireWildcard(_utils);
  1516. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  1517. function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  1518. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  1519. function shimOnTrack(window) {
  1520. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCTrackEvent && 'receiver' in window.RTCTrackEvent.prototype && !('transceiver' in window.RTCTrackEvent.prototype)) {
  1521. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  1522. get: function get() {
  1523. return { receiver: this.receiver };
  1524. }
  1525. });
  1526. }
  1527. }
  1528. function shimPeerConnection(window, browserDetails) {
  1529. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !(window.RTCPeerConnection || window.mozRTCPeerConnection)) {
  1530. return; // probably media.peerconnection.enabled=false in about:config
  1531. }
  1532. if (!window.RTCPeerConnection && window.mozRTCPeerConnection) {
  1533. // very basic support for old versions.
  1534. window.RTCPeerConnection = window.mozRTCPeerConnection;
  1535. }
  1536. if (browserDetails.version < 53) {
  1537. // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
  1538. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'].forEach(function (method) {
  1539. var nativeMethod = window.RTCPeerConnection.prototype[method];
  1540. var methodObj = _defineProperty({}, method, function () {
  1541. arguments[0] = new (method === 'addIceCandidate' ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]);
  1542. return nativeMethod.apply(this, arguments);
  1543. });
  1544. window.RTCPeerConnection.prototype[method] = methodObj[method];
  1545. });
  1546. }
  1547. var modernStatsTypes = {
  1548. inboundrtp: 'inbound-rtp',
  1549. outboundrtp: 'outbound-rtp',
  1550. candidatepair: 'candidate-pair',
  1551. localcandidate: 'local-candidate',
  1552. remotecandidate: 'remote-candidate'
  1553. };
  1554. var nativeGetStats = window.RTCPeerConnection.prototype.getStats;
  1555. window.RTCPeerConnection.prototype.getStats = function getStats() {
  1556. var _arguments = Array.prototype.slice.call(arguments),
  1557. selector = _arguments[0],
  1558. onSucc = _arguments[1],
  1559. onErr = _arguments[2];
  1560. return nativeGetStats.apply(this, [selector || null]).then(function (stats) {
  1561. if (browserDetails.version < 53 && !onSucc) {
  1562. // Shim only promise getStats with spec-hyphens in type names
  1563. // Leave callback version alone; misc old uses of forEach before Map
  1564. try {
  1565. stats.forEach(function (stat) {
  1566. stat.type = modernStatsTypes[stat.type] || stat.type;
  1567. });
  1568. } catch (e) {
  1569. if (e.name !== 'TypeError') {
  1570. throw e;
  1571. }
  1572. // Avoid TypeError: "type" is read-only, in old versions. 34-43ish
  1573. stats.forEach(function (stat, i) {
  1574. stats.set(i, Object.assign({}, stat, {
  1575. type: modernStatsTypes[stat.type] || stat.type
  1576. }));
  1577. });
  1578. }
  1579. }
  1580. return stats;
  1581. }).then(onSucc, onErr);
  1582. };
  1583. }
  1584. function shimSenderGetStats(window) {
  1585. if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) {
  1586. return;
  1587. }
  1588. if (window.RTCRtpSender && 'getStats' in window.RTCRtpSender.prototype) {
  1589. return;
  1590. }
  1591. var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  1592. if (origGetSenders) {
  1593. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  1594. var _this = this;
  1595. var senders = origGetSenders.apply(this, []);
  1596. senders.forEach(function (sender) {
  1597. return sender._pc = _this;
  1598. });
  1599. return senders;
  1600. };
  1601. }
  1602. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  1603. if (origAddTrack) {
  1604. window.RTCPeerConnection.prototype.addTrack = function addTrack() {
  1605. var sender = origAddTrack.apply(this, arguments);
  1606. sender._pc = this;
  1607. return sender;
  1608. };
  1609. }
  1610. window.RTCRtpSender.prototype.getStats = function getStats() {
  1611. return this.track ? this._pc.getStats(this.track) : Promise.resolve(new Map());
  1612. };
  1613. }
  1614. function shimReceiverGetStats(window) {
  1615. if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) {
  1616. return;
  1617. }
  1618. if (window.RTCRtpSender && 'getStats' in window.RTCRtpReceiver.prototype) {
  1619. return;
  1620. }
  1621. var origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
  1622. if (origGetReceivers) {
  1623. window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {
  1624. var _this2 = this;
  1625. var receivers = origGetReceivers.apply(this, []);
  1626. receivers.forEach(function (receiver) {
  1627. return receiver._pc = _this2;
  1628. });
  1629. return receivers;
  1630. };
  1631. }
  1632. utils.wrapPeerConnectionEvent(window, 'track', function (e) {
  1633. e.receiver._pc = e.srcElement;
  1634. return e;
  1635. });
  1636. window.RTCRtpReceiver.prototype.getStats = function getStats() {
  1637. return this._pc.getStats(this.track);
  1638. };
  1639. }
  1640. function shimRemoveStream(window) {
  1641. if (!window.RTCPeerConnection || 'removeStream' in window.RTCPeerConnection.prototype) {
  1642. return;
  1643. }
  1644. window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
  1645. var _this3 = this;
  1646. utils.deprecated('removeStream', 'removeTrack');
  1647. this.getSenders().forEach(function (sender) {
  1648. if (sender.track && stream.getTracks().includes(sender.track)) {
  1649. _this3.removeTrack(sender);
  1650. }
  1651. });
  1652. };
  1653. }
  1654. function shimRTCDataChannel(window) {
  1655. // rename DataChannel to RTCDataChannel (native fix in FF60):
  1656. // https://bugzilla.mozilla.org/show_bug.cgi?id=1173851
  1657. if (window.DataChannel && !window.RTCDataChannel) {
  1658. window.RTCDataChannel = window.DataChannel;
  1659. }
  1660. }
  1661. function shimAddTransceiver(window) {
  1662. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  1663. // Firefox ignores the init sendEncodings options passed to addTransceiver
  1664. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  1665. if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection)) {
  1666. return;
  1667. }
  1668. var origAddTransceiver = window.RTCPeerConnection.prototype.addTransceiver;
  1669. if (origAddTransceiver) {
  1670. window.RTCPeerConnection.prototype.addTransceiver = function addTransceiver() {
  1671. this.setParametersPromises = [];
  1672. // WebIDL input coercion and validation
  1673. var sendEncodings = arguments[1] && arguments[1].sendEncodings;
  1674. if (sendEncodings === undefined) {
  1675. sendEncodings = [];
  1676. }
  1677. sendEncodings = [].concat(_toConsumableArray(sendEncodings));
  1678. var shouldPerformCheck = sendEncodings.length > 0;
  1679. if (shouldPerformCheck) {
  1680. // If sendEncodings params are provided, validate grammar
  1681. sendEncodings.forEach(function (encodingParam) {
  1682. if ('rid' in encodingParam) {
  1683. var ridRegex = /^[a-z0-9]{0,16}$/i;
  1684. if (!ridRegex.test(encodingParam.rid)) {
  1685. throw new TypeError('Invalid RID value provided.');
  1686. }
  1687. }
  1688. if ('scaleResolutionDownBy' in encodingParam) {
  1689. if (!(parseFloat(encodingParam.scaleResolutionDownBy) >= 1.0)) {
  1690. throw new RangeError('scale_resolution_down_by must be >= 1.0');
  1691. }
  1692. }
  1693. if ('maxFramerate' in encodingParam) {
  1694. if (!(parseFloat(encodingParam.maxFramerate) >= 0)) {
  1695. throw new RangeError('max_framerate must be >= 0.0');
  1696. }
  1697. }
  1698. });
  1699. }
  1700. var transceiver = origAddTransceiver.apply(this, arguments);
  1701. if (shouldPerformCheck) {
  1702. // Check if the init options were applied. If not we do this in an
  1703. // asynchronous way and save the promise reference in a global object.
  1704. // This is an ugly hack, but at the same time is way more robust than
  1705. // checking the sender parameters before and after the createOffer
  1706. // Also note that after the createoffer we are not 100% sure that
  1707. // the params were asynchronously applied so we might miss the
  1708. // opportunity to recreate offer.
  1709. var sender = transceiver.sender;
  1710. var params = sender.getParameters();
  1711. if (!('encodings' in params) ||
  1712. // Avoid being fooled by patched getParameters() below.
  1713. params.encodings.length === 1 && Object.keys(params.encodings[0]).length === 0) {
  1714. params.encodings = sendEncodings;
  1715. sender.sendEncodings = sendEncodings;
  1716. this.setParametersPromises.push(sender.setParameters(params).then(function () {
  1717. delete sender.sendEncodings;
  1718. }).catch(function () {
  1719. delete sender.sendEncodings;
  1720. }));
  1721. }
  1722. }
  1723. return transceiver;
  1724. };
  1725. }
  1726. }
  1727. function shimGetParameters(window) {
  1728. if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCRtpSender)) {
  1729. return;
  1730. }
  1731. var origGetParameters = window.RTCRtpSender.prototype.getParameters;
  1732. if (origGetParameters) {
  1733. window.RTCRtpSender.prototype.getParameters = function getParameters() {
  1734. var params = origGetParameters.apply(this, arguments);
  1735. if (!('encodings' in params)) {
  1736. params.encodings = [].concat(this.sendEncodings || [{}]);
  1737. }
  1738. return params;
  1739. };
  1740. }
  1741. }
  1742. function shimCreateOffer(window) {
  1743. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  1744. // Firefox ignores the init sendEncodings options passed to addTransceiver
  1745. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  1746. if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection)) {
  1747. return;
  1748. }
  1749. var origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
  1750. window.RTCPeerConnection.prototype.createOffer = function createOffer() {
  1751. var _this4 = this,
  1752. _arguments2 = arguments;
  1753. if (this.setParametersPromises && this.setParametersPromises.length) {
  1754. return Promise.all(this.setParametersPromises).then(function () {
  1755. return origCreateOffer.apply(_this4, _arguments2);
  1756. }).finally(function () {
  1757. _this4.setParametersPromises = [];
  1758. });
  1759. }
  1760. return origCreateOffer.apply(this, arguments);
  1761. };
  1762. }
  1763. function shimCreateAnswer(window) {
  1764. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  1765. // Firefox ignores the init sendEncodings options passed to addTransceiver
  1766. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  1767. if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection)) {
  1768. return;
  1769. }
  1770. var origCreateAnswer = window.RTCPeerConnection.prototype.createAnswer;
  1771. window.RTCPeerConnection.prototype.createAnswer = function createAnswer() {
  1772. var _this5 = this,
  1773. _arguments3 = arguments;
  1774. if (this.setParametersPromises && this.setParametersPromises.length) {
  1775. return Promise.all(this.setParametersPromises).then(function () {
  1776. return origCreateAnswer.apply(_this5, _arguments3);
  1777. }).finally(function () {
  1778. _this5.setParametersPromises = [];
  1779. });
  1780. }
  1781. return origCreateAnswer.apply(this, arguments);
  1782. };
  1783. }
  1784. },{"../utils":11,"./getdisplaymedia":8,"./getusermedia":9}],8:[function(require,module,exports){
  1785. /*
  1786. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  1787. *
  1788. * Use of this source code is governed by a BSD-style license
  1789. * that can be found in the LICENSE file in the root of the source
  1790. * tree.
  1791. */
  1792. /* eslint-env node */
  1793. 'use strict';
  1794. Object.defineProperty(exports, "__esModule", {
  1795. value: true
  1796. });
  1797. exports.shimGetDisplayMedia = shimGetDisplayMedia;
  1798. function shimGetDisplayMedia(window, preferredMediaSource) {
  1799. if (window.navigator.mediaDevices && 'getDisplayMedia' in window.navigator.mediaDevices) {
  1800. return;
  1801. }
  1802. if (!window.navigator.mediaDevices) {
  1803. return;
  1804. }
  1805. window.navigator.mediaDevices.getDisplayMedia = function getDisplayMedia(constraints) {
  1806. if (!(constraints && constraints.video)) {
  1807. var err = new DOMException('getDisplayMedia without video ' + 'constraints is undefined');
  1808. err.name = 'NotFoundError';
  1809. // from https://heycam.github.io/webidl/#idl-DOMException-error-names
  1810. err.code = 8;
  1811. return Promise.reject(err);
  1812. }
  1813. if (constraints.video === true) {
  1814. constraints.video = { mediaSource: preferredMediaSource };
  1815. } else {
  1816. constraints.video.mediaSource = preferredMediaSource;
  1817. }
  1818. return window.navigator.mediaDevices.getUserMedia(constraints);
  1819. };
  1820. }
  1821. },{}],9:[function(require,module,exports){
  1822. /*
  1823. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1824. *
  1825. * Use of this source code is governed by a BSD-style license
  1826. * that can be found in the LICENSE file in the root of the source
  1827. * tree.
  1828. */
  1829. /* eslint-env node */
  1830. 'use strict';
  1831. Object.defineProperty(exports, "__esModule", {
  1832. value: true
  1833. });
  1834. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  1835. exports.shimGetUserMedia = shimGetUserMedia;
  1836. var _utils = require('../utils');
  1837. var utils = _interopRequireWildcard(_utils);
  1838. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  1839. function shimGetUserMedia(window, browserDetails) {
  1840. var navigator = window && window.navigator;
  1841. var MediaStreamTrack = window && window.MediaStreamTrack;
  1842. navigator.getUserMedia = function (constraints, onSuccess, onError) {
  1843. // Replace Firefox 44+'s deprecation warning with unprefixed version.
  1844. utils.deprecated('navigator.getUserMedia', 'navigator.mediaDevices.getUserMedia');
  1845. navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
  1846. };
  1847. if (!(browserDetails.version > 55 && 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
  1848. var remap = function remap(obj, a, b) {
  1849. if (a in obj && !(b in obj)) {
  1850. obj[b] = obj[a];
  1851. delete obj[a];
  1852. }
  1853. };
  1854. var nativeGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
  1855. navigator.mediaDevices.getUserMedia = function (c) {
  1856. if ((typeof c === 'undefined' ? 'undefined' : _typeof(c)) === 'object' && _typeof(c.audio) === 'object') {
  1857. c = JSON.parse(JSON.stringify(c));
  1858. remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
  1859. remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
  1860. }
  1861. return nativeGetUserMedia(c);
  1862. };
  1863. if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
  1864. var nativeGetSettings = MediaStreamTrack.prototype.getSettings;
  1865. MediaStreamTrack.prototype.getSettings = function () {
  1866. var obj = nativeGetSettings.apply(this, arguments);
  1867. remap(obj, 'mozAutoGainControl', 'autoGainControl');
  1868. remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
  1869. return obj;
  1870. };
  1871. }
  1872. if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
  1873. var nativeApplyConstraints = MediaStreamTrack.prototype.applyConstraints;
  1874. MediaStreamTrack.prototype.applyConstraints = function (c) {
  1875. if (this.kind === 'audio' && (typeof c === 'undefined' ? 'undefined' : _typeof(c)) === 'object') {
  1876. c = JSON.parse(JSON.stringify(c));
  1877. remap(c, 'autoGainControl', 'mozAutoGainControl');
  1878. remap(c, 'noiseSuppression', 'mozNoiseSuppression');
  1879. }
  1880. return nativeApplyConstraints.apply(this, [c]);
  1881. };
  1882. }
  1883. }
  1884. }
  1885. },{"../utils":11}],10:[function(require,module,exports){
  1886. /*
  1887. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1888. *
  1889. * Use of this source code is governed by a BSD-style license
  1890. * that can be found in the LICENSE file in the root of the source
  1891. * tree.
  1892. */
  1893. 'use strict';
  1894. Object.defineProperty(exports, "__esModule", {
  1895. value: true
  1896. });
  1897. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  1898. exports.shimLocalStreamsAPI = shimLocalStreamsAPI;
  1899. exports.shimRemoteStreamsAPI = shimRemoteStreamsAPI;
  1900. exports.shimCallbacksAPI = shimCallbacksAPI;
  1901. exports.shimGetUserMedia = shimGetUserMedia;
  1902. exports.shimConstraints = shimConstraints;
  1903. exports.shimRTCIceServerUrls = shimRTCIceServerUrls;
  1904. exports.shimTrackEventTransceiver = shimTrackEventTransceiver;
  1905. exports.shimCreateOfferLegacy = shimCreateOfferLegacy;
  1906. exports.shimAudioContext = shimAudioContext;
  1907. var _utils = require('../utils');
  1908. var utils = _interopRequireWildcard(_utils);
  1909. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  1910. function shimLocalStreamsAPI(window) {
  1911. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !window.RTCPeerConnection) {
  1912. return;
  1913. }
  1914. if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {
  1915. window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
  1916. if (!this._localStreams) {
  1917. this._localStreams = [];
  1918. }
  1919. return this._localStreams;
  1920. };
  1921. }
  1922. if (!('addStream' in window.RTCPeerConnection.prototype)) {
  1923. var _addTrack = window.RTCPeerConnection.prototype.addTrack;
  1924. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  1925. var _this = this;
  1926. if (!this._localStreams) {
  1927. this._localStreams = [];
  1928. }
  1929. if (!this._localStreams.includes(stream)) {
  1930. this._localStreams.push(stream);
  1931. }
  1932. // Try to emulate Chrome's behaviour of adding in audio-video order.
  1933. // Safari orders by track id.
  1934. stream.getAudioTracks().forEach(function (track) {
  1935. return _addTrack.call(_this, track, stream);
  1936. });
  1937. stream.getVideoTracks().forEach(function (track) {
  1938. return _addTrack.call(_this, track, stream);
  1939. });
  1940. };
  1941. window.RTCPeerConnection.prototype.addTrack = function addTrack(track) {
  1942. var _this2 = this;
  1943. for (var _len = arguments.length, streams = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  1944. streams[_key - 1] = arguments[_key];
  1945. }
  1946. if (streams) {
  1947. streams.forEach(function (stream) {
  1948. if (!_this2._localStreams) {
  1949. _this2._localStreams = [stream];
  1950. } else if (!_this2._localStreams.includes(stream)) {
  1951. _this2._localStreams.push(stream);
  1952. }
  1953. });
  1954. }
  1955. return _addTrack.apply(this, arguments);
  1956. };
  1957. }
  1958. if (!('removeStream' in window.RTCPeerConnection.prototype)) {
  1959. window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
  1960. var _this3 = this;
  1961. if (!this._localStreams) {
  1962. this._localStreams = [];
  1963. }
  1964. var index = this._localStreams.indexOf(stream);
  1965. if (index === -1) {
  1966. return;
  1967. }
  1968. this._localStreams.splice(index, 1);
  1969. var tracks = stream.getTracks();
  1970. this.getSenders().forEach(function (sender) {
  1971. if (tracks.includes(sender.track)) {
  1972. _this3.removeTrack(sender);
  1973. }
  1974. });
  1975. };
  1976. }
  1977. }
  1978. function shimRemoteStreamsAPI(window) {
  1979. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !window.RTCPeerConnection) {
  1980. return;
  1981. }
  1982. if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {
  1983. window.RTCPeerConnection.prototype.getRemoteStreams = function getRemoteStreams() {
  1984. return this._remoteStreams ? this._remoteStreams : [];
  1985. };
  1986. }
  1987. if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
  1988. Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
  1989. get: function get() {
  1990. return this._onaddstream;
  1991. },
  1992. set: function set(f) {
  1993. var _this4 = this;
  1994. if (this._onaddstream) {
  1995. this.removeEventListener('addstream', this._onaddstream);
  1996. this.removeEventListener('track', this._onaddstreampoly);
  1997. }
  1998. this.addEventListener('addstream', this._onaddstream = f);
  1999. this.addEventListener('track', this._onaddstreampoly = function (e) {
  2000. e.streams.forEach(function (stream) {
  2001. if (!_this4._remoteStreams) {
  2002. _this4._remoteStreams = [];
  2003. }
  2004. if (_this4._remoteStreams.includes(stream)) {
  2005. return;
  2006. }
  2007. _this4._remoteStreams.push(stream);
  2008. var event = new Event('addstream');
  2009. event.stream = stream;
  2010. _this4.dispatchEvent(event);
  2011. });
  2012. });
  2013. }
  2014. });
  2015. var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
  2016. window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
  2017. var pc = this;
  2018. if (!this._onaddstreampoly) {
  2019. this.addEventListener('track', this._onaddstreampoly = function (e) {
  2020. e.streams.forEach(function (stream) {
  2021. if (!pc._remoteStreams) {
  2022. pc._remoteStreams = [];
  2023. }
  2024. if (pc._remoteStreams.indexOf(stream) >= 0) {
  2025. return;
  2026. }
  2027. pc._remoteStreams.push(stream);
  2028. var event = new Event('addstream');
  2029. event.stream = stream;
  2030. pc.dispatchEvent(event);
  2031. });
  2032. });
  2033. }
  2034. return origSetRemoteDescription.apply(pc, arguments);
  2035. };
  2036. }
  2037. }
  2038. function shimCallbacksAPI(window) {
  2039. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !window.RTCPeerConnection) {
  2040. return;
  2041. }
  2042. var prototype = window.RTCPeerConnection.prototype;
  2043. var origCreateOffer = prototype.createOffer;
  2044. var origCreateAnswer = prototype.createAnswer;
  2045. var setLocalDescription = prototype.setLocalDescription;
  2046. var setRemoteDescription = prototype.setRemoteDescription;
  2047. var addIceCandidate = prototype.addIceCandidate;
  2048. prototype.createOffer = function createOffer(successCallback, failureCallback) {
  2049. var options = arguments.length >= 2 ? arguments[2] : arguments[0];
  2050. var promise = origCreateOffer.apply(this, [options]);
  2051. if (!failureCallback) {
  2052. return promise;
  2053. }
  2054. promise.then(successCallback, failureCallback);
  2055. return Promise.resolve();
  2056. };
  2057. prototype.createAnswer = function createAnswer(successCallback, failureCallback) {
  2058. var options = arguments.length >= 2 ? arguments[2] : arguments[0];
  2059. var promise = origCreateAnswer.apply(this, [options]);
  2060. if (!failureCallback) {
  2061. return promise;
  2062. }
  2063. promise.then(successCallback, failureCallback);
  2064. return Promise.resolve();
  2065. };
  2066. var withCallback = function withCallback(description, successCallback, failureCallback) {
  2067. var promise = setLocalDescription.apply(this, [description]);
  2068. if (!failureCallback) {
  2069. return promise;
  2070. }
  2071. promise.then(successCallback, failureCallback);
  2072. return Promise.resolve();
  2073. };
  2074. prototype.setLocalDescription = withCallback;
  2075. withCallback = function withCallback(description, successCallback, failureCallback) {
  2076. var promise = setRemoteDescription.apply(this, [description]);
  2077. if (!failureCallback) {
  2078. return promise;
  2079. }
  2080. promise.then(successCallback, failureCallback);
  2081. return Promise.resolve();
  2082. };
  2083. prototype.setRemoteDescription = withCallback;
  2084. withCallback = function withCallback(candidate, successCallback, failureCallback) {
  2085. var promise = addIceCandidate.apply(this, [candidate]);
  2086. if (!failureCallback) {
  2087. return promise;
  2088. }
  2089. promise.then(successCallback, failureCallback);
  2090. return Promise.resolve();
  2091. };
  2092. prototype.addIceCandidate = withCallback;
  2093. }
  2094. function shimGetUserMedia(window) {
  2095. var navigator = window && window.navigator;
  2096. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  2097. // shim not needed in Safari 12.1
  2098. var mediaDevices = navigator.mediaDevices;
  2099. var _getUserMedia = mediaDevices.getUserMedia.bind(mediaDevices);
  2100. navigator.mediaDevices.getUserMedia = function (constraints) {
  2101. return _getUserMedia(shimConstraints(constraints));
  2102. };
  2103. }
  2104. if (!navigator.getUserMedia && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  2105. navigator.getUserMedia = function getUserMedia(constraints, cb, errcb) {
  2106. navigator.mediaDevices.getUserMedia(constraints).then(cb, errcb);
  2107. }.bind(navigator);
  2108. }
  2109. }
  2110. function shimConstraints(constraints) {
  2111. if (constraints && constraints.video !== undefined) {
  2112. return Object.assign({}, constraints, { video: utils.compactObject(constraints.video) });
  2113. }
  2114. return constraints;
  2115. }
  2116. function shimRTCIceServerUrls(window) {
  2117. if (!window.RTCPeerConnection) {
  2118. return;
  2119. }
  2120. // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
  2121. var OrigPeerConnection = window.RTCPeerConnection;
  2122. window.RTCPeerConnection = function RTCPeerConnection(pcConfig, pcConstraints) {
  2123. if (pcConfig && pcConfig.iceServers) {
  2124. var newIceServers = [];
  2125. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2126. var server = pcConfig.iceServers[i];
  2127. if (!server.hasOwnProperty('urls') && server.hasOwnProperty('url')) {
  2128. utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  2129. server = JSON.parse(JSON.stringify(server));
  2130. server.urls = server.url;
  2131. delete server.url;
  2132. newIceServers.push(server);
  2133. } else {
  2134. newIceServers.push(pcConfig.iceServers[i]);
  2135. }
  2136. }
  2137. pcConfig.iceServers = newIceServers;
  2138. }
  2139. return new OrigPeerConnection(pcConfig, pcConstraints);
  2140. };
  2141. window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
  2142. // wrap static methods. Currently just generateCertificate.
  2143. if ('generateCertificate' in OrigPeerConnection) {
  2144. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  2145. get: function get() {
  2146. return OrigPeerConnection.generateCertificate;
  2147. }
  2148. });
  2149. }
  2150. }
  2151. function shimTrackEventTransceiver(window) {
  2152. // Add event.transceiver member over deprecated event.receiver
  2153. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCTrackEvent && 'receiver' in window.RTCTrackEvent.prototype && !('transceiver' in window.RTCTrackEvent.prototype)) {
  2154. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  2155. get: function get() {
  2156. return { receiver: this.receiver };
  2157. }
  2158. });
  2159. }
  2160. }
  2161. function shimCreateOfferLegacy(window) {
  2162. var origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
  2163. window.RTCPeerConnection.prototype.createOffer = function createOffer(offerOptions) {
  2164. if (offerOptions) {
  2165. if (typeof offerOptions.offerToReceiveAudio !== 'undefined') {
  2166. // support bit values
  2167. offerOptions.offerToReceiveAudio = !!offerOptions.offerToReceiveAudio;
  2168. }
  2169. var audioTransceiver = this.getTransceivers().find(function (transceiver) {
  2170. return transceiver.receiver.track.kind === 'audio';
  2171. });
  2172. if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {
  2173. if (audioTransceiver.direction === 'sendrecv') {
  2174. if (audioTransceiver.setDirection) {
  2175. audioTransceiver.setDirection('sendonly');
  2176. } else {
  2177. audioTransceiver.direction = 'sendonly';
  2178. }
  2179. } else if (audioTransceiver.direction === 'recvonly') {
  2180. if (audioTransceiver.setDirection) {
  2181. audioTransceiver.setDirection('inactive');
  2182. } else {
  2183. audioTransceiver.direction = 'inactive';
  2184. }
  2185. }
  2186. } else if (offerOptions.offerToReceiveAudio === true && !audioTransceiver) {
  2187. this.addTransceiver('audio', { direction: 'recvonly' });
  2188. }
  2189. if (typeof offerOptions.offerToReceiveVideo !== 'undefined') {
  2190. // support bit values
  2191. offerOptions.offerToReceiveVideo = !!offerOptions.offerToReceiveVideo;
  2192. }
  2193. var videoTransceiver = this.getTransceivers().find(function (transceiver) {
  2194. return transceiver.receiver.track.kind === 'video';
  2195. });
  2196. if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {
  2197. if (videoTransceiver.direction === 'sendrecv') {
  2198. if (videoTransceiver.setDirection) {
  2199. videoTransceiver.setDirection('sendonly');
  2200. } else {
  2201. videoTransceiver.direction = 'sendonly';
  2202. }
  2203. } else if (videoTransceiver.direction === 'recvonly') {
  2204. if (videoTransceiver.setDirection) {
  2205. videoTransceiver.setDirection('inactive');
  2206. } else {
  2207. videoTransceiver.direction = 'inactive';
  2208. }
  2209. }
  2210. } else if (offerOptions.offerToReceiveVideo === true && !videoTransceiver) {
  2211. this.addTransceiver('video', { direction: 'recvonly' });
  2212. }
  2213. }
  2214. return origCreateOffer.apply(this, arguments);
  2215. };
  2216. }
  2217. function shimAudioContext(window) {
  2218. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || window.AudioContext) {
  2219. return;
  2220. }
  2221. window.AudioContext = window.webkitAudioContext;
  2222. }
  2223. },{"../utils":11}],11:[function(require,module,exports){
  2224. /*
  2225. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  2226. *
  2227. * Use of this source code is governed by a BSD-style license
  2228. * that can be found in the LICENSE file in the root of the source
  2229. * tree.
  2230. */
  2231. /* eslint-env node */
  2232. 'use strict';
  2233. Object.defineProperty(exports, "__esModule", {
  2234. value: true
  2235. });
  2236. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  2237. exports.extractVersion = extractVersion;
  2238. exports.wrapPeerConnectionEvent = wrapPeerConnectionEvent;
  2239. exports.disableLog = disableLog;
  2240. exports.disableWarnings = disableWarnings;
  2241. exports.log = log;
  2242. exports.deprecated = deprecated;
  2243. exports.detectBrowser = detectBrowser;
  2244. exports.compactObject = compactObject;
  2245. exports.walkStats = walkStats;
  2246. exports.filterStats = filterStats;
  2247. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  2248. var logDisabled_ = true;
  2249. var deprecationWarnings_ = true;
  2250. /**
  2251. * Extract browser version out of the provided user agent string.
  2252. *
  2253. * @param {!string} uastring userAgent string.
  2254. * @param {!string} expr Regular expression used as match criteria.
  2255. * @param {!number} pos position in the version string to be returned.
  2256. * @return {!number} browser version.
  2257. */
  2258. function extractVersion(uastring, expr, pos) {
  2259. var match = uastring.match(expr);
  2260. return match && match.length >= pos && parseInt(match[pos], 10);
  2261. }
  2262. // Wraps the peerconnection event eventNameToWrap in a function
  2263. // which returns the modified event object (or false to prevent
  2264. // the event).
  2265. function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {
  2266. if (!window.RTCPeerConnection) {
  2267. return;
  2268. }
  2269. var proto = window.RTCPeerConnection.prototype;
  2270. var nativeAddEventListener = proto.addEventListener;
  2271. proto.addEventListener = function (nativeEventName, cb) {
  2272. if (nativeEventName !== eventNameToWrap) {
  2273. return nativeAddEventListener.apply(this, arguments);
  2274. }
  2275. var wrappedCallback = function wrappedCallback(e) {
  2276. var modifiedEvent = wrapper(e);
  2277. if (modifiedEvent) {
  2278. if (cb.handleEvent) {
  2279. cb.handleEvent(modifiedEvent);
  2280. } else {
  2281. cb(modifiedEvent);
  2282. }
  2283. }
  2284. };
  2285. this._eventMap = this._eventMap || {};
  2286. if (!this._eventMap[eventNameToWrap]) {
  2287. this._eventMap[eventNameToWrap] = new Map();
  2288. }
  2289. this._eventMap[eventNameToWrap].set(cb, wrappedCallback);
  2290. return nativeAddEventListener.apply(this, [nativeEventName, wrappedCallback]);
  2291. };
  2292. var nativeRemoveEventListener = proto.removeEventListener;
  2293. proto.removeEventListener = function (nativeEventName, cb) {
  2294. if (nativeEventName !== eventNameToWrap || !this._eventMap || !this._eventMap[eventNameToWrap]) {
  2295. return nativeRemoveEventListener.apply(this, arguments);
  2296. }
  2297. if (!this._eventMap[eventNameToWrap].has(cb)) {
  2298. return nativeRemoveEventListener.apply(this, arguments);
  2299. }
  2300. var unwrappedCb = this._eventMap[eventNameToWrap].get(cb);
  2301. this._eventMap[eventNameToWrap].delete(cb);
  2302. if (this._eventMap[eventNameToWrap].size === 0) {
  2303. delete this._eventMap[eventNameToWrap];
  2304. }
  2305. if (Object.keys(this._eventMap).length === 0) {
  2306. delete this._eventMap;
  2307. }
  2308. return nativeRemoveEventListener.apply(this, [nativeEventName, unwrappedCb]);
  2309. };
  2310. Object.defineProperty(proto, 'on' + eventNameToWrap, {
  2311. get: function get() {
  2312. return this['_on' + eventNameToWrap];
  2313. },
  2314. set: function set(cb) {
  2315. if (this['_on' + eventNameToWrap]) {
  2316. this.removeEventListener(eventNameToWrap, this['_on' + eventNameToWrap]);
  2317. delete this['_on' + eventNameToWrap];
  2318. }
  2319. if (cb) {
  2320. this.addEventListener(eventNameToWrap, this['_on' + eventNameToWrap] = cb);
  2321. }
  2322. },
  2323. enumerable: true,
  2324. configurable: true
  2325. });
  2326. }
  2327. function disableLog(bool) {
  2328. if (typeof bool !== 'boolean') {
  2329. return new Error('Argument type: ' + (typeof bool === 'undefined' ? 'undefined' : _typeof(bool)) + '. Please use a boolean.');
  2330. }
  2331. logDisabled_ = bool;
  2332. return bool ? 'adapter.js logging disabled' : 'adapter.js logging enabled';
  2333. }
  2334. /**
  2335. * Disable or enable deprecation warnings
  2336. * @param {!boolean} bool set to true to disable warnings.
  2337. */
  2338. function disableWarnings(bool) {
  2339. if (typeof bool !== 'boolean') {
  2340. return new Error('Argument type: ' + (typeof bool === 'undefined' ? 'undefined' : _typeof(bool)) + '. Please use a boolean.');
  2341. }
  2342. deprecationWarnings_ = !bool;
  2343. return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
  2344. }
  2345. function log() {
  2346. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object') {
  2347. if (logDisabled_) {
  2348. return;
  2349. }
  2350. if (typeof console !== 'undefined' && typeof console.log === 'function') {
  2351. console.log.apply(console, arguments);
  2352. }
  2353. }
  2354. }
  2355. /**
  2356. * Shows a deprecation warning suggesting the modern and spec-compatible API.
  2357. */
  2358. function deprecated(oldMethod, newMethod) {
  2359. if (!deprecationWarnings_) {
  2360. return;
  2361. }
  2362. console.warn(oldMethod + ' is deprecated, please use ' + newMethod + ' instead.');
  2363. }
  2364. /**
  2365. * Browser detector.
  2366. *
  2367. * @return {object} result containing browser and version
  2368. * properties.
  2369. */
  2370. function detectBrowser(window) {
  2371. // Returned result object.
  2372. var result = { browser: null, version: null };
  2373. // Fail early if it's not a browser
  2374. if (typeof window === 'undefined' || !window.navigator) {
  2375. result.browser = 'Not a browser.';
  2376. return result;
  2377. }
  2378. var navigator = window.navigator;
  2379. if (navigator.mozGetUserMedia) {
  2380. // Firefox.
  2381. result.browser = 'firefox';
  2382. result.version = extractVersion(navigator.userAgent, /Firefox\/(\d+)\./, 1);
  2383. } else if (navigator.webkitGetUserMedia || window.isSecureContext === false && window.webkitRTCPeerConnection) {
  2384. // Chrome, Chromium, Webview, Opera.
  2385. // Version matches Chrome/WebRTC version.
  2386. // Chrome 74 removed webkitGetUserMedia on http as well so we need the
  2387. // more complicated fallback to webkitRTCPeerConnection.
  2388. result.browser = 'chrome';
  2389. result.version = extractVersion(navigator.userAgent, /Chrom(e|ium)\/(\d+)\./, 2);
  2390. } else if (window.RTCPeerConnection && navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) {
  2391. // Safari.
  2392. result.browser = 'safari';
  2393. result.version = extractVersion(navigator.userAgent, /AppleWebKit\/(\d+)\./, 1);
  2394. result.supportsUnifiedPlan = window.RTCRtpTransceiver && 'currentDirection' in window.RTCRtpTransceiver.prototype;
  2395. } else {
  2396. // Default fallthrough: not supported.
  2397. result.browser = 'Not a supported browser.';
  2398. return result;
  2399. }
  2400. return result;
  2401. }
  2402. /**
  2403. * Checks if something is an object.
  2404. *
  2405. * @param {*} val The something you want to check.
  2406. * @return true if val is an object, false otherwise.
  2407. */
  2408. function isObject(val) {
  2409. return Object.prototype.toString.call(val) === '[object Object]';
  2410. }
  2411. /**
  2412. * Remove all empty objects and undefined values
  2413. * from a nested object -- an enhanced and vanilla version
  2414. * of Lodash's `compact`.
  2415. */
  2416. function compactObject(data) {
  2417. if (!isObject(data)) {
  2418. return data;
  2419. }
  2420. return Object.keys(data).reduce(function (accumulator, key) {
  2421. var isObj = isObject(data[key]);
  2422. var value = isObj ? compactObject(data[key]) : data[key];
  2423. var isEmptyObject = isObj && !Object.keys(value).length;
  2424. if (value === undefined || isEmptyObject) {
  2425. return accumulator;
  2426. }
  2427. return Object.assign(accumulator, _defineProperty({}, key, value));
  2428. }, {});
  2429. }
  2430. /* iterates the stats graph recursively. */
  2431. function walkStats(stats, base, resultSet) {
  2432. if (!base || resultSet.has(base.id)) {
  2433. return;
  2434. }
  2435. resultSet.set(base.id, base);
  2436. Object.keys(base).forEach(function (name) {
  2437. if (name.endsWith('Id')) {
  2438. walkStats(stats, stats.get(base[name]), resultSet);
  2439. } else if (name.endsWith('Ids')) {
  2440. base[name].forEach(function (id) {
  2441. walkStats(stats, stats.get(id), resultSet);
  2442. });
  2443. }
  2444. });
  2445. }
  2446. /* filter getStats for a sender/receiver track. */
  2447. function filterStats(result, track, outbound) {
  2448. var streamStatsType = outbound ? 'outbound-rtp' : 'inbound-rtp';
  2449. var filteredResult = new Map();
  2450. if (track === null) {
  2451. return filteredResult;
  2452. }
  2453. var trackStats = [];
  2454. result.forEach(function (value) {
  2455. if (value.type === 'track' && value.trackIdentifier === track.id) {
  2456. trackStats.push(value);
  2457. }
  2458. });
  2459. trackStats.forEach(function (trackStat) {
  2460. result.forEach(function (stats) {
  2461. if (stats.type === streamStatsType && stats.trackId === trackStat.id) {
  2462. walkStats(result, stats, filteredResult);
  2463. }
  2464. });
  2465. });
  2466. return filteredResult;
  2467. }
  2468. },{}],12:[function(require,module,exports){
  2469. /* eslint-env node */
  2470. 'use strict';
  2471. // SDP helpers.
  2472. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  2473. var SDPUtils = {};
  2474. // Generate an alphanumeric identifier for cname or mids.
  2475. // TODO: use UUIDs instead? https://gist.github.com/jed/982883
  2476. SDPUtils.generateIdentifier = function () {
  2477. return Math.random().toString(36).substr(2, 10);
  2478. };
  2479. // The RTCP CNAME used by all peerconnections from the same JS.
  2480. SDPUtils.localCName = SDPUtils.generateIdentifier();
  2481. // Splits SDP into lines, dealing with both CRLF and LF.
  2482. SDPUtils.splitLines = function (blob) {
  2483. return blob.trim().split('\n').map(function (line) {
  2484. return line.trim();
  2485. });
  2486. };
  2487. // Splits SDP into sessionpart and mediasections. Ensures CRLF.
  2488. SDPUtils.splitSections = function (blob) {
  2489. var parts = blob.split('\nm=');
  2490. return parts.map(function (part, index) {
  2491. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  2492. });
  2493. };
  2494. // Returns the session description.
  2495. SDPUtils.getDescription = function (blob) {
  2496. var sections = SDPUtils.splitSections(blob);
  2497. return sections && sections[0];
  2498. };
  2499. // Returns the individual media sections.
  2500. SDPUtils.getMediaSections = function (blob) {
  2501. var sections = SDPUtils.splitSections(blob);
  2502. sections.shift();
  2503. return sections;
  2504. };
  2505. // Returns lines that start with a certain prefix.
  2506. SDPUtils.matchPrefix = function (blob, prefix) {
  2507. return SDPUtils.splitLines(blob).filter(function (line) {
  2508. return line.indexOf(prefix) === 0;
  2509. });
  2510. };
  2511. // Parses an ICE candidate line. Sample input:
  2512. // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
  2513. // rport 55996"
  2514. // Input can be prefixed with a=.
  2515. SDPUtils.parseCandidate = function (line) {
  2516. var parts = void 0;
  2517. // Parse both variants.
  2518. if (line.indexOf('a=candidate:') === 0) {
  2519. parts = line.substring(12).split(' ');
  2520. } else {
  2521. parts = line.substring(10).split(' ');
  2522. }
  2523. var candidate = {
  2524. foundation: parts[0],
  2525. component: { 1: 'rtp', 2: 'rtcp' }[parts[1]] || parts[1],
  2526. protocol: parts[2].toLowerCase(),
  2527. priority: parseInt(parts[3], 10),
  2528. ip: parts[4],
  2529. address: parts[4], // address is an alias for ip.
  2530. port: parseInt(parts[5], 10),
  2531. // skip parts[6] == 'typ'
  2532. type: parts[7]
  2533. };
  2534. for (var i = 8; i < parts.length; i += 2) {
  2535. switch (parts[i]) {
  2536. case 'raddr':
  2537. candidate.relatedAddress = parts[i + 1];
  2538. break;
  2539. case 'rport':
  2540. candidate.relatedPort = parseInt(parts[i + 1], 10);
  2541. break;
  2542. case 'tcptype':
  2543. candidate.tcpType = parts[i + 1];
  2544. break;
  2545. case 'ufrag':
  2546. candidate.ufrag = parts[i + 1]; // for backward compatibility.
  2547. candidate.usernameFragment = parts[i + 1];
  2548. break;
  2549. default:
  2550. // extension handling, in particular ufrag. Don't overwrite.
  2551. if (candidate[parts[i]] === undefined) {
  2552. candidate[parts[i]] = parts[i + 1];
  2553. }
  2554. break;
  2555. }
  2556. }
  2557. return candidate;
  2558. };
  2559. // Translates a candidate object into SDP candidate attribute.
  2560. // This does not include the a= prefix!
  2561. SDPUtils.writeCandidate = function (candidate) {
  2562. var sdp = [];
  2563. sdp.push(candidate.foundation);
  2564. var component = candidate.component;
  2565. if (component === 'rtp') {
  2566. sdp.push(1);
  2567. } else if (component === 'rtcp') {
  2568. sdp.push(2);
  2569. } else {
  2570. sdp.push(component);
  2571. }
  2572. sdp.push(candidate.protocol.toUpperCase());
  2573. sdp.push(candidate.priority);
  2574. sdp.push(candidate.address || candidate.ip);
  2575. sdp.push(candidate.port);
  2576. var type = candidate.type;
  2577. sdp.push('typ');
  2578. sdp.push(type);
  2579. if (type !== 'host' && candidate.relatedAddress && candidate.relatedPort) {
  2580. sdp.push('raddr');
  2581. sdp.push(candidate.relatedAddress);
  2582. sdp.push('rport');
  2583. sdp.push(candidate.relatedPort);
  2584. }
  2585. if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
  2586. sdp.push('tcptype');
  2587. sdp.push(candidate.tcpType);
  2588. }
  2589. if (candidate.usernameFragment || candidate.ufrag) {
  2590. sdp.push('ufrag');
  2591. sdp.push(candidate.usernameFragment || candidate.ufrag);
  2592. }
  2593. return 'candidate:' + sdp.join(' ');
  2594. };
  2595. // Parses an ice-options line, returns an array of option tags.
  2596. // Sample input:
  2597. // a=ice-options:foo bar
  2598. SDPUtils.parseIceOptions = function (line) {
  2599. return line.substr(14).split(' ');
  2600. };
  2601. // Parses a rtpmap line, returns RTCRtpCoddecParameters. Sample input:
  2602. // a=rtpmap:111 opus/48000/2
  2603. SDPUtils.parseRtpMap = function (line) {
  2604. var parts = line.substr(9).split(' ');
  2605. var parsed = {
  2606. payloadType: parseInt(parts.shift(), 10) // was: id
  2607. };
  2608. parts = parts[0].split('/');
  2609. parsed.name = parts[0];
  2610. parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
  2611. parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
  2612. // legacy alias, got renamed back to channels in ORTC.
  2613. parsed.numChannels = parsed.channels;
  2614. return parsed;
  2615. };
  2616. // Generates a rtpmap line from RTCRtpCodecCapability or
  2617. // RTCRtpCodecParameters.
  2618. SDPUtils.writeRtpMap = function (codec) {
  2619. var pt = codec.payloadType;
  2620. if (codec.preferredPayloadType !== undefined) {
  2621. pt = codec.preferredPayloadType;
  2622. }
  2623. var channels = codec.channels || codec.numChannels || 1;
  2624. return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate + (channels !== 1 ? '/' + channels : '') + '\r\n';
  2625. };
  2626. // Parses a extmap line (headerextension from RFC 5285). Sample input:
  2627. // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  2628. // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
  2629. SDPUtils.parseExtmap = function (line) {
  2630. var parts = line.substr(9).split(' ');
  2631. return {
  2632. id: parseInt(parts[0], 10),
  2633. direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
  2634. uri: parts[1]
  2635. };
  2636. };
  2637. // Generates an extmap line from RTCRtpHeaderExtensionParameters or
  2638. // RTCRtpHeaderExtension.
  2639. SDPUtils.writeExtmap = function (headerExtension) {
  2640. return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) + (headerExtension.direction && headerExtension.direction !== 'sendrecv' ? '/' + headerExtension.direction : '') + ' ' + headerExtension.uri + '\r\n';
  2641. };
  2642. // Parses a fmtp line, returns dictionary. Sample input:
  2643. // a=fmtp:96 vbr=on;cng=on
  2644. // Also deals with vbr=on; cng=on
  2645. SDPUtils.parseFmtp = function (line) {
  2646. var parsed = {};
  2647. var kv = void 0;
  2648. var parts = line.substr(line.indexOf(' ') + 1).split(';');
  2649. for (var j = 0; j < parts.length; j++) {
  2650. kv = parts[j].trim().split('=');
  2651. parsed[kv[0].trim()] = kv[1];
  2652. }
  2653. return parsed;
  2654. };
  2655. // Generates a fmtp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
  2656. SDPUtils.writeFmtp = function (codec) {
  2657. var line = '';
  2658. var pt = codec.payloadType;
  2659. if (codec.preferredPayloadType !== undefined) {
  2660. pt = codec.preferredPayloadType;
  2661. }
  2662. if (codec.parameters && Object.keys(codec.parameters).length) {
  2663. var params = [];
  2664. Object.keys(codec.parameters).forEach(function (param) {
  2665. if (codec.parameters[param] !== undefined) {
  2666. params.push(param + '=' + codec.parameters[param]);
  2667. } else {
  2668. params.push(param);
  2669. }
  2670. });
  2671. line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
  2672. }
  2673. return line;
  2674. };
  2675. // Parses a rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
  2676. // a=rtcp-fb:98 nack rpsi
  2677. SDPUtils.parseRtcpFb = function (line) {
  2678. var parts = line.substr(line.indexOf(' ') + 1).split(' ');
  2679. return {
  2680. type: parts.shift(),
  2681. parameter: parts.join(' ')
  2682. };
  2683. };
  2684. // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
  2685. SDPUtils.writeRtcpFb = function (codec) {
  2686. var lines = '';
  2687. var pt = codec.payloadType;
  2688. if (codec.preferredPayloadType !== undefined) {
  2689. pt = codec.preferredPayloadType;
  2690. }
  2691. if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
  2692. // FIXME: special handling for trr-int?
  2693. codec.rtcpFeedback.forEach(function (fb) {
  2694. lines += 'a=rtcp-fb:' + pt + ' ' + fb.type + (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') + '\r\n';
  2695. });
  2696. }
  2697. return lines;
  2698. };
  2699. // Parses a RFC 5576 ssrc media attribute. Sample input:
  2700. // a=ssrc:3735928559 cname:something
  2701. SDPUtils.parseSsrcMedia = function (line) {
  2702. var sp = line.indexOf(' ');
  2703. var parts = {
  2704. ssrc: parseInt(line.substr(7, sp - 7), 10)
  2705. };
  2706. var colon = line.indexOf(':', sp);
  2707. if (colon > -1) {
  2708. parts.attribute = line.substr(sp + 1, colon - sp - 1);
  2709. parts.value = line.substr(colon + 1);
  2710. } else {
  2711. parts.attribute = line.substr(sp + 1);
  2712. }
  2713. return parts;
  2714. };
  2715. // Parse a ssrc-group line (see RFC 5576). Sample input:
  2716. // a=ssrc-group:semantics 12 34
  2717. SDPUtils.parseSsrcGroup = function (line) {
  2718. var parts = line.substr(13).split(' ');
  2719. return {
  2720. semantics: parts.shift(),
  2721. ssrcs: parts.map(function (ssrc) {
  2722. return parseInt(ssrc, 10);
  2723. })
  2724. };
  2725. };
  2726. // Extracts the MID (RFC 5888) from a media section.
  2727. // Returns the MID or undefined if no mid line was found.
  2728. SDPUtils.getMid = function (mediaSection) {
  2729. var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
  2730. if (mid) {
  2731. return mid.substr(6);
  2732. }
  2733. };
  2734. // Parses a fingerprint line for DTLS-SRTP.
  2735. SDPUtils.parseFingerprint = function (line) {
  2736. var parts = line.substr(14).split(' ');
  2737. return {
  2738. algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.
  2739. value: parts[1].toUpperCase() // the definition is upper-case in RFC 4572.
  2740. };
  2741. };
  2742. // Extracts DTLS parameters from SDP media section or sessionpart.
  2743. // FIXME: for consistency with other functions this should only
  2744. // get the fingerprint line as input. See also getIceParameters.
  2745. SDPUtils.getDtlsParameters = function (mediaSection, sessionpart) {
  2746. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=fingerprint:');
  2747. // Note: a=setup line is ignored since we use the 'auto' role in Edge.
  2748. return {
  2749. role: 'auto',
  2750. fingerprints: lines.map(SDPUtils.parseFingerprint)
  2751. };
  2752. };
  2753. // Serializes DTLS parameters to SDP.
  2754. SDPUtils.writeDtlsParameters = function (params, setupType) {
  2755. var sdp = 'a=setup:' + setupType + '\r\n';
  2756. params.fingerprints.forEach(function (fp) {
  2757. sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
  2758. });
  2759. return sdp;
  2760. };
  2761. // Parses a=crypto lines into
  2762. // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#dictionary-rtcsrtpsdesparameters-members
  2763. SDPUtils.parseCryptoLine = function (line) {
  2764. var parts = line.substr(9).split(' ');
  2765. return {
  2766. tag: parseInt(parts[0], 10),
  2767. cryptoSuite: parts[1],
  2768. keyParams: parts[2],
  2769. sessionParams: parts.slice(3)
  2770. };
  2771. };
  2772. SDPUtils.writeCryptoLine = function (parameters) {
  2773. return 'a=crypto:' + parameters.tag + ' ' + parameters.cryptoSuite + ' ' + (_typeof(parameters.keyParams) === 'object' ? SDPUtils.writeCryptoKeyParams(parameters.keyParams) : parameters.keyParams) + (parameters.sessionParams ? ' ' + parameters.sessionParams.join(' ') : '') + '\r\n';
  2774. };
  2775. // Parses the crypto key parameters into
  2776. // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#rtcsrtpkeyparam*
  2777. SDPUtils.parseCryptoKeyParams = function (keyParams) {
  2778. if (keyParams.indexOf('inline:') !== 0) {
  2779. return null;
  2780. }
  2781. var parts = keyParams.substr(7).split('|');
  2782. return {
  2783. keyMethod: 'inline',
  2784. keySalt: parts[0],
  2785. lifeTime: parts[1],
  2786. mkiValue: parts[2] ? parts[2].split(':')[0] : undefined,
  2787. mkiLength: parts[2] ? parts[2].split(':')[1] : undefined
  2788. };
  2789. };
  2790. SDPUtils.writeCryptoKeyParams = function (keyParams) {
  2791. return keyParams.keyMethod + ':' + keyParams.keySalt + (keyParams.lifeTime ? '|' + keyParams.lifeTime : '') + (keyParams.mkiValue && keyParams.mkiLength ? '|' + keyParams.mkiValue + ':' + keyParams.mkiLength : '');
  2792. };
  2793. // Extracts all SDES parameters.
  2794. SDPUtils.getCryptoParameters = function (mediaSection, sessionpart) {
  2795. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=crypto:');
  2796. return lines.map(SDPUtils.parseCryptoLine);
  2797. };
  2798. // Parses ICE information from SDP media section or sessionpart.
  2799. // FIXME: for consistency with other functions this should only
  2800. // get the ice-ufrag and ice-pwd lines as input.
  2801. SDPUtils.getIceParameters = function (mediaSection, sessionpart) {
  2802. var ufrag = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=ice-ufrag:')[0];
  2803. var pwd = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=ice-pwd:')[0];
  2804. if (!(ufrag && pwd)) {
  2805. return null;
  2806. }
  2807. return {
  2808. usernameFragment: ufrag.substr(12),
  2809. password: pwd.substr(10)
  2810. };
  2811. };
  2812. // Serializes ICE parameters to SDP.
  2813. SDPUtils.writeIceParameters = function (params) {
  2814. var sdp = 'a=ice-ufrag:' + params.usernameFragment + '\r\n' + 'a=ice-pwd:' + params.password + '\r\n';
  2815. if (params.iceLite) {
  2816. sdp += 'a=ice-lite\r\n';
  2817. }
  2818. return sdp;
  2819. };
  2820. // Parses the SDP media section and returns RTCRtpParameters.
  2821. SDPUtils.parseRtpParameters = function (mediaSection) {
  2822. var description = {
  2823. codecs: [],
  2824. headerExtensions: [],
  2825. fecMechanisms: [],
  2826. rtcp: []
  2827. };
  2828. var lines = SDPUtils.splitLines(mediaSection);
  2829. var mline = lines[0].split(' ');
  2830. for (var i = 3; i < mline.length; i++) {
  2831. // find all codecs from mline[3..]
  2832. var pt = mline[i];
  2833. var rtpmapline = SDPUtils.matchPrefix(mediaSection, 'a=rtpmap:' + pt + ' ')[0];
  2834. if (rtpmapline) {
  2835. var codec = SDPUtils.parseRtpMap(rtpmapline);
  2836. var fmtps = SDPUtils.matchPrefix(mediaSection, 'a=fmtp:' + pt + ' ');
  2837. // Only the first a=fmtp:<pt> is considered.
  2838. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
  2839. codec.rtcpFeedback = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-fb:' + pt + ' ').map(SDPUtils.parseRtcpFb);
  2840. description.codecs.push(codec);
  2841. // parse FEC mechanisms from rtpmap lines.
  2842. switch (codec.name.toUpperCase()) {
  2843. case 'RED':
  2844. case 'ULPFEC':
  2845. description.fecMechanisms.push(codec.name.toUpperCase());
  2846. break;
  2847. default:
  2848. // only RED and ULPFEC are recognized as FEC mechanisms.
  2849. break;
  2850. }
  2851. }
  2852. }
  2853. SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function (line) {
  2854. description.headerExtensions.push(SDPUtils.parseExtmap(line));
  2855. });
  2856. // FIXME: parse rtcp.
  2857. return description;
  2858. };
  2859. // Generates parts of the SDP media section describing the capabilities /
  2860. // parameters.
  2861. SDPUtils.writeRtpDescription = function (kind, caps) {
  2862. var sdp = '';
  2863. // Build the mline.
  2864. sdp += 'm=' + kind + ' ';
  2865. sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
  2866. sdp += ' UDP/TLS/RTP/SAVPF ';
  2867. sdp += caps.codecs.map(function (codec) {
  2868. if (codec.preferredPayloadType !== undefined) {
  2869. return codec.preferredPayloadType;
  2870. }
  2871. return codec.payloadType;
  2872. }).join(' ') + '\r\n';
  2873. sdp += 'c=IN IP4 0.0.0.0\r\n';
  2874. sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
  2875. // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
  2876. caps.codecs.forEach(function (codec) {
  2877. sdp += SDPUtils.writeRtpMap(codec);
  2878. sdp += SDPUtils.writeFmtp(codec);
  2879. sdp += SDPUtils.writeRtcpFb(codec);
  2880. });
  2881. var maxptime = 0;
  2882. caps.codecs.forEach(function (codec) {
  2883. if (codec.maxptime > maxptime) {
  2884. maxptime = codec.maxptime;
  2885. }
  2886. });
  2887. if (maxptime > 0) {
  2888. sdp += 'a=maxptime:' + maxptime + '\r\n';
  2889. }
  2890. if (caps.headerExtensions) {
  2891. caps.headerExtensions.forEach(function (extension) {
  2892. sdp += SDPUtils.writeExtmap(extension);
  2893. });
  2894. }
  2895. // FIXME: write fecMechanisms.
  2896. return sdp;
  2897. };
  2898. // Parses the SDP media section and returns an array of
  2899. // RTCRtpEncodingParameters.
  2900. SDPUtils.parseRtpEncodingParameters = function (mediaSection) {
  2901. var encodingParameters = [];
  2902. var description = SDPUtils.parseRtpParameters(mediaSection);
  2903. var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
  2904. var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
  2905. // filter a=ssrc:... cname:, ignore PlanB-msid
  2906. var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(function (line) {
  2907. return SDPUtils.parseSsrcMedia(line);
  2908. }).filter(function (parts) {
  2909. return parts.attribute === 'cname';
  2910. });
  2911. var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
  2912. var secondarySsrc = void 0;
  2913. var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID').map(function (line) {
  2914. var parts = line.substr(17).split(' ');
  2915. return parts.map(function (part) {
  2916. return parseInt(part, 10);
  2917. });
  2918. });
  2919. if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
  2920. secondarySsrc = flows[0][1];
  2921. }
  2922. description.codecs.forEach(function (codec) {
  2923. if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
  2924. var encParam = {
  2925. ssrc: primarySsrc,
  2926. codecPayloadType: parseInt(codec.parameters.apt, 10)
  2927. };
  2928. if (primarySsrc && secondarySsrc) {
  2929. encParam.rtx = { ssrc: secondarySsrc };
  2930. }
  2931. encodingParameters.push(encParam);
  2932. if (hasRed) {
  2933. encParam = JSON.parse(JSON.stringify(encParam));
  2934. encParam.fec = {
  2935. ssrc: primarySsrc,
  2936. mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
  2937. };
  2938. encodingParameters.push(encParam);
  2939. }
  2940. }
  2941. });
  2942. if (encodingParameters.length === 0 && primarySsrc) {
  2943. encodingParameters.push({
  2944. ssrc: primarySsrc
  2945. });
  2946. }
  2947. // we support both b=AS and b=TIAS but interpret AS as TIAS.
  2948. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
  2949. if (bandwidth.length) {
  2950. if (bandwidth[0].indexOf('b=TIAS:') === 0) {
  2951. bandwidth = parseInt(bandwidth[0].substr(7), 10);
  2952. } else if (bandwidth[0].indexOf('b=AS:') === 0) {
  2953. // use formula from JSEP to convert b=AS to TIAS value.
  2954. bandwidth = parseInt(bandwidth[0].substr(5), 10) * 1000 * 0.95 - 50 * 40 * 8;
  2955. } else {
  2956. bandwidth = undefined;
  2957. }
  2958. encodingParameters.forEach(function (params) {
  2959. params.maxBitrate = bandwidth;
  2960. });
  2961. }
  2962. return encodingParameters;
  2963. };
  2964. // parses http://draft.ortc.org/#rtcrtcpparameters*
  2965. SDPUtils.parseRtcpParameters = function (mediaSection) {
  2966. var rtcpParameters = {};
  2967. // Gets the first SSRC. Note that with RTX there might be multiple
  2968. // SSRCs.
  2969. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(function (line) {
  2970. return SDPUtils.parseSsrcMedia(line);
  2971. }).filter(function (obj) {
  2972. return obj.attribute === 'cname';
  2973. })[0];
  2974. if (remoteSsrc) {
  2975. rtcpParameters.cname = remoteSsrc.value;
  2976. rtcpParameters.ssrc = remoteSsrc.ssrc;
  2977. }
  2978. // Edge uses the compound attribute instead of reducedSize
  2979. // compound is !reducedSize
  2980. var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
  2981. rtcpParameters.reducedSize = rsize.length > 0;
  2982. rtcpParameters.compound = rsize.length === 0;
  2983. // parses the rtcp-mux attrіbute.
  2984. // Note that Edge does not support unmuxed RTCP.
  2985. var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
  2986. rtcpParameters.mux = mux.length > 0;
  2987. return rtcpParameters;
  2988. };
  2989. SDPUtils.writeRtcpParameters = function (rtcpParameters) {
  2990. var sdp = '';
  2991. if (rtcpParameters.reducedSize) {
  2992. sdp += 'a=rtcp-rsize\r\n';
  2993. }
  2994. if (rtcpParameters.mux) {
  2995. sdp += 'a=rtcp-mux\r\n';
  2996. }
  2997. if (rtcpParameters.ssrc !== undefined && rtcpParameters.cname) {
  2998. sdp += 'a=ssrc:' + rtcpParameters.ssrc + ' cname:' + rtcpParameters.cname + '\r\n';
  2999. }
  3000. return sdp;
  3001. };
  3002. // parses either a=msid: or a=ssrc:... msid lines and returns
  3003. // the id of the MediaStream and MediaStreamTrack.
  3004. SDPUtils.parseMsid = function (mediaSection) {
  3005. var parts = void 0;
  3006. var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
  3007. if (spec.length === 1) {
  3008. parts = spec[0].substr(7).split(' ');
  3009. return { stream: parts[0], track: parts[1] };
  3010. }
  3011. var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(function (line) {
  3012. return SDPUtils.parseSsrcMedia(line);
  3013. }).filter(function (msidParts) {
  3014. return msidParts.attribute === 'msid';
  3015. });
  3016. if (planB.length > 0) {
  3017. parts = planB[0].value.split(' ');
  3018. return { stream: parts[0], track: parts[1] };
  3019. }
  3020. };
  3021. // SCTP
  3022. // parses draft-ietf-mmusic-sctp-sdp-26 first and falls back
  3023. // to draft-ietf-mmusic-sctp-sdp-05
  3024. SDPUtils.parseSctpDescription = function (mediaSection) {
  3025. var mline = SDPUtils.parseMLine(mediaSection);
  3026. var maxSizeLine = SDPUtils.matchPrefix(mediaSection, 'a=max-message-size:');
  3027. var maxMessageSize = void 0;
  3028. if (maxSizeLine.length > 0) {
  3029. maxMessageSize = parseInt(maxSizeLine[0].substr(19), 10);
  3030. }
  3031. if (isNaN(maxMessageSize)) {
  3032. maxMessageSize = 65536;
  3033. }
  3034. var sctpPort = SDPUtils.matchPrefix(mediaSection, 'a=sctp-port:');
  3035. if (sctpPort.length > 0) {
  3036. return {
  3037. port: parseInt(sctpPort[0].substr(12), 10),
  3038. protocol: mline.fmt,
  3039. maxMessageSize: maxMessageSize
  3040. };
  3041. }
  3042. var sctpMapLines = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:');
  3043. if (sctpMapLines.length > 0) {
  3044. var parts = sctpMapLines[0].substr(10).split(' ');
  3045. return {
  3046. port: parseInt(parts[0], 10),
  3047. protocol: parts[1],
  3048. maxMessageSize: maxMessageSize
  3049. };
  3050. }
  3051. };
  3052. // SCTP
  3053. // outputs the draft-ietf-mmusic-sctp-sdp-26 version that all browsers
  3054. // support by now receiving in this format, unless we originally parsed
  3055. // as the draft-ietf-mmusic-sctp-sdp-05 format (indicated by the m-line
  3056. // protocol of DTLS/SCTP -- without UDP/ or TCP/)
  3057. SDPUtils.writeSctpDescription = function (media, sctp) {
  3058. var output = [];
  3059. if (media.protocol !== 'DTLS/SCTP') {
  3060. output = ['m=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.protocol + '\r\n', 'c=IN IP4 0.0.0.0\r\n', 'a=sctp-port:' + sctp.port + '\r\n'];
  3061. } else {
  3062. output = ['m=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.port + '\r\n', 'c=IN IP4 0.0.0.0\r\n', 'a=sctpmap:' + sctp.port + ' ' + sctp.protocol + ' 65535\r\n'];
  3063. }
  3064. if (sctp.maxMessageSize !== undefined) {
  3065. output.push('a=max-message-size:' + sctp.maxMessageSize + '\r\n');
  3066. }
  3067. return output.join('');
  3068. };
  3069. // Generate a session ID for SDP.
  3070. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
  3071. // recommends using a cryptographically random +ve 64-bit value
  3072. // but right now this should be acceptable and within the right range
  3073. SDPUtils.generateSessionId = function () {
  3074. return Math.random().toString().substr(2, 21);
  3075. };
  3076. // Write boiler plate for start of SDP
  3077. // sessId argument is optional - if not supplied it will
  3078. // be generated randomly
  3079. // sessVersion is optional and defaults to 2
  3080. // sessUser is optional and defaults to 'thisisadapterortc'
  3081. SDPUtils.writeSessionBoilerplate = function (sessId, sessVer, sessUser) {
  3082. var sessionId = void 0;
  3083. var version = sessVer !== undefined ? sessVer : 2;
  3084. if (sessId) {
  3085. sessionId = sessId;
  3086. } else {
  3087. sessionId = SDPUtils.generateSessionId();
  3088. }
  3089. var user = sessUser || 'thisisadapterortc';
  3090. // FIXME: sess-id should be an NTP timestamp.
  3091. return 'v=0\r\n' + 'o=' + user + ' ' + sessionId + ' ' + version + ' IN IP4 127.0.0.1\r\n' + 's=-\r\n' + 't=0 0\r\n';
  3092. };
  3093. // Gets the direction from the mediaSection or the sessionpart.
  3094. SDPUtils.getDirection = function (mediaSection, sessionpart) {
  3095. // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
  3096. var lines = SDPUtils.splitLines(mediaSection);
  3097. for (var i = 0; i < lines.length; i++) {
  3098. switch (lines[i]) {
  3099. case 'a=sendrecv':
  3100. case 'a=sendonly':
  3101. case 'a=recvonly':
  3102. case 'a=inactive':
  3103. return lines[i].substr(2);
  3104. default:
  3105. // FIXME: What should happen here?
  3106. }
  3107. }
  3108. if (sessionpart) {
  3109. return SDPUtils.getDirection(sessionpart);
  3110. }
  3111. return 'sendrecv';
  3112. };
  3113. SDPUtils.getKind = function (mediaSection) {
  3114. var lines = SDPUtils.splitLines(mediaSection);
  3115. var mline = lines[0].split(' ');
  3116. return mline[0].substr(2);
  3117. };
  3118. SDPUtils.isRejected = function (mediaSection) {
  3119. return mediaSection.split(' ', 2)[1] === '0';
  3120. };
  3121. SDPUtils.parseMLine = function (mediaSection) {
  3122. var lines = SDPUtils.splitLines(mediaSection);
  3123. var parts = lines[0].substr(2).split(' ');
  3124. return {
  3125. kind: parts[0],
  3126. port: parseInt(parts[1], 10),
  3127. protocol: parts[2],
  3128. fmt: parts.slice(3).join(' ')
  3129. };
  3130. };
  3131. SDPUtils.parseOLine = function (mediaSection) {
  3132. var line = SDPUtils.matchPrefix(mediaSection, 'o=')[0];
  3133. var parts = line.substr(2).split(' ');
  3134. return {
  3135. username: parts[0],
  3136. sessionId: parts[1],
  3137. sessionVersion: parseInt(parts[2], 10),
  3138. netType: parts[3],
  3139. addressType: parts[4],
  3140. address: parts[5]
  3141. };
  3142. };
  3143. // a very naive interpretation of a valid SDP.
  3144. SDPUtils.isValidSDP = function (blob) {
  3145. if (typeof blob !== 'string' || blob.length === 0) {
  3146. return false;
  3147. }
  3148. var lines = SDPUtils.splitLines(blob);
  3149. for (var i = 0; i < lines.length; i++) {
  3150. if (lines[i].length < 2 || lines[i].charAt(1) !== '=') {
  3151. return false;
  3152. }
  3153. // TODO: check the modifier a bit more.
  3154. }
  3155. return true;
  3156. };
  3157. // Expose public methods.
  3158. if ((typeof module === 'undefined' ? 'undefined' : _typeof(module)) === 'object') {
  3159. module.exports = SDPUtils;
  3160. }
  3161. },{}]},{},[1])(1)
  3162. });