您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TraceablePeerConnection.js 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. /* global $ */
  2. import {getLogger} from "jitsi-meet-logger";
  3. const logger = getLogger(__filename);
  4. var RTC = require('../RTC/RTC');
  5. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  6. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7. var transform = require('sdp-transform');
  8. var RandomUtil = require('../util/RandomUtil');
  9. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  10. var SIMULCAST_LAYERS = 3;
  11. function TraceablePeerConnection(ice_config, constraints, session) {
  12. var self = this;
  13. this.session = session;
  14. this.replaceSSRCs = {
  15. "audio": [],
  16. "video": []
  17. };
  18. this.recvOnlySSRCs = {};
  19. var RTCPeerConnectionType = null;
  20. if (RTCBrowserType.isFirefox()) {
  21. RTCPeerConnectionType = mozRTCPeerConnection;
  22. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  23. RTCPeerConnectionType = RTCPeerConnection;
  24. } else {
  25. RTCPeerConnectionType = webkitRTCPeerConnection;
  26. }
  27. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  28. this.updateLog = [];
  29. this.stats = {};
  30. this.statsinterval = null;
  31. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  32. var Interop = require('sdp-interop').Interop;
  33. this.interop = new Interop();
  34. var Simulcast = require('sdp-simulcast');
  35. this.simulcast = new Simulcast({numOfLayers: SIMULCAST_LAYERS,
  36. explodeRemoteSimulcast: false});
  37. this.eventEmitter = this.session.room.eventEmitter;
  38. // override as desired
  39. this.trace = function (what, info) {
  40. /*logger.warn('WTRACE', what, info);
  41. if (info && RTCBrowserType.isIExplorer()) {
  42. if (info.length > 1024) {
  43. logger.warn('WTRACE', what, info.substr(1024));
  44. }
  45. if (info.length > 2048) {
  46. logger.warn('WTRACE', what, info.substr(2048));
  47. }
  48. }*/
  49. self.updateLog.push({
  50. time: new Date(),
  51. type: what,
  52. value: info || ""
  53. });
  54. };
  55. this.onicecandidate = null;
  56. this.peerconnection.onicecandidate = function (event) {
  57. // FIXME: this causes stack overflow with Temasys Plugin
  58. if (!RTCBrowserType.isTemasysPluginUsed())
  59. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  60. if (self.onicecandidate !== null) {
  61. self.onicecandidate(event);
  62. }
  63. };
  64. this.onaddstream = null;
  65. this.peerconnection.onaddstream = function (event) {
  66. self.trace('onaddstream', event.stream.id);
  67. if (self.onaddstream !== null) {
  68. self.onaddstream(event);
  69. }
  70. };
  71. this.onremovestream = null;
  72. this.peerconnection.onremovestream = function (event) {
  73. self.trace('onremovestream', event.stream.id);
  74. if (self.onremovestream !== null) {
  75. self.onremovestream(event);
  76. }
  77. };
  78. this.onsignalingstatechange = null;
  79. this.peerconnection.onsignalingstatechange = function (event) {
  80. self.trace('onsignalingstatechange', self.signalingState);
  81. if (self.onsignalingstatechange !== null) {
  82. self.onsignalingstatechange(event);
  83. }
  84. };
  85. this.oniceconnectionstatechange = null;
  86. this.peerconnection.oniceconnectionstatechange = function (event) {
  87. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  88. if (self.oniceconnectionstatechange !== null) {
  89. self.oniceconnectionstatechange(event);
  90. }
  91. };
  92. this.onnegotiationneeded = null;
  93. this.peerconnection.onnegotiationneeded = function (event) {
  94. self.trace('onnegotiationneeded');
  95. if (self.onnegotiationneeded !== null) {
  96. self.onnegotiationneeded(event);
  97. }
  98. };
  99. self.ondatachannel = null;
  100. this.peerconnection.ondatachannel = function (event) {
  101. self.trace('ondatachannel', event);
  102. if (self.ondatachannel !== null) {
  103. self.ondatachannel(event);
  104. }
  105. };
  106. // XXX: do all non-firefox browsers which we support also support this?
  107. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  108. this.statsinterval = window.setInterval(function() {
  109. self.peerconnection.getStats(function(stats) {
  110. var results = stats.result();
  111. var now = new Date();
  112. for (var i = 0; i < results.length; ++i) {
  113. results[i].names().forEach(function (name) {
  114. var id = results[i].id + '-' + name;
  115. if (!self.stats[id]) {
  116. self.stats[id] = {
  117. startTime: now,
  118. endTime: now,
  119. values: [],
  120. times: []
  121. };
  122. }
  123. self.stats[id].values.push(results[i].stat(name));
  124. self.stats[id].times.push(now.getTime());
  125. if (self.stats[id].values.length > self.maxstats) {
  126. self.stats[id].values.shift();
  127. self.stats[id].times.shift();
  128. }
  129. self.stats[id].endTime = now;
  130. });
  131. }
  132. });
  133. }, 1000);
  134. }
  135. }
  136. /**
  137. * Returns a string representation of a SessionDescription object.
  138. */
  139. var dumpSDP = function(description) {
  140. if (typeof description === 'undefined' || description == null) {
  141. return '';
  142. }
  143. return 'type: ' + description.type + '\r\n' + description.sdp;
  144. };
  145. /**
  146. * Injects receive only SSRC in the sdp if there are not other SSRCs.
  147. * @param desc the SDP that will be modified.
  148. * @returns the modified SDP.
  149. */
  150. TraceablePeerConnection.prototype.ssrcReplacement = function (desc) {
  151. if (typeof desc !== 'object' || desc === null ||
  152. typeof desc.sdp !== 'string') {
  153. logger.warn('An empty description was passed as an argument.');
  154. return desc;
  155. }
  156. var session = transform.parse(desc.sdp);
  157. if (!Array.isArray(session.media))
  158. {
  159. return;
  160. }
  161. var modded = false;
  162. session.media.forEach(function (bLine) {
  163. if(!this.replaceSSRCs[bLine.type])
  164. return;
  165. modded = true;
  166. var SSRCs = this.replaceSSRCs[bLine.type].splice(0,1);
  167. // Stores all SSRCs that should be used on other SRD/SDL operations.
  168. // For every stream that is unmuted we need to replace it SSRC
  169. // otherwise we are going to send jingle packet.
  170. var permSSRCs = [];
  171. //FIXME: The code expects that we have only SIM group or we
  172. // don't have any groups and we have only one SSRC per
  173. // stream. If we add another groups (FID, etc) this code
  174. // must be changed.
  175. while(SSRCs &&
  176. SSRCs.length){
  177. var ssrcOperation = SSRCs[0];
  178. switch(ssrcOperation.type) {
  179. case "mute":
  180. case "addMuted":
  181. //FIXME: If we want to support multiple streams we have to add
  182. // recv-only ssrcs for the
  183. // muted streams on every change until the stream is unmuted
  184. // or removed. Otherwise the recv-only streams won't be included
  185. // in the SDP
  186. if(!bLine.ssrcs)
  187. bLine.ssrcs = [];
  188. var groups = ssrcOperation.ssrc.groups;
  189. var ssrc = null;
  190. if(groups && groups.length) {
  191. ssrc = groups[0].primarySSRC;
  192. } else if(ssrcOperation.ssrc.ssrcs &&
  193. ssrcOperation.ssrc.ssrcs.length) {
  194. ssrc = ssrcOperation.ssrc.ssrcs[0];
  195. } else {
  196. GlobalOnErrorHandler.callErrorHandler(
  197. new Error("SSRC replacement error!"));
  198. logger.error("SSRC replacement error!");
  199. break;
  200. }
  201. bLine.ssrcs.push({
  202. id: ssrc,
  203. attribute: 'cname',
  204. value: ['recvonly-', ssrc].join('')
  205. });
  206. // If this is executed for another reason we are going to
  207. // include that ssrc as receive only again instead of
  208. // generating new one. Here we are assuming that we have
  209. // only 1 video stream that is muted.
  210. this.recvOnlySSRCs[bLine.type] = ssrc;
  211. break;
  212. case "unmute":
  213. if(!ssrcOperation.ssrc || !ssrcOperation.ssrc.ssrcs ||
  214. !ssrcOperation.ssrc.ssrcs.length)
  215. break;
  216. var ssrcMap = {};
  217. var ssrcLastIdx = ssrcOperation.ssrc.ssrcs.length - 1;
  218. for(var i = 0; i < bLine.ssrcs.length; i++) {
  219. var ssrc = bLine.ssrcs[i];
  220. if (ssrc.attribute !== 'msid' &&
  221. ssrc.value !== ssrcOperation.msid) {
  222. continue;
  223. }
  224. ssrcMap[ssrc.id] =
  225. ssrcOperation.ssrc.ssrcs[ssrcLastIdx];
  226. ssrcLastIdx--;
  227. if(ssrcLastIdx < 0)
  228. break;
  229. }
  230. var groups = ssrcOperation.ssrc.groups;
  231. if (typeof bLine.ssrcGroups !== 'undefined' &&
  232. Array.isArray(bLine.ssrcGroups) && groups &&
  233. groups.length) {
  234. bLine.ssrcGroups.forEach(function (group) {
  235. if(!group.ssrcs)
  236. return;
  237. var currentSSRCs = group.ssrcs.split(" ");
  238. var newGroup = null;
  239. for(var i = 0; i < groups.length; i++) {
  240. newGroup = groups[i].group;
  241. var newSSRCs = newGroup.ssrcs.split(" ");
  242. if(newGroup.semantics !== group.semantics)
  243. continue;
  244. var wrongGroup = false;
  245. for(var j = 0; j < currentSSRCs.length; j++) {
  246. if(newGroup.ssrcs.indexOf(
  247. ssrcMap[currentSSRCs[j]]) === -1){
  248. wrongGroup = true;
  249. break;
  250. }
  251. }
  252. if(!wrongGroup) {
  253. for(j = 0; j < newSSRCs.length; j++) {
  254. ssrcMap[currentSSRCs[j]] = newSSRCs[j];
  255. }
  256. break;
  257. }
  258. }
  259. group.ssrcs = newGroup.ssrcs;
  260. });
  261. }
  262. bLine.ssrcs.forEach(function (ssrc) {
  263. if(ssrcMap[ssrc.id]) {
  264. ssrc.id = ssrcMap[ssrc.id];
  265. }
  266. });
  267. // Storing the unmuted SSRCs.
  268. permSSRCs.push(ssrcOperation);
  269. break;
  270. default:
  271. break;
  272. }
  273. SSRCs = this.replaceSSRCs[bLine.type].splice(0,1);
  274. }
  275. // Restoring the unmuted SSRCs.
  276. this.replaceSSRCs[bLine.type] = permSSRCs;
  277. if (!Array.isArray(bLine.ssrcs) || bLine.ssrcs.length === 0)
  278. {
  279. var ssrc = this.recvOnlySSRCs[bLine.type]
  280. = this.recvOnlySSRCs[bLine.type] ||
  281. RandomUtil.randomInt(1, 0xffffffff);
  282. bLine.ssrcs = [{
  283. id: ssrc,
  284. attribute: 'cname',
  285. value: ['recvonly-', ssrc].join('')
  286. }];
  287. }
  288. }.bind(this));
  289. return (!modded) ? desc : new RTCSessionDescription({
  290. type: desc.type,
  291. sdp: transform.write(session),
  292. });
  293. };
  294. /**
  295. * Returns map with keys msid and values ssrc.
  296. * @param desc the SDP that will be modified.
  297. */
  298. function extractSSRCMap(desc) {
  299. if (typeof desc !== 'object' || desc === null ||
  300. typeof desc.sdp !== 'string') {
  301. logger.warn('An empty description was passed as an argument.');
  302. return desc;
  303. }
  304. var ssrcList = {};
  305. var ssrcGroups = {};
  306. var session = transform.parse(desc.sdp);
  307. if (!Array.isArray(session.media))
  308. {
  309. return;
  310. }
  311. session.media.forEach(function (bLine) {
  312. if (!Array.isArray(bLine.ssrcs))
  313. {
  314. return;
  315. }
  316. if (typeof bLine.ssrcGroups !== 'undefined' &&
  317. Array.isArray(bLine.ssrcGroups)) {
  318. bLine.ssrcGroups.forEach(function (group) {
  319. if (typeof group.semantics !== 'undefined' &&
  320. typeof group.ssrcs !== 'undefined') {
  321. var primarySSRC = Number(group.ssrcs.split(' ')[0]);
  322. ssrcGroups[primarySSRC] = ssrcGroups[primarySSRC] || [];
  323. ssrcGroups[primarySSRC].push(group);
  324. }
  325. });
  326. }
  327. bLine.ssrcs.forEach(function (ssrc) {
  328. if(ssrc.attribute !== 'msid')
  329. return;
  330. ssrcList[ssrc.value] = ssrcList[ssrc.value] ||
  331. {groups: [], ssrcs: []};
  332. ssrcList[ssrc.value].ssrcs.push(ssrc.id);
  333. if(ssrcGroups[ssrc.id]){
  334. ssrcGroups[ssrc.id].forEach(function (group) {
  335. ssrcList[ssrc.value].groups.push(
  336. {primarySSRC: ssrc.id, group: group});
  337. });
  338. }
  339. });
  340. });
  341. return ssrcList;
  342. }
  343. /**
  344. * Takes a SessionDescription object and returns a "normalized" version.
  345. * Currently it only takes care of ordering the a=ssrc lines.
  346. */
  347. var normalizePlanB = function(desc) {
  348. if (typeof desc !== 'object' || desc === null ||
  349. typeof desc.sdp !== 'string') {
  350. logger.warn('An empty description was passed as an argument.');
  351. return desc;
  352. }
  353. var transform = require('sdp-transform');
  354. var session = transform.parse(desc.sdp);
  355. if (typeof session !== 'undefined' &&
  356. typeof session.media !== 'undefined' && Array.isArray(session.media)) {
  357. session.media.forEach(function (mLine) {
  358. // Chrome appears to be picky about the order in which a=ssrc lines
  359. // are listed in an m-line when rtx is enabled (and thus there are
  360. // a=ssrc-group lines with FID semantics). Specifically if we have
  361. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  362. // the "a=ssrc:S1" lines, SRD fails.
  363. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  364. // first.
  365. var firstSsrcs = [];
  366. var newSsrcLines = [];
  367. if (typeof mLine.ssrcGroups !== 'undefined' &&
  368. Array.isArray(mLine.ssrcGroups)) {
  369. mLine.ssrcGroups.forEach(function (group) {
  370. if (typeof group.semantics !== 'undefined' &&
  371. group.semantics === 'FID') {
  372. if (typeof group.ssrcs !== 'undefined') {
  373. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  374. }
  375. }
  376. });
  377. }
  378. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  379. var i;
  380. for (i = 0; i<mLine.ssrcs.length; i++){
  381. if (typeof mLine.ssrcs[i] === 'object'
  382. && typeof mLine.ssrcs[i].id !== 'undefined'
  383. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  384. newSsrcLines.push(mLine.ssrcs[i]);
  385. delete mLine.ssrcs[i];
  386. }
  387. }
  388. for (i = 0; i<mLine.ssrcs.length; i++){
  389. if (typeof mLine.ssrcs[i] !== 'undefined') {
  390. newSsrcLines.push(mLine.ssrcs[i]);
  391. }
  392. }
  393. mLine.ssrcs = newSsrcLines;
  394. }
  395. });
  396. }
  397. var resStr = transform.write(session);
  398. return new RTCSessionDescription({
  399. type: desc.type,
  400. sdp: resStr
  401. });
  402. };
  403. var getters = {
  404. signalingState: function () {
  405. return this.peerconnection.signalingState;
  406. },
  407. iceConnectionState: function () {
  408. return this.peerconnection.iceConnectionState;
  409. },
  410. localDescription: function() {
  411. var desc = this.peerconnection.localDescription;
  412. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  413. // if we're running on FF, transform to Plan B first.
  414. if (RTCBrowserType.usesUnifiedPlan()) {
  415. desc = this.interop.toPlanB(desc);
  416. this.trace('getLocalDescription::postTransform (Plan B)',
  417. dumpSDP(desc));
  418. }
  419. return desc;
  420. },
  421. remoteDescription: function() {
  422. var desc = this.peerconnection.remoteDescription;
  423. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  424. // if we're running on FF, transform to Plan B first.
  425. if (RTCBrowserType.usesUnifiedPlan()) {
  426. desc = this.interop.toPlanB(desc);
  427. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  428. }
  429. return desc;
  430. }
  431. };
  432. Object.keys(getters).forEach(function (prop) {
  433. Object.defineProperty(
  434. TraceablePeerConnection.prototype,
  435. prop, {
  436. get: getters[prop]
  437. }
  438. );
  439. });
  440. TraceablePeerConnection.prototype.addStream = function (stream, ssrcInfo) {
  441. this.trace('addStream', stream? stream.id : "null");
  442. if(stream)
  443. this.peerconnection.addStream(stream);
  444. if(ssrcInfo && this.replaceSSRCs[ssrcInfo.mtype])
  445. this.replaceSSRCs[ssrcInfo.mtype].push(ssrcInfo);
  446. };
  447. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams,
  448. ssrcInfo) {
  449. this.trace('removeStream', stream.id);
  450. if(stopStreams) {
  451. RTC.stopMediaStream(stream);
  452. }
  453. // FF doesn't support this yet.
  454. if (this.peerconnection.removeStream) {
  455. this.peerconnection.removeStream(stream);
  456. // Removing all cached ssrcs for the streams that are removed or
  457. // muted.
  458. if(ssrcInfo && this.replaceSSRCs[ssrcInfo.mtype]) {
  459. for(var i = 0; i < this.replaceSSRCs[ssrcInfo.mtype].length; i++) {
  460. var op = this.replaceSSRCs[ssrcInfo.mtype][i];
  461. if(op.type === "unmute" &&
  462. op.ssrc.ssrcs.join("_") ===
  463. ssrcInfo.ssrc.ssrcs.join("_")) {
  464. this.replaceSSRCs[ssrcInfo.mtype].splice(i, 1);
  465. break;
  466. }
  467. }
  468. this.replaceSSRCs[ssrcInfo.mtype].push(ssrcInfo);
  469. }
  470. }
  471. };
  472. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  473. this.trace('createDataChannel', label, opts);
  474. return this.peerconnection.createDataChannel(label, opts);
  475. };
  476. TraceablePeerConnection.prototype.setLocalDescription
  477. = function (description, successCallback, failureCallback) {
  478. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  479. // if we're running on FF, transform to Plan A first.
  480. if (RTCBrowserType.usesUnifiedPlan()) {
  481. description = this.interop.toUnifiedPlan(description);
  482. this.trace('setLocalDescription::postTransform (Plan A)',
  483. dumpSDP(description));
  484. }
  485. var self = this;
  486. this.peerconnection.setLocalDescription(description,
  487. function () {
  488. self.trace('setLocalDescriptionOnSuccess');
  489. successCallback();
  490. },
  491. function (err) {
  492. self.trace('setLocalDescriptionOnFailure', err);
  493. self.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  494. err, self.peerconnection);
  495. failureCallback(err);
  496. }
  497. );
  498. };
  499. TraceablePeerConnection.prototype.setRemoteDescription
  500. = function (description, successCallback, failureCallback) {
  501. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  502. // TODO the focus should squeze or explode the remote simulcast
  503. description = this.simulcast.mungeRemoteDescription(description);
  504. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  505. // if we're running on FF, transform to Plan A first.
  506. if (RTCBrowserType.usesUnifiedPlan()) {
  507. description = this.interop.toUnifiedPlan(description);
  508. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  509. }
  510. if (RTCBrowserType.usesPlanB()) {
  511. description = normalizePlanB(description);
  512. }
  513. var self = this;
  514. this.peerconnection.setRemoteDescription(description,
  515. function () {
  516. self.trace('setRemoteDescriptionOnSuccess');
  517. successCallback();
  518. },
  519. function (err) {
  520. self.trace('setRemoteDescriptionOnFailure', err);
  521. self.eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  522. err, self.peerconnection);
  523. failureCallback(err);
  524. }
  525. );
  526. /*
  527. if (this.statsinterval === null && this.maxstats > 0) {
  528. // start gathering stats
  529. }
  530. */
  531. };
  532. TraceablePeerConnection.prototype.close = function () {
  533. this.trace('stop');
  534. if (this.statsinterval !== null) {
  535. window.clearInterval(this.statsinterval);
  536. this.statsinterval = null;
  537. }
  538. this.peerconnection.close();
  539. };
  540. TraceablePeerConnection.prototype.createAnswer
  541. = function (successCallback, failureCallback, constraints) {
  542. var self = this;
  543. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  544. this.peerconnection.createAnswer(
  545. function (answer) {
  546. try {
  547. self.trace(
  548. 'createAnswerOnSuccess::preTransform', dumpSDP(answer));
  549. // if we're running on FF, transform to Plan A first.
  550. if (RTCBrowserType.usesUnifiedPlan()) {
  551. answer = self.interop.toPlanB(answer);
  552. self.trace('createAnswerOnSuccess::postTransform (Plan B)',
  553. dumpSDP(answer));
  554. }
  555. if (!self.session.room.options.disableSimulcast
  556. && self.simulcast.isSupported()) {
  557. answer = self.simulcast.mungeLocalDescription(answer);
  558. self.trace(
  559. 'createAnswerOnSuccess::postTransform (simulcast)',
  560. dumpSDP(answer));
  561. }
  562. if (!RTCBrowserType.isFirefox())
  563. {
  564. answer = self.ssrcReplacement(answer);
  565. self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC',
  566. dumpSDP(answer));
  567. }
  568. self.eventEmitter.emit(XMPPEvents.SENDRECV_STREAMS_CHANGED,
  569. extractSSRCMap(answer));
  570. successCallback(answer);
  571. } catch (e) {
  572. // there can be error modifying the answer, for example
  573. // for ssrcReplacement there was a track with ssrc that is null
  574. // and if we do not catch the error no callback is called
  575. // at all
  576. self.trace('createAnswerOnError', e);
  577. self.trace('createAnswerOnError', dumpSDP(answer));
  578. logger.error('createAnswerOnError', e, dumpSDP(answer));
  579. failureCallback(e);
  580. }
  581. },
  582. function(err) {
  583. self.trace('createAnswerOnFailure', err);
  584. self.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_FAILED, err,
  585. self.peerconnection);
  586. failureCallback(err);
  587. },
  588. constraints
  589. );
  590. };
  591. TraceablePeerConnection.prototype.addIceCandidate
  592. = function (candidate, successCallback, failureCallback) {
  593. //var self = this;
  594. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  595. this.peerconnection.addIceCandidate(candidate);
  596. /* maybe later
  597. this.peerconnection.addIceCandidate(candidate,
  598. function () {
  599. self.trace('addIceCandidateOnSuccess');
  600. successCallback();
  601. },
  602. function (err) {
  603. self.trace('addIceCandidateOnFailure', err);
  604. failureCallback(err);
  605. }
  606. );
  607. */
  608. };
  609. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  610. // TODO: Is this the correct way to handle Opera, Temasys?
  611. if (RTCBrowserType.isFirefox()
  612. || RTCBrowserType.isTemasysPluginUsed()
  613. || RTCBrowserType.isReactNative()) {
  614. // ignore for now...
  615. if(!errback)
  616. errback = function () {};
  617. this.peerconnection.getStats(null, callback, errback);
  618. } else {
  619. this.peerconnection.getStats(callback);
  620. }
  621. };
  622. /**
  623. * Generate ssrc info object for a stream with the following properties:
  624. * - ssrcs - Array of the ssrcs associated with the stream.
  625. * - groups - Array of the groups associated with the stream.
  626. */
  627. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function () {
  628. if (!this.session.room.options.disableSimulcast
  629. && this.simulcast.isSupported()) {
  630. var ssrcInfo = {ssrcs: [], groups: []};
  631. for(var i = 0; i < SIMULCAST_LAYERS; i++)
  632. ssrcInfo.ssrcs.push(RandomUtil.randomInt(1, 0xffffffff));
  633. ssrcInfo.groups.push({
  634. primarySSRC: ssrcInfo.ssrcs[0],
  635. group: {ssrcs: ssrcInfo.ssrcs.join(" "), semantics: "SIM"}});
  636. return ssrcInfo;
  637. } else {
  638. return {ssrcs: [RandomUtil.randomInt(1, 0xffffffff)], groups: []};
  639. }
  640. };
  641. module.exports = TraceablePeerConnection;