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

JingleSessionPC.js 81KB

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