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

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