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

SDPUtil.js 17KB

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