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

JingleSessionPC.js 86KB

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