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

TraceablePeerConnection.js 78KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389
  1. /* global __filename, RTCSessionDescription */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import transform from 'sdp-transform';
  4. import * as GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  5. import JitsiRemoteTrack from './JitsiRemoteTrack';
  6. import * as MediaType from '../../service/RTC/MediaType';
  7. import LocalSdpMunger from './LocalSdpMunger';
  8. import RTC from './RTC';
  9. import RTCUtils from './RTCUtils';
  10. import browser from '../browser';
  11. import RTCEvents from '../../service/RTC/RTCEvents';
  12. import RtxModifier from '../xmpp/RtxModifier';
  13. // FIXME SDP tools should end up in some kind of util module
  14. import SDP from '../xmpp/SDP';
  15. import SdpConsistency from '../xmpp/SdpConsistency';
  16. import { SdpTransformWrap } from '../xmpp/SdpTransformUtil';
  17. import SDPUtil from '../xmpp/SDPUtil';
  18. import * as SignalingEvents from '../../service/RTC/SignalingEvents';
  19. const logger = getLogger(__filename);
  20. const SIMULCAST_LAYERS = 3;
  21. const SIM_LAYER_1_RID = '1';
  22. const SIM_LAYER_2_RID = '2';
  23. const SIM_LAYER_3_RID = '3';
  24. const SIM_LAYER_RIDS = [ SIM_LAYER_1_RID, SIM_LAYER_2_RID, SIM_LAYER_3_RID ];
  25. /* eslint-disable max-params */
  26. /**
  27. * Creates new instance of 'TraceablePeerConnection'.
  28. *
  29. * @param {RTC} rtc the instance of <tt>RTC</tt> service
  30. * @param {number} id the peer connection id assigned by the parent RTC module.
  31. * @param {SignalingLayer} signalingLayer the signaling layer instance
  32. * @param {object} iceConfig WebRTC 'PeerConnection' ICE config
  33. * @param {object} constraints WebRTC 'PeerConnection' constraints
  34. * @param {boolean} isP2P indicates whether or not the new instance will be used
  35. * in a peer to peer connection
  36. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  37. * @param {boolean} options.disableSimulcast if set to 'true' will disable
  38. * the simulcast.
  39. * @param {boolean} options.disableRtx if set to 'true' will disable the RTX
  40. * @param {boolean} options.enableFirefoxSimulcast if set to 'true' will enable
  41. * experimental simulcast support on Firefox.
  42. * @param {boolean} options.disableH264 If set to 'true' H264 will be
  43. * disabled by removing it from the SDP.
  44. * @param {boolean} options.preferH264 if set to 'true' H264 will be preferred
  45. * over other video codecs.
  46. *
  47. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  48. * debug the peer connection. Since many other responsibilities have been added
  49. * it would make sense to extract a separate class from it and come up with
  50. * a more suitable name.
  51. *
  52. * @constructor
  53. */
  54. export default function TraceablePeerConnection(
  55. rtc,
  56. id,
  57. signalingLayer,
  58. iceConfig,
  59. constraints,
  60. isP2P,
  61. options) {
  62. /**
  63. * Indicates whether or not this peer connection instance is actively
  64. * sending/receiving audio media. When set to <tt>false</tt> the SDP audio
  65. * media direction will be adjusted to 'inactive' in order to suspend
  66. * the transmission.
  67. * @type {boolean}
  68. * @private
  69. */
  70. this.audioTransferActive = true;
  71. /**
  72. * Indicates whether or not this peer connection instance is actively
  73. * sending/receiving video media. When set to <tt>false</tt> the SDP video
  74. * media direction will be adjusted to 'inactive' in order to suspend
  75. * the transmission.
  76. * @type {boolean}
  77. * @private
  78. */
  79. this.videoTransferActive = true;
  80. /**
  81. * The parent instance of RTC service which created this
  82. * <tt>TracablePeerConnection</tt>.
  83. * @type {RTC}
  84. */
  85. this.rtc = rtc;
  86. /**
  87. * The peer connection identifier assigned by the RTC module.
  88. * @type {number}
  89. */
  90. this.id = id;
  91. /**
  92. * Indicates whether or not this instance is used in a peer to peer
  93. * connection.
  94. * @type {boolean}
  95. */
  96. this.isP2P = isP2P;
  97. // FIXME: We should support multiple streams per jid.
  98. /**
  99. * The map holds remote tracks associated with this peer connection.
  100. * It maps user's JID to media type and remote track
  101. * (one track per media type per user's JID).
  102. * @type {Map<string, Map<MediaType, JitsiRemoteTrack>>}
  103. */
  104. this.remoteTracks = new Map();
  105. /**
  106. * A map which stores local tracks mapped by {@link JitsiLocalTrack.rtcId}
  107. * @type {Map<number, JitsiLocalTrack>}
  108. */
  109. this.localTracks = new Map();
  110. /**
  111. * Keeps tracks of the WebRTC <tt>MediaStream</tt>s that have been added to
  112. * the underlying WebRTC PeerConnection. An Array is used to avoid errors in
  113. * IE11 with adding temasys MediaStream objects into other data structures.
  114. * @type {Array}
  115. * @private
  116. */
  117. this._addedStreams = [];
  118. /**
  119. * @typedef {Object} TPCGroupInfo
  120. * @property {string} semantics the SSRC groups semantics
  121. * @property {Array<number>} ssrcs group's SSRCs in order where the first
  122. * one is group's primary SSRC, the second one is secondary (RTX) and so
  123. * on...
  124. */
  125. /**
  126. * @typedef {Object} TPCSSRCInfo
  127. * @property {Array<number>} ssrcs an array which holds all track's SSRCs
  128. * @property {Array<TPCGroupInfo>} groups an array stores all track's SSRC
  129. * groups
  130. */
  131. /**
  132. * Holds the info about local track's SSRCs mapped per their
  133. * {@link JitsiLocalTrack.rtcId}
  134. * @type {Map<number, TPCSSRCInfo>}
  135. */
  136. this.localSSRCs = new Map();
  137. /**
  138. * The local ICE username fragment for this session.
  139. */
  140. this.localUfrag = null;
  141. /**
  142. * The remote ICE username fragment for this session.
  143. */
  144. this.remoteUfrag = null;
  145. /**
  146. * The signaling layer which operates this peer connection.
  147. * @type {SignalingLayer}
  148. */
  149. this.signalingLayer = signalingLayer;
  150. // SignalingLayer listeners
  151. this._peerVideoTypeChanged = this._peerVideoTypeChanged.bind(this);
  152. this.signalingLayer.on(
  153. SignalingEvents.PEER_VIDEO_TYPE_CHANGED,
  154. this._peerVideoTypeChanged);
  155. this._peerMutedChanged = this._peerMutedChanged.bind(this);
  156. this.signalingLayer.on(
  157. SignalingEvents.PEER_MUTED_CHANGED,
  158. this._peerMutedChanged);
  159. this.options = options;
  160. this.peerconnection
  161. = new RTCUtils.RTCPeerConnectionType(iceConfig, constraints);
  162. this.updateLog = [];
  163. this.stats = {};
  164. this.statsinterval = null;
  165. /**
  166. * @type {number} The max number of stats to keep in this.stats. Limit to
  167. * 300 values, i.e. 5 minutes; set to 0 to disable
  168. */
  169. this.maxstats = options.maxstats;
  170. const Interop = require('sdp-interop').Interop;
  171. this.interop = new Interop();
  172. const Simulcast = require('sdp-simulcast');
  173. this.simulcast = new Simulcast({ numOfLayers: SIMULCAST_LAYERS,
  174. explodeRemoteSimulcast: false });
  175. this.sdpConsistency = new SdpConsistency(this.toString());
  176. /**
  177. * Munges local SDP provided to the Jingle Session in order to prevent from
  178. * sending SSRC updates on attach/detach and mute/unmute (for video).
  179. * @type {LocalSdpMunger}
  180. */
  181. this.localSdpMunger = new LocalSdpMunger(this);
  182. /**
  183. * TracablePeerConnection uses RTC's eventEmitter
  184. * @type {EventEmitter}
  185. */
  186. this.eventEmitter = rtc.eventEmitter;
  187. this.rtxModifier = new RtxModifier();
  188. // override as desired
  189. this.trace = (what, info) => {
  190. logger.debug(what, info);
  191. /*
  192. if (info && browser.isIExplorer()) {
  193. if (info.length > 1024) {
  194. logger.warn('WTRACE', what, info.substr(1024));
  195. }
  196. if (info.length > 2048) {
  197. logger.warn('WTRACE', what, info.substr(2048));
  198. }
  199. }*/
  200. this.updateLog.push({
  201. time: new Date(),
  202. type: what,
  203. value: info || ''
  204. });
  205. };
  206. this.onicecandidate = null;
  207. this.peerconnection.onicecandidate = event => {
  208. // FIXME: this causes stack overflow with Temasys Plugin
  209. if (!browser.isTemasysPluginUsed()) {
  210. this.trace(
  211. 'onicecandidate',
  212. JSON.stringify(event.candidate, null, ' '));
  213. }
  214. if (this.onicecandidate !== null) {
  215. this.onicecandidate(event);
  216. }
  217. };
  218. this.peerconnection.onaddstream
  219. = event => this._remoteStreamAdded(event.stream);
  220. this.peerconnection.onremovestream
  221. = event => this._remoteStreamRemoved(event.stream);
  222. this.onsignalingstatechange = null;
  223. this.peerconnection.onsignalingstatechange = event => {
  224. this.trace('onsignalingstatechange', this.signalingState);
  225. if (this.onsignalingstatechange !== null) {
  226. this.onsignalingstatechange(event);
  227. }
  228. };
  229. this.oniceconnectionstatechange = null;
  230. this.peerconnection.oniceconnectionstatechange = event => {
  231. this.trace('oniceconnectionstatechange', this.iceConnectionState);
  232. if (this.oniceconnectionstatechange !== null) {
  233. this.oniceconnectionstatechange(event);
  234. }
  235. };
  236. this.onnegotiationneeded = null;
  237. this.peerconnection.onnegotiationneeded = event => {
  238. this.trace('onnegotiationneeded');
  239. if (this.onnegotiationneeded !== null) {
  240. this.onnegotiationneeded(event);
  241. }
  242. };
  243. this.ondatachannel = null;
  244. this.peerconnection.ondatachannel = event => {
  245. this.trace('ondatachannel');
  246. if (this.ondatachannel !== null) {
  247. this.ondatachannel(event);
  248. }
  249. };
  250. // XXX: do all non-firefox browsers which we support also support this?
  251. if (!browser.isFirefox() && this.maxstats) {
  252. this.statsinterval = window.setInterval(() => {
  253. this.peerconnection.getStats(stats => {
  254. const results = stats.result();
  255. const now = new Date();
  256. for (let i = 0; i < results.length; ++i) {
  257. results[i].names().forEach(name => {
  258. // eslint-disable-next-line no-shadow
  259. const id = `${results[i].id}-${name}`;
  260. let s = this.stats[id];
  261. if (!s) {
  262. this.stats[id] = s = {
  263. startTime: now,
  264. endTime: now,
  265. values: [],
  266. times: []
  267. };
  268. }
  269. s.values.push(results[i].stat(name));
  270. s.times.push(now.getTime());
  271. if (s.values.length > this.maxstats) {
  272. s.values.shift();
  273. s.times.shift();
  274. }
  275. s.endTime = now;
  276. });
  277. }
  278. });
  279. }, 1000);
  280. }
  281. logger.info(`Create new ${this}`);
  282. }
  283. /* eslint-enable max-params */
  284. /**
  285. * Returns a string representation of a SessionDescription object.
  286. */
  287. const dumpSDP = function(description) {
  288. if (typeof description === 'undefined' || description === null) {
  289. return '';
  290. }
  291. return `type: ${description.type}\r\n${description.sdp}`;
  292. };
  293. /**
  294. * Forwards the {@link peerconnection.iceConnectionState} state except that it
  295. * will convert "completed" into "connected" where both mean that the ICE has
  296. * succeeded and is up and running. We never see "completed" state for
  297. * the JVB connection, but it started appearing for the P2P one. This method
  298. * allows to adapt old logic to this new situation.
  299. * @return {string}
  300. */
  301. TraceablePeerConnection.prototype.getConnectionState = function() {
  302. const state = this.peerconnection.iceConnectionState;
  303. if (state === 'completed') {
  304. return 'connected';
  305. }
  306. return state;
  307. };
  308. /**
  309. * Obtains the media direction for given {@link MediaType}. The method takes
  310. * into account whether or not there are any local tracks for media and
  311. * the {@link audioTransferActive} and {@link videoTransferActive} flags.
  312. * @param {MediaType} mediaType
  313. * @return {string} one of the SDP direction constants ('sendrecv, 'recvonly'
  314. * etc.) which should be used when setting local description on the peer
  315. * connection.
  316. * @private
  317. */
  318. TraceablePeerConnection.prototype._getDesiredMediaDirection = function(
  319. mediaType) {
  320. let mediaTransferActive = true;
  321. if (mediaType === MediaType.AUDIO) {
  322. mediaTransferActive = this.audioTransferActive;
  323. } else if (mediaType === MediaType.VIDEO) {
  324. mediaTransferActive = this.videoTransferActive;
  325. }
  326. if (mediaTransferActive) {
  327. return this.hasAnyTracksOfType(mediaType) ? 'sendrecv' : 'recvonly';
  328. }
  329. return 'inactive';
  330. };
  331. /**
  332. * Tells whether or not this TPC instance is using Simulcast.
  333. * @return {boolean} <tt>true</tt> if simulcast is enabled and active or
  334. * <tt>false</tt> if it's turned off.
  335. */
  336. TraceablePeerConnection.prototype.isSimulcastOn = function() {
  337. return !this.options.disableSimulcast
  338. && browser.supportsSimulcast()
  339. // Firefox has been added as supporting simulcast, but it is
  340. // experimental so we only want to do it for firefox if the config
  341. // option is set. Unfortunately, browser::supportsSimulcast()
  342. // doesn't have a reference to the config options, so we have
  343. // to do it here
  344. && (!browser.isFirefox()
  345. || this.options.enableFirefoxSimulcast);
  346. };
  347. /**
  348. * Handles {@link SignalingEvents.PEER_VIDEO_TYPE_CHANGED}
  349. * @param {string} endpointId the video owner's ID (MUC nickname)
  350. * @param {VideoType} videoType the new value
  351. * @private
  352. */
  353. TraceablePeerConnection.prototype._peerVideoTypeChanged = function(
  354. endpointId,
  355. videoType) {
  356. // Check if endpointId has a value to avoid action on random track
  357. if (!endpointId) {
  358. logger.error(`No endpointID on peerVideoTypeChanged ${this}`);
  359. return;
  360. }
  361. const videoTrack = this.getRemoteTracks(endpointId, MediaType.VIDEO);
  362. if (videoTrack.length) {
  363. // NOTE 1 track per media type is assumed
  364. videoTrack[0]._setVideoType(videoType);
  365. }
  366. };
  367. /**
  368. * Handles remote track mute / unmute events.
  369. * @param {string} endpointId the track owner's identifier (MUC nickname)
  370. * @param {MediaType} mediaType "audio" or "video"
  371. * @param {boolean} isMuted the new mute state
  372. * @private
  373. */
  374. TraceablePeerConnection.prototype._peerMutedChanged = function(
  375. endpointId,
  376. mediaType,
  377. isMuted) {
  378. // Check if endpointId is a value to avoid doing action on all remote tracks
  379. if (!endpointId) {
  380. logger.error('On peerMuteChanged - no endpoint ID');
  381. return;
  382. }
  383. const track = this.getRemoteTracks(endpointId, mediaType);
  384. if (track.length) {
  385. // NOTE 1 track per media type is assumed
  386. track[0].setMute(isMuted);
  387. }
  388. };
  389. /**
  390. * Obtains local tracks for given {@link MediaType}. If the <tt>mediaType</tt>
  391. * argument is omitted the list of all local tracks will be returned.
  392. * @param {MediaType} [mediaType]
  393. * @return {Array<JitsiLocalTrack>}
  394. */
  395. TraceablePeerConnection.prototype.getLocalTracks = function(mediaType) {
  396. let tracks = Array.from(this.localTracks.values());
  397. if (mediaType !== undefined) {
  398. tracks = tracks.filter(track => track.getType() === mediaType);
  399. }
  400. return tracks;
  401. };
  402. /**
  403. * Checks whether or not this {@link TraceablePeerConnection} instance contains
  404. * any local tracks for given <tt>mediaType</tt>.
  405. * @param {MediaType} mediaType
  406. * @return {boolean}
  407. */
  408. TraceablePeerConnection.prototype.hasAnyTracksOfType = function(mediaType) {
  409. if (!mediaType) {
  410. throw new Error('"mediaType" is required');
  411. }
  412. return this.getLocalTracks(mediaType).length > 0;
  413. };
  414. /**
  415. * Obtains all remote tracks currently known to this PeerConnection instance.
  416. * @param {string} [endpointId] the track owner's identifier (MUC nickname)
  417. * @param {MediaType} [mediaType] the remote tracks will be filtered
  418. * by their media type if this argument is specified.
  419. * @return {Array<JitsiRemoteTrack>}
  420. */
  421. TraceablePeerConnection.prototype.getRemoteTracks = function(
  422. endpointId,
  423. mediaType) {
  424. const remoteTracks = [];
  425. const endpoints
  426. = endpointId ? [ endpointId ] : this.remoteTracks.keys();
  427. for (const endpoint of endpoints) {
  428. const endpointTrackMap = this.remoteTracks.get(endpoint);
  429. if (!endpointTrackMap) {
  430. // Otherwise an empty Map() would have to be allocated above
  431. // eslint-disable-next-line no-continue
  432. continue;
  433. }
  434. for (const trackMediaType of endpointTrackMap.keys()) {
  435. // per media type filtering
  436. if (!mediaType || mediaType === trackMediaType) {
  437. const mediaTrack = endpointTrackMap.get(trackMediaType);
  438. if (mediaTrack) {
  439. remoteTracks.push(mediaTrack);
  440. }
  441. }
  442. }
  443. }
  444. return remoteTracks;
  445. };
  446. /**
  447. * Tries to find {@link JitsiTrack} for given SSRC number. It will search both
  448. * local and remote tracks bound to this instance.
  449. * @param {number} ssrc
  450. * @return {JitsiTrack|null}
  451. */
  452. TraceablePeerConnection.prototype.getTrackBySSRC = function(ssrc) {
  453. if (typeof ssrc !== 'number') {
  454. throw new Error(`SSRC ${ssrc} is not a number`);
  455. }
  456. for (const localTrack of this.localTracks.values()) {
  457. if (this.getLocalSSRC(localTrack) === ssrc) {
  458. return localTrack;
  459. }
  460. }
  461. for (const remoteTrack of this.getRemoteTracks()) {
  462. if (remoteTrack.getSSRC() === ssrc) {
  463. return remoteTrack;
  464. }
  465. }
  466. return null;
  467. };
  468. /**
  469. * Called when new remote MediaStream is added to the PeerConnection.
  470. * @param {MediaStream} stream the WebRTC MediaStream for remote participant
  471. */
  472. TraceablePeerConnection.prototype._remoteStreamAdded = function(stream) {
  473. const streamId = RTC.getStreamID(stream);
  474. if (!RTC.isUserStreamById(streamId)) {
  475. logger.info(
  476. `${this} ignored remote 'stream added' event for non-user stream`
  477. + `id: ${streamId}`);
  478. return;
  479. }
  480. // Bind 'addtrack'/'removetrack' event handlers
  481. if (browser.isChrome() || browser.isNWJS()
  482. || browser.isElectron() || browser.isEdge()) {
  483. stream.onaddtrack = event => {
  484. this._remoteTrackAdded(stream, event.track);
  485. };
  486. stream.onremovetrack = event => {
  487. this._remoteTrackRemoved(stream, event.track);
  488. };
  489. }
  490. // Call remoteTrackAdded for each track in the stream
  491. const streamAudioTracks = stream.getAudioTracks();
  492. for (const audioTrack of streamAudioTracks) {
  493. this._remoteTrackAdded(stream, audioTrack);
  494. }
  495. const streamVideoTracks = stream.getVideoTracks();
  496. for (const videoTrack of streamVideoTracks) {
  497. this._remoteTrackAdded(stream, videoTrack);
  498. }
  499. };
  500. /**
  501. * Called on "track added" and "stream added" PeerConnection events (because we
  502. * handle streams on per track basis). Finds the owner and the SSRC for
  503. * the track and passes that to ChatRoom for further processing.
  504. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  505. * the parent of the track
  506. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  507. * participant
  508. */
  509. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track) {
  510. const streamId = RTC.getStreamID(stream);
  511. const mediaType = track.kind;
  512. logger.info(`${this} remote track added:`, streamId, mediaType);
  513. // look up an associated JID for a stream id
  514. if (!mediaType) {
  515. GlobalOnErrorHandler.callErrorHandler(
  516. new Error(
  517. `MediaType undefined for remote track, stream id: ${streamId}`
  518. ));
  519. // Abort
  520. return;
  521. }
  522. const remoteSDP = new SDP(this.remoteDescription.sdp);
  523. const mediaLines
  524. = remoteSDP.media.filter(mls => mls.startsWith(`m=${mediaType}`));
  525. if (!mediaLines.length) {
  526. GlobalOnErrorHandler.callErrorHandler(
  527. new Error(
  528. `No media lines for type ${
  529. mediaType} found in remote SDP for remote track: ${
  530. streamId}`));
  531. // Abort
  532. return;
  533. }
  534. let ssrcLines = SDPUtil.findLines(mediaLines[0], 'a=ssrc:');
  535. ssrcLines = ssrcLines.filter(
  536. line => {
  537. const msid
  538. = browser.isTemasysPluginUsed() ? 'mslabel' : 'msid';
  539. return line.indexOf(`${msid}:${streamId}`) !== -1;
  540. });
  541. if (!ssrcLines.length) {
  542. GlobalOnErrorHandler.callErrorHandler(
  543. new Error(
  544. `No SSRC lines for streamId ${
  545. streamId} for remote track, media type: ${mediaType}`));
  546. // Abort
  547. return;
  548. }
  549. // FIXME the length of ssrcLines[0] not verified, but it will fail
  550. // with global error handler anyway
  551. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  552. const trackSsrc = Number(ssrcStr);
  553. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  554. if (isNaN(trackSsrc) || trackSsrc < 0) {
  555. GlobalOnErrorHandler.callErrorHandler(
  556. new Error(
  557. `Invalid SSRC: ${ssrcStr} for remote track, msid: ${
  558. streamId} media type: ${mediaType}`));
  559. // Abort
  560. return;
  561. } else if (!ownerEndpointId) {
  562. GlobalOnErrorHandler.callErrorHandler(
  563. new Error(
  564. `No SSRC owner known for: ${
  565. trackSsrc} for remote track, msid: ${
  566. streamId} media type: ${mediaType}`));
  567. // Abort
  568. return;
  569. }
  570. logger.log(`${this} associated ssrc`, ownerEndpointId, trackSsrc);
  571. const peerMediaInfo
  572. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  573. if (!peerMediaInfo) {
  574. GlobalOnErrorHandler.callErrorHandler(
  575. new Error(
  576. `${this}: no peer media info available for ${
  577. ownerEndpointId}`));
  578. return;
  579. }
  580. const muted = peerMediaInfo.muted;
  581. const videoType = peerMediaInfo.videoType; // can be undefined
  582. this._createRemoteTrack(
  583. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  584. };
  585. // FIXME cleanup params
  586. /* eslint-disable max-params */
  587. /**
  588. * Initializes a new JitsiRemoteTrack instance with the data provided by
  589. * the signaling layer and SDP.
  590. *
  591. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  592. * @param {MediaStream} stream the WebRTC stream instance
  593. * @param {MediaStreamTrack} track the WebRTC track instance
  594. * @param {MediaType} mediaType the track's type of the media
  595. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  596. * @param {number} ssrc the track's main SSRC number
  597. * @param {boolean} muted the initial muted status
  598. */
  599. TraceablePeerConnection.prototype._createRemoteTrack = function(
  600. ownerEndpointId,
  601. stream,
  602. track,
  603. mediaType,
  604. videoType,
  605. ssrc,
  606. muted) {
  607. const remoteTrack
  608. = new JitsiRemoteTrack(
  609. this.rtc, this.rtc.conference,
  610. ownerEndpointId,
  611. stream, track, mediaType, videoType, ssrc, muted, this.isP2P);
  612. let remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  613. if (!remoteTracksMap) {
  614. remoteTracksMap = new Map();
  615. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  616. }
  617. if (remoteTracksMap.has(mediaType)) {
  618. logger.error(
  619. `${this} overwriting remote track! ${remoteTrack}`,
  620. ownerEndpointId, mediaType);
  621. }
  622. remoteTracksMap.set(mediaType, remoteTrack);
  623. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack);
  624. };
  625. /* eslint-enable max-params */
  626. /**
  627. * Handles remote stream removal.
  628. * @param stream the WebRTC MediaStream object which is being removed from the
  629. * PeerConnection
  630. */
  631. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  632. if (!RTC.isUserStream(stream)) {
  633. const id = RTC.getStreamID(stream);
  634. logger.info(
  635. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  636. return;
  637. }
  638. // Call remoteTrackRemoved for each track in the stream
  639. const streamVideoTracks = stream.getVideoTracks();
  640. for (const videoTrack of streamVideoTracks) {
  641. this._remoteTrackRemoved(stream, videoTrack);
  642. }
  643. const streamAudioTracks = stream.getAudioTracks();
  644. for (const audioTrack of streamAudioTracks) {
  645. this._remoteTrackRemoved(stream, audioTrack);
  646. }
  647. };
  648. /**
  649. * Handles remote media track removal.
  650. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  651. * of the track.
  652. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  653. * removed from the PeerConnection.
  654. */
  655. TraceablePeerConnection.prototype._remoteTrackRemoved = function(
  656. stream,
  657. track) {
  658. const streamId = RTC.getStreamID(stream);
  659. const trackId = track && RTC.getTrackID(track);
  660. logger.info(`${this} - remote track removed: ${streamId}, ${trackId}`);
  661. if (!streamId) {
  662. GlobalOnErrorHandler.callErrorHandler(
  663. new Error(`${this} remote track removal failed - no stream ID`));
  664. return;
  665. }
  666. if (!trackId) {
  667. GlobalOnErrorHandler.callErrorHandler(
  668. new Error(`${this} remote track removal failed - no track ID`));
  669. return;
  670. }
  671. if (!this._removeRemoteTrackById(streamId, trackId)) {
  672. // NOTE this warning is always printed when user leaves the room,
  673. // because we remove remote tracks manually on MUC member left event,
  674. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  675. // ignore this warning, but still it's better to keep it printed for
  676. // debugging purposes.
  677. //
  678. // We could change the behaviour to emit track removed only from here,
  679. // but the order of the events will change and consuming apps could
  680. // behave unexpectedly (the "user left" event would come before "track
  681. // removed" events).
  682. logger.warn(
  683. `${this} Removed track not found for msid: ${streamId},
  684. track id: ${trackId}`);
  685. }
  686. };
  687. /**
  688. * Finds remote track by it's stream and track ids.
  689. * @param {string} streamId the media stream id as defined by the WebRTC
  690. * @param {string} trackId the media track id as defined by the WebRTC
  691. * @return {JitsiRemoteTrack|undefined} the track's instance or
  692. * <tt>undefined</tt> if not found.
  693. * @private
  694. */
  695. TraceablePeerConnection.prototype._getRemoteTrackById = function(
  696. streamId,
  697. trackId) {
  698. // .find will break the loop once the first match is found
  699. for (const endpointTrackMap of this.remoteTracks.values()) {
  700. for (const mediaTrack of endpointTrackMap.values()) {
  701. // FIXME verify and try to use ===
  702. /* eslint-disable eqeqeq */
  703. if (mediaTrack.getStreamId() == streamId
  704. && mediaTrack.getTrackId() == trackId) {
  705. return mediaTrack;
  706. }
  707. /* eslint-enable eqeqeq */
  708. }
  709. }
  710. return undefined;
  711. };
  712. /**
  713. * Removes all JitsiRemoteTracks associated with given MUC nickname
  714. * (resource part of the JID). Returns array of removed tracks.
  715. *
  716. * @param {string} owner - The resource part of the MUC JID.
  717. * @returns {JitsiRemoteTrack[]}
  718. */
  719. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  720. const removedTracks = [];
  721. const remoteTracksMap = this.remoteTracks.get(owner);
  722. if (remoteTracksMap) {
  723. const removedAudioTrack = remoteTracksMap.get(MediaType.AUDIO);
  724. const removedVideoTrack = remoteTracksMap.get(MediaType.VIDEO);
  725. removedAudioTrack && removedTracks.push(removedAudioTrack);
  726. removedVideoTrack && removedTracks.push(removedVideoTrack);
  727. this.remoteTracks.delete(owner);
  728. }
  729. logger.debug(
  730. `${this} removed remote tracks for ${owner} count: ${
  731. removedTracks.length}`);
  732. return removedTracks;
  733. };
  734. /**
  735. * Removes and disposes given <tt>JitsiRemoteTrack</tt> instance. Emits
  736. * {@link RTCEvents.REMOTE_TRACK_REMOVED}.
  737. * @param {JitsiRemoteTrack} toBeRemoved
  738. */
  739. TraceablePeerConnection.prototype._removeRemoteTrack = function(toBeRemoved) {
  740. toBeRemoved.dispose();
  741. const participantId = toBeRemoved.getParticipantId();
  742. const remoteTracksMap = this.remoteTracks.get(participantId);
  743. if (!remoteTracksMap) {
  744. logger.error(
  745. `removeRemoteTrack: no remote tracks map for ${participantId}`);
  746. } else if (!remoteTracksMap.delete(toBeRemoved.getType())) {
  747. logger.error(
  748. `Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  749. }
  750. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  751. };
  752. /**
  753. * Removes and disposes <tt>JitsiRemoteTrack</tt> identified by given stream and
  754. * track ids.
  755. *
  756. * @param {string} streamId the media stream id as defined by the WebRTC
  757. * @param {string} trackId the media track id as defined by the WebRTC
  758. * @returns {JitsiRemoteTrack|undefined} the track which has been removed or
  759. * <tt>undefined</tt> if no track matching given stream and track ids was
  760. * found.
  761. */
  762. TraceablePeerConnection.prototype._removeRemoteTrackById = function(
  763. streamId,
  764. trackId) {
  765. const toBeRemoved = this._getRemoteTrackById(streamId, trackId);
  766. if (toBeRemoved) {
  767. this._removeRemoteTrack(toBeRemoved);
  768. }
  769. return toBeRemoved;
  770. };
  771. /**
  772. * @typedef {Object} SSRCGroupInfo
  773. * @property {Array<number>} ssrcs group's SSRCs
  774. * @property {string} semantics
  775. */
  776. /**
  777. * @typedef {Object} TrackSSRCInfo
  778. * @property {Array<number>} ssrcs track's SSRCs
  779. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  780. */
  781. /**
  782. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  783. * @param {Object} desc the WebRTC SDP instance.
  784. * @return {Map<string,TrackSSRCInfo>}
  785. */
  786. function extractSSRCMap(desc) {
  787. /**
  788. * Track SSRC infos mapped by stream ID (msid)
  789. * @type {Map<string,TrackSSRCInfo>}
  790. */
  791. const ssrcMap = new Map();
  792. /**
  793. * Groups mapped by primary SSRC number
  794. * @type {Map<number,Array<SSRCGroupInfo>>}
  795. */
  796. const groupsMap = new Map();
  797. if (typeof desc !== 'object' || desc === null
  798. || typeof desc.sdp !== 'string') {
  799. logger.warn('An empty description was passed as an argument.');
  800. return ssrcMap;
  801. }
  802. const session = transform.parse(desc.sdp);
  803. if (!Array.isArray(session.media)) {
  804. return ssrcMap;
  805. }
  806. for (const mLine of session.media) {
  807. if (!Array.isArray(mLine.ssrcs)) {
  808. continue; // eslint-disable-line no-continue
  809. }
  810. if (Array.isArray(mLine.ssrcGroups)) {
  811. for (const group of mLine.ssrcGroups) {
  812. if (typeof group.semantics !== 'undefined'
  813. && typeof group.ssrcs !== 'undefined') {
  814. // Parse SSRCs and store as numbers
  815. const groupSSRCs
  816. = group.ssrcs.split(' ').map(
  817. ssrcStr => parseInt(ssrcStr, 10));
  818. const primarySSRC = groupSSRCs[0];
  819. // Note that group.semantics is already present
  820. group.ssrcs = groupSSRCs;
  821. // eslint-disable-next-line max-depth
  822. if (!groupsMap.has(primarySSRC)) {
  823. groupsMap.set(primarySSRC, []);
  824. }
  825. groupsMap.get(primarySSRC).push(group);
  826. }
  827. }
  828. }
  829. for (const ssrc of mLine.ssrcs) {
  830. if (ssrc.attribute !== 'msid') {
  831. continue; // eslint-disable-line no-continue
  832. }
  833. const msid = ssrc.value;
  834. let ssrcInfo = ssrcMap.get(msid);
  835. if (!ssrcInfo) {
  836. ssrcInfo = {
  837. ssrcs: [],
  838. groups: [],
  839. msid
  840. };
  841. ssrcMap.set(msid, ssrcInfo);
  842. }
  843. const ssrcNumber = ssrc.id;
  844. ssrcInfo.ssrcs.push(ssrcNumber);
  845. if (groupsMap.has(ssrcNumber)) {
  846. const ssrcGroups = groupsMap.get(ssrcNumber);
  847. for (const group of ssrcGroups) {
  848. ssrcInfo.groups.push(group);
  849. }
  850. }
  851. }
  852. }
  853. return ssrcMap;
  854. }
  855. /**
  856. * Takes a SessionDescription object and returns a "normalized" version.
  857. * Currently it only takes care of ordering the a=ssrc lines.
  858. */
  859. const normalizePlanB = function(desc) {
  860. if (typeof desc !== 'object' || desc === null
  861. || typeof desc.sdp !== 'string') {
  862. logger.warn('An empty description was passed as an argument.');
  863. return desc;
  864. }
  865. // eslint-disable-next-line no-shadow
  866. const transform = require('sdp-transform');
  867. const session = transform.parse(desc.sdp);
  868. if (typeof session !== 'undefined'
  869. && typeof session.media !== 'undefined'
  870. && Array.isArray(session.media)) {
  871. session.media.forEach(mLine => {
  872. // Chrome appears to be picky about the order in which a=ssrc lines
  873. // are listed in an m-line when rtx is enabled (and thus there are
  874. // a=ssrc-group lines with FID semantics). Specifically if we have
  875. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  876. // the "a=ssrc:S1" lines, SRD fails.
  877. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  878. // first.
  879. const firstSsrcs = [];
  880. const newSsrcLines = [];
  881. if (typeof mLine.ssrcGroups !== 'undefined'
  882. && Array.isArray(mLine.ssrcGroups)) {
  883. mLine.ssrcGroups.forEach(group => {
  884. if (typeof group.semantics !== 'undefined'
  885. && group.semantics === 'FID') {
  886. if (typeof group.ssrcs !== 'undefined') {
  887. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  888. }
  889. }
  890. });
  891. }
  892. if (Array.isArray(mLine.ssrcs)) {
  893. let i;
  894. for (i = 0; i < mLine.ssrcs.length; i++) {
  895. if (typeof mLine.ssrcs[i] === 'object'
  896. && typeof mLine.ssrcs[i].id !== 'undefined'
  897. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  898. newSsrcLines.push(mLine.ssrcs[i]);
  899. delete mLine.ssrcs[i];
  900. }
  901. }
  902. for (i = 0; i < mLine.ssrcs.length; i++) {
  903. if (typeof mLine.ssrcs[i] !== 'undefined') {
  904. newSsrcLines.push(mLine.ssrcs[i]);
  905. }
  906. }
  907. mLine.ssrcs = newSsrcLines;
  908. }
  909. });
  910. }
  911. const resStr = transform.write(session);
  912. return new RTCSessionDescription({
  913. type: desc.type,
  914. sdp: resStr
  915. });
  916. };
  917. /**
  918. * Makes sure that both audio and video directions are configured as 'sendrecv'.
  919. * @param {Object} localDescription the SDP object as defined by WebRTC.
  920. */
  921. const enforceSendRecv = function(localDescription) {
  922. if (!localDescription) {
  923. throw new Error('No local description passed in.');
  924. }
  925. const transformer = new SdpTransformWrap(localDescription.sdp);
  926. const audioMedia = transformer.selectMedia('audio');
  927. let changed = false;
  928. if (audioMedia && audioMedia.direction !== 'sendrecv') {
  929. audioMedia.direction = 'sendrecv';
  930. changed = true;
  931. }
  932. const videoMedia = transformer.selectMedia('video');
  933. if (videoMedia && videoMedia.direction !== 'sendrecv') {
  934. videoMedia.direction = 'sendrecv';
  935. changed = true;
  936. }
  937. if (changed) {
  938. return new RTCSessionDescription({
  939. type: localDescription.type,
  940. sdp: transformer.toRawSDP()
  941. });
  942. }
  943. return localDescription;
  944. };
  945. /**
  946. *
  947. * @param {JitsiLocalTrack} localTrack
  948. */
  949. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  950. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  951. return ssrcInfo && ssrcInfo.ssrcs[0];
  952. };
  953. /**
  954. * When doing unified plan simulcast, we'll have a set of ssrcs with the
  955. * same msid but no ssrc-group, since unified plan signals the simulcast
  956. * group via the a=simulcast line. Unfortunately, Jicofo will complain
  957. * if it sees ssrcs with matching msids but no ssrc-group, so we'll inject
  958. * an ssrc-group line to make Jicofo happy.
  959. * NOTE: unlike plan B simulcast, the ssrcs in this inject ssrc-group will
  960. * NOT necessarily be in order of quality (low to high) because:
  961. * a) when translating between unified plan and plan b the order of the ssrcs
  962. * is not preserved and
  963. * b) it isn't guaranteed that firefox will give them to us in order to begin
  964. * with
  965. * @param desc A session description object (with 'type' and 'sdp' fields)
  966. * @return A session description object with its sdp field modified to
  967. * contain an inject ssrc-group for simulcast
  968. */
  969. TraceablePeerConnection.prototype._injectSsrcGroupForUnifiedSimulcast
  970. = function(desc) {
  971. const sdp = transform.parse(desc.sdp);
  972. const video = sdp.media.find(mline => mline.type === 'video');
  973. if (video.simulcast_03) {
  974. const ssrcs = [];
  975. video.ssrcs.forEach(ssrc => {
  976. if (ssrc.attribute === 'msid') {
  977. ssrcs.push(ssrc.id);
  978. }
  979. });
  980. video.ssrcGroups = video.ssrcGroups || [];
  981. if (video.ssrcGroups.find(group => group.semantics === 'SIM')) {
  982. // Group already exists, no need to do anything
  983. return desc;
  984. }
  985. video.ssrcGroups.push({
  986. semantics: 'SIM',
  987. ssrcs: ssrcs.join(' ')
  988. });
  989. }
  990. return new RTCSessionDescription({
  991. type: desc.type,
  992. sdp: transform.write(sdp)
  993. });
  994. };
  995. /* eslint-disable-next-line vars-on-top */
  996. const getters = {
  997. signalingState() {
  998. return this.peerconnection.signalingState;
  999. },
  1000. iceConnectionState() {
  1001. return this.peerconnection.iceConnectionState;
  1002. },
  1003. localDescription() {
  1004. let desc = this.peerconnection.localDescription;
  1005. if (!desc) {
  1006. logger.debug('getLocalDescription no localDescription found');
  1007. return {};
  1008. }
  1009. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  1010. // if we're running on FF, transform to Plan B first.
  1011. if (browser.usesUnifiedPlan()) {
  1012. desc = this.interop.toPlanB(desc);
  1013. this.trace('getLocalDescription::postTransform (Plan B)',
  1014. dumpSDP(desc));
  1015. desc = this._injectSsrcGroupForUnifiedSimulcast(desc);
  1016. this.trace('getLocalDescription::postTransform (inject ssrc group)',
  1017. dumpSDP(desc));
  1018. }
  1019. if (browser.doesVideoMuteByStreamRemove()) {
  1020. desc = this.localSdpMunger.maybeAddMutedLocalVideoTracksToSDP(desc);
  1021. logger.debug(
  1022. 'getLocalDescription::postTransform (munge local SDP)', desc);
  1023. }
  1024. // What comes out of this getter will be signalled over Jingle to
  1025. // the other peer, so we need to make sure the media direction is
  1026. // 'sendrecv' because we won't change the direction later and don't want
  1027. // the other peer to think we can't send or receive.
  1028. //
  1029. // Note that the description we set in chrome does have the accurate
  1030. // direction (e.g. 'recvonly'), since that is technically what is
  1031. // happening (check setLocalDescription impl).
  1032. desc = enforceSendRecv(desc);
  1033. // See the method's doc for more info about this transformation.
  1034. desc = this.localSdpMunger.transformStreamIdentifiers(desc);
  1035. return desc;
  1036. },
  1037. remoteDescription() {
  1038. let desc = this.peerconnection.remoteDescription;
  1039. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  1040. // if we're running on FF, transform to Plan B first.
  1041. if (browser.usesUnifiedPlan()) {
  1042. desc = this.interop.toPlanB(desc);
  1043. this.trace(
  1044. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  1045. }
  1046. return desc || {};
  1047. }
  1048. };
  1049. Object.keys(getters).forEach(prop => {
  1050. Object.defineProperty(
  1051. TraceablePeerConnection.prototype,
  1052. prop, {
  1053. get: getters[prop]
  1054. }
  1055. );
  1056. });
  1057. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  1058. return this.localSSRCs.get(rtcId);
  1059. };
  1060. /**
  1061. * Add {@link JitsiLocalTrack} to this TPC.
  1062. * @param {JitsiLocalTrack} track
  1063. */
  1064. TraceablePeerConnection.prototype.addTrack = function(track) {
  1065. const rtcId = track.rtcId;
  1066. logger.info(`add ${track} to: ${this}`);
  1067. if (this.localTracks.has(rtcId)) {
  1068. logger.error(`${track} is already in ${this}`);
  1069. return;
  1070. }
  1071. this.localTracks.set(rtcId, track);
  1072. const webrtcStream = track.getOriginalStream();
  1073. if (webrtcStream) {
  1074. this._addStream(webrtcStream);
  1075. // It's not ok for a track to not have a WebRTC stream if:
  1076. } else if (!browser.doesVideoMuteByStreamRemove()
  1077. || track.isAudioTrack()
  1078. || (track.isVideoTrack() && !track.isMuted())) {
  1079. logger.error(`${this} no WebRTC stream for: ${track}`);
  1080. }
  1081. // Muted video tracks do not have WebRTC stream
  1082. if (browser.doesVideoMuteByStreamRemove()
  1083. && track.isVideoTrack() && track.isMuted()) {
  1084. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  1085. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  1086. const simGroup
  1087. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  1088. if (simGroup) {
  1089. this.simulcast.setSsrcCache(simGroup.ssrcs);
  1090. }
  1091. const fidGroups
  1092. = ssrcInfo.groups.filter(
  1093. groupInfo => groupInfo.semantics === 'FID');
  1094. if (fidGroups) {
  1095. const rtxSsrcMapping = new Map();
  1096. fidGroups.forEach(fidGroup => {
  1097. const primarySsrc = fidGroup.ssrcs[0];
  1098. const rtxSsrc = fidGroup.ssrcs[1];
  1099. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  1100. });
  1101. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  1102. }
  1103. }
  1104. };
  1105. /**
  1106. * Adds local track as part of the unmute operation.
  1107. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  1108. * operation
  1109. * @return {boolean} <tt>true</tt> if the state of underlying PC has changed and
  1110. * the renegotiation is required or <tt>false</tt> otherwise.
  1111. */
  1112. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  1113. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  1114. // Abort
  1115. return false;
  1116. }
  1117. logger.info(`Adding ${track} as unmute to ${this}`);
  1118. const webRtcStream = track.getOriginalStream();
  1119. if (!webRtcStream) {
  1120. logger.error(
  1121. `Unable to add ${track} as unmute to ${this} - no WebRTC stream`);
  1122. return false;
  1123. }
  1124. this._addStream(webRtcStream);
  1125. return true;
  1126. };
  1127. /**
  1128. * Adds WebRTC media stream to the underlying PeerConnection
  1129. * @param {MediaStream} mediaStream
  1130. * @private
  1131. */
  1132. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  1133. this.peerconnection.addStream(mediaStream);
  1134. this._addedStreams.push(mediaStream);
  1135. };
  1136. /**
  1137. * Removes WebRTC media stream from the underlying PeerConection
  1138. * @param {MediaStream} mediaStream
  1139. */
  1140. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  1141. if (browser.isFirefox()) {
  1142. this._handleFirefoxRemoveStream(mediaStream);
  1143. } else {
  1144. this.peerconnection.removeStream(mediaStream);
  1145. }
  1146. this._addedStreams
  1147. = this._addedStreams.filter(stream => stream !== mediaStream);
  1148. };
  1149. /**
  1150. * This method when called will check if given <tt>localTrack</tt> belongs to
  1151. * this TPC (that it has been previously added using {@link addTrack}). If the
  1152. * track does not belong an error message will be logged.
  1153. * @param {string} methodName the method name that will be logged in an error
  1154. * message
  1155. * @param {JitsiLocalTrack} localTrack
  1156. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1157. * <tt>false</tt> otherwise.
  1158. * @private
  1159. */
  1160. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1161. methodName,
  1162. localTrack) {
  1163. const doesBelong = this.localTracks.has(localTrack.rtcId);
  1164. if (!doesBelong) {
  1165. logger.error(
  1166. `${methodName}: ${localTrack} does not belong to ${this}`);
  1167. }
  1168. return doesBelong;
  1169. };
  1170. /**
  1171. * Tells if the given WebRTC <tt>MediaStream</tt> has been added to
  1172. * the underlying WebRTC PeerConnection.
  1173. * @param {MediaStream} mediaStream
  1174. * @returns {boolean}
  1175. */
  1176. TraceablePeerConnection.prototype.isMediaStreamInPc = function(mediaStream) {
  1177. return this._addedStreams.indexOf(mediaStream) > -1;
  1178. };
  1179. /**
  1180. * Remove local track from this TPC.
  1181. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1182. *
  1183. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1184. * The same applies to addTrack.
  1185. */
  1186. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1187. const webRtcStream = localTrack.getOriginalStream();
  1188. this.trace(
  1189. 'removeStream',
  1190. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1191. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1192. // Abort - nothing to be done here
  1193. return;
  1194. }
  1195. this.localTracks.delete(localTrack.rtcId);
  1196. this.localSSRCs.delete(localTrack.rtcId);
  1197. if (webRtcStream) {
  1198. if (browser.isFirefox()) {
  1199. this._handleFirefoxRemoveStream(webRtcStream);
  1200. } else {
  1201. this.peerconnection.removeStream(webRtcStream);
  1202. }
  1203. }
  1204. };
  1205. /**
  1206. * Removes local track as part of the mute operation.
  1207. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1208. * the mute operation.
  1209. * @return {boolean} <tt>true</tt> if the underlying PeerConnection's state has
  1210. * changed and the renegotiation is required or <tt>false</tt> otherwise.
  1211. */
  1212. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1213. const webRtcStream = localTrack.getOriginalStream();
  1214. this.trace(
  1215. 'removeStreamMute',
  1216. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1217. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1218. // Abort - nothing to be done here
  1219. return false;
  1220. }
  1221. if (webRtcStream) {
  1222. logger.info(
  1223. `Removing ${localTrack} as mute from ${this}`);
  1224. this._removeStream(webRtcStream);
  1225. return true;
  1226. }
  1227. logger.error(`removeStreamMute - no WebRTC stream for ${localTrack}`);
  1228. return false;
  1229. };
  1230. /**
  1231. * Remove stream handling for firefox
  1232. * @param stream: webrtc media stream
  1233. */
  1234. TraceablePeerConnection.prototype._handleFirefoxRemoveStream = function(
  1235. stream) {
  1236. if (!stream) {
  1237. // There is nothing to be changed
  1238. return;
  1239. }
  1240. let sender = null;
  1241. // On Firefox we don't replace MediaStreams as this messes up the
  1242. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1243. // of complications. Instead, we use the RTPSender and remove just
  1244. // the track.
  1245. let track = null;
  1246. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  1247. track = stream.getAudioTracks()[0];
  1248. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  1249. track = stream.getVideoTracks()[0];
  1250. }
  1251. if (!track) {
  1252. logger.error('Cannot remove tracks: no tracks.');
  1253. return;
  1254. }
  1255. // Find the right sender (for audio or video)
  1256. this.peerconnection.getSenders().some(s => {
  1257. if (s.track === track) {
  1258. sender = s;
  1259. return true;
  1260. }
  1261. return false;
  1262. });
  1263. if (sender) {
  1264. this.peerconnection.removeTrack(sender);
  1265. } else {
  1266. logger.log('Cannot remove tracks: no RTPSender.');
  1267. }
  1268. };
  1269. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1270. this.trace('createDataChannel', label, opts);
  1271. return this.peerconnection.createDataChannel(label, opts);
  1272. };
  1273. /**
  1274. * Ensures that the simulcast ssrc-group appears after any other ssrc-groups
  1275. * in the SDP so that simulcast is properly activated.
  1276. *
  1277. * @param {Object} localSdp the WebRTC session description instance for
  1278. * the local description.
  1279. * @private
  1280. */
  1281. TraceablePeerConnection.prototype._ensureSimulcastGroupIsLast = function(
  1282. localSdp) {
  1283. let sdpStr = localSdp.sdp;
  1284. const videoStartIndex = sdpStr.indexOf('m=video');
  1285. const simStartIndex = sdpStr.indexOf('a=ssrc-group:SIM', videoStartIndex);
  1286. let otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1287. if (simStartIndex === -1
  1288. || otherStartIndex === -1
  1289. || otherStartIndex === simStartIndex) {
  1290. return localSdp;
  1291. }
  1292. const simEndIndex = sdpStr.indexOf('\r\n', simStartIndex);
  1293. const simStr = sdpStr.substring(simStartIndex, simEndIndex + 2);
  1294. sdpStr = sdpStr.replace(simStr, '');
  1295. otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1296. const otherEndIndex = sdpStr.indexOf('\r\n', otherStartIndex);
  1297. const sdpHead = sdpStr.slice(0, otherEndIndex);
  1298. const simStrTrimmed = simStr.trim();
  1299. const sdpTail = sdpStr.slice(otherEndIndex);
  1300. sdpStr = `${sdpHead}\r\n${simStrTrimmed}${sdpTail}`;
  1301. return new RTCSessionDescription({
  1302. type: localSdp.type,
  1303. sdp: sdpStr
  1304. });
  1305. };
  1306. /**
  1307. * Will adjust audio and video media direction in the given SDP object to
  1308. * reflect the current status of the {@link audioTransferActive} and
  1309. * {@link videoTransferActive} flags.
  1310. * @param {Object} localDescription the WebRTC session description instance for
  1311. * the local description.
  1312. * @private
  1313. */
  1314. TraceablePeerConnection.prototype._adjustLocalMediaDirection = function(
  1315. localDescription) {
  1316. const transformer = new SdpTransformWrap(localDescription.sdp);
  1317. let modifiedDirection = false;
  1318. const audioMedia = transformer.selectMedia('audio');
  1319. if (audioMedia) {
  1320. const desiredAudioDirection
  1321. = this._getDesiredMediaDirection(MediaType.AUDIO);
  1322. if (audioMedia.direction !== desiredAudioDirection) {
  1323. audioMedia.direction = desiredAudioDirection;
  1324. logger.info(
  1325. `Adjusted local audio direction to ${desiredAudioDirection}`);
  1326. modifiedDirection = true;
  1327. }
  1328. } else {
  1329. logger.warn('No "audio" media found int the local description');
  1330. }
  1331. const videoMedia = transformer.selectMedia('video');
  1332. if (videoMedia) {
  1333. const desiredVideoDirection
  1334. = this._getDesiredMediaDirection(MediaType.VIDEO);
  1335. if (videoMedia.direction !== desiredVideoDirection) {
  1336. videoMedia.direction = desiredVideoDirection;
  1337. logger.info(
  1338. `Adjusted local video direction to ${desiredVideoDirection}`);
  1339. modifiedDirection = true;
  1340. }
  1341. } else {
  1342. logger.warn('No "video" media found in the local description');
  1343. }
  1344. if (modifiedDirection) {
  1345. return new RTCSessionDescription({
  1346. type: localDescription.type,
  1347. sdp: transformer.toRawSDP()
  1348. });
  1349. }
  1350. return localDescription;
  1351. };
  1352. TraceablePeerConnection.prototype.setLocalDescription = function(
  1353. description,
  1354. successCallback,
  1355. failureCallback) {
  1356. let localSdp = description;
  1357. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1358. if (this.options.disableH264 || this.options.preferH264) {
  1359. const parsedSdp = transform.parse(localSdp.sdp);
  1360. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1361. if (this.options.disableH264) {
  1362. SDPUtil.stripVideoCodec(videoMLine, 'h264');
  1363. } else {
  1364. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1365. }
  1366. localSdp = new RTCSessionDescription({
  1367. type: localSdp.type,
  1368. sdp: transform.write(parsedSdp)
  1369. });
  1370. this.trace('setLocalDescription::postTransform (H264)',
  1371. dumpSDP(localSdp));
  1372. }
  1373. localSdp = this._adjustLocalMediaDirection(localSdp);
  1374. localSdp = this._ensureSimulcastGroupIsLast(localSdp);
  1375. // if we're using unified plan, transform to it first.
  1376. if (browser.usesUnifiedPlan()) {
  1377. localSdp = this.interop.toUnifiedPlan(localSdp);
  1378. this.trace(
  1379. 'setLocalDescription::postTransform (Unified Plan)',
  1380. dumpSDP(localSdp));
  1381. }
  1382. this.peerconnection.setLocalDescription(localSdp,
  1383. () => {
  1384. this.trace('setLocalDescriptionOnSuccess');
  1385. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1386. if (localUfrag !== this.localUfrag) {
  1387. this.localUfrag = localUfrag;
  1388. this.eventEmitter.emit(
  1389. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1390. }
  1391. successCallback();
  1392. },
  1393. err => {
  1394. this.trace('setLocalDescriptionOnFailure', err);
  1395. this.eventEmitter.emit(
  1396. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1397. err, this);
  1398. failureCallback(err);
  1399. }
  1400. );
  1401. };
  1402. /**
  1403. * Enables/disables audio media transmission on this peer connection. When
  1404. * disabled the SDP audio media direction in the local SDP will be adjusted to
  1405. * 'inactive' which means that no data will be sent nor accepted, but
  1406. * the connection should be kept alive.
  1407. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  1408. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1409. * no effect.
  1410. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1411. * needs to be executed in order for the changes to take effect or
  1412. * <tt>false</tt> if the given value was the same as the previous one.
  1413. * @public
  1414. */
  1415. TraceablePeerConnection.prototype.setAudioTransferActive = function(active) {
  1416. logger.debug(`${this} audio transfer active: ${active}`);
  1417. const changed = this.audioTransferActive !== active;
  1418. this.audioTransferActive = active;
  1419. return changed;
  1420. };
  1421. /**
  1422. * Takes in a *unified plan* offer and inserts the appropriate
  1423. * parameters for adding simulcast receive support.
  1424. * @param {Object} desc - A session description object
  1425. * @param {String} desc.type - the type (offer/answer)
  1426. * @param {String} desc.sdp - the sdp content
  1427. *
  1428. * @return {Object} A session description (same format as above) object
  1429. * with its sdp field modified to advertise simulcast receive support
  1430. */
  1431. TraceablePeerConnection.prototype._insertUnifiedPlanSimulcastReceive
  1432. = function(desc) {
  1433. const sdp = transform.parse(desc.sdp);
  1434. const video = sdp.media.find(mline => mline.type === 'video');
  1435. // In order of lowest to highest spatial quality
  1436. video.rids = [
  1437. {
  1438. id: SIM_LAYER_1_RID,
  1439. direction: 'recv'
  1440. },
  1441. {
  1442. id: SIM_LAYER_2_RID,
  1443. direction: 'recv'
  1444. },
  1445. {
  1446. id: SIM_LAYER_3_RID,
  1447. direction: 'recv'
  1448. }
  1449. ];
  1450. // eslint-disable-next-line camelcase
  1451. video.simulcast_03 = {
  1452. value: `recv rid=${SIM_LAYER_RIDS.join(';')}`
  1453. };
  1454. return new RTCSessionDescription({
  1455. type: desc.type,
  1456. sdp: transform.write(sdp)
  1457. });
  1458. };
  1459. TraceablePeerConnection.prototype.setRemoteDescription = function(
  1460. description,
  1461. successCallback,
  1462. failureCallback) {
  1463. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1464. // TODO the focus should squeze or explode the remote simulcast
  1465. // eslint-disable-next-line no-param-reassign
  1466. description = this.simulcast.mungeRemoteDescription(description);
  1467. this.trace(
  1468. 'setRemoteDescription::postTransform (simulcast)',
  1469. dumpSDP(description));
  1470. if (this.options.preferH264) {
  1471. const parsedSdp = transform.parse(description.sdp);
  1472. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1473. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1474. // eslint-disable-next-line no-param-reassign
  1475. description = new RTCSessionDescription({
  1476. type: description.type,
  1477. sdp: transform.write(parsedSdp)
  1478. });
  1479. }
  1480. // If the browser uses unified plan, transform to it first
  1481. if (browser.usesUnifiedPlan()) {
  1482. // eslint-disable-next-line no-param-reassign
  1483. description = new RTCSessionDescription({
  1484. type: description.type,
  1485. sdp: this.rtxModifier.stripRtx(description.sdp)
  1486. });
  1487. this.trace(
  1488. 'setRemoteDescription::postTransform (stripRtx)',
  1489. dumpSDP(description));
  1490. // eslint-disable-next-line no-param-reassign
  1491. description = this.interop.toUnifiedPlan(description);
  1492. this.trace(
  1493. 'setRemoteDescription::postTransform (Plan A)',
  1494. dumpSDP(description));
  1495. if (this.isSimulcastOn()) {
  1496. // eslint-disable-next-line no-param-reassign
  1497. description = this._insertUnifiedPlanSimulcastReceive(description);
  1498. this.trace(
  1499. 'setRemoteDescription::postTransform (sim receive)',
  1500. dumpSDP(description));
  1501. }
  1502. } else {
  1503. // Plan B
  1504. // eslint-disable-next-line no-param-reassign
  1505. description = normalizePlanB(description);
  1506. }
  1507. // Safari WebRTC errors when no supported video codec is found in the offer.
  1508. // To prevent the error, inject H264 into the video mLine.
  1509. if (browser.isSafariWithWebrtc()) {
  1510. logger.debug('Maybe injecting H264 into the remote description');
  1511. // eslint-disable-next-line no-param-reassign
  1512. description = this._injectH264IfNotPresent(description);
  1513. }
  1514. this.peerconnection.setRemoteDescription(
  1515. description,
  1516. () => {
  1517. this.trace('setRemoteDescriptionOnSuccess');
  1518. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  1519. if (remoteUfrag !== this.remoteUfrag) {
  1520. this.remoteUfrag = remoteUfrag;
  1521. this.eventEmitter.emit(
  1522. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1523. }
  1524. successCallback();
  1525. },
  1526. err => {
  1527. this.trace('setRemoteDescriptionOnFailure', err);
  1528. this.eventEmitter.emit(
  1529. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  1530. err,
  1531. this);
  1532. failureCallback(err);
  1533. });
  1534. };
  1535. /**
  1536. * Inserts an H264 payload into the description if not already present. This is
  1537. * need for Safari WebRTC, which errors when no supported video codec is found
  1538. * in the offer. Related bug reports:
  1539. * https://bugs.webkit.org/show_bug.cgi?id=173141
  1540. * https://bugs.chromium.org/p/webrtc/issues/detail?id=4957
  1541. *
  1542. * @param {RTCSessionDescription} description - An RTCSessionDescription
  1543. * to inject with an H264 payload.
  1544. * @private
  1545. * @returns {RTCSessionDescription}
  1546. */
  1547. TraceablePeerConnection.prototype._injectH264IfNotPresent = function(
  1548. description) {
  1549. const parsedSdp = transform.parse(description.sdp);
  1550. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1551. if (!videoMLine) {
  1552. logger.debug('No videoMLine found, no need to inject H264.');
  1553. return description;
  1554. }
  1555. if (videoMLine.rtp.some(rtp => rtp.codec.toLowerCase() === 'h264')) {
  1556. logger.debug('H264 codec found in video mLine, no need to inject.');
  1557. return description;
  1558. }
  1559. const { fmtp, payloads, rtp } = videoMLine;
  1560. const payloadsArray = payloads.toString().split(' ');
  1561. let dummyPayloadType;
  1562. for (let i = 127; i >= 96; i--) {
  1563. if (!payloadsArray.includes(i)) {
  1564. dummyPayloadType = i;
  1565. payloadsArray.push(i);
  1566. videoMLine.payloads = payloadsArray.join(' ');
  1567. break;
  1568. }
  1569. }
  1570. if (typeof dummyPayloadType === 'undefined') {
  1571. logger.error('Could not find valid payload type to inject.');
  1572. return description;
  1573. }
  1574. rtp.push({
  1575. codec: 'H264',
  1576. payload: dummyPayloadType,
  1577. rate: 90000
  1578. });
  1579. fmtp.push({
  1580. config: 'level-asymmetry-allowed=1;'
  1581. + 'packetization-mode=1;'
  1582. + 'profile-level-id=42e01f',
  1583. payload: dummyPayloadType
  1584. });
  1585. logger.debug(
  1586. `Injecting H264 payload type ${dummyPayloadType} into video mLine.`);
  1587. return new RTCSessionDescription({
  1588. type: description.type,
  1589. sdp: transform.write(parsedSdp)
  1590. });
  1591. };
  1592. /**
  1593. * Enables/disables video media transmission on this peer connection. When
  1594. * disabled the SDP video media direction in the local SDP will be adjusted to
  1595. * 'inactive' which means that no data will be sent nor accepted, but
  1596. * the connection should be kept alive.
  1597. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  1598. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1599. * no effect.
  1600. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1601. * needs to be executed in order for the changes to take effect or
  1602. * <tt>false</tt> if the given value was the same as the previous one.
  1603. * @public
  1604. */
  1605. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  1606. logger.debug(`${this} video transfer active: ${active}`);
  1607. const changed = this.videoTransferActive !== active;
  1608. this.videoTransferActive = active;
  1609. return changed;
  1610. };
  1611. /**
  1612. * Makes the underlying TraceablePeerConnection generate new SSRC for
  1613. * the recvonly video stream.
  1614. */
  1615. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  1616. const newSSRC = SDPUtil.generateSsrc();
  1617. logger.info(`${this} generated new recvonly SSRC: ${newSSRC}`);
  1618. this.sdpConsistency.setPrimarySsrc(newSSRC);
  1619. };
  1620. /**
  1621. * Makes the underlying TraceablePeerConnection forget the current primary video
  1622. * SSRC.
  1623. */
  1624. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  1625. logger.info('Clearing primary video SSRC!');
  1626. this.sdpConsistency.clearVideoSsrcCache();
  1627. };
  1628. /**
  1629. * Closes underlying WebRTC PeerConnection instance and removes all remote
  1630. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  1631. * them.
  1632. */
  1633. TraceablePeerConnection.prototype.close = function() {
  1634. this.trace('stop');
  1635. // Off SignalingEvents
  1636. this.signalingLayer.off(
  1637. SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  1638. this.signalingLayer.off(
  1639. SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  1640. for (const peerTracks of this.remoteTracks.values()) {
  1641. for (const remoteTrack of peerTracks.values()) {
  1642. this._removeRemoteTrack(remoteTrack);
  1643. }
  1644. }
  1645. this.remoteTracks.clear();
  1646. this._addedStreams = [];
  1647. if (!this.rtc._removePeerConnection(this)) {
  1648. logger.error('RTC._removePeerConnection returned false');
  1649. }
  1650. if (this.statsinterval !== null) {
  1651. window.clearInterval(this.statsinterval);
  1652. this.statsinterval = null;
  1653. }
  1654. logger.info(`Closing ${this}...`);
  1655. this.peerconnection.close();
  1656. };
  1657. /**
  1658. * Modifies the values of the setup attributes (defined by
  1659. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  1660. * answer in order to overcome a delay of 1 second in the connection
  1661. * establishment between Chrome and Videobridge.
  1662. *
  1663. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  1664. * being prepared to respond
  1665. * @param {SDP} answer - the SDP to modify
  1666. * @private
  1667. */
  1668. const _fixAnswerRFC4145Setup = function(offer, answer) {
  1669. if (!browser.isChrome()) {
  1670. // It looks like Firefox doesn't agree with the fix (at least in its
  1671. // current implementation) because it effectively remains active even
  1672. // after we tell it to become passive. Apart from Firefox which I tested
  1673. // after the fix was deployed, I tested Chrome only. In order to prevent
  1674. // issues with other browsers, limit the fix to Chrome for the time
  1675. // being.
  1676. return;
  1677. }
  1678. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  1679. // answerer (as orchestrated by Jicofo). In accord with
  1680. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  1681. // are ICE FULL agents, Videobridge will take on the controlling role and
  1682. // WebRTC will take on the controlled role. In accord with
  1683. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  1684. // setup attribute value of setup:actpass and WebRTC will be allowed to
  1685. // choose either the setup attribute value of setup:active or
  1686. // setup:passive. Chrome will by default choose setup:active because it is
  1687. // RECOMMENDED by the respective RFC since setup:passive adds additional
  1688. // latency. The case of setup:active allows WebRTC to send a DTLS
  1689. // ClientHello as soon as an ICE connectivity check of its succeeds.
  1690. // Unfortunately, Videobridge will be unable to respond immediately because
  1691. // may not have WebRTC's answer or may have not completed the ICE
  1692. // connectivity establishment. Even more unfortunate is that in the
  1693. // described scenario Chrome's DTLS implementation will insist on
  1694. // retransmitting its ClientHello after a second (the time is in accord
  1695. // with the respective RFC) and will thus cause the whole connection
  1696. // establishment to exceed at least 1 second. To work around Chrome's
  1697. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  1698. // default choice of setup:active to setup:passive.
  1699. if (offer && answer
  1700. && offer.media && answer.media
  1701. && offer.media.length === answer.media.length) {
  1702. answer.media.forEach((a, i) => {
  1703. if (SDPUtil.findLine(
  1704. offer.media[i],
  1705. 'a=setup:actpass',
  1706. offer.session)) {
  1707. answer.media[i]
  1708. = a.replace(/a=setup:active/g, 'a=setup:passive');
  1709. }
  1710. });
  1711. answer.raw = answer.session + answer.media.join('');
  1712. }
  1713. };
  1714. TraceablePeerConnection.prototype.createAnswer = function(
  1715. successCallback,
  1716. failureCallback,
  1717. constraints) {
  1718. if (browser.supportsRtpSender() && this.isSimulcastOn()) {
  1719. const videoSender
  1720. = this.peerconnection.getSenders().find(sender =>
  1721. sender.track.kind === 'video');
  1722. const simParams = {
  1723. encodings: [
  1724. {
  1725. rid: SIM_LAYER_1_RID,
  1726. scaleResolutionDownBy: 4
  1727. },
  1728. {
  1729. rid: SIM_LAYER_2_RID,
  1730. scaleResolutionDownBy: 2
  1731. },
  1732. {
  1733. rid: SIM_LAYER_3_RID
  1734. }
  1735. ]
  1736. };
  1737. videoSender.setParameters(simParams);
  1738. }
  1739. this._createOfferOrAnswer(
  1740. false /* answer */, successCallback, failureCallback, constraints);
  1741. };
  1742. TraceablePeerConnection.prototype.createOffer = function(
  1743. successCallback,
  1744. failureCallback,
  1745. constraints) {
  1746. this._createOfferOrAnswer(
  1747. true /* offer */, successCallback, failureCallback, constraints);
  1748. };
  1749. /* eslint-disable max-params */
  1750. TraceablePeerConnection.prototype._createOfferOrAnswer = function(
  1751. isOffer,
  1752. successCallback,
  1753. failureCallback,
  1754. constraints) {
  1755. const logName = isOffer ? 'Offer' : 'Answer';
  1756. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  1757. const _successCallback = resultSdp => {
  1758. try {
  1759. this.trace(
  1760. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  1761. // if we're using unified plan, transform to Plan B.
  1762. if (browser.usesUnifiedPlan()) {
  1763. // eslint-disable-next-line no-param-reassign
  1764. resultSdp = this.interop.toPlanB(resultSdp);
  1765. this.trace(
  1766. `create${logName}OnSuccess::postTransform (Plan B)`,
  1767. dumpSDP(resultSdp));
  1768. if (this.isSimulcastOn()) {
  1769. // eslint-disable-next-line no-param-reassign
  1770. resultSdp
  1771. = this._injectSsrcGroupForUnifiedSimulcast(resultSdp);
  1772. this.trace(
  1773. `create${logName}OnSuccess::postTransform`
  1774. + '(inject ssrc group)', dumpSDP(resultSdp));
  1775. }
  1776. }
  1777. /**
  1778. * We don't keep ssrcs consitent for Firefox because rewriting
  1779. * the ssrcs between createAnswer and setLocalDescription breaks
  1780. * the caching in sdp-interop (sdp-interop must know about all
  1781. * ssrcs, and it updates its cache in toPlanB so if we rewrite them
  1782. * after that, when we try and go back to unified plan it will
  1783. * complain about unmapped ssrcs)
  1784. */
  1785. if (!browser.isFirefox()) {
  1786. // If there are no local video tracks, then a "recvonly"
  1787. // SSRC needs to be generated
  1788. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  1789. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  1790. this.generateRecvonlySsrc();
  1791. }
  1792. // eslint-disable-next-line no-param-reassign
  1793. resultSdp = new RTCSessionDescription({
  1794. type: resultSdp.type,
  1795. sdp: this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  1796. resultSdp.sdp)
  1797. });
  1798. this.trace(
  1799. `create${logName}OnSuccess::postTransform `
  1800. + '(make primary audio/video ssrcs consistent)',
  1801. dumpSDP(resultSdp));
  1802. }
  1803. // Add simulcast streams if simulcast is enabled
  1804. if (this.isSimulcastOn()) {
  1805. // eslint-disable-next-line no-param-reassign
  1806. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  1807. this.trace(
  1808. `create${logName}`
  1809. + 'OnSuccess::postTransform (simulcast)',
  1810. dumpSDP(resultSdp));
  1811. }
  1812. if (!this.options.disableRtx && browser.supportsRtx()) {
  1813. // eslint-disable-next-line no-param-reassign
  1814. resultSdp = new RTCSessionDescription({
  1815. type: resultSdp.type,
  1816. sdp: this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp)
  1817. });
  1818. this.trace(
  1819. `create${logName}`
  1820. + 'OnSuccess::postTransform (rtx modifier)',
  1821. dumpSDP(resultSdp));
  1822. }
  1823. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  1824. // details)
  1825. if (!isOffer) {
  1826. const remoteDescription
  1827. = new SDP(this.remoteDescription.sdp);
  1828. const localDescription = new SDP(resultSdp.sdp);
  1829. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  1830. // eslint-disable-next-line no-param-reassign
  1831. resultSdp = new RTCSessionDescription({
  1832. type: resultSdp.type,
  1833. sdp: localDescription.raw
  1834. });
  1835. }
  1836. const ssrcMap = extractSSRCMap(resultSdp);
  1837. logger.debug('Got local SSRCs MAP: ', ssrcMap);
  1838. this._processLocalSSRCsMap(ssrcMap);
  1839. successCallback(resultSdp);
  1840. } catch (e) {
  1841. this.trace(`create${logName}OnError`, e);
  1842. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  1843. logger.error(`create${logName}OnError`, e, dumpSDP(resultSdp));
  1844. failureCallback(e);
  1845. }
  1846. };
  1847. const _errorCallback = err => {
  1848. this.trace(`create${logName}OnFailure`, err);
  1849. const eventType
  1850. = isOffer
  1851. ? RTCEvents.CREATE_OFFER_FAILED
  1852. : RTCEvents.CREATE_ANSWER_FAILED;
  1853. this.eventEmitter.emit(eventType, err, this);
  1854. failureCallback(err);
  1855. };
  1856. // NOTE Temasys plugin does not support "bind" on peerconnection methods
  1857. if (isOffer) {
  1858. this.peerconnection.createOffer(
  1859. _successCallback, _errorCallback, constraints);
  1860. } else {
  1861. this.peerconnection.createAnswer(
  1862. _successCallback, _errorCallback, constraints);
  1863. }
  1864. };
  1865. /* eslint-enable max-params */
  1866. /**
  1867. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  1868. * @param {TrackSSRCInfo} ssrcObj
  1869. * @return {number|null} the primary SSRC or <tt>null</tt>
  1870. */
  1871. function extractPrimarySSRC(ssrcObj) {
  1872. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  1873. return ssrcObj.groups[0].ssrcs[0];
  1874. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  1875. return ssrcObj.ssrcs[0];
  1876. }
  1877. return null;
  1878. }
  1879. /**
  1880. * Goes over the SSRC map extracted from the latest local description and tries
  1881. * to match them with the local tracks (by MSID). Will update the values
  1882. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  1883. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  1884. * @private
  1885. */
  1886. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  1887. for (const track of this.localTracks.values()) {
  1888. const trackMSID = track.getMSID();
  1889. if (ssrcMap.has(trackMSID)) {
  1890. const newSSRC = ssrcMap.get(trackMSID);
  1891. if (!newSSRC) {
  1892. logger.error(`No SSRC found for: ${trackMSID} in ${this}`);
  1893. return;
  1894. }
  1895. const oldSSRC = this.localSSRCs.get(track.rtcId);
  1896. const newSSRCNum = extractPrimarySSRC(newSSRC);
  1897. const oldSSRCNum = extractPrimarySSRC(oldSSRC);
  1898. // eslint-disable-next-line no-negated-condition
  1899. if (newSSRCNum !== oldSSRCNum) {
  1900. if (oldSSRCNum === null) {
  1901. logger.info(
  1902. `Storing new local SSRC for ${track} in ${this}`,
  1903. newSSRC);
  1904. } else {
  1905. logger.error(
  1906. `Overwriting SSRC for ${track} ${trackMSID} in ${this
  1907. } with: `, newSSRC);
  1908. }
  1909. this.localSSRCs.set(track.rtcId, newSSRC);
  1910. this.eventEmitter.emit(
  1911. RTCEvents.LOCAL_TRACK_SSRC_UPDATED, track, newSSRCNum);
  1912. } else {
  1913. logger.debug(
  1914. `The local SSRC(${newSSRCNum}) for ${track} ${trackMSID}`
  1915. + `is still up to date in ${this}`);
  1916. }
  1917. } else {
  1918. logger.warn(`No local track matched with: ${trackMSID} in ${this}`);
  1919. }
  1920. }
  1921. };
  1922. TraceablePeerConnection.prototype.addIceCandidate = function(
  1923. candidate,
  1924. successCallback,
  1925. failureCallback) {
  1926. // var self = this;
  1927. // Calling JSON.stringify with temasys objects causes a stack overflow, so
  1928. // instead pick out values to log.
  1929. this.trace('addIceCandidate', JSON.stringify({
  1930. candidate: candidate.candidate,
  1931. sdpMid: candidate.sdpMid,
  1932. sdpMLineIndex: candidate.sdpMLineIndex,
  1933. usernameFragment: candidate.usernameFragment
  1934. }, null, ' '));
  1935. this.peerconnection.addIceCandidate(
  1936. candidate, successCallback, failureCallback);
  1937. /* maybe later
  1938. this.peerconnection.addIceCandidate(candidate,
  1939. function () {
  1940. self.trace('addIceCandidateOnSuccess');
  1941. successCallback();
  1942. },
  1943. function (err) {
  1944. self.trace('addIceCandidateOnFailure', err);
  1945. failureCallback(err);
  1946. }
  1947. );
  1948. */
  1949. };
  1950. /**
  1951. * Obtains call-related stats from the peer connection.
  1952. *
  1953. * @param {Function} callback - The function to invoke after successfully
  1954. * obtaining stats.
  1955. * @param {Function} errback - The function to invoke after failing to obtain
  1956. * stats.
  1957. * @returns {void}
  1958. */
  1959. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  1960. // TODO: Is this the correct way to handle Opera, Temasys?
  1961. // TODO (brian): After moving all browsers to adapter, check if adapter is
  1962. // accounting for different getStats apis, making the browser-checking-if
  1963. // unnecessary.
  1964. if (browser.isFirefox()
  1965. || browser.isTemasysPluginUsed()
  1966. || browser.isReactNative()) {
  1967. this.peerconnection.getStats(
  1968. null,
  1969. callback,
  1970. errback || (() => {
  1971. // Making sure that getStats won't fail if error callback is
  1972. // not passed.
  1973. }));
  1974. } else if (browser.isSafariWithWebrtc()) {
  1975. // FIXME: Safari's native stats implementation is not compatibile with
  1976. // existing stats processing logic. Skip implementing stats for now to
  1977. // at least get native webrtc Safari available for use.
  1978. } else {
  1979. this.peerconnection.getStats(callback);
  1980. }
  1981. };
  1982. /**
  1983. * Generates and stores new SSRC info object for given local track.
  1984. * The method should be called only for a video track being added to this TPC
  1985. * in the muted state (given that the current browser uses this strategy).
  1986. * @param {JitsiLocalTrack} track
  1987. * @return {TPCSSRCInfo}
  1988. */
  1989. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  1990. const rtcId = track.rtcId;
  1991. let ssrcInfo = this._getSSRC(rtcId);
  1992. if (ssrcInfo) {
  1993. logger.error(`Will overwrite local SSRCs for track ID: ${rtcId}`);
  1994. }
  1995. if (this.isSimulcastOn()) {
  1996. ssrcInfo = {
  1997. ssrcs: [],
  1998. groups: []
  1999. };
  2000. for (let i = 0; i < SIMULCAST_LAYERS; i++) {
  2001. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  2002. }
  2003. ssrcInfo.groups.push({
  2004. ssrcs: ssrcInfo.ssrcs.slice(),
  2005. semantics: 'SIM'
  2006. });
  2007. } else {
  2008. ssrcInfo = {
  2009. ssrcs: [ SDPUtil.generateSsrc() ],
  2010. groups: []
  2011. };
  2012. }
  2013. if (!this.options.disableRtx && browser.supportsRtx()) {
  2014. // Specifically use a for loop here because we'll
  2015. // be adding to the list we're iterating over, so we
  2016. // only want to iterate through the items originally
  2017. // on the list
  2018. const currNumSsrcs = ssrcInfo.ssrcs.length;
  2019. for (let i = 0; i < currNumSsrcs; ++i) {
  2020. const primarySsrc = ssrcInfo.ssrcs[i];
  2021. const rtxSsrc = SDPUtil.generateSsrc();
  2022. ssrcInfo.ssrcs.push(rtxSsrc);
  2023. ssrcInfo.groups.push({
  2024. ssrcs: [ primarySsrc, rtxSsrc ],
  2025. semantics: 'FID'
  2026. });
  2027. }
  2028. }
  2029. ssrcInfo.msid = track.storedMSID;
  2030. this.localSSRCs.set(rtcId, ssrcInfo);
  2031. return ssrcInfo;
  2032. };
  2033. /**
  2034. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  2035. * instance.
  2036. * @return {string}
  2037. */
  2038. TraceablePeerConnection.prototype.toString = function() {
  2039. return `TPC[${this.id},p2p:${this.isP2P}]`;
  2040. };