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

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