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

TraceablePeerConnection.js 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. /* global __filename, mozRTCPeerConnection, webkitRTCPeerConnection,
  2. RTCPeerConnection, RTCSessionDescription */
  3. import { getLogger } from 'jitsi-meet-logger';
  4. import * as GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  5. import RTC from './RTC';
  6. import RTCBrowserType from './RTCBrowserType.js';
  7. import RTCEvents from '../../service/RTC/RTCEvents';
  8. import RtxModifier from '../xmpp/RtxModifier.js';
  9. // FIXME SDP tools should end up in some kind of util module
  10. import SDP from '../xmpp/SDP';
  11. import SdpConsistency from '../xmpp/SdpConsistency.js';
  12. import SDPUtil from '../xmpp/SDPUtil';
  13. import transform from 'sdp-transform';
  14. const logger = getLogger(__filename);
  15. const SIMULCAST_LAYERS = 3;
  16. /**
  17. * Creates new instance of 'TraceablePeerConnection'.
  18. *
  19. * @param {RTC} rtc the instance of <tt>RTC</tt> service
  20. * @param {number} id the peer connection id assigned by the parent RTC module.
  21. * @param {SignalingLayer} signalingLayer the signaling layer instance
  22. * @param {object} ice_config WebRTC 'PeerConnection' ICE config
  23. * @param {object} constraints WebRTC 'PeerConnection' constraints
  24. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  25. * @param {boolean} options.disableSimulcast if set to 'true' will disable
  26. * the simulcast
  27. * @param {boolean} options.disableRtx if set to 'true' will disable the RTX
  28. * @param {boolean} options.preferH264 if set to 'true' H264 will be preferred
  29. * over other video codecs.
  30. *
  31. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  32. * debug the peer connection. Since many other responsibilities have been added
  33. * it would make sense to extract a separate class from it and come up with
  34. * a more suitable name.
  35. *
  36. * @constructor
  37. */
  38. function TraceablePeerConnection(rtc, id, signalingLayer, ice_config,
  39. constraints, options) {
  40. const self = this;
  41. /**
  42. * The parent instance of RTC service which created this
  43. * <tt>TracablePeerConnection</tt>.
  44. * @type {RTC}
  45. */
  46. this.rtc = rtc;
  47. /**
  48. * The peer connection identifier assigned by the RTC module.
  49. * @type {number}
  50. */
  51. this.id = id;
  52. /**
  53. * The signaling layer which operates this peer connection.
  54. * @type {SignalingLayer}
  55. */
  56. this.signalingLayer = signalingLayer;
  57. this.options = options;
  58. let RTCPeerConnectionType = null;
  59. if (RTCBrowserType.isFirefox()) {
  60. RTCPeerConnectionType = mozRTCPeerConnection;
  61. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  62. RTCPeerConnectionType = RTCPeerConnection;
  63. } else {
  64. RTCPeerConnectionType = webkitRTCPeerConnection;
  65. }
  66. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  67. this.updateLog = [];
  68. this.stats = {};
  69. this.statsinterval = null;
  70. /**
  71. * @type {number}
  72. */
  73. this.maxstats = 0;
  74. const Interop = require('sdp-interop').Interop;
  75. this.interop = new Interop();
  76. const Simulcast = require('sdp-simulcast');
  77. this.simulcast = new Simulcast({ numOfLayers: SIMULCAST_LAYERS,
  78. explodeRemoteSimulcast: false });
  79. this.sdpConsistency = new SdpConsistency();
  80. /**
  81. * TracablePeerConnection uses RTC's eventEmitter
  82. * @type {EventEmitter}
  83. */
  84. this.eventEmitter = rtc.eventEmitter;
  85. this.rtxModifier = new RtxModifier();
  86. // override as desired
  87. this.trace = function(what, info) {
  88. /* logger.warn('WTRACE', what, info);
  89. if (info && RTCBrowserType.isIExplorer()) {
  90. if (info.length > 1024) {
  91. logger.warn('WTRACE', what, info.substr(1024));
  92. }
  93. if (info.length > 2048) {
  94. logger.warn('WTRACE', what, info.substr(2048));
  95. }
  96. }*/
  97. self.updateLog.push({
  98. time: new Date(),
  99. type: what,
  100. value: info || ''
  101. });
  102. };
  103. this.onicecandidate = null;
  104. this.peerconnection.onicecandidate = function(event) {
  105. // FIXME: this causes stack overflow with Temasys Plugin
  106. if (!RTCBrowserType.isTemasysPluginUsed()) {
  107. self.trace(
  108. 'onicecandidate',
  109. JSON.stringify(event.candidate, null, ' '));
  110. }
  111. if (self.onicecandidate !== null) {
  112. self.onicecandidate(event);
  113. }
  114. };
  115. this.onaddstream = null;
  116. this.peerconnection.onaddstream = function(event) {
  117. self.trace('onaddstream', event.stream.id);
  118. if (self.onaddstream !== null) {
  119. self.onaddstream(event);
  120. }
  121. };
  122. this.onremovestream = null;
  123. this.peerconnection.onremovestream = function(event) {
  124. self.trace('onremovestream', event.stream.id);
  125. if (self.onremovestream !== null) {
  126. self.onremovestream(event);
  127. }
  128. };
  129. this.peerconnection.onaddstream = function(event) {
  130. self._remoteStreamAdded(event.stream);
  131. };
  132. this.peerconnection.onremovestream = function(event) {
  133. self._remoteStreamRemoved(event.stream);
  134. };
  135. this.onsignalingstatechange = null;
  136. this.peerconnection.onsignalingstatechange = function(event) {
  137. self.trace('onsignalingstatechange', self.signalingState);
  138. if (self.onsignalingstatechange !== null) {
  139. self.onsignalingstatechange(event);
  140. }
  141. };
  142. this.oniceconnectionstatechange = null;
  143. this.peerconnection.oniceconnectionstatechange = function(event) {
  144. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  145. if (self.oniceconnectionstatechange !== null) {
  146. self.oniceconnectionstatechange(event);
  147. }
  148. };
  149. this.onnegotiationneeded = null;
  150. this.peerconnection.onnegotiationneeded = function(event) {
  151. self.trace('onnegotiationneeded');
  152. if (self.onnegotiationneeded !== null) {
  153. self.onnegotiationneeded(event);
  154. }
  155. };
  156. self.ondatachannel = null;
  157. this.peerconnection.ondatachannel = function(event) {
  158. self.trace('ondatachannel', event);
  159. if (self.ondatachannel !== null) {
  160. self.ondatachannel(event);
  161. }
  162. };
  163. // XXX: do all non-firefox browsers which we support also support this?
  164. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  165. this.statsinterval = window.setInterval(() => {
  166. self.peerconnection.getStats(stats => {
  167. const results = stats.result();
  168. const now = new Date();
  169. for (let i = 0; i < results.length; ++i) {
  170. results[i].names().forEach(name => {
  171. const id = `${results[i].id}-${name}`;
  172. if (!self.stats[id]) {
  173. self.stats[id] = {
  174. startTime: now,
  175. endTime: now,
  176. values: [],
  177. times: []
  178. };
  179. }
  180. self.stats[id].values.push(results[i].stat(name));
  181. self.stats[id].times.push(now.getTime());
  182. if (self.stats[id].values.length > self.maxstats) {
  183. self.stats[id].values.shift();
  184. self.stats[id].times.shift();
  185. }
  186. self.stats[id].endTime = now;
  187. });
  188. }
  189. });
  190. }, 1000);
  191. }
  192. }
  193. /**
  194. * Returns a string representation of a SessionDescription object.
  195. */
  196. const dumpSDP = function(description) {
  197. if (typeof description === 'undefined' || description === null) {
  198. return '';
  199. }
  200. return `type: ${description.type}\r\n${description.sdp}`;
  201. };
  202. /**
  203. * Called when new remote MediaStream is added to the PeerConnection.
  204. * @param {MediaStream} stream the WebRTC MediaStream for remote participant
  205. */
  206. TraceablePeerConnection.prototype._remoteStreamAdded = function(stream) {
  207. if (!RTC.isUserStream(stream)) {
  208. logger.info(
  209. 'Ignored remote \'stream added\' event for non-user stream',
  210. stream);
  211. return;
  212. }
  213. // Bind 'addtrack'/'removetrack' event handlers
  214. if (RTCBrowserType.isChrome() || RTCBrowserType.isNWJS()
  215. || RTCBrowserType.isElectron()) {
  216. stream.onaddtrack = event => {
  217. this._remoteTrackAdded(event.target, event.track);
  218. };
  219. stream.onremovetrack = event => {
  220. this._remoteTrackRemoved(event.target, event.track);
  221. };
  222. }
  223. // Call remoteTrackAdded for each track in the stream
  224. const streamAudioTracks = stream.getAudioTracks();
  225. for (const audioTrack of streamAudioTracks) {
  226. this._remoteTrackAdded(stream, audioTrack);
  227. }
  228. const streamVideoTracks = stream.getVideoTracks();
  229. for (const videoTrack of streamVideoTracks) {
  230. this._remoteTrackAdded(stream, videoTrack);
  231. }
  232. };
  233. /**
  234. * Called on "track added" and "stream added" PeerConnection events (because we
  235. * handle streams on per track basis). Finds the owner and the SSRC for
  236. * the track and passes that to ChatRoom for further processing.
  237. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  238. * the parent of the track
  239. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  240. * participant
  241. */
  242. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track) {
  243. const streamId = RTC.getStreamID(stream);
  244. const mediaType = track.kind;
  245. logger.info('Remote track added', streamId, mediaType);
  246. // look up an associated JID for a stream id
  247. if (!mediaType) {
  248. GlobalOnErrorHandler.callErrorHandler(
  249. new Error(
  250. `MediaType undefined for remote track, stream id: ${streamId}`
  251. ));
  252. // Abort
  253. return;
  254. }
  255. const remoteSDP = new SDP(this.remoteDescription.sdp);
  256. const mediaLines
  257. = remoteSDP.media.filter(
  258. mediaLines => mediaLines.startsWith(`m=${mediaType}`));
  259. if (!mediaLines.length) {
  260. GlobalOnErrorHandler.callErrorHandler(
  261. new Error(
  262. `No media lines for type ${mediaType
  263. } found in remote SDP for remote track: ${streamId}`));
  264. // Abort
  265. return;
  266. }
  267. let ssrcLines = SDPUtil.find_lines(mediaLines[0], 'a=ssrc:');
  268. ssrcLines = ssrcLines.filter(
  269. line => {
  270. const msid
  271. = RTCBrowserType.isTemasysPluginUsed() ? 'mslabel' : 'msid';
  272. return line.indexOf(`${msid}:${streamId}`) !== -1;
  273. });
  274. if (!ssrcLines.length) {
  275. GlobalOnErrorHandler.callErrorHandler(
  276. new Error(
  277. `No SSRC lines for streamId ${streamId
  278. } for remote track, media type: ${mediaType}`));
  279. // Abort
  280. return;
  281. }
  282. // FIXME the length of ssrcLines[0] not verified, but it will fail
  283. // with global error handler anyway
  284. const trackSsrc = ssrcLines[0].substring(7).split(' ')[0];
  285. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  286. if (!ownerEndpointId) {
  287. GlobalOnErrorHandler.callErrorHandler(
  288. new Error(
  289. `No SSRC owner known for: ${trackSsrc
  290. } for remote track, msid: ${streamId
  291. } media type: ${mediaType}`));
  292. // Abort
  293. return;
  294. }
  295. logger.log('associated ssrc', ownerEndpointId, trackSsrc);
  296. const peerMediaInfo
  297. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  298. if (!peerMediaInfo) {
  299. GlobalOnErrorHandler.callErrorHandler(
  300. new Error(`No peer media info available for: ${ownerEndpointId}`));
  301. // Abort
  302. return;
  303. }
  304. const muted = peerMediaInfo.muted;
  305. const videoType = peerMediaInfo.videoType; // can be undefined
  306. this.rtc._createRemoteTrack(
  307. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  308. };
  309. /**
  310. * Handles remote stream removal.
  311. * @param stream the WebRTC MediaStream object which is being removed from the
  312. * PeerConnection
  313. */
  314. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  315. if (!RTC.isUserStream(stream)) {
  316. const id = RTC.getStreamID(stream);
  317. logger.info(
  318. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  319. return;
  320. }
  321. // Call remoteTrackRemoved for each track in the stream
  322. const streamVideoTracks = stream.getVideoTracks();
  323. for (const videoTrack of streamVideoTracks) {
  324. this._remoteTrackRemoved(stream, videoTrack);
  325. }
  326. const streamAudioTracks = stream.getAudioTracks();
  327. for (const audioTrack of streamAudioTracks) {
  328. this._remoteTrackRemoved(stream, audioTrack);
  329. }
  330. };
  331. /**
  332. * Handles remote media track removal.
  333. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  334. * of the track.
  335. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  336. * removed from the PeerConnection.
  337. */
  338. TraceablePeerConnection.prototype._remoteTrackRemoved
  339. = function(stream, track) {
  340. const streamId = RTC.getStreamID(stream);
  341. const trackId = track && track.id;
  342. logger.info('Remote track removed', streamId, trackId);
  343. if (!streamId) {
  344. GlobalOnErrorHandler.callErrorHandler(
  345. new Error('Remote track removal failed - no stream ID'));
  346. // Abort
  347. return;
  348. }
  349. if (!trackId) {
  350. GlobalOnErrorHandler.callErrorHandler(
  351. new Error('Remote track removal failed - no track ID'));
  352. // Abort
  353. return;
  354. }
  355. if (!this.rtc._removeRemoteTrack(streamId, trackId)) {
  356. // NOTE this warning is always printed when user leaves the room,
  357. // because we remove remote tracks manually on MUC member left event,
  358. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  359. // ignore this warning, but still it's better to keep it printed for
  360. // debugging purposes.
  361. //
  362. // We could change the behaviour to emit track removed only from here,
  363. // but the order of the events will change and consuming apps could
  364. // behave unexpectedly (the "user left" event would come before "track
  365. // removed" events).
  366. logger.warn(
  367. `Removed track not found for msid: ${streamId},
  368. track id: ${trackId}`);
  369. }
  370. };
  371. /**
  372. * @typedef {Object} SSRCGroupInfo
  373. * @property {Array<number>} ssrcs group's SSRCs
  374. * @property {string} semantics
  375. */
  376. /**
  377. * @typedef {Object} TrackSSRCInfo
  378. * @property {Array<number>} ssrcs track's SSRCs
  379. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  380. */
  381. /**
  382. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  383. * @param {Object} desc the WebRTC SDP instance.
  384. * @return {Map<string,TrackSSRCInfo>}
  385. */
  386. function extractSSRCMap(desc) {
  387. /**
  388. * Track SSRC infos mapped by stream ID (msid)
  389. * @type {Map<string,TrackSSRCInfo>}
  390. */
  391. const ssrcMap = new Map();
  392. /**
  393. * Groups mapped by primary SSRC number
  394. * @type {Map<number,Array<SSRCGroupInfo>>}
  395. */
  396. const groupsMap = new Map();
  397. if (typeof desc !== 'object' || desc === null
  398. || typeof desc.sdp !== 'string') {
  399. logger.warn('An empty description was passed as an argument.');
  400. return ssrcMap;
  401. }
  402. const session = transform.parse(desc.sdp);
  403. if (!Array.isArray(session.media)) {
  404. return ssrcMap;
  405. }
  406. for (const mLine of session.media) {
  407. if (!Array.isArray(mLine.ssrcs)) {
  408. continue; // eslint-disable-line no-continue
  409. }
  410. if (Array.isArray(mLine.ssrcGroups)) {
  411. for (const group of mLine.ssrcGroups) {
  412. if (typeof group.semantics !== 'undefined'
  413. && typeof group.ssrcs !== 'undefined') {
  414. // Parse SSRCs and store as numbers
  415. const groupSSRCs
  416. = group.ssrcs.split(' ')
  417. .map(ssrcStr => parseInt(ssrcStr));
  418. const primarySSRC = groupSSRCs[0];
  419. // Note that group.semantics is already present
  420. group.ssrcs = groupSSRCs;
  421. if (!groupsMap.has(primarySSRC)) {
  422. groupsMap.set(primarySSRC, []);
  423. }
  424. groupsMap.get(primarySSRC).push(group);
  425. }
  426. }
  427. }
  428. for (const ssrc of mLine.ssrcs) {
  429. if (ssrc.attribute !== 'msid') {
  430. continue; // eslint-disable-line no-continue
  431. }
  432. const msid = ssrc.value;
  433. let ssrcInfo = ssrcMap.get(msid);
  434. if (!ssrcInfo) {
  435. ssrcInfo = {
  436. ssrcs: [],
  437. groups: []
  438. };
  439. ssrcMap.set(msid, ssrcInfo);
  440. }
  441. const ssrcNumber = ssrc.id;
  442. ssrcInfo.ssrcs.push(ssrcNumber);
  443. if (groupsMap.has(ssrcNumber)) {
  444. const ssrcGroups = groupsMap.get(ssrcNumber);
  445. for (const group of ssrcGroups) {
  446. ssrcInfo.groups.push(group);
  447. }
  448. }
  449. }
  450. }
  451. return ssrcMap;
  452. }
  453. /**
  454. * Takes a SessionDescription object and returns a "normalized" version.
  455. * Currently it only takes care of ordering the a=ssrc lines.
  456. */
  457. const normalizePlanB = function(desc) {
  458. if (typeof desc !== 'object' || desc === null
  459. || typeof desc.sdp !== 'string') {
  460. logger.warn('An empty description was passed as an argument.');
  461. return desc;
  462. }
  463. const transform = require('sdp-transform');
  464. const session = transform.parse(desc.sdp);
  465. if (typeof session !== 'undefined'
  466. && typeof session.media !== 'undefined'
  467. && Array.isArray(session.media)) {
  468. session.media.forEach(mLine => {
  469. // Chrome appears to be picky about the order in which a=ssrc lines
  470. // are listed in an m-line when rtx is enabled (and thus there are
  471. // a=ssrc-group lines with FID semantics). Specifically if we have
  472. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  473. // the "a=ssrc:S1" lines, SRD fails.
  474. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  475. // first.
  476. const firstSsrcs = [];
  477. const newSsrcLines = [];
  478. if (typeof mLine.ssrcGroups !== 'undefined'
  479. && Array.isArray(mLine.ssrcGroups)) {
  480. mLine.ssrcGroups.forEach(group => {
  481. if (typeof group.semantics !== 'undefined'
  482. && group.semantics === 'FID') {
  483. if (typeof group.ssrcs !== 'undefined') {
  484. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  485. }
  486. }
  487. });
  488. }
  489. if (Array.isArray(mLine.ssrcs)) {
  490. let i;
  491. for (i = 0; i < mLine.ssrcs.length; i++) {
  492. if (typeof mLine.ssrcs[i] === 'object'
  493. && typeof mLine.ssrcs[i].id !== 'undefined'
  494. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  495. newSsrcLines.push(mLine.ssrcs[i]);
  496. delete mLine.ssrcs[i];
  497. }
  498. }
  499. for (i = 0; i < mLine.ssrcs.length; i++) {
  500. if (typeof mLine.ssrcs[i] !== 'undefined') {
  501. newSsrcLines.push(mLine.ssrcs[i]);
  502. }
  503. }
  504. mLine.ssrcs = newSsrcLines;
  505. }
  506. });
  507. }
  508. const resStr = transform.write(session);
  509. return new RTCSessionDescription({
  510. type: desc.type,
  511. sdp: resStr
  512. });
  513. };
  514. const getters = {
  515. signalingState() {
  516. return this.peerconnection.signalingState;
  517. },
  518. iceConnectionState() {
  519. return this.peerconnection.iceConnectionState;
  520. },
  521. localDescription() {
  522. let desc = this.peerconnection.localDescription;
  523. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  524. // if we're running on FF, transform to Plan B first.
  525. if (RTCBrowserType.usesUnifiedPlan()) {
  526. desc = this.interop.toPlanB(desc);
  527. this.trace('getLocalDescription::postTransform (Plan B)',
  528. dumpSDP(desc));
  529. }
  530. return desc;
  531. },
  532. remoteDescription() {
  533. let desc = this.peerconnection.remoteDescription;
  534. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  535. // if we're running on FF, transform to Plan B first.
  536. if (RTCBrowserType.usesUnifiedPlan()) {
  537. desc = this.interop.toPlanB(desc);
  538. this.trace(
  539. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  540. }
  541. return desc;
  542. }
  543. };
  544. Object.keys(getters).forEach(prop => {
  545. Object.defineProperty(
  546. TraceablePeerConnection.prototype,
  547. prop, {
  548. get: getters[prop]
  549. }
  550. );
  551. });
  552. TraceablePeerConnection.prototype.addStream = function(stream, ssrcInfo) {
  553. this.trace('addStream', stream ? stream.id : 'null');
  554. if (stream) {
  555. this.peerconnection.addStream(stream);
  556. }
  557. if (ssrcInfo && ssrcInfo.type === 'addMuted') {
  558. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  559. const simGroup
  560. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  561. if (simGroup) {
  562. this.simulcast.setSsrcCache(simGroup.ssrcs);
  563. }
  564. const fidGroups
  565. = ssrcInfo.groups.filter(
  566. groupInfo => groupInfo.semantics === 'FID');
  567. if (fidGroups) {
  568. const rtxSsrcMapping = new Map();
  569. fidGroups.forEach(fidGroup => {
  570. const primarySsrc = fidGroup.ssrcs[0];
  571. const rtxSsrc = fidGroup.ssrcs[1];
  572. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  573. });
  574. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  575. }
  576. }
  577. };
  578. TraceablePeerConnection.prototype.removeStream = function(stream) {
  579. this.trace('removeStream', stream.id);
  580. // FF doesn't support this yet.
  581. if (this.peerconnection.removeStream) {
  582. this.peerconnection.removeStream(stream);
  583. }
  584. };
  585. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  586. this.trace('createDataChannel', label, opts);
  587. return this.peerconnection.createDataChannel(label, opts);
  588. };
  589. TraceablePeerConnection.prototype.setLocalDescription
  590. = function(description, successCallback, failureCallback) {
  591. this.trace(
  592. 'setLocalDescription::preTransform',
  593. dumpSDP(description));
  594. // if we're running on FF, transform to Plan A first.
  595. if (RTCBrowserType.usesUnifiedPlan()) {
  596. description = this.interop.toUnifiedPlan(description);
  597. this.trace('setLocalDescription::postTransform (Plan A)',
  598. dumpSDP(description));
  599. }
  600. const self = this;
  601. this.peerconnection.setLocalDescription(description,
  602. () => {
  603. self.trace('setLocalDescriptionOnSuccess');
  604. successCallback();
  605. },
  606. err => {
  607. self.trace('setLocalDescriptionOnFailure', err);
  608. self.eventEmitter.emit(
  609. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  610. err, self.peerconnection);
  611. failureCallback(err);
  612. }
  613. );
  614. };
  615. TraceablePeerConnection.prototype.setRemoteDescription
  616. = function(description, successCallback, failureCallback) {
  617. this.trace(
  618. 'setRemoteDescription::preTransform',
  619. dumpSDP(description));
  620. // TODO the focus should squeze or explode the remote simulcast
  621. description = this.simulcast.mungeRemoteDescription(description);
  622. this.trace(
  623. 'setRemoteDescription::postTransform (simulcast)',
  624. dumpSDP(description));
  625. if (this.options.preferH264) {
  626. const parsedSdp = transform.parse(description.sdp);
  627. const videoMLine
  628. = parsedSdp.media.find(m => m.type === 'video');
  629. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  630. description.sdp = transform.write(parsedSdp);
  631. }
  632. // if we're running on FF, transform to Plan A first.
  633. if (RTCBrowserType.usesUnifiedPlan()) {
  634. description.sdp = this.rtxModifier.stripRtx(description.sdp);
  635. this.trace(
  636. 'setRemoteDescription::postTransform (stripRtx)',
  637. dumpSDP(description));
  638. description = this.interop.toUnifiedPlan(description);
  639. this.trace(
  640. 'setRemoteDescription::postTransform (Plan A)',
  641. dumpSDP(description));
  642. }
  643. if (RTCBrowserType.usesPlanB()) {
  644. description = normalizePlanB(description);
  645. }
  646. const self = this;
  647. this.peerconnection.setRemoteDescription(description,
  648. () => {
  649. self.trace('setRemoteDescriptionOnSuccess');
  650. successCallback();
  651. },
  652. err => {
  653. self.trace('setRemoteDescriptionOnFailure', err);
  654. self.eventEmitter.emit(RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  655. err, self.peerconnection);
  656. failureCallback(err);
  657. }
  658. );
  659. /*
  660. if (this.statsinterval === null && this.maxstats > 0) {
  661. // start gathering stats
  662. }
  663. */
  664. };
  665. /**
  666. * Makes the underlying TraceablePeerConnection generate new SSRC for
  667. * the recvonly video stream.
  668. * @deprecated
  669. */
  670. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  671. // FIXME replace with SDPUtil.generateSsrc (when it's added)
  672. const newSSRC = this.generateNewStreamSSRCInfo().ssrcs[0];
  673. logger.info(`Generated new recvonly SSRC: ${newSSRC}`);
  674. this.sdpConsistency.setPrimarySsrc(newSSRC);
  675. };
  676. /**
  677. * Makes the underlying TraceablePeerConnection forget the current primary video
  678. * SSRC.
  679. * @deprecated
  680. */
  681. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  682. logger.info('Clearing primary video SSRC!');
  683. this.sdpConsistency.clearSsrcCache();
  684. };
  685. TraceablePeerConnection.prototype.close = function() {
  686. this.trace('stop');
  687. if (!this.rtc._removePeerConnection(this)) {
  688. logger.error('RTC._removePeerConnection returned false');
  689. }
  690. if (this.statsinterval !== null) {
  691. window.clearInterval(this.statsinterval);
  692. this.statsinterval = null;
  693. }
  694. this.peerconnection.close();
  695. };
  696. /**
  697. * Modifies the values of the setup attributes (defined by
  698. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  699. * answer in order to overcome a delay of 1 second in the connection
  700. * establishment between Chrome and Videobridge.
  701. *
  702. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  703. * being prepared to respond
  704. * @param {SDP} answer - the SDP to modify
  705. * @private
  706. */
  707. const _fixAnswerRFC4145Setup = function(offer, answer) {
  708. if (!RTCBrowserType.isChrome()) {
  709. // It looks like Firefox doesn't agree with the fix (at least in its
  710. // current implementation) because it effectively remains active even
  711. // after we tell it to become passive. Apart from Firefox which I tested
  712. // after the fix was deployed, I tested Chrome only. In order to prevent
  713. // issues with other browsers, limit the fix to Chrome for the time
  714. // being.
  715. return;
  716. }
  717. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  718. // answerer (as orchestrated by Jicofo). In accord with
  719. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  720. // are ICE FULL agents, Videobridge will take on the controlling role and
  721. // WebRTC will take on the controlled role. In accord with
  722. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  723. // setup attribute value of setup:actpass and WebRTC will be allowed to
  724. // choose either the setup attribute value of setup:active or
  725. // setup:passive. Chrome will by default choose setup:active because it is
  726. // RECOMMENDED by the respective RFC since setup:passive adds additional
  727. // latency. The case of setup:active allows WebRTC to send a DTLS
  728. // ClientHello as soon as an ICE connectivity check of its succeeds.
  729. // Unfortunately, Videobridge will be unable to respond immediately because
  730. // may not have WebRTC's answer or may have not completed the ICE
  731. // connectivity establishment. Even more unfortunate is that in the
  732. // described scenario Chrome's DTLS implementation will insist on
  733. // retransmitting its ClientHello after a second (the time is in accord
  734. // with the respective RFC) and will thus cause the whole connection
  735. // establishment to exceed at least 1 second. To work around Chrome's
  736. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  737. // default choice of setup:active to setup:passive.
  738. if (offer && answer
  739. && offer.media && answer.media
  740. && offer.media.length == answer.media.length) {
  741. answer.media.forEach((a, i) => {
  742. if (SDPUtil.find_line(
  743. offer.media[i],
  744. 'a=setup:actpass',
  745. offer.session)) {
  746. answer.media[i]
  747. = a.replace(/a=setup:active/g, 'a=setup:passive');
  748. }
  749. });
  750. answer.raw = answer.session + answer.media.join('');
  751. }
  752. };
  753. TraceablePeerConnection.prototype.createAnswer
  754. = function(successCallback, failureCallback, constraints) {
  755. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  756. this.peerconnection.createAnswer(
  757. answer => {
  758. try {
  759. this.trace(
  760. 'createAnswerOnSuccess::preTransform', dumpSDP(answer));
  761. // if we're running on FF, transform to Plan A first.
  762. if (RTCBrowserType.usesUnifiedPlan()) {
  763. answer = this.interop.toPlanB(answer);
  764. this.trace('createAnswerOnSuccess::postTransform (Plan B)',
  765. dumpSDP(answer));
  766. }
  767. /**
  768. * We don't keep ssrcs consitent for Firefox because rewriting
  769. * the ssrcs between createAnswer and setLocalDescription
  770. * breaks the caching in sdp-interop (sdp-interop must
  771. * know about all ssrcs, and it updates its cache in
  772. * toPlanB so if we rewrite them after that, when we
  773. * try and go back to unified plan it will complain
  774. * about unmapped ssrcs)
  775. */
  776. if (!RTCBrowserType.isFirefox()) {
  777. answer.sdp
  778. = this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  779. answer.sdp);
  780. this.trace(
  781. 'createAnswerOnSuccess::postTransform (make primary'
  782. + ' video ssrcs consistent)',
  783. dumpSDP(answer));
  784. }
  785. // Add simulcast streams if simulcast is enabled
  786. if (!this.options.disableSimulcast
  787. && this.simulcast.isSupported()) {
  788. answer = this.simulcast.mungeLocalDescription(answer);
  789. this.trace(
  790. 'createAnswerOnSuccess::postTransform (simulcast)',
  791. dumpSDP(answer));
  792. }
  793. if (!this.options.disableRtx && !RTCBrowserType.isFirefox()) {
  794. answer.sdp = this.rtxModifier.modifyRtxSsrcs(answer.sdp);
  795. this.trace(
  796. 'createAnswerOnSuccess::postTransform (rtx modifier)',
  797. dumpSDP(answer));
  798. }
  799. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  800. // details)
  801. const remoteDescription = new SDP(this.remoteDescription.sdp);
  802. const localDescription = new SDP(answer.sdp);
  803. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  804. answer.sdp = localDescription.raw;
  805. this.eventEmitter.emit(RTCEvents.SENDRECV_STREAMS_CHANGED,
  806. extractSSRCMap(answer));
  807. successCallback(answer);
  808. } catch (e) {
  809. this.trace('createAnswerOnError', e);
  810. this.trace('createAnswerOnError', dumpSDP(answer));
  811. logger.error('createAnswerOnError', e, dumpSDP(answer));
  812. failureCallback(e);
  813. }
  814. },
  815. err => {
  816. this.trace('createAnswerOnFailure', err);
  817. this.eventEmitter.emit(RTCEvents.CREATE_ANSWER_FAILED, err,
  818. this.peerconnection);
  819. failureCallback(err);
  820. },
  821. constraints
  822. );
  823. };
  824. TraceablePeerConnection.prototype.addIceCandidate
  825. // eslint-disable-next-line no-unused-vars
  826. = function(candidate, successCallback, failureCallback) {
  827. // var self = this;
  828. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  829. this.peerconnection.addIceCandidate(candidate);
  830. /* maybe later
  831. this.peerconnection.addIceCandidate(candidate,
  832. function () {
  833. self.trace('addIceCandidateOnSuccess');
  834. successCallback();
  835. },
  836. function (err) {
  837. self.trace('addIceCandidateOnFailure', err);
  838. failureCallback(err);
  839. }
  840. );
  841. */
  842. };
  843. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  844. // TODO: Is this the correct way to handle Opera, Temasys?
  845. if (RTCBrowserType.isFirefox()
  846. || RTCBrowserType.isTemasysPluginUsed()
  847. || RTCBrowserType.isReactNative()) {
  848. if (!errback) {
  849. errback = function() {
  850. // Making sure that getStats won't fail if error callback is
  851. // not passed.
  852. };
  853. }
  854. this.peerconnection.getStats(null, callback, errback);
  855. } else {
  856. this.peerconnection.getStats(callback);
  857. }
  858. };
  859. /**
  860. * Generate ssrc info object for a stream with the following properties:
  861. * - ssrcs - Array of the ssrcs associated with the stream.
  862. * - groups - Array of the groups associated with the stream.
  863. */
  864. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function() {
  865. let ssrcInfo = { ssrcs: [],
  866. groups: [] };
  867. if (!this.options.disableSimulcast
  868. && this.simulcast.isSupported()) {
  869. for (let i = 0; i < SIMULCAST_LAYERS; i++) {
  870. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  871. }
  872. ssrcInfo.groups.push({
  873. ssrcs: ssrcInfo.ssrcs.slice(),
  874. semantics: 'SIM'
  875. });
  876. } else {
  877. ssrcInfo = {
  878. ssrcs: [ SDPUtil.generateSsrc() ],
  879. groups: []
  880. };
  881. }
  882. if (!this.options.disableRtx && !RTCBrowserType.isFirefox()) {
  883. // Specifically use a for loop here because we'll
  884. // be adding to the list we're iterating over, so we
  885. // only want to iterate through the items originally
  886. // on the list
  887. const currNumSsrcs = ssrcInfo.ssrcs.length;
  888. for (let i = 0; i < currNumSsrcs; ++i) {
  889. const primarySsrc = ssrcInfo.ssrcs[i];
  890. const rtxSsrc = SDPUtil.generateSsrc();
  891. ssrcInfo.ssrcs.push(rtxSsrc);
  892. ssrcInfo.groups.push({
  893. ssrcs: [ primarySsrc, rtxSsrc ],
  894. semantics: 'FID'
  895. });
  896. }
  897. }
  898. return ssrcInfo;
  899. };
  900. module.exports = TraceablePeerConnection;