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

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