Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JingleSessionPC.js 54KB

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