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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. function TraceablePeerConnection(ice_config, constraints, session) {
  8. var self = this;
  9. var RTCPeerConnectionType = null;
  10. if (RTCBrowserType.isFirefox()) {
  11. RTCPeerConnectionType = mozRTCPeerConnection;
  12. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  13. RTCPeerConnectionType = RTCPeerConnection;
  14. } else {
  15. RTCPeerConnectionType = webkitRTCPeerConnection;
  16. }
  17. self.eventEmitter = session.eventEmitter;
  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. /*console.warn('WTRACE', what, info);
  30. if (info && RTCBrowserType.isIExplorer()) {
  31. if (info.length > 1024) {
  32. console.warn('WTRACE', what, info.substr(1024));
  33. }
  34. if (info.length > 2048) {
  35. console.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. var insertRecvOnlySSRC = 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 RandomUtil = require('../util/RandomUtil');
  142. var session = transform.parse(desc.sdp);
  143. if (!Array.isArray(session.media))
  144. {
  145. return;
  146. }
  147. var modded = false;
  148. session.media.forEach(function (bLine) {
  149. if (bLine.direction != 'recvonly')
  150. {
  151. return;
  152. }
  153. modded = true;
  154. if (!Array.isArray(bLine.ssrcs) || bLine.ssrcs.length === 0)
  155. {
  156. var ssrc = RandomUtil.randomInt(1, 0xffffffff);
  157. bLine.ssrcs = [{
  158. id: ssrc,
  159. attribute: 'cname',
  160. value: ['recvonly-', ssrc].join('')
  161. }];
  162. }
  163. });
  164. return (!modded) ? desc : new RTCSessionDescription({
  165. type: desc.type,
  166. sdp: transform.write(session),
  167. });
  168. };
  169. /**
  170. * Takes a SessionDescription object and returns a "normalized" version.
  171. * Currently it only takes care of ordering the a=ssrc lines.
  172. */
  173. var normalizePlanB = function(desc) {
  174. if (typeof desc !== 'object' || desc === null ||
  175. typeof desc.sdp !== 'string') {
  176. console.warn('An empty description was passed as an argument.');
  177. return desc;
  178. }
  179. var transform = require('sdp-transform');
  180. var session = transform.parse(desc.sdp);
  181. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  182. Array.isArray(session.media)) {
  183. session.media.forEach(function (mLine) {
  184. // Chrome appears to be picky about the order in which a=ssrc lines
  185. // are listed in an m-line when rtx is enabled (and thus there are
  186. // a=ssrc-group lines with FID semantics). Specifically if we have
  187. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  188. // the "a=ssrc:S1" lines, SRD fails.
  189. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  190. // first.
  191. var firstSsrcs = [];
  192. var newSsrcLines = [];
  193. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  194. mLine.ssrcGroups.forEach(function (group) {
  195. if (typeof group.semantics !== 'undefined' &&
  196. group.semantics === 'FID') {
  197. if (typeof group.ssrcs !== 'undefined') {
  198. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  199. }
  200. }
  201. });
  202. }
  203. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  204. var i;
  205. for (i = 0; i<mLine.ssrcs.length; i++){
  206. if (typeof mLine.ssrcs[i] === 'object'
  207. && typeof mLine.ssrcs[i].id !== 'undefined'
  208. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  209. newSsrcLines.push(mLine.ssrcs[i]);
  210. delete mLine.ssrcs[i];
  211. }
  212. }
  213. for (i = 0; i<mLine.ssrcs.length; i++){
  214. if (typeof mLine.ssrcs[i] !== 'undefined') {
  215. newSsrcLines.push(mLine.ssrcs[i]);
  216. }
  217. }
  218. mLine.ssrcs = newSsrcLines;
  219. }
  220. });
  221. }
  222. var resStr = transform.write(session);
  223. return new RTCSessionDescription({
  224. type: desc.type,
  225. sdp: resStr
  226. });
  227. };
  228. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  229. TraceablePeerConnection.prototype.__defineGetter__(
  230. 'signalingState',
  231. function() { return this.peerconnection.signalingState; });
  232. TraceablePeerConnection.prototype.__defineGetter__(
  233. 'iceConnectionState',
  234. function() { return this.peerconnection.iceConnectionState; });
  235. TraceablePeerConnection.prototype.__defineGetter__(
  236. 'localDescription',
  237. function() {
  238. var desc = this.peerconnection.localDescription;
  239. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  240. // if we're running on FF, transform to Plan B first.
  241. if (RTCBrowserType.usesUnifiedPlan()) {
  242. desc = this.interop.toPlanB(desc);
  243. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  244. }
  245. return desc;
  246. });
  247. TraceablePeerConnection.prototype.__defineGetter__(
  248. 'remoteDescription',
  249. function() {
  250. var desc = this.peerconnection.remoteDescription;
  251. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  252. // if we're running on FF, transform to Plan B first.
  253. if (RTCBrowserType.usesUnifiedPlan()) {
  254. desc = this.interop.toPlanB(desc);
  255. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  256. }
  257. return desc;
  258. });
  259. }
  260. TraceablePeerConnection.prototype.addStream = function (stream) {
  261. this.trace('addStream', stream.id);
  262. try
  263. {
  264. this.peerconnection.addStream(stream);
  265. }
  266. catch (e)
  267. {
  268. console.error(e);
  269. }
  270. };
  271. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  272. this.trace('removeStream', stream.id);
  273. if(stopStreams) {
  274. RTC.stopMediaStream(stream);
  275. }
  276. try {
  277. // FF doesn't support this yet.
  278. if (this.peerconnection.removeStream)
  279. this.peerconnection.removeStream(stream);
  280. } catch (e) {
  281. console.error(e);
  282. }
  283. };
  284. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  285. this.trace('createDataChannel', label, opts);
  286. return this.peerconnection.createDataChannel(label, opts);
  287. };
  288. TraceablePeerConnection.prototype.setLocalDescription
  289. = function (description, successCallback, failureCallback) {
  290. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  291. // if we're running on FF, transform to Plan A first.
  292. if (RTCBrowserType.usesUnifiedPlan()) {
  293. description = this.interop.toUnifiedPlan(description);
  294. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  295. }
  296. var self = this;
  297. this.peerconnection.setLocalDescription(description,
  298. function () {
  299. self.trace('setLocalDescriptionOnSuccess');
  300. successCallback();
  301. },
  302. function (err) {
  303. self.trace('setLocalDescriptionOnFailure', err);
  304. self.eventEmitter.emit(RTCEvents.SET_LOCAL_DESCRIPTION_FAILED, err, self.peerconnection);
  305. failureCallback(err);
  306. }
  307. );
  308. /*
  309. if (this.statsinterval === null && this.maxstats > 0) {
  310. // start gathering stats
  311. }
  312. */
  313. };
  314. TraceablePeerConnection.prototype.setRemoteDescription
  315. = function (description, successCallback, failureCallback) {
  316. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  317. // TODO the focus should squeze or explode the remote simulcast
  318. description = this.simulcast.mungeRemoteDescription(description);
  319. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  320. // if we're running on FF, transform to Plan A first.
  321. if (RTCBrowserType.usesUnifiedPlan()) {
  322. description = this.interop.toUnifiedPlan(description);
  323. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  324. }
  325. if (RTCBrowserType.usesPlanB()) {
  326. description = normalizePlanB(description);
  327. }
  328. var self = this;
  329. this.peerconnection.setRemoteDescription(description,
  330. function () {
  331. self.trace('setRemoteDescriptionOnSuccess');
  332. successCallback();
  333. },
  334. function (err) {
  335. self.trace('setRemoteDescriptionOnFailure', err);
  336. self.eventEmitter.emit(RTCEvents.SET_REMOTE_DESCRIPTION_FAILED, err, self.peerconnection);
  337. failureCallback(err);
  338. }
  339. );
  340. /*
  341. if (this.statsinterval === null && this.maxstats > 0) {
  342. // start gathering stats
  343. }
  344. */
  345. };
  346. TraceablePeerConnection.prototype.close = function () {
  347. this.trace('stop');
  348. if (this.statsinterval !== null) {
  349. window.clearInterval(this.statsinterval);
  350. this.statsinterval = null;
  351. }
  352. this.peerconnection.close();
  353. };
  354. TraceablePeerConnection.prototype.createOffer
  355. = function (successCallback, failureCallback, constraints) {
  356. var self = this;
  357. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  358. this.peerconnection.createOffer(
  359. function (offer) {
  360. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  361. // NOTE this is not tested because in meet the focus generates the
  362. // offer.
  363. // if we're running on FF, transform to Plan B first.
  364. if (RTCBrowserType.usesUnifiedPlan()) {
  365. offer = self.interop.toPlanB(offer);
  366. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  367. }
  368. if (RTCBrowserType.isChrome())
  369. {
  370. offer = insertRecvOnlySSRC(offer);
  371. self.trace('createOfferOnSuccess::mungeLocalVideoSSRC', dumpSDP(offer));
  372. }
  373. if (config.enableSimulcast && self.simulcast.isSupported()) {
  374. offer = self.simulcast.mungeLocalDescription(offer);
  375. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  376. }
  377. successCallback(offer);
  378. },
  379. function(err) {
  380. self.trace('createOfferOnFailure', err);
  381. self.eventEmitter.emit(RTCEvents.CREATE_OFFER_FAILED, err, self.peerconnection);
  382. failureCallback(err);
  383. },
  384. constraints
  385. );
  386. };
  387. TraceablePeerConnection.prototype.createAnswer
  388. = function (successCallback, failureCallback, constraints) {
  389. var self = this;
  390. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  391. this.peerconnection.createAnswer(
  392. function (answer) {
  393. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  394. // if we're running on FF, transform to Plan A first.
  395. if (RTCBrowserType.usesUnifiedPlan()) {
  396. answer = self.interop.toPlanB(answer);
  397. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  398. }
  399. if (RTCBrowserType.isChrome())
  400. {
  401. answer = insertRecvOnlySSRC(answer);
  402. self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC', dumpSDP(answer));
  403. }
  404. if (config.enableSimulcast && self.simulcast.isSupported()) {
  405. answer = self.simulcast.mungeLocalDescription(answer);
  406. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  407. }
  408. successCallback(answer);
  409. },
  410. function(err) {
  411. self.trace('createAnswerOnFailure', err);
  412. self.eventEmitter.emit(RTCEvents.CREATE_ANSWER_FAILED, err, self.peerconnection);
  413. failureCallback(err);
  414. },
  415. constraints
  416. );
  417. };
  418. TraceablePeerConnection.prototype.addIceCandidate
  419. = function (candidate, successCallback, failureCallback) {
  420. //var self = this;
  421. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  422. this.peerconnection.addIceCandidate(candidate);
  423. /* maybe later
  424. this.peerconnection.addIceCandidate(candidate,
  425. function () {
  426. self.trace('addIceCandidateOnSuccess');
  427. successCallback();
  428. },
  429. function (err) {
  430. self.trace('addIceCandidateOnFailure', err);
  431. failureCallback(err);
  432. }
  433. );
  434. */
  435. };
  436. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  437. // TODO: Is this the correct way to handle Opera, Temasys?
  438. if (RTCBrowserType.isFirefox()) {
  439. // ignore for now...
  440. if(!errback)
  441. errback = function () {};
  442. this.peerconnection.getStats(null, callback, errback);
  443. } else {
  444. this.peerconnection.getStats(callback);
  445. }
  446. };
  447. module.exports = TraceablePeerConnection;