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.

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