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

SDPUtil.js 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. import { getLogger } from '@jitsi/logger';
  2. const logger = getLogger(__filename);
  3. import { CodecMimeType } from '../../service/RTC/CodecMimeType';
  4. import { MediaDirection } from '../../service/RTC/MediaDirection';
  5. import browser from '../browser';
  6. import RandomUtil from '../util/RandomUtil';
  7. const SDPUtil = {
  8. filterSpecialChars(text) {
  9. // XXX Neither one of the falsy values (e.g. null, undefined, false,
  10. // "", etc.) "contain" special chars.
  11. // eslint-disable-next-line no-useless-escape
  12. return text ? text.replace(/[\\\/\{,\}\+]/g, '') : text;
  13. },
  14. iceparams(mediadesc, sessiondesc) {
  15. let data = null;
  16. let pwd, ufrag;
  17. if ((ufrag = SDPUtil.findLine(mediadesc, 'a=ice-ufrag:', sessiondesc))
  18. && (pwd
  19. = SDPUtil.findLine(
  20. mediadesc,
  21. 'a=ice-pwd:',
  22. sessiondesc))) {
  23. data = {
  24. ufrag: SDPUtil.parseICEUfrag(ufrag),
  25. pwd: SDPUtil.parseICEPwd(pwd)
  26. };
  27. }
  28. return data;
  29. },
  30. parseICEUfrag(line) {
  31. return line.substring(12);
  32. },
  33. buildICEUfrag(frag) {
  34. return `a=ice-ufrag:${frag}`;
  35. },
  36. parseICEPwd(line) {
  37. return line.substring(10);
  38. },
  39. buildICEPwd(pwd) {
  40. return `a=ice-pwd:${pwd}`;
  41. },
  42. parseMID(line) {
  43. return line.substring(6);
  44. },
  45. /**
  46. * Finds the MSID attribute in the given array of SSRC attribute lines and returns the value.
  47. *
  48. * @param {string[]} ssrcLines - an array of lines similar to 'a:213123 msid:stream-id track-id'.
  49. * @returns {undefined|string}
  50. */
  51. parseMSIDAttribute(ssrcLines) {
  52. const msidLine = ssrcLines.find(line => line.indexOf(' msid:') > 0);
  53. if (!msidLine) {
  54. return undefined;
  55. }
  56. const v = msidLine.substring(msidLine.indexOf(' msid:') + 6 /* the length of ' msid:' */);
  57. return SDPUtil.filterSpecialChars(v);
  58. },
  59. parseMLine(line) {
  60. const data = {};
  61. const parts = line.substring(2).split(' ');
  62. data.media = parts.shift();
  63. data.port = parts.shift();
  64. data.proto = parts.shift();
  65. if (parts[parts.length - 1] === '') { // trailing whitespace
  66. parts.pop();
  67. }
  68. data.fmt = parts;
  69. return data;
  70. },
  71. buildMLine(mline) {
  72. return (
  73. `m=${mline.media} ${mline.port} ${mline.proto} ${
  74. mline.fmt.join(' ')}`);
  75. },
  76. parseRTPMap(line) {
  77. const data = {};
  78. let parts = line.substring(9).split(' ');
  79. data.id = parts.shift();
  80. parts = parts[0].split('/');
  81. data.name = parts.shift();
  82. data.clockrate = parts.shift();
  83. data.channels = parts.length ? parts.shift() : '1';
  84. return data;
  85. },
  86. /**
  87. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  88. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  89. * @returns [SCTP port number, protocol, streams]
  90. */
  91. parseSCTPMap(line) {
  92. const parts = line.substring(10).split(' ');
  93. const sctpPort = parts[0];
  94. const protocol = parts[1];
  95. // Stream count is optional
  96. const streamCount = parts.length > 2 ? parts[2] : null;
  97. return [ sctpPort, protocol, streamCount ];// SCTP port
  98. },
  99. parseSCTPPort(line) {
  100. return line.substring(12);
  101. },
  102. buildRTPMap(el) {
  103. let line
  104. = `a=rtpmap:${el.getAttribute('id')} ${el.getAttribute('name')}/${
  105. el.getAttribute('clockrate')}`;
  106. if (el.getAttribute('channels')
  107. && el.getAttribute('channels') !== '1') {
  108. line += `/${el.getAttribute('channels')}`;
  109. }
  110. return line;
  111. },
  112. parseCrypto(line) {
  113. const data = {};
  114. const parts = line.substring(9).split(' ');
  115. data.tag = parts.shift();
  116. data['crypto-suite'] = parts.shift();
  117. data['key-params'] = parts.shift();
  118. if (parts.length) {
  119. data['session-params'] = parts.join(' ');
  120. }
  121. return data;
  122. },
  123. parseFingerprint(line) { // RFC 4572
  124. const data = {};
  125. const parts = line.substring(14).split(' ');
  126. data.hash = parts.shift();
  127. data.fingerprint = parts.shift();
  128. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  129. return data;
  130. },
  131. parseFmtp(line) {
  132. const data = [];
  133. let parts = line.split(' ');
  134. parts.shift();
  135. parts = parts.join(' ').split(';');
  136. for (let i = 0; i < parts.length; i++) {
  137. let key = parts[i].split('=')[0];
  138. while (key.length && key[0] === ' ') {
  139. key = key.substring(1);
  140. }
  141. const value = parts[i].split('=')[1];
  142. if (key && value) {
  143. data.push({ name: key,
  144. value });
  145. } else if (key) {
  146. // rfc 4733 (DTMF) style stuff
  147. data.push({ name: '',
  148. value: key });
  149. }
  150. }
  151. return data;
  152. },
  153. parseICECandidate(line) {
  154. const candidate = {};
  155. const elems = line.split(' ');
  156. candidate.foundation = elems[0].substring(12);
  157. candidate.component = elems[1];
  158. candidate.protocol = elems[2].toLowerCase();
  159. candidate.priority = elems[3];
  160. candidate.ip = elems[4];
  161. candidate.port = elems[5];
  162. // elems[6] => "typ"
  163. candidate.type = elems[7];
  164. candidate.generation = 0; // default value, may be overwritten below
  165. for (let i = 8; i < elems.length; i += 2) {
  166. switch (elems[i]) {
  167. case 'raddr':
  168. candidate['rel-addr'] = elems[i + 1];
  169. break;
  170. case 'rport':
  171. candidate['rel-port'] = elems[i + 1];
  172. break;
  173. case 'generation':
  174. candidate.generation = elems[i + 1];
  175. break;
  176. case 'tcptype':
  177. candidate.tcptype = elems[i + 1];
  178. break;
  179. default: // TODO
  180. logger.debug(
  181. `parseICECandidate not translating "${
  182. elems[i]}" = "${elems[i + 1]}"`);
  183. }
  184. }
  185. candidate.network = '1';
  186. // not applicable to SDP -- FIXME: should be unique, not just random
  187. // eslint-disable-next-line newline-per-chained-call
  188. candidate.id = Math.random().toString(36).substr(2, 10);
  189. return candidate;
  190. },
  191. buildICECandidate(cand) {
  192. let line = [
  193. `a=candidate:${cand.foundation}`,
  194. cand.component,
  195. cand.protocol,
  196. cand.priority,
  197. cand.ip,
  198. cand.port,
  199. 'typ',
  200. cand.type
  201. ].join(' ');
  202. line += ' ';
  203. switch (cand.type) {
  204. case 'srflx':
  205. case 'prflx':
  206. case 'relay':
  207. if (cand.hasOwnAttribute('rel-addr')
  208. && cand.hasOwnAttribute('rel-port')) {
  209. line += 'raddr';
  210. line += ' ';
  211. line += cand['rel-addr'];
  212. line += ' ';
  213. line += 'rport';
  214. line += ' ';
  215. line += cand['rel-port'];
  216. line += ' ';
  217. }
  218. break;
  219. }
  220. if (cand.hasOwnAttribute('tcptype')) {
  221. line += 'tcptype';
  222. line += ' ';
  223. line += cand.tcptype;
  224. line += ' ';
  225. }
  226. line += 'generation';
  227. line += ' ';
  228. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  229. return line;
  230. },
  231. parseSSRC(desc) {
  232. // proprietary mapping of a=ssrc lines
  233. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher
  234. // on google docs and parse according to that
  235. const data = new Map();
  236. const lines = desc.split('\r\n');
  237. for (let i = 0; i < lines.length; i++) {
  238. if (lines[i].substring(0, 7) === 'a=ssrc:') {
  239. // FIXME: Use regex to smartly find the ssrc.
  240. const ssrc = lines[i].split('a=ssrc:')[1].split(' ')[0];
  241. if (!data.get(ssrc)) {
  242. data.set(ssrc, []);
  243. }
  244. data.get(ssrc).push(lines[i]);
  245. }
  246. }
  247. return data;
  248. },
  249. /**
  250. * Parses the 'a=ssrc-group' line.
  251. *
  252. * @param {string} line - The media line to parse.
  253. * @returns {object}
  254. */
  255. parseSSRCGroupLine(line) {
  256. const parts = line.substr(13).split(' ');
  257. return {
  258. semantics: parts.shift(),
  259. ssrcs: parts
  260. };
  261. },
  262. /**
  263. * Gets the source name out of the name attribute "a=ssrc:254321 name:name1".
  264. *
  265. * @param {string[]} ssrcLines
  266. * @returns {string | undefined}
  267. */
  268. parseSourceNameLine(ssrcLines) {
  269. const sourceNameLine = ssrcLines.find(ssrcSdpLine => ssrcSdpLine.indexOf(' name:') > 0);
  270. // Everything past the "name:" part
  271. return sourceNameLine?.substring(sourceNameLine.indexOf(' name:') + 6);
  272. },
  273. /**
  274. * Parse the "videoType" attribute encoded in a set of SSRC attributes (e.g.
  275. * "a=ssrc:1234 videoType:desktop")
  276. *
  277. * @param {string[]} ssrcLines
  278. * @returns {string | undefined}
  279. */
  280. parseVideoTypeLine(ssrcLines) {
  281. const s = ' videoType:';
  282. const videoTypeLine = ssrcLines.find(ssrcSdpLine => ssrcSdpLine.indexOf(s) > 0);
  283. return videoTypeLine?.substring(videoTypeLine.indexOf(s) + s.length);
  284. },
  285. parseRTCPFB(line) {
  286. const parts = line.substr(10).split(' ');
  287. const data = {};
  288. data.pt = parts.shift();
  289. data.type = parts.shift();
  290. data.params = parts;
  291. return data;
  292. },
  293. parseExtmap(line) {
  294. const parts = line.substr(9).split(' ');
  295. const data = {};
  296. data.value = parts.shift();
  297. if (data.value.indexOf('/') === -1) {
  298. data.direction = 'both';
  299. } else {
  300. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  301. data.value = data.value.substr(0, data.value.indexOf('/'));
  302. }
  303. data.uri = parts.shift();
  304. data.params = parts;
  305. return data;
  306. },
  307. findLine(haystack, needle, sessionpart) {
  308. let lines = haystack.split('\r\n');
  309. for (let i = 0; i < lines.length; i++) {
  310. if (lines[i].substring(0, needle.length) === needle) {
  311. return lines[i];
  312. }
  313. }
  314. if (!sessionpart) {
  315. return false;
  316. }
  317. // search session part
  318. lines = sessionpart.split('\r\n');
  319. for (let j = 0; j < lines.length; j++) {
  320. if (lines[j].substring(0, needle.length) === needle) {
  321. return lines[j];
  322. }
  323. }
  324. return false;
  325. },
  326. findLines(haystack, needle, sessionpart) {
  327. let lines = haystack.split('\r\n');
  328. const needles = [];
  329. for (let i = 0; i < lines.length; i++) {
  330. if (lines[i].substring(0, needle.length) === needle) {
  331. needles.push(lines[i]);
  332. }
  333. }
  334. if (needles.length || !sessionpart) {
  335. return needles;
  336. }
  337. // search session part
  338. lines = sessionpart.split('\r\n');
  339. for (let j = 0; j < lines.length; j++) {
  340. if (lines[j].substring(0, needle.length) === needle) {
  341. needles.push(lines[j]);
  342. }
  343. }
  344. return needles;
  345. },
  346. candidateToJingle(line) {
  347. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host
  348. // generation 0
  349. // <candidate component=... foundation=... generation=... id=...
  350. // ip=... network=... port=... priority=... protocol=... type=.../>
  351. if (line.indexOf('candidate:') === 0) {
  352. // eslint-disable-next-line no-param-reassign
  353. line = `a=${line}`;
  354. } else if (line.substring(0, 12) !== 'a=candidate:') {
  355. logger.warn(
  356. 'parseCandidate called with a line that is not a candidate'
  357. + ' line');
  358. logger.warn(line);
  359. return null;
  360. }
  361. if (line.substring(line.length - 2) === '\r\n') { // chomp it
  362. // eslint-disable-next-line no-param-reassign
  363. line = line.substring(0, line.length - 2);
  364. }
  365. const candidate = {};
  366. const elems = line.split(' ');
  367. if (elems[6] !== 'typ') {
  368. logger.warn('did not find typ in the right place');
  369. logger.warn(line);
  370. return null;
  371. }
  372. candidate.foundation = elems[0].substring(12);
  373. candidate.component = elems[1];
  374. candidate.protocol = elems[2].toLowerCase();
  375. candidate.priority = elems[3];
  376. candidate.ip = elems[4];
  377. candidate.port = elems[5];
  378. // elems[6] => "typ"
  379. candidate.type = elems[7];
  380. candidate.generation = '0'; // default, may be overwritten below
  381. for (let i = 8; i < elems.length; i += 2) {
  382. switch (elems[i]) {
  383. case 'raddr':
  384. candidate['rel-addr'] = elems[i + 1];
  385. break;
  386. case 'rport':
  387. candidate['rel-port'] = elems[i + 1];
  388. break;
  389. case 'generation':
  390. candidate.generation = elems[i + 1];
  391. break;
  392. case 'tcptype':
  393. candidate.tcptype = elems[i + 1];
  394. break;
  395. default: // TODO
  396. logger.debug(`not translating "${elems[i]}" = "${elems[i + 1]}"`);
  397. }
  398. }
  399. candidate.network = '1';
  400. // not applicable to SDP -- FIXME: should be unique, not just random
  401. // eslint-disable-next-line newline-per-chained-call
  402. candidate.id = Math.random().toString(36).substr(2, 10);
  403. return candidate;
  404. },
  405. candidateFromJingle(cand) {
  406. let line = 'a=candidate:';
  407. line += cand.getAttribute('foundation');
  408. line += ' ';
  409. line += cand.getAttribute('component');
  410. line += ' ';
  411. let protocol = cand.getAttribute('protocol');
  412. // use tcp candidates for FF
  413. if (browser.isFirefox() && protocol.toLowerCase() === 'ssltcp') {
  414. protocol = 'tcp';
  415. }
  416. line += protocol; // .toUpperCase(); // chrome M23 doesn't like this
  417. line += ' ';
  418. line += cand.getAttribute('priority');
  419. line += ' ';
  420. line += cand.getAttribute('ip');
  421. line += ' ';
  422. line += cand.getAttribute('port');
  423. line += ' ';
  424. line += 'typ';
  425. line += ` ${cand.getAttribute('type')}`;
  426. line += ' ';
  427. switch (cand.getAttribute('type')) {
  428. case 'srflx':
  429. case 'prflx':
  430. case 'relay':
  431. if (cand.getAttribute('rel-addr')
  432. && cand.getAttribute('rel-port')) {
  433. line += 'raddr';
  434. line += ' ';
  435. line += cand.getAttribute('rel-addr');
  436. line += ' ';
  437. line += 'rport';
  438. line += ' ';
  439. line += cand.getAttribute('rel-port');
  440. line += ' ';
  441. }
  442. break;
  443. }
  444. if (protocol.toLowerCase() === 'tcp') {
  445. line += 'tcptype';
  446. line += ' ';
  447. line += cand.getAttribute('tcptype');
  448. line += ' ';
  449. }
  450. line += 'generation';
  451. line += ' ';
  452. line += cand.getAttribute('generation') || '0';
  453. return `${line}\r\n`;
  454. },
  455. /**
  456. * Parse the 'most' primary video ssrc from the given m line
  457. * @param {object} mLine object as parsed from transform.parse
  458. * @return {number} the primary video ssrc from the given m line
  459. */
  460. parsePrimaryVideoSsrc(videoMLine) {
  461. const numSsrcs = videoMLine.ssrcs
  462. .map(ssrcInfo => ssrcInfo.id)
  463. .filter((ssrc, index, array) => array.indexOf(ssrc) === index)
  464. .length;
  465. const numGroups
  466. = (videoMLine.ssrcGroups && videoMLine.ssrcGroups.length) || 0;
  467. if (numSsrcs > 1 && numGroups === 0) {
  468. // Ambiguous, can't figure out the primary
  469. return;
  470. }
  471. let primarySsrc = null;
  472. if (numSsrcs === 1) {
  473. primarySsrc = videoMLine.ssrcs[0].id;
  474. } else if (numSsrcs === 2) {
  475. // Can figure it out if there's an FID group
  476. const fidGroup
  477. = videoMLine.ssrcGroups.find(
  478. group => group.semantics === 'FID');
  479. if (fidGroup) {
  480. primarySsrc = fidGroup.ssrcs.split(' ')[0];
  481. }
  482. } else if (numSsrcs >= 3) {
  483. // Can figure it out if there's a sim group
  484. const simGroup
  485. = videoMLine.ssrcGroups.find(
  486. group => group.semantics === 'SIM');
  487. if (simGroup) {
  488. primarySsrc = simGroup.ssrcs.split(' ')[0];
  489. }
  490. }
  491. return primarySsrc;
  492. },
  493. /**
  494. * Generate an ssrc
  495. * @returns {number} an ssrc
  496. */
  497. generateSsrc() {
  498. return RandomUtil.randomInt(1, 0xffffffff);
  499. },
  500. /**
  501. * Get an attribute for the given ssrc with the given attributeName
  502. * from the given mline
  503. * @param {object} mLine an mLine object as parsed from transform.parse
  504. * @param {number} ssrc the ssrc for which an attribute is desired
  505. * @param {string} attributeName the name of the desired attribute
  506. * @returns {string} the value corresponding to the given ssrc
  507. * and attributeName
  508. */
  509. getSsrcAttribute(mLine, ssrc, attributeName) {
  510. for (let i = 0; i < mLine.ssrcs.length; ++i) {
  511. const ssrcLine = mLine.ssrcs[i];
  512. if (ssrcLine.id === ssrc
  513. && ssrcLine.attribute === attributeName) {
  514. return ssrcLine.value;
  515. }
  516. }
  517. },
  518. /**
  519. * Parses the ssrcs from the group sdp line and
  520. * returns them as a list of numbers
  521. * @param {object} the ssrcGroup object as parsed from
  522. * sdp-transform
  523. * @returns {list<number>} a list of the ssrcs in the group
  524. * parsed as numbers
  525. */
  526. parseGroupSsrcs(ssrcGroup) {
  527. return ssrcGroup
  528. .ssrcs
  529. .split(' ')
  530. .map(ssrcStr => parseInt(ssrcStr, 10));
  531. },
  532. /**
  533. * Get the mline of the given type from the given sdp
  534. * @param {object} sdp sdp as parsed from transform.parse
  535. * @param {string} type the type of the desired mline (e.g. "video")
  536. * @returns {object} a media object
  537. */
  538. getMedia(sdp, type) {
  539. return sdp.media.find(m => m.type === type);
  540. },
  541. /**
  542. * Extracts the ICE username fragment from an SDP string.
  543. * @param {string} sdp the SDP in raw text format
  544. */
  545. getUfrag(sdp) {
  546. const ufragLines
  547. = sdp.split('\n').filter(line => line.startsWith('a=ice-ufrag:'));
  548. if (ufragLines.length > 0) {
  549. return ufragLines[0].substr('a=ice-ufrag:'.length);
  550. }
  551. },
  552. /**
  553. * Sets the given codecName as the preferred codec by moving it to the beginning
  554. * of the payload types list (modifies the given mline in place). All instances
  555. * of the codec are moved up.
  556. * @param {object} mLine the mline object from an sdp as parsed by transform.parse.
  557. * @param {string} codecName the name of the preferred codec.
  558. * @param {boolean} sortPayloadTypes whether the payloadtypes need to be sorted for a given codec.
  559. */
  560. preferCodec(mline, codecName, sortPayloadTypes = false) {
  561. if (!mline || !codecName) {
  562. return;
  563. }
  564. const matchingPayloadTypes = mline.rtp
  565. .filter(rtp => rtp.codec && rtp.codec.toLowerCase() === codecName.toLowerCase())
  566. .map(rtp => rtp.payload);
  567. if (matchingPayloadTypes) {
  568. if (sortPayloadTypes && codecName === CodecMimeType.H264) {
  569. // Move all the H.264 codecs with packetization-mode=0 to top of the list.
  570. const payloadsWithMode0 = matchingPayloadTypes.filter(payload => {
  571. const fmtp = mline.fmtp.find(item => item.payload === payload);
  572. if (fmtp) {
  573. return fmtp.config.includes('packetization-mode=0');
  574. }
  575. return false;
  576. });
  577. for (const pt of payloadsWithMode0.reverse()) {
  578. const idx = matchingPayloadTypes.findIndex(payloadType => payloadType === pt);
  579. if (idx >= 0) {
  580. matchingPayloadTypes.splice(idx, 1);
  581. matchingPayloadTypes.unshift(pt);
  582. }
  583. }
  584. }
  585. // Call toString() on payloads to get around an issue within SDPTransform that sets
  586. // payloads as a number, instead of a string, when there is only one payload.
  587. const payloadTypes
  588. = mline.payloads
  589. .toString()
  590. .split(' ')
  591. .map(p => parseInt(p, 10));
  592. for (const pt of matchingPayloadTypes.reverse()) {
  593. const payloadIndex = payloadTypes.indexOf(pt);
  594. payloadTypes.splice(payloadIndex, 1);
  595. payloadTypes.unshift(pt);
  596. }
  597. mline.payloads = payloadTypes.join(' ');
  598. } else {
  599. logger.error(`No matching RTP payload type found for ${codecName}, failed to set preferred codecs`);
  600. }
  601. },
  602. /**
  603. * Strips the given codec from the given mline. All related RTX payload
  604. * types are also stripped. If the resulting mline would have no codecs,
  605. * it's disabled.
  606. *
  607. * @param {object} mLine the mline object from an sdp as parsed by transform.parse.
  608. * @param {string} codecName the name of the codec which will be stripped.
  609. * @param {boolean} highProfile determines if only the high profile codec needs to be stripped from the sdp for a
  610. * given codec type.
  611. */
  612. stripCodec(mLine, codecName, highProfile = false) {
  613. if (!mLine || !codecName) {
  614. return;
  615. }
  616. const highProfileCodecs = new Map();
  617. let removePts = [];
  618. for (const rtp of mLine.rtp) {
  619. if (rtp.codec && rtp.codec.toLowerCase() === codecName.toLowerCase()) {
  620. if (highProfile) {
  621. highProfileCodecs.set(rtp.payload, rtp.codec);
  622. } else {
  623. removePts.push(rtp.payload);
  624. }
  625. }
  626. }
  627. if (highProfile) {
  628. removePts = mLine.fmtp
  629. .filter(item => {
  630. const codec = highProfileCodecs.get(item.payload);
  631. if (codec) {
  632. return codec.toLowerCase() === CodecMimeType.VP9
  633. ? !item.config.includes('profile-id=0')
  634. : !item.config.includes('profile-level-id=42');
  635. }
  636. return false;
  637. })
  638. .map(item => item.payload);
  639. }
  640. if (removePts.length > 0) {
  641. // We also need to remove the payload types that are related to RTX
  642. // for the codecs we want to disable.
  643. const rtxApts = removePts.map(item => `apt=${item}`);
  644. const rtxPts = mLine.fmtp.filter(
  645. item => rtxApts.indexOf(item.config) !== -1);
  646. removePts.push(...rtxPts.map(item => item.payload));
  647. // Call toString() on payloads to get around an issue within
  648. // SDPTransform that sets payloads as a number, instead of a string,
  649. // when there is only one payload.
  650. const allPts = mLine.payloads
  651. .toString()
  652. .split(' ')
  653. .map(Number);
  654. const keepPts = allPts.filter(pt => removePts.indexOf(pt) === -1);
  655. if (keepPts.length === 0) {
  656. // There are no other codecs, disable the stream.
  657. mLine.port = 0;
  658. mLine.direction = MediaDirection.INACTIVE;
  659. mLine.payloads = '*';
  660. } else {
  661. mLine.payloads = keepPts.join(' ');
  662. }
  663. mLine.rtp = mLine.rtp.filter(
  664. item => keepPts.indexOf(item.payload) !== -1);
  665. mLine.fmtp = mLine.fmtp.filter(
  666. item => keepPts.indexOf(item.payload) !== -1);
  667. if (mLine.rtcpFb) {
  668. mLine.rtcpFb = mLine.rtcpFb.filter(
  669. item => keepPts.indexOf(item.payload) !== -1);
  670. }
  671. }
  672. }
  673. };
  674. export default SDPUtil;