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

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