您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 55KB

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