blob: 54bb0599d4e57367b3202759f84d3195cf72bab8 [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"
kjellandera96e2d72016-02-04 23:52:28 -080028#include "webrtc/media/base/cryptoparams.h"
kjellanderf4752772016-03-02 05:42:30 -080029#include "webrtc/media/base/mediaconstants.h"
kjellandera96e2d72016-02-04 23:52:28 -080030#include "webrtc/media/base/rtputils.h"
31#include "webrtc/media/sctp/sctpdataengine.h"
32#include "webrtc/p2p/base/candidate.h"
kjellanderf4752772016-03-02 05:42:30 -080033#include "webrtc/p2p/base/p2pconstants.h"
kjellandera96e2d72016-02-04 23:52:28 -080034#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.
deadbeef9d3584c2016-02-16 17:54:10 -080087static const int kLinePrefixLength = 2; // Length of <type>=
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088static 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";
deadbeef9d3584c2016-02-16 17:54:10 -0800107static const char kAttributeMsid[] = "msid";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108static const char kAttributeRtcpMux[] = "rtcp-mux";
deadbeef13871492015-12-09 12:37:51 -0800109static const char kAttributeRtcpReducedSize[] = "rtcp-rsize";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110static const char kAttributeSsrc[] = "ssrc";
111static const char kSsrcAttributeCname[] = "cname";
112static const char kAttributeExtmap[] = "extmap";
113// draft-alvestrand-mmusic-msid-01
114// a=msid-semantic: WMS
115static const char kAttributeMsidSemantics[] = "msid-semantic";
116static const char kMediaStreamSemantic[] = "WMS";
117static const char kSsrcAttributeMsid[] = "msid";
118static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119static const char kSsrcAttributeMslabel[] = "mslabel";
120static const char kSSrcAttributeLabel[] = "label";
121static const char kAttributeSsrcGroup[] = "ssrc-group";
122static const char kAttributeCrypto[] = "crypto";
123static const char kAttributeCandidate[] = "candidate";
124static const char kAttributeCandidateTyp[] = "typ";
125static const char kAttributeCandidateRaddr[] = "raddr";
126static const char kAttributeCandidateRport[] = "rport";
honghaiza54a0802015-12-16 18:37:23 -0800127static const char kAttributeCandidateUfrag[] = "ufrag";
128static const char kAttributeCandidatePwd[] = "pwd";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000129static const char kAttributeCandidateGeneration[] = "generation";
honghaize1a0c942016-02-16 14:54:56 -0800130static const char kAttributeCandidateNetworkCost[] = "network-cost";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000131static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000132static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133static const char kAttributeFmtp[] = "fmtp";
134static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000135static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136static const char kAttributeRtcp[] = "rtcp";
137static const char kAttributeIceUfrag[] = "ice-ufrag";
138static const char kAttributeIcePwd[] = "ice-pwd";
139static const char kAttributeIceLite[] = "ice-lite";
140static const char kAttributeIceOption[] = "ice-options";
141static const char kAttributeSendOnly[] = "sendonly";
142static const char kAttributeRecvOnly[] = "recvonly";
143static const char kAttributeRtcpFb[] = "rtcp-fb";
144static const char kAttributeSendRecv[] = "sendrecv";
145static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000146// draft-ietf-mmusic-sctp-sdp-07
147// a=sctp-port
148static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000149
150// Experimental flags
151static const char kAttributeXGoogleFlag[] = "x-google-flag";
152static const char kValueConference[] = "conference";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000153
154// Candidate
155static const char kCandidateHost[] = "host";
156static const char kCandidateSrflx[] = "srflx";
157// TODO: How to map the prflx with circket candidate type
158// static const char kCandidatePrflx[] = "prflx";
159static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000160static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000161
162static const char kSdpDelimiterEqual = '=';
163static const char kSdpDelimiterSpace = ' ';
164static const char kSdpDelimiterColon = ':';
165static const char kSdpDelimiterSemicolon = ';';
166static const char kSdpDelimiterSlash = '/';
167static const char kNewLine = '\n';
168static const char kReturn = '\r';
169static const char kLineBreak[] = "\r\n";
170
171// TODO: Generate the Session and Time description
172// instead of hardcoding.
173static const char kSessionVersion[] = "v=0";
174// RFC 4566
175static const char kSessionOriginUsername[] = "-";
176static const char kSessionOriginSessionId[] = "0";
177static const char kSessionOriginSessionVersion[] = "0";
178static const char kSessionOriginNettype[] = "IN";
179static const char kSessionOriginAddrtype[] = "IP4";
180static const char kSessionOriginAddress[] = "127.0.0.1";
181static const char kSessionName[] = "s=-";
182static const char kTimeDescription[] = "t=0 0";
183static const char kAttrGroup[] = "a=group:BUNDLE";
184static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000185static const char kConnectionIpv4Addrtype[] = "IP4";
186static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187static const char kMediaTypeVideo[] = "video";
188static const char kMediaTypeAudio[] = "audio";
189static const char kMediaTypeData[] = "application";
190static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000191// draft-ietf-mmusic-trickle-ice-01
192// When no candidates have been gathered, set the connection
193// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000194// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
195// Use IPV4 per default.
196static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000197static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000198// RFC 3556
199static const char kApplicationSpecificMaximum[] = "AS";
200
201static const int kDefaultVideoClockrate = 90000;
202
203// ISAC special-case.
204static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
205static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
206static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
207
wu@webrtc.org78187522013-10-07 23:32:02 +0000208static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000209
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000210// RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
211// types.
212const int kWildcardPayloadType = -1;
213
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000214struct SsrcInfo {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200215 uint32_t ssrc_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000216 std::string cname;
deadbeef9d3584c2016-02-16 17:54:10 -0800217 std::string stream_id;
218 std::string track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000219
220 // For backward compatibility.
221 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
222 std::string label;
223 std::string mslabel;
224};
225typedef std::vector<SsrcInfo> SsrcInfoVec;
226typedef std::vector<SsrcGroup> SsrcGroupVec;
227
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000228template <class T>
229static void AddFmtpLine(const T& codec, std::string* message);
230static void BuildMediaDescription(const ContentInfo* content_info,
231 const TransportInfo* transport_info,
232 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000233 const std::vector<Candidate>& candidates,
deadbeef9d3584c2016-02-16 17:54:10 -0800234 bool unified_plan_sdp,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000235 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000236static void BuildSctpContentAttributes(std::string* message, int sctp_port);
deadbeef9d3584c2016-02-16 17:54:10 -0800237static void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
238 const MediaType media_type,
239 bool unified_plan_sdp,
240 std::string* message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000241static void BuildRtpMap(const MediaContentDescription* media_desc,
242 const MediaType media_type,
243 std::string* message);
244static void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -0800245 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000246 std::string* message);
247static void BuildIceOptions(const std::vector<std::string>& transport_options,
248 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000249static bool IsRtp(const std::string& protocol);
250static bool IsDtlsSctp(const std::string& protocol);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000251static bool ParseSessionDescription(const std::string& message, size_t* pos,
252 std::string* session_id,
253 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000254 TransportDescription* session_td,
255 RtpHeaderExtensions* session_extmaps,
256 cricket::SessionDescription* desc,
257 SdpParseError* error);
258static bool ParseGroupAttribute(const std::string& line,
259 cricket::SessionDescription* desc,
260 SdpParseError* error);
261static bool ParseMediaDescription(
262 const std::string& message,
263 const TransportDescription& session_td,
264 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000265 size_t* pos, cricket::SessionDescription* desc,
266 std::vector<JsepIceCandidate*>* candidates,
267 SdpParseError* error);
268static bool ParseContent(const std::string& message,
269 const MediaType media_type,
270 int mline_index,
271 const std::string& protocol,
272 const std::vector<int>& codec_preference,
273 size_t* pos,
274 std::string* content_name,
275 MediaContentDescription* media_desc,
276 TransportDescription* transport,
277 std::vector<JsepIceCandidate*>* candidates,
278 SdpParseError* error);
279static bool ParseSsrcAttribute(const std::string& line,
280 SsrcInfoVec* ssrc_infos,
281 SdpParseError* error);
282static bool ParseSsrcGroupAttribute(const std::string& line,
283 SsrcGroupVec* ssrc_groups,
284 SdpParseError* error);
285static bool ParseCryptoAttribute(const std::string& line,
286 MediaContentDescription* media_desc,
287 SdpParseError* error);
288static bool ParseRtpmapAttribute(const std::string& line,
289 const MediaType media_type,
290 const std::vector<int>& codec_preference,
291 MediaContentDescription* media_desc,
292 SdpParseError* error);
293static bool ParseFmtpAttributes(const std::string& line,
294 const MediaType media_type,
295 MediaContentDescription* media_desc,
296 SdpParseError* error);
297static bool ParseFmtpParam(const std::string& line, std::string* parameter,
298 std::string* value, SdpParseError* error);
299static bool ParseCandidate(const std::string& message, Candidate* candidate,
300 SdpParseError* error, bool is_raw);
301static bool ParseRtcpFbAttribute(const std::string& line,
302 const MediaType media_type,
303 MediaContentDescription* media_desc,
304 SdpParseError* error);
305static bool ParseIceOptions(const std::string& line,
306 std::vector<std::string>* transport_options,
307 SdpParseError* error);
308static bool ParseExtmap(const std::string& line,
309 RtpHeaderExtension* extmap,
310 SdpParseError* error);
311static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000312 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000313 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000314static bool ParseDtlsSetup(const std::string& line,
315 cricket::ConnectionRole* role,
316 SdpParseError* error);
deadbeef9d3584c2016-02-16 17:54:10 -0800317static bool ParseMsidAttribute(const std::string& line,
318 std::string* stream_id,
319 std::string* track_id,
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
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800571// |msid_stream_id| and |msid_track_id| represent the stream/track ID from the
572// "a=msid" attribute, if it exists. They are empty if the attribute does not
573// exist.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000574void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800575 const std::string& msid_stream_id,
576 const std::string& msid_track_id,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000577 StreamParamsVec* tracks) {
578 ASSERT(tracks != NULL);
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800579 ASSERT(msid_stream_id.empty() == msid_track_id.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000580 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
581 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
582 if (ssrc_info->cname.empty()) {
583 continue;
584 }
585
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800586 std::string stream_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587 std::string track_id;
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800588 if (ssrc_info->stream_id.empty() && !ssrc_info->mslabel.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589 // If there's no msid and there's mslabel, we consider this is a sdp from
590 // a older version of client that doesn't support msid.
591 // In that case, we use the mslabel and label to construct the track.
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800592 stream_id = ssrc_info->mslabel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593 track_id = ssrc_info->label;
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800594 } else if (ssrc_info->stream_id.empty() && !msid_stream_id.empty()) {
595 // If there's no msid in the SSRC attributes, but there's a global one
596 // (from a=msid), use that. This is the case with unified plan SDP.
597 stream_id = msid_stream_id;
598 track_id = msid_track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000599 } else {
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800600 stream_id = ssrc_info->stream_id;
deadbeef9d3584c2016-02-16 17:54:10 -0800601 track_id = ssrc_info->track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000602 }
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800603 // If a stream/track ID wasn't populated from the SSRC attributes OR the
604 // msid attribute, use default/random values.
605 if (stream_id.empty()) {
606 stream_id = kDefaultMsid;
607 }
608 if (track_id.empty()) {
609 // TODO(ronghuawu): What should we do if the track id doesn't appear?
610 // Create random string (which will be used as track label later)?
611 track_id = rtc::CreateRandomString(8);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000612 }
613
614 StreamParamsVec::iterator track = tracks->begin();
615 for (; track != tracks->end(); ++track) {
616 if (track->id == track_id) {
617 break;
618 }
619 }
620 if (track == tracks->end()) {
621 // If we don't find an existing track, create a new one.
622 tracks->push_back(StreamParams());
623 track = tracks->end() - 1;
624 }
625 track->add_ssrc(ssrc_info->ssrc_id);
626 track->cname = ssrc_info->cname;
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800627 track->sync_label = stream_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000628 track->id = track_id;
629 }
630}
631
632void GetMediaStreamLabels(const ContentInfo* content,
633 std::set<std::string>* labels) {
634 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000635 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000636 content->description);
637 const cricket::StreamParamsVec& streams = media_desc->streams();
638 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
639 it != streams.end(); ++it) {
640 labels->insert(it->sync_label);
641 }
642}
643
644// RFC 5245
645// It is RECOMMENDED that default candidates be chosen based on the
646// likelihood of those candidates to work with the peer that is being
647// contacted. It is RECOMMENDED that relayed > reflexive > host.
648static const int kPreferenceUnknown = 0;
649static const int kPreferenceHost = 1;
650static const int kPreferenceReflexive = 2;
651static const int kPreferenceRelayed = 3;
652
653static int GetCandidatePreferenceFromType(const std::string& type) {
654 int preference = kPreferenceUnknown;
655 if (type == cricket::LOCAL_PORT_TYPE) {
656 preference = kPreferenceHost;
657 } else if (type == cricket::STUN_PORT_TYPE) {
658 preference = kPreferenceReflexive;
659 } else if (type == cricket::RELAY_PORT_TYPE) {
660 preference = kPreferenceRelayed;
661 } else {
662 ASSERT(false);
663 }
664 return preference;
665}
666
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000667// Get ip and port of the default destination from the |candidates| with the
668// given value of |component_id|. The default candidate should be the one most
669// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000670// RFC 5245
671// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
672// TODO: Decide the default destination in webrtcsession and
673// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000674static void GetDefaultDestination(
675 const std::vector<Candidate>& candidates,
676 int component_id, std::string* port,
677 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000678 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000679 *port = kDummyPort;
680 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000681 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000682 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000683 for (std::vector<Candidate>::const_iterator it = candidates.begin();
684 it != candidates.end(); ++it) {
685 if (it->component() != component_id) {
686 continue;
687 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000688 // Default destination should be UDP only.
689 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000690 continue;
691 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000692 const int preference = GetCandidatePreferenceFromType(it->type());
693 const int family = it->address().ipaddr().family();
694 // See if this candidate is more preferable then the current one if it's the
695 // same family. Or if the current family is IPv4 already so we could safely
696 // ignore all IPv6 ones. WebRTC bug 4269.
697 // http://code.google.com/p/webrtc/issues/detail?id=4269
698 if ((preference <= current_preference && current_family == family) ||
699 (current_family == AF_INET && family == AF_INET6)) {
700 continue;
701 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000702 if (family == AF_INET) {
703 addr_type->assign(kConnectionIpv4Addrtype);
704 } else if (family == AF_INET6) {
705 addr_type->assign(kConnectionIpv6Addrtype);
706 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000707 current_preference = preference;
708 current_family = family;
709 *port = it->address().PortAsString();
710 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000711 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000712}
713
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000714// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000715static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000716 const std::vector<Candidate>& candidates,
jbauch083b73f2015-07-16 02:46:32 -0700717 const std::string& mline,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000718 std::string* message) {
719 std::string new_lines;
720 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000721 // RFC 4566
722 // m=<media> <port> <proto> <fmt> ...
723 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000724 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725 if (fields.size() < 3) {
726 return;
727 }
728
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000729 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000730 std::string rtp_port, rtp_ip, addr_type;
731 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
732 &rtp_port, &rtp_ip, &addr_type);
733 // Found default RTP candidate.
734 // RFC 5245
735 // The default candidates are added to the SDP as the default
736 // destination for media. For streams based on RTP, this is done by
737 // placing the IP address and port of the RTP candidate into the c and m
738 // lines, respectively.
739 // Update the port in the m line.
740 // If this is a m-line with port equal to 0, we don't change it.
741 if (fields[1] != kMediaPortRejected) {
742 new_lines.replace(fields[0].size() + 1,
743 fields[1].size(),
744 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000745 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000746 // Add the c line.
747 // RFC 4566
748 // c=<nettype> <addrtype> <connection-address>
749 InitLine(kLineTypeConnection, kConnectionNettype, &os);
750 os << " " << addr_type << " " << rtp_ip;
751 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000752 message->append(new_lines);
753}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000754
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000755// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
756static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000757 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
758 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
759 &rtcp_port, &rtcp_ip, &addr_type);
760 // Found default RTCP candidate.
761 // RFC 5245
762 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
763 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000764
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000765 // RFC 3605
766 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
767 // connection-address] CRLF
768 std::ostringstream os;
769 InitAttrLine(kAttributeRtcp, &os);
770 os << kSdpDelimiterColon
771 << rtcp_port << " "
772 << kConnectionNettype << " "
773 << addr_type << " "
774 << rtcp_ip;
775 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000776 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000777}
778
779// Get candidates according to the mline index from SessionDescriptionInterface.
780static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
781 int mline_index,
782 std::vector<Candidate>* candidates) {
783 if (!candidates) {
784 return;
785 }
786 const IceCandidateCollection* cc = desci.candidates(mline_index);
787 for (size_t i = 0; i < cc->count(); ++i) {
788 const IceCandidateInterface* candidate = cc->at(i);
789 candidates->push_back(candidate->candidate());
790 }
791}
792
deadbeef9d3584c2016-02-16 17:54:10 -0800793std::string SdpSerialize(const JsepSessionDescription& jdesc,
794 bool unified_plan_sdp) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000795 const cricket::SessionDescription* desc = jdesc.description();
796 if (!desc) {
797 return "";
798 }
799
800 std::string message;
801
802 // Session Description.
803 AddLine(kSessionVersion, &message);
804 // Session Origin
805 // RFC 4566
806 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
807 // <unicast-address>
808 std::ostringstream os;
809 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
jbauch083b73f2015-07-16 02:46:32 -0700810 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700812 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813 kSessionOriginSessionVersion : jdesc.session_version();
814 os << " " << session_id << " " << session_version << " "
815 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
816 << kSessionOriginAddress;
817 AddLine(os.str(), &message);
818 AddLine(kSessionName, &message);
819
820 // Time Description.
821 AddLine(kTimeDescription, &message);
822
823 // Group
824 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
825 std::string group_line = kAttrGroup;
826 const cricket::ContentGroup* group =
827 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
828 ASSERT(group != NULL);
829 const cricket::ContentNames& content_names = group->content_names();
830 for (cricket::ContentNames::const_iterator it = content_names.begin();
831 it != content_names.end(); ++it) {
832 group_line.append(" ");
833 group_line.append(*it);
834 }
835 AddLine(group_line, &message);
836 }
837
838 // MediaStream semantics
839 InitAttrLine(kAttributeMsidSemantics, &os);
840 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000841
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842 std::set<std::string> media_stream_labels;
843 const ContentInfo* audio_content = GetFirstAudioContent(desc);
844 if (audio_content)
845 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000846
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000847 const ContentInfo* video_content = GetFirstVideoContent(desc);
848 if (video_content)
849 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000850
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000851 for (std::set<std::string>::const_iterator it =
852 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
853 os << " " << *it;
854 }
855 AddLine(os.str(), &message);
856
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000857 // Preserve the order of the media contents.
858 int mline_index = -1;
859 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
860 it != desc->contents().end(); ++it) {
861 const MediaContentDescription* mdesc =
862 static_cast<const MediaContentDescription*>(it->description);
863 std::vector<Candidate> candidates;
864 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
deadbeef9d3584c2016-02-16 17:54:10 -0800865 BuildMediaDescription(&*it, desc->GetTransportInfoByName(it->name),
866 mdesc->type(), candidates, unified_plan_sdp,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000867 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000868 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000869 return message;
870}
871
872// Serializes the passed in IceCandidateInterface to a SDP string.
873// candidate - The candidate to be serialized.
874std::string SdpSerializeCandidate(
875 const IceCandidateInterface& candidate) {
876 std::string message;
877 std::vector<cricket::Candidate> candidates;
878 candidates.push_back(candidate.candidate());
honghaiza54a0802015-12-16 18:37:23 -0800879 BuildCandidate(candidates, true, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000880 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
881 // just candidate:<candidate> not a=candidate:<blah>CRLF
882 ASSERT(message.find("a=") == 0);
883 message.erase(0, 2);
884 ASSERT(message.find(kLineBreak) == message.size() - 2);
885 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886 return message;
887}
888
889bool SdpDeserialize(const std::string& message,
890 JsepSessionDescription* jdesc,
891 SdpParseError* error) {
892 std::string session_id;
893 std::string session_version;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700894 TransportDescription session_td("", "");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000895 RtpHeaderExtensions session_extmaps;
896 cricket::SessionDescription* desc = new cricket::SessionDescription();
897 std::vector<JsepIceCandidate*> candidates;
898 size_t current_pos = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899
900 // Session Description
901 if (!ParseSessionDescription(message, &current_pos, &session_id,
deadbeefc80741f2015-10-22 13:14:45 -0700902 &session_version, &session_td, &session_extmaps,
903 desc, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000904 delete desc;
905 return false;
906 }
907
908 // Media Description
deadbeefc80741f2015-10-22 13:14:45 -0700909 if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
910 desc, &candidates, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000911 delete desc;
912 for (std::vector<JsepIceCandidate*>::const_iterator
913 it = candidates.begin(); it != candidates.end(); ++it) {
914 delete *it;
915 }
916 return false;
917 }
918
919 jdesc->Initialize(desc, session_id, session_version);
920
921 for (std::vector<JsepIceCandidate*>::const_iterator
922 it = candidates.begin(); it != candidates.end(); ++it) {
923 jdesc->AddCandidate(*it);
924 delete *it;
925 }
926 return true;
927}
928
929bool SdpDeserializeCandidate(const std::string& message,
930 JsepIceCandidate* jcandidate,
931 SdpParseError* error) {
932 ASSERT(jcandidate != NULL);
933 Candidate candidate;
934 if (!ParseCandidate(message, &candidate, error, true)) {
935 return false;
936 }
937 jcandidate->SetCandidate(candidate);
938 return true;
939}
940
941bool ParseCandidate(const std::string& message, Candidate* candidate,
942 SdpParseError* error, bool is_raw) {
943 ASSERT(candidate != NULL);
944
945 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000946 std::string first_line = message;
947 size_t pos = 0;
948 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000950 // Makes sure |message| contains only one line.
951 if (message.size() > first_line.size()) {
952 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700953 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
954 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000955 return ParseFailed(message, 0, "Expect one line only", error);
956 }
957 }
958
959 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
960 // candidate:<candidate> when trickled, but we still support
961 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
962 // from the SDP.
963 if (IsLineType(first_line, kLineTypeAttributes)) {
964 first_line = first_line.substr(kLinePrefixLength);
965 }
966
967 std::string attribute_candidate;
968 std::string candidate_value;
969
970 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700971 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
972 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000973 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974 if (is_raw) {
975 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000976 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000977 << ":" << "<candidate-str>";
978 return ParseFailed(first_line, 0, description.str(), error);
979 } else {
980 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
981 kAttributeCandidate, error);
982 }
983 }
984
985 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000986 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
987
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988 // RFC 5245
989 // a=candidate:<foundation> <component-id> <transport> <priority>
990 // <connection-address> <port> typ <candidate-types>
991 // [raddr <connection-address>] [rport <port>]
992 // *(SP extension-att-name SP extension-att-value)
993 const size_t expected_min_fields = 8;
994 if (fields.size() < expected_min_fields ||
995 (fields[6] != kAttributeCandidateTyp)) {
996 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
997 }
jbauch083b73f2015-07-16 02:46:32 -0700998 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000999
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001000 int component_id = 0;
1001 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1002 return false;
1003 }
jbauch083b73f2015-07-16 02:46:32 -07001004 const std::string& transport = fields[2];
Peter Boström0c4e06b2015-10-07 12:23:21 +02001005 uint32_t priority = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001006 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1007 return false;
1008 }
jbauch083b73f2015-07-16 02:46:32 -07001009 const std::string& connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001010 int port = 0;
1011 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1012 return false;
1013 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001014 SocketAddress address(connection_address, port);
1015
1016 cricket::ProtocolType protocol;
1017 if (!StringToProto(transport.c_str(), &protocol)) {
1018 return ParseFailed(first_line, "Unsupported transport type.", error);
1019 }
1020
1021 std::string candidate_type;
jbauch083b73f2015-07-16 02:46:32 -07001022 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001023 if (type == kCandidateHost) {
1024 candidate_type = cricket::LOCAL_PORT_TYPE;
1025 } else if (type == kCandidateSrflx) {
1026 candidate_type = cricket::STUN_PORT_TYPE;
1027 } else if (type == kCandidateRelay) {
1028 candidate_type = cricket::RELAY_PORT_TYPE;
1029 } else {
1030 return ParseFailed(first_line, "Unsupported candidate type.", error);
1031 }
1032
1033 size_t current_position = expected_min_fields;
1034 SocketAddress related_address;
1035 // The 2 optional fields for related address
1036 // [raddr <connection-address>] [rport <port>]
1037 if (fields.size() >= (current_position + 2) &&
1038 fields[current_position] == kAttributeCandidateRaddr) {
1039 related_address.SetIP(fields[++current_position]);
1040 ++current_position;
1041 }
1042 if (fields.size() >= (current_position + 2) &&
1043 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001044 int port = 0;
1045 if (!GetValueFromString(
1046 first_line, fields[++current_position], &port, error)) {
1047 return false;
1048 }
1049 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050 ++current_position;
1051 }
1052
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001053 // If this is a TCP candidate, it has additional extension as defined in
1054 // RFC 6544.
1055 std::string tcptype;
1056 if (fields.size() >= (current_position + 2) &&
1057 fields[current_position] == kTcpCandidateType) {
1058 tcptype = fields[++current_position];
1059 ++current_position;
1060
1061 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1062 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1063 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1064 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1065 }
1066
1067 if (protocol != cricket::PROTO_TCP) {
1068 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1069 }
1070 }
1071
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001072 // Extension
honghaiza54a0802015-12-16 18:37:23 -08001073 // Though non-standard, we support the ICE ufrag and pwd being signaled on
1074 // the candidate to avoid issues with confusing which generation a candidate
1075 // belongs to when trickling multiple generations at the same time.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001076 std::string username;
1077 std::string password;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001078 uint32_t generation = 0;
honghaize1a0c942016-02-16 14:54:56 -08001079 uint32_t network_cost = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001080 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1081 // RFC 5245
1082 // *(SP extension-att-name SP extension-att-value)
1083 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001084 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1085 return false;
1086 }
honghaiza54a0802015-12-16 18:37:23 -08001087 } else if (fields[i] == kAttributeCandidateUfrag) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088 username = fields[++i];
honghaiza54a0802015-12-16 18:37:23 -08001089 } else if (fields[i] == kAttributeCandidatePwd) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001090 password = fields[++i];
honghaize1a0c942016-02-16 14:54:56 -08001091 } else if (fields[i] == kAttributeCandidateNetworkCost) {
1092 if (!GetValueFromString(first_line, fields[++i], &network_cost, error)) {
1093 return false;
1094 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095 } else {
1096 // Skip the unknown extension.
1097 ++i;
1098 }
1099 }
1100
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001101 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001102 address, priority, username, password, candidate_type,
1103 generation, foundation);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001104 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001105 candidate->set_tcptype(tcptype);
honghaize1a0c942016-02-16 14:54:56 -08001106 candidate->set_network_cost(std::min(network_cost, cricket::kMaxNetworkCost));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001107 return true;
1108}
1109
1110bool ParseIceOptions(const std::string& line,
1111 std::vector<std::string>* transport_options,
1112 SdpParseError* error) {
1113 std::string ice_options;
1114 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1115 return false;
1116 }
1117 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001118 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001119 for (size_t i = 0; i < fields.size(); ++i) {
1120 transport_options->push_back(fields[i]);
1121 }
1122 return true;
1123}
1124
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001125bool ParseSctpPort(const std::string& line,
1126 int* sctp_port,
1127 SdpParseError* error) {
1128 // draft-ietf-mmusic-sctp-sdp-07
1129 // a=sctp-port
1130 std::vector<std::string> fields;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001131 const size_t expected_min_fields = 2;
lally69f57602015-10-08 10:15:04 -07001132 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1133 if (fields.size() < expected_min_fields) {
1134 fields.resize(0);
1135 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpace, &fields);
1136 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001137 if (fields.size() < expected_min_fields) {
1138 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1139 }
1140 if (!rtc::FromString(fields[1], sctp_port)) {
lally69f57602015-10-08 10:15:04 -07001141 return ParseFailed(line, "Invalid sctp port value.", error);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001142 }
1143 return true;
1144}
1145
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1147 SdpParseError* error) {
1148 // RFC 5285
1149 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1150 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001151 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152 kSdpDelimiterSpace, &fields);
1153 const size_t expected_min_fields = 2;
1154 if (fields.size() < expected_min_fields) {
1155 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1156 }
1157 std::string uri = fields[1];
1158
1159 std::string value_direction;
1160 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1161 return false;
1162 }
1163 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001164 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001165 int value = 0;
1166 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1167 return false;
1168 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001169
1170 *extmap = RtpHeaderExtension(uri, value);
1171 return true;
1172}
1173
1174void BuildMediaDescription(const ContentInfo* content_info,
1175 const TransportInfo* transport_info,
1176 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001177 const std::vector<Candidate>& candidates,
deadbeef9d3584c2016-02-16 17:54:10 -08001178 bool unified_plan_sdp,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001179 std::string* message) {
1180 ASSERT(message != NULL);
1181 if (content_info == NULL || message == NULL) {
1182 return;
1183 }
1184 // TODO: Rethink if we should use sprintfn instead of stringstream.
1185 // According to the style guide, streams should only be used for logging.
1186 // http://google-styleguide.googlecode.com/svn/
1187 // trunk/cppguide.xml?showone=Streams#Streams
1188 std::ostringstream os;
1189 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001190 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 content_info->description);
1192 ASSERT(media_desc != NULL);
1193
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001194 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001195
1196 // RFC 4566
1197 // m=<media> <port> <proto> <fmt>
1198 // fmt is a list of payload type numbers that MAY be used in the session.
1199 const char* type = NULL;
1200 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1201 type = kMediaTypeAudio;
1202 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1203 type = kMediaTypeVideo;
1204 else if (media_type == cricket::MEDIA_TYPE_DATA)
1205 type = kMediaTypeData;
1206 else
1207 ASSERT(false);
1208
1209 std::string fmt;
1210 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1211 const VideoContentDescription* video_desc =
1212 static_cast<const VideoContentDescription*>(media_desc);
1213 for (std::vector<cricket::VideoCodec>::const_iterator it =
1214 video_desc->codecs().begin();
1215 it != video_desc->codecs().end(); ++it) {
1216 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001217 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001218 }
1219 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1220 const AudioContentDescription* audio_desc =
1221 static_cast<const AudioContentDescription*>(media_desc);
1222 for (std::vector<cricket::AudioCodec>::const_iterator it =
1223 audio_desc->codecs().begin();
1224 it != audio_desc->codecs().end(); ++it) {
1225 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001226 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001227 }
1228 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001229 const DataContentDescription* data_desc =
1230 static_cast<const DataContentDescription*>(media_desc);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001231 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001232 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001233
1234 for (std::vector<cricket::DataCodec>::const_iterator it =
1235 data_desc->codecs().begin();
1236 it != data_desc->codecs().end(); ++it) {
1237 if (it->id == cricket::kGoogleSctpDataCodecId &&
1238 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1239 break;
1240 }
1241 }
1242
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001243 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001244 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001245 for (std::vector<cricket::DataCodec>::const_iterator it =
1246 data_desc->codecs().begin();
1247 it != data_desc->codecs().end(); ++it) {
1248 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001249 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001250 }
1251 }
1252 }
1253 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1254 // to 0.
1255 if (fmt.empty()) {
1256 fmt = " 0";
1257 }
1258
1259 // The port number in the m line will be updated later when associate with
1260 // the candidates.
1261 // RFC 3264
1262 // To reject an offered stream, the port number in the corresponding stream in
1263 // the answer MUST be set to zero.
jbauch083b73f2015-07-16 02:46:32 -07001264 const std::string& port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001265 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001266
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001267 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001268 transport_info->description.identity_fingerprint.get() : NULL;
1269
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001270 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001271 InitLine(kLineTypeMedia, type, &os);
1272 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001273 std::string mline = os.str();
1274 UpdateMediaDefaultDestination(candidates, mline, message);
1275
1276 // RFC 4566
1277 // b=AS:<bandwidth>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001278 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001279 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1280 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1281 AddLine(os.str(), message);
1282 }
1283
1284 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001285 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001286 std::string rtcp_line = GetRtcpLine(candidates);
1287 if (!rtcp_line.empty()) {
1288 AddLine(rtcp_line, message);
1289 }
1290 }
1291
honghaiza54a0802015-12-16 18:37:23 -08001292 // Build the a=candidate lines. We don't include ufrag and pwd in the
1293 // candidates in the SDP to avoid redundancy.
1294 BuildCandidate(candidates, false, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295
1296 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1297 if (transport_info) {
1298 // RFC 5245
1299 // ice-pwd-att = "ice-pwd" ":" password
1300 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1301 // ice-ufrag
deadbeef3f7219b2015-12-28 15:17:14 -08001302 if (!transport_info->description.ice_ufrag.empty()) {
1303 InitAttrLine(kAttributeIceUfrag, &os);
1304 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1305 AddLine(os.str(), message);
1306 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307 // ice-pwd
deadbeef3f7219b2015-12-28 15:17:14 -08001308 if (!transport_info->description.ice_pwd.empty()) {
1309 InitAttrLine(kAttributeIcePwd, &os);
1310 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1311 AddLine(os.str(), message);
1312 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313
1314 // draft-petithuguenin-mmusic-ice-attributes-level-03
1315 BuildIceOptions(transport_info->description.transport_options, message);
1316
1317 // RFC 4572
1318 // fingerprint-attribute =
1319 // "fingerprint" ":" hash-func SP fingerprint
1320 if (fp) {
1321 // Insert the fingerprint attribute.
1322 InitAttrLine(kAttributeFingerprint, &os);
1323 os << kSdpDelimiterColon
1324 << fp->algorithm << kSdpDelimiterSpace
1325 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001327
1328 // Inserting setup attribute.
1329 if (transport_info->description.connection_role !=
1330 cricket::CONNECTIONROLE_NONE) {
1331 // Making sure we are not using "passive" mode.
1332 cricket::ConnectionRole role =
1333 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001334 std::string dtls_role_str;
1335 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001336 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001337 os << kSdpDelimiterColon << dtls_role_str;
1338 AddLine(os.str(), message);
1339 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001340 }
1341 }
1342
1343 // RFC 3388
1344 // mid-attribute = "a=mid:" identification-tag
1345 // identification-tag = token
1346 // Use the content name as the mid identification-tag.
1347 InitAttrLine(kAttributeMid, &os);
1348 os << kSdpDelimiterColon << content_info->name;
1349 AddLine(os.str(), message);
1350
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001351 if (IsDtlsSctp(media_desc->protocol())) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001352 BuildSctpContentAttributes(message, sctp_port);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001353 } else if (IsRtp(media_desc->protocol())) {
deadbeef9d3584c2016-02-16 17:54:10 -08001354 BuildRtpContentAttributes(media_desc, media_type, unified_plan_sdp,
1355 message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001356 }
1357}
1358
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001359void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001360 // draft-ietf-mmusic-sctp-sdp-04
1361 // a=sctpmap:sctpmap-number protocol [streams]
lally69f57602015-10-08 10:15:04 -07001362 // TODO(lally): switch this over to mmusic-sctp-sdp-12 (or later), with
1363 // 'a=sctp-port:'
wu@webrtc.org78187522013-10-07 23:32:02 +00001364 std::ostringstream os;
1365 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001366 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001367 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1368 << (cricket::kMaxSctpSid + 1);
1369 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370}
1371
deadbeef9d3584c2016-02-16 17:54:10 -08001372// If unified_plan_sdp is true, will use "a=msid".
1373void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
1374 const MediaType media_type,
1375 bool unified_plan_sdp,
1376 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001377 std::ostringstream os;
1378 // RFC 5285
1379 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1380 // The definitions MUST be either all session level or all media level. This
1381 // implementation uses all media level.
1382 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1383 InitAttrLine(kAttributeExtmap, &os);
1384 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1385 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1386 AddLine(os.str(), message);
1387 }
1388
1389 // RFC 3264
1390 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
deadbeefc80741f2015-10-22 13:14:45 -07001391 switch (media_desc->direction()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 case cricket::MD_INACTIVE:
1393 InitAttrLine(kAttributeInactive, &os);
1394 break;
1395 case cricket::MD_SENDONLY:
1396 InitAttrLine(kAttributeSendOnly, &os);
1397 break;
1398 case cricket::MD_RECVONLY:
1399 InitAttrLine(kAttributeRecvOnly, &os);
1400 break;
1401 case cricket::MD_SENDRECV:
1402 default:
1403 InitAttrLine(kAttributeSendRecv, &os);
1404 break;
1405 }
1406 AddLine(os.str(), message);
1407
deadbeef9d3584c2016-02-16 17:54:10 -08001408 // draft-ietf-mmusic-msid-11
1409 // a=msid:<stream id> <track id>
1410 if (unified_plan_sdp && !media_desc->streams().empty()) {
1411 if (media_desc->streams().size() > 1u) {
1412 LOG(LS_WARNING) << "Trying to serialize unified plan SDP with more than "
1413 << "one track in a media section. Omitting 'a=msid'.";
1414 } else {
1415 auto track = media_desc->streams().begin();
1416 const std::string& stream_id = track->sync_label;
deadbeef9d3584c2016-02-16 17:54:10 -08001417 InitAttrLine(kAttributeMsid, &os);
1418 os << kSdpDelimiterColon << stream_id << kSdpDelimiterSpace << track->id;
1419 AddLine(os.str(), message);
1420 }
1421 }
1422
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001423 // RFC 5761
1424 // a=rtcp-mux
1425 if (media_desc->rtcp_mux()) {
1426 InitAttrLine(kAttributeRtcpMux, &os);
1427 AddLine(os.str(), message);
1428 }
1429
deadbeef13871492015-12-09 12:37:51 -08001430 // RFC 5506
1431 // a=rtcp-rsize
1432 if (media_desc->rtcp_reduced_size()) {
1433 InitAttrLine(kAttributeRtcpReducedSize, &os);
1434 AddLine(os.str(), message);
1435 }
1436
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001437 // RFC 4568
1438 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1439 for (std::vector<CryptoParams>::const_iterator it =
1440 media_desc->cryptos().begin();
1441 it != media_desc->cryptos().end(); ++it) {
1442 InitAttrLine(kAttributeCrypto, &os);
1443 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1444 << it->key_params;
1445 if (!it->session_params.empty()) {
1446 os << " " << it->session_params;
1447 }
1448 AddLine(os.str(), message);
1449 }
1450
1451 // RFC 4566
1452 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1453 // [/<encodingparameters>]
1454 BuildRtpMap(media_desc, media_type, message);
1455
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001456 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1457 track != media_desc->streams().end(); ++track) {
1458 // Require that the track belongs to a media stream,
1459 // ie the sync_label is set. This extra check is necessary since the
1460 // MediaContentDescription always contains a streamparam with an ssrc even
1461 // if no track or media stream have been created.
1462 if (track->sync_label.empty()) continue;
1463
1464 // Build the ssrc-group lines.
1465 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1466 // RFC 5576
1467 // a=ssrc-group:<semantics> <ssrc-id> ...
1468 if (track->ssrc_groups[i].ssrcs.empty()) {
1469 continue;
1470 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 InitAttrLine(kAttributeSsrcGroup, &os);
1472 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001473 std::vector<uint32_t>::const_iterator ssrc =
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001474 track->ssrc_groups[i].ssrcs.begin();
1475 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001476 os << kSdpDelimiterSpace << rtc::ToString<uint32_t>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001477 }
1478 AddLine(os.str(), message);
1479 }
1480 // Build the ssrc lines for each ssrc.
1481 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001482 uint32_t ssrc = track->ssrcs[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001483 // RFC 5576
1484 // a=ssrc:<ssrc-id> cname:<value>
1485 AddSsrcLine(ssrc, kSsrcAttributeCname,
1486 track->cname, message);
1487
1488 // draft-alvestrand-mmusic-msid-00
1489 // a=ssrc:<ssrc-id> msid:identifier [appdata]
deadbeef9d3584c2016-02-16 17:54:10 -08001490 // The appdata consists of the "id" attribute of a MediaStreamTrack,
1491 // which corresponds to the "id" attribute of StreamParams.
1492 const std::string& stream_id = track->sync_label;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001493 InitAttrLine(kAttributeSsrc, &os);
1494 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
deadbeef9d3584c2016-02-16 17:54:10 -08001495 << kSsrcAttributeMsid << kSdpDelimiterColon << stream_id
1496 << kSdpDelimiterSpace << track->id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001497 AddLine(os.str(), message);
1498
deadbeef9d3584c2016-02-16 17:54:10 -08001499 // TODO(ronghuawu): Remove below code which is for backward
1500 // compatibility.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001501 // draft-alvestrand-rtcweb-mid-01
1502 // a=ssrc:<ssrc-id> mslabel:<value>
1503 // The label isn't yet defined.
1504 // a=ssrc:<ssrc-id> label:<value>
1505 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1506 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1507 }
1508 }
1509}
1510
1511void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1512 // fmtp header: a=fmtp:|payload_type| <parameters>
1513 // Add a=fmtp
1514 InitAttrLine(kAttributeFmtp, os);
1515 // Add :|payload_type|
1516 *os << kSdpDelimiterColon << payload_type;
1517}
1518
1519void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1520 // rtcp-fb header: a=rtcp-fb:|payload_type|
1521 // <parameters>/<ccm <ccm_parameters>>
1522 // Add a=rtcp-fb
1523 InitAttrLine(kAttributeRtcpFb, os);
1524 // Add :
1525 *os << kSdpDelimiterColon;
1526 if (payload_type == kWildcardPayloadType) {
1527 *os << "*";
1528 } else {
1529 *os << payload_type;
1530 }
1531}
1532
1533void WriteFmtpParameter(const std::string& parameter_name,
1534 const std::string& parameter_value,
1535 std::ostringstream* os) {
1536 // fmtp parameters: |parameter_name|=|parameter_value|
1537 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1538}
1539
1540void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1541 std::ostringstream* os) {
1542 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1543 fmtp != parameters.end(); ++fmtp) {
1544 // Each new parameter, except the first one starts with ";" and " ".
1545 if (fmtp != parameters.begin()) {
1546 *os << kSdpDelimiterSemicolon;
1547 }
1548 *os << kSdpDelimiterSpace;
1549 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1550 }
1551}
1552
1553bool IsFmtpParam(const std::string& name) {
1554 const char* kFmtpParams[] = {
1555 kCodecParamMinPTime, kCodecParamSPropStereo,
Minyue Li7100dcd2015-03-27 05:05:59 +01001556 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamUseDtx,
1557 kCodecParamStartBitrate, kCodecParamMaxBitrate, kCodecParamMinBitrate,
1558 kCodecParamMaxQuantization, kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001559 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1560 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001561 };
tfarina5237aaf2015-11-10 23:44:30 -08001562 for (size_t i = 0; i < arraysize(kFmtpParams); ++i) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001563 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1564 return true;
1565 }
1566 }
1567 return false;
1568}
1569
1570// Retreives fmtp parameters from |params|, which may contain other parameters
1571// as well, and puts them in |fmtp_parameters|.
1572void GetFmtpParams(const cricket::CodecParameterMap& params,
1573 cricket::CodecParameterMap* fmtp_parameters) {
1574 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1575 iter != params.end(); ++iter) {
1576 if (IsFmtpParam(iter->first)) {
1577 (*fmtp_parameters)[iter->first] = iter->second;
1578 }
1579 }
1580}
1581
1582template <class T>
1583void AddFmtpLine(const T& codec, std::string* message) {
1584 cricket::CodecParameterMap fmtp_parameters;
1585 GetFmtpParams(codec.params, &fmtp_parameters);
1586 if (fmtp_parameters.empty()) {
1587 // No need to add an fmtp if it will have no (optional) parameters.
1588 return;
1589 }
1590 std::ostringstream os;
1591 WriteFmtpHeader(codec.id, &os);
1592 WriteFmtpParameters(fmtp_parameters, &os);
1593 AddLine(os.str(), message);
1594 return;
1595}
1596
1597template <class T>
1598void AddRtcpFbLines(const T& codec, std::string* message) {
1599 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1600 codec.feedback_params.params().begin();
1601 iter != codec.feedback_params.params().end(); ++iter) {
1602 std::ostringstream os;
1603 WriteRtcpFbHeader(codec.id, &os);
1604 os << " " << iter->id();
1605 if (!iter->param().empty()) {
1606 os << " " << iter->param();
1607 }
1608 AddLine(os.str(), message);
1609 }
1610}
1611
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001612bool AddSctpDataCodec(DataContentDescription* media_desc,
1613 int sctp_port) {
1614 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1615 return ParseFailed("",
1616 "Can't have multiple sctp port attributes.",
1617 NULL);
1618 }
1619 // Add the SCTP Port number as a pseudo-codec "port" parameter
1620 cricket::DataCodec codec_port(
1621 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1622 0);
1623 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1624 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1625 << sctp_port;
1626 media_desc->AddCodec(codec_port);
1627 return true;
1628}
1629
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001630bool GetMinValue(const std::vector<int>& values, int* value) {
1631 if (values.empty()) {
1632 return false;
1633 }
1634 std::vector<int>::const_iterator found =
1635 std::min_element(values.begin(), values.end());
1636 *value = *found;
1637 return true;
1638}
1639
1640bool GetParameter(const std::string& name,
1641 const cricket::CodecParameterMap& params, int* value) {
1642 std::map<std::string, std::string>::const_iterator found =
1643 params.find(name);
1644 if (found == params.end()) {
1645 return false;
1646 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001647 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001648 return false;
1649 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001650 return true;
1651}
1652
1653void BuildRtpMap(const MediaContentDescription* media_desc,
1654 const MediaType media_type,
1655 std::string* message) {
1656 ASSERT(message != NULL);
1657 ASSERT(media_desc != NULL);
1658 std::ostringstream os;
1659 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1660 const VideoContentDescription* video_desc =
1661 static_cast<const VideoContentDescription*>(media_desc);
1662 for (std::vector<cricket::VideoCodec>::const_iterator it =
1663 video_desc->codecs().begin();
1664 it != video_desc->codecs().end(); ++it) {
1665 // RFC 4566
1666 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1667 // [/<encodingparameters>]
1668 if (it->id != kWildcardPayloadType) {
1669 InitAttrLine(kAttributeRtpmap, &os);
1670 os << kSdpDelimiterColon << it->id << " " << it->name
1671 << "/" << kDefaultVideoClockrate;
1672 AddLine(os.str(), message);
1673 }
1674 AddRtcpFbLines(*it, message);
1675 AddFmtpLine(*it, message);
1676 }
1677 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1678 const AudioContentDescription* audio_desc =
1679 static_cast<const AudioContentDescription*>(media_desc);
1680 std::vector<int> ptimes;
1681 std::vector<int> maxptimes;
1682 int max_minptime = 0;
1683 for (std::vector<cricket::AudioCodec>::const_iterator it =
1684 audio_desc->codecs().begin();
1685 it != audio_desc->codecs().end(); ++it) {
1686 ASSERT(!it->name.empty());
1687 // RFC 4566
1688 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1689 // [/<encodingparameters>]
1690 InitAttrLine(kAttributeRtpmap, &os);
1691 os << kSdpDelimiterColon << it->id << " ";
1692 os << it->name << "/" << it->clockrate;
1693 if (it->channels != 1) {
1694 os << "/" << it->channels;
1695 }
1696 AddLine(os.str(), message);
1697 AddRtcpFbLines(*it, message);
1698 AddFmtpLine(*it, message);
1699 int minptime = 0;
1700 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1701 max_minptime = std::max(minptime, max_minptime);
1702 }
1703 int ptime;
1704 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1705 ptimes.push_back(ptime);
1706 }
1707 int maxptime;
1708 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1709 maxptimes.push_back(maxptime);
1710 }
1711 }
1712 // Populate the maxptime attribute with the smallest maxptime of all codecs
1713 // under the same m-line.
1714 int min_maxptime = INT_MAX;
1715 if (GetMinValue(maxptimes, &min_maxptime)) {
1716 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1717 }
1718 ASSERT(min_maxptime > max_minptime);
1719 // Populate the ptime attribute with the smallest ptime or the largest
1720 // minptime, whichever is the largest, for all codecs under the same m-line.
1721 int ptime = INT_MAX;
1722 if (GetMinValue(ptimes, &ptime)) {
1723 ptime = std::min(ptime, min_maxptime);
1724 ptime = std::max(ptime, max_minptime);
1725 AddAttributeLine(kCodecParamPTime, ptime, message);
1726 }
1727 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1728 const DataContentDescription* data_desc =
1729 static_cast<const DataContentDescription*>(media_desc);
1730 for (std::vector<cricket::DataCodec>::const_iterator it =
1731 data_desc->codecs().begin();
1732 it != data_desc->codecs().end(); ++it) {
1733 // RFC 4566
1734 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1735 // [/<encodingparameters>]
1736 InitAttrLine(kAttributeRtpmap, &os);
1737 os << kSdpDelimiterColon << it->id << " "
1738 << it->name << "/" << it->clockrate;
1739 AddLine(os.str(), message);
1740 }
1741 }
1742}
1743
1744void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -08001745 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001746 std::string* message) {
1747 std::ostringstream os;
1748
1749 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1750 it != candidates.end(); ++it) {
1751 // RFC 5245
1752 // a=candidate:<foundation> <component-id> <transport> <priority>
1753 // <connection-address> <port> typ <candidate-types>
1754 // [raddr <connection-address>] [rport <port>]
1755 // *(SP extension-att-name SP extension-att-value)
1756 std::string type;
1757 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1758 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1759 type = kCandidateHost;
1760 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1761 type = kCandidateSrflx;
1762 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1763 type = kCandidateRelay;
1764 } else {
1765 ASSERT(false);
Peter Thatcher019087f2015-04-28 09:06:26 -07001766 // Never write out candidates if we don't know the type.
1767 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001768 }
1769
1770 InitAttrLine(kAttributeCandidate, &os);
1771 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001772 << it->foundation() << " "
1773 << it->component() << " "
1774 << it->protocol() << " "
1775 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001776 << it->address().ipaddr().ToString() << " "
1777 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001778 << kAttributeCandidateTyp << " "
1779 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001780
1781 // Related address
1782 if (!it->related_address().IsNil()) {
1783 os << kAttributeCandidateRaddr << " "
1784 << it->related_address().ipaddr().ToString() << " "
1785 << kAttributeCandidateRport << " "
1786 << it->related_address().PortAsString() << " ";
1787 }
1788
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001789 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001790 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001791 }
1792
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001793 // Extensions
1794 os << kAttributeCandidateGeneration << " " << it->generation();
honghaiza54a0802015-12-16 18:37:23 -08001795 if (include_ufrag && !it->username().empty()) {
1796 os << " " << kAttributeCandidateUfrag << " " << it->username();
1797 }
honghaize1a0c942016-02-16 14:54:56 -08001798 if (it->network_cost() > 0) {
1799 os << " " << kAttributeCandidateNetworkCost << " " << it->network_cost();
1800 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001801
1802 AddLine(os.str(), message);
1803 }
1804}
1805
1806void BuildIceOptions(const std::vector<std::string>& transport_options,
1807 std::string* message) {
1808 if (!transport_options.empty()) {
1809 std::ostringstream os;
1810 InitAttrLine(kAttributeIceOption, &os);
1811 os << kSdpDelimiterColon << transport_options[0];
1812 for (size_t i = 1; i < transport_options.size(); ++i) {
1813 os << kSdpDelimiterSpace << transport_options[i];
1814 }
1815 AddLine(os.str(), message);
1816 }
1817}
1818
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001819bool IsRtp(const std::string& protocol) {
1820 return protocol.empty() ||
1821 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1822}
1823
1824bool IsDtlsSctp(const std::string& protocol) {
1825 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001826 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001827}
1828
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001829bool ParseSessionDescription(const std::string& message, size_t* pos,
1830 std::string* session_id,
1831 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832 TransportDescription* session_td,
1833 RtpHeaderExtensions* session_extmaps,
1834 cricket::SessionDescription* desc,
1835 SdpParseError* error) {
1836 std::string line;
1837
deadbeefc80741f2015-10-22 13:14:45 -07001838 desc->set_msid_supported(false);
1839
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001840 // RFC 4566
1841 // v= (protocol version)
1842 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1843 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1844 std::string(), error);
1845 }
1846 // RFC 4566
1847 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1848 // <unicast-address>
1849 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1850 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1851 std::string(), error);
1852 }
1853 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001854 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001855 kSdpDelimiterSpace, &fields);
1856 const size_t expected_fields = 6;
1857 if (fields.size() != expected_fields) {
1858 return ParseFailedExpectFieldNum(line, expected_fields, error);
1859 }
1860 *session_id = fields[1];
1861 *session_version = fields[2];
1862
1863 // RFC 4566
1864 // s= (session name)
1865 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1866 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1867 std::string(), error);
1868 }
1869
1870 // Optional lines
1871 // Those are the optional lines, so shouldn't return false if not present.
1872 // RFC 4566
1873 // i=* (session information)
1874 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1875
1876 // RFC 4566
1877 // u=* (URI of description)
1878 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1879
1880 // RFC 4566
1881 // e=* (email address)
1882 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1883
1884 // RFC 4566
1885 // p=* (phone number)
1886 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1887
1888 // RFC 4566
1889 // c=* (connection information -- not required if included in
1890 // all media)
1891 GetLineWithType(message, pos, &line, kLineTypeConnection);
1892
1893 // RFC 4566
1894 // b=* (zero or more bandwidth information lines)
1895 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1896 // By pass zero or more b lines.
1897 }
1898
1899 // RFC 4566
1900 // One or more time descriptions ("t=" and "r=" lines; see below)
1901 // t= (time the session is active)
1902 // r=* (zero or more repeat times)
1903 // Ensure there's at least one time description
1904 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1905 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1906 error);
1907 }
1908
1909 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1910 // By pass zero or more r lines.
1911 }
1912
1913 // Go through the rest of the time descriptions
1914 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1915 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1916 // By pass zero or more r lines.
1917 }
1918 }
1919
1920 // RFC 4566
1921 // z=* (time zone adjustments)
1922 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1923
1924 // RFC 4566
1925 // k=* (encryption key)
1926 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1927
1928 // RFC 4566
1929 // a=* (zero or more session attribute lines)
1930 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1931 if (HasAttribute(line, kAttributeGroup)) {
1932 if (!ParseGroupAttribute(line, desc, error)) {
1933 return false;
1934 }
1935 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1936 if (!GetValue(line, kAttributeIceUfrag,
1937 &(session_td->ice_ufrag), error)) {
1938 return false;
1939 }
1940 } else if (HasAttribute(line, kAttributeIcePwd)) {
1941 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1942 return false;
1943 }
1944 } else if (HasAttribute(line, kAttributeIceLite)) {
1945 session_td->ice_mode = cricket::ICEMODE_LITE;
1946 } else if (HasAttribute(line, kAttributeIceOption)) {
1947 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1948 return false;
1949 }
1950 } else if (HasAttribute(line, kAttributeFingerprint)) {
1951 if (session_td->identity_fingerprint.get()) {
1952 return ParseFailed(
1953 line,
1954 "Can't have multiple fingerprint attributes at the same level.",
1955 error);
1956 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001957 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001958 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1959 return false;
1960 }
1961 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001962 } else if (HasAttribute(line, kAttributeSetup)) {
1963 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1964 return false;
1965 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001966 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1967 std::string semantics;
1968 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1969 return false;
1970 }
deadbeefc80741f2015-10-22 13:14:45 -07001971 desc->set_msid_supported(
1972 CaseInsensitiveFind(semantics, kMediaStreamSemantic));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001973 } else if (HasAttribute(line, kAttributeExtmap)) {
1974 RtpHeaderExtension extmap;
1975 if (!ParseExtmap(line, &extmap, error)) {
1976 return false;
1977 }
1978 session_extmaps->push_back(extmap);
1979 }
1980 }
1981
1982 return true;
1983}
1984
1985bool ParseGroupAttribute(const std::string& line,
1986 cricket::SessionDescription* desc,
1987 SdpParseError* error) {
1988 ASSERT(desc != NULL);
1989
1990 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1991 // a=group:BUNDLE video voice
1992 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001993 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001994 kSdpDelimiterSpace, &fields);
1995 std::string semantics;
1996 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1997 return false;
1998 }
1999 cricket::ContentGroup group(semantics);
2000 for (size_t i = 1; i < fields.size(); ++i) {
2001 group.AddContentName(fields[i]);
2002 }
2003 desc->AddGroup(group);
2004 return true;
2005}
2006
2007static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002008 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 SdpParseError* error) {
2010 if (!IsLineType(line, kLineTypeAttributes) ||
2011 !HasAttribute(line, kAttributeFingerprint)) {
2012 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
2013 kAttributeFingerprint, error);
2014 }
2015
2016 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002017 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002018 kSdpDelimiterSpace, &fields);
2019 const size_t expected_fields = 2;
2020 if (fields.size() != expected_fields) {
2021 return ParseFailedExpectFieldNum(line, expected_fields, error);
2022 }
2023
2024 // The first field here is "fingerprint:<hash>.
2025 std::string algorithm;
2026 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2027 return false;
2028 }
2029
2030 // Downcase the algorithm. Note that we don't need to downcase the
2031 // fingerprint because hex_decode can handle upper-case.
2032 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2033 ::tolower);
2034
2035 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002036 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002037 algorithm, fields[1]);
2038 if (!*fingerprint) {
2039 return ParseFailed(line,
2040 "Failed to create fingerprint from the digest.",
2041 error);
2042 }
2043
2044 return true;
2045}
2046
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002047static bool ParseDtlsSetup(const std::string& line,
2048 cricket::ConnectionRole* role,
2049 SdpParseError* error) {
2050 // setup-attr = "a=setup:" role
2051 // role = "active" / "passive" / "actpass" / "holdconn"
2052 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002053 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002054 const size_t expected_fields = 2;
2055 if (fields.size() != expected_fields) {
2056 return ParseFailedExpectFieldNum(line, expected_fields, error);
2057 }
2058 std::string role_str = fields[1];
2059 if (!cricket::StringToConnectionRole(role_str, role)) {
2060 return ParseFailed(line, "Invalid attribute value.", error);
2061 }
2062 return true;
2063}
2064
deadbeef9d3584c2016-02-16 17:54:10 -08002065static bool ParseMsidAttribute(const std::string& line,
2066 std::string* stream_id,
2067 std::string* track_id,
2068 SdpParseError* error) {
2069 // draft-ietf-mmusic-msid-11
2070 // a=msid:<stream id> <track id>
2071 // msid-value = msid-id [ SP msid-appdata ]
2072 // msid-id = 1*64token-char ; see RFC 4566
2073 // msid-appdata = 1*64token-char ; see RFC 4566
2074 std::string field1;
2075 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2076 &field1, track_id)) {
2077 const size_t expected_fields = 2;
2078 return ParseFailedExpectFieldNum(line, expected_fields, error);
2079 }
2080
2081 // msid:<msid-id>
2082 if (!GetValue(field1, kAttributeMsid, stream_id, error)) {
2083 return false;
2084 }
2085 return true;
2086}
2087
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002088// RFC 3551
2089// PT encoding media type clock rate channels
2090// name (Hz)
2091// 0 PCMU A 8,000 1
2092// 1 reserved A
2093// 2 reserved A
2094// 3 GSM A 8,000 1
2095// 4 G723 A 8,000 1
2096// 5 DVI4 A 8,000 1
2097// 6 DVI4 A 16,000 1
2098// 7 LPC A 8,000 1
2099// 8 PCMA A 8,000 1
2100// 9 G722 A 8,000 1
2101// 10 L16 A 44,100 2
2102// 11 L16 A 44,100 1
2103// 12 QCELP A 8,000 1
2104// 13 CN A 8,000 1
2105// 14 MPA A 90,000 (see text)
2106// 15 G728 A 8,000 1
2107// 16 DVI4 A 11,025 1
2108// 17 DVI4 A 22,050 1
2109// 18 G729 A 8,000 1
2110struct StaticPayloadAudioCodec {
2111 const char* name;
2112 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002113 size_t channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002114};
2115static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2116 { "PCMU", 8000, 1 },
2117 { "reserved", 0, 0 },
2118 { "reserved", 0, 0 },
2119 { "GSM", 8000, 1 },
2120 { "G723", 8000, 1 },
2121 { "DVI4", 8000, 1 },
2122 { "DVI4", 16000, 1 },
2123 { "LPC", 8000, 1 },
2124 { "PCMA", 8000, 1 },
2125 { "G722", 8000, 1 },
2126 { "L16", 44100, 2 },
2127 { "L16", 44100, 1 },
2128 { "QCELP", 8000, 1 },
2129 { "CN", 8000, 1 },
2130 { "MPA", 90000, 1 },
2131 { "G728", 8000, 1 },
2132 { "DVI4", 11025, 1 },
2133 { "DVI4", 22050, 1 },
2134 { "G729", 8000, 1 },
2135};
2136
2137void MaybeCreateStaticPayloadAudioCodecs(
2138 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2139 if (!media_desc) {
2140 return;
2141 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002142 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002143 std::vector<int>::const_iterator it = fmts.begin();
2144 bool add_new_codec = false;
2145 for (; it != fmts.end(); ++it) {
2146 int payload_type = *it;
2147 if (!media_desc->HasCodec(payload_type) &&
2148 payload_type >= 0 &&
tfarina5237aaf2015-11-10 23:44:30 -08002149 payload_type < arraysize(kStaticPayloadAudioCodecs)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002150 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2151 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002152 size_t channels = kStaticPayloadAudioCodecs[payload_type].channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002153 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2154 clock_rate, 0, channels,
2155 preference));
2156 add_new_codec = true;
2157 }
2158 --preference;
2159 }
2160 if (add_new_codec) {
2161 media_desc->SortCodecs();
2162 }
2163}
2164
2165template <class C>
2166static C* ParseContentDescription(const std::string& message,
2167 const MediaType media_type,
2168 int mline_index,
2169 const std::string& protocol,
2170 const std::vector<int>& codec_preference,
2171 size_t* pos,
2172 std::string* content_name,
2173 TransportDescription* transport,
2174 std::vector<JsepIceCandidate*>* candidates,
2175 webrtc::SdpParseError* error) {
2176 C* media_desc = new C();
2177 switch (media_type) {
2178 case cricket::MEDIA_TYPE_AUDIO:
2179 *content_name = cricket::CN_AUDIO;
2180 break;
2181 case cricket::MEDIA_TYPE_VIDEO:
2182 *content_name = cricket::CN_VIDEO;
2183 break;
2184 case cricket::MEDIA_TYPE_DATA:
2185 *content_name = cricket::CN_DATA;
2186 break;
2187 default:
2188 ASSERT(false);
2189 break;
2190 }
2191 if (!ParseContent(message, media_type, mline_index, protocol,
2192 codec_preference, pos, content_name,
2193 media_desc, transport, candidates, error)) {
2194 delete media_desc;
2195 return NULL;
2196 }
2197 // Sort the codecs according to the m-line fmt list.
2198 media_desc->SortCodecs();
2199 return media_desc;
2200}
2201
2202bool ParseMediaDescription(const std::string& message,
2203 const TransportDescription& session_td,
2204 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002205 size_t* pos,
2206 cricket::SessionDescription* desc,
2207 std::vector<JsepIceCandidate*>* candidates,
2208 SdpParseError* error) {
2209 ASSERT(desc != NULL);
2210 std::string line;
2211 int mline_index = -1;
2212
2213 // Zero or more media descriptions
2214 // RFC 4566
2215 // m=<media> <port> <proto> <fmt>
2216 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2217 ++mline_index;
2218
2219 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002220 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002221 kSdpDelimiterSpace, &fields);
2222 const size_t expected_min_fields = 4;
2223 if (fields.size() < expected_min_fields) {
2224 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2225 }
2226 bool rejected = false;
2227 // RFC 3264
2228 // To reject an offered stream, the port number in the corresponding stream
2229 // in the answer MUST be set to zero.
2230 if (fields[1] == kMediaPortRejected) {
2231 rejected = true;
2232 }
2233
2234 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002235
2236 // <fmt>
2237 std::vector<int> codec_preference;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002238 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002239 for (size_t j = 3 ; j < fields.size(); ++j) {
2240 // TODO(wu): Remove when below bug is fixed.
2241 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002242 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002243 continue;
2244 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002245
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002246 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002247 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002248 return false;
2249 }
2250 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002251 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 }
2253
2254 // Make a temporary TransportDescription based on |session_td|.
2255 // Some of this gets overwritten by ParseContent.
deadbeef46eed762016-01-28 13:24:37 -08002256 TransportDescription transport(
2257 session_td.transport_options, session_td.ice_ufrag, session_td.ice_pwd,
2258 session_td.ice_mode, session_td.connection_role,
2259 session_td.identity_fingerprint.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002260
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002261 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002262 std::string content_name;
2263 if (HasAttribute(line, kMediaTypeVideo)) {
2264 content.reset(ParseContentDescription<VideoContentDescription>(
2265 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2266 codec_preference, pos, &content_name,
2267 &transport, candidates, error));
2268 } else if (HasAttribute(line, kMediaTypeAudio)) {
2269 content.reset(ParseContentDescription<AudioContentDescription>(
2270 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2271 codec_preference, pos, &content_name,
2272 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002273 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002274 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002275 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002276 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2277 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002278 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002279 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002280
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002281 int p;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002282 if (data_desc && IsDtlsSctp(protocol) && rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002283 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002284 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002285 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002286 } else {
2287 LOG(LS_WARNING) << "Unsupported media type: " << line;
2288 continue;
2289 }
2290 if (!content.get()) {
2291 // ParseContentDescription returns NULL if failed.
2292 return false;
2293 }
2294
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002295 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002296 // Set the extmap.
2297 if (!session_extmaps.empty() &&
2298 !content->rtp_header_extensions().empty()) {
2299 return ParseFailed("",
2300 "The a=extmap MUST be either all session level or "
2301 "all media level.",
2302 error);
2303 }
2304 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2305 content->AddRtpHeaderExtension(session_extmaps[i]);
2306 }
2307 }
2308 content->set_protocol(protocol);
2309 desc->AddContent(content_name,
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002310 IsDtlsSctp(protocol) ? cricket::NS_JINGLE_DRAFT_SCTP :
2311 cricket::NS_JINGLE_RTP,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002312 rejected,
2313 content.release());
2314 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2315 TransportInfo transport_info(content_name, transport);
2316
2317 if (!desc->AddTransportInfo(transport_info)) {
2318 std::ostringstream description;
2319 description << "Failed to AddTransportInfo with content name: "
2320 << content_name;
2321 return ParseFailed("", description.str(), error);
2322 }
2323 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002324
2325 size_t end_of_message = message.size();
2326 if (mline_index == -1 && *pos != end_of_message) {
2327 ParseFailed(message, *pos, "Expects m line.", error);
2328 return false;
2329 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002330 return true;
2331}
2332
2333bool VerifyCodec(const cricket::Codec& codec) {
2334 // Codec has not been populated correctly unless the name has been set. This
2335 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2336 // have a corresponding "rtpmap" line.
2337 cricket::Codec default_codec;
2338 return default_codec.name != codec.name;
2339}
2340
2341bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2342 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2343 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2344 iter != codecs.end(); ++iter) {
2345 if (!VerifyCodec(*iter)) {
2346 return false;
2347 }
2348 }
2349 return true;
2350}
2351
2352bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2353 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2354 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2355 iter != codecs.end(); ++iter) {
2356 if (!VerifyCodec(*iter)) {
2357 return false;
2358 }
2359 }
2360 return true;
2361}
2362
2363void AddParameters(const cricket::CodecParameterMap& parameters,
2364 cricket::Codec* codec) {
2365 for (cricket::CodecParameterMap::const_iterator iter =
2366 parameters.begin(); iter != parameters.end(); ++iter) {
2367 codec->SetParam(iter->first, iter->second);
2368 }
2369}
2370
2371void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2372 cricket::Codec* codec) {
2373 codec->AddFeedbackParam(feedback_param);
2374}
2375
2376void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2377 cricket::Codec* codec) {
2378 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2379 feedback_params.params().begin();
2380 iter != feedback_params.params().end(); ++iter) {
2381 codec->AddFeedbackParam(*iter);
2382 }
2383}
2384
2385// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002386// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002387// with that payload type.
2388template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002389T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2390 T ret_val;
2391 if (!FindCodecById(codecs, payload_type, &ret_val)) {
2392 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002393 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002394 return ret_val;
2395}
2396
2397// Updates or creates a new codec entry in the audio description.
2398template <class T, class U>
2399void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2400 T* desc = static_cast<T*>(content_desc);
2401 std::vector<U> codecs = desc->codecs();
2402 bool found = false;
2403
2404 typename std::vector<U>::iterator iter;
2405 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2406 if (iter->id == codec.id) {
2407 *iter = codec;
2408 found = true;
2409 break;
2410 }
2411 }
2412 if (!found) {
2413 desc->AddCodec(codec);
2414 return;
2415 }
2416 desc->set_codecs(codecs);
2417}
2418
2419// Adds or updates existing codec corresponding to |payload_type| according
2420// to |parameters|.
2421template <class T, class U>
2422void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2423 const cricket::CodecParameterMap& parameters) {
2424 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002425 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2426 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002427 AddParameters(parameters, &new_codec);
2428 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2429}
2430
2431// Adds or updates existing codec corresponding to |payload_type| according
2432// to |feedback_param|.
2433template <class T, class U>
2434void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2435 const cricket::FeedbackParam& feedback_param) {
2436 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002437 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2438 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002439 AddFeedbackParameter(feedback_param, &new_codec);
2440 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2441}
2442
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002443template <class T>
2444bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2445 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002446 if (iter->id == kWildcardPayloadType) {
2447 *wildcard_codec = *iter;
2448 codecs->erase(iter);
2449 return true;
2450 }
2451 }
2452 return false;
2453}
2454
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002455template<class T>
2456void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2457 auto codecs = desc->codecs();
2458 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002459 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2460 return;
2461 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002462 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002463 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2464 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002465 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002466}
2467
2468void AddAudioAttribute(const std::string& name, const std::string& value,
2469 AudioContentDescription* audio_desc) {
2470 if (value.empty()) {
2471 return;
2472 }
2473 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2474 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2475 iter != codecs.end(); ++iter) {
2476 iter->params[name] = value;
2477 }
2478 audio_desc->set_codecs(codecs);
2479}
2480
2481bool ParseContent(const std::string& message,
2482 const MediaType media_type,
2483 int mline_index,
2484 const std::string& protocol,
2485 const std::vector<int>& codec_preference,
2486 size_t* pos,
2487 std::string* content_name,
2488 MediaContentDescription* media_desc,
2489 TransportDescription* transport,
2490 std::vector<JsepIceCandidate*>* candidates,
2491 SdpParseError* error) {
2492 ASSERT(media_desc != NULL);
2493 ASSERT(content_name != NULL);
2494 ASSERT(transport != NULL);
2495
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002496 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2497 MaybeCreateStaticPayloadAudioCodecs(
2498 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2499 }
2500
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002501 // The media level "ice-ufrag" and "ice-pwd".
2502 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2503 Candidates candidates_orig;
2504 std::string line;
2505 std::string mline_id;
2506 // Tracks created out of the ssrc attributes.
2507 StreamParamsVec tracks;
2508 SsrcInfoVec ssrc_infos;
2509 SsrcGroupVec ssrc_groups;
2510 std::string maxptime_as_string;
2511 std::string ptime_as_string;
deadbeef9d3584c2016-02-16 17:54:10 -08002512 std::string stream_id;
2513 std::string track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002514
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002515 // Loop until the next m line
2516 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2517 if (!GetLine(message, pos, &line)) {
2518 if (*pos >= message.size()) {
2519 break; // Done parsing
2520 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002521 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002522 }
2523 }
2524
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002525 // RFC 4566
2526 // b=* (zero or more bandwidth information lines)
2527 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2528 std::string bandwidth;
2529 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2530 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2531 return false;
2532 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002533 int b = 0;
2534 if (!GetValueFromString(line, bandwidth, &b, error)) {
2535 return false;
2536 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002537 // We should never use more than the default bandwidth for RTP-based
2538 // data channels. Don't allow SDP to set the bandwidth, because
2539 // that would give JS the opportunity to "break the Internet".
2540 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2541 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2542 b > cricket::kDataMaxBandwidth / 1000) {
2543 std::ostringstream description;
2544 description << "RTP-based data channels may not send more than "
2545 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2546 return ParseFailed(line, description.str(), error);
2547 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002548 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002549 }
2550 }
2551 continue;
2552 }
2553
2554 if (!IsLineType(line, kLineTypeAttributes)) {
2555 // TODO: Handle other lines if needed.
2556 LOG(LS_INFO) << "Ignored line: " << line;
2557 continue;
2558 }
2559
2560 // Handle attributes common to SCTP and RTP.
2561 if (HasAttribute(line, kAttributeMid)) {
2562 // RFC 3388
2563 // mid-attribute = "a=mid:" identification-tag
2564 // identification-tag = token
2565 // Use the mid identification-tag as the content name.
2566 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2567 return false;
2568 }
2569 *content_name = mline_id;
2570 } else if (HasAttribute(line, kAttributeCandidate)) {
2571 Candidate candidate;
2572 if (!ParseCandidate(line, &candidate, error, false)) {
2573 return false;
2574 }
2575 candidates_orig.push_back(candidate);
2576 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2577 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2578 return false;
2579 }
2580 } else if (HasAttribute(line, kAttributeIcePwd)) {
2581 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2582 return false;
2583 }
2584 } else if (HasAttribute(line, kAttributeIceOption)) {
2585 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2586 return false;
2587 }
2588 } else if (HasAttribute(line, kAttributeFmtp)) {
2589 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2590 return false;
2591 }
2592 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002593 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002594
2595 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2596 return false;
2597 }
2598 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002599 } else if (HasAttribute(line, kAttributeSetup)) {
2600 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2601 return false;
2602 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002603 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002604 int sctp_port;
2605 if (!ParseSctpPort(line, &sctp_port, error)) {
2606 return false;
2607 }
2608 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2609 sctp_port)) {
2610 return false;
2611 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002612 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613 //
2614 // RTP specific attrubtes
2615 //
2616 if (HasAttribute(line, kAttributeRtcpMux)) {
2617 media_desc->set_rtcp_mux(true);
deadbeef13871492015-12-09 12:37:51 -08002618 } else if (HasAttribute(line, kAttributeRtcpReducedSize)) {
2619 media_desc->set_rtcp_reduced_size(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002620 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2621 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2622 return false;
2623 }
2624 } else if (HasAttribute(line, kAttributeSsrc)) {
2625 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2626 return false;
2627 }
2628 } else if (HasAttribute(line, kAttributeCrypto)) {
2629 if (!ParseCryptoAttribute(line, media_desc, error)) {
2630 return false;
2631 }
2632 } else if (HasAttribute(line, kAttributeRtpmap)) {
2633 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2634 media_desc, error)) {
2635 return false;
2636 }
2637 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2638 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2639 return false;
2640 }
2641 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2642 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2643 return false;
2644 }
2645 } else if (HasAttribute(line, kCodecParamPTime)) {
2646 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2647 return false;
2648 }
2649 } else if (HasAttribute(line, kAttributeSendOnly)) {
2650 media_desc->set_direction(cricket::MD_SENDONLY);
2651 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2652 media_desc->set_direction(cricket::MD_RECVONLY);
2653 } else if (HasAttribute(line, kAttributeInactive)) {
2654 media_desc->set_direction(cricket::MD_INACTIVE);
2655 } else if (HasAttribute(line, kAttributeSendRecv)) {
2656 media_desc->set_direction(cricket::MD_SENDRECV);
2657 } else if (HasAttribute(line, kAttributeExtmap)) {
2658 RtpHeaderExtension extmap;
2659 if (!ParseExtmap(line, &extmap, error)) {
2660 return false;
2661 }
2662 media_desc->AddRtpHeaderExtension(extmap);
2663 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2664 // Experimental attribute. Conference mode activates more aggressive
2665 // AEC and NS settings.
2666 // TODO: expose API to set these directly.
2667 std::string flag_value;
2668 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2669 return false;
2670 }
2671 if (flag_value.compare(kValueConference) == 0)
2672 media_desc->set_conference_mode(true);
deadbeef9d3584c2016-02-16 17:54:10 -08002673 } else if (HasAttribute(line, kAttributeMsid)) {
2674 if (!ParseMsidAttribute(line, &stream_id, &track_id, error)) {
2675 return false;
2676 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002677 }
2678 } else {
2679 // Only parse lines that we are interested of.
2680 LOG(LS_INFO) << "Ignored line: " << line;
2681 continue;
2682 }
2683 }
2684
2685 // Create tracks from the |ssrc_infos|.
Taylor Brandstetter5de6b752016-03-09 17:02:30 -08002686 // If the stream_id/track_id for all SSRCS are identical, one StreamParams
2687 // will be created in CreateTracksFromSsrcInfos, containing all the SSRCs from
2688 // the m= section.
2689 CreateTracksFromSsrcInfos(ssrc_infos, stream_id, track_id, &tracks);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002690
2691 // Add the ssrc group to the track.
2692 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2693 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2694 if (ssrc_group->ssrcs.empty()) {
2695 continue;
2696 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002697 uint32_t ssrc = ssrc_group->ssrcs.front();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002698 for (StreamParamsVec::iterator track = tracks.begin();
2699 track != tracks.end(); ++track) {
2700 if (track->has_ssrc(ssrc)) {
2701 track->ssrc_groups.push_back(*ssrc_group);
2702 }
2703 }
2704 }
2705
2706 // Add the new tracks to the |media_desc|.
deadbeef9d3584c2016-02-16 17:54:10 -08002707 for (StreamParams& track : tracks) {
2708 media_desc->AddStream(track);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002709 }
2710
2711 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2712 AudioContentDescription* audio_desc =
2713 static_cast<AudioContentDescription*>(media_desc);
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002714 UpdateFromWildcardCodecs(audio_desc);
2715
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002716 // Verify audio codec ensures that no audio codec has been populated with
2717 // only fmtp.
2718 if (!VerifyAudioCodecs(audio_desc)) {
2719 return ParseFailed("Failed to parse audio codecs correctly.", error);
2720 }
2721 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2722 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2723 }
2724
2725 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002726 VideoContentDescription* video_desc =
2727 static_cast<VideoContentDescription*>(media_desc);
2728 UpdateFromWildcardCodecs(video_desc);
2729 // Verify video codec ensures that no video codec has been populated with
2730 // only rtcp-fb.
2731 if (!VerifyVideoCodecs(video_desc)) {
2732 return ParseFailed("Failed to parse video codecs correctly.", error);
2733 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002734 }
2735
2736 // RFC 5245
2737 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2738 for (Candidates::iterator it = candidates_orig.begin();
2739 it != candidates_orig.end(); ++it) {
honghaiza54a0802015-12-16 18:37:23 -08002740 ASSERT((*it).username().empty() ||
2741 (*it).username() == transport->ice_ufrag);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002742 (*it).set_username(transport->ice_ufrag);
2743 ASSERT((*it).password().empty());
2744 (*it).set_password(transport->ice_pwd);
2745 candidates->push_back(
2746 new JsepIceCandidate(mline_id, mline_index, *it));
2747 }
2748 return true;
2749}
2750
2751bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2752 SdpParseError* error) {
2753 ASSERT(ssrc_infos != NULL);
2754 // RFC 5576
2755 // a=ssrc:<ssrc-id> <attribute>
2756 // a=ssrc:<ssrc-id> <attribute>:<value>
2757 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07002758 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2759 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002760 const size_t expected_fields = 2;
2761 return ParseFailedExpectFieldNum(line, expected_fields, error);
2762 }
2763
2764 // ssrc:<ssrc-id>
2765 std::string ssrc_id_s;
2766 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2767 return false;
2768 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002769 uint32_t ssrc_id = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002770 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2771 return false;
2772 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002773
2774 std::string attribute;
2775 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07002776 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002777 std::ostringstream description;
2778 description << "Failed to get the ssrc attribute value from " << field2
2779 << ". Expected format <attribute>:<value>.";
2780 return ParseFailed(line, description.str(), error);
2781 }
2782
2783 // Check if there's already an item for this |ssrc_id|. Create a new one if
2784 // there isn't.
2785 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2786 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2787 if (ssrc_info->ssrc_id == ssrc_id) {
2788 break;
2789 }
2790 }
2791 if (ssrc_info == ssrc_infos->end()) {
2792 SsrcInfo info;
2793 info.ssrc_id = ssrc_id;
2794 ssrc_infos->push_back(info);
2795 ssrc_info = ssrc_infos->end() - 1;
2796 }
2797
2798 // Store the info to the |ssrc_info|.
2799 if (attribute == kSsrcAttributeCname) {
2800 // RFC 5576
2801 // cname:<value>
2802 ssrc_info->cname = value;
2803 } else if (attribute == kSsrcAttributeMsid) {
2804 // draft-alvestrand-mmusic-msid-00
2805 // "msid:" identifier [ " " appdata ]
2806 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002807 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002808 if (fields.size() < 1 || fields.size() > 2) {
2809 return ParseFailed(line,
2810 "Expected format \"msid:<identifier>[ <appdata>]\".",
2811 error);
2812 }
deadbeef9d3584c2016-02-16 17:54:10 -08002813 ssrc_info->stream_id = fields[0];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002814 if (fields.size() == 2) {
deadbeef9d3584c2016-02-16 17:54:10 -08002815 ssrc_info->track_id = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002816 }
2817 } else if (attribute == kSsrcAttributeMslabel) {
2818 // draft-alvestrand-rtcweb-mid-01
2819 // mslabel:<value>
2820 ssrc_info->mslabel = value;
2821 } else if (attribute == kSSrcAttributeLabel) {
2822 // The label isn't defined.
2823 // label:<value>
2824 ssrc_info->label = value;
2825 }
2826 return true;
2827}
2828
2829bool ParseSsrcGroupAttribute(const std::string& line,
2830 SsrcGroupVec* ssrc_groups,
2831 SdpParseError* error) {
2832 ASSERT(ssrc_groups != NULL);
2833 // RFC 5576
2834 // a=ssrc-group:<semantics> <ssrc-id> ...
2835 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002836 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002837 kSdpDelimiterSpace, &fields);
2838 const size_t expected_min_fields = 2;
2839 if (fields.size() < expected_min_fields) {
2840 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2841 }
2842 std::string semantics;
2843 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2844 return false;
2845 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002846 std::vector<uint32_t> ssrcs;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002847 for (size_t i = 1; i < fields.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02002848 uint32_t ssrc = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002849 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2850 return false;
2851 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002852 ssrcs.push_back(ssrc);
2853 }
2854 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2855 return true;
2856}
2857
2858bool ParseCryptoAttribute(const std::string& line,
2859 MediaContentDescription* media_desc,
2860 SdpParseError* error) {
2861 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002862 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002863 kSdpDelimiterSpace, &fields);
2864 // RFC 4568
2865 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2866 const size_t expected_min_fields = 3;
2867 if (fields.size() < expected_min_fields) {
2868 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2869 }
2870 std::string tag_value;
2871 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2872 return false;
2873 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002874 int tag = 0;
2875 if (!GetValueFromString(line, tag_value, &tag, error)) {
2876 return false;
2877 }
jbauch083b73f2015-07-16 02:46:32 -07002878 const std::string& crypto_suite = fields[1];
2879 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002880 std::string session_params;
2881 if (fields.size() > 3) {
2882 session_params = fields[3];
2883 }
2884 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2885 session_params));
2886 return true;
2887}
2888
2889// Updates or creates a new codec entry in the audio description with according
2890// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2891void UpdateCodec(int payload_type, const std::string& name, int clockrate,
Peter Kasting69558702016-01-12 16:26:35 -08002892 int bitrate, size_t channels, int preference,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002893 AudioContentDescription* audio_desc) {
2894 // Codec may already be populated with (only) optional parameters
2895 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002896 cricket::AudioCodec codec =
2897 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002898 codec.name = name;
2899 codec.clockrate = clockrate;
2900 codec.bitrate = bitrate;
2901 codec.channels = channels;
2902 codec.preference = preference;
2903 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2904 codec);
2905}
2906
2907// Updates or creates a new codec entry in the video description according to
2908// |name|, |width|, |height|, |framerate| and |preference|.
2909void UpdateCodec(int payload_type, const std::string& name, int width,
2910 int height, int framerate, int preference,
2911 VideoContentDescription* video_desc) {
2912 // Codec may already be populated with (only) optional parameters
2913 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002914 cricket::VideoCodec codec =
2915 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002916 codec.name = name;
2917 codec.width = width;
2918 codec.height = height;
2919 codec.framerate = framerate;
2920 codec.preference = preference;
2921 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2922 codec);
2923}
2924
2925bool ParseRtpmapAttribute(const std::string& line,
2926 const MediaType media_type,
2927 const std::vector<int>& codec_preference,
2928 MediaContentDescription* media_desc,
2929 SdpParseError* error) {
2930 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002931 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002932 kSdpDelimiterSpace, &fields);
2933 // RFC 4566
2934 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2935 const size_t expected_min_fields = 2;
2936 if (fields.size() < expected_min_fields) {
2937 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2938 }
2939 std::string payload_type_value;
2940 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2941 return false;
2942 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002943 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002944 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
2945 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002946 return false;
2947 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002948
2949 // Set the preference order depending on the order of the pl type in the
2950 // <fmt> of the m-line.
2951 const int preference = codec_preference.end() -
2952 std::find(codec_preference.begin(), codec_preference.end(),
2953 payload_type);
2954 if (preference == 0) {
2955 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2956 << "<fmt> of the m-line: " << line;
2957 return true;
2958 }
jbauch083b73f2015-07-16 02:46:32 -07002959 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002960 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002961 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002962 // <encoding name>/<clock rate>[/<encodingparameters>]
2963 // 2 mandatory fields
2964 if (codec_params.size() < 2 || codec_params.size() > 3) {
2965 return ParseFailed(line,
2966 "Expected format \"<encoding name>/<clock rate>"
2967 "[/<encodingparameters>]\".",
2968 error);
2969 }
jbauch083b73f2015-07-16 02:46:32 -07002970 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002971 int clock_rate = 0;
2972 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2973 return false;
2974 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002975 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2976 VideoContentDescription* video_desc =
2977 static_cast<VideoContentDescription*>(media_desc);
2978 // TODO: We will send resolution in SDP. For now use
2979 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2980 UpdateCodec(payload_type, encoding_name,
2981 JsepSessionDescription::kMaxVideoCodecWidth,
2982 JsepSessionDescription::kMaxVideoCodecHeight,
2983 JsepSessionDescription::kDefaultVideoCodecFramerate,
2984 preference, video_desc);
2985 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2986 // RFC 4566
2987 // For audio streams, <encoding parameters> indicates the number
2988 // of audio channels. This parameter is OPTIONAL and may be
2989 // omitted if the number of channels is one, provided that no
2990 // additional parameters are needed.
Peter Kasting69558702016-01-12 16:26:35 -08002991 size_t channels = 1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002992 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002993 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2994 return false;
2995 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002996 }
2997 int bitrate = 0;
2998 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2999 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
3000 // The bandwidth adaptation doesn't always work well, so this code
3001 // sets a fixed target bitrate instead.
3002 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
3003 if (clock_rate <= 16000) {
3004 bitrate = kIsacWbDefaultRate;
3005 } else {
3006 bitrate = kIsacSwbDefaultRate;
3007 }
3008 }
3009 AudioContentDescription* audio_desc =
3010 static_cast<AudioContentDescription*>(media_desc);
3011 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
3012 preference, audio_desc);
3013 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
3014 DataContentDescription* data_desc =
3015 static_cast<DataContentDescription*>(media_desc);
3016 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
3017 preference));
3018 }
3019 return true;
3020}
3021
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003022bool ParseFmtpParam(const std::string& line, std::string* parameter,
3023 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003024 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003025 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
3026 return false;
3027 }
3028 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003029 return true;
3030}
3031
3032bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
3033 MediaContentDescription* media_desc,
3034 SdpParseError* error) {
3035 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3036 media_type != cricket::MEDIA_TYPE_VIDEO) {
3037 return true;
3038 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003039
3040 std::string line_payload;
3041 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003042
3043 // RFC 5576
3044 // a=fmtp:<format> <format specific parameters>
3045 // At least two fields, whereas the second one is any of the optional
3046 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07003047 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
3048 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003049 ParseFailedExpectMinFieldNum(line, 2, error);
3050 return false;
3051 }
3052
Donald Curtis0e07f922015-05-15 09:21:23 -07003053 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003054 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07003055 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003056 return false;
3057 }
3058
Donald Curtis0e07f922015-05-15 09:21:23 -07003059 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07003060 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3061 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003062 return false;
3063 }
3064
3065 // Parse out format specific parameters.
3066 std::vector<std::string> fields;
3067 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
3068
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003069 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07003070 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003071 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003072 // Only fmtps with equals are currently supported. Other fmtp types
3073 // should be ignored. Unknown fmtps do not constitute an error.
3074 continue;
3075 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003076
3077 std::string name;
3078 std::string value;
3079 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003080 return false;
3081 }
3082 codec_params[name] = value;
3083 }
3084
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003085 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3086 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003087 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003088 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3089 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003090 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003091 }
3092 return true;
3093}
3094
3095bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3096 MediaContentDescription* media_desc,
3097 SdpParseError* error) {
3098 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3099 media_type != cricket::MEDIA_TYPE_VIDEO) {
3100 return true;
3101 }
3102 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003103 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003104 if (rtcp_fb_fields.size() < 2) {
3105 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3106 }
3107 std::string payload_type_string;
3108 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3109 error)) {
3110 return false;
3111 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003112 int payload_type = kWildcardPayloadType;
3113 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003114 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3115 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003116 return false;
3117 }
3118 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003119 std::string id = rtcp_fb_fields[1];
3120 std::string param = "";
3121 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3122 iter != rtcp_fb_fields.end(); ++iter) {
3123 param.append(*iter);
3124 }
3125 const cricket::FeedbackParam feedback_param(id, param);
3126
3127 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003128 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3129 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003130 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003131 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3132 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003133 }
3134 return true;
3135}
3136
3137} // namespace webrtc