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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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: 2, 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. // TODO this should be after the Unified Plan -> Plan B
  206. // transformation.
  207. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  208. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  209. // if we're running on FF, transform to Plan B first.
  210. if (RTCBrowserType.usesUnifiedPlan()) {
  211. desc = this.interop.toPlanB(desc);
  212. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  213. }
  214. return desc;
  215. });
  216. TraceablePeerConnection.prototype.__defineGetter__(
  217. 'remoteDescription',
  218. function() {
  219. var desc = this.peerconnection.remoteDescription;
  220. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  221. // if we're running on FF, transform to Plan B first.
  222. if (RTCBrowserType.usesUnifiedPlan()) {
  223. desc = this.interop.toPlanB(desc);
  224. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  225. }
  226. return desc;
  227. });
  228. }
  229. TraceablePeerConnection.prototype.addStream = function (stream) {
  230. this.trace('addStream', stream.id);
  231. try
  232. {
  233. this.peerconnection.addStream(stream);
  234. }
  235. catch (e)
  236. {
  237. console.error(e);
  238. }
  239. };
  240. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  241. this.trace('removeStream', stream.id);
  242. if(stopStreams) {
  243. RTC.stopMediaStream(stream);
  244. }
  245. try {
  246. // FF doesn't support this yet.
  247. if (this.peerconnection.removeStream)
  248. this.peerconnection.removeStream(stream);
  249. } catch (e) {
  250. console.error(e);
  251. }
  252. };
  253. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  254. this.trace('createDataChannel', label, opts);
  255. return this.peerconnection.createDataChannel(label, opts);
  256. };
  257. TraceablePeerConnection.prototype.setLocalDescription
  258. = function (description, successCallback, failureCallback) {
  259. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  260. // if we're running on FF, transform to Plan A first.
  261. if (RTCBrowserType.usesUnifiedPlan()) {
  262. description = this.interop.toUnifiedPlan(description);
  263. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  264. }
  265. var self = this;
  266. this.peerconnection.setLocalDescription(description,
  267. function () {
  268. self.trace('setLocalDescriptionOnSuccess');
  269. successCallback();
  270. },
  271. function (err) {
  272. self.trace('setLocalDescriptionOnFailure', err);
  273. self.eventEmitter.emit(RTCEvents.SET_LOCAL_DESCRIPTION_FAILED, err);
  274. failureCallback(err);
  275. }
  276. );
  277. /*
  278. if (this.statsinterval === null && this.maxstats > 0) {
  279. // start gathering stats
  280. }
  281. */
  282. };
  283. TraceablePeerConnection.prototype.setRemoteDescription
  284. = function (description, successCallback, failureCallback) {
  285. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  286. // TODO the focus should squeze or explode the remote simulcast
  287. description = this.simulcast.mungeRemoteDescription(description);
  288. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  289. // if we're running on FF, transform to Plan A first.
  290. if (RTCBrowserType.usesUnifiedPlan()) {
  291. description = this.interop.toUnifiedPlan(description);
  292. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  293. }
  294. if (RTCBrowserType.usesPlanB()) {
  295. description = normalizePlanB(description);
  296. }
  297. var self = this;
  298. this.peerconnection.setRemoteDescription(description,
  299. function () {
  300. self.trace('setRemoteDescriptionOnSuccess');
  301. successCallback();
  302. },
  303. function (err) {
  304. self.trace('setRemoteDescriptionOnFailure', err);
  305. self.eventEmitter.emit(RTCEvents.SET_REMOTE_DESCRIPTION_FAILED, err);
  306. failureCallback(err);
  307. }
  308. );
  309. /*
  310. if (this.statsinterval === null && this.maxstats > 0) {
  311. // start gathering stats
  312. }
  313. */
  314. };
  315. TraceablePeerConnection.prototype.close = function () {
  316. this.trace('stop');
  317. if (this.statsinterval !== null) {
  318. window.clearInterval(this.statsinterval);
  319. this.statsinterval = null;
  320. }
  321. this.peerconnection.close();
  322. };
  323. TraceablePeerConnection.prototype.createOffer
  324. = function (successCallback, failureCallback, constraints) {
  325. var self = this;
  326. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  327. this.peerconnection.createOffer(
  328. function (offer) {
  329. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  330. // NOTE this is not tested because in meet the focus generates the
  331. // offer.
  332. // if we're running on FF, transform to Plan B first.
  333. if (RTCBrowserType.usesUnifiedPlan()) {
  334. offer = self.interop.toPlanB(offer);
  335. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  336. }
  337. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  338. if (config.enableSimulcast && self.simulcast.isSupported()) {
  339. offer = self.simulcast.mungeLocalDescription(offer);
  340. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  341. }
  342. successCallback(offer);
  343. },
  344. function(err) {
  345. self.trace('createOfferOnFailure', err);
  346. self.eventEmitter.emit(RTCEvents.CREATE_OFFER_FAILED, err);
  347. failureCallback(err);
  348. },
  349. constraints
  350. );
  351. };
  352. TraceablePeerConnection.prototype.createAnswer
  353. = function (successCallback, failureCallback, constraints) {
  354. var self = this;
  355. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  356. this.peerconnection.createAnswer(
  357. function (answer) {
  358. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  359. // if we're running on FF, transform to Plan A first.
  360. if (RTCBrowserType.usesUnifiedPlan()) {
  361. answer = self.interop.toPlanB(answer);
  362. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  363. }
  364. // munge local video SSRC
  365. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  366. if (config.enableSimulcast && self.simulcast.isSupported()) {
  367. answer = self.simulcast.mungeLocalDescription(answer);
  368. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  369. }
  370. successCallback(answer);
  371. },
  372. function(err) {
  373. self.trace('createAnswerOnFailure', err);
  374. self.eventEmitter.emit(RTCEvents.CREATE_ANSWER_FAILED, 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;