選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

TraceablePeerConnection.js 16KB

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