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.

RTCPeerConnection.js 72KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353
  1. /* global __filename, RTCIceGatherer, RTCIceTransport, RTCDtlsTransport,
  2. RTCRtpSender, RTCRtpReceiver */
  3. import { getLogger } from 'jitsi-meet-logger';
  4. import yaeti from 'yaeti';
  5. import RTCSessionDescription from './RTCSessionDescription';
  6. import * as utils from './utils';
  7. import { InvalidStateError } from './errors';
  8. import RandomUtil from '../../util/RandomUtil';
  9. import SDPUtil from '../../xmpp/SDPUtil';
  10. const logger = getLogger(__filename);
  11. const RTCSignalingState = {
  12. stable: 'stable',
  13. haveLocalOffer: 'have-local-offer',
  14. haveRemoteOffer: 'have-remote-offer',
  15. closed: 'closed'
  16. };
  17. const RTCIceGatheringState = {
  18. new: 'new',
  19. gathering: 'gathering',
  20. complete: 'complete'
  21. };
  22. const CNAME = `jitsi-ortc-cname-${RandomUtil.randomInt(10000, 99999)}`;
  23. /**
  24. * RTCPeerConnection shim for ORTC based endpoints (such as Edge).
  25. *
  26. * The interface is based on the W3C specification of 2015, which matches
  27. * the implementation of Chrome nowadays:
  28. *
  29. * https://www.w3.org/TR/2015/WD-webrtc-20150210/
  30. *
  31. * It also implements Plan-B for multi-stream, and assumes single BUNDLEd
  32. * transport and rtcp-mux.
  33. */
  34. export default class ortcRTCPeerConnection extends yaeti.EventTarget {
  35. /**
  36. */
  37. constructor(pcConfig) {
  38. super();
  39. logger.debug('constructor() pcConfig:', pcConfig);
  40. // Buffered local ICE candidates (in WebRTC format).
  41. // @type {sequence<RTCIceCandidate>}
  42. this._bufferedIceCandidates = [];
  43. // Closed flag.
  44. // @type {Boolean}
  45. this._closed = false;
  46. // RTCDtlsTransport.
  47. // @type {RTCDtlsTransport}
  48. this._dtlsTransport = null;
  49. // RTCIceGatherer.
  50. // @type {RTCIceGatherer}
  51. this._iceGatherer = null;
  52. // RTCPeerConnection iceGatheringState.
  53. // NOTE: This should not be needed, but Edge does not implement
  54. // iceGatherer.state.
  55. // @type {RTCIceGatheringState}
  56. this._iceGatheringState = RTCIceGatheringState.new;
  57. // Use a promise to signify when the local client has finished gathering
  58. // ice candidates. This is needed to prevent errors on offer creation.
  59. this._resolveLocalIceGatheringPromise = null;
  60. this._iceGatheringCompletePromise = new Promise(resolve => {
  61. this._resolveLocalIceGatheringPromise = resolve;
  62. });
  63. // RTCIceTransport.
  64. // @type {RTCIceTransport}
  65. this._iceTransport = null;
  66. // Local RTP capabilities (filtered with remote ones).
  67. // @type {RTCRtpCapabilities}
  68. this._localCapabilities = null;
  69. // Local RTCSessionDescription.
  70. // @type {RTCSessionDescription}
  71. this._localDescription = null;
  72. // Map with info regarding local media.
  73. // - index: MediaStreamTrack.id
  74. // - value: Object
  75. // - rtpSender: Associated RTCRtpSender instance
  76. // - stream: Associated MediaStream instance
  77. // - ssrc: Provisional or definitive SSRC
  78. // - rtxSsrc: Provisional or definitive SSRC for RTX
  79. // - sending: Boolean indicating whether rtpSender.send() was called.
  80. this._localTrackInfos = new Map();
  81. // Ordered Map with MID as key and kind as value.
  82. // @type {map<String, String>}
  83. this._mids = new Map();
  84. // Remote RTCSessionDescription.
  85. // @type {RTCSessionDescription}
  86. this._remoteDescription = null;
  87. // Map of remote streams.
  88. // - index: MediaStream.jitsiRemoteId (as signaled in remote SDP)
  89. // - value: MediaStream (locally generated so id does not match)
  90. // @type {map<Number, MediaStream>}
  91. this._remoteStreams = new Map();
  92. // Map with info about receiving media.
  93. // - index: Media SSRC
  94. // - value: Object
  95. // - kind: 'audio' / 'video'
  96. // - ssrc: Media SSRC
  97. // - rtxSsrc: RTX SSRC (may be unset)
  98. // - streamId: MediaStream.jitsiRemoteId
  99. // - trackId: MediaStreamTrack.jitsiRemoteId
  100. // - cname: CNAME
  101. // - stream: MediaStream
  102. // - track: MediaStreamTrack
  103. // - rtpReceiver: Associated RTCRtpReceiver instance
  104. // @type {map<Number, Object>}
  105. this._remoteTrackInfos = new Map();
  106. // Local SDP global fields.
  107. this._sdpGlobalFields = {
  108. id: SDPUtil.generateSsrc(),
  109. version: 0
  110. };
  111. // RTCPeerConnection signalingState.
  112. // @type {RTCSignalingState}
  113. this._signalingState = RTCSignalingState.stable;
  114. // Create the RTCIceGatherer.
  115. this._setIceGatherer(pcConfig);
  116. // Create the RTCIceTransport.
  117. this._setIceTransport(this._iceGatherer);
  118. // Create the RTCDtlsTransport.
  119. this._setDtlsTransport(this._iceTransport);
  120. }
  121. /**
  122. * Current ICE+DTLS connection state.
  123. * @return {RTCPeerConnectionState}
  124. */
  125. get connectionState() {
  126. return this._dtlsTransport.state;
  127. }
  128. /**
  129. * Current ICE connection state.
  130. * @return {RTCIceConnectionState}
  131. */
  132. get iceConnectionState() {
  133. return this._iceTransport.state;
  134. }
  135. /**
  136. * Current ICE gathering state.
  137. * @return {RTCIceGatheringState}
  138. */
  139. get iceGatheringState() {
  140. return this._iceGatheringState;
  141. }
  142. /**
  143. * Gets the local description.
  144. * @return {RTCSessionDescription}
  145. */
  146. get localDescription() {
  147. return this._localDescription;
  148. }
  149. /**
  150. * Gets the remote description.
  151. * @return {RTCSessionDescription}
  152. */
  153. get remoteDescription() {
  154. return this._remoteDescription;
  155. }
  156. /**
  157. * Current signaling state.
  158. * @return {RTCSignalingState}
  159. */
  160. get signalingState() {
  161. return this._signalingState;
  162. }
  163. /**
  164. * Adds a remote ICE candidate. Implements both the old callbacks based
  165. * signature and the new Promise based style.
  166. *
  167. * Arguments in Promise mode:
  168. * @param {RTCIceCandidate} candidate
  169. *
  170. * Arguments in callbacks mode:
  171. * @param {RTCIceCandidate} candidate
  172. * @param {function()} callback
  173. * @param {function(error)} errback
  174. */
  175. addIceCandidate(candidate, ...args) {
  176. let usePromise;
  177. let callback;
  178. let errback;
  179. if (!candidate) {
  180. throw new TypeError('candidate missing');
  181. }
  182. if (args.length === 0) {
  183. usePromise = true;
  184. } else {
  185. usePromise = false;
  186. callback = args[0];
  187. errback = args[1];
  188. if (typeof callback !== 'function') {
  189. throw new TypeError('callback missing');
  190. }
  191. if (typeof errback !== 'function') {
  192. throw new TypeError('errback missing');
  193. }
  194. }
  195. logger.debug('addIceCandidate() candidate:', candidate);
  196. if (usePromise) {
  197. return this._addIceCandidate(candidate);
  198. }
  199. this._addIceCandidate(candidate)
  200. .then(() => callback())
  201. .catch(error => errback(error));
  202. }
  203. /**
  204. * Adds a local MediaStream.
  205. * @param {MediaStream} stream.
  206. * NOTE: Deprecated API.
  207. */
  208. addStream(stream) {
  209. logger.debug('addStream()');
  210. this._addStream(stream);
  211. }
  212. /**
  213. * Closes the RTCPeerConnection and all the underlying ORTC objects.
  214. */
  215. close() {
  216. if (this._closed) {
  217. return;
  218. }
  219. this._closed = true;
  220. logger.debug('close()');
  221. this._updateAndEmitSignalingStateChange(RTCSignalingState.closed);
  222. // Close RTCIceGatherer.
  223. // NOTE: Not yet implemented by Edge.
  224. try {
  225. this._iceGatherer.close();
  226. } catch (error) {
  227. logger.warn(`iceGatherer.close() failed:${error}`);
  228. }
  229. // Close RTCIceTransport.
  230. try {
  231. this._iceTransport.stop();
  232. } catch (error) {
  233. logger.warn(`iceTransport.stop() failed:${error}`);
  234. }
  235. // Close RTCDtlsTransport.
  236. try {
  237. this._dtlsTransport.stop();
  238. } catch (error) {
  239. logger.warn(`dtlsTransport.stop() failed:${error}`);
  240. }
  241. // Close and clear RTCRtpSenders.
  242. for (const info of this._localTrackInfos.values()) {
  243. const rtpSender = info.rtpSender;
  244. try {
  245. rtpSender.stop();
  246. } catch (error) {
  247. logger.warn(`rtpSender.stop() failed:${error}`);
  248. }
  249. }
  250. this._localTrackInfos.clear();
  251. // Close and clear RTCRtpReceivers.
  252. for (const info of this._remoteTrackInfos.values()) {
  253. const rtpReceiver = info.rtpReceiver;
  254. try {
  255. rtpReceiver.stop();
  256. } catch (error) {
  257. logger.warn(`rtpReceiver.stop() failed:${error}`);
  258. }
  259. }
  260. this._remoteTrackInfos.clear();
  261. // Clear remote streams.
  262. this._remoteStreams.clear();
  263. }
  264. /**
  265. * Creates a local answer. Implements both the old callbacks based signature
  266. * and the new Promise based style.
  267. *
  268. * Arguments in Promise mode:
  269. * @param {RTCOfferOptions} [options]
  270. *
  271. * Arguments in callbacks mode:
  272. * @param {function(desc)} callback
  273. * @param {function(error)} errback
  274. * @param {MediaConstraints} [constraints]
  275. */
  276. createAnswer(...args) {
  277. let usePromise;
  278. let options;
  279. let callback;
  280. let errback;
  281. if (args.length <= 1) {
  282. usePromise = true;
  283. options = args[0];
  284. } else {
  285. usePromise = false;
  286. callback = args[0];
  287. errback = args[1];
  288. options = args[2];
  289. if (typeof callback !== 'function') {
  290. throw new TypeError('callback missing');
  291. }
  292. if (typeof errback !== 'function') {
  293. throw new TypeError('errback missing');
  294. }
  295. }
  296. logger.debug('createAnswer() options:', options);
  297. if (usePromise) {
  298. return this._createAnswer(options);
  299. }
  300. this._createAnswer(options)
  301. .then(desc => callback(desc))
  302. .catch(error => errback(error));
  303. }
  304. /**
  305. * Creates a RTCDataChannel.
  306. */
  307. createDataChannel() {
  308. logger.debug('createDataChannel()');
  309. // NOTE: DataChannels not implemented in Edge.
  310. throw new Error('createDataChannel() not supported in Edge');
  311. }
  312. /**
  313. * Creates a local offer. Implements both the old callbacks based signature
  314. * and the new Promise based style.
  315. *
  316. * Arguments in Promise mode:
  317. * @param {RTCOfferOptions} [options]
  318. *
  319. * Arguments in callbacks mode:
  320. * @param {function(desc)} callback
  321. * @param {function(error)} errback
  322. * @param {MediaConstraints} [constraints]
  323. */
  324. createOffer(...args) {
  325. let usePromise;
  326. let options;
  327. let callback;
  328. let errback;
  329. if (args.length <= 1) {
  330. usePromise = true;
  331. options = args[0];
  332. } else {
  333. usePromise = false;
  334. callback = args[0];
  335. errback = args[1];
  336. options = args[2];
  337. if (typeof callback !== 'function') {
  338. throw new TypeError('callback missing');
  339. }
  340. if (typeof errback !== 'function') {
  341. throw new TypeError('errback missing');
  342. }
  343. }
  344. logger.debug('createOffer() options:', options);
  345. if (usePromise) {
  346. return this._createOffer(options);
  347. }
  348. this._createOffer(options)
  349. .then(desc => callback(desc))
  350. .catch(error => errback(error));
  351. }
  352. /**
  353. * Gets a sequence of local MediaStreams.
  354. * @return {sequence<MediaStream>}
  355. */
  356. getLocalStreams() {
  357. return Array.from(this._localTrackInfos.values())
  358. .map(info => info.stream)
  359. .filter((elem, pos, arr) => arr.indexOf(elem) === pos);
  360. }
  361. /**
  362. * Gets a sequence of remote MediaStreams.
  363. * @return {sequence<MediaStream>}
  364. */
  365. getRemoteStreams() {
  366. return Array.from(this._remoteStreams.values());
  367. }
  368. /**
  369. * Get RTP statistics. Implements both the old callbacks based signature
  370. * and the new Promise based style.
  371. *
  372. * Arguments in Promise mode:
  373. * @param {MediaStreamTrack} [selector]
  374. *
  375. * Arguments in callbacks mode:
  376. * @param {MediaStreamTrack} [selector]
  377. * @param {function(desc)} callback
  378. * @param {function(error)} errback
  379. */
  380. getStats(...args) {
  381. let usePromise;
  382. let selector;
  383. let callback;
  384. let errback;
  385. if (typeof args[0] === 'function') {
  386. usePromise = false;
  387. callback = args[0];
  388. errback = args[1];
  389. } else if (typeof args[1] === 'function') {
  390. usePromise = false;
  391. selector = args[0];
  392. callback = args[1];
  393. errback = args[2];
  394. } else {
  395. usePromise = true;
  396. selector = args[0];
  397. }
  398. if (!usePromise && !errback) {
  399. errback = error => {
  400. logger.error(`getStats() failed: ${error}`);
  401. logger.error(error.stack);
  402. };
  403. }
  404. if (usePromise) {
  405. return this._getStats(selector);
  406. }
  407. this._getStats(selector)
  408. .then(stats => callback(stats))
  409. .catch(error => errback(error));
  410. }
  411. /**
  412. * Removes a local MediaStream.
  413. * @param {MediaStream} stream.
  414. * NOTE: Deprecated API.
  415. */
  416. removeStream(stream) {
  417. logger.debug('removeStream()');
  418. this._removeStream(stream);
  419. }
  420. /**
  421. * Applies a local description. Implements both the old callbacks based
  422. * signature and the new Promise based style.
  423. *
  424. * Arguments in Promise mode:
  425. * @param {RTCSessionDescriptionInit} desc
  426. *
  427. * Arguments in callbacks mode:
  428. * @param {RTCSessionDescription} desc
  429. * @param {function()} callback
  430. * @param {function(error)} errback
  431. */
  432. setLocalDescription(desc, ...args) {
  433. let usePromise;
  434. let callback;
  435. let errback;
  436. if (!desc) {
  437. throw new TypeError('description missing');
  438. }
  439. if (args.length === 0) {
  440. usePromise = true;
  441. } else {
  442. usePromise = false;
  443. callback = args[0];
  444. errback = args[1];
  445. if (typeof callback !== 'function') {
  446. throw new TypeError('callback missing');
  447. }
  448. if (typeof errback !== 'function') {
  449. throw new TypeError('errback missing');
  450. }
  451. }
  452. logger.debug('setLocalDescription() desc:', desc);
  453. if (usePromise) {
  454. return this._setLocalDescription(desc);
  455. }
  456. this._setLocalDescription(desc)
  457. .then(() => callback())
  458. .catch(error => errback(error));
  459. }
  460. /**
  461. * Applies a remote description. Implements both the old callbacks based
  462. * signature and the new Promise based style.
  463. *
  464. * Arguments in Promise mode:
  465. * @param {RTCSessionDescriptionInit} desc
  466. *
  467. * Arguments in callbacks mode:
  468. * @param {RTCSessionDescription} desc
  469. * @param {function()} callback
  470. * @param {function(error)} errback
  471. */
  472. setRemoteDescription(desc, ...args) {
  473. let usePromise;
  474. let callback;
  475. let errback;
  476. if (!desc) {
  477. throw new TypeError('description missing');
  478. }
  479. if (args.length === 0) {
  480. usePromise = true;
  481. } else {
  482. usePromise = false;
  483. callback = args[0];
  484. errback = args[1];
  485. if (typeof callback !== 'function') {
  486. throw new TypeError('callback missing');
  487. }
  488. if (typeof errback !== 'function') {
  489. throw new TypeError('errback missing');
  490. }
  491. }
  492. logger.debug('setRemoteDescription() desc:', desc);
  493. if (usePromise) {
  494. return this._setRemoteDescription(desc);
  495. }
  496. this._setRemoteDescription(desc)
  497. .then(() => callback())
  498. .catch(error => errback(error));
  499. }
  500. /**
  501. * Promise based implementation for addIceCandidate().
  502. * @return {Promise}
  503. * @private
  504. */
  505. _addIceCandidate(candidate) { // eslint-disable-line no-unused-vars
  506. if (this._closed) {
  507. return Promise.reject(
  508. new InvalidStateError('RTCPeerConnection closed'));
  509. }
  510. // NOTE: Edge does not support Trickle-ICE so just candidates in the
  511. // remote SDP are applied. Candidates given later would be just
  512. // ignored, so notify the called about that.
  513. return Promise.reject(new Error('addIceCandidate() not supported'));
  514. }
  515. /**
  516. * Implementation for addStream().
  517. * @private
  518. */
  519. _addStream(stream) {
  520. if (this._closed) {
  521. throw new InvalidStateError('RTCPeerConnection closed');
  522. }
  523. // Create a RTCRtpSender for each track.
  524. for (const track of stream.getTracks()) {
  525. // Ignore if ended.
  526. if (track.readyState === 'ended') {
  527. logger.warn('ignoring ended MediaStreamTrack');
  528. continue; // eslint-disable-line no-continue
  529. }
  530. // Ignore if track is already present.
  531. if (this._localTrackInfos.has(track.id)) {
  532. logger.warn('ignoring already handled MediaStreamTrack');
  533. continue; // eslint-disable-line no-continue
  534. }
  535. const rtpSender = new RTCRtpSender(track, this._dtlsTransport);
  536. // Store it in the map.
  537. this._localTrackInfos.set(track.id, {
  538. rtpSender,
  539. stream
  540. });
  541. }
  542. // Check for local tracks removal.
  543. for (const [ trackId, info ] of this._localTrackInfos) {
  544. const track = info.rtpSender.track;
  545. // Check if any of the local tracks has been stopped.
  546. if (track.readyState === 'ended') {
  547. logger.warn(
  548. '_addStream() an already handled track was stopped, '
  549. + `track.id:${track.id}`);
  550. try {
  551. info.rtpSender.stop();
  552. } catch (error) {
  553. logger.warn(`rtpSender.stop() failed:${error}`);
  554. }
  555. // Remove from the map.
  556. this._localTrackInfos.delete(track.id);
  557. // Also, if the stream was already handled, check whether tracks
  558. // have been removed via stream.removeTrack() and, if so, stop
  559. // their RtpSenders.
  560. } else if (info.stream === stream
  561. && !stream.getTrackById(trackId)) {
  562. logger.warn(
  563. '_addStream() a track in this stream was removed, '
  564. + `track.id:${trackId}`);
  565. try {
  566. info.rtpSender.stop();
  567. } catch (error) {
  568. logger.warn(`rtpSender.stop() failed:${error}`);
  569. }
  570. // Remove from the map.
  571. this._localTrackInfos.delete(track.id);
  572. }
  573. }
  574. // It may need to renegotiate.
  575. this._emitNegotiationNeeded();
  576. }
  577. /**
  578. * Promise based implementation for createAnswer().
  579. * @returns {Promise}
  580. * @private
  581. */
  582. _createAnswer(options) { // eslint-disable-line no-unused-vars
  583. if (this._closed) {
  584. return Promise.reject(
  585. new InvalidStateError('RTCPeerConnection closed'));
  586. }
  587. if (this.signalingState !== RTCSignalingState.haveRemoteOffer) {
  588. return Promise.reject(new InvalidStateError(
  589. `invalid signalingState "${this.signalingState}"`));
  590. }
  591. // Create an answer.
  592. const localDescription = this._createLocalDescription('answer');
  593. // Resolve with it.
  594. return Promise.resolve(localDescription);
  595. }
  596. /**
  597. * Creates the local RTCSessionDescription.
  598. * @param {String} type - 'offer' / 'answer'.
  599. * @return {RTCSessionDescription}
  600. */
  601. _createLocalDescription(type) {
  602. const sdpObject = {};
  603. const localIceParameters = this._iceGatherer.getLocalParameters();
  604. const localIceCandidates = this._iceGatherer.getLocalCandidates();
  605. const localDtlsParameters = this._dtlsTransport.getLocalParameters();
  606. // remoteDtlsParameters are not needed for offers.
  607. const remoteDtlsParameters = type === 'answer'
  608. ? this._dtlsTransport.getRemoteParameters() : null;
  609. const localCapabilities = this._localCapabilities;
  610. const localTrackInfos = this._localTrackInfos;
  611. // Increase SDP version if an offer.
  612. if (type === 'offer') {
  613. this._sdpGlobalFields.version++;
  614. }
  615. // SDP global fields.
  616. sdpObject.version = 0;
  617. sdpObject.origin = {
  618. address: '127.0.0.1',
  619. ipVer: 4,
  620. netType: 'IN',
  621. sessionId: this._sdpGlobalFields.id,
  622. sessionVersion: this._sdpGlobalFields.version,
  623. username: 'jitsi-ortc-webrtc-shim'
  624. };
  625. sdpObject.name = '-';
  626. sdpObject.timing = {
  627. start: 0,
  628. stop: 0
  629. };
  630. sdpObject.msidSemantic = {
  631. semantic: 'WMS',
  632. token: '*'
  633. };
  634. sdpObject.groups = [
  635. {
  636. mids: Array.from(this._mids.keys()).join(' '),
  637. type: 'BUNDLE'
  638. }
  639. ];
  640. sdpObject.media = [];
  641. // DTLS fingerprint.
  642. sdpObject.fingerprint = {
  643. hash: localDtlsParameters.fingerprints[0].value,
  644. type: localDtlsParameters.fingerprints[0].algorithm
  645. };
  646. // Let's check whether there is video RTX.
  647. let hasVideoRtx = false;
  648. for (const codec of localCapabilities.codecs) {
  649. if (codec.kind === 'video' && codec.name === 'rtx') {
  650. hasVideoRtx = true;
  651. break;
  652. }
  653. }
  654. // Add m= sections.
  655. for (const [ mid, kind ] of this._mids) {
  656. addMediaSection.call(this, mid, kind);
  657. }
  658. // Create a RTCSessionDescription.
  659. const localDescription = new RTCSessionDescription({
  660. type,
  661. _sdpObject: sdpObject
  662. });
  663. logger.debug('_createLocalDescription():', localDescription);
  664. return localDescription;
  665. /**
  666. * Add a m= section.
  667. */
  668. function addMediaSection(mid, kind) {
  669. const mediaObject = {};
  670. // m= line.
  671. mediaObject.type = kind;
  672. switch (kind) {
  673. case 'audio':
  674. case 'video':
  675. mediaObject.protocol = 'RTP/SAVPF';
  676. mediaObject.port = 9;
  677. mediaObject.direction = 'sendrecv';
  678. break;
  679. case 'application':
  680. mediaObject.protocol = 'DTLS/SCTP';
  681. mediaObject.port = 0; // Reject m section.
  682. mediaObject.payloads = '0'; // Just put something.
  683. mediaObject.direction = 'inactive';
  684. break;
  685. }
  686. // c= line.
  687. mediaObject.connection = {
  688. ip: '127.0.0.1',
  689. version: 4
  690. };
  691. // a=mid attribute.
  692. mediaObject.mid = mid;
  693. // ICE.
  694. mediaObject.iceUfrag = localIceParameters.usernameFragment;
  695. mediaObject.icePwd = localIceParameters.password;
  696. mediaObject.candidates = [];
  697. for (const candidate of localIceCandidates) {
  698. const candidateObject = {};
  699. // rtcp-mux is assumed, so component is always 1 (RTP).
  700. candidateObject.component = 1;
  701. candidateObject.foundation = candidate.foundation;
  702. candidateObject.ip = candidate.ip;
  703. candidateObject.port = candidate.port;
  704. candidateObject.priority = candidate.priority;
  705. candidateObject.transport
  706. = candidate.protocol.toLowerCase();
  707. candidateObject.type = candidate.type;
  708. if (candidateObject.transport === 'tcp') {
  709. candidateObject.tcptype = candidate.tcpType;
  710. }
  711. mediaObject.candidates.push(candidateObject);
  712. }
  713. mediaObject.endOfCandidates = 'end-of-candidates';
  714. // DTLS.
  715. // If 'offer' always use 'actpass'.
  716. if (type === 'offer') {
  717. mediaObject.setup = 'actpass';
  718. } else {
  719. mediaObject.setup = remoteDtlsParameters.role === 'server'
  720. ? 'active' : 'passive';
  721. }
  722. if (kind === 'audio' || kind === 'video') {
  723. mediaObject.rtp = [];
  724. mediaObject.rtcpFb = [];
  725. mediaObject.fmtp = [];
  726. // Array of payload types.
  727. const payloads = [];
  728. // Add codecs.
  729. for (const codec of localCapabilities.codecs) {
  730. if (codec.kind && codec.kind !== kind) {
  731. continue; // eslint-disable-line no-continue
  732. }
  733. payloads.push(codec.preferredPayloadType);
  734. const rtpObject = {
  735. codec: codec.name,
  736. payload: codec.preferredPayloadType,
  737. rate: codec.clockRate
  738. };
  739. if (codec.numChannels > 1) {
  740. rtpObject.encoding = codec.numChannels;
  741. }
  742. mediaObject.rtp.push(rtpObject);
  743. // If codec has parameters add them into a=fmtp attributes.
  744. if (codec.parameters) {
  745. const paramFmtp = {
  746. config: '',
  747. payload: codec.preferredPayloadType
  748. };
  749. for (const name of Object.keys(codec.parameters)) {
  750. /* eslint-disable max-depth */
  751. if (paramFmtp.config) {
  752. paramFmtp.config += ';';
  753. }
  754. /* eslint-enable max-depth */
  755. paramFmtp.config
  756. += `${name}=${codec.parameters[name]}`;
  757. }
  758. if (paramFmtp.config) {
  759. mediaObject.fmtp.push(paramFmtp);
  760. }
  761. }
  762. // Set RTCP feedback.
  763. for (const fb of codec.rtcpFeedback || []) {
  764. mediaObject.rtcpFb.push({
  765. payload: codec.preferredPayloadType,
  766. subtype: fb.parameter || undefined,
  767. type: fb.type
  768. });
  769. }
  770. }
  771. // If there are no codecs, set this m section as unavailable.
  772. if (payloads.length === 0) {
  773. mediaObject.payloads = '9'; // Just put something.
  774. mediaObject.port = 0;
  775. mediaObject.direction = 'inactive';
  776. } else {
  777. mediaObject.payloads = payloads.join(' ');
  778. }
  779. // SSRCs.
  780. mediaObject.ssrcs = [];
  781. mediaObject.ssrcGroups = [];
  782. // Add RTP sending stuff.
  783. for (const info of localTrackInfos.values()) {
  784. const rtpSender = info.rtpSender;
  785. const streamId = info.stream.id;
  786. const track = rtpSender.track;
  787. // Ignore if ended.
  788. if (track.readyState === 'ended') {
  789. continue; // eslint-disable-line no-continue
  790. }
  791. if (track.kind !== kind) {
  792. continue; // eslint-disable-line no-continue
  793. }
  794. // Set a random provisional SSRC if not set.
  795. if (!info.ssrc) {
  796. info.ssrc = SDPUtil.generateSsrc();
  797. }
  798. // Whether RTX should be enabled.
  799. const enableRtx = hasVideoRtx && track.kind === 'video';
  800. // Set a random provisional RTX SSRC if not set.
  801. if (enableRtx && !info.rtxSsrc) {
  802. info.rtxSsrc = info.ssrc + 1;
  803. }
  804. mediaObject.ssrcs.push({
  805. attribute: 'cname',
  806. id: info.ssrc,
  807. value: CNAME
  808. });
  809. mediaObject.ssrcs.push({
  810. attribute: 'msid',
  811. id: info.ssrc,
  812. value: `${streamId} ${track.id}`
  813. });
  814. mediaObject.ssrcs.push({
  815. attribute: 'mslabel',
  816. id: info.ssrc,
  817. value: streamId
  818. });
  819. mediaObject.ssrcs.push({
  820. attribute: 'label',
  821. id: info.ssrc,
  822. value: track.id
  823. });
  824. if (enableRtx) {
  825. mediaObject.ssrcs.push({
  826. attribute: 'cname',
  827. id: info.rtxSsrc,
  828. value: CNAME
  829. });
  830. mediaObject.ssrcs.push({
  831. attribute: 'msid',
  832. id: info.rtxSsrc,
  833. value: `${streamId} ${track.id}`
  834. });
  835. mediaObject.ssrcs.push({
  836. attribute: 'mslabel',
  837. id: info.rtxSsrc,
  838. value: streamId
  839. });
  840. mediaObject.ssrcs.push({
  841. attribute: 'label',
  842. id: info.rtxSsrc,
  843. value: track.id
  844. });
  845. mediaObject.ssrcGroups.push({
  846. semantics: 'FID',
  847. ssrcs: `${info.ssrc} ${info.rtxSsrc}`
  848. });
  849. }
  850. }
  851. // RTP header extensions.
  852. mediaObject.ext = [];
  853. for (const extension of localCapabilities.headerExtensions) {
  854. if (extension.kind && extension.kind !== kind) {
  855. continue; // eslint-disable-line no-continue
  856. }
  857. mediaObject.ext.push({
  858. value: extension.preferredId,
  859. uri: extension.uri
  860. });
  861. }
  862. // a=rtcp-mux attribute.
  863. mediaObject.rtcpMux = 'rtcp-mux';
  864. // a=rtcp-rsize.
  865. mediaObject.rtcpRsize = 'rtcp-rsize';
  866. }
  867. // Add the media section.
  868. sdpObject.media.push(mediaObject);
  869. }
  870. }
  871. /**
  872. * Promise based implementation for createOffer().
  873. * @returns {Promise}
  874. * @private
  875. */
  876. _createOffer(options) { // eslint-disable-line no-unused-vars
  877. if (this._closed) {
  878. return Promise.reject(
  879. new InvalidStateError('RTCPeerConnection closed'));
  880. }
  881. if (this.signalingState !== RTCSignalingState.stable) {
  882. return Promise.reject(new InvalidStateError(
  883. `invalid signalingState "${this.signalingState}"`));
  884. }
  885. // Use ice gathering complete promise an invalid state error occurs if
  886. // creating a local description before it is complete.
  887. return this._iceGatheringCompletePromise
  888. .then(() => {
  889. // Stub out _mids and _localCapabilities if creating an offer
  890. // as they are normally set on answer and will cause errors in
  891. // create a local description if falsy.
  892. if (!this.hasAttemptedOffer) {
  893. if (!this._mids.size) {
  894. this._mids = new Map([
  895. [ 'audio', 'audio' ],
  896. [ 'video', 'video' ]
  897. ]);
  898. }
  899. if (!this._localCapabilities) {
  900. this._localCapabilities
  901. = utils.getLocalCapabilities(
  902. RTCRtpSender.getCapabilities());
  903. }
  904. this.hasAttemptedOffer = true;
  905. }
  906. return this._createLocalDescription('offer');
  907. });
  908. }
  909. /**
  910. * Emit 'addstream' event.
  911. * @private
  912. */
  913. _emitAddStream(stream) {
  914. if (this._closed) {
  915. return;
  916. }
  917. logger.debug('emitting "addstream"');
  918. const event = new yaeti.Event('addstream');
  919. event.stream = stream;
  920. this.dispatchEvent(event);
  921. }
  922. /**
  923. * May emit buffered ICE candidates.
  924. * @private
  925. */
  926. _emitBufferedIceCandidates() {
  927. if (this._closed) {
  928. return;
  929. }
  930. for (const sdpCandidate of this._bufferedIceCandidates) {
  931. if (!sdpCandidate) {
  932. continue; // eslint-disable-line no-continue
  933. }
  934. // Now we have set the MID values of the SDP O/A, so let's fill the
  935. // sdpMIndex of the candidate.
  936. sdpCandidate.sdpMIndex = this._mids.keys().next().value;
  937. logger.debug(
  938. 'emitting buffered "icecandidate", candidate:', sdpCandidate);
  939. const event = new yaeti.Event('icecandidate');
  940. event.candidate = sdpCandidate;
  941. this.dispatchEvent(event);
  942. }
  943. this._bufferedIceCandidates = [];
  944. }
  945. /**
  946. * May emit 'connectionstatechange' event.
  947. * @private
  948. */
  949. _emitConnectionStateChange() {
  950. if (this._closed && this.connectionState !== 'closed') {
  951. return;
  952. }
  953. logger.debug(
  954. 'emitting "connectionstatechange", connectionState:',
  955. this.connectionState);
  956. const event = new yaeti.Event('connectionstatechange');
  957. this.dispatchEvent(event);
  958. }
  959. /**
  960. * May emit 'icecandidate' event.
  961. * @private
  962. */
  963. _emitIceCandidate(candidate) {
  964. if (this._closed) {
  965. return;
  966. }
  967. let sdpCandidate = null;
  968. if (candidate) {
  969. // NOTE: We assume BUNDLE so let's just emit candidates for the
  970. // first m= section.
  971. const sdpMIndex = this._mids.keys().next().value;
  972. const sdpMLineIndex = 0;
  973. let sdpAttribute
  974. = `candidate:${candidate.foundation} 1 ${candidate.protocol}`
  975. + ` ${candidate.priority} ${candidate.ip} ${candidate.port}`
  976. + ` typ ${candidate.type}`;
  977. if (candidate.relatedAddress) {
  978. sdpAttribute += ` raddr ${candidate.relatedAddress}`;
  979. }
  980. if (candidate.relatedPort) {
  981. sdpAttribute += ` rport ${candidate.relatedPort}`;
  982. }
  983. if (candidate.protocol === 'tcp') {
  984. sdpAttribute += ` tcptype ${candidate.tcpType}`;
  985. }
  986. sdpCandidate = {
  987. candidate: sdpAttribute,
  988. component: 1, // rtcp-mux assumed, so always 1 (RTP).
  989. foundation: candidate.foundation,
  990. ip: candidate.ip,
  991. port: candidate.port,
  992. priority: candidate.priority,
  993. protocol: candidate.protocol,
  994. type: candidate.type,
  995. sdpMIndex,
  996. sdpMLineIndex
  997. };
  998. if (candidate.protocol === 'tcp') {
  999. sdpCandidate.tcptype = candidate.tcpType;
  1000. }
  1001. if (candidate.relatedAddress) {
  1002. sdpCandidate.relatedAddress = candidate.relatedAddress;
  1003. }
  1004. if (candidate.relatedPort) {
  1005. sdpCandidate.relatedPort = candidate.relatedPort;
  1006. }
  1007. }
  1008. // If we don't have yet a local description, buffer the candidate.
  1009. if (this._localDescription) {
  1010. logger.debug(
  1011. 'emitting "icecandidate", candidate:', sdpCandidate);
  1012. const event = new yaeti.Event('icecandidate');
  1013. event.candidate = sdpCandidate;
  1014. this.dispatchEvent(event);
  1015. } else {
  1016. logger.debug(
  1017. 'buffering gathered ICE candidate:', sdpCandidate);
  1018. this._bufferedIceCandidates.push(sdpCandidate);
  1019. }
  1020. }
  1021. /**
  1022. * May emit 'iceconnectionstatechange' event.
  1023. * @private
  1024. */
  1025. _emitIceConnectionStateChange() {
  1026. if (this._closed && this.iceConnectionState !== 'closed') {
  1027. return;
  1028. }
  1029. logger.debug(
  1030. 'emitting "iceconnectionstatechange", iceConnectionState:',
  1031. this.iceConnectionState);
  1032. const event = new yaeti.Event('iceconnectionstatechange');
  1033. this.dispatchEvent(event);
  1034. }
  1035. /**
  1036. * May emit 'negotiationneeded' event.
  1037. * @private
  1038. */
  1039. _emitNegotiationNeeded() {
  1040. // Ignore if signalingState is not 'stable'.
  1041. if (this.signalingState !== RTCSignalingState.stable) {
  1042. return;
  1043. }
  1044. logger.debug('emitting "negotiationneeded"');
  1045. const event = new yaeti.Event('negotiationneeded');
  1046. this.dispatchEvent(event);
  1047. }
  1048. /**
  1049. * Emit 'removestream' event.
  1050. * @private
  1051. */
  1052. _emitRemoveStream(stream) {
  1053. if (this._closed) {
  1054. return;
  1055. }
  1056. logger.debug('emitting "removestream"');
  1057. const event = new yaeti.Event('removestream');
  1058. event.stream = stream;
  1059. this.dispatchEvent(event);
  1060. }
  1061. /**
  1062. * Get RTP parameters for a RTCRtpReceiver.
  1063. * @private
  1064. * @return {RTCRtpParameters}
  1065. */
  1066. _getParametersForRtpReceiver(kind, data) {
  1067. const ssrc = data.ssrc;
  1068. const rtxSsrc = data.rtxSsrc;
  1069. const cname = data.cname;
  1070. const localCapabilities = this._localCapabilities;
  1071. const parameters = {
  1072. codecs: [],
  1073. degradationPreference: 'balanced',
  1074. encodings: [],
  1075. headerExtensions: [],
  1076. muxId: '',
  1077. rtcp: {
  1078. cname,
  1079. compound: true, // NOTE: Implemented in Edge.
  1080. mux: true,
  1081. reducedSize: true // NOTE: Not yet implemented in Edge.
  1082. }
  1083. };
  1084. const codecs = [];
  1085. let codecPayloadType;
  1086. for (const codecCapability of localCapabilities.codecs) {
  1087. if (codecCapability.kind !== kind
  1088. || codecCapability.name === 'rtx') {
  1089. continue; // eslint-disable-line no-continue
  1090. }
  1091. codecPayloadType = codecCapability.preferredPayloadType;
  1092. codecs.push({
  1093. clockRate: codecCapability.clockRate,
  1094. maxptime: codecCapability.maxptime,
  1095. mimeType: codecCapability.mimeType,
  1096. name: codecCapability.name,
  1097. numChannels: codecCapability.numChannels,
  1098. parameters: codecCapability.parameters,
  1099. payloadType: codecCapability.preferredPayloadType,
  1100. ptime: codecCapability.ptime,
  1101. rtcpFeedback: codecCapability.rtcpFeedback
  1102. });
  1103. break;
  1104. }
  1105. if (rtxSsrc) {
  1106. for (const codecCapability of localCapabilities.codecs) {
  1107. if (codecCapability.kind !== kind
  1108. || codecCapability.name !== 'rtx') {
  1109. continue; // eslint-disable-line no-continue
  1110. }
  1111. codecs.push({
  1112. clockRate: codecCapability.clockRate,
  1113. mimeType: codecCapability.mimeType,
  1114. name: 'rtx',
  1115. parameters: codecCapability.parameters,
  1116. payloadType: codecCapability.preferredPayloadType,
  1117. rtcpFeedback: codecCapability.rtcpFeedback
  1118. });
  1119. break;
  1120. }
  1121. }
  1122. parameters.codecs = codecs;
  1123. const encoding = {
  1124. active: true,
  1125. codecPayloadType,
  1126. ssrc
  1127. };
  1128. if (rtxSsrc) {
  1129. encoding.rtx = {
  1130. ssrc: rtxSsrc
  1131. };
  1132. }
  1133. parameters.encodings.push(encoding);
  1134. for (const extension of localCapabilities.headerExtensions) {
  1135. if (extension.kind !== kind) {
  1136. continue; // eslint-disable-line no-continue
  1137. }
  1138. parameters.headerExtensions.push({
  1139. encrypt: extension.preferredEncrypt,
  1140. id: extension.preferredId,
  1141. uri: extension.uri
  1142. });
  1143. }
  1144. return parameters;
  1145. }
  1146. /**
  1147. * Get RTP parameters for a RTCRtpSender.
  1148. * @private
  1149. * @return {RTCRtpParameters}
  1150. */
  1151. _getParametersForRtpSender(kind, data) {
  1152. const ssrc = data.ssrc;
  1153. const rtxSsrc = data.rtxSsrc;
  1154. const cname = CNAME;
  1155. const localCapabilities = this._localCapabilities;
  1156. const parameters = {
  1157. codecs: [],
  1158. degradationPreference: 'balanced',
  1159. encodings: [],
  1160. headerExtensions: [],
  1161. muxId: '',
  1162. rtcp: {
  1163. cname,
  1164. compound: true, // NOTE: Implemented in Edge.
  1165. mux: true,
  1166. reducedSize: true // NOTE: Not yet implemented in Edge.
  1167. }
  1168. };
  1169. const codecs = [];
  1170. let codecPayloadType;
  1171. for (const codecCapability of localCapabilities.codecs) {
  1172. if (codecCapability.kind !== kind
  1173. || codecCapability.name === 'rtx') {
  1174. continue; // eslint-disable-line no-continue
  1175. }
  1176. codecPayloadType = codecCapability.preferredPayloadType;
  1177. codecs.push({
  1178. clockRate: codecCapability.clockRate,
  1179. maxptime: codecCapability.maxptime,
  1180. mimeType: codecCapability.mimeType,
  1181. name: codecCapability.name,
  1182. numChannels: codecCapability.numChannels,
  1183. parameters: codecCapability.parameters,
  1184. payloadType: codecCapability.preferredPayloadType,
  1185. ptime: codecCapability.ptime,
  1186. rtcpFeedback: codecCapability.rtcpFeedback
  1187. });
  1188. break;
  1189. }
  1190. if (rtxSsrc) {
  1191. for (const codecCapability of localCapabilities.codecs) {
  1192. if (codecCapability.kind !== kind
  1193. || codecCapability.name !== 'rtx') {
  1194. continue; // eslint-disable-line no-continue
  1195. }
  1196. codecs.push({
  1197. clockRate: codecCapability.clockRate,
  1198. mimeType: codecCapability.mimeType,
  1199. name: 'rtx',
  1200. parameters: codecCapability.parameters,
  1201. payloadType: codecCapability.preferredPayloadType,
  1202. rtcpFeedback: codecCapability.rtcpFeedback
  1203. });
  1204. break;
  1205. }
  1206. }
  1207. parameters.codecs = codecs;
  1208. const encoding = {
  1209. active: true,
  1210. codecPayloadType,
  1211. ssrc
  1212. };
  1213. if (rtxSsrc) {
  1214. encoding.rtx = {
  1215. ssrc: rtxSsrc
  1216. };
  1217. }
  1218. parameters.encodings.push(encoding);
  1219. for (const extension of localCapabilities.headerExtensions) {
  1220. if (extension.kind !== kind) {
  1221. continue; // eslint-disable-line no-continue
  1222. }
  1223. parameters.headerExtensions.push({
  1224. encrypt: extension.preferredEncrypt,
  1225. id: extension.preferredId,
  1226. uri: extension.uri
  1227. });
  1228. }
  1229. return parameters;
  1230. }
  1231. /**
  1232. * Promise based implementation for getStats().
  1233. * @return {Promise} RTCStats dictionary.
  1234. * @private
  1235. */
  1236. _getStats(selector) { // eslint-disable-line no-unused-vars
  1237. if (this._closed) {
  1238. return Promise.reject(
  1239. new InvalidStateError('RTCPeerConnection closed'));
  1240. }
  1241. const iceGatherer = this._iceGatherer;
  1242. const iceTransport = this._iceTransport;
  1243. const rtpSenders = [];
  1244. const rtpReceivers = [];
  1245. const promises = [];
  1246. // Get RtpSenders.
  1247. for (const info of this._localTrackInfos.values()) {
  1248. const { rtpSender, sending } = info;
  1249. if (sending) {
  1250. rtpSenders.push(rtpSender);
  1251. }
  1252. }
  1253. // Get RtpReceivers.
  1254. for (const info of this._remoteTrackInfos.values()) {
  1255. const { rtpReceiver } = info;
  1256. rtpReceivers.push(rtpReceiver);
  1257. }
  1258. // Collect all the stats.
  1259. if (iceGatherer) {
  1260. promises.push(
  1261. iceGatherer.getStats()
  1262. .catch(() => null));
  1263. }
  1264. if (iceTransport) {
  1265. promises.push(
  1266. iceTransport.getStats()
  1267. .catch(() => null));
  1268. // NOTE: Proprietary stuff in Edge.
  1269. if (typeof iceTransport.msGetStats === 'function') {
  1270. promises.push(
  1271. iceTransport.msGetStats()
  1272. .catch(() => null));
  1273. }
  1274. }
  1275. for (const rtpSender of rtpSenders) {
  1276. const isAudio = rtpSender.track.kind === 'audio';
  1277. promises.push(rtpSender.getStats()
  1278. .then(data => {
  1279. // Remove audioLevel from type="track" stats if this is
  1280. // not an audio sender.
  1281. if (!isAudio) {
  1282. for (const key of Object.keys(data)) {
  1283. const stat = data[key];
  1284. if (stat.type === 'track') {
  1285. delete stat.audioLevel;
  1286. }
  1287. }
  1288. }
  1289. return data;
  1290. })
  1291. .catch(() => null));
  1292. }
  1293. for (const rtpReceiver of rtpReceivers) {
  1294. const isAudio = rtpReceiver.track.kind === 'audio';
  1295. promises.push(rtpReceiver.getStats()
  1296. .then(data => {
  1297. // Remove audioLevel from type="track" stats if this is
  1298. // not an audio receiver.
  1299. if (!isAudio) {
  1300. for (const key of Object.keys(data)) {
  1301. const stat = data[key];
  1302. if (stat.type === 'track') {
  1303. delete stat.audioLevel;
  1304. }
  1305. }
  1306. }
  1307. return data;
  1308. })
  1309. .catch(() => null));
  1310. }
  1311. return Promise.all(promises)
  1312. .then(datas => {
  1313. const stats = {};
  1314. for (const data of datas) {
  1315. if (!data) {
  1316. continue; // eslint-disable-line no-continue
  1317. }
  1318. for (const key of Object.keys(data)) {
  1319. stats[key] = data[key];
  1320. }
  1321. }
  1322. return stats;
  1323. });
  1324. }
  1325. /**
  1326. * Handles the local initial answer.
  1327. * @return {Promise}
  1328. * @private
  1329. */
  1330. _handleLocalInitialAnswer(desc) {
  1331. logger.debug('_handleLocalInitialAnswer(), desc:', desc);
  1332. const sdpObject = desc.sdpObject;
  1333. // Update local capabilities as decided by the app.
  1334. this._localCapabilities = utils.extractCapabilities(sdpObject);
  1335. logger.debug('local capabilities:', this._localCapabilities);
  1336. // NOTE: We assume that the answer given by the app does not change
  1337. // SSRC or PT values. If so, things won't work as expected.
  1338. }
  1339. /**
  1340. * Handles a local re-answer.
  1341. * @return {Promise}
  1342. * @private
  1343. */
  1344. _handleLocalReAnswer(desc) {
  1345. logger.debug('_handleLocalReAnswer(), desc:', desc);
  1346. const sdpObject = desc.sdpObject;
  1347. // Update local capabilities as decided by the app.
  1348. this._localCapabilities = utils.extractCapabilities(sdpObject);
  1349. logger.debug('local capabilities:', this._localCapabilities);
  1350. // NOTE: We assume that the answer given by the app does not change
  1351. // SSRC or PT values. If so, things won't work as expected.
  1352. }
  1353. /**
  1354. * Handles the remote initial offer.
  1355. * @return {Promise}
  1356. * @private
  1357. */
  1358. _handleRemoteInitialOffer(desc) {
  1359. logger.debug('_handleRemoteInitialOffer(), desc:', desc);
  1360. const sdpObject = desc.sdpObject;
  1361. // Set MID values.
  1362. this._mids = utils.extractMids(sdpObject);
  1363. // Get remote RTP capabilities.
  1364. const remoteCapabilities = utils.extractCapabilities(sdpObject);
  1365. logger.debug('remote capabilities:', remoteCapabilities);
  1366. // Get local RTP capabilities (filter them with remote capabilities).
  1367. this._localCapabilities
  1368. = utils.getLocalCapabilities(remoteCapabilities);
  1369. // Start ICE and DTLS.
  1370. this._startIceAndDtls(desc);
  1371. }
  1372. /**
  1373. * Handles a remote re-offer.
  1374. * @return {Promise}
  1375. * @private
  1376. */
  1377. _handleRemoteReOffer(desc) {
  1378. logger.debug('_handleRemoteReOffer(), desc:', desc);
  1379. const sdpObject = desc.sdpObject;
  1380. // Update MID values (just in case).
  1381. this._mids = utils.extractMids(sdpObject);
  1382. // Get remote RTP capabilities (filter them with remote capabilities).
  1383. const remoteCapabilities = utils.extractCapabilities(sdpObject);
  1384. logger.debug('remote capabilities:', remoteCapabilities);
  1385. // Update local RTP capabilities (just in case).
  1386. this._localCapabilities
  1387. = utils.getLocalCapabilities(remoteCapabilities);
  1388. }
  1389. /**
  1390. * Start receiving remote media.
  1391. */
  1392. _receiveMedia() {
  1393. logger.debug('_receiveMedia()');
  1394. const currentRemoteSsrcs = new Set(this._remoteTrackInfos.keys());
  1395. const newRemoteTrackInfos
  1396. = utils.extractTrackInfos(this._remoteDescription.sdpObject);
  1397. // Map of new remote MediaStream indexed by MediaStream.jitsiRemoteId.
  1398. const addedRemoteStreams = new Map();
  1399. // Map of remote MediaStream indexed by added MediaStreamTrack.
  1400. // NOTE: Just filled for already existing streams.
  1401. const addedRemoteTracks = new Map();
  1402. // Map of remote MediaStream indexed by removed MediaStreamTrack.
  1403. const removedRemoteTracks = new Map();
  1404. logger.debug(
  1405. '_receiveMedia() remote track infos:', newRemoteTrackInfos);
  1406. // Check new tracks.
  1407. for (const [ ssrc, info ] of newRemoteTrackInfos) {
  1408. // If already handled, ignore it.
  1409. if (currentRemoteSsrcs.has(ssrc)) {
  1410. continue; // eslint-disable-line no-continue
  1411. }
  1412. logger.debug(`_receiveMedia() new remote track, ssrc:${ssrc}`);
  1413. // Otherwise append to the map.
  1414. this._remoteTrackInfos.set(ssrc, info);
  1415. const kind = info.kind;
  1416. const rtxSsrc = info.rtxSsrc;
  1417. const streamRemoteId = info.streamId;
  1418. const trackRemoteId = info.trackId;
  1419. const cname = info.cname;
  1420. const isNewStream = !this._remoteStreams.has(streamRemoteId);
  1421. let stream;
  1422. if (isNewStream) {
  1423. logger.debug(
  1424. `_receiveMedia() new remote stream, id:${streamRemoteId}`);
  1425. // Create a new MediaStream.
  1426. stream = new MediaStream();
  1427. // Set custom property with the remote id.
  1428. stream.jitsiRemoteId = streamRemoteId;
  1429. addedRemoteStreams.set(streamRemoteId, stream);
  1430. this._remoteStreams.set(streamRemoteId, stream);
  1431. } else {
  1432. stream = this._remoteStreams.get(streamRemoteId);
  1433. }
  1434. const rtpReceiver = new RTCRtpReceiver(this._dtlsTransport, kind);
  1435. const parameters = this._getParametersForRtpReceiver(kind, {
  1436. ssrc,
  1437. rtxSsrc,
  1438. cname
  1439. });
  1440. // Store the track into the info object.
  1441. // NOTE: This should not be needed, but Edge has a bug:
  1442. // https://developer.microsoft.com/en-us/microsoft-edge/platform/
  1443. // issues/12399497/
  1444. info.track = rtpReceiver.track;
  1445. // Set error handler.
  1446. rtpReceiver.onerror = ev => {
  1447. logger.error('rtpReceiver "error" event, event:');
  1448. logger.error(ev);
  1449. };
  1450. // Fill the info with the stream and rtpReceiver.
  1451. info.stream = stream;
  1452. info.rtpReceiver = rtpReceiver;
  1453. logger.debug(
  1454. 'calling rtpReceiver.receive(), parameters:', parameters);
  1455. // Start receiving media.
  1456. try {
  1457. rtpReceiver.receive(parameters);
  1458. // Get the associated MediaStreamTrack.
  1459. const track = info.track;
  1460. // Set custom property with the remote id.
  1461. track.jitsiRemoteId = trackRemoteId;
  1462. // Add the track to the stream.
  1463. stream.addTrack(track);
  1464. if (!addedRemoteStreams.has(streamRemoteId)) {
  1465. addedRemoteTracks.set(track, stream);
  1466. }
  1467. } catch (error) {
  1468. logger.error(`rtpReceiver.receive() failed:${error.message}`);
  1469. logger.error(error);
  1470. }
  1471. }
  1472. // Check track removal.
  1473. for (const ssrc of currentRemoteSsrcs) {
  1474. if (newRemoteTrackInfos.has(ssrc)) {
  1475. continue; // eslint-disable-line no-continue
  1476. }
  1477. logger.debug(`_receiveMedia() remote track removed, ssrc:${ssrc}`);
  1478. const info = this._remoteTrackInfos.get(ssrc);
  1479. const stream = info.stream;
  1480. const track = info.track;
  1481. const rtpReceiver = info.rtpReceiver;
  1482. try {
  1483. rtpReceiver.stop();
  1484. } catch (error) {
  1485. logger.warn(`rtpReceiver.stop() failed:${error}`);
  1486. }
  1487. removedRemoteTracks.set(track, stream);
  1488. stream.removeTrack(track);
  1489. this._remoteTrackInfos.delete(ssrc);
  1490. }
  1491. // Emit MediaStream 'addtrack' for new tracks in already existing
  1492. // streams.
  1493. for (const [ track, stream ] of addedRemoteTracks) {
  1494. const event = new Event('addtrack');
  1495. event.track = track;
  1496. stream.dispatchEvent(event);
  1497. }
  1498. // Emit MediaStream 'removetrack' for removed tracks.
  1499. for (const [ track, stream ] of removedRemoteTracks) {
  1500. const event = new Event('removetrack');
  1501. event.track = track;
  1502. stream.dispatchEvent(event);
  1503. }
  1504. // Emit RTCPeerConnection 'addstream' for new remote streams.
  1505. for (const stream of addedRemoteStreams.values()) {
  1506. // Check whether at least a track was added, otherwise ignore it.
  1507. if (stream.getTracks().length === 0) {
  1508. logger.warn(
  1509. 'ignoring new stream for which no track could be added');
  1510. addedRemoteStreams.delete(stream.jitsiRemoteId);
  1511. this._remoteStreams.delete(stream.jitsiRemoteId);
  1512. } else {
  1513. this._emitAddStream(stream);
  1514. }
  1515. }
  1516. // Emit RTCPeerConnection 'removestream' for removed remote streams.
  1517. for (const [ streamRemoteId, stream ] of this._remoteStreams) {
  1518. if (stream.getTracks().length > 0) {
  1519. continue; // eslint-disable-line no-continue
  1520. }
  1521. this._remoteStreams.delete(streamRemoteId);
  1522. this._emitRemoveStream(stream);
  1523. }
  1524. }
  1525. /**
  1526. * Implementation for removeStream().
  1527. * @private
  1528. */
  1529. _removeStream(stream) {
  1530. if (this._closed) {
  1531. throw new InvalidStateError('RTCPeerConnection closed');
  1532. }
  1533. // Stop and remove the RTCRtpSender associated to each track.
  1534. for (const track of stream.getTracks()) {
  1535. // Ignore if track not present.
  1536. if (!this._localTrackInfos.has(track.id)) {
  1537. continue; // eslint-disable-line no-continue
  1538. }
  1539. const rtpSender = this._localTrackInfos.get(track.id).rtpSender;
  1540. try {
  1541. rtpSender.stop();
  1542. } catch (error) {
  1543. logger.warn(`rtpSender.stop() failed:${error}`);
  1544. }
  1545. // Remove from the map.
  1546. this._localTrackInfos.delete(track.id);
  1547. }
  1548. // It may need to renegotiate.
  1549. this._emitNegotiationNeeded();
  1550. }
  1551. /**
  1552. * Start sending our media to the remote.
  1553. */
  1554. _sendMedia() {
  1555. logger.debug('_sendMedia()');
  1556. for (const info of this._localTrackInfos.values()) {
  1557. // Ignore if already sending.
  1558. if (info.sending) {
  1559. continue; // eslint-disable-line no-continue
  1560. }
  1561. const rtpSender = info.rtpSender;
  1562. const ssrc = info.ssrc;
  1563. const rtxSsrc = info.rtxSsrc;
  1564. const track = rtpSender.track;
  1565. const kind = track.kind;
  1566. const parameters = this._getParametersForRtpSender(kind, {
  1567. ssrc,
  1568. rtxSsrc
  1569. });
  1570. logger.debug(
  1571. 'calling rtpSender.send(), parameters:', parameters);
  1572. // Start sending media.
  1573. try {
  1574. rtpSender.send(parameters);
  1575. // Update sending field.
  1576. info.sending = true;
  1577. } catch (error) {
  1578. logger.error(`rtpSender.send() failed:${error.message}`);
  1579. logger.error(error);
  1580. }
  1581. }
  1582. }
  1583. /**
  1584. * Creates the RTCDtlsTransport.
  1585. * @private
  1586. */
  1587. _setDtlsTransport(iceTransport) {
  1588. const dtlsTransport = new RTCDtlsTransport(iceTransport);
  1589. // NOTE: Not yet implemented by Edge.
  1590. dtlsTransport.onstatechange = () => {
  1591. logger.debug(
  1592. 'dtlsTransport "statechange" event, '
  1593. + `state:${dtlsTransport.state}`);
  1594. this._emitConnectionStateChange();
  1595. };
  1596. // NOTE: Not standard, but implemented by Edge.
  1597. dtlsTransport.ondtlsstatechange = () => {
  1598. logger.debug(
  1599. 'dtlsTransport "dtlsstatechange" event, '
  1600. + `state:${dtlsTransport.state}`);
  1601. this._emitConnectionStateChange();
  1602. };
  1603. dtlsTransport.onerror = ev => {
  1604. let message;
  1605. if (ev.message) {
  1606. message = ev.message;
  1607. } else if (ev.error) {
  1608. message = ev.error.message;
  1609. }
  1610. logger.error(`dtlsTransport "error" event, message:${message}`);
  1611. // TODO: Edge does not set state to 'failed' on error. We may
  1612. // hack it.
  1613. this._emitConnectionStateChange();
  1614. };
  1615. this._dtlsTransport = dtlsTransport;
  1616. }
  1617. /**
  1618. * Creates the RTCIceGatherer.
  1619. * @private
  1620. */
  1621. _setIceGatherer(pcConfig) {
  1622. const iceGatherOptions = {
  1623. gatherPolicy: pcConfig.iceTransportPolicy || 'all',
  1624. iceServers: pcConfig.iceServers
  1625. };
  1626. const iceGatherer = new RTCIceGatherer(iceGatherOptions);
  1627. // NOTE: Not yet implemented by Edge.
  1628. iceGatherer.onstatechange = () => {
  1629. logger.debug(
  1630. `iceGatherer "statechange" event, state:${iceGatherer.state}`);
  1631. this._updateAndEmitIceGatheringStateChange(iceGatherer.state);
  1632. };
  1633. iceGatherer.onlocalcandidate = ev => {
  1634. let candidate = ev.candidate;
  1635. // NOTE: Not yet implemented by Edge.
  1636. const complete = ev.complete;
  1637. logger.debug(
  1638. 'iceGatherer "localcandidate" event, candidate:', candidate);
  1639. // NOTE: Instead of null candidate or complete:true, current Edge
  1640. // signals end of gathering with an empty candidate object.
  1641. if (complete
  1642. || !candidate
  1643. || Object.keys(candidate).length === 0) {
  1644. candidate = null;
  1645. this._updateAndEmitIceGatheringStateChange(
  1646. RTCIceGatheringState.complete);
  1647. this._resolveLocalIceGatheringPromise();
  1648. this._emitIceCandidate(null);
  1649. } else {
  1650. this._emitIceCandidate(candidate);
  1651. }
  1652. };
  1653. iceGatherer.onerror = ev => {
  1654. const errorCode = ev.errorCode;
  1655. const errorText = ev.errorText;
  1656. logger.error(
  1657. `iceGatherer "error" event, errorCode:${errorCode}, `
  1658. + `errorText:${errorText}`);
  1659. };
  1660. // NOTE: Not yet implemented by Edge, which starts gathering
  1661. // automatically.
  1662. try {
  1663. iceGatherer.gather();
  1664. } catch (error) {
  1665. logger.warn(`iceGatherer.gather() failed:${error}`);
  1666. }
  1667. this._iceGatherer = iceGatherer;
  1668. }
  1669. /**
  1670. * Creates the RTCIceTransport.
  1671. * @private
  1672. */
  1673. _setIceTransport(iceGatherer) {
  1674. const iceTransport = new RTCIceTransport(iceGatherer);
  1675. // NOTE: Not yet implemented by Edge.
  1676. iceTransport.onstatechange = () => {
  1677. logger.debug(
  1678. 'iceTransport "statechange" event, '
  1679. + `state:${iceTransport.state}`);
  1680. this._emitIceConnectionStateChange();
  1681. };
  1682. // NOTE: Not standard, but implemented by Edge.
  1683. iceTransport.onicestatechange = () => {
  1684. logger.debug(
  1685. 'iceTransport "icestatechange" event, '
  1686. + `state:${iceTransport.state}`);
  1687. if (iceTransport.state === 'completed') {
  1688. logger.debug(
  1689. 'nominated candidate pair:',
  1690. iceTransport.getNominatedCandidatePair());
  1691. }
  1692. this._emitIceConnectionStateChange();
  1693. };
  1694. iceTransport.oncandidatepairchange = ev => {
  1695. logger.debug(
  1696. 'iceTransport "candidatepairchange" event, '
  1697. + `pair:${ev.pair}`);
  1698. };
  1699. this._iceTransport = iceTransport;
  1700. }
  1701. /**
  1702. * Promise based implementation for setLocalDescription().
  1703. * @returns {Promise}
  1704. * @private
  1705. */
  1706. _setLocalDescription(desc) {
  1707. if (this._closed) {
  1708. return Promise.reject(
  1709. new InvalidStateError('RTCPeerConnection closed'));
  1710. }
  1711. let localDescription;
  1712. try {
  1713. localDescription = new RTCSessionDescription(desc);
  1714. } catch (error) {
  1715. return Promise.reject(new TypeError(
  1716. `invalid RTCSessionDescriptionInit: ${error}`));
  1717. }
  1718. switch (desc.type) {
  1719. case 'offer': {
  1720. if (this.signalingState !== RTCSignalingState.stable) {
  1721. return Promise.reject(new InvalidStateError(
  1722. `invalid signalingState "${this.signalingState}"`));
  1723. }
  1724. return Promise.resolve()
  1725. .then(() => {
  1726. const sdpObject = localDescription.sdpObject;
  1727. // Update local values? Needed?
  1728. this._localCapabilities
  1729. = utils.extractCapabilities(sdpObject);
  1730. this._localDescription = localDescription;
  1731. // Update signaling state.
  1732. this._updateAndEmitSignalingStateChange(
  1733. RTCSignalingState.haveLocalOffer);
  1734. })
  1735. .catch(error => {
  1736. logger.error(
  1737. `setLocalDescription() failed: ${error.message}`);
  1738. logger.error(error);
  1739. throw error;
  1740. });
  1741. }
  1742. case 'answer': {
  1743. if (this.signalingState !== RTCSignalingState.haveRemoteOffer) {
  1744. return Promise.reject(new InvalidStateError(
  1745. `invalid signalingState "${this.signalingState}"`));
  1746. }
  1747. const isLocalInitialAnswer = Boolean(!this._localDescription);
  1748. return Promise.resolve()
  1749. .then(() => {
  1750. // Different handling for initial answer and re-answer.
  1751. if (isLocalInitialAnswer) {
  1752. return this._handleLocalInitialAnswer(localDescription);
  1753. } else { // eslint-disable-line no-else-return
  1754. return this._handleLocalReAnswer(localDescription);
  1755. }
  1756. })
  1757. .then(() => {
  1758. logger.debug('setLocalDescription() succeed');
  1759. // Update local description.
  1760. this._localDescription = localDescription;
  1761. // Update signaling state.
  1762. this._updateAndEmitSignalingStateChange(
  1763. RTCSignalingState.stable);
  1764. // If initial answer, emit buffered ICE candidates.
  1765. if (isLocalInitialAnswer) {
  1766. this._emitBufferedIceCandidates();
  1767. }
  1768. // Send our RTP.
  1769. this._sendMedia();
  1770. // Receive remote RTP.
  1771. this._receiveMedia();
  1772. })
  1773. .catch(error => {
  1774. logger.error(
  1775. `setLocalDescription() failed: ${error.message}`);
  1776. logger.error(error);
  1777. throw error;
  1778. });
  1779. }
  1780. default:
  1781. return Promise.reject(new TypeError(
  1782. `unsupported description.type "${desc.type}"`));
  1783. }
  1784. }
  1785. /**
  1786. * Promise based implementation for setRemoteDescription().
  1787. * @returns {Promise}
  1788. * @private
  1789. */
  1790. _setRemoteDescription(desc) {
  1791. if (this._closed) {
  1792. return Promise.reject(
  1793. new InvalidStateError('RTCPeerConnection closed'));
  1794. }
  1795. let remoteDescription;
  1796. try {
  1797. remoteDescription = new RTCSessionDescription(desc);
  1798. } catch (error) {
  1799. return Promise.reject(new TypeError(
  1800. `invalid RTCSessionDescriptionInit: ${error}`));
  1801. }
  1802. switch (desc.type) {
  1803. case 'offer': {
  1804. if (this.signalingState !== RTCSignalingState.stable) {
  1805. return Promise.reject(new InvalidStateError(
  1806. `invalid signalingState "${this.signalingState}"`));
  1807. }
  1808. const isRemoteInitialOffer = Boolean(!this._remoteDescription);
  1809. return Promise.resolve()
  1810. .then(() => {
  1811. // Different handling for initial answer and re-answer.
  1812. if (isRemoteInitialOffer) {
  1813. return this._handleRemoteInitialOffer(
  1814. remoteDescription);
  1815. } else { // eslint-disable-line no-else-return
  1816. return this._handleRemoteReOffer(remoteDescription);
  1817. }
  1818. })
  1819. .then(() => {
  1820. logger.debug('setRemoteDescription() succeed');
  1821. this._remoteDescription = remoteDescription;
  1822. this._updateAndEmitSignalingStateChange(
  1823. RTCSignalingState.haveRemoteOffer);
  1824. })
  1825. .catch(error => {
  1826. logger.error(`setRemoteDescription() failed: ${error}`);
  1827. throw error;
  1828. });
  1829. }
  1830. case 'answer': {
  1831. if (this.signalingState !== RTCSignalingState.haveLocalOffer) {
  1832. return Promise.reject(new InvalidStateError(
  1833. `invalid signalingState "${this.signalingState}"`));
  1834. }
  1835. return Promise.resolve()
  1836. .then(() => {
  1837. // Update remote description.
  1838. this._remoteDescription = remoteDescription;
  1839. // Update signaling state.
  1840. this._updateAndEmitSignalingStateChange(
  1841. RTCSignalingState.stable);
  1842. })
  1843. .catch(error => {
  1844. logger.error(`setRemoteDescription() failed: ${error}`);
  1845. throw error;
  1846. });
  1847. }
  1848. default:
  1849. return Promise.reject(new TypeError(
  1850. `unsupported description.type "${desc.type}"`));
  1851. }
  1852. }
  1853. /**
  1854. * Start ICE and DTLS connection procedures.
  1855. * @param {RTCSessionDescription} desc - Remote description.
  1856. */
  1857. _startIceAndDtls(desc) {
  1858. const sdpObject = desc.sdpObject;
  1859. const remoteIceParameters
  1860. = utils.extractIceParameters(sdpObject);
  1861. const remoteIceCandidates
  1862. = utils.extractIceCandidates(sdpObject);
  1863. const remoteDtlsParameters
  1864. = utils.extractDtlsParameters(sdpObject);
  1865. // Start the RTCIceTransport.
  1866. switch (desc.type) {
  1867. case 'offer':
  1868. this._iceTransport.start(
  1869. this._iceGatherer, remoteIceParameters, 'controlled');
  1870. break;
  1871. case 'answer':
  1872. this._iceTransport.start(
  1873. this._iceGatherer, remoteIceParameters, 'controlling');
  1874. break;
  1875. }
  1876. // Add remote ICE candidates.
  1877. // NOTE: Remove candidates that Edge doesn't like.
  1878. for (const candidate of remoteIceCandidates) {
  1879. if (candidate.port === 0 || candidate.port === 9) {
  1880. continue; // eslint-disable-line no-continue
  1881. }
  1882. this._iceTransport.addRemoteCandidate(candidate);
  1883. }
  1884. // Also signal a 'complete' candidate as per spec.
  1885. // NOTE: It should be {complete: true} but Edge prefers {}.
  1886. // NOTE: We know that addCandidate() is never used so we need to signal
  1887. // end of candidates (otherwise the RTCIceTransport never enters the
  1888. // 'completed' state).
  1889. this._iceTransport.addRemoteCandidate({});
  1890. // Set desired remote DTLS role (as we receive the offer).
  1891. switch (desc.type) {
  1892. case 'offer':
  1893. remoteDtlsParameters.role = 'server';
  1894. break;
  1895. case 'answer':
  1896. remoteDtlsParameters.role = 'client';
  1897. break;
  1898. }
  1899. // Start RTCDtlsTransport.
  1900. this._dtlsTransport.start(remoteDtlsParameters);
  1901. }
  1902. /**
  1903. * May update iceGatheringState and emit 'icegatheringstatechange' event.
  1904. * @private
  1905. */
  1906. _updateAndEmitIceGatheringStateChange(state) {
  1907. if (this._closed || state === this.iceGatheringState) {
  1908. return;
  1909. }
  1910. this._iceGatheringState = state;
  1911. logger.debug(
  1912. 'emitting "icegatheringstatechange", iceGatheringState:',
  1913. this.iceGatheringState);
  1914. const event = new yaeti.Event('icegatheringstatechange');
  1915. this.dispatchEvent(event);
  1916. }
  1917. /**
  1918. * May update signalingState and emit 'signalingstatechange' event.
  1919. * @private
  1920. */
  1921. _updateAndEmitSignalingStateChange(state) {
  1922. if (state === this.signalingState) {
  1923. return;
  1924. }
  1925. this._signalingState = state;
  1926. logger.debug(
  1927. 'emitting "signalingstatechange", signalingState:',
  1928. this.signalingState);
  1929. const event = new yaeti.Event('signalingstatechange');
  1930. this.dispatchEvent(event);
  1931. }
  1932. }