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

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