You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TraceablePeerConnection.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. var RTC = require('../RTC/RTC');
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  4. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5. var SSRCReplacement = require("./LocalSSRCReplacement");
  6. function TraceablePeerConnection(ice_config, constraints, session) {
  7. var self = this;
  8. this.session = session;
  9. var RTCPeerConnectionType = null;
  10. if (RTCBrowserType.isFirefox()) {
  11. RTCPeerConnectionType = mozRTCPeerConnection;
  12. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  13. RTCPeerConnectionType = RTCPeerConnection;
  14. } else {
  15. RTCPeerConnectionType = webkitRTCPeerConnection;
  16. }
  17. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  18. this.updateLog = [];
  19. this.stats = {};
  20. this.statsinterval = null;
  21. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  22. var Interop = require('sdp-interop').Interop;
  23. this.interop = new Interop();
  24. var Simulcast = require('sdp-simulcast');
  25. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  26. // override as desired
  27. this.trace = function (what, info) {
  28. /*logger.warn('WTRACE', what, info);
  29. if (info && RTCBrowserType.isIExplorer()) {
  30. if (info.length > 1024) {
  31. logger.warn('WTRACE', what, info.substr(1024));
  32. }
  33. if (info.length > 2048) {
  34. logger.warn('WTRACE', what, info.substr(2048));
  35. }
  36. }*/
  37. self.updateLog.push({
  38. time: new Date(),
  39. type: what,
  40. value: info || ""
  41. });
  42. };
  43. this.onicecandidate = null;
  44. this.peerconnection.onicecandidate = function (event) {
  45. // FIXME: this causes stack overflow with Temasys Plugin
  46. if (!RTCBrowserType.isTemasysPluginUsed())
  47. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  48. if (self.onicecandidate !== null) {
  49. self.onicecandidate(event);
  50. }
  51. };
  52. this.onaddstream = null;
  53. this.peerconnection.onaddstream = function (event) {
  54. self.trace('onaddstream', event.stream.id);
  55. if (self.onaddstream !== null) {
  56. self.onaddstream(event);
  57. }
  58. };
  59. this.onremovestream = null;
  60. this.peerconnection.onremovestream = function (event) {
  61. self.trace('onremovestream', event.stream.id);
  62. if (self.onremovestream !== null) {
  63. self.onremovestream(event);
  64. }
  65. };
  66. this.onsignalingstatechange = null;
  67. this.peerconnection.onsignalingstatechange = function (event) {
  68. self.trace('onsignalingstatechange', self.signalingState);
  69. if (self.onsignalingstatechange !== null) {
  70. self.onsignalingstatechange(event);
  71. }
  72. };
  73. this.oniceconnectionstatechange = null;
  74. this.peerconnection.oniceconnectionstatechange = function (event) {
  75. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  76. if (self.oniceconnectionstatechange !== null) {
  77. self.oniceconnectionstatechange(event);
  78. }
  79. };
  80. this.onnegotiationneeded = null;
  81. this.peerconnection.onnegotiationneeded = function (event) {
  82. self.trace('onnegotiationneeded');
  83. if (self.onnegotiationneeded !== null) {
  84. self.onnegotiationneeded(event);
  85. }
  86. };
  87. self.ondatachannel = null;
  88. this.peerconnection.ondatachannel = function (event) {
  89. self.trace('ondatachannel', event);
  90. if (self.ondatachannel !== null) {
  91. self.ondatachannel(event);
  92. }
  93. };
  94. // XXX: do all non-firefox browsers which we support also support this?
  95. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  96. this.statsinterval = window.setInterval(function() {
  97. self.peerconnection.getStats(function(stats) {
  98. var results = stats.result();
  99. var now = new Date();
  100. for (var i = 0; i < results.length; ++i) {
  101. results[i].names().forEach(function (name) {
  102. var id = results[i].id + '-' + name;
  103. if (!self.stats[id]) {
  104. self.stats[id] = {
  105. startTime: now,
  106. endTime: now,
  107. values: [],
  108. times: []
  109. };
  110. }
  111. self.stats[id].values.push(results[i].stat(name));
  112. self.stats[id].times.push(now.getTime());
  113. if (self.stats[id].values.length > self.maxstats) {
  114. self.stats[id].values.shift();
  115. self.stats[id].times.shift();
  116. }
  117. self.stats[id].endTime = now;
  118. });
  119. }
  120. });
  121. }, 1000);
  122. }
  123. }
  124. /**
  125. * Returns a string representation of a SessionDescription object.
  126. */
  127. var dumpSDP = function(description) {
  128. if (typeof description === 'undefined' || description == null) {
  129. return '';
  130. }
  131. return 'type: ' + description.type + '\r\n' + description.sdp;
  132. };
  133. /**
  134. * Takes a SessionDescription object and returns a "normalized" version.
  135. * Currently it only takes care of ordering the a=ssrc lines.
  136. */
  137. var normalizePlanB = function(desc) {
  138. if (typeof desc !== 'object' || desc === null ||
  139. typeof desc.sdp !== 'string') {
  140. logger.warn('An empty description was passed as an argument.');
  141. return desc;
  142. }
  143. var transform = require('sdp-transform');
  144. var session = transform.parse(desc.sdp);
  145. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  146. Array.isArray(session.media)) {
  147. session.media.forEach(function (mLine) {
  148. // Chrome appears to be picky about the order in which a=ssrc lines
  149. // are listed in an m-line when rtx is enabled (and thus there are
  150. // a=ssrc-group lines with FID semantics). Specifically if we have
  151. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  152. // the "a=ssrc:S1" lines, SRD fails.
  153. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  154. // first.
  155. var firstSsrcs = [];
  156. var newSsrcLines = [];
  157. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  158. mLine.ssrcGroups.forEach(function (group) {
  159. if (typeof group.semantics !== 'undefined' &&
  160. group.semantics === 'FID') {
  161. if (typeof group.ssrcs !== 'undefined') {
  162. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  163. }
  164. }
  165. });
  166. }
  167. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  168. for (var i = 0; i<mLine.ssrcs.length; i++){
  169. if (typeof mLine.ssrcs[i] === 'object'
  170. && typeof mLine.ssrcs[i].id !== 'undefined'
  171. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  172. newSsrcLines.push(mLine.ssrcs[i]);
  173. delete mLine.ssrcs[i];
  174. }
  175. }
  176. for (var i = 0; i<mLine.ssrcs.length; i++){
  177. if (typeof mLine.ssrcs[i] !== 'undefined') {
  178. newSsrcLines.push(mLine.ssrcs[i]);
  179. }
  180. }
  181. mLine.ssrcs = newSsrcLines;
  182. }
  183. });
  184. }
  185. var resStr = transform.write(session);
  186. return new RTCSessionDescription({
  187. type: desc.type,
  188. sdp: resStr
  189. });
  190. };
  191. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  192. TraceablePeerConnection.prototype.__defineGetter__(
  193. 'signalingState',
  194. function() { return this.peerconnection.signalingState; });
  195. TraceablePeerConnection.prototype.__defineGetter__(
  196. 'iceConnectionState',
  197. function() { return this.peerconnection.iceConnectionState; });
  198. TraceablePeerConnection.prototype.__defineGetter__(
  199. 'localDescription',
  200. function() {
  201. var desc = this.peerconnection.localDescription;
  202. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  203. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  204. // if we're running on FF, transform to Plan B first.
  205. if (RTCBrowserType.usesUnifiedPlan()) {
  206. desc = this.interop.toPlanB(desc);
  207. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  208. }
  209. return desc;
  210. });
  211. TraceablePeerConnection.prototype.__defineGetter__(
  212. 'remoteDescription',
  213. function() {
  214. var desc = this.peerconnection.remoteDescription;
  215. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  216. // if we're running on FF, transform to Plan B first.
  217. if (RTCBrowserType.usesUnifiedPlan()) {
  218. desc = this.interop.toPlanB(desc);
  219. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  220. }
  221. return desc;
  222. });
  223. }
  224. TraceablePeerConnection.prototype.addStream = function (stream) {
  225. this.trace('addStream', stream.id);
  226. try
  227. {
  228. this.peerconnection.addStream(stream);
  229. }
  230. catch (e)
  231. {
  232. logger.error(e);
  233. }
  234. };
  235. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  236. this.trace('removeStream', stream.id);
  237. if(stopStreams) {
  238. stream.getAudioTracks().forEach(function (track) {
  239. // stop() not supported with IE
  240. if (track.stop) {
  241. track.stop();
  242. }
  243. });
  244. stream.getVideoTracks().forEach(function (track) {
  245. // stop() not supported with IE
  246. if (track.stop) {
  247. track.stop();
  248. }
  249. });
  250. if (stream.stop) {
  251. stream.stop();
  252. }
  253. }
  254. try {
  255. // FF doesn't support this yet.
  256. if (this.peerconnection.removeStream)
  257. this.peerconnection.removeStream(stream);
  258. } catch (e) {
  259. logger.error(e);
  260. }
  261. };
  262. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  263. this.trace('createDataChannel', label, opts);
  264. return this.peerconnection.createDataChannel(label, opts);
  265. };
  266. TraceablePeerConnection.prototype.setLocalDescription
  267. = function (description, successCallback, failureCallback) {
  268. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  269. // if we're running on FF, transform to Plan A first.
  270. if (RTCBrowserType.usesUnifiedPlan()) {
  271. description = this.interop.toUnifiedPlan(description);
  272. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  273. }
  274. var self = this;
  275. this.peerconnection.setLocalDescription(description,
  276. function () {
  277. self.trace('setLocalDescriptionOnSuccess');
  278. successCallback();
  279. },
  280. function (err) {
  281. self.trace('setLocalDescriptionOnFailure', err);
  282. failureCallback(err);
  283. }
  284. );
  285. /*
  286. if (this.statsinterval === null && this.maxstats > 0) {
  287. // start gathering stats
  288. }
  289. */
  290. };
  291. TraceablePeerConnection.prototype.setRemoteDescription
  292. = function (description, successCallback, failureCallback) {
  293. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  294. // TODO the focus should squeze or explode the remote simulcast
  295. description = this.simulcast.mungeRemoteDescription(description);
  296. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  297. // if we're running on FF, transform to Plan A first.
  298. if (RTCBrowserType.usesUnifiedPlan()) {
  299. description = this.interop.toUnifiedPlan(description);
  300. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  301. }
  302. if (RTCBrowserType.usesPlanB()) {
  303. description = normalizePlanB(description);
  304. }
  305. var self = this;
  306. this.peerconnection.setRemoteDescription(description,
  307. function () {
  308. self.trace('setRemoteDescriptionOnSuccess');
  309. successCallback();
  310. },
  311. function (err) {
  312. self.trace('setRemoteDescriptionOnFailure', err);
  313. failureCallback(err);
  314. }
  315. );
  316. /*
  317. if (this.statsinterval === null && this.maxstats > 0) {
  318. // start gathering stats
  319. }
  320. */
  321. };
  322. TraceablePeerConnection.prototype.close = function () {
  323. this.trace('stop');
  324. if (this.statsinterval !== null) {
  325. window.clearInterval(this.statsinterval);
  326. this.statsinterval = null;
  327. }
  328. this.peerconnection.close();
  329. };
  330. TraceablePeerConnection.prototype.createOffer
  331. = function (successCallback, failureCallback, constraints) {
  332. var self = this;
  333. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  334. this.peerconnection.createOffer(
  335. function (offer) {
  336. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  337. // NOTE this is not tested because in meet the focus generates the
  338. // offer.
  339. // if we're running on FF, transform to Plan B first.
  340. if (RTCBrowserType.usesUnifiedPlan()) {
  341. offer = self.interop.toPlanB(offer);
  342. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  343. }
  344. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  345. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  346. offer = self.simulcast.mungeLocalDescription(offer);
  347. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  348. }
  349. successCallback(offer);
  350. },
  351. function(err) {
  352. self.trace('createOfferOnFailure', err);
  353. failureCallback(err);
  354. },
  355. constraints
  356. );
  357. };
  358. TraceablePeerConnection.prototype.createAnswer
  359. = function (successCallback, failureCallback, constraints) {
  360. var self = this;
  361. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  362. this.peerconnection.createAnswer(
  363. function (answer) {
  364. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  365. // if we're running on FF, transform to Plan A first.
  366. if (RTCBrowserType.usesUnifiedPlan()) {
  367. answer = self.interop.toPlanB(answer);
  368. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  369. }
  370. // munge local video SSRC
  371. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  372. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  373. answer = self.simulcast.mungeLocalDescription(answer);
  374. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  375. }
  376. successCallback(answer);
  377. },
  378. function(err) {
  379. self.trace('createAnswerOnFailure', err);
  380. failureCallback(err);
  381. },
  382. constraints
  383. );
  384. };
  385. TraceablePeerConnection.prototype.addIceCandidate
  386. = function (candidate, successCallback, failureCallback) {
  387. //var self = this;
  388. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  389. this.peerconnection.addIceCandidate(candidate);
  390. /* maybe later
  391. this.peerconnection.addIceCandidate(candidate,
  392. function () {
  393. self.trace('addIceCandidateOnSuccess');
  394. successCallback();
  395. },
  396. function (err) {
  397. self.trace('addIceCandidateOnFailure', err);
  398. failureCallback(err);
  399. }
  400. );
  401. */
  402. };
  403. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  404. // TODO: Is this the correct way to handle Opera, Temasys?
  405. if (RTCBrowserType.isFirefox()) {
  406. // ignore for now...
  407. if(!errback)
  408. errback = function () {};
  409. this.peerconnection.getStats(null, callback, errback);
  410. } else {
  411. this.peerconnection.getStats(callback);
  412. }
  413. };
  414. module.exports = TraceablePeerConnection;