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

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