您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TraceablePeerConnection.js 16KB

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