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 62KB

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