Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JingleSessionPC.js 62KB

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