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

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