blob: eb7a66a82376bf6218d989272a38e4a0c825432a [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2011 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Henrik Kjellander15583c12016-02-10 10:53:12 +010011#include "webrtc/api/webrtcsdp.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
kjellandera96e2d72016-02-04 23:52:28 -080013#include <ctype.h>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000014#include <limits.h>
15#include <stdio.h>
16#include <algorithm>
17#include <string>
18#include <vector>
19
Henrik Kjellander15583c12016-02-10 10:53:12 +010020#include "webrtc/api/jsepicecandidate.h"
21#include "webrtc/api/jsepsessiondescription.h"
tfarina5237aaf2015-11-10 23:44:30 -080022#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000023#include "webrtc/base/common.h"
24#include "webrtc/base/logging.h"
25#include "webrtc/base/messagedigest.h"
26#include "webrtc/base/stringutils.h"
kjellandera96e2d72016-02-04 23:52:28 -080027#include "webrtc/media/base/codec.h"
28#include "webrtc/media/base/constants.h"
29#include "webrtc/media/base/cryptoparams.h"
30#include "webrtc/media/base/rtputils.h"
31#include "webrtc/media/sctp/sctpdataengine.h"
32#include "webrtc/p2p/base/candidate.h"
33#include "webrtc/p2p/base/constants.h"
34#include "webrtc/p2p/base/port.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010035#include "webrtc/pc/mediasession.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000036
37using cricket::AudioContentDescription;
38using cricket::Candidate;
39using cricket::Candidates;
40using cricket::ContentDescription;
41using cricket::ContentInfo;
42using cricket::CryptoParams;
43using cricket::DataContentDescription;
44using cricket::ICE_CANDIDATE_COMPONENT_RTP;
45using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
46using cricket::kCodecParamMaxBitrate;
47using cricket::kCodecParamMaxPTime;
48using cricket::kCodecParamMaxQuantization;
49using cricket::kCodecParamMinBitrate;
50using cricket::kCodecParamMinPTime;
51using cricket::kCodecParamPTime;
52using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000053using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054using cricket::kCodecParamStereo;
55using cricket::kCodecParamUseInbandFec;
Minyue Li7100dcd2015-03-27 05:05:59 +010056using cricket::kCodecParamUseDtx;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057using cricket::kCodecParamSctpProtocol;
58using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000059using cricket::kCodecParamMaxAverageBitrate;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000060using cricket::kCodecParamMaxPlaybackRate;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000061using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062using cricket::MediaContentDescription;
63using cricket::MediaType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064using cricket::RtpHeaderExtension;
65using cricket::SsrcGroup;
66using cricket::StreamParams;
67using cricket::StreamParamsVec;
68using cricket::TransportDescription;
69using cricket::TransportInfo;
70using cricket::VideoContentDescription;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000071using rtc::SocketAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072
73typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
74
75namespace cricket {
76class SessionDescription;
77}
78
79namespace webrtc {
80
81// Line type
82// RFC 4566
83// An SDP session description consists of a number of lines of text of
84// the form:
85// <type>=<value>
86// where <type> MUST be exactly one case-significant character.
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 {
215 SsrcInfo()
deadbeef9d3584c2016-02-16 17:54:10 -0800216 : stream_id(kDefaultMsid),
217 // TODO(ronghuawu): What should we do if the track id doesn't appear?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000218 // Create random string (which will be used as track label later)?
deadbeef9d3584c2016-02-16 17:54:10 -0800219 track_id(rtc::CreateRandomString(8)) {}
Peter Boström0c4e06b2015-10-07 12:23:21 +0200220 uint32_t ssrc_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000221 std::string cname;
deadbeef9d3584c2016-02-16 17:54:10 -0800222 std::string stream_id;
223 std::string track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000224
225 // For backward compatibility.
226 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
227 std::string label;
228 std::string mslabel;
229};
230typedef std::vector<SsrcInfo> SsrcInfoVec;
231typedef std::vector<SsrcGroup> SsrcGroupVec;
232
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000233template <class T>
234static void AddFmtpLine(const T& codec, std::string* message);
235static void BuildMediaDescription(const ContentInfo* content_info,
236 const TransportInfo* transport_info,
237 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000238 const std::vector<Candidate>& candidates,
deadbeef9d3584c2016-02-16 17:54:10 -0800239 bool unified_plan_sdp,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000240 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000241static void BuildSctpContentAttributes(std::string* message, int sctp_port);
deadbeef9d3584c2016-02-16 17:54:10 -0800242static void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
243 const MediaType media_type,
244 bool unified_plan_sdp,
245 std::string* message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000246static void BuildRtpMap(const MediaContentDescription* media_desc,
247 const MediaType media_type,
248 std::string* message);
249static void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -0800250 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000251 std::string* message);
252static void BuildIceOptions(const std::vector<std::string>& transport_options,
253 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000254static bool IsRtp(const std::string& protocol);
255static bool IsDtlsSctp(const std::string& protocol);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000256static bool ParseSessionDescription(const std::string& message, size_t* pos,
257 std::string* session_id,
258 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000259 TransportDescription* session_td,
260 RtpHeaderExtensions* session_extmaps,
261 cricket::SessionDescription* desc,
262 SdpParseError* error);
263static bool ParseGroupAttribute(const std::string& line,
264 cricket::SessionDescription* desc,
265 SdpParseError* error);
266static bool ParseMediaDescription(
267 const std::string& message,
268 const TransportDescription& session_td,
269 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000270 size_t* pos, cricket::SessionDescription* desc,
271 std::vector<JsepIceCandidate*>* candidates,
272 SdpParseError* error);
273static bool ParseContent(const std::string& message,
274 const MediaType media_type,
275 int mline_index,
276 const std::string& protocol,
277 const std::vector<int>& codec_preference,
278 size_t* pos,
279 std::string* content_name,
280 MediaContentDescription* media_desc,
281 TransportDescription* transport,
282 std::vector<JsepIceCandidate*>* candidates,
283 SdpParseError* error);
284static bool ParseSsrcAttribute(const std::string& line,
285 SsrcInfoVec* ssrc_infos,
286 SdpParseError* error);
287static bool ParseSsrcGroupAttribute(const std::string& line,
288 SsrcGroupVec* ssrc_groups,
289 SdpParseError* error);
290static bool ParseCryptoAttribute(const std::string& line,
291 MediaContentDescription* media_desc,
292 SdpParseError* error);
293static bool ParseRtpmapAttribute(const std::string& line,
294 const MediaType media_type,
295 const std::vector<int>& codec_preference,
296 MediaContentDescription* media_desc,
297 SdpParseError* error);
298static bool ParseFmtpAttributes(const std::string& line,
299 const MediaType media_type,
300 MediaContentDescription* media_desc,
301 SdpParseError* error);
302static bool ParseFmtpParam(const std::string& line, std::string* parameter,
303 std::string* value, SdpParseError* error);
304static bool ParseCandidate(const std::string& message, Candidate* candidate,
305 SdpParseError* error, bool is_raw);
306static bool ParseRtcpFbAttribute(const std::string& line,
307 const MediaType media_type,
308 MediaContentDescription* media_desc,
309 SdpParseError* error);
310static bool ParseIceOptions(const std::string& line,
311 std::vector<std::string>* transport_options,
312 SdpParseError* error);
313static bool ParseExtmap(const std::string& line,
314 RtpHeaderExtension* extmap,
315 SdpParseError* error);
316static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000317 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000318 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000319static bool ParseDtlsSetup(const std::string& line,
320 cricket::ConnectionRole* role,
321 SdpParseError* error);
deadbeef9d3584c2016-02-16 17:54:10 -0800322static bool ParseMsidAttribute(const std::string& line,
323 std::string* stream_id,
324 std::string* track_id,
325 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000326
327// Helper functions
328
329// Below ParseFailed*** functions output the line that caused the parsing
330// failure and the detailed reason (|description|) of the failure to |error|.
331// The functions always return false so that they can be used directly in the
332// following way when error happens:
333// "return ParseFailed***(...);"
334
335// The line starting at |line_start| of |message| is the failing line.
336// The reason for the failure should be provided in the |description|.
337// An example of a description could be "unknown character".
338static bool ParseFailed(const std::string& message,
339 size_t line_start,
340 const std::string& description,
341 SdpParseError* error) {
342 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000343 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000344 size_t line_end = message.find(kNewLine, line_start);
345 if (line_end != std::string::npos) {
346 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
347 --line_end;
348 }
349 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000350 } else {
351 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000352 }
353
354 if (error) {
355 error->line = first_line;
356 error->description = description;
357 }
358 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
359 << "\". Reason: " << description;
360 return false;
361}
362
363// |line| is the failing line. The reason for the failure should be
364// provided in the |description|.
365static bool ParseFailed(const std::string& line,
366 const std::string& description,
367 SdpParseError* error) {
368 return ParseFailed(line, 0, description, error);
369}
370
371// Parses failure where the failing SDP line isn't know or there are multiple
372// failing lines.
373static bool ParseFailed(const std::string& description,
374 SdpParseError* error) {
375 return ParseFailed("", description, error);
376}
377
378// |line| is the failing line. The failure is due to the fact that |line|
379// doesn't have |expected_fields| fields.
380static bool ParseFailedExpectFieldNum(const std::string& line,
381 int expected_fields,
382 SdpParseError* error) {
383 std::ostringstream description;
384 description << "Expects " << expected_fields << " fields.";
385 return ParseFailed(line, description.str(), error);
386}
387
388// |line| is the failing line. The failure is due to the fact that |line| has
389// less than |expected_min_fields| fields.
390static bool ParseFailedExpectMinFieldNum(const std::string& line,
391 int expected_min_fields,
392 SdpParseError* error) {
393 std::ostringstream description;
394 description << "Expects at least " << expected_min_fields << " fields.";
395 return ParseFailed(line, description.str(), error);
396}
397
398// |line| is the failing line. The failure is due to the fact that it failed to
399// get the value of |attribute|.
400static bool ParseFailedGetValue(const std::string& line,
401 const std::string& attribute,
402 SdpParseError* error) {
403 std::ostringstream description;
404 description << "Failed to get the value of attribute: " << attribute;
405 return ParseFailed(line, description.str(), error);
406}
407
408// The line starting at |line_start| of |message| is the failing line. The
409// failure is due to the line type (e.g. the "m" part of the "m-line")
410// not matching what is expected. The expected line type should be
411// provided as |line_type|.
412static bool ParseFailedExpectLine(const std::string& message,
413 size_t line_start,
414 const char line_type,
415 const std::string& line_value,
416 SdpParseError* error) {
417 std::ostringstream description;
418 description << "Expect line: " << line_type << "=" << line_value;
419 return ParseFailed(message, line_start, description.str(), error);
420}
421
422static bool AddLine(const std::string& line, std::string* message) {
423 if (!message)
424 return false;
425
426 message->append(line);
427 message->append(kLineBreak);
428 return true;
429}
430
431static bool GetLine(const std::string& message,
432 size_t* pos,
433 std::string* line) {
434 size_t line_begin = *pos;
435 size_t line_end = message.find(kNewLine, line_begin);
436 if (line_end == std::string::npos) {
437 return false;
438 }
439 // Update the new start position
440 *pos = line_end + 1;
441 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
442 --line_end;
443 }
444 *line = message.substr(line_begin, (line_end - line_begin));
445 const char* cline = line->c_str();
446 // RFC 4566
447 // An SDP session description consists of a number of lines of text of
448 // the form:
449 // <type>=<value>
450 // where <type> MUST be exactly one case-significant character and
451 // <value> is structured text whose format depends on <type>.
452 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000453 if (line->length() < 3 ||
454 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000455 cline[1] != kSdpDelimiterEqual ||
456 cline[2] == kSdpDelimiterSpace) {
457 *pos = line_begin;
458 return false;
459 }
460 return true;
461}
462
463// Init |os| to "|type|=|value|".
464static void InitLine(const char type,
465 const std::string& value,
466 std::ostringstream* os) {
467 os->str("");
468 *os << type << kSdpDelimiterEqual << value;
469}
470
471// Init |os| to "a=|attribute|".
472static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
473 InitLine(kLineTypeAttributes, attribute, os);
474}
475
476// Writes a SDP attribute line based on |attribute| and |value| to |message|.
477static void AddAttributeLine(const std::string& attribute, int value,
478 std::string* message) {
479 std::ostringstream os;
480 InitAttrLine(attribute, &os);
481 os << kSdpDelimiterColon << value;
482 AddLine(os.str(), message);
483}
484
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000485static bool IsLineType(const std::string& message,
486 const char type,
487 size_t line_start) {
488 if (message.size() < line_start + kLinePrefixLength) {
489 return false;
490 }
491 const char* cmessage = message.c_str();
492 return (cmessage[line_start] == type &&
493 cmessage[line_start + 1] == kSdpDelimiterEqual);
494}
495
496static bool IsLineType(const std::string& line,
497 const char type) {
498 return IsLineType(line, type, 0);
499}
500
501static bool GetLineWithType(const std::string& message, size_t* pos,
502 std::string* line, const char type) {
503 if (!IsLineType(message, type, *pos)) {
504 return false;
505 }
506
507 if (!GetLine(message, pos, line))
508 return false;
509
510 return true;
511}
512
513static bool HasAttribute(const std::string& line,
514 const std::string& attribute) {
515 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
516}
517
Peter Boström0c4e06b2015-10-07 12:23:21 +0200518static bool AddSsrcLine(uint32_t ssrc_id,
519 const std::string& attribute,
520 const std::string& value,
521 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000522 // RFC 5576
523 // a=ssrc:<ssrc-id> <attribute>:<value>
524 std::ostringstream os;
525 InitAttrLine(kAttributeSsrc, &os);
526 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
527 << attribute << kSdpDelimiterColon << value;
528 return AddLine(os.str(), message);
529}
530
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000531// Get value only from <attribute>:<value>.
532static bool GetValue(const std::string& message, const std::string& attribute,
533 std::string* value, SdpParseError* error) {
534 std::string leftpart;
Donald Curtis0e07f922015-05-15 09:21:23 -0700535 if (!rtc::tokenize_first(message, kSdpDelimiterColon, &leftpart, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000536 return ParseFailedGetValue(message, attribute, error);
537 }
538 // The left part should end with the expected attribute.
539 if (leftpart.length() < attribute.length() ||
540 leftpart.compare(leftpart.length() - attribute.length(),
541 attribute.length(), attribute) != 0) {
542 return ParseFailedGetValue(message, attribute, error);
543 }
544 return true;
545}
546
547static bool CaseInsensitiveFind(std::string str1, std::string str2) {
548 std::transform(str1.begin(), str1.end(), str1.begin(),
549 ::tolower);
550 std::transform(str2.begin(), str2.end(), str2.begin(),
551 ::tolower);
552 return str1.find(str2) != std::string::npos;
553}
554
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000555template <class T>
556static bool GetValueFromString(const std::string& line,
557 const std::string& s,
558 T* t,
559 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000560 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000561 std::ostringstream description;
562 description << "Invalid value: " << s << ".";
563 return ParseFailed(line, description.str(), error);
564 }
565 return true;
566}
567
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000568static bool GetPayloadTypeFromString(const std::string& line,
569 const std::string& s,
570 int* payload_type,
571 SdpParseError* error) {
572 return GetValueFromString(line, s, payload_type, error) &&
573 cricket::IsValidRtpPayloadType(*payload_type);
574}
575
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000576void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
577 StreamParamsVec* tracks) {
578 ASSERT(tracks != NULL);
579 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
580 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
581 if (ssrc_info->cname.empty()) {
582 continue;
583 }
584
585 std::string sync_label;
586 std::string track_id;
deadbeef9d3584c2016-02-16 17:54:10 -0800587 if (ssrc_info->stream_id == kDefaultMsid && !ssrc_info->mslabel.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000588 // If there's no msid and there's mslabel, we consider this is a sdp from
589 // a older version of client that doesn't support msid.
590 // In that case, we use the mslabel and label to construct the track.
591 sync_label = ssrc_info->mslabel;
592 track_id = ssrc_info->label;
593 } else {
deadbeef9d3584c2016-02-16 17:54:10 -0800594 sync_label = ssrc_info->stream_id;
595 track_id = ssrc_info->track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000596 }
597 if (sync_label.empty() || track_id.empty()) {
598 ASSERT(false);
599 continue;
600 }
601
602 StreamParamsVec::iterator track = tracks->begin();
603 for (; track != tracks->end(); ++track) {
604 if (track->id == track_id) {
605 break;
606 }
607 }
608 if (track == tracks->end()) {
609 // If we don't find an existing track, create a new one.
610 tracks->push_back(StreamParams());
611 track = tracks->end() - 1;
612 }
613 track->add_ssrc(ssrc_info->ssrc_id);
614 track->cname = ssrc_info->cname;
615 track->sync_label = sync_label;
616 track->id = track_id;
617 }
618}
619
620void GetMediaStreamLabels(const ContentInfo* content,
621 std::set<std::string>* labels) {
622 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000623 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000624 content->description);
625 const cricket::StreamParamsVec& streams = media_desc->streams();
626 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
627 it != streams.end(); ++it) {
628 labels->insert(it->sync_label);
629 }
630}
631
632// RFC 5245
633// It is RECOMMENDED that default candidates be chosen based on the
634// likelihood of those candidates to work with the peer that is being
635// contacted. It is RECOMMENDED that relayed > reflexive > host.
636static const int kPreferenceUnknown = 0;
637static const int kPreferenceHost = 1;
638static const int kPreferenceReflexive = 2;
639static const int kPreferenceRelayed = 3;
640
641static int GetCandidatePreferenceFromType(const std::string& type) {
642 int preference = kPreferenceUnknown;
643 if (type == cricket::LOCAL_PORT_TYPE) {
644 preference = kPreferenceHost;
645 } else if (type == cricket::STUN_PORT_TYPE) {
646 preference = kPreferenceReflexive;
647 } else if (type == cricket::RELAY_PORT_TYPE) {
648 preference = kPreferenceRelayed;
649 } else {
650 ASSERT(false);
651 }
652 return preference;
653}
654
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000655// Get ip and port of the default destination from the |candidates| with the
656// given value of |component_id|. The default candidate should be the one most
657// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658// RFC 5245
659// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
660// TODO: Decide the default destination in webrtcsession and
661// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000662static void GetDefaultDestination(
663 const std::vector<Candidate>& candidates,
664 int component_id, std::string* port,
665 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000666 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000667 *port = kDummyPort;
668 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000670 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000671 for (std::vector<Candidate>::const_iterator it = candidates.begin();
672 it != candidates.end(); ++it) {
673 if (it->component() != component_id) {
674 continue;
675 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000676 // Default destination should be UDP only.
677 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000678 continue;
679 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000680 const int preference = GetCandidatePreferenceFromType(it->type());
681 const int family = it->address().ipaddr().family();
682 // See if this candidate is more preferable then the current one if it's the
683 // same family. Or if the current family is IPv4 already so we could safely
684 // ignore all IPv6 ones. WebRTC bug 4269.
685 // http://code.google.com/p/webrtc/issues/detail?id=4269
686 if ((preference <= current_preference && current_family == family) ||
687 (current_family == AF_INET && family == AF_INET6)) {
688 continue;
689 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000690 if (family == AF_INET) {
691 addr_type->assign(kConnectionIpv4Addrtype);
692 } else if (family == AF_INET6) {
693 addr_type->assign(kConnectionIpv6Addrtype);
694 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000695 current_preference = preference;
696 current_family = family;
697 *port = it->address().PortAsString();
698 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000699 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000700}
701
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000702// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000703static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000704 const std::vector<Candidate>& candidates,
jbauch083b73f2015-07-16 02:46:32 -0700705 const std::string& mline,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000706 std::string* message) {
707 std::string new_lines;
708 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000709 // RFC 4566
710 // m=<media> <port> <proto> <fmt> ...
711 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000712 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000713 if (fields.size() < 3) {
714 return;
715 }
716
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000717 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000718 std::string rtp_port, rtp_ip, addr_type;
719 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
720 &rtp_port, &rtp_ip, &addr_type);
721 // Found default RTP candidate.
722 // RFC 5245
723 // The default candidates are added to the SDP as the default
724 // destination for media. For streams based on RTP, this is done by
725 // placing the IP address and port of the RTP candidate into the c and m
726 // lines, respectively.
727 // Update the port in the m line.
728 // If this is a m-line with port equal to 0, we don't change it.
729 if (fields[1] != kMediaPortRejected) {
730 new_lines.replace(fields[0].size() + 1,
731 fields[1].size(),
732 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000734 // Add the c line.
735 // RFC 4566
736 // c=<nettype> <addrtype> <connection-address>
737 InitLine(kLineTypeConnection, kConnectionNettype, &os);
738 os << " " << addr_type << " " << rtp_ip;
739 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000740 message->append(new_lines);
741}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000742
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000743// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
744static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000745 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
746 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
747 &rtcp_port, &rtcp_ip, &addr_type);
748 // Found default RTCP candidate.
749 // RFC 5245
750 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
751 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000752
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000753 // RFC 3605
754 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
755 // connection-address] CRLF
756 std::ostringstream os;
757 InitAttrLine(kAttributeRtcp, &os);
758 os << kSdpDelimiterColon
759 << rtcp_port << " "
760 << kConnectionNettype << " "
761 << addr_type << " "
762 << rtcp_ip;
763 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000764 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765}
766
767// Get candidates according to the mline index from SessionDescriptionInterface.
768static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
769 int mline_index,
770 std::vector<Candidate>* candidates) {
771 if (!candidates) {
772 return;
773 }
774 const IceCandidateCollection* cc = desci.candidates(mline_index);
775 for (size_t i = 0; i < cc->count(); ++i) {
776 const IceCandidateInterface* candidate = cc->at(i);
777 candidates->push_back(candidate->candidate());
778 }
779}
780
deadbeef9d3584c2016-02-16 17:54:10 -0800781std::string SdpSerialize(const JsepSessionDescription& jdesc,
782 bool unified_plan_sdp) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000783 const cricket::SessionDescription* desc = jdesc.description();
784 if (!desc) {
785 return "";
786 }
787
788 std::string message;
789
790 // Session Description.
791 AddLine(kSessionVersion, &message);
792 // Session Origin
793 // RFC 4566
794 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
795 // <unicast-address>
796 std::ostringstream os;
797 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
jbauch083b73f2015-07-16 02:46:32 -0700798 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000799 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700800 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000801 kSessionOriginSessionVersion : jdesc.session_version();
802 os << " " << session_id << " " << session_version << " "
803 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
804 << kSessionOriginAddress;
805 AddLine(os.str(), &message);
806 AddLine(kSessionName, &message);
807
808 // Time Description.
809 AddLine(kTimeDescription, &message);
810
811 // Group
812 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
813 std::string group_line = kAttrGroup;
814 const cricket::ContentGroup* group =
815 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
816 ASSERT(group != NULL);
817 const cricket::ContentNames& content_names = group->content_names();
818 for (cricket::ContentNames::const_iterator it = content_names.begin();
819 it != content_names.end(); ++it) {
820 group_line.append(" ");
821 group_line.append(*it);
822 }
823 AddLine(group_line, &message);
824 }
825
826 // MediaStream semantics
827 InitAttrLine(kAttributeMsidSemantics, &os);
828 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000829
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000830 std::set<std::string> media_stream_labels;
831 const ContentInfo* audio_content = GetFirstAudioContent(desc);
832 if (audio_content)
833 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000834
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835 const ContentInfo* video_content = GetFirstVideoContent(desc);
836 if (video_content)
837 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000838
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000839 for (std::set<std::string>::const_iterator it =
840 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
841 os << " " << *it;
842 }
843 AddLine(os.str(), &message);
844
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000845 // Preserve the order of the media contents.
846 int mline_index = -1;
847 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
848 it != desc->contents().end(); ++it) {
849 const MediaContentDescription* mdesc =
850 static_cast<const MediaContentDescription*>(it->description);
851 std::vector<Candidate> candidates;
852 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
deadbeef9d3584c2016-02-16 17:54:10 -0800853 BuildMediaDescription(&*it, desc->GetTransportInfoByName(it->name),
854 mdesc->type(), candidates, unified_plan_sdp,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000855 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000856 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000857 return message;
858}
859
860// Serializes the passed in IceCandidateInterface to a SDP string.
861// candidate - The candidate to be serialized.
862std::string SdpSerializeCandidate(
863 const IceCandidateInterface& candidate) {
864 std::string message;
865 std::vector<cricket::Candidate> candidates;
866 candidates.push_back(candidate.candidate());
honghaiza54a0802015-12-16 18:37:23 -0800867 BuildCandidate(candidates, true, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000868 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
869 // just candidate:<candidate> not a=candidate:<blah>CRLF
870 ASSERT(message.find("a=") == 0);
871 message.erase(0, 2);
872 ASSERT(message.find(kLineBreak) == message.size() - 2);
873 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874 return message;
875}
876
877bool SdpDeserialize(const std::string& message,
878 JsepSessionDescription* jdesc,
879 SdpParseError* error) {
880 std::string session_id;
881 std::string session_version;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700882 TransportDescription session_td("", "");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883 RtpHeaderExtensions session_extmaps;
884 cricket::SessionDescription* desc = new cricket::SessionDescription();
885 std::vector<JsepIceCandidate*> candidates;
886 size_t current_pos = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887
888 // Session Description
889 if (!ParseSessionDescription(message, &current_pos, &session_id,
deadbeefc80741f2015-10-22 13:14:45 -0700890 &session_version, &session_td, &session_extmaps,
891 desc, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000892 delete desc;
893 return false;
894 }
895
896 // Media Description
deadbeefc80741f2015-10-22 13:14:45 -0700897 if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
898 desc, &candidates, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899 delete desc;
900 for (std::vector<JsepIceCandidate*>::const_iterator
901 it = candidates.begin(); it != candidates.end(); ++it) {
902 delete *it;
903 }
904 return false;
905 }
906
907 jdesc->Initialize(desc, session_id, session_version);
908
909 for (std::vector<JsepIceCandidate*>::const_iterator
910 it = candidates.begin(); it != candidates.end(); ++it) {
911 jdesc->AddCandidate(*it);
912 delete *it;
913 }
914 return true;
915}
916
917bool SdpDeserializeCandidate(const std::string& message,
918 JsepIceCandidate* jcandidate,
919 SdpParseError* error) {
920 ASSERT(jcandidate != NULL);
921 Candidate candidate;
922 if (!ParseCandidate(message, &candidate, error, true)) {
923 return false;
924 }
925 jcandidate->SetCandidate(candidate);
926 return true;
927}
928
929bool ParseCandidate(const std::string& message, Candidate* candidate,
930 SdpParseError* error, bool is_raw) {
931 ASSERT(candidate != NULL);
932
933 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000934 std::string first_line = message;
935 size_t pos = 0;
936 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000938 // Makes sure |message| contains only one line.
939 if (message.size() > first_line.size()) {
940 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700941 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
942 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000943 return ParseFailed(message, 0, "Expect one line only", error);
944 }
945 }
946
947 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
948 // candidate:<candidate> when trickled, but we still support
949 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
950 // from the SDP.
951 if (IsLineType(first_line, kLineTypeAttributes)) {
952 first_line = first_line.substr(kLinePrefixLength);
953 }
954
955 std::string attribute_candidate;
956 std::string candidate_value;
957
958 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700959 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
960 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000961 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962 if (is_raw) {
963 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000964 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000965 << ":" << "<candidate-str>";
966 return ParseFailed(first_line, 0, description.str(), error);
967 } else {
968 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
969 kAttributeCandidate, error);
970 }
971 }
972
973 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000974 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
975
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000976 // RFC 5245
977 // a=candidate:<foundation> <component-id> <transport> <priority>
978 // <connection-address> <port> typ <candidate-types>
979 // [raddr <connection-address>] [rport <port>]
980 // *(SP extension-att-name SP extension-att-value)
981 const size_t expected_min_fields = 8;
982 if (fields.size() < expected_min_fields ||
983 (fields[6] != kAttributeCandidateTyp)) {
984 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
985 }
jbauch083b73f2015-07-16 02:46:32 -0700986 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000987
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000988 int component_id = 0;
989 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
990 return false;
991 }
jbauch083b73f2015-07-16 02:46:32 -0700992 const std::string& transport = fields[2];
Peter Boström0c4e06b2015-10-07 12:23:21 +0200993 uint32_t priority = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000994 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
995 return false;
996 }
jbauch083b73f2015-07-16 02:46:32 -0700997 const std::string& connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000998 int port = 0;
999 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1000 return false;
1001 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002 SocketAddress address(connection_address, port);
1003
1004 cricket::ProtocolType protocol;
1005 if (!StringToProto(transport.c_str(), &protocol)) {
1006 return ParseFailed(first_line, "Unsupported transport type.", error);
1007 }
1008
1009 std::string candidate_type;
jbauch083b73f2015-07-16 02:46:32 -07001010 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 if (type == kCandidateHost) {
1012 candidate_type = cricket::LOCAL_PORT_TYPE;
1013 } else if (type == kCandidateSrflx) {
1014 candidate_type = cricket::STUN_PORT_TYPE;
1015 } else if (type == kCandidateRelay) {
1016 candidate_type = cricket::RELAY_PORT_TYPE;
1017 } else {
1018 return ParseFailed(first_line, "Unsupported candidate type.", error);
1019 }
1020
1021 size_t current_position = expected_min_fields;
1022 SocketAddress related_address;
1023 // The 2 optional fields for related address
1024 // [raddr <connection-address>] [rport <port>]
1025 if (fields.size() >= (current_position + 2) &&
1026 fields[current_position] == kAttributeCandidateRaddr) {
1027 related_address.SetIP(fields[++current_position]);
1028 ++current_position;
1029 }
1030 if (fields.size() >= (current_position + 2) &&
1031 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001032 int port = 0;
1033 if (!GetValueFromString(
1034 first_line, fields[++current_position], &port, error)) {
1035 return false;
1036 }
1037 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 ++current_position;
1039 }
1040
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001041 // If this is a TCP candidate, it has additional extension as defined in
1042 // RFC 6544.
1043 std::string tcptype;
1044 if (fields.size() >= (current_position + 2) &&
1045 fields[current_position] == kTcpCandidateType) {
1046 tcptype = fields[++current_position];
1047 ++current_position;
1048
1049 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1050 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1051 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1052 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1053 }
1054
1055 if (protocol != cricket::PROTO_TCP) {
1056 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1057 }
1058 }
1059
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060 // Extension
honghaiza54a0802015-12-16 18:37:23 -08001061 // Though non-standard, we support the ICE ufrag and pwd being signaled on
1062 // the candidate to avoid issues with confusing which generation a candidate
1063 // belongs to when trickling multiple generations at the same time.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001064 std::string username;
1065 std::string password;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001066 uint32_t generation = 0;
honghaize1a0c942016-02-16 14:54:56 -08001067 uint32_t network_cost = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1069 // RFC 5245
1070 // *(SP extension-att-name SP extension-att-value)
1071 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001072 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1073 return false;
1074 }
honghaiza54a0802015-12-16 18:37:23 -08001075 } else if (fields[i] == kAttributeCandidateUfrag) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001076 username = fields[++i];
honghaiza54a0802015-12-16 18:37:23 -08001077 } else if (fields[i] == kAttributeCandidatePwd) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078 password = fields[++i];
honghaize1a0c942016-02-16 14:54:56 -08001079 } else if (fields[i] == kAttributeCandidateNetworkCost) {
1080 if (!GetValueFromString(first_line, fields[++i], &network_cost, error)) {
1081 return false;
1082 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001083 } else {
1084 // Skip the unknown extension.
1085 ++i;
1086 }
1087 }
1088
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001089 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001090 address, priority, username, password, candidate_type,
1091 generation, foundation);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001092 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001093 candidate->set_tcptype(tcptype);
honghaize1a0c942016-02-16 14:54:56 -08001094 candidate->set_network_cost(std::min(network_cost, cricket::kMaxNetworkCost));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095 return true;
1096}
1097
1098bool ParseIceOptions(const std::string& line,
1099 std::vector<std::string>* transport_options,
1100 SdpParseError* error) {
1101 std::string ice_options;
1102 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1103 return false;
1104 }
1105 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001106 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001107 for (size_t i = 0; i < fields.size(); ++i) {
1108 transport_options->push_back(fields[i]);
1109 }
1110 return true;
1111}
1112
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001113bool ParseSctpPort(const std::string& line,
1114 int* sctp_port,
1115 SdpParseError* error) {
1116 // draft-ietf-mmusic-sctp-sdp-07
1117 // a=sctp-port
1118 std::vector<std::string> fields;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001119 const size_t expected_min_fields = 2;
lally69f57602015-10-08 10:15:04 -07001120 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1121 if (fields.size() < expected_min_fields) {
1122 fields.resize(0);
1123 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpace, &fields);
1124 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001125 if (fields.size() < expected_min_fields) {
1126 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1127 }
1128 if (!rtc::FromString(fields[1], sctp_port)) {
lally69f57602015-10-08 10:15:04 -07001129 return ParseFailed(line, "Invalid sctp port value.", error);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001130 }
1131 return true;
1132}
1133
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001134bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1135 SdpParseError* error) {
1136 // RFC 5285
1137 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1138 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001139 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001140 kSdpDelimiterSpace, &fields);
1141 const size_t expected_min_fields = 2;
1142 if (fields.size() < expected_min_fields) {
1143 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1144 }
1145 std::string uri = fields[1];
1146
1147 std::string value_direction;
1148 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1149 return false;
1150 }
1151 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001152 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001153 int value = 0;
1154 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1155 return false;
1156 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001157
1158 *extmap = RtpHeaderExtension(uri, value);
1159 return true;
1160}
1161
1162void BuildMediaDescription(const ContentInfo* content_info,
1163 const TransportInfo* transport_info,
1164 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001165 const std::vector<Candidate>& candidates,
deadbeef9d3584c2016-02-16 17:54:10 -08001166 bool unified_plan_sdp,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001167 std::string* message) {
1168 ASSERT(message != NULL);
1169 if (content_info == NULL || message == NULL) {
1170 return;
1171 }
1172 // TODO: Rethink if we should use sprintfn instead of stringstream.
1173 // According to the style guide, streams should only be used for logging.
1174 // http://google-styleguide.googlecode.com/svn/
1175 // trunk/cppguide.xml?showone=Streams#Streams
1176 std::ostringstream os;
1177 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001178 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001179 content_info->description);
1180 ASSERT(media_desc != NULL);
1181
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001182 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001183
1184 // RFC 4566
1185 // m=<media> <port> <proto> <fmt>
1186 // fmt is a list of payload type numbers that MAY be used in the session.
1187 const char* type = NULL;
1188 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1189 type = kMediaTypeAudio;
1190 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1191 type = kMediaTypeVideo;
1192 else if (media_type == cricket::MEDIA_TYPE_DATA)
1193 type = kMediaTypeData;
1194 else
1195 ASSERT(false);
1196
1197 std::string fmt;
1198 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1199 const VideoContentDescription* video_desc =
1200 static_cast<const VideoContentDescription*>(media_desc);
1201 for (std::vector<cricket::VideoCodec>::const_iterator it =
1202 video_desc->codecs().begin();
1203 it != video_desc->codecs().end(); ++it) {
1204 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001205 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206 }
1207 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1208 const AudioContentDescription* audio_desc =
1209 static_cast<const AudioContentDescription*>(media_desc);
1210 for (std::vector<cricket::AudioCodec>::const_iterator it =
1211 audio_desc->codecs().begin();
1212 it != audio_desc->codecs().end(); ++it) {
1213 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001214 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001215 }
1216 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001217 const DataContentDescription* data_desc =
1218 static_cast<const DataContentDescription*>(media_desc);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001219 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001221
1222 for (std::vector<cricket::DataCodec>::const_iterator it =
1223 data_desc->codecs().begin();
1224 it != data_desc->codecs().end(); ++it) {
1225 if (it->id == cricket::kGoogleSctpDataCodecId &&
1226 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1227 break;
1228 }
1229 }
1230
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001231 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001232 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233 for (std::vector<cricket::DataCodec>::const_iterator it =
1234 data_desc->codecs().begin();
1235 it != data_desc->codecs().end(); ++it) {
1236 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001237 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001238 }
1239 }
1240 }
1241 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1242 // to 0.
1243 if (fmt.empty()) {
1244 fmt = " 0";
1245 }
1246
1247 // The port number in the m line will be updated later when associate with
1248 // the candidates.
1249 // RFC 3264
1250 // To reject an offered stream, the port number in the corresponding stream in
1251 // the answer MUST be set to zero.
jbauch083b73f2015-07-16 02:46:32 -07001252 const std::string& port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001253 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001254
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001255 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256 transport_info->description.identity_fingerprint.get() : NULL;
1257
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001258 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001259 InitLine(kLineTypeMedia, type, &os);
1260 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001261 std::string mline = os.str();
1262 UpdateMediaDefaultDestination(candidates, mline, message);
1263
1264 // RFC 4566
1265 // b=AS:<bandwidth>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001266 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001267 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1268 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1269 AddLine(os.str(), message);
1270 }
1271
1272 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001273 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001274 std::string rtcp_line = GetRtcpLine(candidates);
1275 if (!rtcp_line.empty()) {
1276 AddLine(rtcp_line, message);
1277 }
1278 }
1279
honghaiza54a0802015-12-16 18:37:23 -08001280 // Build the a=candidate lines. We don't include ufrag and pwd in the
1281 // candidates in the SDP to avoid redundancy.
1282 BuildCandidate(candidates, false, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283
1284 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1285 if (transport_info) {
1286 // RFC 5245
1287 // ice-pwd-att = "ice-pwd" ":" password
1288 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1289 // ice-ufrag
deadbeef3f7219b2015-12-28 15:17:14 -08001290 if (!transport_info->description.ice_ufrag.empty()) {
1291 InitAttrLine(kAttributeIceUfrag, &os);
1292 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1293 AddLine(os.str(), message);
1294 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295 // ice-pwd
deadbeef3f7219b2015-12-28 15:17:14 -08001296 if (!transport_info->description.ice_pwd.empty()) {
1297 InitAttrLine(kAttributeIcePwd, &os);
1298 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1299 AddLine(os.str(), message);
1300 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001301
1302 // draft-petithuguenin-mmusic-ice-attributes-level-03
1303 BuildIceOptions(transport_info->description.transport_options, message);
1304
1305 // RFC 4572
1306 // fingerprint-attribute =
1307 // "fingerprint" ":" hash-func SP fingerprint
1308 if (fp) {
1309 // Insert the fingerprint attribute.
1310 InitAttrLine(kAttributeFingerprint, &os);
1311 os << kSdpDelimiterColon
1312 << fp->algorithm << kSdpDelimiterSpace
1313 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001314 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001315
1316 // Inserting setup attribute.
1317 if (transport_info->description.connection_role !=
1318 cricket::CONNECTIONROLE_NONE) {
1319 // Making sure we are not using "passive" mode.
1320 cricket::ConnectionRole role =
1321 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001322 std::string dtls_role_str;
1323 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001324 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001325 os << kSdpDelimiterColon << dtls_role_str;
1326 AddLine(os.str(), message);
1327 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328 }
1329 }
1330
1331 // RFC 3388
1332 // mid-attribute = "a=mid:" identification-tag
1333 // identification-tag = token
1334 // Use the content name as the mid identification-tag.
1335 InitAttrLine(kAttributeMid, &os);
1336 os << kSdpDelimiterColon << content_info->name;
1337 AddLine(os.str(), message);
1338
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001339 if (IsDtlsSctp(media_desc->protocol())) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001340 BuildSctpContentAttributes(message, sctp_port);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001341 } else if (IsRtp(media_desc->protocol())) {
deadbeef9d3584c2016-02-16 17:54:10 -08001342 BuildRtpContentAttributes(media_desc, media_type, unified_plan_sdp,
1343 message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 }
1345}
1346
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001347void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001348 // draft-ietf-mmusic-sctp-sdp-04
1349 // a=sctpmap:sctpmap-number protocol [streams]
lally69f57602015-10-08 10:15:04 -07001350 // TODO(lally): switch this over to mmusic-sctp-sdp-12 (or later), with
1351 // 'a=sctp-port:'
wu@webrtc.org78187522013-10-07 23:32:02 +00001352 std::ostringstream os;
1353 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001354 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001355 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1356 << (cricket::kMaxSctpSid + 1);
1357 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358}
1359
deadbeef9d3584c2016-02-16 17:54:10 -08001360// If unified_plan_sdp is true, will use "a=msid".
1361void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
1362 const MediaType media_type,
1363 bool unified_plan_sdp,
1364 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001365 std::ostringstream os;
1366 // RFC 5285
1367 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1368 // The definitions MUST be either all session level or all media level. This
1369 // implementation uses all media level.
1370 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1371 InitAttrLine(kAttributeExtmap, &os);
1372 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1373 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1374 AddLine(os.str(), message);
1375 }
1376
1377 // RFC 3264
1378 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
deadbeefc80741f2015-10-22 13:14:45 -07001379 switch (media_desc->direction()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001380 case cricket::MD_INACTIVE:
1381 InitAttrLine(kAttributeInactive, &os);
1382 break;
1383 case cricket::MD_SENDONLY:
1384 InitAttrLine(kAttributeSendOnly, &os);
1385 break;
1386 case cricket::MD_RECVONLY:
1387 InitAttrLine(kAttributeRecvOnly, &os);
1388 break;
1389 case cricket::MD_SENDRECV:
1390 default:
1391 InitAttrLine(kAttributeSendRecv, &os);
1392 break;
1393 }
1394 AddLine(os.str(), message);
1395
deadbeef9d3584c2016-02-16 17:54:10 -08001396 // draft-ietf-mmusic-msid-11
1397 // a=msid:<stream id> <track id>
1398 if (unified_plan_sdp && !media_desc->streams().empty()) {
1399 if (media_desc->streams().size() > 1u) {
1400 LOG(LS_WARNING) << "Trying to serialize unified plan SDP with more than "
1401 << "one track in a media section. Omitting 'a=msid'.";
1402 } else {
1403 auto track = media_desc->streams().begin();
1404 const std::string& stream_id = track->sync_label;
deadbeef9d3584c2016-02-16 17:54:10 -08001405 InitAttrLine(kAttributeMsid, &os);
1406 os << kSdpDelimiterColon << stream_id << kSdpDelimiterSpace << track->id;
1407 AddLine(os.str(), message);
1408 }
1409 }
1410
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411 // RFC 5761
1412 // a=rtcp-mux
1413 if (media_desc->rtcp_mux()) {
1414 InitAttrLine(kAttributeRtcpMux, &os);
1415 AddLine(os.str(), message);
1416 }
1417
deadbeef13871492015-12-09 12:37:51 -08001418 // RFC 5506
1419 // a=rtcp-rsize
1420 if (media_desc->rtcp_reduced_size()) {
1421 InitAttrLine(kAttributeRtcpReducedSize, &os);
1422 AddLine(os.str(), message);
1423 }
1424
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001425 // RFC 4568
1426 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1427 for (std::vector<CryptoParams>::const_iterator it =
1428 media_desc->cryptos().begin();
1429 it != media_desc->cryptos().end(); ++it) {
1430 InitAttrLine(kAttributeCrypto, &os);
1431 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1432 << it->key_params;
1433 if (!it->session_params.empty()) {
1434 os << " " << it->session_params;
1435 }
1436 AddLine(os.str(), message);
1437 }
1438
1439 // RFC 4566
1440 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1441 // [/<encodingparameters>]
1442 BuildRtpMap(media_desc, media_type, message);
1443
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1445 track != media_desc->streams().end(); ++track) {
1446 // Require that the track belongs to a media stream,
1447 // ie the sync_label is set. This extra check is necessary since the
1448 // MediaContentDescription always contains a streamparam with an ssrc even
1449 // if no track or media stream have been created.
1450 if (track->sync_label.empty()) continue;
1451
1452 // Build the ssrc-group lines.
1453 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1454 // RFC 5576
1455 // a=ssrc-group:<semantics> <ssrc-id> ...
1456 if (track->ssrc_groups[i].ssrcs.empty()) {
1457 continue;
1458 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459 InitAttrLine(kAttributeSsrcGroup, &os);
1460 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001461 std::vector<uint32_t>::const_iterator ssrc =
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462 track->ssrc_groups[i].ssrcs.begin();
1463 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001464 os << kSdpDelimiterSpace << rtc::ToString<uint32_t>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001465 }
1466 AddLine(os.str(), message);
1467 }
1468 // Build the ssrc lines for each ssrc.
1469 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001470 uint32_t ssrc = track->ssrcs[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 // RFC 5576
1472 // a=ssrc:<ssrc-id> cname:<value>
1473 AddSsrcLine(ssrc, kSsrcAttributeCname,
1474 track->cname, message);
1475
1476 // draft-alvestrand-mmusic-msid-00
1477 // a=ssrc:<ssrc-id> msid:identifier [appdata]
deadbeef9d3584c2016-02-16 17:54:10 -08001478 // The appdata consists of the "id" attribute of a MediaStreamTrack,
1479 // which corresponds to the "id" attribute of StreamParams.
1480 const std::string& stream_id = track->sync_label;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001481 InitAttrLine(kAttributeSsrc, &os);
1482 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
deadbeef9d3584c2016-02-16 17:54:10 -08001483 << kSsrcAttributeMsid << kSdpDelimiterColon << stream_id
1484 << kSdpDelimiterSpace << track->id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001485 AddLine(os.str(), message);
1486
deadbeef9d3584c2016-02-16 17:54:10 -08001487 // TODO(ronghuawu): Remove below code which is for backward
1488 // compatibility.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001489 // draft-alvestrand-rtcweb-mid-01
1490 // a=ssrc:<ssrc-id> mslabel:<value>
1491 // The label isn't yet defined.
1492 // a=ssrc:<ssrc-id> label:<value>
1493 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1494 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1495 }
1496 }
1497}
1498
1499void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1500 // fmtp header: a=fmtp:|payload_type| <parameters>
1501 // Add a=fmtp
1502 InitAttrLine(kAttributeFmtp, os);
1503 // Add :|payload_type|
1504 *os << kSdpDelimiterColon << payload_type;
1505}
1506
1507void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1508 // rtcp-fb header: a=rtcp-fb:|payload_type|
1509 // <parameters>/<ccm <ccm_parameters>>
1510 // Add a=rtcp-fb
1511 InitAttrLine(kAttributeRtcpFb, os);
1512 // Add :
1513 *os << kSdpDelimiterColon;
1514 if (payload_type == kWildcardPayloadType) {
1515 *os << "*";
1516 } else {
1517 *os << payload_type;
1518 }
1519}
1520
1521void WriteFmtpParameter(const std::string& parameter_name,
1522 const std::string& parameter_value,
1523 std::ostringstream* os) {
1524 // fmtp parameters: |parameter_name|=|parameter_value|
1525 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1526}
1527
1528void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1529 std::ostringstream* os) {
1530 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1531 fmtp != parameters.end(); ++fmtp) {
1532 // Each new parameter, except the first one starts with ";" and " ".
1533 if (fmtp != parameters.begin()) {
1534 *os << kSdpDelimiterSemicolon;
1535 }
1536 *os << kSdpDelimiterSpace;
1537 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1538 }
1539}
1540
1541bool IsFmtpParam(const std::string& name) {
1542 const char* kFmtpParams[] = {
1543 kCodecParamMinPTime, kCodecParamSPropStereo,
Minyue Li7100dcd2015-03-27 05:05:59 +01001544 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamUseDtx,
1545 kCodecParamStartBitrate, kCodecParamMaxBitrate, kCodecParamMinBitrate,
1546 kCodecParamMaxQuantization, kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001547 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1548 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001549 };
tfarina5237aaf2015-11-10 23:44:30 -08001550 for (size_t i = 0; i < arraysize(kFmtpParams); ++i) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001551 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1552 return true;
1553 }
1554 }
1555 return false;
1556}
1557
1558// Retreives fmtp parameters from |params|, which may contain other parameters
1559// as well, and puts them in |fmtp_parameters|.
1560void GetFmtpParams(const cricket::CodecParameterMap& params,
1561 cricket::CodecParameterMap* fmtp_parameters) {
1562 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1563 iter != params.end(); ++iter) {
1564 if (IsFmtpParam(iter->first)) {
1565 (*fmtp_parameters)[iter->first] = iter->second;
1566 }
1567 }
1568}
1569
1570template <class T>
1571void AddFmtpLine(const T& codec, std::string* message) {
1572 cricket::CodecParameterMap fmtp_parameters;
1573 GetFmtpParams(codec.params, &fmtp_parameters);
1574 if (fmtp_parameters.empty()) {
1575 // No need to add an fmtp if it will have no (optional) parameters.
1576 return;
1577 }
1578 std::ostringstream os;
1579 WriteFmtpHeader(codec.id, &os);
1580 WriteFmtpParameters(fmtp_parameters, &os);
1581 AddLine(os.str(), message);
1582 return;
1583}
1584
1585template <class T>
1586void AddRtcpFbLines(const T& codec, std::string* message) {
1587 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1588 codec.feedback_params.params().begin();
1589 iter != codec.feedback_params.params().end(); ++iter) {
1590 std::ostringstream os;
1591 WriteRtcpFbHeader(codec.id, &os);
1592 os << " " << iter->id();
1593 if (!iter->param().empty()) {
1594 os << " " << iter->param();
1595 }
1596 AddLine(os.str(), message);
1597 }
1598}
1599
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001600bool AddSctpDataCodec(DataContentDescription* media_desc,
1601 int sctp_port) {
1602 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1603 return ParseFailed("",
1604 "Can't have multiple sctp port attributes.",
1605 NULL);
1606 }
1607 // Add the SCTP Port number as a pseudo-codec "port" parameter
1608 cricket::DataCodec codec_port(
1609 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1610 0);
1611 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1612 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1613 << sctp_port;
1614 media_desc->AddCodec(codec_port);
1615 return true;
1616}
1617
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001618bool GetMinValue(const std::vector<int>& values, int* value) {
1619 if (values.empty()) {
1620 return false;
1621 }
1622 std::vector<int>::const_iterator found =
1623 std::min_element(values.begin(), values.end());
1624 *value = *found;
1625 return true;
1626}
1627
1628bool GetParameter(const std::string& name,
1629 const cricket::CodecParameterMap& params, int* value) {
1630 std::map<std::string, std::string>::const_iterator found =
1631 params.find(name);
1632 if (found == params.end()) {
1633 return false;
1634 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001635 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001636 return false;
1637 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001638 return true;
1639}
1640
1641void BuildRtpMap(const MediaContentDescription* media_desc,
1642 const MediaType media_type,
1643 std::string* message) {
1644 ASSERT(message != NULL);
1645 ASSERT(media_desc != NULL);
1646 std::ostringstream os;
1647 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1648 const VideoContentDescription* video_desc =
1649 static_cast<const VideoContentDescription*>(media_desc);
1650 for (std::vector<cricket::VideoCodec>::const_iterator it =
1651 video_desc->codecs().begin();
1652 it != video_desc->codecs().end(); ++it) {
1653 // RFC 4566
1654 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1655 // [/<encodingparameters>]
1656 if (it->id != kWildcardPayloadType) {
1657 InitAttrLine(kAttributeRtpmap, &os);
1658 os << kSdpDelimiterColon << it->id << " " << it->name
1659 << "/" << kDefaultVideoClockrate;
1660 AddLine(os.str(), message);
1661 }
1662 AddRtcpFbLines(*it, message);
1663 AddFmtpLine(*it, message);
1664 }
1665 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1666 const AudioContentDescription* audio_desc =
1667 static_cast<const AudioContentDescription*>(media_desc);
1668 std::vector<int> ptimes;
1669 std::vector<int> maxptimes;
1670 int max_minptime = 0;
1671 for (std::vector<cricket::AudioCodec>::const_iterator it =
1672 audio_desc->codecs().begin();
1673 it != audio_desc->codecs().end(); ++it) {
1674 ASSERT(!it->name.empty());
1675 // RFC 4566
1676 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1677 // [/<encodingparameters>]
1678 InitAttrLine(kAttributeRtpmap, &os);
1679 os << kSdpDelimiterColon << it->id << " ";
1680 os << it->name << "/" << it->clockrate;
1681 if (it->channels != 1) {
1682 os << "/" << it->channels;
1683 }
1684 AddLine(os.str(), message);
1685 AddRtcpFbLines(*it, message);
1686 AddFmtpLine(*it, message);
1687 int minptime = 0;
1688 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1689 max_minptime = std::max(minptime, max_minptime);
1690 }
1691 int ptime;
1692 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1693 ptimes.push_back(ptime);
1694 }
1695 int maxptime;
1696 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1697 maxptimes.push_back(maxptime);
1698 }
1699 }
1700 // Populate the maxptime attribute with the smallest maxptime of all codecs
1701 // under the same m-line.
1702 int min_maxptime = INT_MAX;
1703 if (GetMinValue(maxptimes, &min_maxptime)) {
1704 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1705 }
1706 ASSERT(min_maxptime > max_minptime);
1707 // Populate the ptime attribute with the smallest ptime or the largest
1708 // minptime, whichever is the largest, for all codecs under the same m-line.
1709 int ptime = INT_MAX;
1710 if (GetMinValue(ptimes, &ptime)) {
1711 ptime = std::min(ptime, min_maxptime);
1712 ptime = std::max(ptime, max_minptime);
1713 AddAttributeLine(kCodecParamPTime, ptime, message);
1714 }
1715 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1716 const DataContentDescription* data_desc =
1717 static_cast<const DataContentDescription*>(media_desc);
1718 for (std::vector<cricket::DataCodec>::const_iterator it =
1719 data_desc->codecs().begin();
1720 it != data_desc->codecs().end(); ++it) {
1721 // RFC 4566
1722 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1723 // [/<encodingparameters>]
1724 InitAttrLine(kAttributeRtpmap, &os);
1725 os << kSdpDelimiterColon << it->id << " "
1726 << it->name << "/" << it->clockrate;
1727 AddLine(os.str(), message);
1728 }
1729 }
1730}
1731
1732void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -08001733 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734 std::string* message) {
1735 std::ostringstream os;
1736
1737 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1738 it != candidates.end(); ++it) {
1739 // RFC 5245
1740 // a=candidate:<foundation> <component-id> <transport> <priority>
1741 // <connection-address> <port> typ <candidate-types>
1742 // [raddr <connection-address>] [rport <port>]
1743 // *(SP extension-att-name SP extension-att-value)
1744 std::string type;
1745 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1746 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1747 type = kCandidateHost;
1748 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1749 type = kCandidateSrflx;
1750 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1751 type = kCandidateRelay;
1752 } else {
1753 ASSERT(false);
Peter Thatcher019087f2015-04-28 09:06:26 -07001754 // Never write out candidates if we don't know the type.
1755 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001756 }
1757
1758 InitAttrLine(kAttributeCandidate, &os);
1759 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001760 << it->foundation() << " "
1761 << it->component() << " "
1762 << it->protocol() << " "
1763 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764 << it->address().ipaddr().ToString() << " "
1765 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001766 << kAttributeCandidateTyp << " "
1767 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001768
1769 // Related address
1770 if (!it->related_address().IsNil()) {
1771 os << kAttributeCandidateRaddr << " "
1772 << it->related_address().ipaddr().ToString() << " "
1773 << kAttributeCandidateRport << " "
1774 << it->related_address().PortAsString() << " ";
1775 }
1776
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001777 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001778 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001779 }
1780
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001781 // Extensions
1782 os << kAttributeCandidateGeneration << " " << it->generation();
honghaiza54a0802015-12-16 18:37:23 -08001783 if (include_ufrag && !it->username().empty()) {
1784 os << " " << kAttributeCandidateUfrag << " " << it->username();
1785 }
honghaize1a0c942016-02-16 14:54:56 -08001786 if (it->network_cost() > 0) {
1787 os << " " << kAttributeCandidateNetworkCost << " " << it->network_cost();
1788 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001789
1790 AddLine(os.str(), message);
1791 }
1792}
1793
1794void BuildIceOptions(const std::vector<std::string>& transport_options,
1795 std::string* message) {
1796 if (!transport_options.empty()) {
1797 std::ostringstream os;
1798 InitAttrLine(kAttributeIceOption, &os);
1799 os << kSdpDelimiterColon << transport_options[0];
1800 for (size_t i = 1; i < transport_options.size(); ++i) {
1801 os << kSdpDelimiterSpace << transport_options[i];
1802 }
1803 AddLine(os.str(), message);
1804 }
1805}
1806
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001807bool IsRtp(const std::string& protocol) {
1808 return protocol.empty() ||
1809 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1810}
1811
1812bool IsDtlsSctp(const std::string& protocol) {
1813 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001814 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001815}
1816
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001817bool ParseSessionDescription(const std::string& message, size_t* pos,
1818 std::string* session_id,
1819 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820 TransportDescription* session_td,
1821 RtpHeaderExtensions* session_extmaps,
1822 cricket::SessionDescription* desc,
1823 SdpParseError* error) {
1824 std::string line;
1825
deadbeefc80741f2015-10-22 13:14:45 -07001826 desc->set_msid_supported(false);
1827
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001828 // RFC 4566
1829 // v= (protocol version)
1830 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1831 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1832 std::string(), error);
1833 }
1834 // RFC 4566
1835 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1836 // <unicast-address>
1837 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1838 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1839 std::string(), error);
1840 }
1841 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001842 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001843 kSdpDelimiterSpace, &fields);
1844 const size_t expected_fields = 6;
1845 if (fields.size() != expected_fields) {
1846 return ParseFailedExpectFieldNum(line, expected_fields, error);
1847 }
1848 *session_id = fields[1];
1849 *session_version = fields[2];
1850
1851 // RFC 4566
1852 // s= (session name)
1853 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1854 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1855 std::string(), error);
1856 }
1857
1858 // Optional lines
1859 // Those are the optional lines, so shouldn't return false if not present.
1860 // RFC 4566
1861 // i=* (session information)
1862 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1863
1864 // RFC 4566
1865 // u=* (URI of description)
1866 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1867
1868 // RFC 4566
1869 // e=* (email address)
1870 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1871
1872 // RFC 4566
1873 // p=* (phone number)
1874 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1875
1876 // RFC 4566
1877 // c=* (connection information -- not required if included in
1878 // all media)
1879 GetLineWithType(message, pos, &line, kLineTypeConnection);
1880
1881 // RFC 4566
1882 // b=* (zero or more bandwidth information lines)
1883 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1884 // By pass zero or more b lines.
1885 }
1886
1887 // RFC 4566
1888 // One or more time descriptions ("t=" and "r=" lines; see below)
1889 // t= (time the session is active)
1890 // r=* (zero or more repeat times)
1891 // Ensure there's at least one time description
1892 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1893 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1894 error);
1895 }
1896
1897 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1898 // By pass zero or more r lines.
1899 }
1900
1901 // Go through the rest of the time descriptions
1902 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1903 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1904 // By pass zero or more r lines.
1905 }
1906 }
1907
1908 // RFC 4566
1909 // z=* (time zone adjustments)
1910 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1911
1912 // RFC 4566
1913 // k=* (encryption key)
1914 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1915
1916 // RFC 4566
1917 // a=* (zero or more session attribute lines)
1918 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1919 if (HasAttribute(line, kAttributeGroup)) {
1920 if (!ParseGroupAttribute(line, desc, error)) {
1921 return false;
1922 }
1923 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1924 if (!GetValue(line, kAttributeIceUfrag,
1925 &(session_td->ice_ufrag), error)) {
1926 return false;
1927 }
1928 } else if (HasAttribute(line, kAttributeIcePwd)) {
1929 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1930 return false;
1931 }
1932 } else if (HasAttribute(line, kAttributeIceLite)) {
1933 session_td->ice_mode = cricket::ICEMODE_LITE;
1934 } else if (HasAttribute(line, kAttributeIceOption)) {
1935 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1936 return false;
1937 }
1938 } else if (HasAttribute(line, kAttributeFingerprint)) {
1939 if (session_td->identity_fingerprint.get()) {
1940 return ParseFailed(
1941 line,
1942 "Can't have multiple fingerprint attributes at the same level.",
1943 error);
1944 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001945 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001946 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1947 return false;
1948 }
1949 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001950 } else if (HasAttribute(line, kAttributeSetup)) {
1951 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1952 return false;
1953 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001954 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1955 std::string semantics;
1956 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1957 return false;
1958 }
deadbeefc80741f2015-10-22 13:14:45 -07001959 desc->set_msid_supported(
1960 CaseInsensitiveFind(semantics, kMediaStreamSemantic));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001961 } else if (HasAttribute(line, kAttributeExtmap)) {
1962 RtpHeaderExtension extmap;
1963 if (!ParseExtmap(line, &extmap, error)) {
1964 return false;
1965 }
1966 session_extmaps->push_back(extmap);
1967 }
1968 }
1969
1970 return true;
1971}
1972
1973bool ParseGroupAttribute(const std::string& line,
1974 cricket::SessionDescription* desc,
1975 SdpParseError* error) {
1976 ASSERT(desc != NULL);
1977
1978 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1979 // a=group:BUNDLE video voice
1980 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001981 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001982 kSdpDelimiterSpace, &fields);
1983 std::string semantics;
1984 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1985 return false;
1986 }
1987 cricket::ContentGroup group(semantics);
1988 for (size_t i = 1; i < fields.size(); ++i) {
1989 group.AddContentName(fields[i]);
1990 }
1991 desc->AddGroup(group);
1992 return true;
1993}
1994
1995static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001996 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001997 SdpParseError* error) {
1998 if (!IsLineType(line, kLineTypeAttributes) ||
1999 !HasAttribute(line, kAttributeFingerprint)) {
2000 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
2001 kAttributeFingerprint, error);
2002 }
2003
2004 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002005 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006 kSdpDelimiterSpace, &fields);
2007 const size_t expected_fields = 2;
2008 if (fields.size() != expected_fields) {
2009 return ParseFailedExpectFieldNum(line, expected_fields, error);
2010 }
2011
2012 // The first field here is "fingerprint:<hash>.
2013 std::string algorithm;
2014 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2015 return false;
2016 }
2017
2018 // Downcase the algorithm. Note that we don't need to downcase the
2019 // fingerprint because hex_decode can handle upper-case.
2020 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2021 ::tolower);
2022
2023 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002024 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002025 algorithm, fields[1]);
2026 if (!*fingerprint) {
2027 return ParseFailed(line,
2028 "Failed to create fingerprint from the digest.",
2029 error);
2030 }
2031
2032 return true;
2033}
2034
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002035static bool ParseDtlsSetup(const std::string& line,
2036 cricket::ConnectionRole* role,
2037 SdpParseError* error) {
2038 // setup-attr = "a=setup:" role
2039 // role = "active" / "passive" / "actpass" / "holdconn"
2040 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002041 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002042 const size_t expected_fields = 2;
2043 if (fields.size() != expected_fields) {
2044 return ParseFailedExpectFieldNum(line, expected_fields, error);
2045 }
2046 std::string role_str = fields[1];
2047 if (!cricket::StringToConnectionRole(role_str, role)) {
2048 return ParseFailed(line, "Invalid attribute value.", error);
2049 }
2050 return true;
2051}
2052
deadbeef9d3584c2016-02-16 17:54:10 -08002053static bool ParseMsidAttribute(const std::string& line,
2054 std::string* stream_id,
2055 std::string* track_id,
2056 SdpParseError* error) {
2057 // draft-ietf-mmusic-msid-11
2058 // a=msid:<stream id> <track id>
2059 // msid-value = msid-id [ SP msid-appdata ]
2060 // msid-id = 1*64token-char ; see RFC 4566
2061 // msid-appdata = 1*64token-char ; see RFC 4566
2062 std::string field1;
2063 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2064 &field1, track_id)) {
2065 const size_t expected_fields = 2;
2066 return ParseFailedExpectFieldNum(line, expected_fields, error);
2067 }
2068
2069 // msid:<msid-id>
2070 if (!GetValue(field1, kAttributeMsid, stream_id, error)) {
2071 return false;
2072 }
2073 return true;
2074}
2075
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002076// RFC 3551
2077// PT encoding media type clock rate channels
2078// name (Hz)
2079// 0 PCMU A 8,000 1
2080// 1 reserved A
2081// 2 reserved A
2082// 3 GSM A 8,000 1
2083// 4 G723 A 8,000 1
2084// 5 DVI4 A 8,000 1
2085// 6 DVI4 A 16,000 1
2086// 7 LPC A 8,000 1
2087// 8 PCMA A 8,000 1
2088// 9 G722 A 8,000 1
2089// 10 L16 A 44,100 2
2090// 11 L16 A 44,100 1
2091// 12 QCELP A 8,000 1
2092// 13 CN A 8,000 1
2093// 14 MPA A 90,000 (see text)
2094// 15 G728 A 8,000 1
2095// 16 DVI4 A 11,025 1
2096// 17 DVI4 A 22,050 1
2097// 18 G729 A 8,000 1
2098struct StaticPayloadAudioCodec {
2099 const char* name;
2100 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002101 size_t channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002102};
2103static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2104 { "PCMU", 8000, 1 },
2105 { "reserved", 0, 0 },
2106 { "reserved", 0, 0 },
2107 { "GSM", 8000, 1 },
2108 { "G723", 8000, 1 },
2109 { "DVI4", 8000, 1 },
2110 { "DVI4", 16000, 1 },
2111 { "LPC", 8000, 1 },
2112 { "PCMA", 8000, 1 },
2113 { "G722", 8000, 1 },
2114 { "L16", 44100, 2 },
2115 { "L16", 44100, 1 },
2116 { "QCELP", 8000, 1 },
2117 { "CN", 8000, 1 },
2118 { "MPA", 90000, 1 },
2119 { "G728", 8000, 1 },
2120 { "DVI4", 11025, 1 },
2121 { "DVI4", 22050, 1 },
2122 { "G729", 8000, 1 },
2123};
2124
2125void MaybeCreateStaticPayloadAudioCodecs(
2126 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2127 if (!media_desc) {
2128 return;
2129 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002130 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002131 std::vector<int>::const_iterator it = fmts.begin();
2132 bool add_new_codec = false;
2133 for (; it != fmts.end(); ++it) {
2134 int payload_type = *it;
2135 if (!media_desc->HasCodec(payload_type) &&
2136 payload_type >= 0 &&
tfarina5237aaf2015-11-10 23:44:30 -08002137 payload_type < arraysize(kStaticPayloadAudioCodecs)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002138 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2139 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002140 size_t channels = kStaticPayloadAudioCodecs[payload_type].channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002141 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2142 clock_rate, 0, channels,
2143 preference));
2144 add_new_codec = true;
2145 }
2146 --preference;
2147 }
2148 if (add_new_codec) {
2149 media_desc->SortCodecs();
2150 }
2151}
2152
2153template <class C>
2154static C* ParseContentDescription(const std::string& message,
2155 const MediaType media_type,
2156 int mline_index,
2157 const std::string& protocol,
2158 const std::vector<int>& codec_preference,
2159 size_t* pos,
2160 std::string* content_name,
2161 TransportDescription* transport,
2162 std::vector<JsepIceCandidate*>* candidates,
2163 webrtc::SdpParseError* error) {
2164 C* media_desc = new C();
2165 switch (media_type) {
2166 case cricket::MEDIA_TYPE_AUDIO:
2167 *content_name = cricket::CN_AUDIO;
2168 break;
2169 case cricket::MEDIA_TYPE_VIDEO:
2170 *content_name = cricket::CN_VIDEO;
2171 break;
2172 case cricket::MEDIA_TYPE_DATA:
2173 *content_name = cricket::CN_DATA;
2174 break;
2175 default:
2176 ASSERT(false);
2177 break;
2178 }
2179 if (!ParseContent(message, media_type, mline_index, protocol,
2180 codec_preference, pos, content_name,
2181 media_desc, transport, candidates, error)) {
2182 delete media_desc;
2183 return NULL;
2184 }
2185 // Sort the codecs according to the m-line fmt list.
2186 media_desc->SortCodecs();
2187 return media_desc;
2188}
2189
2190bool ParseMediaDescription(const std::string& message,
2191 const TransportDescription& session_td,
2192 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002193 size_t* pos,
2194 cricket::SessionDescription* desc,
2195 std::vector<JsepIceCandidate*>* candidates,
2196 SdpParseError* error) {
2197 ASSERT(desc != NULL);
2198 std::string line;
2199 int mline_index = -1;
2200
2201 // Zero or more media descriptions
2202 // RFC 4566
2203 // m=<media> <port> <proto> <fmt>
2204 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2205 ++mline_index;
2206
2207 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002208 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209 kSdpDelimiterSpace, &fields);
2210 const size_t expected_min_fields = 4;
2211 if (fields.size() < expected_min_fields) {
2212 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2213 }
2214 bool rejected = false;
2215 // RFC 3264
2216 // To reject an offered stream, the port number in the corresponding stream
2217 // in the answer MUST be set to zero.
2218 if (fields[1] == kMediaPortRejected) {
2219 rejected = true;
2220 }
2221
2222 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223
2224 // <fmt>
2225 std::vector<int> codec_preference;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002226 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002227 for (size_t j = 3 ; j < fields.size(); ++j) {
2228 // TODO(wu): Remove when below bug is fixed.
2229 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002230 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002231 continue;
2232 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002233
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002234 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002235 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002236 return false;
2237 }
2238 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002239 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002240 }
2241
2242 // Make a temporary TransportDescription based on |session_td|.
2243 // Some of this gets overwritten by ParseContent.
deadbeef46eed762016-01-28 13:24:37 -08002244 TransportDescription transport(
2245 session_td.transport_options, session_td.ice_ufrag, session_td.ice_pwd,
2246 session_td.ice_mode, session_td.connection_role,
2247 session_td.identity_fingerprint.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002248
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002249 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002250 std::string content_name;
2251 if (HasAttribute(line, kMediaTypeVideo)) {
2252 content.reset(ParseContentDescription<VideoContentDescription>(
2253 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2254 codec_preference, pos, &content_name,
2255 &transport, candidates, error));
2256 } else if (HasAttribute(line, kMediaTypeAudio)) {
2257 content.reset(ParseContentDescription<AudioContentDescription>(
2258 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2259 codec_preference, pos, &content_name,
2260 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002261 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002262 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002263 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002264 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2265 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002266 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002267 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002268
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002269 int p;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002270 if (data_desc && IsDtlsSctp(protocol) && rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002271 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002272 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002273 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002274 } else {
2275 LOG(LS_WARNING) << "Unsupported media type: " << line;
2276 continue;
2277 }
2278 if (!content.get()) {
2279 // ParseContentDescription returns NULL if failed.
2280 return false;
2281 }
2282
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002283 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002284 // Set the extmap.
2285 if (!session_extmaps.empty() &&
2286 !content->rtp_header_extensions().empty()) {
2287 return ParseFailed("",
2288 "The a=extmap MUST be either all session level or "
2289 "all media level.",
2290 error);
2291 }
2292 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2293 content->AddRtpHeaderExtension(session_extmaps[i]);
2294 }
2295 }
2296 content->set_protocol(protocol);
2297 desc->AddContent(content_name,
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002298 IsDtlsSctp(protocol) ? cricket::NS_JINGLE_DRAFT_SCTP :
2299 cricket::NS_JINGLE_RTP,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 rejected,
2301 content.release());
2302 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2303 TransportInfo transport_info(content_name, transport);
2304
2305 if (!desc->AddTransportInfo(transport_info)) {
2306 std::ostringstream description;
2307 description << "Failed to AddTransportInfo with content name: "
2308 << content_name;
2309 return ParseFailed("", description.str(), error);
2310 }
2311 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002312
2313 size_t end_of_message = message.size();
2314 if (mline_index == -1 && *pos != end_of_message) {
2315 ParseFailed(message, *pos, "Expects m line.", error);
2316 return false;
2317 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002318 return true;
2319}
2320
2321bool VerifyCodec(const cricket::Codec& codec) {
2322 // Codec has not been populated correctly unless the name has been set. This
2323 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2324 // have a corresponding "rtpmap" line.
2325 cricket::Codec default_codec;
2326 return default_codec.name != codec.name;
2327}
2328
2329bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2330 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2331 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2332 iter != codecs.end(); ++iter) {
2333 if (!VerifyCodec(*iter)) {
2334 return false;
2335 }
2336 }
2337 return true;
2338}
2339
2340bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2341 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2342 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2343 iter != codecs.end(); ++iter) {
2344 if (!VerifyCodec(*iter)) {
2345 return false;
2346 }
2347 }
2348 return true;
2349}
2350
2351void AddParameters(const cricket::CodecParameterMap& parameters,
2352 cricket::Codec* codec) {
2353 for (cricket::CodecParameterMap::const_iterator iter =
2354 parameters.begin(); iter != parameters.end(); ++iter) {
2355 codec->SetParam(iter->first, iter->second);
2356 }
2357}
2358
2359void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2360 cricket::Codec* codec) {
2361 codec->AddFeedbackParam(feedback_param);
2362}
2363
2364void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2365 cricket::Codec* codec) {
2366 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2367 feedback_params.params().begin();
2368 iter != feedback_params.params().end(); ++iter) {
2369 codec->AddFeedbackParam(*iter);
2370 }
2371}
2372
2373// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002374// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002375// with that payload type.
2376template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002377T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2378 T ret_val;
2379 if (!FindCodecById(codecs, payload_type, &ret_val)) {
2380 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002381 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002382 return ret_val;
2383}
2384
2385// Updates or creates a new codec entry in the audio description.
2386template <class T, class U>
2387void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2388 T* desc = static_cast<T*>(content_desc);
2389 std::vector<U> codecs = desc->codecs();
2390 bool found = false;
2391
2392 typename std::vector<U>::iterator iter;
2393 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2394 if (iter->id == codec.id) {
2395 *iter = codec;
2396 found = true;
2397 break;
2398 }
2399 }
2400 if (!found) {
2401 desc->AddCodec(codec);
2402 return;
2403 }
2404 desc->set_codecs(codecs);
2405}
2406
2407// Adds or updates existing codec corresponding to |payload_type| according
2408// to |parameters|.
2409template <class T, class U>
2410void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2411 const cricket::CodecParameterMap& parameters) {
2412 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002413 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2414 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002415 AddParameters(parameters, &new_codec);
2416 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2417}
2418
2419// Adds or updates existing codec corresponding to |payload_type| according
2420// to |feedback_param|.
2421template <class T, class U>
2422void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2423 const cricket::FeedbackParam& feedback_param) {
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 AddFeedbackParameter(feedback_param, &new_codec);
2428 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2429}
2430
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002431template <class T>
2432bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2433 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002434 if (iter->id == kWildcardPayloadType) {
2435 *wildcard_codec = *iter;
2436 codecs->erase(iter);
2437 return true;
2438 }
2439 }
2440 return false;
2441}
2442
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002443template<class T>
2444void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2445 auto codecs = desc->codecs();
2446 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002447 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2448 return;
2449 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002450 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002451 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2452 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002453 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002454}
2455
2456void AddAudioAttribute(const std::string& name, const std::string& value,
2457 AudioContentDescription* audio_desc) {
2458 if (value.empty()) {
2459 return;
2460 }
2461 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2462 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2463 iter != codecs.end(); ++iter) {
2464 iter->params[name] = value;
2465 }
2466 audio_desc->set_codecs(codecs);
2467}
2468
2469bool ParseContent(const std::string& message,
2470 const MediaType media_type,
2471 int mline_index,
2472 const std::string& protocol,
2473 const std::vector<int>& codec_preference,
2474 size_t* pos,
2475 std::string* content_name,
2476 MediaContentDescription* media_desc,
2477 TransportDescription* transport,
2478 std::vector<JsepIceCandidate*>* candidates,
2479 SdpParseError* error) {
2480 ASSERT(media_desc != NULL);
2481 ASSERT(content_name != NULL);
2482 ASSERT(transport != NULL);
2483
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002484 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2485 MaybeCreateStaticPayloadAudioCodecs(
2486 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2487 }
2488
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002489 // The media level "ice-ufrag" and "ice-pwd".
2490 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2491 Candidates candidates_orig;
2492 std::string line;
2493 std::string mline_id;
2494 // Tracks created out of the ssrc attributes.
2495 StreamParamsVec tracks;
2496 SsrcInfoVec ssrc_infos;
2497 SsrcGroupVec ssrc_groups;
2498 std::string maxptime_as_string;
2499 std::string ptime_as_string;
deadbeef9d3584c2016-02-16 17:54:10 -08002500 std::string stream_id;
2501 std::string track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002502
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002503 // Loop until the next m line
2504 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2505 if (!GetLine(message, pos, &line)) {
2506 if (*pos >= message.size()) {
2507 break; // Done parsing
2508 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002509 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002510 }
2511 }
2512
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002513 // RFC 4566
2514 // b=* (zero or more bandwidth information lines)
2515 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2516 std::string bandwidth;
2517 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2518 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2519 return false;
2520 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002521 int b = 0;
2522 if (!GetValueFromString(line, bandwidth, &b, error)) {
2523 return false;
2524 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002525 // We should never use more than the default bandwidth for RTP-based
2526 // data channels. Don't allow SDP to set the bandwidth, because
2527 // that would give JS the opportunity to "break the Internet".
2528 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2529 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2530 b > cricket::kDataMaxBandwidth / 1000) {
2531 std::ostringstream description;
2532 description << "RTP-based data channels may not send more than "
2533 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2534 return ParseFailed(line, description.str(), error);
2535 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002536 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002537 }
2538 }
2539 continue;
2540 }
2541
2542 if (!IsLineType(line, kLineTypeAttributes)) {
2543 // TODO: Handle other lines if needed.
2544 LOG(LS_INFO) << "Ignored line: " << line;
2545 continue;
2546 }
2547
2548 // Handle attributes common to SCTP and RTP.
2549 if (HasAttribute(line, kAttributeMid)) {
2550 // RFC 3388
2551 // mid-attribute = "a=mid:" identification-tag
2552 // identification-tag = token
2553 // Use the mid identification-tag as the content name.
2554 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2555 return false;
2556 }
2557 *content_name = mline_id;
2558 } else if (HasAttribute(line, kAttributeCandidate)) {
2559 Candidate candidate;
2560 if (!ParseCandidate(line, &candidate, error, false)) {
2561 return false;
2562 }
2563 candidates_orig.push_back(candidate);
2564 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2565 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2566 return false;
2567 }
2568 } else if (HasAttribute(line, kAttributeIcePwd)) {
2569 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2570 return false;
2571 }
2572 } else if (HasAttribute(line, kAttributeIceOption)) {
2573 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2574 return false;
2575 }
2576 } else if (HasAttribute(line, kAttributeFmtp)) {
2577 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2578 return false;
2579 }
2580 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002581 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002582
2583 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2584 return false;
2585 }
2586 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002587 } else if (HasAttribute(line, kAttributeSetup)) {
2588 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2589 return false;
2590 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002591 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002592 int sctp_port;
2593 if (!ParseSctpPort(line, &sctp_port, error)) {
2594 return false;
2595 }
2596 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2597 sctp_port)) {
2598 return false;
2599 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002600 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002601 //
2602 // RTP specific attrubtes
2603 //
2604 if (HasAttribute(line, kAttributeRtcpMux)) {
2605 media_desc->set_rtcp_mux(true);
deadbeef13871492015-12-09 12:37:51 -08002606 } else if (HasAttribute(line, kAttributeRtcpReducedSize)) {
2607 media_desc->set_rtcp_reduced_size(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002608 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2609 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2610 return false;
2611 }
2612 } else if (HasAttribute(line, kAttributeSsrc)) {
2613 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2614 return false;
2615 }
2616 } else if (HasAttribute(line, kAttributeCrypto)) {
2617 if (!ParseCryptoAttribute(line, media_desc, error)) {
2618 return false;
2619 }
2620 } else if (HasAttribute(line, kAttributeRtpmap)) {
2621 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2622 media_desc, error)) {
2623 return false;
2624 }
2625 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2626 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2627 return false;
2628 }
2629 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2630 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2631 return false;
2632 }
2633 } else if (HasAttribute(line, kCodecParamPTime)) {
2634 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2635 return false;
2636 }
2637 } else if (HasAttribute(line, kAttributeSendOnly)) {
2638 media_desc->set_direction(cricket::MD_SENDONLY);
2639 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2640 media_desc->set_direction(cricket::MD_RECVONLY);
2641 } else if (HasAttribute(line, kAttributeInactive)) {
2642 media_desc->set_direction(cricket::MD_INACTIVE);
2643 } else if (HasAttribute(line, kAttributeSendRecv)) {
2644 media_desc->set_direction(cricket::MD_SENDRECV);
2645 } else if (HasAttribute(line, kAttributeExtmap)) {
2646 RtpHeaderExtension extmap;
2647 if (!ParseExtmap(line, &extmap, error)) {
2648 return false;
2649 }
2650 media_desc->AddRtpHeaderExtension(extmap);
2651 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2652 // Experimental attribute. Conference mode activates more aggressive
2653 // AEC and NS settings.
2654 // TODO: expose API to set these directly.
2655 std::string flag_value;
2656 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2657 return false;
2658 }
2659 if (flag_value.compare(kValueConference) == 0)
2660 media_desc->set_conference_mode(true);
deadbeef9d3584c2016-02-16 17:54:10 -08002661 } else if (HasAttribute(line, kAttributeMsid)) {
2662 if (!ParseMsidAttribute(line, &stream_id, &track_id, error)) {
2663 return false;
2664 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002665 }
2666 } else {
2667 // Only parse lines that we are interested of.
2668 LOG(LS_INFO) << "Ignored line: " << line;
2669 continue;
2670 }
2671 }
2672
deadbeef9d3584c2016-02-16 17:54:10 -08002673 // Found an msid attribute.
2674 // Setting the stream_id/track_id will cause only one StreamParams
2675 // to be created in CreateTracksFromSsrcInfos, containing all the SSRCs from
2676 // the m= section.
2677 if (!stream_id.empty() && !track_id.empty()) {
2678 for (SsrcInfo& ssrc_info : ssrc_infos) {
2679 ssrc_info.stream_id = stream_id;
2680 ssrc_info.track_id = track_id;
2681 }
2682 }
2683
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002684 // Create tracks from the |ssrc_infos|.
2685 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2686
2687 // Add the ssrc group to the track.
2688 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2689 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2690 if (ssrc_group->ssrcs.empty()) {
2691 continue;
2692 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002693 uint32_t ssrc = ssrc_group->ssrcs.front();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002694 for (StreamParamsVec::iterator track = tracks.begin();
2695 track != tracks.end(); ++track) {
2696 if (track->has_ssrc(ssrc)) {
2697 track->ssrc_groups.push_back(*ssrc_group);
2698 }
2699 }
2700 }
2701
2702 // Add the new tracks to the |media_desc|.
deadbeef9d3584c2016-02-16 17:54:10 -08002703 for (StreamParams& track : tracks) {
2704 media_desc->AddStream(track);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002705 }
2706
2707 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2708 AudioContentDescription* audio_desc =
2709 static_cast<AudioContentDescription*>(media_desc);
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002710 UpdateFromWildcardCodecs(audio_desc);
2711
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002712 // Verify audio codec ensures that no audio codec has been populated with
2713 // only fmtp.
2714 if (!VerifyAudioCodecs(audio_desc)) {
2715 return ParseFailed("Failed to parse audio codecs correctly.", error);
2716 }
2717 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2718 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2719 }
2720
2721 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002722 VideoContentDescription* video_desc =
2723 static_cast<VideoContentDescription*>(media_desc);
2724 UpdateFromWildcardCodecs(video_desc);
2725 // Verify video codec ensures that no video codec has been populated with
2726 // only rtcp-fb.
2727 if (!VerifyVideoCodecs(video_desc)) {
2728 return ParseFailed("Failed to parse video codecs correctly.", error);
2729 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002730 }
2731
2732 // RFC 5245
2733 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2734 for (Candidates::iterator it = candidates_orig.begin();
2735 it != candidates_orig.end(); ++it) {
honghaiza54a0802015-12-16 18:37:23 -08002736 ASSERT((*it).username().empty() ||
2737 (*it).username() == transport->ice_ufrag);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002738 (*it).set_username(transport->ice_ufrag);
2739 ASSERT((*it).password().empty());
2740 (*it).set_password(transport->ice_pwd);
2741 candidates->push_back(
2742 new JsepIceCandidate(mline_id, mline_index, *it));
2743 }
2744 return true;
2745}
2746
2747bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2748 SdpParseError* error) {
2749 ASSERT(ssrc_infos != NULL);
2750 // RFC 5576
2751 // a=ssrc:<ssrc-id> <attribute>
2752 // a=ssrc:<ssrc-id> <attribute>:<value>
2753 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07002754 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2755 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002756 const size_t expected_fields = 2;
2757 return ParseFailedExpectFieldNum(line, expected_fields, error);
2758 }
2759
2760 // ssrc:<ssrc-id>
2761 std::string ssrc_id_s;
2762 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2763 return false;
2764 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002765 uint32_t ssrc_id = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002766 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2767 return false;
2768 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002769
2770 std::string attribute;
2771 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07002772 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002773 std::ostringstream description;
2774 description << "Failed to get the ssrc attribute value from " << field2
2775 << ". Expected format <attribute>:<value>.";
2776 return ParseFailed(line, description.str(), error);
2777 }
2778
2779 // Check if there's already an item for this |ssrc_id|. Create a new one if
2780 // there isn't.
2781 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2782 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2783 if (ssrc_info->ssrc_id == ssrc_id) {
2784 break;
2785 }
2786 }
2787 if (ssrc_info == ssrc_infos->end()) {
2788 SsrcInfo info;
2789 info.ssrc_id = ssrc_id;
2790 ssrc_infos->push_back(info);
2791 ssrc_info = ssrc_infos->end() - 1;
2792 }
2793
2794 // Store the info to the |ssrc_info|.
2795 if (attribute == kSsrcAttributeCname) {
2796 // RFC 5576
2797 // cname:<value>
2798 ssrc_info->cname = value;
2799 } else if (attribute == kSsrcAttributeMsid) {
2800 // draft-alvestrand-mmusic-msid-00
2801 // "msid:" identifier [ " " appdata ]
2802 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002803 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002804 if (fields.size() < 1 || fields.size() > 2) {
2805 return ParseFailed(line,
2806 "Expected format \"msid:<identifier>[ <appdata>]\".",
2807 error);
2808 }
deadbeef9d3584c2016-02-16 17:54:10 -08002809 ssrc_info->stream_id = fields[0];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002810 if (fields.size() == 2) {
deadbeef9d3584c2016-02-16 17:54:10 -08002811 ssrc_info->track_id = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002812 }
2813 } else if (attribute == kSsrcAttributeMslabel) {
2814 // draft-alvestrand-rtcweb-mid-01
2815 // mslabel:<value>
2816 ssrc_info->mslabel = value;
2817 } else if (attribute == kSSrcAttributeLabel) {
2818 // The label isn't defined.
2819 // label:<value>
2820 ssrc_info->label = value;
2821 }
2822 return true;
2823}
2824
2825bool ParseSsrcGroupAttribute(const std::string& line,
2826 SsrcGroupVec* ssrc_groups,
2827 SdpParseError* error) {
2828 ASSERT(ssrc_groups != NULL);
2829 // RFC 5576
2830 // a=ssrc-group:<semantics> <ssrc-id> ...
2831 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002832 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002833 kSdpDelimiterSpace, &fields);
2834 const size_t expected_min_fields = 2;
2835 if (fields.size() < expected_min_fields) {
2836 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2837 }
2838 std::string semantics;
2839 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2840 return false;
2841 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002842 std::vector<uint32_t> ssrcs;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002843 for (size_t i = 1; i < fields.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02002844 uint32_t ssrc = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002845 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2846 return false;
2847 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002848 ssrcs.push_back(ssrc);
2849 }
2850 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2851 return true;
2852}
2853
2854bool ParseCryptoAttribute(const std::string& line,
2855 MediaContentDescription* media_desc,
2856 SdpParseError* error) {
2857 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002858 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002859 kSdpDelimiterSpace, &fields);
2860 // RFC 4568
2861 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2862 const size_t expected_min_fields = 3;
2863 if (fields.size() < expected_min_fields) {
2864 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2865 }
2866 std::string tag_value;
2867 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2868 return false;
2869 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002870 int tag = 0;
2871 if (!GetValueFromString(line, tag_value, &tag, error)) {
2872 return false;
2873 }
jbauch083b73f2015-07-16 02:46:32 -07002874 const std::string& crypto_suite = fields[1];
2875 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002876 std::string session_params;
2877 if (fields.size() > 3) {
2878 session_params = fields[3];
2879 }
2880 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2881 session_params));
2882 return true;
2883}
2884
2885// Updates or creates a new codec entry in the audio description with according
2886// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2887void UpdateCodec(int payload_type, const std::string& name, int clockrate,
Peter Kasting69558702016-01-12 16:26:35 -08002888 int bitrate, size_t channels, int preference,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002889 AudioContentDescription* audio_desc) {
2890 // Codec may already be populated with (only) optional parameters
2891 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002892 cricket::AudioCodec codec =
2893 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002894 codec.name = name;
2895 codec.clockrate = clockrate;
2896 codec.bitrate = bitrate;
2897 codec.channels = channels;
2898 codec.preference = preference;
2899 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2900 codec);
2901}
2902
2903// Updates or creates a new codec entry in the video description according to
2904// |name|, |width|, |height|, |framerate| and |preference|.
2905void UpdateCodec(int payload_type, const std::string& name, int width,
2906 int height, int framerate, int preference,
2907 VideoContentDescription* video_desc) {
2908 // Codec may already be populated with (only) optional parameters
2909 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002910 cricket::VideoCodec codec =
2911 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002912 codec.name = name;
2913 codec.width = width;
2914 codec.height = height;
2915 codec.framerate = framerate;
2916 codec.preference = preference;
2917 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2918 codec);
2919}
2920
2921bool ParseRtpmapAttribute(const std::string& line,
2922 const MediaType media_type,
2923 const std::vector<int>& codec_preference,
2924 MediaContentDescription* media_desc,
2925 SdpParseError* error) {
2926 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002927 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002928 kSdpDelimiterSpace, &fields);
2929 // RFC 4566
2930 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2931 const size_t expected_min_fields = 2;
2932 if (fields.size() < expected_min_fields) {
2933 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2934 }
2935 std::string payload_type_value;
2936 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2937 return false;
2938 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002939 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002940 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
2941 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002942 return false;
2943 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002944
2945 // Set the preference order depending on the order of the pl type in the
2946 // <fmt> of the m-line.
2947 const int preference = codec_preference.end() -
2948 std::find(codec_preference.begin(), codec_preference.end(),
2949 payload_type);
2950 if (preference == 0) {
2951 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2952 << "<fmt> of the m-line: " << line;
2953 return true;
2954 }
jbauch083b73f2015-07-16 02:46:32 -07002955 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002956 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002957 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002958 // <encoding name>/<clock rate>[/<encodingparameters>]
2959 // 2 mandatory fields
2960 if (codec_params.size() < 2 || codec_params.size() > 3) {
2961 return ParseFailed(line,
2962 "Expected format \"<encoding name>/<clock rate>"
2963 "[/<encodingparameters>]\".",
2964 error);
2965 }
jbauch083b73f2015-07-16 02:46:32 -07002966 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002967 int clock_rate = 0;
2968 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2969 return false;
2970 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002971 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2972 VideoContentDescription* video_desc =
2973 static_cast<VideoContentDescription*>(media_desc);
2974 // TODO: We will send resolution in SDP. For now use
2975 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2976 UpdateCodec(payload_type, encoding_name,
2977 JsepSessionDescription::kMaxVideoCodecWidth,
2978 JsepSessionDescription::kMaxVideoCodecHeight,
2979 JsepSessionDescription::kDefaultVideoCodecFramerate,
2980 preference, video_desc);
2981 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2982 // RFC 4566
2983 // For audio streams, <encoding parameters> indicates the number
2984 // of audio channels. This parameter is OPTIONAL and may be
2985 // omitted if the number of channels is one, provided that no
2986 // additional parameters are needed.
Peter Kasting69558702016-01-12 16:26:35 -08002987 size_t channels = 1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002988 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002989 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2990 return false;
2991 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002992 }
2993 int bitrate = 0;
2994 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2995 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2996 // The bandwidth adaptation doesn't always work well, so this code
2997 // sets a fixed target bitrate instead.
2998 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2999 if (clock_rate <= 16000) {
3000 bitrate = kIsacWbDefaultRate;
3001 } else {
3002 bitrate = kIsacSwbDefaultRate;
3003 }
3004 }
3005 AudioContentDescription* audio_desc =
3006 static_cast<AudioContentDescription*>(media_desc);
3007 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
3008 preference, audio_desc);
3009 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
3010 DataContentDescription* data_desc =
3011 static_cast<DataContentDescription*>(media_desc);
3012 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
3013 preference));
3014 }
3015 return true;
3016}
3017
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003018bool ParseFmtpParam(const std::string& line, std::string* parameter,
3019 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003020 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003021 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
3022 return false;
3023 }
3024 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003025 return true;
3026}
3027
3028bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
3029 MediaContentDescription* media_desc,
3030 SdpParseError* error) {
3031 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3032 media_type != cricket::MEDIA_TYPE_VIDEO) {
3033 return true;
3034 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003035
3036 std::string line_payload;
3037 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003038
3039 // RFC 5576
3040 // a=fmtp:<format> <format specific parameters>
3041 // At least two fields, whereas the second one is any of the optional
3042 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07003043 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
3044 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003045 ParseFailedExpectMinFieldNum(line, 2, error);
3046 return false;
3047 }
3048
Donald Curtis0e07f922015-05-15 09:21:23 -07003049 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003050 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07003051 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003052 return false;
3053 }
3054
Donald Curtis0e07f922015-05-15 09:21:23 -07003055 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07003056 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3057 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003058 return false;
3059 }
3060
3061 // Parse out format specific parameters.
3062 std::vector<std::string> fields;
3063 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
3064
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003065 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07003066 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003067 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003068 // Only fmtps with equals are currently supported. Other fmtp types
3069 // should be ignored. Unknown fmtps do not constitute an error.
3070 continue;
3071 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003072
3073 std::string name;
3074 std::string value;
3075 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003076 return false;
3077 }
3078 codec_params[name] = value;
3079 }
3080
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003081 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3082 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003083 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003084 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3085 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003086 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003087 }
3088 return true;
3089}
3090
3091bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3092 MediaContentDescription* media_desc,
3093 SdpParseError* error) {
3094 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3095 media_type != cricket::MEDIA_TYPE_VIDEO) {
3096 return true;
3097 }
3098 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003099 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003100 if (rtcp_fb_fields.size() < 2) {
3101 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3102 }
3103 std::string payload_type_string;
3104 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3105 error)) {
3106 return false;
3107 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003108 int payload_type = kWildcardPayloadType;
3109 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003110 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3111 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003112 return false;
3113 }
3114 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003115 std::string id = rtcp_fb_fields[1];
3116 std::string param = "";
3117 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3118 iter != rtcp_fb_fields.end(); ++iter) {
3119 param.append(*iter);
3120 }
3121 const cricket::FeedbackParam feedback_param(id, param);
3122
3123 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003124 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3125 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003126 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003127 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3128 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003129 }
3130 return true;
3131}
3132
3133} // namespace webrtc