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

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