Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

TraceablePeerConnection.js 16KB

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