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.

JingleSessionPC.js 55KB

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