sdp.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. /* eslint-env node */
  2. 'use strict';
  3. // SDP helpers.
  4. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  5. var SDPUtils = {};
  6. // Generate an alphanumeric identifier for cname or mids.
  7. // TODO: use UUIDs instead? https://gist.github.com/jed/982883
  8. SDPUtils.generateIdentifier = function () {
  9. return Math.random().toString(36).substring(2, 12);
  10. };
  11. // The RTCP CNAME used by all peerconnections from the same JS.
  12. SDPUtils.localCName = SDPUtils.generateIdentifier();
  13. // Splits SDP into lines, dealing with both CRLF and LF.
  14. SDPUtils.splitLines = function (blob) {
  15. return blob.trim().split('\n').map(function (line) {
  16. return line.trim();
  17. });
  18. };
  19. // Splits SDP into sessionpart and mediasections. Ensures CRLF.
  20. SDPUtils.splitSections = function (blob) {
  21. var parts = blob.split('\nm=');
  22. return parts.map(function (part, index) {
  23. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  24. });
  25. };
  26. // Returns the session description.
  27. SDPUtils.getDescription = function (blob) {
  28. var sections = SDPUtils.splitSections(blob);
  29. return sections && sections[0];
  30. };
  31. // Returns the individual media sections.
  32. SDPUtils.getMediaSections = function (blob) {
  33. var sections = SDPUtils.splitSections(blob);
  34. sections.shift();
  35. return sections;
  36. };
  37. // Returns lines that start with a certain prefix.
  38. SDPUtils.matchPrefix = function (blob, prefix) {
  39. return SDPUtils.splitLines(blob).filter(function (line) {
  40. return line.indexOf(prefix) === 0;
  41. });
  42. };
  43. // Parses an ICE candidate line. Sample input:
  44. // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
  45. // rport 55996"
  46. // Input can be prefixed with a=.
  47. SDPUtils.parseCandidate = function (line) {
  48. var parts = void 0;
  49. // Parse both variants.
  50. if (line.indexOf('a=candidate:') === 0) {
  51. parts = line.substring(12).split(' ');
  52. } else {
  53. parts = line.substring(10).split(' ');
  54. }
  55. var candidate = {
  56. foundation: parts[0],
  57. component: { 1: 'rtp', 2: 'rtcp' }[parts[1]] || parts[1],
  58. protocol: parts[2].toLowerCase(),
  59. priority: parseInt(parts[3], 10),
  60. ip: parts[4],
  61. address: parts[4], // address is an alias for ip.
  62. port: parseInt(parts[5], 10),
  63. // skip parts[6] == 'typ'
  64. type: parts[7]
  65. };
  66. for (var i = 8; i < parts.length; i += 2) {
  67. switch (parts[i]) {
  68. case 'raddr':
  69. candidate.relatedAddress = parts[i + 1];
  70. break;
  71. case 'rport':
  72. candidate.relatedPort = parseInt(parts[i + 1], 10);
  73. break;
  74. case 'tcptype':
  75. candidate.tcpType = parts[i + 1];
  76. break;
  77. case 'ufrag':
  78. candidate.ufrag = parts[i + 1]; // for backward compatibility.
  79. candidate.usernameFragment = parts[i + 1];
  80. break;
  81. default:
  82. // extension handling, in particular ufrag. Don't overwrite.
  83. if (candidate[parts[i]] === undefined) {
  84. candidate[parts[i]] = parts[i + 1];
  85. }
  86. break;
  87. }
  88. }
  89. return candidate;
  90. };
  91. // Translates a candidate object into SDP candidate attribute.
  92. // This does not include the a= prefix!
  93. SDPUtils.writeCandidate = function (candidate) {
  94. var sdp = [];
  95. sdp.push(candidate.foundation);
  96. var component = candidate.component;
  97. if (component === 'rtp') {
  98. sdp.push(1);
  99. } else if (component === 'rtcp') {
  100. sdp.push(2);
  101. } else {
  102. sdp.push(component);
  103. }
  104. sdp.push(candidate.protocol.toUpperCase());
  105. sdp.push(candidate.priority);
  106. sdp.push(candidate.address || candidate.ip);
  107. sdp.push(candidate.port);
  108. var type = candidate.type;
  109. sdp.push('typ');
  110. sdp.push(type);
  111. if (type !== 'host' && candidate.relatedAddress && candidate.relatedPort) {
  112. sdp.push('raddr');
  113. sdp.push(candidate.relatedAddress);
  114. sdp.push('rport');
  115. sdp.push(candidate.relatedPort);
  116. }
  117. if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
  118. sdp.push('tcptype');
  119. sdp.push(candidate.tcpType);
  120. }
  121. if (candidate.usernameFragment || candidate.ufrag) {
  122. sdp.push('ufrag');
  123. sdp.push(candidate.usernameFragment || candidate.ufrag);
  124. }
  125. return 'candidate:' + sdp.join(' ');
  126. };
  127. // Parses an ice-options line, returns an array of option tags.
  128. // Sample input:
  129. // a=ice-options:foo bar
  130. SDPUtils.parseIceOptions = function (line) {
  131. return line.substring(14).split(' ');
  132. };
  133. // Parses a rtpmap line, returns RTCRtpCoddecParameters. Sample input:
  134. // a=rtpmap:111 opus/48000/2
  135. SDPUtils.parseRtpMap = function (line) {
  136. var parts = line.substring(9).split(' ');
  137. var parsed = {
  138. payloadType: parseInt(parts.shift(), 10) // was: id
  139. };
  140. parts = parts[0].split('/');
  141. parsed.name = parts[0];
  142. parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
  143. parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
  144. // legacy alias, got renamed back to channels in ORTC.
  145. parsed.numChannels = parsed.channels;
  146. return parsed;
  147. };
  148. // Generates a rtpmap line from RTCRtpCodecCapability or
  149. // RTCRtpCodecParameters.
  150. SDPUtils.writeRtpMap = function (codec) {
  151. var pt = codec.payloadType;
  152. if (codec.preferredPayloadType !== undefined) {
  153. pt = codec.preferredPayloadType;
  154. }
  155. var channels = codec.channels || codec.numChannels || 1;
  156. return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate + (channels !== 1 ? '/' + channels : '') + '\r\n';
  157. };
  158. // Parses a extmap line (headerextension from RFC 5285). Sample input:
  159. // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  160. // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
  161. SDPUtils.parseExtmap = function (line) {
  162. var parts = line.substring(9).split(' ');
  163. return {
  164. id: parseInt(parts[0], 10),
  165. direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
  166. uri: parts[1],
  167. attributes: parts.slice(2).join(' ')
  168. };
  169. };
  170. // Generates an extmap line from RTCRtpHeaderExtensionParameters or
  171. // RTCRtpHeaderExtension.
  172. SDPUtils.writeExtmap = function (headerExtension) {
  173. return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) + (headerExtension.direction && headerExtension.direction !== 'sendrecv' ? '/' + headerExtension.direction : '') + ' ' + headerExtension.uri + (headerExtension.attributes ? ' ' + headerExtension.attributes : '') + '\r\n';
  174. };
  175. // Parses a fmtp line, returns dictionary. Sample input:
  176. // a=fmtp:96 vbr=on;cng=on
  177. // Also deals with vbr=on; cng=on
  178. SDPUtils.parseFmtp = function (line) {
  179. var parsed = {};
  180. var kv = void 0;
  181. var parts = line.substring(line.indexOf(' ') + 1).split(';');
  182. for (var j = 0; j < parts.length; j++) {
  183. kv = parts[j].trim().split('=');
  184. parsed[kv[0].trim()] = kv[1];
  185. }
  186. return parsed;
  187. };
  188. // Generates a fmtp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
  189. SDPUtils.writeFmtp = function (codec) {
  190. var line = '';
  191. var pt = codec.payloadType;
  192. if (codec.preferredPayloadType !== undefined) {
  193. pt = codec.preferredPayloadType;
  194. }
  195. if (codec.parameters && Object.keys(codec.parameters).length) {
  196. var params = [];
  197. Object.keys(codec.parameters).forEach(function (param) {
  198. if (codec.parameters[param] !== undefined) {
  199. params.push(param + '=' + codec.parameters[param]);
  200. } else {
  201. params.push(param);
  202. }
  203. });
  204. line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
  205. }
  206. return line;
  207. };
  208. // Parses a rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
  209. // a=rtcp-fb:98 nack rpsi
  210. SDPUtils.parseRtcpFb = function (line) {
  211. var parts = line.substring(line.indexOf(' ') + 1).split(' ');
  212. return {
  213. type: parts.shift(),
  214. parameter: parts.join(' ')
  215. };
  216. };
  217. // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
  218. SDPUtils.writeRtcpFb = function (codec) {
  219. var lines = '';
  220. var pt = codec.payloadType;
  221. if (codec.preferredPayloadType !== undefined) {
  222. pt = codec.preferredPayloadType;
  223. }
  224. if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
  225. // FIXME: special handling for trr-int?
  226. codec.rtcpFeedback.forEach(function (fb) {
  227. lines += 'a=rtcp-fb:' + pt + ' ' + fb.type + (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') + '\r\n';
  228. });
  229. }
  230. return lines;
  231. };
  232. // Parses a RFC 5576 ssrc media attribute. Sample input:
  233. // a=ssrc:3735928559 cname:something
  234. SDPUtils.parseSsrcMedia = function (line) {
  235. var sp = line.indexOf(' ');
  236. var parts = {
  237. ssrc: parseInt(line.substring(7, sp), 10)
  238. };
  239. var colon = line.indexOf(':', sp);
  240. if (colon > -1) {
  241. parts.attribute = line.substring(sp + 1, colon);
  242. parts.value = line.substring(colon + 1);
  243. } else {
  244. parts.attribute = line.substring(sp + 1);
  245. }
  246. return parts;
  247. };
  248. // Parse a ssrc-group line (see RFC 5576). Sample input:
  249. // a=ssrc-group:semantics 12 34
  250. SDPUtils.parseSsrcGroup = function (line) {
  251. var parts = line.substring(13).split(' ');
  252. return {
  253. semantics: parts.shift(),
  254. ssrcs: parts.map(function (ssrc) {
  255. return parseInt(ssrc, 10);
  256. })
  257. };
  258. };
  259. // Extracts the MID (RFC 5888) from a media section.
  260. // Returns the MID or undefined if no mid line was found.
  261. SDPUtils.getMid = function (mediaSection) {
  262. var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
  263. if (mid) {
  264. return mid.substring(6);
  265. }
  266. };
  267. // Parses a fingerprint line for DTLS-SRTP.
  268. SDPUtils.parseFingerprint = function (line) {
  269. var parts = line.substring(14).split(' ');
  270. return {
  271. algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.
  272. value: parts[1].toUpperCase() // the definition is upper-case in RFC 4572.
  273. };
  274. };
  275. // Extracts DTLS parameters from SDP media section or sessionpart.
  276. // FIXME: for consistency with other functions this should only
  277. // get the fingerprint line as input. See also getIceParameters.
  278. SDPUtils.getDtlsParameters = function (mediaSection, sessionpart) {
  279. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=fingerprint:');
  280. // Note: a=setup line is ignored since we use the 'auto' role in Edge.
  281. return {
  282. role: 'auto',
  283. fingerprints: lines.map(SDPUtils.parseFingerprint)
  284. };
  285. };
  286. // Serializes DTLS parameters to SDP.
  287. SDPUtils.writeDtlsParameters = function (params, setupType) {
  288. var sdp = 'a=setup:' + setupType + '\r\n';
  289. params.fingerprints.forEach(function (fp) {
  290. sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
  291. });
  292. return sdp;
  293. };
  294. // Parses a=crypto lines into
  295. // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#dictionary-rtcsrtpsdesparameters-members
  296. SDPUtils.parseCryptoLine = function (line) {
  297. var parts = line.substring(9).split(' ');
  298. return {
  299. tag: parseInt(parts[0], 10),
  300. cryptoSuite: parts[1],
  301. keyParams: parts[2],
  302. sessionParams: parts.slice(3)
  303. };
  304. };
  305. SDPUtils.writeCryptoLine = function (parameters) {
  306. return 'a=crypto:' + parameters.tag + ' ' + parameters.cryptoSuite + ' ' + (_typeof(parameters.keyParams) === 'object' ? SDPUtils.writeCryptoKeyParams(parameters.keyParams) : parameters.keyParams) + (parameters.sessionParams ? ' ' + parameters.sessionParams.join(' ') : '') + '\r\n';
  307. };
  308. // Parses the crypto key parameters into
  309. // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#rtcsrtpkeyparam*
  310. SDPUtils.parseCryptoKeyParams = function (keyParams) {
  311. if (keyParams.indexOf('inline:') !== 0) {
  312. return null;
  313. }
  314. var parts = keyParams.substring(7).split('|');
  315. return {
  316. keyMethod: 'inline',
  317. keySalt: parts[0],
  318. lifeTime: parts[1],
  319. mkiValue: parts[2] ? parts[2].split(':')[0] : undefined,
  320. mkiLength: parts[2] ? parts[2].split(':')[1] : undefined
  321. };
  322. };
  323. SDPUtils.writeCryptoKeyParams = function (keyParams) {
  324. return keyParams.keyMethod + ':' + keyParams.keySalt + (keyParams.lifeTime ? '|' + keyParams.lifeTime : '') + (keyParams.mkiValue && keyParams.mkiLength ? '|' + keyParams.mkiValue + ':' + keyParams.mkiLength : '');
  325. };
  326. // Extracts all SDES parameters.
  327. SDPUtils.getCryptoParameters = function (mediaSection, sessionpart) {
  328. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=crypto:');
  329. return lines.map(SDPUtils.parseCryptoLine);
  330. };
  331. // Parses ICE information from SDP media section or sessionpart.
  332. // FIXME: for consistency with other functions this should only
  333. // get the ice-ufrag and ice-pwd lines as input.
  334. SDPUtils.getIceParameters = function (mediaSection, sessionpart) {
  335. var ufrag = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=ice-ufrag:')[0];
  336. var pwd = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=ice-pwd:')[0];
  337. if (!(ufrag && pwd)) {
  338. return null;
  339. }
  340. return {
  341. usernameFragment: ufrag.substring(12),
  342. password: pwd.substring(10)
  343. };
  344. };
  345. // Serializes ICE parameters to SDP.
  346. SDPUtils.writeIceParameters = function (params) {
  347. var sdp = 'a=ice-ufrag:' + params.usernameFragment + '\r\n' + 'a=ice-pwd:' + params.password + '\r\n';
  348. if (params.iceLite) {
  349. sdp += 'a=ice-lite\r\n';
  350. }
  351. return sdp;
  352. };
  353. // Parses the SDP media section and returns RTCRtpParameters.
  354. SDPUtils.parseRtpParameters = function (mediaSection) {
  355. var description = {
  356. codecs: [],
  357. headerExtensions: [],
  358. fecMechanisms: [],
  359. rtcp: []
  360. };
  361. var lines = SDPUtils.splitLines(mediaSection);
  362. var mline = lines[0].split(' ');
  363. description.profile = mline[2];
  364. for (var i = 3; i < mline.length; i++) {
  365. // find all codecs from mline[3..]
  366. var pt = mline[i];
  367. var rtpmapline = SDPUtils.matchPrefix(mediaSection, 'a=rtpmap:' + pt + ' ')[0];
  368. if (rtpmapline) {
  369. var codec = SDPUtils.parseRtpMap(rtpmapline);
  370. var fmtps = SDPUtils.matchPrefix(mediaSection, 'a=fmtp:' + pt + ' ');
  371. // Only the first a=fmtp:<pt> is considered.
  372. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
  373. codec.rtcpFeedback = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-fb:' + pt + ' ').map(SDPUtils.parseRtcpFb);
  374. description.codecs.push(codec);
  375. // parse FEC mechanisms from rtpmap lines.
  376. switch (codec.name.toUpperCase()) {
  377. case 'RED':
  378. case 'ULPFEC':
  379. description.fecMechanisms.push(codec.name.toUpperCase());
  380. break;
  381. default:
  382. // only RED and ULPFEC are recognized as FEC mechanisms.
  383. break;
  384. }
  385. }
  386. }
  387. SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function (line) {
  388. description.headerExtensions.push(SDPUtils.parseExtmap(line));
  389. });
  390. var wildcardRtcpFb = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-fb:* ').map(SDPUtils.parseRtcpFb);
  391. description.codecs.forEach(function (codec) {
  392. wildcardRtcpFb.forEach(function (fb) {
  393. var duplicate = codec.rtcpFeedback.find(function (existingFeedback) {
  394. return existingFeedback.type === fb.type && existingFeedback.parameter === fb.parameter;
  395. });
  396. if (!duplicate) {
  397. codec.rtcpFeedback.push(fb);
  398. }
  399. });
  400. });
  401. // FIXME: parse rtcp.
  402. return description;
  403. };
  404. // Generates parts of the SDP media section describing the capabilities /
  405. // parameters.
  406. SDPUtils.writeRtpDescription = function (kind, caps) {
  407. var sdp = '';
  408. // Build the mline.
  409. sdp += 'm=' + kind + ' ';
  410. sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
  411. sdp += ' ' + (caps.profile || 'UDP/TLS/RTP/SAVPF') + ' ';
  412. sdp += caps.codecs.map(function (codec) {
  413. if (codec.preferredPayloadType !== undefined) {
  414. return codec.preferredPayloadType;
  415. }
  416. return codec.payloadType;
  417. }).join(' ') + '\r\n';
  418. sdp += 'c=IN IP4 0.0.0.0\r\n';
  419. sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
  420. // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
  421. caps.codecs.forEach(function (codec) {
  422. sdp += SDPUtils.writeRtpMap(codec);
  423. sdp += SDPUtils.writeFmtp(codec);
  424. sdp += SDPUtils.writeRtcpFb(codec);
  425. });
  426. var maxptime = 0;
  427. caps.codecs.forEach(function (codec) {
  428. if (codec.maxptime > maxptime) {
  429. maxptime = codec.maxptime;
  430. }
  431. });
  432. if (maxptime > 0) {
  433. sdp += 'a=maxptime:' + maxptime + '\r\n';
  434. }
  435. if (caps.headerExtensions) {
  436. caps.headerExtensions.forEach(function (extension) {
  437. sdp += SDPUtils.writeExtmap(extension);
  438. });
  439. }
  440. // FIXME: write fecMechanisms.
  441. return sdp;
  442. };
  443. // Parses the SDP media section and returns an array of
  444. // RTCRtpEncodingParameters.
  445. SDPUtils.parseRtpEncodingParameters = function (mediaSection) {
  446. var encodingParameters = [];
  447. var description = SDPUtils.parseRtpParameters(mediaSection);
  448. var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
  449. var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
  450. // filter a=ssrc:... cname:, ignore PlanB-msid
  451. var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(function (line) {
  452. return SDPUtils.parseSsrcMedia(line);
  453. }).filter(function (parts) {
  454. return parts.attribute === 'cname';
  455. });
  456. var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
  457. var secondarySsrc = void 0;
  458. var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID').map(function (line) {
  459. var parts = line.substring(17).split(' ');
  460. return parts.map(function (part) {
  461. return parseInt(part, 10);
  462. });
  463. });
  464. if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
  465. secondarySsrc = flows[0][1];
  466. }
  467. description.codecs.forEach(function (codec) {
  468. if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
  469. var encParam = {
  470. ssrc: primarySsrc,
  471. codecPayloadType: parseInt(codec.parameters.apt, 10)
  472. };
  473. if (primarySsrc && secondarySsrc) {
  474. encParam.rtx = { ssrc: secondarySsrc };
  475. }
  476. encodingParameters.push(encParam);
  477. if (hasRed) {
  478. encParam = JSON.parse(JSON.stringify(encParam));
  479. encParam.fec = {
  480. ssrc: primarySsrc,
  481. mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
  482. };
  483. encodingParameters.push(encParam);
  484. }
  485. }
  486. });
  487. if (encodingParameters.length === 0 && primarySsrc) {
  488. encodingParameters.push({
  489. ssrc: primarySsrc
  490. });
  491. }
  492. // we support both b=AS and b=TIAS but interpret AS as TIAS.
  493. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
  494. if (bandwidth.length) {
  495. if (bandwidth[0].indexOf('b=TIAS:') === 0) {
  496. bandwidth = parseInt(bandwidth[0].substring(7), 10);
  497. } else if (bandwidth[0].indexOf('b=AS:') === 0) {
  498. // use formula from JSEP to convert b=AS to TIAS value.
  499. bandwidth = parseInt(bandwidth[0].substring(5), 10) * 1000 * 0.95 - 50 * 40 * 8;
  500. } else {
  501. bandwidth = undefined;
  502. }
  503. encodingParameters.forEach(function (params) {
  504. params.maxBitrate = bandwidth;
  505. });
  506. }
  507. return encodingParameters;
  508. };
  509. // parses http://draft.ortc.org/#rtcrtcpparameters*
  510. SDPUtils.parseRtcpParameters = function (mediaSection) {
  511. var rtcpParameters = {};
  512. // Gets the first SSRC. Note that with RTX there might be multiple
  513. // SSRCs.
  514. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(function (line) {
  515. return SDPUtils.parseSsrcMedia(line);
  516. }).filter(function (obj) {
  517. return obj.attribute === 'cname';
  518. })[0];
  519. if (remoteSsrc) {
  520. rtcpParameters.cname = remoteSsrc.value;
  521. rtcpParameters.ssrc = remoteSsrc.ssrc;
  522. }
  523. // Edge uses the compound attribute instead of reducedSize
  524. // compound is !reducedSize
  525. var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
  526. rtcpParameters.reducedSize = rsize.length > 0;
  527. rtcpParameters.compound = rsize.length === 0;
  528. // parses the rtcp-mux attrіbute.
  529. // Note that Edge does not support unmuxed RTCP.
  530. var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
  531. rtcpParameters.mux = mux.length > 0;
  532. return rtcpParameters;
  533. };
  534. SDPUtils.writeRtcpParameters = function (rtcpParameters) {
  535. var sdp = '';
  536. if (rtcpParameters.reducedSize) {
  537. sdp += 'a=rtcp-rsize\r\n';
  538. }
  539. if (rtcpParameters.mux) {
  540. sdp += 'a=rtcp-mux\r\n';
  541. }
  542. if (rtcpParameters.ssrc !== undefined && rtcpParameters.cname) {
  543. sdp += 'a=ssrc:' + rtcpParameters.ssrc + ' cname:' + rtcpParameters.cname + '\r\n';
  544. }
  545. return sdp;
  546. };
  547. // parses either a=msid: or a=ssrc:... msid lines and returns
  548. // the id of the MediaStream and MediaStreamTrack.
  549. SDPUtils.parseMsid = function (mediaSection) {
  550. var parts = void 0;
  551. var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
  552. if (spec.length === 1) {
  553. parts = spec[0].substring(7).split(' ');
  554. return { stream: parts[0], track: parts[1] };
  555. }
  556. var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map(function (line) {
  557. return SDPUtils.parseSsrcMedia(line);
  558. }).filter(function (msidParts) {
  559. return msidParts.attribute === 'msid';
  560. });
  561. if (planB.length > 0) {
  562. parts = planB[0].value.split(' ');
  563. return { stream: parts[0], track: parts[1] };
  564. }
  565. };
  566. // SCTP
  567. // parses draft-ietf-mmusic-sctp-sdp-26 first and falls back
  568. // to draft-ietf-mmusic-sctp-sdp-05
  569. SDPUtils.parseSctpDescription = function (mediaSection) {
  570. var mline = SDPUtils.parseMLine(mediaSection);
  571. var maxSizeLine = SDPUtils.matchPrefix(mediaSection, 'a=max-message-size:');
  572. var maxMessageSize = void 0;
  573. if (maxSizeLine.length > 0) {
  574. maxMessageSize = parseInt(maxSizeLine[0].substring(19), 10);
  575. }
  576. if (isNaN(maxMessageSize)) {
  577. maxMessageSize = 65536;
  578. }
  579. var sctpPort = SDPUtils.matchPrefix(mediaSection, 'a=sctp-port:');
  580. if (sctpPort.length > 0) {
  581. return {
  582. port: parseInt(sctpPort[0].substring(12), 10),
  583. protocol: mline.fmt,
  584. maxMessageSize: maxMessageSize
  585. };
  586. }
  587. var sctpMapLines = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:');
  588. if (sctpMapLines.length > 0) {
  589. var parts = sctpMapLines[0].substring(10).split(' ');
  590. return {
  591. port: parseInt(parts[0], 10),
  592. protocol: parts[1],
  593. maxMessageSize: maxMessageSize
  594. };
  595. }
  596. };
  597. // SCTP
  598. // outputs the draft-ietf-mmusic-sctp-sdp-26 version that all browsers
  599. // support by now receiving in this format, unless we originally parsed
  600. // as the draft-ietf-mmusic-sctp-sdp-05 format (indicated by the m-line
  601. // protocol of DTLS/SCTP -- without UDP/ or TCP/)
  602. SDPUtils.writeSctpDescription = function (media, sctp) {
  603. var output = [];
  604. if (media.protocol !== 'DTLS/SCTP') {
  605. output = ['m=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.protocol + '\r\n', 'c=IN IP4 0.0.0.0\r\n', 'a=sctp-port:' + sctp.port + '\r\n'];
  606. } else {
  607. output = ['m=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.port + '\r\n', 'c=IN IP4 0.0.0.0\r\n', 'a=sctpmap:' + sctp.port + ' ' + sctp.protocol + ' 65535\r\n'];
  608. }
  609. if (sctp.maxMessageSize !== undefined) {
  610. output.push('a=max-message-size:' + sctp.maxMessageSize + '\r\n');
  611. }
  612. return output.join('');
  613. };
  614. // Generate a session ID for SDP.
  615. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
  616. // recommends using a cryptographically random +ve 64-bit value
  617. // but right now this should be acceptable and within the right range
  618. SDPUtils.generateSessionId = function () {
  619. return Math.random().toString().substr(2, 22);
  620. };
  621. // Write boiler plate for start of SDP
  622. // sessId argument is optional - if not supplied it will
  623. // be generated randomly
  624. // sessVersion is optional and defaults to 2
  625. // sessUser is optional and defaults to 'thisisadapterortc'
  626. SDPUtils.writeSessionBoilerplate = function (sessId, sessVer, sessUser) {
  627. var sessionId = void 0;
  628. var version = sessVer !== undefined ? sessVer : 2;
  629. if (sessId) {
  630. sessionId = sessId;
  631. } else {
  632. sessionId = SDPUtils.generateSessionId();
  633. }
  634. var user = sessUser || 'thisisadapterortc';
  635. // FIXME: sess-id should be an NTP timestamp.
  636. return 'v=0\r\n' + 'o=' + user + ' ' + sessionId + ' ' + version + ' IN IP4 127.0.0.1\r\n' + 's=-\r\n' + 't=0 0\r\n';
  637. };
  638. // Gets the direction from the mediaSection or the sessionpart.
  639. SDPUtils.getDirection = function (mediaSection, sessionpart) {
  640. // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
  641. var lines = SDPUtils.splitLines(mediaSection);
  642. for (var i = 0; i < lines.length; i++) {
  643. switch (lines[i]) {
  644. case 'a=sendrecv':
  645. case 'a=sendonly':
  646. case 'a=recvonly':
  647. case 'a=inactive':
  648. return lines[i].substring(2);
  649. default:
  650. // FIXME: What should happen here?
  651. }
  652. }
  653. if (sessionpart) {
  654. return SDPUtils.getDirection(sessionpart);
  655. }
  656. return 'sendrecv';
  657. };
  658. SDPUtils.getKind = function (mediaSection) {
  659. var lines = SDPUtils.splitLines(mediaSection);
  660. var mline = lines[0].split(' ');
  661. return mline[0].substring(2);
  662. };
  663. SDPUtils.isRejected = function (mediaSection) {
  664. return mediaSection.split(' ', 2)[1] === '0';
  665. };
  666. SDPUtils.parseMLine = function (mediaSection) {
  667. var lines = SDPUtils.splitLines(mediaSection);
  668. var parts = lines[0].substring(2).split(' ');
  669. return {
  670. kind: parts[0],
  671. port: parseInt(parts[1], 10),
  672. protocol: parts[2],
  673. fmt: parts.slice(3).join(' ')
  674. };
  675. };
  676. SDPUtils.parseOLine = function (mediaSection) {
  677. var line = SDPUtils.matchPrefix(mediaSection, 'o=')[0];
  678. var parts = line.substring(2).split(' ');
  679. return {
  680. username: parts[0],
  681. sessionId: parts[1],
  682. sessionVersion: parseInt(parts[2], 10),
  683. netType: parts[3],
  684. addressType: parts[4],
  685. address: parts[5]
  686. };
  687. };
  688. // a very naive interpretation of a valid SDP.
  689. SDPUtils.isValidSDP = function (blob) {
  690. if (typeof blob !== 'string' || blob.length === 0) {
  691. return false;
  692. }
  693. var lines = SDPUtils.splitLines(blob);
  694. for (var i = 0; i < lines.length; i++) {
  695. if (lines[i].length < 2 || lines[i].charAt(1) !== '=') {
  696. return false;
  697. }
  698. // TODO: check the modifier a bit more.
  699. }
  700. return true;
  701. };
  702. // Expose public methods.
  703. if ((typeof module === 'undefined' ? 'undefined' : _typeof(module)) === 'object') {
  704. module.exports = SDPUtils;
  705. }