blob: a308a084140fb2edd5b1cf8dc6b81ee3dcab330f [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2011 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Henrik Kjellander15583c12016-02-10 10:53:12 +010011#include "webrtc/api/webrtcsdp.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
kjellandera96e2d72016-02-04 23:52:28 -080013#include <ctype.h>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000014#include <limits.h>
15#include <stdio.h>
16#include <algorithm>
17#include <string>
18#include <vector>
19
Henrik Kjellander15583c12016-02-10 10:53:12 +010020#include "webrtc/api/jsepicecandidate.h"
21#include "webrtc/api/jsepsessiondescription.h"
tfarina5237aaf2015-11-10 23:44:30 -080022#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000023#include "webrtc/base/common.h"
24#include "webrtc/base/logging.h"
25#include "webrtc/base/messagedigest.h"
26#include "webrtc/base/stringutils.h"
kjellandera96e2d72016-02-04 23:52:28 -080027#include "webrtc/media/base/codec.h"
28#include "webrtc/media/base/constants.h"
29#include "webrtc/media/base/cryptoparams.h"
30#include "webrtc/media/base/rtputils.h"
31#include "webrtc/media/sctp/sctpdataengine.h"
32#include "webrtc/p2p/base/candidate.h"
33#include "webrtc/p2p/base/constants.h"
34#include "webrtc/p2p/base/port.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010035#include "webrtc/pc/mediasession.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000036
37using cricket::AudioContentDescription;
38using cricket::Candidate;
39using cricket::Candidates;
40using cricket::ContentDescription;
41using cricket::ContentInfo;
42using cricket::CryptoParams;
43using cricket::DataContentDescription;
44using cricket::ICE_CANDIDATE_COMPONENT_RTP;
45using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
46using cricket::kCodecParamMaxBitrate;
47using cricket::kCodecParamMaxPTime;
48using cricket::kCodecParamMaxQuantization;
49using cricket::kCodecParamMinBitrate;
50using cricket::kCodecParamMinPTime;
51using cricket::kCodecParamPTime;
52using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000053using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054using cricket::kCodecParamStereo;
55using cricket::kCodecParamUseInbandFec;
Minyue Li7100dcd2015-03-27 05:05:59 +010056using cricket::kCodecParamUseDtx;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057using cricket::kCodecParamSctpProtocol;
58using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000059using cricket::kCodecParamMaxAverageBitrate;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000060using cricket::kCodecParamMaxPlaybackRate;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000061using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062using cricket::MediaContentDescription;
63using cricket::MediaType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064using cricket::RtpHeaderExtension;
65using cricket::SsrcGroup;
66using cricket::StreamParams;
67using cricket::StreamParamsVec;
68using cricket::TransportDescription;
69using cricket::TransportInfo;
70using cricket::VideoContentDescription;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000071using rtc::SocketAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072
73typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
74
75namespace cricket {
76class SessionDescription;
77}
78
79namespace webrtc {
80
81// Line type
82// RFC 4566
83// An SDP session description consists of a number of lines of text of
84// the form:
85// <type>=<value>
86// where <type> MUST be exactly one case-significant character.
87static const int kLinePrefixLength = 2; // Lenght of <type>=
88static const char kLineTypeVersion = 'v';
89static const char kLineTypeOrigin = 'o';
90static const char kLineTypeSessionName = 's';
91static const char kLineTypeSessionInfo = 'i';
92static const char kLineTypeSessionUri = 'u';
93static const char kLineTypeSessionEmail = 'e';
94static const char kLineTypeSessionPhone = 'p';
95static const char kLineTypeSessionBandwidth = 'b';
96static const char kLineTypeTiming = 't';
97static const char kLineTypeRepeatTimes = 'r';
98static const char kLineTypeTimeZone = 'z';
99static const char kLineTypeEncryptionKey = 'k';
100static const char kLineTypeMedia = 'm';
101static const char kLineTypeConnection = 'c';
102static const char kLineTypeAttributes = 'a';
103
104// Attributes
105static const char kAttributeGroup[] = "group";
106static const char kAttributeMid[] = "mid";
107static const char kAttributeRtcpMux[] = "rtcp-mux";
deadbeef13871492015-12-09 12:37:51 -0800108static const char kAttributeRtcpReducedSize[] = "rtcp-rsize";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109static const char kAttributeSsrc[] = "ssrc";
110static const char kSsrcAttributeCname[] = "cname";
111static const char kAttributeExtmap[] = "extmap";
112// draft-alvestrand-mmusic-msid-01
113// a=msid-semantic: WMS
114static const char kAttributeMsidSemantics[] = "msid-semantic";
115static const char kMediaStreamSemantic[] = "WMS";
116static const char kSsrcAttributeMsid[] = "msid";
117static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118static const char kSsrcAttributeMslabel[] = "mslabel";
119static const char kSSrcAttributeLabel[] = "label";
120static const char kAttributeSsrcGroup[] = "ssrc-group";
121static const char kAttributeCrypto[] = "crypto";
122static const char kAttributeCandidate[] = "candidate";
123static const char kAttributeCandidateTyp[] = "typ";
124static const char kAttributeCandidateRaddr[] = "raddr";
125static const char kAttributeCandidateRport[] = "rport";
honghaiza54a0802015-12-16 18:37:23 -0800126static const char kAttributeCandidateUfrag[] = "ufrag";
127static const char kAttributeCandidatePwd[] = "pwd";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000128static const char kAttributeCandidateGeneration[] = "generation";
honghaize1a0c942016-02-16 14:54:56 -0800129static const char kAttributeCandidateNetworkCost[] = "network-cost";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000130static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000131static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000132static const char kAttributeFmtp[] = "fmtp";
133static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000134static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000135static const char kAttributeRtcp[] = "rtcp";
136static const char kAttributeIceUfrag[] = "ice-ufrag";
137static const char kAttributeIcePwd[] = "ice-pwd";
138static const char kAttributeIceLite[] = "ice-lite";
139static const char kAttributeIceOption[] = "ice-options";
140static const char kAttributeSendOnly[] = "sendonly";
141static const char kAttributeRecvOnly[] = "recvonly";
142static const char kAttributeRtcpFb[] = "rtcp-fb";
143static const char kAttributeSendRecv[] = "sendrecv";
144static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000145// draft-ietf-mmusic-sctp-sdp-07
146// a=sctp-port
147static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000148
149// Experimental flags
150static const char kAttributeXGoogleFlag[] = "x-google-flag";
151static const char kValueConference[] = "conference";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000152
153// Candidate
154static const char kCandidateHost[] = "host";
155static const char kCandidateSrflx[] = "srflx";
156// TODO: How to map the prflx with circket candidate type
157// static const char kCandidatePrflx[] = "prflx";
158static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000159static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000160
161static const char kSdpDelimiterEqual = '=';
162static const char kSdpDelimiterSpace = ' ';
163static const char kSdpDelimiterColon = ':';
164static const char kSdpDelimiterSemicolon = ';';
165static const char kSdpDelimiterSlash = '/';
166static const char kNewLine = '\n';
167static const char kReturn = '\r';
168static const char kLineBreak[] = "\r\n";
169
170// TODO: Generate the Session and Time description
171// instead of hardcoding.
172static const char kSessionVersion[] = "v=0";
173// RFC 4566
174static const char kSessionOriginUsername[] = "-";
175static const char kSessionOriginSessionId[] = "0";
176static const char kSessionOriginSessionVersion[] = "0";
177static const char kSessionOriginNettype[] = "IN";
178static const char kSessionOriginAddrtype[] = "IP4";
179static const char kSessionOriginAddress[] = "127.0.0.1";
180static const char kSessionName[] = "s=-";
181static const char kTimeDescription[] = "t=0 0";
182static const char kAttrGroup[] = "a=group:BUNDLE";
183static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000184static const char kConnectionIpv4Addrtype[] = "IP4";
185static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000186static const char kMediaTypeVideo[] = "video";
187static const char kMediaTypeAudio[] = "audio";
188static const char kMediaTypeData[] = "application";
189static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000190// draft-ietf-mmusic-trickle-ice-01
191// When no candidates have been gathered, set the connection
192// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000193// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
194// Use IPV4 per default.
195static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000196static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000197// RFC 3556
198static const char kApplicationSpecificMaximum[] = "AS";
199
200static const int kDefaultVideoClockrate = 90000;
201
202// ISAC special-case.
203static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
204static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
205static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
206
wu@webrtc.org78187522013-10-07 23:32:02 +0000207static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000208
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000209// RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
210// types.
211const int kWildcardPayloadType = -1;
212
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000213struct SsrcInfo {
214 SsrcInfo()
215 : msid_identifier(kDefaultMsid),
216 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
217 // Create random string (which will be used as track label later)?
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000218 msid_appdata(rtc::CreateRandomString(8)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000219 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200220 uint32_t ssrc_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000221 std::string cname;
222 std::string msid_identifier;
223 std::string msid_appdata;
224
225 // For backward compatibility.
226 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
227 std::string label;
228 std::string mslabel;
229};
230typedef std::vector<SsrcInfo> SsrcInfoVec;
231typedef std::vector<SsrcGroup> SsrcGroupVec;
232
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000233template <class T>
234static void AddFmtpLine(const T& codec, std::string* message);
235static void BuildMediaDescription(const ContentInfo* content_info,
236 const TransportInfo* transport_info,
237 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000238 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000239 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000240static void BuildSctpContentAttributes(std::string* message, int sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000241static void BuildRtpContentAttributes(
242 const MediaContentDescription* media_desc,
243 const MediaType media_type,
244 std::string* message);
245static void BuildRtpMap(const MediaContentDescription* media_desc,
246 const MediaType media_type,
247 std::string* message);
248static void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -0800249 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000250 std::string* message);
251static void BuildIceOptions(const std::vector<std::string>& transport_options,
252 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000253static bool IsRtp(const std::string& protocol);
254static bool IsDtlsSctp(const std::string& protocol);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000255static bool ParseSessionDescription(const std::string& message, size_t* pos,
256 std::string* session_id,
257 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258 TransportDescription* session_td,
259 RtpHeaderExtensions* session_extmaps,
260 cricket::SessionDescription* desc,
261 SdpParseError* error);
262static bool ParseGroupAttribute(const std::string& line,
263 cricket::SessionDescription* desc,
264 SdpParseError* error);
265static bool ParseMediaDescription(
266 const std::string& message,
267 const TransportDescription& session_td,
268 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000269 size_t* pos, cricket::SessionDescription* desc,
270 std::vector<JsepIceCandidate*>* candidates,
271 SdpParseError* error);
272static bool ParseContent(const std::string& message,
273 const MediaType media_type,
274 int mline_index,
275 const std::string& protocol,
276 const std::vector<int>& codec_preference,
277 size_t* pos,
278 std::string* content_name,
279 MediaContentDescription* media_desc,
280 TransportDescription* transport,
281 std::vector<JsepIceCandidate*>* candidates,
282 SdpParseError* error);
283static bool ParseSsrcAttribute(const std::string& line,
284 SsrcInfoVec* ssrc_infos,
285 SdpParseError* error);
286static bool ParseSsrcGroupAttribute(const std::string& line,
287 SsrcGroupVec* ssrc_groups,
288 SdpParseError* error);
289static bool ParseCryptoAttribute(const std::string& line,
290 MediaContentDescription* media_desc,
291 SdpParseError* error);
292static bool ParseRtpmapAttribute(const std::string& line,
293 const MediaType media_type,
294 const std::vector<int>& codec_preference,
295 MediaContentDescription* media_desc,
296 SdpParseError* error);
297static bool ParseFmtpAttributes(const std::string& line,
298 const MediaType media_type,
299 MediaContentDescription* media_desc,
300 SdpParseError* error);
301static bool ParseFmtpParam(const std::string& line, std::string* parameter,
302 std::string* value, SdpParseError* error);
303static bool ParseCandidate(const std::string& message, Candidate* candidate,
304 SdpParseError* error, bool is_raw);
305static bool ParseRtcpFbAttribute(const std::string& line,
306 const MediaType media_type,
307 MediaContentDescription* media_desc,
308 SdpParseError* error);
309static bool ParseIceOptions(const std::string& line,
310 std::vector<std::string>* transport_options,
311 SdpParseError* error);
312static bool ParseExtmap(const std::string& line,
313 RtpHeaderExtension* extmap,
314 SdpParseError* error);
315static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000316 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000317 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000318static bool ParseDtlsSetup(const std::string& line,
319 cricket::ConnectionRole* role,
320 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000321
322// Helper functions
323
324// Below ParseFailed*** functions output the line that caused the parsing
325// failure and the detailed reason (|description|) of the failure to |error|.
326// The functions always return false so that they can be used directly in the
327// following way when error happens:
328// "return ParseFailed***(...);"
329
330// The line starting at |line_start| of |message| is the failing line.
331// The reason for the failure should be provided in the |description|.
332// An example of a description could be "unknown character".
333static bool ParseFailed(const std::string& message,
334 size_t line_start,
335 const std::string& description,
336 SdpParseError* error) {
337 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000338 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000339 size_t line_end = message.find(kNewLine, line_start);
340 if (line_end != std::string::npos) {
341 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
342 --line_end;
343 }
344 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000345 } else {
346 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000347 }
348
349 if (error) {
350 error->line = first_line;
351 error->description = description;
352 }
353 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
354 << "\". Reason: " << description;
355 return false;
356}
357
358// |line| is the failing line. The reason for the failure should be
359// provided in the |description|.
360static bool ParseFailed(const std::string& line,
361 const std::string& description,
362 SdpParseError* error) {
363 return ParseFailed(line, 0, description, error);
364}
365
366// Parses failure where the failing SDP line isn't know or there are multiple
367// failing lines.
368static bool ParseFailed(const std::string& description,
369 SdpParseError* error) {
370 return ParseFailed("", description, error);
371}
372
373// |line| is the failing line. The failure is due to the fact that |line|
374// doesn't have |expected_fields| fields.
375static bool ParseFailedExpectFieldNum(const std::string& line,
376 int expected_fields,
377 SdpParseError* error) {
378 std::ostringstream description;
379 description << "Expects " << expected_fields << " fields.";
380 return ParseFailed(line, description.str(), error);
381}
382
383// |line| is the failing line. The failure is due to the fact that |line| has
384// less than |expected_min_fields| fields.
385static bool ParseFailedExpectMinFieldNum(const std::string& line,
386 int expected_min_fields,
387 SdpParseError* error) {
388 std::ostringstream description;
389 description << "Expects at least " << expected_min_fields << " fields.";
390 return ParseFailed(line, description.str(), error);
391}
392
393// |line| is the failing line. The failure is due to the fact that it failed to
394// get the value of |attribute|.
395static bool ParseFailedGetValue(const std::string& line,
396 const std::string& attribute,
397 SdpParseError* error) {
398 std::ostringstream description;
399 description << "Failed to get the value of attribute: " << attribute;
400 return ParseFailed(line, description.str(), error);
401}
402
403// The line starting at |line_start| of |message| is the failing line. The
404// failure is due to the line type (e.g. the "m" part of the "m-line")
405// not matching what is expected. The expected line type should be
406// provided as |line_type|.
407static bool ParseFailedExpectLine(const std::string& message,
408 size_t line_start,
409 const char line_type,
410 const std::string& line_value,
411 SdpParseError* error) {
412 std::ostringstream description;
413 description << "Expect line: " << line_type << "=" << line_value;
414 return ParseFailed(message, line_start, description.str(), error);
415}
416
417static bool AddLine(const std::string& line, std::string* message) {
418 if (!message)
419 return false;
420
421 message->append(line);
422 message->append(kLineBreak);
423 return true;
424}
425
426static bool GetLine(const std::string& message,
427 size_t* pos,
428 std::string* line) {
429 size_t line_begin = *pos;
430 size_t line_end = message.find(kNewLine, line_begin);
431 if (line_end == std::string::npos) {
432 return false;
433 }
434 // Update the new start position
435 *pos = line_end + 1;
436 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
437 --line_end;
438 }
439 *line = message.substr(line_begin, (line_end - line_begin));
440 const char* cline = line->c_str();
441 // RFC 4566
442 // An SDP session description consists of a number of lines of text of
443 // the form:
444 // <type>=<value>
445 // where <type> MUST be exactly one case-significant character and
446 // <value> is structured text whose format depends on <type>.
447 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000448 if (line->length() < 3 ||
449 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000450 cline[1] != kSdpDelimiterEqual ||
451 cline[2] == kSdpDelimiterSpace) {
452 *pos = line_begin;
453 return false;
454 }
455 return true;
456}
457
458// Init |os| to "|type|=|value|".
459static void InitLine(const char type,
460 const std::string& value,
461 std::ostringstream* os) {
462 os->str("");
463 *os << type << kSdpDelimiterEqual << value;
464}
465
466// Init |os| to "a=|attribute|".
467static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
468 InitLine(kLineTypeAttributes, attribute, os);
469}
470
471// Writes a SDP attribute line based on |attribute| and |value| to |message|.
472static void AddAttributeLine(const std::string& attribute, int value,
473 std::string* message) {
474 std::ostringstream os;
475 InitAttrLine(attribute, &os);
476 os << kSdpDelimiterColon << value;
477 AddLine(os.str(), message);
478}
479
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000480static bool IsLineType(const std::string& message,
481 const char type,
482 size_t line_start) {
483 if (message.size() < line_start + kLinePrefixLength) {
484 return false;
485 }
486 const char* cmessage = message.c_str();
487 return (cmessage[line_start] == type &&
488 cmessage[line_start + 1] == kSdpDelimiterEqual);
489}
490
491static bool IsLineType(const std::string& line,
492 const char type) {
493 return IsLineType(line, type, 0);
494}
495
496static bool GetLineWithType(const std::string& message, size_t* pos,
497 std::string* line, const char type) {
498 if (!IsLineType(message, type, *pos)) {
499 return false;
500 }
501
502 if (!GetLine(message, pos, line))
503 return false;
504
505 return true;
506}
507
508static bool HasAttribute(const std::string& line,
509 const std::string& attribute) {
510 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
511}
512
Peter Boström0c4e06b2015-10-07 12:23:21 +0200513static bool AddSsrcLine(uint32_t ssrc_id,
514 const std::string& attribute,
515 const std::string& value,
516 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000517 // RFC 5576
518 // a=ssrc:<ssrc-id> <attribute>:<value>
519 std::ostringstream os;
520 InitAttrLine(kAttributeSsrc, &os);
521 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
522 << attribute << kSdpDelimiterColon << value;
523 return AddLine(os.str(), message);
524}
525
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000526// Get value only from <attribute>:<value>.
527static bool GetValue(const std::string& message, const std::string& attribute,
528 std::string* value, SdpParseError* error) {
529 std::string leftpart;
Donald Curtis0e07f922015-05-15 09:21:23 -0700530 if (!rtc::tokenize_first(message, kSdpDelimiterColon, &leftpart, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000531 return ParseFailedGetValue(message, attribute, error);
532 }
533 // The left part should end with the expected attribute.
534 if (leftpart.length() < attribute.length() ||
535 leftpart.compare(leftpart.length() - attribute.length(),
536 attribute.length(), attribute) != 0) {
537 return ParseFailedGetValue(message, attribute, error);
538 }
539 return true;
540}
541
542static bool CaseInsensitiveFind(std::string str1, std::string str2) {
543 std::transform(str1.begin(), str1.end(), str1.begin(),
544 ::tolower);
545 std::transform(str2.begin(), str2.end(), str2.begin(),
546 ::tolower);
547 return str1.find(str2) != std::string::npos;
548}
549
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000550template <class T>
551static bool GetValueFromString(const std::string& line,
552 const std::string& s,
553 T* t,
554 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000555 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000556 std::ostringstream description;
557 description << "Invalid value: " << s << ".";
558 return ParseFailed(line, description.str(), error);
559 }
560 return true;
561}
562
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000563static bool GetPayloadTypeFromString(const std::string& line,
564 const std::string& s,
565 int* payload_type,
566 SdpParseError* error) {
567 return GetValueFromString(line, s, payload_type, error) &&
568 cricket::IsValidRtpPayloadType(*payload_type);
569}
570
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000571void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
572 StreamParamsVec* tracks) {
573 ASSERT(tracks != NULL);
574 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
575 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
576 if (ssrc_info->cname.empty()) {
577 continue;
578 }
579
580 std::string sync_label;
581 std::string track_id;
582 if (ssrc_info->msid_identifier == kDefaultMsid &&
583 !ssrc_info->mslabel.empty()) {
584 // If there's no msid and there's mslabel, we consider this is a sdp from
585 // a older version of client that doesn't support msid.
586 // In that case, we use the mslabel and label to construct the track.
587 sync_label = ssrc_info->mslabel;
588 track_id = ssrc_info->label;
589 } else {
590 sync_label = ssrc_info->msid_identifier;
591 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
592 // is corresponding to the "id" attribute of StreamParams.
593 track_id = ssrc_info->msid_appdata;
594 }
595 if (sync_label.empty() || track_id.empty()) {
596 ASSERT(false);
597 continue;
598 }
599
600 StreamParamsVec::iterator track = tracks->begin();
601 for (; track != tracks->end(); ++track) {
602 if (track->id == track_id) {
603 break;
604 }
605 }
606 if (track == tracks->end()) {
607 // If we don't find an existing track, create a new one.
608 tracks->push_back(StreamParams());
609 track = tracks->end() - 1;
610 }
611 track->add_ssrc(ssrc_info->ssrc_id);
612 track->cname = ssrc_info->cname;
613 track->sync_label = sync_label;
614 track->id = track_id;
615 }
616}
617
618void GetMediaStreamLabels(const ContentInfo* content,
619 std::set<std::string>* labels) {
620 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000621 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000622 content->description);
623 const cricket::StreamParamsVec& streams = media_desc->streams();
624 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
625 it != streams.end(); ++it) {
626 labels->insert(it->sync_label);
627 }
628}
629
630// RFC 5245
631// It is RECOMMENDED that default candidates be chosen based on the
632// likelihood of those candidates to work with the peer that is being
633// contacted. It is RECOMMENDED that relayed > reflexive > host.
634static const int kPreferenceUnknown = 0;
635static const int kPreferenceHost = 1;
636static const int kPreferenceReflexive = 2;
637static const int kPreferenceRelayed = 3;
638
639static int GetCandidatePreferenceFromType(const std::string& type) {
640 int preference = kPreferenceUnknown;
641 if (type == cricket::LOCAL_PORT_TYPE) {
642 preference = kPreferenceHost;
643 } else if (type == cricket::STUN_PORT_TYPE) {
644 preference = kPreferenceReflexive;
645 } else if (type == cricket::RELAY_PORT_TYPE) {
646 preference = kPreferenceRelayed;
647 } else {
648 ASSERT(false);
649 }
650 return preference;
651}
652
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000653// Get ip and port of the default destination from the |candidates| with the
654// given value of |component_id|. The default candidate should be the one most
655// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000656// RFC 5245
657// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
658// TODO: Decide the default destination in webrtcsession and
659// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000660static void GetDefaultDestination(
661 const std::vector<Candidate>& candidates,
662 int component_id, std::string* port,
663 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000664 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000665 *port = kDummyPort;
666 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000668 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669 for (std::vector<Candidate>::const_iterator it = candidates.begin();
670 it != candidates.end(); ++it) {
671 if (it->component() != component_id) {
672 continue;
673 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000674 // Default destination should be UDP only.
675 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676 continue;
677 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000678 const int preference = GetCandidatePreferenceFromType(it->type());
679 const int family = it->address().ipaddr().family();
680 // See if this candidate is more preferable then the current one if it's the
681 // same family. Or if the current family is IPv4 already so we could safely
682 // ignore all IPv6 ones. WebRTC bug 4269.
683 // http://code.google.com/p/webrtc/issues/detail?id=4269
684 if ((preference <= current_preference && current_family == family) ||
685 (current_family == AF_INET && family == AF_INET6)) {
686 continue;
687 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000688 if (family == AF_INET) {
689 addr_type->assign(kConnectionIpv4Addrtype);
690 } else if (family == AF_INET6) {
691 addr_type->assign(kConnectionIpv6Addrtype);
692 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000693 current_preference = preference;
694 current_family = family;
695 *port = it->address().PortAsString();
696 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000697 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000698}
699
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000700// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000701static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000702 const std::vector<Candidate>& candidates,
jbauch083b73f2015-07-16 02:46:32 -0700703 const std::string& mline,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000704 std::string* message) {
705 std::string new_lines;
706 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707 // RFC 4566
708 // m=<media> <port> <proto> <fmt> ...
709 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000710 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000711 if (fields.size() < 3) {
712 return;
713 }
714
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000715 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000716 std::string rtp_port, rtp_ip, addr_type;
717 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
718 &rtp_port, &rtp_ip, &addr_type);
719 // Found default RTP candidate.
720 // RFC 5245
721 // The default candidates are added to the SDP as the default
722 // destination for media. For streams based on RTP, this is done by
723 // placing the IP address and port of the RTP candidate into the c and m
724 // lines, respectively.
725 // Update the port in the m line.
726 // If this is a m-line with port equal to 0, we don't change it.
727 if (fields[1] != kMediaPortRejected) {
728 new_lines.replace(fields[0].size() + 1,
729 fields[1].size(),
730 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000732 // Add the c line.
733 // RFC 4566
734 // c=<nettype> <addrtype> <connection-address>
735 InitLine(kLineTypeConnection, kConnectionNettype, &os);
736 os << " " << addr_type << " " << rtp_ip;
737 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000738 message->append(new_lines);
739}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000741// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
742static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000743 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
744 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
745 &rtcp_port, &rtcp_ip, &addr_type);
746 // Found default RTCP candidate.
747 // RFC 5245
748 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
749 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000750
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000751 // RFC 3605
752 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
753 // connection-address] CRLF
754 std::ostringstream os;
755 InitAttrLine(kAttributeRtcp, &os);
756 os << kSdpDelimiterColon
757 << rtcp_port << " "
758 << kConnectionNettype << " "
759 << addr_type << " "
760 << rtcp_ip;
761 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000762 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000763}
764
765// Get candidates according to the mline index from SessionDescriptionInterface.
766static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
767 int mline_index,
768 std::vector<Candidate>* candidates) {
769 if (!candidates) {
770 return;
771 }
772 const IceCandidateCollection* cc = desci.candidates(mline_index);
773 for (size_t i = 0; i < cc->count(); ++i) {
774 const IceCandidateInterface* candidate = cc->at(i);
775 candidates->push_back(candidate->candidate());
776 }
777}
778
779std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000780 const cricket::SessionDescription* desc = jdesc.description();
781 if (!desc) {
782 return "";
783 }
784
785 std::string message;
786
787 // Session Description.
788 AddLine(kSessionVersion, &message);
789 // Session Origin
790 // RFC 4566
791 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
792 // <unicast-address>
793 std::ostringstream os;
794 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
jbauch083b73f2015-07-16 02:46:32 -0700795 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700797 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000798 kSessionOriginSessionVersion : jdesc.session_version();
799 os << " " << session_id << " " << session_version << " "
800 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
801 << kSessionOriginAddress;
802 AddLine(os.str(), &message);
803 AddLine(kSessionName, &message);
804
805 // Time Description.
806 AddLine(kTimeDescription, &message);
807
808 // Group
809 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
810 std::string group_line = kAttrGroup;
811 const cricket::ContentGroup* group =
812 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
813 ASSERT(group != NULL);
814 const cricket::ContentNames& content_names = group->content_names();
815 for (cricket::ContentNames::const_iterator it = content_names.begin();
816 it != content_names.end(); ++it) {
817 group_line.append(" ");
818 group_line.append(*it);
819 }
820 AddLine(group_line, &message);
821 }
822
823 // MediaStream semantics
824 InitAttrLine(kAttributeMsidSemantics, &os);
825 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000826
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827 std::set<std::string> media_stream_labels;
828 const ContentInfo* audio_content = GetFirstAudioContent(desc);
829 if (audio_content)
830 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000831
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832 const ContentInfo* video_content = GetFirstVideoContent(desc);
833 if (video_content)
834 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000835
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000836 for (std::set<std::string>::const_iterator it =
837 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
838 os << " " << *it;
839 }
840 AddLine(os.str(), &message);
841
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000842 // Preserve the order of the media contents.
843 int mline_index = -1;
844 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
845 it != desc->contents().end(); ++it) {
846 const MediaContentDescription* mdesc =
847 static_cast<const MediaContentDescription*>(it->description);
848 std::vector<Candidate> candidates;
849 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
850 BuildMediaDescription(&*it,
851 desc->GetTransportInfoByName(it->name),
852 mdesc->type(),
853 candidates,
854 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000855 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000856 return message;
857}
858
859// Serializes the passed in IceCandidateInterface to a SDP string.
860// candidate - The candidate to be serialized.
861std::string SdpSerializeCandidate(
862 const IceCandidateInterface& candidate) {
863 std::string message;
864 std::vector<cricket::Candidate> candidates;
865 candidates.push_back(candidate.candidate());
honghaiza54a0802015-12-16 18:37:23 -0800866 BuildCandidate(candidates, true, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000867 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
868 // just candidate:<candidate> not a=candidate:<blah>CRLF
869 ASSERT(message.find("a=") == 0);
870 message.erase(0, 2);
871 ASSERT(message.find(kLineBreak) == message.size() - 2);
872 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000873 return message;
874}
875
876bool SdpDeserialize(const std::string& message,
877 JsepSessionDescription* jdesc,
878 SdpParseError* error) {
879 std::string session_id;
880 std::string session_version;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700881 TransportDescription session_td("", "");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000882 RtpHeaderExtensions session_extmaps;
883 cricket::SessionDescription* desc = new cricket::SessionDescription();
884 std::vector<JsepIceCandidate*> candidates;
885 size_t current_pos = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886
887 // Session Description
888 if (!ParseSessionDescription(message, &current_pos, &session_id,
deadbeefc80741f2015-10-22 13:14:45 -0700889 &session_version, &session_td, &session_extmaps,
890 desc, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000891 delete desc;
892 return false;
893 }
894
895 // Media Description
deadbeefc80741f2015-10-22 13:14:45 -0700896 if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
897 desc, &candidates, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000898 delete desc;
899 for (std::vector<JsepIceCandidate*>::const_iterator
900 it = candidates.begin(); it != candidates.end(); ++it) {
901 delete *it;
902 }
903 return false;
904 }
905
906 jdesc->Initialize(desc, session_id, session_version);
907
908 for (std::vector<JsepIceCandidate*>::const_iterator
909 it = candidates.begin(); it != candidates.end(); ++it) {
910 jdesc->AddCandidate(*it);
911 delete *it;
912 }
913 return true;
914}
915
916bool SdpDeserializeCandidate(const std::string& message,
917 JsepIceCandidate* jcandidate,
918 SdpParseError* error) {
919 ASSERT(jcandidate != NULL);
920 Candidate candidate;
921 if (!ParseCandidate(message, &candidate, error, true)) {
922 return false;
923 }
924 jcandidate->SetCandidate(candidate);
925 return true;
926}
927
928bool ParseCandidate(const std::string& message, Candidate* candidate,
929 SdpParseError* error, bool is_raw) {
930 ASSERT(candidate != NULL);
931
932 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000933 std::string first_line = message;
934 size_t pos = 0;
935 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000937 // Makes sure |message| contains only one line.
938 if (message.size() > first_line.size()) {
939 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700940 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
941 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000942 return ParseFailed(message, 0, "Expect one line only", error);
943 }
944 }
945
946 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
947 // candidate:<candidate> when trickled, but we still support
948 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
949 // from the SDP.
950 if (IsLineType(first_line, kLineTypeAttributes)) {
951 first_line = first_line.substr(kLinePrefixLength);
952 }
953
954 std::string attribute_candidate;
955 std::string candidate_value;
956
957 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700958 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
959 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000960 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000961 if (is_raw) {
962 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000963 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000964 << ":" << "<candidate-str>";
965 return ParseFailed(first_line, 0, description.str(), error);
966 } else {
967 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
968 kAttributeCandidate, error);
969 }
970 }
971
972 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000973 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
974
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000975 // RFC 5245
976 // a=candidate:<foundation> <component-id> <transport> <priority>
977 // <connection-address> <port> typ <candidate-types>
978 // [raddr <connection-address>] [rport <port>]
979 // *(SP extension-att-name SP extension-att-value)
980 const size_t expected_min_fields = 8;
981 if (fields.size() < expected_min_fields ||
982 (fields[6] != kAttributeCandidateTyp)) {
983 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
984 }
jbauch083b73f2015-07-16 02:46:32 -0700985 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000986
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000987 int component_id = 0;
988 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
989 return false;
990 }
jbauch083b73f2015-07-16 02:46:32 -0700991 const std::string& transport = fields[2];
Peter Boström0c4e06b2015-10-07 12:23:21 +0200992 uint32_t priority = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000993 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
994 return false;
995 }
jbauch083b73f2015-07-16 02:46:32 -0700996 const std::string& connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000997 int port = 0;
998 if (!GetValueFromString(first_line, fields[5], &port, error)) {
999 return false;
1000 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001 SocketAddress address(connection_address, port);
1002
1003 cricket::ProtocolType protocol;
1004 if (!StringToProto(transport.c_str(), &protocol)) {
1005 return ParseFailed(first_line, "Unsupported transport type.", error);
1006 }
1007
1008 std::string candidate_type;
jbauch083b73f2015-07-16 02:46:32 -07001009 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001010 if (type == kCandidateHost) {
1011 candidate_type = cricket::LOCAL_PORT_TYPE;
1012 } else if (type == kCandidateSrflx) {
1013 candidate_type = cricket::STUN_PORT_TYPE;
1014 } else if (type == kCandidateRelay) {
1015 candidate_type = cricket::RELAY_PORT_TYPE;
1016 } else {
1017 return ParseFailed(first_line, "Unsupported candidate type.", error);
1018 }
1019
1020 size_t current_position = expected_min_fields;
1021 SocketAddress related_address;
1022 // The 2 optional fields for related address
1023 // [raddr <connection-address>] [rport <port>]
1024 if (fields.size() >= (current_position + 2) &&
1025 fields[current_position] == kAttributeCandidateRaddr) {
1026 related_address.SetIP(fields[++current_position]);
1027 ++current_position;
1028 }
1029 if (fields.size() >= (current_position + 2) &&
1030 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001031 int port = 0;
1032 if (!GetValueFromString(
1033 first_line, fields[++current_position], &port, error)) {
1034 return false;
1035 }
1036 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037 ++current_position;
1038 }
1039
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001040 // If this is a TCP candidate, it has additional extension as defined in
1041 // RFC 6544.
1042 std::string tcptype;
1043 if (fields.size() >= (current_position + 2) &&
1044 fields[current_position] == kTcpCandidateType) {
1045 tcptype = fields[++current_position];
1046 ++current_position;
1047
1048 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1049 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1050 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1051 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1052 }
1053
1054 if (protocol != cricket::PROTO_TCP) {
1055 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1056 }
1057 }
1058
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059 // Extension
honghaiza54a0802015-12-16 18:37:23 -08001060 // Though non-standard, we support the ICE ufrag and pwd being signaled on
1061 // the candidate to avoid issues with confusing which generation a candidate
1062 // belongs to when trickling multiple generations at the same time.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001063 std::string username;
1064 std::string password;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001065 uint32_t generation = 0;
honghaize1a0c942016-02-16 14:54:56 -08001066 uint32_t network_cost = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001067 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1068 // RFC 5245
1069 // *(SP extension-att-name SP extension-att-value)
1070 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001071 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1072 return false;
1073 }
honghaiza54a0802015-12-16 18:37:23 -08001074 } else if (fields[i] == kAttributeCandidateUfrag) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001075 username = fields[++i];
honghaiza54a0802015-12-16 18:37:23 -08001076 } else if (fields[i] == kAttributeCandidatePwd) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001077 password = fields[++i];
honghaize1a0c942016-02-16 14:54:56 -08001078 } else if (fields[i] == kAttributeCandidateNetworkCost) {
1079 if (!GetValueFromString(first_line, fields[++i], &network_cost, error)) {
1080 return false;
1081 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082 } else {
1083 // Skip the unknown extension.
1084 ++i;
1085 }
1086 }
1087
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001088 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001089 address, priority, username, password, candidate_type,
1090 generation, foundation);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001092 candidate->set_tcptype(tcptype);
honghaize1a0c942016-02-16 14:54:56 -08001093 candidate->set_network_cost(std::min(network_cost, cricket::kMaxNetworkCost));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001094 return true;
1095}
1096
1097bool ParseIceOptions(const std::string& line,
1098 std::vector<std::string>* transport_options,
1099 SdpParseError* error) {
1100 std::string ice_options;
1101 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1102 return false;
1103 }
1104 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001105 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001106 for (size_t i = 0; i < fields.size(); ++i) {
1107 transport_options->push_back(fields[i]);
1108 }
1109 return true;
1110}
1111
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001112bool ParseSctpPort(const std::string& line,
1113 int* sctp_port,
1114 SdpParseError* error) {
1115 // draft-ietf-mmusic-sctp-sdp-07
1116 // a=sctp-port
1117 std::vector<std::string> fields;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001118 const size_t expected_min_fields = 2;
lally69f57602015-10-08 10:15:04 -07001119 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1120 if (fields.size() < expected_min_fields) {
1121 fields.resize(0);
1122 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpace, &fields);
1123 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001124 if (fields.size() < expected_min_fields) {
1125 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1126 }
1127 if (!rtc::FromString(fields[1], sctp_port)) {
lally69f57602015-10-08 10:15:04 -07001128 return ParseFailed(line, "Invalid sctp port value.", error);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001129 }
1130 return true;
1131}
1132
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001133bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1134 SdpParseError* error) {
1135 // RFC 5285
1136 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1137 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001138 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001139 kSdpDelimiterSpace, &fields);
1140 const size_t expected_min_fields = 2;
1141 if (fields.size() < expected_min_fields) {
1142 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1143 }
1144 std::string uri = fields[1];
1145
1146 std::string value_direction;
1147 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1148 return false;
1149 }
1150 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001151 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001152 int value = 0;
1153 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1154 return false;
1155 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001156
1157 *extmap = RtpHeaderExtension(uri, value);
1158 return true;
1159}
1160
1161void BuildMediaDescription(const ContentInfo* content_info,
1162 const TransportInfo* transport_info,
1163 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001164 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165 std::string* message) {
1166 ASSERT(message != NULL);
1167 if (content_info == NULL || message == NULL) {
1168 return;
1169 }
1170 // TODO: Rethink if we should use sprintfn instead of stringstream.
1171 // According to the style guide, streams should only be used for logging.
1172 // http://google-styleguide.googlecode.com/svn/
1173 // trunk/cppguide.xml?showone=Streams#Streams
1174 std::ostringstream os;
1175 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001176 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001177 content_info->description);
1178 ASSERT(media_desc != NULL);
1179
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001180 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001181
1182 // RFC 4566
1183 // m=<media> <port> <proto> <fmt>
1184 // fmt is a list of payload type numbers that MAY be used in the session.
1185 const char* type = NULL;
1186 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1187 type = kMediaTypeAudio;
1188 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1189 type = kMediaTypeVideo;
1190 else if (media_type == cricket::MEDIA_TYPE_DATA)
1191 type = kMediaTypeData;
1192 else
1193 ASSERT(false);
1194
1195 std::string fmt;
1196 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1197 const VideoContentDescription* video_desc =
1198 static_cast<const VideoContentDescription*>(media_desc);
1199 for (std::vector<cricket::VideoCodec>::const_iterator it =
1200 video_desc->codecs().begin();
1201 it != video_desc->codecs().end(); ++it) {
1202 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001203 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001204 }
1205 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1206 const AudioContentDescription* audio_desc =
1207 static_cast<const AudioContentDescription*>(media_desc);
1208 for (std::vector<cricket::AudioCodec>::const_iterator it =
1209 audio_desc->codecs().begin();
1210 it != audio_desc->codecs().end(); ++it) {
1211 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001212 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001213 }
1214 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001215 const DataContentDescription* data_desc =
1216 static_cast<const DataContentDescription*>(media_desc);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001217 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001218 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001219
1220 for (std::vector<cricket::DataCodec>::const_iterator it =
1221 data_desc->codecs().begin();
1222 it != data_desc->codecs().end(); ++it) {
1223 if (it->id == cricket::kGoogleSctpDataCodecId &&
1224 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1225 break;
1226 }
1227 }
1228
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001229 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001230 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001231 for (std::vector<cricket::DataCodec>::const_iterator it =
1232 data_desc->codecs().begin();
1233 it != data_desc->codecs().end(); ++it) {
1234 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001235 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001236 }
1237 }
1238 }
1239 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1240 // to 0.
1241 if (fmt.empty()) {
1242 fmt = " 0";
1243 }
1244
1245 // The port number in the m line will be updated later when associate with
1246 // the candidates.
1247 // RFC 3264
1248 // To reject an offered stream, the port number in the corresponding stream in
1249 // the answer MUST be set to zero.
jbauch083b73f2015-07-16 02:46:32 -07001250 const std::string& port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001251 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001252
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001253 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001254 transport_info->description.identity_fingerprint.get() : NULL;
1255
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001256 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001257 InitLine(kLineTypeMedia, type, &os);
1258 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001259 std::string mline = os.str();
1260 UpdateMediaDefaultDestination(candidates, mline, message);
1261
1262 // RFC 4566
1263 // b=AS:<bandwidth>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001264 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001265 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1266 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1267 AddLine(os.str(), message);
1268 }
1269
1270 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001271 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001272 std::string rtcp_line = GetRtcpLine(candidates);
1273 if (!rtcp_line.empty()) {
1274 AddLine(rtcp_line, message);
1275 }
1276 }
1277
honghaiza54a0802015-12-16 18:37:23 -08001278 // Build the a=candidate lines. We don't include ufrag and pwd in the
1279 // candidates in the SDP to avoid redundancy.
1280 BuildCandidate(candidates, false, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001281
1282 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1283 if (transport_info) {
1284 // RFC 5245
1285 // ice-pwd-att = "ice-pwd" ":" password
1286 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1287 // ice-ufrag
deadbeef3f7219b2015-12-28 15:17:14 -08001288 if (!transport_info->description.ice_ufrag.empty()) {
1289 InitAttrLine(kAttributeIceUfrag, &os);
1290 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1291 AddLine(os.str(), message);
1292 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293 // ice-pwd
deadbeef3f7219b2015-12-28 15:17:14 -08001294 if (!transport_info->description.ice_pwd.empty()) {
1295 InitAttrLine(kAttributeIcePwd, &os);
1296 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1297 AddLine(os.str(), message);
1298 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299
1300 // draft-petithuguenin-mmusic-ice-attributes-level-03
1301 BuildIceOptions(transport_info->description.transport_options, message);
1302
1303 // RFC 4572
1304 // fingerprint-attribute =
1305 // "fingerprint" ":" hash-func SP fingerprint
1306 if (fp) {
1307 // Insert the fingerprint attribute.
1308 InitAttrLine(kAttributeFingerprint, &os);
1309 os << kSdpDelimiterColon
1310 << fp->algorithm << kSdpDelimiterSpace
1311 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001313
1314 // Inserting setup attribute.
1315 if (transport_info->description.connection_role !=
1316 cricket::CONNECTIONROLE_NONE) {
1317 // Making sure we are not using "passive" mode.
1318 cricket::ConnectionRole role =
1319 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001320 std::string dtls_role_str;
1321 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001322 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001323 os << kSdpDelimiterColon << dtls_role_str;
1324 AddLine(os.str(), message);
1325 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326 }
1327 }
1328
1329 // RFC 3388
1330 // mid-attribute = "a=mid:" identification-tag
1331 // identification-tag = token
1332 // Use the content name as the mid identification-tag.
1333 InitAttrLine(kAttributeMid, &os);
1334 os << kSdpDelimiterColon << content_info->name;
1335 AddLine(os.str(), message);
1336
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001337 if (IsDtlsSctp(media_desc->protocol())) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001338 BuildSctpContentAttributes(message, sctp_port);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001339 } else if (IsRtp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001340 BuildRtpContentAttributes(media_desc, media_type, message);
1341 }
1342}
1343
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001344void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001345 // draft-ietf-mmusic-sctp-sdp-04
1346 // a=sctpmap:sctpmap-number protocol [streams]
lally69f57602015-10-08 10:15:04 -07001347 // TODO(lally): switch this over to mmusic-sctp-sdp-12 (or later), with
1348 // 'a=sctp-port:'
wu@webrtc.org78187522013-10-07 23:32:02 +00001349 std::ostringstream os;
1350 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001351 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001352 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1353 << (cricket::kMaxSctpSid + 1);
1354 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001355}
1356
1357void BuildRtpContentAttributes(
1358 const MediaContentDescription* media_desc,
1359 const MediaType media_type,
1360 std::string* message) {
1361 std::ostringstream os;
1362 // RFC 5285
1363 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1364 // The definitions MUST be either all session level or all media level. This
1365 // implementation uses all media level.
1366 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1367 InitAttrLine(kAttributeExtmap, &os);
1368 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1369 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1370 AddLine(os.str(), message);
1371 }
1372
1373 // RFC 3264
1374 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
deadbeefc80741f2015-10-22 13:14:45 -07001375 switch (media_desc->direction()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376 case cricket::MD_INACTIVE:
1377 InitAttrLine(kAttributeInactive, &os);
1378 break;
1379 case cricket::MD_SENDONLY:
1380 InitAttrLine(kAttributeSendOnly, &os);
1381 break;
1382 case cricket::MD_RECVONLY:
1383 InitAttrLine(kAttributeRecvOnly, &os);
1384 break;
1385 case cricket::MD_SENDRECV:
1386 default:
1387 InitAttrLine(kAttributeSendRecv, &os);
1388 break;
1389 }
1390 AddLine(os.str(), message);
1391
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 // RFC 5761
1393 // a=rtcp-mux
1394 if (media_desc->rtcp_mux()) {
1395 InitAttrLine(kAttributeRtcpMux, &os);
1396 AddLine(os.str(), message);
1397 }
1398
deadbeef13871492015-12-09 12:37:51 -08001399 // RFC 5506
1400 // a=rtcp-rsize
1401 if (media_desc->rtcp_reduced_size()) {
1402 InitAttrLine(kAttributeRtcpReducedSize, &os);
1403 AddLine(os.str(), message);
1404 }
1405
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001406 // RFC 4568
1407 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1408 for (std::vector<CryptoParams>::const_iterator it =
1409 media_desc->cryptos().begin();
1410 it != media_desc->cryptos().end(); ++it) {
1411 InitAttrLine(kAttributeCrypto, &os);
1412 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1413 << it->key_params;
1414 if (!it->session_params.empty()) {
1415 os << " " << it->session_params;
1416 }
1417 AddLine(os.str(), message);
1418 }
1419
1420 // RFC 4566
1421 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1422 // [/<encodingparameters>]
1423 BuildRtpMap(media_desc, media_type, message);
1424
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001425 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1426 track != media_desc->streams().end(); ++track) {
1427 // Require that the track belongs to a media stream,
1428 // ie the sync_label is set. This extra check is necessary since the
1429 // MediaContentDescription always contains a streamparam with an ssrc even
1430 // if no track or media stream have been created.
1431 if (track->sync_label.empty()) continue;
1432
1433 // Build the ssrc-group lines.
1434 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1435 // RFC 5576
1436 // a=ssrc-group:<semantics> <ssrc-id> ...
1437 if (track->ssrc_groups[i].ssrcs.empty()) {
1438 continue;
1439 }
1440 std::ostringstream os;
1441 InitAttrLine(kAttributeSsrcGroup, &os);
1442 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001443 std::vector<uint32_t>::const_iterator ssrc =
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444 track->ssrc_groups[i].ssrcs.begin();
1445 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001446 os << kSdpDelimiterSpace << rtc::ToString<uint32_t>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001447 }
1448 AddLine(os.str(), message);
1449 }
1450 // Build the ssrc lines for each ssrc.
1451 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001452 uint32_t ssrc = track->ssrcs[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001453 // RFC 5576
1454 // a=ssrc:<ssrc-id> cname:<value>
1455 AddSsrcLine(ssrc, kSsrcAttributeCname,
1456 track->cname, message);
1457
1458 // draft-alvestrand-mmusic-msid-00
1459 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1460 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1461 // is corresponding to the "name" attribute of StreamParams.
1462 std::string appdata = track->id;
1463 std::ostringstream os;
1464 InitAttrLine(kAttributeSsrc, &os);
1465 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1466 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1467 << kSdpDelimiterSpace << appdata;
1468 AddLine(os.str(), message);
1469
1470 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1471 // draft-alvestrand-rtcweb-mid-01
1472 // a=ssrc:<ssrc-id> mslabel:<value>
1473 // The label isn't yet defined.
1474 // a=ssrc:<ssrc-id> label:<value>
1475 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1476 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1477 }
1478 }
1479}
1480
1481void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1482 // fmtp header: a=fmtp:|payload_type| <parameters>
1483 // Add a=fmtp
1484 InitAttrLine(kAttributeFmtp, os);
1485 // Add :|payload_type|
1486 *os << kSdpDelimiterColon << payload_type;
1487}
1488
1489void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1490 // rtcp-fb header: a=rtcp-fb:|payload_type|
1491 // <parameters>/<ccm <ccm_parameters>>
1492 // Add a=rtcp-fb
1493 InitAttrLine(kAttributeRtcpFb, os);
1494 // Add :
1495 *os << kSdpDelimiterColon;
1496 if (payload_type == kWildcardPayloadType) {
1497 *os << "*";
1498 } else {
1499 *os << payload_type;
1500 }
1501}
1502
1503void WriteFmtpParameter(const std::string& parameter_name,
1504 const std::string& parameter_value,
1505 std::ostringstream* os) {
1506 // fmtp parameters: |parameter_name|=|parameter_value|
1507 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1508}
1509
1510void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1511 std::ostringstream* os) {
1512 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1513 fmtp != parameters.end(); ++fmtp) {
1514 // Each new parameter, except the first one starts with ";" and " ".
1515 if (fmtp != parameters.begin()) {
1516 *os << kSdpDelimiterSemicolon;
1517 }
1518 *os << kSdpDelimiterSpace;
1519 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1520 }
1521}
1522
1523bool IsFmtpParam(const std::string& name) {
1524 const char* kFmtpParams[] = {
1525 kCodecParamMinPTime, kCodecParamSPropStereo,
Minyue Li7100dcd2015-03-27 05:05:59 +01001526 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamUseDtx,
1527 kCodecParamStartBitrate, kCodecParamMaxBitrate, kCodecParamMinBitrate,
1528 kCodecParamMaxQuantization, kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001529 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1530 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001531 };
tfarina5237aaf2015-11-10 23:44:30 -08001532 for (size_t i = 0; i < arraysize(kFmtpParams); ++i) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1534 return true;
1535 }
1536 }
1537 return false;
1538}
1539
1540// Retreives fmtp parameters from |params|, which may contain other parameters
1541// as well, and puts them in |fmtp_parameters|.
1542void GetFmtpParams(const cricket::CodecParameterMap& params,
1543 cricket::CodecParameterMap* fmtp_parameters) {
1544 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1545 iter != params.end(); ++iter) {
1546 if (IsFmtpParam(iter->first)) {
1547 (*fmtp_parameters)[iter->first] = iter->second;
1548 }
1549 }
1550}
1551
1552template <class T>
1553void AddFmtpLine(const T& codec, std::string* message) {
1554 cricket::CodecParameterMap fmtp_parameters;
1555 GetFmtpParams(codec.params, &fmtp_parameters);
1556 if (fmtp_parameters.empty()) {
1557 // No need to add an fmtp if it will have no (optional) parameters.
1558 return;
1559 }
1560 std::ostringstream os;
1561 WriteFmtpHeader(codec.id, &os);
1562 WriteFmtpParameters(fmtp_parameters, &os);
1563 AddLine(os.str(), message);
1564 return;
1565}
1566
1567template <class T>
1568void AddRtcpFbLines(const T& codec, std::string* message) {
1569 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1570 codec.feedback_params.params().begin();
1571 iter != codec.feedback_params.params().end(); ++iter) {
1572 std::ostringstream os;
1573 WriteRtcpFbHeader(codec.id, &os);
1574 os << " " << iter->id();
1575 if (!iter->param().empty()) {
1576 os << " " << iter->param();
1577 }
1578 AddLine(os.str(), message);
1579 }
1580}
1581
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001582bool AddSctpDataCodec(DataContentDescription* media_desc,
1583 int sctp_port) {
1584 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1585 return ParseFailed("",
1586 "Can't have multiple sctp port attributes.",
1587 NULL);
1588 }
1589 // Add the SCTP Port number as a pseudo-codec "port" parameter
1590 cricket::DataCodec codec_port(
1591 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1592 0);
1593 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1594 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1595 << sctp_port;
1596 media_desc->AddCodec(codec_port);
1597 return true;
1598}
1599
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001600bool GetMinValue(const std::vector<int>& values, int* value) {
1601 if (values.empty()) {
1602 return false;
1603 }
1604 std::vector<int>::const_iterator found =
1605 std::min_element(values.begin(), values.end());
1606 *value = *found;
1607 return true;
1608}
1609
1610bool GetParameter(const std::string& name,
1611 const cricket::CodecParameterMap& params, int* value) {
1612 std::map<std::string, std::string>::const_iterator found =
1613 params.find(name);
1614 if (found == params.end()) {
1615 return false;
1616 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001617 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001618 return false;
1619 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001620 return true;
1621}
1622
1623void BuildRtpMap(const MediaContentDescription* media_desc,
1624 const MediaType media_type,
1625 std::string* message) {
1626 ASSERT(message != NULL);
1627 ASSERT(media_desc != NULL);
1628 std::ostringstream os;
1629 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1630 const VideoContentDescription* video_desc =
1631 static_cast<const VideoContentDescription*>(media_desc);
1632 for (std::vector<cricket::VideoCodec>::const_iterator it =
1633 video_desc->codecs().begin();
1634 it != video_desc->codecs().end(); ++it) {
1635 // RFC 4566
1636 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1637 // [/<encodingparameters>]
1638 if (it->id != kWildcardPayloadType) {
1639 InitAttrLine(kAttributeRtpmap, &os);
1640 os << kSdpDelimiterColon << it->id << " " << it->name
1641 << "/" << kDefaultVideoClockrate;
1642 AddLine(os.str(), message);
1643 }
1644 AddRtcpFbLines(*it, message);
1645 AddFmtpLine(*it, message);
1646 }
1647 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1648 const AudioContentDescription* audio_desc =
1649 static_cast<const AudioContentDescription*>(media_desc);
1650 std::vector<int> ptimes;
1651 std::vector<int> maxptimes;
1652 int max_minptime = 0;
1653 for (std::vector<cricket::AudioCodec>::const_iterator it =
1654 audio_desc->codecs().begin();
1655 it != audio_desc->codecs().end(); ++it) {
1656 ASSERT(!it->name.empty());
1657 // RFC 4566
1658 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1659 // [/<encodingparameters>]
1660 InitAttrLine(kAttributeRtpmap, &os);
1661 os << kSdpDelimiterColon << it->id << " ";
1662 os << it->name << "/" << it->clockrate;
1663 if (it->channels != 1) {
1664 os << "/" << it->channels;
1665 }
1666 AddLine(os.str(), message);
1667 AddRtcpFbLines(*it, message);
1668 AddFmtpLine(*it, message);
1669 int minptime = 0;
1670 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1671 max_minptime = std::max(minptime, max_minptime);
1672 }
1673 int ptime;
1674 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1675 ptimes.push_back(ptime);
1676 }
1677 int maxptime;
1678 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1679 maxptimes.push_back(maxptime);
1680 }
1681 }
1682 // Populate the maxptime attribute with the smallest maxptime of all codecs
1683 // under the same m-line.
1684 int min_maxptime = INT_MAX;
1685 if (GetMinValue(maxptimes, &min_maxptime)) {
1686 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1687 }
1688 ASSERT(min_maxptime > max_minptime);
1689 // Populate the ptime attribute with the smallest ptime or the largest
1690 // minptime, whichever is the largest, for all codecs under the same m-line.
1691 int ptime = INT_MAX;
1692 if (GetMinValue(ptimes, &ptime)) {
1693 ptime = std::min(ptime, min_maxptime);
1694 ptime = std::max(ptime, max_minptime);
1695 AddAttributeLine(kCodecParamPTime, ptime, message);
1696 }
1697 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1698 const DataContentDescription* data_desc =
1699 static_cast<const DataContentDescription*>(media_desc);
1700 for (std::vector<cricket::DataCodec>::const_iterator it =
1701 data_desc->codecs().begin();
1702 it != data_desc->codecs().end(); ++it) {
1703 // RFC 4566
1704 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1705 // [/<encodingparameters>]
1706 InitAttrLine(kAttributeRtpmap, &os);
1707 os << kSdpDelimiterColon << it->id << " "
1708 << it->name << "/" << it->clockrate;
1709 AddLine(os.str(), message);
1710 }
1711 }
1712}
1713
1714void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -08001715 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716 std::string* message) {
1717 std::ostringstream os;
1718
1719 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1720 it != candidates.end(); ++it) {
1721 // RFC 5245
1722 // a=candidate:<foundation> <component-id> <transport> <priority>
1723 // <connection-address> <port> typ <candidate-types>
1724 // [raddr <connection-address>] [rport <port>]
1725 // *(SP extension-att-name SP extension-att-value)
1726 std::string type;
1727 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1728 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1729 type = kCandidateHost;
1730 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1731 type = kCandidateSrflx;
1732 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1733 type = kCandidateRelay;
1734 } else {
1735 ASSERT(false);
Peter Thatcher019087f2015-04-28 09:06:26 -07001736 // Never write out candidates if we don't know the type.
1737 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001738 }
1739
1740 InitAttrLine(kAttributeCandidate, &os);
1741 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001742 << it->foundation() << " "
1743 << it->component() << " "
1744 << it->protocol() << " "
1745 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001746 << it->address().ipaddr().ToString() << " "
1747 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001748 << kAttributeCandidateTyp << " "
1749 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001750
1751 // Related address
1752 if (!it->related_address().IsNil()) {
1753 os << kAttributeCandidateRaddr << " "
1754 << it->related_address().ipaddr().ToString() << " "
1755 << kAttributeCandidateRport << " "
1756 << it->related_address().PortAsString() << " ";
1757 }
1758
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001759 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001760 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001761 }
1762
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001763 // Extensions
1764 os << kAttributeCandidateGeneration << " " << it->generation();
honghaiza54a0802015-12-16 18:37:23 -08001765 if (include_ufrag && !it->username().empty()) {
1766 os << " " << kAttributeCandidateUfrag << " " << it->username();
1767 }
honghaize1a0c942016-02-16 14:54:56 -08001768 if (it->network_cost() > 0) {
1769 os << " " << kAttributeCandidateNetworkCost << " " << it->network_cost();
1770 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001771
1772 AddLine(os.str(), message);
1773 }
1774}
1775
1776void BuildIceOptions(const std::vector<std::string>& transport_options,
1777 std::string* message) {
1778 if (!transport_options.empty()) {
1779 std::ostringstream os;
1780 InitAttrLine(kAttributeIceOption, &os);
1781 os << kSdpDelimiterColon << transport_options[0];
1782 for (size_t i = 1; i < transport_options.size(); ++i) {
1783 os << kSdpDelimiterSpace << transport_options[i];
1784 }
1785 AddLine(os.str(), message);
1786 }
1787}
1788
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001789bool IsRtp(const std::string& protocol) {
1790 return protocol.empty() ||
1791 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1792}
1793
1794bool IsDtlsSctp(const std::string& protocol) {
1795 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001796 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001797}
1798
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001799bool ParseSessionDescription(const std::string& message, size_t* pos,
1800 std::string* session_id,
1801 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001802 TransportDescription* session_td,
1803 RtpHeaderExtensions* session_extmaps,
1804 cricket::SessionDescription* desc,
1805 SdpParseError* error) {
1806 std::string line;
1807
deadbeefc80741f2015-10-22 13:14:45 -07001808 desc->set_msid_supported(false);
1809
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001810 // RFC 4566
1811 // v= (protocol version)
1812 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1813 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1814 std::string(), error);
1815 }
1816 // RFC 4566
1817 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1818 // <unicast-address>
1819 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1820 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1821 std::string(), error);
1822 }
1823 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001824 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001825 kSdpDelimiterSpace, &fields);
1826 const size_t expected_fields = 6;
1827 if (fields.size() != expected_fields) {
1828 return ParseFailedExpectFieldNum(line, expected_fields, error);
1829 }
1830 *session_id = fields[1];
1831 *session_version = fields[2];
1832
1833 // RFC 4566
1834 // s= (session name)
1835 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1836 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1837 std::string(), error);
1838 }
1839
1840 // Optional lines
1841 // Those are the optional lines, so shouldn't return false if not present.
1842 // RFC 4566
1843 // i=* (session information)
1844 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1845
1846 // RFC 4566
1847 // u=* (URI of description)
1848 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1849
1850 // RFC 4566
1851 // e=* (email address)
1852 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1853
1854 // RFC 4566
1855 // p=* (phone number)
1856 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1857
1858 // RFC 4566
1859 // c=* (connection information -- not required if included in
1860 // all media)
1861 GetLineWithType(message, pos, &line, kLineTypeConnection);
1862
1863 // RFC 4566
1864 // b=* (zero or more bandwidth information lines)
1865 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1866 // By pass zero or more b lines.
1867 }
1868
1869 // RFC 4566
1870 // One or more time descriptions ("t=" and "r=" lines; see below)
1871 // t= (time the session is active)
1872 // r=* (zero or more repeat times)
1873 // Ensure there's at least one time description
1874 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1875 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1876 error);
1877 }
1878
1879 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1880 // By pass zero or more r lines.
1881 }
1882
1883 // Go through the rest of the time descriptions
1884 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1885 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1886 // By pass zero or more r lines.
1887 }
1888 }
1889
1890 // RFC 4566
1891 // z=* (time zone adjustments)
1892 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1893
1894 // RFC 4566
1895 // k=* (encryption key)
1896 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1897
1898 // RFC 4566
1899 // a=* (zero or more session attribute lines)
1900 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1901 if (HasAttribute(line, kAttributeGroup)) {
1902 if (!ParseGroupAttribute(line, desc, error)) {
1903 return false;
1904 }
1905 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1906 if (!GetValue(line, kAttributeIceUfrag,
1907 &(session_td->ice_ufrag), error)) {
1908 return false;
1909 }
1910 } else if (HasAttribute(line, kAttributeIcePwd)) {
1911 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1912 return false;
1913 }
1914 } else if (HasAttribute(line, kAttributeIceLite)) {
1915 session_td->ice_mode = cricket::ICEMODE_LITE;
1916 } else if (HasAttribute(line, kAttributeIceOption)) {
1917 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1918 return false;
1919 }
1920 } else if (HasAttribute(line, kAttributeFingerprint)) {
1921 if (session_td->identity_fingerprint.get()) {
1922 return ParseFailed(
1923 line,
1924 "Can't have multiple fingerprint attributes at the same level.",
1925 error);
1926 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001927 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1929 return false;
1930 }
1931 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001932 } else if (HasAttribute(line, kAttributeSetup)) {
1933 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1934 return false;
1935 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001936 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1937 std::string semantics;
1938 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1939 return false;
1940 }
deadbeefc80741f2015-10-22 13:14:45 -07001941 desc->set_msid_supported(
1942 CaseInsensitiveFind(semantics, kMediaStreamSemantic));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001943 } else if (HasAttribute(line, kAttributeExtmap)) {
1944 RtpHeaderExtension extmap;
1945 if (!ParseExtmap(line, &extmap, error)) {
1946 return false;
1947 }
1948 session_extmaps->push_back(extmap);
1949 }
1950 }
1951
1952 return true;
1953}
1954
1955bool ParseGroupAttribute(const std::string& line,
1956 cricket::SessionDescription* desc,
1957 SdpParseError* error) {
1958 ASSERT(desc != NULL);
1959
1960 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1961 // a=group:BUNDLE video voice
1962 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001963 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001964 kSdpDelimiterSpace, &fields);
1965 std::string semantics;
1966 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1967 return false;
1968 }
1969 cricket::ContentGroup group(semantics);
1970 for (size_t i = 1; i < fields.size(); ++i) {
1971 group.AddContentName(fields[i]);
1972 }
1973 desc->AddGroup(group);
1974 return true;
1975}
1976
1977static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001978 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001979 SdpParseError* error) {
1980 if (!IsLineType(line, kLineTypeAttributes) ||
1981 !HasAttribute(line, kAttributeFingerprint)) {
1982 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1983 kAttributeFingerprint, error);
1984 }
1985
1986 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001987 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001988 kSdpDelimiterSpace, &fields);
1989 const size_t expected_fields = 2;
1990 if (fields.size() != expected_fields) {
1991 return ParseFailedExpectFieldNum(line, expected_fields, error);
1992 }
1993
1994 // The first field here is "fingerprint:<hash>.
1995 std::string algorithm;
1996 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
1997 return false;
1998 }
1999
2000 // Downcase the algorithm. Note that we don't need to downcase the
2001 // fingerprint because hex_decode can handle upper-case.
2002 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2003 ::tolower);
2004
2005 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002006 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002007 algorithm, fields[1]);
2008 if (!*fingerprint) {
2009 return ParseFailed(line,
2010 "Failed to create fingerprint from the digest.",
2011 error);
2012 }
2013
2014 return true;
2015}
2016
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002017static bool ParseDtlsSetup(const std::string& line,
2018 cricket::ConnectionRole* role,
2019 SdpParseError* error) {
2020 // setup-attr = "a=setup:" role
2021 // role = "active" / "passive" / "actpass" / "holdconn"
2022 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002023 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002024 const size_t expected_fields = 2;
2025 if (fields.size() != expected_fields) {
2026 return ParseFailedExpectFieldNum(line, expected_fields, error);
2027 }
2028 std::string role_str = fields[1];
2029 if (!cricket::StringToConnectionRole(role_str, role)) {
2030 return ParseFailed(line, "Invalid attribute value.", error);
2031 }
2032 return true;
2033}
2034
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002035// RFC 3551
2036// PT encoding media type clock rate channels
2037// name (Hz)
2038// 0 PCMU A 8,000 1
2039// 1 reserved A
2040// 2 reserved A
2041// 3 GSM A 8,000 1
2042// 4 G723 A 8,000 1
2043// 5 DVI4 A 8,000 1
2044// 6 DVI4 A 16,000 1
2045// 7 LPC A 8,000 1
2046// 8 PCMA A 8,000 1
2047// 9 G722 A 8,000 1
2048// 10 L16 A 44,100 2
2049// 11 L16 A 44,100 1
2050// 12 QCELP A 8,000 1
2051// 13 CN A 8,000 1
2052// 14 MPA A 90,000 (see text)
2053// 15 G728 A 8,000 1
2054// 16 DVI4 A 11,025 1
2055// 17 DVI4 A 22,050 1
2056// 18 G729 A 8,000 1
2057struct StaticPayloadAudioCodec {
2058 const char* name;
2059 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002060 size_t channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002061};
2062static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2063 { "PCMU", 8000, 1 },
2064 { "reserved", 0, 0 },
2065 { "reserved", 0, 0 },
2066 { "GSM", 8000, 1 },
2067 { "G723", 8000, 1 },
2068 { "DVI4", 8000, 1 },
2069 { "DVI4", 16000, 1 },
2070 { "LPC", 8000, 1 },
2071 { "PCMA", 8000, 1 },
2072 { "G722", 8000, 1 },
2073 { "L16", 44100, 2 },
2074 { "L16", 44100, 1 },
2075 { "QCELP", 8000, 1 },
2076 { "CN", 8000, 1 },
2077 { "MPA", 90000, 1 },
2078 { "G728", 8000, 1 },
2079 { "DVI4", 11025, 1 },
2080 { "DVI4", 22050, 1 },
2081 { "G729", 8000, 1 },
2082};
2083
2084void MaybeCreateStaticPayloadAudioCodecs(
2085 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2086 if (!media_desc) {
2087 return;
2088 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002089 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002090 std::vector<int>::const_iterator it = fmts.begin();
2091 bool add_new_codec = false;
2092 for (; it != fmts.end(); ++it) {
2093 int payload_type = *it;
2094 if (!media_desc->HasCodec(payload_type) &&
2095 payload_type >= 0 &&
tfarina5237aaf2015-11-10 23:44:30 -08002096 payload_type < arraysize(kStaticPayloadAudioCodecs)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002097 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2098 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002099 size_t channels = kStaticPayloadAudioCodecs[payload_type].channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002100 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2101 clock_rate, 0, channels,
2102 preference));
2103 add_new_codec = true;
2104 }
2105 --preference;
2106 }
2107 if (add_new_codec) {
2108 media_desc->SortCodecs();
2109 }
2110}
2111
2112template <class C>
2113static C* ParseContentDescription(const std::string& message,
2114 const MediaType media_type,
2115 int mline_index,
2116 const std::string& protocol,
2117 const std::vector<int>& codec_preference,
2118 size_t* pos,
2119 std::string* content_name,
2120 TransportDescription* transport,
2121 std::vector<JsepIceCandidate*>* candidates,
2122 webrtc::SdpParseError* error) {
2123 C* media_desc = new C();
2124 switch (media_type) {
2125 case cricket::MEDIA_TYPE_AUDIO:
2126 *content_name = cricket::CN_AUDIO;
2127 break;
2128 case cricket::MEDIA_TYPE_VIDEO:
2129 *content_name = cricket::CN_VIDEO;
2130 break;
2131 case cricket::MEDIA_TYPE_DATA:
2132 *content_name = cricket::CN_DATA;
2133 break;
2134 default:
2135 ASSERT(false);
2136 break;
2137 }
2138 if (!ParseContent(message, media_type, mline_index, protocol,
2139 codec_preference, pos, content_name,
2140 media_desc, transport, candidates, error)) {
2141 delete media_desc;
2142 return NULL;
2143 }
2144 // Sort the codecs according to the m-line fmt list.
2145 media_desc->SortCodecs();
2146 return media_desc;
2147}
2148
2149bool ParseMediaDescription(const std::string& message,
2150 const TransportDescription& session_td,
2151 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002152 size_t* pos,
2153 cricket::SessionDescription* desc,
2154 std::vector<JsepIceCandidate*>* candidates,
2155 SdpParseError* error) {
2156 ASSERT(desc != NULL);
2157 std::string line;
2158 int mline_index = -1;
2159
2160 // Zero or more media descriptions
2161 // RFC 4566
2162 // m=<media> <port> <proto> <fmt>
2163 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2164 ++mline_index;
2165
2166 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002167 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002168 kSdpDelimiterSpace, &fields);
2169 const size_t expected_min_fields = 4;
2170 if (fields.size() < expected_min_fields) {
2171 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2172 }
2173 bool rejected = false;
2174 // RFC 3264
2175 // To reject an offered stream, the port number in the corresponding stream
2176 // in the answer MUST be set to zero.
2177 if (fields[1] == kMediaPortRejected) {
2178 rejected = true;
2179 }
2180
2181 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002182
2183 // <fmt>
2184 std::vector<int> codec_preference;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002185 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002186 for (size_t j = 3 ; j < fields.size(); ++j) {
2187 // TODO(wu): Remove when below bug is fixed.
2188 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002189 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002190 continue;
2191 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002192
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002193 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002194 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002195 return false;
2196 }
2197 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002198 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002199 }
2200
2201 // Make a temporary TransportDescription based on |session_td|.
2202 // Some of this gets overwritten by ParseContent.
deadbeef46eed762016-01-28 13:24:37 -08002203 TransportDescription transport(
2204 session_td.transport_options, session_td.ice_ufrag, session_td.ice_pwd,
2205 session_td.ice_mode, session_td.connection_role,
2206 session_td.identity_fingerprint.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002207
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002208 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209 std::string content_name;
2210 if (HasAttribute(line, kMediaTypeVideo)) {
2211 content.reset(ParseContentDescription<VideoContentDescription>(
2212 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2213 codec_preference, pos, &content_name,
2214 &transport, candidates, error));
2215 } else if (HasAttribute(line, kMediaTypeAudio)) {
2216 content.reset(ParseContentDescription<AudioContentDescription>(
2217 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2218 codec_preference, pos, &content_name,
2219 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002220 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002221 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002222 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2224 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002225 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002226 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002227
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002228 int p;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002229 if (data_desc && IsDtlsSctp(protocol) && rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002230 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002231 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002232 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002233 } else {
2234 LOG(LS_WARNING) << "Unsupported media type: " << line;
2235 continue;
2236 }
2237 if (!content.get()) {
2238 // ParseContentDescription returns NULL if failed.
2239 return false;
2240 }
2241
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002242 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002243 // Set the extmap.
2244 if (!session_extmaps.empty() &&
2245 !content->rtp_header_extensions().empty()) {
2246 return ParseFailed("",
2247 "The a=extmap MUST be either all session level or "
2248 "all media level.",
2249 error);
2250 }
2251 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2252 content->AddRtpHeaderExtension(session_extmaps[i]);
2253 }
2254 }
2255 content->set_protocol(protocol);
2256 desc->AddContent(content_name,
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002257 IsDtlsSctp(protocol) ? cricket::NS_JINGLE_DRAFT_SCTP :
2258 cricket::NS_JINGLE_RTP,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 rejected,
2260 content.release());
2261 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2262 TransportInfo transport_info(content_name, transport);
2263
2264 if (!desc->AddTransportInfo(transport_info)) {
2265 std::ostringstream description;
2266 description << "Failed to AddTransportInfo with content name: "
2267 << content_name;
2268 return ParseFailed("", description.str(), error);
2269 }
2270 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002271
2272 size_t end_of_message = message.size();
2273 if (mline_index == -1 && *pos != end_of_message) {
2274 ParseFailed(message, *pos, "Expects m line.", error);
2275 return false;
2276 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002277 return true;
2278}
2279
2280bool VerifyCodec(const cricket::Codec& codec) {
2281 // Codec has not been populated correctly unless the name has been set. This
2282 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2283 // have a corresponding "rtpmap" line.
2284 cricket::Codec default_codec;
2285 return default_codec.name != codec.name;
2286}
2287
2288bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2289 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2290 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2291 iter != codecs.end(); ++iter) {
2292 if (!VerifyCodec(*iter)) {
2293 return false;
2294 }
2295 }
2296 return true;
2297}
2298
2299bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2300 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2301 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2302 iter != codecs.end(); ++iter) {
2303 if (!VerifyCodec(*iter)) {
2304 return false;
2305 }
2306 }
2307 return true;
2308}
2309
2310void AddParameters(const cricket::CodecParameterMap& parameters,
2311 cricket::Codec* codec) {
2312 for (cricket::CodecParameterMap::const_iterator iter =
2313 parameters.begin(); iter != parameters.end(); ++iter) {
2314 codec->SetParam(iter->first, iter->second);
2315 }
2316}
2317
2318void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2319 cricket::Codec* codec) {
2320 codec->AddFeedbackParam(feedback_param);
2321}
2322
2323void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2324 cricket::Codec* codec) {
2325 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2326 feedback_params.params().begin();
2327 iter != feedback_params.params().end(); ++iter) {
2328 codec->AddFeedbackParam(*iter);
2329 }
2330}
2331
2332// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002333// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002334// with that payload type.
2335template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002336T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2337 T ret_val;
2338 if (!FindCodecById(codecs, payload_type, &ret_val)) {
2339 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002340 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002341 return ret_val;
2342}
2343
2344// Updates or creates a new codec entry in the audio description.
2345template <class T, class U>
2346void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2347 T* desc = static_cast<T*>(content_desc);
2348 std::vector<U> codecs = desc->codecs();
2349 bool found = false;
2350
2351 typename std::vector<U>::iterator iter;
2352 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2353 if (iter->id == codec.id) {
2354 *iter = codec;
2355 found = true;
2356 break;
2357 }
2358 }
2359 if (!found) {
2360 desc->AddCodec(codec);
2361 return;
2362 }
2363 desc->set_codecs(codecs);
2364}
2365
2366// Adds or updates existing codec corresponding to |payload_type| according
2367// to |parameters|.
2368template <class T, class U>
2369void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2370 const cricket::CodecParameterMap& parameters) {
2371 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002372 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2373 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002374 AddParameters(parameters, &new_codec);
2375 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2376}
2377
2378// Adds or updates existing codec corresponding to |payload_type| according
2379// to |feedback_param|.
2380template <class T, class U>
2381void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2382 const cricket::FeedbackParam& feedback_param) {
2383 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002384 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2385 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002386 AddFeedbackParameter(feedback_param, &new_codec);
2387 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2388}
2389
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002390template <class T>
2391bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2392 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002393 if (iter->id == kWildcardPayloadType) {
2394 *wildcard_codec = *iter;
2395 codecs->erase(iter);
2396 return true;
2397 }
2398 }
2399 return false;
2400}
2401
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002402template<class T>
2403void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2404 auto codecs = desc->codecs();
2405 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002406 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2407 return;
2408 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002409 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002410 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2411 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002412 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002413}
2414
2415void AddAudioAttribute(const std::string& name, const std::string& value,
2416 AudioContentDescription* audio_desc) {
2417 if (value.empty()) {
2418 return;
2419 }
2420 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2421 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2422 iter != codecs.end(); ++iter) {
2423 iter->params[name] = value;
2424 }
2425 audio_desc->set_codecs(codecs);
2426}
2427
2428bool ParseContent(const std::string& message,
2429 const MediaType media_type,
2430 int mline_index,
2431 const std::string& protocol,
2432 const std::vector<int>& codec_preference,
2433 size_t* pos,
2434 std::string* content_name,
2435 MediaContentDescription* media_desc,
2436 TransportDescription* transport,
2437 std::vector<JsepIceCandidate*>* candidates,
2438 SdpParseError* error) {
2439 ASSERT(media_desc != NULL);
2440 ASSERT(content_name != NULL);
2441 ASSERT(transport != NULL);
2442
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002443 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2444 MaybeCreateStaticPayloadAudioCodecs(
2445 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2446 }
2447
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002448 // The media level "ice-ufrag" and "ice-pwd".
2449 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2450 Candidates candidates_orig;
2451 std::string line;
2452 std::string mline_id;
2453 // Tracks created out of the ssrc attributes.
2454 StreamParamsVec tracks;
2455 SsrcInfoVec ssrc_infos;
2456 SsrcGroupVec ssrc_groups;
2457 std::string maxptime_as_string;
2458 std::string ptime_as_string;
2459
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002460 // Loop until the next m line
2461 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2462 if (!GetLine(message, pos, &line)) {
2463 if (*pos >= message.size()) {
2464 break; // Done parsing
2465 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002466 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002467 }
2468 }
2469
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002470 // RFC 4566
2471 // b=* (zero or more bandwidth information lines)
2472 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2473 std::string bandwidth;
2474 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2475 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2476 return false;
2477 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002478 int b = 0;
2479 if (!GetValueFromString(line, bandwidth, &b, error)) {
2480 return false;
2481 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002482 // We should never use more than the default bandwidth for RTP-based
2483 // data channels. Don't allow SDP to set the bandwidth, because
2484 // that would give JS the opportunity to "break the Internet".
2485 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2486 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2487 b > cricket::kDataMaxBandwidth / 1000) {
2488 std::ostringstream description;
2489 description << "RTP-based data channels may not send more than "
2490 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2491 return ParseFailed(line, description.str(), error);
2492 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002493 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002494 }
2495 }
2496 continue;
2497 }
2498
2499 if (!IsLineType(line, kLineTypeAttributes)) {
2500 // TODO: Handle other lines if needed.
2501 LOG(LS_INFO) << "Ignored line: " << line;
2502 continue;
2503 }
2504
2505 // Handle attributes common to SCTP and RTP.
2506 if (HasAttribute(line, kAttributeMid)) {
2507 // RFC 3388
2508 // mid-attribute = "a=mid:" identification-tag
2509 // identification-tag = token
2510 // Use the mid identification-tag as the content name.
2511 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2512 return false;
2513 }
2514 *content_name = mline_id;
2515 } else if (HasAttribute(line, kAttributeCandidate)) {
2516 Candidate candidate;
2517 if (!ParseCandidate(line, &candidate, error, false)) {
2518 return false;
2519 }
2520 candidates_orig.push_back(candidate);
2521 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2522 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2523 return false;
2524 }
2525 } else if (HasAttribute(line, kAttributeIcePwd)) {
2526 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2527 return false;
2528 }
2529 } else if (HasAttribute(line, kAttributeIceOption)) {
2530 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2531 return false;
2532 }
2533 } else if (HasAttribute(line, kAttributeFmtp)) {
2534 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2535 return false;
2536 }
2537 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002538 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002539
2540 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2541 return false;
2542 }
2543 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002544 } else if (HasAttribute(line, kAttributeSetup)) {
2545 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2546 return false;
2547 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002548 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002549 int sctp_port;
2550 if (!ParseSctpPort(line, &sctp_port, error)) {
2551 return false;
2552 }
2553 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2554 sctp_port)) {
2555 return false;
2556 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002557 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002558 //
2559 // RTP specific attrubtes
2560 //
2561 if (HasAttribute(line, kAttributeRtcpMux)) {
2562 media_desc->set_rtcp_mux(true);
deadbeef13871492015-12-09 12:37:51 -08002563 } else if (HasAttribute(line, kAttributeRtcpReducedSize)) {
2564 media_desc->set_rtcp_reduced_size(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002565 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2566 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2567 return false;
2568 }
2569 } else if (HasAttribute(line, kAttributeSsrc)) {
2570 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2571 return false;
2572 }
2573 } else if (HasAttribute(line, kAttributeCrypto)) {
2574 if (!ParseCryptoAttribute(line, media_desc, error)) {
2575 return false;
2576 }
2577 } else if (HasAttribute(line, kAttributeRtpmap)) {
2578 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2579 media_desc, error)) {
2580 return false;
2581 }
2582 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2583 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2584 return false;
2585 }
2586 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2587 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2588 return false;
2589 }
2590 } else if (HasAttribute(line, kCodecParamPTime)) {
2591 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2592 return false;
2593 }
2594 } else if (HasAttribute(line, kAttributeSendOnly)) {
2595 media_desc->set_direction(cricket::MD_SENDONLY);
2596 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2597 media_desc->set_direction(cricket::MD_RECVONLY);
2598 } else if (HasAttribute(line, kAttributeInactive)) {
2599 media_desc->set_direction(cricket::MD_INACTIVE);
2600 } else if (HasAttribute(line, kAttributeSendRecv)) {
2601 media_desc->set_direction(cricket::MD_SENDRECV);
2602 } else if (HasAttribute(line, kAttributeExtmap)) {
2603 RtpHeaderExtension extmap;
2604 if (!ParseExtmap(line, &extmap, error)) {
2605 return false;
2606 }
2607 media_desc->AddRtpHeaderExtension(extmap);
2608 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2609 // Experimental attribute. Conference mode activates more aggressive
2610 // AEC and NS settings.
2611 // TODO: expose API to set these directly.
2612 std::string flag_value;
2613 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2614 return false;
2615 }
2616 if (flag_value.compare(kValueConference) == 0)
2617 media_desc->set_conference_mode(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002618 }
2619 } else {
2620 // Only parse lines that we are interested of.
2621 LOG(LS_INFO) << "Ignored line: " << line;
2622 continue;
2623 }
2624 }
2625
2626 // Create tracks from the |ssrc_infos|.
2627 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2628
2629 // Add the ssrc group to the track.
2630 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2631 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2632 if (ssrc_group->ssrcs.empty()) {
2633 continue;
2634 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002635 uint32_t ssrc = ssrc_group->ssrcs.front();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002636 for (StreamParamsVec::iterator track = tracks.begin();
2637 track != tracks.end(); ++track) {
2638 if (track->has_ssrc(ssrc)) {
2639 track->ssrc_groups.push_back(*ssrc_group);
2640 }
2641 }
2642 }
2643
2644 // Add the new tracks to the |media_desc|.
2645 for (StreamParamsVec::iterator track = tracks.begin();
2646 track != tracks.end(); ++track) {
2647 media_desc->AddStream(*track);
2648 }
2649
2650 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2651 AudioContentDescription* audio_desc =
2652 static_cast<AudioContentDescription*>(media_desc);
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002653 UpdateFromWildcardCodecs(audio_desc);
2654
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002655 // Verify audio codec ensures that no audio codec has been populated with
2656 // only fmtp.
2657 if (!VerifyAudioCodecs(audio_desc)) {
2658 return ParseFailed("Failed to parse audio codecs correctly.", error);
2659 }
2660 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2661 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2662 }
2663
2664 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002665 VideoContentDescription* video_desc =
2666 static_cast<VideoContentDescription*>(media_desc);
2667 UpdateFromWildcardCodecs(video_desc);
2668 // Verify video codec ensures that no video codec has been populated with
2669 // only rtcp-fb.
2670 if (!VerifyVideoCodecs(video_desc)) {
2671 return ParseFailed("Failed to parse video codecs correctly.", error);
2672 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673 }
2674
2675 // RFC 5245
2676 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2677 for (Candidates::iterator it = candidates_orig.begin();
2678 it != candidates_orig.end(); ++it) {
honghaiza54a0802015-12-16 18:37:23 -08002679 ASSERT((*it).username().empty() ||
2680 (*it).username() == transport->ice_ufrag);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002681 (*it).set_username(transport->ice_ufrag);
2682 ASSERT((*it).password().empty());
2683 (*it).set_password(transport->ice_pwd);
2684 candidates->push_back(
2685 new JsepIceCandidate(mline_id, mline_index, *it));
2686 }
2687 return true;
2688}
2689
2690bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2691 SdpParseError* error) {
2692 ASSERT(ssrc_infos != NULL);
2693 // RFC 5576
2694 // a=ssrc:<ssrc-id> <attribute>
2695 // a=ssrc:<ssrc-id> <attribute>:<value>
2696 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07002697 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2698 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002699 const size_t expected_fields = 2;
2700 return ParseFailedExpectFieldNum(line, expected_fields, error);
2701 }
2702
2703 // ssrc:<ssrc-id>
2704 std::string ssrc_id_s;
2705 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2706 return false;
2707 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002708 uint32_t ssrc_id = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002709 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2710 return false;
2711 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002712
2713 std::string attribute;
2714 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07002715 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002716 std::ostringstream description;
2717 description << "Failed to get the ssrc attribute value from " << field2
2718 << ". Expected format <attribute>:<value>.";
2719 return ParseFailed(line, description.str(), error);
2720 }
2721
2722 // Check if there's already an item for this |ssrc_id|. Create a new one if
2723 // there isn't.
2724 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2725 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2726 if (ssrc_info->ssrc_id == ssrc_id) {
2727 break;
2728 }
2729 }
2730 if (ssrc_info == ssrc_infos->end()) {
2731 SsrcInfo info;
2732 info.ssrc_id = ssrc_id;
2733 ssrc_infos->push_back(info);
2734 ssrc_info = ssrc_infos->end() - 1;
2735 }
2736
2737 // Store the info to the |ssrc_info|.
2738 if (attribute == kSsrcAttributeCname) {
2739 // RFC 5576
2740 // cname:<value>
2741 ssrc_info->cname = value;
2742 } else if (attribute == kSsrcAttributeMsid) {
2743 // draft-alvestrand-mmusic-msid-00
2744 // "msid:" identifier [ " " appdata ]
2745 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002746 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002747 if (fields.size() < 1 || fields.size() > 2) {
2748 return ParseFailed(line,
2749 "Expected format \"msid:<identifier>[ <appdata>]\".",
2750 error);
2751 }
2752 ssrc_info->msid_identifier = fields[0];
2753 if (fields.size() == 2) {
2754 ssrc_info->msid_appdata = fields[1];
2755 }
2756 } else if (attribute == kSsrcAttributeMslabel) {
2757 // draft-alvestrand-rtcweb-mid-01
2758 // mslabel:<value>
2759 ssrc_info->mslabel = value;
2760 } else if (attribute == kSSrcAttributeLabel) {
2761 // The label isn't defined.
2762 // label:<value>
2763 ssrc_info->label = value;
2764 }
2765 return true;
2766}
2767
2768bool ParseSsrcGroupAttribute(const std::string& line,
2769 SsrcGroupVec* ssrc_groups,
2770 SdpParseError* error) {
2771 ASSERT(ssrc_groups != NULL);
2772 // RFC 5576
2773 // a=ssrc-group:<semantics> <ssrc-id> ...
2774 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002775 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002776 kSdpDelimiterSpace, &fields);
2777 const size_t expected_min_fields = 2;
2778 if (fields.size() < expected_min_fields) {
2779 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2780 }
2781 std::string semantics;
2782 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2783 return false;
2784 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002785 std::vector<uint32_t> ssrcs;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002786 for (size_t i = 1; i < fields.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02002787 uint32_t ssrc = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002788 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2789 return false;
2790 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002791 ssrcs.push_back(ssrc);
2792 }
2793 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2794 return true;
2795}
2796
2797bool ParseCryptoAttribute(const std::string& line,
2798 MediaContentDescription* media_desc,
2799 SdpParseError* error) {
2800 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002801 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002802 kSdpDelimiterSpace, &fields);
2803 // RFC 4568
2804 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2805 const size_t expected_min_fields = 3;
2806 if (fields.size() < expected_min_fields) {
2807 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2808 }
2809 std::string tag_value;
2810 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2811 return false;
2812 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002813 int tag = 0;
2814 if (!GetValueFromString(line, tag_value, &tag, error)) {
2815 return false;
2816 }
jbauch083b73f2015-07-16 02:46:32 -07002817 const std::string& crypto_suite = fields[1];
2818 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002819 std::string session_params;
2820 if (fields.size() > 3) {
2821 session_params = fields[3];
2822 }
2823 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2824 session_params));
2825 return true;
2826}
2827
2828// Updates or creates a new codec entry in the audio description with according
2829// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2830void UpdateCodec(int payload_type, const std::string& name, int clockrate,
Peter Kasting69558702016-01-12 16:26:35 -08002831 int bitrate, size_t channels, int preference,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002832 AudioContentDescription* audio_desc) {
2833 // Codec may already be populated with (only) optional parameters
2834 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002835 cricket::AudioCodec codec =
2836 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002837 codec.name = name;
2838 codec.clockrate = clockrate;
2839 codec.bitrate = bitrate;
2840 codec.channels = channels;
2841 codec.preference = preference;
2842 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2843 codec);
2844}
2845
2846// Updates or creates a new codec entry in the video description according to
2847// |name|, |width|, |height|, |framerate| and |preference|.
2848void UpdateCodec(int payload_type, const std::string& name, int width,
2849 int height, int framerate, int preference,
2850 VideoContentDescription* video_desc) {
2851 // Codec may already be populated with (only) optional parameters
2852 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002853 cricket::VideoCodec codec =
2854 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002855 codec.name = name;
2856 codec.width = width;
2857 codec.height = height;
2858 codec.framerate = framerate;
2859 codec.preference = preference;
2860 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2861 codec);
2862}
2863
2864bool ParseRtpmapAttribute(const std::string& line,
2865 const MediaType media_type,
2866 const std::vector<int>& codec_preference,
2867 MediaContentDescription* media_desc,
2868 SdpParseError* error) {
2869 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002870 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002871 kSdpDelimiterSpace, &fields);
2872 // RFC 4566
2873 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2874 const size_t expected_min_fields = 2;
2875 if (fields.size() < expected_min_fields) {
2876 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2877 }
2878 std::string payload_type_value;
2879 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2880 return false;
2881 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002882 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002883 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
2884 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002885 return false;
2886 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002887
2888 // Set the preference order depending on the order of the pl type in the
2889 // <fmt> of the m-line.
2890 const int preference = codec_preference.end() -
2891 std::find(codec_preference.begin(), codec_preference.end(),
2892 payload_type);
2893 if (preference == 0) {
2894 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2895 << "<fmt> of the m-line: " << line;
2896 return true;
2897 }
jbauch083b73f2015-07-16 02:46:32 -07002898 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002899 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002900 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002901 // <encoding name>/<clock rate>[/<encodingparameters>]
2902 // 2 mandatory fields
2903 if (codec_params.size() < 2 || codec_params.size() > 3) {
2904 return ParseFailed(line,
2905 "Expected format \"<encoding name>/<clock rate>"
2906 "[/<encodingparameters>]\".",
2907 error);
2908 }
jbauch083b73f2015-07-16 02:46:32 -07002909 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002910 int clock_rate = 0;
2911 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2912 return false;
2913 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002914 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2915 VideoContentDescription* video_desc =
2916 static_cast<VideoContentDescription*>(media_desc);
2917 // TODO: We will send resolution in SDP. For now use
2918 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2919 UpdateCodec(payload_type, encoding_name,
2920 JsepSessionDescription::kMaxVideoCodecWidth,
2921 JsepSessionDescription::kMaxVideoCodecHeight,
2922 JsepSessionDescription::kDefaultVideoCodecFramerate,
2923 preference, video_desc);
2924 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2925 // RFC 4566
2926 // For audio streams, <encoding parameters> indicates the number
2927 // of audio channels. This parameter is OPTIONAL and may be
2928 // omitted if the number of channels is one, provided that no
2929 // additional parameters are needed.
Peter Kasting69558702016-01-12 16:26:35 -08002930 size_t channels = 1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002931 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002932 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2933 return false;
2934 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002935 }
2936 int bitrate = 0;
2937 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2938 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2939 // The bandwidth adaptation doesn't always work well, so this code
2940 // sets a fixed target bitrate instead.
2941 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2942 if (clock_rate <= 16000) {
2943 bitrate = kIsacWbDefaultRate;
2944 } else {
2945 bitrate = kIsacSwbDefaultRate;
2946 }
2947 }
2948 AudioContentDescription* audio_desc =
2949 static_cast<AudioContentDescription*>(media_desc);
2950 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2951 preference, audio_desc);
2952 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2953 DataContentDescription* data_desc =
2954 static_cast<DataContentDescription*>(media_desc);
2955 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2956 preference));
2957 }
2958 return true;
2959}
2960
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002961bool ParseFmtpParam(const std::string& line, std::string* parameter,
2962 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07002963 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002964 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2965 return false;
2966 }
2967 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002968 return true;
2969}
2970
2971bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
2972 MediaContentDescription* media_desc,
2973 SdpParseError* error) {
2974 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2975 media_type != cricket::MEDIA_TYPE_VIDEO) {
2976 return true;
2977 }
Donald Curtis0e07f922015-05-15 09:21:23 -07002978
2979 std::string line_payload;
2980 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002981
2982 // RFC 5576
2983 // a=fmtp:<format> <format specific parameters>
2984 // At least two fields, whereas the second one is any of the optional
2985 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07002986 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2987 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002988 ParseFailedExpectMinFieldNum(line, 2, error);
2989 return false;
2990 }
2991
Donald Curtis0e07f922015-05-15 09:21:23 -07002992 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00002993 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07002994 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002995 return false;
2996 }
2997
Donald Curtis0e07f922015-05-15 09:21:23 -07002998 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07002999 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3000 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003001 return false;
3002 }
3003
3004 // Parse out format specific parameters.
3005 std::vector<std::string> fields;
3006 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
3007
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003008 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07003009 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003010 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003011 // Only fmtps with equals are currently supported. Other fmtp types
3012 // should be ignored. Unknown fmtps do not constitute an error.
3013 continue;
3014 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003015
3016 std::string name;
3017 std::string value;
3018 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003019 return false;
3020 }
3021 codec_params[name] = value;
3022 }
3023
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003024 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3025 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003026 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003027 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3028 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003029 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003030 }
3031 return true;
3032}
3033
3034bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3035 MediaContentDescription* media_desc,
3036 SdpParseError* error) {
3037 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3038 media_type != cricket::MEDIA_TYPE_VIDEO) {
3039 return true;
3040 }
3041 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003042 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003043 if (rtcp_fb_fields.size() < 2) {
3044 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3045 }
3046 std::string payload_type_string;
3047 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3048 error)) {
3049 return false;
3050 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003051 int payload_type = kWildcardPayloadType;
3052 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003053 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3054 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003055 return false;
3056 }
3057 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058 std::string id = rtcp_fb_fields[1];
3059 std::string param = "";
3060 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3061 iter != rtcp_fb_fields.end(); ++iter) {
3062 param.append(*iter);
3063 }
3064 const cricket::FeedbackParam feedback_param(id, param);
3065
3066 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003067 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3068 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003069 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003070 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3071 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003072 }
3073 return true;
3074}
3075
3076} // namespace webrtc