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

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