Debian Codegraph @

sdp.js

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