adapter.js 139 KB

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