blob: 701fbb75c1ea9cb02e63a35c4dd8faabfd482493 [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.
Taylor Brandstetter93a7b242018-04-16 10:45:24 -0700460 //
461 // However, an exception to the whitespace rule is made for "s=", since
462 // RFC4566 also says:
463 //
464 // If a session has no meaningful name, the value "s= " SHOULD be used
465 // (i.e., a single space as the session name).
466 if (line->length() < 3 || !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000467 cline[1] != kSdpDelimiterEqual ||
Taylor Brandstetter93a7b242018-04-16 10:45:24 -0700468 (cline[0] != kLineTypeSessionName && cline[2] == kSdpDelimiterSpace)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000469 *pos = line_begin;
470 return false;
471 }
472 return true;
473}
474
475// Init |os| to "|type|=|value|".
476static void InitLine(const char type,
477 const std::string& value,
478 std::ostringstream* os) {
479 os->str("");
480 *os << type << kSdpDelimiterEqual << value;
481}
482
483// Init |os| to "a=|attribute|".
484static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
485 InitLine(kLineTypeAttributes, attribute, os);
486}
487
488// Writes a SDP attribute line based on |attribute| and |value| to |message|.
489static void AddAttributeLine(const std::string& attribute, int value,
490 std::string* message) {
491 std::ostringstream os;
492 InitAttrLine(attribute, &os);
493 os << kSdpDelimiterColon << value;
494 AddLine(os.str(), message);
495}
496
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000497static bool IsLineType(const std::string& message,
498 const char type,
499 size_t line_start) {
500 if (message.size() < line_start + kLinePrefixLength) {
501 return false;
502 }
503 const char* cmessage = message.c_str();
504 return (cmessage[line_start] == type &&
505 cmessage[line_start + 1] == kSdpDelimiterEqual);
506}
507
508static bool IsLineType(const std::string& line,
509 const char type) {
510 return IsLineType(line, type, 0);
511}
512
513static bool GetLineWithType(const std::string& message, size_t* pos,
514 std::string* line, const char type) {
515 if (!IsLineType(message, type, *pos)) {
516 return false;
517 }
518
519 if (!GetLine(message, pos, line))
520 return false;
521
522 return true;
523}
524
525static bool HasAttribute(const std::string& line,
526 const std::string& attribute) {
527 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
528}
529
Peter Boström0c4e06b2015-10-07 12:23:21 +0200530static bool AddSsrcLine(uint32_t ssrc_id,
531 const std::string& attribute,
532 const std::string& value,
533 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000534 // RFC 5576
535 // a=ssrc:<ssrc-id> <attribute>:<value>
536 std::ostringstream os;
537 InitAttrLine(kAttributeSsrc, &os);
538 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
539 << attribute << kSdpDelimiterColon << value;
540 return AddLine(os.str(), message);
541}
542
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000543// Get value only from <attribute>:<value>.
544static bool GetValue(const std::string& message, const std::string& attribute,
545 std::string* value, SdpParseError* error) {
546 std::string leftpart;
Donald Curtis0e07f922015-05-15 09:21:23 -0700547 if (!rtc::tokenize_first(message, kSdpDelimiterColon, &leftpart, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000548 return ParseFailedGetValue(message, attribute, error);
549 }
550 // The left part should end with the expected attribute.
551 if (leftpart.length() < attribute.length() ||
552 leftpart.compare(leftpart.length() - attribute.length(),
553 attribute.length(), attribute) != 0) {
554 return ParseFailedGetValue(message, attribute, error);
555 }
556 return true;
557}
558
559static bool CaseInsensitiveFind(std::string str1, std::string str2) {
560 std::transform(str1.begin(), str1.end(), str1.begin(),
561 ::tolower);
562 std::transform(str2.begin(), str2.end(), str2.begin(),
563 ::tolower);
564 return str1.find(str2) != std::string::npos;
565}
566
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000567template <class T>
568static bool GetValueFromString(const std::string& line,
569 const std::string& s,
570 T* t,
571 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000572 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000573 std::ostringstream description;
574 description << "Invalid value: " << s << ".";
575 return ParseFailed(line, description.str(), error);
576 }
577 return true;
578}
579
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000580static bool GetPayloadTypeFromString(const std::string& line,
581 const std::string& s,
582 int* payload_type,
583 SdpParseError* error) {
584 return GetValueFromString(line, s, payload_type, error) &&
585 cricket::IsValidRtpPayloadType(*payload_type);
586}
587
Seth Hampson5897a6e2018-04-03 11:16:33 -0700588// Creates a StreamParams track in the case when no SSRC lines are signaled.
589// This is a track that does not contain SSRCs and only contains
590// stream_ids/track_id if it's signaled with a=msid lines.
591void CreateTrackWithNoSsrcs(const std::vector<std::string>& msid_stream_ids,
592 const std::string& msid_track_id,
593 StreamParamsVec* tracks) {
594 StreamParams track;
595 if (msid_track_id.empty() || msid_stream_ids.empty()) {
596 // We only create an unsignaled track if a=msid lines were signaled.
597 return;
598 }
599 track.set_stream_ids(msid_stream_ids);
600 track.id = msid_track_id;
601 tracks->push_back(track);
602}
603
604// Creates the StreamParams tracks, for the case when SSRC lines are signaled.
605// |msid_stream_ids| and |msid_track_id| represent the stream/track ID from the
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800606// "a=msid" attribute, if it exists. They are empty if the attribute does not
Seth Hampson5897a6e2018-04-03 11:16:33 -0700607// exist. We prioritize getting stream_ids/track_ids signaled in a=msid lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000608void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
Seth Hampson5b4f0752018-04-02 16:31:36 -0700609 const std::vector<std::string>& msid_stream_ids,
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800610 const std::string& msid_track_id,
Seth Hampson5b4f0752018-04-02 16:31:36 -0700611 StreamParamsVec* tracks,
612 int msid_signaling) {
nisseede5da42017-01-12 05:15:36 -0800613 RTC_DCHECK(tracks != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000614 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
615 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
616 if (ssrc_info->cname.empty()) {
617 continue;
618 }
619
Seth Hampson5b4f0752018-04-02 16:31:36 -0700620 std::vector<std::string> stream_ids;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000621 std::string track_id;
Seth Hampson5b4f0752018-04-02 16:31:36 -0700622 if (msid_signaling & cricket::kMsidSignalingMediaSection) {
623 // This is the case with Unified Plan SDP msid signaling.
624 stream_ids = msid_stream_ids;
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +0000625 track_id = msid_track_id;
Seth Hampson5b4f0752018-04-02 16:31:36 -0700626 } else if (msid_signaling & cricket::kMsidSignalingSsrcAttribute) {
627 // This is the case with Plan B SDP msid signaling.
628 stream_ids.push_back(ssrc_info->stream_id);
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +0000629 track_id = ssrc_info->track_id;
Seth Hampson5b4f0752018-04-02 16:31:36 -0700630 } else if (!ssrc_info->mslabel.empty()) {
631 // Since there's no a=msid or a=ssrc msid signaling, this is a sdp from
632 // an older version of client that doesn't support msid.
633 // In that case, we use the mslabel and label to construct the track.
634 stream_ids.push_back(ssrc_info->mslabel);
635 track_id = ssrc_info->label;
636 } else {
637 // Since no media streams isn't supported with older SDP signaling, we
638 // use a default a stream id.
639 stream_ids.push_back(kDefaultMsid);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000640 }
Seth Hampson5b4f0752018-04-02 16:31:36 -0700641 // If a track ID wasn't populated from the SSRC attributes OR the
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800642 // msid attribute, use default/random values.
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800643 if (track_id.empty()) {
644 // TODO(ronghuawu): What should we do if the track id doesn't appear?
645 // Create random string (which will be used as track label later)?
646 track_id = rtc::CreateRandomString(8);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000647 }
648
649 StreamParamsVec::iterator track = tracks->begin();
650 for (; track != tracks->end(); ++track) {
651 if (track->id == track_id) {
652 break;
653 }
654 }
655 if (track == tracks->end()) {
656 // If we don't find an existing track, create a new one.
657 tracks->push_back(StreamParams());
658 track = tracks->end() - 1;
659 }
660 track->add_ssrc(ssrc_info->ssrc_id);
661 track->cname = ssrc_info->cname;
Seth Hampson5b4f0752018-04-02 16:31:36 -0700662 track->set_stream_ids(stream_ids);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000663 track->id = track_id;
664 }
665}
666
Seth Hampson845e8782018-03-02 11:34:10 -0800667void GetMediaStreamIds(const ContentInfo* content,
668 std::set<std::string>* labels) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800669 for (const StreamParams& stream_params :
670 content->media_description()->streams()) {
Seth Hampson845e8782018-03-02 11:34:10 -0800671 for (const std::string& stream_id : stream_params.stream_ids()) {
672 labels->insert(stream_id);
Steve Anton5a26a3a2018-02-28 11:38:47 -0800673 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000674 }
675}
676
677// RFC 5245
678// It is RECOMMENDED that default candidates be chosen based on the
679// likelihood of those candidates to work with the peer that is being
680// contacted. It is RECOMMENDED that relayed > reflexive > host.
681static const int kPreferenceUnknown = 0;
682static const int kPreferenceHost = 1;
683static const int kPreferenceReflexive = 2;
684static const int kPreferenceRelayed = 3;
685
686static int GetCandidatePreferenceFromType(const std::string& type) {
687 int preference = kPreferenceUnknown;
688 if (type == cricket::LOCAL_PORT_TYPE) {
689 preference = kPreferenceHost;
690 } else if (type == cricket::STUN_PORT_TYPE) {
691 preference = kPreferenceReflexive;
692 } else if (type == cricket::RELAY_PORT_TYPE) {
693 preference = kPreferenceRelayed;
694 } else {
nissec80e7412017-01-11 05:56:46 -0800695 RTC_NOTREACHED();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000696 }
697 return preference;
698}
699
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000700// Get ip and port of the default destination from the |candidates| with the
701// given value of |component_id|. The default candidate should be the one most
702// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000703// RFC 5245
704// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
Steve Anton36b29d12017-10-30 09:57:42 -0700705// TODO(deadbeef): Decide the default destination in webrtcsession and
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000706// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000707static void GetDefaultDestination(
708 const std::vector<Candidate>& candidates,
709 int component_id, std::string* port,
710 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000711 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000712 *port = kDummyPort;
713 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000714 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000715 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716 for (std::vector<Candidate>::const_iterator it = candidates.begin();
717 it != candidates.end(); ++it) {
718 if (it->component() != component_id) {
719 continue;
720 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000721 // Default destination should be UDP only.
722 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723 continue;
724 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000725 const int preference = GetCandidatePreferenceFromType(it->type());
726 const int family = it->address().ipaddr().family();
727 // See if this candidate is more preferable then the current one if it's the
728 // same family. Or if the current family is IPv4 already so we could safely
729 // ignore all IPv6 ones. WebRTC bug 4269.
730 // http://code.google.com/p/webrtc/issues/detail?id=4269
731 if ((preference <= current_preference && current_family == family) ||
732 (current_family == AF_INET && family == AF_INET6)) {
733 continue;
734 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000735 if (family == AF_INET) {
736 addr_type->assign(kConnectionIpv4Addrtype);
737 } else if (family == AF_INET6) {
738 addr_type->assign(kConnectionIpv6Addrtype);
739 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000740 current_preference = preference;
741 current_family = family;
742 *port = it->address().PortAsString();
743 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000744 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000745}
746
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000747// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
748static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000749 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
750 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
751 &rtcp_port, &rtcp_ip, &addr_type);
752 // Found default RTCP candidate.
753 // RFC 5245
754 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
755 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000757 // RFC 3605
758 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
759 // connection-address] CRLF
760 std::ostringstream os;
761 InitAttrLine(kAttributeRtcp, &os);
762 os << kSdpDelimiterColon
763 << rtcp_port << " "
764 << kConnectionNettype << " "
765 << addr_type << " "
766 << rtcp_ip;
767 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000768 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000769}
770
771// Get candidates according to the mline index from SessionDescriptionInterface.
772static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
773 int mline_index,
774 std::vector<Candidate>* candidates) {
775 if (!candidates) {
776 return;
777 }
778 const IceCandidateCollection* cc = desci.candidates(mline_index);
779 for (size_t i = 0; i < cc->count(); ++i) {
780 const IceCandidateInterface* candidate = cc->at(i);
781 candidates->push_back(candidate->candidate());
782 }
783}
784
deadbeef90f1e1e2017-02-10 12:35:05 -0800785static bool IsValidPort(int port) {
786 return port >= 0 && port <= 65535;
787}
788
Steve Antone831b8c2018-02-01 12:22:16 -0800789std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000790 const cricket::SessionDescription* desc = jdesc.description();
791 if (!desc) {
792 return "";
793 }
794
795 std::string message;
796
797 // Session Description.
798 AddLine(kSessionVersion, &message);
799 // Session Origin
800 // RFC 4566
801 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
802 // <unicast-address>
803 std::ostringstream os;
804 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
jbauch083b73f2015-07-16 02:46:32 -0700805 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000806 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700807 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000808 kSessionOriginSessionVersion : jdesc.session_version();
809 os << " " << session_id << " " << session_version << " "
810 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
811 << kSessionOriginAddress;
812 AddLine(os.str(), &message);
813 AddLine(kSessionName, &message);
814
815 // Time Description.
816 AddLine(kTimeDescription, &message);
817
818 // Group
819 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
820 std::string group_line = kAttrGroup;
821 const cricket::ContentGroup* group =
822 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
nisseede5da42017-01-12 05:15:36 -0800823 RTC_DCHECK(group != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000824 const cricket::ContentNames& content_names = group->content_names();
825 for (cricket::ContentNames::const_iterator it = content_names.begin();
826 it != content_names.end(); ++it) {
827 group_line.append(" ");
828 group_line.append(*it);
829 }
830 AddLine(group_line, &message);
831 }
832
833 // MediaStream semantics
834 InitAttrLine(kAttributeMsidSemantics, &os);
835 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000836
Seth Hampson845e8782018-03-02 11:34:10 -0800837 std::set<std::string> media_stream_ids;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000838 const ContentInfo* audio_content = GetFirstAudioContent(desc);
839 if (audio_content)
Seth Hampson845e8782018-03-02 11:34:10 -0800840 GetMediaStreamIds(audio_content, &media_stream_ids);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000841
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842 const ContentInfo* video_content = GetFirstVideoContent(desc);
843 if (video_content)
Seth Hampson845e8782018-03-02 11:34:10 -0800844 GetMediaStreamIds(video_content, &media_stream_ids);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000845
Seth Hampson845e8782018-03-02 11:34:10 -0800846 for (std::set<std::string>::const_iterator it = media_stream_ids.begin();
847 it != media_stream_ids.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848 os << " " << *it;
849 }
850 AddLine(os.str(), &message);
851
Taylor Brandstetter2f65ec52018-05-24 11:37:28 -0700852 // a=ice-lite
853 //
854 // TODO(deadbeef): It's weird that we need to iterate TransportInfos for
855 // this, when it's a session-level attribute. It really should be moved to a
856 // session-level structure like SessionDescription.
857 for (const cricket::TransportInfo& transport : desc->transport_infos()) {
858 if (transport.description.ice_mode == cricket::ICEMODE_LITE) {
859 InitAttrLine(kAttributeIceLite, &os);
860 AddLine(os.str(), &message);
861 break;
862 }
863 }
864
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000865 // Preserve the order of the media contents.
866 int mline_index = -1;
867 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
868 it != desc->contents().end(); ++it) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800869 const MediaContentDescription* mdesc = it->media_description();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000870 std::vector<Candidate> candidates;
871 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
deadbeef9d3584c2016-02-16 17:54:10 -0800872 BuildMediaDescription(&*it, desc->GetTransportInfoByName(it->name),
Steve Antone831b8c2018-02-01 12:22:16 -0800873 mdesc->type(), candidates, desc->msid_signaling(),
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000874 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000875 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000876 return message;
877}
878
879// Serializes the passed in IceCandidateInterface to a SDP string.
880// candidate - The candidate to be serialized.
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700881std::string SdpSerializeCandidate(const IceCandidateInterface& candidate) {
882 return SdpSerializeCandidate(candidate.candidate());
883}
884
885// Serializes a cricket Candidate.
886std::string SdpSerializeCandidate(const cricket::Candidate& candidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887 std::string message;
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700888 std::vector<cricket::Candidate> candidates(1, candidate);
honghaiza54a0802015-12-16 18:37:23 -0800889 BuildCandidate(candidates, true, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000890 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
891 // just candidate:<candidate> not a=candidate:<blah>CRLF
nisseede5da42017-01-12 05:15:36 -0800892 RTC_DCHECK(message.find("a=") == 0);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000893 message.erase(0, 2);
nisseede5da42017-01-12 05:15:36 -0800894 RTC_DCHECK(message.find(kLineBreak) == message.size() - 2);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000895 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000896 return message;
897}
898
899bool SdpDeserialize(const std::string& message,
900 JsepSessionDescription* jdesc,
901 SdpParseError* error) {
902 std::string session_id;
903 std::string session_version;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700904 TransportDescription session_td("", "");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905 RtpHeaderExtensions session_extmaps;
zhihuang38989e52017-03-21 11:04:53 -0700906 rtc::SocketAddress session_connection_addr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000907 cricket::SessionDescription* desc = new cricket::SessionDescription();
908 std::vector<JsepIceCandidate*> candidates;
909 size_t current_pos = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910
911 // Session Description
912 if (!ParseSessionDescription(message, &current_pos, &session_id,
deadbeefc80741f2015-10-22 13:14:45 -0700913 &session_version, &session_td, &session_extmaps,
zhihuang38989e52017-03-21 11:04:53 -0700914 &session_connection_addr, desc, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915 delete desc;
916 return false;
917 }
918
919 // Media Description
deadbeefc80741f2015-10-22 13:14:45 -0700920 if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
zhihuang38989e52017-03-21 11:04:53 -0700921 session_connection_addr, desc, &candidates,
922 error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923 delete desc;
924 for (std::vector<JsepIceCandidate*>::const_iterator
925 it = candidates.begin(); it != candidates.end(); ++it) {
926 delete *it;
927 }
928 return false;
929 }
930
931 jdesc->Initialize(desc, session_id, session_version);
932
933 for (std::vector<JsepIceCandidate*>::const_iterator
934 it = candidates.begin(); it != candidates.end(); ++it) {
935 jdesc->AddCandidate(*it);
936 delete *it;
937 }
938 return true;
939}
940
941bool SdpDeserializeCandidate(const std::string& message,
942 JsepIceCandidate* jcandidate,
943 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -0800944 RTC_DCHECK(jcandidate != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945 Candidate candidate;
946 if (!ParseCandidate(message, &candidate, error, true)) {
947 return false;
948 }
949 jcandidate->SetCandidate(candidate);
950 return true;
951}
952
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700953bool SdpDeserializeCandidate(const std::string& transport_name,
954 const std::string& message,
955 cricket::Candidate* candidate,
956 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -0800957 RTC_DCHECK(candidate != nullptr);
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700958 if (!ParseCandidate(message, candidate, error, true)) {
959 return false;
960 }
961 candidate->set_transport_name(transport_name);
962 return true;
963}
964
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000965bool ParseCandidate(const std::string& message, Candidate* candidate,
966 SdpParseError* error, bool is_raw) {
nisseede5da42017-01-12 05:15:36 -0800967 RTC_DCHECK(candidate != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000968
969 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000970 std::string first_line = message;
971 size_t pos = 0;
972 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000973
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000974 // Makes sure |message| contains only one line.
975 if (message.size() > first_line.size()) {
976 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700977 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
978 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000979 return ParseFailed(message, 0, "Expect one line only", error);
980 }
981 }
982
983 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
984 // candidate:<candidate> when trickled, but we still support
985 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
986 // from the SDP.
987 if (IsLineType(first_line, kLineTypeAttributes)) {
988 first_line = first_line.substr(kLinePrefixLength);
989 }
990
991 std::string attribute_candidate;
992 std::string candidate_value;
993
994 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700995 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
996 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000997 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000998 if (is_raw) {
999 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001000 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001 << ":" << "<candidate-str>";
1002 return ParseFailed(first_line, 0, description.str(), error);
1003 } else {
1004 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
1005 kAttributeCandidate, error);
1006 }
1007 }
1008
1009 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001010 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
1011
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012 // RFC 5245
1013 // a=candidate:<foundation> <component-id> <transport> <priority>
1014 // <connection-address> <port> typ <candidate-types>
1015 // [raddr <connection-address>] [rport <port>]
1016 // *(SP extension-att-name SP extension-att-value)
1017 const size_t expected_min_fields = 8;
1018 if (fields.size() < expected_min_fields ||
1019 (fields[6] != kAttributeCandidateTyp)) {
1020 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
1021 }
jbauch083b73f2015-07-16 02:46:32 -07001022 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001023
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001024 int component_id = 0;
1025 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1026 return false;
1027 }
jbauch083b73f2015-07-16 02:46:32 -07001028 const std::string& transport = fields[2];
Peter Boström0c4e06b2015-10-07 12:23:21 +02001029 uint32_t priority = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001030 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1031 return false;
1032 }
jbauch083b73f2015-07-16 02:46:32 -07001033 const std::string& connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001034 int port = 0;
1035 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1036 return false;
1037 }
deadbeef90f1e1e2017-02-10 12:35:05 -08001038 if (!IsValidPort(port)) {
1039 return ParseFailed(first_line, "Invalid port number.", error);
1040 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041 SocketAddress address(connection_address, port);
1042
1043 cricket::ProtocolType protocol;
hnslb68cc752016-12-13 10:33:41 -08001044 if (!StringToProto(transport.c_str(), &protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001045 return ParseFailed(first_line, "Unsupported transport type.", error);
1046 }
hnslb68cc752016-12-13 10:33:41 -08001047 switch (protocol) {
1048 case cricket::PROTO_UDP:
1049 case cricket::PROTO_TCP:
1050 case cricket::PROTO_SSLTCP:
1051 // Supported protocol.
1052 break;
1053 default:
1054 return ParseFailed(first_line, "Unsupported transport type.", error);
1055 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056
1057 std::string candidate_type;
jbauch083b73f2015-07-16 02:46:32 -07001058 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059 if (type == kCandidateHost) {
1060 candidate_type = cricket::LOCAL_PORT_TYPE;
1061 } else if (type == kCandidateSrflx) {
1062 candidate_type = cricket::STUN_PORT_TYPE;
1063 } else if (type == kCandidateRelay) {
1064 candidate_type = cricket::RELAY_PORT_TYPE;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001065 } else if (type == kCandidatePrflx) {
1066 candidate_type = cricket::PRFLX_PORT_TYPE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001067 } else {
1068 return ParseFailed(first_line, "Unsupported candidate type.", error);
1069 }
1070
1071 size_t current_position = expected_min_fields;
1072 SocketAddress related_address;
1073 // The 2 optional fields for related address
1074 // [raddr <connection-address>] [rport <port>]
1075 if (fields.size() >= (current_position + 2) &&
1076 fields[current_position] == kAttributeCandidateRaddr) {
1077 related_address.SetIP(fields[++current_position]);
1078 ++current_position;
1079 }
1080 if (fields.size() >= (current_position + 2) &&
1081 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001082 int port = 0;
1083 if (!GetValueFromString(
1084 first_line, fields[++current_position], &port, error)) {
1085 return false;
1086 }
deadbeef90f1e1e2017-02-10 12:35:05 -08001087 if (!IsValidPort(port)) {
1088 return ParseFailed(first_line, "Invalid port number.", error);
1089 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001090 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 ++current_position;
1092 }
1093
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001094 // If this is a TCP candidate, it has additional extension as defined in
1095 // RFC 6544.
1096 std::string tcptype;
1097 if (fields.size() >= (current_position + 2) &&
1098 fields[current_position] == kTcpCandidateType) {
1099 tcptype = fields[++current_position];
1100 ++current_position;
1101
1102 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1103 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1104 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1105 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1106 }
1107
1108 if (protocol != cricket::PROTO_TCP) {
1109 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1110 }
1111 }
1112
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001113 // Extension
honghaiza54a0802015-12-16 18:37:23 -08001114 // Though non-standard, we support the ICE ufrag and pwd being signaled on
1115 // the candidate to avoid issues with confusing which generation a candidate
1116 // belongs to when trickling multiple generations at the same time.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001117 std::string username;
1118 std::string password;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001119 uint32_t generation = 0;
honghaiza0c44ea2016-03-23 16:07:48 -07001120 uint16_t network_id = 0;
1121 uint16_t network_cost = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001122 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1123 // RFC 5245
1124 // *(SP extension-att-name SP extension-att-value)
1125 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001126 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1127 return false;
1128 }
honghaiza54a0802015-12-16 18:37:23 -08001129 } else if (fields[i] == kAttributeCandidateUfrag) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 username = fields[++i];
honghaiza54a0802015-12-16 18:37:23 -08001131 } else if (fields[i] == kAttributeCandidatePwd) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001132 password = fields[++i];
honghaiza0c44ea2016-03-23 16:07:48 -07001133 } else if (fields[i] == kAttributeCandidateNetworkId) {
1134 if (!GetValueFromString(first_line, fields[++i], &network_id, error)) {
1135 return false;
1136 }
honghaize1a0c942016-02-16 14:54:56 -08001137 } else if (fields[i] == kAttributeCandidateNetworkCost) {
1138 if (!GetValueFromString(first_line, fields[++i], &network_cost, error)) {
1139 return false;
1140 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001141 network_cost = std::min(network_cost, rtc::kNetworkCostMax);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001142 } else {
1143 // Skip the unknown extension.
1144 ++i;
1145 }
1146 }
1147
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001148 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001149 address, priority, username, password, candidate_type,
honghaiza0c44ea2016-03-23 16:07:48 -07001150 generation, foundation, network_id, network_cost);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001151 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001152 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001153 return true;
1154}
1155
1156bool ParseIceOptions(const std::string& line,
1157 std::vector<std::string>* transport_options,
1158 SdpParseError* error) {
1159 std::string ice_options;
1160 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1161 return false;
1162 }
1163 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001164 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165 for (size_t i = 0; i < fields.size(); ++i) {
1166 transport_options->push_back(fields[i]);
1167 }
1168 return true;
1169}
1170
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001171bool ParseSctpPort(const std::string& line,
1172 int* sctp_port,
1173 SdpParseError* error) {
1174 // draft-ietf-mmusic-sctp-sdp-07
1175 // a=sctp-port
1176 std::vector<std::string> fields;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001177 const size_t expected_min_fields = 2;
lally69f57602015-10-08 10:15:04 -07001178 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1179 if (fields.size() < expected_min_fields) {
1180 fields.resize(0);
1181 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpace, &fields);
1182 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001183 if (fields.size() < expected_min_fields) {
1184 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1185 }
1186 if (!rtc::FromString(fields[1], sctp_port)) {
lally69f57602015-10-08 10:15:04 -07001187 return ParseFailed(line, "Invalid sctp port value.", error);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001188 }
1189 return true;
1190}
1191
isheriff6f8d6862016-05-26 11:24:55 -07001192bool ParseExtmap(const std::string& line,
1193 RtpExtension* extmap,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001194 SdpParseError* error) {
1195 // RFC 5285
1196 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1197 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001198 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001199 kSdpDelimiterSpace, &fields);
1200 const size_t expected_min_fields = 2;
1201 if (fields.size() < expected_min_fields) {
1202 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1203 }
1204 std::string uri = fields[1];
1205
1206 std::string value_direction;
1207 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1208 return false;
1209 }
1210 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001211 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001212 int value = 0;
1213 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1214 return false;
1215 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001216
jbauch5869f502017-06-29 12:31:36 -07001217 bool encrypted = false;
1218 if (uri == RtpExtension::kEncryptHeaderExtensionsUri) {
1219 // RFC 6904
Steve Anton36b29d12017-10-30 09:57:42 -07001220 // a=extmap:<value["/"<direction>] urn:ietf:params:rtp-hdrext:encrypt <URI>
1221 // <extensionattributes>
jbauch5869f502017-06-29 12:31:36 -07001222 const size_t expected_min_fields_encrypted = expected_min_fields + 1;
1223 if (fields.size() < expected_min_fields_encrypted) {
1224 return ParseFailedExpectMinFieldNum(line, expected_min_fields_encrypted,
1225 error);
1226 }
1227
1228 encrypted = true;
1229 uri = fields[2];
1230 if (uri == RtpExtension::kEncryptHeaderExtensionsUri) {
1231 return ParseFailed(line, "Recursive encrypted header.", error);
1232 }
1233 }
1234
1235 *extmap = RtpExtension(uri, value, encrypted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001236 return true;
1237}
1238
1239void BuildMediaDescription(const ContentInfo* content_info,
1240 const TransportInfo* transport_info,
1241 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001242 const std::vector<Candidate>& candidates,
Steve Antone831b8c2018-02-01 12:22:16 -08001243 int msid_signaling,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001244 std::string* message) {
nisseede5da42017-01-12 05:15:36 -08001245 RTC_DCHECK(message != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001246 if (content_info == NULL || message == NULL) {
1247 return;
1248 }
Steve Anton36b29d12017-10-30 09:57:42 -07001249 // TODO(deadbeef): Rethink if we should use sprintfn instead of stringstream.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001250 // According to the style guide, streams should only be used for logging.
1251 // http://google-styleguide.googlecode.com/svn/
1252 // trunk/cppguide.xml?showone=Streams#Streams
1253 std::ostringstream os;
Steve Antonb1c1de12017-12-21 15:14:30 -08001254 const MediaContentDescription* media_desc = content_info->media_description();
1255 RTC_DCHECK(media_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001257 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258
1259 // RFC 4566
1260 // m=<media> <port> <proto> <fmt>
1261 // fmt is a list of payload type numbers that MAY be used in the session.
1262 const char* type = NULL;
1263 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1264 type = kMediaTypeAudio;
1265 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1266 type = kMediaTypeVideo;
1267 else if (media_type == cricket::MEDIA_TYPE_DATA)
1268 type = kMediaTypeData;
1269 else
nissec80e7412017-01-11 05:56:46 -08001270 RTC_NOTREACHED();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001271
1272 std::string fmt;
1273 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001274 const VideoContentDescription* video_desc = media_desc->as_video();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001275 for (std::vector<cricket::VideoCodec>::const_iterator it =
1276 video_desc->codecs().begin();
1277 it != video_desc->codecs().end(); ++it) {
1278 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001279 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280 }
1281 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001282 const AudioContentDescription* audio_desc = media_desc->as_audio();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283 for (std::vector<cricket::AudioCodec>::const_iterator it =
1284 audio_desc->codecs().begin();
1285 it != audio_desc->codecs().end(); ++it) {
1286 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001287 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288 }
1289 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001290 const DataContentDescription* data_desc = media_desc->as_data();
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001291 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001292 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001293
zstein4b2e0822017-02-17 19:48:38 -08001294 if (data_desc->use_sctpmap()) {
1295 for (std::vector<cricket::DataCodec>::const_iterator it =
1296 data_desc->codecs().begin();
1297 it != data_desc->codecs().end(); ++it) {
1298 if (cricket::CodecNamesEq(it->name,
1299 cricket::kGoogleSctpDataCodecName) &&
1300 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1301 break;
1302 }
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001303 }
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001304
zstein4b2e0822017-02-17 19:48:38 -08001305 fmt.append(rtc::ToString<int>(sctp_port));
1306 } else {
1307 fmt.append(kDefaultSctpmapProtocol);
1308 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001309 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001310 for (std::vector<cricket::DataCodec>::const_iterator it =
1311 data_desc->codecs().begin();
1312 it != data_desc->codecs().end(); ++it) {
1313 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001314 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001315 }
1316 }
1317 }
1318 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1319 // to 0.
1320 if (fmt.empty()) {
1321 fmt = " 0";
1322 }
1323
deadbeef25ed4352016-12-12 18:37:36 -08001324 // The port number in the m line will be updated later when associated with
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001325 // the candidates.
deadbeef25ed4352016-12-12 18:37:36 -08001326 //
1327 // A port value of 0 indicates that the m= section is rejected.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328 // RFC 3264
1329 // To reject an offered stream, the port number in the corresponding stream in
1330 // the answer MUST be set to zero.
deadbeef25ed4352016-12-12 18:37:36 -08001331 //
1332 // However, the BUNDLE draft adds a new meaning to port zero, when used along
1333 // with a=bundle-only.
zhihuang38989e52017-03-21 11:04:53 -07001334 std::string port = kDummyPort;
1335 if (content_info->rejected || content_info->bundle_only) {
1336 port = kMediaPortRejected;
1337 } else if (!media_desc->connection_address().IsNil()) {
1338 port = rtc::ToString(media_desc->connection_address().port());
1339 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001340
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001341 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001342 transport_info->description.identity_fingerprint.get() : NULL;
1343
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001344 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345 InitLine(kLineTypeMedia, type, &os);
1346 os << " " << port << " " << media_desc->protocol() << fmt;
zhihuang38989e52017-03-21 11:04:53 -07001347 AddLine(os.str(), message);
1348
1349 InitLine(kLineTypeConnection, kConnectionNettype, &os);
1350 if (media_desc->connection_address().IsNil()) {
1351 os << " " << kConnectionIpv4Addrtype << " " << kDummyAddress;
1352 } else if (media_desc->connection_address().family() == AF_INET) {
1353 os << " " << kConnectionIpv4Addrtype << " "
1354 << media_desc->connection_address().ipaddr().ToString();
1355 } else {
1356 os << " " << kConnectionIpv6Addrtype << " "
1357 << media_desc->connection_address().ipaddr().ToString();
1358 }
1359 AddLine(os.str(), message);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001360
1361 // RFC 4566
1362 // b=AS:<bandwidth>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001363 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001364 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1365 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1366 AddLine(os.str(), message);
1367 }
1368
deadbeef25ed4352016-12-12 18:37:36 -08001369 // Add the a=bundle-only line.
1370 if (content_info->bundle_only) {
1371 InitAttrLine(kAttributeBundleOnly, &os);
1372 AddLine(os.str(), message);
1373 }
1374
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001375 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001376 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001377 std::string rtcp_line = GetRtcpLine(candidates);
1378 if (!rtcp_line.empty()) {
1379 AddLine(rtcp_line, message);
1380 }
1381 }
1382
honghaiza54a0802015-12-16 18:37:23 -08001383 // Build the a=candidate lines. We don't include ufrag and pwd in the
1384 // candidates in the SDP to avoid redundancy.
1385 BuildCandidate(candidates, false, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001386
1387 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1388 if (transport_info) {
1389 // RFC 5245
1390 // ice-pwd-att = "ice-pwd" ":" password
1391 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1392 // ice-ufrag
deadbeef3f7219b2015-12-28 15:17:14 -08001393 if (!transport_info->description.ice_ufrag.empty()) {
1394 InitAttrLine(kAttributeIceUfrag, &os);
1395 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1396 AddLine(os.str(), message);
1397 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398 // ice-pwd
deadbeef3f7219b2015-12-28 15:17:14 -08001399 if (!transport_info->description.ice_pwd.empty()) {
1400 InitAttrLine(kAttributeIcePwd, &os);
1401 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1402 AddLine(os.str(), message);
1403 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404
1405 // draft-petithuguenin-mmusic-ice-attributes-level-03
1406 BuildIceOptions(transport_info->description.transport_options, message);
1407
1408 // RFC 4572
1409 // fingerprint-attribute =
1410 // "fingerprint" ":" hash-func SP fingerprint
1411 if (fp) {
1412 // Insert the fingerprint attribute.
1413 InitAttrLine(kAttributeFingerprint, &os);
1414 os << kSdpDelimiterColon
1415 << fp->algorithm << kSdpDelimiterSpace
1416 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001417 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001418
1419 // Inserting setup attribute.
1420 if (transport_info->description.connection_role !=
1421 cricket::CONNECTIONROLE_NONE) {
1422 // Making sure we are not using "passive" mode.
1423 cricket::ConnectionRole role =
1424 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001425 std::string dtls_role_str;
nissec16fa5e2017-02-07 07:18:43 -08001426 const bool success =
1427 cricket::ConnectionRoleToString(role, &dtls_role_str);
1428 RTC_DCHECK(success);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001429 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001430 os << kSdpDelimiterColon << dtls_role_str;
1431 AddLine(os.str(), message);
1432 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001433 }
1434 }
1435
1436 // RFC 3388
1437 // mid-attribute = "a=mid:" identification-tag
1438 // identification-tag = token
1439 // Use the content name as the mid identification-tag.
1440 InitAttrLine(kAttributeMid, &os);
1441 os << kSdpDelimiterColon << content_info->name;
1442 AddLine(os.str(), message);
1443
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001444 if (IsDtlsSctp(media_desc->protocol())) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001445 const DataContentDescription* data_desc = media_desc->as_data();
zstein4b2e0822017-02-17 19:48:38 -08001446 bool use_sctpmap = data_desc->use_sctpmap();
1447 BuildSctpContentAttributes(message, sctp_port, use_sctpmap);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001448 } else if (IsRtp(media_desc->protocol())) {
Steve Antone831b8c2018-02-01 12:22:16 -08001449 BuildRtpContentAttributes(media_desc, media_type, msid_signaling, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450 }
1451}
1452
zstein4b2e0822017-02-17 19:48:38 -08001453void BuildSctpContentAttributes(std::string* message,
1454 int sctp_port,
1455 bool use_sctpmap) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001456 std::ostringstream os;
zstein4b2e0822017-02-17 19:48:38 -08001457 if (use_sctpmap) {
1458 // draft-ietf-mmusic-sctp-sdp-04
1459 // a=sctpmap:sctpmap-number protocol [streams]
1460 InitAttrLine(kAttributeSctpmap, &os);
1461 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
1462 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1463 << cricket::kMaxSctpStreams;
1464 } else {
1465 // draft-ietf-mmusic-sctp-sdp-23
1466 // a=sctp-port:<port>
1467 InitAttrLine(kAttributeSctpPort, &os);
1468 os << kSdpDelimiterColon << sctp_port;
1469 // TODO(zstein): emit max-message-size here
1470 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001471 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472}
1473
deadbeef9d3584c2016-02-16 17:54:10 -08001474void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
1475 const MediaType media_type,
Steve Antone831b8c2018-02-01 12:22:16 -08001476 int msid_signaling,
deadbeef9d3584c2016-02-16 17:54:10 -08001477 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478 std::ostringstream os;
1479 // RFC 5285
1480 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1481 // The definitions MUST be either all session level or all media level. This
1482 // implementation uses all media level.
1483 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
jbauch5869f502017-06-29 12:31:36 -07001484 const RtpExtension& extension = media_desc->rtp_header_extensions()[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001485 InitAttrLine(kAttributeExtmap, &os);
jbauch5869f502017-06-29 12:31:36 -07001486 os << kSdpDelimiterColon << extension.id;
1487 if (extension.encrypt) {
1488 os << kSdpDelimiterSpace << RtpExtension::kEncryptHeaderExtensionsUri;
1489 }
1490 os << kSdpDelimiterSpace << extension.uri;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001491 AddLine(os.str(), message);
1492 }
1493
1494 // RFC 3264
1495 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
deadbeefc80741f2015-10-22 13:14:45 -07001496 switch (media_desc->direction()) {
Steve Anton4e70a722017-11-28 14:57:10 -08001497 case RtpTransceiverDirection::kInactive:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001498 InitAttrLine(kAttributeInactive, &os);
1499 break;
Steve Anton4e70a722017-11-28 14:57:10 -08001500 case RtpTransceiverDirection::kSendOnly:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001501 InitAttrLine(kAttributeSendOnly, &os);
1502 break;
Steve Anton4e70a722017-11-28 14:57:10 -08001503 case RtpTransceiverDirection::kRecvOnly:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001504 InitAttrLine(kAttributeRecvOnly, &os);
1505 break;
Steve Anton4e70a722017-11-28 14:57:10 -08001506 case RtpTransceiverDirection::kSendRecv:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001507 default:
1508 InitAttrLine(kAttributeSendRecv, &os);
1509 break;
1510 }
1511 AddLine(os.str(), message);
1512
Seth Hampson5b4f0752018-04-02 16:31:36 -07001513 // Specified in https://datatracker.ietf.org/doc/draft-ietf-mmusic-msid/16/
1514 // a=msid:<msid-id> <msid-appdata>
1515 // The msid-id is a 1*64 token char representing the media stream id, and the
1516 // msid-appdata is a 1*64 token char representing the track id. There is a
1517 // line for every media stream, with a special msid-id value of "-"
1518 // representing no streams. The value of "msid-appdata" MUST be identical for
1519 // all lines.
Steve Antone831b8c2018-02-01 12:22:16 -08001520 if (msid_signaling & cricket::kMsidSignalingMediaSection) {
1521 const StreamParamsVec& streams = media_desc->streams();
1522 if (streams.size() == 1u) {
1523 const StreamParams& track = streams[0];
Seth Hampson5b4f0752018-04-02 16:31:36 -07001524 std::vector<std::string> stream_ids = track.stream_ids();
1525 if (stream_ids.empty()) {
1526 stream_ids.push_back(kNoStreamMsid);
1527 }
1528 for (const std::string& stream_id : stream_ids) {
1529 InitAttrLine(kAttributeMsid, &os);
1530 os << kSdpDelimiterColon << stream_id << kSdpDelimiterSpace << track.id;
1531 AddLine(os.str(), message);
1532 }
Steve Antone831b8c2018-02-01 12:22:16 -08001533 } else if (streams.size() > 1u) {
1534 RTC_LOG(LS_WARNING)
1535 << "Trying to serialize Unified Plan SDP with more than "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001536 "one track in a media section. Omitting 'a=msid'.";
deadbeef9d3584c2016-02-16 17:54:10 -08001537 }
1538 }
1539
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001540 // RFC 5761
1541 // a=rtcp-mux
1542 if (media_desc->rtcp_mux()) {
1543 InitAttrLine(kAttributeRtcpMux, &os);
1544 AddLine(os.str(), message);
1545 }
1546
deadbeef13871492015-12-09 12:37:51 -08001547 // RFC 5506
1548 // a=rtcp-rsize
1549 if (media_desc->rtcp_reduced_size()) {
1550 InitAttrLine(kAttributeRtcpReducedSize, &os);
1551 AddLine(os.str(), message);
1552 }
1553
deadbeefd45aea82017-09-16 01:24:29 -07001554 if (media_desc->conference_mode()) {
1555 InitAttrLine(kAttributeXGoogleFlag, &os);
1556 os << kSdpDelimiterColon << kValueConference;
1557 AddLine(os.str(), message);
1558 }
1559
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001560 // RFC 4568
1561 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1562 for (std::vector<CryptoParams>::const_iterator it =
1563 media_desc->cryptos().begin();
1564 it != media_desc->cryptos().end(); ++it) {
1565 InitAttrLine(kAttributeCrypto, &os);
1566 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1567 << it->key_params;
1568 if (!it->session_params.empty()) {
1569 os << " " << it->session_params;
1570 }
1571 AddLine(os.str(), message);
1572 }
1573
1574 // RFC 4566
1575 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1576 // [/<encodingparameters>]
1577 BuildRtpMap(media_desc, media_type, message);
1578
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001579 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1580 track != media_desc->streams().end(); ++track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001581 // Build the ssrc-group lines.
1582 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1583 // RFC 5576
1584 // a=ssrc-group:<semantics> <ssrc-id> ...
1585 if (track->ssrc_groups[i].ssrcs.empty()) {
1586 continue;
1587 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001588 InitAttrLine(kAttributeSsrcGroup, &os);
1589 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001590 std::vector<uint32_t>::const_iterator ssrc =
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001591 track->ssrc_groups[i].ssrcs.begin();
1592 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001593 os << kSdpDelimiterSpace << rtc::ToString<uint32_t>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001594 }
1595 AddLine(os.str(), message);
1596 }
1597 // Build the ssrc lines for each ssrc.
1598 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001599 uint32_t ssrc = track->ssrcs[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001600 // RFC 5576
1601 // a=ssrc:<ssrc-id> cname:<value>
1602 AddSsrcLine(ssrc, kSsrcAttributeCname,
1603 track->cname, message);
1604
Steve Antone831b8c2018-02-01 12:22:16 -08001605 if (msid_signaling & cricket::kMsidSignalingSsrcAttribute) {
1606 // draft-alvestrand-mmusic-msid-00
1607 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1608 // The appdata consists of the "id" attribute of a MediaStreamTrack,
1609 // which corresponds to the "id" attribute of StreamParams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07001610 // Since a=ssrc msid signaling is used in Plan B SDP semantics, and
1611 // multiple stream ids are not supported for Plan B, we are only adding
1612 // a line for the first media stream id here.
Seth Hampson845e8782018-03-02 11:34:10 -08001613 const std::string& stream_id = track->first_stream_id();
Steve Antone831b8c2018-02-01 12:22:16 -08001614 InitAttrLine(kAttributeSsrc, &os);
1615 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1616 << kSsrcAttributeMsid << kSdpDelimiterColon << stream_id
1617 << kSdpDelimiterSpace << track->id;
1618 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001619
Steve Antone831b8c2018-02-01 12:22:16 -08001620 // TODO(ronghuawu): Remove below code which is for backward
1621 // compatibility.
1622 // draft-alvestrand-rtcweb-mid-01
1623 // a=ssrc:<ssrc-id> mslabel:<value>
1624 // The label isn't yet defined.
1625 // a=ssrc:<ssrc-id> label:<value>
Seth Hampson5b4f0752018-04-02 16:31:36 -07001626 AddSsrcLine(ssrc, kSsrcAttributeMslabel, stream_id, message);
Steve Antone831b8c2018-02-01 12:22:16 -08001627 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1628 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001629 }
1630 }
1631}
1632
1633void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1634 // fmtp header: a=fmtp:|payload_type| <parameters>
1635 // Add a=fmtp
1636 InitAttrLine(kAttributeFmtp, os);
1637 // Add :|payload_type|
1638 *os << kSdpDelimiterColon << payload_type;
1639}
1640
1641void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1642 // rtcp-fb header: a=rtcp-fb:|payload_type|
1643 // <parameters>/<ccm <ccm_parameters>>
1644 // Add a=rtcp-fb
1645 InitAttrLine(kAttributeRtcpFb, os);
1646 // Add :
1647 *os << kSdpDelimiterColon;
1648 if (payload_type == kWildcardPayloadType) {
1649 *os << "*";
1650 } else {
1651 *os << payload_type;
1652 }
1653}
1654
1655void WriteFmtpParameter(const std::string& parameter_name,
1656 const std::string& parameter_value,
1657 std::ostringstream* os) {
1658 // fmtp parameters: |parameter_name|=|parameter_value|
1659 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1660}
1661
1662void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1663 std::ostringstream* os) {
1664 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1665 fmtp != parameters.end(); ++fmtp) {
hta62a216e2016-04-15 11:02:14 -07001666 // Parameters are a semicolon-separated list, no spaces.
1667 // The list is separated from the header by a space.
1668 if (fmtp == parameters.begin()) {
1669 *os << kSdpDelimiterSpace;
1670 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001671 *os << kSdpDelimiterSemicolon;
1672 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001673 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1674 }
1675}
1676
1677bool IsFmtpParam(const std::string& name) {
ossuaa4b0772017-01-30 07:41:18 -08001678 // RFC 4855, section 3 specifies the mapping of media format parameters to SDP
1679 // parameters. Only ptime, maxptime, channels and rate are placed outside of
1680 // the fmtp line. In WebRTC, channels and rate are already handled separately
1681 // and thus not included in the CodecParameterMap.
1682 return name != kCodecParamPTime && name != kCodecParamMaxPTime;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683}
1684
1685// Retreives fmtp parameters from |params|, which may contain other parameters
1686// as well, and puts them in |fmtp_parameters|.
1687void GetFmtpParams(const cricket::CodecParameterMap& params,
1688 cricket::CodecParameterMap* fmtp_parameters) {
1689 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1690 iter != params.end(); ++iter) {
1691 if (IsFmtpParam(iter->first)) {
1692 (*fmtp_parameters)[iter->first] = iter->second;
1693 }
1694 }
1695}
1696
1697template <class T>
1698void AddFmtpLine(const T& codec, std::string* message) {
1699 cricket::CodecParameterMap fmtp_parameters;
1700 GetFmtpParams(codec.params, &fmtp_parameters);
1701 if (fmtp_parameters.empty()) {
1702 // No need to add an fmtp if it will have no (optional) parameters.
1703 return;
1704 }
1705 std::ostringstream os;
1706 WriteFmtpHeader(codec.id, &os);
1707 WriteFmtpParameters(fmtp_parameters, &os);
1708 AddLine(os.str(), message);
1709 return;
1710}
1711
1712template <class T>
1713void AddRtcpFbLines(const T& codec, std::string* message) {
1714 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1715 codec.feedback_params.params().begin();
1716 iter != codec.feedback_params.params().end(); ++iter) {
1717 std::ostringstream os;
1718 WriteRtcpFbHeader(codec.id, &os);
1719 os << " " << iter->id();
1720 if (!iter->param().empty()) {
1721 os << " " << iter->param();
1722 }
1723 AddLine(os.str(), message);
1724 }
1725}
1726
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001727bool AddSctpDataCodec(DataContentDescription* media_desc,
1728 int sctp_port) {
solenberg9fa49752016-10-08 13:02:44 -07001729 for (const auto& codec : media_desc->codecs()) {
1730 if (cricket::CodecNamesEq(codec.name, cricket::kGoogleSctpDataCodecName)) {
1731 return ParseFailed("",
1732 "Can't have multiple sctp port attributes.",
1733 NULL);
1734 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001735 }
1736 // Add the SCTP Port number as a pseudo-codec "port" parameter
solenberg9fa49752016-10-08 13:02:44 -07001737 cricket::DataCodec codec_port(cricket::kGoogleSctpDataCodecPlType,
deadbeef67cf2c12016-04-13 10:07:16 -07001738 cricket::kGoogleSctpDataCodecName);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001739 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
Mirko Bonadei675513b2017-11-09 11:09:25 +01001740 RTC_LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number " << sctp_port;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001741 media_desc->AddCodec(codec_port);
1742 return true;
1743}
1744
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001745bool GetMinValue(const std::vector<int>& values, int* value) {
1746 if (values.empty()) {
1747 return false;
1748 }
1749 std::vector<int>::const_iterator found =
1750 std::min_element(values.begin(), values.end());
1751 *value = *found;
1752 return true;
1753}
1754
1755bool GetParameter(const std::string& name,
1756 const cricket::CodecParameterMap& params, int* value) {
1757 std::map<std::string, std::string>::const_iterator found =
1758 params.find(name);
1759 if (found == params.end()) {
1760 return false;
1761 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001762 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001763 return false;
1764 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001765 return true;
1766}
1767
1768void BuildRtpMap(const MediaContentDescription* media_desc,
1769 const MediaType media_type,
1770 std::string* message) {
nisseede5da42017-01-12 05:15:36 -08001771 RTC_DCHECK(message != NULL);
1772 RTC_DCHECK(media_desc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001773 std::ostringstream os;
1774 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001775 const VideoContentDescription* video_desc = media_desc->as_video();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001776 for (std::vector<cricket::VideoCodec>::const_iterator it =
1777 video_desc->codecs().begin();
1778 it != video_desc->codecs().end(); ++it) {
1779 // RFC 4566
1780 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1781 // [/<encodingparameters>]
1782 if (it->id != kWildcardPayloadType) {
1783 InitAttrLine(kAttributeRtpmap, &os);
deadbeefe814a0d2017-02-25 18:15:09 -08001784 os << kSdpDelimiterColon << it->id << " " << it->name << "/"
1785 << cricket::kVideoCodecClockrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001786 AddLine(os.str(), message);
1787 }
1788 AddRtcpFbLines(*it, message);
1789 AddFmtpLine(*it, message);
1790 }
1791 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001792 const AudioContentDescription* audio_desc = media_desc->as_audio();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001793 std::vector<int> ptimes;
1794 std::vector<int> maxptimes;
1795 int max_minptime = 0;
1796 for (std::vector<cricket::AudioCodec>::const_iterator it =
1797 audio_desc->codecs().begin();
1798 it != audio_desc->codecs().end(); ++it) {
nisseede5da42017-01-12 05:15:36 -08001799 RTC_DCHECK(!it->name.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001800 // RFC 4566
1801 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1802 // [/<encodingparameters>]
1803 InitAttrLine(kAttributeRtpmap, &os);
1804 os << kSdpDelimiterColon << it->id << " ";
1805 os << it->name << "/" << it->clockrate;
1806 if (it->channels != 1) {
1807 os << "/" << it->channels;
1808 }
1809 AddLine(os.str(), message);
1810 AddRtcpFbLines(*it, message);
1811 AddFmtpLine(*it, message);
1812 int minptime = 0;
1813 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1814 max_minptime = std::max(minptime, max_minptime);
1815 }
1816 int ptime;
1817 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1818 ptimes.push_back(ptime);
1819 }
1820 int maxptime;
1821 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1822 maxptimes.push_back(maxptime);
1823 }
1824 }
1825 // Populate the maxptime attribute with the smallest maxptime of all codecs
1826 // under the same m-line.
1827 int min_maxptime = INT_MAX;
1828 if (GetMinValue(maxptimes, &min_maxptime)) {
1829 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1830 }
nisseede5da42017-01-12 05:15:36 -08001831 RTC_DCHECK(min_maxptime > max_minptime);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832 // Populate the ptime attribute with the smallest ptime or the largest
1833 // minptime, whichever is the largest, for all codecs under the same m-line.
1834 int ptime = INT_MAX;
1835 if (GetMinValue(ptimes, &ptime)) {
1836 ptime = std::min(ptime, min_maxptime);
1837 ptime = std::max(ptime, max_minptime);
1838 AddAttributeLine(kCodecParamPTime, ptime, message);
1839 }
1840 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001841 const DataContentDescription* data_desc = media_desc->as_data();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001842 for (std::vector<cricket::DataCodec>::const_iterator it =
1843 data_desc->codecs().begin();
1844 it != data_desc->codecs().end(); ++it) {
1845 // RFC 4566
1846 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1847 // [/<encodingparameters>]
1848 InitAttrLine(kAttributeRtpmap, &os);
1849 os << kSdpDelimiterColon << it->id << " "
1850 << it->name << "/" << it->clockrate;
1851 AddLine(os.str(), message);
1852 }
1853 }
1854}
1855
1856void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -08001857 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858 std::string* message) {
1859 std::ostringstream os;
1860
1861 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1862 it != candidates.end(); ++it) {
1863 // RFC 5245
1864 // a=candidate:<foundation> <component-id> <transport> <priority>
1865 // <connection-address> <port> typ <candidate-types>
1866 // [raddr <connection-address>] [rport <port>]
1867 // *(SP extension-att-name SP extension-att-value)
1868 std::string type;
1869 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1870 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1871 type = kCandidateHost;
1872 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1873 type = kCandidateSrflx;
1874 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1875 type = kCandidateRelay;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001876 } else if (it->type() == cricket::PRFLX_PORT_TYPE) {
1877 type = kCandidatePrflx;
1878 // Peer reflexive candidate may be signaled for being removed.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001879 } else {
nissec80e7412017-01-11 05:56:46 -08001880 RTC_NOTREACHED();
Peter Thatcher019087f2015-04-28 09:06:26 -07001881 // Never write out candidates if we don't know the type.
1882 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001883 }
1884
1885 InitAttrLine(kAttributeCandidate, &os);
1886 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001887 << it->foundation() << " "
1888 << it->component() << " "
1889 << it->protocol() << " "
1890 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001891 << it->address().ipaddr().ToString() << " "
1892 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001893 << kAttributeCandidateTyp << " "
1894 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001895
1896 // Related address
1897 if (!it->related_address().IsNil()) {
1898 os << kAttributeCandidateRaddr << " "
1899 << it->related_address().ipaddr().ToString() << " "
1900 << kAttributeCandidateRport << " "
1901 << it->related_address().PortAsString() << " ";
1902 }
1903
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001904 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001905 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001906 }
1907
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001908 // Extensions
1909 os << kAttributeCandidateGeneration << " " << it->generation();
honghaiza54a0802015-12-16 18:37:23 -08001910 if (include_ufrag && !it->username().empty()) {
1911 os << " " << kAttributeCandidateUfrag << " " << it->username();
1912 }
honghaiza0c44ea2016-03-23 16:07:48 -07001913 if (it->network_id() > 0) {
1914 os << " " << kAttributeCandidateNetworkId << " " << it->network_id();
1915 }
honghaize1a0c942016-02-16 14:54:56 -08001916 if (it->network_cost() > 0) {
1917 os << " " << kAttributeCandidateNetworkCost << " " << it->network_cost();
1918 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001919
1920 AddLine(os.str(), message);
1921 }
1922}
1923
1924void BuildIceOptions(const std::vector<std::string>& transport_options,
1925 std::string* message) {
1926 if (!transport_options.empty()) {
1927 std::ostringstream os;
1928 InitAttrLine(kAttributeIceOption, &os);
1929 os << kSdpDelimiterColon << transport_options[0];
1930 for (size_t i = 1; i < transport_options.size(); ++i) {
1931 os << kSdpDelimiterSpace << transport_options[i];
1932 }
1933 AddLine(os.str(), message);
1934 }
1935}
1936
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001937bool IsRtp(const std::string& protocol) {
1938 return protocol.empty() ||
1939 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1940}
1941
1942bool IsDtlsSctp(const std::string& protocol) {
1943 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001944 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001945}
1946
zhihuang38989e52017-03-21 11:04:53 -07001947bool ParseConnectionData(const std::string& line,
1948 rtc::SocketAddress* addr,
1949 SdpParseError* error) {
1950 // Parse the line from left to right.
1951 std::string token;
1952 std::string rightpart;
1953 // RFC 4566
1954 // c=<nettype> <addrtype> <connection-address>
1955 // Skip the "c="
1956 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, &token, &rightpart)) {
1957 return ParseFailed(line, "Failed to parse the network type.", error);
1958 }
1959
1960 // Extract and verify the <nettype>
1961 if (!rtc::tokenize_first(rightpart, kSdpDelimiterSpace, &token, &rightpart) ||
1962 token != kConnectionNettype) {
1963 return ParseFailed(line,
1964 "Failed to parse the connection data. The network type "
1965 "is not currently supported.",
1966 error);
1967 }
1968
1969 // Extract the "<addrtype>" and "<connection-address>".
1970 if (!rtc::tokenize_first(rightpart, kSdpDelimiterSpace, &token, &rightpart)) {
1971 return ParseFailed(line, "Failed to parse the address type.", error);
1972 }
1973
1974 // The rightpart part should be the IP address without the slash which is used
1975 // for multicast.
1976 if (rightpart.find('/') != std::string::npos) {
1977 return ParseFailed(line,
1978 "Failed to parse the connection data. Multicast is not "
1979 "currently supported.",
1980 error);
1981 }
1982 addr->SetIP(rightpart);
1983
1984 // Verify that the addrtype matches the type of the parsed address.
1985 if ((addr->family() == AF_INET && token != "IP4") ||
1986 (addr->family() == AF_INET6 && token != "IP6")) {
1987 addr->Clear();
1988 return ParseFailed(
1989 line,
1990 "Failed to parse the connection data. The address type is mismatching.",
1991 error);
1992 }
1993 return true;
1994}
1995
1996bool ParseSessionDescription(const std::string& message,
1997 size_t* pos,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001998 std::string* session_id,
1999 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002000 TransportDescription* session_td,
2001 RtpHeaderExtensions* session_extmaps,
zhihuang38989e52017-03-21 11:04:53 -07002002 rtc::SocketAddress* connection_addr,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002003 cricket::SessionDescription* desc,
2004 SdpParseError* error) {
2005 std::string line;
2006
deadbeefc80741f2015-10-22 13:14:45 -07002007 desc->set_msid_supported(false);
2008
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 // RFC 4566
2010 // v= (protocol version)
2011 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
2012 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
2013 std::string(), error);
2014 }
2015 // RFC 4566
2016 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
2017 // <unicast-address>
2018 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
2019 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
2020 std::string(), error);
2021 }
2022 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002023 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002024 kSdpDelimiterSpace, &fields);
2025 const size_t expected_fields = 6;
2026 if (fields.size() != expected_fields) {
2027 return ParseFailedExpectFieldNum(line, expected_fields, error);
2028 }
2029 *session_id = fields[1];
2030 *session_version = fields[2];
2031
2032 // RFC 4566
2033 // s= (session name)
2034 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
2035 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
2036 std::string(), error);
2037 }
2038
2039 // Optional lines
2040 // Those are the optional lines, so shouldn't return false if not present.
2041 // RFC 4566
2042 // i=* (session information)
2043 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
2044
2045 // RFC 4566
2046 // u=* (URI of description)
2047 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
2048
2049 // RFC 4566
2050 // e=* (email address)
2051 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
2052
2053 // RFC 4566
2054 // p=* (phone number)
2055 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
2056
2057 // RFC 4566
2058 // c=* (connection information -- not required if included in
2059 // all media)
zhihuang38989e52017-03-21 11:04:53 -07002060 if (GetLineWithType(message, pos, &line, kLineTypeConnection)) {
2061 if (!ParseConnectionData(line, connection_addr, error)) {
2062 return false;
2063 }
2064 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002065
2066 // RFC 4566
2067 // b=* (zero or more bandwidth information lines)
2068 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
2069 // By pass zero or more b lines.
2070 }
2071
2072 // RFC 4566
2073 // One or more time descriptions ("t=" and "r=" lines; see below)
2074 // t= (time the session is active)
2075 // r=* (zero or more repeat times)
2076 // Ensure there's at least one time description
2077 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
2078 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
2079 error);
2080 }
2081
2082 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
2083 // By pass zero or more r lines.
2084 }
2085
2086 // Go through the rest of the time descriptions
2087 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
2088 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
2089 // By pass zero or more r lines.
2090 }
2091 }
2092
2093 // RFC 4566
2094 // z=* (time zone adjustments)
2095 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
2096
2097 // RFC 4566
2098 // k=* (encryption key)
2099 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
2100
2101 // RFC 4566
2102 // a=* (zero or more session attribute lines)
2103 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
2104 if (HasAttribute(line, kAttributeGroup)) {
2105 if (!ParseGroupAttribute(line, desc, error)) {
2106 return false;
2107 }
2108 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2109 if (!GetValue(line, kAttributeIceUfrag,
2110 &(session_td->ice_ufrag), error)) {
2111 return false;
2112 }
2113 } else if (HasAttribute(line, kAttributeIcePwd)) {
2114 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
2115 return false;
2116 }
2117 } else if (HasAttribute(line, kAttributeIceLite)) {
2118 session_td->ice_mode = cricket::ICEMODE_LITE;
2119 } else if (HasAttribute(line, kAttributeIceOption)) {
2120 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
2121 return false;
2122 }
2123 } else if (HasAttribute(line, kAttributeFingerprint)) {
2124 if (session_td->identity_fingerprint.get()) {
2125 return ParseFailed(
2126 line,
2127 "Can't have multiple fingerprint attributes at the same level.",
2128 error);
2129 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002130 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002131 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2132 return false;
2133 }
2134 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002135 } else if (HasAttribute(line, kAttributeSetup)) {
2136 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
2137 return false;
2138 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002139 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
2140 std::string semantics;
2141 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
2142 return false;
2143 }
deadbeefc80741f2015-10-22 13:14:45 -07002144 desc->set_msid_supported(
2145 CaseInsensitiveFind(semantics, kMediaStreamSemantic));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002146 } else if (HasAttribute(line, kAttributeExtmap)) {
isheriff6f8d6862016-05-26 11:24:55 -07002147 RtpExtension extmap;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002148 if (!ParseExtmap(line, &extmap, error)) {
2149 return false;
2150 }
2151 session_extmaps->push_back(extmap);
2152 }
2153 }
2154
2155 return true;
2156}
2157
2158bool ParseGroupAttribute(const std::string& line,
2159 cricket::SessionDescription* desc,
2160 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08002161 RTC_DCHECK(desc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162
2163 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
2164 // a=group:BUNDLE video voice
2165 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002166 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002167 kSdpDelimiterSpace, &fields);
2168 std::string semantics;
2169 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
2170 return false;
2171 }
2172 cricket::ContentGroup group(semantics);
2173 for (size_t i = 1; i < fields.size(); ++i) {
2174 group.AddContentName(fields[i]);
2175 }
2176 desc->AddGroup(group);
2177 return true;
2178}
2179
2180static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002181 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002182 SdpParseError* error) {
2183 if (!IsLineType(line, kLineTypeAttributes) ||
2184 !HasAttribute(line, kAttributeFingerprint)) {
2185 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
2186 kAttributeFingerprint, error);
2187 }
2188
2189 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002190 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002191 kSdpDelimiterSpace, &fields);
2192 const size_t expected_fields = 2;
2193 if (fields.size() != expected_fields) {
2194 return ParseFailedExpectFieldNum(line, expected_fields, error);
2195 }
2196
2197 // The first field here is "fingerprint:<hash>.
2198 std::string algorithm;
2199 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2200 return false;
2201 }
2202
2203 // Downcase the algorithm. Note that we don't need to downcase the
2204 // fingerprint because hex_decode can handle upper-case.
2205 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2206 ::tolower);
2207
2208 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002209 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002210 algorithm, fields[1]);
2211 if (!*fingerprint) {
2212 return ParseFailed(line,
2213 "Failed to create fingerprint from the digest.",
2214 error);
2215 }
2216
2217 return true;
2218}
2219
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002220static bool ParseDtlsSetup(const std::string& line,
2221 cricket::ConnectionRole* role,
2222 SdpParseError* error) {
2223 // setup-attr = "a=setup:" role
2224 // role = "active" / "passive" / "actpass" / "holdconn"
2225 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002226 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002227 const size_t expected_fields = 2;
2228 if (fields.size() != expected_fields) {
2229 return ParseFailedExpectFieldNum(line, expected_fields, error);
2230 }
2231 std::string role_str = fields[1];
2232 if (!cricket::StringToConnectionRole(role_str, role)) {
2233 return ParseFailed(line, "Invalid attribute value.", error);
2234 }
2235 return true;
2236}
2237
deadbeef9d3584c2016-02-16 17:54:10 -08002238static bool ParseMsidAttribute(const std::string& line,
Seth Hampson5b4f0752018-04-02 16:31:36 -07002239 std::vector<std::string>* stream_ids,
deadbeef9d3584c2016-02-16 17:54:10 -08002240 std::string* track_id,
2241 SdpParseError* error) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07002242 // https://datatracker.ietf.org/doc/draft-ietf-mmusic-msid/16/
deadbeef9d3584c2016-02-16 17:54:10 -08002243 // a=msid:<stream id> <track id>
2244 // msid-value = msid-id [ SP msid-appdata ]
2245 // msid-id = 1*64token-char ; see RFC 4566
2246 // msid-appdata = 1*64token-char ; see RFC 4566
2247 std::string field1;
Seth Hampson5b4f0752018-04-02 16:31:36 -07002248 std::string new_stream_id;
2249 std::string new_track_id;
deadbeef9d3584c2016-02-16 17:54:10 -08002250 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
Seth Hampson5b4f0752018-04-02 16:31:36 -07002251 &field1, &new_track_id)) {
deadbeef9d3584c2016-02-16 17:54:10 -08002252 const size_t expected_fields = 2;
2253 return ParseFailedExpectFieldNum(line, expected_fields, error);
2254 }
2255
Seth Hampson5b4f0752018-04-02 16:31:36 -07002256 if (new_track_id.empty()) {
deadbeefa4549d62017-02-10 17:26:22 -08002257 return ParseFailed(line, "Missing track ID in msid attribute.", error);
2258 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07002259 // All track ids should be the same within an m section in a Unified Plan SDP.
2260 if (!track_id->empty() && new_track_id.compare(*track_id) != 0) {
2261 return ParseFailed(
2262 line, "Two different track IDs in msid attribute in one m= section",
2263 error);
2264 }
2265 *track_id = new_track_id;
deadbeefa4549d62017-02-10 17:26:22 -08002266
deadbeef9d3584c2016-02-16 17:54:10 -08002267 // msid:<msid-id>
Seth Hampson5b4f0752018-04-02 16:31:36 -07002268 if (!GetValue(field1, kAttributeMsid, &new_stream_id, error)) {
deadbeef9d3584c2016-02-16 17:54:10 -08002269 return false;
2270 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07002271 if (new_stream_id.empty()) {
deadbeefa4549d62017-02-10 17:26:22 -08002272 return ParseFailed(line, "Missing stream ID in msid attribute.", error);
2273 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07002274 // The special value "-" indicates "no MediaStream".
2275 if (new_stream_id.compare(kNoStreamMsid) != 0) {
2276 stream_ids->push_back(new_stream_id);
2277 }
deadbeef9d3584c2016-02-16 17:54:10 -08002278 return true;
2279}
2280
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002281// RFC 3551
2282// PT encoding media type clock rate channels
2283// name (Hz)
2284// 0 PCMU A 8,000 1
2285// 1 reserved A
2286// 2 reserved A
2287// 3 GSM A 8,000 1
2288// 4 G723 A 8,000 1
2289// 5 DVI4 A 8,000 1
2290// 6 DVI4 A 16,000 1
2291// 7 LPC A 8,000 1
2292// 8 PCMA A 8,000 1
2293// 9 G722 A 8,000 1
2294// 10 L16 A 44,100 2
2295// 11 L16 A 44,100 1
2296// 12 QCELP A 8,000 1
2297// 13 CN A 8,000 1
2298// 14 MPA A 90,000 (see text)
2299// 15 G728 A 8,000 1
2300// 16 DVI4 A 11,025 1
2301// 17 DVI4 A 22,050 1
2302// 18 G729 A 8,000 1
2303struct StaticPayloadAudioCodec {
2304 const char* name;
2305 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002306 size_t channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307};
2308static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2309 { "PCMU", 8000, 1 },
2310 { "reserved", 0, 0 },
2311 { "reserved", 0, 0 },
2312 { "GSM", 8000, 1 },
2313 { "G723", 8000, 1 },
2314 { "DVI4", 8000, 1 },
2315 { "DVI4", 16000, 1 },
2316 { "LPC", 8000, 1 },
2317 { "PCMA", 8000, 1 },
2318 { "G722", 8000, 1 },
2319 { "L16", 44100, 2 },
2320 { "L16", 44100, 1 },
2321 { "QCELP", 8000, 1 },
2322 { "CN", 8000, 1 },
2323 { "MPA", 90000, 1 },
2324 { "G728", 8000, 1 },
2325 { "DVI4", 11025, 1 },
2326 { "DVI4", 22050, 1 },
2327 { "G729", 8000, 1 },
2328};
2329
2330void MaybeCreateStaticPayloadAudioCodecs(
2331 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2332 if (!media_desc) {
2333 return;
2334 }
deadbeef67cf2c12016-04-13 10:07:16 -07002335 RTC_DCHECK(media_desc->codecs().empty());
solenberg9fa49752016-10-08 13:02:44 -07002336 for (int payload_type : fmts) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002337 if (!media_desc->HasCodec(payload_type) &&
2338 payload_type >= 0 &&
kjellander3e33bfe2016-06-20 07:04:09 -07002339 static_cast<uint32_t>(payload_type) <
2340 arraysize(kStaticPayloadAudioCodecs)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002341 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2342 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002343 size_t channels = kStaticPayloadAudioCodecs[payload_type].channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002344 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
deadbeef67cf2c12016-04-13 10:07:16 -07002345 clock_rate, 0, channels));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002346 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002347 }
2348}
2349
2350template <class C>
2351static C* ParseContentDescription(const std::string& message,
2352 const MediaType media_type,
2353 int mline_index,
2354 const std::string& protocol,
deadbeef67cf2c12016-04-13 10:07:16 -07002355 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002356 size_t* pos,
2357 std::string* content_name,
deadbeef25ed4352016-12-12 18:37:36 -08002358 bool* bundle_only,
Steve Antone831b8c2018-02-01 12:22:16 -08002359 int* msid_signaling,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002360 TransportDescription* transport,
2361 std::vector<JsepIceCandidate*>* candidates,
2362 webrtc::SdpParseError* error) {
2363 C* media_desc = new C();
2364 switch (media_type) {
2365 case cricket::MEDIA_TYPE_AUDIO:
2366 *content_name = cricket::CN_AUDIO;
2367 break;
2368 case cricket::MEDIA_TYPE_VIDEO:
2369 *content_name = cricket::CN_VIDEO;
2370 break;
2371 case cricket::MEDIA_TYPE_DATA:
2372 *content_name = cricket::CN_DATA;
2373 break;
2374 default:
nissec80e7412017-01-11 05:56:46 -08002375 RTC_NOTREACHED();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002376 break;
2377 }
deadbeef67cf2c12016-04-13 10:07:16 -07002378 if (!ParseContent(message, media_type, mline_index, protocol, payload_types,
Steve Antone831b8c2018-02-01 12:22:16 -08002379 pos, content_name, bundle_only, msid_signaling, media_desc,
2380 transport, candidates, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002381 delete media_desc;
zhihuang38989e52017-03-21 11:04:53 -07002382 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002383 }
2384 // Sort the codecs according to the m-line fmt list.
deadbeef67cf2c12016-04-13 10:07:16 -07002385 std::unordered_map<int, int> payload_type_preferences;
2386 // "size + 1" so that the lowest preference payload type has a preference of
2387 // 1, which is greater than the default (0) for payload types not in the fmt
2388 // list.
2389 int preference = static_cast<int>(payload_types.size() + 1);
2390 for (int pt : payload_types) {
2391 payload_type_preferences[pt] = preference--;
2392 }
2393 std::vector<typename C::CodecType> codecs = media_desc->codecs();
2394 std::sort(codecs.begin(), codecs.end(), [&payload_type_preferences](
2395 const typename C::CodecType& a,
2396 const typename C::CodecType& b) {
2397 return payload_type_preferences[a.id] > payload_type_preferences[b.id];
2398 });
2399 media_desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002400 return media_desc;
2401}
2402
2403bool ParseMediaDescription(const std::string& message,
2404 const TransportDescription& session_td,
2405 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002406 size_t* pos,
zhihuang38989e52017-03-21 11:04:53 -07002407 const rtc::SocketAddress& session_connection_addr,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002408 cricket::SessionDescription* desc,
2409 std::vector<JsepIceCandidate*>* candidates,
2410 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08002411 RTC_DCHECK(desc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002412 std::string line;
2413 int mline_index = -1;
Steve Antone831b8c2018-02-01 12:22:16 -08002414 int msid_signaling = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002415
2416 // Zero or more media descriptions
2417 // RFC 4566
2418 // m=<media> <port> <proto> <fmt>
2419 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2420 ++mline_index;
2421
2422 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002423 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002424 kSdpDelimiterSpace, &fields);
zstein4b2e0822017-02-17 19:48:38 -08002425
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002426 const size_t expected_min_fields = 4;
2427 if (fields.size() < expected_min_fields) {
2428 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2429 }
deadbeef25ed4352016-12-12 18:37:36 -08002430 bool port_rejected = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002431 // RFC 3264
2432 // To reject an offered stream, the port number in the corresponding stream
2433 // in the answer MUST be set to zero.
2434 if (fields[1] == kMediaPortRejected) {
deadbeef25ed4352016-12-12 18:37:36 -08002435 port_rejected = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002436 }
2437
zhihuang38989e52017-03-21 11:04:53 -07002438 int port = 0;
2439 if (!rtc::FromString<int>(fields[1], &port) || !IsValidPort(port)) {
2440 return ParseFailed(line, "The port number is invalid", error);
2441 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002442 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002443
2444 // <fmt>
deadbeef67cf2c12016-04-13 10:07:16 -07002445 std::vector<int> payload_types;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002446 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002447 for (size_t j = 3 ; j < fields.size(); ++j) {
2448 // TODO(wu): Remove when below bug is fixed.
2449 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002450 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002451 continue;
2452 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002453
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002454 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002455 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002456 return false;
2457 }
deadbeef67cf2c12016-04-13 10:07:16 -07002458 payload_types.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002459 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002460 }
2461
2462 // Make a temporary TransportDescription based on |session_td|.
2463 // Some of this gets overwritten by ParseContent.
deadbeef46eed762016-01-28 13:24:37 -08002464 TransportDescription transport(
2465 session_td.transport_options, session_td.ice_ufrag, session_td.ice_pwd,
2466 session_td.ice_mode, session_td.connection_role,
2467 session_td.identity_fingerprint.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002468
kwibergd1fe2812016-04-27 06:47:29 -07002469 std::unique_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002470 std::string content_name;
deadbeef25ed4352016-12-12 18:37:36 -08002471 bool bundle_only = false;
Steve Antone831b8c2018-02-01 12:22:16 -08002472 int section_msid_signaling = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002473 if (HasAttribute(line, kMediaTypeVideo)) {
2474 content.reset(ParseContentDescription<VideoContentDescription>(
deadbeef67cf2c12016-04-13 10:07:16 -07002475 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
Steve Antone831b8c2018-02-01 12:22:16 -08002476 payload_types, pos, &content_name, &bundle_only,
2477 &section_msid_signaling, &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002478 } else if (HasAttribute(line, kMediaTypeAudio)) {
2479 content.reset(ParseContentDescription<AudioContentDescription>(
deadbeef67cf2c12016-04-13 10:07:16 -07002480 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
Steve Antone831b8c2018-02-01 12:22:16 -08002481 payload_types, pos, &content_name, &bundle_only,
2482 &section_msid_signaling, &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002483 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002484 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002485 ParseContentDescription<DataContentDescription>(
deadbeef67cf2c12016-04-13 10:07:16 -07002486 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
Steve Antone831b8c2018-02-01 12:22:16 -08002487 payload_types, pos, &content_name, &bundle_only,
2488 &section_msid_signaling, &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002489 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002490
zstein4b2e0822017-02-17 19:48:38 -08002491 if (data_desc && IsDtlsSctp(protocol)) {
2492 int p;
2493 if (rtc::FromString(fields[3], &p)) {
2494 if (!AddSctpDataCodec(data_desc, p)) {
2495 return false;
2496 }
2497 } else if (fields[3] == kDefaultSctpmapProtocol) {
2498 data_desc->set_use_sctpmap(false);
2499 }
wu@webrtc.org78187522013-10-07 23:32:02 +00002500 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002501 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002502 RTC_LOG(LS_WARNING) << "Unsupported media type: " << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002503 continue;
2504 }
2505 if (!content.get()) {
2506 // ParseContentDescription returns NULL if failed.
2507 return false;
2508 }
2509
Steve Antone831b8c2018-02-01 12:22:16 -08002510 msid_signaling |= section_msid_signaling;
2511
deadbeef25ed4352016-12-12 18:37:36 -08002512 bool content_rejected = false;
deadbeef12771a12017-01-03 13:53:47 -08002513 // A port of 0 is not interpreted as a rejected m= section when it's
2514 // used along with a=bundle-only.
deadbeef25ed4352016-12-12 18:37:36 -08002515 if (bundle_only) {
deadbeef25ed4352016-12-12 18:37:36 -08002516 if (!port_rejected) {
deadbeef12771a12017-01-03 13:53:47 -08002517 // Usage of bundle-only with a nonzero port is unspecified. So just
2518 // ignore bundle-only if we see this.
2519 bundle_only = false;
Mirko Bonadei675513b2017-11-09 11:09:25 +01002520 RTC_LOG(LS_WARNING)
deadbeef12771a12017-01-03 13:53:47 -08002521 << "a=bundle-only attribute observed with a nonzero "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002522 "port; this usage is unspecified so the attribute is being "
2523 "ignored.";
deadbeef25ed4352016-12-12 18:37:36 -08002524 }
2525 } else {
2526 // If not using bundle-only, interpret port 0 in the normal way; the m=
2527 // section is being rejected.
2528 content_rejected = port_rejected;
2529 }
2530
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002531 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002532 // Set the extmap.
2533 if (!session_extmaps.empty() &&
2534 !content->rtp_header_extensions().empty()) {
2535 return ParseFailed("",
2536 "The a=extmap MUST be either all session level or "
2537 "all media level.",
2538 error);
2539 }
2540 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2541 content->AddRtpHeaderExtension(session_extmaps[i]);
2542 }
2543 }
2544 content->set_protocol(protocol);
zhihuang38989e52017-03-21 11:04:53 -07002545
2546 // Use the session level connection address if the media level addresses are
2547 // not specified.
2548 rtc::SocketAddress address;
2549 address = content->connection_address().IsNil()
2550 ? session_connection_addr
2551 : content->connection_address();
2552 address.SetPort(port);
2553 content->set_connection_address(address);
2554
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002555 desc->AddContent(content_name,
Steve Anton5adfafd2017-12-20 16:34:00 -08002556 IsDtlsSctp(protocol) ? MediaProtocolType::kSctp
2557 : MediaProtocolType::kRtp,
deadbeef25ed4352016-12-12 18:37:36 -08002558 content_rejected, bundle_only, content.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002559 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2560 TransportInfo transport_info(content_name, transport);
2561
2562 if (!desc->AddTransportInfo(transport_info)) {
2563 std::ostringstream description;
2564 description << "Failed to AddTransportInfo with content name: "
2565 << content_name;
2566 return ParseFailed("", description.str(), error);
2567 }
2568 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002569
Steve Antone831b8c2018-02-01 12:22:16 -08002570 desc->set_msid_signaling(msid_signaling);
2571
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002572 size_t end_of_message = message.size();
2573 if (mline_index == -1 && *pos != end_of_message) {
2574 ParseFailed(message, *pos, "Expects m line.", error);
2575 return false;
2576 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002577 return true;
2578}
2579
2580bool VerifyCodec(const cricket::Codec& codec) {
2581 // Codec has not been populated correctly unless the name has been set. This
2582 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2583 // have a corresponding "rtpmap" line.
htab39db842016-12-08 01:50:48 -08002584 return !codec.name.empty();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002585}
2586
2587bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2588 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2589 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2590 iter != codecs.end(); ++iter) {
2591 if (!VerifyCodec(*iter)) {
2592 return false;
2593 }
2594 }
2595 return true;
2596}
2597
2598bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2599 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2600 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2601 iter != codecs.end(); ++iter) {
2602 if (!VerifyCodec(*iter)) {
2603 return false;
2604 }
2605 }
2606 return true;
2607}
2608
2609void AddParameters(const cricket::CodecParameterMap& parameters,
2610 cricket::Codec* codec) {
2611 for (cricket::CodecParameterMap::const_iterator iter =
2612 parameters.begin(); iter != parameters.end(); ++iter) {
2613 codec->SetParam(iter->first, iter->second);
2614 }
2615}
2616
2617void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2618 cricket::Codec* codec) {
2619 codec->AddFeedbackParam(feedback_param);
2620}
2621
2622void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2623 cricket::Codec* codec) {
2624 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2625 feedback_params.params().begin();
2626 iter != feedback_params.params().end(); ++iter) {
2627 codec->AddFeedbackParam(*iter);
2628 }
2629}
2630
2631// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002632// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002633// with that payload type.
2634template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002635T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
magjedb05fa242016-11-11 04:00:16 -08002636 const T* codec = FindCodecById(codecs, payload_type);
2637 if (codec)
2638 return *codec;
2639 // Return empty codec with |payload_type|.
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002640 T ret_val;
magjedb05fa242016-11-11 04:00:16 -08002641 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002642 return ret_val;
2643}
2644
2645// Updates or creates a new codec entry in the audio description.
2646template <class T, class U>
2647void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2648 T* desc = static_cast<T*>(content_desc);
2649 std::vector<U> codecs = desc->codecs();
2650 bool found = false;
2651
2652 typename std::vector<U>::iterator iter;
2653 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2654 if (iter->id == codec.id) {
2655 *iter = codec;
2656 found = true;
2657 break;
2658 }
2659 }
2660 if (!found) {
2661 desc->AddCodec(codec);
2662 return;
2663 }
2664 desc->set_codecs(codecs);
2665}
2666
2667// Adds or updates existing codec corresponding to |payload_type| according
2668// to |parameters|.
2669template <class T, class U>
2670void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2671 const cricket::CodecParameterMap& parameters) {
2672 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002673 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2674 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002675 AddParameters(parameters, &new_codec);
2676 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2677}
2678
2679// Adds or updates existing codec corresponding to |payload_type| according
2680// to |feedback_param|.
2681template <class T, class U>
2682void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2683 const cricket::FeedbackParam& feedback_param) {
2684 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002685 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2686 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002687 AddFeedbackParameter(feedback_param, &new_codec);
2688 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2689}
2690
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002691template <class T>
2692bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2693 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002694 if (iter->id == kWildcardPayloadType) {
2695 *wildcard_codec = *iter;
2696 codecs->erase(iter);
2697 return true;
2698 }
2699 }
2700 return false;
2701}
2702
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002703template<class T>
2704void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2705 auto codecs = desc->codecs();
2706 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002707 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2708 return;
2709 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002710 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002711 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2712 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002713 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002714}
2715
2716void AddAudioAttribute(const std::string& name, const std::string& value,
2717 AudioContentDescription* audio_desc) {
2718 if (value.empty()) {
2719 return;
2720 }
2721 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2722 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2723 iter != codecs.end(); ++iter) {
2724 iter->params[name] = value;
2725 }
2726 audio_desc->set_codecs(codecs);
2727}
2728
2729bool ParseContent(const std::string& message,
2730 const MediaType media_type,
2731 int mline_index,
2732 const std::string& protocol,
deadbeef67cf2c12016-04-13 10:07:16 -07002733 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002734 size_t* pos,
2735 std::string* content_name,
deadbeef25ed4352016-12-12 18:37:36 -08002736 bool* bundle_only,
Steve Antone831b8c2018-02-01 12:22:16 -08002737 int* msid_signaling,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002738 MediaContentDescription* media_desc,
2739 TransportDescription* transport,
2740 std::vector<JsepIceCandidate*>* candidates,
2741 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08002742 RTC_DCHECK(media_desc != NULL);
2743 RTC_DCHECK(content_name != NULL);
2744 RTC_DCHECK(transport != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002745
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002746 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08002747 MaybeCreateStaticPayloadAudioCodecs(payload_types, media_desc->as_audio());
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002748 }
2749
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002750 // The media level "ice-ufrag" and "ice-pwd".
2751 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2752 Candidates candidates_orig;
2753 std::string line;
2754 std::string mline_id;
2755 // Tracks created out of the ssrc attributes.
2756 StreamParamsVec tracks;
2757 SsrcInfoVec ssrc_infos;
2758 SsrcGroupVec ssrc_groups;
2759 std::string maxptime_as_string;
2760 std::string ptime_as_string;
Seth Hampson5b4f0752018-04-02 16:31:36 -07002761 std::vector<std::string> stream_ids;
deadbeef9d3584c2016-02-16 17:54:10 -08002762 std::string track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002763
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002764 // Loop until the next m line
2765 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2766 if (!GetLine(message, pos, &line)) {
2767 if (*pos >= message.size()) {
2768 break; // Done parsing
2769 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002770 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002771 }
2772 }
2773
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002774 // RFC 4566
2775 // b=* (zero or more bandwidth information lines)
2776 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2777 std::string bandwidth;
2778 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2779 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2780 return false;
2781 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002782 int b = 0;
2783 if (!GetValueFromString(line, bandwidth, &b, error)) {
2784 return false;
2785 }
deadbeef3e8016e2017-08-03 17:49:30 -07002786 // TODO(deadbeef): Historically, applications may be setting a value
2787 // of -1 to mean "unset any previously set bandwidth limit", even
2788 // though ommitting the "b=AS" entirely will do just that. Once we've
2789 // transitioned applications to doing the right thing, it would be
2790 // better to treat this as a hard error instead of just ignoring it.
2791 if (b == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002792 RTC_LOG(LS_WARNING)
2793 << "Ignoring \"b=AS:-1\"; will be treated as \"no "
2794 "bandwidth limit\".";
deadbeef3e8016e2017-08-03 17:49:30 -07002795 continue;
2796 }
deadbeefbc88c6b2017-08-02 11:26:34 -07002797 if (b < 0) {
2798 return ParseFailed(line, "b=AS value can't be negative.", error);
2799 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002800 // We should never use more than the default bandwidth for RTP-based
2801 // data channels. Don't allow SDP to set the bandwidth, because
2802 // that would give JS the opportunity to "break the Internet".
2803 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2804 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2805 b > cricket::kDataMaxBandwidth / 1000) {
2806 std::ostringstream description;
2807 description << "RTP-based data channels may not send more than "
2808 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2809 return ParseFailed(line, description.str(), error);
2810 }
deadbeefb2362572016-12-13 16:37:06 -08002811 // Prevent integer overflow.
2812 b = std::min(b, INT_MAX / 1000);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002813 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002814 }
2815 }
2816 continue;
2817 }
2818
zhihuang38989e52017-03-21 11:04:53 -07002819 // Parse the media level connection data.
2820 if (IsLineType(line, kLineTypeConnection)) {
2821 rtc::SocketAddress addr;
2822 if (!ParseConnectionData(line, &addr, error)) {
2823 return false;
2824 }
2825 media_desc->set_connection_address(addr);
2826 continue;
2827 }
2828
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002829 if (!IsLineType(line, kLineTypeAttributes)) {
Steve Anton36b29d12017-10-30 09:57:42 -07002830 // TODO(deadbeef): Handle other lines if needed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01002831 RTC_LOG(LS_INFO) << "Ignored line: " << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002832 continue;
2833 }
2834
2835 // Handle attributes common to SCTP and RTP.
2836 if (HasAttribute(line, kAttributeMid)) {
2837 // RFC 3388
2838 // mid-attribute = "a=mid:" identification-tag
2839 // identification-tag = token
2840 // Use the mid identification-tag as the content name.
2841 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2842 return false;
2843 }
2844 *content_name = mline_id;
deadbeef25ed4352016-12-12 18:37:36 -08002845 } else if (HasAttribute(line, kAttributeBundleOnly)) {
2846 *bundle_only = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002847 } else if (HasAttribute(line, kAttributeCandidate)) {
2848 Candidate candidate;
2849 if (!ParseCandidate(line, &candidate, error, false)) {
2850 return false;
2851 }
deadbeef7bcdb692017-01-20 12:43:58 -08002852 // ParseCandidate will parse non-standard ufrag and password attributes,
2853 // since it's used for candidate trickling, but we only want to process
2854 // the "a=ice-ufrag"/"a=ice-pwd" values in a session description, so
2855 // strip them off at this point.
2856 candidate.set_username(std::string());
2857 candidate.set_password(std::string());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002858 candidates_orig.push_back(candidate);
2859 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2860 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2861 return false;
2862 }
2863 } else if (HasAttribute(line, kAttributeIcePwd)) {
2864 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2865 return false;
2866 }
2867 } else if (HasAttribute(line, kAttributeIceOption)) {
2868 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2869 return false;
2870 }
2871 } else if (HasAttribute(line, kAttributeFmtp)) {
2872 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2873 return false;
2874 }
2875 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002876 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002877
2878 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2879 return false;
2880 }
2881 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002882 } else if (HasAttribute(line, kAttributeSetup)) {
2883 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2884 return false;
2885 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002886 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
deadbeef7e146cb2016-09-28 10:04:34 -07002887 if (media_type != cricket::MEDIA_TYPE_DATA) {
2888 return ParseFailed(
2889 line, "sctp-port attribute found in non-data media description.",
2890 error);
2891 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002892 int sctp_port;
2893 if (!ParseSctpPort(line, &sctp_port, error)) {
2894 return false;
2895 }
Steve Antonb1c1de12017-12-21 15:14:30 -08002896 if (!AddSctpDataCodec(media_desc->as_data(), sctp_port)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002897 return false;
2898 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002899 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002900 //
2901 // RTP specific attrubtes
2902 //
2903 if (HasAttribute(line, kAttributeRtcpMux)) {
2904 media_desc->set_rtcp_mux(true);
deadbeef13871492015-12-09 12:37:51 -08002905 } else if (HasAttribute(line, kAttributeRtcpReducedSize)) {
2906 media_desc->set_rtcp_reduced_size(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002907 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2908 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2909 return false;
2910 }
2911 } else if (HasAttribute(line, kAttributeSsrc)) {
Steve Antone831b8c2018-02-01 12:22:16 -08002912 if (!ParseSsrcAttribute(line, &ssrc_infos, msid_signaling, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002913 return false;
2914 }
2915 } else if (HasAttribute(line, kAttributeCrypto)) {
2916 if (!ParseCryptoAttribute(line, media_desc, error)) {
2917 return false;
2918 }
2919 } else if (HasAttribute(line, kAttributeRtpmap)) {
deadbeef67cf2c12016-04-13 10:07:16 -07002920 if (!ParseRtpmapAttribute(line, media_type, payload_types, media_desc,
2921 error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002922 return false;
2923 }
2924 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2925 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2926 return false;
2927 }
2928 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2929 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2930 return false;
2931 }
2932 } else if (HasAttribute(line, kCodecParamPTime)) {
2933 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2934 return false;
2935 }
2936 } else if (HasAttribute(line, kAttributeSendOnly)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002937 media_desc->set_direction(RtpTransceiverDirection::kSendOnly);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002938 } else if (HasAttribute(line, kAttributeRecvOnly)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002939 media_desc->set_direction(RtpTransceiverDirection::kRecvOnly);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002940 } else if (HasAttribute(line, kAttributeInactive)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002941 media_desc->set_direction(RtpTransceiverDirection::kInactive);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002942 } else if (HasAttribute(line, kAttributeSendRecv)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002943 media_desc->set_direction(RtpTransceiverDirection::kSendRecv);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002944 } else if (HasAttribute(line, kAttributeExtmap)) {
isheriff6f8d6862016-05-26 11:24:55 -07002945 RtpExtension extmap;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002946 if (!ParseExtmap(line, &extmap, error)) {
2947 return false;
2948 }
2949 media_desc->AddRtpHeaderExtension(extmap);
2950 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2951 // Experimental attribute. Conference mode activates more aggressive
2952 // AEC and NS settings.
Steve Anton36b29d12017-10-30 09:57:42 -07002953 // TODO(deadbeef): expose API to set these directly.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002954 std::string flag_value;
2955 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2956 return false;
2957 }
2958 if (flag_value.compare(kValueConference) == 0)
2959 media_desc->set_conference_mode(true);
deadbeef9d3584c2016-02-16 17:54:10 -08002960 } else if (HasAttribute(line, kAttributeMsid)) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07002961 if (!ParseMsidAttribute(line, &stream_ids, &track_id, error)) {
deadbeef9d3584c2016-02-16 17:54:10 -08002962 return false;
2963 }
Steve Antone831b8c2018-02-01 12:22:16 -08002964 *msid_signaling |= cricket::kMsidSignalingMediaSection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002965 }
2966 } else {
2967 // Only parse lines that we are interested of.
Mirko Bonadei675513b2017-11-09 11:09:25 +01002968 RTC_LOG(LS_INFO) << "Ignored line: " << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002969 continue;
2970 }
2971 }
2972
2973 // Create tracks from the |ssrc_infos|.
Taylor Brandstetter5de6b752016-03-09 17:02:30 -08002974 // If the stream_id/track_id for all SSRCS are identical, one StreamParams
2975 // will be created in CreateTracksFromSsrcInfos, containing all the SSRCs from
2976 // the m= section.
Seth Hampson5897a6e2018-04-03 11:16:33 -07002977 if (!ssrc_infos.empty()) {
2978 CreateTracksFromSsrcInfos(ssrc_infos, stream_ids, track_id, &tracks,
2979 *msid_signaling);
2980 } else if (media_type != cricket::MEDIA_TYPE_DATA &&
2981 (*msid_signaling & cricket::kMsidSignalingMediaSection)) {
2982 // If the stream_ids/track_id was signaled but SSRCs were unsignaled we
2983 // still create a track. This isn't done for data media types because
2984 // StreamParams aren't used for SCTP streams, and RTP data channels don't
2985 // support unsignaled SSRCs.
2986 CreateTrackWithNoSsrcs(stream_ids, track_id, &tracks);
2987 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002988
2989 // Add the ssrc group to the track.
2990 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2991 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2992 if (ssrc_group->ssrcs.empty()) {
2993 continue;
2994 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002995 uint32_t ssrc = ssrc_group->ssrcs.front();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002996 for (StreamParamsVec::iterator track = tracks.begin();
2997 track != tracks.end(); ++track) {
2998 if (track->has_ssrc(ssrc)) {
2999 track->ssrc_groups.push_back(*ssrc_group);
3000 }
3001 }
3002 }
3003
3004 // Add the new tracks to the |media_desc|.
deadbeef9d3584c2016-02-16 17:54:10 -08003005 for (StreamParams& track : tracks) {
3006 media_desc->AddStream(track);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003007 }
3008
3009 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08003010 AudioContentDescription* audio_desc = media_desc->as_audio();
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00003011 UpdateFromWildcardCodecs(audio_desc);
3012
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003013 // Verify audio codec ensures that no audio codec has been populated with
3014 // only fmtp.
3015 if (!VerifyAudioCodecs(audio_desc)) {
3016 return ParseFailed("Failed to parse audio codecs correctly.", error);
3017 }
3018 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
3019 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
3020 }
3021
3022 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08003023 VideoContentDescription* video_desc = media_desc->as_video();
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00003024 UpdateFromWildcardCodecs(video_desc);
3025 // Verify video codec ensures that no video codec has been populated with
3026 // only rtcp-fb.
3027 if (!VerifyVideoCodecs(video_desc)) {
3028 return ParseFailed("Failed to parse video codecs correctly.", error);
3029 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003030 }
3031
3032 // RFC 5245
3033 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
3034 for (Candidates::iterator it = candidates_orig.begin();
3035 it != candidates_orig.end(); ++it) {
nisseede5da42017-01-12 05:15:36 -08003036 RTC_DCHECK((*it).username().empty() ||
3037 (*it).username() == transport->ice_ufrag);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003038 (*it).set_username(transport->ice_ufrag);
nisseede5da42017-01-12 05:15:36 -08003039 RTC_DCHECK((*it).password().empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003040 (*it).set_password(transport->ice_pwd);
3041 candidates->push_back(
3042 new JsepIceCandidate(mline_id, mline_index, *it));
3043 }
3044 return true;
3045}
3046
Steve Antone831b8c2018-02-01 12:22:16 -08003047bool ParseSsrcAttribute(const std::string& line,
3048 SsrcInfoVec* ssrc_infos,
3049 int* msid_signaling,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003050 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08003051 RTC_DCHECK(ssrc_infos != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003052 // RFC 5576
3053 // a=ssrc:<ssrc-id> <attribute>
3054 // a=ssrc:<ssrc-id> <attribute>:<value>
3055 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07003056 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
3057 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058 const size_t expected_fields = 2;
3059 return ParseFailedExpectFieldNum(line, expected_fields, error);
3060 }
3061
3062 // ssrc:<ssrc-id>
3063 std::string ssrc_id_s;
3064 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
3065 return false;
3066 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02003067 uint32_t ssrc_id = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003068 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
3069 return false;
3070 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003071
3072 std::string attribute;
3073 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07003074 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003075 std::ostringstream description;
3076 description << "Failed to get the ssrc attribute value from " << field2
3077 << ". Expected format <attribute>:<value>.";
3078 return ParseFailed(line, description.str(), error);
3079 }
3080
3081 // Check if there's already an item for this |ssrc_id|. Create a new one if
3082 // there isn't.
3083 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
3084 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
3085 if (ssrc_info->ssrc_id == ssrc_id) {
3086 break;
3087 }
3088 }
3089 if (ssrc_info == ssrc_infos->end()) {
3090 SsrcInfo info;
3091 info.ssrc_id = ssrc_id;
3092 ssrc_infos->push_back(info);
3093 ssrc_info = ssrc_infos->end() - 1;
3094 }
3095
3096 // Store the info to the |ssrc_info|.
3097 if (attribute == kSsrcAttributeCname) {
3098 // RFC 5576
3099 // cname:<value>
3100 ssrc_info->cname = value;
3101 } else if (attribute == kSsrcAttributeMsid) {
3102 // draft-alvestrand-mmusic-msid-00
Seth Hampson5b4f0752018-04-02 16:31:36 -07003103 // msid:identifier [appdata]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003104 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003105 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003106 if (fields.size() < 1 || fields.size() > 2) {
3107 return ParseFailed(line,
3108 "Expected format \"msid:<identifier>[ <appdata>]\".",
3109 error);
3110 }
deadbeef9d3584c2016-02-16 17:54:10 -08003111 ssrc_info->stream_id = fields[0];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003112 if (fields.size() == 2) {
deadbeef9d3584c2016-02-16 17:54:10 -08003113 ssrc_info->track_id = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003114 }
Steve Antone831b8c2018-02-01 12:22:16 -08003115 *msid_signaling |= cricket::kMsidSignalingSsrcAttribute;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003116 } else if (attribute == kSsrcAttributeMslabel) {
3117 // draft-alvestrand-rtcweb-mid-01
3118 // mslabel:<value>
3119 ssrc_info->mslabel = value;
3120 } else if (attribute == kSSrcAttributeLabel) {
3121 // The label isn't defined.
3122 // label:<value>
3123 ssrc_info->label = value;
3124 }
3125 return true;
3126}
3127
3128bool ParseSsrcGroupAttribute(const std::string& line,
3129 SsrcGroupVec* ssrc_groups,
3130 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08003131 RTC_DCHECK(ssrc_groups != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003132 // RFC 5576
3133 // a=ssrc-group:<semantics> <ssrc-id> ...
3134 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003135 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003136 kSdpDelimiterSpace, &fields);
3137 const size_t expected_min_fields = 2;
3138 if (fields.size() < expected_min_fields) {
3139 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3140 }
3141 std::string semantics;
3142 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
3143 return false;
3144 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02003145 std::vector<uint32_t> ssrcs;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003146 for (size_t i = 1; i < fields.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02003147 uint32_t ssrc = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003148 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
3149 return false;
3150 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003151 ssrcs.push_back(ssrc);
3152 }
3153 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
3154 return true;
3155}
3156
3157bool ParseCryptoAttribute(const std::string& line,
3158 MediaContentDescription* media_desc,
3159 SdpParseError* error) {
3160 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003161 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003162 kSdpDelimiterSpace, &fields);
3163 // RFC 4568
3164 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
3165 const size_t expected_min_fields = 3;
3166 if (fields.size() < expected_min_fields) {
3167 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3168 }
3169 std::string tag_value;
3170 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
3171 return false;
3172 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003173 int tag = 0;
3174 if (!GetValueFromString(line, tag_value, &tag, error)) {
3175 return false;
3176 }
jbauch083b73f2015-07-16 02:46:32 -07003177 const std::string& crypto_suite = fields[1];
3178 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003179 std::string session_params;
3180 if (fields.size() > 3) {
3181 session_params = fields[3];
3182 }
3183 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
3184 session_params));
3185 return true;
3186}
3187
3188// Updates or creates a new codec entry in the audio description with according
deadbeef67cf2c12016-04-13 10:07:16 -07003189// to |name|, |clockrate|, |bitrate|, and |channels|.
3190void UpdateCodec(int payload_type,
3191 const std::string& name,
3192 int clockrate,
3193 int bitrate,
3194 size_t channels,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003195 AudioContentDescription* audio_desc) {
3196 // Codec may already be populated with (only) optional parameters
3197 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00003198 cricket::AudioCodec codec =
3199 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003200 codec.name = name;
3201 codec.clockrate = clockrate;
3202 codec.bitrate = bitrate;
3203 codec.channels = channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003204 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
3205 codec);
3206}
3207
3208// Updates or creates a new codec entry in the video description according to
deadbeef67cf2c12016-04-13 10:07:16 -07003209// |name|, |width|, |height|, and |framerate|.
3210void UpdateCodec(int payload_type,
3211 const std::string& name,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003212 VideoContentDescription* video_desc) {
3213 // Codec may already be populated with (only) optional parameters
3214 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00003215 cricket::VideoCodec codec =
3216 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217 codec.name = name;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003218 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
3219 codec);
3220}
3221
3222bool ParseRtpmapAttribute(const std::string& line,
3223 const MediaType media_type,
deadbeef67cf2c12016-04-13 10:07:16 -07003224 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003225 MediaContentDescription* media_desc,
3226 SdpParseError* error) {
3227 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003228 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003229 kSdpDelimiterSpace, &fields);
3230 // RFC 4566
3231 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
3232 const size_t expected_min_fields = 2;
3233 if (fields.size() < expected_min_fields) {
3234 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3235 }
3236 std::string payload_type_value;
3237 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
3238 return false;
3239 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003240 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003241 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
3242 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003243 return false;
3244 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003245
deadbeef67cf2c12016-04-13 10:07:16 -07003246 if (std::find(payload_types.begin(), payload_types.end(), payload_type) ==
3247 payload_types.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003248 RTC_LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003249 "<fmt> of the m-line: "
3250 << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003251 return true;
3252 }
jbauch083b73f2015-07-16 02:46:32 -07003253 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003254 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003255 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003256 // <encoding name>/<clock rate>[/<encodingparameters>]
3257 // 2 mandatory fields
3258 if (codec_params.size() < 2 || codec_params.size() > 3) {
3259 return ParseFailed(line,
3260 "Expected format \"<encoding name>/<clock rate>"
3261 "[/<encodingparameters>]\".",
3262 error);
3263 }
jbauch083b73f2015-07-16 02:46:32 -07003264 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003265 int clock_rate = 0;
3266 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
3267 return false;
3268 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003269 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08003270 VideoContentDescription* video_desc = media_desc->as_video();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003271 UpdateCodec(payload_type, encoding_name,
deadbeef67cf2c12016-04-13 10:07:16 -07003272 video_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003273 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3274 // RFC 4566
3275 // For audio streams, <encoding parameters> indicates the number
3276 // of audio channels. This parameter is OPTIONAL and may be
3277 // omitted if the number of channels is one, provided that no
3278 // additional parameters are needed.
Peter Kasting69558702016-01-12 16:26:35 -08003279 size_t channels = 1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003280 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003281 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
3282 return false;
3283 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003284 }
Steve Antonb1c1de12017-12-21 15:14:30 -08003285 AudioContentDescription* audio_desc = media_desc->as_audio();
ossue1405ad2017-01-23 08:55:48 -08003286 UpdateCodec(payload_type, encoding_name, clock_rate, 0, channels,
deadbeef67cf2c12016-04-13 10:07:16 -07003287 audio_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003288 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonb1c1de12017-12-21 15:14:30 -08003289 DataContentDescription* data_desc = media_desc->as_data();
deadbeef67cf2c12016-04-13 10:07:16 -07003290 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003291 }
3292 return true;
3293}
3294
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003295bool ParseFmtpParam(const std::string& line, std::string* parameter,
3296 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003297 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003298 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
3299 return false;
3300 }
3301 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003302 return true;
3303}
3304
3305bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
3306 MediaContentDescription* media_desc,
3307 SdpParseError* error) {
3308 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3309 media_type != cricket::MEDIA_TYPE_VIDEO) {
3310 return true;
3311 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003312
3313 std::string line_payload;
3314 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003315
3316 // RFC 5576
3317 // a=fmtp:<format> <format specific parameters>
3318 // At least two fields, whereas the second one is any of the optional
3319 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07003320 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
3321 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003322 ParseFailedExpectMinFieldNum(line, 2, error);
3323 return false;
3324 }
3325
Donald Curtis0e07f922015-05-15 09:21:23 -07003326 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003327 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07003328 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003329 return false;
3330 }
3331
Donald Curtis0e07f922015-05-15 09:21:23 -07003332 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07003333 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3334 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003335 return false;
3336 }
3337
3338 // Parse out format specific parameters.
3339 std::vector<std::string> fields;
3340 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
3341
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003342 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07003343 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003344 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003345 // Only fmtps with equals are currently supported. Other fmtp types
3346 // should be ignored. Unknown fmtps do not constitute an error.
3347 continue;
3348 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003349
3350 std::string name;
3351 std::string value;
3352 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003353 return false;
3354 }
3355 codec_params[name] = value;
3356 }
3357
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003358 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3359 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003360 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003361 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3362 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003363 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003364 }
3365 return true;
3366}
3367
3368bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3369 MediaContentDescription* media_desc,
3370 SdpParseError* error) {
3371 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3372 media_type != cricket::MEDIA_TYPE_VIDEO) {
3373 return true;
3374 }
3375 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003376 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003377 if (rtcp_fb_fields.size() < 2) {
3378 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3379 }
3380 std::string payload_type_string;
3381 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3382 error)) {
3383 return false;
3384 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003385 int payload_type = kWildcardPayloadType;
3386 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003387 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3388 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003389 return false;
3390 }
3391 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003392 std::string id = rtcp_fb_fields[1];
3393 std::string param = "";
3394 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3395 iter != rtcp_fb_fields.end(); ++iter) {
3396 param.append(*iter);
3397 }
3398 const cricket::FeedbackParam feedback_param(id, param);
3399
3400 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003401 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3402 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003403 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003404 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3405 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003406 }
3407 return true;
3408}
3409
3410} // namespace webrtc