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.

JingleSession.js 53KB

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