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

RTCPeerConnection.js 72KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381
  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. * Pares STUN and TURN servers to only one. This works around an issue on
  1619. * edge where an error occurs if multiple are declared.
  1620. * See https://developer.microsoft.com/en-us/microsoft-edge/platform
  1621. * /issues/10163458
  1622. *
  1623. * @param {array} servers - All STUN AND TURN servers to connect to.
  1624. * @private
  1625. * @returns {array} An array with only one STUN server and one TURN server
  1626. * at the most.
  1627. */
  1628. _filterServers(servers = []) {
  1629. const filteredServers = [];
  1630. const firstStun = servers.find(server => server.url.startsWith('stun'));
  1631. if (firstStun) {
  1632. filteredServers.push(firstStun);
  1633. }
  1634. const firstTurn = servers.find(server => server.url.startsWith('turn'));
  1635. if (firstTurn) {
  1636. filteredServers.push(firstTurn);
  1637. }
  1638. return filteredServers;
  1639. }
  1640. /**
  1641. * Creates the RTCIceGatherer.
  1642. * @private
  1643. */
  1644. _setIceGatherer(pcConfig) {
  1645. const iceGatherOptions = {
  1646. gatherPolicy: pcConfig.iceTransportPolicy || 'all',
  1647. iceServers: this._filterServers(pcConfig.iceServers)
  1648. };
  1649. const iceGatherer = new RTCIceGatherer(iceGatherOptions);
  1650. // NOTE: Not yet implemented by Edge.
  1651. iceGatherer.onstatechange = () => {
  1652. logger.debug(
  1653. `iceGatherer "statechange" event, state:${iceGatherer.state}`);
  1654. this._updateAndEmitIceGatheringStateChange(iceGatherer.state);
  1655. };
  1656. iceGatherer.onlocalcandidate = ev => {
  1657. let candidate = ev.candidate;
  1658. // NOTE: Not yet implemented by Edge.
  1659. const complete = ev.complete;
  1660. logger.debug(
  1661. 'iceGatherer "localcandidate" event, candidate:', candidate);
  1662. // NOTE: Instead of null candidate or complete:true, current Edge
  1663. // signals end of gathering with an empty candidate object.
  1664. if (complete
  1665. || !candidate
  1666. || Object.keys(candidate).length === 0) {
  1667. candidate = null;
  1668. this._updateAndEmitIceGatheringStateChange(
  1669. RTCIceGatheringState.complete);
  1670. this._resolveLocalIceGatheringPromise();
  1671. this._emitIceCandidate(null);
  1672. } else {
  1673. this._emitIceCandidate(candidate);
  1674. }
  1675. };
  1676. iceGatherer.onerror = ev => {
  1677. const errorCode = ev.errorCode;
  1678. const errorText = ev.errorText;
  1679. logger.error(
  1680. `iceGatherer "error" event, errorCode:${errorCode}, `
  1681. + `errorText:${errorText}`);
  1682. };
  1683. // NOTE: Not yet implemented by Edge, which starts gathering
  1684. // automatically.
  1685. try {
  1686. iceGatherer.gather();
  1687. } catch (error) {
  1688. logger.warn(`iceGatherer.gather() failed:${error}`);
  1689. }
  1690. this._iceGatherer = iceGatherer;
  1691. }
  1692. /**
  1693. * Creates the RTCIceTransport.
  1694. * @private
  1695. */
  1696. _setIceTransport(iceGatherer) {
  1697. const iceTransport = new RTCIceTransport(iceGatherer);
  1698. // NOTE: Not yet implemented by Edge.
  1699. iceTransport.onstatechange = () => {
  1700. logger.debug(
  1701. 'iceTransport "statechange" event, '
  1702. + `state:${iceTransport.state}`);
  1703. this._emitIceConnectionStateChange();
  1704. };
  1705. // NOTE: Not standard, but implemented by Edge.
  1706. iceTransport.onicestatechange = () => {
  1707. logger.debug(
  1708. 'iceTransport "icestatechange" event, '
  1709. + `state:${iceTransport.state}`);
  1710. if (iceTransport.state === 'completed') {
  1711. logger.debug(
  1712. 'nominated candidate pair:',
  1713. iceTransport.getNominatedCandidatePair());
  1714. }
  1715. this._emitIceConnectionStateChange();
  1716. };
  1717. iceTransport.oncandidatepairchange = ev => {
  1718. logger.debug(
  1719. 'iceTransport "candidatepairchange" event, '
  1720. + `pair:${ev.pair}`);
  1721. };
  1722. this._iceTransport = iceTransport;
  1723. }
  1724. /**
  1725. * Promise based implementation for setLocalDescription().
  1726. * @returns {Promise}
  1727. * @private
  1728. */
  1729. _setLocalDescription(desc) {
  1730. if (this._closed) {
  1731. return Promise.reject(
  1732. new InvalidStateError('RTCPeerConnection closed'));
  1733. }
  1734. let localDescription;
  1735. try {
  1736. localDescription = new RTCSessionDescription(desc);
  1737. } catch (error) {
  1738. return Promise.reject(new TypeError(
  1739. `invalid RTCSessionDescriptionInit: ${error}`));
  1740. }
  1741. switch (desc.type) {
  1742. case 'offer': {
  1743. if (this.signalingState !== RTCSignalingState.stable) {
  1744. return Promise.reject(new InvalidStateError(
  1745. `invalid signalingState "${this.signalingState}"`));
  1746. }
  1747. return Promise.resolve()
  1748. .then(() => {
  1749. const sdpObject = localDescription.sdpObject;
  1750. // Update local values? Needed?
  1751. this._localCapabilities
  1752. = utils.extractCapabilities(sdpObject);
  1753. this._localDescription = localDescription;
  1754. // Update signaling state.
  1755. this._updateAndEmitSignalingStateChange(
  1756. RTCSignalingState.haveLocalOffer);
  1757. })
  1758. .catch(error => {
  1759. logger.error(
  1760. `setLocalDescription() failed: ${error.message}`);
  1761. logger.error(error);
  1762. throw error;
  1763. });
  1764. }
  1765. case 'answer': {
  1766. if (this.signalingState !== RTCSignalingState.haveRemoteOffer) {
  1767. return Promise.reject(new InvalidStateError(
  1768. `invalid signalingState "${this.signalingState}"`));
  1769. }
  1770. const isLocalInitialAnswer = Boolean(!this._localDescription);
  1771. return Promise.resolve()
  1772. .then(() => {
  1773. // Different handling for initial answer and re-answer.
  1774. if (isLocalInitialAnswer) {
  1775. return this._handleLocalInitialAnswer(localDescription);
  1776. } else { // eslint-disable-line no-else-return
  1777. return this._handleLocalReAnswer(localDescription);
  1778. }
  1779. })
  1780. .then(() => {
  1781. logger.debug('setLocalDescription() succeed');
  1782. // Update local description.
  1783. this._localDescription = localDescription;
  1784. // Update signaling state.
  1785. this._updateAndEmitSignalingStateChange(
  1786. RTCSignalingState.stable);
  1787. // If initial answer, emit buffered ICE candidates.
  1788. if (isLocalInitialAnswer) {
  1789. this._emitBufferedIceCandidates();
  1790. }
  1791. // Send our RTP.
  1792. this._sendMedia();
  1793. // Receive remote RTP.
  1794. this._receiveMedia();
  1795. })
  1796. .catch(error => {
  1797. logger.error(
  1798. `setLocalDescription() failed: ${error.message}`);
  1799. logger.error(error);
  1800. throw error;
  1801. });
  1802. }
  1803. default:
  1804. return Promise.reject(new TypeError(
  1805. `unsupported description.type "${desc.type}"`));
  1806. }
  1807. }
  1808. /**
  1809. * Promise based implementation for setRemoteDescription().
  1810. * @returns {Promise}
  1811. * @private
  1812. */
  1813. _setRemoteDescription(desc) {
  1814. if (this._closed) {
  1815. return Promise.reject(
  1816. new InvalidStateError('RTCPeerConnection closed'));
  1817. }
  1818. let remoteDescription;
  1819. try {
  1820. remoteDescription = new RTCSessionDescription(desc);
  1821. } catch (error) {
  1822. return Promise.reject(new TypeError(
  1823. `invalid RTCSessionDescriptionInit: ${error}`));
  1824. }
  1825. switch (desc.type) {
  1826. case 'offer': {
  1827. if (this.signalingState !== RTCSignalingState.stable) {
  1828. return Promise.reject(new InvalidStateError(
  1829. `invalid signalingState "${this.signalingState}"`));
  1830. }
  1831. const isRemoteInitialOffer = Boolean(!this._remoteDescription);
  1832. return Promise.resolve()
  1833. .then(() => {
  1834. // Different handling for initial answer and re-answer.
  1835. if (isRemoteInitialOffer) {
  1836. return this._handleRemoteInitialOffer(
  1837. remoteDescription);
  1838. } else { // eslint-disable-line no-else-return
  1839. return this._handleRemoteReOffer(remoteDescription);
  1840. }
  1841. })
  1842. .then(() => {
  1843. logger.debug('setRemoteDescription() succeed');
  1844. this._remoteDescription = remoteDescription;
  1845. this._updateAndEmitSignalingStateChange(
  1846. RTCSignalingState.haveRemoteOffer);
  1847. })
  1848. .catch(error => {
  1849. logger.error(`setRemoteDescription() failed: ${error}`);
  1850. throw error;
  1851. });
  1852. }
  1853. case 'answer': {
  1854. if (this.signalingState !== RTCSignalingState.haveLocalOffer) {
  1855. return Promise.reject(new InvalidStateError(
  1856. `invalid signalingState "${this.signalingState}"`));
  1857. }
  1858. return Promise.resolve()
  1859. .then(() => {
  1860. // Update remote description.
  1861. this._remoteDescription = remoteDescription;
  1862. // Update signaling state.
  1863. this._updateAndEmitSignalingStateChange(
  1864. RTCSignalingState.stable);
  1865. })
  1866. .catch(error => {
  1867. logger.error(`setRemoteDescription() failed: ${error}`);
  1868. throw error;
  1869. });
  1870. }
  1871. default:
  1872. return Promise.reject(new TypeError(
  1873. `unsupported description.type "${desc.type}"`));
  1874. }
  1875. }
  1876. /**
  1877. * Start ICE and DTLS connection procedures.
  1878. * @param {RTCSessionDescription} desc - Remote description.
  1879. */
  1880. _startIceAndDtls(desc) {
  1881. const sdpObject = desc.sdpObject;
  1882. const remoteIceParameters
  1883. = utils.extractIceParameters(sdpObject);
  1884. const remoteIceCandidates
  1885. = utils.extractIceCandidates(sdpObject);
  1886. const remoteDtlsParameters
  1887. = utils.extractDtlsParameters(sdpObject);
  1888. // Start the RTCIceTransport.
  1889. switch (desc.type) {
  1890. case 'offer':
  1891. this._iceTransport.start(
  1892. this._iceGatherer, remoteIceParameters, 'controlled');
  1893. break;
  1894. case 'answer':
  1895. this._iceTransport.start(
  1896. this._iceGatherer, remoteIceParameters, 'controlling');
  1897. break;
  1898. }
  1899. // Add remote ICE candidates.
  1900. // NOTE: Remove candidates that Edge doesn't like.
  1901. for (const candidate of remoteIceCandidates) {
  1902. if (candidate.port === 0 || candidate.port === 9) {
  1903. continue; // eslint-disable-line no-continue
  1904. }
  1905. this._iceTransport.addRemoteCandidate(candidate);
  1906. }
  1907. // Also signal a 'complete' candidate as per spec.
  1908. // NOTE: It should be {complete: true} but Edge prefers {}.
  1909. // NOTE: We know that addCandidate() is never used so we need to signal
  1910. // end of candidates (otherwise the RTCIceTransport never enters the
  1911. // 'completed' state).
  1912. this._iceTransport.addRemoteCandidate({});
  1913. // Set desired remote DTLS role (as we receive the offer).
  1914. switch (desc.type) {
  1915. case 'offer':
  1916. remoteDtlsParameters.role = 'server';
  1917. break;
  1918. case 'answer':
  1919. remoteDtlsParameters.role = 'client';
  1920. break;
  1921. }
  1922. // Start RTCDtlsTransport.
  1923. this._dtlsTransport.start(remoteDtlsParameters);
  1924. }
  1925. /**
  1926. * May update iceGatheringState and emit 'icegatheringstatechange' event.
  1927. * @private
  1928. */
  1929. _updateAndEmitIceGatheringStateChange(state) {
  1930. if (this._closed || state === this.iceGatheringState) {
  1931. return;
  1932. }
  1933. this._iceGatheringState = state;
  1934. logger.debug(
  1935. 'emitting "icegatheringstatechange", iceGatheringState:',
  1936. this.iceGatheringState);
  1937. const event = new yaeti.Event('icegatheringstatechange');
  1938. this.dispatchEvent(event);
  1939. }
  1940. /**
  1941. * May update signalingState and emit 'signalingstatechange' event.
  1942. * @private
  1943. */
  1944. _updateAndEmitSignalingStateChange(state) {
  1945. if (state === this.signalingState) {
  1946. return;
  1947. }
  1948. this._signalingState = state;
  1949. logger.debug(
  1950. 'emitting "signalingstatechange", signalingState:',
  1951. this.signalingState);
  1952. const event = new yaeti.Event('signalingstatechange');
  1953. this.dispatchEvent(event);
  1954. }
  1955. }