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