blob: a0887a6f78e6604162bb33501d091743f12d499f [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/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>
kwibergd1fe2812016-04-27 06:47:29 -070016
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017#include <algorithm>
Steve Anton36b29d12017-10-30 09:57:42 -070018#include <map>
kwibergd1fe2812016-04-27 06:47:29 -070019#include <memory>
Steve Anton36b29d12017-10-30 09:57:42 -070020#include <set>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000021#include <string>
deadbeef67cf2c12016-04-13 10:07:16 -070022#include <unordered_map>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000023#include <vector>
24
Patrik Höglunde2d6a062017-10-05 14:53:33 +020025#include "api/candidate.h"
Patrik Höglund7aee3d52017-11-15 13:15:17 +010026#include "api/cryptoparams.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "api/jsepicecandidate.h"
28#include "api/jsepsessiondescription.h"
isheriff6f8d6862016-05-26 11:24:55 -070029// for RtpExtension
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "api/rtpparameters.h"
31#include "media/base/codec.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "media/base/mediaconstants.h"
33#include "media/base/rtputils.h"
34#include "media/sctp/sctptransportinternal.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "p2p/base/p2pconstants.h"
36#include "p2p/base/port.h"
37#include "pc/mediasession.h"
38#include "rtc_base/arraysize.h"
39#include "rtc_base/checks.h"
40#include "rtc_base/logging.h"
41#include "rtc_base/messagedigest.h"
42#include "rtc_base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000043
44using cricket::AudioContentDescription;
45using cricket::Candidate;
46using cricket::Candidates;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000047using cricket::ContentInfo;
48using cricket::CryptoParams;
49using cricket::DataContentDescription;
50using cricket::ICE_CANDIDATE_COMPONENT_RTP;
51using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
52using cricket::kCodecParamMaxBitrate;
53using cricket::kCodecParamMaxPTime;
54using cricket::kCodecParamMaxQuantization;
55using cricket::kCodecParamMinBitrate;
56using cricket::kCodecParamMinPTime;
57using cricket::kCodecParamPTime;
58using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000059using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060using cricket::kCodecParamStereo;
61using cricket::kCodecParamUseInbandFec;
Minyue Li7100dcd2015-03-27 05:05:59 +010062using cricket::kCodecParamUseDtx;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063using cricket::kCodecParamSctpProtocol;
64using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000065using cricket::kCodecParamMaxAverageBitrate;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000066using cricket::kCodecParamMaxPlaybackRate;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000067using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000068using cricket::MediaContentDescription;
69using cricket::MediaType;
isheriff6f8d6862016-05-26 11:24:55 -070070using cricket::RtpHeaderExtensions;
Steve Anton5adfafd2017-12-20 16:34:00 -080071using cricket::MediaProtocolType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072using cricket::SsrcGroup;
73using cricket::StreamParams;
74using cricket::StreamParamsVec;
75using cricket::TransportDescription;
76using cricket::TransportInfo;
77using cricket::VideoContentDescription;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000078using rtc::SocketAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000079
henrike@webrtc.org28e20752013-07-10 00:45:36 +000080namespace cricket {
81class SessionDescription;
82}
83
deadbeef90f1e1e2017-02-10 12:35:05 -080084// TODO(deadbeef): Switch to using anonymous namespace rather than declaring
85// everything "static".
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086namespace webrtc {
87
88// Line type
89// RFC 4566
90// An SDP session description consists of a number of lines of text of
91// the form:
92// <type>=<value>
93// where <type> MUST be exactly one case-significant character.
deadbeef9d3584c2016-02-16 17:54:10 -080094static const int kLinePrefixLength = 2; // Length of <type>=
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095static const char kLineTypeVersion = 'v';
96static const char kLineTypeOrigin = 'o';
97static const char kLineTypeSessionName = 's';
98static const char kLineTypeSessionInfo = 'i';
99static const char kLineTypeSessionUri = 'u';
100static const char kLineTypeSessionEmail = 'e';
101static const char kLineTypeSessionPhone = 'p';
102static const char kLineTypeSessionBandwidth = 'b';
103static const char kLineTypeTiming = 't';
104static const char kLineTypeRepeatTimes = 'r';
105static const char kLineTypeTimeZone = 'z';
106static const char kLineTypeEncryptionKey = 'k';
107static const char kLineTypeMedia = 'm';
108static const char kLineTypeConnection = 'c';
109static const char kLineTypeAttributes = 'a';
110
111// Attributes
112static const char kAttributeGroup[] = "group";
113static const char kAttributeMid[] = "mid";
deadbeef9d3584c2016-02-16 17:54:10 -0800114static const char kAttributeMsid[] = "msid";
deadbeef25ed4352016-12-12 18:37:36 -0800115static const char kAttributeBundleOnly[] = "bundle-only";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116static const char kAttributeRtcpMux[] = "rtcp-mux";
deadbeef13871492015-12-09 12:37:51 -0800117static const char kAttributeRtcpReducedSize[] = "rtcp-rsize";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118static const char kAttributeSsrc[] = "ssrc";
119static const char kSsrcAttributeCname[] = "cname";
120static const char kAttributeExtmap[] = "extmap";
121// draft-alvestrand-mmusic-msid-01
122// a=msid-semantic: WMS
Seth Hampson5b4f0752018-04-02 16:31:36 -0700123// This is a legacy field supported only for Plan B semantics.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000124static const char kAttributeMsidSemantics[] = "msid-semantic";
125static const char kMediaStreamSemantic[] = "WMS";
126static const char kSsrcAttributeMsid[] = "msid";
127static const char kDefaultMsid[] = "default";
Seth Hampson5b4f0752018-04-02 16:31:36 -0700128static const char kNoStreamMsid[] = "-";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000129static const char kSsrcAttributeMslabel[] = "mslabel";
130static const char kSSrcAttributeLabel[] = "label";
131static const char kAttributeSsrcGroup[] = "ssrc-group";
132static const char kAttributeCrypto[] = "crypto";
133static const char kAttributeCandidate[] = "candidate";
134static const char kAttributeCandidateTyp[] = "typ";
135static const char kAttributeCandidateRaddr[] = "raddr";
136static const char kAttributeCandidateRport[] = "rport";
honghaiza54a0802015-12-16 18:37:23 -0800137static const char kAttributeCandidateUfrag[] = "ufrag";
138static const char kAttributeCandidatePwd[] = "pwd";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000139static const char kAttributeCandidateGeneration[] = "generation";
honghaiza0c44ea2016-03-23 16:07:48 -0700140static const char kAttributeCandidateNetworkId[] = "network-id";
honghaize1a0c942016-02-16 14:54:56 -0800141static const char kAttributeCandidateNetworkCost[] = "network-cost";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000142static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000143static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000144static const char kAttributeFmtp[] = "fmtp";
145static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000146static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000147static const char kAttributeRtcp[] = "rtcp";
148static const char kAttributeIceUfrag[] = "ice-ufrag";
149static const char kAttributeIcePwd[] = "ice-pwd";
150static const char kAttributeIceLite[] = "ice-lite";
151static const char kAttributeIceOption[] = "ice-options";
152static const char kAttributeSendOnly[] = "sendonly";
153static const char kAttributeRecvOnly[] = "recvonly";
154static const char kAttributeRtcpFb[] = "rtcp-fb";
155static const char kAttributeSendRecv[] = "sendrecv";
156static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000157// draft-ietf-mmusic-sctp-sdp-07
158// a=sctp-port
159static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000160
161// Experimental flags
162static const char kAttributeXGoogleFlag[] = "x-google-flag";
163static const char kValueConference[] = "conference";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000164
165// Candidate
166static const char kCandidateHost[] = "host";
167static const char kCandidateSrflx[] = "srflx";
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700168static const char kCandidatePrflx[] = "prflx";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000169static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000170static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000171
172static const char kSdpDelimiterEqual = '=';
173static const char kSdpDelimiterSpace = ' ';
174static const char kSdpDelimiterColon = ':';
175static const char kSdpDelimiterSemicolon = ';';
176static const char kSdpDelimiterSlash = '/';
177static const char kNewLine = '\n';
178static const char kReturn = '\r';
179static const char kLineBreak[] = "\r\n";
180
Steve Anton36b29d12017-10-30 09:57:42 -0700181// TODO(deadbeef): Generate the Session and Time description
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000182// instead of hardcoding.
183static const char kSessionVersion[] = "v=0";
184// RFC 4566
185static const char kSessionOriginUsername[] = "-";
186static const char kSessionOriginSessionId[] = "0";
187static const char kSessionOriginSessionVersion[] = "0";
188static const char kSessionOriginNettype[] = "IN";
189static const char kSessionOriginAddrtype[] = "IP4";
190static const char kSessionOriginAddress[] = "127.0.0.1";
191static const char kSessionName[] = "s=-";
192static const char kTimeDescription[] = "t=0 0";
193static const char kAttrGroup[] = "a=group:BUNDLE";
194static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000195static const char kConnectionIpv4Addrtype[] = "IP4";
196static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000197static const char kMediaTypeVideo[] = "video";
198static const char kMediaTypeAudio[] = "audio";
199static const char kMediaTypeData[] = "application";
200static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000201// draft-ietf-mmusic-trickle-ice-01
202// When no candidates have been gathered, set the connection
203// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000204// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
205// Use IPV4 per default.
206static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000207static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000208// RFC 3556
209static const char kApplicationSpecificMaximum[] = "AS";
210
wu@webrtc.org78187522013-10-07 23:32:02 +0000211static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000212
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000213// RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
214// types.
215const int kWildcardPayloadType = -1;
216
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000217struct SsrcInfo {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200218 uint32_t ssrc_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000219 std::string cname;
deadbeef9d3584c2016-02-16 17:54:10 -0800220 std::string stream_id;
221 std::string track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000222
223 // For backward compatibility.
224 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
225 std::string label;
226 std::string mslabel;
227};
228typedef std::vector<SsrcInfo> SsrcInfoVec;
229typedef std::vector<SsrcGroup> SsrcGroupVec;
230
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000231template <class T>
232static void AddFmtpLine(const T& codec, std::string* message);
233static void BuildMediaDescription(const ContentInfo* content_info,
234 const TransportInfo* transport_info,
235 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000236 const std::vector<Candidate>& candidates,
Steve Antone831b8c2018-02-01 12:22:16 -0800237 int msid_signaling,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000238 std::string* message);
zstein4b2e0822017-02-17 19:48:38 -0800239static void BuildSctpContentAttributes(std::string* message,
240 int sctp_port,
241 bool use_sctpmap);
deadbeef9d3584c2016-02-16 17:54:10 -0800242static void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
243 const MediaType media_type,
Steve Antone831b8c2018-02-01 12:22:16 -0800244 int msid_signaling,
deadbeef9d3584c2016-02-16 17:54:10 -0800245 std::string* message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000246static void BuildRtpMap(const MediaContentDescription* media_desc,
247 const MediaType media_type,
248 std::string* message);
249static void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -0800250 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000251 std::string* message);
252static void BuildIceOptions(const std::vector<std::string>& transport_options,
253 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000254static bool IsRtp(const std::string& protocol);
255static bool IsDtlsSctp(const std::string& protocol);
zhihuang38989e52017-03-21 11:04:53 -0700256static bool ParseSessionDescription(const std::string& message,
257 size_t* pos,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258 std::string* session_id,
259 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000260 TransportDescription* session_td,
261 RtpHeaderExtensions* session_extmaps,
zhihuang38989e52017-03-21 11:04:53 -0700262 rtc::SocketAddress* connection_addr,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000263 cricket::SessionDescription* desc,
264 SdpParseError* error);
265static bool ParseGroupAttribute(const std::string& line,
266 cricket::SessionDescription* desc,
267 SdpParseError* error);
268static bool ParseMediaDescription(
269 const std::string& message,
270 const TransportDescription& session_td,
271 const RtpHeaderExtensions& session_extmaps,
zhihuang38989e52017-03-21 11:04:53 -0700272 size_t* pos,
273 const rtc::SocketAddress& session_connection_addr,
274 cricket::SessionDescription* desc,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000275 std::vector<JsepIceCandidate*>* candidates,
276 SdpParseError* error);
277static bool ParseContent(const std::string& message,
278 const MediaType media_type,
279 int mline_index,
280 const std::string& protocol,
deadbeef67cf2c12016-04-13 10:07:16 -0700281 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000282 size_t* pos,
283 std::string* content_name,
deadbeef25ed4352016-12-12 18:37:36 -0800284 bool* bundle_only,
Steve Antone831b8c2018-02-01 12:22:16 -0800285 int* msid_signaling,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000286 MediaContentDescription* media_desc,
287 TransportDescription* transport,
288 std::vector<JsepIceCandidate*>* candidates,
289 SdpParseError* error);
290static bool ParseSsrcAttribute(const std::string& line,
291 SsrcInfoVec* ssrc_infos,
Steve Antone831b8c2018-02-01 12:22:16 -0800292 int* msid_signaling,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000293 SdpParseError* error);
294static bool ParseSsrcGroupAttribute(const std::string& line,
295 SsrcGroupVec* ssrc_groups,
296 SdpParseError* error);
297static bool ParseCryptoAttribute(const std::string& line,
298 MediaContentDescription* media_desc,
299 SdpParseError* error);
300static bool ParseRtpmapAttribute(const std::string& line,
301 const MediaType media_type,
deadbeef67cf2c12016-04-13 10:07:16 -0700302 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000303 MediaContentDescription* media_desc,
304 SdpParseError* error);
305static bool ParseFmtpAttributes(const std::string& line,
306 const MediaType media_type,
307 MediaContentDescription* media_desc,
308 SdpParseError* error);
309static bool ParseFmtpParam(const std::string& line, std::string* parameter,
310 std::string* value, SdpParseError* error);
311static bool ParseCandidate(const std::string& message, Candidate* candidate,
312 SdpParseError* error, bool is_raw);
313static bool ParseRtcpFbAttribute(const std::string& line,
314 const MediaType media_type,
315 MediaContentDescription* media_desc,
316 SdpParseError* error);
317static bool ParseIceOptions(const std::string& line,
318 std::vector<std::string>* transport_options,
319 SdpParseError* error);
320static bool ParseExtmap(const std::string& line,
isheriff6f8d6862016-05-26 11:24:55 -0700321 RtpExtension* extmap,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000322 SdpParseError* error);
323static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000324 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000325 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000326static bool ParseDtlsSetup(const std::string& line,
327 cricket::ConnectionRole* role,
328 SdpParseError* error);
deadbeef9d3584c2016-02-16 17:54:10 -0800329static bool ParseMsidAttribute(const std::string& line,
Seth Hampson5b4f0752018-04-02 16:31:36 -0700330 std::vector<std::string>* stream_ids,
deadbeef9d3584c2016-02-16 17:54:10 -0800331 std::string* track_id,
332 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000333
334// Helper functions
335
336// Below ParseFailed*** functions output the line that caused the parsing
337// failure and the detailed reason (|description|) of the failure to |error|.
338// The functions always return false so that they can be used directly in the
339// following way when error happens:
340// "return ParseFailed***(...);"
341
342// The line starting at |line_start| of |message| is the failing line.
343// The reason for the failure should be provided in the |description|.
344// An example of a description could be "unknown character".
345static bool ParseFailed(const std::string& message,
346 size_t line_start,
347 const std::string& description,
348 SdpParseError* error) {
349 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000350 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000351 size_t line_end = message.find(kNewLine, line_start);
352 if (line_end != std::string::npos) {
353 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
354 --line_end;
355 }
356 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000357 } else {
358 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000359 }
360
361 if (error) {
362 error->line = first_line;
363 error->description = description;
364 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100365 RTC_LOG(LS_ERROR) << "Failed to parse: \"" << first_line
366 << "\". Reason: " << description;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000367 return false;
368}
369
370// |line| is the failing line. The reason for the failure should be
371// provided in the |description|.
372static bool ParseFailed(const std::string& line,
373 const std::string& description,
374 SdpParseError* error) {
375 return ParseFailed(line, 0, description, error);
376}
377
378// Parses failure where the failing SDP line isn't know or there are multiple
379// failing lines.
380static bool ParseFailed(const std::string& description,
381 SdpParseError* error) {
382 return ParseFailed("", description, error);
383}
384
385// |line| is the failing line. The failure is due to the fact that |line|
386// doesn't have |expected_fields| fields.
387static bool ParseFailedExpectFieldNum(const std::string& line,
388 int expected_fields,
389 SdpParseError* error) {
390 std::ostringstream description;
391 description << "Expects " << expected_fields << " fields.";
392 return ParseFailed(line, description.str(), error);
393}
394
395// |line| is the failing line. The failure is due to the fact that |line| has
396// less than |expected_min_fields| fields.
397static bool ParseFailedExpectMinFieldNum(const std::string& line,
398 int expected_min_fields,
399 SdpParseError* error) {
400 std::ostringstream description;
401 description << "Expects at least " << expected_min_fields << " fields.";
402 return ParseFailed(line, description.str(), error);
403}
404
405// |line| is the failing line. The failure is due to the fact that it failed to
406// get the value of |attribute|.
407static bool ParseFailedGetValue(const std::string& line,
408 const std::string& attribute,
409 SdpParseError* error) {
410 std::ostringstream description;
411 description << "Failed to get the value of attribute: " << attribute;
412 return ParseFailed(line, description.str(), error);
413}
414
415// The line starting at |line_start| of |message| is the failing line. The
416// failure is due to the line type (e.g. the "m" part of the "m-line")
417// not matching what is expected. The expected line type should be
418// provided as |line_type|.
419static bool ParseFailedExpectLine(const std::string& message,
420 size_t line_start,
421 const char line_type,
422 const std::string& line_value,
423 SdpParseError* error) {
424 std::ostringstream description;
425 description << "Expect line: " << line_type << "=" << line_value;
426 return ParseFailed(message, line_start, description.str(), error);
427}
428
429static bool AddLine(const std::string& line, std::string* message) {
430 if (!message)
431 return false;
432
433 message->append(line);
434 message->append(kLineBreak);
435 return true;
436}
437
438static bool GetLine(const std::string& message,
439 size_t* pos,
440 std::string* line) {
441 size_t line_begin = *pos;
442 size_t line_end = message.find(kNewLine, line_begin);
443 if (line_end == std::string::npos) {
444 return false;
445 }
446 // Update the new start position
447 *pos = line_end + 1;
448 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
449 --line_end;
450 }
451 *line = message.substr(line_begin, (line_end - line_begin));
452 const char* cline = line->c_str();
453 // RFC 4566
454 // An SDP session description consists of a number of lines of text of
455 // the form:
456 // <type>=<value>
457 // where <type> MUST be exactly one case-significant character and
458 // <value> is structured text whose format depends on <type>.
459 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000460 if (line->length() < 3 ||
461 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000462 cline[1] != kSdpDelimiterEqual ||
463 cline[2] == kSdpDelimiterSpace) {
464 *pos = line_begin;
465 return false;
466 }
467 return true;
468}
469
470// Init |os| to "|type|=|value|".
471static void InitLine(const char type,
472 const std::string& value,
473 std::ostringstream* os) {
474 os->str("");
475 *os << type << kSdpDelimiterEqual << value;
476}
477
478// Init |os| to "a=|attribute|".
479static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
480 InitLine(kLineTypeAttributes, attribute, os);
481}
482
483// Writes a SDP attribute line based on |attribute| and |value| to |message|.
484static void AddAttributeLine(const std::string& attribute, int value,
485 std::string* message) {
486 std::ostringstream os;
487 InitAttrLine(attribute, &os);
488 os << kSdpDelimiterColon << value;
489 AddLine(os.str(), message);
490}
491
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000492static bool IsLineType(const std::string& message,
493 const char type,
494 size_t line_start) {
495 if (message.size() < line_start + kLinePrefixLength) {
496 return false;
497 }
498 const char* cmessage = message.c_str();
499 return (cmessage[line_start] == type &&
500 cmessage[line_start + 1] == kSdpDelimiterEqual);
501}
502
503static bool IsLineType(const std::string& line,
504 const char type) {
505 return IsLineType(line, type, 0);
506}
507
508static bool GetLineWithType(const std::string& message, size_t* pos,
509 std::string* line, const char type) {
510 if (!IsLineType(message, type, *pos)) {
511 return false;
512 }
513
514 if (!GetLine(message, pos, line))
515 return false;
516
517 return true;
518}
519
520static bool HasAttribute(const std::string& line,
521 const std::string& attribute) {
522 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
523}
524
Peter Boström0c4e06b2015-10-07 12:23:21 +0200525static bool AddSsrcLine(uint32_t ssrc_id,
526 const std::string& attribute,
527 const std::string& value,
528 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000529 // RFC 5576
530 // a=ssrc:<ssrc-id> <attribute>:<value>
531 std::ostringstream os;
532 InitAttrLine(kAttributeSsrc, &os);
533 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
534 << attribute << kSdpDelimiterColon << value;
535 return AddLine(os.str(), message);
536}
537
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000538// Get value only from <attribute>:<value>.
539static bool GetValue(const std::string& message, const std::string& attribute,
540 std::string* value, SdpParseError* error) {
541 std::string leftpart;
Donald Curtis0e07f922015-05-15 09:21:23 -0700542 if (!rtc::tokenize_first(message, kSdpDelimiterColon, &leftpart, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000543 return ParseFailedGetValue(message, attribute, error);
544 }
545 // The left part should end with the expected attribute.
546 if (leftpart.length() < attribute.length() ||
547 leftpart.compare(leftpart.length() - attribute.length(),
548 attribute.length(), attribute) != 0) {
549 return ParseFailedGetValue(message, attribute, error);
550 }
551 return true;
552}
553
554static bool CaseInsensitiveFind(std::string str1, std::string str2) {
555 std::transform(str1.begin(), str1.end(), str1.begin(),
556 ::tolower);
557 std::transform(str2.begin(), str2.end(), str2.begin(),
558 ::tolower);
559 return str1.find(str2) != std::string::npos;
560}
561
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000562template <class T>
563static bool GetValueFromString(const std::string& line,
564 const std::string& s,
565 T* t,
566 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000567 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000568 std::ostringstream description;
569 description << "Invalid value: " << s << ".";
570 return ParseFailed(line, description.str(), error);
571 }
572 return true;
573}
574
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000575static bool GetPayloadTypeFromString(const std::string& line,
576 const std::string& s,
577 int* payload_type,
578 SdpParseError* error) {
579 return GetValueFromString(line, s, payload_type, error) &&
580 cricket::IsValidRtpPayloadType(*payload_type);
581}
582
Seth Hampson5b4f0752018-04-02 16:31:36 -0700583// |msid_stream_idss| and |msid_track_id| represent the stream/track ID from the
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800584// "a=msid" attribute, if it exists. They are empty if the attribute does not
585// exist.
Seth Hampson5b4f0752018-04-02 16:31:36 -0700586// TODO(bugs.webrtc.org/7932): Currently we require that an a=ssrc line is
587// signalled in order to add the appropriate stream_ids. Update here to add both
588// StreamParams objects for the a=ssrc msid lines, and add the
589// stream_id/track_id, to the MediaContentDescription for the a=msid lines. This
590// way the logic will get pushed out to peerconnection.cc for interpreting the
591// media stream ids.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000592void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
Seth Hampson5b4f0752018-04-02 16:31:36 -0700593 const std::vector<std::string>& msid_stream_ids,
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800594 const std::string& msid_track_id,
Seth Hampson5b4f0752018-04-02 16:31:36 -0700595 StreamParamsVec* tracks,
596 int msid_signaling) {
nisseede5da42017-01-12 05:15:36 -0800597 RTC_DCHECK(tracks != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000598 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
599 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
600 if (ssrc_info->cname.empty()) {
601 continue;
602 }
603
Seth Hampson5b4f0752018-04-02 16:31:36 -0700604 std::vector<std::string> stream_ids;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000605 std::string track_id;
Seth Hampson5b4f0752018-04-02 16:31:36 -0700606 if (msid_signaling & cricket::kMsidSignalingMediaSection) {
607 // This is the case with Unified Plan SDP msid signaling.
608 stream_ids = msid_stream_ids;
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +0000609 track_id = msid_track_id;
Seth Hampson5b4f0752018-04-02 16:31:36 -0700610 } else if (msid_signaling & cricket::kMsidSignalingSsrcAttribute) {
611 // This is the case with Plan B SDP msid signaling.
612 stream_ids.push_back(ssrc_info->stream_id);
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +0000613 track_id = ssrc_info->track_id;
Seth Hampson5b4f0752018-04-02 16:31:36 -0700614 } else if (!ssrc_info->mslabel.empty()) {
615 // Since there's no a=msid or a=ssrc msid signaling, this is a sdp from
616 // an older version of client that doesn't support msid.
617 // In that case, we use the mslabel and label to construct the track.
618 stream_ids.push_back(ssrc_info->mslabel);
619 track_id = ssrc_info->label;
620 } else {
621 // Since no media streams isn't supported with older SDP signaling, we
622 // use a default a stream id.
623 stream_ids.push_back(kDefaultMsid);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000624 }
Seth Hampson5b4f0752018-04-02 16:31:36 -0700625 // If a track ID wasn't populated from the SSRC attributes OR the
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800626 // msid attribute, use default/random values.
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800627 if (track_id.empty()) {
628 // TODO(ronghuawu): What should we do if the track id doesn't appear?
629 // Create random string (which will be used as track label later)?
630 track_id = rtc::CreateRandomString(8);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000631 }
632
633 StreamParamsVec::iterator track = tracks->begin();
634 for (; track != tracks->end(); ++track) {
635 if (track->id == track_id) {
636 break;
637 }
638 }
639 if (track == tracks->end()) {
640 // If we don't find an existing track, create a new one.
641 tracks->push_back(StreamParams());
642 track = tracks->end() - 1;
643 }
644 track->add_ssrc(ssrc_info->ssrc_id);
645 track->cname = ssrc_info->cname;
Seth Hampson5b4f0752018-04-02 16:31:36 -0700646 track->set_stream_ids(stream_ids);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000647 track->id = track_id;
648 }
649}
650
Seth Hampson845e8782018-03-02 11:34:10 -0800651void GetMediaStreamIds(const ContentInfo* content,
652 std::set<std::string>* labels) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800653 for (const StreamParams& stream_params :
654 content->media_description()->streams()) {
Seth Hampson845e8782018-03-02 11:34:10 -0800655 for (const std::string& stream_id : stream_params.stream_ids()) {
656 labels->insert(stream_id);
Steve Anton5a26a3a2018-02-28 11:38:47 -0800657 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658 }
659}
660
661// RFC 5245
662// It is RECOMMENDED that default candidates be chosen based on the
663// likelihood of those candidates to work with the peer that is being
664// contacted. It is RECOMMENDED that relayed > reflexive > host.
665static const int kPreferenceUnknown = 0;
666static const int kPreferenceHost = 1;
667static const int kPreferenceReflexive = 2;
668static const int kPreferenceRelayed = 3;
669
670static int GetCandidatePreferenceFromType(const std::string& type) {
671 int preference = kPreferenceUnknown;
672 if (type == cricket::LOCAL_PORT_TYPE) {
673 preference = kPreferenceHost;
674 } else if (type == cricket::STUN_PORT_TYPE) {
675 preference = kPreferenceReflexive;
676 } else if (type == cricket::RELAY_PORT_TYPE) {
677 preference = kPreferenceRelayed;
678 } else {
nissec80e7412017-01-11 05:56:46 -0800679 RTC_NOTREACHED();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680 }
681 return preference;
682}
683
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000684// Get ip and port of the default destination from the |candidates| with the
685// given value of |component_id|. The default candidate should be the one most
686// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000687// RFC 5245
688// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
Steve Anton36b29d12017-10-30 09:57:42 -0700689// TODO(deadbeef): Decide the default destination in webrtcsession and
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000690// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000691static void GetDefaultDestination(
692 const std::vector<Candidate>& candidates,
693 int component_id, std::string* port,
694 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000695 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000696 *port = kDummyPort;
697 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000698 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000699 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000700 for (std::vector<Candidate>::const_iterator it = candidates.begin();
701 it != candidates.end(); ++it) {
702 if (it->component() != component_id) {
703 continue;
704 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000705 // Default destination should be UDP only.
706 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707 continue;
708 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000709 const int preference = GetCandidatePreferenceFromType(it->type());
710 const int family = it->address().ipaddr().family();
711 // See if this candidate is more preferable then the current one if it's the
712 // same family. Or if the current family is IPv4 already so we could safely
713 // ignore all IPv6 ones. WebRTC bug 4269.
714 // http://code.google.com/p/webrtc/issues/detail?id=4269
715 if ((preference <= current_preference && current_family == family) ||
716 (current_family == AF_INET && family == AF_INET6)) {
717 continue;
718 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000719 if (family == AF_INET) {
720 addr_type->assign(kConnectionIpv4Addrtype);
721 } else if (family == AF_INET6) {
722 addr_type->assign(kConnectionIpv6Addrtype);
723 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000724 current_preference = preference;
725 current_family = family;
726 *port = it->address().PortAsString();
727 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000729}
730
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000731// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
732static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000733 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
734 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
735 &rtcp_port, &rtcp_ip, &addr_type);
736 // Found default RTCP candidate.
737 // RFC 5245
738 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
739 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000741 // RFC 3605
742 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
743 // connection-address] CRLF
744 std::ostringstream os;
745 InitAttrLine(kAttributeRtcp, &os);
746 os << kSdpDelimiterColon
747 << rtcp_port << " "
748 << kConnectionNettype << " "
749 << addr_type << " "
750 << rtcp_ip;
751 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000752 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753}
754
755// Get candidates according to the mline index from SessionDescriptionInterface.
756static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
757 int mline_index,
758 std::vector<Candidate>* candidates) {
759 if (!candidates) {
760 return;
761 }
762 const IceCandidateCollection* cc = desci.candidates(mline_index);
763 for (size_t i = 0; i < cc->count(); ++i) {
764 const IceCandidateInterface* candidate = cc->at(i);
765 candidates->push_back(candidate->candidate());
766 }
767}
768
deadbeef90f1e1e2017-02-10 12:35:05 -0800769static bool IsValidPort(int port) {
770 return port >= 0 && port <= 65535;
771}
772
Steve Antone831b8c2018-02-01 12:22:16 -0800773std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000774 const cricket::SessionDescription* desc = jdesc.description();
775 if (!desc) {
776 return "";
777 }
778
779 std::string message;
780
781 // Session Description.
782 AddLine(kSessionVersion, &message);
783 // Session Origin
784 // RFC 4566
785 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
786 // <unicast-address>
787 std::ostringstream os;
788 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
jbauch083b73f2015-07-16 02:46:32 -0700789 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000790 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700791 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000792 kSessionOriginSessionVersion : jdesc.session_version();
793 os << " " << session_id << " " << session_version << " "
794 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
795 << kSessionOriginAddress;
796 AddLine(os.str(), &message);
797 AddLine(kSessionName, &message);
798
799 // Time Description.
800 AddLine(kTimeDescription, &message);
801
802 // Group
803 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
804 std::string group_line = kAttrGroup;
805 const cricket::ContentGroup* group =
806 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
nisseede5da42017-01-12 05:15:36 -0800807 RTC_DCHECK(group != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000808 const cricket::ContentNames& content_names = group->content_names();
809 for (cricket::ContentNames::const_iterator it = content_names.begin();
810 it != content_names.end(); ++it) {
811 group_line.append(" ");
812 group_line.append(*it);
813 }
814 AddLine(group_line, &message);
815 }
816
817 // MediaStream semantics
818 InitAttrLine(kAttributeMsidSemantics, &os);
819 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000820
Seth Hampson845e8782018-03-02 11:34:10 -0800821 std::set<std::string> media_stream_ids;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822 const ContentInfo* audio_content = GetFirstAudioContent(desc);
823 if (audio_content)
Seth Hampson845e8782018-03-02 11:34:10 -0800824 GetMediaStreamIds(audio_content, &media_stream_ids);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000825
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826 const ContentInfo* video_content = GetFirstVideoContent(desc);
827 if (video_content)
Seth Hampson845e8782018-03-02 11:34:10 -0800828 GetMediaStreamIds(video_content, &media_stream_ids);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000829
Seth Hampson845e8782018-03-02 11:34:10 -0800830 for (std::set<std::string>::const_iterator it = media_stream_ids.begin();
831 it != media_stream_ids.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832 os << " " << *it;
833 }
834 AddLine(os.str(), &message);
835
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000836 // Preserve the order of the media contents.
837 int mline_index = -1;
838 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
839 it != desc->contents().end(); ++it) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800840 const MediaContentDescription* mdesc = it->media_description();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000841 std::vector<Candidate> candidates;
842 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
deadbeef9d3584c2016-02-16 17:54:10 -0800843 BuildMediaDescription(&*it, desc->GetTransportInfoByName(it->name),
Steve Antone831b8c2018-02-01 12:22:16 -0800844 mdesc->type(), candidates, desc->msid_signaling(),
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000845 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000847 return message;
848}
849
850// Serializes the passed in IceCandidateInterface to a SDP string.
851// candidate - The candidate to be serialized.
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700852std::string SdpSerializeCandidate(const IceCandidateInterface& candidate) {
853 return SdpSerializeCandidate(candidate.candidate());
854}
855
856// Serializes a cricket Candidate.
857std::string SdpSerializeCandidate(const cricket::Candidate& candidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000858 std::string message;
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700859 std::vector<cricket::Candidate> candidates(1, candidate);
honghaiza54a0802015-12-16 18:37:23 -0800860 BuildCandidate(candidates, true, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000861 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
862 // just candidate:<candidate> not a=candidate:<blah>CRLF
nisseede5da42017-01-12 05:15:36 -0800863 RTC_DCHECK(message.find("a=") == 0);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000864 message.erase(0, 2);
nisseede5da42017-01-12 05:15:36 -0800865 RTC_DCHECK(message.find(kLineBreak) == message.size() - 2);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000866 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000867 return message;
868}
869
870bool SdpDeserialize(const std::string& message,
871 JsepSessionDescription* jdesc,
872 SdpParseError* error) {
873 std::string session_id;
874 std::string session_version;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700875 TransportDescription session_td("", "");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000876 RtpHeaderExtensions session_extmaps;
zhihuang38989e52017-03-21 11:04:53 -0700877 rtc::SocketAddress session_connection_addr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000878 cricket::SessionDescription* desc = new cricket::SessionDescription();
879 std::vector<JsepIceCandidate*> candidates;
880 size_t current_pos = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000881
882 // Session Description
883 if (!ParseSessionDescription(message, &current_pos, &session_id,
deadbeefc80741f2015-10-22 13:14:45 -0700884 &session_version, &session_td, &session_extmaps,
zhihuang38989e52017-03-21 11:04:53 -0700885 &session_connection_addr, desc, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886 delete desc;
887 return false;
888 }
889
890 // Media Description
deadbeefc80741f2015-10-22 13:14:45 -0700891 if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
zhihuang38989e52017-03-21 11:04:53 -0700892 session_connection_addr, desc, &candidates,
893 error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000894 delete desc;
895 for (std::vector<JsepIceCandidate*>::const_iterator
896 it = candidates.begin(); it != candidates.end(); ++it) {
897 delete *it;
898 }
899 return false;
900 }
901
902 jdesc->Initialize(desc, session_id, session_version);
903
904 for (std::vector<JsepIceCandidate*>::const_iterator
905 it = candidates.begin(); it != candidates.end(); ++it) {
906 jdesc->AddCandidate(*it);
907 delete *it;
908 }
909 return true;
910}
911
912bool SdpDeserializeCandidate(const std::string& message,
913 JsepIceCandidate* jcandidate,
914 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -0800915 RTC_DCHECK(jcandidate != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000916 Candidate candidate;
917 if (!ParseCandidate(message, &candidate, error, true)) {
918 return false;
919 }
920 jcandidate->SetCandidate(candidate);
921 return true;
922}
923
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700924bool SdpDeserializeCandidate(const std::string& transport_name,
925 const std::string& message,
926 cricket::Candidate* candidate,
927 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -0800928 RTC_DCHECK(candidate != nullptr);
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700929 if (!ParseCandidate(message, candidate, error, true)) {
930 return false;
931 }
932 candidate->set_transport_name(transport_name);
933 return true;
934}
935
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936bool ParseCandidate(const std::string& message, Candidate* candidate,
937 SdpParseError* error, bool is_raw) {
nisseede5da42017-01-12 05:15:36 -0800938 RTC_DCHECK(candidate != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939
940 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000941 std::string first_line = message;
942 size_t pos = 0;
943 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000945 // Makes sure |message| contains only one line.
946 if (message.size() > first_line.size()) {
947 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700948 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
949 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000950 return ParseFailed(message, 0, "Expect one line only", error);
951 }
952 }
953
954 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
955 // candidate:<candidate> when trickled, but we still support
956 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
957 // from the SDP.
958 if (IsLineType(first_line, kLineTypeAttributes)) {
959 first_line = first_line.substr(kLinePrefixLength);
960 }
961
962 std::string attribute_candidate;
963 std::string candidate_value;
964
965 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700966 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
967 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000968 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969 if (is_raw) {
970 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000971 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000972 << ":" << "<candidate-str>";
973 return ParseFailed(first_line, 0, description.str(), error);
974 } else {
975 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
976 kAttributeCandidate, error);
977 }
978 }
979
980 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000981 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
982
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000983 // RFC 5245
984 // a=candidate:<foundation> <component-id> <transport> <priority>
985 // <connection-address> <port> typ <candidate-types>
986 // [raddr <connection-address>] [rport <port>]
987 // *(SP extension-att-name SP extension-att-value)
988 const size_t expected_min_fields = 8;
989 if (fields.size() < expected_min_fields ||
990 (fields[6] != kAttributeCandidateTyp)) {
991 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
992 }
jbauch083b73f2015-07-16 02:46:32 -0700993 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000994
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000995 int component_id = 0;
996 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
997 return false;
998 }
jbauch083b73f2015-07-16 02:46:32 -0700999 const std::string& transport = fields[2];
Peter Boström0c4e06b2015-10-07 12:23:21 +02001000 uint32_t priority = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001001 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1002 return false;
1003 }
jbauch083b73f2015-07-16 02:46:32 -07001004 const std::string& connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001005 int port = 0;
1006 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1007 return false;
1008 }
deadbeef90f1e1e2017-02-10 12:35:05 -08001009 if (!IsValidPort(port)) {
1010 return ParseFailed(first_line, "Invalid port number.", error);
1011 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012 SocketAddress address(connection_address, port);
1013
1014 cricket::ProtocolType protocol;
hnslb68cc752016-12-13 10:33:41 -08001015 if (!StringToProto(transport.c_str(), &protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001016 return ParseFailed(first_line, "Unsupported transport type.", error);
1017 }
hnslb68cc752016-12-13 10:33:41 -08001018 switch (protocol) {
1019 case cricket::PROTO_UDP:
1020 case cricket::PROTO_TCP:
1021 case cricket::PROTO_SSLTCP:
1022 // Supported protocol.
1023 break;
1024 default:
1025 return ParseFailed(first_line, "Unsupported transport type.", error);
1026 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027
1028 std::string candidate_type;
jbauch083b73f2015-07-16 02:46:32 -07001029 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030 if (type == kCandidateHost) {
1031 candidate_type = cricket::LOCAL_PORT_TYPE;
1032 } else if (type == kCandidateSrflx) {
1033 candidate_type = cricket::STUN_PORT_TYPE;
1034 } else if (type == kCandidateRelay) {
1035 candidate_type = cricket::RELAY_PORT_TYPE;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001036 } else if (type == kCandidatePrflx) {
1037 candidate_type = cricket::PRFLX_PORT_TYPE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 } else {
1039 return ParseFailed(first_line, "Unsupported candidate type.", error);
1040 }
1041
1042 size_t current_position = expected_min_fields;
1043 SocketAddress related_address;
1044 // The 2 optional fields for related address
1045 // [raddr <connection-address>] [rport <port>]
1046 if (fields.size() >= (current_position + 2) &&
1047 fields[current_position] == kAttributeCandidateRaddr) {
1048 related_address.SetIP(fields[++current_position]);
1049 ++current_position;
1050 }
1051 if (fields.size() >= (current_position + 2) &&
1052 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001053 int port = 0;
1054 if (!GetValueFromString(
1055 first_line, fields[++current_position], &port, error)) {
1056 return false;
1057 }
deadbeef90f1e1e2017-02-10 12:35:05 -08001058 if (!IsValidPort(port)) {
1059 return ParseFailed(first_line, "Invalid port number.", error);
1060 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001061 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001062 ++current_position;
1063 }
1064
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001065 // If this is a TCP candidate, it has additional extension as defined in
1066 // RFC 6544.
1067 std::string tcptype;
1068 if (fields.size() >= (current_position + 2) &&
1069 fields[current_position] == kTcpCandidateType) {
1070 tcptype = fields[++current_position];
1071 ++current_position;
1072
1073 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1074 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1075 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1076 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1077 }
1078
1079 if (protocol != cricket::PROTO_TCP) {
1080 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1081 }
1082 }
1083
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001084 // Extension
honghaiza54a0802015-12-16 18:37:23 -08001085 // Though non-standard, we support the ICE ufrag and pwd being signaled on
1086 // the candidate to avoid issues with confusing which generation a candidate
1087 // belongs to when trickling multiple generations at the same time.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088 std::string username;
1089 std::string password;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001090 uint32_t generation = 0;
honghaiza0c44ea2016-03-23 16:07:48 -07001091 uint16_t network_id = 0;
1092 uint16_t network_cost = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1094 // RFC 5245
1095 // *(SP extension-att-name SP extension-att-value)
1096 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001097 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1098 return false;
1099 }
honghaiza54a0802015-12-16 18:37:23 -08001100 } else if (fields[i] == kAttributeCandidateUfrag) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 username = fields[++i];
honghaiza54a0802015-12-16 18:37:23 -08001102 } else if (fields[i] == kAttributeCandidatePwd) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001103 password = fields[++i];
honghaiza0c44ea2016-03-23 16:07:48 -07001104 } else if (fields[i] == kAttributeCandidateNetworkId) {
1105 if (!GetValueFromString(first_line, fields[++i], &network_id, error)) {
1106 return false;
1107 }
honghaize1a0c942016-02-16 14:54:56 -08001108 } else if (fields[i] == kAttributeCandidateNetworkCost) {
1109 if (!GetValueFromString(first_line, fields[++i], &network_cost, error)) {
1110 return false;
1111 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001112 network_cost = std::min(network_cost, rtc::kNetworkCostMax);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001113 } else {
1114 // Skip the unknown extension.
1115 ++i;
1116 }
1117 }
1118
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001119 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001120 address, priority, username, password, candidate_type,
honghaiza0c44ea2016-03-23 16:07:48 -07001121 generation, foundation, network_id, network_cost);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001122 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001123 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001124 return true;
1125}
1126
1127bool ParseIceOptions(const std::string& line,
1128 std::vector<std::string>* transport_options,
1129 SdpParseError* error) {
1130 std::string ice_options;
1131 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1132 return false;
1133 }
1134 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001135 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001136 for (size_t i = 0; i < fields.size(); ++i) {
1137 transport_options->push_back(fields[i]);
1138 }
1139 return true;
1140}
1141
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001142bool ParseSctpPort(const std::string& line,
1143 int* sctp_port,
1144 SdpParseError* error) {
1145 // draft-ietf-mmusic-sctp-sdp-07
1146 // a=sctp-port
1147 std::vector<std::string> fields;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001148 const size_t expected_min_fields = 2;
lally69f57602015-10-08 10:15:04 -07001149 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1150 if (fields.size() < expected_min_fields) {
1151 fields.resize(0);
1152 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpace, &fields);
1153 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001154 if (fields.size() < expected_min_fields) {
1155 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1156 }
1157 if (!rtc::FromString(fields[1], sctp_port)) {
lally69f57602015-10-08 10:15:04 -07001158 return ParseFailed(line, "Invalid sctp port value.", error);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001159 }
1160 return true;
1161}
1162
isheriff6f8d6862016-05-26 11:24:55 -07001163bool ParseExtmap(const std::string& line,
1164 RtpExtension* extmap,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165 SdpParseError* error) {
1166 // RFC 5285
1167 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1168 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001169 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001170 kSdpDelimiterSpace, &fields);
1171 const size_t expected_min_fields = 2;
1172 if (fields.size() < expected_min_fields) {
1173 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1174 }
1175 std::string uri = fields[1];
1176
1177 std::string value_direction;
1178 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1179 return false;
1180 }
1181 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001182 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001183 int value = 0;
1184 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1185 return false;
1186 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001187
jbauch5869f502017-06-29 12:31:36 -07001188 bool encrypted = false;
1189 if (uri == RtpExtension::kEncryptHeaderExtensionsUri) {
1190 // RFC 6904
Steve Anton36b29d12017-10-30 09:57:42 -07001191 // a=extmap:<value["/"<direction>] urn:ietf:params:rtp-hdrext:encrypt <URI>
1192 // <extensionattributes>
jbauch5869f502017-06-29 12:31:36 -07001193 const size_t expected_min_fields_encrypted = expected_min_fields + 1;
1194 if (fields.size() < expected_min_fields_encrypted) {
1195 return ParseFailedExpectMinFieldNum(line, expected_min_fields_encrypted,
1196 error);
1197 }
1198
1199 encrypted = true;
1200 uri = fields[2];
1201 if (uri == RtpExtension::kEncryptHeaderExtensionsUri) {
1202 return ParseFailed(line, "Recursive encrypted header.", error);
1203 }
1204 }
1205
1206 *extmap = RtpExtension(uri, value, encrypted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001207 return true;
1208}
1209
1210void BuildMediaDescription(const ContentInfo* content_info,
1211 const TransportInfo* transport_info,
1212 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001213 const std::vector<Candidate>& candidates,
Steve Antone831b8c2018-02-01 12:22:16 -08001214 int msid_signaling,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001215 std::string* message) {
nisseede5da42017-01-12 05:15:36 -08001216 RTC_DCHECK(message != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217 if (content_info == NULL || message == NULL) {
1218 return;
1219 }
Steve Anton36b29d12017-10-30 09:57:42 -07001220 // TODO(deadbeef): Rethink if we should use sprintfn instead of stringstream.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001221 // According to the style guide, streams should only be used for logging.
1222 // http://google-styleguide.googlecode.com/svn/
1223 // trunk/cppguide.xml?showone=Streams#Streams
1224 std::ostringstream os;
Steve Antonb1c1de12017-12-21 15:14:30 -08001225 const MediaContentDescription* media_desc = content_info->media_description();
1226 RTC_DCHECK(media_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001227
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001228 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001229
1230 // RFC 4566
1231 // m=<media> <port> <proto> <fmt>
1232 // fmt is a list of payload type numbers that MAY be used in the session.
1233 const char* type = NULL;
1234 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1235 type = kMediaTypeAudio;
1236 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1237 type = kMediaTypeVideo;
1238 else if (media_type == cricket::MEDIA_TYPE_DATA)
1239 type = kMediaTypeData;
1240 else
nissec80e7412017-01-11 05:56:46 -08001241 RTC_NOTREACHED();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001242
1243 std::string fmt;
1244 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001245 const VideoContentDescription* video_desc = media_desc->as_video();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001246 for (std::vector<cricket::VideoCodec>::const_iterator it =
1247 video_desc->codecs().begin();
1248 it != video_desc->codecs().end(); ++it) {
1249 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001250 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001251 }
1252 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001253 const AudioContentDescription* audio_desc = media_desc->as_audio();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001254 for (std::vector<cricket::AudioCodec>::const_iterator it =
1255 audio_desc->codecs().begin();
1256 it != audio_desc->codecs().end(); ++it) {
1257 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001258 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001259 }
1260 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001261 const DataContentDescription* data_desc = media_desc->as_data();
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001262 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001263 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001264
zstein4b2e0822017-02-17 19:48:38 -08001265 if (data_desc->use_sctpmap()) {
1266 for (std::vector<cricket::DataCodec>::const_iterator it =
1267 data_desc->codecs().begin();
1268 it != data_desc->codecs().end(); ++it) {
1269 if (cricket::CodecNamesEq(it->name,
1270 cricket::kGoogleSctpDataCodecName) &&
1271 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1272 break;
1273 }
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001274 }
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001275
zstein4b2e0822017-02-17 19:48:38 -08001276 fmt.append(rtc::ToString<int>(sctp_port));
1277 } else {
1278 fmt.append(kDefaultSctpmapProtocol);
1279 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001281 for (std::vector<cricket::DataCodec>::const_iterator it =
1282 data_desc->codecs().begin();
1283 it != data_desc->codecs().end(); ++it) {
1284 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001285 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286 }
1287 }
1288 }
1289 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1290 // to 0.
1291 if (fmt.empty()) {
1292 fmt = " 0";
1293 }
1294
deadbeef25ed4352016-12-12 18:37:36 -08001295 // The port number in the m line will be updated later when associated with
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001296 // the candidates.
deadbeef25ed4352016-12-12 18:37:36 -08001297 //
1298 // A port value of 0 indicates that the m= section is rejected.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 // RFC 3264
1300 // To reject an offered stream, the port number in the corresponding stream in
1301 // the answer MUST be set to zero.
deadbeef25ed4352016-12-12 18:37:36 -08001302 //
1303 // However, the BUNDLE draft adds a new meaning to port zero, when used along
1304 // with a=bundle-only.
zhihuang38989e52017-03-21 11:04:53 -07001305 std::string port = kDummyPort;
1306 if (content_info->rejected || content_info->bundle_only) {
1307 port = kMediaPortRejected;
1308 } else if (!media_desc->connection_address().IsNil()) {
1309 port = rtc::ToString(media_desc->connection_address().port());
1310 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001312 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313 transport_info->description.identity_fingerprint.get() : NULL;
1314
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001315 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316 InitLine(kLineTypeMedia, type, &os);
1317 os << " " << port << " " << media_desc->protocol() << fmt;
zhihuang38989e52017-03-21 11:04:53 -07001318 AddLine(os.str(), message);
1319
1320 InitLine(kLineTypeConnection, kConnectionNettype, &os);
1321 if (media_desc->connection_address().IsNil()) {
1322 os << " " << kConnectionIpv4Addrtype << " " << kDummyAddress;
1323 } else if (media_desc->connection_address().family() == AF_INET) {
1324 os << " " << kConnectionIpv4Addrtype << " "
1325 << media_desc->connection_address().ipaddr().ToString();
1326 } else {
1327 os << " " << kConnectionIpv6Addrtype << " "
1328 << media_desc->connection_address().ipaddr().ToString();
1329 }
1330 AddLine(os.str(), message);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001331
1332 // RFC 4566
1333 // b=AS:<bandwidth>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001334 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001335 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1336 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1337 AddLine(os.str(), message);
1338 }
1339
deadbeef25ed4352016-12-12 18:37:36 -08001340 // Add the a=bundle-only line.
1341 if (content_info->bundle_only) {
1342 InitAttrLine(kAttributeBundleOnly, &os);
1343 AddLine(os.str(), message);
1344 }
1345
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001346 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001347 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001348 std::string rtcp_line = GetRtcpLine(candidates);
1349 if (!rtcp_line.empty()) {
1350 AddLine(rtcp_line, message);
1351 }
1352 }
1353
honghaiza54a0802015-12-16 18:37:23 -08001354 // Build the a=candidate lines. We don't include ufrag and pwd in the
1355 // candidates in the SDP to avoid redundancy.
1356 BuildCandidate(candidates, false, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357
1358 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1359 if (transport_info) {
1360 // RFC 5245
1361 // ice-pwd-att = "ice-pwd" ":" password
1362 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1363 // ice-ufrag
deadbeef3f7219b2015-12-28 15:17:14 -08001364 if (!transport_info->description.ice_ufrag.empty()) {
1365 InitAttrLine(kAttributeIceUfrag, &os);
1366 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1367 AddLine(os.str(), message);
1368 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 // ice-pwd
deadbeef3f7219b2015-12-28 15:17:14 -08001370 if (!transport_info->description.ice_pwd.empty()) {
1371 InitAttrLine(kAttributeIcePwd, &os);
1372 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1373 AddLine(os.str(), message);
1374 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375
1376 // draft-petithuguenin-mmusic-ice-attributes-level-03
1377 BuildIceOptions(transport_info->description.transport_options, message);
1378
1379 // RFC 4572
1380 // fingerprint-attribute =
1381 // "fingerprint" ":" hash-func SP fingerprint
1382 if (fp) {
1383 // Insert the fingerprint attribute.
1384 InitAttrLine(kAttributeFingerprint, &os);
1385 os << kSdpDelimiterColon
1386 << fp->algorithm << kSdpDelimiterSpace
1387 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001388 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001389
1390 // Inserting setup attribute.
1391 if (transport_info->description.connection_role !=
1392 cricket::CONNECTIONROLE_NONE) {
1393 // Making sure we are not using "passive" mode.
1394 cricket::ConnectionRole role =
1395 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001396 std::string dtls_role_str;
nissec16fa5e2017-02-07 07:18:43 -08001397 const bool success =
1398 cricket::ConnectionRoleToString(role, &dtls_role_str);
1399 RTC_DCHECK(success);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001400 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001401 os << kSdpDelimiterColon << dtls_role_str;
1402 AddLine(os.str(), message);
1403 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404 }
1405 }
1406
1407 // RFC 3388
1408 // mid-attribute = "a=mid:" identification-tag
1409 // identification-tag = token
1410 // Use the content name as the mid identification-tag.
1411 InitAttrLine(kAttributeMid, &os);
1412 os << kSdpDelimiterColon << content_info->name;
1413 AddLine(os.str(), message);
1414
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001415 if (IsDtlsSctp(media_desc->protocol())) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001416 const DataContentDescription* data_desc = media_desc->as_data();
zstein4b2e0822017-02-17 19:48:38 -08001417 bool use_sctpmap = data_desc->use_sctpmap();
1418 BuildSctpContentAttributes(message, sctp_port, use_sctpmap);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001419 } else if (IsRtp(media_desc->protocol())) {
Steve Antone831b8c2018-02-01 12:22:16 -08001420 BuildRtpContentAttributes(media_desc, media_type, msid_signaling, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001421 }
1422}
1423
zstein4b2e0822017-02-17 19:48:38 -08001424void BuildSctpContentAttributes(std::string* message,
1425 int sctp_port,
1426 bool use_sctpmap) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001427 std::ostringstream os;
zstein4b2e0822017-02-17 19:48:38 -08001428 if (use_sctpmap) {
1429 // draft-ietf-mmusic-sctp-sdp-04
1430 // a=sctpmap:sctpmap-number protocol [streams]
1431 InitAttrLine(kAttributeSctpmap, &os);
1432 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
1433 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1434 << cricket::kMaxSctpStreams;
1435 } else {
1436 // draft-ietf-mmusic-sctp-sdp-23
1437 // a=sctp-port:<port>
1438 InitAttrLine(kAttributeSctpPort, &os);
1439 os << kSdpDelimiterColon << sctp_port;
1440 // TODO(zstein): emit max-message-size here
1441 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001442 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001443}
1444
deadbeef9d3584c2016-02-16 17:54:10 -08001445void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
1446 const MediaType media_type,
Steve Antone831b8c2018-02-01 12:22:16 -08001447 int msid_signaling,
deadbeef9d3584c2016-02-16 17:54:10 -08001448 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001449 std::ostringstream os;
1450 // RFC 5285
1451 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1452 // The definitions MUST be either all session level or all media level. This
1453 // implementation uses all media level.
1454 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
jbauch5869f502017-06-29 12:31:36 -07001455 const RtpExtension& extension = media_desc->rtp_header_extensions()[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001456 InitAttrLine(kAttributeExtmap, &os);
jbauch5869f502017-06-29 12:31:36 -07001457 os << kSdpDelimiterColon << extension.id;
1458 if (extension.encrypt) {
1459 os << kSdpDelimiterSpace << RtpExtension::kEncryptHeaderExtensionsUri;
1460 }
1461 os << kSdpDelimiterSpace << extension.uri;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462 AddLine(os.str(), message);
1463 }
1464
1465 // RFC 3264
1466 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
deadbeefc80741f2015-10-22 13:14:45 -07001467 switch (media_desc->direction()) {
Steve Anton4e70a722017-11-28 14:57:10 -08001468 case RtpTransceiverDirection::kInactive:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469 InitAttrLine(kAttributeInactive, &os);
1470 break;
Steve Anton4e70a722017-11-28 14:57:10 -08001471 case RtpTransceiverDirection::kSendOnly:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472 InitAttrLine(kAttributeSendOnly, &os);
1473 break;
Steve Anton4e70a722017-11-28 14:57:10 -08001474 case RtpTransceiverDirection::kRecvOnly:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001475 InitAttrLine(kAttributeRecvOnly, &os);
1476 break;
Steve Anton4e70a722017-11-28 14:57:10 -08001477 case RtpTransceiverDirection::kSendRecv:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478 default:
1479 InitAttrLine(kAttributeSendRecv, &os);
1480 break;
1481 }
1482 AddLine(os.str(), message);
1483
Seth Hampson5b4f0752018-04-02 16:31:36 -07001484 // Specified in https://datatracker.ietf.org/doc/draft-ietf-mmusic-msid/16/
1485 // a=msid:<msid-id> <msid-appdata>
1486 // The msid-id is a 1*64 token char representing the media stream id, and the
1487 // msid-appdata is a 1*64 token char representing the track id. There is a
1488 // line for every media stream, with a special msid-id value of "-"
1489 // representing no streams. The value of "msid-appdata" MUST be identical for
1490 // all lines.
Steve Antone831b8c2018-02-01 12:22:16 -08001491 if (msid_signaling & cricket::kMsidSignalingMediaSection) {
1492 const StreamParamsVec& streams = media_desc->streams();
1493 if (streams.size() == 1u) {
1494 const StreamParams& track = streams[0];
Seth Hampson5b4f0752018-04-02 16:31:36 -07001495 std::vector<std::string> stream_ids = track.stream_ids();
1496 if (stream_ids.empty()) {
1497 stream_ids.push_back(kNoStreamMsid);
1498 }
1499 for (const std::string& stream_id : stream_ids) {
1500 InitAttrLine(kAttributeMsid, &os);
1501 os << kSdpDelimiterColon << stream_id << kSdpDelimiterSpace << track.id;
1502 AddLine(os.str(), message);
1503 }
Steve Antone831b8c2018-02-01 12:22:16 -08001504 } else if (streams.size() > 1u) {
1505 RTC_LOG(LS_WARNING)
1506 << "Trying to serialize Unified Plan SDP with more than "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001507 "one track in a media section. Omitting 'a=msid'.";
deadbeef9d3584c2016-02-16 17:54:10 -08001508 }
1509 }
1510
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001511 // RFC 5761
1512 // a=rtcp-mux
1513 if (media_desc->rtcp_mux()) {
1514 InitAttrLine(kAttributeRtcpMux, &os);
1515 AddLine(os.str(), message);
1516 }
1517
deadbeef13871492015-12-09 12:37:51 -08001518 // RFC 5506
1519 // a=rtcp-rsize
1520 if (media_desc->rtcp_reduced_size()) {
1521 InitAttrLine(kAttributeRtcpReducedSize, &os);
1522 AddLine(os.str(), message);
1523 }
1524
deadbeefd45aea82017-09-16 01:24:29 -07001525 if (media_desc->conference_mode()) {
1526 InitAttrLine(kAttributeXGoogleFlag, &os);
1527 os << kSdpDelimiterColon << kValueConference;
1528 AddLine(os.str(), message);
1529 }
1530
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001531 // RFC 4568
1532 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1533 for (std::vector<CryptoParams>::const_iterator it =
1534 media_desc->cryptos().begin();
1535 it != media_desc->cryptos().end(); ++it) {
1536 InitAttrLine(kAttributeCrypto, &os);
1537 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1538 << it->key_params;
1539 if (!it->session_params.empty()) {
1540 os << " " << it->session_params;
1541 }
1542 AddLine(os.str(), message);
1543 }
1544
1545 // RFC 4566
1546 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1547 // [/<encodingparameters>]
1548 BuildRtpMap(media_desc, media_type, message);
1549
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001550 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1551 track != media_desc->streams().end(); ++track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001552 // Build the ssrc-group lines.
1553 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1554 // RFC 5576
1555 // a=ssrc-group:<semantics> <ssrc-id> ...
1556 if (track->ssrc_groups[i].ssrcs.empty()) {
1557 continue;
1558 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559 InitAttrLine(kAttributeSsrcGroup, &os);
1560 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001561 std::vector<uint32_t>::const_iterator ssrc =
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001562 track->ssrc_groups[i].ssrcs.begin();
1563 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001564 os << kSdpDelimiterSpace << rtc::ToString<uint32_t>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565 }
1566 AddLine(os.str(), message);
1567 }
1568 // Build the ssrc lines for each ssrc.
1569 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001570 uint32_t ssrc = track->ssrcs[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001571 // RFC 5576
1572 // a=ssrc:<ssrc-id> cname:<value>
1573 AddSsrcLine(ssrc, kSsrcAttributeCname,
1574 track->cname, message);
1575
Steve Antone831b8c2018-02-01 12:22:16 -08001576 if (msid_signaling & cricket::kMsidSignalingSsrcAttribute) {
1577 // draft-alvestrand-mmusic-msid-00
1578 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1579 // The appdata consists of the "id" attribute of a MediaStreamTrack,
1580 // which corresponds to the "id" attribute of StreamParams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07001581 // Since a=ssrc msid signaling is used in Plan B SDP semantics, and
1582 // multiple stream ids are not supported for Plan B, we are only adding
1583 // a line for the first media stream id here.
Seth Hampson845e8782018-03-02 11:34:10 -08001584 const std::string& stream_id = track->first_stream_id();
Steve Antone831b8c2018-02-01 12:22:16 -08001585 InitAttrLine(kAttributeSsrc, &os);
1586 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1587 << kSsrcAttributeMsid << kSdpDelimiterColon << stream_id
1588 << kSdpDelimiterSpace << track->id;
1589 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001590
Steve Antone831b8c2018-02-01 12:22:16 -08001591 // TODO(ronghuawu): Remove below code which is for backward
1592 // compatibility.
1593 // draft-alvestrand-rtcweb-mid-01
1594 // a=ssrc:<ssrc-id> mslabel:<value>
1595 // The label isn't yet defined.
1596 // a=ssrc:<ssrc-id> label:<value>
Seth Hampson5b4f0752018-04-02 16:31:36 -07001597 AddSsrcLine(ssrc, kSsrcAttributeMslabel, stream_id, message);
Steve Antone831b8c2018-02-01 12:22:16 -08001598 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1599 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001600 }
1601 }
1602}
1603
1604void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1605 // fmtp header: a=fmtp:|payload_type| <parameters>
1606 // Add a=fmtp
1607 InitAttrLine(kAttributeFmtp, os);
1608 // Add :|payload_type|
1609 *os << kSdpDelimiterColon << payload_type;
1610}
1611
1612void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1613 // rtcp-fb header: a=rtcp-fb:|payload_type|
1614 // <parameters>/<ccm <ccm_parameters>>
1615 // Add a=rtcp-fb
1616 InitAttrLine(kAttributeRtcpFb, os);
1617 // Add :
1618 *os << kSdpDelimiterColon;
1619 if (payload_type == kWildcardPayloadType) {
1620 *os << "*";
1621 } else {
1622 *os << payload_type;
1623 }
1624}
1625
1626void WriteFmtpParameter(const std::string& parameter_name,
1627 const std::string& parameter_value,
1628 std::ostringstream* os) {
1629 // fmtp parameters: |parameter_name|=|parameter_value|
1630 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1631}
1632
1633void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1634 std::ostringstream* os) {
1635 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1636 fmtp != parameters.end(); ++fmtp) {
hta62a216e2016-04-15 11:02:14 -07001637 // Parameters are a semicolon-separated list, no spaces.
1638 // The list is separated from the header by a space.
1639 if (fmtp == parameters.begin()) {
1640 *os << kSdpDelimiterSpace;
1641 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001642 *os << kSdpDelimiterSemicolon;
1643 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001644 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1645 }
1646}
1647
1648bool IsFmtpParam(const std::string& name) {
ossuaa4b0772017-01-30 07:41:18 -08001649 // RFC 4855, section 3 specifies the mapping of media format parameters to SDP
1650 // parameters. Only ptime, maxptime, channels and rate are placed outside of
1651 // the fmtp line. In WebRTC, channels and rate are already handled separately
1652 // and thus not included in the CodecParameterMap.
1653 return name != kCodecParamPTime && name != kCodecParamMaxPTime;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001654}
1655
1656// Retreives fmtp parameters from |params|, which may contain other parameters
1657// as well, and puts them in |fmtp_parameters|.
1658void GetFmtpParams(const cricket::CodecParameterMap& params,
1659 cricket::CodecParameterMap* fmtp_parameters) {
1660 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1661 iter != params.end(); ++iter) {
1662 if (IsFmtpParam(iter->first)) {
1663 (*fmtp_parameters)[iter->first] = iter->second;
1664 }
1665 }
1666}
1667
1668template <class T>
1669void AddFmtpLine(const T& codec, std::string* message) {
1670 cricket::CodecParameterMap fmtp_parameters;
1671 GetFmtpParams(codec.params, &fmtp_parameters);
1672 if (fmtp_parameters.empty()) {
1673 // No need to add an fmtp if it will have no (optional) parameters.
1674 return;
1675 }
1676 std::ostringstream os;
1677 WriteFmtpHeader(codec.id, &os);
1678 WriteFmtpParameters(fmtp_parameters, &os);
1679 AddLine(os.str(), message);
1680 return;
1681}
1682
1683template <class T>
1684void AddRtcpFbLines(const T& codec, std::string* message) {
1685 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1686 codec.feedback_params.params().begin();
1687 iter != codec.feedback_params.params().end(); ++iter) {
1688 std::ostringstream os;
1689 WriteRtcpFbHeader(codec.id, &os);
1690 os << " " << iter->id();
1691 if (!iter->param().empty()) {
1692 os << " " << iter->param();
1693 }
1694 AddLine(os.str(), message);
1695 }
1696}
1697
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001698bool AddSctpDataCodec(DataContentDescription* media_desc,
1699 int sctp_port) {
solenberg9fa49752016-10-08 13:02:44 -07001700 for (const auto& codec : media_desc->codecs()) {
1701 if (cricket::CodecNamesEq(codec.name, cricket::kGoogleSctpDataCodecName)) {
1702 return ParseFailed("",
1703 "Can't have multiple sctp port attributes.",
1704 NULL);
1705 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001706 }
1707 // Add the SCTP Port number as a pseudo-codec "port" parameter
solenberg9fa49752016-10-08 13:02:44 -07001708 cricket::DataCodec codec_port(cricket::kGoogleSctpDataCodecPlType,
deadbeef67cf2c12016-04-13 10:07:16 -07001709 cricket::kGoogleSctpDataCodecName);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001710 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
Mirko Bonadei675513b2017-11-09 11:09:25 +01001711 RTC_LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number " << sctp_port;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001712 media_desc->AddCodec(codec_port);
1713 return true;
1714}
1715
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716bool GetMinValue(const std::vector<int>& values, int* value) {
1717 if (values.empty()) {
1718 return false;
1719 }
1720 std::vector<int>::const_iterator found =
1721 std::min_element(values.begin(), values.end());
1722 *value = *found;
1723 return true;
1724}
1725
1726bool GetParameter(const std::string& name,
1727 const cricket::CodecParameterMap& params, int* value) {
1728 std::map<std::string, std::string>::const_iterator found =
1729 params.find(name);
1730 if (found == params.end()) {
1731 return false;
1732 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001733 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001734 return false;
1735 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001736 return true;
1737}
1738
1739void BuildRtpMap(const MediaContentDescription* media_desc,
1740 const MediaType media_type,
1741 std::string* message) {
nisseede5da42017-01-12 05:15:36 -08001742 RTC_DCHECK(message != NULL);
1743 RTC_DCHECK(media_desc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001744 std::ostringstream os;
1745 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001746 const VideoContentDescription* video_desc = media_desc->as_video();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001747 for (std::vector<cricket::VideoCodec>::const_iterator it =
1748 video_desc->codecs().begin();
1749 it != video_desc->codecs().end(); ++it) {
1750 // RFC 4566
1751 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1752 // [/<encodingparameters>]
1753 if (it->id != kWildcardPayloadType) {
1754 InitAttrLine(kAttributeRtpmap, &os);
deadbeefe814a0d2017-02-25 18:15:09 -08001755 os << kSdpDelimiterColon << it->id << " " << it->name << "/"
1756 << cricket::kVideoCodecClockrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001757 AddLine(os.str(), message);
1758 }
1759 AddRtcpFbLines(*it, message);
1760 AddFmtpLine(*it, message);
1761 }
1762 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001763 const AudioContentDescription* audio_desc = media_desc->as_audio();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764 std::vector<int> ptimes;
1765 std::vector<int> maxptimes;
1766 int max_minptime = 0;
1767 for (std::vector<cricket::AudioCodec>::const_iterator it =
1768 audio_desc->codecs().begin();
1769 it != audio_desc->codecs().end(); ++it) {
nisseede5da42017-01-12 05:15:36 -08001770 RTC_DCHECK(!it->name.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001771 // RFC 4566
1772 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1773 // [/<encodingparameters>]
1774 InitAttrLine(kAttributeRtpmap, &os);
1775 os << kSdpDelimiterColon << it->id << " ";
1776 os << it->name << "/" << it->clockrate;
1777 if (it->channels != 1) {
1778 os << "/" << it->channels;
1779 }
1780 AddLine(os.str(), message);
1781 AddRtcpFbLines(*it, message);
1782 AddFmtpLine(*it, message);
1783 int minptime = 0;
1784 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1785 max_minptime = std::max(minptime, max_minptime);
1786 }
1787 int ptime;
1788 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1789 ptimes.push_back(ptime);
1790 }
1791 int maxptime;
1792 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1793 maxptimes.push_back(maxptime);
1794 }
1795 }
1796 // Populate the maxptime attribute with the smallest maxptime of all codecs
1797 // under the same m-line.
1798 int min_maxptime = INT_MAX;
1799 if (GetMinValue(maxptimes, &min_maxptime)) {
1800 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1801 }
nisseede5da42017-01-12 05:15:36 -08001802 RTC_DCHECK(min_maxptime > max_minptime);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803 // Populate the ptime attribute with the smallest ptime or the largest
1804 // minptime, whichever is the largest, for all codecs under the same m-line.
1805 int ptime = INT_MAX;
1806 if (GetMinValue(ptimes, &ptime)) {
1807 ptime = std::min(ptime, min_maxptime);
1808 ptime = std::max(ptime, max_minptime);
1809 AddAttributeLine(kCodecParamPTime, ptime, message);
1810 }
1811 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001812 const DataContentDescription* data_desc = media_desc->as_data();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813 for (std::vector<cricket::DataCodec>::const_iterator it =
1814 data_desc->codecs().begin();
1815 it != data_desc->codecs().end(); ++it) {
1816 // RFC 4566
1817 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1818 // [/<encodingparameters>]
1819 InitAttrLine(kAttributeRtpmap, &os);
1820 os << kSdpDelimiterColon << it->id << " "
1821 << it->name << "/" << it->clockrate;
1822 AddLine(os.str(), message);
1823 }
1824 }
1825}
1826
1827void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -08001828 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001829 std::string* message) {
1830 std::ostringstream os;
1831
1832 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1833 it != candidates.end(); ++it) {
1834 // RFC 5245
1835 // a=candidate:<foundation> <component-id> <transport> <priority>
1836 // <connection-address> <port> typ <candidate-types>
1837 // [raddr <connection-address>] [rport <port>]
1838 // *(SP extension-att-name SP extension-att-value)
1839 std::string type;
1840 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1841 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1842 type = kCandidateHost;
1843 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1844 type = kCandidateSrflx;
1845 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1846 type = kCandidateRelay;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001847 } else if (it->type() == cricket::PRFLX_PORT_TYPE) {
1848 type = kCandidatePrflx;
1849 // Peer reflexive candidate may be signaled for being removed.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850 } else {
nissec80e7412017-01-11 05:56:46 -08001851 RTC_NOTREACHED();
Peter Thatcher019087f2015-04-28 09:06:26 -07001852 // Never write out candidates if we don't know the type.
1853 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854 }
1855
1856 InitAttrLine(kAttributeCandidate, &os);
1857 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001858 << it->foundation() << " "
1859 << it->component() << " "
1860 << it->protocol() << " "
1861 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862 << it->address().ipaddr().ToString() << " "
1863 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001864 << kAttributeCandidateTyp << " "
1865 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001866
1867 // Related address
1868 if (!it->related_address().IsNil()) {
1869 os << kAttributeCandidateRaddr << " "
1870 << it->related_address().ipaddr().ToString() << " "
1871 << kAttributeCandidateRport << " "
1872 << it->related_address().PortAsString() << " ";
1873 }
1874
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001875 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001876 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001877 }
1878
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001879 // Extensions
1880 os << kAttributeCandidateGeneration << " " << it->generation();
honghaiza54a0802015-12-16 18:37:23 -08001881 if (include_ufrag && !it->username().empty()) {
1882 os << " " << kAttributeCandidateUfrag << " " << it->username();
1883 }
honghaiza0c44ea2016-03-23 16:07:48 -07001884 if (it->network_id() > 0) {
1885 os << " " << kAttributeCandidateNetworkId << " " << it->network_id();
1886 }
honghaize1a0c942016-02-16 14:54:56 -08001887 if (it->network_cost() > 0) {
1888 os << " " << kAttributeCandidateNetworkCost << " " << it->network_cost();
1889 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001890
1891 AddLine(os.str(), message);
1892 }
1893}
1894
1895void BuildIceOptions(const std::vector<std::string>& transport_options,
1896 std::string* message) {
1897 if (!transport_options.empty()) {
1898 std::ostringstream os;
1899 InitAttrLine(kAttributeIceOption, &os);
1900 os << kSdpDelimiterColon << transport_options[0];
1901 for (size_t i = 1; i < transport_options.size(); ++i) {
1902 os << kSdpDelimiterSpace << transport_options[i];
1903 }
1904 AddLine(os.str(), message);
1905 }
1906}
1907
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001908bool IsRtp(const std::string& protocol) {
1909 return protocol.empty() ||
1910 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1911}
1912
1913bool IsDtlsSctp(const std::string& protocol) {
1914 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001915 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001916}
1917
zhihuang38989e52017-03-21 11:04:53 -07001918bool ParseConnectionData(const std::string& line,
1919 rtc::SocketAddress* addr,
1920 SdpParseError* error) {
1921 // Parse the line from left to right.
1922 std::string token;
1923 std::string rightpart;
1924 // RFC 4566
1925 // c=<nettype> <addrtype> <connection-address>
1926 // Skip the "c="
1927 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, &token, &rightpart)) {
1928 return ParseFailed(line, "Failed to parse the network type.", error);
1929 }
1930
1931 // Extract and verify the <nettype>
1932 if (!rtc::tokenize_first(rightpart, kSdpDelimiterSpace, &token, &rightpart) ||
1933 token != kConnectionNettype) {
1934 return ParseFailed(line,
1935 "Failed to parse the connection data. The network type "
1936 "is not currently supported.",
1937 error);
1938 }
1939
1940 // Extract the "<addrtype>" and "<connection-address>".
1941 if (!rtc::tokenize_first(rightpart, kSdpDelimiterSpace, &token, &rightpart)) {
1942 return ParseFailed(line, "Failed to parse the address type.", error);
1943 }
1944
1945 // The rightpart part should be the IP address without the slash which is used
1946 // for multicast.
1947 if (rightpart.find('/') != std::string::npos) {
1948 return ParseFailed(line,
1949 "Failed to parse the connection data. Multicast is not "
1950 "currently supported.",
1951 error);
1952 }
1953 addr->SetIP(rightpart);
1954
1955 // Verify that the addrtype matches the type of the parsed address.
1956 if ((addr->family() == AF_INET && token != "IP4") ||
1957 (addr->family() == AF_INET6 && token != "IP6")) {
1958 addr->Clear();
1959 return ParseFailed(
1960 line,
1961 "Failed to parse the connection data. The address type is mismatching.",
1962 error);
1963 }
1964 return true;
1965}
1966
1967bool ParseSessionDescription(const std::string& message,
1968 size_t* pos,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001969 std::string* session_id,
1970 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001971 TransportDescription* session_td,
1972 RtpHeaderExtensions* session_extmaps,
zhihuang38989e52017-03-21 11:04:53 -07001973 rtc::SocketAddress* connection_addr,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001974 cricket::SessionDescription* desc,
1975 SdpParseError* error) {
1976 std::string line;
1977
deadbeefc80741f2015-10-22 13:14:45 -07001978 desc->set_msid_supported(false);
1979
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001980 // RFC 4566
1981 // v= (protocol version)
1982 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1983 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1984 std::string(), error);
1985 }
1986 // RFC 4566
1987 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1988 // <unicast-address>
1989 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1990 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1991 std::string(), error);
1992 }
1993 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001994 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001995 kSdpDelimiterSpace, &fields);
1996 const size_t expected_fields = 6;
1997 if (fields.size() != expected_fields) {
1998 return ParseFailedExpectFieldNum(line, expected_fields, error);
1999 }
2000 *session_id = fields[1];
2001 *session_version = fields[2];
2002
2003 // RFC 4566
2004 // s= (session name)
2005 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
2006 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
2007 std::string(), error);
2008 }
2009
2010 // Optional lines
2011 // Those are the optional lines, so shouldn't return false if not present.
2012 // RFC 4566
2013 // i=* (session information)
2014 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
2015
2016 // RFC 4566
2017 // u=* (URI of description)
2018 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
2019
2020 // RFC 4566
2021 // e=* (email address)
2022 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
2023
2024 // RFC 4566
2025 // p=* (phone number)
2026 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
2027
2028 // RFC 4566
2029 // c=* (connection information -- not required if included in
2030 // all media)
zhihuang38989e52017-03-21 11:04:53 -07002031 if (GetLineWithType(message, pos, &line, kLineTypeConnection)) {
2032 if (!ParseConnectionData(line, connection_addr, error)) {
2033 return false;
2034 }
2035 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002036
2037 // RFC 4566
2038 // b=* (zero or more bandwidth information lines)
2039 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
2040 // By pass zero or more b lines.
2041 }
2042
2043 // RFC 4566
2044 // One or more time descriptions ("t=" and "r=" lines; see below)
2045 // t= (time the session is active)
2046 // r=* (zero or more repeat times)
2047 // Ensure there's at least one time description
2048 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
2049 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
2050 error);
2051 }
2052
2053 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
2054 // By pass zero or more r lines.
2055 }
2056
2057 // Go through the rest of the time descriptions
2058 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
2059 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
2060 // By pass zero or more r lines.
2061 }
2062 }
2063
2064 // RFC 4566
2065 // z=* (time zone adjustments)
2066 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
2067
2068 // RFC 4566
2069 // k=* (encryption key)
2070 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
2071
2072 // RFC 4566
2073 // a=* (zero or more session attribute lines)
2074 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
2075 if (HasAttribute(line, kAttributeGroup)) {
2076 if (!ParseGroupAttribute(line, desc, error)) {
2077 return false;
2078 }
2079 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2080 if (!GetValue(line, kAttributeIceUfrag,
2081 &(session_td->ice_ufrag), error)) {
2082 return false;
2083 }
2084 } else if (HasAttribute(line, kAttributeIcePwd)) {
2085 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
2086 return false;
2087 }
2088 } else if (HasAttribute(line, kAttributeIceLite)) {
2089 session_td->ice_mode = cricket::ICEMODE_LITE;
2090 } else if (HasAttribute(line, kAttributeIceOption)) {
2091 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
2092 return false;
2093 }
2094 } else if (HasAttribute(line, kAttributeFingerprint)) {
2095 if (session_td->identity_fingerprint.get()) {
2096 return ParseFailed(
2097 line,
2098 "Can't have multiple fingerprint attributes at the same level.",
2099 error);
2100 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002101 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002102 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2103 return false;
2104 }
2105 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002106 } else if (HasAttribute(line, kAttributeSetup)) {
2107 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
2108 return false;
2109 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002110 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
2111 std::string semantics;
2112 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
2113 return false;
2114 }
deadbeefc80741f2015-10-22 13:14:45 -07002115 desc->set_msid_supported(
2116 CaseInsensitiveFind(semantics, kMediaStreamSemantic));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002117 } else if (HasAttribute(line, kAttributeExtmap)) {
isheriff6f8d6862016-05-26 11:24:55 -07002118 RtpExtension extmap;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002119 if (!ParseExtmap(line, &extmap, error)) {
2120 return false;
2121 }
2122 session_extmaps->push_back(extmap);
2123 }
2124 }
2125
2126 return true;
2127}
2128
2129bool ParseGroupAttribute(const std::string& line,
2130 cricket::SessionDescription* desc,
2131 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08002132 RTC_DCHECK(desc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002133
2134 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
2135 // a=group:BUNDLE video voice
2136 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002137 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002138 kSdpDelimiterSpace, &fields);
2139 std::string semantics;
2140 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
2141 return false;
2142 }
2143 cricket::ContentGroup group(semantics);
2144 for (size_t i = 1; i < fields.size(); ++i) {
2145 group.AddContentName(fields[i]);
2146 }
2147 desc->AddGroup(group);
2148 return true;
2149}
2150
2151static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002152 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002153 SdpParseError* error) {
2154 if (!IsLineType(line, kLineTypeAttributes) ||
2155 !HasAttribute(line, kAttributeFingerprint)) {
2156 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
2157 kAttributeFingerprint, error);
2158 }
2159
2160 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002161 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162 kSdpDelimiterSpace, &fields);
2163 const size_t expected_fields = 2;
2164 if (fields.size() != expected_fields) {
2165 return ParseFailedExpectFieldNum(line, expected_fields, error);
2166 }
2167
2168 // The first field here is "fingerprint:<hash>.
2169 std::string algorithm;
2170 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2171 return false;
2172 }
2173
2174 // Downcase the algorithm. Note that we don't need to downcase the
2175 // fingerprint because hex_decode can handle upper-case.
2176 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2177 ::tolower);
2178
2179 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002180 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002181 algorithm, fields[1]);
2182 if (!*fingerprint) {
2183 return ParseFailed(line,
2184 "Failed to create fingerprint from the digest.",
2185 error);
2186 }
2187
2188 return true;
2189}
2190
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002191static bool ParseDtlsSetup(const std::string& line,
2192 cricket::ConnectionRole* role,
2193 SdpParseError* error) {
2194 // setup-attr = "a=setup:" role
2195 // role = "active" / "passive" / "actpass" / "holdconn"
2196 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002197 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002198 const size_t expected_fields = 2;
2199 if (fields.size() != expected_fields) {
2200 return ParseFailedExpectFieldNum(line, expected_fields, error);
2201 }
2202 std::string role_str = fields[1];
2203 if (!cricket::StringToConnectionRole(role_str, role)) {
2204 return ParseFailed(line, "Invalid attribute value.", error);
2205 }
2206 return true;
2207}
2208
deadbeef9d3584c2016-02-16 17:54:10 -08002209static bool ParseMsidAttribute(const std::string& line,
Seth Hampson5b4f0752018-04-02 16:31:36 -07002210 std::vector<std::string>* stream_ids,
deadbeef9d3584c2016-02-16 17:54:10 -08002211 std::string* track_id,
2212 SdpParseError* error) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07002213 // https://datatracker.ietf.org/doc/draft-ietf-mmusic-msid/16/
deadbeef9d3584c2016-02-16 17:54:10 -08002214 // a=msid:<stream id> <track id>
2215 // msid-value = msid-id [ SP msid-appdata ]
2216 // msid-id = 1*64token-char ; see RFC 4566
2217 // msid-appdata = 1*64token-char ; see RFC 4566
2218 std::string field1;
Seth Hampson5b4f0752018-04-02 16:31:36 -07002219 std::string new_stream_id;
2220 std::string new_track_id;
deadbeef9d3584c2016-02-16 17:54:10 -08002221 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
Seth Hampson5b4f0752018-04-02 16:31:36 -07002222 &field1, &new_track_id)) {
deadbeef9d3584c2016-02-16 17:54:10 -08002223 const size_t expected_fields = 2;
2224 return ParseFailedExpectFieldNum(line, expected_fields, error);
2225 }
2226
Seth Hampson5b4f0752018-04-02 16:31:36 -07002227 if (new_track_id.empty()) {
deadbeefa4549d62017-02-10 17:26:22 -08002228 return ParseFailed(line, "Missing track ID in msid attribute.", error);
2229 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07002230 // All track ids should be the same within an m section in a Unified Plan SDP.
2231 if (!track_id->empty() && new_track_id.compare(*track_id) != 0) {
2232 return ParseFailed(
2233 line, "Two different track IDs in msid attribute in one m= section",
2234 error);
2235 }
2236 *track_id = new_track_id;
deadbeefa4549d62017-02-10 17:26:22 -08002237
deadbeef9d3584c2016-02-16 17:54:10 -08002238 // msid:<msid-id>
Seth Hampson5b4f0752018-04-02 16:31:36 -07002239 if (!GetValue(field1, kAttributeMsid, &new_stream_id, error)) {
deadbeef9d3584c2016-02-16 17:54:10 -08002240 return false;
2241 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07002242 if (new_stream_id.empty()) {
deadbeefa4549d62017-02-10 17:26:22 -08002243 return ParseFailed(line, "Missing stream ID in msid attribute.", error);
2244 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07002245 // The special value "-" indicates "no MediaStream".
2246 if (new_stream_id.compare(kNoStreamMsid) != 0) {
2247 stream_ids->push_back(new_stream_id);
2248 }
deadbeef9d3584c2016-02-16 17:54:10 -08002249 return true;
2250}
2251
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252// RFC 3551
2253// PT encoding media type clock rate channels
2254// name (Hz)
2255// 0 PCMU A 8,000 1
2256// 1 reserved A
2257// 2 reserved A
2258// 3 GSM A 8,000 1
2259// 4 G723 A 8,000 1
2260// 5 DVI4 A 8,000 1
2261// 6 DVI4 A 16,000 1
2262// 7 LPC A 8,000 1
2263// 8 PCMA A 8,000 1
2264// 9 G722 A 8,000 1
2265// 10 L16 A 44,100 2
2266// 11 L16 A 44,100 1
2267// 12 QCELP A 8,000 1
2268// 13 CN A 8,000 1
2269// 14 MPA A 90,000 (see text)
2270// 15 G728 A 8,000 1
2271// 16 DVI4 A 11,025 1
2272// 17 DVI4 A 22,050 1
2273// 18 G729 A 8,000 1
2274struct StaticPayloadAudioCodec {
2275 const char* name;
2276 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002277 size_t channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002278};
2279static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2280 { "PCMU", 8000, 1 },
2281 { "reserved", 0, 0 },
2282 { "reserved", 0, 0 },
2283 { "GSM", 8000, 1 },
2284 { "G723", 8000, 1 },
2285 { "DVI4", 8000, 1 },
2286 { "DVI4", 16000, 1 },
2287 { "LPC", 8000, 1 },
2288 { "PCMA", 8000, 1 },
2289 { "G722", 8000, 1 },
2290 { "L16", 44100, 2 },
2291 { "L16", 44100, 1 },
2292 { "QCELP", 8000, 1 },
2293 { "CN", 8000, 1 },
2294 { "MPA", 90000, 1 },
2295 { "G728", 8000, 1 },
2296 { "DVI4", 11025, 1 },
2297 { "DVI4", 22050, 1 },
2298 { "G729", 8000, 1 },
2299};
2300
2301void MaybeCreateStaticPayloadAudioCodecs(
2302 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2303 if (!media_desc) {
2304 return;
2305 }
deadbeef67cf2c12016-04-13 10:07:16 -07002306 RTC_DCHECK(media_desc->codecs().empty());
solenberg9fa49752016-10-08 13:02:44 -07002307 for (int payload_type : fmts) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002308 if (!media_desc->HasCodec(payload_type) &&
2309 payload_type >= 0 &&
kjellander3e33bfe2016-06-20 07:04:09 -07002310 static_cast<uint32_t>(payload_type) <
2311 arraysize(kStaticPayloadAudioCodecs)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002312 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2313 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002314 size_t channels = kStaticPayloadAudioCodecs[payload_type].channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002315 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
deadbeef67cf2c12016-04-13 10:07:16 -07002316 clock_rate, 0, channels));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002317 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002318 }
2319}
2320
2321template <class C>
2322static C* ParseContentDescription(const std::string& message,
2323 const MediaType media_type,
2324 int mline_index,
2325 const std::string& protocol,
deadbeef67cf2c12016-04-13 10:07:16 -07002326 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002327 size_t* pos,
2328 std::string* content_name,
deadbeef25ed4352016-12-12 18:37:36 -08002329 bool* bundle_only,
Steve Antone831b8c2018-02-01 12:22:16 -08002330 int* msid_signaling,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002331 TransportDescription* transport,
2332 std::vector<JsepIceCandidate*>* candidates,
2333 webrtc::SdpParseError* error) {
2334 C* media_desc = new C();
2335 switch (media_type) {
2336 case cricket::MEDIA_TYPE_AUDIO:
2337 *content_name = cricket::CN_AUDIO;
2338 break;
2339 case cricket::MEDIA_TYPE_VIDEO:
2340 *content_name = cricket::CN_VIDEO;
2341 break;
2342 case cricket::MEDIA_TYPE_DATA:
2343 *content_name = cricket::CN_DATA;
2344 break;
2345 default:
nissec80e7412017-01-11 05:56:46 -08002346 RTC_NOTREACHED();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002347 break;
2348 }
deadbeef67cf2c12016-04-13 10:07:16 -07002349 if (!ParseContent(message, media_type, mline_index, protocol, payload_types,
Steve Antone831b8c2018-02-01 12:22:16 -08002350 pos, content_name, bundle_only, msid_signaling, media_desc,
2351 transport, candidates, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002352 delete media_desc;
zhihuang38989e52017-03-21 11:04:53 -07002353 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002354 }
2355 // Sort the codecs according to the m-line fmt list.
deadbeef67cf2c12016-04-13 10:07:16 -07002356 std::unordered_map<int, int> payload_type_preferences;
2357 // "size + 1" so that the lowest preference payload type has a preference of
2358 // 1, which is greater than the default (0) for payload types not in the fmt
2359 // list.
2360 int preference = static_cast<int>(payload_types.size() + 1);
2361 for (int pt : payload_types) {
2362 payload_type_preferences[pt] = preference--;
2363 }
2364 std::vector<typename C::CodecType> codecs = media_desc->codecs();
2365 std::sort(codecs.begin(), codecs.end(), [&payload_type_preferences](
2366 const typename C::CodecType& a,
2367 const typename C::CodecType& b) {
2368 return payload_type_preferences[a.id] > payload_type_preferences[b.id];
2369 });
2370 media_desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002371 return media_desc;
2372}
2373
2374bool ParseMediaDescription(const std::string& message,
2375 const TransportDescription& session_td,
2376 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377 size_t* pos,
zhihuang38989e52017-03-21 11:04:53 -07002378 const rtc::SocketAddress& session_connection_addr,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002379 cricket::SessionDescription* desc,
2380 std::vector<JsepIceCandidate*>* candidates,
2381 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08002382 RTC_DCHECK(desc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002383 std::string line;
2384 int mline_index = -1;
Steve Antone831b8c2018-02-01 12:22:16 -08002385 int msid_signaling = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002386
2387 // Zero or more media descriptions
2388 // RFC 4566
2389 // m=<media> <port> <proto> <fmt>
2390 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2391 ++mline_index;
2392
2393 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002394 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002395 kSdpDelimiterSpace, &fields);
zstein4b2e0822017-02-17 19:48:38 -08002396
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002397 const size_t expected_min_fields = 4;
2398 if (fields.size() < expected_min_fields) {
2399 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2400 }
deadbeef25ed4352016-12-12 18:37:36 -08002401 bool port_rejected = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002402 // RFC 3264
2403 // To reject an offered stream, the port number in the corresponding stream
2404 // in the answer MUST be set to zero.
2405 if (fields[1] == kMediaPortRejected) {
deadbeef25ed4352016-12-12 18:37:36 -08002406 port_rejected = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002407 }
2408
zhihuang38989e52017-03-21 11:04:53 -07002409 int port = 0;
2410 if (!rtc::FromString<int>(fields[1], &port) || !IsValidPort(port)) {
2411 return ParseFailed(line, "The port number is invalid", error);
2412 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002413 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002414
2415 // <fmt>
deadbeef67cf2c12016-04-13 10:07:16 -07002416 std::vector<int> payload_types;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002417 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002418 for (size_t j = 3 ; j < fields.size(); ++j) {
2419 // TODO(wu): Remove when below bug is fixed.
2420 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002421 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002422 continue;
2423 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002424
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002425 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002426 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002427 return false;
2428 }
deadbeef67cf2c12016-04-13 10:07:16 -07002429 payload_types.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002430 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002431 }
2432
2433 // Make a temporary TransportDescription based on |session_td|.
2434 // Some of this gets overwritten by ParseContent.
deadbeef46eed762016-01-28 13:24:37 -08002435 TransportDescription transport(
2436 session_td.transport_options, session_td.ice_ufrag, session_td.ice_pwd,
2437 session_td.ice_mode, session_td.connection_role,
2438 session_td.identity_fingerprint.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002439
kwibergd1fe2812016-04-27 06:47:29 -07002440 std::unique_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002441 std::string content_name;
deadbeef25ed4352016-12-12 18:37:36 -08002442 bool bundle_only = false;
Steve Antone831b8c2018-02-01 12:22:16 -08002443 int section_msid_signaling = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002444 if (HasAttribute(line, kMediaTypeVideo)) {
2445 content.reset(ParseContentDescription<VideoContentDescription>(
deadbeef67cf2c12016-04-13 10:07:16 -07002446 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
Steve Antone831b8c2018-02-01 12:22:16 -08002447 payload_types, pos, &content_name, &bundle_only,
2448 &section_msid_signaling, &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002449 } else if (HasAttribute(line, kMediaTypeAudio)) {
2450 content.reset(ParseContentDescription<AudioContentDescription>(
deadbeef67cf2c12016-04-13 10:07:16 -07002451 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
Steve Antone831b8c2018-02-01 12:22:16 -08002452 payload_types, pos, &content_name, &bundle_only,
2453 &section_msid_signaling, &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002454 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002455 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002456 ParseContentDescription<DataContentDescription>(
deadbeef67cf2c12016-04-13 10:07:16 -07002457 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
Steve Antone831b8c2018-02-01 12:22:16 -08002458 payload_types, pos, &content_name, &bundle_only,
2459 &section_msid_signaling, &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002460 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002461
zstein4b2e0822017-02-17 19:48:38 -08002462 if (data_desc && IsDtlsSctp(protocol)) {
2463 int p;
2464 if (rtc::FromString(fields[3], &p)) {
2465 if (!AddSctpDataCodec(data_desc, p)) {
2466 return false;
2467 }
2468 } else if (fields[3] == kDefaultSctpmapProtocol) {
2469 data_desc->set_use_sctpmap(false);
2470 }
wu@webrtc.org78187522013-10-07 23:32:02 +00002471 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002472 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002473 RTC_LOG(LS_WARNING) << "Unsupported media type: " << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002474 continue;
2475 }
2476 if (!content.get()) {
2477 // ParseContentDescription returns NULL if failed.
2478 return false;
2479 }
2480
Steve Antone831b8c2018-02-01 12:22:16 -08002481 msid_signaling |= section_msid_signaling;
2482
deadbeef25ed4352016-12-12 18:37:36 -08002483 bool content_rejected = false;
deadbeef12771a12017-01-03 13:53:47 -08002484 // A port of 0 is not interpreted as a rejected m= section when it's
2485 // used along with a=bundle-only.
deadbeef25ed4352016-12-12 18:37:36 -08002486 if (bundle_only) {
deadbeef25ed4352016-12-12 18:37:36 -08002487 if (!port_rejected) {
deadbeef12771a12017-01-03 13:53:47 -08002488 // Usage of bundle-only with a nonzero port is unspecified. So just
2489 // ignore bundle-only if we see this.
2490 bundle_only = false;
Mirko Bonadei675513b2017-11-09 11:09:25 +01002491 RTC_LOG(LS_WARNING)
deadbeef12771a12017-01-03 13:53:47 -08002492 << "a=bundle-only attribute observed with a nonzero "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002493 "port; this usage is unspecified so the attribute is being "
2494 "ignored.";
deadbeef25ed4352016-12-12 18:37:36 -08002495 }
2496 } else {
2497 // If not using bundle-only, interpret port 0 in the normal way; the m=
2498 // section is being rejected.
2499 content_rejected = port_rejected;
2500 }
2501
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002502 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002503 // Set the extmap.
2504 if (!session_extmaps.empty() &&
2505 !content->rtp_header_extensions().empty()) {
2506 return ParseFailed("",
2507 "The a=extmap MUST be either all session level or "
2508 "all media level.",
2509 error);
2510 }
2511 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2512 content->AddRtpHeaderExtension(session_extmaps[i]);
2513 }
2514 }
2515 content->set_protocol(protocol);
zhihuang38989e52017-03-21 11:04:53 -07002516
2517 // Use the session level connection address if the media level addresses are
2518 // not specified.
2519 rtc::SocketAddress address;
2520 address = content->connection_address().IsNil()
2521 ? session_connection_addr
2522 : content->connection_address();
2523 address.SetPort(port);
2524 content->set_connection_address(address);
2525
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002526 desc->AddContent(content_name,
Steve Anton5adfafd2017-12-20 16:34:00 -08002527 IsDtlsSctp(protocol) ? MediaProtocolType::kSctp
2528 : MediaProtocolType::kRtp,
deadbeef25ed4352016-12-12 18:37:36 -08002529 content_rejected, bundle_only, content.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002530 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2531 TransportInfo transport_info(content_name, transport);
2532
2533 if (!desc->AddTransportInfo(transport_info)) {
2534 std::ostringstream description;
2535 description << "Failed to AddTransportInfo with content name: "
2536 << content_name;
2537 return ParseFailed("", description.str(), error);
2538 }
2539 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002540
Steve Antone831b8c2018-02-01 12:22:16 -08002541 desc->set_msid_signaling(msid_signaling);
2542
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002543 size_t end_of_message = message.size();
2544 if (mline_index == -1 && *pos != end_of_message) {
2545 ParseFailed(message, *pos, "Expects m line.", error);
2546 return false;
2547 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002548 return true;
2549}
2550
2551bool VerifyCodec(const cricket::Codec& codec) {
2552 // Codec has not been populated correctly unless the name has been set. This
2553 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2554 // have a corresponding "rtpmap" line.
htab39db842016-12-08 01:50:48 -08002555 return !codec.name.empty();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002556}
2557
2558bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2559 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2560 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2561 iter != codecs.end(); ++iter) {
2562 if (!VerifyCodec(*iter)) {
2563 return false;
2564 }
2565 }
2566 return true;
2567}
2568
2569bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2570 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2571 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2572 iter != codecs.end(); ++iter) {
2573 if (!VerifyCodec(*iter)) {
2574 return false;
2575 }
2576 }
2577 return true;
2578}
2579
2580void AddParameters(const cricket::CodecParameterMap& parameters,
2581 cricket::Codec* codec) {
2582 for (cricket::CodecParameterMap::const_iterator iter =
2583 parameters.begin(); iter != parameters.end(); ++iter) {
2584 codec->SetParam(iter->first, iter->second);
2585 }
2586}
2587
2588void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2589 cricket::Codec* codec) {
2590 codec->AddFeedbackParam(feedback_param);
2591}
2592
2593void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2594 cricket::Codec* codec) {
2595 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2596 feedback_params.params().begin();
2597 iter != feedback_params.params().end(); ++iter) {
2598 codec->AddFeedbackParam(*iter);
2599 }
2600}
2601
2602// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002603// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002604// with that payload type.
2605template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002606T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
magjedb05fa242016-11-11 04:00:16 -08002607 const T* codec = FindCodecById(codecs, payload_type);
2608 if (codec)
2609 return *codec;
2610 // Return empty codec with |payload_type|.
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002611 T ret_val;
magjedb05fa242016-11-11 04:00:16 -08002612 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613 return ret_val;
2614}
2615
2616// Updates or creates a new codec entry in the audio description.
2617template <class T, class U>
2618void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2619 T* desc = static_cast<T*>(content_desc);
2620 std::vector<U> codecs = desc->codecs();
2621 bool found = false;
2622
2623 typename std::vector<U>::iterator iter;
2624 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2625 if (iter->id == codec.id) {
2626 *iter = codec;
2627 found = true;
2628 break;
2629 }
2630 }
2631 if (!found) {
2632 desc->AddCodec(codec);
2633 return;
2634 }
2635 desc->set_codecs(codecs);
2636}
2637
2638// Adds or updates existing codec corresponding to |payload_type| according
2639// to |parameters|.
2640template <class T, class U>
2641void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2642 const cricket::CodecParameterMap& parameters) {
2643 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002644 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2645 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002646 AddParameters(parameters, &new_codec);
2647 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2648}
2649
2650// Adds or updates existing codec corresponding to |payload_type| according
2651// to |feedback_param|.
2652template <class T, class U>
2653void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2654 const cricket::FeedbackParam& feedback_param) {
2655 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002656 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2657 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002658 AddFeedbackParameter(feedback_param, &new_codec);
2659 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2660}
2661
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002662template <class T>
2663bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2664 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002665 if (iter->id == kWildcardPayloadType) {
2666 *wildcard_codec = *iter;
2667 codecs->erase(iter);
2668 return true;
2669 }
2670 }
2671 return false;
2672}
2673
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002674template<class T>
2675void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2676 auto codecs = desc->codecs();
2677 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002678 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2679 return;
2680 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002681 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002682 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2683 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002684 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002685}
2686
2687void AddAudioAttribute(const std::string& name, const std::string& value,
2688 AudioContentDescription* audio_desc) {
2689 if (value.empty()) {
2690 return;
2691 }
2692 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2693 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2694 iter != codecs.end(); ++iter) {
2695 iter->params[name] = value;
2696 }
2697 audio_desc->set_codecs(codecs);
2698}
2699
2700bool ParseContent(const std::string& message,
2701 const MediaType media_type,
2702 int mline_index,
2703 const std::string& protocol,
deadbeef67cf2c12016-04-13 10:07:16 -07002704 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002705 size_t* pos,
2706 std::string* content_name,
deadbeef25ed4352016-12-12 18:37:36 -08002707 bool* bundle_only,
Steve Antone831b8c2018-02-01 12:22:16 -08002708 int* msid_signaling,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002709 MediaContentDescription* media_desc,
2710 TransportDescription* transport,
2711 std::vector<JsepIceCandidate*>* candidates,
2712 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08002713 RTC_DCHECK(media_desc != NULL);
2714 RTC_DCHECK(content_name != NULL);
2715 RTC_DCHECK(transport != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002716
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002717 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08002718 MaybeCreateStaticPayloadAudioCodecs(payload_types, media_desc->as_audio());
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002719 }
2720
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002721 // The media level "ice-ufrag" and "ice-pwd".
2722 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2723 Candidates candidates_orig;
2724 std::string line;
2725 std::string mline_id;
2726 // Tracks created out of the ssrc attributes.
2727 StreamParamsVec tracks;
2728 SsrcInfoVec ssrc_infos;
2729 SsrcGroupVec ssrc_groups;
2730 std::string maxptime_as_string;
2731 std::string ptime_as_string;
Seth Hampson5b4f0752018-04-02 16:31:36 -07002732 std::vector<std::string> stream_ids;
deadbeef9d3584c2016-02-16 17:54:10 -08002733 std::string track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002734
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002735 // Loop until the next m line
2736 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2737 if (!GetLine(message, pos, &line)) {
2738 if (*pos >= message.size()) {
2739 break; // Done parsing
2740 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002741 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002742 }
2743 }
2744
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002745 // RFC 4566
2746 // b=* (zero or more bandwidth information lines)
2747 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2748 std::string bandwidth;
2749 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2750 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2751 return false;
2752 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002753 int b = 0;
2754 if (!GetValueFromString(line, bandwidth, &b, error)) {
2755 return false;
2756 }
deadbeef3e8016e2017-08-03 17:49:30 -07002757 // TODO(deadbeef): Historically, applications may be setting a value
2758 // of -1 to mean "unset any previously set bandwidth limit", even
2759 // though ommitting the "b=AS" entirely will do just that. Once we've
2760 // transitioned applications to doing the right thing, it would be
2761 // better to treat this as a hard error instead of just ignoring it.
2762 if (b == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002763 RTC_LOG(LS_WARNING)
2764 << "Ignoring \"b=AS:-1\"; will be treated as \"no "
2765 "bandwidth limit\".";
deadbeef3e8016e2017-08-03 17:49:30 -07002766 continue;
2767 }
deadbeefbc88c6b2017-08-02 11:26:34 -07002768 if (b < 0) {
2769 return ParseFailed(line, "b=AS value can't be negative.", error);
2770 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002771 // We should never use more than the default bandwidth for RTP-based
2772 // data channels. Don't allow SDP to set the bandwidth, because
2773 // that would give JS the opportunity to "break the Internet".
2774 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2775 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2776 b > cricket::kDataMaxBandwidth / 1000) {
2777 std::ostringstream description;
2778 description << "RTP-based data channels may not send more than "
2779 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2780 return ParseFailed(line, description.str(), error);
2781 }
deadbeefb2362572016-12-13 16:37:06 -08002782 // Prevent integer overflow.
2783 b = std::min(b, INT_MAX / 1000);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002784 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002785 }
2786 }
2787 continue;
2788 }
2789
zhihuang38989e52017-03-21 11:04:53 -07002790 // Parse the media level connection data.
2791 if (IsLineType(line, kLineTypeConnection)) {
2792 rtc::SocketAddress addr;
2793 if (!ParseConnectionData(line, &addr, error)) {
2794 return false;
2795 }
2796 media_desc->set_connection_address(addr);
2797 continue;
2798 }
2799
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002800 if (!IsLineType(line, kLineTypeAttributes)) {
Steve Anton36b29d12017-10-30 09:57:42 -07002801 // TODO(deadbeef): Handle other lines if needed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01002802 RTC_LOG(LS_INFO) << "Ignored line: " << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002803 continue;
2804 }
2805
2806 // Handle attributes common to SCTP and RTP.
2807 if (HasAttribute(line, kAttributeMid)) {
2808 // RFC 3388
2809 // mid-attribute = "a=mid:" identification-tag
2810 // identification-tag = token
2811 // Use the mid identification-tag as the content name.
2812 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2813 return false;
2814 }
2815 *content_name = mline_id;
deadbeef25ed4352016-12-12 18:37:36 -08002816 } else if (HasAttribute(line, kAttributeBundleOnly)) {
2817 *bundle_only = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002818 } else if (HasAttribute(line, kAttributeCandidate)) {
2819 Candidate candidate;
2820 if (!ParseCandidate(line, &candidate, error, false)) {
2821 return false;
2822 }
deadbeef7bcdb692017-01-20 12:43:58 -08002823 // ParseCandidate will parse non-standard ufrag and password attributes,
2824 // since it's used for candidate trickling, but we only want to process
2825 // the "a=ice-ufrag"/"a=ice-pwd" values in a session description, so
2826 // strip them off at this point.
2827 candidate.set_username(std::string());
2828 candidate.set_password(std::string());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002829 candidates_orig.push_back(candidate);
2830 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2831 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2832 return false;
2833 }
2834 } else if (HasAttribute(line, kAttributeIcePwd)) {
2835 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2836 return false;
2837 }
2838 } else if (HasAttribute(line, kAttributeIceOption)) {
2839 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2840 return false;
2841 }
2842 } else if (HasAttribute(line, kAttributeFmtp)) {
2843 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2844 return false;
2845 }
2846 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002847 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002848
2849 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2850 return false;
2851 }
2852 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002853 } else if (HasAttribute(line, kAttributeSetup)) {
2854 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2855 return false;
2856 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002857 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
deadbeef7e146cb2016-09-28 10:04:34 -07002858 if (media_type != cricket::MEDIA_TYPE_DATA) {
2859 return ParseFailed(
2860 line, "sctp-port attribute found in non-data media description.",
2861 error);
2862 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002863 int sctp_port;
2864 if (!ParseSctpPort(line, &sctp_port, error)) {
2865 return false;
2866 }
Steve Antonb1c1de12017-12-21 15:14:30 -08002867 if (!AddSctpDataCodec(media_desc->as_data(), sctp_port)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002868 return false;
2869 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002870 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002871 //
2872 // RTP specific attrubtes
2873 //
2874 if (HasAttribute(line, kAttributeRtcpMux)) {
2875 media_desc->set_rtcp_mux(true);
deadbeef13871492015-12-09 12:37:51 -08002876 } else if (HasAttribute(line, kAttributeRtcpReducedSize)) {
2877 media_desc->set_rtcp_reduced_size(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002878 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2879 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2880 return false;
2881 }
2882 } else if (HasAttribute(line, kAttributeSsrc)) {
Steve Antone831b8c2018-02-01 12:22:16 -08002883 if (!ParseSsrcAttribute(line, &ssrc_infos, msid_signaling, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002884 return false;
2885 }
2886 } else if (HasAttribute(line, kAttributeCrypto)) {
2887 if (!ParseCryptoAttribute(line, media_desc, error)) {
2888 return false;
2889 }
2890 } else if (HasAttribute(line, kAttributeRtpmap)) {
deadbeef67cf2c12016-04-13 10:07:16 -07002891 if (!ParseRtpmapAttribute(line, media_type, payload_types, media_desc,
2892 error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002893 return false;
2894 }
2895 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2896 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2897 return false;
2898 }
2899 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2900 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2901 return false;
2902 }
2903 } else if (HasAttribute(line, kCodecParamPTime)) {
2904 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2905 return false;
2906 }
2907 } else if (HasAttribute(line, kAttributeSendOnly)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002908 media_desc->set_direction(RtpTransceiverDirection::kSendOnly);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002909 } else if (HasAttribute(line, kAttributeRecvOnly)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002910 media_desc->set_direction(RtpTransceiverDirection::kRecvOnly);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002911 } else if (HasAttribute(line, kAttributeInactive)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002912 media_desc->set_direction(RtpTransceiverDirection::kInactive);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002913 } else if (HasAttribute(line, kAttributeSendRecv)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002914 media_desc->set_direction(RtpTransceiverDirection::kSendRecv);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002915 } else if (HasAttribute(line, kAttributeExtmap)) {
isheriff6f8d6862016-05-26 11:24:55 -07002916 RtpExtension extmap;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002917 if (!ParseExtmap(line, &extmap, error)) {
2918 return false;
2919 }
2920 media_desc->AddRtpHeaderExtension(extmap);
2921 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2922 // Experimental attribute. Conference mode activates more aggressive
2923 // AEC and NS settings.
Steve Anton36b29d12017-10-30 09:57:42 -07002924 // TODO(deadbeef): expose API to set these directly.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002925 std::string flag_value;
2926 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2927 return false;
2928 }
2929 if (flag_value.compare(kValueConference) == 0)
2930 media_desc->set_conference_mode(true);
deadbeef9d3584c2016-02-16 17:54:10 -08002931 } else if (HasAttribute(line, kAttributeMsid)) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07002932 if (!ParseMsidAttribute(line, &stream_ids, &track_id, error)) {
deadbeef9d3584c2016-02-16 17:54:10 -08002933 return false;
2934 }
Steve Antone831b8c2018-02-01 12:22:16 -08002935 *msid_signaling |= cricket::kMsidSignalingMediaSection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002936 }
2937 } else {
2938 // Only parse lines that we are interested of.
Mirko Bonadei675513b2017-11-09 11:09:25 +01002939 RTC_LOG(LS_INFO) << "Ignored line: " << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002940 continue;
2941 }
2942 }
2943
2944 // Create tracks from the |ssrc_infos|.
Taylor Brandstetter5de6b752016-03-09 17:02:30 -08002945 // If the stream_id/track_id for all SSRCS are identical, one StreamParams
2946 // will be created in CreateTracksFromSsrcInfos, containing all the SSRCs from
2947 // the m= section.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002948 CreateTracksFromSsrcInfos(ssrc_infos, stream_ids, track_id, &tracks,
2949 *msid_signaling);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002950
2951 // Add the ssrc group to the track.
2952 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2953 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2954 if (ssrc_group->ssrcs.empty()) {
2955 continue;
2956 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002957 uint32_t ssrc = ssrc_group->ssrcs.front();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002958 for (StreamParamsVec::iterator track = tracks.begin();
2959 track != tracks.end(); ++track) {
2960 if (track->has_ssrc(ssrc)) {
2961 track->ssrc_groups.push_back(*ssrc_group);
2962 }
2963 }
2964 }
2965
2966 // Add the new tracks to the |media_desc|.
deadbeef9d3584c2016-02-16 17:54:10 -08002967 for (StreamParams& track : tracks) {
2968 media_desc->AddStream(track);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002969 }
2970
2971 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08002972 AudioContentDescription* audio_desc = media_desc->as_audio();
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002973 UpdateFromWildcardCodecs(audio_desc);
2974
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002975 // Verify audio codec ensures that no audio codec has been populated with
2976 // only fmtp.
2977 if (!VerifyAudioCodecs(audio_desc)) {
2978 return ParseFailed("Failed to parse audio codecs correctly.", error);
2979 }
2980 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2981 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2982 }
2983
2984 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08002985 VideoContentDescription* video_desc = media_desc->as_video();
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002986 UpdateFromWildcardCodecs(video_desc);
2987 // Verify video codec ensures that no video codec has been populated with
2988 // only rtcp-fb.
2989 if (!VerifyVideoCodecs(video_desc)) {
2990 return ParseFailed("Failed to parse video codecs correctly.", error);
2991 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002992 }
2993
2994 // RFC 5245
2995 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2996 for (Candidates::iterator it = candidates_orig.begin();
2997 it != candidates_orig.end(); ++it) {
nisseede5da42017-01-12 05:15:36 -08002998 RTC_DCHECK((*it).username().empty() ||
2999 (*it).username() == transport->ice_ufrag);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003000 (*it).set_username(transport->ice_ufrag);
nisseede5da42017-01-12 05:15:36 -08003001 RTC_DCHECK((*it).password().empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003002 (*it).set_password(transport->ice_pwd);
3003 candidates->push_back(
3004 new JsepIceCandidate(mline_id, mline_index, *it));
3005 }
3006 return true;
3007}
3008
Steve Antone831b8c2018-02-01 12:22:16 -08003009bool ParseSsrcAttribute(const std::string& line,
3010 SsrcInfoVec* ssrc_infos,
3011 int* msid_signaling,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003012 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08003013 RTC_DCHECK(ssrc_infos != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003014 // RFC 5576
3015 // a=ssrc:<ssrc-id> <attribute>
3016 // a=ssrc:<ssrc-id> <attribute>:<value>
3017 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07003018 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
3019 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003020 const size_t expected_fields = 2;
3021 return ParseFailedExpectFieldNum(line, expected_fields, error);
3022 }
3023
3024 // ssrc:<ssrc-id>
3025 std::string ssrc_id_s;
3026 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
3027 return false;
3028 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02003029 uint32_t ssrc_id = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003030 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
3031 return false;
3032 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003033
3034 std::string attribute;
3035 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07003036 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003037 std::ostringstream description;
3038 description << "Failed to get the ssrc attribute value from " << field2
3039 << ". Expected format <attribute>:<value>.";
3040 return ParseFailed(line, description.str(), error);
3041 }
3042
3043 // Check if there's already an item for this |ssrc_id|. Create a new one if
3044 // there isn't.
3045 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
3046 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
3047 if (ssrc_info->ssrc_id == ssrc_id) {
3048 break;
3049 }
3050 }
3051 if (ssrc_info == ssrc_infos->end()) {
3052 SsrcInfo info;
3053 info.ssrc_id = ssrc_id;
3054 ssrc_infos->push_back(info);
3055 ssrc_info = ssrc_infos->end() - 1;
3056 }
3057
3058 // Store the info to the |ssrc_info|.
3059 if (attribute == kSsrcAttributeCname) {
3060 // RFC 5576
3061 // cname:<value>
3062 ssrc_info->cname = value;
3063 } else if (attribute == kSsrcAttributeMsid) {
3064 // draft-alvestrand-mmusic-msid-00
Seth Hampson5b4f0752018-04-02 16:31:36 -07003065 // msid:identifier [appdata]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003066 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003067 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003068 if (fields.size() < 1 || fields.size() > 2) {
3069 return ParseFailed(line,
3070 "Expected format \"msid:<identifier>[ <appdata>]\".",
3071 error);
3072 }
deadbeef9d3584c2016-02-16 17:54:10 -08003073 ssrc_info->stream_id = fields[0];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003074 if (fields.size() == 2) {
deadbeef9d3584c2016-02-16 17:54:10 -08003075 ssrc_info->track_id = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003076 }
Steve Antone831b8c2018-02-01 12:22:16 -08003077 *msid_signaling |= cricket::kMsidSignalingSsrcAttribute;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003078 } else if (attribute == kSsrcAttributeMslabel) {
3079 // draft-alvestrand-rtcweb-mid-01
3080 // mslabel:<value>
3081 ssrc_info->mslabel = value;
3082 } else if (attribute == kSSrcAttributeLabel) {
3083 // The label isn't defined.
3084 // label:<value>
3085 ssrc_info->label = value;
3086 }
3087 return true;
3088}
3089
3090bool ParseSsrcGroupAttribute(const std::string& line,
3091 SsrcGroupVec* ssrc_groups,
3092 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08003093 RTC_DCHECK(ssrc_groups != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003094 // RFC 5576
3095 // a=ssrc-group:<semantics> <ssrc-id> ...
3096 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003097 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003098 kSdpDelimiterSpace, &fields);
3099 const size_t expected_min_fields = 2;
3100 if (fields.size() < expected_min_fields) {
3101 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3102 }
3103 std::string semantics;
3104 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
3105 return false;
3106 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02003107 std::vector<uint32_t> ssrcs;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003108 for (size_t i = 1; i < fields.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02003109 uint32_t ssrc = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003110 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
3111 return false;
3112 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003113 ssrcs.push_back(ssrc);
3114 }
3115 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
3116 return true;
3117}
3118
3119bool ParseCryptoAttribute(const std::string& line,
3120 MediaContentDescription* media_desc,
3121 SdpParseError* error) {
3122 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003123 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003124 kSdpDelimiterSpace, &fields);
3125 // RFC 4568
3126 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
3127 const size_t expected_min_fields = 3;
3128 if (fields.size() < expected_min_fields) {
3129 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3130 }
3131 std::string tag_value;
3132 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
3133 return false;
3134 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003135 int tag = 0;
3136 if (!GetValueFromString(line, tag_value, &tag, error)) {
3137 return false;
3138 }
jbauch083b73f2015-07-16 02:46:32 -07003139 const std::string& crypto_suite = fields[1];
3140 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003141 std::string session_params;
3142 if (fields.size() > 3) {
3143 session_params = fields[3];
3144 }
3145 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
3146 session_params));
3147 return true;
3148}
3149
3150// Updates or creates a new codec entry in the audio description with according
deadbeef67cf2c12016-04-13 10:07:16 -07003151// to |name|, |clockrate|, |bitrate|, and |channels|.
3152void UpdateCodec(int payload_type,
3153 const std::string& name,
3154 int clockrate,
3155 int bitrate,
3156 size_t channels,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003157 AudioContentDescription* audio_desc) {
3158 // Codec may already be populated with (only) optional parameters
3159 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00003160 cricket::AudioCodec codec =
3161 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003162 codec.name = name;
3163 codec.clockrate = clockrate;
3164 codec.bitrate = bitrate;
3165 codec.channels = channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003166 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
3167 codec);
3168}
3169
3170// Updates or creates a new codec entry in the video description according to
deadbeef67cf2c12016-04-13 10:07:16 -07003171// |name|, |width|, |height|, and |framerate|.
3172void UpdateCodec(int payload_type,
3173 const std::string& name,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003174 VideoContentDescription* video_desc) {
3175 // Codec may already be populated with (only) optional parameters
3176 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00003177 cricket::VideoCodec codec =
3178 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003179 codec.name = name;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003180 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
3181 codec);
3182}
3183
3184bool ParseRtpmapAttribute(const std::string& line,
3185 const MediaType media_type,
deadbeef67cf2c12016-04-13 10:07:16 -07003186 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003187 MediaContentDescription* media_desc,
3188 SdpParseError* error) {
3189 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003190 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003191 kSdpDelimiterSpace, &fields);
3192 // RFC 4566
3193 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
3194 const size_t expected_min_fields = 2;
3195 if (fields.size() < expected_min_fields) {
3196 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3197 }
3198 std::string payload_type_value;
3199 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
3200 return false;
3201 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003202 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003203 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
3204 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003205 return false;
3206 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003207
deadbeef67cf2c12016-04-13 10:07:16 -07003208 if (std::find(payload_types.begin(), payload_types.end(), payload_type) ==
3209 payload_types.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003210 RTC_LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003211 "<fmt> of the m-line: "
3212 << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003213 return true;
3214 }
jbauch083b73f2015-07-16 02:46:32 -07003215 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003216 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003217 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003218 // <encoding name>/<clock rate>[/<encodingparameters>]
3219 // 2 mandatory fields
3220 if (codec_params.size() < 2 || codec_params.size() > 3) {
3221 return ParseFailed(line,
3222 "Expected format \"<encoding name>/<clock rate>"
3223 "[/<encodingparameters>]\".",
3224 error);
3225 }
jbauch083b73f2015-07-16 02:46:32 -07003226 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003227 int clock_rate = 0;
3228 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
3229 return false;
3230 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003231 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08003232 VideoContentDescription* video_desc = media_desc->as_video();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003233 UpdateCodec(payload_type, encoding_name,
deadbeef67cf2c12016-04-13 10:07:16 -07003234 video_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003235 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3236 // RFC 4566
3237 // For audio streams, <encoding parameters> indicates the number
3238 // of audio channels. This parameter is OPTIONAL and may be
3239 // omitted if the number of channels is one, provided that no
3240 // additional parameters are needed.
Peter Kasting69558702016-01-12 16:26:35 -08003241 size_t channels = 1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003242 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003243 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
3244 return false;
3245 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246 }
Steve Antonb1c1de12017-12-21 15:14:30 -08003247 AudioContentDescription* audio_desc = media_desc->as_audio();
ossue1405ad2017-01-23 08:55:48 -08003248 UpdateCodec(payload_type, encoding_name, clock_rate, 0, channels,
deadbeef67cf2c12016-04-13 10:07:16 -07003249 audio_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003250 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonb1c1de12017-12-21 15:14:30 -08003251 DataContentDescription* data_desc = media_desc->as_data();
deadbeef67cf2c12016-04-13 10:07:16 -07003252 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003253 }
3254 return true;
3255}
3256
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003257bool ParseFmtpParam(const std::string& line, std::string* parameter,
3258 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003259 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003260 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
3261 return false;
3262 }
3263 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003264 return true;
3265}
3266
3267bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
3268 MediaContentDescription* media_desc,
3269 SdpParseError* error) {
3270 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3271 media_type != cricket::MEDIA_TYPE_VIDEO) {
3272 return true;
3273 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003274
3275 std::string line_payload;
3276 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277
3278 // RFC 5576
3279 // a=fmtp:<format> <format specific parameters>
3280 // At least two fields, whereas the second one is any of the optional
3281 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07003282 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
3283 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003284 ParseFailedExpectMinFieldNum(line, 2, error);
3285 return false;
3286 }
3287
Donald Curtis0e07f922015-05-15 09:21:23 -07003288 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003289 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07003290 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003291 return false;
3292 }
3293
Donald Curtis0e07f922015-05-15 09:21:23 -07003294 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07003295 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3296 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003297 return false;
3298 }
3299
3300 // Parse out format specific parameters.
3301 std::vector<std::string> fields;
3302 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
3303
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003304 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07003305 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003306 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003307 // Only fmtps with equals are currently supported. Other fmtp types
3308 // should be ignored. Unknown fmtps do not constitute an error.
3309 continue;
3310 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003311
3312 std::string name;
3313 std::string value;
3314 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003315 return false;
3316 }
3317 codec_params[name] = value;
3318 }
3319
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003320 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3321 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003322 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003323 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3324 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003325 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003326 }
3327 return true;
3328}
3329
3330bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3331 MediaContentDescription* media_desc,
3332 SdpParseError* error) {
3333 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3334 media_type != cricket::MEDIA_TYPE_VIDEO) {
3335 return true;
3336 }
3337 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003338 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003339 if (rtcp_fb_fields.size() < 2) {
3340 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3341 }
3342 std::string payload_type_string;
3343 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3344 error)) {
3345 return false;
3346 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003347 int payload_type = kWildcardPayloadType;
3348 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003349 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3350 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003351 return false;
3352 }
3353 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003354 std::string id = rtcp_fb_fields[1];
3355 std::string param = "";
3356 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3357 iter != rtcp_fb_fields.end(); ++iter) {
3358 param.append(*iter);
3359 }
3360 const cricket::FeedbackParam feedback_param(id, param);
3361
3362 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003363 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3364 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003365 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003366 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3367 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003368 }
3369 return true;
3370}
3371
3372} // namespace webrtc