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

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