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 59KB

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