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

TraceablePeerConnection.js 79KB

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