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

TraceablePeerConnection.js 35KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  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} iceConfig 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, iceConfig,
  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(iceConfig, 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. // eslint-disable-next-line no-shadow
  172. const id = `${results[i].id}-${name}`;
  173. let s = self.stats[id];
  174. if (!s) {
  175. self.stats[id] = s = {
  176. startTime: now,
  177. endTime: now,
  178. values: [],
  179. times: []
  180. };
  181. }
  182. s.values.push(results[i].stat(name));
  183. s.times.push(now.getTime());
  184. if (s.values.length > self.maxstats) {
  185. s.values.shift();
  186. s.times.shift();
  187. }
  188. s.endTime = now;
  189. });
  190. }
  191. });
  192. }, 1000);
  193. }
  194. }
  195. /**
  196. * Returns a string representation of a SessionDescription object.
  197. */
  198. const dumpSDP = function(description) {
  199. if (typeof description === 'undefined' || description === null) {
  200. return '';
  201. }
  202. return `type: ${description.type}\r\n${description.sdp}`;
  203. };
  204. /**
  205. * Called when new remote MediaStream is added to the PeerConnection.
  206. * @param {MediaStream} stream the WebRTC MediaStream for remote participant
  207. */
  208. TraceablePeerConnection.prototype._remoteStreamAdded = function(stream) {
  209. if (!RTC.isUserStream(stream)) {
  210. logger.info(
  211. 'Ignored remote \'stream added\' event for non-user stream',
  212. stream);
  213. return;
  214. }
  215. // Bind 'addtrack'/'removetrack' event handlers
  216. if (RTCBrowserType.isChrome() || RTCBrowserType.isNWJS()
  217. || RTCBrowserType.isElectron()) {
  218. stream.onaddtrack = event => {
  219. this._remoteTrackAdded(event.target, event.track);
  220. };
  221. stream.onremovetrack = event => {
  222. this._remoteTrackRemoved(event.target, event.track);
  223. };
  224. }
  225. // Call remoteTrackAdded for each track in the stream
  226. const streamAudioTracks = stream.getAudioTracks();
  227. for (const audioTrack of streamAudioTracks) {
  228. this._remoteTrackAdded(stream, audioTrack);
  229. }
  230. const streamVideoTracks = stream.getVideoTracks();
  231. for (const videoTrack of streamVideoTracks) {
  232. this._remoteTrackAdded(stream, videoTrack);
  233. }
  234. };
  235. /**
  236. * Called on "track added" and "stream added" PeerConnection events (because we
  237. * handle streams on per track basis). Finds the owner and the SSRC for
  238. * the track and passes that to ChatRoom for further processing.
  239. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  240. * the parent of the track
  241. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  242. * participant
  243. */
  244. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track) {
  245. const streamId = RTC.getStreamID(stream);
  246. const mediaType = track.kind;
  247. logger.info('Remote track added', streamId, mediaType);
  248. // look up an associated JID for a stream id
  249. if (!mediaType) {
  250. GlobalOnErrorHandler.callErrorHandler(
  251. new Error(
  252. `MediaType undefined for remote track, stream id: ${streamId}`
  253. ));
  254. // Abort
  255. return;
  256. }
  257. const remoteSDP = new SDP(this.remoteDescription.sdp);
  258. const mediaLines
  259. = remoteSDP.media.filter(mls => mls.startsWith(`m=${mediaType}`));
  260. if (!mediaLines.length) {
  261. GlobalOnErrorHandler.callErrorHandler(
  262. new Error(
  263. `No media lines for type ${mediaType
  264. } found in remote SDP for remote track: ${streamId}`));
  265. // Abort
  266. return;
  267. }
  268. let ssrcLines = SDPUtil.findLines(mediaLines[0], 'a=ssrc:');
  269. ssrcLines = ssrcLines.filter(
  270. line => {
  271. const msid
  272. = RTCBrowserType.isTemasysPluginUsed() ? 'mslabel' : 'msid';
  273. return line.indexOf(`${msid}:${streamId}`) !== -1;
  274. });
  275. if (!ssrcLines.length) {
  276. GlobalOnErrorHandler.callErrorHandler(
  277. new Error(
  278. `No SSRC lines for streamId ${streamId
  279. } for remote track, media type: ${mediaType}`));
  280. // Abort
  281. return;
  282. }
  283. // FIXME the length of ssrcLines[0] not verified, but it will fail
  284. // with global error handler anyway
  285. const trackSsrc = ssrcLines[0].substring(7).split(' ')[0];
  286. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  287. if (!ownerEndpointId) {
  288. GlobalOnErrorHandler.callErrorHandler(
  289. new Error(
  290. `No SSRC owner known for: ${trackSsrc
  291. } for remote track, msid: ${streamId
  292. } media type: ${mediaType}`));
  293. // Abort
  294. return;
  295. }
  296. logger.log('associated ssrc', ownerEndpointId, trackSsrc);
  297. const peerMediaInfo
  298. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  299. if (!peerMediaInfo) {
  300. GlobalOnErrorHandler.callErrorHandler(
  301. new Error(`No peer media info available for: ${ownerEndpointId}`));
  302. // Abort
  303. return;
  304. }
  305. const muted = peerMediaInfo.muted;
  306. const videoType = peerMediaInfo.videoType; // can be undefined
  307. this.rtc._createRemoteTrack(
  308. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  309. };
  310. /**
  311. * Handles remote stream removal.
  312. * @param stream the WebRTC MediaStream object which is being removed from the
  313. * PeerConnection
  314. */
  315. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  316. if (!RTC.isUserStream(stream)) {
  317. const id = RTC.getStreamID(stream);
  318. logger.info(
  319. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  320. return;
  321. }
  322. // Call remoteTrackRemoved for each track in the stream
  323. const streamVideoTracks = stream.getVideoTracks();
  324. for (const videoTrack of streamVideoTracks) {
  325. this._remoteTrackRemoved(stream, videoTrack);
  326. }
  327. const streamAudioTracks = stream.getAudioTracks();
  328. for (const audioTrack of streamAudioTracks) {
  329. this._remoteTrackRemoved(stream, audioTrack);
  330. }
  331. };
  332. /**
  333. * Handles remote media track removal.
  334. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  335. * of the track.
  336. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  337. * removed from the PeerConnection.
  338. */
  339. TraceablePeerConnection.prototype._remoteTrackRemoved
  340. = function(stream, track) {
  341. const streamId = RTC.getStreamID(stream);
  342. const trackId = track && track.id;
  343. logger.info('Remote track removed', streamId, trackId);
  344. if (!streamId) {
  345. GlobalOnErrorHandler.callErrorHandler(
  346. new Error('Remote track removal failed - no stream ID'));
  347. // Abort
  348. return;
  349. }
  350. if (!trackId) {
  351. GlobalOnErrorHandler.callErrorHandler(
  352. new Error('Remote track removal failed - no track ID'));
  353. // Abort
  354. return;
  355. }
  356. if (!this.rtc._removeRemoteTrack(streamId, trackId)) {
  357. // NOTE this warning is always printed when user leaves the room,
  358. // because we remove remote tracks manually on MUC member left event,
  359. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  360. // ignore this warning, but still it's better to keep it printed for
  361. // debugging purposes.
  362. //
  363. // We could change the behaviour to emit track removed only from here,
  364. // but the order of the events will change and consuming apps could
  365. // behave unexpectedly (the "user left" event would come before "track
  366. // removed" events).
  367. logger.warn(
  368. `Removed track not found for msid: ${streamId},
  369. track id: ${trackId}`);
  370. }
  371. };
  372. /**
  373. * @typedef {Object} SSRCGroupInfo
  374. * @property {Array<number>} ssrcs group's SSRCs
  375. * @property {string} semantics
  376. */
  377. /**
  378. * @typedef {Object} TrackSSRCInfo
  379. * @property {Array<number>} ssrcs track's SSRCs
  380. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  381. */
  382. /**
  383. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  384. * @param {Object} desc the WebRTC SDP instance.
  385. * @return {Map<string,TrackSSRCInfo>}
  386. */
  387. function extractSSRCMap(desc) {
  388. /**
  389. * Track SSRC infos mapped by stream ID (msid)
  390. * @type {Map<string,TrackSSRCInfo>}
  391. */
  392. const ssrcMap = new Map();
  393. /**
  394. * Groups mapped by primary SSRC number
  395. * @type {Map<number,Array<SSRCGroupInfo>>}
  396. */
  397. const groupsMap = new Map();
  398. if (typeof desc !== 'object' || desc === null
  399. || typeof desc.sdp !== 'string') {
  400. logger.warn('An empty description was passed as an argument.');
  401. return ssrcMap;
  402. }
  403. const session = transform.parse(desc.sdp);
  404. if (!Array.isArray(session.media)) {
  405. return ssrcMap;
  406. }
  407. for (const mLine of session.media) {
  408. if (!Array.isArray(mLine.ssrcs)) {
  409. continue; // eslint-disable-line no-continue
  410. }
  411. if (Array.isArray(mLine.ssrcGroups)) {
  412. for (const group of mLine.ssrcGroups) {
  413. if (typeof group.semantics !== 'undefined'
  414. && typeof group.ssrcs !== 'undefined') {
  415. // Parse SSRCs and store as numbers
  416. const groupSSRCs
  417. = group.ssrcs.split(' ')
  418. .map(ssrcStr => parseInt(ssrcStr, 10));
  419. const primarySSRC = groupSSRCs[0];
  420. // Note that group.semantics is already present
  421. group.ssrcs = groupSSRCs;
  422. if (!groupsMap.has(primarySSRC)) {
  423. groupsMap.set(primarySSRC, []);
  424. }
  425. groupsMap.get(primarySSRC).push(group);
  426. }
  427. }
  428. }
  429. for (const ssrc of mLine.ssrcs) {
  430. if (ssrc.attribute !== 'msid') {
  431. continue; // eslint-disable-line no-continue
  432. }
  433. const msid = ssrc.value;
  434. let ssrcInfo = ssrcMap.get(msid);
  435. if (!ssrcInfo) {
  436. ssrcInfo = {
  437. ssrcs: [],
  438. groups: []
  439. };
  440. ssrcMap.set(msid, ssrcInfo);
  441. }
  442. const ssrcNumber = ssrc.id;
  443. ssrcInfo.ssrcs.push(ssrcNumber);
  444. if (groupsMap.has(ssrcNumber)) {
  445. const ssrcGroups = groupsMap.get(ssrcNumber);
  446. for (const group of ssrcGroups) {
  447. ssrcInfo.groups.push(group);
  448. }
  449. }
  450. }
  451. }
  452. return ssrcMap;
  453. }
  454. /**
  455. * Takes a SessionDescription object and returns a "normalized" version.
  456. * Currently it only takes care of ordering the a=ssrc lines.
  457. */
  458. const normalizePlanB = function(desc) {
  459. if (typeof desc !== 'object' || desc === null
  460. || typeof desc.sdp !== 'string') {
  461. logger.warn('An empty description was passed as an argument.');
  462. return desc;
  463. }
  464. // eslint-disable-next-line no-shadow
  465. const transform = require('sdp-transform');
  466. const session = transform.parse(desc.sdp);
  467. if (typeof session !== 'undefined'
  468. && typeof session.media !== 'undefined'
  469. && Array.isArray(session.media)) {
  470. session.media.forEach(mLine => {
  471. // Chrome appears to be picky about the order in which a=ssrc lines
  472. // are listed in an m-line when rtx is enabled (and thus there are
  473. // a=ssrc-group lines with FID semantics). Specifically if we have
  474. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  475. // the "a=ssrc:S1" lines, SRD fails.
  476. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  477. // first.
  478. const firstSsrcs = [];
  479. const newSsrcLines = [];
  480. if (typeof mLine.ssrcGroups !== 'undefined'
  481. && Array.isArray(mLine.ssrcGroups)) {
  482. mLine.ssrcGroups.forEach(group => {
  483. if (typeof group.semantics !== 'undefined'
  484. && group.semantics === 'FID') {
  485. if (typeof group.ssrcs !== 'undefined') {
  486. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  487. }
  488. }
  489. });
  490. }
  491. if (Array.isArray(mLine.ssrcs)) {
  492. let i;
  493. for (i = 0; i < mLine.ssrcs.length; i++) {
  494. if (typeof mLine.ssrcs[i] === 'object'
  495. && typeof mLine.ssrcs[i].id !== 'undefined'
  496. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  497. newSsrcLines.push(mLine.ssrcs[i]);
  498. delete mLine.ssrcs[i];
  499. }
  500. }
  501. for (i = 0; i < mLine.ssrcs.length; i++) {
  502. if (typeof mLine.ssrcs[i] !== 'undefined') {
  503. newSsrcLines.push(mLine.ssrcs[i]);
  504. }
  505. }
  506. mLine.ssrcs = newSsrcLines;
  507. }
  508. });
  509. }
  510. const resStr = transform.write(session);
  511. return new RTCSessionDescription({
  512. type: desc.type,
  513. sdp: resStr
  514. });
  515. };
  516. const getters = {
  517. signalingState() {
  518. return this.peerconnection.signalingState;
  519. },
  520. iceConnectionState() {
  521. return this.peerconnection.iceConnectionState;
  522. },
  523. localDescription() {
  524. let desc = this.peerconnection.localDescription;
  525. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  526. // if we're running on FF, transform to Plan B first.
  527. if (RTCBrowserType.usesUnifiedPlan()) {
  528. desc = this.interop.toPlanB(desc);
  529. this.trace('getLocalDescription::postTransform (Plan B)',
  530. dumpSDP(desc));
  531. }
  532. return desc;
  533. },
  534. remoteDescription() {
  535. let desc = this.peerconnection.remoteDescription;
  536. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  537. // if we're running on FF, transform to Plan B first.
  538. if (RTCBrowserType.usesUnifiedPlan()) {
  539. desc = this.interop.toPlanB(desc);
  540. this.trace(
  541. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  542. }
  543. return desc;
  544. }
  545. };
  546. Object.keys(getters).forEach(prop => {
  547. Object.defineProperty(
  548. TraceablePeerConnection.prototype,
  549. prop, {
  550. get: getters[prop]
  551. }
  552. );
  553. });
  554. TraceablePeerConnection.prototype.addStream = function(stream, ssrcInfo) {
  555. this.trace('addStream', stream ? stream.id : 'null');
  556. if (stream) {
  557. this.peerconnection.addStream(stream);
  558. }
  559. if (ssrcInfo && ssrcInfo.type === 'addMuted') {
  560. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  561. const simGroup
  562. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  563. if (simGroup) {
  564. this.simulcast.setSsrcCache(simGroup.ssrcs);
  565. }
  566. const fidGroups
  567. = ssrcInfo.groups.filter(
  568. groupInfo => groupInfo.semantics === 'FID');
  569. if (fidGroups) {
  570. const rtxSsrcMapping = new Map();
  571. fidGroups.forEach(fidGroup => {
  572. const primarySsrc = fidGroup.ssrcs[0];
  573. const rtxSsrc = fidGroup.ssrcs[1];
  574. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  575. });
  576. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  577. }
  578. }
  579. };
  580. TraceablePeerConnection.prototype.removeStream = function(stream) {
  581. this.trace('removeStream', stream.id);
  582. // FF doesn't support this yet.
  583. if (this.peerconnection.removeStream) {
  584. this.peerconnection.removeStream(stream);
  585. }
  586. };
  587. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  588. this.trace('createDataChannel', label, opts);
  589. return this.peerconnection.createDataChannel(label, opts);
  590. };
  591. TraceablePeerConnection.prototype.setLocalDescription
  592. = function(description, successCallback, failureCallback) {
  593. let d = description;
  594. this.trace('setLocalDescription::preTransform', dumpSDP(d));
  595. // if we're running on FF, transform to Plan A first.
  596. if (RTCBrowserType.usesUnifiedPlan()) {
  597. d = this.interop.toUnifiedPlan(d);
  598. this.trace(
  599. 'setLocalDescription::postTransform (Plan A)',
  600. dumpSDP(d));
  601. }
  602. const self = this;
  603. this.peerconnection.setLocalDescription(
  604. d,
  605. () => {
  606. self.trace('setLocalDescriptionOnSuccess');
  607. successCallback();
  608. },
  609. err => {
  610. self.trace('setLocalDescriptionOnFailure', err);
  611. self.eventEmitter.emit(
  612. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  613. err, self.peerconnection);
  614. failureCallback(err);
  615. }
  616. );
  617. };
  618. TraceablePeerConnection.prototype.setRemoteDescription
  619. = function(description, successCallback, failureCallback) {
  620. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  621. // TODO the focus should squeze or explode the remote simulcast
  622. // eslint-disable-next-line no-param-reassign
  623. description = this.simulcast.mungeRemoteDescription(description);
  624. this.trace(
  625. 'setRemoteDescription::postTransform (simulcast)',
  626. dumpSDP(description));
  627. if (this.options.preferH264) {
  628. const parsedSdp = transform.parse(description.sdp);
  629. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  630. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  631. description.sdp = transform.write(parsedSdp);
  632. }
  633. // if we're running on FF, transform to Plan A first.
  634. if (RTCBrowserType.usesUnifiedPlan()) {
  635. description.sdp = this.rtxModifier.stripRtx(description.sdp);
  636. this.trace(
  637. 'setRemoteDescription::postTransform (stripRtx)',
  638. dumpSDP(description));
  639. // eslint-disable-next-line no-param-reassign
  640. description = this.interop.toUnifiedPlan(description);
  641. this.trace(
  642. 'setRemoteDescription::postTransform (Plan A)',
  643. dumpSDP(description));
  644. }
  645. if (RTCBrowserType.usesPlanB()) {
  646. // eslint-disable-next-line no-param-reassign
  647. description = normalizePlanB(description);
  648. }
  649. this.peerconnection.setRemoteDescription(
  650. description,
  651. () => {
  652. this.trace('setRemoteDescriptionOnSuccess');
  653. successCallback();
  654. },
  655. err => {
  656. this.trace('setRemoteDescriptionOnFailure', err);
  657. this.eventEmitter.emit(
  658. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  659. err,
  660. this.peerconnection);
  661. failureCallback(err);
  662. });
  663. };
  664. /**
  665. * Makes the underlying TraceablePeerConnection generate new SSRC for
  666. * the recvonly video stream.
  667. * @deprecated
  668. */
  669. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  670. // FIXME replace with SDPUtil.generateSsrc (when it's added)
  671. const newSSRC = this.generateNewStreamSSRCInfo().ssrcs[0];
  672. logger.info(`Generated new recvonly SSRC: ${newSSRC}`);
  673. this.sdpConsistency.setPrimarySsrc(newSSRC);
  674. };
  675. /**
  676. * Makes the underlying TraceablePeerConnection forget the current primary video
  677. * SSRC.
  678. * @deprecated
  679. */
  680. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  681. logger.info('Clearing primary video SSRC!');
  682. this.sdpConsistency.clearSsrcCache();
  683. };
  684. TraceablePeerConnection.prototype.close = function() {
  685. this.trace('stop');
  686. if (!this.rtc._removePeerConnection(this)) {
  687. logger.error('RTC._removePeerConnection returned false');
  688. }
  689. if (this.statsinterval !== null) {
  690. window.clearInterval(this.statsinterval);
  691. this.statsinterval = null;
  692. }
  693. this.peerconnection.close();
  694. };
  695. /**
  696. * Modifies the values of the setup attributes (defined by
  697. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  698. * answer in order to overcome a delay of 1 second in the connection
  699. * establishment between Chrome and Videobridge.
  700. *
  701. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  702. * being prepared to respond
  703. * @param {SDP} answer - the SDP to modify
  704. * @private
  705. */
  706. const _fixAnswerRFC4145Setup = function(offer, answer) {
  707. if (!RTCBrowserType.isChrome()) {
  708. // It looks like Firefox doesn't agree with the fix (at least in its
  709. // current implementation) because it effectively remains active even
  710. // after we tell it to become passive. Apart from Firefox which I tested
  711. // after the fix was deployed, I tested Chrome only. In order to prevent
  712. // issues with other browsers, limit the fix to Chrome for the time
  713. // being.
  714. return;
  715. }
  716. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  717. // answerer (as orchestrated by Jicofo). In accord with
  718. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  719. // are ICE FULL agents, Videobridge will take on the controlling role and
  720. // WebRTC will take on the controlled role. In accord with
  721. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  722. // setup attribute value of setup:actpass and WebRTC will be allowed to
  723. // choose either the setup attribute value of setup:active or
  724. // setup:passive. Chrome will by default choose setup:active because it is
  725. // RECOMMENDED by the respective RFC since setup:passive adds additional
  726. // latency. The case of setup:active allows WebRTC to send a DTLS
  727. // ClientHello as soon as an ICE connectivity check of its succeeds.
  728. // Unfortunately, Videobridge will be unable to respond immediately because
  729. // may not have WebRTC's answer or may have not completed the ICE
  730. // connectivity establishment. Even more unfortunate is that in the
  731. // described scenario Chrome's DTLS implementation will insist on
  732. // retransmitting its ClientHello after a second (the time is in accord
  733. // with the respective RFC) and will thus cause the whole connection
  734. // establishment to exceed at least 1 second. To work around Chrome's
  735. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  736. // default choice of setup:active to setup:passive.
  737. if (offer && answer
  738. && offer.media && answer.media
  739. && offer.media.length === answer.media.length) {
  740. answer.media.forEach((a, i) => {
  741. if (SDPUtil.findLine(
  742. offer.media[i],
  743. 'a=setup:actpass',
  744. offer.session)) {
  745. answer.media[i]
  746. = a.replace(/a=setup:active/g, 'a=setup:passive');
  747. }
  748. });
  749. answer.raw = answer.session + answer.media.join('');
  750. }
  751. };
  752. TraceablePeerConnection.prototype.createAnswer
  753. = function(successCallback, failureCallback, constraints) {
  754. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  755. this.peerconnection.createAnswer(
  756. answer => {
  757. try {
  758. this.trace(
  759. 'createAnswerOnSuccess::preTransform', dumpSDP(answer));
  760. // if we're running on FF, transform to Plan A first.
  761. if (RTCBrowserType.usesUnifiedPlan()) {
  762. // eslint-disable-next-line no-param-reassign
  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. // eslint-disable-next-line no-param-reassign
  789. answer = this.simulcast.mungeLocalDescription(answer);
  790. this.trace(
  791. 'createAnswerOnSuccess::postTransform (simulcast)',
  792. dumpSDP(answer));
  793. }
  794. if (!this.options.disableRtx && !RTCBrowserType.isFirefox()) {
  795. answer.sdp = this.rtxModifier.modifyRtxSsrcs(answer.sdp);
  796. this.trace(
  797. 'createAnswerOnSuccess::postTransform (rtx modifier)',
  798. dumpSDP(answer));
  799. }
  800. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  801. // details)
  802. const remoteDescription = new SDP(this.remoteDescription.sdp);
  803. const localDescription = new SDP(answer.sdp);
  804. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  805. answer.sdp = localDescription.raw;
  806. this.eventEmitter.emit(RTCEvents.SENDRECV_STREAMS_CHANGED,
  807. extractSSRCMap(answer));
  808. successCallback(answer);
  809. } catch (e) {
  810. this.trace('createAnswerOnError', e);
  811. this.trace('createAnswerOnError', dumpSDP(answer));
  812. logger.error('createAnswerOnError', e, dumpSDP(answer));
  813. failureCallback(e);
  814. }
  815. },
  816. err => {
  817. this.trace('createAnswerOnFailure', err);
  818. this.eventEmitter.emit(RTCEvents.CREATE_ANSWER_FAILED, err,
  819. this.peerconnection);
  820. failureCallback(err);
  821. },
  822. constraints);
  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. this.peerconnection.getStats(
  849. null,
  850. callback,
  851. errback || (() => {
  852. // Making sure that getStats won't fail if error callback is
  853. // not passed.
  854. }));
  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;