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

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