modified lib-jitsi-meet dev repo
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 56KB

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