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

TraceablePeerConnection.js 78KB

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