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

JingleSessionPC.js 106KB

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