blob: 56f4c991caa31649686a0eb2c31344d1f6681542 [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
123static const char kAttributeMsidSemantics[] = "msid-semantic";
124static const char kMediaStreamSemantic[] = "WMS";
125static const char kSsrcAttributeMsid[] = "msid";
126static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000127static const char kSsrcAttributeMslabel[] = "mslabel";
128static const char kSSrcAttributeLabel[] = "label";
129static const char kAttributeSsrcGroup[] = "ssrc-group";
130static const char kAttributeCrypto[] = "crypto";
131static const char kAttributeCandidate[] = "candidate";
132static const char kAttributeCandidateTyp[] = "typ";
133static const char kAttributeCandidateRaddr[] = "raddr";
134static const char kAttributeCandidateRport[] = "rport";
honghaiza54a0802015-12-16 18:37:23 -0800135static const char kAttributeCandidateUfrag[] = "ufrag";
136static const char kAttributeCandidatePwd[] = "pwd";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137static const char kAttributeCandidateGeneration[] = "generation";
honghaiza0c44ea2016-03-23 16:07:48 -0700138static const char kAttributeCandidateNetworkId[] = "network-id";
honghaize1a0c942016-02-16 14:54:56 -0800139static const char kAttributeCandidateNetworkCost[] = "network-cost";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000140static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000141static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000142static const char kAttributeFmtp[] = "fmtp";
143static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000144static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000145static const char kAttributeRtcp[] = "rtcp";
146static const char kAttributeIceUfrag[] = "ice-ufrag";
147static const char kAttributeIcePwd[] = "ice-pwd";
148static const char kAttributeIceLite[] = "ice-lite";
149static const char kAttributeIceOption[] = "ice-options";
150static const char kAttributeSendOnly[] = "sendonly";
151static const char kAttributeRecvOnly[] = "recvonly";
152static const char kAttributeRtcpFb[] = "rtcp-fb";
153static const char kAttributeSendRecv[] = "sendrecv";
154static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000155// draft-ietf-mmusic-sctp-sdp-07
156// a=sctp-port
157static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000158
159// Experimental flags
160static const char kAttributeXGoogleFlag[] = "x-google-flag";
161static const char kValueConference[] = "conference";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000162
163// Candidate
164static const char kCandidateHost[] = "host";
165static const char kCandidateSrflx[] = "srflx";
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700166static const char kCandidatePrflx[] = "prflx";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000167static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000168static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000169
170static const char kSdpDelimiterEqual = '=';
171static const char kSdpDelimiterSpace = ' ';
172static const char kSdpDelimiterColon = ':';
173static const char kSdpDelimiterSemicolon = ';';
174static const char kSdpDelimiterSlash = '/';
175static const char kNewLine = '\n';
176static const char kReturn = '\r';
177static const char kLineBreak[] = "\r\n";
178
Steve Anton36b29d12017-10-30 09:57:42 -0700179// TODO(deadbeef): Generate the Session and Time description
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000180// instead of hardcoding.
181static const char kSessionVersion[] = "v=0";
182// RFC 4566
183static const char kSessionOriginUsername[] = "-";
184static const char kSessionOriginSessionId[] = "0";
185static const char kSessionOriginSessionVersion[] = "0";
186static const char kSessionOriginNettype[] = "IN";
187static const char kSessionOriginAddrtype[] = "IP4";
188static const char kSessionOriginAddress[] = "127.0.0.1";
189static const char kSessionName[] = "s=-";
190static const char kTimeDescription[] = "t=0 0";
191static const char kAttrGroup[] = "a=group:BUNDLE";
192static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000193static const char kConnectionIpv4Addrtype[] = "IP4";
194static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000195static const char kMediaTypeVideo[] = "video";
196static const char kMediaTypeAudio[] = "audio";
197static const char kMediaTypeData[] = "application";
198static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000199// draft-ietf-mmusic-trickle-ice-01
200// When no candidates have been gathered, set the connection
201// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000202// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
203// Use IPV4 per default.
204static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000205static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000206// RFC 3556
207static const char kApplicationSpecificMaximum[] = "AS";
208
wu@webrtc.org78187522013-10-07 23:32:02 +0000209static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000210
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000211// RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
212// types.
213const int kWildcardPayloadType = -1;
214
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000215struct SsrcInfo {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200216 uint32_t ssrc_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000217 std::string cname;
deadbeef9d3584c2016-02-16 17:54:10 -0800218 std::string stream_id;
219 std::string track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000220
221 // For backward compatibility.
222 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
223 std::string label;
224 std::string mslabel;
225};
226typedef std::vector<SsrcInfo> SsrcInfoVec;
227typedef std::vector<SsrcGroup> SsrcGroupVec;
228
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000229template <class T>
230static void AddFmtpLine(const T& codec, std::string* message);
231static void BuildMediaDescription(const ContentInfo* content_info,
232 const TransportInfo* transport_info,
233 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000234 const std::vector<Candidate>& candidates,
deadbeef9d3584c2016-02-16 17:54:10 -0800235 bool unified_plan_sdp,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000236 std::string* message);
zstein4b2e0822017-02-17 19:48:38 -0800237static void BuildSctpContentAttributes(std::string* message,
238 int sctp_port,
239 bool use_sctpmap);
deadbeef9d3584c2016-02-16 17:54:10 -0800240static void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
241 const MediaType media_type,
242 bool unified_plan_sdp,
243 std::string* message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000244static void BuildRtpMap(const MediaContentDescription* media_desc,
245 const MediaType media_type,
246 std::string* message);
247static void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -0800248 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249 std::string* message);
250static void BuildIceOptions(const std::vector<std::string>& transport_options,
251 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000252static bool IsRtp(const std::string& protocol);
253static bool IsDtlsSctp(const std::string& protocol);
zhihuang38989e52017-03-21 11:04:53 -0700254static bool ParseSessionDescription(const std::string& message,
255 size_t* pos,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000256 std::string* session_id,
257 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258 TransportDescription* session_td,
259 RtpHeaderExtensions* session_extmaps,
zhihuang38989e52017-03-21 11:04:53 -0700260 rtc::SocketAddress* connection_addr,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000261 cricket::SessionDescription* desc,
262 SdpParseError* error);
263static bool ParseGroupAttribute(const std::string& line,
264 cricket::SessionDescription* desc,
265 SdpParseError* error);
266static bool ParseMediaDescription(
267 const std::string& message,
268 const TransportDescription& session_td,
269 const RtpHeaderExtensions& session_extmaps,
zhihuang38989e52017-03-21 11:04:53 -0700270 size_t* pos,
271 const rtc::SocketAddress& session_connection_addr,
272 cricket::SessionDescription* desc,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000273 std::vector<JsepIceCandidate*>* candidates,
274 SdpParseError* error);
275static bool ParseContent(const std::string& message,
276 const MediaType media_type,
277 int mline_index,
278 const std::string& protocol,
deadbeef67cf2c12016-04-13 10:07:16 -0700279 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000280 size_t* pos,
281 std::string* content_name,
deadbeef25ed4352016-12-12 18:37:36 -0800282 bool* bundle_only,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000283 MediaContentDescription* media_desc,
284 TransportDescription* transport,
285 std::vector<JsepIceCandidate*>* candidates,
286 SdpParseError* error);
287static bool ParseSsrcAttribute(const std::string& line,
288 SsrcInfoVec* ssrc_infos,
289 SdpParseError* error);
290static bool ParseSsrcGroupAttribute(const std::string& line,
291 SsrcGroupVec* ssrc_groups,
292 SdpParseError* error);
293static bool ParseCryptoAttribute(const std::string& line,
294 MediaContentDescription* media_desc,
295 SdpParseError* error);
296static bool ParseRtpmapAttribute(const std::string& line,
297 const MediaType media_type,
deadbeef67cf2c12016-04-13 10:07:16 -0700298 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000299 MediaContentDescription* media_desc,
300 SdpParseError* error);
301static bool ParseFmtpAttributes(const std::string& line,
302 const MediaType media_type,
303 MediaContentDescription* media_desc,
304 SdpParseError* error);
305static bool ParseFmtpParam(const std::string& line, std::string* parameter,
306 std::string* value, SdpParseError* error);
307static bool ParseCandidate(const std::string& message, Candidate* candidate,
308 SdpParseError* error, bool is_raw);
309static bool ParseRtcpFbAttribute(const std::string& line,
310 const MediaType media_type,
311 MediaContentDescription* media_desc,
312 SdpParseError* error);
313static bool ParseIceOptions(const std::string& line,
314 std::vector<std::string>* transport_options,
315 SdpParseError* error);
316static bool ParseExtmap(const std::string& line,
isheriff6f8d6862016-05-26 11:24:55 -0700317 RtpExtension* extmap,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000318 SdpParseError* error);
319static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000320 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000321 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000322static bool ParseDtlsSetup(const std::string& line,
323 cricket::ConnectionRole* role,
324 SdpParseError* error);
deadbeef9d3584c2016-02-16 17:54:10 -0800325static bool ParseMsidAttribute(const std::string& line,
326 std::string* stream_id,
327 std::string* track_id,
328 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000329
330// Helper functions
331
332// Below ParseFailed*** functions output the line that caused the parsing
333// failure and the detailed reason (|description|) of the failure to |error|.
334// The functions always return false so that they can be used directly in the
335// following way when error happens:
336// "return ParseFailed***(...);"
337
338// The line starting at |line_start| of |message| is the failing line.
339// The reason for the failure should be provided in the |description|.
340// An example of a description could be "unknown character".
341static bool ParseFailed(const std::string& message,
342 size_t line_start,
343 const std::string& description,
344 SdpParseError* error) {
345 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000346 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000347 size_t line_end = message.find(kNewLine, line_start);
348 if (line_end != std::string::npos) {
349 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
350 --line_end;
351 }
352 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000353 } else {
354 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000355 }
356
357 if (error) {
358 error->line = first_line;
359 error->description = description;
360 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100361 RTC_LOG(LS_ERROR) << "Failed to parse: \"" << first_line
362 << "\". Reason: " << description;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000363 return false;
364}
365
366// |line| is the failing line. The reason for the failure should be
367// provided in the |description|.
368static bool ParseFailed(const std::string& line,
369 const std::string& description,
370 SdpParseError* error) {
371 return ParseFailed(line, 0, description, error);
372}
373
374// Parses failure where the failing SDP line isn't know or there are multiple
375// failing lines.
376static bool ParseFailed(const std::string& description,
377 SdpParseError* error) {
378 return ParseFailed("", description, error);
379}
380
381// |line| is the failing line. The failure is due to the fact that |line|
382// doesn't have |expected_fields| fields.
383static bool ParseFailedExpectFieldNum(const std::string& line,
384 int expected_fields,
385 SdpParseError* error) {
386 std::ostringstream description;
387 description << "Expects " << expected_fields << " fields.";
388 return ParseFailed(line, description.str(), error);
389}
390
391// |line| is the failing line. The failure is due to the fact that |line| has
392// less than |expected_min_fields| fields.
393static bool ParseFailedExpectMinFieldNum(const std::string& line,
394 int expected_min_fields,
395 SdpParseError* error) {
396 std::ostringstream description;
397 description << "Expects at least " << expected_min_fields << " fields.";
398 return ParseFailed(line, description.str(), error);
399}
400
401// |line| is the failing line. The failure is due to the fact that it failed to
402// get the value of |attribute|.
403static bool ParseFailedGetValue(const std::string& line,
404 const std::string& attribute,
405 SdpParseError* error) {
406 std::ostringstream description;
407 description << "Failed to get the value of attribute: " << attribute;
408 return ParseFailed(line, description.str(), error);
409}
410
411// The line starting at |line_start| of |message| is the failing line. The
412// failure is due to the line type (e.g. the "m" part of the "m-line")
413// not matching what is expected. The expected line type should be
414// provided as |line_type|.
415static bool ParseFailedExpectLine(const std::string& message,
416 size_t line_start,
417 const char line_type,
418 const std::string& line_value,
419 SdpParseError* error) {
420 std::ostringstream description;
421 description << "Expect line: " << line_type << "=" << line_value;
422 return ParseFailed(message, line_start, description.str(), error);
423}
424
425static bool AddLine(const std::string& line, std::string* message) {
426 if (!message)
427 return false;
428
429 message->append(line);
430 message->append(kLineBreak);
431 return true;
432}
433
434static bool GetLine(const std::string& message,
435 size_t* pos,
436 std::string* line) {
437 size_t line_begin = *pos;
438 size_t line_end = message.find(kNewLine, line_begin);
439 if (line_end == std::string::npos) {
440 return false;
441 }
442 // Update the new start position
443 *pos = line_end + 1;
444 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
445 --line_end;
446 }
447 *line = message.substr(line_begin, (line_end - line_begin));
448 const char* cline = line->c_str();
449 // RFC 4566
450 // An SDP session description consists of a number of lines of text of
451 // the form:
452 // <type>=<value>
453 // where <type> MUST be exactly one case-significant character and
454 // <value> is structured text whose format depends on <type>.
455 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000456 if (line->length() < 3 ||
457 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000458 cline[1] != kSdpDelimiterEqual ||
459 cline[2] == kSdpDelimiterSpace) {
460 *pos = line_begin;
461 return false;
462 }
463 return true;
464}
465
466// Init |os| to "|type|=|value|".
467static void InitLine(const char type,
468 const std::string& value,
469 std::ostringstream* os) {
470 os->str("");
471 *os << type << kSdpDelimiterEqual << value;
472}
473
474// Init |os| to "a=|attribute|".
475static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
476 InitLine(kLineTypeAttributes, attribute, os);
477}
478
479// Writes a SDP attribute line based on |attribute| and |value| to |message|.
480static void AddAttributeLine(const std::string& attribute, int value,
481 std::string* message) {
482 std::ostringstream os;
483 InitAttrLine(attribute, &os);
484 os << kSdpDelimiterColon << value;
485 AddLine(os.str(), message);
486}
487
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000488static bool IsLineType(const std::string& message,
489 const char type,
490 size_t line_start) {
491 if (message.size() < line_start + kLinePrefixLength) {
492 return false;
493 }
494 const char* cmessage = message.c_str();
495 return (cmessage[line_start] == type &&
496 cmessage[line_start + 1] == kSdpDelimiterEqual);
497}
498
499static bool IsLineType(const std::string& line,
500 const char type) {
501 return IsLineType(line, type, 0);
502}
503
504static bool GetLineWithType(const std::string& message, size_t* pos,
505 std::string* line, const char type) {
506 if (!IsLineType(message, type, *pos)) {
507 return false;
508 }
509
510 if (!GetLine(message, pos, line))
511 return false;
512
513 return true;
514}
515
516static bool HasAttribute(const std::string& line,
517 const std::string& attribute) {
518 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
519}
520
Peter Boström0c4e06b2015-10-07 12:23:21 +0200521static bool AddSsrcLine(uint32_t ssrc_id,
522 const std::string& attribute,
523 const std::string& value,
524 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000525 // RFC 5576
526 // a=ssrc:<ssrc-id> <attribute>:<value>
527 std::ostringstream os;
528 InitAttrLine(kAttributeSsrc, &os);
529 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
530 << attribute << kSdpDelimiterColon << value;
531 return AddLine(os.str(), message);
532}
533
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000534// Get value only from <attribute>:<value>.
535static bool GetValue(const std::string& message, const std::string& attribute,
536 std::string* value, SdpParseError* error) {
537 std::string leftpart;
Donald Curtis0e07f922015-05-15 09:21:23 -0700538 if (!rtc::tokenize_first(message, kSdpDelimiterColon, &leftpart, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000539 return ParseFailedGetValue(message, attribute, error);
540 }
541 // The left part should end with the expected attribute.
542 if (leftpart.length() < attribute.length() ||
543 leftpart.compare(leftpart.length() - attribute.length(),
544 attribute.length(), attribute) != 0) {
545 return ParseFailedGetValue(message, attribute, error);
546 }
547 return true;
548}
549
550static bool CaseInsensitiveFind(std::string str1, std::string str2) {
551 std::transform(str1.begin(), str1.end(), str1.begin(),
552 ::tolower);
553 std::transform(str2.begin(), str2.end(), str2.begin(),
554 ::tolower);
555 return str1.find(str2) != std::string::npos;
556}
557
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000558template <class T>
559static bool GetValueFromString(const std::string& line,
560 const std::string& s,
561 T* t,
562 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000563 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000564 std::ostringstream description;
565 description << "Invalid value: " << s << ".";
566 return ParseFailed(line, description.str(), error);
567 }
568 return true;
569}
570
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000571static bool GetPayloadTypeFromString(const std::string& line,
572 const std::string& s,
573 int* payload_type,
574 SdpParseError* error) {
575 return GetValueFromString(line, s, payload_type, error) &&
576 cricket::IsValidRtpPayloadType(*payload_type);
577}
578
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800579// |msid_stream_id| and |msid_track_id| represent the stream/track ID from the
580// "a=msid" attribute, if it exists. They are empty if the attribute does not
581// exist.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000582void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800583 const std::string& msid_stream_id,
584 const std::string& msid_track_id,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000585 StreamParamsVec* tracks) {
nisseede5da42017-01-12 05:15:36 -0800586 RTC_DCHECK(tracks != NULL);
587 RTC_DCHECK(msid_stream_id.empty() == msid_track_id.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000588 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
589 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
590 if (ssrc_info->cname.empty()) {
591 continue;
592 }
593
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800594 std::string stream_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000595 std::string track_id;
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800596 if (ssrc_info->stream_id.empty() && !ssrc_info->mslabel.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000597 // If there's no msid and there's mslabel, we consider this is a sdp from
598 // a older version of client that doesn't support msid.
599 // In that case, we use the mslabel and label to construct the track.
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800600 stream_id = ssrc_info->mslabel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000601 track_id = ssrc_info->label;
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800602 } else if (ssrc_info->stream_id.empty() && !msid_stream_id.empty()) {
603 // If there's no msid in the SSRC attributes, but there's a global one
604 // (from a=msid), use that. This is the case with unified plan SDP.
605 stream_id = msid_stream_id;
606 track_id = msid_track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000607 } else {
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800608 stream_id = ssrc_info->stream_id;
deadbeef9d3584c2016-02-16 17:54:10 -0800609 track_id = ssrc_info->track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000610 }
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800611 // If a stream/track ID wasn't populated from the SSRC attributes OR the
612 // msid attribute, use default/random values.
613 if (stream_id.empty()) {
614 stream_id = kDefaultMsid;
615 }
616 if (track_id.empty()) {
617 // TODO(ronghuawu): What should we do if the track id doesn't appear?
618 // Create random string (which will be used as track label later)?
619 track_id = rtc::CreateRandomString(8);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000620 }
621
622 StreamParamsVec::iterator track = tracks->begin();
623 for (; track != tracks->end(); ++track) {
624 if (track->id == track_id) {
625 break;
626 }
627 }
628 if (track == tracks->end()) {
629 // If we don't find an existing track, create a new one.
630 tracks->push_back(StreamParams());
631 track = tracks->end() - 1;
632 }
633 track->add_ssrc(ssrc_info->ssrc_id);
634 track->cname = ssrc_info->cname;
Taylor Brandstetter5de6b752016-03-09 17:02:30 -0800635 track->sync_label = stream_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000636 track->id = track_id;
637 }
638}
639
640void GetMediaStreamLabels(const ContentInfo* content,
641 std::set<std::string>* labels) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800642 for (const StreamParams& stream_params :
643 content->media_description()->streams()) {
644 labels->insert(stream_params.sync_label);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000645 }
646}
647
648// RFC 5245
649// It is RECOMMENDED that default candidates be chosen based on the
650// likelihood of those candidates to work with the peer that is being
651// contacted. It is RECOMMENDED that relayed > reflexive > host.
652static const int kPreferenceUnknown = 0;
653static const int kPreferenceHost = 1;
654static const int kPreferenceReflexive = 2;
655static const int kPreferenceRelayed = 3;
656
657static int GetCandidatePreferenceFromType(const std::string& type) {
658 int preference = kPreferenceUnknown;
659 if (type == cricket::LOCAL_PORT_TYPE) {
660 preference = kPreferenceHost;
661 } else if (type == cricket::STUN_PORT_TYPE) {
662 preference = kPreferenceReflexive;
663 } else if (type == cricket::RELAY_PORT_TYPE) {
664 preference = kPreferenceRelayed;
665 } else {
nissec80e7412017-01-11 05:56:46 -0800666 RTC_NOTREACHED();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667 }
668 return preference;
669}
670
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000671// Get ip and port of the default destination from the |candidates| with the
672// given value of |component_id|. The default candidate should be the one most
673// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000674// RFC 5245
675// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
Steve Anton36b29d12017-10-30 09:57:42 -0700676// TODO(deadbeef): Decide the default destination in webrtcsession and
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000677// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000678static void GetDefaultDestination(
679 const std::vector<Candidate>& candidates,
680 int component_id, std::string* port,
681 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000682 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000683 *port = kDummyPort;
684 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000686 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000687 for (std::vector<Candidate>::const_iterator it = candidates.begin();
688 it != candidates.end(); ++it) {
689 if (it->component() != component_id) {
690 continue;
691 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000692 // Default destination should be UDP only.
693 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000694 continue;
695 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000696 const int preference = GetCandidatePreferenceFromType(it->type());
697 const int family = it->address().ipaddr().family();
698 // See if this candidate is more preferable then the current one if it's the
699 // same family. Or if the current family is IPv4 already so we could safely
700 // ignore all IPv6 ones. WebRTC bug 4269.
701 // http://code.google.com/p/webrtc/issues/detail?id=4269
702 if ((preference <= current_preference && current_family == family) ||
703 (current_family == AF_INET && family == AF_INET6)) {
704 continue;
705 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000706 if (family == AF_INET) {
707 addr_type->assign(kConnectionIpv4Addrtype);
708 } else if (family == AF_INET6) {
709 addr_type->assign(kConnectionIpv6Addrtype);
710 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000711 current_preference = preference;
712 current_family = family;
713 *port = it->address().PortAsString();
714 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000715 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716}
717
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000718// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
719static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000720 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
721 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
722 &rtcp_port, &rtcp_ip, &addr_type);
723 // Found default RTCP candidate.
724 // RFC 5245
725 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
726 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000728 // RFC 3605
729 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
730 // connection-address] CRLF
731 std::ostringstream os;
732 InitAttrLine(kAttributeRtcp, &os);
733 os << kSdpDelimiterColon
734 << rtcp_port << " "
735 << kConnectionNettype << " "
736 << addr_type << " "
737 << rtcp_ip;
738 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000739 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740}
741
742// Get candidates according to the mline index from SessionDescriptionInterface.
743static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
744 int mline_index,
745 std::vector<Candidate>* candidates) {
746 if (!candidates) {
747 return;
748 }
749 const IceCandidateCollection* cc = desci.candidates(mline_index);
750 for (size_t i = 0; i < cc->count(); ++i) {
751 const IceCandidateInterface* candidate = cc->at(i);
752 candidates->push_back(candidate->candidate());
753 }
754}
755
deadbeef90f1e1e2017-02-10 12:35:05 -0800756static bool IsValidPort(int port) {
757 return port >= 0 && port <= 65535;
758}
759
deadbeef9d3584c2016-02-16 17:54:10 -0800760std::string SdpSerialize(const JsepSessionDescription& jdesc,
761 bool unified_plan_sdp) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000762 const cricket::SessionDescription* desc = jdesc.description();
763 if (!desc) {
764 return "";
765 }
766
767 std::string message;
768
769 // Session Description.
770 AddLine(kSessionVersion, &message);
771 // Session Origin
772 // RFC 4566
773 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
774 // <unicast-address>
775 std::ostringstream os;
776 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
jbauch083b73f2015-07-16 02:46:32 -0700777 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700779 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000780 kSessionOriginSessionVersion : jdesc.session_version();
781 os << " " << session_id << " " << session_version << " "
782 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
783 << kSessionOriginAddress;
784 AddLine(os.str(), &message);
785 AddLine(kSessionName, &message);
786
787 // Time Description.
788 AddLine(kTimeDescription, &message);
789
790 // Group
791 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
792 std::string group_line = kAttrGroup;
793 const cricket::ContentGroup* group =
794 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
nisseede5da42017-01-12 05:15:36 -0800795 RTC_DCHECK(group != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796 const cricket::ContentNames& content_names = group->content_names();
797 for (cricket::ContentNames::const_iterator it = content_names.begin();
798 it != content_names.end(); ++it) {
799 group_line.append(" ");
800 group_line.append(*it);
801 }
802 AddLine(group_line, &message);
803 }
804
805 // MediaStream semantics
806 InitAttrLine(kAttributeMsidSemantics, &os);
807 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000808
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000809 std::set<std::string> media_stream_labels;
810 const ContentInfo* audio_content = GetFirstAudioContent(desc);
811 if (audio_content)
812 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000813
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000814 const ContentInfo* video_content = GetFirstVideoContent(desc);
815 if (video_content)
816 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000817
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818 for (std::set<std::string>::const_iterator it =
819 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
820 os << " " << *it;
821 }
822 AddLine(os.str(), &message);
823
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000824 // Preserve the order of the media contents.
825 int mline_index = -1;
826 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
827 it != desc->contents().end(); ++it) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800828 const MediaContentDescription* mdesc = it->media_description();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000829 std::vector<Candidate> candidates;
830 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
deadbeef9d3584c2016-02-16 17:54:10 -0800831 BuildMediaDescription(&*it, desc->GetTransportInfoByName(it->name),
832 mdesc->type(), candidates, unified_plan_sdp,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000833 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835 return message;
836}
837
838// Serializes the passed in IceCandidateInterface to a SDP string.
839// candidate - The candidate to be serialized.
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700840std::string SdpSerializeCandidate(const IceCandidateInterface& candidate) {
841 return SdpSerializeCandidate(candidate.candidate());
842}
843
844// Serializes a cricket Candidate.
845std::string SdpSerializeCandidate(const cricket::Candidate& candidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846 std::string message;
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700847 std::vector<cricket::Candidate> candidates(1, candidate);
honghaiza54a0802015-12-16 18:37:23 -0800848 BuildCandidate(candidates, true, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000849 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
850 // just candidate:<candidate> not a=candidate:<blah>CRLF
nisseede5da42017-01-12 05:15:36 -0800851 RTC_DCHECK(message.find("a=") == 0);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000852 message.erase(0, 2);
nisseede5da42017-01-12 05:15:36 -0800853 RTC_DCHECK(message.find(kLineBreak) == message.size() - 2);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000854 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000855 return message;
856}
857
858bool SdpDeserialize(const std::string& message,
859 JsepSessionDescription* jdesc,
860 SdpParseError* error) {
861 std::string session_id;
862 std::string session_version;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700863 TransportDescription session_td("", "");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000864 RtpHeaderExtensions session_extmaps;
zhihuang38989e52017-03-21 11:04:53 -0700865 rtc::SocketAddress session_connection_addr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000866 cricket::SessionDescription* desc = new cricket::SessionDescription();
867 std::vector<JsepIceCandidate*> candidates;
868 size_t current_pos = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000869
870 // Session Description
871 if (!ParseSessionDescription(message, &current_pos, &session_id,
deadbeefc80741f2015-10-22 13:14:45 -0700872 &session_version, &session_td, &session_extmaps,
zhihuang38989e52017-03-21 11:04:53 -0700873 &session_connection_addr, desc, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874 delete desc;
875 return false;
876 }
877
878 // Media Description
deadbeefc80741f2015-10-22 13:14:45 -0700879 if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
zhihuang38989e52017-03-21 11:04:53 -0700880 session_connection_addr, desc, &candidates,
881 error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000882 delete desc;
883 for (std::vector<JsepIceCandidate*>::const_iterator
884 it = candidates.begin(); it != candidates.end(); ++it) {
885 delete *it;
886 }
887 return false;
888 }
889
890 jdesc->Initialize(desc, session_id, session_version);
891
892 for (std::vector<JsepIceCandidate*>::const_iterator
893 it = candidates.begin(); it != candidates.end(); ++it) {
894 jdesc->AddCandidate(*it);
895 delete *it;
896 }
897 return true;
898}
899
900bool SdpDeserializeCandidate(const std::string& message,
901 JsepIceCandidate* jcandidate,
902 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -0800903 RTC_DCHECK(jcandidate != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000904 Candidate candidate;
905 if (!ParseCandidate(message, &candidate, error, true)) {
906 return false;
907 }
908 jcandidate->SetCandidate(candidate);
909 return true;
910}
911
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700912bool SdpDeserializeCandidate(const std::string& transport_name,
913 const std::string& message,
914 cricket::Candidate* candidate,
915 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -0800916 RTC_DCHECK(candidate != nullptr);
Honghai Zhang7fb69db2016-03-14 11:59:18 -0700917 if (!ParseCandidate(message, candidate, error, true)) {
918 return false;
919 }
920 candidate->set_transport_name(transport_name);
921 return true;
922}
923
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000924bool ParseCandidate(const std::string& message, Candidate* candidate,
925 SdpParseError* error, bool is_raw) {
nisseede5da42017-01-12 05:15:36 -0800926 RTC_DCHECK(candidate != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000927
928 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000929 std::string first_line = message;
930 size_t pos = 0;
931 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000933 // Makes sure |message| contains only one line.
934 if (message.size() > first_line.size()) {
935 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700936 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
937 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000938 return ParseFailed(message, 0, "Expect one line only", error);
939 }
940 }
941
942 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
943 // candidate:<candidate> when trickled, but we still support
944 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
945 // from the SDP.
946 if (IsLineType(first_line, kLineTypeAttributes)) {
947 first_line = first_line.substr(kLinePrefixLength);
948 }
949
950 std::string attribute_candidate;
951 std::string candidate_value;
952
953 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700954 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
955 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000956 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000957 if (is_raw) {
958 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000959 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960 << ":" << "<candidate-str>";
961 return ParseFailed(first_line, 0, description.str(), error);
962 } else {
963 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
964 kAttributeCandidate, error);
965 }
966 }
967
968 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000969 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
970
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000971 // RFC 5245
972 // a=candidate:<foundation> <component-id> <transport> <priority>
973 // <connection-address> <port> typ <candidate-types>
974 // [raddr <connection-address>] [rport <port>]
975 // *(SP extension-att-name SP extension-att-value)
976 const size_t expected_min_fields = 8;
977 if (fields.size() < expected_min_fields ||
978 (fields[6] != kAttributeCandidateTyp)) {
979 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
980 }
jbauch083b73f2015-07-16 02:46:32 -0700981 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000982
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000983 int component_id = 0;
984 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
985 return false;
986 }
jbauch083b73f2015-07-16 02:46:32 -0700987 const std::string& transport = fields[2];
Peter Boström0c4e06b2015-10-07 12:23:21 +0200988 uint32_t priority = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000989 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
990 return false;
991 }
jbauch083b73f2015-07-16 02:46:32 -0700992 const std::string& connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000993 int port = 0;
994 if (!GetValueFromString(first_line, fields[5], &port, error)) {
995 return false;
996 }
deadbeef90f1e1e2017-02-10 12:35:05 -0800997 if (!IsValidPort(port)) {
998 return ParseFailed(first_line, "Invalid port number.", error);
999 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000 SocketAddress address(connection_address, port);
1001
1002 cricket::ProtocolType protocol;
hnslb68cc752016-12-13 10:33:41 -08001003 if (!StringToProto(transport.c_str(), &protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001004 return ParseFailed(first_line, "Unsupported transport type.", error);
1005 }
hnslb68cc752016-12-13 10:33:41 -08001006 switch (protocol) {
1007 case cricket::PROTO_UDP:
1008 case cricket::PROTO_TCP:
1009 case cricket::PROTO_SSLTCP:
1010 // Supported protocol.
1011 break;
1012 default:
1013 return ParseFailed(first_line, "Unsupported transport type.", error);
1014 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015
1016 std::string candidate_type;
jbauch083b73f2015-07-16 02:46:32 -07001017 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001018 if (type == kCandidateHost) {
1019 candidate_type = cricket::LOCAL_PORT_TYPE;
1020 } else if (type == kCandidateSrflx) {
1021 candidate_type = cricket::STUN_PORT_TYPE;
1022 } else if (type == kCandidateRelay) {
1023 candidate_type = cricket::RELAY_PORT_TYPE;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001024 } else if (type == kCandidatePrflx) {
1025 candidate_type = cricket::PRFLX_PORT_TYPE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026 } else {
1027 return ParseFailed(first_line, "Unsupported candidate type.", error);
1028 }
1029
1030 size_t current_position = expected_min_fields;
1031 SocketAddress related_address;
1032 // The 2 optional fields for related address
1033 // [raddr <connection-address>] [rport <port>]
1034 if (fields.size() >= (current_position + 2) &&
1035 fields[current_position] == kAttributeCandidateRaddr) {
1036 related_address.SetIP(fields[++current_position]);
1037 ++current_position;
1038 }
1039 if (fields.size() >= (current_position + 2) &&
1040 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001041 int port = 0;
1042 if (!GetValueFromString(
1043 first_line, fields[++current_position], &port, error)) {
1044 return false;
1045 }
deadbeef90f1e1e2017-02-10 12:35:05 -08001046 if (!IsValidPort(port)) {
1047 return ParseFailed(first_line, "Invalid port number.", error);
1048 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001049 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050 ++current_position;
1051 }
1052
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001053 // If this is a TCP candidate, it has additional extension as defined in
1054 // RFC 6544.
1055 std::string tcptype;
1056 if (fields.size() >= (current_position + 2) &&
1057 fields[current_position] == kTcpCandidateType) {
1058 tcptype = fields[++current_position];
1059 ++current_position;
1060
1061 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1062 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1063 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1064 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1065 }
1066
1067 if (protocol != cricket::PROTO_TCP) {
1068 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1069 }
1070 }
1071
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001072 // Extension
honghaiza54a0802015-12-16 18:37:23 -08001073 // Though non-standard, we support the ICE ufrag and pwd being signaled on
1074 // the candidate to avoid issues with confusing which generation a candidate
1075 // belongs to when trickling multiple generations at the same time.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001076 std::string username;
1077 std::string password;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001078 uint32_t generation = 0;
honghaiza0c44ea2016-03-23 16:07:48 -07001079 uint16_t network_id = 0;
1080 uint16_t network_cost = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1082 // RFC 5245
1083 // *(SP extension-att-name SP extension-att-value)
1084 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001085 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1086 return false;
1087 }
honghaiza54a0802015-12-16 18:37:23 -08001088 } else if (fields[i] == kAttributeCandidateUfrag) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001089 username = fields[++i];
honghaiza54a0802015-12-16 18:37:23 -08001090 } else if (fields[i] == kAttributeCandidatePwd) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 password = fields[++i];
honghaiza0c44ea2016-03-23 16:07:48 -07001092 } else if (fields[i] == kAttributeCandidateNetworkId) {
1093 if (!GetValueFromString(first_line, fields[++i], &network_id, error)) {
1094 return false;
1095 }
honghaize1a0c942016-02-16 14:54:56 -08001096 } else if (fields[i] == kAttributeCandidateNetworkCost) {
1097 if (!GetValueFromString(first_line, fields[++i], &network_cost, error)) {
1098 return false;
1099 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001100 network_cost = std::min(network_cost, rtc::kNetworkCostMax);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 } else {
1102 // Skip the unknown extension.
1103 ++i;
1104 }
1105 }
1106
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001107 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001108 address, priority, username, password, candidate_type,
honghaiza0c44ea2016-03-23 16:07:48 -07001109 generation, foundation, network_id, network_cost);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001110 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001111 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112 return true;
1113}
1114
1115bool ParseIceOptions(const std::string& line,
1116 std::vector<std::string>* transport_options,
1117 SdpParseError* error) {
1118 std::string ice_options;
1119 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1120 return false;
1121 }
1122 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001123 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001124 for (size_t i = 0; i < fields.size(); ++i) {
1125 transport_options->push_back(fields[i]);
1126 }
1127 return true;
1128}
1129
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001130bool ParseSctpPort(const std::string& line,
1131 int* sctp_port,
1132 SdpParseError* error) {
1133 // draft-ietf-mmusic-sctp-sdp-07
1134 // a=sctp-port
1135 std::vector<std::string> fields;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001136 const size_t expected_min_fields = 2;
lally69f57602015-10-08 10:15:04 -07001137 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1138 if (fields.size() < expected_min_fields) {
1139 fields.resize(0);
1140 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpace, &fields);
1141 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001142 if (fields.size() < expected_min_fields) {
1143 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1144 }
1145 if (!rtc::FromString(fields[1], sctp_port)) {
lally69f57602015-10-08 10:15:04 -07001146 return ParseFailed(line, "Invalid sctp port value.", error);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001147 }
1148 return true;
1149}
1150
isheriff6f8d6862016-05-26 11:24:55 -07001151bool ParseExtmap(const std::string& line,
1152 RtpExtension* extmap,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001153 SdpParseError* error) {
1154 // RFC 5285
1155 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1156 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001157 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001158 kSdpDelimiterSpace, &fields);
1159 const size_t expected_min_fields = 2;
1160 if (fields.size() < expected_min_fields) {
1161 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1162 }
1163 std::string uri = fields[1];
1164
1165 std::string value_direction;
1166 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1167 return false;
1168 }
1169 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001170 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001171 int value = 0;
1172 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1173 return false;
1174 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001175
jbauch5869f502017-06-29 12:31:36 -07001176 bool encrypted = false;
1177 if (uri == RtpExtension::kEncryptHeaderExtensionsUri) {
1178 // RFC 6904
Steve Anton36b29d12017-10-30 09:57:42 -07001179 // a=extmap:<value["/"<direction>] urn:ietf:params:rtp-hdrext:encrypt <URI>
1180 // <extensionattributes>
jbauch5869f502017-06-29 12:31:36 -07001181 const size_t expected_min_fields_encrypted = expected_min_fields + 1;
1182 if (fields.size() < expected_min_fields_encrypted) {
1183 return ParseFailedExpectMinFieldNum(line, expected_min_fields_encrypted,
1184 error);
1185 }
1186
1187 encrypted = true;
1188 uri = fields[2];
1189 if (uri == RtpExtension::kEncryptHeaderExtensionsUri) {
1190 return ParseFailed(line, "Recursive encrypted header.", error);
1191 }
1192 }
1193
1194 *extmap = RtpExtension(uri, value, encrypted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001195 return true;
1196}
1197
1198void BuildMediaDescription(const ContentInfo* content_info,
1199 const TransportInfo* transport_info,
1200 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001201 const std::vector<Candidate>& candidates,
deadbeef9d3584c2016-02-16 17:54:10 -08001202 bool unified_plan_sdp,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001203 std::string* message) {
nisseede5da42017-01-12 05:15:36 -08001204 RTC_DCHECK(message != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001205 if (content_info == NULL || message == NULL) {
1206 return;
1207 }
Steve Anton36b29d12017-10-30 09:57:42 -07001208 // TODO(deadbeef): Rethink if we should use sprintfn instead of stringstream.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001209 // According to the style guide, streams should only be used for logging.
1210 // http://google-styleguide.googlecode.com/svn/
1211 // trunk/cppguide.xml?showone=Streams#Streams
1212 std::ostringstream os;
Steve Antonb1c1de12017-12-21 15:14:30 -08001213 const MediaContentDescription* media_desc = content_info->media_description();
1214 RTC_DCHECK(media_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001215
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001216 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217
1218 // RFC 4566
1219 // m=<media> <port> <proto> <fmt>
1220 // fmt is a list of payload type numbers that MAY be used in the session.
1221 const char* type = NULL;
1222 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1223 type = kMediaTypeAudio;
1224 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1225 type = kMediaTypeVideo;
1226 else if (media_type == cricket::MEDIA_TYPE_DATA)
1227 type = kMediaTypeData;
1228 else
nissec80e7412017-01-11 05:56:46 -08001229 RTC_NOTREACHED();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001230
1231 std::string fmt;
1232 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001233 const VideoContentDescription* video_desc = media_desc->as_video();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001234 for (std::vector<cricket::VideoCodec>::const_iterator it =
1235 video_desc->codecs().begin();
1236 it != video_desc->codecs().end(); ++it) {
1237 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001238 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001239 }
1240 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001241 const AudioContentDescription* audio_desc = media_desc->as_audio();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001242 for (std::vector<cricket::AudioCodec>::const_iterator it =
1243 audio_desc->codecs().begin();
1244 it != audio_desc->codecs().end(); ++it) {
1245 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001246 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001247 }
1248 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001249 const DataContentDescription* data_desc = media_desc->as_data();
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001250 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001251 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001252
zstein4b2e0822017-02-17 19:48:38 -08001253 if (data_desc->use_sctpmap()) {
1254 for (std::vector<cricket::DataCodec>::const_iterator it =
1255 data_desc->codecs().begin();
1256 it != data_desc->codecs().end(); ++it) {
1257 if (cricket::CodecNamesEq(it->name,
1258 cricket::kGoogleSctpDataCodecName) &&
1259 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1260 break;
1261 }
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001262 }
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001263
zstein4b2e0822017-02-17 19:48:38 -08001264 fmt.append(rtc::ToString<int>(sctp_port));
1265 } else {
1266 fmt.append(kDefaultSctpmapProtocol);
1267 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001268 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001269 for (std::vector<cricket::DataCodec>::const_iterator it =
1270 data_desc->codecs().begin();
1271 it != data_desc->codecs().end(); ++it) {
1272 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001273 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001274 }
1275 }
1276 }
1277 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1278 // to 0.
1279 if (fmt.empty()) {
1280 fmt = " 0";
1281 }
1282
deadbeef25ed4352016-12-12 18:37:36 -08001283 // The port number in the m line will be updated later when associated with
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001284 // the candidates.
deadbeef25ed4352016-12-12 18:37:36 -08001285 //
1286 // A port value of 0 indicates that the m= section is rejected.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287 // RFC 3264
1288 // To reject an offered stream, the port number in the corresponding stream in
1289 // the answer MUST be set to zero.
deadbeef25ed4352016-12-12 18:37:36 -08001290 //
1291 // However, the BUNDLE draft adds a new meaning to port zero, when used along
1292 // with a=bundle-only.
zhihuang38989e52017-03-21 11:04:53 -07001293 std::string port = kDummyPort;
1294 if (content_info->rejected || content_info->bundle_only) {
1295 port = kMediaPortRejected;
1296 } else if (!media_desc->connection_address().IsNil()) {
1297 port = rtc::ToString(media_desc->connection_address().port());
1298 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001300 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001301 transport_info->description.identity_fingerprint.get() : NULL;
1302
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001303 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001304 InitLine(kLineTypeMedia, type, &os);
1305 os << " " << port << " " << media_desc->protocol() << fmt;
zhihuang38989e52017-03-21 11:04:53 -07001306 AddLine(os.str(), message);
1307
1308 InitLine(kLineTypeConnection, kConnectionNettype, &os);
1309 if (media_desc->connection_address().IsNil()) {
1310 os << " " << kConnectionIpv4Addrtype << " " << kDummyAddress;
1311 } else if (media_desc->connection_address().family() == AF_INET) {
1312 os << " " << kConnectionIpv4Addrtype << " "
1313 << media_desc->connection_address().ipaddr().ToString();
1314 } else {
1315 os << " " << kConnectionIpv6Addrtype << " "
1316 << media_desc->connection_address().ipaddr().ToString();
1317 }
1318 AddLine(os.str(), message);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001319
1320 // RFC 4566
1321 // b=AS:<bandwidth>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001322 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001323 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1324 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1325 AddLine(os.str(), message);
1326 }
1327
deadbeef25ed4352016-12-12 18:37:36 -08001328 // Add the a=bundle-only line.
1329 if (content_info->bundle_only) {
1330 InitAttrLine(kAttributeBundleOnly, &os);
1331 AddLine(os.str(), message);
1332 }
1333
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001334 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001335 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001336 std::string rtcp_line = GetRtcpLine(candidates);
1337 if (!rtcp_line.empty()) {
1338 AddLine(rtcp_line, message);
1339 }
1340 }
1341
honghaiza54a0802015-12-16 18:37:23 -08001342 // Build the a=candidate lines. We don't include ufrag and pwd in the
1343 // candidates in the SDP to avoid redundancy.
1344 BuildCandidate(candidates, false, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345
1346 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1347 if (transport_info) {
1348 // RFC 5245
1349 // ice-pwd-att = "ice-pwd" ":" password
1350 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1351 // ice-ufrag
deadbeef3f7219b2015-12-28 15:17:14 -08001352 if (!transport_info->description.ice_ufrag.empty()) {
1353 InitAttrLine(kAttributeIceUfrag, &os);
1354 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1355 AddLine(os.str(), message);
1356 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357 // ice-pwd
deadbeef3f7219b2015-12-28 15:17:14 -08001358 if (!transport_info->description.ice_pwd.empty()) {
1359 InitAttrLine(kAttributeIcePwd, &os);
1360 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1361 AddLine(os.str(), message);
1362 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363
1364 // draft-petithuguenin-mmusic-ice-attributes-level-03
1365 BuildIceOptions(transport_info->description.transport_options, message);
1366
1367 // RFC 4572
1368 // fingerprint-attribute =
1369 // "fingerprint" ":" hash-func SP fingerprint
1370 if (fp) {
1371 // Insert the fingerprint attribute.
1372 InitAttrLine(kAttributeFingerprint, &os);
1373 os << kSdpDelimiterColon
1374 << fp->algorithm << kSdpDelimiterSpace
1375 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001377
1378 // Inserting setup attribute.
1379 if (transport_info->description.connection_role !=
1380 cricket::CONNECTIONROLE_NONE) {
1381 // Making sure we are not using "passive" mode.
1382 cricket::ConnectionRole role =
1383 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001384 std::string dtls_role_str;
nissec16fa5e2017-02-07 07:18:43 -08001385 const bool success =
1386 cricket::ConnectionRoleToString(role, &dtls_role_str);
1387 RTC_DCHECK(success);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001388 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001389 os << kSdpDelimiterColon << dtls_role_str;
1390 AddLine(os.str(), message);
1391 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 }
1393 }
1394
1395 // RFC 3388
1396 // mid-attribute = "a=mid:" identification-tag
1397 // identification-tag = token
1398 // Use the content name as the mid identification-tag.
1399 InitAttrLine(kAttributeMid, &os);
1400 os << kSdpDelimiterColon << content_info->name;
1401 AddLine(os.str(), message);
1402
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001403 if (IsDtlsSctp(media_desc->protocol())) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001404 const DataContentDescription* data_desc = media_desc->as_data();
zstein4b2e0822017-02-17 19:48:38 -08001405 bool use_sctpmap = data_desc->use_sctpmap();
1406 BuildSctpContentAttributes(message, sctp_port, use_sctpmap);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001407 } else if (IsRtp(media_desc->protocol())) {
deadbeef9d3584c2016-02-16 17:54:10 -08001408 BuildRtpContentAttributes(media_desc, media_type, unified_plan_sdp,
1409 message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001410 }
1411}
1412
zstein4b2e0822017-02-17 19:48:38 -08001413void BuildSctpContentAttributes(std::string* message,
1414 int sctp_port,
1415 bool use_sctpmap) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001416 std::ostringstream os;
zstein4b2e0822017-02-17 19:48:38 -08001417 if (use_sctpmap) {
1418 // draft-ietf-mmusic-sctp-sdp-04
1419 // a=sctpmap:sctpmap-number protocol [streams]
1420 InitAttrLine(kAttributeSctpmap, &os);
1421 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
1422 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1423 << cricket::kMaxSctpStreams;
1424 } else {
1425 // draft-ietf-mmusic-sctp-sdp-23
1426 // a=sctp-port:<port>
1427 InitAttrLine(kAttributeSctpPort, &os);
1428 os << kSdpDelimiterColon << sctp_port;
1429 // TODO(zstein): emit max-message-size here
1430 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001431 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432}
1433
deadbeef9d3584c2016-02-16 17:54:10 -08001434// If unified_plan_sdp is true, will use "a=msid".
1435void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
1436 const MediaType media_type,
1437 bool unified_plan_sdp,
1438 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001439 std::ostringstream os;
1440 // RFC 5285
1441 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1442 // The definitions MUST be either all session level or all media level. This
1443 // implementation uses all media level.
1444 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
jbauch5869f502017-06-29 12:31:36 -07001445 const RtpExtension& extension = media_desc->rtp_header_extensions()[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001446 InitAttrLine(kAttributeExtmap, &os);
jbauch5869f502017-06-29 12:31:36 -07001447 os << kSdpDelimiterColon << extension.id;
1448 if (extension.encrypt) {
1449 os << kSdpDelimiterSpace << RtpExtension::kEncryptHeaderExtensionsUri;
1450 }
1451 os << kSdpDelimiterSpace << extension.uri;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001452 AddLine(os.str(), message);
1453 }
1454
1455 // RFC 3264
1456 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
deadbeefc80741f2015-10-22 13:14:45 -07001457 switch (media_desc->direction()) {
Steve Anton4e70a722017-11-28 14:57:10 -08001458 case RtpTransceiverDirection::kInactive:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459 InitAttrLine(kAttributeInactive, &os);
1460 break;
Steve Anton4e70a722017-11-28 14:57:10 -08001461 case RtpTransceiverDirection::kSendOnly:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462 InitAttrLine(kAttributeSendOnly, &os);
1463 break;
Steve Anton4e70a722017-11-28 14:57:10 -08001464 case RtpTransceiverDirection::kRecvOnly:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001465 InitAttrLine(kAttributeRecvOnly, &os);
1466 break;
Steve Anton4e70a722017-11-28 14:57:10 -08001467 case RtpTransceiverDirection::kSendRecv:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001468 default:
1469 InitAttrLine(kAttributeSendRecv, &os);
1470 break;
1471 }
1472 AddLine(os.str(), message);
1473
deadbeef9d3584c2016-02-16 17:54:10 -08001474 // draft-ietf-mmusic-msid-11
1475 // a=msid:<stream id> <track id>
1476 if (unified_plan_sdp && !media_desc->streams().empty()) {
1477 if (media_desc->streams().size() > 1u) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001478 RTC_LOG(LS_WARNING)
1479 << "Trying to serialize unified plan SDP with more than "
1480 << "one track in a media section. Omitting 'a=msid'.";
deadbeef9d3584c2016-02-16 17:54:10 -08001481 } else {
1482 auto track = media_desc->streams().begin();
1483 const std::string& stream_id = track->sync_label;
deadbeef9d3584c2016-02-16 17:54:10 -08001484 InitAttrLine(kAttributeMsid, &os);
1485 os << kSdpDelimiterColon << stream_id << kSdpDelimiterSpace << track->id;
1486 AddLine(os.str(), message);
1487 }
1488 }
1489
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001490 // RFC 5761
1491 // a=rtcp-mux
1492 if (media_desc->rtcp_mux()) {
1493 InitAttrLine(kAttributeRtcpMux, &os);
1494 AddLine(os.str(), message);
1495 }
1496
deadbeef13871492015-12-09 12:37:51 -08001497 // RFC 5506
1498 // a=rtcp-rsize
1499 if (media_desc->rtcp_reduced_size()) {
1500 InitAttrLine(kAttributeRtcpReducedSize, &os);
1501 AddLine(os.str(), message);
1502 }
1503
deadbeefd45aea82017-09-16 01:24:29 -07001504 if (media_desc->conference_mode()) {
1505 InitAttrLine(kAttributeXGoogleFlag, &os);
1506 os << kSdpDelimiterColon << kValueConference;
1507 AddLine(os.str(), message);
1508 }
1509
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001510 // RFC 4568
1511 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1512 for (std::vector<CryptoParams>::const_iterator it =
1513 media_desc->cryptos().begin();
1514 it != media_desc->cryptos().end(); ++it) {
1515 InitAttrLine(kAttributeCrypto, &os);
1516 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1517 << it->key_params;
1518 if (!it->session_params.empty()) {
1519 os << " " << it->session_params;
1520 }
1521 AddLine(os.str(), message);
1522 }
1523
1524 // RFC 4566
1525 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1526 // [/<encodingparameters>]
1527 BuildRtpMap(media_desc, media_type, message);
1528
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001529 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1530 track != media_desc->streams().end(); ++track) {
1531 // Require that the track belongs to a media stream,
1532 // ie the sync_label is set. This extra check is necessary since the
1533 // MediaContentDescription always contains a streamparam with an ssrc even
1534 // if no track or media stream have been created.
1535 if (track->sync_label.empty()) continue;
1536
1537 // Build the ssrc-group lines.
1538 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1539 // RFC 5576
1540 // a=ssrc-group:<semantics> <ssrc-id> ...
1541 if (track->ssrc_groups[i].ssrcs.empty()) {
1542 continue;
1543 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001544 InitAttrLine(kAttributeSsrcGroup, &os);
1545 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001546 std::vector<uint32_t>::const_iterator ssrc =
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547 track->ssrc_groups[i].ssrcs.begin();
1548 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001549 os << kSdpDelimiterSpace << rtc::ToString<uint32_t>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001550 }
1551 AddLine(os.str(), message);
1552 }
1553 // Build the ssrc lines for each ssrc.
1554 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001555 uint32_t ssrc = track->ssrcs[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001556 // RFC 5576
1557 // a=ssrc:<ssrc-id> cname:<value>
1558 AddSsrcLine(ssrc, kSsrcAttributeCname,
1559 track->cname, message);
1560
1561 // draft-alvestrand-mmusic-msid-00
1562 // a=ssrc:<ssrc-id> msid:identifier [appdata]
deadbeef9d3584c2016-02-16 17:54:10 -08001563 // The appdata consists of the "id" attribute of a MediaStreamTrack,
1564 // which corresponds to the "id" attribute of StreamParams.
1565 const std::string& stream_id = track->sync_label;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001566 InitAttrLine(kAttributeSsrc, &os);
1567 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
deadbeef9d3584c2016-02-16 17:54:10 -08001568 << kSsrcAttributeMsid << kSdpDelimiterColon << stream_id
1569 << kSdpDelimiterSpace << track->id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001570 AddLine(os.str(), message);
1571
deadbeef9d3584c2016-02-16 17:54:10 -08001572 // TODO(ronghuawu): Remove below code which is for backward
1573 // compatibility.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001574 // draft-alvestrand-rtcweb-mid-01
1575 // a=ssrc:<ssrc-id> mslabel:<value>
1576 // The label isn't yet defined.
1577 // a=ssrc:<ssrc-id> label:<value>
1578 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1579 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1580 }
1581 }
1582}
1583
1584void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1585 // fmtp header: a=fmtp:|payload_type| <parameters>
1586 // Add a=fmtp
1587 InitAttrLine(kAttributeFmtp, os);
1588 // Add :|payload_type|
1589 *os << kSdpDelimiterColon << payload_type;
1590}
1591
1592void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1593 // rtcp-fb header: a=rtcp-fb:|payload_type|
1594 // <parameters>/<ccm <ccm_parameters>>
1595 // Add a=rtcp-fb
1596 InitAttrLine(kAttributeRtcpFb, os);
1597 // Add :
1598 *os << kSdpDelimiterColon;
1599 if (payload_type == kWildcardPayloadType) {
1600 *os << "*";
1601 } else {
1602 *os << payload_type;
1603 }
1604}
1605
1606void WriteFmtpParameter(const std::string& parameter_name,
1607 const std::string& parameter_value,
1608 std::ostringstream* os) {
1609 // fmtp parameters: |parameter_name|=|parameter_value|
1610 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1611}
1612
1613void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1614 std::ostringstream* os) {
1615 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1616 fmtp != parameters.end(); ++fmtp) {
hta62a216e2016-04-15 11:02:14 -07001617 // Parameters are a semicolon-separated list, no spaces.
1618 // The list is separated from the header by a space.
1619 if (fmtp == parameters.begin()) {
1620 *os << kSdpDelimiterSpace;
1621 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001622 *os << kSdpDelimiterSemicolon;
1623 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001624 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1625 }
1626}
1627
1628bool IsFmtpParam(const std::string& name) {
ossuaa4b0772017-01-30 07:41:18 -08001629 // RFC 4855, section 3 specifies the mapping of media format parameters to SDP
1630 // parameters. Only ptime, maxptime, channels and rate are placed outside of
1631 // the fmtp line. In WebRTC, channels and rate are already handled separately
1632 // and thus not included in the CodecParameterMap.
1633 return name != kCodecParamPTime && name != kCodecParamMaxPTime;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001634}
1635
1636// Retreives fmtp parameters from |params|, which may contain other parameters
1637// as well, and puts them in |fmtp_parameters|.
1638void GetFmtpParams(const cricket::CodecParameterMap& params,
1639 cricket::CodecParameterMap* fmtp_parameters) {
1640 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1641 iter != params.end(); ++iter) {
1642 if (IsFmtpParam(iter->first)) {
1643 (*fmtp_parameters)[iter->first] = iter->second;
1644 }
1645 }
1646}
1647
1648template <class T>
1649void AddFmtpLine(const T& codec, std::string* message) {
1650 cricket::CodecParameterMap fmtp_parameters;
1651 GetFmtpParams(codec.params, &fmtp_parameters);
1652 if (fmtp_parameters.empty()) {
1653 // No need to add an fmtp if it will have no (optional) parameters.
1654 return;
1655 }
1656 std::ostringstream os;
1657 WriteFmtpHeader(codec.id, &os);
1658 WriteFmtpParameters(fmtp_parameters, &os);
1659 AddLine(os.str(), message);
1660 return;
1661}
1662
1663template <class T>
1664void AddRtcpFbLines(const T& codec, std::string* message) {
1665 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1666 codec.feedback_params.params().begin();
1667 iter != codec.feedback_params.params().end(); ++iter) {
1668 std::ostringstream os;
1669 WriteRtcpFbHeader(codec.id, &os);
1670 os << " " << iter->id();
1671 if (!iter->param().empty()) {
1672 os << " " << iter->param();
1673 }
1674 AddLine(os.str(), message);
1675 }
1676}
1677
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001678bool AddSctpDataCodec(DataContentDescription* media_desc,
1679 int sctp_port) {
solenberg9fa49752016-10-08 13:02:44 -07001680 for (const auto& codec : media_desc->codecs()) {
1681 if (cricket::CodecNamesEq(codec.name, cricket::kGoogleSctpDataCodecName)) {
1682 return ParseFailed("",
1683 "Can't have multiple sctp port attributes.",
1684 NULL);
1685 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001686 }
1687 // Add the SCTP Port number as a pseudo-codec "port" parameter
solenberg9fa49752016-10-08 13:02:44 -07001688 cricket::DataCodec codec_port(cricket::kGoogleSctpDataCodecPlType,
deadbeef67cf2c12016-04-13 10:07:16 -07001689 cricket::kGoogleSctpDataCodecName);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001690 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
Mirko Bonadei675513b2017-11-09 11:09:25 +01001691 RTC_LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number " << sctp_port;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001692 media_desc->AddCodec(codec_port);
1693 return true;
1694}
1695
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001696bool GetMinValue(const std::vector<int>& values, int* value) {
1697 if (values.empty()) {
1698 return false;
1699 }
1700 std::vector<int>::const_iterator found =
1701 std::min_element(values.begin(), values.end());
1702 *value = *found;
1703 return true;
1704}
1705
1706bool GetParameter(const std::string& name,
1707 const cricket::CodecParameterMap& params, int* value) {
1708 std::map<std::string, std::string>::const_iterator found =
1709 params.find(name);
1710 if (found == params.end()) {
1711 return false;
1712 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001713 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001714 return false;
1715 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716 return true;
1717}
1718
1719void BuildRtpMap(const MediaContentDescription* media_desc,
1720 const MediaType media_type,
1721 std::string* message) {
nisseede5da42017-01-12 05:15:36 -08001722 RTC_DCHECK(message != NULL);
1723 RTC_DCHECK(media_desc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001724 std::ostringstream os;
1725 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001726 const VideoContentDescription* video_desc = media_desc->as_video();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001727 for (std::vector<cricket::VideoCodec>::const_iterator it =
1728 video_desc->codecs().begin();
1729 it != video_desc->codecs().end(); ++it) {
1730 // RFC 4566
1731 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1732 // [/<encodingparameters>]
1733 if (it->id != kWildcardPayloadType) {
1734 InitAttrLine(kAttributeRtpmap, &os);
deadbeefe814a0d2017-02-25 18:15:09 -08001735 os << kSdpDelimiterColon << it->id << " " << it->name << "/"
1736 << cricket::kVideoCodecClockrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001737 AddLine(os.str(), message);
1738 }
1739 AddRtcpFbLines(*it, message);
1740 AddFmtpLine(*it, message);
1741 }
1742 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001743 const AudioContentDescription* audio_desc = media_desc->as_audio();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001744 std::vector<int> ptimes;
1745 std::vector<int> maxptimes;
1746 int max_minptime = 0;
1747 for (std::vector<cricket::AudioCodec>::const_iterator it =
1748 audio_desc->codecs().begin();
1749 it != audio_desc->codecs().end(); ++it) {
nisseede5da42017-01-12 05:15:36 -08001750 RTC_DCHECK(!it->name.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001751 // RFC 4566
1752 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1753 // [/<encodingparameters>]
1754 InitAttrLine(kAttributeRtpmap, &os);
1755 os << kSdpDelimiterColon << it->id << " ";
1756 os << it->name << "/" << it->clockrate;
1757 if (it->channels != 1) {
1758 os << "/" << it->channels;
1759 }
1760 AddLine(os.str(), message);
1761 AddRtcpFbLines(*it, message);
1762 AddFmtpLine(*it, message);
1763 int minptime = 0;
1764 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1765 max_minptime = std::max(minptime, max_minptime);
1766 }
1767 int ptime;
1768 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1769 ptimes.push_back(ptime);
1770 }
1771 int maxptime;
1772 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1773 maxptimes.push_back(maxptime);
1774 }
1775 }
1776 // Populate the maxptime attribute with the smallest maxptime of all codecs
1777 // under the same m-line.
1778 int min_maxptime = INT_MAX;
1779 if (GetMinValue(maxptimes, &min_maxptime)) {
1780 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1781 }
nisseede5da42017-01-12 05:15:36 -08001782 RTC_DCHECK(min_maxptime > max_minptime);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001783 // Populate the ptime attribute with the smallest ptime or the largest
1784 // minptime, whichever is the largest, for all codecs under the same m-line.
1785 int ptime = INT_MAX;
1786 if (GetMinValue(ptimes, &ptime)) {
1787 ptime = std::min(ptime, min_maxptime);
1788 ptime = std::max(ptime, max_minptime);
1789 AddAttributeLine(kCodecParamPTime, ptime, message);
1790 }
1791 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonb1c1de12017-12-21 15:14:30 -08001792 const DataContentDescription* data_desc = media_desc->as_data();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001793 for (std::vector<cricket::DataCodec>::const_iterator it =
1794 data_desc->codecs().begin();
1795 it != data_desc->codecs().end(); ++it) {
1796 // RFC 4566
1797 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1798 // [/<encodingparameters>]
1799 InitAttrLine(kAttributeRtpmap, &os);
1800 os << kSdpDelimiterColon << it->id << " "
1801 << it->name << "/" << it->clockrate;
1802 AddLine(os.str(), message);
1803 }
1804 }
1805}
1806
1807void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -08001808 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001809 std::string* message) {
1810 std::ostringstream os;
1811
1812 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1813 it != candidates.end(); ++it) {
1814 // RFC 5245
1815 // a=candidate:<foundation> <component-id> <transport> <priority>
1816 // <connection-address> <port> typ <candidate-types>
1817 // [raddr <connection-address>] [rport <port>]
1818 // *(SP extension-att-name SP extension-att-value)
1819 std::string type;
1820 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1821 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1822 type = kCandidateHost;
1823 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1824 type = kCandidateSrflx;
1825 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1826 type = kCandidateRelay;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001827 } else if (it->type() == cricket::PRFLX_PORT_TYPE) {
1828 type = kCandidatePrflx;
1829 // Peer reflexive candidate may be signaled for being removed.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830 } else {
nissec80e7412017-01-11 05:56:46 -08001831 RTC_NOTREACHED();
Peter Thatcher019087f2015-04-28 09:06:26 -07001832 // Never write out candidates if we don't know the type.
1833 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001834 }
1835
1836 InitAttrLine(kAttributeCandidate, &os);
1837 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001838 << it->foundation() << " "
1839 << it->component() << " "
1840 << it->protocol() << " "
1841 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001842 << it->address().ipaddr().ToString() << " "
1843 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001844 << kAttributeCandidateTyp << " "
1845 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001846
1847 // Related address
1848 if (!it->related_address().IsNil()) {
1849 os << kAttributeCandidateRaddr << " "
1850 << it->related_address().ipaddr().ToString() << " "
1851 << kAttributeCandidateRport << " "
1852 << it->related_address().PortAsString() << " ";
1853 }
1854
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001855 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001856 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001857 }
1858
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001859 // Extensions
1860 os << kAttributeCandidateGeneration << " " << it->generation();
honghaiza54a0802015-12-16 18:37:23 -08001861 if (include_ufrag && !it->username().empty()) {
1862 os << " " << kAttributeCandidateUfrag << " " << it->username();
1863 }
honghaiza0c44ea2016-03-23 16:07:48 -07001864 if (it->network_id() > 0) {
1865 os << " " << kAttributeCandidateNetworkId << " " << it->network_id();
1866 }
honghaize1a0c942016-02-16 14:54:56 -08001867 if (it->network_cost() > 0) {
1868 os << " " << kAttributeCandidateNetworkCost << " " << it->network_cost();
1869 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001870
1871 AddLine(os.str(), message);
1872 }
1873}
1874
1875void BuildIceOptions(const std::vector<std::string>& transport_options,
1876 std::string* message) {
1877 if (!transport_options.empty()) {
1878 std::ostringstream os;
1879 InitAttrLine(kAttributeIceOption, &os);
1880 os << kSdpDelimiterColon << transport_options[0];
1881 for (size_t i = 1; i < transport_options.size(); ++i) {
1882 os << kSdpDelimiterSpace << transport_options[i];
1883 }
1884 AddLine(os.str(), message);
1885 }
1886}
1887
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001888bool IsRtp(const std::string& protocol) {
1889 return protocol.empty() ||
1890 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1891}
1892
1893bool IsDtlsSctp(const std::string& protocol) {
1894 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001895 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001896}
1897
zhihuang38989e52017-03-21 11:04:53 -07001898bool ParseConnectionData(const std::string& line,
1899 rtc::SocketAddress* addr,
1900 SdpParseError* error) {
1901 // Parse the line from left to right.
1902 std::string token;
1903 std::string rightpart;
1904 // RFC 4566
1905 // c=<nettype> <addrtype> <connection-address>
1906 // Skip the "c="
1907 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, &token, &rightpart)) {
1908 return ParseFailed(line, "Failed to parse the network type.", error);
1909 }
1910
1911 // Extract and verify the <nettype>
1912 if (!rtc::tokenize_first(rightpart, kSdpDelimiterSpace, &token, &rightpart) ||
1913 token != kConnectionNettype) {
1914 return ParseFailed(line,
1915 "Failed to parse the connection data. The network type "
1916 "is not currently supported.",
1917 error);
1918 }
1919
1920 // Extract the "<addrtype>" and "<connection-address>".
1921 if (!rtc::tokenize_first(rightpart, kSdpDelimiterSpace, &token, &rightpart)) {
1922 return ParseFailed(line, "Failed to parse the address type.", error);
1923 }
1924
1925 // The rightpart part should be the IP address without the slash which is used
1926 // for multicast.
1927 if (rightpart.find('/') != std::string::npos) {
1928 return ParseFailed(line,
1929 "Failed to parse the connection data. Multicast is not "
1930 "currently supported.",
1931 error);
1932 }
1933 addr->SetIP(rightpart);
1934
1935 // Verify that the addrtype matches the type of the parsed address.
1936 if ((addr->family() == AF_INET && token != "IP4") ||
1937 (addr->family() == AF_INET6 && token != "IP6")) {
1938 addr->Clear();
1939 return ParseFailed(
1940 line,
1941 "Failed to parse the connection data. The address type is mismatching.",
1942 error);
1943 }
1944 return true;
1945}
1946
1947bool ParseSessionDescription(const std::string& message,
1948 size_t* pos,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001949 std::string* session_id,
1950 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001951 TransportDescription* session_td,
1952 RtpHeaderExtensions* session_extmaps,
zhihuang38989e52017-03-21 11:04:53 -07001953 rtc::SocketAddress* connection_addr,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001954 cricket::SessionDescription* desc,
1955 SdpParseError* error) {
1956 std::string line;
1957
deadbeefc80741f2015-10-22 13:14:45 -07001958 desc->set_msid_supported(false);
1959
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960 // RFC 4566
1961 // v= (protocol version)
1962 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1963 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1964 std::string(), error);
1965 }
1966 // RFC 4566
1967 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1968 // <unicast-address>
1969 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1970 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1971 std::string(), error);
1972 }
1973 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001974 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001975 kSdpDelimiterSpace, &fields);
1976 const size_t expected_fields = 6;
1977 if (fields.size() != expected_fields) {
1978 return ParseFailedExpectFieldNum(line, expected_fields, error);
1979 }
1980 *session_id = fields[1];
1981 *session_version = fields[2];
1982
1983 // RFC 4566
1984 // s= (session name)
1985 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1986 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1987 std::string(), error);
1988 }
1989
1990 // Optional lines
1991 // Those are the optional lines, so shouldn't return false if not present.
1992 // RFC 4566
1993 // i=* (session information)
1994 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1995
1996 // RFC 4566
1997 // u=* (URI of description)
1998 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1999
2000 // RFC 4566
2001 // e=* (email address)
2002 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
2003
2004 // RFC 4566
2005 // p=* (phone number)
2006 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
2007
2008 // RFC 4566
2009 // c=* (connection information -- not required if included in
2010 // all media)
zhihuang38989e52017-03-21 11:04:53 -07002011 if (GetLineWithType(message, pos, &line, kLineTypeConnection)) {
2012 if (!ParseConnectionData(line, connection_addr, error)) {
2013 return false;
2014 }
2015 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002016
2017 // RFC 4566
2018 // b=* (zero or more bandwidth information lines)
2019 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
2020 // By pass zero or more b lines.
2021 }
2022
2023 // RFC 4566
2024 // One or more time descriptions ("t=" and "r=" lines; see below)
2025 // t= (time the session is active)
2026 // r=* (zero or more repeat times)
2027 // Ensure there's at least one time description
2028 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
2029 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
2030 error);
2031 }
2032
2033 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
2034 // By pass zero or more r lines.
2035 }
2036
2037 // Go through the rest of the time descriptions
2038 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
2039 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
2040 // By pass zero or more r lines.
2041 }
2042 }
2043
2044 // RFC 4566
2045 // z=* (time zone adjustments)
2046 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
2047
2048 // RFC 4566
2049 // k=* (encryption key)
2050 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
2051
2052 // RFC 4566
2053 // a=* (zero or more session attribute lines)
2054 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
2055 if (HasAttribute(line, kAttributeGroup)) {
2056 if (!ParseGroupAttribute(line, desc, error)) {
2057 return false;
2058 }
2059 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2060 if (!GetValue(line, kAttributeIceUfrag,
2061 &(session_td->ice_ufrag), error)) {
2062 return false;
2063 }
2064 } else if (HasAttribute(line, kAttributeIcePwd)) {
2065 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
2066 return false;
2067 }
2068 } else if (HasAttribute(line, kAttributeIceLite)) {
2069 session_td->ice_mode = cricket::ICEMODE_LITE;
2070 } else if (HasAttribute(line, kAttributeIceOption)) {
2071 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
2072 return false;
2073 }
2074 } else if (HasAttribute(line, kAttributeFingerprint)) {
2075 if (session_td->identity_fingerprint.get()) {
2076 return ParseFailed(
2077 line,
2078 "Can't have multiple fingerprint attributes at the same level.",
2079 error);
2080 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002081 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002082 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2083 return false;
2084 }
2085 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002086 } else if (HasAttribute(line, kAttributeSetup)) {
2087 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
2088 return false;
2089 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002090 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
2091 std::string semantics;
2092 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
2093 return false;
2094 }
deadbeefc80741f2015-10-22 13:14:45 -07002095 desc->set_msid_supported(
2096 CaseInsensitiveFind(semantics, kMediaStreamSemantic));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002097 } else if (HasAttribute(line, kAttributeExtmap)) {
isheriff6f8d6862016-05-26 11:24:55 -07002098 RtpExtension extmap;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002099 if (!ParseExtmap(line, &extmap, error)) {
2100 return false;
2101 }
2102 session_extmaps->push_back(extmap);
2103 }
2104 }
2105
2106 return true;
2107}
2108
2109bool ParseGroupAttribute(const std::string& line,
2110 cricket::SessionDescription* desc,
2111 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08002112 RTC_DCHECK(desc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002113
2114 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
2115 // a=group:BUNDLE video voice
2116 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002117 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002118 kSdpDelimiterSpace, &fields);
2119 std::string semantics;
2120 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
2121 return false;
2122 }
2123 cricket::ContentGroup group(semantics);
2124 for (size_t i = 1; i < fields.size(); ++i) {
2125 group.AddContentName(fields[i]);
2126 }
2127 desc->AddGroup(group);
2128 return true;
2129}
2130
2131static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002132 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002133 SdpParseError* error) {
2134 if (!IsLineType(line, kLineTypeAttributes) ||
2135 !HasAttribute(line, kAttributeFingerprint)) {
2136 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
2137 kAttributeFingerprint, error);
2138 }
2139
2140 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002141 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002142 kSdpDelimiterSpace, &fields);
2143 const size_t expected_fields = 2;
2144 if (fields.size() != expected_fields) {
2145 return ParseFailedExpectFieldNum(line, expected_fields, error);
2146 }
2147
2148 // The first field here is "fingerprint:<hash>.
2149 std::string algorithm;
2150 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2151 return false;
2152 }
2153
2154 // Downcase the algorithm. Note that we don't need to downcase the
2155 // fingerprint because hex_decode can handle upper-case.
2156 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2157 ::tolower);
2158
2159 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002160 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002161 algorithm, fields[1]);
2162 if (!*fingerprint) {
2163 return ParseFailed(line,
2164 "Failed to create fingerprint from the digest.",
2165 error);
2166 }
2167
2168 return true;
2169}
2170
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002171static bool ParseDtlsSetup(const std::string& line,
2172 cricket::ConnectionRole* role,
2173 SdpParseError* error) {
2174 // setup-attr = "a=setup:" role
2175 // role = "active" / "passive" / "actpass" / "holdconn"
2176 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002177 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002178 const size_t expected_fields = 2;
2179 if (fields.size() != expected_fields) {
2180 return ParseFailedExpectFieldNum(line, expected_fields, error);
2181 }
2182 std::string role_str = fields[1];
2183 if (!cricket::StringToConnectionRole(role_str, role)) {
2184 return ParseFailed(line, "Invalid attribute value.", error);
2185 }
2186 return true;
2187}
2188
deadbeef9d3584c2016-02-16 17:54:10 -08002189static bool ParseMsidAttribute(const std::string& line,
2190 std::string* stream_id,
2191 std::string* track_id,
2192 SdpParseError* error) {
2193 // draft-ietf-mmusic-msid-11
2194 // a=msid:<stream id> <track id>
2195 // msid-value = msid-id [ SP msid-appdata ]
2196 // msid-id = 1*64token-char ; see RFC 4566
2197 // msid-appdata = 1*64token-char ; see RFC 4566
2198 std::string field1;
2199 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2200 &field1, track_id)) {
2201 const size_t expected_fields = 2;
2202 return ParseFailedExpectFieldNum(line, expected_fields, error);
2203 }
2204
deadbeefa4549d62017-02-10 17:26:22 -08002205 if (track_id->empty()) {
2206 return ParseFailed(line, "Missing track ID in msid attribute.", error);
2207 }
2208
deadbeef9d3584c2016-02-16 17:54:10 -08002209 // msid:<msid-id>
2210 if (!GetValue(field1, kAttributeMsid, stream_id, error)) {
2211 return false;
2212 }
deadbeefa4549d62017-02-10 17:26:22 -08002213 if (stream_id->empty()) {
2214 return ParseFailed(line, "Missing stream ID in msid attribute.", error);
2215 }
deadbeef9d3584c2016-02-16 17:54:10 -08002216 return true;
2217}
2218
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219// RFC 3551
2220// PT encoding media type clock rate channels
2221// name (Hz)
2222// 0 PCMU A 8,000 1
2223// 1 reserved A
2224// 2 reserved A
2225// 3 GSM A 8,000 1
2226// 4 G723 A 8,000 1
2227// 5 DVI4 A 8,000 1
2228// 6 DVI4 A 16,000 1
2229// 7 LPC A 8,000 1
2230// 8 PCMA A 8,000 1
2231// 9 G722 A 8,000 1
2232// 10 L16 A 44,100 2
2233// 11 L16 A 44,100 1
2234// 12 QCELP A 8,000 1
2235// 13 CN A 8,000 1
2236// 14 MPA A 90,000 (see text)
2237// 15 G728 A 8,000 1
2238// 16 DVI4 A 11,025 1
2239// 17 DVI4 A 22,050 1
2240// 18 G729 A 8,000 1
2241struct StaticPayloadAudioCodec {
2242 const char* name;
2243 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002244 size_t channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002245};
2246static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2247 { "PCMU", 8000, 1 },
2248 { "reserved", 0, 0 },
2249 { "reserved", 0, 0 },
2250 { "GSM", 8000, 1 },
2251 { "G723", 8000, 1 },
2252 { "DVI4", 8000, 1 },
2253 { "DVI4", 16000, 1 },
2254 { "LPC", 8000, 1 },
2255 { "PCMA", 8000, 1 },
2256 { "G722", 8000, 1 },
2257 { "L16", 44100, 2 },
2258 { "L16", 44100, 1 },
2259 { "QCELP", 8000, 1 },
2260 { "CN", 8000, 1 },
2261 { "MPA", 90000, 1 },
2262 { "G728", 8000, 1 },
2263 { "DVI4", 11025, 1 },
2264 { "DVI4", 22050, 1 },
2265 { "G729", 8000, 1 },
2266};
2267
2268void MaybeCreateStaticPayloadAudioCodecs(
2269 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2270 if (!media_desc) {
2271 return;
2272 }
deadbeef67cf2c12016-04-13 10:07:16 -07002273 RTC_DCHECK(media_desc->codecs().empty());
solenberg9fa49752016-10-08 13:02:44 -07002274 for (int payload_type : fmts) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002275 if (!media_desc->HasCodec(payload_type) &&
2276 payload_type >= 0 &&
kjellander3e33bfe2016-06-20 07:04:09 -07002277 static_cast<uint32_t>(payload_type) <
2278 arraysize(kStaticPayloadAudioCodecs)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002279 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2280 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
Peter Kasting69558702016-01-12 16:26:35 -08002281 size_t channels = kStaticPayloadAudioCodecs[payload_type].channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002282 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
deadbeef67cf2c12016-04-13 10:07:16 -07002283 clock_rate, 0, channels));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002284 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002285 }
2286}
2287
2288template <class C>
2289static C* ParseContentDescription(const std::string& message,
2290 const MediaType media_type,
2291 int mline_index,
2292 const std::string& protocol,
deadbeef67cf2c12016-04-13 10:07:16 -07002293 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002294 size_t* pos,
2295 std::string* content_name,
deadbeef25ed4352016-12-12 18:37:36 -08002296 bool* bundle_only,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002297 TransportDescription* transport,
2298 std::vector<JsepIceCandidate*>* candidates,
2299 webrtc::SdpParseError* error) {
2300 C* media_desc = new C();
2301 switch (media_type) {
2302 case cricket::MEDIA_TYPE_AUDIO:
2303 *content_name = cricket::CN_AUDIO;
2304 break;
2305 case cricket::MEDIA_TYPE_VIDEO:
2306 *content_name = cricket::CN_VIDEO;
2307 break;
2308 case cricket::MEDIA_TYPE_DATA:
2309 *content_name = cricket::CN_DATA;
2310 break;
2311 default:
nissec80e7412017-01-11 05:56:46 -08002312 RTC_NOTREACHED();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002313 break;
2314 }
deadbeef67cf2c12016-04-13 10:07:16 -07002315 if (!ParseContent(message, media_type, mline_index, protocol, payload_types,
deadbeef25ed4352016-12-12 18:37:36 -08002316 pos, content_name, bundle_only, media_desc, transport,
2317 candidates, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002318 delete media_desc;
zhihuang38989e52017-03-21 11:04:53 -07002319 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002320 }
2321 // Sort the codecs according to the m-line fmt list.
deadbeef67cf2c12016-04-13 10:07:16 -07002322 std::unordered_map<int, int> payload_type_preferences;
2323 // "size + 1" so that the lowest preference payload type has a preference of
2324 // 1, which is greater than the default (0) for payload types not in the fmt
2325 // list.
2326 int preference = static_cast<int>(payload_types.size() + 1);
2327 for (int pt : payload_types) {
2328 payload_type_preferences[pt] = preference--;
2329 }
2330 std::vector<typename C::CodecType> codecs = media_desc->codecs();
2331 std::sort(codecs.begin(), codecs.end(), [&payload_type_preferences](
2332 const typename C::CodecType& a,
2333 const typename C::CodecType& b) {
2334 return payload_type_preferences[a.id] > payload_type_preferences[b.id];
2335 });
2336 media_desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002337 return media_desc;
2338}
2339
2340bool ParseMediaDescription(const std::string& message,
2341 const TransportDescription& session_td,
2342 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002343 size_t* pos,
zhihuang38989e52017-03-21 11:04:53 -07002344 const rtc::SocketAddress& session_connection_addr,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345 cricket::SessionDescription* desc,
2346 std::vector<JsepIceCandidate*>* candidates,
2347 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08002348 RTC_DCHECK(desc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002349 std::string line;
2350 int mline_index = -1;
2351
2352 // Zero or more media descriptions
2353 // RFC 4566
2354 // m=<media> <port> <proto> <fmt>
2355 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2356 ++mline_index;
2357
2358 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002359 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002360 kSdpDelimiterSpace, &fields);
zstein4b2e0822017-02-17 19:48:38 -08002361
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002362 const size_t expected_min_fields = 4;
2363 if (fields.size() < expected_min_fields) {
2364 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2365 }
deadbeef25ed4352016-12-12 18:37:36 -08002366 bool port_rejected = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002367 // RFC 3264
2368 // To reject an offered stream, the port number in the corresponding stream
2369 // in the answer MUST be set to zero.
2370 if (fields[1] == kMediaPortRejected) {
deadbeef25ed4352016-12-12 18:37:36 -08002371 port_rejected = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002372 }
2373
zhihuang38989e52017-03-21 11:04:53 -07002374 int port = 0;
2375 if (!rtc::FromString<int>(fields[1], &port) || !IsValidPort(port)) {
2376 return ParseFailed(line, "The port number is invalid", error);
2377 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002379
2380 // <fmt>
deadbeef67cf2c12016-04-13 10:07:16 -07002381 std::vector<int> payload_types;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002382 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002383 for (size_t j = 3 ; j < fields.size(); ++j) {
2384 // TODO(wu): Remove when below bug is fixed.
2385 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002386 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002387 continue;
2388 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002389
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002390 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002391 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002392 return false;
2393 }
deadbeef67cf2c12016-04-13 10:07:16 -07002394 payload_types.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002395 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002396 }
2397
2398 // Make a temporary TransportDescription based on |session_td|.
2399 // Some of this gets overwritten by ParseContent.
deadbeef46eed762016-01-28 13:24:37 -08002400 TransportDescription transport(
2401 session_td.transport_options, session_td.ice_ufrag, session_td.ice_pwd,
2402 session_td.ice_mode, session_td.connection_role,
2403 session_td.identity_fingerprint.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002404
kwibergd1fe2812016-04-27 06:47:29 -07002405 std::unique_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002406 std::string content_name;
deadbeef25ed4352016-12-12 18:37:36 -08002407 bool bundle_only = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002408 if (HasAttribute(line, kMediaTypeVideo)) {
2409 content.reset(ParseContentDescription<VideoContentDescription>(
deadbeef67cf2c12016-04-13 10:07:16 -07002410 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
deadbeef25ed4352016-12-12 18:37:36 -08002411 payload_types, pos, &content_name, &bundle_only, &transport,
2412 candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002413 } else if (HasAttribute(line, kMediaTypeAudio)) {
2414 content.reset(ParseContentDescription<AudioContentDescription>(
deadbeef67cf2c12016-04-13 10:07:16 -07002415 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
deadbeef25ed4352016-12-12 18:37:36 -08002416 payload_types, pos, &content_name, &bundle_only, &transport,
2417 candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002418 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002419 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002420 ParseContentDescription<DataContentDescription>(
deadbeef67cf2c12016-04-13 10:07:16 -07002421 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
deadbeef25ed4352016-12-12 18:37:36 -08002422 payload_types, pos, &content_name, &bundle_only, &transport,
2423 candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002424 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002425
zstein4b2e0822017-02-17 19:48:38 -08002426 if (data_desc && IsDtlsSctp(protocol)) {
2427 int p;
2428 if (rtc::FromString(fields[3], &p)) {
2429 if (!AddSctpDataCodec(data_desc, p)) {
2430 return false;
2431 }
2432 } else if (fields[3] == kDefaultSctpmapProtocol) {
2433 data_desc->set_use_sctpmap(false);
2434 }
wu@webrtc.org78187522013-10-07 23:32:02 +00002435 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002436 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002437 RTC_LOG(LS_WARNING) << "Unsupported media type: " << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002438 continue;
2439 }
2440 if (!content.get()) {
2441 // ParseContentDescription returns NULL if failed.
2442 return false;
2443 }
2444
deadbeef25ed4352016-12-12 18:37:36 -08002445 bool content_rejected = false;
deadbeef12771a12017-01-03 13:53:47 -08002446 // A port of 0 is not interpreted as a rejected m= section when it's
2447 // used along with a=bundle-only.
deadbeef25ed4352016-12-12 18:37:36 -08002448 if (bundle_only) {
deadbeef25ed4352016-12-12 18:37:36 -08002449 if (!port_rejected) {
deadbeef12771a12017-01-03 13:53:47 -08002450 // Usage of bundle-only with a nonzero port is unspecified. So just
2451 // ignore bundle-only if we see this.
2452 bundle_only = false;
Mirko Bonadei675513b2017-11-09 11:09:25 +01002453 RTC_LOG(LS_WARNING)
deadbeef12771a12017-01-03 13:53:47 -08002454 << "a=bundle-only attribute observed with a nonzero "
2455 << "port; this usage is unspecified so the attribute is being "
2456 << "ignored.";
deadbeef25ed4352016-12-12 18:37:36 -08002457 }
2458 } else {
2459 // If not using bundle-only, interpret port 0 in the normal way; the m=
2460 // section is being rejected.
2461 content_rejected = port_rejected;
2462 }
2463
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002464 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002465 // Set the extmap.
2466 if (!session_extmaps.empty() &&
2467 !content->rtp_header_extensions().empty()) {
2468 return ParseFailed("",
2469 "The a=extmap MUST be either all session level or "
2470 "all media level.",
2471 error);
2472 }
2473 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2474 content->AddRtpHeaderExtension(session_extmaps[i]);
2475 }
2476 }
2477 content->set_protocol(protocol);
zhihuang38989e52017-03-21 11:04:53 -07002478
2479 // Use the session level connection address if the media level addresses are
2480 // not specified.
2481 rtc::SocketAddress address;
2482 address = content->connection_address().IsNil()
2483 ? session_connection_addr
2484 : content->connection_address();
2485 address.SetPort(port);
2486 content->set_connection_address(address);
2487
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002488 desc->AddContent(content_name,
Steve Anton5adfafd2017-12-20 16:34:00 -08002489 IsDtlsSctp(protocol) ? MediaProtocolType::kSctp
2490 : MediaProtocolType::kRtp,
deadbeef25ed4352016-12-12 18:37:36 -08002491 content_rejected, bundle_only, content.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002492 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2493 TransportInfo transport_info(content_name, transport);
2494
2495 if (!desc->AddTransportInfo(transport_info)) {
2496 std::ostringstream description;
2497 description << "Failed to AddTransportInfo with content name: "
2498 << content_name;
2499 return ParseFailed("", description.str(), error);
2500 }
2501 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002502
2503 size_t end_of_message = message.size();
2504 if (mline_index == -1 && *pos != end_of_message) {
2505 ParseFailed(message, *pos, "Expects m line.", error);
2506 return false;
2507 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002508 return true;
2509}
2510
2511bool VerifyCodec(const cricket::Codec& codec) {
2512 // Codec has not been populated correctly unless the name has been set. This
2513 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2514 // have a corresponding "rtpmap" line.
htab39db842016-12-08 01:50:48 -08002515 return !codec.name.empty();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002516}
2517
2518bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2519 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2520 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2521 iter != codecs.end(); ++iter) {
2522 if (!VerifyCodec(*iter)) {
2523 return false;
2524 }
2525 }
2526 return true;
2527}
2528
2529bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2530 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2531 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2532 iter != codecs.end(); ++iter) {
2533 if (!VerifyCodec(*iter)) {
2534 return false;
2535 }
2536 }
2537 return true;
2538}
2539
2540void AddParameters(const cricket::CodecParameterMap& parameters,
2541 cricket::Codec* codec) {
2542 for (cricket::CodecParameterMap::const_iterator iter =
2543 parameters.begin(); iter != parameters.end(); ++iter) {
2544 codec->SetParam(iter->first, iter->second);
2545 }
2546}
2547
2548void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2549 cricket::Codec* codec) {
2550 codec->AddFeedbackParam(feedback_param);
2551}
2552
2553void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2554 cricket::Codec* codec) {
2555 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2556 feedback_params.params().begin();
2557 iter != feedback_params.params().end(); ++iter) {
2558 codec->AddFeedbackParam(*iter);
2559 }
2560}
2561
2562// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002563// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002564// with that payload type.
2565template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002566T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
magjedb05fa242016-11-11 04:00:16 -08002567 const T* codec = FindCodecById(codecs, payload_type);
2568 if (codec)
2569 return *codec;
2570 // Return empty codec with |payload_type|.
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002571 T ret_val;
magjedb05fa242016-11-11 04:00:16 -08002572 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002573 return ret_val;
2574}
2575
2576// Updates or creates a new codec entry in the audio description.
2577template <class T, class U>
2578void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2579 T* desc = static_cast<T*>(content_desc);
2580 std::vector<U> codecs = desc->codecs();
2581 bool found = false;
2582
2583 typename std::vector<U>::iterator iter;
2584 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2585 if (iter->id == codec.id) {
2586 *iter = codec;
2587 found = true;
2588 break;
2589 }
2590 }
2591 if (!found) {
2592 desc->AddCodec(codec);
2593 return;
2594 }
2595 desc->set_codecs(codecs);
2596}
2597
2598// Adds or updates existing codec corresponding to |payload_type| according
2599// to |parameters|.
2600template <class T, class U>
2601void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2602 const cricket::CodecParameterMap& parameters) {
2603 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002604 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2605 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002606 AddParameters(parameters, &new_codec);
2607 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2608}
2609
2610// Adds or updates existing codec corresponding to |payload_type| according
2611// to |feedback_param|.
2612template <class T, class U>
2613void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2614 const cricket::FeedbackParam& feedback_param) {
2615 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002616 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2617 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002618 AddFeedbackParameter(feedback_param, &new_codec);
2619 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2620}
2621
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002622template <class T>
2623bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2624 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002625 if (iter->id == kWildcardPayloadType) {
2626 *wildcard_codec = *iter;
2627 codecs->erase(iter);
2628 return true;
2629 }
2630 }
2631 return false;
2632}
2633
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002634template<class T>
2635void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2636 auto codecs = desc->codecs();
2637 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002638 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2639 return;
2640 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002641 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002642 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2643 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002644 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002645}
2646
2647void AddAudioAttribute(const std::string& name, const std::string& value,
2648 AudioContentDescription* audio_desc) {
2649 if (value.empty()) {
2650 return;
2651 }
2652 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2653 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2654 iter != codecs.end(); ++iter) {
2655 iter->params[name] = value;
2656 }
2657 audio_desc->set_codecs(codecs);
2658}
2659
2660bool ParseContent(const std::string& message,
2661 const MediaType media_type,
2662 int mline_index,
2663 const std::string& protocol,
deadbeef67cf2c12016-04-13 10:07:16 -07002664 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002665 size_t* pos,
2666 std::string* content_name,
deadbeef25ed4352016-12-12 18:37:36 -08002667 bool* bundle_only,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002668 MediaContentDescription* media_desc,
2669 TransportDescription* transport,
2670 std::vector<JsepIceCandidate*>* candidates,
2671 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08002672 RTC_DCHECK(media_desc != NULL);
2673 RTC_DCHECK(content_name != NULL);
2674 RTC_DCHECK(transport != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002675
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002676 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08002677 MaybeCreateStaticPayloadAudioCodecs(payload_types, media_desc->as_audio());
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002678 }
2679
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002680 // The media level "ice-ufrag" and "ice-pwd".
2681 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2682 Candidates candidates_orig;
2683 std::string line;
2684 std::string mline_id;
2685 // Tracks created out of the ssrc attributes.
2686 StreamParamsVec tracks;
2687 SsrcInfoVec ssrc_infos;
2688 SsrcGroupVec ssrc_groups;
2689 std::string maxptime_as_string;
2690 std::string ptime_as_string;
deadbeef9d3584c2016-02-16 17:54:10 -08002691 std::string stream_id;
2692 std::string track_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002693
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002694 // Loop until the next m line
2695 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2696 if (!GetLine(message, pos, &line)) {
2697 if (*pos >= message.size()) {
2698 break; // Done parsing
2699 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002700 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002701 }
2702 }
2703
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002704 // RFC 4566
2705 // b=* (zero or more bandwidth information lines)
2706 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2707 std::string bandwidth;
2708 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2709 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2710 return false;
2711 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002712 int b = 0;
2713 if (!GetValueFromString(line, bandwidth, &b, error)) {
2714 return false;
2715 }
deadbeef3e8016e2017-08-03 17:49:30 -07002716 // TODO(deadbeef): Historically, applications may be setting a value
2717 // of -1 to mean "unset any previously set bandwidth limit", even
2718 // though ommitting the "b=AS" entirely will do just that. Once we've
2719 // transitioned applications to doing the right thing, it would be
2720 // better to treat this as a hard error instead of just ignoring it.
2721 if (b == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002722 RTC_LOG(LS_WARNING)
2723 << "Ignoring \"b=AS:-1\"; will be treated as \"no "
2724 "bandwidth limit\".";
deadbeef3e8016e2017-08-03 17:49:30 -07002725 continue;
2726 }
deadbeefbc88c6b2017-08-02 11:26:34 -07002727 if (b < 0) {
2728 return ParseFailed(line, "b=AS value can't be negative.", error);
2729 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002730 // We should never use more than the default bandwidth for RTP-based
2731 // data channels. Don't allow SDP to set the bandwidth, because
2732 // that would give JS the opportunity to "break the Internet".
2733 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2734 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2735 b > cricket::kDataMaxBandwidth / 1000) {
2736 std::ostringstream description;
2737 description << "RTP-based data channels may not send more than "
2738 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2739 return ParseFailed(line, description.str(), error);
2740 }
deadbeefb2362572016-12-13 16:37:06 -08002741 // Prevent integer overflow.
2742 b = std::min(b, INT_MAX / 1000);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002743 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002744 }
2745 }
2746 continue;
2747 }
2748
zhihuang38989e52017-03-21 11:04:53 -07002749 // Parse the media level connection data.
2750 if (IsLineType(line, kLineTypeConnection)) {
2751 rtc::SocketAddress addr;
2752 if (!ParseConnectionData(line, &addr, error)) {
2753 return false;
2754 }
2755 media_desc->set_connection_address(addr);
2756 continue;
2757 }
2758
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002759 if (!IsLineType(line, kLineTypeAttributes)) {
Steve Anton36b29d12017-10-30 09:57:42 -07002760 // TODO(deadbeef): Handle other lines if needed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01002761 RTC_LOG(LS_INFO) << "Ignored line: " << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002762 continue;
2763 }
2764
2765 // Handle attributes common to SCTP and RTP.
2766 if (HasAttribute(line, kAttributeMid)) {
2767 // RFC 3388
2768 // mid-attribute = "a=mid:" identification-tag
2769 // identification-tag = token
2770 // Use the mid identification-tag as the content name.
2771 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2772 return false;
2773 }
2774 *content_name = mline_id;
deadbeef25ed4352016-12-12 18:37:36 -08002775 } else if (HasAttribute(line, kAttributeBundleOnly)) {
2776 *bundle_only = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002777 } else if (HasAttribute(line, kAttributeCandidate)) {
2778 Candidate candidate;
2779 if (!ParseCandidate(line, &candidate, error, false)) {
2780 return false;
2781 }
deadbeef7bcdb692017-01-20 12:43:58 -08002782 // ParseCandidate will parse non-standard ufrag and password attributes,
2783 // since it's used for candidate trickling, but we only want to process
2784 // the "a=ice-ufrag"/"a=ice-pwd" values in a session description, so
2785 // strip them off at this point.
2786 candidate.set_username(std::string());
2787 candidate.set_password(std::string());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002788 candidates_orig.push_back(candidate);
2789 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2790 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2791 return false;
2792 }
2793 } else if (HasAttribute(line, kAttributeIcePwd)) {
2794 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2795 return false;
2796 }
2797 } else if (HasAttribute(line, kAttributeIceOption)) {
2798 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2799 return false;
2800 }
2801 } else if (HasAttribute(line, kAttributeFmtp)) {
2802 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2803 return false;
2804 }
2805 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002806 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002807
2808 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2809 return false;
2810 }
2811 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002812 } else if (HasAttribute(line, kAttributeSetup)) {
2813 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2814 return false;
2815 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002816 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
deadbeef7e146cb2016-09-28 10:04:34 -07002817 if (media_type != cricket::MEDIA_TYPE_DATA) {
2818 return ParseFailed(
2819 line, "sctp-port attribute found in non-data media description.",
2820 error);
2821 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002822 int sctp_port;
2823 if (!ParseSctpPort(line, &sctp_port, error)) {
2824 return false;
2825 }
Steve Antonb1c1de12017-12-21 15:14:30 -08002826 if (!AddSctpDataCodec(media_desc->as_data(), sctp_port)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002827 return false;
2828 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002829 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002830 //
2831 // RTP specific attrubtes
2832 //
2833 if (HasAttribute(line, kAttributeRtcpMux)) {
2834 media_desc->set_rtcp_mux(true);
deadbeef13871492015-12-09 12:37:51 -08002835 } else if (HasAttribute(line, kAttributeRtcpReducedSize)) {
2836 media_desc->set_rtcp_reduced_size(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002837 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2838 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2839 return false;
2840 }
2841 } else if (HasAttribute(line, kAttributeSsrc)) {
2842 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2843 return false;
2844 }
2845 } else if (HasAttribute(line, kAttributeCrypto)) {
2846 if (!ParseCryptoAttribute(line, media_desc, error)) {
2847 return false;
2848 }
2849 } else if (HasAttribute(line, kAttributeRtpmap)) {
deadbeef67cf2c12016-04-13 10:07:16 -07002850 if (!ParseRtpmapAttribute(line, media_type, payload_types, media_desc,
2851 error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002852 return false;
2853 }
2854 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2855 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2856 return false;
2857 }
2858 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2859 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2860 return false;
2861 }
2862 } else if (HasAttribute(line, kCodecParamPTime)) {
2863 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2864 return false;
2865 }
2866 } else if (HasAttribute(line, kAttributeSendOnly)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002867 media_desc->set_direction(RtpTransceiverDirection::kSendOnly);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002868 } else if (HasAttribute(line, kAttributeRecvOnly)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002869 media_desc->set_direction(RtpTransceiverDirection::kRecvOnly);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002870 } else if (HasAttribute(line, kAttributeInactive)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002871 media_desc->set_direction(RtpTransceiverDirection::kInactive);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002872 } else if (HasAttribute(line, kAttributeSendRecv)) {
Steve Anton4e70a722017-11-28 14:57:10 -08002873 media_desc->set_direction(RtpTransceiverDirection::kSendRecv);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002874 } else if (HasAttribute(line, kAttributeExtmap)) {
isheriff6f8d6862016-05-26 11:24:55 -07002875 RtpExtension extmap;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002876 if (!ParseExtmap(line, &extmap, error)) {
2877 return false;
2878 }
2879 media_desc->AddRtpHeaderExtension(extmap);
2880 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2881 // Experimental attribute. Conference mode activates more aggressive
2882 // AEC and NS settings.
Steve Anton36b29d12017-10-30 09:57:42 -07002883 // TODO(deadbeef): expose API to set these directly.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002884 std::string flag_value;
2885 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2886 return false;
2887 }
2888 if (flag_value.compare(kValueConference) == 0)
2889 media_desc->set_conference_mode(true);
deadbeef9d3584c2016-02-16 17:54:10 -08002890 } else if (HasAttribute(line, kAttributeMsid)) {
2891 if (!ParseMsidAttribute(line, &stream_id, &track_id, error)) {
2892 return false;
2893 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002894 }
2895 } else {
2896 // Only parse lines that we are interested of.
Mirko Bonadei675513b2017-11-09 11:09:25 +01002897 RTC_LOG(LS_INFO) << "Ignored line: " << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002898 continue;
2899 }
2900 }
2901
2902 // Create tracks from the |ssrc_infos|.
Taylor Brandstetter5de6b752016-03-09 17:02:30 -08002903 // If the stream_id/track_id for all SSRCS are identical, one StreamParams
2904 // will be created in CreateTracksFromSsrcInfos, containing all the SSRCs from
2905 // the m= section.
2906 CreateTracksFromSsrcInfos(ssrc_infos, stream_id, track_id, &tracks);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002907
2908 // Add the ssrc group to the track.
2909 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2910 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2911 if (ssrc_group->ssrcs.empty()) {
2912 continue;
2913 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002914 uint32_t ssrc = ssrc_group->ssrcs.front();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002915 for (StreamParamsVec::iterator track = tracks.begin();
2916 track != tracks.end(); ++track) {
2917 if (track->has_ssrc(ssrc)) {
2918 track->ssrc_groups.push_back(*ssrc_group);
2919 }
2920 }
2921 }
2922
2923 // Add the new tracks to the |media_desc|.
deadbeef9d3584c2016-02-16 17:54:10 -08002924 for (StreamParams& track : tracks) {
2925 media_desc->AddStream(track);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002926 }
2927
2928 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08002929 AudioContentDescription* audio_desc = media_desc->as_audio();
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002930 UpdateFromWildcardCodecs(audio_desc);
2931
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002932 // Verify audio codec ensures that no audio codec has been populated with
2933 // only fmtp.
2934 if (!VerifyAudioCodecs(audio_desc)) {
2935 return ParseFailed("Failed to parse audio codecs correctly.", error);
2936 }
2937 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2938 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2939 }
2940
2941 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08002942 VideoContentDescription* video_desc = media_desc->as_video();
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002943 UpdateFromWildcardCodecs(video_desc);
2944 // Verify video codec ensures that no video codec has been populated with
2945 // only rtcp-fb.
2946 if (!VerifyVideoCodecs(video_desc)) {
2947 return ParseFailed("Failed to parse video codecs correctly.", error);
2948 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002949 }
2950
2951 // RFC 5245
2952 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2953 for (Candidates::iterator it = candidates_orig.begin();
2954 it != candidates_orig.end(); ++it) {
nisseede5da42017-01-12 05:15:36 -08002955 RTC_DCHECK((*it).username().empty() ||
2956 (*it).username() == transport->ice_ufrag);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002957 (*it).set_username(transport->ice_ufrag);
nisseede5da42017-01-12 05:15:36 -08002958 RTC_DCHECK((*it).password().empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002959 (*it).set_password(transport->ice_pwd);
2960 candidates->push_back(
2961 new JsepIceCandidate(mline_id, mline_index, *it));
2962 }
2963 return true;
2964}
2965
2966bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2967 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08002968 RTC_DCHECK(ssrc_infos != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002969 // RFC 5576
2970 // a=ssrc:<ssrc-id> <attribute>
2971 // a=ssrc:<ssrc-id> <attribute>:<value>
2972 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07002973 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2974 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002975 const size_t expected_fields = 2;
2976 return ParseFailedExpectFieldNum(line, expected_fields, error);
2977 }
2978
2979 // ssrc:<ssrc-id>
2980 std::string ssrc_id_s;
2981 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2982 return false;
2983 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002984 uint32_t ssrc_id = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002985 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2986 return false;
2987 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002988
2989 std::string attribute;
2990 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07002991 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002992 std::ostringstream description;
2993 description << "Failed to get the ssrc attribute value from " << field2
2994 << ". Expected format <attribute>:<value>.";
2995 return ParseFailed(line, description.str(), error);
2996 }
2997
2998 // Check if there's already an item for this |ssrc_id|. Create a new one if
2999 // there isn't.
3000 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
3001 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
3002 if (ssrc_info->ssrc_id == ssrc_id) {
3003 break;
3004 }
3005 }
3006 if (ssrc_info == ssrc_infos->end()) {
3007 SsrcInfo info;
3008 info.ssrc_id = ssrc_id;
3009 ssrc_infos->push_back(info);
3010 ssrc_info = ssrc_infos->end() - 1;
3011 }
3012
3013 // Store the info to the |ssrc_info|.
3014 if (attribute == kSsrcAttributeCname) {
3015 // RFC 5576
3016 // cname:<value>
3017 ssrc_info->cname = value;
3018 } else if (attribute == kSsrcAttributeMsid) {
3019 // draft-alvestrand-mmusic-msid-00
3020 // "msid:" identifier [ " " appdata ]
3021 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003022 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003023 if (fields.size() < 1 || fields.size() > 2) {
3024 return ParseFailed(line,
3025 "Expected format \"msid:<identifier>[ <appdata>]\".",
3026 error);
3027 }
deadbeef9d3584c2016-02-16 17:54:10 -08003028 ssrc_info->stream_id = fields[0];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003029 if (fields.size() == 2) {
deadbeef9d3584c2016-02-16 17:54:10 -08003030 ssrc_info->track_id = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003031 }
3032 } else if (attribute == kSsrcAttributeMslabel) {
3033 // draft-alvestrand-rtcweb-mid-01
3034 // mslabel:<value>
3035 ssrc_info->mslabel = value;
3036 } else if (attribute == kSSrcAttributeLabel) {
3037 // The label isn't defined.
3038 // label:<value>
3039 ssrc_info->label = value;
3040 }
3041 return true;
3042}
3043
3044bool ParseSsrcGroupAttribute(const std::string& line,
3045 SsrcGroupVec* ssrc_groups,
3046 SdpParseError* error) {
nisseede5da42017-01-12 05:15:36 -08003047 RTC_DCHECK(ssrc_groups != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003048 // RFC 5576
3049 // a=ssrc-group:<semantics> <ssrc-id> ...
3050 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003051 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003052 kSdpDelimiterSpace, &fields);
3053 const size_t expected_min_fields = 2;
3054 if (fields.size() < expected_min_fields) {
3055 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3056 }
3057 std::string semantics;
3058 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
3059 return false;
3060 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02003061 std::vector<uint32_t> ssrcs;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003062 for (size_t i = 1; i < fields.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02003063 uint32_t ssrc = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003064 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
3065 return false;
3066 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003067 ssrcs.push_back(ssrc);
3068 }
3069 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
3070 return true;
3071}
3072
3073bool ParseCryptoAttribute(const std::string& line,
3074 MediaContentDescription* media_desc,
3075 SdpParseError* error) {
3076 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003077 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003078 kSdpDelimiterSpace, &fields);
3079 // RFC 4568
3080 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
3081 const size_t expected_min_fields = 3;
3082 if (fields.size() < expected_min_fields) {
3083 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3084 }
3085 std::string tag_value;
3086 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
3087 return false;
3088 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003089 int tag = 0;
3090 if (!GetValueFromString(line, tag_value, &tag, error)) {
3091 return false;
3092 }
jbauch083b73f2015-07-16 02:46:32 -07003093 const std::string& crypto_suite = fields[1];
3094 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003095 std::string session_params;
3096 if (fields.size() > 3) {
3097 session_params = fields[3];
3098 }
3099 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
3100 session_params));
3101 return true;
3102}
3103
3104// Updates or creates a new codec entry in the audio description with according
deadbeef67cf2c12016-04-13 10:07:16 -07003105// to |name|, |clockrate|, |bitrate|, and |channels|.
3106void UpdateCodec(int payload_type,
3107 const std::string& name,
3108 int clockrate,
3109 int bitrate,
3110 size_t channels,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003111 AudioContentDescription* audio_desc) {
3112 // Codec may already be populated with (only) optional parameters
3113 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00003114 cricket::AudioCodec codec =
3115 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003116 codec.name = name;
3117 codec.clockrate = clockrate;
3118 codec.bitrate = bitrate;
3119 codec.channels = channels;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003120 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
3121 codec);
3122}
3123
3124// Updates or creates a new codec entry in the video description according to
deadbeef67cf2c12016-04-13 10:07:16 -07003125// |name|, |width|, |height|, and |framerate|.
3126void UpdateCodec(int payload_type,
3127 const std::string& name,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003128 VideoContentDescription* video_desc) {
3129 // Codec may already be populated with (only) optional parameters
3130 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00003131 cricket::VideoCodec codec =
3132 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003133 codec.name = name;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003134 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
3135 codec);
3136}
3137
3138bool ParseRtpmapAttribute(const std::string& line,
3139 const MediaType media_type,
deadbeef67cf2c12016-04-13 10:07:16 -07003140 const std::vector<int>& payload_types,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003141 MediaContentDescription* media_desc,
3142 SdpParseError* error) {
3143 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003144 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003145 kSdpDelimiterSpace, &fields);
3146 // RFC 4566
3147 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
3148 const size_t expected_min_fields = 2;
3149 if (fields.size() < expected_min_fields) {
3150 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3151 }
3152 std::string payload_type_value;
3153 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
3154 return false;
3155 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003156 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003157 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
3158 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003159 return false;
3160 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003161
deadbeef67cf2c12016-04-13 10:07:16 -07003162 if (std::find(payload_types.begin(), payload_types.end(), payload_type) ==
3163 payload_types.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003164 RTC_LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
3165 << "<fmt> of the m-line: " << line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003166 return true;
3167 }
jbauch083b73f2015-07-16 02:46:32 -07003168 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003169 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003170 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003171 // <encoding name>/<clock rate>[/<encodingparameters>]
3172 // 2 mandatory fields
3173 if (codec_params.size() < 2 || codec_params.size() > 3) {
3174 return ParseFailed(line,
3175 "Expected format \"<encoding name>/<clock rate>"
3176 "[/<encodingparameters>]\".",
3177 error);
3178 }
jbauch083b73f2015-07-16 02:46:32 -07003179 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003180 int clock_rate = 0;
3181 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
3182 return false;
3183 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003184 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Antonb1c1de12017-12-21 15:14:30 -08003185 VideoContentDescription* video_desc = media_desc->as_video();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003186 UpdateCodec(payload_type, encoding_name,
deadbeef67cf2c12016-04-13 10:07:16 -07003187 video_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003188 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3189 // RFC 4566
3190 // For audio streams, <encoding parameters> indicates the number
3191 // of audio channels. This parameter is OPTIONAL and may be
3192 // omitted if the number of channels is one, provided that no
3193 // additional parameters are needed.
Peter Kasting69558702016-01-12 16:26:35 -08003194 size_t channels = 1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003195 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003196 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
3197 return false;
3198 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003199 }
Steve Antonb1c1de12017-12-21 15:14:30 -08003200 AudioContentDescription* audio_desc = media_desc->as_audio();
ossue1405ad2017-01-23 08:55:48 -08003201 UpdateCodec(payload_type, encoding_name, clock_rate, 0, channels,
deadbeef67cf2c12016-04-13 10:07:16 -07003202 audio_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003203 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonb1c1de12017-12-21 15:14:30 -08003204 DataContentDescription* data_desc = media_desc->as_data();
deadbeef67cf2c12016-04-13 10:07:16 -07003205 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003206 }
3207 return true;
3208}
3209
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003210bool ParseFmtpParam(const std::string& line, std::string* parameter,
3211 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003212 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003213 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
3214 return false;
3215 }
3216 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217 return true;
3218}
3219
3220bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
3221 MediaContentDescription* media_desc,
3222 SdpParseError* error) {
3223 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3224 media_type != cricket::MEDIA_TYPE_VIDEO) {
3225 return true;
3226 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003227
3228 std::string line_payload;
3229 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003230
3231 // RFC 5576
3232 // a=fmtp:<format> <format specific parameters>
3233 // At least two fields, whereas the second one is any of the optional
3234 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07003235 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
3236 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003237 ParseFailedExpectMinFieldNum(line, 2, error);
3238 return false;
3239 }
3240
Donald Curtis0e07f922015-05-15 09:21:23 -07003241 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003242 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07003243 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003244 return false;
3245 }
3246
Donald Curtis0e07f922015-05-15 09:21:23 -07003247 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07003248 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3249 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003250 return false;
3251 }
3252
3253 // Parse out format specific parameters.
3254 std::vector<std::string> fields;
3255 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
3256
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003257 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07003258 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003259 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003260 // Only fmtps with equals are currently supported. Other fmtp types
3261 // should be ignored. Unknown fmtps do not constitute an error.
3262 continue;
3263 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003264
3265 std::string name;
3266 std::string value;
3267 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003268 return false;
3269 }
3270 codec_params[name] = value;
3271 }
3272
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003273 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3274 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003275 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3277 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003278 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003279 }
3280 return true;
3281}
3282
3283bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3284 MediaContentDescription* media_desc,
3285 SdpParseError* error) {
3286 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3287 media_type != cricket::MEDIA_TYPE_VIDEO) {
3288 return true;
3289 }
3290 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003291 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003292 if (rtcp_fb_fields.size() < 2) {
3293 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3294 }
3295 std::string payload_type_string;
3296 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3297 error)) {
3298 return false;
3299 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003300 int payload_type = kWildcardPayloadType;
3301 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003302 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3303 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003304 return false;
3305 }
3306 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003307 std::string id = rtcp_fb_fields[1];
3308 std::string param = "";
3309 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3310 iter != rtcp_fb_fields.end(); ++iter) {
3311 param.append(*iter);
3312 }
3313 const cricket::FeedbackParam feedback_param(id, param);
3314
3315 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003316 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3317 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003318 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003319 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3320 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003321 }
3322 return true;
3323}
3324
3325} // namespace webrtc