您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSession.js 54KB

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