Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

TraceablePeerConnection.js 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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(function() {
  166. self.peerconnection.getStats(function(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(function(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', stream);
  210. return;
  211. }
  212. // Bind 'addtrack'/'removetrack' event handlers
  213. if (RTCBrowserType.isChrome() || RTCBrowserType.isNWJS()
  214. || RTCBrowserType.isElectron()) {
  215. stream.onaddtrack = event => {
  216. this._remoteTrackAdded(event.target, event.track);
  217. };
  218. stream.onremovetrack = event => {
  219. this._remoteTrackRemoved(event.target, event.track);
  220. };
  221. }
  222. // Call remoteTrackAdded for each track in the stream
  223. const streamAudioTracks = stream.getAudioTracks();
  224. for (const audioTrack of streamAudioTracks) {
  225. this._remoteTrackAdded(stream, audioTrack);
  226. }
  227. const streamVideoTracks = stream.getVideoTracks();
  228. for (const videoTrack of streamVideoTracks) {
  229. this._remoteTrackAdded(stream, videoTrack);
  230. }
  231. };
  232. /**
  233. * Called on "track added" and "stream added" PeerConnection events (because we
  234. * handle streams on per track basis). Finds the owner and the SSRC for
  235. * the track and passes that to ChatRoom for further processing.
  236. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  237. * the parent of the track
  238. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  239. * participant
  240. */
  241. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track) {
  242. const streamId = RTC.getStreamID(stream);
  243. const mediaType = track.kind;
  244. logger.info('Remote track added', streamId, mediaType);
  245. // look up an associated JID for a stream id
  246. if (!mediaType) {
  247. GlobalOnErrorHandler.callErrorHandler(
  248. new Error(
  249. `MediaType undefined for remote track, stream id: ${streamId}`
  250. ));
  251. // Abort
  252. return;
  253. }
  254. const remoteSDP = new SDP(this.remoteDescription.sdp);
  255. const mediaLines = remoteSDP.media.filter(
  256. function(mediaLines) {
  257. return mediaLines.startsWith('m=' + mediaType);
  258. });
  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. function(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;
  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;
  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' && Array.isArray(session.media)) {
  467. session.media.forEach(function(mLine) {
  468. // Chrome appears to be picky about the order in which a=ssrc lines
  469. // are listed in an m-line when rtx is enabled (and thus there are
  470. // a=ssrc-group lines with FID semantics). Specifically if we have
  471. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  472. // the "a=ssrc:S1" lines, SRD fails.
  473. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  474. // first.
  475. const firstSsrcs = [];
  476. const newSsrcLines = [];
  477. if (typeof mLine.ssrcGroups !== 'undefined'
  478. && Array.isArray(mLine.ssrcGroups)) {
  479. mLine.ssrcGroups.forEach(function(group) {
  480. if (typeof group.semantics !== 'undefined'
  481. && group.semantics === 'FID') {
  482. if (typeof group.ssrcs !== 'undefined') {
  483. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  484. }
  485. }
  486. });
  487. }
  488. if (Array.isArray(mLine.ssrcs)) {
  489. let i;
  490. for (i = 0; i < mLine.ssrcs.length; i++) {
  491. if (typeof mLine.ssrcs[i] === 'object'
  492. && typeof mLine.ssrcs[i].id !== 'undefined'
  493. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  494. newSsrcLines.push(mLine.ssrcs[i]);
  495. delete mLine.ssrcs[i];
  496. }
  497. }
  498. for (i = 0; i < mLine.ssrcs.length; i++) {
  499. if (typeof mLine.ssrcs[i] !== 'undefined') {
  500. newSsrcLines.push(mLine.ssrcs[i]);
  501. }
  502. }
  503. mLine.ssrcs = newSsrcLines;
  504. }
  505. });
  506. }
  507. const resStr = transform.write(session);
  508. return new RTCSessionDescription({
  509. type: desc.type,
  510. sdp: resStr
  511. });
  512. };
  513. const getters = {
  514. signalingState() {
  515. return this.peerconnection.signalingState;
  516. },
  517. iceConnectionState() {
  518. return this.peerconnection.iceConnectionState;
  519. },
  520. localDescription() {
  521. let desc = this.peerconnection.localDescription;
  522. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  523. // if we're running on FF, transform to Plan B first.
  524. if (RTCBrowserType.usesUnifiedPlan()) {
  525. desc = this.interop.toPlanB(desc);
  526. this.trace('getLocalDescription::postTransform (Plan B)',
  527. dumpSDP(desc));
  528. }
  529. return desc;
  530. },
  531. remoteDescription() {
  532. let desc = this.peerconnection.remoteDescription;
  533. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  534. // if we're running on FF, transform to Plan B first.
  535. if (RTCBrowserType.usesUnifiedPlan()) {
  536. desc = this.interop.toPlanB(desc);
  537. this.trace(
  538. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  539. }
  540. return desc;
  541. }
  542. };
  543. Object.keys(getters).forEach(function(prop) {
  544. Object.defineProperty(
  545. TraceablePeerConnection.prototype,
  546. prop, {
  547. get: getters[prop]
  548. }
  549. );
  550. });
  551. TraceablePeerConnection.prototype.addStream = function(stream, ssrcInfo) {
  552. this.trace('addStream', stream ? stream.id : 'null');
  553. if (stream) {
  554. this.peerconnection.addStream(stream);
  555. }
  556. if (ssrcInfo && ssrcInfo.type === 'addMuted') {
  557. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  558. const simGroup
  559. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  560. if (simGroup) {
  561. this.simulcast.setSsrcCache(simGroup.ssrcs);
  562. }
  563. const fidGroups
  564. = ssrcInfo.groups.filter(
  565. groupInfo => groupInfo.semantics === 'FID');
  566. if (fidGroups) {
  567. const rtxSsrcMapping = new Map();
  568. fidGroups.forEach(fidGroup => {
  569. const primarySsrc = fidGroup.ssrcs[0];
  570. const rtxSsrc = fidGroup.ssrcs[1];
  571. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  572. });
  573. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  574. }
  575. }
  576. };
  577. TraceablePeerConnection.prototype.removeStream = function(stream) {
  578. this.trace('removeStream', stream.id);
  579. // FF doesn't support this yet.
  580. if (this.peerconnection.removeStream) {
  581. this.peerconnection.removeStream(stream);
  582. }
  583. };
  584. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  585. this.trace('createDataChannel', label, opts);
  586. return this.peerconnection.createDataChannel(label, opts);
  587. };
  588. TraceablePeerConnection.prototype.setLocalDescription
  589. = function(description, successCallback, failureCallback) {
  590. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  591. // if we're running on FF, transform to Plan A first.
  592. if (RTCBrowserType.usesUnifiedPlan()) {
  593. description = this.interop.toUnifiedPlan(description);
  594. this.trace('setLocalDescription::postTransform (Plan A)',
  595. dumpSDP(description));
  596. }
  597. const self = this;
  598. this.peerconnection.setLocalDescription(description,
  599. function() {
  600. self.trace('setLocalDescriptionOnSuccess');
  601. successCallback();
  602. },
  603. function(err) {
  604. self.trace('setLocalDescriptionOnFailure', err);
  605. self.eventEmitter.emit(
  606. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  607. err, self.peerconnection);
  608. failureCallback(err);
  609. }
  610. );
  611. };
  612. TraceablePeerConnection.prototype.setRemoteDescription
  613. = function(description, successCallback, failureCallback) {
  614. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  615. // TODO the focus should squeze or explode the remote simulcast
  616. description = this.simulcast.mungeRemoteDescription(description);
  617. this.trace(
  618. 'setRemoteDescription::postTransform (simulcast)',
  619. dumpSDP(description));
  620. if (this.options.preferH264) {
  621. const parsedSdp = transform.parse(description.sdp);
  622. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  623. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  624. description.sdp = transform.write(parsedSdp);
  625. }
  626. // if we're running on FF, transform to Plan A first.
  627. if (RTCBrowserType.usesUnifiedPlan()) {
  628. description.sdp = this.rtxModifier.stripRtx(description.sdp);
  629. this.trace('setRemoteDescription::postTransform (stripRtx)', dumpSDP(description));
  630. description = this.interop.toUnifiedPlan(description);
  631. this.trace(
  632. 'setRemoteDescription::postTransform (Plan A)',
  633. dumpSDP(description));
  634. }
  635. if (RTCBrowserType.usesPlanB()) {
  636. description = normalizePlanB(description);
  637. }
  638. const self = this;
  639. this.peerconnection.setRemoteDescription(description,
  640. function() {
  641. self.trace('setRemoteDescriptionOnSuccess');
  642. successCallback();
  643. },
  644. function(err) {
  645. self.trace('setRemoteDescriptionOnFailure', err);
  646. self.eventEmitter.emit(RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  647. err, self.peerconnection);
  648. failureCallback(err);
  649. }
  650. );
  651. /*
  652. if (this.statsinterval === null && this.maxstats > 0) {
  653. // start gathering stats
  654. }
  655. */
  656. };
  657. /**
  658. * Makes the underlying TraceablePeerConnection generate new SSRC for
  659. * the recvonly video stream.
  660. * @deprecated
  661. */
  662. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  663. // FIXME replace with SDPUtil.generateSsrc (when it's added)
  664. const newSSRC = this.generateNewStreamSSRCInfo().ssrcs[0];
  665. logger.info('Generated new recvonly SSRC: ' + newSSRC);
  666. this.sdpConsistency.setPrimarySsrc(newSSRC);
  667. };
  668. /**
  669. * Makes the underlying TraceablePeerConnection forget the current primary video
  670. * SSRC.
  671. * @deprecated
  672. */
  673. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  674. logger.info('Clearing primary video SSRC!');
  675. this.sdpConsistency.clearSsrcCache();
  676. };
  677. TraceablePeerConnection.prototype.close = function() {
  678. this.trace('stop');
  679. if (!this.rtc._removePeerConnection(this)) {
  680. logger.error('RTC._removePeerConnection returned false');
  681. }
  682. if (this.statsinterval !== null) {
  683. window.clearInterval(this.statsinterval);
  684. this.statsinterval = null;
  685. }
  686. this.peerconnection.close();
  687. };
  688. /**
  689. * Modifies the values of the setup attributes (defined by
  690. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  691. * answer in order to overcome a delay of 1 second in the connection
  692. * establishment between Chrome and Videobridge.
  693. *
  694. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  695. * being prepared to respond
  696. * @param {SDP} answer - the SDP to modify
  697. * @private
  698. */
  699. const _fixAnswerRFC4145Setup = function(offer, answer) {
  700. if (!RTCBrowserType.isChrome()) {
  701. // It looks like Firefox doesn't agree with the fix (at least in its
  702. // current implementation) because it effectively remains active even
  703. // after we tell it to become passive. Apart from Firefox which I tested
  704. // after the fix was deployed, I tested Chrome only. In order to prevent
  705. // issues with other browsers, limit the fix to Chrome for the time
  706. // being.
  707. return;
  708. }
  709. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  710. // answerer (as orchestrated by Jicofo). In accord with
  711. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  712. // are ICE FULL agents, Videobridge will take on the controlling role and
  713. // WebRTC will take on the controlled role. In accord with
  714. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  715. // setup attribute value of setup:actpass and WebRTC will be allowed to
  716. // choose either the setup attribute value of setup:active or
  717. // setup:passive. Chrome will by default choose setup:active because it is
  718. // RECOMMENDED by the respective RFC since setup:passive adds additional
  719. // latency. The case of setup:active allows WebRTC to send a DTLS
  720. // ClientHello as soon as an ICE connectivity check of its succeeds.
  721. // Unfortunately, Videobridge will be unable to respond immediately because
  722. // may not have WebRTC's answer or may have not completed the ICE
  723. // connectivity establishment. Even more unfortunate is that in the
  724. // described scenario Chrome's DTLS implementation will insist on
  725. // retransmitting its ClientHello after a second (the time is in accord
  726. // with the respective RFC) and will thus cause the whole connection
  727. // establishment to exceed at least 1 second. To work around Chrome's
  728. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  729. // default choice of setup:active to setup:passive.
  730. if (offer && answer
  731. && offer.media && answer.media
  732. && offer.media.length == answer.media.length) {
  733. answer.media.forEach(function(a, i) {
  734. if (SDPUtil.find_line(
  735. offer.media[i],
  736. 'a=setup:actpass',
  737. offer.session)) {
  738. answer.media[i]
  739. = a.replace(/a=setup:active/g, 'a=setup:passive');
  740. }
  741. });
  742. answer.raw = answer.session + answer.media.join('');
  743. }
  744. };
  745. TraceablePeerConnection.prototype.createAnswer
  746. = function(successCallback, failureCallback, constraints) {
  747. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  748. this.peerconnection.createAnswer(
  749. answer => {
  750. try {
  751. this.trace(
  752. 'createAnswerOnSuccess::preTransform', dumpSDP(answer));
  753. // if we're running on FF, transform to Plan A first.
  754. if (RTCBrowserType.usesUnifiedPlan()) {
  755. answer = this.interop.toPlanB(answer);
  756. this.trace('createAnswerOnSuccess::postTransform (Plan B)',
  757. dumpSDP(answer));
  758. }
  759. /**
  760. * We don't keep ssrcs consitent for Firefox because rewriting
  761. * the ssrcs between createAnswer and setLocalDescription
  762. * breaks the caching in sdp-interop (sdp-interop must
  763. * know about all ssrcs, and it updates its cache in
  764. * toPlanB so if we rewrite them after that, when we
  765. * try and go back to unified plan it will complain
  766. * about unmapped ssrcs)
  767. */
  768. if (!RTCBrowserType.isFirefox()) {
  769. answer.sdp = this.sdpConsistency.makeVideoPrimarySsrcsConsistent(answer.sdp);
  770. this.trace('createAnswerOnSuccess::postTransform (make primary video ssrcs consistent)',
  771. dumpSDP(answer));
  772. }
  773. // Add simulcast streams if simulcast is enabled
  774. if (!this.options.disableSimulcast
  775. && this.simulcast.isSupported()) {
  776. answer = this.simulcast.mungeLocalDescription(answer);
  777. this.trace(
  778. 'createAnswerOnSuccess::postTransform (simulcast)',
  779. dumpSDP(answer));
  780. }
  781. if (!this.options.disableRtx && !RTCBrowserType.isFirefox()) {
  782. answer.sdp = this.rtxModifier.modifyRtxSsrcs(answer.sdp);
  783. this.trace(
  784. 'createAnswerOnSuccess::postTransform (rtx modifier)',
  785. dumpSDP(answer));
  786. }
  787. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  788. // details)
  789. const remoteDescription = new SDP(this.remoteDescription.sdp);
  790. const localDescription = new SDP(answer.sdp);
  791. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  792. answer.sdp = localDescription.raw;
  793. this.eventEmitter.emit(RTCEvents.SENDRECV_STREAMS_CHANGED,
  794. extractSSRCMap(answer));
  795. successCallback(answer);
  796. } catch (e) {
  797. this.trace('createAnswerOnError', e);
  798. this.trace('createAnswerOnError', dumpSDP(answer));
  799. logger.error('createAnswerOnError', e, dumpSDP(answer));
  800. failureCallback(e);
  801. }
  802. },
  803. err => {
  804. this.trace('createAnswerOnFailure', err);
  805. this.eventEmitter.emit(RTCEvents.CREATE_ANSWER_FAILED, err,
  806. this.peerconnection);
  807. failureCallback(err);
  808. },
  809. constraints
  810. );
  811. };
  812. TraceablePeerConnection.prototype.addIceCandidate
  813. // eslint-disable-next-line no-unused-vars
  814. = function(candidate, successCallback, failureCallback) {
  815. // var self = this;
  816. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  817. this.peerconnection.addIceCandidate(candidate);
  818. /* maybe later
  819. this.peerconnection.addIceCandidate(candidate,
  820. function () {
  821. self.trace('addIceCandidateOnSuccess');
  822. successCallback();
  823. },
  824. function (err) {
  825. self.trace('addIceCandidateOnFailure', err);
  826. failureCallback(err);
  827. }
  828. );
  829. */
  830. };
  831. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  832. // TODO: Is this the correct way to handle Opera, Temasys?
  833. if (RTCBrowserType.isFirefox()
  834. || RTCBrowserType.isTemasysPluginUsed()
  835. || RTCBrowserType.isReactNative()) {
  836. if(!errback) {
  837. errback = function() {
  838. // Making sure that getStats won't fail if error callback is
  839. // not passed.
  840. };
  841. }
  842. this.peerconnection.getStats(null, callback, errback);
  843. } else {
  844. this.peerconnection.getStats(callback);
  845. }
  846. };
  847. /**
  848. * Generate ssrc info object for a stream with the following properties:
  849. * - ssrcs - Array of the ssrcs associated with the stream.
  850. * - groups - Array of the groups associated with the stream.
  851. */
  852. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function() {
  853. let ssrcInfo = {ssrcs: [], groups: []};
  854. if (!this.options.disableSimulcast
  855. && this.simulcast.isSupported()) {
  856. for (let i = 0; i < SIMULCAST_LAYERS; i++) {
  857. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  858. }
  859. ssrcInfo.groups.push({
  860. ssrcs: ssrcInfo.ssrcs.slice(),
  861. semantics: 'SIM'
  862. });
  863. } else {
  864. ssrcInfo = {
  865. ssrcs: [SDPUtil.generateSsrc()],
  866. groups: []
  867. };
  868. }
  869. if (!this.options.disableRtx && !RTCBrowserType.isFirefox()) {
  870. // Specifically use a for loop here because we'll
  871. // be adding to the list we're iterating over, so we
  872. // only want to iterate through the items originally
  873. // on the list
  874. const currNumSsrcs = ssrcInfo.ssrcs.length;
  875. for (let i = 0; i < currNumSsrcs; ++i) {
  876. const primarySsrc = ssrcInfo.ssrcs[i];
  877. const rtxSsrc = SDPUtil.generateSsrc();
  878. ssrcInfo.ssrcs.push(rtxSsrc);
  879. ssrcInfo.groups.push({
  880. ssrcs: [primarySsrc, rtxSsrc],
  881. semantics: 'FID'
  882. });
  883. }
  884. }
  885. return ssrcInfo;
  886. };
  887. module.exports = TraceablePeerConnection;