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

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