Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TraceablePeerConnection.js 16KB

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