Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JingleSessionPC.js 57KB

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