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

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