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

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