You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SDPUtil.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. import {getLogger} from 'jitsi-meet-logger';
  2. const logger = getLogger(__filename);
  3. import RandomUtil from '../util/RandomUtil';
  4. const RTCBrowserType = require('../RTC/RTCBrowserType');
  5. const SDPUtil = {
  6. filter_special_chars(text) {
  7. // XXX Neither one of the falsy values (e.g. null, undefined, false,
  8. // "", etc.) "contain" special chars.
  9. return text ? text.replace(/[\\\/\{,\}\+]/g, '') : text;
  10. },
  11. iceparams(mediadesc, sessiondesc) {
  12. let data = null;
  13. let pwd, ufrag;
  14. if ((ufrag = SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc))
  15. && (pwd = SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))) {
  16. data = {
  17. ufrag: SDPUtil.parse_iceufrag(ufrag),
  18. pwd: SDPUtil.parse_icepwd(pwd)
  19. };
  20. }
  21. return data;
  22. },
  23. parse_iceufrag(line) {
  24. return line.substring(12);
  25. },
  26. build_iceufrag(frag) {
  27. return `a=ice-ufrag:${frag}`;
  28. },
  29. parse_icepwd(line) {
  30. return line.substring(10);
  31. },
  32. build_icepwd(pwd) {
  33. return `a=ice-pwd:${pwd}`;
  34. },
  35. parse_mid(line) {
  36. return line.substring(6);
  37. },
  38. parse_mline(line) {
  39. const data = {};
  40. const parts = line.substring(2).split(' ');
  41. data.media = parts.shift();
  42. data.port = parts.shift();
  43. data.proto = parts.shift();
  44. if (parts[parts.length - 1] === '') { // trailing whitespace
  45. parts.pop();
  46. }
  47. data.fmt = parts;
  48. return data;
  49. },
  50. build_mline(mline) {
  51. return `m=${mline.media} ${mline.port} ${mline.proto} ${mline.fmt.join(' ')}`;
  52. },
  53. parse_rtpmap(line) {
  54. const data = {};
  55. let parts = line.substring(9).split(' ');
  56. data.id = parts.shift();
  57. parts = parts[0].split('/');
  58. data.name = parts.shift();
  59. data.clockrate = parts.shift();
  60. data.channels = parts.length ? parts.shift() : '1';
  61. return data;
  62. },
  63. /**
  64. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  65. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  66. * @returns [SCTP port number, protocol, streams]
  67. */
  68. parse_sctpmap(line) {
  69. const parts = line.substring(10).split(' ');
  70. const sctpPort = parts[0];
  71. const protocol = parts[1];
  72. // Stream count is optional
  73. const streamCount = parts.length > 2 ? parts[2] : null;
  74. return [sctpPort, protocol, streamCount];// SCTP port
  75. },
  76. build_rtpmap(el) {
  77. let line = `a=rtpmap:${el.getAttribute('id')} ${el.getAttribute('name')}/${el.getAttribute('clockrate')}`;
  78. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  79. line += `/${el.getAttribute('channels')}`;
  80. }
  81. return line;
  82. },
  83. parse_crypto(line) {
  84. const data = {};
  85. const parts = line.substring(9).split(' ');
  86. data.tag = parts.shift();
  87. data['crypto-suite'] = parts.shift();
  88. data['key-params'] = parts.shift();
  89. if (parts.length) {
  90. data['session-params'] = parts.join(' ');
  91. }
  92. return data;
  93. },
  94. parse_fingerprint(line) { // RFC 4572
  95. const data = {};
  96. const parts = line.substring(14).split(' ');
  97. data.hash = parts.shift();
  98. data.fingerprint = parts.shift();
  99. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  100. return data;
  101. },
  102. parse_fmtp(line) {
  103. const data = [];
  104. let parts = line.split(' ');
  105. parts.shift();
  106. parts = parts.join(' ').split(';');
  107. for (let i = 0; i < parts.length; i++) {
  108. let key = parts[i].split('=')[0];
  109. while (key.length && key[0] == ' ') {
  110. key = key.substring(1);
  111. }
  112. const value = parts[i].split('=')[1];
  113. if (key && value) {
  114. data.push({name: key, value});
  115. } else if (key) {
  116. // rfc 4733 (DTMF) style stuff
  117. data.push({name: '', value: key});
  118. }
  119. }
  120. return data;
  121. },
  122. parse_icecandidate(line) {
  123. const candidate = {};
  124. const elems = line.split(' ');
  125. candidate.foundation = elems[0].substring(12);
  126. candidate.component = elems[1];
  127. candidate.protocol = elems[2].toLowerCase();
  128. candidate.priority = elems[3];
  129. candidate.ip = elems[4];
  130. candidate.port = elems[5];
  131. // elems[6] => "typ"
  132. candidate.type = elems[7];
  133. candidate.generation = 0; // default value, may be overwritten below
  134. for (let i = 8; i < elems.length; i += 2) {
  135. switch (elems[i]) {
  136. case 'raddr':
  137. candidate['rel-addr'] = elems[i + 1];
  138. break;
  139. case 'rport':
  140. candidate['rel-port'] = elems[i + 1];
  141. break;
  142. case 'generation':
  143. candidate.generation = elems[i + 1];
  144. break;
  145. case 'tcptype':
  146. candidate.tcptype = elems[i + 1];
  147. break;
  148. default: // TODO
  149. logger.log(`parse_icecandidate not translating "${elems[i]}" = "${elems[i + 1]}"`);
  150. }
  151. }
  152. candidate.network = '1';
  153. // not applicable to SDP -- FIXME: should be unique, not just random
  154. // eslint-disable-next-line newline-per-chained-call
  155. candidate.id = Math.random().toString(36).substr(2, 10);
  156. return candidate;
  157. },
  158. build_icecandidate(cand) {
  159. let line = [`a=candidate:${cand.foundation}`, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  160. line += ' ';
  161. switch (cand.type) {
  162. case 'srflx':
  163. case 'prflx':
  164. case 'relay':
  165. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  166. line += 'raddr';
  167. line += ' ';
  168. line += cand['rel-addr'];
  169. line += ' ';
  170. line += 'rport';
  171. line += ' ';
  172. line += cand['rel-port'];
  173. line += ' ';
  174. }
  175. break;
  176. }
  177. if (cand.hasOwnAttribute('tcptype')) {
  178. line += 'tcptype';
  179. line += ' ';
  180. line += cand.tcptype;
  181. line += ' ';
  182. }
  183. line += 'generation';
  184. line += ' ';
  185. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  186. return line;
  187. },
  188. parse_ssrc(desc) {
  189. // proprietary mapping of a=ssrc lines
  190. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  191. // and parse according to that
  192. const data = {};
  193. const lines = desc.split('\r\n');
  194. for (let i = 0; i < lines.length; i++) {
  195. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  196. const idx = lines[i].indexOf(' ');
  197. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  198. }
  199. }
  200. return data;
  201. },
  202. parse_rtcpfb(line) {
  203. const parts = line.substr(10).split(' ');
  204. const data = {};
  205. data.pt = parts.shift();
  206. data.type = parts.shift();
  207. data.params = parts;
  208. return data;
  209. },
  210. parse_extmap(line) {
  211. const parts = line.substr(9).split(' ');
  212. const data = {};
  213. data.value = parts.shift();
  214. if (data.value.indexOf('/') === -1) {
  215. data.direction = 'both';
  216. } else {
  217. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  218. data.value = data.value.substr(0, data.value.indexOf('/'));
  219. }
  220. data.uri = parts.shift();
  221. data.params = parts;
  222. return data;
  223. },
  224. find_line(haystack, needle, sessionpart) {
  225. let lines = haystack.split('\r\n');
  226. for (let i = 0; i < lines.length; i++) {
  227. if (lines[i].substring(0, needle.length) == needle) {
  228. return lines[i];
  229. }
  230. }
  231. if (!sessionpart) {
  232. return false;
  233. }
  234. // search session part
  235. lines = sessionpart.split('\r\n');
  236. for (let j = 0; j < lines.length; j++) {
  237. if (lines[j].substring(0, needle.length) == needle) {
  238. return lines[j];
  239. }
  240. }
  241. return false;
  242. },
  243. find_lines(haystack, needle, sessionpart) {
  244. let lines = haystack.split('\r\n');
  245. const needles = [];
  246. for (let i = 0; i < lines.length; i++) {
  247. if (lines[i].substring(0, needle.length) == needle) {
  248. needles.push(lines[i]);
  249. }
  250. }
  251. if (needles.length || !sessionpart) {
  252. return needles;
  253. }
  254. // search session part
  255. lines = sessionpart.split('\r\n');
  256. for (let j = 0; j < lines.length; j++) {
  257. if (lines[j].substring(0, needle.length) == needle) {
  258. needles.push(lines[j]);
  259. }
  260. }
  261. return needles;
  262. },
  263. candidateToJingle(line) {
  264. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  265. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  266. if (line.indexOf('candidate:') === 0) {
  267. line = `a=${line}`;
  268. } else if (line.substring(0, 12) != 'a=candidate:') {
  269. logger.log('parseCandidate called with a line that is not a candidate line');
  270. logger.log(line);
  271. return null;
  272. }
  273. if (line.substring(line.length - 2) == '\r\n') {// chomp it
  274. line = line.substring(0, line.length - 2);
  275. }
  276. const candidate = {};
  277. const elems = line.split(' ');
  278. if (elems[6] != 'typ') {
  279. logger.log('did not find typ in the right place');
  280. logger.log(line);
  281. return null;
  282. }
  283. candidate.foundation = elems[0].substring(12);
  284. candidate.component = elems[1];
  285. candidate.protocol = elems[2].toLowerCase();
  286. candidate.priority = elems[3];
  287. candidate.ip = elems[4];
  288. candidate.port = elems[5];
  289. // elems[6] => "typ"
  290. candidate.type = elems[7];
  291. candidate.generation = '0'; // default, may be overwritten below
  292. for (let i = 8; i < elems.length; i += 2) {
  293. switch (elems[i]) {
  294. case 'raddr':
  295. candidate['rel-addr'] = elems[i + 1];
  296. break;
  297. case 'rport':
  298. candidate['rel-port'] = elems[i + 1];
  299. break;
  300. case 'generation':
  301. candidate.generation = elems[i + 1];
  302. break;
  303. case 'tcptype':
  304. candidate.tcptype = elems[i + 1];
  305. break;
  306. default: // TODO
  307. logger.log(`not translating "${elems[i]}" = "${elems[i + 1]}"`);
  308. }
  309. }
  310. candidate.network = '1';
  311. // not applicable to SDP -- FIXME: should be unique, not just random
  312. // eslint-disable-next-line newline-per-chained-call
  313. candidate.id = Math.random().toString(36).substr(2, 10);
  314. return candidate;
  315. },
  316. candidateFromJingle(cand) {
  317. let line = 'a=candidate:';
  318. line += cand.getAttribute('foundation');
  319. line += ' ';
  320. line += cand.getAttribute('component');
  321. line += ' ';
  322. let protocol = cand.getAttribute('protocol');
  323. // use tcp candidates for FF
  324. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  325. protocol = 'tcp';
  326. }
  327. line += protocol; // .toUpperCase(); // chrome M23 doesn't like this
  328. line += ' ';
  329. line += cand.getAttribute('priority');
  330. line += ' ';
  331. line += cand.getAttribute('ip');
  332. line += ' ';
  333. line += cand.getAttribute('port');
  334. line += ' ';
  335. line += 'typ';
  336. line += ` ${cand.getAttribute('type')}`;
  337. line += ' ';
  338. switch (cand.getAttribute('type')) {
  339. case 'srflx':
  340. case 'prflx':
  341. case 'relay':
  342. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  343. line += 'raddr';
  344. line += ' ';
  345. line += cand.getAttribute('rel-addr');
  346. line += ' ';
  347. line += 'rport';
  348. line += ' ';
  349. line += cand.getAttribute('rel-port');
  350. line += ' ';
  351. }
  352. break;
  353. }
  354. if (protocol.toLowerCase() == 'tcp') {
  355. line += 'tcptype';
  356. line += ' ';
  357. line += cand.getAttribute('tcptype');
  358. line += ' ';
  359. }
  360. line += 'generation';
  361. line += ' ';
  362. line += cand.getAttribute('generation') || '0';
  363. return `${line}\r\n`;
  364. },
  365. /**
  366. * Parse the 'most' primary video ssrc from the given m line
  367. * @param {object} mLine object as parsed from transform.parse
  368. * @return {number} the primary video ssrc from the given m line
  369. */
  370. parsePrimaryVideoSsrc(videoMLine) {
  371. const numSsrcs = videoMLine.ssrcs
  372. .map(ssrcInfo => ssrcInfo.id)
  373. .filter((ssrc, index, array) => array.indexOf(ssrc) === index)
  374. .length;
  375. const numGroups
  376. = (videoMLine.ssrcGroups && videoMLine.ssrcGroups.length) || 0;
  377. if (numSsrcs > 1 && numGroups === 0) {
  378. // Ambiguous, can't figure out the primary
  379. return;
  380. }
  381. let primarySsrc = null;
  382. if (numSsrcs === 1) {
  383. primarySsrc = videoMLine.ssrcs[0].id;
  384. } else if (numSsrcs === 2) {
  385. // Can figure it out if there's an FID group
  386. const fidGroup
  387. = videoMLine.ssrcGroups.find(
  388. group => group.semantics === 'FID');
  389. if (fidGroup) {
  390. primarySsrc = fidGroup.ssrcs.split(' ')[0];
  391. }
  392. } else if (numSsrcs >= 3) {
  393. // Can figure it out if there's a sim group
  394. const simGroup
  395. = videoMLine.ssrcGroups.find(
  396. group => group.semantics === 'SIM');
  397. if (simGroup) {
  398. primarySsrc = simGroup.ssrcs.split(' ')[0];
  399. }
  400. }
  401. return primarySsrc;
  402. },
  403. /**
  404. * Generate an ssrc
  405. * @returns {number} an ssrc
  406. */
  407. generateSsrc() {
  408. return RandomUtil.randomInt(1, 0xffffffff);
  409. },
  410. /**
  411. * Get an attribute for the given ssrc with the given attributeName
  412. * from the given mline
  413. * @param {object} mLine an mLine object as parsed from transform.parse
  414. * @param {number} ssrc the ssrc for which an attribtue is desired
  415. * @param {string} attributeName the name of the desired attribute
  416. * @returns {string} the value corresponding to the given ssrc
  417. * and attributeName
  418. */
  419. getSsrcAttribute(mLine, ssrc, attributeName) {
  420. for (let i = 0; i < mLine.ssrcs.length; ++i) {
  421. const ssrcLine = mLine.ssrcs[i];
  422. if (ssrcLine.id === ssrc
  423. && ssrcLine.attribute === attributeName) {
  424. return ssrcLine.value;
  425. }
  426. }
  427. },
  428. /**
  429. * Parses the ssrcs from the group sdp line and
  430. * returns them as a list of numbers
  431. * @param {object} the ssrcGroup object as parsed from
  432. * sdp-transform
  433. * @returns {list<number>} a list of the ssrcs in the group
  434. * parsed as numbers
  435. */
  436. parseGroupSsrcs(ssrcGroup) {
  437. return ssrcGroup
  438. .ssrcs
  439. .split(' ')
  440. .map(ssrcStr => parseInt(ssrcStr));
  441. },
  442. /**
  443. * Get the mline of the given type from the given sdp
  444. * @param {object} sdp sdp as parsed from transform.parse
  445. * @param {string} type the type of the desired mline (e.g. "video")
  446. * @returns {object} a media object
  447. */
  448. getMedia(sdp, type) {
  449. return sdp.media.find(m => m.type === type);
  450. },
  451. /**
  452. * Sets the given codecName as the preferred codec by
  453. * moving it to the beginning of the payload types
  454. * list (modifies the given mline in place). If there
  455. * are multiple options within the same codec (multiple h264
  456. * profiles, for instance), this will prefer the first one
  457. * that is found.
  458. * @param {object} videoMLine the video mline object from
  459. * an sdp as parsed by transform.parse
  460. * @param {string} the name of the preferred codec
  461. */
  462. preferVideoCodec(videoMLine, codecName) {
  463. let payloadType = null;
  464. for (let i = 0; i < videoMLine.rtp.length; ++i) {
  465. const rtp = videoMLine.rtp[i];
  466. if (rtp.codec === codecName) {
  467. payloadType = rtp.payload;
  468. break;
  469. }
  470. }
  471. if (payloadType) {
  472. const payloadTypes = videoMLine.payloads.split(' ').map(p => parseInt(p));
  473. const payloadIndex = payloadTypes.indexOf(payloadType);
  474. payloadTypes.splice(payloadIndex, 1);
  475. payloadTypes.unshift(payloadType);
  476. videoMLine.payloads = payloadTypes.join(' ');
  477. }
  478. },
  479. };
  480. module.exports = SDPUtil;