blob: 4a296d9ce2e28a274377e3ca79e727f45c5b6e91 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2011 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Henrik Kjellander15583c12016-02-10 10:53:12 +010011#include "webrtc/api/webrtcsdp.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
kjellandera96e2d72016-02-04 23:52:28 -080013#include <ctype.h>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000014#include <limits.h>
15#include <stdio.h>
16#include <algorithm>
17#include <string>
18#include <vector>
19
Henrik Kjellander15583c12016-02-10 10:53:12 +010020#include "webrtc/api/jsepicecandidate.h"
21#include "webrtc/api/jsepsessiondescription.h"
tfarina5237aaf2015-11-10 23:44:30 -080022#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000023#include "webrtc/base/common.h"
24#include "webrtc/base/logging.h"
25#include "webrtc/base/messagedigest.h"
26#include "webrtc/base/stringutils.h"
kjellandera96e2d72016-02-04 23:52:28 -080027#include "webrtc/media/base/codec.h"
kjellandera96e2d72016-02-04 23:52:28 -080028#include "webrtc/media/base/cryptoparams.h"
kjellanderf4752772016-03-02 05:42:30 -080029#include "webrtc/media/base/mediaconstants.h"
kjellandera96e2d72016-02-04 23:52:28 -080030#include "webrtc/media/base/rtputils.h"
31#include "webrtc/media/sctp/sctpdataengine.h"
32#include "webrtc/p2p/base/candidate.h"
kjellanderf4752772016-03-02 05:42:30 -080033#include "webrtc/p2p/base/p2pconstants.h"
kjellandera96e2d72016-02-04 23:52:28 -080034#include "webrtc/p2p/base/port.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010035#include "webrtc/pc/mediasession.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000036
37using cricket::AudioContentDescription;
38using cricket::Candidate;
39using cricket::Candidates;
40using cricket::ContentDescription;
41using cricket::ContentInfo;
42using cricket::CryptoParams;
43using cricket::DataContentDescription;
44using cricket::ICE_CANDIDATE_COMPONENT_RTP;
45using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
46using cricket::kCodecParamMaxBitrate;
47using cricket::kCodecParamMaxPTime;
48using cricket::kCodecParamMaxQuantization;
49using cricket::kCodecParamMinBitrate;
50using cricket::kCodecParamMinPTime;
51using cricket::kCodecParamPTime;
52using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000053using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054using cricket::kCodecParamStereo;
55using cricket::kCodecParamUseInbandFec;
Minyue Li7100dcd2015-03-27 05:05:59 +010056using cricket::kCodecParamUseDtx;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057using cricket::kCodecParamSctpProtocol;
58using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000059using cricket::kCodecParamMaxAverageBitrate;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000060using cricket::kCodecParamMaxPlaybackRate;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000061using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062using cricket::MediaContentDescription;
63using cricket::MediaType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064using cricket::RtpHeaderExtension;
65using cricket::SsrcGroup;
66using cricket::StreamParams;
67using cricket::StreamParamsVec;
68using cricket::TransportDescription;
69using cricket::TransportInfo;
70using cricket::VideoContentDescription;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000071using rtc::SocketAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072
73typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
74
75namespace cricket {
76class SessionDescription;
77}
78
79namespace webrtc {
80
81// Line type
82// RFC 4566
83// An SDP session description consists of a number of lines of text of
84// the form:
85// <type>=<value>
86// where <type> MUST be exactly one case-significant character.
deadbeef9d3584c2016-02-16 17:54:10 -080087static const int kLinePrefixLength = 2; // Length of <type>=
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088static const char kLineTypeVersion = 'v';
89static const char kLineTypeOrigin = 'o';
90static const char kLineTypeSessionName = 's';
91static const char kLineTypeSessionInfo = 'i';
92static const char kLineTypeSessionUri = 'u';
93static const char kLineTypeSessionEmail = 'e';
94static const char kLineTypeSessionPhone = 'p';
95static const char kLineTypeSessionBandwidth = 'b';
96static const char kLineTypeTiming = 't';
97static const char kLineTypeRepeatTimes = 'r';
98static const char kLineTypeTimeZone = 'z';
99static const char kLineTypeEncryptionKey = 'k';
100static const char kLineTypeMedia = 'm';
101static const char kLineTypeConnection = 'c';
102static const char kLineTypeAttributes = 'a';
103
104// Attributes
105static const char kAttributeGroup[] = "group";
106static const char kAttributeMid[] = "mid";
deadbeef9d3584c2016-02-16 17:54:10 -0800107static const char kAttributeMsid[] = "msid";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108static const char kAttributeRtcpMux[] = "rtcp-mux";
deadbeef13871492015-12-09 12:37:51 -0800109static const char kAttributeRtcpReducedSize[] = "rtcp-rsize";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110static const char kAttributeSsrc[] = "ssrc";
111static const char kSsrcAttributeCname[] = "cname";
112static const char kAttributeExtmap[] = "extmap";
113// draft-alvestrand-mmusic-msid-01
114// a=msid-semantic: WMS
115static const char kAttributeMsidSemantics[] = "msid-semantic";
116static const char kMediaStreamSemantic[] = "WMS";
117static const char kSsrcAttributeMsid[] = "msid";
118static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119static const char kSsrcAttributeMslabel[] = "mslabel";
120static const char kSSrcAttributeLabel[] = "label";
121static const char kAttributeSsrcGroup[] = "ssrc-group";
122static const char kAttributeCrypto[] = "crypto";
123static const char kAttributeCandidate[] = "candidate";
124static const char kAttributeCandidateTyp[] = "typ";
125static const char kAttributeCandidateRaddr[] = "raddr";
126static const char kAttributeCandidateRport[] = "rport";
honghaiza54a0802015-12-16 18:37:23 -0800127static const char kAttributeCandidateUfrag[] = "ufrag";
128static const char kAttributeCandidatePwd[] = "pwd";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000129static const char kAttributeCandidateGeneration[] = "generation";
honghaize1a0c942016-02-16 14:54:56 -0800130static const char kAttributeCandidateNetworkCost[] = "network-cost";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000131static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000132static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133static const char kAttributeFmtp[] = "fmtp";
134static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000135static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136static const char kAttributeRtcp[] = "rtcp";
137static const char kAttributeIceUfrag[] = "ice-ufrag";
138static const char kAttributeIcePwd[] = "ice-pwd";
139static const char kAttributeIceLite[] = "ice-lite";
140static const char kAttributeIceOption[] = "ice-options";
141static const char kAttributeSendOnly[] = "sendonly";
142static const char kAttributeRecvOnly[] = "recvonly";
143static const char kAttributeRtcpFb[] = "rtcp-fb";
144static const char kAttributeSendRecv[] = "sendrecv";
145static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000146// draft-ietf-mmusic-sctp-sdp-07
147// a=sctp-port
148static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000149
150// Experimental flags
151static const char kAttributeXGoogleFlag[] = "x-google-flag";
152static const char kValueConference[] = "conference";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000153
154// Candidate
155static const char kCandidateHost[] = "host";
156static const char kCandidateSrflx[] = "srflx";
honghaiz84430da2016-03-11 13:28:09 -0800157static const char kCandidatePrflx[] = "prflx";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000158static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000159static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000160
161static const char kSdpDelimiterEqual = '=';
162static const char kSdpDelimiterSpace = ' ';
163static const char kSdpDelimiterColon = ':';
164static const char kSdpDelimiterSemicolon = ';';
165static const char kSdpDelimiterSlash = '/';
166static const char kNewLine = '\n';
167static const char kReturn = '\r';
168static const char kLineBreak[] = "\r\n";
169
170// TODO: Generate the Session and Time description
171// instead of hardcoding.
172static const char kSessionVersion[] = "v=0";
173// RFC 4566
174static const char kSessionOriginUsername[] = "-";
175static const char kSessionOriginSessionId[] = "0";
176static const char kSessionOriginSessionVersion[] = "0";
177static const char kSessionOriginNettype[] = "IN";
178static const char kSessionOriginAddrtype[] = "IP4";
179static const char kSessionOriginAddress[] = "127.0.0.1";
180static const char kSessionName[] = "s=-";
181static const char kTimeDescription[] = "t=0 0";
182static const char kAttrGroup[] = "a=group:BUNDLE";
183static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000184static const char kConnectionIpv4Addrtype[] = "IP4";
185static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000186static const char kMediaTypeVideo[] = "video";
187static const char kMediaTypeAudio[] = "audio";
188static const char kMediaTypeData[] = "application";
189static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000190// draft-ietf-mmusic-trickle-ice-01
191// When no candidates have been gathered, set the connection
192// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000193// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
194// Use IPV4 per default.
195static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000196static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000197// RFC 3556
198static const char kApplicationSpecificMaximum[] = "AS";
199
200static const int kDefaultVideoClockrate = 90000;
201
202// ISAC special-case.
203static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
204static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
205static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
206
wu@webrtc.org78187522013-10-07 23:32:02 +0000207static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000208
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000209// RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
210// types.
211const int kWildcardPayloadType = -1;
212
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000213struct SsrcInfo {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200214 uint32_t ssrc_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000215 std::string cname;
deadbeef9d3584c2016-02-16 17:54:10 -0800216 std::string stream_id;
217 std::string track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000218
219 // For backward compatibility.
220 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
221 std::string label;
222 std::string mslabel;
223};
224typedef std::vector<SsrcInfo> SsrcInfoVec;
225typedef std::vector<SsrcGroup> SsrcGroupVec;
226
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000227template <class T>
228static void AddFmtpLine(const T& codec, std::string* message);
229static void BuildMediaDescription(const ContentInfo* content_info,
230 const TransportInfo* transport_info,
231 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000232 const std::vector<Candidate>& candidates,
deadbeef9d3584c2016-02-16 17:54:10 -0800233 bool unified_plan_sdp,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000234 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000235static void BuildSctpContentAttributes(std::string* message, int sctp_port);
deadbeef9d3584c2016-02-16 17:54:10 -0800236static void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
237 const MediaType media_type,
238 bool unified_plan_sdp,
239 std::string* message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000240static void BuildRtpMap(const MediaContentDescription* media_desc,
241 const MediaType media_type,
242 std::string* message);
243static void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -0800244 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000245 std::string* message);
246static void BuildIceOptions(const std::vector<std::string>& transport_options,
247 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000248static bool IsRtp(const std::string& protocol);
249static bool IsDtlsSctp(const std::string& protocol);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000250static bool ParseSessionDescription(const std::string& message, size_t* pos,
251 std::string* session_id,
252 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000253 TransportDescription* session_td,
254 RtpHeaderExtensions* session_extmaps,
255 cricket::SessionDescription* desc,
256 SdpParseError* error);
257static bool ParseGroupAttribute(const std::string& line,
258 cricket::SessionDescription* desc,
259 SdpParseError* error);
260static bool ParseMediaDescription(
261 const std::string& message,
262 const TransportDescription& session_td,
263 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000264 size_t* pos, cricket::SessionDescription* desc,
265 std::vector<JsepIceCandidate*>* candidates,
266 SdpParseError* error);
267static bool ParseContent(const std::string& message,
268 const MediaType media_type,
269 int mline_index,
270 const std::string& protocol,
271 const std::vector<int>& codec_preference,
272 size_t* pos,
273 std::string* content_name,
274 MediaContentDescription* media_desc,
275 TransportDescription* transport,
276 std::vector<JsepIceCandidate*>* candidates,
277 SdpParseError* error);
278static bool ParseSsrcAttribute(const std::string& line,
279 SsrcInfoVec* ssrc_infos,
280 SdpParseError* error);
281static bool ParseSsrcGroupAttribute(const std::string& line,
282 SsrcGroupVec* ssrc_groups,
283 SdpParseError* error);
284static bool ParseCryptoAttribute(const std::string& line,
285 MediaContentDescription* media_desc,
286 SdpParseError* error);
287static bool ParseRtpmapAttribute(const std::string& line,
288 const MediaType media_type,
289 const std::vector<int>& codec_preference,
290 MediaContentDescription* media_desc,
291 SdpParseError* error);
292static bool ParseFmtpAttributes(const std::string& line,
293 const MediaType media_type,
294 MediaContentDescription* media_desc,
295 SdpParseError* error);
296static bool ParseFmtpParam(const std::string& line, std::string* parameter,
297 std::string* value, SdpParseError* error);
298static bool ParseCandidate(const std::string& message, Candidate* candidate,
299 SdpParseError* error, bool is_raw);
300static bool ParseRtcpFbAttribute(const std::string& line,
301 const MediaType media_type,
302 MediaContentDescription* media_desc,
303 SdpParseError* error);
304static bool ParseIceOptions(const std::string& line,
305 std::vector<std::string>* transport_options,
306 SdpParseError* error);
307static bool ParseExtmap(const std::string& line,
308 RtpHeaderExtension* extmap,
309 SdpParseError* error);
310static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000311 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000312 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000313static bool ParseDtlsSetup(const std::string& line,
314 cricket::ConnectionRole* role,
315 SdpParseError* error);
deadbeef9d3584c2016-02-16 17:54:10 -0800316static bool ParseMsidAttribute(const std::string& line,
317 std::string* stream_id,
318 std::string* track_id,
319 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000320
321// Helper functions
322
323// Below ParseFailed*** functions output the line that caused the parsing
324// failure and the detailed reason (|description|) of the failure to |error|.
325// The functions always return false so that they can be used directly in the
326// following way when error happens:
327// "return ParseFailed***(...);"
328
329// The line starting at |line_start| of |message| is the failing line.
330// The reason for the failure should be provided in the |description|.
331// An example of a description could be "unknown character".
332static bool ParseFailed(const std::string& message,
333 size_t line_start,
334 const std::string& description,
335 SdpParseError* error) {
336 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000337 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000338 size_t line_end = message.find(kNewLine, line_start);
339 if (line_end != std::string::npos) {
340 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
341 --line_end;
342 }
343 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000344 } else {
345 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000346 }
347
348 if (error) {
349 error->line = first_line;
350 error->description = description;
351 }
352 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
353 << "\". Reason: " << description;
354 return false;
355}
356
357// |line| is the failing line. The reason for the failure should be
358// provided in the |description|.
359static bool ParseFailed(const std::string& line,
360 const std::string& description,
361 SdpParseError* error) {
362 return ParseFailed(line, 0, description, error);
363}
364
365// Parses failure where the failing SDP line isn't know or there are multiple
366// failing lines.
367static bool ParseFailed(const std::string& description,
368 SdpParseError* error) {
369 return ParseFailed("", description, error);
370}
371
372// |line| is the failing line. The failure is due to the fact that |line|
373// doesn't have |expected_fields| fields.
374static bool ParseFailedExpectFieldNum(const std::string& line,
375 int expected_fields,
376 SdpParseError* error) {
377 std::ostringstream description;
378 description << "Expects " << expected_fields << " fields.";
379 return ParseFailed(line, description.str(), error);
380}
381
382// |line| is the failing line. The failure is due to the fact that |line| has
383// less than |expected_min_fields| fields.
384static bool ParseFailedExpectMinFieldNum(const std::string& line,
385 int expected_min_fields,
386 SdpParseError* error) {
387 std::ostringstream description;
388 description << "Expects at least " << expected_min_fields << " fields.";
389 return ParseFailed(line, description.str(), error);
390}
391
392// |line| is the failing line. The failure is due to the fact that it failed to
393// get the value of |attribute|.
394static bool ParseFailedGetValue(const std::string& line,
395 const std::string& attribute,
396 SdpParseError* error) {
397 std::ostringstream description;
398 description << "Failed to get the value of attribute: " << attribute;
399 return ParseFailed(line, description.str(), error);
400}
401
402// The line starting at |line_start| of |message| is the failing line. The
403// failure is due to the line type (e.g. the "m" part of the "m-line")
404// not matching what is expected. The expected line type should be
405// provided as |line_type|.
406static bool ParseFailedExpectLine(const std::string& message,
407 size_t line_start,
408 const char line_type,
409 const std::string& line_value,
410 SdpParseError* error) {
411 std::ostringstream description;
412 description << "Expect line: " << line_type << "=" << line_value;
413 return ParseFailed(message, line_start, description.str(), error);
414}
415
416static bool AddLine(const std::string& line, std::string* message) {
417 if (!message)
418 return false;
419
420 message->append(line);
421 message->append(kLineBreak);
422 return true;
423}
424
425static bool GetLine(const std::string& message,
426 size_t* pos,
427 std::string* line) {
428 size_t line_begin = *pos;
429 size_t line_end = message.find(kNewLine, line_begin);
430 if (line_end == std::string::npos) {
431 return false;
432 }
433 // Update the new start position
434 *pos = line_end + 1;
435 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
436 --line_end;
437 }
438 *line = message.substr(line_begin, (line_end - line_begin));
439 const char* cline = line->c_str();
440 // RFC 4566
441 // An SDP session description consists of a number of lines of text of
442 // the form:
443 // <type>=<value>
444 // where <type> MUST be exactly one case-significant character and
445 // <value> is structured text whose format depends on <type>.
446 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000447 if (line->length() < 3 ||
448 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000449 cline[1] != kSdpDelimiterEqual ||
450 cline[2] == kSdpDelimiterSpace) {
451 *pos = line_begin;
452 return false;
453 }
454 return true;
455}
456
457// Init |os| to "|type|=|value|".
458static void InitLine(const char type,
459 const std::string& value,
460 std::ostringstream* os) {
461 os->str("");
462 *os << type << kSdpDelimiterEqual << value;
463}
464
465// Init |os| to "a=|attribute|".
466static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
467 InitLine(kLineTypeAttributes, attribute, os);
468}
469
470// Writes a SDP attribute line based on |attribute| and |value| to |message|.
471static void AddAttributeLine(const std::string& attribute, int value,
472 std::string* message) {
473 std::ostringstream os;
474 InitAttrLine(attribute, &os);
475 os << kSdpDelimiterColon << value;
476 AddLine(os.str(), message);
477}
478
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000479static bool IsLineType(const std::string& message,
480 const char type,
481 size_t line_start) {
482 if (message.size() < line_start + kLinePrefixLength) {
483 return false;
484 }
485 const char* cmessage = message.c_str();
486 return (cmessage[line_start] == type &&
487 cmessage[line_start + 1] == kSdpDelimiterEqual);
488}
489
490static bool IsLineType(const std::string& line,
491 const char type) {
492 return IsLineType(line, type, 0);
493}
494
495static bool GetLineWithType(const std::string& message, size_t* pos,
496 std::string* line, const char type) {
497 if (!IsLineType(message, type, *pos)) {
498 return false;
499 }
500
501 if (!GetLine(message, pos, line))
502 return false;
503
504 return true;
505}
506
507static bool HasAttribute(const std::string& line,
508 const std::string& attribute) {
509 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
510}
511
Peter Boström0c4e06b2015-10-07 12:23:21 +0200512static bool AddSsrcLine(uint32_t ssrc_id,
513 const std::string& attribute,
514 const std::string& value,
515 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000516 // RFC 5576
517 // a=ssrc:<ssrc-id> <attribute>:<value>
518 std::ostringstream os;
519 InitAttrLine(kAttributeSsrc, &os);
520 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
521 << attribute << kSdpDelimiterColon << value;
522 return AddLine(os.str(), message);
523}
524
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000525// Get value only from <attribute>:<value>.
526static bool GetValue(const std::string& message, const std::string& attribute,
527 std::string* value, SdpParseError* error) {
528 std::string leftpart;
Donald Curtis0e07f922015-05-15 09:21:23 -0700529 if (!rtc::tokenize_first(message, kSdpDelimiterColon, &leftpart, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000530 return ParseFailedGetValue(message, attribute, error);
531 }
532 // The left part should end with the expected attribute.
533 if (leftpart.length() < attribute.length() ||
534 leftpart.compare(leftpart.length() - attribute.length(),
535 attribute.length(), attribute) != 0) {
536 return ParseFailedGetValue(message, attribute, error);
537 }
538 return true;
539}
540
541static bool CaseInsensitiveFind(std::string str1, std::string str2) {
542 std::transform(str1.begin(), str1.end(), str1.begin(),
543 ::tolower);
544 std::transform(str2.begin(), str2.end(), str2.begin(),
545 ::tolower);
546 return str1.find(str2) != std::string::npos;
547}
548
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000549template <class T>
550static bool GetValueFromString(const std::string& line,
551 const std::string& s,
552 T* t,
553 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000554 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000555 std::ostringstream description;
556 description << "Invalid value: " << s << ".";
557 return ParseFailed(line, description.str(), error);
558 }
559 return true;
560}
561
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000562static bool GetPayloadTypeFromString(const std::string& line,
563 const std::string& s,
564 int* payload_type,
565 SdpParseError* error) {
566 return GetValueFromString(line, s, payload_type, error) &&
567 cricket::IsValidRtpPayloadType(*payload_type);
568}
569
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800570// |msid_stream_id| and |msid_track_id| represent the stream/track ID from the
571// "a=msid" attribute, if it exists. They are empty if the attribute does not
572// exist.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000573void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800574 const std::string& msid_stream_id,
575 const std::string& msid_track_id,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000576 StreamParamsVec* tracks) {
577 ASSERT(tracks != NULL);
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800578 ASSERT(msid_stream_id.empty() == msid_track_id.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000579 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
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800585 std::string stream_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000586 std::string track_id;
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800587 if (ssrc_info->stream_id.empty() && !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.
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800591 stream_id = ssrc_info->mslabel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000592 track_id = ssrc_info->label;
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800593 } else if (ssrc_info->stream_id.empty() && !msid_stream_id.empty()) {
594 // If there's no msid in the SSRC attributes, but there's a global one
595 // (from a=msid), use that. This is the case with unified plan SDP.
596 stream_id = msid_stream_id;
597 track_id = msid_track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000598 } else {
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800599 stream_id = ssrc_info->stream_id;
deadbeef9d3584c2016-02-16 17:54:10 -0800600 track_id = ssrc_info->track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000601 }
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800602 // If a stream/track ID wasn't populated from the SSRC attributes OR the
603 // msid attribute, use default/random values.
604 if (stream_id.empty()) {
605 stream_id = kDefaultMsid;
606 }
607 if (track_id.empty()) {
608 // TODO(ronghuawu): What should we do if the track id doesn't appear?
609 // Create random string (which will be used as track label later)?
610 track_id = rtc::CreateRandomString(8);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000611 }
612
613 StreamParamsVec::iterator track = tracks->begin();
614 for (; track != tracks->end(); ++track) {
615 if (track->id == track_id) {
616 break;
617 }
618 }
619 if (track == tracks->end()) {
620 // If we don't find an existing track, create a new one.
621 tracks->push_back(StreamParams());
622 track = tracks->end() - 1;
623 }
624 track->add_ssrc(ssrc_info->ssrc_id);
625 track->cname = ssrc_info->cname;
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800626 track->sync_label = stream_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000627 track->id = track_id;
628 }
629}
630
631void GetMediaStreamLabels(const ContentInfo* content,
632 std::set<std::string>* labels) {
633 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000634 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000635 content->description);
636 const cricket::StreamParamsVec& streams = media_desc->streams();
637 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
638 it != streams.end(); ++it) {
639 labels->insert(it->sync_label);
640 }
641}
642
643// RFC 5245
644// It is RECOMMENDED that default candidates be chosen based on the
645// likelihood of those candidates to work with the peer that is being
646// contacted. It is RECOMMENDED that relayed > reflexive > host.
647static const int kPreferenceUnknown = 0;
648static const int kPreferenceHost = 1;
649static const int kPreferenceReflexive = 2;
650static const int kPreferenceRelayed = 3;
651
652static int GetCandidatePreferenceFromType(const std::string& type) {
653 int preference = kPreferenceUnknown;
654 if (type == cricket::LOCAL_PORT_TYPE) {
655 preference = kPreferenceHost;
656 } else if (type == cricket::STUN_PORT_TYPE) {
657 preference = kPreferenceReflexive;
658 } else if (type == cricket::RELAY_PORT_TYPE) {
659 preference = kPreferenceRelayed;
660 } else {
661 ASSERT(false);
662 }
663 return preference;
664}
665
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000666// Get ip and port of the default destination from the |candidates| with the
667// given value of |component_id|. The default candidate should be the one most
668// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669// RFC 5245
670// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
671// TODO: Decide the default destination in webrtcsession and
672// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000673static void GetDefaultDestination(
674 const std::vector<Candidate>& candidates,
675 int component_id, std::string* port,
676 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000677 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000678 *port = kDummyPort;
679 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000681 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682 for (std::vector<Candidate>::const_iterator it = candidates.begin();
683 it != candidates.end(); ++it) {
684 if (it->component() != component_id) {
685 continue;
686 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000687 // Default destination should be UDP only.
688 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 continue;
690 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000691 const int preference = GetCandidatePreferenceFromType(it->type());
692 const int family = it->address().ipaddr().family();
693 // See if this candidate is more preferable then the current one if it's the
694 // same family. Or if the current family is IPv4 already so we could safely
695 // ignore all IPv6 ones. WebRTC bug 4269.
696 // http://code.google.com/p/webrtc/issues/detail?id=4269
697 if ((preference <= current_preference && current_family == family) ||
698 (current_family == AF_INET && family == AF_INET6)) {
699 continue;
700 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000701 if (family == AF_INET) {
702 addr_type->assign(kConnectionIpv4Addrtype);
703 } else if (family == AF_INET6) {
704 addr_type->assign(kConnectionIpv6Addrtype);
705 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000706 current_preference = preference;
707 current_family = family;
708 *port = it->address().PortAsString();
709 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000710 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000711}
712
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000713// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000714static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000715 const std::vector<Candidate>& candidates,
jbauch083b73f2015-07-16 02:46:32 -0700716 const std::string& mline,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000717 std::string* message) {
718 std::string new_lines;
719 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000720 // RFC 4566
721 // m=<media> <port> <proto> <fmt> ...
722 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000723 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000724 if (fields.size() < 3) {
725 return;
726 }
727
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000729 std::string rtp_port, rtp_ip, addr_type;
730 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
731 &rtp_port, &rtp_ip, &addr_type);
732 // Found default RTP candidate.
733 // RFC 5245
734 // The default candidates are added to the SDP as the default
735 // destination for media. For streams based on RTP, this is done by
736 // placing the IP address and port of the RTP candidate into the c and m
737 // lines, respectively.
738 // Update the port in the m line.
739 // If this is a m-line with port equal to 0, we don't change it.
740 if (fields[1] != kMediaPortRejected) {
741 new_lines.replace(fields[0].size() + 1,
742 fields[1].size(),
743 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000744 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000745 // Add the c line.
746 // RFC 4566
747 // c=<nettype> <addrtype> <connection-address>
748 InitLine(kLineTypeConnection, kConnectionNettype, &os);
749 os << " " << addr_type << " " << rtp_ip;
750 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000751 message->append(new_lines);
752}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000754// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
755static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000756 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
757 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
758 &rtcp_port, &rtcp_ip, &addr_type);
759 // Found default RTCP candidate.
760 // RFC 5245
761 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
762 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000763
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000764 // RFC 3605
765 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
766 // connection-address] CRLF
767 std::ostringstream os;
768 InitAttrLine(kAttributeRtcp, &os);
769 os << kSdpDelimiterColon
770 << rtcp_port << " "
771 << kConnectionNettype << " "
772 << addr_type << " "
773 << rtcp_ip;
774 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000775 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000776}
777
778// Get candidates according to the mline index from SessionDescriptionInterface.
779static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
780 int mline_index,
781 std::vector<Candidate>* candidates) {
782 if (!candidates) {
783 return;
784 }
785 const IceCandidateCollection* cc = desci.candidates(mline_index);
786 for (size_t i = 0; i < cc->count(); ++i) {
787 const IceCandidateInterface* candidate = cc->at(i);
788 candidates->push_back(candidate->candidate());
789 }
790}
791
deadbeef9d3584c2016-02-16 17:54:10 -0800792std::string SdpSerialize(const JsepSessionDescription& jdesc,
793 bool unified_plan_sdp) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794 const cricket::SessionDescription* desc = jdesc.description();
795 if (!desc) {
796 return "";
797 }
798
799 std::string message;
800
801 // Session Description.
802 AddLine(kSessionVersion, &message);
803 // Session Origin
804 // RFC 4566
805 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
806 // <unicast-address>
807 std::ostringstream os;
808 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
jbauch083b73f2015-07-16 02:46:32 -0700809 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000810 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700811 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812 kSessionOriginSessionVersion : jdesc.session_version();
813 os << " " << session_id << " " << session_version << " "
814 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
815 << kSessionOriginAddress;
816 AddLine(os.str(), &message);
817 AddLine(kSessionName, &message);
818
819 // Time Description.
820 AddLine(kTimeDescription, &message);
821
822 // Group
823 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
824 std::string group_line = kAttrGroup;
825 const cricket::ContentGroup* group =
826 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
827 ASSERT(group != NULL);
828 const cricket::ContentNames& content_names = group->content_names();
829 for (cricket::ContentNames::const_iterator it = content_names.begin();
830 it != content_names.end(); ++it) {
831 group_line.append(" ");
832 group_line.append(*it);
833 }
834 AddLine(group_line, &message);
835 }
836
837 // MediaStream semantics
838 InitAttrLine(kAttributeMsidSemantics, &os);
839 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000840
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000841 std::set<std::string> media_stream_labels;
842 const ContentInfo* audio_content = GetFirstAudioContent(desc);
843 if (audio_content)
844 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000845
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846 const ContentInfo* video_content = GetFirstVideoContent(desc);
847 if (video_content)
848 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000849
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000850 for (std::set<std::string>::const_iterator it =
851 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
852 os << " " << *it;
853 }
854 AddLine(os.str(), &message);
855
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000856 // Preserve the order of the media contents.
857 int mline_index = -1;
858 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
859 it != desc->contents().end(); ++it) {
860 const MediaContentDescription* mdesc =
861 static_cast<const MediaContentDescription*>(it->description);
862 std::vector<Candidate> candidates;
863 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
deadbeef9d3584c2016-02-16 17:54:10 -0800864 BuildMediaDescription(&*it, desc->GetTransportInfoByName(it->name),
865 mdesc->type(), candidates, unified_plan_sdp,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000866 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000867 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000868 return message;
869}
870
871// Serializes the passed in IceCandidateInterface to a SDP string.
872// candidate - The candidate to be serialized.
honghaiz84430da2016-03-11 13:28:09 -0800873std::string SdpSerializeCandidate(const IceCandidateInterface& candidate) {
874 return SdpSerializeCandidate(candidate.candidate());
875}
876
877// Serializes a cricket Candidate.
878std::string SdpSerializeCandidate(const cricket::Candidate& candidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879 std::string message;
honghaiz84430da2016-03-11 13:28:09 -0800880 std::vector<cricket::Candidate> candidates(1, candidate);
honghaiza54a0802015-12-16 18:37:23 -0800881 BuildCandidate(candidates, true, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000882 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
883 // just candidate:<candidate> not a=candidate:<blah>CRLF
884 ASSERT(message.find("a=") == 0);
885 message.erase(0, 2);
886 ASSERT(message.find(kLineBreak) == message.size() - 2);
887 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000888 return message;
889}
890
891bool SdpDeserialize(const std::string& message,
892 JsepSessionDescription* jdesc,
893 SdpParseError* error) {
894 std::string session_id;
895 std::string session_version;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700896 TransportDescription session_td("", "");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000897 RtpHeaderExtensions session_extmaps;
898 cricket::SessionDescription* desc = new cricket::SessionDescription();
899 std::vector<JsepIceCandidate*> candidates;
900 size_t current_pos = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000901
902 // Session Description
903 if (!ParseSessionDescription(message, &current_pos, &session_id,
deadbeefc80741f2015-10-22 13:14:45 -0700904 &session_version, &session_td, &session_extmaps,
905 desc, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906 delete desc;
907 return false;
908 }
909
910 // Media Description
deadbeefc80741f2015-10-22 13:14:45 -0700911 if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
912 desc, &candidates, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000913 delete desc;
914 for (std::vector<JsepIceCandidate*>::const_iterator
915 it = candidates.begin(); it != candidates.end(); ++it) {
916 delete *it;
917 }
918 return false;
919 }
920
921 jdesc->Initialize(desc, session_id, session_version);
922
923 for (std::vector<JsepIceCandidate*>::const_iterator
924 it = candidates.begin(); it != candidates.end(); ++it) {
925 jdesc->AddCandidate(*it);
926 delete *it;
927 }
928 return true;
929}
930
931bool SdpDeserializeCandidate(const std::string& message,
932 JsepIceCandidate* jcandidate,
933 SdpParseError* error) {
934 ASSERT(jcandidate != NULL);
935 Candidate candidate;
936 if (!ParseCandidate(message, &candidate, error, true)) {
937 return false;
938 }
939 jcandidate->SetCandidate(candidate);
940 return true;
941}
942
honghaiz84430da2016-03-11 13:28:09 -0800943bool SdpDeserializeCandidate(const std::string& transport_name,
944 const std::string& message,
945 cricket::Candidate* candidate,
946 SdpParseError* error) {
947 ASSERT(candidate != nullptr);
948 if (!ParseCandidate(message, candidate, error, true)) {
949 return false;
950 }
951 candidate->set_transport_name(transport_name);
952 return true;
953}
954
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955bool ParseCandidate(const std::string& message, Candidate* candidate,
956 SdpParseError* error, bool is_raw) {
957 ASSERT(candidate != NULL);
958
959 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000960 std::string first_line = message;
961 size_t pos = 0;
962 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000964 // Makes sure |message| contains only one line.
965 if (message.size() > first_line.size()) {
966 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700967 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
968 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000969 return ParseFailed(message, 0, "Expect one line only", error);
970 }
971 }
972
973 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
974 // candidate:<candidate> when trickled, but we still support
975 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
976 // from the SDP.
977 if (IsLineType(first_line, kLineTypeAttributes)) {
978 first_line = first_line.substr(kLinePrefixLength);
979 }
980
981 std::string attribute_candidate;
982 std::string candidate_value;
983
984 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700985 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
986 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000987 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988 if (is_raw) {
989 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000990 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991 << ":" << "<candidate-str>";
992 return ParseFailed(first_line, 0, description.str(), error);
993 } else {
994 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
995 kAttributeCandidate, error);
996 }
997 }
998
999 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001000 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
1001
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002 // RFC 5245
1003 // a=candidate:<foundation> <component-id> <transport> <priority>
1004 // <connection-address> <port> typ <candidate-types>
1005 // [raddr <connection-address>] [rport <port>]
1006 // *(SP extension-att-name SP extension-att-value)
1007 const size_t expected_min_fields = 8;
1008 if (fields.size() < expected_min_fields ||
1009 (fields[6] != kAttributeCandidateTyp)) {
1010 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
1011 }
jbauch083b73f2015-07-16 02:46:32 -07001012 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001013
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001014 int component_id = 0;
1015 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1016 return false;
1017 }
jbauch083b73f2015-07-16 02:46:32 -07001018 const std::string& transport = fields[2];
Peter Boström0c4e06b2015-10-07 12:23:21 +02001019 uint32_t priority = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001020 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1021 return false;
1022 }
jbauch083b73f2015-07-16 02:46:32 -07001023 const std::string& connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001024 int port = 0;
1025 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1026 return false;
1027 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028 SocketAddress address(connection_address, port);
1029
1030 cricket::ProtocolType protocol;
1031 if (!StringToProto(transport.c_str(), &protocol)) {
1032 return ParseFailed(first_line, "Unsupported transport type.", error);
1033 }
1034
1035 std::string candidate_type;
jbauch083b73f2015-07-16 02:46:32 -07001036 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037 if (type == kCandidateHost) {
1038 candidate_type = cricket::LOCAL_PORT_TYPE;
1039 } else if (type == kCandidateSrflx) {
1040 candidate_type = cricket::STUN_PORT_TYPE;
1041 } else if (type == kCandidateRelay) {
1042 candidate_type = cricket::RELAY_PORT_TYPE;
honghaiz84430da2016-03-11 13:28:09 -08001043 } else if (type == kCandidatePrflx) {
1044 candidate_type = cricket::PRFLX_PORT_TYPE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001045 } else {
1046 return ParseFailed(first_line, "Unsupported candidate type.", error);
1047 }
1048
1049 size_t current_position = expected_min_fields;
1050 SocketAddress related_address;
1051 // The 2 optional fields for related address
1052 // [raddr <connection-address>] [rport <port>]
1053 if (fields.size() >= (current_position + 2) &&
1054 fields[current_position] == kAttributeCandidateRaddr) {
1055 related_address.SetIP(fields[++current_position]);
1056 ++current_position;
1057 }
1058 if (fields.size() >= (current_position + 2) &&
1059 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001060 int port = 0;
1061 if (!GetValueFromString(
1062 first_line, fields[++current_position], &port, error)) {
1063 return false;
1064 }
1065 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066 ++current_position;
1067 }
1068
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001069 // If this is a TCP candidate, it has additional extension as defined in
1070 // RFC 6544.
1071 std::string tcptype;
1072 if (fields.size() >= (current_position + 2) &&
1073 fields[current_position] == kTcpCandidateType) {
1074 tcptype = fields[++current_position];
1075 ++current_position;
1076
1077 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1078 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1079 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1080 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1081 }
1082
1083 if (protocol != cricket::PROTO_TCP) {
1084 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1085 }
1086 }
1087
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088 // Extension
honghaiza54a0802015-12-16 18:37:23 -08001089 // Though non-standard, we support the ICE ufrag and pwd being signaled on
1090 // the candidate to avoid issues with confusing which generation a candidate
1091 // belongs to when trickling multiple generations at the same time.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001092 std::string username;
1093 std::string password;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001094 uint32_t generation = 0;
honghaize1a0c942016-02-16 14:54:56 -08001095 uint32_t network_cost = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001096 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1097 // RFC 5245
1098 // *(SP extension-att-name SP extension-att-value)
1099 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001100 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1101 return false;
1102 }
honghaiza54a0802015-12-16 18:37:23 -08001103 } else if (fields[i] == kAttributeCandidateUfrag) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001104 username = fields[++i];
honghaiza54a0802015-12-16 18:37:23 -08001105 } else if (fields[i] == kAttributeCandidatePwd) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001106 password = fields[++i];
honghaize1a0c942016-02-16 14:54:56 -08001107 } else if (fields[i] == kAttributeCandidateNetworkCost) {
1108 if (!GetValueFromString(first_line, fields[++i], &network_cost, error)) {
1109 return false;
1110 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001111 } else {
1112 // Skip the unknown extension.
1113 ++i;
1114 }
1115 }
1116
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001117 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001118 address, priority, username, password, candidate_type,
1119 generation, foundation);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001120 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001121 candidate->set_tcptype(tcptype);
honghaize1a0c942016-02-16 14:54:56 -08001122 candidate->set_network_cost(std::min(network_cost, cricket::kMaxNetworkCost));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001123 return true;
1124}
1125
1126bool ParseIceOptions(const std::string& line,
1127 std::vector<std::string>* transport_options,
1128 SdpParseError* error) {
1129 std::string ice_options;
1130 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1131 return false;
1132 }
1133 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001134 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001135 for (size_t i = 0; i < fields.size(); ++i) {
1136 transport_options->push_back(fields[i]);
1137 }
1138 return true;
1139}
1140
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001141bool ParseSctpPort(const std::string& line,
1142 int* sctp_port,
1143 SdpParseError* error) {
1144 // draft-ietf-mmusic-sctp-sdp-07
1145 // a=sctp-port
1146 std::vector<std::string> fields;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001147 const size_t expected_min_fields = 2;
lally69f57602015-10-08 10:15:04 -07001148 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1149 if (fields.size() < expected_min_fields) {
1150 fields.resize(0);
1151 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpace, &fields);
1152 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001153 if (fields.size() < expected_min_fields) {
1154 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1155 }
1156 if (!rtc::FromString(fields[1], sctp_port)) {
lally69f57602015-10-08 10:15:04 -07001157 return ParseFailed(line, "Invalid sctp port value.", error);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001158 }
1159 return true;
1160}
1161
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001162bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1163 SdpParseError* error) {
1164 // RFC 5285
1165 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1166 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001167 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001168 kSdpDelimiterSpace, &fields);
1169 const size_t expected_min_fields = 2;
1170 if (fields.size() < expected_min_fields) {
1171 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1172 }
1173 std::string uri = fields[1];
1174
1175 std::string value_direction;
1176 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1177 return false;
1178 }
1179 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001180 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001181 int value = 0;
1182 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1183 return false;
1184 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001185
1186 *extmap = RtpHeaderExtension(uri, value);
1187 return true;
1188}
1189
1190void BuildMediaDescription(const ContentInfo* content_info,
1191 const TransportInfo* transport_info,
1192 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001193 const std::vector<Candidate>& candidates,
deadbeef9d3584c2016-02-16 17:54:10 -08001194 bool unified_plan_sdp,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001195 std::string* message) {
1196 ASSERT(message != NULL);
1197 if (content_info == NULL || message == NULL) {
1198 return;
1199 }
1200 // TODO: Rethink if we should use sprintfn instead of stringstream.
1201 // According to the style guide, streams should only be used for logging.
1202 // http://google-styleguide.googlecode.com/svn/
1203 // trunk/cppguide.xml?showone=Streams#Streams
1204 std::ostringstream os;
1205 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001206 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001207 content_info->description);
1208 ASSERT(media_desc != NULL);
1209
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001210 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001211
1212 // RFC 4566
1213 // m=<media> <port> <proto> <fmt>
1214 // fmt is a list of payload type numbers that MAY be used in the session.
1215 const char* type = NULL;
1216 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1217 type = kMediaTypeAudio;
1218 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1219 type = kMediaTypeVideo;
1220 else if (media_type == cricket::MEDIA_TYPE_DATA)
1221 type = kMediaTypeData;
1222 else
1223 ASSERT(false);
1224
1225 std::string fmt;
1226 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1227 const VideoContentDescription* video_desc =
1228 static_cast<const VideoContentDescription*>(media_desc);
1229 for (std::vector<cricket::VideoCodec>::const_iterator it =
1230 video_desc->codecs().begin();
1231 it != video_desc->codecs().end(); ++it) {
1232 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001233 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001234 }
1235 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1236 const AudioContentDescription* audio_desc =
1237 static_cast<const AudioContentDescription*>(media_desc);
1238 for (std::vector<cricket::AudioCodec>::const_iterator it =
1239 audio_desc->codecs().begin();
1240 it != audio_desc->codecs().end(); ++it) {
1241 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001242 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001243 }
1244 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001245 const DataContentDescription* data_desc =
1246 static_cast<const DataContentDescription*>(media_desc);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001247 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001248 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001249
1250 for (std::vector<cricket::DataCodec>::const_iterator it =
1251 data_desc->codecs().begin();
1252 it != data_desc->codecs().end(); ++it) {
1253 if (it->id == cricket::kGoogleSctpDataCodecId &&
1254 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1255 break;
1256 }
1257 }
1258
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001259 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001260 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001261 for (std::vector<cricket::DataCodec>::const_iterator it =
1262 data_desc->codecs().begin();
1263 it != data_desc->codecs().end(); ++it) {
1264 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001265 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001266 }
1267 }
1268 }
1269 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1270 // to 0.
1271 if (fmt.empty()) {
1272 fmt = " 0";
1273 }
1274
1275 // The port number in the m line will be updated later when associate with
1276 // the candidates.
1277 // RFC 3264
1278 // To reject an offered stream, the port number in the corresponding stream in
1279 // the answer MUST be set to zero.
jbauch083b73f2015-07-16 02:46:32 -07001280 const std::string& port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001281 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001283 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001284 transport_info->description.identity_fingerprint.get() : NULL;
1285
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001286 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287 InitLine(kLineTypeMedia, type, &os);
1288 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001289 std::string mline = os.str();
1290 UpdateMediaDefaultDestination(candidates, mline, message);
1291
1292 // RFC 4566
1293 // b=AS:<bandwidth>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001294 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001295 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1296 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1297 AddLine(os.str(), message);
1298 }
1299
1300 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001301 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001302 std::string rtcp_line = GetRtcpLine(candidates);
1303 if (!rtcp_line.empty()) {
1304 AddLine(rtcp_line, message);
1305 }
1306 }
1307
honghaiza54a0802015-12-16 18:37:23 -08001308 // Build the a=candidate lines. We don't include ufrag and pwd in the
1309 // candidates in the SDP to avoid redundancy.
1310 BuildCandidate(candidates, false, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311
1312 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1313 if (transport_info) {
1314 // RFC 5245
1315 // ice-pwd-att = "ice-pwd" ":" password
1316 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1317 // ice-ufrag
deadbeef3f7219b2015-12-28 15:17:14 -08001318 if (!transport_info->description.ice_ufrag.empty()) {
1319 InitAttrLine(kAttributeIceUfrag, &os);
1320 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1321 AddLine(os.str(), message);
1322 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323 // ice-pwd
deadbeef3f7219b2015-12-28 15:17:14 -08001324 if (!transport_info->description.ice_pwd.empty()) {
1325 InitAttrLine(kAttributeIcePwd, &os);
1326 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1327 AddLine(os.str(), message);
1328 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329
1330 // draft-petithuguenin-mmusic-ice-attributes-level-03
1331 BuildIceOptions(transport_info->description.transport_options, message);
1332
1333 // RFC 4572
1334 // fingerprint-attribute =
1335 // "fingerprint" ":" hash-func SP fingerprint
1336 if (fp) {
1337 // Insert the fingerprint attribute.
1338 InitAttrLine(kAttributeFingerprint, &os);
1339 os << kSdpDelimiterColon
1340 << fp->algorithm << kSdpDelimiterSpace
1341 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001342 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001343
1344 // Inserting setup attribute.
1345 if (transport_info->description.connection_role !=
1346 cricket::CONNECTIONROLE_NONE) {
1347 // Making sure we are not using "passive" mode.
1348 cricket::ConnectionRole role =
1349 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001350 std::string dtls_role_str;
1351 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001352 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001353 os << kSdpDelimiterColon << dtls_role_str;
1354 AddLine(os.str(), message);
1355 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001356 }
1357 }
1358
1359 // RFC 3388
1360 // mid-attribute = "a=mid:" identification-tag
1361 // identification-tag = token
1362 // Use the content name as the mid identification-tag.
1363 InitAttrLine(kAttributeMid, &os);
1364 os << kSdpDelimiterColon << content_info->name;
1365 AddLine(os.str(), message);
1366
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001367 if (IsDtlsSctp(media_desc->protocol())) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001368 BuildSctpContentAttributes(message, sctp_port);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001369 } else if (IsRtp(media_desc->protocol())) {
deadbeef9d3584c2016-02-16 17:54:10 -08001370 BuildRtpContentAttributes(media_desc, media_type, unified_plan_sdp,
1371 message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372 }
1373}
1374
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001375void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001376 // draft-ietf-mmusic-sctp-sdp-04
1377 // a=sctpmap:sctpmap-number protocol [streams]
lally69f57602015-10-08 10:15:04 -07001378 // TODO(lally): switch this over to mmusic-sctp-sdp-12 (or later), with
1379 // 'a=sctp-port:'
wu@webrtc.org78187522013-10-07 23:32:02 +00001380 std::ostringstream os;
1381 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001382 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001383 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1384 << (cricket::kMaxSctpSid + 1);
1385 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001386}
1387
deadbeef9d3584c2016-02-16 17:54:10 -08001388// If unified_plan_sdp is true, will use "a=msid".
1389void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
1390 const MediaType media_type,
1391 bool unified_plan_sdp,
1392 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393 std::ostringstream os;
1394 // RFC 5285
1395 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1396 // The definitions MUST be either all session level or all media level. This
1397 // implementation uses all media level.
1398 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1399 InitAttrLine(kAttributeExtmap, &os);
1400 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1401 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1402 AddLine(os.str(), message);
1403 }
1404
1405 // RFC 3264
1406 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
deadbeefc80741f2015-10-22 13:14:45 -07001407 switch (media_desc->direction()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001408 case cricket::MD_INACTIVE:
1409 InitAttrLine(kAttributeInactive, &os);
1410 break;
1411 case cricket::MD_SENDONLY:
1412 InitAttrLine(kAttributeSendOnly, &os);
1413 break;
1414 case cricket::MD_RECVONLY:
1415 InitAttrLine(kAttributeRecvOnly, &os);
1416 break;
1417 case cricket::MD_SENDRECV:
1418 default:
1419 InitAttrLine(kAttributeSendRecv, &os);
1420 break;
1421 }
1422 AddLine(os.str(), message);
1423
deadbeef9d3584c2016-02-16 17:54:10 -08001424 // draft-ietf-mmusic-msid-11
1425 // a=msid:<stream id> <track id>
1426 if (unified_plan_sdp && !media_desc->streams().empty()) {
1427 if (media_desc->streams().size() > 1u) {
1428 LOG(LS_WARNING) << "Trying to serialize unified plan SDP with more than "
1429 << "one track in a media section. Omitting 'a=msid'.";
1430 } else {
1431 auto track = media_desc->streams().begin();
1432 const std::string& stream_id = track->sync_label;
deadbeef9d3584c2016-02-16 17:54:10 -08001433 InitAttrLine(kAttributeMsid, &os);
1434 os << kSdpDelimiterColon << stream_id << kSdpDelimiterSpace << track->id;
1435 AddLine(os.str(), message);
1436 }
1437 }
1438
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001439 // RFC 5761
1440 // a=rtcp-mux
1441 if (media_desc->rtcp_mux()) {
1442 InitAttrLine(kAttributeRtcpMux, &os);
1443 AddLine(os.str(), message);
1444 }
1445
deadbeef13871492015-12-09 12:37:51 -08001446 // RFC 5506
1447 // a=rtcp-rsize
1448 if (media_desc->rtcp_reduced_size()) {
1449 InitAttrLine(kAttributeRtcpReducedSize, &os);
1450 AddLine(os.str(), message);
1451 }
1452
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001453 // RFC 4568
1454 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1455 for (std::vector<CryptoParams>::const_iterator it =
1456 media_desc->cryptos().begin();
1457 it != media_desc->cryptos().end(); ++it) {
1458 InitAttrLine(kAttributeCrypto, &os);
1459 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1460 << it->key_params;
1461 if (!it->session_params.empty()) {
1462 os << " " << it->session_params;
1463 }
1464 AddLine(os.str(), message);
1465 }
1466
1467 // RFC 4566
1468 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1469 // [/<encodingparameters>]
1470 BuildRtpMap(media_desc, media_type, message);
1471
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1473 track != media_desc->streams().end(); ++track) {
1474 // Require that the track belongs to a media stream,
1475 // ie the sync_label is set. This extra check is necessary since the
1476 // MediaContentDescription always contains a streamparam with an ssrc even
1477 // if no track or media stream have been created.
1478 if (track->sync_label.empty()) continue;
1479
1480 // Build the ssrc-group lines.
1481 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1482 // RFC 5576
1483 // a=ssrc-group:<semantics> <ssrc-id> ...
1484 if (track->ssrc_groups[i].ssrcs.empty()) {
1485 continue;
1486 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487 InitAttrLine(kAttributeSsrcGroup, &os);
1488 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001489 std::vector<uint32_t>::const_iterator ssrc =
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001490 track->ssrc_groups[i].ssrcs.begin();
1491 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001492 os << kSdpDelimiterSpace << rtc::ToString<uint32_t>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001493 }
1494 AddLine(os.str(), message);
1495 }
1496 // Build the ssrc lines for each ssrc.
1497 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001498 uint32_t ssrc = track->ssrcs[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001499 // RFC 5576
1500 // a=ssrc:<ssrc-id> cname:<value>
1501 AddSsrcLine(ssrc, kSsrcAttributeCname,
1502 track->cname, message);
1503
1504 // draft-alvestrand-mmusic-msid-00
1505 // a=ssrc:<ssrc-id> msid:identifier [appdata]
deadbeef9d3584c2016-02-16 17:54:10 -08001506 // The appdata consists of the "id" attribute of a MediaStreamTrack,
1507 // which corresponds to the "id" attribute of StreamParams.
1508 const std::string& stream_id = track->sync_label;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001509 InitAttrLine(kAttributeSsrc, &os);
1510 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
deadbeef9d3584c2016-02-16 17:54:10 -08001511 << kSsrcAttributeMsid << kSdpDelimiterColon << stream_id
1512 << kSdpDelimiterSpace << track->id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001513 AddLine(os.str(), message);
1514
deadbeef9d3584c2016-02-16 17:54:10 -08001515 // TODO(ronghuawu): Remove below code which is for backward
1516 // compatibility.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001517 // draft-alvestrand-rtcweb-mid-01
1518 // a=ssrc:<ssrc-id> mslabel:<value>
1519 // The label isn't yet defined.
1520 // a=ssrc:<ssrc-id> label:<value>
1521 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1522 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1523 }
1524 }
1525}
1526
1527void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1528 // fmtp header: a=fmtp:|payload_type| <parameters>
1529 // Add a=fmtp
1530 InitAttrLine(kAttributeFmtp, os);
1531 // Add :|payload_type|
1532 *os << kSdpDelimiterColon << payload_type;
1533}
1534
1535void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1536 // rtcp-fb header: a=rtcp-fb:|payload_type|
1537 // <parameters>/<ccm <ccm_parameters>>
1538 // Add a=rtcp-fb
1539 InitAttrLine(kAttributeRtcpFb, os);
1540 // Add :
1541 *os << kSdpDelimiterColon;
1542 if (payload_type == kWildcardPayloadType) {
1543 *os << "*";
1544 } else {
1545 *os << payload_type;
1546 }
1547}
1548
1549void WriteFmtpParameter(const std::string& parameter_name,
1550 const std::string& parameter_value,
1551 std::ostringstream* os) {
1552 // fmtp parameters: |parameter_name|=|parameter_value|
1553 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1554}
1555
1556void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1557 std::ostringstream* os) {
1558 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1559 fmtp != parameters.end(); ++fmtp) {
1560 // Each new parameter, except the first one starts with ";" and " ".
1561 if (fmtp != parameters.begin()) {
1562 *os << kSdpDelimiterSemicolon;
1563 }
1564 *os << kSdpDelimiterSpace;
1565 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1566 }
1567}
1568
1569bool IsFmtpParam(const std::string& name) {
1570 const char* kFmtpParams[] = {
1571 kCodecParamMinPTime, kCodecParamSPropStereo,
Minyue Li7100dcd2015-03-27 05:05:59 +01001572 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamUseDtx,
1573 kCodecParamStartBitrate, kCodecParamMaxBitrate, kCodecParamMinBitrate,
1574 kCodecParamMaxQuantization, kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001575 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1576 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001577 };
tfarina5237aaf2015-11-10 23:44:30 -08001578 for (size_t i = 0; i < arraysize(kFmtpParams); ++i) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001579 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1580 return true;
1581 }
1582 }
1583 return false;
1584}
1585
1586// Retreives fmtp parameters from |params|, which may contain other parameters
1587// as well, and puts them in |fmtp_parameters|.
1588void GetFmtpParams(const cricket::CodecParameterMap& params,
1589 cricket::CodecParameterMap* fmtp_parameters) {
1590 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1591 iter != params.end(); ++iter) {
1592 if (IsFmtpParam(iter->first)) {
1593 (*fmtp_parameters)[iter->first] = iter->second;
1594 }
1595 }
1596}
1597
1598template <class T>
1599void AddFmtpLine(const T& codec, std::string* message) {
1600 cricket::CodecParameterMap fmtp_parameters;
1601 GetFmtpParams(codec.params, &fmtp_parameters);
1602 if (fmtp_parameters.empty()) {
1603 // No need to add an fmtp if it will have no (optional) parameters.
1604 return;
1605 }
1606 std::ostringstream os;
1607 WriteFmtpHeader(codec.id, &os);
1608 WriteFmtpParameters(fmtp_parameters, &os);
1609 AddLine(os.str(), message);
1610 return;
1611}
1612
1613template <class T>
1614void AddRtcpFbLines(const T& codec, std::string* message) {
1615 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1616 codec.feedback_params.params().begin();
1617 iter != codec.feedback_params.params().end(); ++iter) {
1618 std::ostringstream os;
1619 WriteRtcpFbHeader(codec.id, &os);
1620 os << " " << iter->id();
1621 if (!iter->param().empty()) {
1622 os << " " << iter->param();
1623 }
1624 AddLine(os.str(), message);
1625 }
1626}
1627
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001628bool AddSctpDataCodec(DataContentDescription* media_desc,
1629 int sctp_port) {
1630 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1631 return ParseFailed("",
1632 "Can't have multiple sctp port attributes.",
1633 NULL);
1634 }
1635 // Add the SCTP Port number as a pseudo-codec "port" parameter
1636 cricket::DataCodec codec_port(
1637 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1638 0);
1639 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1640 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1641 << sctp_port;
1642 media_desc->AddCodec(codec_port);
1643 return true;
1644}
1645
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001646bool GetMinValue(const std::vector<int>& values, int* value) {
1647 if (values.empty()) {
1648 return false;
1649 }
1650 std::vector<int>::const_iterator found =
1651 std::min_element(values.begin(), values.end());
1652 *value = *found;
1653 return true;
1654}
1655
1656bool GetParameter(const std::string& name,
1657 const cricket::CodecParameterMap& params, int* value) {
1658 std::map<std::string, std::string>::const_iterator found =
1659 params.find(name);
1660 if (found == params.end()) {
1661 return false;
1662 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001663 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001664 return false;
1665 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001666 return true;
1667}
1668
1669void BuildRtpMap(const MediaContentDescription* media_desc,
1670 const MediaType media_type,
1671 std::string* message) {
1672 ASSERT(message != NULL);
1673 ASSERT(media_desc != NULL);
1674 std::ostringstream os;
1675 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1676 const VideoContentDescription* video_desc =
1677 static_cast<const VideoContentDescription*>(media_desc);
1678 for (std::vector<cricket::VideoCodec>::const_iterator it =
1679 video_desc->codecs().begin();
1680 it != video_desc->codecs().end(); ++it) {
1681 // RFC 4566
1682 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1683 // [/<encodingparameters>]
1684 if (it->id != kWildcardPayloadType) {
1685 InitAttrLine(kAttributeRtpmap, &os);
1686 os << kSdpDelimiterColon << it->id << " " << it->name
1687 << "/" << kDefaultVideoClockrate;
1688 AddLine(os.str(), message);
1689 }
1690 AddRtcpFbLines(*it, message);
1691 AddFmtpLine(*it, message);
1692 }
1693 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1694 const AudioContentDescription* audio_desc =
1695 static_cast<const AudioContentDescription*>(media_desc);
1696 std::vector<int> ptimes;
1697 std::vector<int> maxptimes;
1698 int max_minptime = 0;
1699 for (std::vector<cricket::AudioCodec>::const_iterator it =
1700 audio_desc->codecs().begin();
1701 it != audio_desc->codecs().end(); ++it) {
1702 ASSERT(!it->name.empty());
1703 // RFC 4566
1704 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1705 // [/<encodingparameters>]
1706 InitAttrLine(kAttributeRtpmap, &os);
1707 os << kSdpDelimiterColon << it->id << " ";
1708 os << it->name << "/" << it->clockrate;
1709 if (it->channels != 1) {
1710 os << "/" << it->channels;
1711 }
1712 AddLine(os.str(), message);
1713 AddRtcpFbLines(*it, message);
1714 AddFmtpLine(*it, message);
1715 int minptime = 0;
1716 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1717 max_minptime = std::max(minptime, max_minptime);
1718 }
1719 int ptime;
1720 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1721 ptimes.push_back(ptime);
1722 }
1723 int maxptime;
1724 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1725 maxptimes.push_back(maxptime);
1726 }
1727 }
1728 // Populate the maxptime attribute with the smallest maxptime of all codecs
1729 // under the same m-line.
1730 int min_maxptime = INT_MAX;
1731 if (GetMinValue(maxptimes, &min_maxptime)) {
1732 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1733 }
1734 ASSERT(min_maxptime > max_minptime);
1735 // Populate the ptime attribute with the smallest ptime or the largest
1736 // minptime, whichever is the largest, for all codecs under the same m-line.
1737 int ptime = INT_MAX;
1738 if (GetMinValue(ptimes, &ptime)) {
1739 ptime = std::min(ptime, min_maxptime);
1740 ptime = std::max(ptime, max_minptime);
1741 AddAttributeLine(kCodecParamPTime, ptime, message);
1742 }
1743 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1744 const DataContentDescription* data_desc =
1745 static_cast<const DataContentDescription*>(media_desc);
1746 for (std::vector<cricket::DataCodec>::const_iterator it =
1747 data_desc->codecs().begin();
1748 it != data_desc->codecs().end(); ++it) {
1749 // RFC 4566
1750 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1751 // [/<encodingparameters>]
1752 InitAttrLine(kAttributeRtpmap, &os);
1753 os << kSdpDelimiterColon << it->id << " "
1754 << it->name << "/" << it->clockrate;
1755 AddLine(os.str(), message);
1756 }
1757 }
1758}
1759
1760void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -08001761 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001762 std::string* message) {
1763 std::ostringstream os;
1764
1765 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1766 it != candidates.end(); ++it) {
1767 // RFC 5245
1768 // a=candidate:<foundation> <component-id> <transport> <priority>
1769 // <connection-address> <port> typ <candidate-types>
1770 // [raddr <connection-address>] [rport <port>]
1771 // *(SP extension-att-name SP extension-att-value)
1772 std::string type;
1773 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1774 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1775 type = kCandidateHost;
1776 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1777 type = kCandidateSrflx;
1778 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1779 type = kCandidateRelay;
honghaiz84430da2016-03-11 13:28:09 -08001780 } else if (it->type() == cricket::PRFLX_PORT_TYPE) {
1781 type = kCandidatePrflx;
1782 // Peer reflexive candidate may be signaled for being removed.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001783 } else {
1784 ASSERT(false);
Peter Thatcher019087f2015-04-28 09:06:26 -07001785 // Never write out candidates if we don't know the type.
1786 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001787 }
1788
1789 InitAttrLine(kAttributeCandidate, &os);
1790 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001791 << it->foundation() << " "
1792 << it->component() << " "
1793 << it->protocol() << " "
1794 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001795 << it->address().ipaddr().ToString() << " "
1796 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001797 << kAttributeCandidateTyp << " "
1798 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001799
1800 // Related address
1801 if (!it->related_address().IsNil()) {
1802 os << kAttributeCandidateRaddr << " "
1803 << it->related_address().ipaddr().ToString() << " "
1804 << kAttributeCandidateRport << " "
1805 << it->related_address().PortAsString() << " ";
1806 }
1807
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001808 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001809 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001810 }
1811
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001812 // Extensions
1813 os << kAttributeCandidateGeneration << " " << it->generation();
honghaiza54a0802015-12-16 18:37:23 -08001814 if (include_ufrag && !it->username().empty()) {
1815 os << " " << kAttributeCandidateUfrag << " " << it->username();
1816 }
honghaize1a0c942016-02-16 14:54:56 -08001817 if (it->network_cost() > 0) {
1818 os << " " << kAttributeCandidateNetworkCost << " " << it->network_cost();
1819 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820
1821 AddLine(os.str(), message);
1822 }
1823}
1824
1825void BuildIceOptions(const std::vector<std::string>& transport_options,
1826 std::string* message) {
1827 if (!transport_options.empty()) {
1828 std::ostringstream os;
1829 InitAttrLine(kAttributeIceOption, &os);
1830 os << kSdpDelimiterColon << transport_options[0];
1831 for (size_t i = 1; i < transport_options.size(); ++i) {
1832 os << kSdpDelimiterSpace << transport_options[i];
1833 }
1834 AddLine(os.str(), message);
1835 }
1836}
1837
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001838bool IsRtp(const std::string& protocol) {
1839 return protocol.empty() ||
1840 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1841}
1842
1843bool IsDtlsSctp(const std::string& protocol) {
1844 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001845 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001846}
1847
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001848bool ParseSessionDescription(const std::string& message, size_t* pos,
1849 std::string* session_id,
1850 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001851 TransportDescription* session_td,
1852 RtpHeaderExtensions* session_extmaps,
1853 cricket::SessionDescription* desc,
1854 SdpParseError* error) {
1855 std::string line;
1856
deadbeefc80741f2015-10-22 13:14:45 -07001857 desc->set_msid_supported(false);
1858
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001859 // RFC 4566
1860 // v= (protocol version)
1861 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1862 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1863 std::string(), error);
1864 }
1865 // RFC 4566
1866 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1867 // <unicast-address>
1868 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1869 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1870 std::string(), error);
1871 }
1872 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001873 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001874 kSdpDelimiterSpace, &fields);
1875 const size_t expected_fields = 6;
1876 if (fields.size() != expected_fields) {
1877 return ParseFailedExpectFieldNum(line, expected_fields, error);
1878 }
1879 *session_id = fields[1];
1880 *session_version = fields[2];
1881
1882 // RFC 4566
1883 // s= (session name)
1884 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1885 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1886 std::string(), error);
1887 }
1888
1889 // Optional lines
1890 // Those are the optional lines, so shouldn't return false if not present.
1891 // RFC 4566
1892 // i=* (session information)
1893 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1894
1895 // RFC 4566
1896 // u=* (URI of description)
1897 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1898
1899 // RFC 4566
1900 // e=* (email address)
1901 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1902
1903 // RFC 4566
1904 // p=* (phone number)
1905 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1906
1907 // RFC 4566
1908 // c=* (connection information -- not required if included in
1909 // all media)
1910 GetLineWithType(message, pos, &line, kLineTypeConnection);
1911
1912 // RFC 4566
1913 // b=* (zero or more bandwidth information lines)
1914 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1915 // By pass zero or more b lines.
1916 }
1917
1918 // RFC 4566
1919 // One or more time descriptions ("t=" and "r=" lines; see below)
1920 // t= (time the session is active)
1921 // r=* (zero or more repeat times)
1922 // Ensure there's at least one time description
1923 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1924 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1925 error);
1926 }
1927
1928 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1929 // By pass zero or more r lines.
1930 }
1931
1932 // Go through the rest of the time descriptions
1933 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1934 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1935 // By pass zero or more r lines.
1936 }
1937 }
1938
1939 // RFC 4566
1940 // z=* (time zone adjustments)
1941 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1942
1943 // RFC 4566
1944 // k=* (encryption key)
1945 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1946
1947 // RFC 4566
1948 // a=* (zero or more session attribute lines)
1949 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1950 if (HasAttribute(line, kAttributeGroup)) {
1951 if (!ParseGroupAttribute(line, desc, error)) {
1952 return false;
1953 }
1954 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1955 if (!GetValue(line, kAttributeIceUfrag,
1956 &(session_td->ice_ufrag), error)) {
1957 return false;
1958 }
1959 } else if (HasAttribute(line, kAttributeIcePwd)) {
1960 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1961 return false;
1962 }
1963 } else if (HasAttribute(line, kAttributeIceLite)) {
1964 session_td->ice_mode = cricket::ICEMODE_LITE;
1965 } else if (HasAttribute(line, kAttributeIceOption)) {
1966 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1967 return false;
1968 }
1969 } else if (HasAttribute(line, kAttributeFingerprint)) {
1970 if (session_td->identity_fingerprint.get()) {
1971 return ParseFailed(
1972 line,
1973 "Can't have multiple fingerprint attributes at the same level.",
1974 error);
1975 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001976 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1978 return false;
1979 }
1980 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001981 } else if (HasAttribute(line, kAttributeSetup)) {
1982 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1983 return false;
1984 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1986 std::string semantics;
1987 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1988 return false;
1989 }
deadbeefc80741f2015-10-22 13:14:45 -07001990 desc->set_msid_supported(
1991 CaseInsensitiveFind(semantics, kMediaStreamSemantic));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992 } else if (HasAttribute(line, kAttributeExtmap)) {
1993 RtpHeaderExtension extmap;
1994 if (!ParseExtmap(line, &extmap, error)) {
1995 return false;
1996 }
1997 session_extmaps->push_back(extmap);
1998 }
1999 }
2000
2001 return true;
2002}
2003
2004bool ParseGroupAttribute(const std::string& line,
2005 cricket::SessionDescription* desc,
2006 SdpParseError* error) {
2007 ASSERT(desc != NULL);
2008
2009 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
2010 // a=group:BUNDLE video voice
2011 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002012 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013 kSdpDelimiterSpace, &fields);
2014 std::string semantics;
2015 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
2016 return false;
2017 }
2018 cricket::ContentGroup group(semantics);
2019 for (size_t i = 1; i < fields.size(); ++i) {
2020 group.AddContentName(fields[i]);
2021 }
2022 desc->AddGroup(group);
2023 return true;
2024}
2025
2026static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002027 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028 SdpParseError* error) {
2029 if (!IsLineType(line, kLineTypeAttributes) ||
2030 !HasAttribute(line, kAttributeFingerprint)) {
2031 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
2032 kAttributeFingerprint, error);
2033 }
2034
2035 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002036 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002037 kSdpDelimiterSpace, &fields);
2038 const size_t expected_fields = 2;
2039 if (fields.size() != expected_fields) {
2040 return ParseFailedExpectFieldNum(line, expected_fields, error);
2041 }
2042
2043 // The first field here is "fingerprint:<hash>.
2044 std::string algorithm;
2045 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2046 return false;
2047 }
2048
2049 // Downcase the algorithm. Note that we don't need to downcase the
2050 // fingerprint because hex_decode can handle upper-case.
2051 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2052 ::tolower);
2053
2054 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002055 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002056 algorithm, fields[1]);
2057 if (!*fingerprint) {
2058 return ParseFailed(line,
2059 "Failed to create fingerprint from the digest.",
2060 error);
2061 }
2062
2063 return true;
2064}
2065
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002066static bool ParseDtlsSetup(const std::string& line,
2067 cricket::ConnectionRole* role,
2068 SdpParseError* error) {
2069 // setup-attr = "a=setup:" role
2070 // role = "active" / "passive" / "actpass" / "holdconn"
2071 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002072 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002073 const size_t expected_fields = 2;
2074 if (fields.size() != expected_fields) {
2075 return ParseFailedExpectFieldNum(line, expected_fields, error);
2076 }
2077 std::string role_str = fields[1];
2078 if (!cricket::StringToConnectionRole(role_str, role)) {
2079 return ParseFailed(line, "Invalid attribute value.", error);
2080 }
2081 return true;
2082}
2083
deadbeef9d3584c2016-02-16 17:54:10 -08002084static bool ParseMsidAttribute(const std::string& line,
2085 std::string* stream_id,
2086 std::string* track_id,
2087 SdpParseError* error) {
2088 // draft-ietf-mmusic-msid-11
2089 // a=msid:<stream id> <track id>
2090 // msid-value = msid-id [ SP msid-appdata ]
2091 // msid-id = 1*64token-char ; see RFC 4566
2092 // msid-appdata = 1*64token-char ; see RFC 4566
2093 std::string field1;
2094 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2095 &field1, track_id)) {
2096 const size_t expected_fields = 2;
2097 return ParseFailedExpectFieldNum(line, expected_fields, error);
2098 }
2099
2100 // msid:<msid-id>
2101 if (!GetValue(field1, kAttributeMsid, stream_id, error)) {
2102 return false;
2103 }
2104 return true;
2105}
2106
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002107// RFC 3551
2108// PT encoding media type clock rate channels
2109// name (Hz)
2110// 0 PCMU A 8,000 1
2111// 1 reserved A
2112// 2 reserved A
2113// 3 GSM A 8,000 1
2114// 4 G723 A 8,000 1
2115// 5 DVI4 A 8,000 1
2116// 6 DVI4 A 16,000 1
2117// 7 LPC A 8,000 1
2118// 8 PCMA A 8,000 1
2119// 9 G722 A 8,000 1
2120// 10 L16 A 44,100 2
2121// 11 L16 A 44,100 1
2122// 12 QCELP A 8,000 1
2123// 13 CN A 8,000 1
2124// 14 MPA A 90,000 (see text)
2125// 15 G728 A 8,000 1
2126// 16 DVI4 A 11,025 1
2127// 17 DVI4 A 22,050 1
2128// 18 G729 A 8,000 1
2129struct StaticPayloadAudioCodec {
2130 const char* name;
2131 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002132 size_t channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002133};
2134static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2135 { "PCMU", 8000, 1 },
2136 { "reserved", 0, 0 },
2137 { "reserved", 0, 0 },
2138 { "GSM", 8000, 1 },
2139 { "G723", 8000, 1 },
2140 { "DVI4", 8000, 1 },
2141 { "DVI4", 16000, 1 },
2142 { "LPC", 8000, 1 },
2143 { "PCMA", 8000, 1 },
2144 { "G722", 8000, 1 },
2145 { "L16", 44100, 2 },
2146 { "L16", 44100, 1 },
2147 { "QCELP", 8000, 1 },
2148 { "CN", 8000, 1 },
2149 { "MPA", 90000, 1 },
2150 { "G728", 8000, 1 },
2151 { "DVI4", 11025, 1 },
2152 { "DVI4", 22050, 1 },
2153 { "G729", 8000, 1 },
2154};
2155
2156void MaybeCreateStaticPayloadAudioCodecs(
2157 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2158 if (!media_desc) {
2159 return;
2160 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002161 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162 std::vector<int>::const_iterator it = fmts.begin();
2163 bool add_new_codec = false;
2164 for (; it != fmts.end(); ++it) {
2165 int payload_type = *it;
2166 if (!media_desc->HasCodec(payload_type) &&
2167 payload_type >= 0 &&
tfarina5237aaf2015-11-10 23:44:30 -08002168 payload_type < arraysize(kStaticPayloadAudioCodecs)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002169 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2170 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002171 size_t channels = kStaticPayloadAudioCodecs[payload_type].channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002172 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2173 clock_rate, 0, channels,
2174 preference));
2175 add_new_codec = true;
2176 }
2177 --preference;
2178 }
2179 if (add_new_codec) {
2180 media_desc->SortCodecs();
2181 }
2182}
2183
2184template <class C>
2185static C* ParseContentDescription(const std::string& message,
2186 const MediaType media_type,
2187 int mline_index,
2188 const std::string& protocol,
2189 const std::vector<int>& codec_preference,
2190 size_t* pos,
2191 std::string* content_name,
2192 TransportDescription* transport,
2193 std::vector<JsepIceCandidate*>* candidates,
2194 webrtc::SdpParseError* error) {
2195 C* media_desc = new C();
2196 switch (media_type) {
2197 case cricket::MEDIA_TYPE_AUDIO:
2198 *content_name = cricket::CN_AUDIO;
2199 break;
2200 case cricket::MEDIA_TYPE_VIDEO:
2201 *content_name = cricket::CN_VIDEO;
2202 break;
2203 case cricket::MEDIA_TYPE_DATA:
2204 *content_name = cricket::CN_DATA;
2205 break;
2206 default:
2207 ASSERT(false);
2208 break;
2209 }
2210 if (!ParseContent(message, media_type, mline_index, protocol,
2211 codec_preference, pos, content_name,
2212 media_desc, transport, candidates, error)) {
2213 delete media_desc;
2214 return NULL;
2215 }
2216 // Sort the codecs according to the m-line fmt list.
2217 media_desc->SortCodecs();
2218 return media_desc;
2219}
2220
2221bool ParseMediaDescription(const std::string& message,
2222 const TransportDescription& session_td,
2223 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002224 size_t* pos,
2225 cricket::SessionDescription* desc,
2226 std::vector<JsepIceCandidate*>* candidates,
2227 SdpParseError* error) {
2228 ASSERT(desc != NULL);
2229 std::string line;
2230 int mline_index = -1;
2231
2232 // Zero or more media descriptions
2233 // RFC 4566
2234 // m=<media> <port> <proto> <fmt>
2235 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2236 ++mline_index;
2237
2238 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002239 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002240 kSdpDelimiterSpace, &fields);
2241 const size_t expected_min_fields = 4;
2242 if (fields.size() < expected_min_fields) {
2243 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2244 }
2245 bool rejected = false;
2246 // RFC 3264
2247 // To reject an offered stream, the port number in the corresponding stream
2248 // in the answer MUST be set to zero.
2249 if (fields[1] == kMediaPortRejected) {
2250 rejected = true;
2251 }
2252
2253 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002254
2255 // <fmt>
2256 std::vector<int> codec_preference;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002257 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002258 for (size_t j = 3 ; j < fields.size(); ++j) {
2259 // TODO(wu): Remove when below bug is fixed.
2260 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002261 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002262 continue;
2263 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002264
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002265 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002266 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002267 return false;
2268 }
2269 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002270 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002271 }
2272
2273 // Make a temporary TransportDescription based on |session_td|.
2274 // Some of this gets overwritten by ParseContent.
deadbeef46eed762016-01-28 13:24:37 -08002275 TransportDescription transport(
2276 session_td.transport_options, session_td.ice_ufrag, session_td.ice_pwd,
2277 session_td.ice_mode, session_td.connection_role,
2278 session_td.identity_fingerprint.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002279
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002280 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002281 std::string content_name;
2282 if (HasAttribute(line, kMediaTypeVideo)) {
2283 content.reset(ParseContentDescription<VideoContentDescription>(
2284 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2285 codec_preference, pos, &content_name,
2286 &transport, candidates, error));
2287 } else if (HasAttribute(line, kMediaTypeAudio)) {
2288 content.reset(ParseContentDescription<AudioContentDescription>(
2289 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2290 codec_preference, pos, &content_name,
2291 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002292 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002293 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002294 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002295 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2296 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002297 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002298 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002299
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002300 int p;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002301 if (data_desc && IsDtlsSctp(protocol) && rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002302 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002303 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002304 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002305 } else {
2306 LOG(LS_WARNING) << "Unsupported media type: " << line;
2307 continue;
2308 }
2309 if (!content.get()) {
2310 // ParseContentDescription returns NULL if failed.
2311 return false;
2312 }
2313
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002314 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002315 // Set the extmap.
2316 if (!session_extmaps.empty() &&
2317 !content->rtp_header_extensions().empty()) {
2318 return ParseFailed("",
2319 "The a=extmap MUST be either all session level or "
2320 "all media level.",
2321 error);
2322 }
2323 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2324 content->AddRtpHeaderExtension(session_extmaps[i]);
2325 }
2326 }
2327 content->set_protocol(protocol);
2328 desc->AddContent(content_name,
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002329 IsDtlsSctp(protocol) ? cricket::NS_JINGLE_DRAFT_SCTP :
2330 cricket::NS_JINGLE_RTP,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002331 rejected,
2332 content.release());
2333 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2334 TransportInfo transport_info(content_name, transport);
2335
2336 if (!desc->AddTransportInfo(transport_info)) {
2337 std::ostringstream description;
2338 description << "Failed to AddTransportInfo with content name: "
2339 << content_name;
2340 return ParseFailed("", description.str(), error);
2341 }
2342 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002343
2344 size_t end_of_message = message.size();
2345 if (mline_index == -1 && *pos != end_of_message) {
2346 ParseFailed(message, *pos, "Expects m line.", error);
2347 return false;
2348 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002349 return true;
2350}
2351
2352bool VerifyCodec(const cricket::Codec& codec) {
2353 // Codec has not been populated correctly unless the name has been set. This
2354 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2355 // have a corresponding "rtpmap" line.
2356 cricket::Codec default_codec;
2357 return default_codec.name != codec.name;
2358}
2359
2360bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2361 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2362 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2363 iter != codecs.end(); ++iter) {
2364 if (!VerifyCodec(*iter)) {
2365 return false;
2366 }
2367 }
2368 return true;
2369}
2370
2371bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2372 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2373 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2374 iter != codecs.end(); ++iter) {
2375 if (!VerifyCodec(*iter)) {
2376 return false;
2377 }
2378 }
2379 return true;
2380}
2381
2382void AddParameters(const cricket::CodecParameterMap& parameters,
2383 cricket::Codec* codec) {
2384 for (cricket::CodecParameterMap::const_iterator iter =
2385 parameters.begin(); iter != parameters.end(); ++iter) {
2386 codec->SetParam(iter->first, iter->second);
2387 }
2388}
2389
2390void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2391 cricket::Codec* codec) {
2392 codec->AddFeedbackParam(feedback_param);
2393}
2394
2395void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2396 cricket::Codec* codec) {
2397 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2398 feedback_params.params().begin();
2399 iter != feedback_params.params().end(); ++iter) {
2400 codec->AddFeedbackParam(*iter);
2401 }
2402}
2403
2404// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002405// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002406// with that payload type.
2407template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002408T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2409 T ret_val;
2410 if (!FindCodecById(codecs, payload_type, &ret_val)) {
2411 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002412 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002413 return ret_val;
2414}
2415
2416// Updates or creates a new codec entry in the audio description.
2417template <class T, class U>
2418void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2419 T* desc = static_cast<T*>(content_desc);
2420 std::vector<U> codecs = desc->codecs();
2421 bool found = false;
2422
2423 typename std::vector<U>::iterator iter;
2424 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2425 if (iter->id == codec.id) {
2426 *iter = codec;
2427 found = true;
2428 break;
2429 }
2430 }
2431 if (!found) {
2432 desc->AddCodec(codec);
2433 return;
2434 }
2435 desc->set_codecs(codecs);
2436}
2437
2438// Adds or updates existing codec corresponding to |payload_type| according
2439// to |parameters|.
2440template <class T, class U>
2441void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2442 const cricket::CodecParameterMap& parameters) {
2443 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002444 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2445 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002446 AddParameters(parameters, &new_codec);
2447 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2448}
2449
2450// Adds or updates existing codec corresponding to |payload_type| according
2451// to |feedback_param|.
2452template <class T, class U>
2453void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2454 const cricket::FeedbackParam& feedback_param) {
2455 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002456 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2457 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002458 AddFeedbackParameter(feedback_param, &new_codec);
2459 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2460}
2461
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002462template <class T>
2463bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2464 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002465 if (iter->id == kWildcardPayloadType) {
2466 *wildcard_codec = *iter;
2467 codecs->erase(iter);
2468 return true;
2469 }
2470 }
2471 return false;
2472}
2473
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002474template<class T>
2475void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2476 auto codecs = desc->codecs();
2477 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002478 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2479 return;
2480 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002481 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002482 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2483 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002484 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002485}
2486
2487void AddAudioAttribute(const std::string& name, const std::string& value,
2488 AudioContentDescription* audio_desc) {
2489 if (value.empty()) {
2490 return;
2491 }
2492 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2493 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2494 iter != codecs.end(); ++iter) {
2495 iter->params[name] = value;
2496 }
2497 audio_desc->set_codecs(codecs);
2498}
2499
2500bool ParseContent(const std::string& message,
2501 const MediaType media_type,
2502 int mline_index,
2503 const std::string& protocol,
2504 const std::vector<int>& codec_preference,
2505 size_t* pos,
2506 std::string* content_name,
2507 MediaContentDescription* media_desc,
2508 TransportDescription* transport,
2509 std::vector<JsepIceCandidate*>* candidates,
2510 SdpParseError* error) {
2511 ASSERT(media_desc != NULL);
2512 ASSERT(content_name != NULL);
2513 ASSERT(transport != NULL);
2514
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002515 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2516 MaybeCreateStaticPayloadAudioCodecs(
2517 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2518 }
2519
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002520 // The media level "ice-ufrag" and "ice-pwd".
2521 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2522 Candidates candidates_orig;
2523 std::string line;
2524 std::string mline_id;
2525 // Tracks created out of the ssrc attributes.
2526 StreamParamsVec tracks;
2527 SsrcInfoVec ssrc_infos;
2528 SsrcGroupVec ssrc_groups;
2529 std::string maxptime_as_string;
2530 std::string ptime_as_string;
deadbeef9d3584c2016-02-16 17:54:10 -08002531 std::string stream_id;
2532 std::string track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002533
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002534 // Loop until the next m line
2535 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2536 if (!GetLine(message, pos, &line)) {
2537 if (*pos >= message.size()) {
2538 break; // Done parsing
2539 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002540 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002541 }
2542 }
2543
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002544 // RFC 4566
2545 // b=* (zero or more bandwidth information lines)
2546 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2547 std::string bandwidth;
2548 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2549 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2550 return false;
2551 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002552 int b = 0;
2553 if (!GetValueFromString(line, bandwidth, &b, error)) {
2554 return false;
2555 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002556 // We should never use more than the default bandwidth for RTP-based
2557 // data channels. Don't allow SDP to set the bandwidth, because
2558 // that would give JS the opportunity to "break the Internet".
2559 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2560 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2561 b > cricket::kDataMaxBandwidth / 1000) {
2562 std::ostringstream description;
2563 description << "RTP-based data channels may not send more than "
2564 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2565 return ParseFailed(line, description.str(), error);
2566 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002567 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002568 }
2569 }
2570 continue;
2571 }
2572
2573 if (!IsLineType(line, kLineTypeAttributes)) {
2574 // TODO: Handle other lines if needed.
2575 LOG(LS_INFO) << "Ignored line: " << line;
2576 continue;
2577 }
2578
2579 // Handle attributes common to SCTP and RTP.
2580 if (HasAttribute(line, kAttributeMid)) {
2581 // RFC 3388
2582 // mid-attribute = "a=mid:" identification-tag
2583 // identification-tag = token
2584 // Use the mid identification-tag as the content name.
2585 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2586 return false;
2587 }
2588 *content_name = mline_id;
2589 } else if (HasAttribute(line, kAttributeCandidate)) {
2590 Candidate candidate;
2591 if (!ParseCandidate(line, &candidate, error, false)) {
2592 return false;
2593 }
2594 candidates_orig.push_back(candidate);
2595 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2596 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2597 return false;
2598 }
2599 } else if (HasAttribute(line, kAttributeIcePwd)) {
2600 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2601 return false;
2602 }
2603 } else if (HasAttribute(line, kAttributeIceOption)) {
2604 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2605 return false;
2606 }
2607 } else if (HasAttribute(line, kAttributeFmtp)) {
2608 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2609 return false;
2610 }
2611 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002612 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613
2614 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2615 return false;
2616 }
2617 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002618 } else if (HasAttribute(line, kAttributeSetup)) {
2619 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2620 return false;
2621 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002622 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002623 int sctp_port;
2624 if (!ParseSctpPort(line, &sctp_port, error)) {
2625 return false;
2626 }
2627 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2628 sctp_port)) {
2629 return false;
2630 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002631 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002632 //
2633 // RTP specific attrubtes
2634 //
2635 if (HasAttribute(line, kAttributeRtcpMux)) {
2636 media_desc->set_rtcp_mux(true);
deadbeef13871492015-12-09 12:37:51 -08002637 } else if (HasAttribute(line, kAttributeRtcpReducedSize)) {
2638 media_desc->set_rtcp_reduced_size(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002639 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2640 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2641 return false;
2642 }
2643 } else if (HasAttribute(line, kAttributeSsrc)) {
2644 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2645 return false;
2646 }
2647 } else if (HasAttribute(line, kAttributeCrypto)) {
2648 if (!ParseCryptoAttribute(line, media_desc, error)) {
2649 return false;
2650 }
2651 } else if (HasAttribute(line, kAttributeRtpmap)) {
2652 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2653 media_desc, error)) {
2654 return false;
2655 }
2656 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2657 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2658 return false;
2659 }
2660 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2661 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2662 return false;
2663 }
2664 } else if (HasAttribute(line, kCodecParamPTime)) {
2665 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2666 return false;
2667 }
2668 } else if (HasAttribute(line, kAttributeSendOnly)) {
2669 media_desc->set_direction(cricket::MD_SENDONLY);
2670 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2671 media_desc->set_direction(cricket::MD_RECVONLY);
2672 } else if (HasAttribute(line, kAttributeInactive)) {
2673 media_desc->set_direction(cricket::MD_INACTIVE);
2674 } else if (HasAttribute(line, kAttributeSendRecv)) {
2675 media_desc->set_direction(cricket::MD_SENDRECV);
2676 } else if (HasAttribute(line, kAttributeExtmap)) {
2677 RtpHeaderExtension extmap;
2678 if (!ParseExtmap(line, &extmap, error)) {
2679 return false;
2680 }
2681 media_desc->AddRtpHeaderExtension(extmap);
2682 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2683 // Experimental attribute. Conference mode activates more aggressive
2684 // AEC and NS settings.
2685 // TODO: expose API to set these directly.
2686 std::string flag_value;
2687 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2688 return false;
2689 }
2690 if (flag_value.compare(kValueConference) == 0)
2691 media_desc->set_conference_mode(true);
deadbeef9d3584c2016-02-16 17:54:10 -08002692 } else if (HasAttribute(line, kAttributeMsid)) {
2693 if (!ParseMsidAttribute(line, &stream_id, &track_id, error)) {
2694 return false;
2695 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002696 }
2697 } else {
2698 // Only parse lines that we are interested of.
2699 LOG(LS_INFO) << "Ignored line: " << line;
2700 continue;
2701 }
2702 }
2703
2704 // Create tracks from the |ssrc_infos|.
Taylor Brandstetter5de6b752016-03-09 17:02:30 -08002705 // If the stream_id/track_id for all SSRCS are identical, one StreamParams
2706 // will be created in CreateTracksFromSsrcInfos, containing all the SSRCs from
2707 // the m= section.
2708 CreateTracksFromSsrcInfos(ssrc_infos, stream_id, track_id, &tracks);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002709
2710 // Add the ssrc group to the track.
2711 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2712 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2713 if (ssrc_group->ssrcs.empty()) {
2714 continue;
2715 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002716 uint32_t ssrc = ssrc_group->ssrcs.front();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002717 for (StreamParamsVec::iterator track = tracks.begin();
2718 track != tracks.end(); ++track) {
2719 if (track->has_ssrc(ssrc)) {
2720 track->ssrc_groups.push_back(*ssrc_group);
2721 }
2722 }
2723 }
2724
2725 // Add the new tracks to the |media_desc|.
deadbeef9d3584c2016-02-16 17:54:10 -08002726 for (StreamParams& track : tracks) {
2727 media_desc->AddStream(track);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002728 }
2729
2730 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2731 AudioContentDescription* audio_desc =
2732 static_cast<AudioContentDescription*>(media_desc);
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002733 UpdateFromWildcardCodecs(audio_desc);
2734
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002735 // Verify audio codec ensures that no audio codec has been populated with
2736 // only fmtp.
2737 if (!VerifyAudioCodecs(audio_desc)) {
2738 return ParseFailed("Failed to parse audio codecs correctly.", error);
2739 }
2740 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2741 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2742 }
2743
2744 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002745 VideoContentDescription* video_desc =
2746 static_cast<VideoContentDescription*>(media_desc);
2747 UpdateFromWildcardCodecs(video_desc);
2748 // Verify video codec ensures that no video codec has been populated with
2749 // only rtcp-fb.
2750 if (!VerifyVideoCodecs(video_desc)) {
2751 return ParseFailed("Failed to parse video codecs correctly.", error);
2752 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002753 }
2754
2755 // RFC 5245
2756 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2757 for (Candidates::iterator it = candidates_orig.begin();
2758 it != candidates_orig.end(); ++it) {
honghaiza54a0802015-12-16 18:37:23 -08002759 ASSERT((*it).username().empty() ||
2760 (*it).username() == transport->ice_ufrag);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002761 (*it).set_username(transport->ice_ufrag);
2762 ASSERT((*it).password().empty());
2763 (*it).set_password(transport->ice_pwd);
2764 candidates->push_back(
2765 new JsepIceCandidate(mline_id, mline_index, *it));
2766 }
2767 return true;
2768}
2769
2770bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2771 SdpParseError* error) {
2772 ASSERT(ssrc_infos != NULL);
2773 // RFC 5576
2774 // a=ssrc:<ssrc-id> <attribute>
2775 // a=ssrc:<ssrc-id> <attribute>:<value>
2776 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07002777 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2778 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002779 const size_t expected_fields = 2;
2780 return ParseFailedExpectFieldNum(line, expected_fields, error);
2781 }
2782
2783 // ssrc:<ssrc-id>
2784 std::string ssrc_id_s;
2785 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2786 return false;
2787 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002788 uint32_t ssrc_id = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002789 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2790 return false;
2791 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002792
2793 std::string attribute;
2794 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07002795 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002796 std::ostringstream description;
2797 description << "Failed to get the ssrc attribute value from " << field2
2798 << ". Expected format <attribute>:<value>.";
2799 return ParseFailed(line, description.str(), error);
2800 }
2801
2802 // Check if there's already an item for this |ssrc_id|. Create a new one if
2803 // there isn't.
2804 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2805 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2806 if (ssrc_info->ssrc_id == ssrc_id) {
2807 break;
2808 }
2809 }
2810 if (ssrc_info == ssrc_infos->end()) {
2811 SsrcInfo info;
2812 info.ssrc_id = ssrc_id;
2813 ssrc_infos->push_back(info);
2814 ssrc_info = ssrc_infos->end() - 1;
2815 }
2816
2817 // Store the info to the |ssrc_info|.
2818 if (attribute == kSsrcAttributeCname) {
2819 // RFC 5576
2820 // cname:<value>
2821 ssrc_info->cname = value;
2822 } else if (attribute == kSsrcAttributeMsid) {
2823 // draft-alvestrand-mmusic-msid-00
2824 // "msid:" identifier [ " " appdata ]
2825 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002826 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002827 if (fields.size() < 1 || fields.size() > 2) {
2828 return ParseFailed(line,
2829 "Expected format \"msid:<identifier>[ <appdata>]\".",
2830 error);
2831 }
deadbeef9d3584c2016-02-16 17:54:10 -08002832 ssrc_info->stream_id = fields[0];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002833 if (fields.size() == 2) {
deadbeef9d3584c2016-02-16 17:54:10 -08002834 ssrc_info->track_id = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002835 }
2836 } else if (attribute == kSsrcAttributeMslabel) {
2837 // draft-alvestrand-rtcweb-mid-01
2838 // mslabel:<value>
2839 ssrc_info->mslabel = value;
2840 } else if (attribute == kSSrcAttributeLabel) {
2841 // The label isn't defined.
2842 // label:<value>
2843 ssrc_info->label = value;
2844 }
2845 return true;
2846}
2847
2848bool ParseSsrcGroupAttribute(const std::string& line,
2849 SsrcGroupVec* ssrc_groups,
2850 SdpParseError* error) {
2851 ASSERT(ssrc_groups != NULL);
2852 // RFC 5576
2853 // a=ssrc-group:<semantics> <ssrc-id> ...
2854 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002855 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002856 kSdpDelimiterSpace, &fields);
2857 const size_t expected_min_fields = 2;
2858 if (fields.size() < expected_min_fields) {
2859 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2860 }
2861 std::string semantics;
2862 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2863 return false;
2864 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002865 std::vector<uint32_t> ssrcs;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002866 for (size_t i = 1; i < fields.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02002867 uint32_t ssrc = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002868 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2869 return false;
2870 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002871 ssrcs.push_back(ssrc);
2872 }
2873 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2874 return true;
2875}
2876
2877bool ParseCryptoAttribute(const std::string& line,
2878 MediaContentDescription* media_desc,
2879 SdpParseError* error) {
2880 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002881 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002882 kSdpDelimiterSpace, &fields);
2883 // RFC 4568
2884 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2885 const size_t expected_min_fields = 3;
2886 if (fields.size() < expected_min_fields) {
2887 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2888 }
2889 std::string tag_value;
2890 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2891 return false;
2892 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002893 int tag = 0;
2894 if (!GetValueFromString(line, tag_value, &tag, error)) {
2895 return false;
2896 }
jbauch083b73f2015-07-16 02:46:32 -07002897 const std::string& crypto_suite = fields[1];
2898 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002899 std::string session_params;
2900 if (fields.size() > 3) {
2901 session_params = fields[3];
2902 }
2903 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2904 session_params));
2905 return true;
2906}
2907
2908// Updates or creates a new codec entry in the audio description with according
2909// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2910void UpdateCodec(int payload_type, const std::string& name, int clockrate,
Peter Kasting69558702016-01-12 16:26:35 -08002911 int bitrate, size_t channels, int preference,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002912 AudioContentDescription* audio_desc) {
2913 // Codec may already be populated with (only) optional parameters
2914 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002915 cricket::AudioCodec codec =
2916 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002917 codec.name = name;
2918 codec.clockrate = clockrate;
2919 codec.bitrate = bitrate;
2920 codec.channels = channels;
2921 codec.preference = preference;
2922 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2923 codec);
2924}
2925
2926// Updates or creates a new codec entry in the video description according to
2927// |name|, |width|, |height|, |framerate| and |preference|.
2928void UpdateCodec(int payload_type, const std::string& name, int width,
2929 int height, int framerate, int preference,
2930 VideoContentDescription* video_desc) {
2931 // Codec may already be populated with (only) optional parameters
2932 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002933 cricket::VideoCodec codec =
2934 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002935 codec.name = name;
2936 codec.width = width;
2937 codec.height = height;
2938 codec.framerate = framerate;
2939 codec.preference = preference;
2940 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2941 codec);
2942}
2943
2944bool ParseRtpmapAttribute(const std::string& line,
2945 const MediaType media_type,
2946 const std::vector<int>& codec_preference,
2947 MediaContentDescription* media_desc,
2948 SdpParseError* error) {
2949 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002950 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002951 kSdpDelimiterSpace, &fields);
2952 // RFC 4566
2953 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2954 const size_t expected_min_fields = 2;
2955 if (fields.size() < expected_min_fields) {
2956 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2957 }
2958 std::string payload_type_value;
2959 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2960 return false;
2961 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002962 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002963 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
2964 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002965 return false;
2966 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002967
2968 // Set the preference order depending on the order of the pl type in the
2969 // <fmt> of the m-line.
2970 const int preference = codec_preference.end() -
2971 std::find(codec_preference.begin(), codec_preference.end(),
2972 payload_type);
2973 if (preference == 0) {
2974 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2975 << "<fmt> of the m-line: " << line;
2976 return true;
2977 }
jbauch083b73f2015-07-16 02:46:32 -07002978 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002979 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002980 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002981 // <encoding name>/<clock rate>[/<encodingparameters>]
2982 // 2 mandatory fields
2983 if (codec_params.size() < 2 || codec_params.size() > 3) {
2984 return ParseFailed(line,
2985 "Expected format \"<encoding name>/<clock rate>"
2986 "[/<encodingparameters>]\".",
2987 error);
2988 }
jbauch083b73f2015-07-16 02:46:32 -07002989 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002990 int clock_rate = 0;
2991 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2992 return false;
2993 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002994 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2995 VideoContentDescription* video_desc =
2996 static_cast<VideoContentDescription*>(media_desc);
2997 // TODO: We will send resolution in SDP. For now use
2998 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2999 UpdateCodec(payload_type, encoding_name,
3000 JsepSessionDescription::kMaxVideoCodecWidth,
3001 JsepSessionDescription::kMaxVideoCodecHeight,
3002 JsepSessionDescription::kDefaultVideoCodecFramerate,
3003 preference, video_desc);
3004 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3005 // RFC 4566
3006 // For audio streams, <encoding parameters> indicates the number
3007 // of audio channels. This parameter is OPTIONAL and may be
3008 // omitted if the number of channels is one, provided that no
3009 // additional parameters are needed.
Peter Kasting69558702016-01-12 16:26:35 -08003010 size_t channels = 1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003011 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003012 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
3013 return false;
3014 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003015 }
3016 int bitrate = 0;
3017 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
3018 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
3019 // The bandwidth adaptation doesn't always work well, so this code
3020 // sets a fixed target bitrate instead.
3021 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
3022 if (clock_rate <= 16000) {
3023 bitrate = kIsacWbDefaultRate;
3024 } else {
3025 bitrate = kIsacSwbDefaultRate;
3026 }
3027 }
3028 AudioContentDescription* audio_desc =
3029 static_cast<AudioContentDescription*>(media_desc);
3030 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
3031 preference, audio_desc);
3032 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
3033 DataContentDescription* data_desc =
3034 static_cast<DataContentDescription*>(media_desc);
3035 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
3036 preference));
3037 }
3038 return true;
3039}
3040
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003041bool ParseFmtpParam(const std::string& line, std::string* parameter,
3042 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003043 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003044 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
3045 return false;
3046 }
3047 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003048 return true;
3049}
3050
3051bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
3052 MediaContentDescription* media_desc,
3053 SdpParseError* error) {
3054 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3055 media_type != cricket::MEDIA_TYPE_VIDEO) {
3056 return true;
3057 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003058
3059 std::string line_payload;
3060 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003061
3062 // RFC 5576
3063 // a=fmtp:<format> <format specific parameters>
3064 // At least two fields, whereas the second one is any of the optional
3065 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07003066 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
3067 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003068 ParseFailedExpectMinFieldNum(line, 2, error);
3069 return false;
3070 }
3071
Donald Curtis0e07f922015-05-15 09:21:23 -07003072 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003073 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07003074 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003075 return false;
3076 }
3077
Donald Curtis0e07f922015-05-15 09:21:23 -07003078 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07003079 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3080 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003081 return false;
3082 }
3083
3084 // Parse out format specific parameters.
3085 std::vector<std::string> fields;
3086 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
3087
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003088 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07003089 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003090 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003091 // Only fmtps with equals are currently supported. Other fmtp types
3092 // should be ignored. Unknown fmtps do not constitute an error.
3093 continue;
3094 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003095
3096 std::string name;
3097 std::string value;
3098 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003099 return false;
3100 }
3101 codec_params[name] = value;
3102 }
3103
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003104 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3105 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003106 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003107 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3108 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003109 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003110 }
3111 return true;
3112}
3113
3114bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3115 MediaContentDescription* media_desc,
3116 SdpParseError* error) {
3117 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3118 media_type != cricket::MEDIA_TYPE_VIDEO) {
3119 return true;
3120 }
3121 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003122 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003123 if (rtcp_fb_fields.size() < 2) {
3124 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3125 }
3126 std::string payload_type_string;
3127 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3128 error)) {
3129 return false;
3130 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003131 int payload_type = kWildcardPayloadType;
3132 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003133 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3134 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003135 return false;
3136 }
3137 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138 std::string id = rtcp_fb_fields[1];
3139 std::string param = "";
3140 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3141 iter != rtcp_fb_fields.end(); ++iter) {
3142 param.append(*iter);
3143 }
3144 const cricket::FeedbackParam feedback_param(id, param);
3145
3146 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003147 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3148 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003149 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003150 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3151 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003152 }
3153 return true;
3154}
3155
3156} // namespace webrtc