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.

JingleSessionPC.js 58KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  1. /* jshint -W117 */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var JingleSession = require("./JingleSession");
  4. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5. var MediaType = require("../../service/RTC/MediaType");
  6. var SDPDiffer = require("./SDPDiffer");
  7. var SDPUtil = require("./SDPUtil");
  8. var SDP = require("./SDP");
  9. var async = require("async");
  10. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11. var RTCBrowserType = require("../RTC/RTCBrowserType");
  12. var RTC = require("../RTC/RTC");
  13. /**
  14. * Constant tells how long we're going to wait for IQ response, before timeout
  15. * error is triggered.
  16. * @type {number}
  17. */
  18. var IQ_TIMEOUT = 10000;
  19. // Jingle stuff
  20. function JingleSessionPC(me, sid, peerjid, connection,
  21. media_constraints, ice_config, service, eventEmitter) {
  22. JingleSession.call(this, me, sid, peerjid, connection,
  23. media_constraints, ice_config, service, eventEmitter);
  24. this.localSDP = null;
  25. this.remoteSDP = null;
  26. this.hadstuncandidate = false;
  27. this.hadturncandidate = false;
  28. this.lasticecandidate = false;
  29. this.closed = false;
  30. this.addssrc = [];
  31. this.removessrc = [];
  32. this.pendingop = null;
  33. this.modifyingLocalStreams = false;
  34. this.modifiedSSRCs = {};
  35. /**
  36. * A map that stores SSRCs of remote streams. And is used only locally
  37. * We store the mapping when jingle is received, and later is used
  38. * onaddstream webrtc event where we have only the ssrc
  39. * FIXME: This map got filled and never cleaned and can grow durring long
  40. * conference
  41. * @type {{}} maps SSRC number to jid
  42. */
  43. this.ssrcOwners = {};
  44. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  45. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  46. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  47. // We start with the queue paused. We resume it when the signaling state is
  48. // stable and the ice connection state is connected.
  49. this.modifySourcesQueue.pause();
  50. }
  51. //XXX this is badly broken...
  52. JingleSessionPC.prototype = JingleSession.prototype;
  53. JingleSessionPC.prototype.constructor = JingleSessionPC;
  54. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  55. var signalingState = this.peerconnection.signalingState;
  56. var iceConnectionState = this.peerconnection.iceConnectionState;
  57. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  58. this.modifySourcesQueue.resume();
  59. } else {
  60. this.modifySourcesQueue.pause();
  61. }
  62. };
  63. JingleSessionPC.prototype.doInitialize = function () {
  64. var self = this;
  65. this.hadstuncandidate = false;
  66. this.hadturncandidate = false;
  67. this.lasticecandidate = false;
  68. // True if reconnect is in progress
  69. this.isreconnect = false;
  70. // Set to true if the connection was ever stable
  71. this.wasstable = false;
  72. this.peerconnection = new TraceablePeerConnection(
  73. this.connection.jingle.ice_config,
  74. RTC.getPCConstraints(),
  75. this);
  76. this.peerconnection.onicecandidate = function (ev) {
  77. if (!ev) {
  78. // There was an incomplete check for ev before which left the last
  79. // line of the function unprotected from a potential throw of an
  80. // exception. Consequently, it may be argued that the check is
  81. // unnecessary. Anyway, I'm leaving it and making the check
  82. // complete.
  83. return;
  84. }
  85. var candidate = ev.candidate;
  86. if (candidate) {
  87. // Discard candidates of disabled protocols.
  88. var protocol = candidate.protocol;
  89. if (typeof protocol === 'string') {
  90. protocol = protocol.toLowerCase();
  91. if (protocol == 'tcp') {
  92. if (self.webrtcIceTcpDisable)
  93. return;
  94. } else if (protocol == 'udp') {
  95. if (self.webrtcIceUdpDisable)
  96. return;
  97. }
  98. }
  99. }
  100. self.sendIceCandidate(candidate);
  101. };
  102. this.peerconnection.onaddstream = function (event) {
  103. self.remoteStreamAdded(event.stream);
  104. };
  105. this.peerconnection.onremovestream = function (event) {
  106. self.remoteStreamRemoved(event.stream);
  107. };
  108. this.peerconnection.onsignalingstatechange = function (event) {
  109. if (!(self && self.peerconnection)) return;
  110. if (self.peerconnection.signalingState === 'stable') {
  111. self.wasstable = true;
  112. }
  113. self.updateModifySourcesQueue();
  114. };
  115. /**
  116. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  117. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  118. * RTCPeerConnection.iceConnectionState changes.
  119. *
  120. * @param event the event containing information about the change
  121. */
  122. this.peerconnection.oniceconnectionstatechange = function (event) {
  123. if (!(self && self.peerconnection)) return;
  124. var now = window.performance.now();
  125. self.room.connectionTimes["ice.state." +
  126. self.peerconnection.iceConnectionState] = now;
  127. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  128. ":\t", now);
  129. self.updateModifySourcesQueue();
  130. switch (self.peerconnection.iceConnectionState) {
  131. case 'connected':
  132. // Informs interested parties that the connection has been restored.
  133. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  134. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  135. self.isreconnect = false;
  136. break;
  137. case 'disconnected':
  138. if(self.closed)
  139. break;
  140. self.isreconnect = true;
  141. // Informs interested parties that the connection has been interrupted.
  142. if (self.wasstable)
  143. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  144. break;
  145. case 'failed':
  146. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_ICE_FAILED,
  147. self.peerconnection);
  148. break;
  149. }
  150. };
  151. this.peerconnection.onnegotiationneeded = function (event) {
  152. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  153. };
  154. };
  155. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  156. var self = this;
  157. if (candidate && !this.lasticecandidate) {
  158. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  159. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  160. if (!(ice && jcand)) {
  161. logger.error('failed to get ice && jcand');
  162. return;
  163. }
  164. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  165. if (jcand.type === 'srflx') {
  166. this.hadstuncandidate = true;
  167. } else if (jcand.type === 'relay') {
  168. this.hadturncandidate = true;
  169. }
  170. if (this.usedrip) {
  171. if (this.drip_container.length === 0) {
  172. // start 20ms callout
  173. window.setTimeout(function () {
  174. if (self.drip_container.length === 0) return;
  175. self.sendIceCandidates(self.drip_container);
  176. self.drip_container = [];
  177. }, 20);
  178. }
  179. this.drip_container.push(candidate);
  180. } else {
  181. self.sendIceCandidates([candidate]);
  182. }
  183. } else {
  184. logger.log('sendIceCandidate: last candidate.');
  185. // FIXME: remember to re-think in ICE-restart
  186. this.lasticecandidate = true;
  187. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  188. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  189. }
  190. };
  191. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  192. logger.log('sendIceCandidates', candidates);
  193. var cand = $iq({to: this.peerjid, type: 'set'})
  194. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  195. action: 'transport-info',
  196. initiator: this.initiator,
  197. sid: this.sid});
  198. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  199. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  200. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  201. if (cands.length > 0) {
  202. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  203. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  204. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  205. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  206. }).c('transport', ice);
  207. for (var i = 0; i < cands.length; i++) {
  208. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  209. }
  210. // add fingerprint
  211. var fingerprint_line = SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session);
  212. if (fingerprint_line) {
  213. var tmp = SDPUtil.parse_fingerprint(fingerprint_line);
  214. tmp.required = true;
  215. cand.c(
  216. 'fingerprint',
  217. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  218. .t(tmp.fingerprint);
  219. delete tmp.fingerprint;
  220. cand.attrs(tmp);
  221. cand.up();
  222. }
  223. cand.up(); // transport
  224. cand.up(); // content
  225. }
  226. }
  227. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  228. //logger.log('was this the last candidate', this.lasticecandidate);
  229. this.connection.sendIQ(
  230. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  231. };
  232. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  233. var self = this;
  234. $(contents).each(function (idx, content) {
  235. var name = $(content).attr('name');
  236. var mediaType = this.getAttribute('name');
  237. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  238. ssrcs.each(function () {
  239. var ssrc = this.getAttribute('ssrc');
  240. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  241. function () {
  242. var owner = this.getAttribute('owner');
  243. self.ssrcOwners[ssrc] = owner;
  244. }
  245. );
  246. });
  247. });
  248. };
  249. /**
  250. * Does accept incoming Jingle 'session-initiate' and should send
  251. * 'session-accept' in result.
  252. * @param jingleOffer jQuery selector pointing to the jingle element of
  253. * the offer IQ
  254. * @param success callback called when we accept incoming session successfully
  255. * and receive RESULT packet to 'session-accept' sent.
  256. * @param failure function(error) called if for any reason we fail to accept
  257. * the incoming offer. 'error' argument can be used to log some details
  258. * about the error.
  259. */
  260. JingleSessionPC.prototype.acceptOffer = function(jingleOffer,
  261. success, failure) {
  262. this.state = 'active';
  263. this.setOfferCycle(jingleOffer,
  264. function() {
  265. // setOfferCycle succeeded, now we have self.localSDP up to date
  266. // Let's send an answer !
  267. // FIXME we may not care about RESULT packet for session-accept
  268. // then we should either call 'success' here immediately or
  269. // modify sendSessionAccept method to do that
  270. this.sendSessionAccept(this.localSDP, success, failure);
  271. }.bind(this),
  272. failure);
  273. };
  274. /**
  275. * This is a setRemoteDescription/setLocalDescription cycle which starts at
  276. * converting Strophe Jingle IQ into remote offer SDP. Once converted
  277. * setRemoteDescription, createAnswer and setLocalDescription calls follow.
  278. * @param jingleOfferIq jQuery selector pointing to the jingle element of
  279. * the offer IQ
  280. * @param success callback called when sRD/sLD cycle finishes successfully.
  281. * @param failure callback called with an error object as an argument if we fail
  282. * at any point during setRD, createAnswer, setLD.
  283. */
  284. JingleSessionPC.prototype.setOfferCycle = function (jingleOfferIq,
  285. success,
  286. failure) {
  287. // Set Jingle offer as RD
  288. this.setOffer(jingleOfferIq,
  289. function() {
  290. // Set offer OK, now let's try create an answer
  291. this.createAnswer(function(answer) {
  292. // Create answer OK, set it as local SDP
  293. this.setLocalDescription(answer, success, failure);
  294. }.bind(this),
  295. failure);
  296. }.bind(this),
  297. failure);
  298. };
  299. /**
  300. * Sets remote offer on PeerConnection by converting given Jingle offer IQ into
  301. * SDP and setting it as remote description.
  302. * @param jingleOfferIq jQuery selector pointing to the jingle element of
  303. * the offer IQ
  304. * @param success callback called when setRemoteDescription on PeerConnection
  305. * succeeds
  306. * @param failure callback called with an error argument when
  307. * setRemoteDescription fails.
  308. */
  309. JingleSessionPC.prototype.setOffer = function (jingleOfferIq, success, failure) {
  310. this.remoteSDP = new SDP('');
  311. if (this.webrtcIceTcpDisable) {
  312. this.remoteSDP.removeTcpCandidates = true;
  313. }
  314. if (this.webrtcIceUdpDisable) {
  315. this.remoteSDP.removeUdpCandidates = true;
  316. }
  317. this.remoteSDP.fromJingle(jingleOfferIq);
  318. this.readSsrcInfo($(jingleOfferIq).find(">content"));
  319. var remotedesc
  320. = new RTCSessionDescription({type: 'offer', sdp: this.remoteSDP.raw});
  321. this.peerconnection.setRemoteDescription(remotedesc,
  322. function () {
  323. //logger.log('setRemoteDescription success');
  324. if (success) {
  325. success();
  326. }
  327. },
  328. function (e) {
  329. logger.error('setRemoteDescription error', e);
  330. if (failure)
  331. failure(e);
  332. JingleSessionPC.onJingleFatalError(this, e);
  333. }.bind(this)
  334. );
  335. };
  336. /**
  337. * This is a wrapper to PeerConnection.createAnswer in order to generate failure
  338. * event when error occurs. It also includes "media_constraints" if any are set
  339. * on this JingleSessionPC instance.
  340. * @param success callback called when PC.createAnswer succeeds, SDP will be
  341. * the first argument
  342. * @param failure callback called with error argument when setAnswer fails
  343. */
  344. JingleSessionPC.prototype.createAnswer = function (success, failure) {
  345. //logger.log('createAnswer');
  346. var self = this;
  347. this.peerconnection.createAnswer(
  348. function (answer) {
  349. var modifiedAnswer = new SDP(answer.sdp);
  350. JingleSessionPC._fixAnswerRFC4145Setup(
  351. /* offer */ self.remoteSDP,
  352. /* answer */ modifiedAnswer);
  353. answer.sdp = modifiedAnswer.raw;
  354. success(answer);
  355. },
  356. function (error) {
  357. logger.error("createAnswer failed", error);
  358. if (failure)
  359. failure(error);
  360. self.room.eventEmitter.emit(
  361. XMPPEvents.CONFERENCE_SETUP_FAILED, error);
  362. },
  363. this.media_constraints
  364. );
  365. };
  366. JingleSessionPC.prototype.setLocalDescription = function (sdp, success,
  367. failure) {
  368. var self = this;
  369. this.localSDP = new SDP(sdp.sdp);
  370. sdp.sdp = this.localSDP.raw;
  371. this.peerconnection.setLocalDescription(sdp,
  372. function () {
  373. if (success)
  374. success();
  375. },
  376. function (error) {
  377. logger.error('setLocalDescription failed', error);
  378. if (failure)
  379. failure(error);
  380. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  381. }
  382. );
  383. // Some checks for STUN and TURN candiates present in local SDP
  384. // Eventually could be removed as we don't really care
  385. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  386. for (var j = 0; j < cands.length; j++) {
  387. var cand = SDPUtil.parse_icecandidate(cands[j]);
  388. if (cand.type == 'srflx') {
  389. this.hadstuncandidate = true;
  390. } else if (cand.type == 'relay') {
  391. this.hadturncandidate = true;
  392. }
  393. }
  394. };
  395. /**
  396. * Modifies the values of the setup attributes (defined by
  397. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  398. * answer in order to overcome a delay of 1 second in the connection
  399. * establishment between Chrome and Videobridge.
  400. *
  401. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  402. * being prepared to respond
  403. * @param {SDP} answer - the SDP to modify
  404. * @private
  405. */
  406. JingleSessionPC._fixAnswerRFC4145Setup = function (offer, answer) {
  407. if (!RTCBrowserType.isChrome()) {
  408. // It looks like Firefox doesn't agree with the fix (at least in its
  409. // current implementation) because it effectively remains active even
  410. // after we tell it to become passive. Apart from Firefox which I tested
  411. // after the fix was deployed, I tested Chrome only. In order to prevent
  412. // issues with other browsers, limit the fix to Chrome for the time
  413. // being.
  414. return;
  415. }
  416. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  417. // answerer (as orchestrated by Jicofo). In accord with
  418. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  419. // are ICE FULL agents, Videobridge will take on the controlling role and
  420. // WebRTC will take on the controlled role. In accord with
  421. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  422. // setup attribute value of setup:actpass and WebRTC will be allowed to
  423. // choose either the setup attribute value of setup:active or
  424. // setup:passive. Chrome will by default choose setup:active because it is
  425. // RECOMMENDED by the respective RFC since setup:passive adds additional
  426. // latency. The case of setup:active allows WebRTC to send a DTLS
  427. // ClientHello as soon as an ICE connectivity check of its succeeds.
  428. // Unfortunately, Videobridge will be unable to respond immediately because
  429. // may not have WebRTC's answer or may have not completed the ICE
  430. // connectivity establishment. Even more unfortunate is that in the
  431. // described scenario Chrome's DTLS implementation will insist on
  432. // retransmitting its ClientHello after a second (the time is in accord
  433. // with the respective RFC) and will thus cause the whole connection
  434. // establishment to exceed at least 1 second. To work around Chrome's
  435. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  436. // default choice of setup:active to setup:passive.
  437. if (offer && answer
  438. && offer.media && answer.media
  439. && offer.media.length == answer.media.length) {
  440. answer.media.forEach(function (a, i) {
  441. if (SDPUtil.find_line(
  442. offer.media[i],
  443. 'a=setup:actpass',
  444. offer.session)) {
  445. answer.media[i]
  446. = a.replace(/a=setup:active/g, 'a=setup:passive');
  447. }
  448. });
  449. answer.raw = answer.session + answer.media.join('');
  450. }
  451. };
  452. /**
  453. * Although it states "replace transport" it does accept full Jingle offer
  454. * which should contain new ICE transport details.
  455. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  456. * transport info.
  457. * @param success callback called when we succeed to accept new offer.
  458. * @param failure function(error) called when we fail to accept new offer.
  459. */
  460. JingleSessionPC.prototype.replaceTransport = function (jingleOfferElem,
  461. success,
  462. failure) {
  463. // We need to first set an offer without the 'data' section to have the SCTP
  464. // stack cleaned up. After that the original offer is set to have the SCTP
  465. // connection established with the new bridge.
  466. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING);
  467. var originalOffer = jingleOfferElem.clone();
  468. jingleOfferElem.find(">content[name='data']").remove();
  469. var self = this;
  470. // First set an offer without the 'data' section
  471. this.setOfferCycle(
  472. jingleOfferElem,
  473. function() {
  474. // Now set the original offer(with the 'data' section)
  475. self.setOfferCycle(originalOffer,
  476. function () {
  477. // Set local description OK, now localSDP up to date
  478. self.sendTransportAccept(self.localSDP, success, failure);
  479. },
  480. failure);
  481. },
  482. failure
  483. );
  484. };
  485. /**
  486. * Sends Jingle 'session-accept' message.
  487. * @param localSDP the 'SDP' object with local session description
  488. * @param success callback called when we recive 'RESULT' packet for
  489. * 'session-accept'
  490. * @param failure function(error) called when we receive an error response or
  491. * when the request has timed out.
  492. */
  493. JingleSessionPC.prototype.sendSessionAccept = function (localSDP,
  494. success, failure) {
  495. var accept = $iq({to: this.peerjid,
  496. type: 'set'})
  497. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  498. action: 'session-accept',
  499. initiator: this.initiator,
  500. responder: this.responder,
  501. sid: this.sid });
  502. if (this.webrtcIceTcpDisable) {
  503. localSDP.removeTcpCandidates = true;
  504. }
  505. if (this.webrtcIceUdpDisable) {
  506. localSDP.removeUdpCandidates = true;
  507. }
  508. localSDP.toJingle(
  509. accept,
  510. this.initiator == this.me ? 'initiator' : 'responder',
  511. null);
  512. this.fixJingle(accept);
  513. // Calling tree() to print something useful
  514. accept = accept.tree();
  515. logger.info("Sending session-accept", accept);
  516. this.connection.sendIQ(accept,
  517. success,
  518. this.newJingleErrorHandler(accept, failure),
  519. IQ_TIMEOUT);
  520. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  521. // fingerprint and setup) ASAP in order to start the connection
  522. // establishment.
  523. this.connection.flush();
  524. };
  525. /**
  526. * Sends Jingle 'transport-accept' message which is a response to
  527. * 'transport-replace'.
  528. * @param localSDP the 'SDP' object with local session description
  529. * @param success callback called when we receive 'RESULT' packet for
  530. * 'transport-replace'
  531. * @param failure function(error) called when we receive an error response or
  532. * when the request has timed out.
  533. */
  534. JingleSessionPC.prototype.sendTransportAccept = function(localSDP, success,
  535. failure) {
  536. var self = this;
  537. var tAccept = $iq({to: this.peerjid, type: 'set'})
  538. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  539. action: 'transport-accept',
  540. initiator: this.initiator,
  541. sid: this.sid});
  542. localSDP.media.forEach(function(medialines, idx){
  543. var mline = SDPUtil.parse_mline(medialines.split('\r\n')[0]);
  544. tAccept.c('content',
  545. { creator: self.initiator == self.me ? 'initiator' : 'responder',
  546. name: mline.media
  547. }
  548. );
  549. localSDP.transportToJingle(idx, tAccept);
  550. tAccept.up();
  551. });
  552. // Calling tree() to print something useful to the logger
  553. tAccept = tAccept.tree();
  554. console.info("Sending transport-accept: ", tAccept);
  555. self.connection.sendIQ(tAccept,
  556. success,
  557. self.newJingleErrorHandler(tAccept, failure),
  558. IQ_TIMEOUT);
  559. };
  560. /**
  561. * Sends Jingle 'transport-reject' message which is a response to
  562. * 'transport-replace'.
  563. * @param success callback called when we receive 'RESULT' packet for
  564. * 'transport-replace'
  565. * @param failure function(error) called when we receive an error response or
  566. * when the request has timed out.
  567. */
  568. JingleSessionPC.prototype.sendTransportReject = function(success, failure) {
  569. // Send 'transport-reject', so that the focus will
  570. // know that we've failed
  571. var tReject = $iq({to: this.peerjid, type: 'set'})
  572. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  573. action: 'transport-reject',
  574. initiator: this.initiator,
  575. sid: this.sid});
  576. tReject = tReject.tree();
  577. logger.info("Sending 'transport-reject", tReject);
  578. this.connection.sendIQ(tReject,
  579. success,
  580. this.newJingleErrorHandler(tReject, failure),
  581. IQ_TIMEOUT);
  582. };
  583. JingleSessionPC.prototype.terminate = function (reason, text,
  584. success, failure) {
  585. var term = $iq({to: this.peerjid,
  586. type: 'set'})
  587. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  588. action: 'session-terminate',
  589. initiator: this.initiator,
  590. sid: this.sid})
  591. .c('reason')
  592. .c(reason || 'success');
  593. if (text) {
  594. term.up().c('text').t(text);
  595. }
  596. // Calling tree() to print something useful
  597. term = term.tree();
  598. logger.info("Sending session-terminate", term);
  599. this.connection.sendIQ(
  600. term, success, this.newJingleErrorHandler(term, failure), IQ_TIMEOUT);
  601. // this should result in 'onTerminated' being called by strope.jingle.js
  602. this.connection.jingle.terminate(this.sid);
  603. };
  604. JingleSessionPC.prototype.onTerminated = function (reasonCondition,
  605. reasonText) {
  606. this.state = 'ended';
  607. // Do something with reason and reasonCondition when we start to care
  608. //this.reasonCondition = reasonCondition;
  609. //this.reasonText = reasonText;
  610. logger.info("Session terminated", this, reasonCondition, reasonText);
  611. this.close();
  612. };
  613. /**
  614. * Handles a Jingle source-add message for this Jingle session.
  615. * @param elem An array of Jingle "content" elements.
  616. */
  617. JingleSessionPC.prototype.addSource = function (elem) {
  618. var self = this;
  619. // FIXME: dirty waiting
  620. if (!this.peerconnection.localDescription)
  621. {
  622. logger.warn("addSource - localDescription not ready yet")
  623. setTimeout(function()
  624. {
  625. self.addSource(elem);
  626. },
  627. 200
  628. );
  629. return;
  630. }
  631. logger.log('addssrc', new Date().getTime());
  632. logger.log('ice', this.peerconnection.iceConnectionState);
  633. this.readSsrcInfo(elem);
  634. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  635. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  636. $(elem).each(function (idx, content) {
  637. var name = $(content).attr('name');
  638. var lines = '';
  639. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  640. var semantics = this.getAttribute('semantics');
  641. var ssrcs = $(this).find('>source').map(function () {
  642. return this.getAttribute('ssrc');
  643. }).get();
  644. if (ssrcs.length) {
  645. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  646. }
  647. });
  648. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  649. tmp.each(function () {
  650. var ssrc = $(this).attr('ssrc');
  651. if(mySdp.containsSSRC(ssrc)){
  652. /**
  653. * This happens when multiple participants change their streams at the same time and
  654. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  655. * addssrc are scheduled for update IQ. See
  656. */
  657. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  658. return;
  659. }
  660. if (sdp.containsSSRC(ssrc)) {
  661. logger.warn("Source-add request for existing SSRC: " + ssrc);
  662. return;
  663. }
  664. $(this).find('>parameter').each(function () {
  665. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  666. if ($(this).attr('value') && $(this).attr('value').length)
  667. lines += ':' + $(this).attr('value');
  668. lines += '\r\n';
  669. });
  670. });
  671. sdp.media.forEach(function(media, idx) {
  672. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  673. return;
  674. sdp.media[idx] += lines;
  675. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  676. self.addssrc[idx] += lines;
  677. });
  678. sdp.raw = sdp.session + sdp.media.join('');
  679. });
  680. this.modifySourcesQueue.push(function() {
  681. // When a source is added and if this is FF, a new channel is allocated
  682. // for receiving the added source. We need to diffuse the SSRC of this
  683. // new recvonly channel to the rest of the peers.
  684. logger.log('modify sources done');
  685. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  686. logger.log("SDPs", mySdp, newSdp);
  687. self.notifyMySSRCUpdate(mySdp, newSdp);
  688. });
  689. };
  690. /**
  691. * Handles a Jingle source-remove message for this Jingle session.
  692. * @param elem An array of Jingle "content" elements.
  693. */
  694. JingleSessionPC.prototype.removeSource = function (elem) {
  695. var self = this;
  696. // FIXME: dirty waiting
  697. if (!this.peerconnection.localDescription) {
  698. logger.warn("removeSource - localDescription not ready yet");
  699. setTimeout(function() {
  700. self.removeSource(elem);
  701. },
  702. 200
  703. );
  704. return;
  705. }
  706. logger.log('removessrc', new Date().getTime());
  707. logger.log('ice', this.peerconnection.iceConnectionState);
  708. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  709. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  710. $(elem).each(function (idx, content) {
  711. var name = $(content).attr('name');
  712. var lines = '';
  713. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  714. var semantics = this.getAttribute('semantics');
  715. var ssrcs = $(this).find('>source').map(function () {
  716. return this.getAttribute('ssrc');
  717. }).get();
  718. if (ssrcs.length) {
  719. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  720. }
  721. });
  722. var ssrcs = [];
  723. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  724. tmp.each(function () {
  725. var ssrc = $(this).attr('ssrc');
  726. // This should never happen, but can be useful for bug detection
  727. if(mySdp.containsSSRC(ssrc)){
  728. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  729. return;
  730. }
  731. ssrcs.push(ssrc);
  732. });
  733. sdp.media.forEach(function(media, idx) {
  734. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  735. return;
  736. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  737. ssrcs.forEach(function(ssrc) {
  738. var ssrcLines = SDPUtil.find_lines(media, 'a=ssrc:' + ssrc);
  739. if (ssrcLines.length)
  740. self.removessrc[idx] += ssrcLines.join("\r\n")+"\r\n";
  741. // Clear any pending 'source-add' for this SSRC
  742. if (self.addssrc[idx]) {
  743. self.addssrc[idx]
  744. = self.addssrc[idx].replace(
  745. new RegExp('^a=ssrc:'+ssrc+' .*\r\n', 'gm'), '');
  746. }
  747. });
  748. self.removessrc[idx] += lines;
  749. });
  750. sdp.raw = sdp.session + sdp.media.join('');
  751. });
  752. this.modifySourcesQueue.push(function() {
  753. // When a source is removed and if this is FF, the recvonly channel that
  754. // receives the remote stream is deactivated . We need to diffuse the
  755. // recvonly SSRC removal to the rest of the peers.
  756. logger.log('modify sources done');
  757. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  758. logger.log("SDPs", mySdp, newSdp);
  759. self.notifyMySSRCUpdate(mySdp, newSdp);
  760. });
  761. };
  762. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  763. var self = this;
  764. if (this.peerconnection.signalingState == 'closed') return;
  765. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  766. || this.modifyingLocalStreams)){
  767. // There is nothing to do since scheduled job might have been
  768. // executed by another succeeding call
  769. if(successCallback){
  770. successCallback();
  771. }
  772. queueCallback();
  773. return;
  774. }
  775. // Reset switch streams flags
  776. this.modifyingLocalStreams = false;
  777. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  778. // add sources
  779. this.addssrc.forEach(function(lines, idx) {
  780. sdp.media[idx] += lines;
  781. });
  782. this.addssrc = [];
  783. // remove sources
  784. this.removessrc.forEach(function(lines, idx) {
  785. lines = lines.split('\r\n');
  786. lines.pop(); // remove empty last element;
  787. lines.forEach(function(line) {
  788. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  789. });
  790. });
  791. this.removessrc = [];
  792. sdp.raw = sdp.session + sdp.media.join('');
  793. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  794. function() {
  795. if(self.signalingState == 'closed') {
  796. logger.error("createAnswer attempt on closed state");
  797. queueCallback("createAnswer attempt on closed state");
  798. return;
  799. }
  800. self.peerconnection.createAnswer(
  801. function(modifiedAnswer) {
  802. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  803. if (self.pendingop !== null) {
  804. var sdp = new SDP(modifiedAnswer.sdp);
  805. if (sdp.media.length > 1) {
  806. switch(self.pendingop) {
  807. case 'mute':
  808. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  809. break;
  810. case 'unmute':
  811. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  812. break;
  813. }
  814. sdp.raw = sdp.session + sdp.media.join('');
  815. modifiedAnswer.sdp = sdp.raw;
  816. }
  817. self.pendingop = null;
  818. }
  819. // FIXME: pushing down an answer while ice connection state
  820. // is still checking is bad...
  821. //logger.log(self.peerconnection.iceConnectionState);
  822. // trying to work around another chrome bug
  823. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  824. self.peerconnection.setLocalDescription(modifiedAnswer,
  825. function() {
  826. if(successCallback){
  827. successCallback();
  828. }
  829. queueCallback();
  830. },
  831. function(error) {
  832. logger.error('modified setLocalDescription failed', error);
  833. queueCallback(error);
  834. }
  835. );
  836. },
  837. function(error) {
  838. logger.error('modified answer failed', error);
  839. queueCallback(error);
  840. }
  841. );
  842. },
  843. function(error) {
  844. logger.error('modify failed', error);
  845. queueCallback(error);
  846. }
  847. );
  848. };
  849. /**
  850. * Adds stream.
  851. * @param stream new stream that will be added.
  852. * @param success_callback callback executed after successful stream addition.
  853. * @param ssrcInfo object with information about the SSRCs associated with the
  854. * stream.
  855. * @param dontModifySources {boolean} if true _modifySources won't be called.
  856. * Used for streams added before the call start.
  857. * @throws error if modifySourcesQueue is paused.
  858. */
  859. JingleSessionPC.prototype.addStream = function (stream, callback, ssrcInfo,
  860. dontModifySources) {
  861. // Remember SDP to figure out added/removed SSRCs
  862. var oldSdp = null;
  863. if(this.peerconnection && this.peerconnection.localDescription) {
  864. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  865. }
  866. // Conference is not active
  867. if(!oldSdp || !this.peerconnection || dontModifySources) {
  868. //when adding muted stream we have to pass the ssrcInfo but we don't
  869. //have a stream
  870. if(this.peerconnection && (stream || ssrcInfo))
  871. this.peerconnection.addStream(stream, ssrcInfo);
  872. if(ssrcInfo) {
  873. //available only on video unmute or when adding muted stream
  874. this.modifiedSSRCs[ssrcInfo.type] =
  875. this.modifiedSSRCs[ssrcInfo.type] || [];
  876. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  877. }
  878. callback();
  879. return;
  880. }
  881. if(this.modifySourcesQueue.paused) {
  882. // if this.modifySourcesQueue.paused, modifySources won't be called and
  883. // the SDPs won't be updated. Basically removeStream will fail. That's
  884. // why we are throwing the error to inform the callers of the method.
  885. throw new Error("modifySourcesQueue paused");
  886. return;
  887. }
  888. if(stream || ssrcInfo)
  889. this.peerconnection.addStream(stream, ssrcInfo);
  890. this.modifyingLocalStreams = true;
  891. var self = this;
  892. this.modifySourcesQueue.push(function() {
  893. logger.log('modify sources done');
  894. if(ssrcInfo) {
  895. //available only on video unmute or when adding muted stream
  896. self.modifiedSSRCs[ssrcInfo.type] =
  897. self.modifiedSSRCs[ssrcInfo.type] || [];
  898. self.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  899. }
  900. callback();
  901. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  902. logger.log("SDPs", oldSdp, newSdp);
  903. self.notifyMySSRCUpdate(oldSdp, newSdp);
  904. });
  905. }
  906. /**
  907. * Generate ssrc info object for a stream with the following properties:
  908. * - ssrcs - Array of the ssrcs associated with the stream.
  909. * - groups - Array of the groups associated with the stream.
  910. */
  911. JingleSessionPC.prototype.generateNewStreamSSRCInfo = function () {
  912. return this.peerconnection.generateNewStreamSSRCInfo();
  913. };
  914. /**
  915. * Remove streams.
  916. * @param stream stream that will be removed.
  917. * @param success_callback callback executed after successful stream addition.
  918. * @param ssrcInfo object with information about the SSRCs associated with the
  919. * stream.
  920. * @throws error if modifySourcesQueue is paused.
  921. */
  922. JingleSessionPC.prototype.removeStream = function (stream, callback, ssrcInfo) {
  923. // Conference is not active
  924. if(!this.peerconnection) {
  925. callback();
  926. return;
  927. }
  928. // Remember SDP to figure out added/removed SSRCs
  929. var oldSdp = null;
  930. if(this.peerconnection.localDescription) {
  931. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  932. }
  933. if(!oldSdp) {
  934. callback();
  935. return;
  936. }
  937. if (RTCBrowserType.getBrowserType() ===
  938. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  939. if(!stream) {//There is nothing to be changed
  940. callback();
  941. return;
  942. }
  943. var sender = null;
  944. // On Firefox we don't replace MediaStreams as this messes up the
  945. // m-lines (which can't be removed in Plan Unified) and brings a lot
  946. // of complications. Instead, we use the RTPSender and remove just
  947. // the track.
  948. var track = null;
  949. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  950. track = stream.getAudioTracks()[0];
  951. } else if(stream.getVideoTracks() && stream.getVideoTracks().length) {
  952. track = stream.getVideoTracks()[0];
  953. }
  954. if(!track) {
  955. logger.log("Cannot remove tracks: no tracks.");
  956. callback();
  957. return;
  958. }
  959. if(this.modifySourcesQueue.paused) {
  960. // if this.modifySourcesQueue.paused, modifySources won't be called and
  961. // the SDPs won't be updated. Basically removeStream will fail. That's
  962. // why we are throwing the error to inform the callers of the method.
  963. throw new Error("modifySourcesQueue paused");
  964. return;
  965. }
  966. // Find the right sender (for audio or video)
  967. this.peerconnection.peerconnection.getSenders().some(function (s) {
  968. if (s.track === track) {
  969. sender = s;
  970. return true;
  971. }
  972. });
  973. if (sender) {
  974. this.peerconnection.peerconnection.removeTrack(sender);
  975. } else {
  976. logger.log("Cannot remove tracks: no RTPSender.");
  977. }
  978. } else if(this.modifySourcesQueue.paused) {
  979. // if this.modifySourcesQueue.paused, modifySources won't be called and
  980. // the SDPs won't be updated. Basically removeStream will fail. That's
  981. // why we are throwing the error to inform the callers of the method.
  982. throw new Error("modifySourcesQueue paused");
  983. return;
  984. } else if(stream)
  985. this.peerconnection.removeStream(stream, false, ssrcInfo);
  986. // else
  987. // NOTE: If there is no stream and the browser is not FF we still need to do
  988. // some transformation in order to send remove-source for the muted
  989. // streams. That's why we aren't calling return here.
  990. this.modifyingLocalStreams = true;
  991. var self = this;
  992. this.modifySourcesQueue.push(function() {
  993. logger.log('modify sources done');
  994. callback();
  995. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  996. if(ssrcInfo) {
  997. self.modifiedSSRCs[ssrcInfo.type] =
  998. self.modifiedSSRCs[ssrcInfo.type] || [];
  999. self.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1000. }
  1001. logger.log("SDPs", oldSdp, newSdp);
  1002. self.notifyMySSRCUpdate(oldSdp, newSdp);
  1003. });
  1004. }
  1005. /**
  1006. * Figures out added/removed ssrcs and send update IQs.
  1007. * @param old_sdp SDP object for old description.
  1008. * @param new_sdp SDP object for new description.
  1009. */
  1010. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  1011. if (!(this.peerconnection.signalingState == 'stable' &&
  1012. this.peerconnection.iceConnectionState == 'connected')){
  1013. logger.log("Too early to send updates");
  1014. return;
  1015. }
  1016. // send source-remove IQ.
  1017. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  1018. var remove = $iq({to: this.peerjid, type: 'set'})
  1019. .c('jingle', {
  1020. xmlns: 'urn:xmpp:jingle:1',
  1021. action: 'source-remove',
  1022. initiator: this.initiator,
  1023. sid: this.sid
  1024. }
  1025. );
  1026. sdpDiffer.toJingle(remove);
  1027. var removed = this.fixJingle(remove);
  1028. if (removed && remove) {
  1029. logger.info("Sending source-remove", remove.tree());
  1030. this.connection.sendIQ(
  1031. remove, null, this.newJingleErrorHandler(remove), IQ_TIMEOUT);
  1032. } else {
  1033. logger.log('removal not necessary');
  1034. }
  1035. // send source-add IQ.
  1036. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  1037. var add = $iq({to: this.peerjid, type: 'set'})
  1038. .c('jingle', {
  1039. xmlns: 'urn:xmpp:jingle:1',
  1040. action: 'source-add',
  1041. initiator: this.initiator,
  1042. sid: this.sid
  1043. }
  1044. );
  1045. sdpDiffer.toJingle(add);
  1046. var added = this.fixJingle(add);
  1047. if (added && add) {
  1048. logger.info("Sending source-add", add.tree());
  1049. this.connection.sendIQ(
  1050. add, null, this.newJingleErrorHandler(add), IQ_TIMEOUT);
  1051. } else {
  1052. logger.log('addition not necessary');
  1053. }
  1054. };
  1055. /**
  1056. * Method returns function(errorResponse) which is a callback to be passed to
  1057. * Strophe connection.sendIQ method. An 'error' structure is created that is
  1058. * passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1059. * structure is as follows:
  1060. * {
  1061. * code: {XMPP error response code}
  1062. * reason: {the name of XMPP error reason element or 'timeout' if the request
  1063. * has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1064. * source: {request.tree() that provides original request}
  1065. * session: {JingleSessionPC instance on which the error occurred}
  1066. * }
  1067. * @param request Strophe IQ instance which is the request to be dumped into
  1068. * the error structure
  1069. * @param failureCb function(error) called when error response was returned or
  1070. * when a timeout has occurred.
  1071. * @returns {function(this:JingleSessionPC)}
  1072. */
  1073. JingleSessionPC.prototype.newJingleErrorHandler = function(request, failureCb) {
  1074. return function (errResponse) {
  1075. var error = { };
  1076. // Get XMPP error code and condition(reason)
  1077. var errorElSel = $(errResponse).find('error');
  1078. if (errorElSel.length) {
  1079. error.code = errorElSel.attr('code');
  1080. var errorReasonSel = $(errResponse).find('error :first');
  1081. if (errorReasonSel.length)
  1082. error.reason = errorReasonSel[0].tagName;
  1083. }
  1084. if (!errResponse) {
  1085. error.reason = 'timeout';
  1086. }
  1087. error.source = null;
  1088. if (request && "function" == typeof request.tree) {
  1089. error.source = request.tree();
  1090. }
  1091. error.session = this;
  1092. logger.error("Jingle error", error);
  1093. if (failureCb) {
  1094. failureCb(error);
  1095. }
  1096. this.room.eventEmitter.emit(XMPPEvents.JINGLE_ERROR, error);
  1097. }.bind(this);
  1098. };
  1099. JingleSessionPC.onJingleFatalError = function (session, error)
  1100. {
  1101. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  1102. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1103. };
  1104. /**
  1105. * Called when new remote MediaStream is added to the PeerConnection.
  1106. * @param stream the WebRTC MediaStream for remote participant
  1107. */
  1108. JingleSessionPC.prototype.remoteStreamAdded = function (stream) {
  1109. var self = this;
  1110. if (!RTC.isUserStream(stream)) {
  1111. logger.info(
  1112. "Ignored remote 'stream added' event for non-user stream", stream);
  1113. return;
  1114. }
  1115. // Bind 'addtrack'/'removetrack' event handlers
  1116. if (RTCBrowserType.isChrome()) {
  1117. stream.onaddtrack = function (event) {
  1118. self.remoteTrackAdded(event.target, event.track);
  1119. };
  1120. stream.onremovetrack = function (event) {
  1121. self.remoteTrackRemoved(event.target, event.track);
  1122. };
  1123. }
  1124. // Call remoteTrackAdded for each track in the stream
  1125. stream.getAudioTracks().forEach(function (track) {
  1126. self.remoteTrackAdded(stream, track);
  1127. });
  1128. stream.getVideoTracks().forEach(function (track) {
  1129. self.remoteTrackAdded(stream, track);
  1130. });
  1131. };
  1132. /**
  1133. * Called on "track added" and "stream added" PeerConnection events(cause we
  1134. * handle streams on per track basis). Does find the owner and the SSRC for
  1135. * the track and passes that to ChatRoom for further processing.
  1136. * @param stream WebRTC MediaStream instance which is the parent of the track
  1137. * @param track the WebRTC MediaStreamTrack added for remote participant
  1138. */
  1139. JingleSessionPC.prototype.remoteTrackAdded = function (stream, track) {
  1140. logger.info("Remote track added", stream, track);
  1141. var streamId = RTC.getStreamID(stream);
  1142. var mediaType = track.kind;
  1143. // This is our event structure which will be passed by the ChatRoom as
  1144. // XMPPEvents.REMOTE_TRACK_ADDED data
  1145. var jitsiTrackAddedEvent = {
  1146. stream: stream,
  1147. track: track,
  1148. mediaType: track.kind, /* 'audio' or 'video' */
  1149. owner: undefined, /* to be determined below */
  1150. muted: null /* will be set in the ChatRoom */
  1151. };
  1152. // look up an associated JID for a stream id
  1153. if (!mediaType) {
  1154. logger.error("MediaType undefined", track);
  1155. return;
  1156. }
  1157. var remoteSDP = new SDP(this.peerconnection.remoteDescription.sdp);
  1158. var medialines = remoteSDP.media.filter(function (mediaLines){
  1159. return mediaLines.startsWith("m=" + mediaType);
  1160. });
  1161. if (!medialines.length) {
  1162. logger.error("No media for type " + mediaType + " found in remote SDP");
  1163. return;
  1164. }
  1165. var ssrclines = SDPUtil.find_lines(medialines[0], 'a=ssrc:');
  1166. ssrclines = ssrclines.filter(function (line) {
  1167. if (RTCBrowserType.isTemasysPluginUsed()) {
  1168. return ((line.indexOf('mslabel:' + streamId) !== -1));
  1169. } else {
  1170. return ((line.indexOf('msid:' + streamId) !== -1));
  1171. }
  1172. });
  1173. var thessrc;
  1174. if (ssrclines.length) {
  1175. thessrc = ssrclines[0].substring(7).split(' ')[0];
  1176. if (!this.ssrcOwners[thessrc]) {
  1177. logger.error("No SSRC owner known for: " + thessrc);
  1178. return;
  1179. }
  1180. jitsiTrackAddedEvent.owner = this.ssrcOwners[thessrc];
  1181. logger.log('associated jid', this.ssrcOwners[thessrc], thessrc);
  1182. } else {
  1183. logger.error("No SSRC lines for ", streamId);
  1184. return;
  1185. }
  1186. jitsiTrackAddedEvent.ssrc = thessrc;
  1187. this.room.remoteTrackAdded(jitsiTrackAddedEvent);
  1188. };
  1189. /**
  1190. * Handles remote stream removal.
  1191. * @param stream the WebRTC MediaStream object which is being removed from the
  1192. * PeerConnection
  1193. */
  1194. JingleSessionPC.prototype.remoteStreamRemoved = function (stream) {
  1195. var self = this;
  1196. if (!RTC.isUserStream(stream)) {
  1197. logger.info(
  1198. "Ignored remote 'stream removed' event for non-user stream", stream);
  1199. return;
  1200. }
  1201. // Call remoteTrackRemoved for each track in the stream
  1202. stream.getVideoTracks().forEach(function(track){
  1203. self.remoteTrackRemoved(stream, track);
  1204. });
  1205. stream.getAudioTracks().forEach(function(track) {
  1206. self.remoteTrackRemoved(stream, track);
  1207. });
  1208. };
  1209. /**
  1210. * Handles remote media track removal.
  1211. * @param stream WebRTC MediaStream instance which is the parent of the track
  1212. * @param track the WebRTC MediaStreamTrack which has been removed from
  1213. * the PeerConnection.
  1214. */
  1215. JingleSessionPC.prototype.remoteTrackRemoved = function (stream, track) {
  1216. logger.info("Remote track removed", stream, track);
  1217. var streamId = RTC.getStreamID(stream);
  1218. var trackId = track && track.id;
  1219. if (!streamId) {
  1220. logger.error("No stream ID for", stream);
  1221. } else if (!trackId) {
  1222. logger.error("No track ID for", track);
  1223. } else {
  1224. this.room.eventEmitter.emit(
  1225. XMPPEvents.REMOTE_TRACK_REMOVED, streamId, trackId);
  1226. }
  1227. };
  1228. /**
  1229. * Returns the ice connection state for the peer connection.
  1230. * @returns the ice connection state for the peer connection.
  1231. */
  1232. JingleSessionPC.prototype.getIceConnectionState = function () {
  1233. return this.peerconnection.iceConnectionState;
  1234. };
  1235. /**
  1236. * Closes the peerconnection.
  1237. */
  1238. JingleSessionPC.prototype.close = function () {
  1239. this.closed = true;
  1240. this.peerconnection && this.peerconnection.close();
  1241. };
  1242. /**
  1243. * Fixes the outgoing jingle packets by removing the nodes related to the
  1244. * muted/unmuted streams, handles removing of muted stream, etc.
  1245. * @param jingle the jingle packet that is going to be sent
  1246. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1247. */
  1248. JingleSessionPC.prototype.fixJingle = function(jingle) {
  1249. var action = $(jingle.nodeTree).find("jingle").attr("action");
  1250. switch (action) {
  1251. case "source-add":
  1252. case "session-accept":
  1253. this.fixSourceAddJingle(jingle);
  1254. break;
  1255. case "source-remove":
  1256. this.fixSourceRemoveJingle(jingle);
  1257. break;
  1258. default:
  1259. logger.error("Unknown jingle action!");
  1260. return false;
  1261. }
  1262. var sources = $(jingle.tree()).find(">jingle>content>description>source");
  1263. return sources && sources.length > 0;
  1264. };
  1265. /**
  1266. * Fixes the outgoing jingle packets with action source-add by removing the
  1267. * nodes related to the unmuted streams
  1268. * @param jingle the jingle packet that is going to be sent
  1269. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1270. */
  1271. JingleSessionPC.prototype.fixSourceAddJingle = function (jingle) {
  1272. var ssrcs = this.modifiedSSRCs["unmute"];
  1273. this.modifiedSSRCs["unmute"] = [];
  1274. if(ssrcs && ssrcs.length) {
  1275. ssrcs.forEach(function (ssrcObj) {
  1276. var desc = $(jingle.tree()).find(">jingle>content[name=\"" +
  1277. ssrcObj.mtype + "\"]>description");
  1278. if(!desc || !desc.length)
  1279. return;
  1280. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1281. var sourceNode = desc.find(">source[ssrc=\"" +
  1282. ssrc + "\"]");
  1283. sourceNode.remove();
  1284. });
  1285. ssrcObj.ssrc.groups.forEach(function (group) {
  1286. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1287. group.group.semantics + "\"]:has(source[ssrc=\"" +
  1288. group.primarySSRC +
  1289. "\"])");
  1290. groupNode.remove();
  1291. });
  1292. });
  1293. }
  1294. ssrcs = this.modifiedSSRCs["addMuted"];
  1295. this.modifiedSSRCs["addMuted"] = [];
  1296. if(ssrcs && ssrcs.length) {
  1297. ssrcs.forEach(function (ssrcObj) {
  1298. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  1299. var cname = Math.random().toString(36).substring(2);
  1300. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1301. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  1302. sourceNode.remove();
  1303. var sourceXML = "<source " +
  1304. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  1305. ssrc + "\">" +
  1306. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  1307. " value=\"" + ssrcObj.msid + "\" name=\"msid\"/>" +
  1308. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  1309. " value=\"" + cname + "\" name=\"cname\" />" + "</source>";
  1310. desc.append(sourceXML);
  1311. });
  1312. ssrcObj.ssrc.groups.forEach(function (group) {
  1313. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1314. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1315. "\"])");
  1316. groupNode.remove();
  1317. desc.append("<ssrc-group semantics=\"" +
  1318. group.group.semantics +
  1319. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  1320. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  1321. "</ssrc-group>");
  1322. });
  1323. });
  1324. }
  1325. };
  1326. /**
  1327. * Fixes the outgoing jingle packets with action source-remove by removing the
  1328. * nodes related to the muted streams, handles removing of muted stream
  1329. * @param jingle the jingle packet that is going to be sent
  1330. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1331. */
  1332. JingleSessionPC.prototype.fixSourceRemoveJingle = function(jingle) {
  1333. var ssrcs = this.modifiedSSRCs["mute"];
  1334. this.modifiedSSRCs["mute"] = [];
  1335. if(ssrcs && ssrcs.length)
  1336. ssrcs.forEach(function (ssrcObj) {
  1337. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1338. var sourceNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  1339. ssrcObj.mtype + "\"]>description>source[ssrc=\"" +
  1340. ssrc + "\"]");
  1341. sourceNode.remove();
  1342. });
  1343. ssrcObj.ssrc.groups.forEach(function (group) {
  1344. var groupNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  1345. ssrcObj.mtype + "\"]>description>ssrc-group[semantics=\"" +
  1346. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1347. "\"])");
  1348. groupNode.remove();
  1349. });
  1350. });
  1351. ssrcs = this.modifiedSSRCs["remove"];
  1352. this.modifiedSSRCs["remove"] = [];
  1353. if(ssrcs && ssrcs.length)
  1354. ssrcs.forEach(function (ssrcObj) {
  1355. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  1356. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1357. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  1358. if(!sourceNode || !sourceNode.length) {
  1359. //Maybe we have to include cname, msid, etc here?
  1360. desc.append("<source " +
  1361. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  1362. ssrc + "\"></source>");
  1363. }
  1364. });
  1365. ssrcObj.ssrc.groups.forEach(function (group) {
  1366. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1367. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1368. "\"])");
  1369. if(!groupNode || !groupNode.length) {
  1370. desc.append("<ssrc-group semantics=\"" +
  1371. group.group.semantics +
  1372. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  1373. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  1374. "</ssrc-group>");
  1375. }
  1376. });
  1377. });
  1378. };
  1379. /**
  1380. * Returns the description node related to the passed content type. If the node
  1381. * doesn't exists it will be created.
  1382. * @param jingle - the jingle packet
  1383. * @param mtype - the content type(audio, video, etc.)
  1384. */
  1385. function createDescriptionNode(jingle, mtype) {
  1386. var content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1387. mtype + "\"]");
  1388. if(!content || !content.length) {
  1389. $(jingle.tree()).find(">jingle").append(
  1390. "<content name=\"" + mtype + "\"></content>");
  1391. content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1392. mtype + "\"]");
  1393. }
  1394. var desc = content.find(">description");
  1395. if(!desc || !desc.length) {
  1396. content.append("<description " +
  1397. "xmlns=\"urn:xmpp:jingle:apps:rtp:1\" media=\"" +
  1398. mtype + "\"></description>");
  1399. desc = content.find(">description");
  1400. }
  1401. return desc;
  1402. }
  1403. module.exports = JingleSessionPC;