blob: 3fa9a7d469381bcf0df0e994e34e5d353d60d7c6 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00003 * Copyright 2011 Google Inc.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/app/webrtc/webrtcsdp.h"
29
30#include <limits.h>
31#include <stdio.h>
32#include <algorithm>
33#include <string>
34#include <vector>
decurtis@webrtc.org8af11042015-01-07 19:15:51 +000035#include <ctype.h>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000036
37#include "talk/app/webrtc/jsepicecandidate.h"
38#include "talk/app/webrtc/jsepsessiondescription.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000039#include "talk/media/base/codec.h"
40#include "talk/media/base/constants.h"
41#include "talk/media/base/cryptoparams.h"
pkasting@chromium.orge9facf82015-02-17 20:36:28 +000042#include "talk/media/base/rtputils.h"
mallinath@webrtc.org1112c302013-09-23 20:34:45 +000043#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000044#include "webrtc/p2p/base/candidate.h"
45#include "webrtc/p2p/base/constants.h"
46#include "webrtc/p2p/base/port.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000047#include "talk/session/media/mediasession.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000048#include "webrtc/base/common.h"
49#include "webrtc/base/logging.h"
50#include "webrtc/base/messagedigest.h"
51#include "webrtc/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052
53using cricket::AudioContentDescription;
54using cricket::Candidate;
55using cricket::Candidates;
56using cricket::ContentDescription;
57using cricket::ContentInfo;
58using cricket::CryptoParams;
59using cricket::DataContentDescription;
60using cricket::ICE_CANDIDATE_COMPONENT_RTP;
61using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
62using cricket::kCodecParamMaxBitrate;
63using cricket::kCodecParamMaxPTime;
64using cricket::kCodecParamMaxQuantization;
65using cricket::kCodecParamMinBitrate;
66using cricket::kCodecParamMinPTime;
67using cricket::kCodecParamPTime;
68using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000069using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070using cricket::kCodecParamStereo;
71using cricket::kCodecParamUseInbandFec;
Minyue Li7100dcd2015-03-27 05:05:59 +010072using cricket::kCodecParamUseDtx;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073using cricket::kCodecParamSctpProtocol;
74using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000075using cricket::kCodecParamMaxAverageBitrate;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000076using cricket::kCodecParamMaxPlaybackRate;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000077using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000078using cricket::MediaContentDescription;
79using cricket::MediaType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000080using cricket::RtpHeaderExtension;
81using cricket::SsrcGroup;
82using cricket::StreamParams;
83using cricket::StreamParamsVec;
84using cricket::TransportDescription;
85using cricket::TransportInfo;
86using cricket::VideoContentDescription;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000087using rtc::SocketAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088
89typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
90
91namespace cricket {
92class SessionDescription;
93}
94
95namespace webrtc {
96
97// Line type
98// RFC 4566
99// An SDP session description consists of a number of lines of text of
100// the form:
101// <type>=<value>
102// where <type> MUST be exactly one case-significant character.
103static const int kLinePrefixLength = 2; // Lenght of <type>=
104static const char kLineTypeVersion = 'v';
105static const char kLineTypeOrigin = 'o';
106static const char kLineTypeSessionName = 's';
107static const char kLineTypeSessionInfo = 'i';
108static const char kLineTypeSessionUri = 'u';
109static const char kLineTypeSessionEmail = 'e';
110static const char kLineTypeSessionPhone = 'p';
111static const char kLineTypeSessionBandwidth = 'b';
112static const char kLineTypeTiming = 't';
113static const char kLineTypeRepeatTimes = 'r';
114static const char kLineTypeTimeZone = 'z';
115static const char kLineTypeEncryptionKey = 'k';
116static const char kLineTypeMedia = 'm';
117static const char kLineTypeConnection = 'c';
118static const char kLineTypeAttributes = 'a';
119
120// Attributes
121static const char kAttributeGroup[] = "group";
122static const char kAttributeMid[] = "mid";
123static const char kAttributeRtcpMux[] = "rtcp-mux";
124static const char kAttributeSsrc[] = "ssrc";
125static const char kSsrcAttributeCname[] = "cname";
126static const char kAttributeExtmap[] = "extmap";
127// draft-alvestrand-mmusic-msid-01
128// a=msid-semantic: WMS
129static const char kAttributeMsidSemantics[] = "msid-semantic";
130static const char kMediaStreamSemantic[] = "WMS";
131static const char kSsrcAttributeMsid[] = "msid";
132static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133static const char kSsrcAttributeMslabel[] = "mslabel";
134static const char kSSrcAttributeLabel[] = "label";
135static const char kAttributeSsrcGroup[] = "ssrc-group";
136static const char kAttributeCrypto[] = "crypto";
137static const char kAttributeCandidate[] = "candidate";
138static const char kAttributeCandidateTyp[] = "typ";
139static const char kAttributeCandidateRaddr[] = "raddr";
140static const char kAttributeCandidateRport[] = "rport";
141static const char kAttributeCandidateUsername[] = "username";
142static const char kAttributeCandidatePassword[] = "password";
143static const char kAttributeCandidateGeneration[] = "generation";
144static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000145static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000146static const char kAttributeFmtp[] = "fmtp";
147static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000148static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000149static const char kAttributeRtcp[] = "rtcp";
150static const char kAttributeIceUfrag[] = "ice-ufrag";
151static const char kAttributeIcePwd[] = "ice-pwd";
152static const char kAttributeIceLite[] = "ice-lite";
153static const char kAttributeIceOption[] = "ice-options";
154static const char kAttributeSendOnly[] = "sendonly";
155static const char kAttributeRecvOnly[] = "recvonly";
156static const char kAttributeRtcpFb[] = "rtcp-fb";
157static const char kAttributeSendRecv[] = "sendrecv";
158static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000159// draft-ietf-mmusic-sctp-sdp-07
160// a=sctp-port
161static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000162
163// Experimental flags
164static const char kAttributeXGoogleFlag[] = "x-google-flag";
165static const char kValueConference[] = "conference";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000166
167// Candidate
168static const char kCandidateHost[] = "host";
169static const char kCandidateSrflx[] = "srflx";
170// TODO: How to map the prflx with circket candidate type
171// static const char kCandidatePrflx[] = "prflx";
172static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000173static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000174
175static const char kSdpDelimiterEqual = '=';
176static const char kSdpDelimiterSpace = ' ';
177static const char kSdpDelimiterColon = ':';
178static const char kSdpDelimiterSemicolon = ';';
179static const char kSdpDelimiterSlash = '/';
180static const char kNewLine = '\n';
181static const char kReturn = '\r';
182static const char kLineBreak[] = "\r\n";
183
184// TODO: Generate the Session and Time description
185// instead of hardcoding.
186static const char kSessionVersion[] = "v=0";
187// RFC 4566
188static const char kSessionOriginUsername[] = "-";
189static const char kSessionOriginSessionId[] = "0";
190static const char kSessionOriginSessionVersion[] = "0";
191static const char kSessionOriginNettype[] = "IN";
192static const char kSessionOriginAddrtype[] = "IP4";
193static const char kSessionOriginAddress[] = "127.0.0.1";
194static const char kSessionName[] = "s=-";
195static const char kTimeDescription[] = "t=0 0";
196static const char kAttrGroup[] = "a=group:BUNDLE";
197static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000198static const char kConnectionIpv4Addrtype[] = "IP4";
199static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000200static const char kMediaTypeVideo[] = "video";
201static const char kMediaTypeAudio[] = "audio";
202static const char kMediaTypeData[] = "application";
203static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000204// draft-ietf-mmusic-trickle-ice-01
205// When no candidates have been gathered, set the connection
206// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000207// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
208// Use IPV4 per default.
209static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000210static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000211// RFC 3556
212static const char kApplicationSpecificMaximum[] = "AS";
213
214static const int kDefaultVideoClockrate = 90000;
215
216// ISAC special-case.
217static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
218static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
219static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
220
wu@webrtc.org78187522013-10-07 23:32:02 +0000221static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000222
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000223// RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
224// types.
225const int kWildcardPayloadType = -1;
226
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000227struct SsrcInfo {
228 SsrcInfo()
229 : msid_identifier(kDefaultMsid),
230 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
231 // Create random string (which will be used as track label later)?
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000232 msid_appdata(rtc::CreateRandomString(8)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000233 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200234 uint32_t ssrc_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000235 std::string cname;
236 std::string msid_identifier;
237 std::string msid_appdata;
238
239 // For backward compatibility.
240 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
241 std::string label;
242 std::string mslabel;
243};
244typedef std::vector<SsrcInfo> SsrcInfoVec;
245typedef std::vector<SsrcGroup> SsrcGroupVec;
246
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000247template <class T>
248static void AddFmtpLine(const T& codec, std::string* message);
249static void BuildMediaDescription(const ContentInfo* content_info,
250 const TransportInfo* transport_info,
251 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000252 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000253 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000254static void BuildSctpContentAttributes(std::string* message, int sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000255static void BuildRtpContentAttributes(
256 const MediaContentDescription* media_desc,
257 const MediaType media_type,
258 std::string* message);
259static void BuildRtpMap(const MediaContentDescription* media_desc,
260 const MediaType media_type,
261 std::string* message);
262static void BuildCandidate(const std::vector<Candidate>& candidates,
263 std::string* message);
264static void BuildIceOptions(const std::vector<std::string>& transport_options,
265 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000266static bool IsRtp(const std::string& protocol);
267static bool IsDtlsSctp(const std::string& protocol);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000268static bool ParseSessionDescription(const std::string& message, size_t* pos,
269 std::string* session_id,
270 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271 TransportDescription* session_td,
272 RtpHeaderExtensions* session_extmaps,
273 cricket::SessionDescription* desc,
274 SdpParseError* error);
275static bool ParseGroupAttribute(const std::string& line,
276 cricket::SessionDescription* desc,
277 SdpParseError* error);
278static bool ParseMediaDescription(
279 const std::string& message,
280 const TransportDescription& session_td,
281 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000282 size_t* pos, cricket::SessionDescription* desc,
283 std::vector<JsepIceCandidate*>* candidates,
284 SdpParseError* error);
285static bool ParseContent(const std::string& message,
286 const MediaType media_type,
287 int mline_index,
288 const std::string& protocol,
289 const std::vector<int>& codec_preference,
290 size_t* pos,
291 std::string* content_name,
292 MediaContentDescription* media_desc,
293 TransportDescription* transport,
294 std::vector<JsepIceCandidate*>* candidates,
295 SdpParseError* error);
296static bool ParseSsrcAttribute(const std::string& line,
297 SsrcInfoVec* ssrc_infos,
298 SdpParseError* error);
299static bool ParseSsrcGroupAttribute(const std::string& line,
300 SsrcGroupVec* ssrc_groups,
301 SdpParseError* error);
302static bool ParseCryptoAttribute(const std::string& line,
303 MediaContentDescription* media_desc,
304 SdpParseError* error);
305static bool ParseRtpmapAttribute(const std::string& line,
306 const MediaType media_type,
307 const std::vector<int>& codec_preference,
308 MediaContentDescription* media_desc,
309 SdpParseError* error);
310static bool ParseFmtpAttributes(const std::string& line,
311 const MediaType media_type,
312 MediaContentDescription* media_desc,
313 SdpParseError* error);
314static bool ParseFmtpParam(const std::string& line, std::string* parameter,
315 std::string* value, SdpParseError* error);
316static bool ParseCandidate(const std::string& message, Candidate* candidate,
317 SdpParseError* error, bool is_raw);
318static bool ParseRtcpFbAttribute(const std::string& line,
319 const MediaType media_type,
320 MediaContentDescription* media_desc,
321 SdpParseError* error);
322static bool ParseIceOptions(const std::string& line,
323 std::vector<std::string>* transport_options,
324 SdpParseError* error);
325static bool ParseExtmap(const std::string& line,
326 RtpHeaderExtension* extmap,
327 SdpParseError* error);
328static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000329 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000330 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000331static bool ParseDtlsSetup(const std::string& line,
332 cricket::ConnectionRole* role,
333 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000334
335// Helper functions
336
337// Below ParseFailed*** functions output the line that caused the parsing
338// failure and the detailed reason (|description|) of the failure to |error|.
339// The functions always return false so that they can be used directly in the
340// following way when error happens:
341// "return ParseFailed***(...);"
342
343// The line starting at |line_start| of |message| is the failing line.
344// The reason for the failure should be provided in the |description|.
345// An example of a description could be "unknown character".
346static bool ParseFailed(const std::string& message,
347 size_t line_start,
348 const std::string& description,
349 SdpParseError* error) {
350 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000351 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000352 size_t line_end = message.find(kNewLine, line_start);
353 if (line_end != std::string::npos) {
354 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
355 --line_end;
356 }
357 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000358 } else {
359 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000360 }
361
362 if (error) {
363 error->line = first_line;
364 error->description = description;
365 }
366 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
367 << "\". Reason: " << description;
368 return false;
369}
370
371// |line| is the failing line. The reason for the failure should be
372// provided in the |description|.
373static bool ParseFailed(const std::string& line,
374 const std::string& description,
375 SdpParseError* error) {
376 return ParseFailed(line, 0, description, error);
377}
378
379// Parses failure where the failing SDP line isn't know or there are multiple
380// failing lines.
381static bool ParseFailed(const std::string& description,
382 SdpParseError* error) {
383 return ParseFailed("", description, error);
384}
385
386// |line| is the failing line. The failure is due to the fact that |line|
387// doesn't have |expected_fields| fields.
388static bool ParseFailedExpectFieldNum(const std::string& line,
389 int expected_fields,
390 SdpParseError* error) {
391 std::ostringstream description;
392 description << "Expects " << expected_fields << " fields.";
393 return ParseFailed(line, description.str(), error);
394}
395
396// |line| is the failing line. The failure is due to the fact that |line| has
397// less than |expected_min_fields| fields.
398static bool ParseFailedExpectMinFieldNum(const std::string& line,
399 int expected_min_fields,
400 SdpParseError* error) {
401 std::ostringstream description;
402 description << "Expects at least " << expected_min_fields << " fields.";
403 return ParseFailed(line, description.str(), error);
404}
405
406// |line| is the failing line. The failure is due to the fact that it failed to
407// get the value of |attribute|.
408static bool ParseFailedGetValue(const std::string& line,
409 const std::string& attribute,
410 SdpParseError* error) {
411 std::ostringstream description;
412 description << "Failed to get the value of attribute: " << attribute;
413 return ParseFailed(line, description.str(), error);
414}
415
416// The line starting at |line_start| of |message| is the failing line. The
417// failure is due to the line type (e.g. the "m" part of the "m-line")
418// not matching what is expected. The expected line type should be
419// provided as |line_type|.
420static bool ParseFailedExpectLine(const std::string& message,
421 size_t line_start,
422 const char line_type,
423 const std::string& line_value,
424 SdpParseError* error) {
425 std::ostringstream description;
426 description << "Expect line: " << line_type << "=" << line_value;
427 return ParseFailed(message, line_start, description.str(), error);
428}
429
430static bool AddLine(const std::string& line, std::string* message) {
431 if (!message)
432 return false;
433
434 message->append(line);
435 message->append(kLineBreak);
436 return true;
437}
438
439static bool GetLine(const std::string& message,
440 size_t* pos,
441 std::string* line) {
442 size_t line_begin = *pos;
443 size_t line_end = message.find(kNewLine, line_begin);
444 if (line_end == std::string::npos) {
445 return false;
446 }
447 // Update the new start position
448 *pos = line_end + 1;
449 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
450 --line_end;
451 }
452 *line = message.substr(line_begin, (line_end - line_begin));
453 const char* cline = line->c_str();
454 // RFC 4566
455 // An SDP session description consists of a number of lines of text of
456 // the form:
457 // <type>=<value>
458 // where <type> MUST be exactly one case-significant character and
459 // <value> is structured text whose format depends on <type>.
460 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000461 if (line->length() < 3 ||
462 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000463 cline[1] != kSdpDelimiterEqual ||
464 cline[2] == kSdpDelimiterSpace) {
465 *pos = line_begin;
466 return false;
467 }
468 return true;
469}
470
471// Init |os| to "|type|=|value|".
472static void InitLine(const char type,
473 const std::string& value,
474 std::ostringstream* os) {
475 os->str("");
476 *os << type << kSdpDelimiterEqual << value;
477}
478
479// Init |os| to "a=|attribute|".
480static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
481 InitLine(kLineTypeAttributes, attribute, os);
482}
483
484// Writes a SDP attribute line based on |attribute| and |value| to |message|.
485static void AddAttributeLine(const std::string& attribute, int value,
486 std::string* message) {
487 std::ostringstream os;
488 InitAttrLine(attribute, &os);
489 os << kSdpDelimiterColon << value;
490 AddLine(os.str(), message);
491}
492
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000493static bool IsLineType(const std::string& message,
494 const char type,
495 size_t line_start) {
496 if (message.size() < line_start + kLinePrefixLength) {
497 return false;
498 }
499 const char* cmessage = message.c_str();
500 return (cmessage[line_start] == type &&
501 cmessage[line_start + 1] == kSdpDelimiterEqual);
502}
503
504static bool IsLineType(const std::string& line,
505 const char type) {
506 return IsLineType(line, type, 0);
507}
508
509static bool GetLineWithType(const std::string& message, size_t* pos,
510 std::string* line, const char type) {
511 if (!IsLineType(message, type, *pos)) {
512 return false;
513 }
514
515 if (!GetLine(message, pos, line))
516 return false;
517
518 return true;
519}
520
521static bool HasAttribute(const std::string& line,
522 const std::string& attribute) {
523 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
524}
525
Peter Boström0c4e06b2015-10-07 12:23:21 +0200526static bool AddSsrcLine(uint32_t ssrc_id,
527 const std::string& attribute,
528 const std::string& value,
529 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000530 // RFC 5576
531 // a=ssrc:<ssrc-id> <attribute>:<value>
532 std::ostringstream os;
533 InitAttrLine(kAttributeSsrc, &os);
534 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
535 << attribute << kSdpDelimiterColon << value;
536 return AddLine(os.str(), message);
537}
538
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000539// Get value only from <attribute>:<value>.
540static bool GetValue(const std::string& message, const std::string& attribute,
541 std::string* value, SdpParseError* error) {
542 std::string leftpart;
Donald Curtis0e07f922015-05-15 09:21:23 -0700543 if (!rtc::tokenize_first(message, kSdpDelimiterColon, &leftpart, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000544 return ParseFailedGetValue(message, attribute, error);
545 }
546 // The left part should end with the expected attribute.
547 if (leftpart.length() < attribute.length() ||
548 leftpart.compare(leftpart.length() - attribute.length(),
549 attribute.length(), attribute) != 0) {
550 return ParseFailedGetValue(message, attribute, error);
551 }
552 return true;
553}
554
555static bool CaseInsensitiveFind(std::string str1, std::string str2) {
556 std::transform(str1.begin(), str1.end(), str1.begin(),
557 ::tolower);
558 std::transform(str2.begin(), str2.end(), str2.begin(),
559 ::tolower);
560 return str1.find(str2) != std::string::npos;
561}
562
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000563template <class T>
564static bool GetValueFromString(const std::string& line,
565 const std::string& s,
566 T* t,
567 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000568 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000569 std::ostringstream description;
570 description << "Invalid value: " << s << ".";
571 return ParseFailed(line, description.str(), error);
572 }
573 return true;
574}
575
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000576static bool GetPayloadTypeFromString(const std::string& line,
577 const std::string& s,
578 int* payload_type,
579 SdpParseError* error) {
580 return GetValueFromString(line, s, payload_type, error) &&
581 cricket::IsValidRtpPayloadType(*payload_type);
582}
583
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000584void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
585 StreamParamsVec* tracks) {
586 ASSERT(tracks != NULL);
587 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
588 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
589 if (ssrc_info->cname.empty()) {
590 continue;
591 }
592
593 std::string sync_label;
594 std::string track_id;
595 if (ssrc_info->msid_identifier == kDefaultMsid &&
596 !ssrc_info->mslabel.empty()) {
597 // If there's no msid and there's mslabel, we consider this is a sdp from
598 // a older version of client that doesn't support msid.
599 // In that case, we use the mslabel and label to construct the track.
600 sync_label = ssrc_info->mslabel;
601 track_id = ssrc_info->label;
602 } else {
603 sync_label = ssrc_info->msid_identifier;
604 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
605 // is corresponding to the "id" attribute of StreamParams.
606 track_id = ssrc_info->msid_appdata;
607 }
608 if (sync_label.empty() || track_id.empty()) {
609 ASSERT(false);
610 continue;
611 }
612
613 StreamParamsVec::iterator track = tracks->begin();
614 for (; track != tracks->end(); ++track) {
615 if (track->id == track_id) {
616 break;
617 }
618 }
619 if (track == tracks->end()) {
620 // If we don't find an existing track, create a new one.
621 tracks->push_back(StreamParams());
622 track = tracks->end() - 1;
623 }
624 track->add_ssrc(ssrc_info->ssrc_id);
625 track->cname = ssrc_info->cname;
626 track->sync_label = sync_label;
627 track->id = track_id;
628 }
629}
630
631void GetMediaStreamLabels(const ContentInfo* content,
632 std::set<std::string>* labels) {
633 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000634 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000635 content->description);
636 const cricket::StreamParamsVec& streams = media_desc->streams();
637 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
638 it != streams.end(); ++it) {
639 labels->insert(it->sync_label);
640 }
641}
642
643// RFC 5245
644// It is RECOMMENDED that default candidates be chosen based on the
645// likelihood of those candidates to work with the peer that is being
646// contacted. It is RECOMMENDED that relayed > reflexive > host.
647static const int kPreferenceUnknown = 0;
648static const int kPreferenceHost = 1;
649static const int kPreferenceReflexive = 2;
650static const int kPreferenceRelayed = 3;
651
652static int GetCandidatePreferenceFromType(const std::string& type) {
653 int preference = kPreferenceUnknown;
654 if (type == cricket::LOCAL_PORT_TYPE) {
655 preference = kPreferenceHost;
656 } else if (type == cricket::STUN_PORT_TYPE) {
657 preference = kPreferenceReflexive;
658 } else if (type == cricket::RELAY_PORT_TYPE) {
659 preference = kPreferenceRelayed;
660 } else {
661 ASSERT(false);
662 }
663 return preference;
664}
665
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000666// Get ip and port of the default destination from the |candidates| with the
667// given value of |component_id|. The default candidate should be the one most
668// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669// RFC 5245
670// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
671// TODO: Decide the default destination in webrtcsession and
672// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000673static void GetDefaultDestination(
674 const std::vector<Candidate>& candidates,
675 int component_id, std::string* port,
676 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000677 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000678 *port = kDummyPort;
679 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000681 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682 for (std::vector<Candidate>::const_iterator it = candidates.begin();
683 it != candidates.end(); ++it) {
684 if (it->component() != component_id) {
685 continue;
686 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000687 // Default destination should be UDP only.
688 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 continue;
690 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000691 const int preference = GetCandidatePreferenceFromType(it->type());
692 const int family = it->address().ipaddr().family();
693 // See if this candidate is more preferable then the current one if it's the
694 // same family. Or if the current family is IPv4 already so we could safely
695 // ignore all IPv6 ones. WebRTC bug 4269.
696 // http://code.google.com/p/webrtc/issues/detail?id=4269
697 if ((preference <= current_preference && current_family == family) ||
698 (current_family == AF_INET && family == AF_INET6)) {
699 continue;
700 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000701 if (family == AF_INET) {
702 addr_type->assign(kConnectionIpv4Addrtype);
703 } else if (family == AF_INET6) {
704 addr_type->assign(kConnectionIpv6Addrtype);
705 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000706 current_preference = preference;
707 current_family = family;
708 *port = it->address().PortAsString();
709 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000710 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000711}
712
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000713// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000714static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000715 const std::vector<Candidate>& candidates,
jbauch083b73f2015-07-16 02:46:32 -0700716 const std::string& mline,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000717 std::string* message) {
718 std::string new_lines;
719 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000720 // RFC 4566
721 // m=<media> <port> <proto> <fmt> ...
722 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000723 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000724 if (fields.size() < 3) {
725 return;
726 }
727
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000729 std::string rtp_port, rtp_ip, addr_type;
730 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
731 &rtp_port, &rtp_ip, &addr_type);
732 // Found default RTP candidate.
733 // RFC 5245
734 // The default candidates are added to the SDP as the default
735 // destination for media. For streams based on RTP, this is done by
736 // placing the IP address and port of the RTP candidate into the c and m
737 // lines, respectively.
738 // Update the port in the m line.
739 // If this is a m-line with port equal to 0, we don't change it.
740 if (fields[1] != kMediaPortRejected) {
741 new_lines.replace(fields[0].size() + 1,
742 fields[1].size(),
743 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000744 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000745 // Add the c line.
746 // RFC 4566
747 // c=<nettype> <addrtype> <connection-address>
748 InitLine(kLineTypeConnection, kConnectionNettype, &os);
749 os << " " << addr_type << " " << rtp_ip;
750 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000751 message->append(new_lines);
752}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000754// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
755static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000756 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
757 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
758 &rtcp_port, &rtcp_ip, &addr_type);
759 // Found default RTCP candidate.
760 // RFC 5245
761 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
762 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000763
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000764 // RFC 3605
765 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
766 // connection-address] CRLF
767 std::ostringstream os;
768 InitAttrLine(kAttributeRtcp, &os);
769 os << kSdpDelimiterColon
770 << rtcp_port << " "
771 << kConnectionNettype << " "
772 << addr_type << " "
773 << rtcp_ip;
774 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000775 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000776}
777
778// Get candidates according to the mline index from SessionDescriptionInterface.
779static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
780 int mline_index,
781 std::vector<Candidate>* candidates) {
782 if (!candidates) {
783 return;
784 }
785 const IceCandidateCollection* cc = desci.candidates(mline_index);
786 for (size_t i = 0; i < cc->count(); ++i) {
787 const IceCandidateInterface* candidate = cc->at(i);
788 candidates->push_back(candidate->candidate());
789 }
790}
791
792std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000793 const cricket::SessionDescription* desc = jdesc.description();
794 if (!desc) {
795 return "";
796 }
797
798 std::string message;
799
800 // Session Description.
801 AddLine(kSessionVersion, &message);
802 // Session Origin
803 // RFC 4566
804 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
805 // <unicast-address>
806 std::ostringstream os;
807 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
jbauch083b73f2015-07-16 02:46:32 -0700808 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000809 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700810 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 kSessionOriginSessionVersion : jdesc.session_version();
812 os << " " << session_id << " " << session_version << " "
813 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
814 << kSessionOriginAddress;
815 AddLine(os.str(), &message);
816 AddLine(kSessionName, &message);
817
818 // Time Description.
819 AddLine(kTimeDescription, &message);
820
821 // Group
822 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
823 std::string group_line = kAttrGroup;
824 const cricket::ContentGroup* group =
825 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
826 ASSERT(group != NULL);
827 const cricket::ContentNames& content_names = group->content_names();
828 for (cricket::ContentNames::const_iterator it = content_names.begin();
829 it != content_names.end(); ++it) {
830 group_line.append(" ");
831 group_line.append(*it);
832 }
833 AddLine(group_line, &message);
834 }
835
836 // MediaStream semantics
837 InitAttrLine(kAttributeMsidSemantics, &os);
838 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000839
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840 std::set<std::string> media_stream_labels;
841 const ContentInfo* audio_content = GetFirstAudioContent(desc);
842 if (audio_content)
843 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000844
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000845 const ContentInfo* video_content = GetFirstVideoContent(desc);
846 if (video_content)
847 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000848
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000849 for (std::set<std::string>::const_iterator it =
850 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
851 os << " " << *it;
852 }
853 AddLine(os.str(), &message);
854
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000855 // Preserve the order of the media contents.
856 int mline_index = -1;
857 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
858 it != desc->contents().end(); ++it) {
859 const MediaContentDescription* mdesc =
860 static_cast<const MediaContentDescription*>(it->description);
861 std::vector<Candidate> candidates;
862 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
863 BuildMediaDescription(&*it,
864 desc->GetTransportInfoByName(it->name),
865 mdesc->type(),
866 candidates,
867 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000868 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000869 return message;
870}
871
872// Serializes the passed in IceCandidateInterface to a SDP string.
873// candidate - The candidate to be serialized.
874std::string SdpSerializeCandidate(
875 const IceCandidateInterface& candidate) {
876 std::string message;
877 std::vector<cricket::Candidate> candidates;
878 candidates.push_back(candidate.candidate());
879 BuildCandidate(candidates, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000880 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
881 // just candidate:<candidate> not a=candidate:<blah>CRLF
882 ASSERT(message.find("a=") == 0);
883 message.erase(0, 2);
884 ASSERT(message.find(kLineBreak) == message.size() - 2);
885 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886 return message;
887}
888
889bool SdpDeserialize(const std::string& message,
890 JsepSessionDescription* jdesc,
891 SdpParseError* error) {
892 std::string session_id;
893 std::string session_version;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700894 TransportDescription session_td("", "");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000895 RtpHeaderExtensions session_extmaps;
896 cricket::SessionDescription* desc = new cricket::SessionDescription();
897 std::vector<JsepIceCandidate*> candidates;
898 size_t current_pos = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899
900 // Session Description
901 if (!ParseSessionDescription(message, &current_pos, &session_id,
deadbeefc80741f2015-10-22 13:14:45 -0700902 &session_version, &session_td, &session_extmaps,
903 desc, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000904 delete desc;
905 return false;
906 }
907
908 // Media Description
deadbeefc80741f2015-10-22 13:14:45 -0700909 if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
910 desc, &candidates, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000911 delete desc;
912 for (std::vector<JsepIceCandidate*>::const_iterator
913 it = candidates.begin(); it != candidates.end(); ++it) {
914 delete *it;
915 }
916 return false;
917 }
918
919 jdesc->Initialize(desc, session_id, session_version);
920
921 for (std::vector<JsepIceCandidate*>::const_iterator
922 it = candidates.begin(); it != candidates.end(); ++it) {
923 jdesc->AddCandidate(*it);
924 delete *it;
925 }
926 return true;
927}
928
929bool SdpDeserializeCandidate(const std::string& message,
930 JsepIceCandidate* jcandidate,
931 SdpParseError* error) {
932 ASSERT(jcandidate != NULL);
933 Candidate candidate;
934 if (!ParseCandidate(message, &candidate, error, true)) {
935 return false;
936 }
937 jcandidate->SetCandidate(candidate);
938 return true;
939}
940
941bool ParseCandidate(const std::string& message, Candidate* candidate,
942 SdpParseError* error, bool is_raw) {
943 ASSERT(candidate != NULL);
944
945 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000946 std::string first_line = message;
947 size_t pos = 0;
948 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000950 // Makes sure |message| contains only one line.
951 if (message.size() > first_line.size()) {
952 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700953 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
954 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000955 return ParseFailed(message, 0, "Expect one line only", error);
956 }
957 }
958
959 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
960 // candidate:<candidate> when trickled, but we still support
961 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
962 // from the SDP.
963 if (IsLineType(first_line, kLineTypeAttributes)) {
964 first_line = first_line.substr(kLinePrefixLength);
965 }
966
967 std::string attribute_candidate;
968 std::string candidate_value;
969
970 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700971 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
972 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000973 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974 if (is_raw) {
975 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000976 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000977 << ":" << "<candidate-str>";
978 return ParseFailed(first_line, 0, description.str(), error);
979 } else {
980 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
981 kAttributeCandidate, error);
982 }
983 }
984
985 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000986 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
987
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988 // RFC 5245
989 // a=candidate:<foundation> <component-id> <transport> <priority>
990 // <connection-address> <port> typ <candidate-types>
991 // [raddr <connection-address>] [rport <port>]
992 // *(SP extension-att-name SP extension-att-value)
993 const size_t expected_min_fields = 8;
994 if (fields.size() < expected_min_fields ||
995 (fields[6] != kAttributeCandidateTyp)) {
996 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
997 }
jbauch083b73f2015-07-16 02:46:32 -0700998 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000999
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001000 int component_id = 0;
1001 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1002 return false;
1003 }
jbauch083b73f2015-07-16 02:46:32 -07001004 const std::string& transport = fields[2];
Peter Boström0c4e06b2015-10-07 12:23:21 +02001005 uint32_t priority = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001006 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1007 return false;
1008 }
jbauch083b73f2015-07-16 02:46:32 -07001009 const std::string& connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001010 int port = 0;
1011 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1012 return false;
1013 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001014 SocketAddress address(connection_address, port);
1015
1016 cricket::ProtocolType protocol;
1017 if (!StringToProto(transport.c_str(), &protocol)) {
1018 return ParseFailed(first_line, "Unsupported transport type.", error);
1019 }
1020
1021 std::string candidate_type;
jbauch083b73f2015-07-16 02:46:32 -07001022 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001023 if (type == kCandidateHost) {
1024 candidate_type = cricket::LOCAL_PORT_TYPE;
1025 } else if (type == kCandidateSrflx) {
1026 candidate_type = cricket::STUN_PORT_TYPE;
1027 } else if (type == kCandidateRelay) {
1028 candidate_type = cricket::RELAY_PORT_TYPE;
1029 } else {
1030 return ParseFailed(first_line, "Unsupported candidate type.", error);
1031 }
1032
1033 size_t current_position = expected_min_fields;
1034 SocketAddress related_address;
1035 // The 2 optional fields for related address
1036 // [raddr <connection-address>] [rport <port>]
1037 if (fields.size() >= (current_position + 2) &&
1038 fields[current_position] == kAttributeCandidateRaddr) {
1039 related_address.SetIP(fields[++current_position]);
1040 ++current_position;
1041 }
1042 if (fields.size() >= (current_position + 2) &&
1043 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001044 int port = 0;
1045 if (!GetValueFromString(
1046 first_line, fields[++current_position], &port, error)) {
1047 return false;
1048 }
1049 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050 ++current_position;
1051 }
1052
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001053 // If this is a TCP candidate, it has additional extension as defined in
1054 // RFC 6544.
1055 std::string tcptype;
1056 if (fields.size() >= (current_position + 2) &&
1057 fields[current_position] == kTcpCandidateType) {
1058 tcptype = fields[++current_position];
1059 ++current_position;
1060
1061 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1062 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1063 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1064 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1065 }
1066
1067 if (protocol != cricket::PROTO_TCP) {
1068 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1069 }
1070 }
1071
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001072 // Extension
1073 // Empty string as the candidate username and password.
1074 // Will be updated later with the ice-ufrag and ice-pwd.
1075 // TODO: Remove the username/password extension, which is currently
1076 // kept for backwards compatibility.
1077 std::string username;
1078 std::string password;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001079 uint32_t generation = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001080 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1081 // RFC 5245
1082 // *(SP extension-att-name SP extension-att-value)
1083 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001084 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1085 return false;
1086 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001087 } else if (fields[i] == kAttributeCandidateUsername) {
1088 username = fields[++i];
1089 } else if (fields[i] == kAttributeCandidatePassword) {
1090 password = fields[++i];
1091 } else {
1092 // Skip the unknown extension.
1093 ++i;
1094 }
1095 }
1096
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001097 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001098 address, priority, username, password, candidate_type,
1099 generation, foundation);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001100 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001101 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001102 return true;
1103}
1104
1105bool ParseIceOptions(const std::string& line,
1106 std::vector<std::string>* transport_options,
1107 SdpParseError* error) {
1108 std::string ice_options;
1109 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1110 return false;
1111 }
1112 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001113 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001114 for (size_t i = 0; i < fields.size(); ++i) {
1115 transport_options->push_back(fields[i]);
1116 }
1117 return true;
1118}
1119
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001120bool ParseSctpPort(const std::string& line,
1121 int* sctp_port,
1122 SdpParseError* error) {
1123 // draft-ietf-mmusic-sctp-sdp-07
1124 // a=sctp-port
1125 std::vector<std::string> fields;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001126 const size_t expected_min_fields = 2;
lally69f57602015-10-08 10:15:04 -07001127 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1128 if (fields.size() < expected_min_fields) {
1129 fields.resize(0);
1130 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpace, &fields);
1131 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001132 if (fields.size() < expected_min_fields) {
1133 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1134 }
1135 if (!rtc::FromString(fields[1], sctp_port)) {
lally69f57602015-10-08 10:15:04 -07001136 return ParseFailed(line, "Invalid sctp port value.", error);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001137 }
1138 return true;
1139}
1140
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001141bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1142 SdpParseError* error) {
1143 // RFC 5285
1144 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1145 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001146 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001147 kSdpDelimiterSpace, &fields);
1148 const size_t expected_min_fields = 2;
1149 if (fields.size() < expected_min_fields) {
1150 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1151 }
1152 std::string uri = fields[1];
1153
1154 std::string value_direction;
1155 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1156 return false;
1157 }
1158 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001159 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001160 int value = 0;
1161 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1162 return false;
1163 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001164
1165 *extmap = RtpHeaderExtension(uri, value);
1166 return true;
1167}
1168
1169void BuildMediaDescription(const ContentInfo* content_info,
1170 const TransportInfo* transport_info,
1171 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001172 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173 std::string* message) {
1174 ASSERT(message != NULL);
1175 if (content_info == NULL || message == NULL) {
1176 return;
1177 }
1178 // TODO: Rethink if we should use sprintfn instead of stringstream.
1179 // According to the style guide, streams should only be used for logging.
1180 // http://google-styleguide.googlecode.com/svn/
1181 // trunk/cppguide.xml?showone=Streams#Streams
1182 std::ostringstream os;
1183 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001184 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001185 content_info->description);
1186 ASSERT(media_desc != NULL);
1187
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001188 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001189
1190 // RFC 4566
1191 // m=<media> <port> <proto> <fmt>
1192 // fmt is a list of payload type numbers that MAY be used in the session.
1193 const char* type = NULL;
1194 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1195 type = kMediaTypeAudio;
1196 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1197 type = kMediaTypeVideo;
1198 else if (media_type == cricket::MEDIA_TYPE_DATA)
1199 type = kMediaTypeData;
1200 else
1201 ASSERT(false);
1202
1203 std::string fmt;
1204 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1205 const VideoContentDescription* video_desc =
1206 static_cast<const VideoContentDescription*>(media_desc);
1207 for (std::vector<cricket::VideoCodec>::const_iterator it =
1208 video_desc->codecs().begin();
1209 it != video_desc->codecs().end(); ++it) {
1210 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001211 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001212 }
1213 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1214 const AudioContentDescription* audio_desc =
1215 static_cast<const AudioContentDescription*>(media_desc);
1216 for (std::vector<cricket::AudioCodec>::const_iterator it =
1217 audio_desc->codecs().begin();
1218 it != audio_desc->codecs().end(); ++it) {
1219 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001220 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001221 }
1222 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001223 const DataContentDescription* data_desc =
1224 static_cast<const DataContentDescription*>(media_desc);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001225 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001226 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001227
1228 for (std::vector<cricket::DataCodec>::const_iterator it =
1229 data_desc->codecs().begin();
1230 it != data_desc->codecs().end(); ++it) {
1231 if (it->id == cricket::kGoogleSctpDataCodecId &&
1232 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1233 break;
1234 }
1235 }
1236
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001237 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001238 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001239 for (std::vector<cricket::DataCodec>::const_iterator it =
1240 data_desc->codecs().begin();
1241 it != data_desc->codecs().end(); ++it) {
1242 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001243 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001244 }
1245 }
1246 }
1247 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1248 // to 0.
1249 if (fmt.empty()) {
1250 fmt = " 0";
1251 }
1252
1253 // The port number in the m line will be updated later when associate with
1254 // the candidates.
1255 // RFC 3264
1256 // To reject an offered stream, the port number in the corresponding stream in
1257 // the answer MUST be set to zero.
jbauch083b73f2015-07-16 02:46:32 -07001258 const std::string& port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001259 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001260
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001261 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001262 transport_info->description.identity_fingerprint.get() : NULL;
1263
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001264 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001265 InitLine(kLineTypeMedia, type, &os);
1266 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001267 std::string mline = os.str();
1268 UpdateMediaDefaultDestination(candidates, mline, message);
1269
1270 // RFC 4566
1271 // b=AS:<bandwidth>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001272 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001273 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1274 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1275 AddLine(os.str(), message);
1276 }
1277
1278 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001279 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001280 std::string rtcp_line = GetRtcpLine(candidates);
1281 if (!rtcp_line.empty()) {
1282 AddLine(rtcp_line, message);
1283 }
1284 }
1285
1286 // Build the a=candidate lines.
1287 BuildCandidate(candidates, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288
1289 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1290 if (transport_info) {
1291 // RFC 5245
1292 // ice-pwd-att = "ice-pwd" ":" password
1293 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1294 // ice-ufrag
1295 InitAttrLine(kAttributeIceUfrag, &os);
1296 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1297 AddLine(os.str(), message);
1298 // ice-pwd
1299 InitAttrLine(kAttributeIcePwd, &os);
1300 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1301 AddLine(os.str(), message);
1302
1303 // draft-petithuguenin-mmusic-ice-attributes-level-03
1304 BuildIceOptions(transport_info->description.transport_options, message);
1305
1306 // RFC 4572
1307 // fingerprint-attribute =
1308 // "fingerprint" ":" hash-func SP fingerprint
1309 if (fp) {
1310 // Insert the fingerprint attribute.
1311 InitAttrLine(kAttributeFingerprint, &os);
1312 os << kSdpDelimiterColon
1313 << fp->algorithm << kSdpDelimiterSpace
1314 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001315 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001316
1317 // Inserting setup attribute.
1318 if (transport_info->description.connection_role !=
1319 cricket::CONNECTIONROLE_NONE) {
1320 // Making sure we are not using "passive" mode.
1321 cricket::ConnectionRole role =
1322 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001323 std::string dtls_role_str;
1324 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001325 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001326 os << kSdpDelimiterColon << dtls_role_str;
1327 AddLine(os.str(), message);
1328 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329 }
1330 }
1331
1332 // RFC 3388
1333 // mid-attribute = "a=mid:" identification-tag
1334 // identification-tag = token
1335 // Use the content name as the mid identification-tag.
1336 InitAttrLine(kAttributeMid, &os);
1337 os << kSdpDelimiterColon << content_info->name;
1338 AddLine(os.str(), message);
1339
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001340 if (IsDtlsSctp(media_desc->protocol())) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001341 BuildSctpContentAttributes(message, sctp_port);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001342 } else if (IsRtp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343 BuildRtpContentAttributes(media_desc, media_type, message);
1344 }
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
1360void BuildRtpContentAttributes(
1361 const MediaContentDescription* media_desc,
1362 const MediaType media_type,
1363 std::string* message) {
1364 std::ostringstream os;
1365 // RFC 5285
1366 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1367 // The definitions MUST be either all session level or all media level. This
1368 // implementation uses all media level.
1369 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1370 InitAttrLine(kAttributeExtmap, &os);
1371 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1372 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1373 AddLine(os.str(), message);
1374 }
1375
1376 // RFC 3264
1377 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
deadbeefc80741f2015-10-22 13:14:45 -07001378 switch (media_desc->direction()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001379 case cricket::MD_INACTIVE:
1380 InitAttrLine(kAttributeInactive, &os);
1381 break;
1382 case cricket::MD_SENDONLY:
1383 InitAttrLine(kAttributeSendOnly, &os);
1384 break;
1385 case cricket::MD_RECVONLY:
1386 InitAttrLine(kAttributeRecvOnly, &os);
1387 break;
1388 case cricket::MD_SENDRECV:
1389 default:
1390 InitAttrLine(kAttributeSendRecv, &os);
1391 break;
1392 }
1393 AddLine(os.str(), message);
1394
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395 // RFC 5761
1396 // a=rtcp-mux
1397 if (media_desc->rtcp_mux()) {
1398 InitAttrLine(kAttributeRtcpMux, &os);
1399 AddLine(os.str(), message);
1400 }
1401
1402 // RFC 4568
1403 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1404 for (std::vector<CryptoParams>::const_iterator it =
1405 media_desc->cryptos().begin();
1406 it != media_desc->cryptos().end(); ++it) {
1407 InitAttrLine(kAttributeCrypto, &os);
1408 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1409 << it->key_params;
1410 if (!it->session_params.empty()) {
1411 os << " " << it->session_params;
1412 }
1413 AddLine(os.str(), message);
1414 }
1415
1416 // RFC 4566
1417 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1418 // [/<encodingparameters>]
1419 BuildRtpMap(media_desc, media_type, message);
1420
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001421 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1422 track != media_desc->streams().end(); ++track) {
1423 // Require that the track belongs to a media stream,
1424 // ie the sync_label is set. This extra check is necessary since the
1425 // MediaContentDescription always contains a streamparam with an ssrc even
1426 // if no track or media stream have been created.
1427 if (track->sync_label.empty()) continue;
1428
1429 // Build the ssrc-group lines.
1430 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1431 // RFC 5576
1432 // a=ssrc-group:<semantics> <ssrc-id> ...
1433 if (track->ssrc_groups[i].ssrcs.empty()) {
1434 continue;
1435 }
1436 std::ostringstream os;
1437 InitAttrLine(kAttributeSsrcGroup, &os);
1438 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001439 std::vector<uint32_t>::const_iterator ssrc =
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001440 track->ssrc_groups[i].ssrcs.begin();
1441 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001442 os << kSdpDelimiterSpace << rtc::ToString<uint32_t>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001443 }
1444 AddLine(os.str(), message);
1445 }
1446 // Build the ssrc lines for each ssrc.
1447 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001448 uint32_t ssrc = track->ssrcs[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001449 // RFC 5576
1450 // a=ssrc:<ssrc-id> cname:<value>
1451 AddSsrcLine(ssrc, kSsrcAttributeCname,
1452 track->cname, message);
1453
1454 // draft-alvestrand-mmusic-msid-00
1455 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1456 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1457 // is corresponding to the "name" attribute of StreamParams.
1458 std::string appdata = track->id;
1459 std::ostringstream os;
1460 InitAttrLine(kAttributeSsrc, &os);
1461 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1462 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1463 << kSdpDelimiterSpace << appdata;
1464 AddLine(os.str(), message);
1465
1466 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1467 // draft-alvestrand-rtcweb-mid-01
1468 // a=ssrc:<ssrc-id> mslabel:<value>
1469 // The label isn't yet defined.
1470 // a=ssrc:<ssrc-id> label:<value>
1471 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1472 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1473 }
1474 }
1475}
1476
1477void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1478 // fmtp header: a=fmtp:|payload_type| <parameters>
1479 // Add a=fmtp
1480 InitAttrLine(kAttributeFmtp, os);
1481 // Add :|payload_type|
1482 *os << kSdpDelimiterColon << payload_type;
1483}
1484
1485void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1486 // rtcp-fb header: a=rtcp-fb:|payload_type|
1487 // <parameters>/<ccm <ccm_parameters>>
1488 // Add a=rtcp-fb
1489 InitAttrLine(kAttributeRtcpFb, os);
1490 // Add :
1491 *os << kSdpDelimiterColon;
1492 if (payload_type == kWildcardPayloadType) {
1493 *os << "*";
1494 } else {
1495 *os << payload_type;
1496 }
1497}
1498
1499void WriteFmtpParameter(const std::string& parameter_name,
1500 const std::string& parameter_value,
1501 std::ostringstream* os) {
1502 // fmtp parameters: |parameter_name|=|parameter_value|
1503 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1504}
1505
1506void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1507 std::ostringstream* os) {
1508 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1509 fmtp != parameters.end(); ++fmtp) {
1510 // Each new parameter, except the first one starts with ";" and " ".
1511 if (fmtp != parameters.begin()) {
1512 *os << kSdpDelimiterSemicolon;
1513 }
1514 *os << kSdpDelimiterSpace;
1515 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1516 }
1517}
1518
1519bool IsFmtpParam(const std::string& name) {
1520 const char* kFmtpParams[] = {
1521 kCodecParamMinPTime, kCodecParamSPropStereo,
Minyue Li7100dcd2015-03-27 05:05:59 +01001522 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamUseDtx,
1523 kCodecParamStartBitrate, kCodecParamMaxBitrate, kCodecParamMinBitrate,
1524 kCodecParamMaxQuantization, kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001525 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1526 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001527 };
1528 for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
1529 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1530 return true;
1531 }
1532 }
1533 return false;
1534}
1535
1536// Retreives fmtp parameters from |params|, which may contain other parameters
1537// as well, and puts them in |fmtp_parameters|.
1538void GetFmtpParams(const cricket::CodecParameterMap& params,
1539 cricket::CodecParameterMap* fmtp_parameters) {
1540 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1541 iter != params.end(); ++iter) {
1542 if (IsFmtpParam(iter->first)) {
1543 (*fmtp_parameters)[iter->first] = iter->second;
1544 }
1545 }
1546}
1547
1548template <class T>
1549void AddFmtpLine(const T& codec, std::string* message) {
1550 cricket::CodecParameterMap fmtp_parameters;
1551 GetFmtpParams(codec.params, &fmtp_parameters);
1552 if (fmtp_parameters.empty()) {
1553 // No need to add an fmtp if it will have no (optional) parameters.
1554 return;
1555 }
1556 std::ostringstream os;
1557 WriteFmtpHeader(codec.id, &os);
1558 WriteFmtpParameters(fmtp_parameters, &os);
1559 AddLine(os.str(), message);
1560 return;
1561}
1562
1563template <class T>
1564void AddRtcpFbLines(const T& codec, std::string* message) {
1565 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1566 codec.feedback_params.params().begin();
1567 iter != codec.feedback_params.params().end(); ++iter) {
1568 std::ostringstream os;
1569 WriteRtcpFbHeader(codec.id, &os);
1570 os << " " << iter->id();
1571 if (!iter->param().empty()) {
1572 os << " " << iter->param();
1573 }
1574 AddLine(os.str(), message);
1575 }
1576}
1577
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001578bool AddSctpDataCodec(DataContentDescription* media_desc,
1579 int sctp_port) {
1580 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1581 return ParseFailed("",
1582 "Can't have multiple sctp port attributes.",
1583 NULL);
1584 }
1585 // Add the SCTP Port number as a pseudo-codec "port" parameter
1586 cricket::DataCodec codec_port(
1587 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1588 0);
1589 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1590 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1591 << sctp_port;
1592 media_desc->AddCodec(codec_port);
1593 return true;
1594}
1595
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001596bool GetMinValue(const std::vector<int>& values, int* value) {
1597 if (values.empty()) {
1598 return false;
1599 }
1600 std::vector<int>::const_iterator found =
1601 std::min_element(values.begin(), values.end());
1602 *value = *found;
1603 return true;
1604}
1605
1606bool GetParameter(const std::string& name,
1607 const cricket::CodecParameterMap& params, int* value) {
1608 std::map<std::string, std::string>::const_iterator found =
1609 params.find(name);
1610 if (found == params.end()) {
1611 return false;
1612 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001613 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001614 return false;
1615 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001616 return true;
1617}
1618
1619void BuildRtpMap(const MediaContentDescription* media_desc,
1620 const MediaType media_type,
1621 std::string* message) {
1622 ASSERT(message != NULL);
1623 ASSERT(media_desc != NULL);
1624 std::ostringstream os;
1625 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1626 const VideoContentDescription* video_desc =
1627 static_cast<const VideoContentDescription*>(media_desc);
1628 for (std::vector<cricket::VideoCodec>::const_iterator it =
1629 video_desc->codecs().begin();
1630 it != video_desc->codecs().end(); ++it) {
1631 // RFC 4566
1632 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1633 // [/<encodingparameters>]
1634 if (it->id != kWildcardPayloadType) {
1635 InitAttrLine(kAttributeRtpmap, &os);
1636 os << kSdpDelimiterColon << it->id << " " << it->name
1637 << "/" << kDefaultVideoClockrate;
1638 AddLine(os.str(), message);
1639 }
1640 AddRtcpFbLines(*it, message);
1641 AddFmtpLine(*it, message);
1642 }
1643 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1644 const AudioContentDescription* audio_desc =
1645 static_cast<const AudioContentDescription*>(media_desc);
1646 std::vector<int> ptimes;
1647 std::vector<int> maxptimes;
1648 int max_minptime = 0;
1649 for (std::vector<cricket::AudioCodec>::const_iterator it =
1650 audio_desc->codecs().begin();
1651 it != audio_desc->codecs().end(); ++it) {
1652 ASSERT(!it->name.empty());
1653 // RFC 4566
1654 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1655 // [/<encodingparameters>]
1656 InitAttrLine(kAttributeRtpmap, &os);
1657 os << kSdpDelimiterColon << it->id << " ";
1658 os << it->name << "/" << it->clockrate;
1659 if (it->channels != 1) {
1660 os << "/" << it->channels;
1661 }
1662 AddLine(os.str(), message);
1663 AddRtcpFbLines(*it, message);
1664 AddFmtpLine(*it, message);
1665 int minptime = 0;
1666 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1667 max_minptime = std::max(minptime, max_minptime);
1668 }
1669 int ptime;
1670 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1671 ptimes.push_back(ptime);
1672 }
1673 int maxptime;
1674 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1675 maxptimes.push_back(maxptime);
1676 }
1677 }
1678 // Populate the maxptime attribute with the smallest maxptime of all codecs
1679 // under the same m-line.
1680 int min_maxptime = INT_MAX;
1681 if (GetMinValue(maxptimes, &min_maxptime)) {
1682 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1683 }
1684 ASSERT(min_maxptime > max_minptime);
1685 // Populate the ptime attribute with the smallest ptime or the largest
1686 // minptime, whichever is the largest, for all codecs under the same m-line.
1687 int ptime = INT_MAX;
1688 if (GetMinValue(ptimes, &ptime)) {
1689 ptime = std::min(ptime, min_maxptime);
1690 ptime = std::max(ptime, max_minptime);
1691 AddAttributeLine(kCodecParamPTime, ptime, message);
1692 }
1693 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1694 const DataContentDescription* data_desc =
1695 static_cast<const DataContentDescription*>(media_desc);
1696 for (std::vector<cricket::DataCodec>::const_iterator it =
1697 data_desc->codecs().begin();
1698 it != data_desc->codecs().end(); ++it) {
1699 // RFC 4566
1700 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1701 // [/<encodingparameters>]
1702 InitAttrLine(kAttributeRtpmap, &os);
1703 os << kSdpDelimiterColon << it->id << " "
1704 << it->name << "/" << it->clockrate;
1705 AddLine(os.str(), message);
1706 }
1707 }
1708}
1709
1710void BuildCandidate(const std::vector<Candidate>& candidates,
1711 std::string* message) {
1712 std::ostringstream os;
1713
1714 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1715 it != candidates.end(); ++it) {
1716 // RFC 5245
1717 // a=candidate:<foundation> <component-id> <transport> <priority>
1718 // <connection-address> <port> typ <candidate-types>
1719 // [raddr <connection-address>] [rport <port>]
1720 // *(SP extension-att-name SP extension-att-value)
1721 std::string type;
1722 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1723 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1724 type = kCandidateHost;
1725 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1726 type = kCandidateSrflx;
1727 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1728 type = kCandidateRelay;
1729 } else {
1730 ASSERT(false);
Peter Thatcher019087f2015-04-28 09:06:26 -07001731 // Never write out candidates if we don't know the type.
1732 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001733 }
1734
1735 InitAttrLine(kAttributeCandidate, &os);
1736 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001737 << it->foundation() << " "
1738 << it->component() << " "
1739 << it->protocol() << " "
1740 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001741 << it->address().ipaddr().ToString() << " "
1742 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001743 << kAttributeCandidateTyp << " "
1744 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001745
1746 // Related address
1747 if (!it->related_address().IsNil()) {
1748 os << kAttributeCandidateRaddr << " "
1749 << it->related_address().ipaddr().ToString() << " "
1750 << kAttributeCandidateRport << " "
1751 << it->related_address().PortAsString() << " ";
1752 }
1753
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001754 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001755 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001756 }
1757
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001758 // Extensions
1759 os << kAttributeCandidateGeneration << " " << it->generation();
1760
1761 AddLine(os.str(), message);
1762 }
1763}
1764
1765void BuildIceOptions(const std::vector<std::string>& transport_options,
1766 std::string* message) {
1767 if (!transport_options.empty()) {
1768 std::ostringstream os;
1769 InitAttrLine(kAttributeIceOption, &os);
1770 os << kSdpDelimiterColon << transport_options[0];
1771 for (size_t i = 1; i < transport_options.size(); ++i) {
1772 os << kSdpDelimiterSpace << transport_options[i];
1773 }
1774 AddLine(os.str(), message);
1775 }
1776}
1777
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001778bool IsRtp(const std::string& protocol) {
1779 return protocol.empty() ||
1780 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1781}
1782
1783bool IsDtlsSctp(const std::string& protocol) {
1784 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001785 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001786}
1787
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001788bool ParseSessionDescription(const std::string& message, size_t* pos,
1789 std::string* session_id,
1790 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001791 TransportDescription* session_td,
1792 RtpHeaderExtensions* session_extmaps,
1793 cricket::SessionDescription* desc,
1794 SdpParseError* error) {
1795 std::string line;
1796
deadbeefc80741f2015-10-22 13:14:45 -07001797 desc->set_msid_supported(false);
1798
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001799 // RFC 4566
1800 // v= (protocol version)
1801 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1802 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1803 std::string(), error);
1804 }
1805 // RFC 4566
1806 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1807 // <unicast-address>
1808 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1809 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1810 std::string(), error);
1811 }
1812 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001813 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001814 kSdpDelimiterSpace, &fields);
1815 const size_t expected_fields = 6;
1816 if (fields.size() != expected_fields) {
1817 return ParseFailedExpectFieldNum(line, expected_fields, error);
1818 }
1819 *session_id = fields[1];
1820 *session_version = fields[2];
1821
1822 // RFC 4566
1823 // s= (session name)
1824 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1825 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1826 std::string(), error);
1827 }
1828
1829 // Optional lines
1830 // Those are the optional lines, so shouldn't return false if not present.
1831 // RFC 4566
1832 // i=* (session information)
1833 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1834
1835 // RFC 4566
1836 // u=* (URI of description)
1837 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1838
1839 // RFC 4566
1840 // e=* (email address)
1841 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1842
1843 // RFC 4566
1844 // p=* (phone number)
1845 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1846
1847 // RFC 4566
1848 // c=* (connection information -- not required if included in
1849 // all media)
1850 GetLineWithType(message, pos, &line, kLineTypeConnection);
1851
1852 // RFC 4566
1853 // b=* (zero or more bandwidth information lines)
1854 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1855 // By pass zero or more b lines.
1856 }
1857
1858 // RFC 4566
1859 // One or more time descriptions ("t=" and "r=" lines; see below)
1860 // t= (time the session is active)
1861 // r=* (zero or more repeat times)
1862 // Ensure there's at least one time description
1863 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1864 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1865 error);
1866 }
1867
1868 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1869 // By pass zero or more r lines.
1870 }
1871
1872 // Go through the rest of the time descriptions
1873 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1874 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1875 // By pass zero or more r lines.
1876 }
1877 }
1878
1879 // RFC 4566
1880 // z=* (time zone adjustments)
1881 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1882
1883 // RFC 4566
1884 // k=* (encryption key)
1885 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1886
1887 // RFC 4566
1888 // a=* (zero or more session attribute lines)
1889 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1890 if (HasAttribute(line, kAttributeGroup)) {
1891 if (!ParseGroupAttribute(line, desc, error)) {
1892 return false;
1893 }
1894 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1895 if (!GetValue(line, kAttributeIceUfrag,
1896 &(session_td->ice_ufrag), error)) {
1897 return false;
1898 }
1899 } else if (HasAttribute(line, kAttributeIcePwd)) {
1900 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1901 return false;
1902 }
1903 } else if (HasAttribute(line, kAttributeIceLite)) {
1904 session_td->ice_mode = cricket::ICEMODE_LITE;
1905 } else if (HasAttribute(line, kAttributeIceOption)) {
1906 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1907 return false;
1908 }
1909 } else if (HasAttribute(line, kAttributeFingerprint)) {
1910 if (session_td->identity_fingerprint.get()) {
1911 return ParseFailed(
1912 line,
1913 "Can't have multiple fingerprint attributes at the same level.",
1914 error);
1915 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001916 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001917 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1918 return false;
1919 }
1920 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001921 } else if (HasAttribute(line, kAttributeSetup)) {
1922 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1923 return false;
1924 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001925 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1926 std::string semantics;
1927 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1928 return false;
1929 }
deadbeefc80741f2015-10-22 13:14:45 -07001930 desc->set_msid_supported(
1931 CaseInsensitiveFind(semantics, kMediaStreamSemantic));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001932 } else if (HasAttribute(line, kAttributeExtmap)) {
1933 RtpHeaderExtension extmap;
1934 if (!ParseExtmap(line, &extmap, error)) {
1935 return false;
1936 }
1937 session_extmaps->push_back(extmap);
1938 }
1939 }
1940
1941 return true;
1942}
1943
1944bool ParseGroupAttribute(const std::string& line,
1945 cricket::SessionDescription* desc,
1946 SdpParseError* error) {
1947 ASSERT(desc != NULL);
1948
1949 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1950 // a=group:BUNDLE video voice
1951 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001952 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001953 kSdpDelimiterSpace, &fields);
1954 std::string semantics;
1955 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1956 return false;
1957 }
1958 cricket::ContentGroup group(semantics);
1959 for (size_t i = 1; i < fields.size(); ++i) {
1960 group.AddContentName(fields[i]);
1961 }
1962 desc->AddGroup(group);
1963 return true;
1964}
1965
1966static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001967 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001968 SdpParseError* error) {
1969 if (!IsLineType(line, kLineTypeAttributes) ||
1970 !HasAttribute(line, kAttributeFingerprint)) {
1971 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1972 kAttributeFingerprint, error);
1973 }
1974
1975 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001976 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977 kSdpDelimiterSpace, &fields);
1978 const size_t expected_fields = 2;
1979 if (fields.size() != expected_fields) {
1980 return ParseFailedExpectFieldNum(line, expected_fields, error);
1981 }
1982
1983 // The first field here is "fingerprint:<hash>.
1984 std::string algorithm;
1985 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
1986 return false;
1987 }
1988
1989 // Downcase the algorithm. Note that we don't need to downcase the
1990 // fingerprint because hex_decode can handle upper-case.
1991 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
1992 ::tolower);
1993
1994 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001995 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001996 algorithm, fields[1]);
1997 if (!*fingerprint) {
1998 return ParseFailed(line,
1999 "Failed to create fingerprint from the digest.",
2000 error);
2001 }
2002
2003 return true;
2004}
2005
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002006static bool ParseDtlsSetup(const std::string& line,
2007 cricket::ConnectionRole* role,
2008 SdpParseError* error) {
2009 // setup-attr = "a=setup:" role
2010 // role = "active" / "passive" / "actpass" / "holdconn"
2011 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002012 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002013 const size_t expected_fields = 2;
2014 if (fields.size() != expected_fields) {
2015 return ParseFailedExpectFieldNum(line, expected_fields, error);
2016 }
2017 std::string role_str = fields[1];
2018 if (!cricket::StringToConnectionRole(role_str, role)) {
2019 return ParseFailed(line, "Invalid attribute value.", error);
2020 }
2021 return true;
2022}
2023
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002024// RFC 3551
2025// PT encoding media type clock rate channels
2026// name (Hz)
2027// 0 PCMU A 8,000 1
2028// 1 reserved A
2029// 2 reserved A
2030// 3 GSM A 8,000 1
2031// 4 G723 A 8,000 1
2032// 5 DVI4 A 8,000 1
2033// 6 DVI4 A 16,000 1
2034// 7 LPC A 8,000 1
2035// 8 PCMA A 8,000 1
2036// 9 G722 A 8,000 1
2037// 10 L16 A 44,100 2
2038// 11 L16 A 44,100 1
2039// 12 QCELP A 8,000 1
2040// 13 CN A 8,000 1
2041// 14 MPA A 90,000 (see text)
2042// 15 G728 A 8,000 1
2043// 16 DVI4 A 11,025 1
2044// 17 DVI4 A 22,050 1
2045// 18 G729 A 8,000 1
2046struct StaticPayloadAudioCodec {
2047 const char* name;
2048 int clockrate;
2049 int channels;
2050};
2051static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2052 { "PCMU", 8000, 1 },
2053 { "reserved", 0, 0 },
2054 { "reserved", 0, 0 },
2055 { "GSM", 8000, 1 },
2056 { "G723", 8000, 1 },
2057 { "DVI4", 8000, 1 },
2058 { "DVI4", 16000, 1 },
2059 { "LPC", 8000, 1 },
2060 { "PCMA", 8000, 1 },
2061 { "G722", 8000, 1 },
2062 { "L16", 44100, 2 },
2063 { "L16", 44100, 1 },
2064 { "QCELP", 8000, 1 },
2065 { "CN", 8000, 1 },
2066 { "MPA", 90000, 1 },
2067 { "G728", 8000, 1 },
2068 { "DVI4", 11025, 1 },
2069 { "DVI4", 22050, 1 },
2070 { "G729", 8000, 1 },
2071};
2072
2073void MaybeCreateStaticPayloadAudioCodecs(
2074 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2075 if (!media_desc) {
2076 return;
2077 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002078 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002079 std::vector<int>::const_iterator it = fmts.begin();
2080 bool add_new_codec = false;
2081 for (; it != fmts.end(); ++it) {
2082 int payload_type = *it;
2083 if (!media_desc->HasCodec(payload_type) &&
2084 payload_type >= 0 &&
2085 payload_type < ARRAY_SIZE(kStaticPayloadAudioCodecs)) {
2086 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2087 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2088 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2089 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2090 clock_rate, 0, channels,
2091 preference));
2092 add_new_codec = true;
2093 }
2094 --preference;
2095 }
2096 if (add_new_codec) {
2097 media_desc->SortCodecs();
2098 }
2099}
2100
2101template <class C>
2102static C* ParseContentDescription(const std::string& message,
2103 const MediaType media_type,
2104 int mline_index,
2105 const std::string& protocol,
2106 const std::vector<int>& codec_preference,
2107 size_t* pos,
2108 std::string* content_name,
2109 TransportDescription* transport,
2110 std::vector<JsepIceCandidate*>* candidates,
2111 webrtc::SdpParseError* error) {
2112 C* media_desc = new C();
2113 switch (media_type) {
2114 case cricket::MEDIA_TYPE_AUDIO:
2115 *content_name = cricket::CN_AUDIO;
2116 break;
2117 case cricket::MEDIA_TYPE_VIDEO:
2118 *content_name = cricket::CN_VIDEO;
2119 break;
2120 case cricket::MEDIA_TYPE_DATA:
2121 *content_name = cricket::CN_DATA;
2122 break;
2123 default:
2124 ASSERT(false);
2125 break;
2126 }
2127 if (!ParseContent(message, media_type, mline_index, protocol,
2128 codec_preference, pos, content_name,
2129 media_desc, transport, candidates, error)) {
2130 delete media_desc;
2131 return NULL;
2132 }
2133 // Sort the codecs according to the m-line fmt list.
2134 media_desc->SortCodecs();
2135 return media_desc;
2136}
2137
2138bool ParseMediaDescription(const std::string& message,
2139 const TransportDescription& session_td,
2140 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002141 size_t* pos,
2142 cricket::SessionDescription* desc,
2143 std::vector<JsepIceCandidate*>* candidates,
2144 SdpParseError* error) {
2145 ASSERT(desc != NULL);
2146 std::string line;
2147 int mline_index = -1;
2148
2149 // Zero or more media descriptions
2150 // RFC 4566
2151 // m=<media> <port> <proto> <fmt>
2152 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2153 ++mline_index;
2154
2155 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002156 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002157 kSdpDelimiterSpace, &fields);
2158 const size_t expected_min_fields = 4;
2159 if (fields.size() < expected_min_fields) {
2160 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2161 }
2162 bool rejected = false;
2163 // RFC 3264
2164 // To reject an offered stream, the port number in the corresponding stream
2165 // in the answer MUST be set to zero.
2166 if (fields[1] == kMediaPortRejected) {
2167 rejected = true;
2168 }
2169
2170 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002171
2172 // <fmt>
2173 std::vector<int> codec_preference;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002174 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002175 for (size_t j = 3 ; j < fields.size(); ++j) {
2176 // TODO(wu): Remove when below bug is fixed.
2177 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002178 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002179 continue;
2180 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002181
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002182 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002183 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002184 return false;
2185 }
2186 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002187 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002188 }
2189
2190 // Make a temporary TransportDescription based on |session_td|.
2191 // Some of this gets overwritten by ParseContent.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002192 TransportDescription transport(session_td.transport_options,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002193 session_td.ice_ufrag,
2194 session_td.ice_pwd,
2195 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002196 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002197 session_td.identity_fingerprint.get(),
2198 Candidates());
2199
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002200 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002201 std::string content_name;
2202 if (HasAttribute(line, kMediaTypeVideo)) {
2203 content.reset(ParseContentDescription<VideoContentDescription>(
2204 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2205 codec_preference, pos, &content_name,
2206 &transport, candidates, error));
2207 } else if (HasAttribute(line, kMediaTypeAudio)) {
2208 content.reset(ParseContentDescription<AudioContentDescription>(
2209 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2210 codec_preference, pos, &content_name,
2211 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002212 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002213 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002214 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002215 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2216 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002217 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002218 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002219
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002220 int p;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002221 if (data_desc && IsDtlsSctp(protocol) && rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002222 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002223 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002224 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225 } else {
2226 LOG(LS_WARNING) << "Unsupported media type: " << line;
2227 continue;
2228 }
2229 if (!content.get()) {
2230 // ParseContentDescription returns NULL if failed.
2231 return false;
2232 }
2233
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002234 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002235 // Set the extmap.
2236 if (!session_extmaps.empty() &&
2237 !content->rtp_header_extensions().empty()) {
2238 return ParseFailed("",
2239 "The a=extmap MUST be either all session level or "
2240 "all media level.",
2241 error);
2242 }
2243 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2244 content->AddRtpHeaderExtension(session_extmaps[i]);
2245 }
2246 }
2247 content->set_protocol(protocol);
2248 desc->AddContent(content_name,
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002249 IsDtlsSctp(protocol) ? cricket::NS_JINGLE_DRAFT_SCTP :
2250 cricket::NS_JINGLE_RTP,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002251 rejected,
2252 content.release());
2253 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2254 TransportInfo transport_info(content_name, transport);
2255
2256 if (!desc->AddTransportInfo(transport_info)) {
2257 std::ostringstream description;
2258 description << "Failed to AddTransportInfo with content name: "
2259 << content_name;
2260 return ParseFailed("", description.str(), error);
2261 }
2262 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002263
2264 size_t end_of_message = message.size();
2265 if (mline_index == -1 && *pos != end_of_message) {
2266 ParseFailed(message, *pos, "Expects m line.", error);
2267 return false;
2268 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002269 return true;
2270}
2271
2272bool VerifyCodec(const cricket::Codec& codec) {
2273 // Codec has not been populated correctly unless the name has been set. This
2274 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2275 // have a corresponding "rtpmap" line.
2276 cricket::Codec default_codec;
2277 return default_codec.name != codec.name;
2278}
2279
2280bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2281 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2282 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2283 iter != codecs.end(); ++iter) {
2284 if (!VerifyCodec(*iter)) {
2285 return false;
2286 }
2287 }
2288 return true;
2289}
2290
2291bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2292 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2293 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2294 iter != codecs.end(); ++iter) {
2295 if (!VerifyCodec(*iter)) {
2296 return false;
2297 }
2298 }
2299 return true;
2300}
2301
2302void AddParameters(const cricket::CodecParameterMap& parameters,
2303 cricket::Codec* codec) {
2304 for (cricket::CodecParameterMap::const_iterator iter =
2305 parameters.begin(); iter != parameters.end(); ++iter) {
2306 codec->SetParam(iter->first, iter->second);
2307 }
2308}
2309
2310void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2311 cricket::Codec* codec) {
2312 codec->AddFeedbackParam(feedback_param);
2313}
2314
2315void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2316 cricket::Codec* codec) {
2317 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2318 feedback_params.params().begin();
2319 iter != feedback_params.params().end(); ++iter) {
2320 codec->AddFeedbackParam(*iter);
2321 }
2322}
2323
2324// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002325// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002326// with that payload type.
2327template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002328T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2329 T ret_val;
2330 if (!FindCodecById(codecs, payload_type, &ret_val)) {
2331 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002332 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002333 return ret_val;
2334}
2335
2336// Updates or creates a new codec entry in the audio description.
2337template <class T, class U>
2338void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2339 T* desc = static_cast<T*>(content_desc);
2340 std::vector<U> codecs = desc->codecs();
2341 bool found = false;
2342
2343 typename std::vector<U>::iterator iter;
2344 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2345 if (iter->id == codec.id) {
2346 *iter = codec;
2347 found = true;
2348 break;
2349 }
2350 }
2351 if (!found) {
2352 desc->AddCodec(codec);
2353 return;
2354 }
2355 desc->set_codecs(codecs);
2356}
2357
2358// Adds or updates existing codec corresponding to |payload_type| according
2359// to |parameters|.
2360template <class T, class U>
2361void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2362 const cricket::CodecParameterMap& parameters) {
2363 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002364 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2365 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002366 AddParameters(parameters, &new_codec);
2367 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2368}
2369
2370// Adds or updates existing codec corresponding to |payload_type| according
2371// to |feedback_param|.
2372template <class T, class U>
2373void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2374 const cricket::FeedbackParam& feedback_param) {
2375 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002376 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2377 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378 AddFeedbackParameter(feedback_param, &new_codec);
2379 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2380}
2381
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002382template <class T>
2383bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2384 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002385 if (iter->id == kWildcardPayloadType) {
2386 *wildcard_codec = *iter;
2387 codecs->erase(iter);
2388 return true;
2389 }
2390 }
2391 return false;
2392}
2393
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002394template<class T>
2395void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2396 auto codecs = desc->codecs();
2397 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002398 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2399 return;
2400 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002401 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002402 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2403 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002404 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002405}
2406
2407void AddAudioAttribute(const std::string& name, const std::string& value,
2408 AudioContentDescription* audio_desc) {
2409 if (value.empty()) {
2410 return;
2411 }
2412 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2413 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2414 iter != codecs.end(); ++iter) {
2415 iter->params[name] = value;
2416 }
2417 audio_desc->set_codecs(codecs);
2418}
2419
2420bool ParseContent(const std::string& message,
2421 const MediaType media_type,
2422 int mline_index,
2423 const std::string& protocol,
2424 const std::vector<int>& codec_preference,
2425 size_t* pos,
2426 std::string* content_name,
2427 MediaContentDescription* media_desc,
2428 TransportDescription* transport,
2429 std::vector<JsepIceCandidate*>* candidates,
2430 SdpParseError* error) {
2431 ASSERT(media_desc != NULL);
2432 ASSERT(content_name != NULL);
2433 ASSERT(transport != NULL);
2434
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002435 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2436 MaybeCreateStaticPayloadAudioCodecs(
2437 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2438 }
2439
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002440 // The media level "ice-ufrag" and "ice-pwd".
2441 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2442 Candidates candidates_orig;
2443 std::string line;
2444 std::string mline_id;
2445 // Tracks created out of the ssrc attributes.
2446 StreamParamsVec tracks;
2447 SsrcInfoVec ssrc_infos;
2448 SsrcGroupVec ssrc_groups;
2449 std::string maxptime_as_string;
2450 std::string ptime_as_string;
2451
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002452 // Loop until the next m line
2453 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2454 if (!GetLine(message, pos, &line)) {
2455 if (*pos >= message.size()) {
2456 break; // Done parsing
2457 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002458 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002459 }
2460 }
2461
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002462 // RFC 4566
2463 // b=* (zero or more bandwidth information lines)
2464 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2465 std::string bandwidth;
2466 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2467 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2468 return false;
2469 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002470 int b = 0;
2471 if (!GetValueFromString(line, bandwidth, &b, error)) {
2472 return false;
2473 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002474 // We should never use more than the default bandwidth for RTP-based
2475 // data channels. Don't allow SDP to set the bandwidth, because
2476 // that would give JS the opportunity to "break the Internet".
2477 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2478 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2479 b > cricket::kDataMaxBandwidth / 1000) {
2480 std::ostringstream description;
2481 description << "RTP-based data channels may not send more than "
2482 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2483 return ParseFailed(line, description.str(), error);
2484 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002485 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002486 }
2487 }
2488 continue;
2489 }
2490
2491 if (!IsLineType(line, kLineTypeAttributes)) {
2492 // TODO: Handle other lines if needed.
2493 LOG(LS_INFO) << "Ignored line: " << line;
2494 continue;
2495 }
2496
2497 // Handle attributes common to SCTP and RTP.
2498 if (HasAttribute(line, kAttributeMid)) {
2499 // RFC 3388
2500 // mid-attribute = "a=mid:" identification-tag
2501 // identification-tag = token
2502 // Use the mid identification-tag as the content name.
2503 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2504 return false;
2505 }
2506 *content_name = mline_id;
2507 } else if (HasAttribute(line, kAttributeCandidate)) {
2508 Candidate candidate;
2509 if (!ParseCandidate(line, &candidate, error, false)) {
2510 return false;
2511 }
2512 candidates_orig.push_back(candidate);
2513 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2514 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2515 return false;
2516 }
2517 } else if (HasAttribute(line, kAttributeIcePwd)) {
2518 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2519 return false;
2520 }
2521 } else if (HasAttribute(line, kAttributeIceOption)) {
2522 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2523 return false;
2524 }
2525 } else if (HasAttribute(line, kAttributeFmtp)) {
2526 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2527 return false;
2528 }
2529 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002530 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002531
2532 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2533 return false;
2534 }
2535 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002536 } else if (HasAttribute(line, kAttributeSetup)) {
2537 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2538 return false;
2539 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002540 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002541 int sctp_port;
2542 if (!ParseSctpPort(line, &sctp_port, error)) {
2543 return false;
2544 }
2545 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2546 sctp_port)) {
2547 return false;
2548 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002549 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002550 //
2551 // RTP specific attrubtes
2552 //
2553 if (HasAttribute(line, kAttributeRtcpMux)) {
2554 media_desc->set_rtcp_mux(true);
2555 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2556 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2557 return false;
2558 }
2559 } else if (HasAttribute(line, kAttributeSsrc)) {
2560 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2561 return false;
2562 }
2563 } else if (HasAttribute(line, kAttributeCrypto)) {
2564 if (!ParseCryptoAttribute(line, media_desc, error)) {
2565 return false;
2566 }
2567 } else if (HasAttribute(line, kAttributeRtpmap)) {
2568 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2569 media_desc, error)) {
2570 return false;
2571 }
2572 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2573 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2574 return false;
2575 }
2576 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2577 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2578 return false;
2579 }
2580 } else if (HasAttribute(line, kCodecParamPTime)) {
2581 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2582 return false;
2583 }
2584 } else if (HasAttribute(line, kAttributeSendOnly)) {
2585 media_desc->set_direction(cricket::MD_SENDONLY);
2586 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2587 media_desc->set_direction(cricket::MD_RECVONLY);
2588 } else if (HasAttribute(line, kAttributeInactive)) {
2589 media_desc->set_direction(cricket::MD_INACTIVE);
2590 } else if (HasAttribute(line, kAttributeSendRecv)) {
2591 media_desc->set_direction(cricket::MD_SENDRECV);
2592 } else if (HasAttribute(line, kAttributeExtmap)) {
2593 RtpHeaderExtension extmap;
2594 if (!ParseExtmap(line, &extmap, error)) {
2595 return false;
2596 }
2597 media_desc->AddRtpHeaderExtension(extmap);
2598 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2599 // Experimental attribute. Conference mode activates more aggressive
2600 // AEC and NS settings.
2601 // TODO: expose API to set these directly.
2602 std::string flag_value;
2603 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2604 return false;
2605 }
2606 if (flag_value.compare(kValueConference) == 0)
2607 media_desc->set_conference_mode(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002608 }
2609 } else {
2610 // Only parse lines that we are interested of.
2611 LOG(LS_INFO) << "Ignored line: " << line;
2612 continue;
2613 }
2614 }
2615
2616 // Create tracks from the |ssrc_infos|.
2617 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2618
2619 // Add the ssrc group to the track.
2620 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2621 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2622 if (ssrc_group->ssrcs.empty()) {
2623 continue;
2624 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002625 uint32_t ssrc = ssrc_group->ssrcs.front();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002626 for (StreamParamsVec::iterator track = tracks.begin();
2627 track != tracks.end(); ++track) {
2628 if (track->has_ssrc(ssrc)) {
2629 track->ssrc_groups.push_back(*ssrc_group);
2630 }
2631 }
2632 }
2633
2634 // Add the new tracks to the |media_desc|.
2635 for (StreamParamsVec::iterator track = tracks.begin();
2636 track != tracks.end(); ++track) {
2637 media_desc->AddStream(*track);
2638 }
2639
2640 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2641 AudioContentDescription* audio_desc =
2642 static_cast<AudioContentDescription*>(media_desc);
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002643 UpdateFromWildcardCodecs(audio_desc);
2644
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002645 // Verify audio codec ensures that no audio codec has been populated with
2646 // only fmtp.
2647 if (!VerifyAudioCodecs(audio_desc)) {
2648 return ParseFailed("Failed to parse audio codecs correctly.", error);
2649 }
2650 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2651 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2652 }
2653
2654 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002655 VideoContentDescription* video_desc =
2656 static_cast<VideoContentDescription*>(media_desc);
2657 UpdateFromWildcardCodecs(video_desc);
2658 // Verify video codec ensures that no video codec has been populated with
2659 // only rtcp-fb.
2660 if (!VerifyVideoCodecs(video_desc)) {
2661 return ParseFailed("Failed to parse video codecs correctly.", error);
2662 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002663 }
2664
2665 // RFC 5245
2666 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2667 for (Candidates::iterator it = candidates_orig.begin();
2668 it != candidates_orig.end(); ++it) {
2669 ASSERT((*it).username().empty());
2670 (*it).set_username(transport->ice_ufrag);
2671 ASSERT((*it).password().empty());
2672 (*it).set_password(transport->ice_pwd);
2673 candidates->push_back(
2674 new JsepIceCandidate(mline_id, mline_index, *it));
2675 }
2676 return true;
2677}
2678
2679bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2680 SdpParseError* error) {
2681 ASSERT(ssrc_infos != NULL);
2682 // RFC 5576
2683 // a=ssrc:<ssrc-id> <attribute>
2684 // a=ssrc:<ssrc-id> <attribute>:<value>
2685 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07002686 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2687 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002688 const size_t expected_fields = 2;
2689 return ParseFailedExpectFieldNum(line, expected_fields, error);
2690 }
2691
2692 // ssrc:<ssrc-id>
2693 std::string ssrc_id_s;
2694 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2695 return false;
2696 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002697 uint32_t ssrc_id = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002698 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2699 return false;
2700 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002701
2702 std::string attribute;
2703 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07002704 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002705 std::ostringstream description;
2706 description << "Failed to get the ssrc attribute value from " << field2
2707 << ". Expected format <attribute>:<value>.";
2708 return ParseFailed(line, description.str(), error);
2709 }
2710
2711 // Check if there's already an item for this |ssrc_id|. Create a new one if
2712 // there isn't.
2713 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2714 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2715 if (ssrc_info->ssrc_id == ssrc_id) {
2716 break;
2717 }
2718 }
2719 if (ssrc_info == ssrc_infos->end()) {
2720 SsrcInfo info;
2721 info.ssrc_id = ssrc_id;
2722 ssrc_infos->push_back(info);
2723 ssrc_info = ssrc_infos->end() - 1;
2724 }
2725
2726 // Store the info to the |ssrc_info|.
2727 if (attribute == kSsrcAttributeCname) {
2728 // RFC 5576
2729 // cname:<value>
2730 ssrc_info->cname = value;
2731 } else if (attribute == kSsrcAttributeMsid) {
2732 // draft-alvestrand-mmusic-msid-00
2733 // "msid:" identifier [ " " appdata ]
2734 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002735 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002736 if (fields.size() < 1 || fields.size() > 2) {
2737 return ParseFailed(line,
2738 "Expected format \"msid:<identifier>[ <appdata>]\".",
2739 error);
2740 }
2741 ssrc_info->msid_identifier = fields[0];
2742 if (fields.size() == 2) {
2743 ssrc_info->msid_appdata = fields[1];
2744 }
2745 } else if (attribute == kSsrcAttributeMslabel) {
2746 // draft-alvestrand-rtcweb-mid-01
2747 // mslabel:<value>
2748 ssrc_info->mslabel = value;
2749 } else if (attribute == kSSrcAttributeLabel) {
2750 // The label isn't defined.
2751 // label:<value>
2752 ssrc_info->label = value;
2753 }
2754 return true;
2755}
2756
2757bool ParseSsrcGroupAttribute(const std::string& line,
2758 SsrcGroupVec* ssrc_groups,
2759 SdpParseError* error) {
2760 ASSERT(ssrc_groups != NULL);
2761 // RFC 5576
2762 // a=ssrc-group:<semantics> <ssrc-id> ...
2763 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002764 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002765 kSdpDelimiterSpace, &fields);
2766 const size_t expected_min_fields = 2;
2767 if (fields.size() < expected_min_fields) {
2768 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2769 }
2770 std::string semantics;
2771 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2772 return false;
2773 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002774 std::vector<uint32_t> ssrcs;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002775 for (size_t i = 1; i < fields.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02002776 uint32_t ssrc = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002777 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2778 return false;
2779 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002780 ssrcs.push_back(ssrc);
2781 }
2782 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2783 return true;
2784}
2785
2786bool ParseCryptoAttribute(const std::string& line,
2787 MediaContentDescription* media_desc,
2788 SdpParseError* error) {
2789 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002790 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002791 kSdpDelimiterSpace, &fields);
2792 // RFC 4568
2793 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2794 const size_t expected_min_fields = 3;
2795 if (fields.size() < expected_min_fields) {
2796 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2797 }
2798 std::string tag_value;
2799 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2800 return false;
2801 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002802 int tag = 0;
2803 if (!GetValueFromString(line, tag_value, &tag, error)) {
2804 return false;
2805 }
jbauch083b73f2015-07-16 02:46:32 -07002806 const std::string& crypto_suite = fields[1];
2807 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002808 std::string session_params;
2809 if (fields.size() > 3) {
2810 session_params = fields[3];
2811 }
2812 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2813 session_params));
2814 return true;
2815}
2816
2817// Updates or creates a new codec entry in the audio description with according
2818// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2819void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2820 int bitrate, int channels, int preference,
2821 AudioContentDescription* audio_desc) {
2822 // Codec may already be populated with (only) optional parameters
2823 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002824 cricket::AudioCodec codec =
2825 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002826 codec.name = name;
2827 codec.clockrate = clockrate;
2828 codec.bitrate = bitrate;
2829 codec.channels = channels;
2830 codec.preference = preference;
2831 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2832 codec);
2833}
2834
2835// Updates or creates a new codec entry in the video description according to
2836// |name|, |width|, |height|, |framerate| and |preference|.
2837void UpdateCodec(int payload_type, const std::string& name, int width,
2838 int height, int framerate, int preference,
2839 VideoContentDescription* video_desc) {
2840 // Codec may already be populated with (only) optional parameters
2841 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002842 cricket::VideoCodec codec =
2843 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002844 codec.name = name;
2845 codec.width = width;
2846 codec.height = height;
2847 codec.framerate = framerate;
2848 codec.preference = preference;
2849 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2850 codec);
2851}
2852
2853bool ParseRtpmapAttribute(const std::string& line,
2854 const MediaType media_type,
2855 const std::vector<int>& codec_preference,
2856 MediaContentDescription* media_desc,
2857 SdpParseError* error) {
2858 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002859 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002860 kSdpDelimiterSpace, &fields);
2861 // RFC 4566
2862 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2863 const size_t expected_min_fields = 2;
2864 if (fields.size() < expected_min_fields) {
2865 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2866 }
2867 std::string payload_type_value;
2868 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2869 return false;
2870 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002871 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002872 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
2873 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002874 return false;
2875 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002876
2877 // Set the preference order depending on the order of the pl type in the
2878 // <fmt> of the m-line.
2879 const int preference = codec_preference.end() -
2880 std::find(codec_preference.begin(), codec_preference.end(),
2881 payload_type);
2882 if (preference == 0) {
2883 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2884 << "<fmt> of the m-line: " << line;
2885 return true;
2886 }
jbauch083b73f2015-07-16 02:46:32 -07002887 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002888 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002889 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002890 // <encoding name>/<clock rate>[/<encodingparameters>]
2891 // 2 mandatory fields
2892 if (codec_params.size() < 2 || codec_params.size() > 3) {
2893 return ParseFailed(line,
2894 "Expected format \"<encoding name>/<clock rate>"
2895 "[/<encodingparameters>]\".",
2896 error);
2897 }
jbauch083b73f2015-07-16 02:46:32 -07002898 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002899 int clock_rate = 0;
2900 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2901 return false;
2902 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002903 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2904 VideoContentDescription* video_desc =
2905 static_cast<VideoContentDescription*>(media_desc);
2906 // TODO: We will send resolution in SDP. For now use
2907 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2908 UpdateCodec(payload_type, encoding_name,
2909 JsepSessionDescription::kMaxVideoCodecWidth,
2910 JsepSessionDescription::kMaxVideoCodecHeight,
2911 JsepSessionDescription::kDefaultVideoCodecFramerate,
2912 preference, video_desc);
2913 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2914 // RFC 4566
2915 // For audio streams, <encoding parameters> indicates the number
2916 // of audio channels. This parameter is OPTIONAL and may be
2917 // omitted if the number of channels is one, provided that no
2918 // additional parameters are needed.
2919 int channels = 1;
2920 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002921 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2922 return false;
2923 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002924 }
2925 int bitrate = 0;
2926 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2927 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2928 // The bandwidth adaptation doesn't always work well, so this code
2929 // sets a fixed target bitrate instead.
2930 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2931 if (clock_rate <= 16000) {
2932 bitrate = kIsacWbDefaultRate;
2933 } else {
2934 bitrate = kIsacSwbDefaultRate;
2935 }
2936 }
2937 AudioContentDescription* audio_desc =
2938 static_cast<AudioContentDescription*>(media_desc);
2939 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2940 preference, audio_desc);
2941 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2942 DataContentDescription* data_desc =
2943 static_cast<DataContentDescription*>(media_desc);
2944 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2945 preference));
2946 }
2947 return true;
2948}
2949
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002950bool ParseFmtpParam(const std::string& line, std::string* parameter,
2951 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07002952 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002953 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2954 return false;
2955 }
2956 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002957 return true;
2958}
2959
2960bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
2961 MediaContentDescription* media_desc,
2962 SdpParseError* error) {
2963 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2964 media_type != cricket::MEDIA_TYPE_VIDEO) {
2965 return true;
2966 }
Donald Curtis0e07f922015-05-15 09:21:23 -07002967
2968 std::string line_payload;
2969 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002970
2971 // RFC 5576
2972 // a=fmtp:<format> <format specific parameters>
2973 // At least two fields, whereas the second one is any of the optional
2974 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07002975 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2976 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002977 ParseFailedExpectMinFieldNum(line, 2, error);
2978 return false;
2979 }
2980
Donald Curtis0e07f922015-05-15 09:21:23 -07002981 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00002982 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07002983 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002984 return false;
2985 }
2986
Donald Curtis0e07f922015-05-15 09:21:23 -07002987 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07002988 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
2989 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07002990 return false;
2991 }
2992
2993 // Parse out format specific parameters.
2994 std::vector<std::string> fields;
2995 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
2996
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002997 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07002998 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07002999 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003000 // Only fmtps with equals are currently supported. Other fmtp types
3001 // should be ignored. Unknown fmtps do not constitute an error.
3002 continue;
3003 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003004
3005 std::string name;
3006 std::string value;
3007 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003008 return false;
3009 }
3010 codec_params[name] = value;
3011 }
3012
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003013 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3014 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003015 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003016 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3017 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003018 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003019 }
3020 return true;
3021}
3022
3023bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3024 MediaContentDescription* media_desc,
3025 SdpParseError* error) {
3026 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3027 media_type != cricket::MEDIA_TYPE_VIDEO) {
3028 return true;
3029 }
3030 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003031 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003032 if (rtcp_fb_fields.size() < 2) {
3033 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3034 }
3035 std::string payload_type_string;
3036 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3037 error)) {
3038 return false;
3039 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003040 int payload_type = kWildcardPayloadType;
3041 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003042 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3043 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003044 return false;
3045 }
3046 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003047 std::string id = rtcp_fb_fields[1];
3048 std::string param = "";
3049 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3050 iter != rtcp_fb_fields.end(); ++iter) {
3051 param.append(*iter);
3052 }
3053 const cricket::FeedbackParam feedback_param(id, param);
3054
3055 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003056 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3057 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003059 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3060 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003061 }
3062 return true;
3063}
3064
3065} // namespace webrtc