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

TraceablePeerConnection.js 79KB

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