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

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