modified lib-jitsi-meet dev repo
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 56KB

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