Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

JingleSessionPC.js 101KB

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