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

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