Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JingleSessionPC.js 54KB

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