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

SDPUtil.js 21KB

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