modified lib-jitsi-meet dev repo
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 63KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700
  1. /* global $, $iq, Strophe */
  2. import {getLogger} from 'jitsi-meet-logger';
  3. const logger = getLogger(__filename);
  4. import JingleSession from './JingleSession';
  5. const SDPDiffer = require('./SDPDiffer');
  6. const SDPUtil = require('./SDPUtil');
  7. const SDP = require('./SDP');
  8. const async = require('async');
  9. const XMPPEvents = require('../../service/xmpp/XMPPEvents');
  10. const RTCBrowserType = require('../RTC/RTCBrowserType');
  11. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  12. const Statistics = require('../statistics/statistics');
  13. import * as JingleSessionState from './JingleSessionState';
  14. /**
  15. * Constant tells how long we're going to wait for IQ response, before timeout
  16. * error is triggered.
  17. * @type {number}
  18. */
  19. const IQ_TIMEOUT = 10000;
  20. export default class JingleSessionPC extends JingleSession {
  21. /**
  22. * Creates new <tt>JingleSessionPC</tt>
  23. * @param {string} sid the Jingle Session ID - random string which
  24. * identifies the session
  25. * @param {string} me our JID
  26. * @param {string} peerjid remote peer JID
  27. * @param {Strophe.Connection} connection Strophe XMPP connection instance
  28. * used to send packets.
  29. * @param media_constraints the media constraints object passed to
  30. * createOffer/Answer, as defined by the WebRTC standard
  31. * @param ice_config the ICE servers config object as defined by the WebRTC
  32. * standard.
  33. * @param {object} options a set of config options
  34. * @param {boolean} options.webrtcIceUdpDisable <tt>true</tt> to block UDP
  35. * candidates.
  36. * @param {boolean} options.webrtcIceTcpDisable <tt>true</tt> to block TCP
  37. * candidates.
  38. * @param {boolean} options.failICE it's an option used in the tests. Set to
  39. * <tt>true</tt> to block any real candidates and make the ICE fail.
  40. *
  41. * @constructor
  42. *
  43. * @implements {SignalingLayer}
  44. */
  45. constructor(sid, me, peerjid, connection,
  46. media_constraints, ice_config, options) {
  47. super(sid, me, peerjid, connection, media_constraints, ice_config);
  48. this.lasticecandidate = false;
  49. this.closed = false;
  50. this.modifyingLocalStreams = false;
  51. /**
  52. * Used to keep state about muted/unmuted video streams
  53. * so we can prevent errant source-add/source-removes
  54. * from happening
  55. */
  56. this.modifiedSSRCs = {};
  57. /**
  58. * The local ICE username fragment for this session.
  59. */
  60. this.localUfrag = null;
  61. /**
  62. * The remote ICE username fragment for this session.
  63. */
  64. this.remoteUfrag = null;
  65. /**
  66. * A map that stores SSRCs of remote streams. And is used only locally
  67. * We store the mapping when jingle is received, and later is used
  68. * onaddstream webrtc event where we have only the ssrc
  69. * FIXME: This map got filled and never cleaned and can grow during
  70. * long conference
  71. * @type {{}} maps SSRC number to jid
  72. */
  73. this.ssrcOwners = {};
  74. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  75. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  76. /**
  77. * Flag used to enforce ICE failure through the URL parameter for
  78. * the automatic testing purpose.
  79. * @type {boolean}
  80. */
  81. this.failICE = Boolean(options.failICE);
  82. this.modificationQueue
  83. = async.queue(this._processQueueTasks.bind(this), 1);
  84. }
  85. doInitialize() {
  86. this.lasticecandidate = false;
  87. // True if reconnect is in progress
  88. this.isreconnect = false;
  89. // Set to true if the connection was ever stable
  90. this.wasstable = false;
  91. // Create new peer connection instance
  92. this.peerconnection
  93. = this.rtc.createPeerConnection(
  94. this,
  95. this.connection.jingle.ice_config,
  96. /* Options */
  97. {
  98. disableSimulcast: this.room.options.disableSimulcast,
  99. disableRtx: this.room.options.disableRtx,
  100. preferH264: this.room.options.preferH264
  101. });
  102. this.peerconnection.onicecandidate = ev => {
  103. if (!ev) {
  104. // There was an incomplete check for ev before which left
  105. // the last line of the function unprotected from a potential
  106. // throw of an exception. Consequently, it may be argued that
  107. // the check is unnecessary. Anyway, I'm leaving it and making
  108. // the check complete.
  109. return;
  110. }
  111. // XXX this is broken, candidate is not parsed.
  112. const candidate = ev.candidate;
  113. if (candidate) {
  114. // Discard candidates of disabled protocols.
  115. let protocol = candidate.protocol;
  116. if (typeof protocol === 'string') {
  117. protocol = protocol.toLowerCase();
  118. if (protocol === 'tcp' || protocol === 'ssltcp') {
  119. if (this.webrtcIceTcpDisable) {
  120. return;
  121. }
  122. } else if (protocol == 'udp') {
  123. if (this.webrtcIceUdpDisable) {
  124. return;
  125. }
  126. }
  127. }
  128. }
  129. this.sendIceCandidate(candidate);
  130. };
  131. // Note there is a change in the spec about closed:
  132. // This value moved into the RTCPeerConnectionState enum in
  133. // the May 13, 2016 draft of the specification, as it reflects the state
  134. // of the RTCPeerConnection, not the signaling connection. You now
  135. // detect a closed connection by checking for connectionState to be
  136. // "closed" instead.
  137. // I suppose at some point this will be moved to onconnectionstatechange
  138. this.peerconnection.onsignalingstatechange = () => {
  139. if (!this.peerconnection) {
  140. return;
  141. }
  142. if (this.peerconnection.signalingState === 'stable') {
  143. this.wasstable = true;
  144. } else if (
  145. (this.peerconnection.signalingState === 'closed'
  146. || this.peerconnection.connectionState === 'closed')
  147. && !this.closed) {
  148. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED);
  149. }
  150. };
  151. /**
  152. * The oniceconnectionstatechange event handler contains the code to
  153. * execute when the iceconnectionstatechange event, of type Event,
  154. * is received by this RTCPeerConnection. Such an event is sent when
  155. * the value of RTCPeerConnection.iceConnectionState changes.
  156. */
  157. this.peerconnection.oniceconnectionstatechange = () => {
  158. if (!this.peerconnection) {
  159. return;
  160. }
  161. const now = window.performance.now();
  162. this.room.connectionTimes[
  163. `ice.state.${this.peerconnection.iceConnectionState}`]
  164. = now;
  165. logger.log(
  166. `(TIME) ICE ${this.peerconnection.iceConnectionState}:\t`,
  167. now);
  168. Statistics.analytics.sendEvent(
  169. `ice.${this.peerconnection.iceConnectionState}`,
  170. {value: now});
  171. this.room.eventEmitter.emit(
  172. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  173. this.peerconnection.iceConnectionState);
  174. switch (this.peerconnection.iceConnectionState) {
  175. case 'connected':
  176. // Informs interested parties that the connection has been
  177. // restored.
  178. if (this.peerconnection.signalingState === 'stable'
  179. && this.isreconnect) {
  180. this.room.eventEmitter.emit(
  181. XMPPEvents.CONNECTION_RESTORED);
  182. }
  183. this.isreconnect = false;
  184. break;
  185. case 'disconnected':
  186. if (this.closed) {
  187. break;
  188. }
  189. this.isreconnect = true;
  190. // Informs interested parties that the connection has been
  191. // interrupted.
  192. if (this.wasstable) {
  193. this.room.eventEmitter.emit(
  194. XMPPEvents.CONNECTION_INTERRUPTED);
  195. }
  196. break;
  197. case 'failed':
  198. this.room.eventEmitter.emit(
  199. XMPPEvents.CONNECTION_ICE_FAILED, this.peerconnection);
  200. break;
  201. }
  202. };
  203. this.peerconnection.onnegotiationneeded = () => {
  204. this.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, this);
  205. };
  206. }
  207. sendIceCandidate(candidate) {
  208. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  209. if (candidate && !this.lasticecandidate) {
  210. const ice
  211. = SDPUtil.iceparams(
  212. localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  213. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  214. if (!(ice && jcand)) {
  215. const errorMesssage = 'failed to get ice && jcand';
  216. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  217. logger.error(errorMesssage);
  218. return;
  219. }
  220. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  221. if (this.usedrip) {
  222. if (this.drip_container.length === 0) {
  223. // start 20ms callout
  224. setTimeout(() => {
  225. if (this.drip_container.length === 0) {
  226. return;
  227. }
  228. this.sendIceCandidates(this.drip_container);
  229. this.drip_container = [];
  230. }, 20);
  231. }
  232. this.drip_container.push(candidate);
  233. } else {
  234. this.sendIceCandidates([candidate]);
  235. }
  236. } else {
  237. logger.log('sendIceCandidate: last candidate.');
  238. // FIXME: remember to re-think in ICE-restart
  239. this.lasticecandidate = true;
  240. }
  241. }
  242. sendIceCandidates(candidates) {
  243. logger.log('sendIceCandidates', candidates);
  244. const cand = $iq({to: this.peerjid, type: 'set'})
  245. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  246. action: 'transport-info',
  247. initiator: this.initiator,
  248. sid: this.sid});
  249. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  250. for (let mid = 0; mid < localSDP.media.length; mid++) {
  251. const cands = candidates.filter(el => el.sdpMLineIndex == mid);
  252. const mline
  253. = SDPUtil.parse_mline(localSDP.media[mid].split('\r\n')[0]);
  254. if (cands.length > 0) {
  255. const ice
  256. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  257. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  258. cand.c('content', {
  259. creator: this.initiator == this.localJid
  260. ? 'initiator' : 'responder',
  261. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  262. }).c('transport', ice);
  263. for (let i = 0; i < cands.length; i++) {
  264. const candidate
  265. = SDPUtil.candidateToJingle(cands[i].candidate);
  266. // Mangle ICE candidate if 'failICE' test option is enabled
  267. if (this.failICE) {
  268. candidate.ip = '1.1.1.1';
  269. }
  270. cand.c('candidate', candidate).up();
  271. }
  272. // add fingerprint
  273. const fingerprint_line
  274. = SDPUtil.find_line(
  275. localSDP.media[mid],
  276. 'a=fingerprint:', localSDP.session);
  277. if (fingerprint_line) {
  278. const tmp = SDPUtil.parse_fingerprint(fingerprint_line);
  279. tmp.required = true;
  280. cand.c(
  281. 'fingerprint',
  282. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  283. .t(tmp.fingerprint);
  284. delete tmp.fingerprint;
  285. cand.attrs(tmp);
  286. cand.up();
  287. }
  288. cand.up(); // transport
  289. cand.up(); // content
  290. }
  291. }
  292. // might merge last-candidate notification into this, but it is called
  293. // a lot later. See webrtc issue #2340
  294. // logger.log('was this the last candidate', this.lasticecandidate);
  295. this.connection.sendIQ(
  296. cand, null, this.newJingleErrorHandler(cand, error => {
  297. GlobalOnErrorHandler.callErrorHandler(
  298. new Error(`Jingle error: ${JSON.stringify(error)}`));
  299. }), IQ_TIMEOUT);
  300. }
  301. readSsrcInfo(contents) {
  302. $(contents).each((idx, content) => {
  303. const ssrcs
  304. = $(content).find(
  305. 'description>'
  306. + 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  307. ssrcs.each((idx, ssrcElement) => {
  308. const ssrc = ssrcElement.getAttribute('ssrc');
  309. $(ssrcElement)
  310. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  311. .each((idx, ssrcInfoElement) => {
  312. const owner = ssrcInfoElement.getAttribute('owner');
  313. if (owner && owner.length) {
  314. this.ssrcOwners[ssrc]
  315. = Strophe.getResourceFromJid(owner);
  316. }
  317. }
  318. );
  319. });
  320. });
  321. }
  322. /**
  323. * Makes the underlying TraceablePeerConnection generate new SSRC for
  324. * the recvonly video stream.
  325. * @deprecated
  326. */
  327. generateRecvonlySsrc() {
  328. if (this.peerconnection) {
  329. this.peerconnection.generateRecvonlySsrc();
  330. } else {
  331. logger.error(
  332. 'Unable to generate recvonly SSRC - no peerconnection');
  333. }
  334. }
  335. /**
  336. * Accepts incoming Jingle 'session-initiate' and should send
  337. * 'session-accept' in result.
  338. * @param jingleOffer jQuery selector pointing to the jingle element of
  339. * the offer IQ
  340. * @param success callback called when we accept incoming session
  341. * successfully and receive RESULT packet to 'session-accept' sent.
  342. * @param failure function(error) called if for any reason we fail to accept
  343. * the incoming offer. 'error' argument can be used to log some
  344. * details about the error.
  345. */
  346. acceptOffer(jingleOffer, success, failure) {
  347. this.state = JingleSessionState.ACTIVE;
  348. this.setOfferCycle(
  349. jingleOffer,
  350. () => {
  351. // FIXME we may not care about RESULT packet for session-accept
  352. // then we should either call 'success' here immediately or
  353. // modify sendSessionAccept method to do that
  354. this.sendSessionAccept(success, failure);
  355. },
  356. failure);
  357. }
  358. /**
  359. * This is a setRemoteDescription/setLocalDescription cycle which starts at
  360. * converting Strophe Jingle IQ into remote offer SDP. Once converted
  361. * setRemoteDescription, createAnswer and setLocalDescription calls follow.
  362. * @param jingleOfferIq jQuery selector pointing to the jingle element of
  363. * the offer IQ
  364. * @param success callback called when sRD/sLD cycle finishes successfully.
  365. * @param failure callback called with an error object as an argument if we
  366. * fail at any point during setRD, createAnswer, setLD.
  367. */
  368. setOfferCycle(jingleOfferIq, success, failure) {
  369. const workFunction = finishedCallback => {
  370. const newRemoteSdp = this._processNewJingleOfferIq(jingleOfferIq);
  371. this._renegotiate(newRemoteSdp)
  372. .then(() => {
  373. finishedCallback();
  374. }, error => {
  375. logger.error(
  376. `Error renegotiating after setting new remote offer: ${
  377. error}`);
  378. JingleSessionPC.onJingleFatalError(this, error);
  379. finishedCallback(error);
  380. });
  381. };
  382. this.modificationQueue.push(
  383. workFunction,
  384. error => {
  385. error ? failure(error) : success();
  386. });
  387. }
  388. /**
  389. * Although it states "replace transport" it does accept full Jingle offer
  390. * which should contain new ICE transport details.
  391. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  392. * transport info.
  393. * @param success callback called when we succeed to accept new offer.
  394. * @param failure function(error) called when we fail to accept new offer.
  395. */
  396. replaceTransport(jingleOfferElem, success, failure) {
  397. // We need to first set an offer without the 'data' section to have the
  398. // SCTP stack cleaned up. After that the original offer is set to have
  399. // the SCTP connection established with the new bridge.
  400. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING);
  401. const originalOffer = jingleOfferElem.clone();
  402. jingleOfferElem.find('>content[name=\'data\']').remove();
  403. // First set an offer without the 'data' section
  404. this.setOfferCycle(
  405. jingleOfferElem,
  406. () => {
  407. // Now set the original offer(with the 'data' section)
  408. this.setOfferCycle(
  409. originalOffer,
  410. () => {
  411. const localSDP
  412. = new SDP(this.peerconnection.localDescription.sdp);
  413. this.sendTransportAccept(localSDP, success, failure);
  414. },
  415. failure);
  416. },
  417. failure
  418. );
  419. }
  420. /**
  421. * Sends Jingle 'session-accept' message.
  422. * @param {function()} success callback called when we receive 'RESULT'
  423. * packet for the 'session-accept'
  424. * @param {function(error)} failure called when we receive an error response
  425. * or when the request has timed out.
  426. */
  427. sendSessionAccept(success, failure) {
  428. // NOTE: since we're just reading from it, we don't need to be within
  429. // the modification queue to access the local description
  430. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  431. let accept = $iq({to: this.peerjid,
  432. type: 'set'})
  433. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  434. action: 'session-accept',
  435. initiator: this.initiator,
  436. responder: this.responder,
  437. sid: this.sid });
  438. if (this.webrtcIceTcpDisable) {
  439. localSDP.removeTcpCandidates = true;
  440. }
  441. if (this.webrtcIceUdpDisable) {
  442. localSDP.removeUdpCandidates = true;
  443. }
  444. if (this.failICE) {
  445. localSDP.failICE = true;
  446. }
  447. localSDP.toJingle(
  448. accept,
  449. this.initiator == this.localJid ? 'initiator' : 'responder',
  450. null);
  451. this.fixJingle(accept);
  452. // Calling tree() to print something useful
  453. accept = accept.tree();
  454. logger.info('Sending session-accept', accept);
  455. this.connection.sendIQ(accept,
  456. success,
  457. this.newJingleErrorHandler(accept, error => {
  458. failure(error);
  459. // 'session-accept' is a critical timeout and we'll
  460. // have to restart
  461. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_TIMEOUT);
  462. }),
  463. IQ_TIMEOUT);
  464. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  465. // fingerprint and setup) ASAP in order to start the connection
  466. // establishment.
  467. //
  468. // FIXME Flushing the connection at this point triggers an issue with
  469. // BOSH request handling in Prosody on slow connections.
  470. //
  471. // The problem is that this request will be quite large and it may take
  472. // time before it reaches Prosody. In the meantime Strophe may decide
  473. // to send the next one. And it was observed that a small request with
  474. // 'transport-info' usually follows this one. It does reach Prosody
  475. // before the previous one was completely received. 'rid' on the server
  476. // is increased and Prosody ignores the request with 'session-accept'.
  477. // It will never reach Jicofo and everything in the request table is
  478. // lost. Removing the flush does not guarantee it will never happen, but
  479. // makes it much less likely('transport-info' is bundled with
  480. // 'session-accept' and any immediate requests).
  481. //
  482. // this.connection.flush();
  483. }
  484. /**
  485. * Sends Jingle 'transport-accept' message which is a response to
  486. * 'transport-replace'.
  487. * @param localSDP the 'SDP' object with local session description
  488. * @param success callback called when we receive 'RESULT' packet for
  489. * 'transport-replace'
  490. * @param failure function(error) called when we receive an error response
  491. * or when the request has timed out.
  492. */
  493. sendTransportAccept(localSDP, success, failure) {
  494. let transportAccept = $iq({to: this.peerjid, type: 'set'})
  495. .c('jingle', {
  496. xmlns: 'urn:xmpp:jingle:1',
  497. action: 'transport-accept',
  498. initiator: this.initiator,
  499. sid: this.sid
  500. });
  501. localSDP.media.forEach((medialines, idx) => {
  502. const mline = SDPUtil.parse_mline(medialines.split('\r\n')[0]);
  503. transportAccept.c('content',
  504. {
  505. creator:
  506. this.initiator == this.localJid
  507. ? 'initiator'
  508. : 'responder',
  509. name: mline.media
  510. }
  511. );
  512. localSDP.transportToJingle(idx, transportAccept);
  513. transportAccept.up();
  514. });
  515. // Calling tree() to print something useful to the logger
  516. transportAccept = transportAccept.tree();
  517. logger.info('Sending transport-accept: ', transportAccept);
  518. this.connection.sendIQ(transportAccept,
  519. success,
  520. this.newJingleErrorHandler(transportAccept, failure),
  521. IQ_TIMEOUT);
  522. }
  523. /**
  524. * Sends Jingle 'transport-reject' message which is a response to
  525. * 'transport-replace'.
  526. * @param success callback called when we receive 'RESULT' packet for
  527. * 'transport-replace'
  528. * @param failure function(error) called when we receive an error response
  529. * or when the request has timed out.
  530. */
  531. sendTransportReject(success, failure) {
  532. // Send 'transport-reject', so that the focus will
  533. // know that we've failed
  534. let transportReject = $iq({to: this.peerjid, type: 'set'})
  535. .c('jingle', {
  536. xmlns: 'urn:xmpp:jingle:1',
  537. action: 'transport-reject',
  538. initiator: this.initiator,
  539. sid: this.sid
  540. });
  541. transportReject = transportReject.tree();
  542. logger.info('Sending \'transport-reject', transportReject);
  543. this.connection.sendIQ(transportReject,
  544. success,
  545. this.newJingleErrorHandler(transportReject, failure),
  546. IQ_TIMEOUT);
  547. }
  548. /**
  549. * @inheritDoc
  550. */
  551. terminate(reason, text, success, failure) {
  552. this.state = JingleSessionState.ENDED;
  553. let sessionTerminate = $iq({ to: this.peerjid, type: 'set' })
  554. .c('jingle', {
  555. xmlns: 'urn:xmpp:jingle:1',
  556. action: 'session-terminate',
  557. initiator: this.initiator,
  558. sid: this.sid
  559. })
  560. .c('reason')
  561. .c(reason || 'success');
  562. if (text) {
  563. // eslint-disable-next-line newline-per-chained-call
  564. sessionTerminate.up().c('text').t(text);
  565. }
  566. // Calling tree() to print something useful
  567. sessionTerminate = sessionTerminate.tree();
  568. logger.info('Sending session-terminate', sessionTerminate);
  569. this.connection.sendIQ(
  570. sessionTerminate,
  571. success,
  572. this.newJingleErrorHandler(sessionTerminate, failure), IQ_TIMEOUT);
  573. // this should result in 'onTerminated' being called by strope.jingle.js
  574. this.connection.jingle.terminate(this.sid);
  575. }
  576. onTerminated(reasonCondition, reasonText) {
  577. this.state = 'ended';
  578. // Do something with reason and reasonCondition when we start to care
  579. // this.reasonCondition = reasonCondition;
  580. // this.reasonText = reasonText;
  581. logger.info('Session terminated', this, reasonCondition, reasonText);
  582. this.close();
  583. }
  584. /**
  585. * Parse the information from the xml sourceAddElem and translate it
  586. * into sdp lines
  587. * @param {jquery xml element} sourceAddElem the source-add
  588. * element from jingle
  589. * @param {SDP object} currentRemoteSdp the current remote
  590. * sdp (as of this new source-add)
  591. * @returns {list} a list of SDP line strings that should
  592. * be added to the remote SDP
  593. */
  594. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  595. const addSsrcInfo = [];
  596. $(sourceAddElem).each((idx, content) => {
  597. const name = $(content).attr('name');
  598. let lines = '';
  599. $(content)
  600. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  601. .each(function() {
  602. const semantics = this.getAttribute('semantics');
  603. const ssrcs
  604. = $(this)
  605. .find('>source')
  606. .map(function() {
  607. return this.getAttribute('ssrc');
  608. })
  609. .get();
  610. if (ssrcs.length) {
  611. lines
  612. += `a=ssrc-group:${semantics} ${ssrcs.join(' ')
  613. }\r\n`;
  614. }
  615. });
  616. // handles both >source and >description>source
  617. const tmp
  618. = $(content).find(
  619. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  620. tmp.each(function() {
  621. const ssrc = $(this).attr('ssrc');
  622. if (currentRemoteSdp.containsSSRC(ssrc)) {
  623. logger.warn(
  624. `Source-add request for existing SSRC: ${ssrc}`);
  625. return;
  626. }
  627. // eslint-disable-next-line newline-per-chained-call
  628. $(this).find('>parameter').each(function() {
  629. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  630. if ($(this).attr('value') && $(this).attr('value').length) {
  631. lines += `:${$(this).attr('value')}`;
  632. }
  633. lines += '\r\n';
  634. });
  635. });
  636. currentRemoteSdp.media.forEach((media, idx) => {
  637. if (!SDPUtil.find_line(media, `a=mid:${name}`)) {
  638. return;
  639. }
  640. if (!addSsrcInfo[idx]) {
  641. addSsrcInfo[idx] = '';
  642. }
  643. addSsrcInfo[idx] += lines;
  644. });
  645. });
  646. return addSsrcInfo;
  647. }
  648. /**
  649. * Handles a Jingle source-add message for this Jingle session.
  650. * @param elem An array of Jingle "content" elements.
  651. */
  652. addRemoteStream(elem) {
  653. // FIXME there is not stop condition for this wait !!!
  654. if (!this.peerconnection.localDescription) {
  655. logger.warn('addSource - localDescription not ready yet');
  656. setTimeout(() => this.addRemoteStream(elem), 200);
  657. return;
  658. }
  659. logger.log('Processing add remote stream');
  660. logger.log(
  661. 'ICE connection state: ', this.peerconnection.iceConnectionState);
  662. this.readSsrcInfo(elem);
  663. const workFunction = finishedCallback => {
  664. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  665. const mySdp = new SDP(this.peerconnection.localDescription.sdp);
  666. const addSsrcInfo = this._parseSsrcInfoFromSourceAdd(elem, sdp);
  667. const newRemoteSdp = this._processRemoteAddSource(addSsrcInfo);
  668. this._renegotiate(newRemoteSdp)
  669. .then(() => {
  670. logger.info('Remote source-add processed');
  671. const newSdp
  672. = new SDP(this.peerconnection.localDescription.sdp);
  673. logger.log('SDPs', mySdp, newSdp);
  674. this.notifyMySSRCUpdate(mySdp, newSdp);
  675. finishedCallback();
  676. }, error => {
  677. logger.error(
  678. `Error renegotiating after processing remote source-add: ${error}`);
  679. finishedCallback(error);
  680. });
  681. };
  682. this.modificationQueue.push(workFunction);
  683. }
  684. /**
  685. * Handles a Jingle source-remove message for this Jingle session.
  686. * @param elem An array of Jingle "content" elements.
  687. */
  688. removeRemoteStream(elem) {
  689. // FIXME there is no stop condition for this wait !
  690. if (!this.peerconnection.localDescription) {
  691. logger.warn('removeSource - localDescription not ready yet');
  692. setTimeout(() => this.removeRemoteStream(elem), 200);
  693. return;
  694. }
  695. logger.log('Remove remote stream');
  696. logger.log(
  697. 'ICE connection state: ', this.peerconnection.iceConnectionState);
  698. const workFunction = finishedCallback => {
  699. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  700. const mySdp = new SDP(this.peerconnection.localDescription.sdp);
  701. const removeSsrcInfo
  702. = this._parseSsrcInfoFromSourceRemove(elem, sdp);
  703. const newRemoteSdp
  704. = this._processRemoteRemoveSource(removeSsrcInfo);
  705. this._renegotiate(newRemoteSdp)
  706. .then(() => {
  707. logger.info('Remote source-remove processed');
  708. const newSdp
  709. = new SDP(this.peerconnection.localDescription.sdp);
  710. logger.log('SDPs', mySdp, newSdp);
  711. this.notifyMySSRCUpdate(mySdp, newSdp);
  712. finishedCallback();
  713. }, error => {
  714. logger.error(
  715. `Error renegotiating after processing remote source-remove: ${error}`);
  716. finishedCallback(error);
  717. });
  718. };
  719. this.modificationQueue.push(workFunction);
  720. }
  721. /**
  722. * The 'task' function will be given a callback it MUST call with either:
  723. * 1) No arguments if it was successful or
  724. * 2) An error argument if there was an error
  725. * If the task wants to process the success or failure of the task, it
  726. * should pass a handler to the .push function, e.g.:
  727. * queue.push(task, (err) => {
  728. * if (err) {
  729. * // error handling
  730. * } else {
  731. * // success handling
  732. * }
  733. * });
  734. */
  735. _processQueueTasks(task, finishedCallback) {
  736. task(finishedCallback);
  737. }
  738. /**
  739. * Takes in a jingle offer iq, returns the new sdp offer
  740. * @param {jquery xml element} offerIq the incoming offer
  741. * @returns {SDP object} the jingle offer translated to SDP
  742. */
  743. _processNewJingleOfferIq(offerIq) {
  744. const remoteSdp = new SDP('');
  745. if (this.webrtcIceTcpDisable) {
  746. remoteSdp.removeTcpCandidates = true;
  747. }
  748. if (this.webrtcIceUdpDisable) {
  749. remoteSdp.removeUdpCandidates = true;
  750. }
  751. if (this.failICE) {
  752. remoteSdp.failICE = true;
  753. }
  754. remoteSdp.fromJingle(offerIq);
  755. this.readSsrcInfo($(offerIq).find('>content'));
  756. return remoteSdp;
  757. }
  758. /**
  759. * Remove the given ssrc lines from the current remote sdp
  760. * @param {list} removeSsrcInfo a list of SDP line strings that
  761. * should be removed from the remote SDP
  762. * @returns type {SDP Object} the new remote SDP (after removing the lines
  763. * in removeSsrcInfo
  764. */
  765. _processRemoteRemoveSource(removeSsrcInfo) {
  766. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  767. removeSsrcInfo.forEach((lines, idx) => {
  768. lines = lines.split('\r\n');
  769. lines.pop(); // remove empty last element;
  770. lines.forEach(line => {
  771. remoteSdp.media[idx]
  772. = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  773. });
  774. });
  775. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  776. return remoteSdp;
  777. }
  778. /**
  779. * Add the given ssrc lines to the current remote sdp
  780. * @param {list} addSsrcInfo a list of SDP line strings that
  781. * should be added to the remote SDP
  782. * @returns type {SDP Object} the new remote SDP (after removing the lines
  783. * in removeSsrcInfo
  784. */
  785. _processRemoteAddSource(addSsrcInfo) {
  786. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  787. addSsrcInfo.forEach((lines, idx) => {
  788. remoteSdp.media[idx] += lines;
  789. });
  790. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  791. return remoteSdp;
  792. }
  793. /**
  794. * Do a new o/a flow using the existing remote description
  795. * @param {SDP object} optionalRemoteSdp optional remote sdp
  796. * to use. If not provided, the remote sdp from the
  797. * peerconnection will be used
  798. * @returns {Promise} promise which resolves when the
  799. * o/a flow is complete with no arguments or
  800. * rejects with an error {string}
  801. */
  802. _renegotiate(optionalRemoteSdp) {
  803. const media_constraints = this.media_constraints;
  804. const remoteSdp
  805. = optionalRemoteSdp
  806. || new SDP(this.peerconnection.remoteDescription.sdp);
  807. const remoteDescription = new RTCSessionDescription({
  808. type: 'offer',
  809. sdp: remoteSdp.raw
  810. });
  811. // TODO(brian): in the code below there are 2 chunks of code that relate
  812. // to observing changes in local and remove ufrags. since they
  813. // just need to read and observe the SDPs, we should create the
  814. // notion of an SDP observer in TraceablePeerConnection that
  815. // gets notified of all SDP changes. Code like the ufrag
  816. // logic below could listen to that and be separated from
  817. // core flows like this.
  818. return new Promise((resolve, reject) => {
  819. const remoteUfrag = JingleSessionPC.getUfrag(remoteDescription.sdp);
  820. if (remoteUfrag != this.remoteUfrag) {
  821. this.remoteUfrag = remoteUfrag;
  822. this.room.eventEmitter.emit(
  823. XMPPEvents.REMOTE_UFRAG_CHANGED, remoteUfrag);
  824. }
  825. logger.debug('Renegotiate: setting remote description');
  826. this.peerconnection.setRemoteDescription(
  827. remoteDescription,
  828. () => {
  829. if (this.signalingState === 'closed') {
  830. reject('Attempted to setRemoteDescription in state closed');
  831. return;
  832. }
  833. logger.debug('Renegotiate: creating answer');
  834. this.peerconnection.createAnswer(
  835. answer => {
  836. const localUfrag
  837. = JingleSessionPC.getUfrag(answer.sdp);
  838. if (localUfrag != this.localUfrag) {
  839. this.localUfrag = localUfrag;
  840. this.room.eventEmitter.emit(
  841. XMPPEvents.LOCAL_UFRAG_CHANGED,
  842. localUfrag);
  843. }
  844. logger.debug(
  845. 'Renegotiate: setting local description');
  846. this.peerconnection.setLocalDescription(
  847. answer,
  848. () => {
  849. resolve();
  850. },
  851. error => {
  852. reject(
  853. `setLocalDescription failed: ${error}`);
  854. }
  855. );
  856. },
  857. error => reject(`createAnswer failed: ${error}`),
  858. media_constraints
  859. );
  860. },
  861. error => {
  862. reject(`setRemoteDescription failed: ${error}`);
  863. }
  864. );
  865. });
  866. }
  867. /**
  868. * Replaces oldStream with newStream and performs a single offer/answer
  869. * cycle after both operations are done. Either oldStream or newStream
  870. * can be null; replacing a valid 'oldStream' with a null 'newStream'
  871. * effectively just removes 'oldStream'
  872. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  873. * replaced
  874. * @param {JitsiLocalTrack|null} newTrack the new track to use
  875. * @returns {Promise} which resolves once the replacement is complete
  876. * with no arguments or rejects with an error {string}
  877. */
  878. replaceTrack(oldTrack, newTrack) {
  879. return new Promise((resolve, reject) => {
  880. const workFunction = finishedCallback => {
  881. const oldSdp
  882. = new SDP(this.peerconnection.localDescription.sdp);
  883. // NOTE the code below assumes that no more than 1 video track
  884. // can be added to the peer connection.
  885. // Transition from no video to video (possibly screen sharing)
  886. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  887. // Clearing current primary SSRC will make
  888. // the SdpConsistency generate a new one which will result
  889. // with:
  890. // 1. source-remove for the recvonly
  891. // 2. source-add for the new video stream
  892. this.peerconnection.clearRecvonlySsrc();
  893. // Transition from video to no video
  894. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  895. // Clearing current primary SSRC and generating the recvonly
  896. // will result in:
  897. // 1. source-remove for the old video stream
  898. // 2. source-add for the recvonly stream
  899. this.peerconnection.clearRecvonlySsrc();
  900. this.peerconnection.generateRecvonlySsrc();
  901. }
  902. this.removeStreamFromPeerConnection(oldTrack);
  903. this.addStreamToPeerConnection(newTrack);
  904. this._renegotiate()
  905. .then(() => {
  906. const newSdp
  907. = new SDP(this.peerconnection.localDescription.sdp);
  908. this.notifyMySSRCUpdate(oldSdp, newSdp);
  909. finishedCallback();
  910. }, error => {
  911. logger.error(
  912. `replaceTrack renegotiation failed: ${error}`);
  913. finishedCallback(error);
  914. });
  915. };
  916. this.modificationQueue.push(
  917. workFunction,
  918. error => {
  919. error ? reject(error) : resolve();
  920. });
  921. });
  922. }
  923. /**
  924. * Just add the stream to the peerconnection
  925. * @param stream either the low-level webrtc MediaStream or
  926. * a Jitsi mediastream
  927. * NOTE: must be called within a work function being executed
  928. * by the modification queue.
  929. */
  930. addStreamToPeerConnection(stream, ssrcInfo) {
  931. const actualStream
  932. = stream && stream.getOriginalStream
  933. ? stream.getOriginalStream() : stream;
  934. if (this.peerconnection) {
  935. this.peerconnection.addStream(actualStream, ssrcInfo);
  936. }
  937. }
  938. /**
  939. * Parse the information from the xml sourceRemoveElem and translate it
  940. * into sdp lines
  941. * @param {jquery xml element} sourceRemoveElem the source-remove
  942. * element from jingle
  943. * @param {SDP object} currentRemoteSdp the current remote
  944. * sdp (as of this new source-remove)
  945. * @returns {list} a list of SDP line strings that should
  946. * be removed from the remote SDP
  947. */
  948. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  949. const removeSsrcInfo = [];
  950. $(sourceRemoveElem).each((idx, content) => {
  951. const name = $(content).attr('name');
  952. let lines = '';
  953. $(content)
  954. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  955. .each(function() {
  956. const semantics = this.getAttribute('semantics');
  957. const ssrcs
  958. = $(this)
  959. .find('>source')
  960. .map(function() {
  961. return this.getAttribute('ssrc');
  962. })
  963. .get();
  964. if (ssrcs.length) {
  965. lines
  966. += `a=ssrc-group:${semantics} ${ssrcs.join(' ')
  967. }\r\n`;
  968. }
  969. });
  970. const ssrcs = [];
  971. // handles both >source and >description>source versions
  972. const tmp
  973. = $(content).find(
  974. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  975. tmp.each(function() {
  976. const ssrc = $(this).attr('ssrc');
  977. ssrcs.push(ssrc);
  978. });
  979. currentRemoteSdp.media.forEach((media, idx) => {
  980. if (!SDPUtil.find_line(media, `a=mid:${name}`)) {
  981. return;
  982. }
  983. if (!removeSsrcInfo[idx]) {
  984. removeSsrcInfo[idx] = '';
  985. }
  986. ssrcs.forEach(ssrc => {
  987. const ssrcLines
  988. = SDPUtil.find_lines(media, `a=ssrc:${ssrc}`);
  989. if (ssrcLines.length) {
  990. removeSsrcInfo[idx] += `${ssrcLines.join('\r\n')}\r\n`;
  991. }
  992. });
  993. removeSsrcInfo[idx] += lines;
  994. });
  995. });
  996. return removeSsrcInfo;
  997. }
  998. /**
  999. * Adds stream.
  1000. * @param stream new stream that will be added.
  1001. * @param callback callback executed after successful stream addition.
  1002. * @param errorCallback callback executed if stream addition fail.
  1003. * @param ssrcInfo object with information about the SSRCs associated with
  1004. * the stream.
  1005. * @param dontModifySources {boolean} if true _modifySources won't be
  1006. * called.
  1007. * Used for streams added before the call start.
  1008. * NOTE(brian): there is a decent amount of overlap here with replaceTrack
  1009. * that could be re-used...however we can't leverage that currently because
  1010. * the extra work we do here must be in the work function context and if we
  1011. * then called replaceTrack we'd be adding another task on the queue
  1012. * from within a task which would then deadlock. The 'replaceTrack' core
  1013. * logic should be moved into a helper function that could be called within
  1014. * the 'doReplaceStream' task or the 'doAddStream' task (for example)
  1015. */
  1016. addStream(stream, callback, errorCallback, ssrcInfo, dontModifySources) {
  1017. const workFunction = finishedCallback => {
  1018. if (!this.peerconnection) {
  1019. finishedCallback(
  1020. 'Error: tried adding stream with no active peer connection');
  1021. return;
  1022. }
  1023. this.addStreamToPeerConnection(stream, ssrcInfo);
  1024. if (ssrcInfo) {
  1025. // available only on video mute/unmute
  1026. this.modifiedSSRCs[ssrcInfo.type]
  1027. = this.modifiedSSRCs[ssrcInfo.type] || [];
  1028. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1029. }
  1030. if (dontModifySources) {
  1031. finishedCallback();
  1032. return;
  1033. }
  1034. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1035. this._renegotiate()
  1036. .then(() => {
  1037. const newSdp
  1038. = new SDP(this.peerconnection.localDescription.sdp);
  1039. // FIXME objects should not be logged
  1040. logger.log('SDPs', oldSdp, newSdp);
  1041. this.notifyMySSRCUpdate(oldSdp, newSdp);
  1042. finishedCallback();
  1043. }, error => {
  1044. finishedCallback(error);
  1045. });
  1046. };
  1047. this.modificationQueue.push(
  1048. workFunction,
  1049. error => {
  1050. error ? errorCallback(error) : callback();
  1051. });
  1052. }
  1053. /**
  1054. * Generate ssrc info object for a stream with the following properties:
  1055. * - ssrcs - Array of the ssrcs associated with the stream.
  1056. * - groups - Array of the groups associated with the stream.
  1057. */
  1058. generateNewStreamSSRCInfo() {
  1059. return this.peerconnection.generateNewStreamSSRCInfo();
  1060. }
  1061. /**
  1062. * Remove stream handling for firefox
  1063. * @param stream: webrtc media stream
  1064. */
  1065. _handleFirefoxRemoveStream(stream) {
  1066. if (!stream) { // There is nothing to be changed
  1067. return;
  1068. }
  1069. let sender = null;
  1070. // On Firefox we don't replace MediaStreams as this messes up the
  1071. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1072. // of complications. Instead, we use the RTPSender and remove just
  1073. // the track.
  1074. let track = null;
  1075. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  1076. track = stream.getAudioTracks()[0];
  1077. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  1078. track = stream.getVideoTracks()[0];
  1079. }
  1080. if (!track) {
  1081. const msg = 'Cannot remove tracks: no tracks.';
  1082. logger.log(msg);
  1083. return;
  1084. }
  1085. // Find the right sender (for audio or video)
  1086. this.peerconnection.peerconnection.getSenders().some(s => {
  1087. if (s.track === track) {
  1088. sender = s;
  1089. return true;
  1090. }
  1091. return false;
  1092. });
  1093. if (sender) {
  1094. this.peerconnection.peerconnection.removeTrack(sender);
  1095. } else {
  1096. logger.log('Cannot remove tracks: no RTPSender.');
  1097. }
  1098. }
  1099. /**
  1100. * Just remove the stream from the peerconnection
  1101. * @param {JitsiLocalTrack|MediaStream} stream the stream to remove
  1102. * NOTE: must be called within a work function being executed
  1103. * by the modification queue.
  1104. */
  1105. removeStreamFromPeerConnection(stream) {
  1106. const actualStream
  1107. = stream && stream.getOriginalStream
  1108. ? stream.getOriginalStream() : stream;
  1109. if (!this.peerconnection) {
  1110. return;
  1111. }
  1112. if (RTCBrowserType.getBrowserType()
  1113. === RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1114. this._handleFirefoxRemoveStream(actualStream);
  1115. } else if (actualStream) {
  1116. this.peerconnection.removeStream(actualStream);
  1117. }
  1118. }
  1119. /**
  1120. * Remove streams.
  1121. * @param stream stream that will be removed.
  1122. * @param callback callback executed after successful stream addition.
  1123. * @param errorCallback callback executed if stream addition fail.
  1124. * @param ssrcInfo object with information about the SSRCs associated with
  1125. * the stream.
  1126. */
  1127. removeStream(stream, callback, errorCallback, ssrcInfo) {
  1128. const workFunction = finishedCallback => {
  1129. if (!this.peerconnection) {
  1130. finishedCallback();
  1131. return;
  1132. }
  1133. if (RTCBrowserType.getBrowserType()
  1134. === RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1135. this._handleFirefoxRemoveStream(stream);
  1136. } else if (stream) {
  1137. this.removeStreamFromPeerConnection(stream);
  1138. }
  1139. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1140. this._renegotiate()
  1141. .then(() => {
  1142. const newSdp
  1143. = new SDP(this.peerconnection.localDescription.sdp);
  1144. if (ssrcInfo) {
  1145. this.modifiedSSRCs[ssrcInfo.type]
  1146. = this.modifiedSSRCs[ssrcInfo.type] || [];
  1147. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1148. }
  1149. logger.log('SDPs', oldSdp, newSdp);
  1150. this.notifyMySSRCUpdate(oldSdp, newSdp);
  1151. finishedCallback();
  1152. }, error => {
  1153. finishedCallback(error);
  1154. });
  1155. };
  1156. this.modificationQueue.push(
  1157. workFunction,
  1158. error => {
  1159. error ? errorCallback(error) : callback();
  1160. });
  1161. }
  1162. /**
  1163. * Figures out added/removed ssrcs and send update IQs.
  1164. * @param old_sdp SDP object for old description.
  1165. * @param new_sdp SDP object for new description.
  1166. */
  1167. notifyMySSRCUpdate(old_sdp, new_sdp) {
  1168. if (this.state !== JingleSessionState.ACTIVE) {
  1169. logger.warn(`Skipping SSRC update in '${this.state} ' state.`);
  1170. return;
  1171. }
  1172. // send source-remove IQ.
  1173. let sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  1174. const remove = $iq({to: this.peerjid, type: 'set'})
  1175. .c('jingle', {
  1176. xmlns: 'urn:xmpp:jingle:1',
  1177. action: 'source-remove',
  1178. initiator: this.initiator,
  1179. sid: this.sid
  1180. }
  1181. );
  1182. sdpDiffer.toJingle(remove);
  1183. const removed = this.fixJingle(remove);
  1184. if (removed && remove) {
  1185. logger.info('Sending source-remove', remove.tree());
  1186. this.connection.sendIQ(
  1187. remove, null,
  1188. this.newJingleErrorHandler(remove, error => {
  1189. GlobalOnErrorHandler.callErrorHandler(
  1190. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1191. }), IQ_TIMEOUT);
  1192. } else {
  1193. logger.log('removal not necessary');
  1194. }
  1195. // send source-add IQ.
  1196. sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  1197. const add = $iq({to: this.peerjid, type: 'set'})
  1198. .c('jingle', {
  1199. xmlns: 'urn:xmpp:jingle:1',
  1200. action: 'source-add',
  1201. initiator: this.initiator,
  1202. sid: this.sid
  1203. }
  1204. );
  1205. sdpDiffer.toJingle(add);
  1206. const added = this.fixJingle(add);
  1207. if (added && add) {
  1208. logger.info('Sending source-add', add.tree());
  1209. this.connection.sendIQ(
  1210. add, null, this.newJingleErrorHandler(add, error => {
  1211. GlobalOnErrorHandler.callErrorHandler(
  1212. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1213. }), IQ_TIMEOUT);
  1214. } else {
  1215. logger.log('addition not necessary');
  1216. }
  1217. }
  1218. /**
  1219. * Method returns function(errorResponse) which is a callback to be passed
  1220. * to Strophe connection.sendIQ method. An 'error' structure is created that
  1221. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1222. * structure is as follows:
  1223. * {
  1224. * code: {XMPP error response code}
  1225. * reason: {the name of XMPP error reason element or 'timeout' if the
  1226. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1227. * source: {request.tree() that provides original request}
  1228. * session: {JingleSessionPC instance on which the error occurred}
  1229. * }
  1230. * @param request Strophe IQ instance which is the request to be dumped into
  1231. * the error structure
  1232. * @param failureCb function(error) called when error response was returned
  1233. * or when a timeout has occurred.
  1234. * @returns {function(this:JingleSessionPC)}
  1235. */
  1236. newJingleErrorHandler(request, failureCb) {
  1237. return function(errResponse) {
  1238. const error = {};
  1239. // Get XMPP error code and condition(reason)
  1240. const errorElSel = $(errResponse).find('error');
  1241. if (errorElSel.length) {
  1242. error.code = errorElSel.attr('code');
  1243. const errorReasonSel = $(errResponse).find('error :first');
  1244. if (errorReasonSel.length) {
  1245. error.reason = errorReasonSel[0].tagName;
  1246. }
  1247. }
  1248. if (!errResponse) {
  1249. error.reason = 'timeout';
  1250. }
  1251. error.source = null;
  1252. if (request && 'function' == typeof request.tree) {
  1253. error.source = request.tree();
  1254. }
  1255. // Commented to fix JSON.stringify(error) exception for circular
  1256. // dependancies when we print that error.
  1257. // FIXME: Maybe we can include part of the session object
  1258. // error.session = this;
  1259. logger.error('Jingle error', error);
  1260. if (failureCb) {
  1261. failureCb(error);
  1262. }
  1263. };
  1264. }
  1265. static onJingleFatalError(session, error) {
  1266. if (this.room) {
  1267. this.room.eventEmitter.emit(
  1268. XMPPEvents.CONFERENCE_SETUP_FAILED, error);
  1269. this.room.eventEmitter.emit(
  1270. XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1271. }
  1272. }
  1273. /**
  1274. * @inheritDoc
  1275. */
  1276. getPeerMediaInfo(owner, mediaType) {
  1277. return this.room.getMediaPresenceInfo(owner, mediaType);
  1278. }
  1279. /**
  1280. * @inheritDoc
  1281. */
  1282. getSSRCOwner(ssrc) {
  1283. return this.ssrcOwners[ssrc];
  1284. }
  1285. /**
  1286. * Returns the ice connection state for the peer connection.
  1287. * @returns the ice connection state for the peer connection.
  1288. */
  1289. getIceConnectionState() {
  1290. return this.peerconnection.iceConnectionState;
  1291. }
  1292. /**
  1293. * Closes the peerconnection.
  1294. */
  1295. close() {
  1296. this.closed = true;
  1297. // do not try to close if already closed.
  1298. this.peerconnection
  1299. && ((this.peerconnection.signalingState
  1300. && this.peerconnection.signalingState !== 'closed')
  1301. || (this.peerconnection.connectionState
  1302. && this.peerconnection.connectionState !== 'closed'))
  1303. && this.peerconnection.close();
  1304. }
  1305. /**
  1306. * Fixes the outgoing jingle packets by removing the nodes related to the
  1307. * muted/unmuted streams, handles removing of muted stream, etc.
  1308. * @param jingle the jingle packet that is going to be sent
  1309. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1310. */
  1311. fixJingle(jingle) {
  1312. // eslint-disable-next-line newline-per-chained-call
  1313. const action = $(jingle.nodeTree).find('jingle').attr('action');
  1314. switch (action) {
  1315. case 'source-add':
  1316. case 'session-accept':
  1317. this.fixSourceAddJingle(jingle);
  1318. break;
  1319. case 'source-remove':
  1320. this.fixSourceRemoveJingle(jingle);
  1321. break;
  1322. default: {
  1323. const errmsg = 'Unknown jingle action!';
  1324. GlobalOnErrorHandler.callErrorHandler(errmsg);
  1325. logger.error(errmsg);
  1326. return false;
  1327. }
  1328. }
  1329. const sources
  1330. = $(jingle.tree()).find('>jingle>content>description>source');
  1331. return sources && sources.length > 0;
  1332. }
  1333. /**
  1334. * Fixes the outgoing jingle packets with action source-add by removing the
  1335. * nodes related to the unmuted streams
  1336. * @param jingle the jingle packet that is going to be sent
  1337. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1338. */
  1339. fixSourceAddJingle(jingle) {
  1340. let ssrcs = this.modifiedSSRCs.unmute;
  1341. this.modifiedSSRCs.unmute = [];
  1342. if (ssrcs && ssrcs.length) {
  1343. ssrcs.forEach(ssrcObj => {
  1344. const desc
  1345. = $(jingle.tree()).find(
  1346. `>jingle>content[name="${ssrcObj.mtype}"]>description`);
  1347. if (!desc || !desc.length) {
  1348. return;
  1349. }
  1350. ssrcObj.ssrcs.forEach(ssrc => {
  1351. const sourceNode = desc.find(`>source[ssrc="${ssrc}"]`);
  1352. sourceNode.remove();
  1353. });
  1354. ssrcObj.groups.forEach(group => {
  1355. const groupNode = desc.find(`>ssrc-group[semantics="${
  1356. group.semantics}"]:has(source[ssrc="${
  1357. group.ssrcs[0]}"])`);
  1358. groupNode.remove();
  1359. });
  1360. });
  1361. }
  1362. ssrcs = this.modifiedSSRCs.addMuted;
  1363. this.modifiedSSRCs.addMuted = [];
  1364. if (ssrcs && ssrcs.length) {
  1365. ssrcs.forEach(ssrcObj => {
  1366. const desc
  1367. = JingleSessionPC.createDescriptionNode(
  1368. jingle, ssrcObj.mtype);
  1369. // eslint-disable-next-line newline-per-chained-call
  1370. const cname = Math.random().toString(36).substring(2);
  1371. ssrcObj.ssrcs.forEach(ssrc => {
  1372. const sourceNode
  1373. = desc.find(`>source[ssrc="${ssrc}"]`);
  1374. sourceNode.remove();
  1375. const sourceXML
  1376. = '<source xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1377. + ` ssrc="${ssrc}">`
  1378. + '<parameter xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1379. + ` value="${ssrcObj.msid}" name="msid"/>`
  1380. + '<parameter xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1381. + ` value="${cname}" name="cname" />`
  1382. + '</source>';
  1383. desc.append(sourceXML);
  1384. });
  1385. ssrcObj.groups.forEach(group => {
  1386. const groupNode
  1387. = desc.find(
  1388. `>ssrc-group[semantics="${group.semantics
  1389. }"]:has(source[ssrc="${group.ssrcs[0]}"])`);
  1390. groupNode.remove();
  1391. desc.append(
  1392. `<ssrc-group semantics="${group.semantics
  1393. }" xmlns="urn:xmpp:jingle:apps:rtp:ssma:0">`
  1394. + `<source ssrc="${group.ssrcs.join('"/><source ssrc="')
  1395. }"/></ssrc-group>`);
  1396. });
  1397. });
  1398. }
  1399. }
  1400. /**
  1401. * Fixes the outgoing jingle packets with action source-remove by removing
  1402. * the nodes related to the muted streams, handles removing of muted stream
  1403. * @param jingle the jingle packet that is going to be sent
  1404. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1405. */
  1406. fixSourceRemoveJingle(jingle) {
  1407. let ssrcs = this.modifiedSSRCs.mute;
  1408. this.modifiedSSRCs.mute = [];
  1409. if (ssrcs && ssrcs.length) {
  1410. ssrcs.forEach(ssrcObj => {
  1411. ssrcObj.ssrcs.forEach(ssrc => {
  1412. const sourceNode
  1413. = $(jingle.tree()).find(
  1414. `>jingle>content[name="${ssrcObj.mtype
  1415. }"]>description>source[ssrc="${ssrc}"]`);
  1416. sourceNode.remove();
  1417. });
  1418. ssrcObj.groups.forEach(group => {
  1419. const groupNode
  1420. = $(jingle.tree()).find(
  1421. `>jingle>content[name="${ssrcObj.mtype
  1422. }"]>description>ssrc-group[semantics="${
  1423. group.semantics}"]:has(source[ssrc="${
  1424. group.ssrcs[0]}"])`);
  1425. groupNode.remove();
  1426. });
  1427. });
  1428. }
  1429. ssrcs = this.modifiedSSRCs.remove;
  1430. this.modifiedSSRCs.remove = [];
  1431. if (ssrcs && ssrcs.length) {
  1432. ssrcs.forEach(ssrcObj => {
  1433. const desc
  1434. = JingleSessionPC.createDescriptionNode(
  1435. jingle, ssrcObj.mtype);
  1436. ssrcObj.ssrcs.forEach(ssrc => {
  1437. const sourceNode
  1438. = desc.find(`>source[ssrc="${ssrc}"]`);
  1439. if (!sourceNode || !sourceNode.length) {
  1440. // Maybe we have to include cname, msid, etc here?
  1441. desc.append(
  1442. '<source xmlns="urn:xmpp:jingle:apps:rtp:ssma:0" '
  1443. + `ssrc="${ssrc}"></source>`);
  1444. }
  1445. });
  1446. ssrcObj.groups.forEach(group => {
  1447. const groupNode
  1448. = desc.find(`>ssrc-group[semantics="${
  1449. group.semantics}"]:has(source[ssrc="${
  1450. group.ssrcs[0]}"])`);
  1451. if (!groupNode || !groupNode.length) {
  1452. desc.append(
  1453. `<ssrc-group semantics="${group.semantics
  1454. }" xmlns="urn:xmpp:jingle:apps:rtp:ssma:0">`
  1455. + `<source ssrc="${
  1456. group.ssrcs.join('"/><source ssrc="')}"/>`
  1457. + '</ssrc-group>');
  1458. }
  1459. });
  1460. });
  1461. }
  1462. }
  1463. /**
  1464. * Returns the description node related to the passed content type. If the
  1465. * node doesn't exists it will be created.
  1466. * @param jingle - the jingle packet
  1467. * @param mtype - the content type(audio, video, etc.)
  1468. */
  1469. static createDescriptionNode(jingle, mtype) {
  1470. let content = $(jingle.tree()).find(`>jingle>content[name="${mtype}"]`);
  1471. if (!content || !content.length) {
  1472. $(jingle.tree())
  1473. .find('>jingle')
  1474. .append(`<content name="${mtype}"></content>`);
  1475. content = $(jingle.tree()).find(`>jingle>content[name="${mtype}"]`);
  1476. }
  1477. let desc = content.find('>description');
  1478. if (!desc || !desc.length) {
  1479. content.append(
  1480. `<description xmlns="urn:xmpp:jingle:apps:rtp:1" media="${
  1481. mtype}"></description>`);
  1482. desc = content.find('>description');
  1483. }
  1484. return desc;
  1485. }
  1486. /**
  1487. * Extracts the ice username fragment from an SDP string.
  1488. */
  1489. static getUfrag(sdp) {
  1490. const ufragLines
  1491. = sdp.split('\n').filter(line => line.startsWith('a=ice-ufrag:'));
  1492. if (ufragLines.length > 0) {
  1493. return ufragLines[0].substr('a=ice-ufrag:'.length);
  1494. }
  1495. }
  1496. }