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

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