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.

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