You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 60KB

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