選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JingleSessionPC.js 63KB

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