Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JingleSessionPC.js 61KB

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