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

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