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

JingleSessionPC.js 55KB

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