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

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