Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JingleSessionPC.js 81KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200
  1. /* global __filename, $, $iq, Strophe */
  2. import async from 'async';
  3. import { getLogger } from 'jitsi-meet-logger';
  4. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  5. import JingleSession from './JingleSession';
  6. import SDP from './SDP';
  7. import SDPDiffer from './SDPDiffer';
  8. import SDPUtil from './SDPUtil';
  9. import SignalingLayerImpl from './SignalingLayerImpl';
  10. import Statistics from '../statistics/statistics';
  11. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  12. import * as JingleSessionState from './JingleSessionState';
  13. const logger = getLogger(__filename);
  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. /**
  21. *
  22. */
  23. export default class JingleSessionPC extends JingleSession {
  24. /**
  25. * Parses 'senders' attribute of the video content.
  26. * @param {jQuery} jingleContents
  27. * @return {string|null} one of the values of content "senders" attribute
  28. * defined by Jingle. If there is no "senders" attribute or if the value is
  29. * invalid then <tt>null</tt> will be returned.
  30. * @private
  31. */
  32. static parseVideoSenders(jingleContents) {
  33. const videoContents = jingleContents.find('>content[name="video"]');
  34. if (videoContents.length) {
  35. const senders = videoContents[0].getAttribute('senders');
  36. if (senders === 'both'
  37. || senders === 'initiator'
  38. || senders === 'responder'
  39. || senders === 'none') {
  40. return senders;
  41. }
  42. }
  43. return null;
  44. }
  45. /* eslint-disable max-params */
  46. /**
  47. * Creates new <tt>JingleSessionPC</tt>
  48. * @param {string} sid the Jingle Session ID - random string which
  49. * identifies the session
  50. * @param {string} me our JID
  51. * @param {string} peerjid remote peer JID
  52. * @param {Strophe.Connection} connection Strophe XMPP connection instance
  53. * used to send packets.
  54. * @param mediaConstraints the media constraints object passed to
  55. * createOffer/Answer, as defined by the WebRTC standard
  56. * @param iceConfig the ICE servers config object as defined by the WebRTC
  57. * standard.
  58. * @param {boolean} isP2P indicates whether this instance is
  59. * meant to be used in a direct, peer to peer connection or <tt>false</tt>
  60. * if it's a JVB connection.
  61. * @param {boolean} isInitiator indicates whether or not we are the side
  62. * which sends the 'session-intiate'.
  63. * @param {object} options a set of config options
  64. * @param {boolean} options.webrtcIceUdpDisable <tt>true</tt> to block UDP
  65. * candidates.
  66. * @param {boolean} options.webrtcIceTcpDisable <tt>true</tt> to block TCP
  67. * candidates.
  68. * @param {boolean} options.failICE it's an option used in the tests. Set to
  69. * <tt>true</tt> to block any real candidates and make the ICE fail.
  70. *
  71. * @constructor
  72. *
  73. * @implements {SignalingLayer}
  74. */
  75. constructor(
  76. sid,
  77. me,
  78. peerjid,
  79. connection,
  80. mediaConstraints,
  81. iceConfig,
  82. isP2P,
  83. isInitiator,
  84. options) {
  85. super(sid, me, peerjid, connection, mediaConstraints, iceConfig);
  86. /**
  87. * Stores result of {@link window.performance.now()} at the time when
  88. * ICE enters 'checking' state.
  89. * @type {number|null} null if no value has been stored yet
  90. * @private
  91. */
  92. this._iceCheckingStartedTimestamp = null;
  93. /**
  94. * Stores result of {@link window.performance.now()} at the time when
  95. * first ICE candidate is spawned by the peerconnection to mark when
  96. * ICE gathering started. That's, because ICE gathering state changed
  97. * events are not supported by most of the browsers, so we try something
  98. * that will work everywhere. It may not be as accurate, but given that
  99. * 'host' candidate usually comes first, the delay should be minimal.
  100. * @type {number|null} null if no value has been stored yet
  101. * @private
  102. */
  103. this._gatheringStartedTimestamp = null;
  104. /**
  105. * Indicates whether or not this session is willing to send/receive
  106. * video media. When set to <tt>false</tt> the underlying peer
  107. * connection will disable local video transfer and the remote peer will
  108. * be will be asked to stop sending video via 'content-modify' IQ
  109. * (the senders attribute of video contents will be adjusted
  110. * accordingly). Note that this notification is sent only in P2P
  111. * session, because Jicofo does not support it yet. Obviously when
  112. * the value is changed from <tt>false</tt> to <tt>true</tt> another
  113. * notification will be sent to resume video transfer on the remote
  114. * side.
  115. * @type {boolean}
  116. * @private
  117. */
  118. this._localVideoActive = true;
  119. /**
  120. * Indicates whether or not the remote peer has video transfer active.
  121. * When set to <tt>true</tt> it means that remote peer is neither
  122. * sending nor willing to receive video. In such case we'll ask
  123. * our peerconnection to stop sending video by calling
  124. * {@link TraceablePeerConnection.setVideoTransferActive} with
  125. * <tt>false</tt>.
  126. * @type {boolean}
  127. * @private
  128. */
  129. this._remoteVideoActive = true;
  130. /**
  131. * Marks that ICE gathering duration has been reported already. That
  132. * prevents reporting it again, after eventual 'transport-replace' (JVB
  133. * conference migration/ICE restart).
  134. * @type {boolean}
  135. * @private
  136. */
  137. this._gatheringReported = false;
  138. /**
  139. * WebSocket URL for the bridge channel with the videobridge.
  140. * @type {string}
  141. */
  142. this.bridgeWebSocketUrl = null;
  143. this.lasticecandidate = false;
  144. this.closed = false;
  145. /**
  146. * Indicates whether this instance is an initiator or an answerer of
  147. * the Jingle session.
  148. * @type {boolean}
  149. */
  150. this.isInitiator = isInitiator;
  151. /**
  152. * Indicates whether or not this <tt>JingleSessionPC</tt> is used in
  153. * a peer to peer type of session.
  154. * @type {boolean} <tt>true</tt> if it's a peer to peer
  155. * session or <tt>false</tt> if it's a JVB session
  156. */
  157. this.isP2P = isP2P;
  158. /**
  159. * The signaling layer implementation.
  160. * @type {SignalingLayerImpl}
  161. */
  162. this.signalingLayer = new SignalingLayerImpl();
  163. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  164. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  165. /**
  166. * Flag used to enforce ICE failure through the URL parameter for
  167. * the automatic testing purpose.
  168. * @type {boolean}
  169. */
  170. this.failICE = Boolean(options.failICE);
  171. this.modificationQueue
  172. = async.queue(this._processQueueTasks.bind(this), 1);
  173. /**
  174. * Flag used to guarantee that the connection established event is
  175. * triggered just once.
  176. * @type {boolean}
  177. */
  178. this.wasConnected = false;
  179. /**
  180. * Keeps track of how long (in ms) it took from ICE start to ICE
  181. * connect.
  182. *
  183. * @type {number}
  184. */
  185. this.establishmentDuration = undefined;
  186. }
  187. /* eslint-enable max-params */
  188. /**
  189. * Checks whether or not this session instance has been ended and eventually
  190. * logs a message which mentions that given <tt>actionName</tt> was
  191. * cancelled.
  192. * @param {string} actionName
  193. * @return {boolean} <tt>true</tt> if this {@link JingleSessionPC} has
  194. * entered {@link JingleSessionState.ENDED} or <tt>false</tt> otherwise.
  195. * @private
  196. */
  197. _assertNotEnded(actionName) {
  198. if (this.state === JingleSessionState.ENDED) {
  199. logger.log(
  200. `The session has ended - cancelling action: ${actionName}`);
  201. return false;
  202. }
  203. return true;
  204. }
  205. /**
  206. *
  207. */
  208. doInitialize() {
  209. this.lasticecandidate = false;
  210. // True if reconnect is in progress
  211. this.isreconnect = false;
  212. // Set to true if the connection was ever stable
  213. this.wasstable = false;
  214. // Create new peer connection instance
  215. if (this.isP2P) {
  216. this.peerconnection = this.rtc.createPeerConnection(
  217. this.signalingLayer,
  218. this.iceConfig,
  219. this.isP2P,
  220. {
  221. // simulcast needs to be disabled for P2P (121) calls
  222. disableSimulcast: true,
  223. disableRtx: this.room.options.disableRtx,
  224. preferH264: this.room.options.p2p
  225. && this.room.options.p2p.preferH264
  226. });
  227. } else {
  228. this.peerconnection = this.rtc.createPeerConnection(
  229. this.signalingLayer,
  230. this.iceConfig,
  231. this.isP2P,
  232. {
  233. // H264 does not support simulcast, so it needs to be
  234. // disabled.
  235. disableSimulcast: this.room.options.disableSimulcast
  236. || this.room.options.preferH264,
  237. disableRtx: this.room.options.disableRtx,
  238. preferH264: this.room.options.preferH264,
  239. enableFirefoxSimulcast: this.room.options.testing
  240. && this.room.options.testing.enableFirefoxSimulcast
  241. });
  242. }
  243. this.peerconnection.onicecandidate = ev => {
  244. if (!ev) {
  245. // There was an incomplete check for ev before which left
  246. // the last line of the function unprotected from a potential
  247. // throw of an exception. Consequently, it may be argued that
  248. // the check is unnecessary. Anyway, I'm leaving it and making
  249. // the check complete.
  250. return;
  251. }
  252. // XXX this is broken, candidate is not parsed.
  253. const candidate = ev.candidate;
  254. const now = window.performance.now();
  255. if (candidate) {
  256. if (this._gatheringStartedTimestamp === null) {
  257. this._gatheringStartedTimestamp = now;
  258. }
  259. // Discard candidates of disabled protocols.
  260. let protocol = candidate.protocol;
  261. if (typeof protocol === 'string') {
  262. protocol = protocol.toLowerCase();
  263. if (protocol === 'tcp' || protocol === 'ssltcp') {
  264. if (this.webrtcIceTcpDisable) {
  265. return;
  266. }
  267. } else if (protocol === 'udp') {
  268. if (this.webrtcIceUdpDisable) {
  269. return;
  270. }
  271. }
  272. }
  273. } else if (!this._gatheringReported) {
  274. // End of gathering
  275. let eventName = this.isP2P ? 'p2p.ice.' : 'ice.';
  276. eventName += this.isInitiator ? 'initiator' : 'responder';
  277. eventName += '.gatheringDuration';
  278. Statistics.analytics.sendEvent(
  279. eventName,
  280. { value: now - this._gatheringStartedTimestamp });
  281. this._gatheringReported = true;
  282. }
  283. this.sendIceCandidate(candidate);
  284. };
  285. // Note there is a change in the spec about closed:
  286. // This value moved into the RTCPeerConnectionState enum in
  287. // the May 13, 2016 draft of the specification, as it reflects the state
  288. // of the RTCPeerConnection, not the signaling connection. You now
  289. // detect a closed connection by checking for connectionState to be
  290. // "closed" instead.
  291. // I suppose at some point this will be moved to onconnectionstatechange
  292. this.peerconnection.onsignalingstatechange = () => {
  293. if (!this.peerconnection) {
  294. return;
  295. }
  296. if (this.peerconnection.signalingState === 'stable') {
  297. this.wasstable = true;
  298. } else if (
  299. (this.peerconnection.signalingState === 'closed'
  300. || this.peerconnection.connectionState === 'closed')
  301. && !this.closed) {
  302. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED, this);
  303. }
  304. };
  305. /**
  306. * The oniceconnectionstatechange event handler contains the code to
  307. * execute when the iceconnectionstatechange event, of type Event,
  308. * is received by this RTCPeerConnection. Such an event is sent when
  309. * the value of RTCPeerConnection.iceConnectionState changes.
  310. */
  311. this.peerconnection.oniceconnectionstatechange = () => {
  312. if (!this.peerconnection
  313. || !this._assertNotEnded('oniceconnectionstatechange')) {
  314. return;
  315. }
  316. const now = window.performance.now();
  317. if (!this.isP2P) {
  318. this.room.connectionTimes[
  319. `ice.state.${this.peerconnection.iceConnectionState}`]
  320. = now;
  321. }
  322. logger.log(
  323. `(TIME) ICE ${this.peerconnection.iceConnectionState}`
  324. + ` P2P? ${this.isP2P}:\t`,
  325. now);
  326. Statistics.analytics.sendEvent(
  327. `${this.isP2P ? 'p2p.ice.' : 'ice.'}`
  328. + `${this.peerconnection.iceConnectionState}`,
  329. { value: now });
  330. this.room.eventEmitter.emit(
  331. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  332. this,
  333. this.peerconnection.iceConnectionState);
  334. switch (this.peerconnection.iceConnectionState) {
  335. case 'checking':
  336. this._iceCheckingStartedTimestamp = now;
  337. break;
  338. case 'connected':
  339. // Informs interested parties that the connection has been
  340. // restored.
  341. if (this.peerconnection.signalingState === 'stable') {
  342. if (this.isreconnect) {
  343. this.room.eventEmitter.emit(
  344. XMPPEvents.CONNECTION_RESTORED, this);
  345. }
  346. }
  347. if (!this.wasConnected && this.wasstable) {
  348. let eventName = this.isP2P ? 'p2p.ice.' : 'ice.';
  349. eventName += this.isInitiator ? 'initiator.' : 'responder.';
  350. Statistics.analytics.sendEvent(
  351. `${eventName}checksDuration`,
  352. {
  353. value: now - this._iceCheckingStartedTimestamp
  354. });
  355. // Switch between ICE gathering and ICE checking whichever
  356. // started first (scenarios are different for initiator
  357. // vs responder)
  358. const iceStarted
  359. = Math.min(
  360. this._iceCheckingStartedTimestamp,
  361. this._gatheringStartedTimestamp);
  362. this.establishmentDuration = now - iceStarted;
  363. Statistics.analytics.sendEvent(
  364. `${eventName}establishmentDuration`,
  365. {
  366. value: this.establishmentDuration
  367. });
  368. this.wasConnected = true;
  369. this.room.eventEmitter.emit(
  370. XMPPEvents.CONNECTION_ESTABLISHED, this);
  371. }
  372. this.isreconnect = false;
  373. break;
  374. case 'disconnected':
  375. if (this.closed) {
  376. break;
  377. }
  378. this.isreconnect = true;
  379. // Informs interested parties that the connection has been
  380. // interrupted.
  381. if (this.wasstable) {
  382. this.room.eventEmitter.emit(
  383. XMPPEvents.CONNECTION_INTERRUPTED, this);
  384. }
  385. break;
  386. case 'failed':
  387. this.room.eventEmitter.emit(
  388. XMPPEvents.CONNECTION_ICE_FAILED, this);
  389. this.room.eventEmitter.emit(
  390. XMPPEvents.CONFERENCE_SETUP_FAILED,
  391. this,
  392. new Error('ICE fail'));
  393. break;
  394. }
  395. };
  396. this.peerconnection.onnegotiationneeded = () => {
  397. this.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, this);
  398. };
  399. // The signaling layer will bind it's listeners at this point
  400. this.signalingLayer.setChatRoom(this.room);
  401. }
  402. /**
  403. * Sends given candidate in Jingle 'transport-info' message.
  404. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  405. * @private
  406. */
  407. sendIceCandidate(candidate) {
  408. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  409. if (candidate && !this.lasticecandidate) {
  410. const ice
  411. = SDPUtil.iceparams(
  412. localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  413. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  414. if (!(ice && jcand)) {
  415. const errorMesssage = 'failed to get ice && jcand';
  416. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  417. logger.error(errorMesssage);
  418. return;
  419. }
  420. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  421. if (this.usedrip) {
  422. if (this.dripContainer.length === 0) {
  423. // start 20ms callout
  424. setTimeout(() => {
  425. if (this.dripContainer.length === 0) {
  426. return;
  427. }
  428. this.sendIceCandidates(this.dripContainer);
  429. this.dripContainer = [];
  430. }, 20);
  431. }
  432. this.dripContainer.push(candidate);
  433. } else {
  434. this.sendIceCandidates([ candidate ]);
  435. }
  436. } else {
  437. logger.log('sendIceCandidate: last candidate.');
  438. // FIXME: remember to re-think in ICE-restart
  439. this.lasticecandidate = true;
  440. }
  441. }
  442. /**
  443. * Sends given candidates in Jingle 'transport-info' message.
  444. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE
  445. * candidate instances
  446. * @private
  447. */
  448. sendIceCandidates(candidates) {
  449. if (!this._assertNotEnded('sendIceCandidates')) {
  450. return;
  451. }
  452. logger.log('sendIceCandidates', candidates);
  453. const cand = $iq({ to: this.peerjid,
  454. type: 'set' })
  455. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  456. action: 'transport-info',
  457. initiator: this.initiator,
  458. sid: this.sid });
  459. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  460. for (let mid = 0; mid < localSDP.media.length; mid++) {
  461. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  462. const mline
  463. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  464. if (cands.length > 0) {
  465. const ice
  466. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  467. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  468. cand.c('content', {
  469. creator: this.initiator === this.localJid
  470. ? 'initiator' : 'responder',
  471. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  472. }).c('transport', ice);
  473. for (let i = 0; i < cands.length; i++) {
  474. const candidate
  475. = SDPUtil.candidateToJingle(cands[i].candidate);
  476. // Mangle ICE candidate if 'failICE' test option is enabled
  477. if (this.failICE) {
  478. candidate.ip = '1.1.1.1';
  479. }
  480. cand.c('candidate', candidate).up();
  481. }
  482. // add fingerprint
  483. const fingerprintLine
  484. = SDPUtil.findLine(
  485. localSDP.media[mid],
  486. 'a=fingerprint:', localSDP.session);
  487. if (fingerprintLine) {
  488. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  489. tmp.required = true;
  490. cand.c(
  491. 'fingerprint',
  492. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  493. .t(tmp.fingerprint);
  494. delete tmp.fingerprint;
  495. cand.attrs(tmp);
  496. cand.up();
  497. }
  498. cand.up(); // transport
  499. cand.up(); // content
  500. }
  501. }
  502. // might merge last-candidate notification into this, but it is called
  503. // a lot later. See webrtc issue #2340
  504. // logger.log('was this the last candidate', this.lasticecandidate);
  505. this.connection.sendIQ(
  506. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  507. }
  508. /**
  509. * {@inheritDoc}
  510. */
  511. addIceCandidates(elem) {
  512. if (this.peerconnection.signalingState === 'closed') {
  513. logger.warn('Ignored add ICE candidate when in closed state');
  514. return;
  515. }
  516. const iceCandidates = [];
  517. elem.find('>content>transport>candidate')
  518. .each((idx, candidate) => {
  519. let line = SDPUtil.candidateFromJingle(candidate);
  520. line = line.replace('\r\n', '').replace('a=', '');
  521. // FIXME this code does not care to handle
  522. // non-bundle transport
  523. const rtcCandidate = new RTCIceCandidate({
  524. sdpMLineIndex: 0,
  525. // FF comes up with more complex names like audio-23423,
  526. // Given that it works on both Chrome and FF without
  527. // providing it, let's leave it like this for the time
  528. // being...
  529. // sdpMid: 'audio',
  530. sdpMid: '',
  531. candidate: line
  532. });
  533. iceCandidates.push(rtcCandidate);
  534. });
  535. if (!iceCandidates.length) {
  536. logger.error(
  537. 'No ICE candidates to add ?', elem[0] && elem[0].outerHTML);
  538. return;
  539. }
  540. // We want to have this task queued, so that we know it is executed,
  541. // after the initial sRD/sLD offer/answer cycle was done (based on
  542. // the assumption that candidates are spawned after the offer/answer
  543. // and XMPP preserves order).
  544. const workFunction = finishedCallback => {
  545. for (const iceCandidate of iceCandidates) {
  546. this.peerconnection.addIceCandidate(
  547. iceCandidate,
  548. () => {
  549. logger.debug('addIceCandidate ok!');
  550. },
  551. error => {
  552. logger.error('addIceCandidate failed!', error);
  553. });
  554. }
  555. finishedCallback();
  556. };
  557. logger.debug(
  558. `Queued add (${iceCandidates.length}) ICE candidates task...`);
  559. this.modificationQueue.push(workFunction);
  560. }
  561. /**
  562. *
  563. * @param contents
  564. */
  565. readSsrcInfo(contents) {
  566. const ssrcs
  567. = $(contents).find(
  568. '>description>'
  569. + 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  570. ssrcs.each((i, ssrcElement) => {
  571. const ssrc = Number(ssrcElement.getAttribute('ssrc'));
  572. if (this.isP2P) {
  573. // In P2P all SSRCs are owner by the remote peer
  574. this.signalingLayer.setSSRCOwner(
  575. ssrc, Strophe.getResourceFromJid(this.peerjid));
  576. } else {
  577. $(ssrcElement)
  578. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  579. .each((i3, ssrcInfoElement) => {
  580. const owner = ssrcInfoElement.getAttribute('owner');
  581. if (owner && owner.length) {
  582. if (isNaN(ssrc) || ssrc < 0) {
  583. logger.warn(
  584. `Invalid SSRC ${ssrc} value received`
  585. + ` for ${owner}`);
  586. } else {
  587. this.signalingLayer.setSSRCOwner(
  588. ssrc, Strophe.getResourceFromJid(owner));
  589. }
  590. }
  591. });
  592. }
  593. });
  594. }
  595. /**
  596. * Reads the "url" parameter in the <web-socket> tag of the jingle offer iq
  597. * and stores it into this.bridgeWebSocketUrl.
  598. * @param contets
  599. */
  600. readBridgeWebSocketUrl(contents) {
  601. const webSocket
  602. = $(contents)
  603. .find('transport>web-socket')
  604. .first();
  605. if (webSocket.length === 1) {
  606. this.bridgeWebSocketUrl = webSocket[0].getAttribute('url');
  607. }
  608. }
  609. /**
  610. * Makes the underlying TraceablePeerConnection generate new SSRC for
  611. * the recvonly video stream.
  612. * @deprecated
  613. */
  614. generateRecvonlySsrc() {
  615. if (this.peerconnection) {
  616. this.peerconnection.generateRecvonlySsrc();
  617. } else {
  618. logger.error(
  619. 'Unable to generate recvonly SSRC - no peerconnection');
  620. }
  621. }
  622. /* eslint-disable max-params */
  623. /**
  624. * Accepts incoming Jingle 'session-initiate' and should send
  625. * 'session-accept' in result.
  626. * @param jingleOffer jQuery selector pointing to the jingle element of
  627. * the offer IQ
  628. * @param success callback called when we accept incoming session
  629. * successfully and receive RESULT packet to 'session-accept' sent.
  630. * @param failure function(error) called if for any reason we fail to accept
  631. * the incoming offer. 'error' argument can be used to log some details
  632. * about the error.
  633. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
  634. * the local tracks that will be added, before the offer/answer cycle
  635. * executes. We allow the localTracks to optionally be passed in so that
  636. * the addition of the local tracks and the processing of the initial offer
  637. * can all be done atomically. We want to make sure that any other
  638. * operations which originate in the XMPP Jingle messages related with
  639. * this session to be executed with an assumption that the initial
  640. * offer/answer cycle has been executed already.
  641. */
  642. acceptOffer(jingleOffer, success, failure, localTracks) {
  643. this.setOfferAnswerCycle(
  644. jingleOffer,
  645. () => {
  646. // FIXME we may not care about RESULT packet for session-accept
  647. // then we should either call 'success' here immediately or
  648. // modify sendSessionAccept method to do that
  649. this.sendSessionAccept(success, failure);
  650. },
  651. failure,
  652. localTracks);
  653. }
  654. /* eslint-enable max-params */
  655. /**
  656. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  657. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be
  658. * added, before the offer/answer cycle executes (for the local track
  659. * addition to be an atomic operation together with the offer/answer).
  660. */
  661. invite(localTracks) {
  662. if (!this.isInitiator) {
  663. throw new Error('Trying to invite from the responder session');
  664. }
  665. const workFunction = finishedCallback => {
  666. for (const localTrack of localTracks) {
  667. this.peerconnection.addTrack(localTrack);
  668. }
  669. this.peerconnection.createOffer(
  670. sdp => {
  671. this.sendSessionInitiate(
  672. sdp,
  673. finishedCallback,
  674. finishedCallback
  675. );
  676. },
  677. error => {
  678. logger.error(
  679. 'Failed to create an offer',
  680. error,
  681. this.mediaConstraints);
  682. finishedCallback(error);
  683. },
  684. this.mediaConstraints);
  685. };
  686. this.modificationQueue.push(
  687. workFunction,
  688. error => {
  689. if (error) {
  690. logger.error('invite error', error);
  691. } else {
  692. logger.debug('invite executed - OK');
  693. }
  694. });
  695. }
  696. /**
  697. * Sends 'session-initiate' to the remote peer.
  698. * @param {object} sdp the local session description object as defined by
  699. * the WebRTC standard.
  700. * @param {function} success executed when the operation succeeds.
  701. * @param {function(error)} failure executed when the operation fails with
  702. * an error passed as an argument.
  703. * @private
  704. */
  705. sendSessionInitiate(sdp, success, failure) {
  706. logger.log('createdOffer', sdp);
  707. const sendJingle = () => {
  708. let init = $iq({
  709. to: this.peerjid,
  710. type: 'set'
  711. }).c('jingle', {
  712. xmlns: 'urn:xmpp:jingle:1',
  713. action: 'session-initiate',
  714. initiator: this.initiator,
  715. sid: this.sid
  716. });
  717. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  718. localSDP.toJingle(
  719. init,
  720. this.initiator === this.me ? 'initiator' : 'responder');
  721. init = init.tree();
  722. logger.info('Session-initiate: ', init);
  723. this.connection.sendIQ(init,
  724. () => {
  725. logger.info('Got RESULT for "session-initiate"');
  726. },
  727. error => {
  728. logger.error('"session-initiate" error', error);
  729. },
  730. IQ_TIMEOUT);
  731. // NOTE the callback is executed immediately as we don't want to
  732. // wait for the XMPP response which would delay the startup process.
  733. success();
  734. };
  735. this.peerconnection.setLocalDescription(
  736. sdp, sendJingle,
  737. error => {
  738. logger.error('session-init setLocalDescription failed', error);
  739. failure(error);
  740. }
  741. );
  742. }
  743. /**
  744. * Sets the answer received from the remote peer.
  745. * @param jingleAnswer
  746. */
  747. setAnswer(jingleAnswer) {
  748. if (!this.isInitiator) {
  749. throw new Error('Trying to set an answer on the responder session');
  750. }
  751. this.setOfferAnswerCycle(
  752. jingleAnswer,
  753. () => {
  754. logger.info('setAnswer - succeeded');
  755. },
  756. error => {
  757. logger.error('setAnswer failed: ', error);
  758. });
  759. }
  760. /* eslint-disable max-params */
  761. /**
  762. * This is a setRemoteDescription/setLocalDescription cycle which starts at
  763. * converting Strophe Jingle IQ into remote offer SDP. Once converted
  764. * setRemoteDescription, createAnswer and setLocalDescription calls follow.
  765. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element
  766. * of the offer (or answer) IQ
  767. * @param success callback called when sRD/sLD cycle finishes successfully.
  768. * @param failure callback called with an error object as an argument if we
  769. * fail at any point during setRD, createAnswer, setLD.
  770. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
  771. * the local tracks that will be added, before the offer/answer cycle
  772. * executes (for the local track addition to be an atomic operation together
  773. * with the offer/answer).
  774. */
  775. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks) {
  776. const workFunction = finishedCallback => {
  777. if (localTracks) {
  778. for (const track of localTracks) {
  779. this.peerconnection.addTrack(track);
  780. }
  781. }
  782. const newRemoteSdp
  783. = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  784. const oldLocalSdp
  785. = this.peerconnection.localDescription.sdp;
  786. this._renegotiate(newRemoteSdp.raw)
  787. .then(() => {
  788. if (this.state === JingleSessionState.PENDING) {
  789. this.state = JingleSessionState.ACTIVE;
  790. // Sync up video transfer active/inactive only after
  791. // the initial O/A cycle. We want to adjust the video
  792. // media direction only in the local SDP and the Jingle
  793. // contents direction included in the initial
  794. // offer/answer is mapped to the remote SDP. Jingle
  795. // 'content-modify' IQ is processed in a way that it
  796. // will only modify local SDP when remote peer is no
  797. // longer interested in receiving video content.
  798. // Changing media direction in the remote SDP will mess
  799. // up our SDP translation chain (simulcast, video mute,
  800. // RTX etc.)
  801. if (this.isP2P && !this._localVideoActive) {
  802. this.sendContentModify(this._localVideoActive);
  803. }
  804. }
  805. // Old local SDP will be available when we're setting answer
  806. // for the first time, but not when offer and it's fine
  807. // since we're generating an answer now it will contain all
  808. // our SSRCs
  809. if (oldLocalSdp) {
  810. const newLocalSdp
  811. = new SDP(this.peerconnection.localDescription.sdp);
  812. this.notifyMySSRCUpdate(
  813. new SDP(oldLocalSdp), newLocalSdp);
  814. }
  815. finishedCallback();
  816. }, error => {
  817. logger.error(
  818. `Error renegotiating after setting new remote ${
  819. (this.isInitiator ? 'answer: ' : 'offer: ')
  820. }${error}`, newRemoteSdp);
  821. JingleSessionPC.onJingleFatalError(this, error);
  822. finishedCallback(error);
  823. });
  824. };
  825. this.modificationQueue.push(
  826. workFunction,
  827. error => {
  828. error ? failure(error) : success();
  829. });
  830. }
  831. /* eslint-enable max-params */
  832. /**
  833. * Although it states "replace transport" it does accept full Jingle offer
  834. * which should contain new ICE transport details.
  835. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  836. * transport info.
  837. * @param success callback called when we succeed to accept new offer.
  838. * @param failure function(error) called when we fail to accept new offer.
  839. */
  840. replaceTransport(jingleOfferElem, success, failure) {
  841. // We need to first set an offer without the 'data' section to have the
  842. // SCTP stack cleaned up. After that the original offer is set to have
  843. // the SCTP connection established with the new bridge.
  844. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  845. const originalOffer = jingleOfferElem.clone();
  846. jingleOfferElem.find('>content[name=\'data\']').remove();
  847. // First set an offer without the 'data' section
  848. this.setOfferAnswerCycle(
  849. jingleOfferElem,
  850. () => {
  851. // Now set the original offer(with the 'data' section)
  852. this.setOfferAnswerCycle(
  853. originalOffer,
  854. () => {
  855. const localSDP
  856. = new SDP(this.peerconnection.localDescription.sdp);
  857. this.sendTransportAccept(localSDP, success, failure);
  858. },
  859. failure);
  860. },
  861. failure
  862. );
  863. }
  864. /**
  865. * Sends Jingle 'session-accept' message.
  866. * @param {function()} success callback called when we receive 'RESULT'
  867. * packet for the 'session-accept'
  868. * @param {function(error)} failure called when we receive an error response
  869. * or when the request has timed out.
  870. * @private
  871. */
  872. sendSessionAccept(success, failure) {
  873. // NOTE: since we're just reading from it, we don't need to be within
  874. // the modification queue to access the local description
  875. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  876. let accept = $iq({ to: this.peerjid,
  877. type: 'set' })
  878. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  879. action: 'session-accept',
  880. initiator: this.initiator,
  881. responder: this.responder,
  882. sid: this.sid });
  883. if (this.webrtcIceTcpDisable) {
  884. localSDP.removeTcpCandidates = true;
  885. }
  886. if (this.webrtcIceUdpDisable) {
  887. localSDP.removeUdpCandidates = true;
  888. }
  889. if (this.failICE) {
  890. localSDP.failICE = true;
  891. }
  892. localSDP.toJingle(
  893. accept,
  894. this.initiator === this.localJid ? 'initiator' : 'responder',
  895. null);
  896. // Calling tree() to print something useful
  897. accept = accept.tree();
  898. logger.info('Sending session-accept', accept);
  899. this.connection.sendIQ(accept,
  900. success,
  901. this.newJingleErrorHandler(accept, error => {
  902. failure(error);
  903. // 'session-accept' is a critical timeout and we'll
  904. // have to restart
  905. this.room.eventEmitter.emit(
  906. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  907. }),
  908. IQ_TIMEOUT);
  909. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  910. // fingerprint and setup) ASAP in order to start the connection
  911. // establishment.
  912. //
  913. // FIXME Flushing the connection at this point triggers an issue with
  914. // BOSH request handling in Prosody on slow connections.
  915. //
  916. // The problem is that this request will be quite large and it may take
  917. // time before it reaches Prosody. In the meantime Strophe may decide
  918. // to send the next one. And it was observed that a small request with
  919. // 'transport-info' usually follows this one. It does reach Prosody
  920. // before the previous one was completely received. 'rid' on the server
  921. // is increased and Prosody ignores the request with 'session-accept'.
  922. // It will never reach Jicofo and everything in the request table is
  923. // lost. Removing the flush does not guarantee it will never happen, but
  924. // makes it much less likely('transport-info' is bundled with
  925. // 'session-accept' and any immediate requests).
  926. //
  927. // this.connection.flush();
  928. }
  929. /**
  930. * Will send 'content-modify' IQ in order to ask the remote peer to
  931. * either stop or resume sending video media.
  932. * @param {boolean} videoTransferActive <tt>false</tt> to let the other peer
  933. * know that we're not sending nor interested in receiving video contents.
  934. * When set to <tt>true</tt> remote peer will be asked to resume video
  935. * transfer.
  936. * @private
  937. */
  938. sendContentModify(videoTransferActive) {
  939. const newSendersValue = videoTransferActive ? 'both' : 'none';
  940. const sessionModify
  941. = $iq({
  942. to: this.peerjid,
  943. type: 'set'
  944. })
  945. .c('jingle', {
  946. xmlns: 'urn:xmpp:jingle:1',
  947. action: 'content-modify',
  948. initiator: this.initiator,
  949. sid: this.sid
  950. })
  951. .c('content', {
  952. name: 'video',
  953. senders: newSendersValue
  954. });
  955. logger.info(
  956. `Sending content-modify, video senders: ${newSendersValue}`);
  957. this.connection.sendIQ(
  958. sessionModify,
  959. null,
  960. this.newJingleErrorHandler(sessionModify),
  961. IQ_TIMEOUT);
  962. }
  963. /**
  964. * Sends Jingle 'transport-accept' message which is a response to
  965. * 'transport-replace'.
  966. * @param localSDP the 'SDP' object with local session description
  967. * @param success callback called when we receive 'RESULT' packet for
  968. * 'transport-replace'
  969. * @param failure function(error) called when we receive an error response
  970. * or when the request has timed out.
  971. * @private
  972. */
  973. sendTransportAccept(localSDP, success, failure) {
  974. let transportAccept = $iq({ to: this.peerjid,
  975. type: 'set' })
  976. .c('jingle', {
  977. xmlns: 'urn:xmpp:jingle:1',
  978. action: 'transport-accept',
  979. initiator: this.initiator,
  980. sid: this.sid
  981. });
  982. localSDP.media.forEach((medialines, idx) => {
  983. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  984. transportAccept.c('content',
  985. {
  986. creator:
  987. this.initiator === this.localJid
  988. ? 'initiator'
  989. : 'responder',
  990. name: mline.media
  991. }
  992. );
  993. localSDP.transportToJingle(idx, transportAccept);
  994. transportAccept.up();
  995. });
  996. // Calling tree() to print something useful to the logger
  997. transportAccept = transportAccept.tree();
  998. logger.info('Sending transport-accept: ', transportAccept);
  999. this.connection.sendIQ(transportAccept,
  1000. success,
  1001. this.newJingleErrorHandler(transportAccept, failure),
  1002. IQ_TIMEOUT);
  1003. }
  1004. /**
  1005. * Sends Jingle 'transport-reject' message which is a response to
  1006. * 'transport-replace'.
  1007. * @param success callback called when we receive 'RESULT' packet for
  1008. * 'transport-replace'
  1009. * @param failure function(error) called when we receive an error response
  1010. * or when the request has timed out.
  1011. *
  1012. * FIXME method should be marked as private, but there's some spaghetti that
  1013. * needs to be fixed prior doing that
  1014. */
  1015. sendTransportReject(success, failure) {
  1016. // Send 'transport-reject', so that the focus will
  1017. // know that we've failed
  1018. let transportReject = $iq({ to: this.peerjid,
  1019. type: 'set' })
  1020. .c('jingle', {
  1021. xmlns: 'urn:xmpp:jingle:1',
  1022. action: 'transport-reject',
  1023. initiator: this.initiator,
  1024. sid: this.sid
  1025. });
  1026. transportReject = transportReject.tree();
  1027. logger.info('Sending \'transport-reject', transportReject);
  1028. this.connection.sendIQ(transportReject,
  1029. success,
  1030. this.newJingleErrorHandler(transportReject, failure),
  1031. IQ_TIMEOUT);
  1032. }
  1033. /**
  1034. * @inheritDoc
  1035. */
  1036. terminate(success, failure, options) {
  1037. if (this.state === JingleSessionState.ENDED) {
  1038. return;
  1039. }
  1040. if (!options || Boolean(options.sendSessionTerminate)) {
  1041. let sessionTerminate
  1042. = $iq({
  1043. to: this.peerjid,
  1044. type: 'set'
  1045. })
  1046. .c('jingle', {
  1047. xmlns: 'urn:xmpp:jingle:1',
  1048. action: 'session-terminate',
  1049. initiator: this.initiator,
  1050. sid: this.sid
  1051. })
  1052. .c('reason')
  1053. .c((options && options.reason) || 'success');
  1054. if (options && options.reasonDescription) {
  1055. sessionTerminate.up()
  1056. .c('text')
  1057. .t(options.reasonDescription);
  1058. }
  1059. // Calling tree() to print something useful
  1060. sessionTerminate = sessionTerminate.tree();
  1061. logger.info('Sending session-terminate', sessionTerminate);
  1062. this.connection.sendIQ(
  1063. sessionTerminate,
  1064. success,
  1065. this.newJingleErrorHandler(sessionTerminate, failure),
  1066. IQ_TIMEOUT);
  1067. } else {
  1068. logger.info(`Skipped sending session-terminate for ${this}`);
  1069. }
  1070. // this should result in 'onTerminated' being called by strope.jingle.js
  1071. this.connection.jingle.terminate(this.sid);
  1072. }
  1073. /**
  1074. *
  1075. * @param reasonCondition
  1076. * @param reasonText
  1077. */
  1078. onTerminated(reasonCondition, reasonText) {
  1079. this.state = JingleSessionState.ENDED;
  1080. this.establishmentDuration = undefined;
  1081. // Do something with reason and reasonCondition when we start to care
  1082. // this.reasonCondition = reasonCondition;
  1083. // this.reasonText = reasonText;
  1084. logger.info(`Session terminated ${this}`, reasonCondition, reasonText);
  1085. this.close();
  1086. }
  1087. /**
  1088. * Parse the information from the xml sourceAddElem and translate it
  1089. * into sdp lines
  1090. * @param {jquery xml element} sourceAddElem the source-add
  1091. * element from jingle
  1092. * @param {SDP object} currentRemoteSdp the current remote
  1093. * sdp (as of this new source-add)
  1094. * @returns {list} a list of SDP line strings that should
  1095. * be added to the remote SDP
  1096. */
  1097. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1098. const addSsrcInfo = [];
  1099. $(sourceAddElem).each((i1, content) => {
  1100. const name = $(content).attr('name');
  1101. let lines = '';
  1102. $(content)
  1103. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1104. .each(function() {
  1105. // eslint-disable-next-line no-invalid-this
  1106. const semantics = this.getAttribute('semantics');
  1107. const ssrcs
  1108. = $(this) // eslint-disable-line no-invalid-this
  1109. .find('>source')
  1110. .map(function() {
  1111. // eslint-disable-next-line no-invalid-this
  1112. return this.getAttribute('ssrc');
  1113. })
  1114. .get();
  1115. if (ssrcs.length) {
  1116. lines
  1117. += `a=ssrc-group:${semantics} ${ssrcs.join(' ')
  1118. }\r\n`;
  1119. }
  1120. });
  1121. // handles both >source and >description>source
  1122. const tmp
  1123. = $(content).find(
  1124. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1125. /* eslint-disable no-invalid-this */
  1126. tmp.each(function() {
  1127. const ssrc = $(this).attr('ssrc');
  1128. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1129. logger.warn(
  1130. `Source-add request for existing SSRC: ${ssrc}`);
  1131. return;
  1132. }
  1133. // eslint-disable-next-line newline-per-chained-call
  1134. $(this).find('>parameter').each(function() {
  1135. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1136. if ($(this).attr('value') && $(this).attr('value').length) {
  1137. lines += `:${$(this).attr('value')}`;
  1138. }
  1139. lines += '\r\n';
  1140. });
  1141. });
  1142. /* eslint-enable no-invalid-this */
  1143. currentRemoteSdp.media.forEach((media, i2) => {
  1144. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1145. return;
  1146. }
  1147. if (!addSsrcInfo[i2]) {
  1148. addSsrcInfo[i2] = '';
  1149. }
  1150. addSsrcInfo[i2] += lines;
  1151. });
  1152. });
  1153. return addSsrcInfo;
  1154. }
  1155. /**
  1156. * Handles a Jingle source-add message for this Jingle session.
  1157. * @param elem An array of Jingle "content" elements.
  1158. */
  1159. addRemoteStream(elem) {
  1160. this._addOrRemoveRemoteStream(true /* add */, elem);
  1161. }
  1162. /**
  1163. * Handles a Jingle source-remove message for this Jingle session.
  1164. * @param elem An array of Jingle "content" elements.
  1165. */
  1166. removeRemoteStream(elem) {
  1167. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1168. }
  1169. /**
  1170. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1171. * Jingle session.
  1172. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1173. * otherwise.
  1174. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1175. * @private
  1176. */
  1177. _addOrRemoveRemoteStream(isAdd, elem) {
  1178. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1179. if (isAdd) {
  1180. this.readSsrcInfo(elem);
  1181. }
  1182. const workFunction = finishedCallback => {
  1183. if (!this.peerconnection.localDescription
  1184. || !this.peerconnection.localDescription.sdp) {
  1185. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1186. logger.error(errMsg);
  1187. finishedCallback(errMsg);
  1188. return;
  1189. }
  1190. logger.log(`Processing ${logPrefix}`);
  1191. logger.log(
  1192. 'ICE connection state: ',
  1193. this.peerconnection.iceConnectionState);
  1194. const oldLocalSdp
  1195. = new SDP(this.peerconnection.localDescription.sdp);
  1196. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1197. const addOrRemoveSsrcInfo
  1198. = isAdd
  1199. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1200. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1201. const newRemoteSdp
  1202. = isAdd
  1203. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1204. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1205. this._renegotiate(newRemoteSdp.raw)
  1206. .then(() => {
  1207. const newLocalSdp
  1208. = new SDP(this.peerconnection.localDescription.sdp);
  1209. logger.log(
  1210. `${logPrefix} - OK, SDPs: `, oldLocalSdp, newLocalSdp);
  1211. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1212. finishedCallback();
  1213. }, error => {
  1214. logger.error(`${logPrefix} failed:`, error);
  1215. finishedCallback(error);
  1216. });
  1217. };
  1218. // Queue and execute
  1219. this.modificationQueue.push(workFunction);
  1220. }
  1221. /**
  1222. * The 'task' function will be given a callback it MUST call with either:
  1223. * 1) No arguments if it was successful or
  1224. * 2) An error argument if there was an error
  1225. * If the task wants to process the success or failure of the task, it
  1226. * should pass a handler to the .push function, e.g.:
  1227. * queue.push(task, (err) => {
  1228. * if (err) {
  1229. * // error handling
  1230. * } else {
  1231. * // success handling
  1232. * }
  1233. * });
  1234. */
  1235. _processQueueTasks(task, finishedCallback) {
  1236. task(finishedCallback);
  1237. }
  1238. /**
  1239. * Takes in a jingle offer iq, returns the new sdp offer
  1240. * @param {jquery xml element} offerIq the incoming offer
  1241. * @returns {SDP object} the jingle offer translated to SDP
  1242. */
  1243. _processNewJingleOfferIq(offerIq) {
  1244. const remoteSdp = new SDP('');
  1245. if (this.webrtcIceTcpDisable) {
  1246. remoteSdp.removeTcpCandidates = true;
  1247. }
  1248. if (this.webrtcIceUdpDisable) {
  1249. remoteSdp.removeUdpCandidates = true;
  1250. }
  1251. if (this.failICE) {
  1252. remoteSdp.failICE = true;
  1253. }
  1254. remoteSdp.fromJingle(offerIq);
  1255. this.readSsrcInfo($(offerIq).find('>content'));
  1256. this.readBridgeWebSocketUrl($(offerIq).find('>content'));
  1257. return remoteSdp;
  1258. }
  1259. /**
  1260. * Remove the given ssrc lines from the current remote sdp
  1261. * @param {list} removeSsrcInfo a list of SDP line strings that
  1262. * should be removed from the remote SDP
  1263. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1264. * in removeSsrcInfo
  1265. */
  1266. _processRemoteRemoveSource(removeSsrcInfo) {
  1267. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1268. removeSsrcInfo.forEach((lines, idx) => {
  1269. // eslint-disable-next-line no-param-reassign
  1270. lines = lines.split('\r\n');
  1271. lines.pop(); // remove empty last element;
  1272. lines.forEach(line => {
  1273. remoteSdp.media[idx]
  1274. = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1275. });
  1276. });
  1277. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1278. return remoteSdp;
  1279. }
  1280. /**
  1281. * Add the given ssrc lines to the current remote sdp
  1282. * @param {list} addSsrcInfo a list of SDP line strings that
  1283. * should be added to the remote SDP
  1284. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1285. * in removeSsrcInfo
  1286. */
  1287. _processRemoteAddSource(addSsrcInfo) {
  1288. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1289. addSsrcInfo.forEach((lines, idx) => {
  1290. remoteSdp.media[idx] += lines;
  1291. });
  1292. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1293. return remoteSdp;
  1294. }
  1295. /**
  1296. * Do a new o/a flow using the existing remote description
  1297. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1298. * to use. If not provided, the remote sdp from the
  1299. * peerconnection will be used
  1300. * @returns {Promise} promise which resolves when the
  1301. * o/a flow is complete with no arguments or
  1302. * rejects with an error {string}
  1303. */
  1304. _renegotiate(optionalRemoteSdp) {
  1305. const remoteSdp
  1306. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1307. if (!remoteSdp) {
  1308. return Promise.reject(
  1309. 'Can not renegotiate without remote description,'
  1310. + `- current state: ${this.state}`);
  1311. }
  1312. const remoteDescription = new RTCSessionDescription({
  1313. type: this.isInitiator ? 'answer' : 'offer',
  1314. sdp: remoteSdp
  1315. });
  1316. return new Promise((resolve, reject) => {
  1317. if (this.peerconnection.signalingState === 'closed') {
  1318. reject('Attempted to renegotiate in state closed');
  1319. return;
  1320. }
  1321. if (this.isInitiator) {
  1322. this._initiatorRenegotiate(remoteDescription, resolve, reject);
  1323. } else {
  1324. this._responderRenegotiate(remoteDescription, resolve, reject);
  1325. }
  1326. });
  1327. }
  1328. /**
  1329. * Renegotiate cycle implementation for the responder case.
  1330. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1331. * which will be used as remote description in the cycle.
  1332. * @param {function} resolve the success callback
  1333. * @param {function} reject the failure callback
  1334. * @private
  1335. */
  1336. _responderRenegotiate(remoteDescription, resolve, reject) {
  1337. // FIXME use WebRTC promise API to simplify things
  1338. logger.debug('Renegotiate: setting remote description');
  1339. this.peerconnection.setRemoteDescription(
  1340. remoteDescription,
  1341. () => {
  1342. logger.debug('Renegotiate: creating answer');
  1343. this.peerconnection.createAnswer(
  1344. answer => {
  1345. logger.debug('Renegotiate: setting local description');
  1346. this.peerconnection.setLocalDescription(
  1347. answer,
  1348. () => {
  1349. resolve();
  1350. },
  1351. error => {
  1352. reject(
  1353. `setLocalDescription failed: ${error}`);
  1354. }
  1355. );
  1356. },
  1357. error => reject(`createAnswer failed: ${error}`),
  1358. this.mediaConstraints
  1359. );
  1360. },
  1361. error => reject(`setRemoteDescription failed: ${error}`)
  1362. );
  1363. }
  1364. /**
  1365. * Renegotiate cycle implementation for the initiator's case.
  1366. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1367. * which will be used as remote description in the cycle.
  1368. * @param {function} resolve the success callback
  1369. * @param {function} reject the failure callback
  1370. * @private
  1371. */
  1372. _initiatorRenegotiate(remoteDescription, resolve, reject) {
  1373. // FIXME use WebRTC promise API to simplify things
  1374. if (this.peerconnection.signalingState === 'have-local-offer') {
  1375. // Skip createOffer and setLocalDescription or FF will fail
  1376. logger.debug(
  1377. 'Renegotiate: setting remote description');
  1378. this.peerconnection.setRemoteDescription(
  1379. remoteDescription,
  1380. () => {
  1381. resolve();
  1382. },
  1383. error => reject(`setRemoteDescription failed: ${error}`)
  1384. );
  1385. } else {
  1386. logger.debug('Renegotiate: creating offer');
  1387. this.peerconnection.createOffer(
  1388. offer => {
  1389. logger.debug('Renegotiate: setting local description');
  1390. this.peerconnection.setLocalDescription(offer,
  1391. () => {
  1392. logger.debug(
  1393. 'Renegotiate: setting remote description');
  1394. this.peerconnection.setRemoteDescription(
  1395. remoteDescription,
  1396. () => {
  1397. resolve();
  1398. },
  1399. error => reject(
  1400. `setRemoteDescription failed: ${error}`)
  1401. );
  1402. },
  1403. error => {
  1404. reject('setLocalDescription failed: ', error);
  1405. });
  1406. },
  1407. error => reject(`createOffer failed: ${error}`),
  1408. this.mediaConstraints);
  1409. }
  1410. }
  1411. /**
  1412. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1413. * offer/answer cycle after both operations are done. Either
  1414. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1415. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1416. * <tt>oldTrack</tt>
  1417. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  1418. * replaced
  1419. * @param {JitsiLocalTrack|null} newTrack the new track to use
  1420. * @returns {Promise} which resolves once the replacement is complete
  1421. * with no arguments or rejects with an error {string}
  1422. */
  1423. replaceTrack(oldTrack, newTrack) {
  1424. const workFunction = finishedCallback => {
  1425. // Check if the connection was closed and pretend everything is OK.
  1426. // This can happen if a track removal is scheduled but takes place
  1427. // after the connection is closed.
  1428. if (this.peerconnection.signalingState === 'closed'
  1429. || this.peerconnection.connectionState === 'closed'
  1430. || this.closed) {
  1431. finishedCallback();
  1432. return;
  1433. }
  1434. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  1435. // NOTE the code below assumes that no more than 1 video track
  1436. // can be added to the peer connection.
  1437. // Transition from no video to video (possibly screen sharing)
  1438. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  1439. // Clearing current primary SSRC will make
  1440. // the SdpConsistency generate a new one which will result
  1441. // with:
  1442. // 1. source-remove for the recvonly
  1443. // 2. source-add for the new video stream
  1444. this.peerconnection.clearRecvonlySsrc();
  1445. // Transition from video to no video
  1446. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  1447. // Clearing current primary SSRC and generating the recvonly
  1448. // will result in:
  1449. // 1. source-remove for the old video stream
  1450. // 2. source-add for the recvonly stream
  1451. this.peerconnection.clearRecvonlySsrc();
  1452. this.peerconnection.generateRecvonlySsrc();
  1453. }
  1454. if (oldTrack) {
  1455. this.peerconnection.removeTrack(oldTrack);
  1456. }
  1457. if (newTrack) {
  1458. this.peerconnection.addTrack(newTrack);
  1459. }
  1460. if ((oldTrack || newTrack)
  1461. && this.state === JingleSessionState.ACTIVE) {
  1462. this._renegotiate()
  1463. .then(() => {
  1464. const newLocalSDP
  1465. = new SDP(
  1466. this.peerconnection.localDescription.sdp);
  1467. this.notifyMySSRCUpdate(
  1468. new SDP(oldLocalSdp), newLocalSDP);
  1469. finishedCallback();
  1470. },
  1471. finishedCallback /* will be called with en error */);
  1472. } else {
  1473. finishedCallback();
  1474. }
  1475. };
  1476. this.modificationQueue.push(
  1477. workFunction,
  1478. error => {
  1479. if (error) {
  1480. logger.error('Replace track error:', error);
  1481. } else {
  1482. logger.info('Replace track done!');
  1483. }
  1484. });
  1485. }
  1486. /**
  1487. * Parse the information from the xml sourceRemoveElem and translate it
  1488. * into sdp lines
  1489. * @param {jquery xml element} sourceRemoveElem the source-remove
  1490. * element from jingle
  1491. * @param {SDP object} currentRemoteSdp the current remote
  1492. * sdp (as of this new source-remove)
  1493. * @returns {list} a list of SDP line strings that should
  1494. * be removed from the remote SDP
  1495. */
  1496. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  1497. const removeSsrcInfo = [];
  1498. $(sourceRemoveElem).each((i1, content) => {
  1499. const name = $(content).attr('name');
  1500. let lines = '';
  1501. $(content)
  1502. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1503. .each(function() {
  1504. /* eslint-disable no-invalid-this */
  1505. const semantics = this.getAttribute('semantics');
  1506. const ssrcs
  1507. = $(this)
  1508. .find('>source')
  1509. .map(function() {
  1510. return this.getAttribute('ssrc');
  1511. })
  1512. .get();
  1513. if (ssrcs.length) {
  1514. lines
  1515. += `a=ssrc-group:${semantics} ${ssrcs.join(' ')
  1516. }\r\n`;
  1517. }
  1518. /* eslint-enable no-invalid-this */
  1519. });
  1520. const ssrcs = [];
  1521. // handles both >source and >description>source versions
  1522. const tmp
  1523. = $(content).find(
  1524. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1525. tmp.each(function() {
  1526. // eslint-disable-next-line no-invalid-this
  1527. const ssrc = $(this).attr('ssrc');
  1528. ssrcs.push(ssrc);
  1529. });
  1530. currentRemoteSdp.media.forEach((media, i2) => {
  1531. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1532. return;
  1533. }
  1534. if (!removeSsrcInfo[i2]) {
  1535. removeSsrcInfo[i2] = '';
  1536. }
  1537. ssrcs.forEach(ssrc => {
  1538. const ssrcLines
  1539. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  1540. if (ssrcLines.length) {
  1541. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  1542. }
  1543. });
  1544. removeSsrcInfo[i2] += lines;
  1545. });
  1546. });
  1547. return removeSsrcInfo;
  1548. }
  1549. /**
  1550. * Will print an error if there is any difference, between the SSRCs given
  1551. * in the <tt>oldSDP</tt> and the ones currently described in
  1552. * the peerconnection's local description.
  1553. * @param {string} operationName the operation's name which will be printed
  1554. * in the error message.
  1555. * @param {SDP} oldSDP the old local SDP which will be compared with
  1556. * the current one.
  1557. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  1558. * otherwise.
  1559. * @private
  1560. */
  1561. _verifyNoSSRCChanged(operationName, oldSDP) {
  1562. const currentLocalSDP
  1563. = new SDP(this.peerconnection.localDescription.sdp);
  1564. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  1565. const addedMedia = sdpDiff.getNewMedia();
  1566. if (Object.keys(addedMedia).length) {
  1567. logger.error(
  1568. `Some SSRC were added on ${operationName}`, addedMedia);
  1569. return false;
  1570. }
  1571. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  1572. const removedMedia = sdpDiff.getNewMedia();
  1573. if (Object.keys(removedMedia).length) {
  1574. logger.error(
  1575. `Some SSRCs were removed on ${operationName}`, removedMedia);
  1576. return false;
  1577. }
  1578. return true;
  1579. }
  1580. /**
  1581. * Adds local track back to this session, as part of the unmute operation.
  1582. * @param {JitsiLocalTrack} track
  1583. * @return {Promise} a promise that will resolve once the local track is
  1584. * added back to this session and renegotiation succeeds. Will be rejected
  1585. * with a <tt>string</tt> that provides some error details in case something
  1586. * goes wrong.
  1587. */
  1588. addTrackAsUnmute(track) {
  1589. return this._addRemoveTrackAsMuteUnmute(
  1590. false /* add as unmute */, track);
  1591. }
  1592. /**
  1593. * Remove local track as part of the mute operation.
  1594. * @param {JitsiLocalTrack} track the local track to be removed
  1595. * @return {Promise} a promise which will be resolved once the local track
  1596. * is removed from this session and the renegotiation is performed.
  1597. * The promise will be rejected with a <tt>string</tt> that the describes
  1598. * the error if anything goes wrong.
  1599. */
  1600. removeTrackAsMute(track) {
  1601. return this._addRemoveTrackAsMuteUnmute(
  1602. true /* remove as mute */, track);
  1603. }
  1604. /**
  1605. * See {@link addTrackAsUnmute} and {@link removeTrackAsMute}.
  1606. * @param {boolean} isMute <tt>true</tt> for "remove as mute" or
  1607. * <tt>false</tt> for "add as unmute".
  1608. * @param {JitsiLocalTrack} track the track that will be added/removed
  1609. * @private
  1610. */
  1611. _addRemoveTrackAsMuteUnmute(isMute, track) {
  1612. if (!track) {
  1613. return Promise.reject('invalid "track" argument value');
  1614. }
  1615. const operationName = isMute ? 'removeTrackMute' : 'addTrackUnmute';
  1616. const workFunction = finishedCallback => {
  1617. const tpc = this.peerconnection;
  1618. if (!tpc) {
  1619. finishedCallback(
  1620. `Error: tried ${operationName} track with no active peer`
  1621. + 'connection');
  1622. return;
  1623. }
  1624. const oldLocalSDP = tpc.localDescription.sdp;
  1625. const tpcOperation
  1626. = isMute
  1627. ? tpc.removeTrackMute.bind(tpc, track)
  1628. : tpc.addTrackUnmute.bind(tpc, track);
  1629. if (!tpcOperation()) {
  1630. finishedCallback(`${operationName} failed!`);
  1631. } else if (!oldLocalSDP || !tpc.remoteDescription.sdp) {
  1632. finishedCallback();
  1633. } else {
  1634. this._renegotiate()
  1635. .then(() => {
  1636. // The results are ignored, as this check failure is not
  1637. // enough to fail the whole operation. It will log
  1638. // an error inside.
  1639. this._verifyNoSSRCChanged(
  1640. operationName, new SDP(oldLocalSDP));
  1641. finishedCallback();
  1642. },
  1643. finishedCallback /* will be called with an error */);
  1644. }
  1645. };
  1646. return new Promise((resolve, reject) => {
  1647. this.modificationQueue.push(
  1648. workFunction,
  1649. error => {
  1650. if (error) {
  1651. reject(error);
  1652. } else {
  1653. resolve();
  1654. }
  1655. });
  1656. });
  1657. }
  1658. /**
  1659. * Resumes or suspends media transfer over the underlying peer connection.
  1660. * @param {boolean} audioActive <tt>true</tt> to enable audio media
  1661. * transfer or <tt>false</tt> to suspend audio media transmission.
  1662. * @param {boolean} videoActive <tt>true</tt> to enable video media
  1663. * transfer or <tt>false</tt> to suspend video media transmission.
  1664. * @return {Promise} a <tt>Promise</tt> which will resolve once
  1665. * the operation is done. It will be rejected with an error description as
  1666. * a string in case anything goes wrong.
  1667. */
  1668. setMediaTransferActive(audioActive, videoActive) {
  1669. if (!this.peerconnection) {
  1670. return Promise.reject(
  1671. 'Can not modify transfer active state,'
  1672. + ' before "initialize" is called');
  1673. }
  1674. const logAudioStr = audioActive ? 'audio active' : 'audio inactive';
  1675. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  1676. logger.info(`Queued make ${logVideoStr}, ${logAudioStr} task...`);
  1677. const workFunction = finishedCallback => {
  1678. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  1679. // Because the value is modified on the queue it's impossible to
  1680. // check it's final value reliably prior to submitting the task.
  1681. // The rule here is that the last submitted state counts.
  1682. // Check the values here to avoid unnecessary renegotiation cycle.
  1683. const audioActiveChanged
  1684. = this.peerconnection.setAudioTransferActive(audioActive);
  1685. if (this._localVideoActive !== videoActive) {
  1686. this._localVideoActive = videoActive;
  1687. // Do only for P2P - Jicofo will reply with 'bad-request'
  1688. // We don't want to send 'content-modify', before the initial
  1689. // O/A (state === JingleSessionState.ACTIVE), because that will
  1690. // mess up video media direction in the remote SDP.
  1691. // 'content-modify' when processed only affects the media
  1692. // direction in the local SDP. We're doing that, because setting
  1693. // 'inactive' on video media in remote SDP will mess up our SDP
  1694. // translation chain (simulcast, RTX, video mute etc.).
  1695. if (this.isP2P && isSessionActive) {
  1696. this.sendContentModify(videoActive);
  1697. }
  1698. }
  1699. const pcVideoActiveChanged
  1700. = this.peerconnection.setVideoTransferActive(
  1701. this._localVideoActive && this._remoteVideoActive);
  1702. // Will do the sRD/sLD cycle to update SDPs and adjust the media
  1703. // direction
  1704. if (isSessionActive
  1705. && (audioActiveChanged || pcVideoActiveChanged)) {
  1706. this._renegotiate()
  1707. .then(
  1708. finishedCallback,
  1709. finishedCallback /* will be called with an error */);
  1710. } else {
  1711. finishedCallback();
  1712. }
  1713. };
  1714. return new Promise((resolve, reject) => {
  1715. this.modificationQueue.push(
  1716. workFunction,
  1717. error => {
  1718. if (error) {
  1719. reject(error);
  1720. } else {
  1721. resolve();
  1722. }
  1723. });
  1724. });
  1725. }
  1726. /**
  1727. * Will put and execute on the queue a session modify task. Currently it
  1728. * only checks the senders attribute of the video content in order to figure
  1729. * out if the remote peer has video in the inactive state (stored locally
  1730. * in {@link _remoteVideoActive} - see field description for more info).
  1731. * @param {jQuery} jingleContents jQuery selector pointing to the jingle
  1732. * element of the session modify IQ.
  1733. * @see {@link _remoteVideoActive}
  1734. * @see {@link _localVideoActive}
  1735. */
  1736. modifyContents(jingleContents) {
  1737. const newVideoSenders
  1738. = JingleSessionPC.parseVideoSenders(jingleContents);
  1739. if (newVideoSenders === null) {
  1740. logger.error(
  1741. `${this} - failed to parse video "senders" attribute in`
  1742. + '"content-modify" action');
  1743. return;
  1744. }
  1745. const workFunction = finishedCallback => {
  1746. if (this._assertNotEnded('content-modify')
  1747. && this._modifyRemoteVideoActive(newVideoSenders)) {
  1748. // Will do the sRD/sLD cycle to update SDPs and adjust
  1749. // the media direction
  1750. this._renegotiate()
  1751. .then(finishedCallback, finishedCallback /* (error) */);
  1752. } else {
  1753. finishedCallback();
  1754. }
  1755. };
  1756. logger.debug(
  1757. `${this} queued "content-modify" task`
  1758. + `(video senders="${newVideoSenders}")`);
  1759. this.modificationQueue.push(
  1760. workFunction,
  1761. error => {
  1762. if (error) {
  1763. logger.error('"content-modify" failed', error);
  1764. }
  1765. });
  1766. }
  1767. /**
  1768. * Processes new value of remote video "senders" Jingle attribute and tries
  1769. * to apply it for {@link _remoteVideoActive}.
  1770. * @param {string} remoteVideoSenders the value of "senders" attribute of
  1771. * Jingle video content element advertised by remote peer.
  1772. * @return {boolean} <tt>true</tt> if the change affected state of
  1773. * the underlying peerconnection and renegotiation is required for
  1774. * the changes to take effect.
  1775. * @private
  1776. */
  1777. _modifyRemoteVideoActive(remoteVideoSenders) {
  1778. const isRemoteVideoActive
  1779. = remoteVideoSenders === 'both'
  1780. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  1781. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  1782. if (isRemoteVideoActive !== this._remoteVideoActive) {
  1783. logger.debug(
  1784. `${this} new remote video active: ${isRemoteVideoActive}`);
  1785. this._remoteVideoActive = isRemoteVideoActive;
  1786. }
  1787. return this.peerconnection.setVideoTransferActive(
  1788. this._localVideoActive && this._remoteVideoActive);
  1789. }
  1790. /**
  1791. * Figures out added/removed ssrcs and send update IQs.
  1792. * @param oldSDP SDP object for old description.
  1793. * @param newSDP SDP object for new description.
  1794. */
  1795. notifyMySSRCUpdate(oldSDP, newSDP) {
  1796. if (this.state !== JingleSessionState.ACTIVE) {
  1797. logger.warn(`Skipping SSRC update in '${this.state} ' state.`);
  1798. return;
  1799. }
  1800. // send source-remove IQ.
  1801. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  1802. const remove = $iq({ to: this.peerjid,
  1803. type: 'set' })
  1804. .c('jingle', {
  1805. xmlns: 'urn:xmpp:jingle:1',
  1806. action: 'source-remove',
  1807. initiator: this.initiator,
  1808. sid: this.sid
  1809. }
  1810. );
  1811. const removedAnySSRCs = sdpDiffer.toJingle(remove);
  1812. if (removedAnySSRCs) {
  1813. logger.info('Sending source-remove', remove.tree());
  1814. this.connection.sendIQ(
  1815. remove, null,
  1816. this.newJingleErrorHandler(remove, error => {
  1817. GlobalOnErrorHandler.callErrorHandler(
  1818. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1819. }), IQ_TIMEOUT);
  1820. } else {
  1821. logger.log('removal not necessary');
  1822. }
  1823. // send source-add IQ.
  1824. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  1825. const add = $iq({ to: this.peerjid,
  1826. type: 'set' })
  1827. .c('jingle', {
  1828. xmlns: 'urn:xmpp:jingle:1',
  1829. action: 'source-add',
  1830. initiator: this.initiator,
  1831. sid: this.sid
  1832. }
  1833. );
  1834. const containsNewSSRCs = sdpDiffer.toJingle(add);
  1835. if (containsNewSSRCs) {
  1836. logger.info('Sending source-add', add.tree());
  1837. this.connection.sendIQ(
  1838. add, null, this.newJingleErrorHandler(add, error => {
  1839. GlobalOnErrorHandler.callErrorHandler(
  1840. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1841. }), IQ_TIMEOUT);
  1842. } else {
  1843. logger.log('addition not necessary');
  1844. }
  1845. }
  1846. /**
  1847. * Method returns function(errorResponse) which is a callback to be passed
  1848. * to Strophe connection.sendIQ method. An 'error' structure is created that
  1849. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1850. * structure is as follows:
  1851. * {
  1852. * code: {XMPP error response code}
  1853. * reason: {the name of XMPP error reason element or 'timeout' if the
  1854. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1855. * source: {request.tree() that provides original request}
  1856. * session: {this JingleSessionPC.toString()}
  1857. * }
  1858. * @param request Strophe IQ instance which is the request to be dumped into
  1859. * the error structure
  1860. * @param failureCb function(error) called when error response was returned
  1861. * or when a timeout has occurred.
  1862. * @returns {function(this:JingleSessionPC)}
  1863. */
  1864. newJingleErrorHandler(request, failureCb) {
  1865. return errResponse => {
  1866. const error = {};
  1867. // Get XMPP error code and condition(reason)
  1868. const errorElSel = $(errResponse).find('error');
  1869. if (errorElSel.length) {
  1870. error.code = errorElSel.attr('code');
  1871. const errorReasonSel = $(errResponse).find('error :first');
  1872. if (errorReasonSel.length) {
  1873. error.reason = errorReasonSel[0].tagName;
  1874. }
  1875. }
  1876. if (!errResponse) {
  1877. error.reason = 'timeout';
  1878. }
  1879. error.source = request;
  1880. if (request && typeof request.tree === 'function') {
  1881. error.source = request.tree();
  1882. }
  1883. if (error.source && error.source.outerHTML) {
  1884. error.source = error.source.outerHTML;
  1885. }
  1886. error.session = this.toString();
  1887. if (failureCb) {
  1888. failureCb(error);
  1889. } else if (this.state === JingleSessionState.ENDED
  1890. && error.reason === 'item-not-found') {
  1891. // When remote peer decides to terminate the session, but it
  1892. // still have few messages on the queue for processing,
  1893. // it will first send us 'session-terminate' (we enter ENDED)
  1894. // and then follow with 'item-not-found' for the queued requests
  1895. // We don't want to have that logged on error level.
  1896. logger.debug('Jingle error', error);
  1897. } else {
  1898. GlobalOnErrorHandler.callErrorHandler(
  1899. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1900. }
  1901. };
  1902. }
  1903. /**
  1904. *
  1905. * @param session
  1906. * @param error
  1907. */
  1908. static onJingleFatalError(session, error) {
  1909. if (this.room) {
  1910. this.room.eventEmitter.emit(
  1911. XMPPEvents.CONFERENCE_SETUP_FAILED, session, error);
  1912. this.room.eventEmitter.emit(
  1913. XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1914. }
  1915. }
  1916. /**
  1917. * Returns the ice connection state for the peer connection.
  1918. * @returns the ice connection state for the peer connection.
  1919. */
  1920. getIceConnectionState() {
  1921. return this.peerconnection.iceConnectionState;
  1922. }
  1923. /**
  1924. * Closes the peerconnection.
  1925. */
  1926. close() {
  1927. this.closed = true;
  1928. // The signaling layer will remove it's listeners
  1929. this.signalingLayer.setChatRoom(null);
  1930. // do not try to close if already closed.
  1931. this.peerconnection
  1932. && ((this.peerconnection.signalingState
  1933. && this.peerconnection.signalingState !== 'closed')
  1934. || (this.peerconnection.connectionState
  1935. && this.peerconnection.connectionState !== 'closed'))
  1936. && this.peerconnection.close();
  1937. }
  1938. /**
  1939. * Converts to string with minor summary.
  1940. * @return {string}
  1941. */
  1942. toString() {
  1943. return `JingleSessionPC[p2p=${this.isP2P},`
  1944. + `initiator=${this.isInitiator},sid=${this.sid}]`;
  1945. }
  1946. }