Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

TraceablePeerConnection.js 16KB

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