You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TraceablePeerConnection.js 78KB

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