blob: 60cc53966c660e55c9d0c67e72e03ef9dc28abe4 [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"
tfarina5237aaf2015-11-10 23:44:30 -080048#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000049#include "webrtc/base/common.h"
50#include "webrtc/base/logging.h"
51#include "webrtc/base/messagedigest.h"
52#include "webrtc/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000053
54using cricket::AudioContentDescription;
55using cricket::Candidate;
56using cricket::Candidates;
57using cricket::ContentDescription;
58using cricket::ContentInfo;
59using cricket::CryptoParams;
60using cricket::DataContentDescription;
61using cricket::ICE_CANDIDATE_COMPONENT_RTP;
62using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
63using cricket::kCodecParamMaxBitrate;
64using cricket::kCodecParamMaxPTime;
65using cricket::kCodecParamMaxQuantization;
66using cricket::kCodecParamMinBitrate;
67using cricket::kCodecParamMinPTime;
68using cricket::kCodecParamPTime;
69using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000070using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071using cricket::kCodecParamStereo;
72using cricket::kCodecParamUseInbandFec;
Minyue Li7100dcd2015-03-27 05:05:59 +010073using cricket::kCodecParamUseDtx;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074using cricket::kCodecParamSctpProtocol;
75using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000076using cricket::kCodecParamMaxAverageBitrate;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000077using cricket::kCodecParamMaxPlaybackRate;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000078using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000079using cricket::MediaContentDescription;
80using cricket::MediaType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000081using cricket::RtpHeaderExtension;
82using cricket::SsrcGroup;
83using cricket::StreamParams;
84using cricket::StreamParamsVec;
85using cricket::TransportDescription;
86using cricket::TransportInfo;
87using cricket::VideoContentDescription;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000088using rtc::SocketAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089
90typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
91
92namespace cricket {
93class SessionDescription;
94}
95
96namespace webrtc {
97
98// Line type
99// RFC 4566
100// An SDP session description consists of a number of lines of text of
101// the form:
102// <type>=<value>
103// where <type> MUST be exactly one case-significant character.
104static const int kLinePrefixLength = 2; // Lenght of <type>=
105static const char kLineTypeVersion = 'v';
106static const char kLineTypeOrigin = 'o';
107static const char kLineTypeSessionName = 's';
108static const char kLineTypeSessionInfo = 'i';
109static const char kLineTypeSessionUri = 'u';
110static const char kLineTypeSessionEmail = 'e';
111static const char kLineTypeSessionPhone = 'p';
112static const char kLineTypeSessionBandwidth = 'b';
113static const char kLineTypeTiming = 't';
114static const char kLineTypeRepeatTimes = 'r';
115static const char kLineTypeTimeZone = 'z';
116static const char kLineTypeEncryptionKey = 'k';
117static const char kLineTypeMedia = 'm';
118static const char kLineTypeConnection = 'c';
119static const char kLineTypeAttributes = 'a';
120
121// Attributes
122static const char kAttributeGroup[] = "group";
123static const char kAttributeMid[] = "mid";
124static const char kAttributeRtcpMux[] = "rtcp-mux";
deadbeef13871492015-12-09 12:37:51 -0800125static const char kAttributeRtcpReducedSize[] = "rtcp-rsize";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000126static const char kAttributeSsrc[] = "ssrc";
127static const char kSsrcAttributeCname[] = "cname";
128static const char kAttributeExtmap[] = "extmap";
129// draft-alvestrand-mmusic-msid-01
130// a=msid-semantic: WMS
131static const char kAttributeMsidSemantics[] = "msid-semantic";
132static const char kMediaStreamSemantic[] = "WMS";
133static const char kSsrcAttributeMsid[] = "msid";
134static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000135static const char kSsrcAttributeMslabel[] = "mslabel";
136static const char kSSrcAttributeLabel[] = "label";
137static const char kAttributeSsrcGroup[] = "ssrc-group";
138static const char kAttributeCrypto[] = "crypto";
139static const char kAttributeCandidate[] = "candidate";
140static const char kAttributeCandidateTyp[] = "typ";
141static const char kAttributeCandidateRaddr[] = "raddr";
142static const char kAttributeCandidateRport[] = "rport";
honghaiza54a0802015-12-16 18:37:23 -0800143static const char kAttributeCandidateUfrag[] = "ufrag";
144static const char kAttributeCandidatePwd[] = "pwd";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000145static const char kAttributeCandidateGeneration[] = "generation";
146static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000147static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000148static const char kAttributeFmtp[] = "fmtp";
149static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000150static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000151static const char kAttributeRtcp[] = "rtcp";
152static const char kAttributeIceUfrag[] = "ice-ufrag";
153static const char kAttributeIcePwd[] = "ice-pwd";
154static const char kAttributeIceLite[] = "ice-lite";
155static const char kAttributeIceOption[] = "ice-options";
156static const char kAttributeSendOnly[] = "sendonly";
157static const char kAttributeRecvOnly[] = "recvonly";
158static const char kAttributeRtcpFb[] = "rtcp-fb";
159static const char kAttributeSendRecv[] = "sendrecv";
160static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000161// draft-ietf-mmusic-sctp-sdp-07
162// a=sctp-port
163static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000164
165// Experimental flags
166static const char kAttributeXGoogleFlag[] = "x-google-flag";
167static const char kValueConference[] = "conference";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000168
169// Candidate
170static const char kCandidateHost[] = "host";
171static const char kCandidateSrflx[] = "srflx";
172// TODO: How to map the prflx with circket candidate type
173// static const char kCandidatePrflx[] = "prflx";
174static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000175static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176
177static const char kSdpDelimiterEqual = '=';
178static const char kSdpDelimiterSpace = ' ';
179static const char kSdpDelimiterColon = ':';
180static const char kSdpDelimiterSemicolon = ';';
181static const char kSdpDelimiterSlash = '/';
182static const char kNewLine = '\n';
183static const char kReturn = '\r';
184static const char kLineBreak[] = "\r\n";
185
186// TODO: Generate the Session and Time description
187// instead of hardcoding.
188static const char kSessionVersion[] = "v=0";
189// RFC 4566
190static const char kSessionOriginUsername[] = "-";
191static const char kSessionOriginSessionId[] = "0";
192static const char kSessionOriginSessionVersion[] = "0";
193static const char kSessionOriginNettype[] = "IN";
194static const char kSessionOriginAddrtype[] = "IP4";
195static const char kSessionOriginAddress[] = "127.0.0.1";
196static const char kSessionName[] = "s=-";
197static const char kTimeDescription[] = "t=0 0";
198static const char kAttrGroup[] = "a=group:BUNDLE";
199static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000200static const char kConnectionIpv4Addrtype[] = "IP4";
201static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000202static const char kMediaTypeVideo[] = "video";
203static const char kMediaTypeAudio[] = "audio";
204static const char kMediaTypeData[] = "application";
205static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000206// draft-ietf-mmusic-trickle-ice-01
207// When no candidates have been gathered, set the connection
208// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000209// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
210// Use IPV4 per default.
211static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000212static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000213// RFC 3556
214static const char kApplicationSpecificMaximum[] = "AS";
215
216static const int kDefaultVideoClockrate = 90000;
217
218// ISAC special-case.
219static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
220static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
221static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
222
wu@webrtc.org78187522013-10-07 23:32:02 +0000223static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000224
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000225// RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
226// types.
227const int kWildcardPayloadType = -1;
228
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000229struct SsrcInfo {
230 SsrcInfo()
231 : msid_identifier(kDefaultMsid),
232 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
233 // Create random string (which will be used as track label later)?
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000234 msid_appdata(rtc::CreateRandomString(8)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000235 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200236 uint32_t ssrc_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000237 std::string cname;
238 std::string msid_identifier;
239 std::string msid_appdata;
240
241 // For backward compatibility.
242 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
243 std::string label;
244 std::string mslabel;
245};
246typedef std::vector<SsrcInfo> SsrcInfoVec;
247typedef std::vector<SsrcGroup> SsrcGroupVec;
248
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249template <class T>
250static void AddFmtpLine(const T& codec, std::string* message);
251static void BuildMediaDescription(const ContentInfo* content_info,
252 const TransportInfo* transport_info,
253 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000254 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000255 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000256static void BuildSctpContentAttributes(std::string* message, int sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000257static void BuildRtpContentAttributes(
258 const MediaContentDescription* media_desc,
259 const MediaType media_type,
260 std::string* message);
261static void BuildRtpMap(const MediaContentDescription* media_desc,
262 const MediaType media_type,
263 std::string* message);
264static void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -0800265 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000266 std::string* message);
267static void BuildIceOptions(const std::vector<std::string>& transport_options,
268 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000269static bool IsRtp(const std::string& protocol);
270static bool IsDtlsSctp(const std::string& protocol);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271static bool ParseSessionDescription(const std::string& message, size_t* pos,
272 std::string* session_id,
273 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000274 TransportDescription* session_td,
275 RtpHeaderExtensions* session_extmaps,
276 cricket::SessionDescription* desc,
277 SdpParseError* error);
278static bool ParseGroupAttribute(const std::string& line,
279 cricket::SessionDescription* desc,
280 SdpParseError* error);
281static bool ParseMediaDescription(
282 const std::string& message,
283 const TransportDescription& session_td,
284 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000285 size_t* pos, cricket::SessionDescription* desc,
286 std::vector<JsepIceCandidate*>* candidates,
287 SdpParseError* error);
288static bool ParseContent(const std::string& message,
289 const MediaType media_type,
290 int mline_index,
291 const std::string& protocol,
292 const std::vector<int>& codec_preference,
293 size_t* pos,
294 std::string* content_name,
295 MediaContentDescription* media_desc,
296 TransportDescription* transport,
297 std::vector<JsepIceCandidate*>* candidates,
298 SdpParseError* error);
299static bool ParseSsrcAttribute(const std::string& line,
300 SsrcInfoVec* ssrc_infos,
301 SdpParseError* error);
302static bool ParseSsrcGroupAttribute(const std::string& line,
303 SsrcGroupVec* ssrc_groups,
304 SdpParseError* error);
305static bool ParseCryptoAttribute(const std::string& line,
306 MediaContentDescription* media_desc,
307 SdpParseError* error);
308static bool ParseRtpmapAttribute(const std::string& line,
309 const MediaType media_type,
310 const std::vector<int>& codec_preference,
311 MediaContentDescription* media_desc,
312 SdpParseError* error);
313static bool ParseFmtpAttributes(const std::string& line,
314 const MediaType media_type,
315 MediaContentDescription* media_desc,
316 SdpParseError* error);
317static bool ParseFmtpParam(const std::string& line, std::string* parameter,
318 std::string* value, SdpParseError* error);
319static bool ParseCandidate(const std::string& message, Candidate* candidate,
320 SdpParseError* error, bool is_raw);
321static bool ParseRtcpFbAttribute(const std::string& line,
322 const MediaType media_type,
323 MediaContentDescription* media_desc,
324 SdpParseError* error);
325static bool ParseIceOptions(const std::string& line,
326 std::vector<std::string>* transport_options,
327 SdpParseError* error);
328static bool ParseExtmap(const std::string& line,
329 RtpHeaderExtension* extmap,
330 SdpParseError* error);
331static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000332 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000333 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000334static bool ParseDtlsSetup(const std::string& line,
335 cricket::ConnectionRole* role,
336 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000337
338// Helper functions
339
340// Below ParseFailed*** functions output the line that caused the parsing
341// failure and the detailed reason (|description|) of the failure to |error|.
342// The functions always return false so that they can be used directly in the
343// following way when error happens:
344// "return ParseFailed***(...);"
345
346// The line starting at |line_start| of |message| is the failing line.
347// The reason for the failure should be provided in the |description|.
348// An example of a description could be "unknown character".
349static bool ParseFailed(const std::string& message,
350 size_t line_start,
351 const std::string& description,
352 SdpParseError* error) {
353 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000354 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000355 size_t line_end = message.find(kNewLine, line_start);
356 if (line_end != std::string::npos) {
357 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
358 --line_end;
359 }
360 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000361 } else {
362 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000363 }
364
365 if (error) {
366 error->line = first_line;
367 error->description = description;
368 }
369 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
370 << "\". Reason: " << description;
371 return false;
372}
373
374// |line| is the failing line. The reason for the failure should be
375// provided in the |description|.
376static bool ParseFailed(const std::string& line,
377 const std::string& description,
378 SdpParseError* error) {
379 return ParseFailed(line, 0, description, error);
380}
381
382// Parses failure where the failing SDP line isn't know or there are multiple
383// failing lines.
384static bool ParseFailed(const std::string& description,
385 SdpParseError* error) {
386 return ParseFailed("", description, error);
387}
388
389// |line| is the failing line. The failure is due to the fact that |line|
390// doesn't have |expected_fields| fields.
391static bool ParseFailedExpectFieldNum(const std::string& line,
392 int expected_fields,
393 SdpParseError* error) {
394 std::ostringstream description;
395 description << "Expects " << expected_fields << " fields.";
396 return ParseFailed(line, description.str(), error);
397}
398
399// |line| is the failing line. The failure is due to the fact that |line| has
400// less than |expected_min_fields| fields.
401static bool ParseFailedExpectMinFieldNum(const std::string& line,
402 int expected_min_fields,
403 SdpParseError* error) {
404 std::ostringstream description;
405 description << "Expects at least " << expected_min_fields << " fields.";
406 return ParseFailed(line, description.str(), error);
407}
408
409// |line| is the failing line. The failure is due to the fact that it failed to
410// get the value of |attribute|.
411static bool ParseFailedGetValue(const std::string& line,
412 const std::string& attribute,
413 SdpParseError* error) {
414 std::ostringstream description;
415 description << "Failed to get the value of attribute: " << attribute;
416 return ParseFailed(line, description.str(), error);
417}
418
419// The line starting at |line_start| of |message| is the failing line. The
420// failure is due to the line type (e.g. the "m" part of the "m-line")
421// not matching what is expected. The expected line type should be
422// provided as |line_type|.
423static bool ParseFailedExpectLine(const std::string& message,
424 size_t line_start,
425 const char line_type,
426 const std::string& line_value,
427 SdpParseError* error) {
428 std::ostringstream description;
429 description << "Expect line: " << line_type << "=" << line_value;
430 return ParseFailed(message, line_start, description.str(), error);
431}
432
433static bool AddLine(const std::string& line, std::string* message) {
434 if (!message)
435 return false;
436
437 message->append(line);
438 message->append(kLineBreak);
439 return true;
440}
441
442static bool GetLine(const std::string& message,
443 size_t* pos,
444 std::string* line) {
445 size_t line_begin = *pos;
446 size_t line_end = message.find(kNewLine, line_begin);
447 if (line_end == std::string::npos) {
448 return false;
449 }
450 // Update the new start position
451 *pos = line_end + 1;
452 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
453 --line_end;
454 }
455 *line = message.substr(line_begin, (line_end - line_begin));
456 const char* cline = line->c_str();
457 // RFC 4566
458 // An SDP session description consists of a number of lines of text of
459 // the form:
460 // <type>=<value>
461 // where <type> MUST be exactly one case-significant character and
462 // <value> is structured text whose format depends on <type>.
463 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000464 if (line->length() < 3 ||
465 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000466 cline[1] != kSdpDelimiterEqual ||
467 cline[2] == kSdpDelimiterSpace) {
468 *pos = line_begin;
469 return false;
470 }
471 return true;
472}
473
474// Init |os| to "|type|=|value|".
475static void InitLine(const char type,
476 const std::string& value,
477 std::ostringstream* os) {
478 os->str("");
479 *os << type << kSdpDelimiterEqual << value;
480}
481
482// Init |os| to "a=|attribute|".
483static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
484 InitLine(kLineTypeAttributes, attribute, os);
485}
486
487// Writes a SDP attribute line based on |attribute| and |value| to |message|.
488static void AddAttributeLine(const std::string& attribute, int value,
489 std::string* message) {
490 std::ostringstream os;
491 InitAttrLine(attribute, &os);
492 os << kSdpDelimiterColon << value;
493 AddLine(os.str(), message);
494}
495
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000496static bool IsLineType(const std::string& message,
497 const char type,
498 size_t line_start) {
499 if (message.size() < line_start + kLinePrefixLength) {
500 return false;
501 }
502 const char* cmessage = message.c_str();
503 return (cmessage[line_start] == type &&
504 cmessage[line_start + 1] == kSdpDelimiterEqual);
505}
506
507static bool IsLineType(const std::string& line,
508 const char type) {
509 return IsLineType(line, type, 0);
510}
511
512static bool GetLineWithType(const std::string& message, size_t* pos,
513 std::string* line, const char type) {
514 if (!IsLineType(message, type, *pos)) {
515 return false;
516 }
517
518 if (!GetLine(message, pos, line))
519 return false;
520
521 return true;
522}
523
524static bool HasAttribute(const std::string& line,
525 const std::string& attribute) {
526 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
527}
528
Peter Boström0c4e06b2015-10-07 12:23:21 +0200529static bool AddSsrcLine(uint32_t ssrc_id,
530 const std::string& attribute,
531 const std::string& value,
532 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000533 // RFC 5576
534 // a=ssrc:<ssrc-id> <attribute>:<value>
535 std::ostringstream os;
536 InitAttrLine(kAttributeSsrc, &os);
537 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
538 << attribute << kSdpDelimiterColon << value;
539 return AddLine(os.str(), message);
540}
541
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000542// Get value only from <attribute>:<value>.
543static bool GetValue(const std::string& message, const std::string& attribute,
544 std::string* value, SdpParseError* error) {
545 std::string leftpart;
Donald Curtis0e07f922015-05-15 09:21:23 -0700546 if (!rtc::tokenize_first(message, kSdpDelimiterColon, &leftpart, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000547 return ParseFailedGetValue(message, attribute, error);
548 }
549 // The left part should end with the expected attribute.
550 if (leftpart.length() < attribute.length() ||
551 leftpart.compare(leftpart.length() - attribute.length(),
552 attribute.length(), attribute) != 0) {
553 return ParseFailedGetValue(message, attribute, error);
554 }
555 return true;
556}
557
558static bool CaseInsensitiveFind(std::string str1, std::string str2) {
559 std::transform(str1.begin(), str1.end(), str1.begin(),
560 ::tolower);
561 std::transform(str2.begin(), str2.end(), str2.begin(),
562 ::tolower);
563 return str1.find(str2) != std::string::npos;
564}
565
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000566template <class T>
567static bool GetValueFromString(const std::string& line,
568 const std::string& s,
569 T* t,
570 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000571 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000572 std::ostringstream description;
573 description << "Invalid value: " << s << ".";
574 return ParseFailed(line, description.str(), error);
575 }
576 return true;
577}
578
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000579static bool GetPayloadTypeFromString(const std::string& line,
580 const std::string& s,
581 int* payload_type,
582 SdpParseError* error) {
583 return GetValueFromString(line, s, payload_type, error) &&
584 cricket::IsValidRtpPayloadType(*payload_type);
585}
586
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
588 StreamParamsVec* tracks) {
589 ASSERT(tracks != NULL);
590 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
591 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
592 if (ssrc_info->cname.empty()) {
593 continue;
594 }
595
596 std::string sync_label;
597 std::string track_id;
598 if (ssrc_info->msid_identifier == kDefaultMsid &&
599 !ssrc_info->mslabel.empty()) {
600 // If there's no msid and there's mslabel, we consider this is a sdp from
601 // a older version of client that doesn't support msid.
602 // In that case, we use the mslabel and label to construct the track.
603 sync_label = ssrc_info->mslabel;
604 track_id = ssrc_info->label;
605 } else {
606 sync_label = ssrc_info->msid_identifier;
607 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
608 // is corresponding to the "id" attribute of StreamParams.
609 track_id = ssrc_info->msid_appdata;
610 }
611 if (sync_label.empty() || track_id.empty()) {
612 ASSERT(false);
613 continue;
614 }
615
616 StreamParamsVec::iterator track = tracks->begin();
617 for (; track != tracks->end(); ++track) {
618 if (track->id == track_id) {
619 break;
620 }
621 }
622 if (track == tracks->end()) {
623 // If we don't find an existing track, create a new one.
624 tracks->push_back(StreamParams());
625 track = tracks->end() - 1;
626 }
627 track->add_ssrc(ssrc_info->ssrc_id);
628 track->cname = ssrc_info->cname;
629 track->sync_label = sync_label;
630 track->id = track_id;
631 }
632}
633
634void GetMediaStreamLabels(const ContentInfo* content,
635 std::set<std::string>* labels) {
636 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000637 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000638 content->description);
639 const cricket::StreamParamsVec& streams = media_desc->streams();
640 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
641 it != streams.end(); ++it) {
642 labels->insert(it->sync_label);
643 }
644}
645
646// RFC 5245
647// It is RECOMMENDED that default candidates be chosen based on the
648// likelihood of those candidates to work with the peer that is being
649// contacted. It is RECOMMENDED that relayed > reflexive > host.
650static const int kPreferenceUnknown = 0;
651static const int kPreferenceHost = 1;
652static const int kPreferenceReflexive = 2;
653static const int kPreferenceRelayed = 3;
654
655static int GetCandidatePreferenceFromType(const std::string& type) {
656 int preference = kPreferenceUnknown;
657 if (type == cricket::LOCAL_PORT_TYPE) {
658 preference = kPreferenceHost;
659 } else if (type == cricket::STUN_PORT_TYPE) {
660 preference = kPreferenceReflexive;
661 } else if (type == cricket::RELAY_PORT_TYPE) {
662 preference = kPreferenceRelayed;
663 } else {
664 ASSERT(false);
665 }
666 return preference;
667}
668
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000669// Get ip and port of the default destination from the |candidates| with the
670// given value of |component_id|. The default candidate should be the one most
671// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672// RFC 5245
673// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
674// TODO: Decide the default destination in webrtcsession and
675// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000676static void GetDefaultDestination(
677 const std::vector<Candidate>& candidates,
678 int component_id, std::string* port,
679 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000680 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000681 *port = kDummyPort;
682 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000683 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000684 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685 for (std::vector<Candidate>::const_iterator it = candidates.begin();
686 it != candidates.end(); ++it) {
687 if (it->component() != component_id) {
688 continue;
689 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000690 // Default destination should be UDP only.
691 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000692 continue;
693 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000694 const int preference = GetCandidatePreferenceFromType(it->type());
695 const int family = it->address().ipaddr().family();
696 // See if this candidate is more preferable then the current one if it's the
697 // same family. Or if the current family is IPv4 already so we could safely
698 // ignore all IPv6 ones. WebRTC bug 4269.
699 // http://code.google.com/p/webrtc/issues/detail?id=4269
700 if ((preference <= current_preference && current_family == family) ||
701 (current_family == AF_INET && family == AF_INET6)) {
702 continue;
703 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000704 if (family == AF_INET) {
705 addr_type->assign(kConnectionIpv4Addrtype);
706 } else if (family == AF_INET6) {
707 addr_type->assign(kConnectionIpv6Addrtype);
708 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000709 current_preference = preference;
710 current_family = family;
711 *port = it->address().PortAsString();
712 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000713 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000714}
715
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000716// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000717static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000718 const std::vector<Candidate>& candidates,
jbauch083b73f2015-07-16 02:46:32 -0700719 const std::string& mline,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000720 std::string* message) {
721 std::string new_lines;
722 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723 // RFC 4566
724 // m=<media> <port> <proto> <fmt> ...
725 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000726 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727 if (fields.size() < 3) {
728 return;
729 }
730
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000732 std::string rtp_port, rtp_ip, addr_type;
733 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
734 &rtp_port, &rtp_ip, &addr_type);
735 // Found default RTP candidate.
736 // RFC 5245
737 // The default candidates are added to the SDP as the default
738 // destination for media. For streams based on RTP, this is done by
739 // placing the IP address and port of the RTP candidate into the c and m
740 // lines, respectively.
741 // Update the port in the m line.
742 // If this is a m-line with port equal to 0, we don't change it.
743 if (fields[1] != kMediaPortRejected) {
744 new_lines.replace(fields[0].size() + 1,
745 fields[1].size(),
746 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000747 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000748 // Add the c line.
749 // RFC 4566
750 // c=<nettype> <addrtype> <connection-address>
751 InitLine(kLineTypeConnection, kConnectionNettype, &os);
752 os << " " << addr_type << " " << rtp_ip;
753 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000754 message->append(new_lines);
755}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000757// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
758static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000759 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
760 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
761 &rtcp_port, &rtcp_ip, &addr_type);
762 // Found default RTCP candidate.
763 // RFC 5245
764 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
765 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000766
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000767 // RFC 3605
768 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
769 // connection-address] CRLF
770 std::ostringstream os;
771 InitAttrLine(kAttributeRtcp, &os);
772 os << kSdpDelimiterColon
773 << rtcp_port << " "
774 << kConnectionNettype << " "
775 << addr_type << " "
776 << rtcp_ip;
777 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000778 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000779}
780
781// Get candidates according to the mline index from SessionDescriptionInterface.
782static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
783 int mline_index,
784 std::vector<Candidate>* candidates) {
785 if (!candidates) {
786 return;
787 }
788 const IceCandidateCollection* cc = desci.candidates(mline_index);
789 for (size_t i = 0; i < cc->count(); ++i) {
790 const IceCandidateInterface* candidate = cc->at(i);
791 candidates->push_back(candidate->candidate());
792 }
793}
794
795std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796 const cricket::SessionDescription* desc = jdesc.description();
797 if (!desc) {
798 return "";
799 }
800
801 std::string message;
802
803 // Session Description.
804 AddLine(kSessionVersion, &message);
805 // Session Origin
806 // RFC 4566
807 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
808 // <unicast-address>
809 std::ostringstream os;
810 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
jbauch083b73f2015-07-16 02:46:32 -0700811 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700813 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000814 kSessionOriginSessionVersion : jdesc.session_version();
815 os << " " << session_id << " " << session_version << " "
816 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
817 << kSessionOriginAddress;
818 AddLine(os.str(), &message);
819 AddLine(kSessionName, &message);
820
821 // Time Description.
822 AddLine(kTimeDescription, &message);
823
824 // Group
825 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
826 std::string group_line = kAttrGroup;
827 const cricket::ContentGroup* group =
828 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
829 ASSERT(group != NULL);
830 const cricket::ContentNames& content_names = group->content_names();
831 for (cricket::ContentNames::const_iterator it = content_names.begin();
832 it != content_names.end(); ++it) {
833 group_line.append(" ");
834 group_line.append(*it);
835 }
836 AddLine(group_line, &message);
837 }
838
839 // MediaStream semantics
840 InitAttrLine(kAttributeMsidSemantics, &os);
841 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000842
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843 std::set<std::string> media_stream_labels;
844 const ContentInfo* audio_content = GetFirstAudioContent(desc);
845 if (audio_content)
846 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000847
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848 const ContentInfo* video_content = GetFirstVideoContent(desc);
849 if (video_content)
850 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000851
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000852 for (std::set<std::string>::const_iterator it =
853 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
854 os << " " << *it;
855 }
856 AddLine(os.str(), &message);
857
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000858 // Preserve the order of the media contents.
859 int mline_index = -1;
860 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
861 it != desc->contents().end(); ++it) {
862 const MediaContentDescription* mdesc =
863 static_cast<const MediaContentDescription*>(it->description);
864 std::vector<Candidate> candidates;
865 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
866 BuildMediaDescription(&*it,
867 desc->GetTransportInfoByName(it->name),
868 mdesc->type(),
869 candidates,
870 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000871 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872 return message;
873}
874
875// Serializes the passed in IceCandidateInterface to a SDP string.
876// candidate - The candidate to be serialized.
877std::string SdpSerializeCandidate(
878 const IceCandidateInterface& candidate) {
879 std::string message;
880 std::vector<cricket::Candidate> candidates;
881 candidates.push_back(candidate.candidate());
honghaiza54a0802015-12-16 18:37:23 -0800882 BuildCandidate(candidates, true, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000883 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
884 // just candidate:<candidate> not a=candidate:<blah>CRLF
885 ASSERT(message.find("a=") == 0);
886 message.erase(0, 2);
887 ASSERT(message.find(kLineBreak) == message.size() - 2);
888 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000889 return message;
890}
891
892bool SdpDeserialize(const std::string& message,
893 JsepSessionDescription* jdesc,
894 SdpParseError* error) {
895 std::string session_id;
896 std::string session_version;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700897 TransportDescription session_td("", "");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000898 RtpHeaderExtensions session_extmaps;
899 cricket::SessionDescription* desc = new cricket::SessionDescription();
900 std::vector<JsepIceCandidate*> candidates;
901 size_t current_pos = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000902
903 // Session Description
904 if (!ParseSessionDescription(message, &current_pos, &session_id,
deadbeefc80741f2015-10-22 13:14:45 -0700905 &session_version, &session_td, &session_extmaps,
906 desc, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000907 delete desc;
908 return false;
909 }
910
911 // Media Description
deadbeefc80741f2015-10-22 13:14:45 -0700912 if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
913 desc, &candidates, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000914 delete desc;
915 for (std::vector<JsepIceCandidate*>::const_iterator
916 it = candidates.begin(); it != candidates.end(); ++it) {
917 delete *it;
918 }
919 return false;
920 }
921
922 jdesc->Initialize(desc, session_id, session_version);
923
924 for (std::vector<JsepIceCandidate*>::const_iterator
925 it = candidates.begin(); it != candidates.end(); ++it) {
926 jdesc->AddCandidate(*it);
927 delete *it;
928 }
929 return true;
930}
931
932bool SdpDeserializeCandidate(const std::string& message,
933 JsepIceCandidate* jcandidate,
934 SdpParseError* error) {
935 ASSERT(jcandidate != NULL);
936 Candidate candidate;
937 if (!ParseCandidate(message, &candidate, error, true)) {
938 return false;
939 }
940 jcandidate->SetCandidate(candidate);
941 return true;
942}
943
944bool ParseCandidate(const std::string& message, Candidate* candidate,
945 SdpParseError* error, bool is_raw) {
946 ASSERT(candidate != NULL);
947
948 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000949 std::string first_line = message;
950 size_t pos = 0;
951 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000953 // Makes sure |message| contains only one line.
954 if (message.size() > first_line.size()) {
955 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700956 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
957 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000958 return ParseFailed(message, 0, "Expect one line only", error);
959 }
960 }
961
962 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
963 // candidate:<candidate> when trickled, but we still support
964 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
965 // from the SDP.
966 if (IsLineType(first_line, kLineTypeAttributes)) {
967 first_line = first_line.substr(kLinePrefixLength);
968 }
969
970 std::string attribute_candidate;
971 std::string candidate_value;
972
973 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700974 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
975 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000976 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000977 if (is_raw) {
978 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000979 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000980 << ":" << "<candidate-str>";
981 return ParseFailed(first_line, 0, description.str(), error);
982 } else {
983 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
984 kAttributeCandidate, error);
985 }
986 }
987
988 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000989 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
990
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991 // RFC 5245
992 // a=candidate:<foundation> <component-id> <transport> <priority>
993 // <connection-address> <port> typ <candidate-types>
994 // [raddr <connection-address>] [rport <port>]
995 // *(SP extension-att-name SP extension-att-value)
996 const size_t expected_min_fields = 8;
997 if (fields.size() < expected_min_fields ||
998 (fields[6] != kAttributeCandidateTyp)) {
999 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
1000 }
jbauch083b73f2015-07-16 02:46:32 -07001001 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001002
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001003 int component_id = 0;
1004 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1005 return false;
1006 }
jbauch083b73f2015-07-16 02:46:32 -07001007 const std::string& transport = fields[2];
Peter Boström0c4e06b2015-10-07 12:23:21 +02001008 uint32_t priority = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001009 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1010 return false;
1011 }
jbauch083b73f2015-07-16 02:46:32 -07001012 const std::string& connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001013 int port = 0;
1014 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1015 return false;
1016 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001017 SocketAddress address(connection_address, port);
1018
1019 cricket::ProtocolType protocol;
1020 if (!StringToProto(transport.c_str(), &protocol)) {
1021 return ParseFailed(first_line, "Unsupported transport type.", error);
1022 }
1023
1024 std::string candidate_type;
jbauch083b73f2015-07-16 02:46:32 -07001025 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026 if (type == kCandidateHost) {
1027 candidate_type = cricket::LOCAL_PORT_TYPE;
1028 } else if (type == kCandidateSrflx) {
1029 candidate_type = cricket::STUN_PORT_TYPE;
1030 } else if (type == kCandidateRelay) {
1031 candidate_type = cricket::RELAY_PORT_TYPE;
1032 } else {
1033 return ParseFailed(first_line, "Unsupported candidate type.", error);
1034 }
1035
1036 size_t current_position = expected_min_fields;
1037 SocketAddress related_address;
1038 // The 2 optional fields for related address
1039 // [raddr <connection-address>] [rport <port>]
1040 if (fields.size() >= (current_position + 2) &&
1041 fields[current_position] == kAttributeCandidateRaddr) {
1042 related_address.SetIP(fields[++current_position]);
1043 ++current_position;
1044 }
1045 if (fields.size() >= (current_position + 2) &&
1046 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001047 int port = 0;
1048 if (!GetValueFromString(
1049 first_line, fields[++current_position], &port, error)) {
1050 return false;
1051 }
1052 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001053 ++current_position;
1054 }
1055
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001056 // If this is a TCP candidate, it has additional extension as defined in
1057 // RFC 6544.
1058 std::string tcptype;
1059 if (fields.size() >= (current_position + 2) &&
1060 fields[current_position] == kTcpCandidateType) {
1061 tcptype = fields[++current_position];
1062 ++current_position;
1063
1064 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1065 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1066 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1067 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1068 }
1069
1070 if (protocol != cricket::PROTO_TCP) {
1071 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1072 }
1073 }
1074
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001075 // Extension
honghaiza54a0802015-12-16 18:37:23 -08001076 // Though non-standard, we support the ICE ufrag and pwd being signaled on
1077 // the candidate to avoid issues with confusing which generation a candidate
1078 // belongs to when trickling multiple generations at the same time.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001079 std::string username;
1080 std::string password;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001081 uint32_t generation = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1083 // RFC 5245
1084 // *(SP extension-att-name SP extension-att-value)
1085 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001086 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1087 return false;
1088 }
honghaiza54a0802015-12-16 18:37:23 -08001089 } else if (fields[i] == kAttributeCandidateUfrag) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001090 username = fields[++i];
honghaiza54a0802015-12-16 18:37:23 -08001091 } else if (fields[i] == kAttributeCandidatePwd) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001092 password = fields[++i];
1093 } else {
1094 // Skip the unknown extension.
1095 ++i;
1096 }
1097 }
1098
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001099 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001100 address, priority, username, password, candidate_type,
1101 generation, foundation);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001102 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001103 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001104 return true;
1105}
1106
1107bool ParseIceOptions(const std::string& line,
1108 std::vector<std::string>* transport_options,
1109 SdpParseError* error) {
1110 std::string ice_options;
1111 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1112 return false;
1113 }
1114 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001115 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001116 for (size_t i = 0; i < fields.size(); ++i) {
1117 transport_options->push_back(fields[i]);
1118 }
1119 return true;
1120}
1121
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001122bool ParseSctpPort(const std::string& line,
1123 int* sctp_port,
1124 SdpParseError* error) {
1125 // draft-ietf-mmusic-sctp-sdp-07
1126 // a=sctp-port
1127 std::vector<std::string> fields;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001128 const size_t expected_min_fields = 2;
lally69f57602015-10-08 10:15:04 -07001129 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1130 if (fields.size() < expected_min_fields) {
1131 fields.resize(0);
1132 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpace, &fields);
1133 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001134 if (fields.size() < expected_min_fields) {
1135 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1136 }
1137 if (!rtc::FromString(fields[1], sctp_port)) {
lally69f57602015-10-08 10:15:04 -07001138 return ParseFailed(line, "Invalid sctp port value.", error);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001139 }
1140 return true;
1141}
1142
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001143bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1144 SdpParseError* error) {
1145 // RFC 5285
1146 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1147 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001148 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001149 kSdpDelimiterSpace, &fields);
1150 const size_t expected_min_fields = 2;
1151 if (fields.size() < expected_min_fields) {
1152 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1153 }
1154 std::string uri = fields[1];
1155
1156 std::string value_direction;
1157 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1158 return false;
1159 }
1160 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001161 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001162 int value = 0;
1163 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1164 return false;
1165 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001166
1167 *extmap = RtpHeaderExtension(uri, value);
1168 return true;
1169}
1170
1171void BuildMediaDescription(const ContentInfo* content_info,
1172 const TransportInfo* transport_info,
1173 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001174 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001175 std::string* message) {
1176 ASSERT(message != NULL);
1177 if (content_info == NULL || message == NULL) {
1178 return;
1179 }
1180 // TODO: Rethink if we should use sprintfn instead of stringstream.
1181 // According to the style guide, streams should only be used for logging.
1182 // http://google-styleguide.googlecode.com/svn/
1183 // trunk/cppguide.xml?showone=Streams#Streams
1184 std::ostringstream os;
1185 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001186 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001187 content_info->description);
1188 ASSERT(media_desc != NULL);
1189
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001190 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191
1192 // RFC 4566
1193 // m=<media> <port> <proto> <fmt>
1194 // fmt is a list of payload type numbers that MAY be used in the session.
1195 const char* type = NULL;
1196 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1197 type = kMediaTypeAudio;
1198 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1199 type = kMediaTypeVideo;
1200 else if (media_type == cricket::MEDIA_TYPE_DATA)
1201 type = kMediaTypeData;
1202 else
1203 ASSERT(false);
1204
1205 std::string fmt;
1206 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1207 const VideoContentDescription* video_desc =
1208 static_cast<const VideoContentDescription*>(media_desc);
1209 for (std::vector<cricket::VideoCodec>::const_iterator it =
1210 video_desc->codecs().begin();
1211 it != video_desc->codecs().end(); ++it) {
1212 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001213 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001214 }
1215 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1216 const AudioContentDescription* audio_desc =
1217 static_cast<const AudioContentDescription*>(media_desc);
1218 for (std::vector<cricket::AudioCodec>::const_iterator it =
1219 audio_desc->codecs().begin();
1220 it != audio_desc->codecs().end(); ++it) {
1221 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001222 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001223 }
1224 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001225 const DataContentDescription* data_desc =
1226 static_cast<const DataContentDescription*>(media_desc);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001227 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001229
1230 for (std::vector<cricket::DataCodec>::const_iterator it =
1231 data_desc->codecs().begin();
1232 it != data_desc->codecs().end(); ++it) {
1233 if (it->id == cricket::kGoogleSctpDataCodecId &&
1234 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1235 break;
1236 }
1237 }
1238
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001239 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001240 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241 for (std::vector<cricket::DataCodec>::const_iterator it =
1242 data_desc->codecs().begin();
1243 it != data_desc->codecs().end(); ++it) {
1244 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001245 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001246 }
1247 }
1248 }
1249 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1250 // to 0.
1251 if (fmt.empty()) {
1252 fmt = " 0";
1253 }
1254
1255 // The port number in the m line will be updated later when associate with
1256 // the candidates.
1257 // RFC 3264
1258 // To reject an offered stream, the port number in the corresponding stream in
1259 // the answer MUST be set to zero.
jbauch083b73f2015-07-16 02:46:32 -07001260 const std::string& port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001261 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001262
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001263 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001264 transport_info->description.identity_fingerprint.get() : NULL;
1265
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001266 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001267 InitLine(kLineTypeMedia, type, &os);
1268 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001269 std::string mline = os.str();
1270 UpdateMediaDefaultDestination(candidates, mline, message);
1271
1272 // RFC 4566
1273 // b=AS:<bandwidth>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001274 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001275 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1276 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1277 AddLine(os.str(), message);
1278 }
1279
1280 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001281 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001282 std::string rtcp_line = GetRtcpLine(candidates);
1283 if (!rtcp_line.empty()) {
1284 AddLine(rtcp_line, message);
1285 }
1286 }
1287
honghaiza54a0802015-12-16 18:37:23 -08001288 // Build the a=candidate lines. We don't include ufrag and pwd in the
1289 // candidates in the SDP to avoid redundancy.
1290 BuildCandidate(candidates, false, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291
1292 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1293 if (transport_info) {
1294 // RFC 5245
1295 // ice-pwd-att = "ice-pwd" ":" password
1296 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1297 // ice-ufrag
1298 InitAttrLine(kAttributeIceUfrag, &os);
1299 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1300 AddLine(os.str(), message);
1301 // ice-pwd
1302 InitAttrLine(kAttributeIcePwd, &os);
1303 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1304 AddLine(os.str(), message);
1305
1306 // draft-petithuguenin-mmusic-ice-attributes-level-03
1307 BuildIceOptions(transport_info->description.transport_options, message);
1308
1309 // RFC 4572
1310 // fingerprint-attribute =
1311 // "fingerprint" ":" hash-func SP fingerprint
1312 if (fp) {
1313 // Insert the fingerprint attribute.
1314 InitAttrLine(kAttributeFingerprint, &os);
1315 os << kSdpDelimiterColon
1316 << fp->algorithm << kSdpDelimiterSpace
1317 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001318 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001319
1320 // Inserting setup attribute.
1321 if (transport_info->description.connection_role !=
1322 cricket::CONNECTIONROLE_NONE) {
1323 // Making sure we are not using "passive" mode.
1324 cricket::ConnectionRole role =
1325 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001326 std::string dtls_role_str;
1327 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001328 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001329 os << kSdpDelimiterColon << dtls_role_str;
1330 AddLine(os.str(), message);
1331 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332 }
1333 }
1334
1335 // RFC 3388
1336 // mid-attribute = "a=mid:" identification-tag
1337 // identification-tag = token
1338 // Use the content name as the mid identification-tag.
1339 InitAttrLine(kAttributeMid, &os);
1340 os << kSdpDelimiterColon << content_info->name;
1341 AddLine(os.str(), message);
1342
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001343 if (IsDtlsSctp(media_desc->protocol())) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001344 BuildSctpContentAttributes(message, sctp_port);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001345 } else if (IsRtp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346 BuildRtpContentAttributes(media_desc, media_type, message);
1347 }
1348}
1349
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001350void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001351 // draft-ietf-mmusic-sctp-sdp-04
1352 // a=sctpmap:sctpmap-number protocol [streams]
lally69f57602015-10-08 10:15:04 -07001353 // TODO(lally): switch this over to mmusic-sctp-sdp-12 (or later), with
1354 // 'a=sctp-port:'
wu@webrtc.org78187522013-10-07 23:32:02 +00001355 std::ostringstream os;
1356 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001357 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001358 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1359 << (cricket::kMaxSctpSid + 1);
1360 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361}
1362
1363void BuildRtpContentAttributes(
1364 const MediaContentDescription* media_desc,
1365 const MediaType media_type,
1366 std::string* message) {
1367 std::ostringstream os;
1368 // RFC 5285
1369 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1370 // The definitions MUST be either all session level or all media level. This
1371 // implementation uses all media level.
1372 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1373 InitAttrLine(kAttributeExtmap, &os);
1374 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1375 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1376 AddLine(os.str(), message);
1377 }
1378
1379 // RFC 3264
1380 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
deadbeefc80741f2015-10-22 13:14:45 -07001381 switch (media_desc->direction()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001382 case cricket::MD_INACTIVE:
1383 InitAttrLine(kAttributeInactive, &os);
1384 break;
1385 case cricket::MD_SENDONLY:
1386 InitAttrLine(kAttributeSendOnly, &os);
1387 break;
1388 case cricket::MD_RECVONLY:
1389 InitAttrLine(kAttributeRecvOnly, &os);
1390 break;
1391 case cricket::MD_SENDRECV:
1392 default:
1393 InitAttrLine(kAttributeSendRecv, &os);
1394 break;
1395 }
1396 AddLine(os.str(), message);
1397
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398 // RFC 5761
1399 // a=rtcp-mux
1400 if (media_desc->rtcp_mux()) {
1401 InitAttrLine(kAttributeRtcpMux, &os);
1402 AddLine(os.str(), message);
1403 }
1404
deadbeef13871492015-12-09 12:37:51 -08001405 // RFC 5506
1406 // a=rtcp-rsize
1407 if (media_desc->rtcp_reduced_size()) {
1408 InitAttrLine(kAttributeRtcpReducedSize, &os);
1409 AddLine(os.str(), message);
1410 }
1411
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001412 // RFC 4568
1413 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1414 for (std::vector<CryptoParams>::const_iterator it =
1415 media_desc->cryptos().begin();
1416 it != media_desc->cryptos().end(); ++it) {
1417 InitAttrLine(kAttributeCrypto, &os);
1418 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1419 << it->key_params;
1420 if (!it->session_params.empty()) {
1421 os << " " << it->session_params;
1422 }
1423 AddLine(os.str(), message);
1424 }
1425
1426 // RFC 4566
1427 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1428 // [/<encodingparameters>]
1429 BuildRtpMap(media_desc, media_type, message);
1430
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001431 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1432 track != media_desc->streams().end(); ++track) {
1433 // Require that the track belongs to a media stream,
1434 // ie the sync_label is set. This extra check is necessary since the
1435 // MediaContentDescription always contains a streamparam with an ssrc even
1436 // if no track or media stream have been created.
1437 if (track->sync_label.empty()) continue;
1438
1439 // Build the ssrc-group lines.
1440 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1441 // RFC 5576
1442 // a=ssrc-group:<semantics> <ssrc-id> ...
1443 if (track->ssrc_groups[i].ssrcs.empty()) {
1444 continue;
1445 }
1446 std::ostringstream os;
1447 InitAttrLine(kAttributeSsrcGroup, &os);
1448 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001449 std::vector<uint32_t>::const_iterator ssrc =
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450 track->ssrc_groups[i].ssrcs.begin();
1451 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001452 os << kSdpDelimiterSpace << rtc::ToString<uint32_t>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001453 }
1454 AddLine(os.str(), message);
1455 }
1456 // Build the ssrc lines for each ssrc.
1457 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001458 uint32_t ssrc = track->ssrcs[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459 // RFC 5576
1460 // a=ssrc:<ssrc-id> cname:<value>
1461 AddSsrcLine(ssrc, kSsrcAttributeCname,
1462 track->cname, message);
1463
1464 // draft-alvestrand-mmusic-msid-00
1465 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1466 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1467 // is corresponding to the "name" attribute of StreamParams.
1468 std::string appdata = track->id;
1469 std::ostringstream os;
1470 InitAttrLine(kAttributeSsrc, &os);
1471 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1472 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1473 << kSdpDelimiterSpace << appdata;
1474 AddLine(os.str(), message);
1475
1476 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1477 // draft-alvestrand-rtcweb-mid-01
1478 // a=ssrc:<ssrc-id> mslabel:<value>
1479 // The label isn't yet defined.
1480 // a=ssrc:<ssrc-id> label:<value>
1481 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1482 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1483 }
1484 }
1485}
1486
1487void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1488 // fmtp header: a=fmtp:|payload_type| <parameters>
1489 // Add a=fmtp
1490 InitAttrLine(kAttributeFmtp, os);
1491 // Add :|payload_type|
1492 *os << kSdpDelimiterColon << payload_type;
1493}
1494
1495void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1496 // rtcp-fb header: a=rtcp-fb:|payload_type|
1497 // <parameters>/<ccm <ccm_parameters>>
1498 // Add a=rtcp-fb
1499 InitAttrLine(kAttributeRtcpFb, os);
1500 // Add :
1501 *os << kSdpDelimiterColon;
1502 if (payload_type == kWildcardPayloadType) {
1503 *os << "*";
1504 } else {
1505 *os << payload_type;
1506 }
1507}
1508
1509void WriteFmtpParameter(const std::string& parameter_name,
1510 const std::string& parameter_value,
1511 std::ostringstream* os) {
1512 // fmtp parameters: |parameter_name|=|parameter_value|
1513 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1514}
1515
1516void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1517 std::ostringstream* os) {
1518 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1519 fmtp != parameters.end(); ++fmtp) {
1520 // Each new parameter, except the first one starts with ";" and " ".
1521 if (fmtp != parameters.begin()) {
1522 *os << kSdpDelimiterSemicolon;
1523 }
1524 *os << kSdpDelimiterSpace;
1525 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1526 }
1527}
1528
1529bool IsFmtpParam(const std::string& name) {
1530 const char* kFmtpParams[] = {
1531 kCodecParamMinPTime, kCodecParamSPropStereo,
Minyue Li7100dcd2015-03-27 05:05:59 +01001532 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamUseDtx,
1533 kCodecParamStartBitrate, kCodecParamMaxBitrate, kCodecParamMinBitrate,
1534 kCodecParamMaxQuantization, kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001535 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1536 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001537 };
tfarina5237aaf2015-11-10 23:44:30 -08001538 for (size_t i = 0; i < arraysize(kFmtpParams); ++i) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001539 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1540 return true;
1541 }
1542 }
1543 return false;
1544}
1545
1546// Retreives fmtp parameters from |params|, which may contain other parameters
1547// as well, and puts them in |fmtp_parameters|.
1548void GetFmtpParams(const cricket::CodecParameterMap& params,
1549 cricket::CodecParameterMap* fmtp_parameters) {
1550 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1551 iter != params.end(); ++iter) {
1552 if (IsFmtpParam(iter->first)) {
1553 (*fmtp_parameters)[iter->first] = iter->second;
1554 }
1555 }
1556}
1557
1558template <class T>
1559void AddFmtpLine(const T& codec, std::string* message) {
1560 cricket::CodecParameterMap fmtp_parameters;
1561 GetFmtpParams(codec.params, &fmtp_parameters);
1562 if (fmtp_parameters.empty()) {
1563 // No need to add an fmtp if it will have no (optional) parameters.
1564 return;
1565 }
1566 std::ostringstream os;
1567 WriteFmtpHeader(codec.id, &os);
1568 WriteFmtpParameters(fmtp_parameters, &os);
1569 AddLine(os.str(), message);
1570 return;
1571}
1572
1573template <class T>
1574void AddRtcpFbLines(const T& codec, std::string* message) {
1575 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1576 codec.feedback_params.params().begin();
1577 iter != codec.feedback_params.params().end(); ++iter) {
1578 std::ostringstream os;
1579 WriteRtcpFbHeader(codec.id, &os);
1580 os << " " << iter->id();
1581 if (!iter->param().empty()) {
1582 os << " " << iter->param();
1583 }
1584 AddLine(os.str(), message);
1585 }
1586}
1587
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001588bool AddSctpDataCodec(DataContentDescription* media_desc,
1589 int sctp_port) {
1590 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1591 return ParseFailed("",
1592 "Can't have multiple sctp port attributes.",
1593 NULL);
1594 }
1595 // Add the SCTP Port number as a pseudo-codec "port" parameter
1596 cricket::DataCodec codec_port(
1597 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1598 0);
1599 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1600 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1601 << sctp_port;
1602 media_desc->AddCodec(codec_port);
1603 return true;
1604}
1605
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001606bool GetMinValue(const std::vector<int>& values, int* value) {
1607 if (values.empty()) {
1608 return false;
1609 }
1610 std::vector<int>::const_iterator found =
1611 std::min_element(values.begin(), values.end());
1612 *value = *found;
1613 return true;
1614}
1615
1616bool GetParameter(const std::string& name,
1617 const cricket::CodecParameterMap& params, int* value) {
1618 std::map<std::string, std::string>::const_iterator found =
1619 params.find(name);
1620 if (found == params.end()) {
1621 return false;
1622 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001623 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001624 return false;
1625 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001626 return true;
1627}
1628
1629void BuildRtpMap(const MediaContentDescription* media_desc,
1630 const MediaType media_type,
1631 std::string* message) {
1632 ASSERT(message != NULL);
1633 ASSERT(media_desc != NULL);
1634 std::ostringstream os;
1635 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1636 const VideoContentDescription* video_desc =
1637 static_cast<const VideoContentDescription*>(media_desc);
1638 for (std::vector<cricket::VideoCodec>::const_iterator it =
1639 video_desc->codecs().begin();
1640 it != video_desc->codecs().end(); ++it) {
1641 // RFC 4566
1642 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1643 // [/<encodingparameters>]
1644 if (it->id != kWildcardPayloadType) {
1645 InitAttrLine(kAttributeRtpmap, &os);
1646 os << kSdpDelimiterColon << it->id << " " << it->name
1647 << "/" << kDefaultVideoClockrate;
1648 AddLine(os.str(), message);
1649 }
1650 AddRtcpFbLines(*it, message);
1651 AddFmtpLine(*it, message);
1652 }
1653 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1654 const AudioContentDescription* audio_desc =
1655 static_cast<const AudioContentDescription*>(media_desc);
1656 std::vector<int> ptimes;
1657 std::vector<int> maxptimes;
1658 int max_minptime = 0;
1659 for (std::vector<cricket::AudioCodec>::const_iterator it =
1660 audio_desc->codecs().begin();
1661 it != audio_desc->codecs().end(); ++it) {
1662 ASSERT(!it->name.empty());
1663 // RFC 4566
1664 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1665 // [/<encodingparameters>]
1666 InitAttrLine(kAttributeRtpmap, &os);
1667 os << kSdpDelimiterColon << it->id << " ";
1668 os << it->name << "/" << it->clockrate;
1669 if (it->channels != 1) {
1670 os << "/" << it->channels;
1671 }
1672 AddLine(os.str(), message);
1673 AddRtcpFbLines(*it, message);
1674 AddFmtpLine(*it, message);
1675 int minptime = 0;
1676 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1677 max_minptime = std::max(minptime, max_minptime);
1678 }
1679 int ptime;
1680 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1681 ptimes.push_back(ptime);
1682 }
1683 int maxptime;
1684 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1685 maxptimes.push_back(maxptime);
1686 }
1687 }
1688 // Populate the maxptime attribute with the smallest maxptime of all codecs
1689 // under the same m-line.
1690 int min_maxptime = INT_MAX;
1691 if (GetMinValue(maxptimes, &min_maxptime)) {
1692 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1693 }
1694 ASSERT(min_maxptime > max_minptime);
1695 // Populate the ptime attribute with the smallest ptime or the largest
1696 // minptime, whichever is the largest, for all codecs under the same m-line.
1697 int ptime = INT_MAX;
1698 if (GetMinValue(ptimes, &ptime)) {
1699 ptime = std::min(ptime, min_maxptime);
1700 ptime = std::max(ptime, max_minptime);
1701 AddAttributeLine(kCodecParamPTime, ptime, message);
1702 }
1703 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1704 const DataContentDescription* data_desc =
1705 static_cast<const DataContentDescription*>(media_desc);
1706 for (std::vector<cricket::DataCodec>::const_iterator it =
1707 data_desc->codecs().begin();
1708 it != data_desc->codecs().end(); ++it) {
1709 // RFC 4566
1710 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1711 // [/<encodingparameters>]
1712 InitAttrLine(kAttributeRtpmap, &os);
1713 os << kSdpDelimiterColon << it->id << " "
1714 << it->name << "/" << it->clockrate;
1715 AddLine(os.str(), message);
1716 }
1717 }
1718}
1719
1720void BuildCandidate(const std::vector<Candidate>& candidates,
honghaiza54a0802015-12-16 18:37:23 -08001721 bool include_ufrag,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001722 std::string* message) {
1723 std::ostringstream os;
1724
1725 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1726 it != candidates.end(); ++it) {
1727 // RFC 5245
1728 // a=candidate:<foundation> <component-id> <transport> <priority>
1729 // <connection-address> <port> typ <candidate-types>
1730 // [raddr <connection-address>] [rport <port>]
1731 // *(SP extension-att-name SP extension-att-value)
1732 std::string type;
1733 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1734 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1735 type = kCandidateHost;
1736 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1737 type = kCandidateSrflx;
1738 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1739 type = kCandidateRelay;
1740 } else {
1741 ASSERT(false);
Peter Thatcher019087f2015-04-28 09:06:26 -07001742 // Never write out candidates if we don't know the type.
1743 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001744 }
1745
1746 InitAttrLine(kAttributeCandidate, &os);
1747 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001748 << it->foundation() << " "
1749 << it->component() << " "
1750 << it->protocol() << " "
1751 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001752 << it->address().ipaddr().ToString() << " "
1753 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001754 << kAttributeCandidateTyp << " "
1755 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001756
1757 // Related address
1758 if (!it->related_address().IsNil()) {
1759 os << kAttributeCandidateRaddr << " "
1760 << it->related_address().ipaddr().ToString() << " "
1761 << kAttributeCandidateRport << " "
1762 << it->related_address().PortAsString() << " ";
1763 }
1764
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001765 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001766 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001767 }
1768
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001769 // Extensions
1770 os << kAttributeCandidateGeneration << " " << it->generation();
honghaiza54a0802015-12-16 18:37:23 -08001771 if (include_ufrag && !it->username().empty()) {
1772 os << " " << kAttributeCandidateUfrag << " " << it->username();
1773 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001774
1775 AddLine(os.str(), message);
1776 }
1777}
1778
1779void BuildIceOptions(const std::vector<std::string>& transport_options,
1780 std::string* message) {
1781 if (!transport_options.empty()) {
1782 std::ostringstream os;
1783 InitAttrLine(kAttributeIceOption, &os);
1784 os << kSdpDelimiterColon << transport_options[0];
1785 for (size_t i = 1; i < transport_options.size(); ++i) {
1786 os << kSdpDelimiterSpace << transport_options[i];
1787 }
1788 AddLine(os.str(), message);
1789 }
1790}
1791
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001792bool IsRtp(const std::string& protocol) {
1793 return protocol.empty() ||
1794 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1795}
1796
1797bool IsDtlsSctp(const std::string& protocol) {
1798 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001799 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001800}
1801
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001802bool ParseSessionDescription(const std::string& message, size_t* pos,
1803 std::string* session_id,
1804 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001805 TransportDescription* session_td,
1806 RtpHeaderExtensions* session_extmaps,
1807 cricket::SessionDescription* desc,
1808 SdpParseError* error) {
1809 std::string line;
1810
deadbeefc80741f2015-10-22 13:14:45 -07001811 desc->set_msid_supported(false);
1812
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813 // RFC 4566
1814 // v= (protocol version)
1815 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1816 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1817 std::string(), error);
1818 }
1819 // RFC 4566
1820 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1821 // <unicast-address>
1822 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1823 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1824 std::string(), error);
1825 }
1826 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001827 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001828 kSdpDelimiterSpace, &fields);
1829 const size_t expected_fields = 6;
1830 if (fields.size() != expected_fields) {
1831 return ParseFailedExpectFieldNum(line, expected_fields, error);
1832 }
1833 *session_id = fields[1];
1834 *session_version = fields[2];
1835
1836 // RFC 4566
1837 // s= (session name)
1838 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1839 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1840 std::string(), error);
1841 }
1842
1843 // Optional lines
1844 // Those are the optional lines, so shouldn't return false if not present.
1845 // RFC 4566
1846 // i=* (session information)
1847 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1848
1849 // RFC 4566
1850 // u=* (URI of description)
1851 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1852
1853 // RFC 4566
1854 // e=* (email address)
1855 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1856
1857 // RFC 4566
1858 // p=* (phone number)
1859 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1860
1861 // RFC 4566
1862 // c=* (connection information -- not required if included in
1863 // all media)
1864 GetLineWithType(message, pos, &line, kLineTypeConnection);
1865
1866 // RFC 4566
1867 // b=* (zero or more bandwidth information lines)
1868 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1869 // By pass zero or more b lines.
1870 }
1871
1872 // RFC 4566
1873 // One or more time descriptions ("t=" and "r=" lines; see below)
1874 // t= (time the session is active)
1875 // r=* (zero or more repeat times)
1876 // Ensure there's at least one time description
1877 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1878 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1879 error);
1880 }
1881
1882 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1883 // By pass zero or more r lines.
1884 }
1885
1886 // Go through the rest of the time descriptions
1887 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1888 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1889 // By pass zero or more r lines.
1890 }
1891 }
1892
1893 // RFC 4566
1894 // z=* (time zone adjustments)
1895 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1896
1897 // RFC 4566
1898 // k=* (encryption key)
1899 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1900
1901 // RFC 4566
1902 // a=* (zero or more session attribute lines)
1903 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1904 if (HasAttribute(line, kAttributeGroup)) {
1905 if (!ParseGroupAttribute(line, desc, error)) {
1906 return false;
1907 }
1908 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1909 if (!GetValue(line, kAttributeIceUfrag,
1910 &(session_td->ice_ufrag), error)) {
1911 return false;
1912 }
1913 } else if (HasAttribute(line, kAttributeIcePwd)) {
1914 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1915 return false;
1916 }
1917 } else if (HasAttribute(line, kAttributeIceLite)) {
1918 session_td->ice_mode = cricket::ICEMODE_LITE;
1919 } else if (HasAttribute(line, kAttributeIceOption)) {
1920 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1921 return false;
1922 }
1923 } else if (HasAttribute(line, kAttributeFingerprint)) {
1924 if (session_td->identity_fingerprint.get()) {
1925 return ParseFailed(
1926 line,
1927 "Can't have multiple fingerprint attributes at the same level.",
1928 error);
1929 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001930 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001931 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1932 return false;
1933 }
1934 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001935 } else if (HasAttribute(line, kAttributeSetup)) {
1936 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1937 return false;
1938 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001939 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1940 std::string semantics;
1941 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1942 return false;
1943 }
deadbeefc80741f2015-10-22 13:14:45 -07001944 desc->set_msid_supported(
1945 CaseInsensitiveFind(semantics, kMediaStreamSemantic));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001946 } else if (HasAttribute(line, kAttributeExtmap)) {
1947 RtpHeaderExtension extmap;
1948 if (!ParseExtmap(line, &extmap, error)) {
1949 return false;
1950 }
1951 session_extmaps->push_back(extmap);
1952 }
1953 }
1954
1955 return true;
1956}
1957
1958bool ParseGroupAttribute(const std::string& line,
1959 cricket::SessionDescription* desc,
1960 SdpParseError* error) {
1961 ASSERT(desc != NULL);
1962
1963 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1964 // a=group:BUNDLE video voice
1965 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001966 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001967 kSdpDelimiterSpace, &fields);
1968 std::string semantics;
1969 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1970 return false;
1971 }
1972 cricket::ContentGroup group(semantics);
1973 for (size_t i = 1; i < fields.size(); ++i) {
1974 group.AddContentName(fields[i]);
1975 }
1976 desc->AddGroup(group);
1977 return true;
1978}
1979
1980static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001981 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001982 SdpParseError* error) {
1983 if (!IsLineType(line, kLineTypeAttributes) ||
1984 !HasAttribute(line, kAttributeFingerprint)) {
1985 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1986 kAttributeFingerprint, error);
1987 }
1988
1989 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001990 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991 kSdpDelimiterSpace, &fields);
1992 const size_t expected_fields = 2;
1993 if (fields.size() != expected_fields) {
1994 return ParseFailedExpectFieldNum(line, expected_fields, error);
1995 }
1996
1997 // The first field here is "fingerprint:<hash>.
1998 std::string algorithm;
1999 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2000 return false;
2001 }
2002
2003 // Downcase the algorithm. Note that we don't need to downcase the
2004 // fingerprint because hex_decode can handle upper-case.
2005 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2006 ::tolower);
2007
2008 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002009 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010 algorithm, fields[1]);
2011 if (!*fingerprint) {
2012 return ParseFailed(line,
2013 "Failed to create fingerprint from the digest.",
2014 error);
2015 }
2016
2017 return true;
2018}
2019
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002020static bool ParseDtlsSetup(const std::string& line,
2021 cricket::ConnectionRole* role,
2022 SdpParseError* error) {
2023 // setup-attr = "a=setup:" role
2024 // role = "active" / "passive" / "actpass" / "holdconn"
2025 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002026 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002027 const size_t expected_fields = 2;
2028 if (fields.size() != expected_fields) {
2029 return ParseFailedExpectFieldNum(line, expected_fields, error);
2030 }
2031 std::string role_str = fields[1];
2032 if (!cricket::StringToConnectionRole(role_str, role)) {
2033 return ParseFailed(line, "Invalid attribute value.", error);
2034 }
2035 return true;
2036}
2037
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002038// RFC 3551
2039// PT encoding media type clock rate channels
2040// name (Hz)
2041// 0 PCMU A 8,000 1
2042// 1 reserved A
2043// 2 reserved A
2044// 3 GSM A 8,000 1
2045// 4 G723 A 8,000 1
2046// 5 DVI4 A 8,000 1
2047// 6 DVI4 A 16,000 1
2048// 7 LPC A 8,000 1
2049// 8 PCMA A 8,000 1
2050// 9 G722 A 8,000 1
2051// 10 L16 A 44,100 2
2052// 11 L16 A 44,100 1
2053// 12 QCELP A 8,000 1
2054// 13 CN A 8,000 1
2055// 14 MPA A 90,000 (see text)
2056// 15 G728 A 8,000 1
2057// 16 DVI4 A 11,025 1
2058// 17 DVI4 A 22,050 1
2059// 18 G729 A 8,000 1
2060struct StaticPayloadAudioCodec {
2061 const char* name;
2062 int clockrate;
2063 int channels;
2064};
2065static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2066 { "PCMU", 8000, 1 },
2067 { "reserved", 0, 0 },
2068 { "reserved", 0, 0 },
2069 { "GSM", 8000, 1 },
2070 { "G723", 8000, 1 },
2071 { "DVI4", 8000, 1 },
2072 { "DVI4", 16000, 1 },
2073 { "LPC", 8000, 1 },
2074 { "PCMA", 8000, 1 },
2075 { "G722", 8000, 1 },
2076 { "L16", 44100, 2 },
2077 { "L16", 44100, 1 },
2078 { "QCELP", 8000, 1 },
2079 { "CN", 8000, 1 },
2080 { "MPA", 90000, 1 },
2081 { "G728", 8000, 1 },
2082 { "DVI4", 11025, 1 },
2083 { "DVI4", 22050, 1 },
2084 { "G729", 8000, 1 },
2085};
2086
2087void MaybeCreateStaticPayloadAudioCodecs(
2088 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2089 if (!media_desc) {
2090 return;
2091 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002092 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002093 std::vector<int>::const_iterator it = fmts.begin();
2094 bool add_new_codec = false;
2095 for (; it != fmts.end(); ++it) {
2096 int payload_type = *it;
2097 if (!media_desc->HasCodec(payload_type) &&
2098 payload_type >= 0 &&
tfarina5237aaf2015-11-10 23:44:30 -08002099 payload_type < arraysize(kStaticPayloadAudioCodecs)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002100 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2101 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2102 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2103 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2104 clock_rate, 0, channels,
2105 preference));
2106 add_new_codec = true;
2107 }
2108 --preference;
2109 }
2110 if (add_new_codec) {
2111 media_desc->SortCodecs();
2112 }
2113}
2114
2115template <class C>
2116static C* ParseContentDescription(const std::string& message,
2117 const MediaType media_type,
2118 int mline_index,
2119 const std::string& protocol,
2120 const std::vector<int>& codec_preference,
2121 size_t* pos,
2122 std::string* content_name,
2123 TransportDescription* transport,
2124 std::vector<JsepIceCandidate*>* candidates,
2125 webrtc::SdpParseError* error) {
2126 C* media_desc = new C();
2127 switch (media_type) {
2128 case cricket::MEDIA_TYPE_AUDIO:
2129 *content_name = cricket::CN_AUDIO;
2130 break;
2131 case cricket::MEDIA_TYPE_VIDEO:
2132 *content_name = cricket::CN_VIDEO;
2133 break;
2134 case cricket::MEDIA_TYPE_DATA:
2135 *content_name = cricket::CN_DATA;
2136 break;
2137 default:
2138 ASSERT(false);
2139 break;
2140 }
2141 if (!ParseContent(message, media_type, mline_index, protocol,
2142 codec_preference, pos, content_name,
2143 media_desc, transport, candidates, error)) {
2144 delete media_desc;
2145 return NULL;
2146 }
2147 // Sort the codecs according to the m-line fmt list.
2148 media_desc->SortCodecs();
2149 return media_desc;
2150}
2151
2152bool ParseMediaDescription(const std::string& message,
2153 const TransportDescription& session_td,
2154 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002155 size_t* pos,
2156 cricket::SessionDescription* desc,
2157 std::vector<JsepIceCandidate*>* candidates,
2158 SdpParseError* error) {
2159 ASSERT(desc != NULL);
2160 std::string line;
2161 int mline_index = -1;
2162
2163 // Zero or more media descriptions
2164 // RFC 4566
2165 // m=<media> <port> <proto> <fmt>
2166 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2167 ++mline_index;
2168
2169 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002170 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002171 kSdpDelimiterSpace, &fields);
2172 const size_t expected_min_fields = 4;
2173 if (fields.size() < expected_min_fields) {
2174 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2175 }
2176 bool rejected = false;
2177 // RFC 3264
2178 // To reject an offered stream, the port number in the corresponding stream
2179 // in the answer MUST be set to zero.
2180 if (fields[1] == kMediaPortRejected) {
2181 rejected = true;
2182 }
2183
2184 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002185
2186 // <fmt>
2187 std::vector<int> codec_preference;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002188 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002189 for (size_t j = 3 ; j < fields.size(); ++j) {
2190 // TODO(wu): Remove when below bug is fixed.
2191 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002192 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002193 continue;
2194 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002195
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002196 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002197 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002198 return false;
2199 }
2200 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002201 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202 }
2203
2204 // Make a temporary TransportDescription based on |session_td|.
2205 // Some of this gets overwritten by ParseContent.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002206 TransportDescription transport(session_td.transport_options,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002207 session_td.ice_ufrag,
2208 session_td.ice_pwd,
2209 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002210 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211 session_td.identity_fingerprint.get(),
2212 Candidates());
2213
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002214 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002215 std::string content_name;
2216 if (HasAttribute(line, kMediaTypeVideo)) {
2217 content.reset(ParseContentDescription<VideoContentDescription>(
2218 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2219 codec_preference, pos, &content_name,
2220 &transport, candidates, error));
2221 } else if (HasAttribute(line, kMediaTypeAudio)) {
2222 content.reset(ParseContentDescription<AudioContentDescription>(
2223 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2224 codec_preference, pos, &content_name,
2225 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002226 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002227 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002228 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002229 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2230 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002231 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002232 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002233
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002234 int p;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002235 if (data_desc && IsDtlsSctp(protocol) && rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002236 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002237 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002238 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002239 } else {
2240 LOG(LS_WARNING) << "Unsupported media type: " << line;
2241 continue;
2242 }
2243 if (!content.get()) {
2244 // ParseContentDescription returns NULL if failed.
2245 return false;
2246 }
2247
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002248 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002249 // Set the extmap.
2250 if (!session_extmaps.empty() &&
2251 !content->rtp_header_extensions().empty()) {
2252 return ParseFailed("",
2253 "The a=extmap MUST be either all session level or "
2254 "all media level.",
2255 error);
2256 }
2257 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2258 content->AddRtpHeaderExtension(session_extmaps[i]);
2259 }
2260 }
2261 content->set_protocol(protocol);
2262 desc->AddContent(content_name,
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002263 IsDtlsSctp(protocol) ? cricket::NS_JINGLE_DRAFT_SCTP :
2264 cricket::NS_JINGLE_RTP,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002265 rejected,
2266 content.release());
2267 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2268 TransportInfo transport_info(content_name, transport);
2269
2270 if (!desc->AddTransportInfo(transport_info)) {
2271 std::ostringstream description;
2272 description << "Failed to AddTransportInfo with content name: "
2273 << content_name;
2274 return ParseFailed("", description.str(), error);
2275 }
2276 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002277
2278 size_t end_of_message = message.size();
2279 if (mline_index == -1 && *pos != end_of_message) {
2280 ParseFailed(message, *pos, "Expects m line.", error);
2281 return false;
2282 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002283 return true;
2284}
2285
2286bool VerifyCodec(const cricket::Codec& codec) {
2287 // Codec has not been populated correctly unless the name has been set. This
2288 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2289 // have a corresponding "rtpmap" line.
2290 cricket::Codec default_codec;
2291 return default_codec.name != codec.name;
2292}
2293
2294bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2295 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2296 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2297 iter != codecs.end(); ++iter) {
2298 if (!VerifyCodec(*iter)) {
2299 return false;
2300 }
2301 }
2302 return true;
2303}
2304
2305bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2306 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2307 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2308 iter != codecs.end(); ++iter) {
2309 if (!VerifyCodec(*iter)) {
2310 return false;
2311 }
2312 }
2313 return true;
2314}
2315
2316void AddParameters(const cricket::CodecParameterMap& parameters,
2317 cricket::Codec* codec) {
2318 for (cricket::CodecParameterMap::const_iterator iter =
2319 parameters.begin(); iter != parameters.end(); ++iter) {
2320 codec->SetParam(iter->first, iter->second);
2321 }
2322}
2323
2324void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2325 cricket::Codec* codec) {
2326 codec->AddFeedbackParam(feedback_param);
2327}
2328
2329void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2330 cricket::Codec* codec) {
2331 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2332 feedback_params.params().begin();
2333 iter != feedback_params.params().end(); ++iter) {
2334 codec->AddFeedbackParam(*iter);
2335 }
2336}
2337
2338// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002339// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002340// with that payload type.
2341template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002342T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2343 T ret_val;
2344 if (!FindCodecById(codecs, payload_type, &ret_val)) {
2345 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002346 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002347 return ret_val;
2348}
2349
2350// Updates or creates a new codec entry in the audio description.
2351template <class T, class U>
2352void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2353 T* desc = static_cast<T*>(content_desc);
2354 std::vector<U> codecs = desc->codecs();
2355 bool found = false;
2356
2357 typename std::vector<U>::iterator iter;
2358 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2359 if (iter->id == codec.id) {
2360 *iter = codec;
2361 found = true;
2362 break;
2363 }
2364 }
2365 if (!found) {
2366 desc->AddCodec(codec);
2367 return;
2368 }
2369 desc->set_codecs(codecs);
2370}
2371
2372// Adds or updates existing codec corresponding to |payload_type| according
2373// to |parameters|.
2374template <class T, class U>
2375void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2376 const cricket::CodecParameterMap& parameters) {
2377 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002378 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2379 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002380 AddParameters(parameters, &new_codec);
2381 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2382}
2383
2384// Adds or updates existing codec corresponding to |payload_type| according
2385// to |feedback_param|.
2386template <class T, class U>
2387void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2388 const cricket::FeedbackParam& feedback_param) {
2389 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002390 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2391 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002392 AddFeedbackParameter(feedback_param, &new_codec);
2393 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2394}
2395
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002396template <class T>
2397bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2398 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002399 if (iter->id == kWildcardPayloadType) {
2400 *wildcard_codec = *iter;
2401 codecs->erase(iter);
2402 return true;
2403 }
2404 }
2405 return false;
2406}
2407
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002408template<class T>
2409void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2410 auto codecs = desc->codecs();
2411 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002412 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2413 return;
2414 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002415 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002416 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2417 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002418 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002419}
2420
2421void AddAudioAttribute(const std::string& name, const std::string& value,
2422 AudioContentDescription* audio_desc) {
2423 if (value.empty()) {
2424 return;
2425 }
2426 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2427 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2428 iter != codecs.end(); ++iter) {
2429 iter->params[name] = value;
2430 }
2431 audio_desc->set_codecs(codecs);
2432}
2433
2434bool ParseContent(const std::string& message,
2435 const MediaType media_type,
2436 int mline_index,
2437 const std::string& protocol,
2438 const std::vector<int>& codec_preference,
2439 size_t* pos,
2440 std::string* content_name,
2441 MediaContentDescription* media_desc,
2442 TransportDescription* transport,
2443 std::vector<JsepIceCandidate*>* candidates,
2444 SdpParseError* error) {
2445 ASSERT(media_desc != NULL);
2446 ASSERT(content_name != NULL);
2447 ASSERT(transport != NULL);
2448
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002449 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2450 MaybeCreateStaticPayloadAudioCodecs(
2451 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2452 }
2453
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002454 // The media level "ice-ufrag" and "ice-pwd".
2455 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2456 Candidates candidates_orig;
2457 std::string line;
2458 std::string mline_id;
2459 // Tracks created out of the ssrc attributes.
2460 StreamParamsVec tracks;
2461 SsrcInfoVec ssrc_infos;
2462 SsrcGroupVec ssrc_groups;
2463 std::string maxptime_as_string;
2464 std::string ptime_as_string;
2465
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002466 // Loop until the next m line
2467 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2468 if (!GetLine(message, pos, &line)) {
2469 if (*pos >= message.size()) {
2470 break; // Done parsing
2471 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002472 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002473 }
2474 }
2475
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002476 // RFC 4566
2477 // b=* (zero or more bandwidth information lines)
2478 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2479 std::string bandwidth;
2480 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2481 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2482 return false;
2483 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002484 int b = 0;
2485 if (!GetValueFromString(line, bandwidth, &b, error)) {
2486 return false;
2487 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002488 // We should never use more than the default bandwidth for RTP-based
2489 // data channels. Don't allow SDP to set the bandwidth, because
2490 // that would give JS the opportunity to "break the Internet".
2491 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2492 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2493 b > cricket::kDataMaxBandwidth / 1000) {
2494 std::ostringstream description;
2495 description << "RTP-based data channels may not send more than "
2496 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2497 return ParseFailed(line, description.str(), error);
2498 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002499 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002500 }
2501 }
2502 continue;
2503 }
2504
2505 if (!IsLineType(line, kLineTypeAttributes)) {
2506 // TODO: Handle other lines if needed.
2507 LOG(LS_INFO) << "Ignored line: " << line;
2508 continue;
2509 }
2510
2511 // Handle attributes common to SCTP and RTP.
2512 if (HasAttribute(line, kAttributeMid)) {
2513 // RFC 3388
2514 // mid-attribute = "a=mid:" identification-tag
2515 // identification-tag = token
2516 // Use the mid identification-tag as the content name.
2517 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2518 return false;
2519 }
2520 *content_name = mline_id;
2521 } else if (HasAttribute(line, kAttributeCandidate)) {
2522 Candidate candidate;
2523 if (!ParseCandidate(line, &candidate, error, false)) {
2524 return false;
2525 }
2526 candidates_orig.push_back(candidate);
2527 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2528 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2529 return false;
2530 }
2531 } else if (HasAttribute(line, kAttributeIcePwd)) {
2532 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2533 return false;
2534 }
2535 } else if (HasAttribute(line, kAttributeIceOption)) {
2536 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2537 return false;
2538 }
2539 } else if (HasAttribute(line, kAttributeFmtp)) {
2540 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2541 return false;
2542 }
2543 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002544 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002545
2546 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2547 return false;
2548 }
2549 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002550 } else if (HasAttribute(line, kAttributeSetup)) {
2551 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2552 return false;
2553 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002554 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002555 int sctp_port;
2556 if (!ParseSctpPort(line, &sctp_port, error)) {
2557 return false;
2558 }
2559 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2560 sctp_port)) {
2561 return false;
2562 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002563 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002564 //
2565 // RTP specific attrubtes
2566 //
2567 if (HasAttribute(line, kAttributeRtcpMux)) {
2568 media_desc->set_rtcp_mux(true);
deadbeef13871492015-12-09 12:37:51 -08002569 } else if (HasAttribute(line, kAttributeRtcpReducedSize)) {
2570 media_desc->set_rtcp_reduced_size(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002571 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2572 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2573 return false;
2574 }
2575 } else if (HasAttribute(line, kAttributeSsrc)) {
2576 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2577 return false;
2578 }
2579 } else if (HasAttribute(line, kAttributeCrypto)) {
2580 if (!ParseCryptoAttribute(line, media_desc, error)) {
2581 return false;
2582 }
2583 } else if (HasAttribute(line, kAttributeRtpmap)) {
2584 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2585 media_desc, error)) {
2586 return false;
2587 }
2588 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2589 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2590 return false;
2591 }
2592 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2593 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2594 return false;
2595 }
2596 } else if (HasAttribute(line, kCodecParamPTime)) {
2597 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2598 return false;
2599 }
2600 } else if (HasAttribute(line, kAttributeSendOnly)) {
2601 media_desc->set_direction(cricket::MD_SENDONLY);
2602 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2603 media_desc->set_direction(cricket::MD_RECVONLY);
2604 } else if (HasAttribute(line, kAttributeInactive)) {
2605 media_desc->set_direction(cricket::MD_INACTIVE);
2606 } else if (HasAttribute(line, kAttributeSendRecv)) {
2607 media_desc->set_direction(cricket::MD_SENDRECV);
2608 } else if (HasAttribute(line, kAttributeExtmap)) {
2609 RtpHeaderExtension extmap;
2610 if (!ParseExtmap(line, &extmap, error)) {
2611 return false;
2612 }
2613 media_desc->AddRtpHeaderExtension(extmap);
2614 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2615 // Experimental attribute. Conference mode activates more aggressive
2616 // AEC and NS settings.
2617 // TODO: expose API to set these directly.
2618 std::string flag_value;
2619 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2620 return false;
2621 }
2622 if (flag_value.compare(kValueConference) == 0)
2623 media_desc->set_conference_mode(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002624 }
2625 } else {
2626 // Only parse lines that we are interested of.
2627 LOG(LS_INFO) << "Ignored line: " << line;
2628 continue;
2629 }
2630 }
2631
2632 // Create tracks from the |ssrc_infos|.
2633 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2634
2635 // Add the ssrc group to the track.
2636 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2637 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2638 if (ssrc_group->ssrcs.empty()) {
2639 continue;
2640 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002641 uint32_t ssrc = ssrc_group->ssrcs.front();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002642 for (StreamParamsVec::iterator track = tracks.begin();
2643 track != tracks.end(); ++track) {
2644 if (track->has_ssrc(ssrc)) {
2645 track->ssrc_groups.push_back(*ssrc_group);
2646 }
2647 }
2648 }
2649
2650 // Add the new tracks to the |media_desc|.
2651 for (StreamParamsVec::iterator track = tracks.begin();
2652 track != tracks.end(); ++track) {
2653 media_desc->AddStream(*track);
2654 }
2655
2656 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2657 AudioContentDescription* audio_desc =
2658 static_cast<AudioContentDescription*>(media_desc);
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002659 UpdateFromWildcardCodecs(audio_desc);
2660
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002661 // Verify audio codec ensures that no audio codec has been populated with
2662 // only fmtp.
2663 if (!VerifyAudioCodecs(audio_desc)) {
2664 return ParseFailed("Failed to parse audio codecs correctly.", error);
2665 }
2666 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2667 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2668 }
2669
2670 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002671 VideoContentDescription* video_desc =
2672 static_cast<VideoContentDescription*>(media_desc);
2673 UpdateFromWildcardCodecs(video_desc);
2674 // Verify video codec ensures that no video codec has been populated with
2675 // only rtcp-fb.
2676 if (!VerifyVideoCodecs(video_desc)) {
2677 return ParseFailed("Failed to parse video codecs correctly.", error);
2678 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002679 }
2680
2681 // RFC 5245
2682 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2683 for (Candidates::iterator it = candidates_orig.begin();
2684 it != candidates_orig.end(); ++it) {
honghaiza54a0802015-12-16 18:37:23 -08002685 ASSERT((*it).username().empty() ||
2686 (*it).username() == transport->ice_ufrag);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002687 (*it).set_username(transport->ice_ufrag);
2688 ASSERT((*it).password().empty());
2689 (*it).set_password(transport->ice_pwd);
2690 candidates->push_back(
2691 new JsepIceCandidate(mline_id, mline_index, *it));
2692 }
2693 return true;
2694}
2695
2696bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2697 SdpParseError* error) {
2698 ASSERT(ssrc_infos != NULL);
2699 // RFC 5576
2700 // a=ssrc:<ssrc-id> <attribute>
2701 // a=ssrc:<ssrc-id> <attribute>:<value>
2702 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07002703 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2704 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002705 const size_t expected_fields = 2;
2706 return ParseFailedExpectFieldNum(line, expected_fields, error);
2707 }
2708
2709 // ssrc:<ssrc-id>
2710 std::string ssrc_id_s;
2711 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2712 return false;
2713 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002714 uint32_t ssrc_id = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002715 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2716 return false;
2717 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002718
2719 std::string attribute;
2720 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07002721 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002722 std::ostringstream description;
2723 description << "Failed to get the ssrc attribute value from " << field2
2724 << ". Expected format <attribute>:<value>.";
2725 return ParseFailed(line, description.str(), error);
2726 }
2727
2728 // Check if there's already an item for this |ssrc_id|. Create a new one if
2729 // there isn't.
2730 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2731 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2732 if (ssrc_info->ssrc_id == ssrc_id) {
2733 break;
2734 }
2735 }
2736 if (ssrc_info == ssrc_infos->end()) {
2737 SsrcInfo info;
2738 info.ssrc_id = ssrc_id;
2739 ssrc_infos->push_back(info);
2740 ssrc_info = ssrc_infos->end() - 1;
2741 }
2742
2743 // Store the info to the |ssrc_info|.
2744 if (attribute == kSsrcAttributeCname) {
2745 // RFC 5576
2746 // cname:<value>
2747 ssrc_info->cname = value;
2748 } else if (attribute == kSsrcAttributeMsid) {
2749 // draft-alvestrand-mmusic-msid-00
2750 // "msid:" identifier [ " " appdata ]
2751 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002752 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002753 if (fields.size() < 1 || fields.size() > 2) {
2754 return ParseFailed(line,
2755 "Expected format \"msid:<identifier>[ <appdata>]\".",
2756 error);
2757 }
2758 ssrc_info->msid_identifier = fields[0];
2759 if (fields.size() == 2) {
2760 ssrc_info->msid_appdata = fields[1];
2761 }
2762 } else if (attribute == kSsrcAttributeMslabel) {
2763 // draft-alvestrand-rtcweb-mid-01
2764 // mslabel:<value>
2765 ssrc_info->mslabel = value;
2766 } else if (attribute == kSSrcAttributeLabel) {
2767 // The label isn't defined.
2768 // label:<value>
2769 ssrc_info->label = value;
2770 }
2771 return true;
2772}
2773
2774bool ParseSsrcGroupAttribute(const std::string& line,
2775 SsrcGroupVec* ssrc_groups,
2776 SdpParseError* error) {
2777 ASSERT(ssrc_groups != NULL);
2778 // RFC 5576
2779 // a=ssrc-group:<semantics> <ssrc-id> ...
2780 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002781 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002782 kSdpDelimiterSpace, &fields);
2783 const size_t expected_min_fields = 2;
2784 if (fields.size() < expected_min_fields) {
2785 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2786 }
2787 std::string semantics;
2788 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2789 return false;
2790 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002791 std::vector<uint32_t> ssrcs;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002792 for (size_t i = 1; i < fields.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02002793 uint32_t ssrc = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002794 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2795 return false;
2796 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002797 ssrcs.push_back(ssrc);
2798 }
2799 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2800 return true;
2801}
2802
2803bool ParseCryptoAttribute(const std::string& line,
2804 MediaContentDescription* media_desc,
2805 SdpParseError* error) {
2806 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002807 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002808 kSdpDelimiterSpace, &fields);
2809 // RFC 4568
2810 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2811 const size_t expected_min_fields = 3;
2812 if (fields.size() < expected_min_fields) {
2813 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2814 }
2815 std::string tag_value;
2816 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2817 return false;
2818 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002819 int tag = 0;
2820 if (!GetValueFromString(line, tag_value, &tag, error)) {
2821 return false;
2822 }
jbauch083b73f2015-07-16 02:46:32 -07002823 const std::string& crypto_suite = fields[1];
2824 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002825 std::string session_params;
2826 if (fields.size() > 3) {
2827 session_params = fields[3];
2828 }
2829 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2830 session_params));
2831 return true;
2832}
2833
2834// Updates or creates a new codec entry in the audio description with according
2835// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2836void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2837 int bitrate, int channels, int preference,
2838 AudioContentDescription* audio_desc) {
2839 // Codec may already be populated with (only) optional parameters
2840 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002841 cricket::AudioCodec codec =
2842 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002843 codec.name = name;
2844 codec.clockrate = clockrate;
2845 codec.bitrate = bitrate;
2846 codec.channels = channels;
2847 codec.preference = preference;
2848 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2849 codec);
2850}
2851
2852// Updates or creates a new codec entry in the video description according to
2853// |name|, |width|, |height|, |framerate| and |preference|.
2854void UpdateCodec(int payload_type, const std::string& name, int width,
2855 int height, int framerate, int preference,
2856 VideoContentDescription* video_desc) {
2857 // Codec may already be populated with (only) optional parameters
2858 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002859 cricket::VideoCodec codec =
2860 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002861 codec.name = name;
2862 codec.width = width;
2863 codec.height = height;
2864 codec.framerate = framerate;
2865 codec.preference = preference;
2866 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2867 codec);
2868}
2869
2870bool ParseRtpmapAttribute(const std::string& line,
2871 const MediaType media_type,
2872 const std::vector<int>& codec_preference,
2873 MediaContentDescription* media_desc,
2874 SdpParseError* error) {
2875 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002876 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002877 kSdpDelimiterSpace, &fields);
2878 // RFC 4566
2879 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2880 const size_t expected_min_fields = 2;
2881 if (fields.size() < expected_min_fields) {
2882 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2883 }
2884 std::string payload_type_value;
2885 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2886 return false;
2887 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002888 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002889 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
2890 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002891 return false;
2892 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002893
2894 // Set the preference order depending on the order of the pl type in the
2895 // <fmt> of the m-line.
2896 const int preference = codec_preference.end() -
2897 std::find(codec_preference.begin(), codec_preference.end(),
2898 payload_type);
2899 if (preference == 0) {
2900 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2901 << "<fmt> of the m-line: " << line;
2902 return true;
2903 }
jbauch083b73f2015-07-16 02:46:32 -07002904 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002905 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002906 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002907 // <encoding name>/<clock rate>[/<encodingparameters>]
2908 // 2 mandatory fields
2909 if (codec_params.size() < 2 || codec_params.size() > 3) {
2910 return ParseFailed(line,
2911 "Expected format \"<encoding name>/<clock rate>"
2912 "[/<encodingparameters>]\".",
2913 error);
2914 }
jbauch083b73f2015-07-16 02:46:32 -07002915 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002916 int clock_rate = 0;
2917 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2918 return false;
2919 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002920 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2921 VideoContentDescription* video_desc =
2922 static_cast<VideoContentDescription*>(media_desc);
2923 // TODO: We will send resolution in SDP. For now use
2924 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2925 UpdateCodec(payload_type, encoding_name,
2926 JsepSessionDescription::kMaxVideoCodecWidth,
2927 JsepSessionDescription::kMaxVideoCodecHeight,
2928 JsepSessionDescription::kDefaultVideoCodecFramerate,
2929 preference, video_desc);
2930 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2931 // RFC 4566
2932 // For audio streams, <encoding parameters> indicates the number
2933 // of audio channels. This parameter is OPTIONAL and may be
2934 // omitted if the number of channels is one, provided that no
2935 // additional parameters are needed.
2936 int channels = 1;
2937 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002938 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2939 return false;
2940 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002941 }
2942 int bitrate = 0;
2943 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2944 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2945 // The bandwidth adaptation doesn't always work well, so this code
2946 // sets a fixed target bitrate instead.
2947 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2948 if (clock_rate <= 16000) {
2949 bitrate = kIsacWbDefaultRate;
2950 } else {
2951 bitrate = kIsacSwbDefaultRate;
2952 }
2953 }
2954 AudioContentDescription* audio_desc =
2955 static_cast<AudioContentDescription*>(media_desc);
2956 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2957 preference, audio_desc);
2958 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2959 DataContentDescription* data_desc =
2960 static_cast<DataContentDescription*>(media_desc);
2961 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2962 preference));
2963 }
2964 return true;
2965}
2966
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002967bool ParseFmtpParam(const std::string& line, std::string* parameter,
2968 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07002969 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002970 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2971 return false;
2972 }
2973 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002974 return true;
2975}
2976
2977bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
2978 MediaContentDescription* media_desc,
2979 SdpParseError* error) {
2980 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2981 media_type != cricket::MEDIA_TYPE_VIDEO) {
2982 return true;
2983 }
Donald Curtis0e07f922015-05-15 09:21:23 -07002984
2985 std::string line_payload;
2986 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002987
2988 // RFC 5576
2989 // a=fmtp:<format> <format specific parameters>
2990 // At least two fields, whereas the second one is any of the optional
2991 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07002992 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2993 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002994 ParseFailedExpectMinFieldNum(line, 2, error);
2995 return false;
2996 }
2997
Donald Curtis0e07f922015-05-15 09:21:23 -07002998 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00002999 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07003000 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003001 return false;
3002 }
3003
Donald Curtis0e07f922015-05-15 09:21:23 -07003004 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07003005 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3006 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003007 return false;
3008 }
3009
3010 // Parse out format specific parameters.
3011 std::vector<std::string> fields;
3012 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
3013
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003014 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07003015 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003016 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003017 // Only fmtps with equals are currently supported. Other fmtp types
3018 // should be ignored. Unknown fmtps do not constitute an error.
3019 continue;
3020 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003021
3022 std::string name;
3023 std::string value;
3024 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003025 return false;
3026 }
3027 codec_params[name] = value;
3028 }
3029
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003030 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3031 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003032 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003033 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3034 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003035 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003036 }
3037 return true;
3038}
3039
3040bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3041 MediaContentDescription* media_desc,
3042 SdpParseError* error) {
3043 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3044 media_type != cricket::MEDIA_TYPE_VIDEO) {
3045 return true;
3046 }
3047 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003048 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003049 if (rtcp_fb_fields.size() < 2) {
3050 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3051 }
3052 std::string payload_type_string;
3053 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3054 error)) {
3055 return false;
3056 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003057 int payload_type = kWildcardPayloadType;
3058 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003059 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3060 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003061 return false;
3062 }
3063 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003064 std::string id = rtcp_fb_fields[1];
3065 std::string param = "";
3066 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3067 iter != rtcp_fb_fields.end(); ++iter) {
3068 param.append(*iter);
3069 }
3070 const cricket::FeedbackParam feedback_param(id, param);
3071
3072 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003073 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3074 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003075 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003076 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3077 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003078 }
3079 return true;
3080}
3081
3082} // namespace webrtc