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

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