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

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