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

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