blob: 1fca0aec8143f2fd9a4aacfaf830b619a0bd294b [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2011, Google Inc.
4 *
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"
mallinath@webrtc.org1112c302013-09-23 20:34:45 +000042#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000043#include "webrtc/p2p/base/candidate.h"
44#include "webrtc/p2p/base/constants.h"
45#include "webrtc/p2p/base/port.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000046#include "talk/session/media/mediasession.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000047#include "webrtc/base/common.h"
48#include "webrtc/base/logging.h"
49#include "webrtc/base/messagedigest.h"
50#include "webrtc/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051
52using cricket::AudioContentDescription;
53using cricket::Candidate;
54using cricket::Candidates;
55using cricket::ContentDescription;
56using cricket::ContentInfo;
57using cricket::CryptoParams;
58using cricket::DataContentDescription;
59using cricket::ICE_CANDIDATE_COMPONENT_RTP;
60using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
61using cricket::kCodecParamMaxBitrate;
62using cricket::kCodecParamMaxPTime;
63using cricket::kCodecParamMaxQuantization;
64using cricket::kCodecParamMinBitrate;
65using cricket::kCodecParamMinPTime;
66using cricket::kCodecParamPTime;
67using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000068using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069using cricket::kCodecParamStereo;
70using cricket::kCodecParamUseInbandFec;
71using cricket::kCodecParamSctpProtocol;
72using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000073using cricket::kCodecParamMaxAverageBitrate;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000074using cricket::kCodecParamMaxPlaybackRate;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000075using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000076using cricket::kWildcardPayloadType;
77using cricket::MediaContentDescription;
78using cricket::MediaType;
79using cricket::NS_JINGLE_ICE_UDP;
80using cricket::RtpHeaderExtension;
81using cricket::SsrcGroup;
82using cricket::StreamParams;
83using cricket::StreamParamsVec;
84using cricket::TransportDescription;
85using cricket::TransportInfo;
86using cricket::VideoContentDescription;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000087using rtc::SocketAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088
89typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
90
91namespace cricket {
92class SessionDescription;
93}
94
95namespace webrtc {
96
97// Line type
98// RFC 4566
99// An SDP session description consists of a number of lines of text of
100// the form:
101// <type>=<value>
102// where <type> MUST be exactly one case-significant character.
103static const int kLinePrefixLength = 2; // Lenght of <type>=
104static const char kLineTypeVersion = 'v';
105static const char kLineTypeOrigin = 'o';
106static const char kLineTypeSessionName = 's';
107static const char kLineTypeSessionInfo = 'i';
108static const char kLineTypeSessionUri = 'u';
109static const char kLineTypeSessionEmail = 'e';
110static const char kLineTypeSessionPhone = 'p';
111static const char kLineTypeSessionBandwidth = 'b';
112static const char kLineTypeTiming = 't';
113static const char kLineTypeRepeatTimes = 'r';
114static const char kLineTypeTimeZone = 'z';
115static const char kLineTypeEncryptionKey = 'k';
116static const char kLineTypeMedia = 'm';
117static const char kLineTypeConnection = 'c';
118static const char kLineTypeAttributes = 'a';
119
120// Attributes
121static const char kAttributeGroup[] = "group";
122static const char kAttributeMid[] = "mid";
123static const char kAttributeRtcpMux[] = "rtcp-mux";
124static const char kAttributeSsrc[] = "ssrc";
125static const char kSsrcAttributeCname[] = "cname";
126static const char kAttributeExtmap[] = "extmap";
127// draft-alvestrand-mmusic-msid-01
128// a=msid-semantic: WMS
129static const char kAttributeMsidSemantics[] = "msid-semantic";
130static const char kMediaStreamSemantic[] = "WMS";
131static const char kSsrcAttributeMsid[] = "msid";
132static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133static const char kSsrcAttributeMslabel[] = "mslabel";
134static const char kSSrcAttributeLabel[] = "label";
135static const char kAttributeSsrcGroup[] = "ssrc-group";
136static const char kAttributeCrypto[] = "crypto";
137static const char kAttributeCandidate[] = "candidate";
138static const char kAttributeCandidateTyp[] = "typ";
139static const char kAttributeCandidateRaddr[] = "raddr";
140static const char kAttributeCandidateRport[] = "rport";
141static const char kAttributeCandidateUsername[] = "username";
142static const char kAttributeCandidatePassword[] = "password";
143static const char kAttributeCandidateGeneration[] = "generation";
144static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000145static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000146static const char kAttributeFmtp[] = "fmtp";
147static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000148static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000149static const char kAttributeRtcp[] = "rtcp";
150static const char kAttributeIceUfrag[] = "ice-ufrag";
151static const char kAttributeIcePwd[] = "ice-pwd";
152static const char kAttributeIceLite[] = "ice-lite";
153static const char kAttributeIceOption[] = "ice-options";
154static const char kAttributeSendOnly[] = "sendonly";
155static const char kAttributeRecvOnly[] = "recvonly";
156static const char kAttributeRtcpFb[] = "rtcp-fb";
157static const char kAttributeSendRecv[] = "sendrecv";
158static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000159// draft-ietf-mmusic-sctp-sdp-07
160// a=sctp-port
161static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000162
163// Experimental flags
164static const char kAttributeXGoogleFlag[] = "x-google-flag";
165static const char kValueConference[] = "conference";
166static const char kAttributeXGoogleBufferLatency[] =
167 "x-google-buffer-latency";
168
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
225struct SsrcInfo {
226 SsrcInfo()
227 : msid_identifier(kDefaultMsid),
228 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
229 // Create random string (which will be used as track label later)?
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000230 msid_appdata(rtc::CreateRandomString(8)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000231 }
232 uint32 ssrc_id;
233 std::string cname;
234 std::string msid_identifier;
235 std::string msid_appdata;
236
237 // For backward compatibility.
238 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
239 std::string label;
240 std::string mslabel;
241};
242typedef std::vector<SsrcInfo> SsrcInfoVec;
243typedef std::vector<SsrcGroup> SsrcGroupVec;
244
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000245template <class T>
246static void AddFmtpLine(const T& codec, std::string* message);
247static void BuildMediaDescription(const ContentInfo* content_info,
248 const TransportInfo* transport_info,
249 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000250 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000251 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000252static void BuildSctpContentAttributes(std::string* message, int sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000253static void BuildRtpContentAttributes(
254 const MediaContentDescription* media_desc,
255 const MediaType media_type,
256 std::string* message);
257static void BuildRtpMap(const MediaContentDescription* media_desc,
258 const MediaType media_type,
259 std::string* message);
260static void BuildCandidate(const std::vector<Candidate>& candidates,
261 std::string* message);
262static void BuildIceOptions(const std::vector<std::string>& transport_options,
263 std::string* message);
264
265static bool ParseSessionDescription(const std::string& message, size_t* pos,
266 std::string* session_id,
267 std::string* session_version,
268 bool* supports_msid,
269 TransportDescription* session_td,
270 RtpHeaderExtensions* session_extmaps,
271 cricket::SessionDescription* desc,
272 SdpParseError* error);
273static bool ParseGroupAttribute(const std::string& line,
274 cricket::SessionDescription* desc,
275 SdpParseError* error);
276static bool ParseMediaDescription(
277 const std::string& message,
278 const TransportDescription& session_td,
279 const RtpHeaderExtensions& session_extmaps,
280 bool supports_msid,
281 size_t* pos, cricket::SessionDescription* desc,
282 std::vector<JsepIceCandidate*>* candidates,
283 SdpParseError* error);
284static bool ParseContent(const std::string& message,
285 const MediaType media_type,
286 int mline_index,
287 const std::string& protocol,
288 const std::vector<int>& codec_preference,
289 size_t* pos,
290 std::string* content_name,
291 MediaContentDescription* media_desc,
292 TransportDescription* transport,
293 std::vector<JsepIceCandidate*>* candidates,
294 SdpParseError* error);
295static bool ParseSsrcAttribute(const std::string& line,
296 SsrcInfoVec* ssrc_infos,
297 SdpParseError* error);
298static bool ParseSsrcGroupAttribute(const std::string& line,
299 SsrcGroupVec* ssrc_groups,
300 SdpParseError* error);
301static bool ParseCryptoAttribute(const std::string& line,
302 MediaContentDescription* media_desc,
303 SdpParseError* error);
304static bool ParseRtpmapAttribute(const std::string& line,
305 const MediaType media_type,
306 const std::vector<int>& codec_preference,
307 MediaContentDescription* media_desc,
308 SdpParseError* error);
309static bool ParseFmtpAttributes(const std::string& line,
310 const MediaType media_type,
311 MediaContentDescription* media_desc,
312 SdpParseError* error);
313static bool ParseFmtpParam(const std::string& line, std::string* parameter,
314 std::string* value, SdpParseError* error);
315static bool ParseCandidate(const std::string& message, Candidate* candidate,
316 SdpParseError* error, bool is_raw);
317static bool ParseRtcpFbAttribute(const std::string& line,
318 const MediaType media_type,
319 MediaContentDescription* media_desc,
320 SdpParseError* error);
321static bool ParseIceOptions(const std::string& line,
322 std::vector<std::string>* transport_options,
323 SdpParseError* error);
324static bool ParseExtmap(const std::string& line,
325 RtpHeaderExtension* extmap,
326 SdpParseError* error);
327static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000328 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000329 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000330static bool ParseDtlsSetup(const std::string& line,
331 cricket::ConnectionRole* role,
332 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000333
334// Helper functions
335
336// Below ParseFailed*** functions output the line that caused the parsing
337// failure and the detailed reason (|description|) of the failure to |error|.
338// The functions always return false so that they can be used directly in the
339// following way when error happens:
340// "return ParseFailed***(...);"
341
342// The line starting at |line_start| of |message| is the failing line.
343// The reason for the failure should be provided in the |description|.
344// An example of a description could be "unknown character".
345static bool ParseFailed(const std::string& message,
346 size_t line_start,
347 const std::string& description,
348 SdpParseError* error) {
349 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000350 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000351 size_t line_end = message.find(kNewLine, line_start);
352 if (line_end != std::string::npos) {
353 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
354 --line_end;
355 }
356 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000357 } else {
358 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000359 }
360
361 if (error) {
362 error->line = first_line;
363 error->description = description;
364 }
365 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
366 << "\". Reason: " << description;
367 return false;
368}
369
370// |line| is the failing line. The reason for the failure should be
371// provided in the |description|.
372static bool ParseFailed(const std::string& line,
373 const std::string& description,
374 SdpParseError* error) {
375 return ParseFailed(line, 0, description, error);
376}
377
378// Parses failure where the failing SDP line isn't know or there are multiple
379// failing lines.
380static bool ParseFailed(const std::string& description,
381 SdpParseError* error) {
382 return ParseFailed("", description, error);
383}
384
385// |line| is the failing line. The failure is due to the fact that |line|
386// doesn't have |expected_fields| fields.
387static bool ParseFailedExpectFieldNum(const std::string& line,
388 int expected_fields,
389 SdpParseError* error) {
390 std::ostringstream description;
391 description << "Expects " << expected_fields << " fields.";
392 return ParseFailed(line, description.str(), error);
393}
394
395// |line| is the failing line. The failure is due to the fact that |line| has
396// less than |expected_min_fields| fields.
397static bool ParseFailedExpectMinFieldNum(const std::string& line,
398 int expected_min_fields,
399 SdpParseError* error) {
400 std::ostringstream description;
401 description << "Expects at least " << expected_min_fields << " fields.";
402 return ParseFailed(line, description.str(), error);
403}
404
405// |line| is the failing line. The failure is due to the fact that it failed to
406// get the value of |attribute|.
407static bool ParseFailedGetValue(const std::string& line,
408 const std::string& attribute,
409 SdpParseError* error) {
410 std::ostringstream description;
411 description << "Failed to get the value of attribute: " << attribute;
412 return ParseFailed(line, description.str(), error);
413}
414
415// The line starting at |line_start| of |message| is the failing line. The
416// failure is due to the line type (e.g. the "m" part of the "m-line")
417// not matching what is expected. The expected line type should be
418// provided as |line_type|.
419static bool ParseFailedExpectLine(const std::string& message,
420 size_t line_start,
421 const char line_type,
422 const std::string& line_value,
423 SdpParseError* error) {
424 std::ostringstream description;
425 description << "Expect line: " << line_type << "=" << line_value;
426 return ParseFailed(message, line_start, description.str(), error);
427}
428
429static bool AddLine(const std::string& line, std::string* message) {
430 if (!message)
431 return false;
432
433 message->append(line);
434 message->append(kLineBreak);
435 return true;
436}
437
438static bool GetLine(const std::string& message,
439 size_t* pos,
440 std::string* line) {
441 size_t line_begin = *pos;
442 size_t line_end = message.find(kNewLine, line_begin);
443 if (line_end == std::string::npos) {
444 return false;
445 }
446 // Update the new start position
447 *pos = line_end + 1;
448 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
449 --line_end;
450 }
451 *line = message.substr(line_begin, (line_end - line_begin));
452 const char* cline = line->c_str();
453 // RFC 4566
454 // An SDP session description consists of a number of lines of text of
455 // the form:
456 // <type>=<value>
457 // where <type> MUST be exactly one case-significant character and
458 // <value> is structured text whose format depends on <type>.
459 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000460 if (line->length() < 3 ||
461 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000462 cline[1] != kSdpDelimiterEqual ||
463 cline[2] == kSdpDelimiterSpace) {
464 *pos = line_begin;
465 return false;
466 }
467 return true;
468}
469
470// Init |os| to "|type|=|value|".
471static void InitLine(const char type,
472 const std::string& value,
473 std::ostringstream* os) {
474 os->str("");
475 *os << type << kSdpDelimiterEqual << value;
476}
477
478// Init |os| to "a=|attribute|".
479static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
480 InitLine(kLineTypeAttributes, attribute, os);
481}
482
483// Writes a SDP attribute line based on |attribute| and |value| to |message|.
484static void AddAttributeLine(const std::string& attribute, int value,
485 std::string* message) {
486 std::ostringstream os;
487 InitAttrLine(attribute, &os);
488 os << kSdpDelimiterColon << value;
489 AddLine(os.str(), message);
490}
491
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000492static bool IsLineType(const std::string& message,
493 const char type,
494 size_t line_start) {
495 if (message.size() < line_start + kLinePrefixLength) {
496 return false;
497 }
498 const char* cmessage = message.c_str();
499 return (cmessage[line_start] == type &&
500 cmessage[line_start + 1] == kSdpDelimiterEqual);
501}
502
503static bool IsLineType(const std::string& line,
504 const char type) {
505 return IsLineType(line, type, 0);
506}
507
508static bool GetLineWithType(const std::string& message, size_t* pos,
509 std::string* line, const char type) {
510 if (!IsLineType(message, type, *pos)) {
511 return false;
512 }
513
514 if (!GetLine(message, pos, line))
515 return false;
516
517 return true;
518}
519
520static bool HasAttribute(const std::string& line,
521 const std::string& attribute) {
522 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
523}
524
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000525static bool AddSsrcLine(uint32 ssrc_id, const std::string& attribute,
526 const std::string& value, std::string* message) {
527 // RFC 5576
528 // a=ssrc:<ssrc-id> <attribute>:<value>
529 std::ostringstream os;
530 InitAttrLine(kAttributeSsrc, &os);
531 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
532 << attribute << kSdpDelimiterColon << value;
533 return AddLine(os.str(), message);
534}
535
536// Split the message into two parts by the first delimiter.
537static bool SplitByDelimiter(const std::string& message,
538 const char delimiter,
539 std::string* field1,
540 std::string* field2) {
541 // Find the first delimiter
542 size_t pos = message.find(delimiter);
543 if (pos == std::string::npos) {
544 return false;
545 }
546 *field1 = message.substr(0, pos);
547 // The rest is the value.
548 *field2 = message.substr(pos + 1);
549 return true;
550}
551
552// Get value only from <attribute>:<value>.
553static bool GetValue(const std::string& message, const std::string& attribute,
554 std::string* value, SdpParseError* error) {
555 std::string leftpart;
556 if (!SplitByDelimiter(message, kSdpDelimiterColon, &leftpart, value)) {
557 return ParseFailedGetValue(message, attribute, error);
558 }
559 // The left part should end with the expected attribute.
560 if (leftpart.length() < attribute.length() ||
561 leftpart.compare(leftpart.length() - attribute.length(),
562 attribute.length(), attribute) != 0) {
563 return ParseFailedGetValue(message, attribute, error);
564 }
565 return true;
566}
567
568static bool CaseInsensitiveFind(std::string str1, std::string str2) {
569 std::transform(str1.begin(), str1.end(), str1.begin(),
570 ::tolower);
571 std::transform(str2.begin(), str2.end(), str2.begin(),
572 ::tolower);
573 return str1.find(str2) != std::string::npos;
574}
575
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000576template <class T>
577static bool GetValueFromString(const std::string& line,
578 const std::string& s,
579 T* t,
580 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000581 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000582 std::ostringstream description;
583 description << "Invalid value: " << s << ".";
584 return ParseFailed(line, description.str(), error);
585 }
586 return true;
587}
588
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
590 StreamParamsVec* tracks) {
591 ASSERT(tracks != NULL);
592 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
593 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
594 if (ssrc_info->cname.empty()) {
595 continue;
596 }
597
598 std::string sync_label;
599 std::string track_id;
600 if (ssrc_info->msid_identifier == kDefaultMsid &&
601 !ssrc_info->mslabel.empty()) {
602 // If there's no msid and there's mslabel, we consider this is a sdp from
603 // a older version of client that doesn't support msid.
604 // In that case, we use the mslabel and label to construct the track.
605 sync_label = ssrc_info->mslabel;
606 track_id = ssrc_info->label;
607 } else {
608 sync_label = ssrc_info->msid_identifier;
609 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
610 // is corresponding to the "id" attribute of StreamParams.
611 track_id = ssrc_info->msid_appdata;
612 }
613 if (sync_label.empty() || track_id.empty()) {
614 ASSERT(false);
615 continue;
616 }
617
618 StreamParamsVec::iterator track = tracks->begin();
619 for (; track != tracks->end(); ++track) {
620 if (track->id == track_id) {
621 break;
622 }
623 }
624 if (track == tracks->end()) {
625 // If we don't find an existing track, create a new one.
626 tracks->push_back(StreamParams());
627 track = tracks->end() - 1;
628 }
629 track->add_ssrc(ssrc_info->ssrc_id);
630 track->cname = ssrc_info->cname;
631 track->sync_label = sync_label;
632 track->id = track_id;
633 }
634}
635
636void GetMediaStreamLabels(const ContentInfo* content,
637 std::set<std::string>* labels) {
638 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000639 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000640 content->description);
641 const cricket::StreamParamsVec& streams = media_desc->streams();
642 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
643 it != streams.end(); ++it) {
644 labels->insert(it->sync_label);
645 }
646}
647
648// RFC 5245
649// It is RECOMMENDED that default candidates be chosen based on the
650// likelihood of those candidates to work with the peer that is being
651// contacted. It is RECOMMENDED that relayed > reflexive > host.
652static const int kPreferenceUnknown = 0;
653static const int kPreferenceHost = 1;
654static const int kPreferenceReflexive = 2;
655static const int kPreferenceRelayed = 3;
656
657static int GetCandidatePreferenceFromType(const std::string& type) {
658 int preference = kPreferenceUnknown;
659 if (type == cricket::LOCAL_PORT_TYPE) {
660 preference = kPreferenceHost;
661 } else if (type == cricket::STUN_PORT_TYPE) {
662 preference = kPreferenceReflexive;
663 } else if (type == cricket::RELAY_PORT_TYPE) {
664 preference = kPreferenceRelayed;
665 } else {
666 ASSERT(false);
667 }
668 return preference;
669}
670
671// Get ip and port of the default destination from the |candidates| with
672// the given value of |component_id|.
673// RFC 5245
674// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
675// TODO: Decide the default destination in webrtcsession and
676// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000677static void GetDefaultDestination(
678 const std::vector<Candidate>& candidates,
679 int component_id, std::string* port,
680 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000681 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000682 *port = kDummyPort;
683 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684 int current_preference = kPreferenceUnknown;
685 for (std::vector<Candidate>::const_iterator it = candidates.begin();
686 it != candidates.end(); ++it) {
687 if (it->component() != component_id) {
688 continue;
689 }
690 const int preference = GetCandidatePreferenceFromType(it->type());
691 // See if this candidate is more preferable then the current one.
692 if (preference <= current_preference) {
693 continue;
694 }
695 current_preference = preference;
696 *port = it->address().PortAsString();
697 *ip = it->address().ipaddr().ToString();
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000698 int family = it->address().ipaddr().family();
699 if (family == AF_INET) {
700 addr_type->assign(kConnectionIpv4Addrtype);
701 } else if (family == AF_INET6) {
702 addr_type->assign(kConnectionIpv6Addrtype);
703 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705}
706
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000707// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000708static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000709 const std::vector<Candidate>& candidates,
710 const std::string mline,
711 std::string* message) {
712 std::string new_lines;
713 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000714 // RFC 4566
715 // m=<media> <port> <proto> <fmt> ...
716 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000717 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000718 if (fields.size() < 3) {
719 return;
720 }
721
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000723 std::string rtp_port, rtp_ip, addr_type;
724 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
725 &rtp_port, &rtp_ip, &addr_type);
726 // Found default RTP candidate.
727 // RFC 5245
728 // The default candidates are added to the SDP as the default
729 // destination for media. For streams based on RTP, this is done by
730 // placing the IP address and port of the RTP candidate into the c and m
731 // lines, respectively.
732 // Update the port in the m line.
733 // If this is a m-line with port equal to 0, we don't change it.
734 if (fields[1] != kMediaPortRejected) {
735 new_lines.replace(fields[0].size() + 1,
736 fields[1].size(),
737 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000738 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000739 // Add the c line.
740 // RFC 4566
741 // c=<nettype> <addrtype> <connection-address>
742 InitLine(kLineTypeConnection, kConnectionNettype, &os);
743 os << " " << addr_type << " " << rtp_ip;
744 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000745 message->append(new_lines);
746}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000747
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000748// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
749static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000750 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
751 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
752 &rtcp_port, &rtcp_ip, &addr_type);
753 // Found default RTCP candidate.
754 // RFC 5245
755 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
756 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000757
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000758 // RFC 3605
759 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
760 // connection-address] CRLF
761 std::ostringstream os;
762 InitAttrLine(kAttributeRtcp, &os);
763 os << kSdpDelimiterColon
764 << rtcp_port << " "
765 << kConnectionNettype << " "
766 << addr_type << " "
767 << rtcp_ip;
768 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000769 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000770}
771
772// Get candidates according to the mline index from SessionDescriptionInterface.
773static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
774 int mline_index,
775 std::vector<Candidate>* candidates) {
776 if (!candidates) {
777 return;
778 }
779 const IceCandidateCollection* cc = desci.candidates(mline_index);
780 for (size_t i = 0; i < cc->count(); ++i) {
781 const IceCandidateInterface* candidate = cc->at(i);
782 candidates->push_back(candidate->candidate());
783 }
784}
785
786std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000787 const cricket::SessionDescription* desc = jdesc.description();
788 if (!desc) {
789 return "";
790 }
791
792 std::string message;
793
794 // Session Description.
795 AddLine(kSessionVersion, &message);
796 // Session Origin
797 // RFC 4566
798 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
799 // <unicast-address>
800 std::ostringstream os;
801 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
802 const std::string session_id = jdesc.session_id().empty() ?
803 kSessionOriginSessionId : jdesc.session_id();
804 const std::string session_version = jdesc.session_version().empty() ?
805 kSessionOriginSessionVersion : jdesc.session_version();
806 os << " " << session_id << " " << session_version << " "
807 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
808 << kSessionOriginAddress;
809 AddLine(os.str(), &message);
810 AddLine(kSessionName, &message);
811
812 // Time Description.
813 AddLine(kTimeDescription, &message);
814
815 // Group
816 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
817 std::string group_line = kAttrGroup;
818 const cricket::ContentGroup* group =
819 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
820 ASSERT(group != NULL);
821 const cricket::ContentNames& content_names = group->content_names();
822 for (cricket::ContentNames::const_iterator it = content_names.begin();
823 it != content_names.end(); ++it) {
824 group_line.append(" ");
825 group_line.append(*it);
826 }
827 AddLine(group_line, &message);
828 }
829
830 // MediaStream semantics
831 InitAttrLine(kAttributeMsidSemantics, &os);
832 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000833
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834 std::set<std::string> media_stream_labels;
835 const ContentInfo* audio_content = GetFirstAudioContent(desc);
836 if (audio_content)
837 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000838
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000839 const ContentInfo* video_content = GetFirstVideoContent(desc);
840 if (video_content)
841 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000842
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843 for (std::set<std::string>::const_iterator it =
844 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
845 os << " " << *it;
846 }
847 AddLine(os.str(), &message);
848
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000849 // Preserve the order of the media contents.
850 int mline_index = -1;
851 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
852 it != desc->contents().end(); ++it) {
853 const MediaContentDescription* mdesc =
854 static_cast<const MediaContentDescription*>(it->description);
855 std::vector<Candidate> candidates;
856 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
857 BuildMediaDescription(&*it,
858 desc->GetTransportInfoByName(it->name),
859 mdesc->type(),
860 candidates,
861 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000862 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000863 return message;
864}
865
866// Serializes the passed in IceCandidateInterface to a SDP string.
867// candidate - The candidate to be serialized.
868std::string SdpSerializeCandidate(
869 const IceCandidateInterface& candidate) {
870 std::string message;
871 std::vector<cricket::Candidate> candidates;
872 candidates.push_back(candidate.candidate());
873 BuildCandidate(candidates, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000874 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
875 // just candidate:<candidate> not a=candidate:<blah>CRLF
876 ASSERT(message.find("a=") == 0);
877 message.erase(0, 2);
878 ASSERT(message.find(kLineBreak) == message.size() - 2);
879 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000880 return message;
881}
882
883bool SdpDeserialize(const std::string& message,
884 JsepSessionDescription* jdesc,
885 SdpParseError* error) {
886 std::string session_id;
887 std::string session_version;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000888 TransportDescription session_td(NS_JINGLE_ICE_UDP,
889 std::string(), std::string());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000890 RtpHeaderExtensions session_extmaps;
891 cricket::SessionDescription* desc = new cricket::SessionDescription();
892 std::vector<JsepIceCandidate*> candidates;
893 size_t current_pos = 0;
894 bool supports_msid = false;
895
896 // Session Description
897 if (!ParseSessionDescription(message, &current_pos, &session_id,
898 &session_version, &supports_msid, &session_td,
899 &session_extmaps, desc, error)) {
900 delete desc;
901 return false;
902 }
903
904 // Media Description
905 if (!ParseMediaDescription(message, session_td, session_extmaps,
906 supports_msid, &current_pos, desc, &candidates,
907 error)) {
908 delete desc;
909 for (std::vector<JsepIceCandidate*>::const_iterator
910 it = candidates.begin(); it != candidates.end(); ++it) {
911 delete *it;
912 }
913 return false;
914 }
915
916 jdesc->Initialize(desc, session_id, session_version);
917
918 for (std::vector<JsepIceCandidate*>::const_iterator
919 it = candidates.begin(); it != candidates.end(); ++it) {
920 jdesc->AddCandidate(*it);
921 delete *it;
922 }
923 return true;
924}
925
926bool SdpDeserializeCandidate(const std::string& message,
927 JsepIceCandidate* jcandidate,
928 SdpParseError* error) {
929 ASSERT(jcandidate != NULL);
930 Candidate candidate;
931 if (!ParseCandidate(message, &candidate, error, true)) {
932 return false;
933 }
934 jcandidate->SetCandidate(candidate);
935 return true;
936}
937
938bool ParseCandidate(const std::string& message, Candidate* candidate,
939 SdpParseError* error, bool is_raw) {
940 ASSERT(candidate != NULL);
941
942 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000943 std::string first_line = message;
944 size_t pos = 0;
945 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000947 // Makes sure |message| contains only one line.
948 if (message.size() > first_line.size()) {
949 std::string left, right;
950 if (SplitByDelimiter(message, kNewLine, &left, &right) && !right.empty()) {
951 return ParseFailed(message, 0, "Expect one line only", error);
952 }
953 }
954
955 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
956 // candidate:<candidate> when trickled, but we still support
957 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
958 // from the SDP.
959 if (IsLineType(first_line, kLineTypeAttributes)) {
960 first_line = first_line.substr(kLinePrefixLength);
961 }
962
963 std::string attribute_candidate;
964 std::string candidate_value;
965
966 // |first_line| must be in the form of "candidate:<value>".
967 if (!SplitByDelimiter(first_line, kSdpDelimiterColon,
968 &attribute_candidate, &candidate_value) ||
969 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 if (is_raw) {
971 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000972 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000973 << ":" << "<candidate-str>";
974 return ParseFailed(first_line, 0, description.str(), error);
975 } else {
976 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
977 kAttributeCandidate, error);
978 }
979 }
980
981 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000982 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
983
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984 // RFC 5245
985 // a=candidate:<foundation> <component-id> <transport> <priority>
986 // <connection-address> <port> typ <candidate-types>
987 // [raddr <connection-address>] [rport <port>]
988 // *(SP extension-att-name SP extension-att-value)
989 const size_t expected_min_fields = 8;
990 if (fields.size() < expected_min_fields ||
991 (fields[6] != kAttributeCandidateTyp)) {
992 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
993 }
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000994 std::string foundation = fields[0];
995
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000996 int component_id = 0;
997 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
998 return false;
999 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000 const std::string transport = fields[2];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001001 uint32 priority = 0;
1002 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1003 return false;
1004 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005 const std::string connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001006 int port = 0;
1007 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1008 return false;
1009 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001010 SocketAddress address(connection_address, port);
1011
1012 cricket::ProtocolType protocol;
1013 if (!StringToProto(transport.c_str(), &protocol)) {
1014 return ParseFailed(first_line, "Unsupported transport type.", error);
1015 }
1016
1017 std::string candidate_type;
1018 const std::string type = fields[7];
1019 if (type == kCandidateHost) {
1020 candidate_type = cricket::LOCAL_PORT_TYPE;
1021 } else if (type == kCandidateSrflx) {
1022 candidate_type = cricket::STUN_PORT_TYPE;
1023 } else if (type == kCandidateRelay) {
1024 candidate_type = cricket::RELAY_PORT_TYPE;
1025 } else {
1026 return ParseFailed(first_line, "Unsupported candidate type.", error);
1027 }
1028
1029 size_t current_position = expected_min_fields;
1030 SocketAddress related_address;
1031 // The 2 optional fields for related address
1032 // [raddr <connection-address>] [rport <port>]
1033 if (fields.size() >= (current_position + 2) &&
1034 fields[current_position] == kAttributeCandidateRaddr) {
1035 related_address.SetIP(fields[++current_position]);
1036 ++current_position;
1037 }
1038 if (fields.size() >= (current_position + 2) &&
1039 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001040 int port = 0;
1041 if (!GetValueFromString(
1042 first_line, fields[++current_position], &port, error)) {
1043 return false;
1044 }
1045 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001046 ++current_position;
1047 }
1048
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001049 // If this is a TCP candidate, it has additional extension as defined in
1050 // RFC 6544.
1051 std::string tcptype;
1052 if (fields.size() >= (current_position + 2) &&
1053 fields[current_position] == kTcpCandidateType) {
1054 tcptype = fields[++current_position];
1055 ++current_position;
1056
1057 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1058 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1059 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1060 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1061 }
1062
1063 if (protocol != cricket::PROTO_TCP) {
1064 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1065 }
1066 }
1067
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068 // Extension
1069 // Empty string as the candidate username and password.
1070 // Will be updated later with the ice-ufrag and ice-pwd.
1071 // TODO: Remove the username/password extension, which is currently
1072 // kept for backwards compatibility.
1073 std::string username;
1074 std::string password;
1075 uint32 generation = 0;
1076 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1077 // RFC 5245
1078 // *(SP extension-att-name SP extension-att-value)
1079 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001080 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1081 return false;
1082 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001083 } else if (fields[i] == kAttributeCandidateUsername) {
1084 username = fields[++i];
1085 } else if (fields[i] == kAttributeCandidatePassword) {
1086 password = fields[++i];
1087 } else {
1088 // Skip the unknown extension.
1089 ++i;
1090 }
1091 }
1092
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001093 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001094 address, priority, username, password, candidate_type,
1095 generation, foundation);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001096 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001097 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001098 return true;
1099}
1100
1101bool ParseIceOptions(const std::string& line,
1102 std::vector<std::string>* transport_options,
1103 SdpParseError* error) {
1104 std::string ice_options;
1105 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1106 return false;
1107 }
1108 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001109 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001110 for (size_t i = 0; i < fields.size(); ++i) {
1111 transport_options->push_back(fields[i]);
1112 }
1113 return true;
1114}
1115
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001116bool ParseSctpPort(const std::string& line,
1117 int* sctp_port,
1118 SdpParseError* error) {
1119 // draft-ietf-mmusic-sctp-sdp-07
1120 // a=sctp-port
1121 std::vector<std::string> fields;
1122 rtc::split(line.substr(kLinePrefixLength),
1123 kSdpDelimiterSpace, &fields);
1124 const size_t expected_min_fields = 2;
1125 if (fields.size() < expected_min_fields) {
1126 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1127 }
1128 if (!rtc::FromString(fields[1], sctp_port)) {
1129 return ParseFailed(line,
1130 "Invalid sctp port value.",
1131 error);
1132 }
1133 return true;
1134}
1135
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001136bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1137 SdpParseError* error) {
1138 // RFC 5285
1139 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1140 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001141 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001142 kSdpDelimiterSpace, &fields);
1143 const size_t expected_min_fields = 2;
1144 if (fields.size() < expected_min_fields) {
1145 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1146 }
1147 std::string uri = fields[1];
1148
1149 std::string value_direction;
1150 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1151 return false;
1152 }
1153 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001154 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001155 int value = 0;
1156 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1157 return false;
1158 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001159
1160 *extmap = RtpHeaderExtension(uri, value);
1161 return true;
1162}
1163
1164void BuildMediaDescription(const ContentInfo* content_info,
1165 const TransportInfo* transport_info,
1166 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001167 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001168 std::string* message) {
1169 ASSERT(message != NULL);
1170 if (content_info == NULL || message == NULL) {
1171 return;
1172 }
1173 // TODO: Rethink if we should use sprintfn instead of stringstream.
1174 // According to the style guide, streams should only be used for logging.
1175 // http://google-styleguide.googlecode.com/svn/
1176 // trunk/cppguide.xml?showone=Streams#Streams
1177 std::ostringstream os;
1178 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001179 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001180 content_info->description);
1181 ASSERT(media_desc != NULL);
1182
1183 bool is_sctp = (media_desc->protocol() == cricket::kMediaProtocolDtlsSctp);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001184 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001185
1186 // RFC 4566
1187 // m=<media> <port> <proto> <fmt>
1188 // fmt is a list of payload type numbers that MAY be used in the session.
1189 const char* type = NULL;
1190 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1191 type = kMediaTypeAudio;
1192 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1193 type = kMediaTypeVideo;
1194 else if (media_type == cricket::MEDIA_TYPE_DATA)
1195 type = kMediaTypeData;
1196 else
1197 ASSERT(false);
1198
1199 std::string fmt;
1200 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1201 const VideoContentDescription* video_desc =
1202 static_cast<const VideoContentDescription*>(media_desc);
1203 for (std::vector<cricket::VideoCodec>::const_iterator it =
1204 video_desc->codecs().begin();
1205 it != video_desc->codecs().end(); ++it) {
1206 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001207 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001208 }
1209 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1210 const AudioContentDescription* audio_desc =
1211 static_cast<const AudioContentDescription*>(media_desc);
1212 for (std::vector<cricket::AudioCodec>::const_iterator it =
1213 audio_desc->codecs().begin();
1214 it != audio_desc->codecs().end(); ++it) {
1215 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001216 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217 }
1218 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001219 const DataContentDescription* data_desc =
1220 static_cast<const DataContentDescription*>(media_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001221 if (is_sctp) {
1222 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001223
1224 for (std::vector<cricket::DataCodec>::const_iterator it =
1225 data_desc->codecs().begin();
1226 it != data_desc->codecs().end(); ++it) {
1227 if (it->id == cricket::kGoogleSctpDataCodecId &&
1228 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1229 break;
1230 }
1231 }
1232
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001233 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001234 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001235 for (std::vector<cricket::DataCodec>::const_iterator it =
1236 data_desc->codecs().begin();
1237 it != data_desc->codecs().end(); ++it) {
1238 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001239 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001240 }
1241 }
1242 }
1243 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1244 // to 0.
1245 if (fmt.empty()) {
1246 fmt = " 0";
1247 }
1248
1249 // The port number in the m line will be updated later when associate with
1250 // the candidates.
1251 // RFC 3264
1252 // To reject an offered stream, the port number in the corresponding stream in
1253 // the answer MUST be set to zero.
1254 const std::string port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001255 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001257 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258 transport_info->description.identity_fingerprint.get() : NULL;
1259
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001260 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001261 InitLine(kLineTypeMedia, type, &os);
1262 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001263 std::string mline = os.str();
1264 UpdateMediaDefaultDestination(candidates, mline, message);
1265
1266 // RFC 4566
1267 // b=AS:<bandwidth>
1268 // We should always use the default bandwidth for RTP-based data
1269 // channels. Don't allow SDP to set the bandwidth, because that
1270 // would give JS the opportunity to "break the Internet".
1271 // TODO(pthatcher): But we need to temporarily allow the SDP to control
1272 // this for backwards-compatibility. Once we don't need that any
1273 // more, remove this.
1274 bool support_dc_sdp_bandwidth_temporarily = true;
1275 if (media_desc->bandwidth() >= 1000 &&
1276 (media_type != cricket::MEDIA_TYPE_DATA ||
1277 support_dc_sdp_bandwidth_temporarily)) {
1278 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1279 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1280 AddLine(os.str(), message);
1281 }
1282
1283 // Add the a=rtcp line.
1284 bool is_rtp =
1285 media_desc->protocol().empty() ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001286 rtc::starts_with(media_desc->protocol().data(),
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001287 cricket::kMediaProtocolRtpPrefix);
1288 if (is_rtp) {
1289 std::string rtcp_line = GetRtcpLine(candidates);
1290 if (!rtcp_line.empty()) {
1291 AddLine(rtcp_line, message);
1292 }
1293 }
1294
1295 // Build the a=candidate lines.
1296 BuildCandidate(candidates, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297
1298 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1299 if (transport_info) {
1300 // RFC 5245
1301 // ice-pwd-att = "ice-pwd" ":" password
1302 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1303 // ice-ufrag
1304 InitAttrLine(kAttributeIceUfrag, &os);
1305 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1306 AddLine(os.str(), message);
1307 // ice-pwd
1308 InitAttrLine(kAttributeIcePwd, &os);
1309 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1310 AddLine(os.str(), message);
1311
1312 // draft-petithuguenin-mmusic-ice-attributes-level-03
1313 BuildIceOptions(transport_info->description.transport_options, message);
1314
1315 // RFC 4572
1316 // fingerprint-attribute =
1317 // "fingerprint" ":" hash-func SP fingerprint
1318 if (fp) {
1319 // Insert the fingerprint attribute.
1320 InitAttrLine(kAttributeFingerprint, &os);
1321 os << kSdpDelimiterColon
1322 << fp->algorithm << kSdpDelimiterSpace
1323 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001325
1326 // Inserting setup attribute.
1327 if (transport_info->description.connection_role !=
1328 cricket::CONNECTIONROLE_NONE) {
1329 // Making sure we are not using "passive" mode.
1330 cricket::ConnectionRole role =
1331 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001332 std::string dtls_role_str;
1333 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001334 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001335 os << kSdpDelimiterColon << dtls_role_str;
1336 AddLine(os.str(), message);
1337 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001338 }
1339 }
1340
1341 // RFC 3388
1342 // mid-attribute = "a=mid:" identification-tag
1343 // identification-tag = token
1344 // Use the content name as the mid identification-tag.
1345 InitAttrLine(kAttributeMid, &os);
1346 os << kSdpDelimiterColon << content_info->name;
1347 AddLine(os.str(), message);
1348
1349 if (is_sctp) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001350 BuildSctpContentAttributes(message, sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 } else {
1352 BuildRtpContentAttributes(media_desc, media_type, message);
1353 }
1354}
1355
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001356void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001357 // draft-ietf-mmusic-sctp-sdp-04
1358 // a=sctpmap:sctpmap-number protocol [streams]
1359 std::ostringstream os;
1360 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001361 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001362 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1363 << (cricket::kMaxSctpSid + 1);
1364 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001365}
1366
1367void BuildRtpContentAttributes(
1368 const MediaContentDescription* media_desc,
1369 const MediaType media_type,
1370 std::string* message) {
1371 std::ostringstream os;
1372 // RFC 5285
1373 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1374 // The definitions MUST be either all session level or all media level. This
1375 // implementation uses all media level.
1376 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1377 InitAttrLine(kAttributeExtmap, &os);
1378 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1379 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1380 AddLine(os.str(), message);
1381 }
1382
1383 // RFC 3264
1384 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
1385
1386 cricket::MediaContentDirection direction = media_desc->direction();
1387 if (media_desc->streams().empty() && direction == cricket::MD_SENDRECV) {
1388 direction = cricket::MD_RECVONLY;
1389 }
1390
1391 switch (direction) {
1392 case cricket::MD_INACTIVE:
1393 InitAttrLine(kAttributeInactive, &os);
1394 break;
1395 case cricket::MD_SENDONLY:
1396 InitAttrLine(kAttributeSendOnly, &os);
1397 break;
1398 case cricket::MD_RECVONLY:
1399 InitAttrLine(kAttributeRecvOnly, &os);
1400 break;
1401 case cricket::MD_SENDRECV:
1402 default:
1403 InitAttrLine(kAttributeSendRecv, &os);
1404 break;
1405 }
1406 AddLine(os.str(), message);
1407
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001408 // RFC 5761
1409 // a=rtcp-mux
1410 if (media_desc->rtcp_mux()) {
1411 InitAttrLine(kAttributeRtcpMux, &os);
1412 AddLine(os.str(), message);
1413 }
1414
1415 // RFC 4568
1416 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1417 for (std::vector<CryptoParams>::const_iterator it =
1418 media_desc->cryptos().begin();
1419 it != media_desc->cryptos().end(); ++it) {
1420 InitAttrLine(kAttributeCrypto, &os);
1421 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1422 << it->key_params;
1423 if (!it->session_params.empty()) {
1424 os << " " << it->session_params;
1425 }
1426 AddLine(os.str(), message);
1427 }
1428
1429 // RFC 4566
1430 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1431 // [/<encodingparameters>]
1432 BuildRtpMap(media_desc, media_type, message);
1433
1434 // Specify latency for buffered mode.
1435 // a=x-google-buffer-latency:<value>
1436 if (media_desc->buffered_mode_latency() != cricket::kBufferedModeDisabled) {
1437 std::ostringstream os;
1438 InitAttrLine(kAttributeXGoogleBufferLatency, &os);
1439 os << kSdpDelimiterColon << media_desc->buffered_mode_latency();
1440 AddLine(os.str(), message);
1441 }
1442
1443 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1444 track != media_desc->streams().end(); ++track) {
1445 // Require that the track belongs to a media stream,
1446 // ie the sync_label is set. This extra check is necessary since the
1447 // MediaContentDescription always contains a streamparam with an ssrc even
1448 // if no track or media stream have been created.
1449 if (track->sync_label.empty()) continue;
1450
1451 // Build the ssrc-group lines.
1452 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1453 // RFC 5576
1454 // a=ssrc-group:<semantics> <ssrc-id> ...
1455 if (track->ssrc_groups[i].ssrcs.empty()) {
1456 continue;
1457 }
1458 std::ostringstream os;
1459 InitAttrLine(kAttributeSsrcGroup, &os);
1460 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
1461 std::vector<uint32>::const_iterator ssrc =
1462 track->ssrc_groups[i].ssrcs.begin();
1463 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001464 os << kSdpDelimiterSpace << rtc::ToString<uint32>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001465 }
1466 AddLine(os.str(), message);
1467 }
1468 // Build the ssrc lines for each ssrc.
1469 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
1470 uint32 ssrc = track->ssrcs[i];
1471 // RFC 5576
1472 // a=ssrc:<ssrc-id> cname:<value>
1473 AddSsrcLine(ssrc, kSsrcAttributeCname,
1474 track->cname, message);
1475
1476 // draft-alvestrand-mmusic-msid-00
1477 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1478 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1479 // is corresponding to the "name" attribute of StreamParams.
1480 std::string appdata = track->id;
1481 std::ostringstream os;
1482 InitAttrLine(kAttributeSsrc, &os);
1483 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1484 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1485 << kSdpDelimiterSpace << appdata;
1486 AddLine(os.str(), message);
1487
1488 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1489 // draft-alvestrand-rtcweb-mid-01
1490 // a=ssrc:<ssrc-id> mslabel:<value>
1491 // The label isn't yet defined.
1492 // a=ssrc:<ssrc-id> label:<value>
1493 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1494 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1495 }
1496 }
1497}
1498
1499void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1500 // fmtp header: a=fmtp:|payload_type| <parameters>
1501 // Add a=fmtp
1502 InitAttrLine(kAttributeFmtp, os);
1503 // Add :|payload_type|
1504 *os << kSdpDelimiterColon << payload_type;
1505}
1506
1507void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1508 // rtcp-fb header: a=rtcp-fb:|payload_type|
1509 // <parameters>/<ccm <ccm_parameters>>
1510 // Add a=rtcp-fb
1511 InitAttrLine(kAttributeRtcpFb, os);
1512 // Add :
1513 *os << kSdpDelimiterColon;
1514 if (payload_type == kWildcardPayloadType) {
1515 *os << "*";
1516 } else {
1517 *os << payload_type;
1518 }
1519}
1520
1521void WriteFmtpParameter(const std::string& parameter_name,
1522 const std::string& parameter_value,
1523 std::ostringstream* os) {
1524 // fmtp parameters: |parameter_name|=|parameter_value|
1525 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1526}
1527
1528void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1529 std::ostringstream* os) {
1530 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1531 fmtp != parameters.end(); ++fmtp) {
1532 // Each new parameter, except the first one starts with ";" and " ".
1533 if (fmtp != parameters.begin()) {
1534 *os << kSdpDelimiterSemicolon;
1535 }
1536 *os << kSdpDelimiterSpace;
1537 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1538 }
1539}
1540
1541bool IsFmtpParam(const std::string& name) {
1542 const char* kFmtpParams[] = {
1543 kCodecParamMinPTime, kCodecParamSPropStereo,
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +00001544 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamStartBitrate,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545 kCodecParamMaxBitrate, kCodecParamMinBitrate, kCodecParamMaxQuantization,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001546 kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001547 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1548 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001549 };
1550 for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
1551 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1552 return true;
1553 }
1554 }
1555 return false;
1556}
1557
1558// Retreives fmtp parameters from |params|, which may contain other parameters
1559// as well, and puts them in |fmtp_parameters|.
1560void GetFmtpParams(const cricket::CodecParameterMap& params,
1561 cricket::CodecParameterMap* fmtp_parameters) {
1562 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1563 iter != params.end(); ++iter) {
1564 if (IsFmtpParam(iter->first)) {
1565 (*fmtp_parameters)[iter->first] = iter->second;
1566 }
1567 }
1568}
1569
1570template <class T>
1571void AddFmtpLine(const T& codec, std::string* message) {
1572 cricket::CodecParameterMap fmtp_parameters;
1573 GetFmtpParams(codec.params, &fmtp_parameters);
1574 if (fmtp_parameters.empty()) {
1575 // No need to add an fmtp if it will have no (optional) parameters.
1576 return;
1577 }
1578 std::ostringstream os;
1579 WriteFmtpHeader(codec.id, &os);
1580 WriteFmtpParameters(fmtp_parameters, &os);
1581 AddLine(os.str(), message);
1582 return;
1583}
1584
1585template <class T>
1586void AddRtcpFbLines(const T& codec, std::string* message) {
1587 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1588 codec.feedback_params.params().begin();
1589 iter != codec.feedback_params.params().end(); ++iter) {
1590 std::ostringstream os;
1591 WriteRtcpFbHeader(codec.id, &os);
1592 os << " " << iter->id();
1593 if (!iter->param().empty()) {
1594 os << " " << iter->param();
1595 }
1596 AddLine(os.str(), message);
1597 }
1598}
1599
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001600bool AddSctpDataCodec(DataContentDescription* media_desc,
1601 int sctp_port) {
1602 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1603 return ParseFailed("",
1604 "Can't have multiple sctp port attributes.",
1605 NULL);
1606 }
1607 // Add the SCTP Port number as a pseudo-codec "port" parameter
1608 cricket::DataCodec codec_port(
1609 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1610 0);
1611 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1612 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1613 << sctp_port;
1614 media_desc->AddCodec(codec_port);
1615 return true;
1616}
1617
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001618bool GetMinValue(const std::vector<int>& values, int* value) {
1619 if (values.empty()) {
1620 return false;
1621 }
1622 std::vector<int>::const_iterator found =
1623 std::min_element(values.begin(), values.end());
1624 *value = *found;
1625 return true;
1626}
1627
1628bool GetParameter(const std::string& name,
1629 const cricket::CodecParameterMap& params, int* value) {
1630 std::map<std::string, std::string>::const_iterator found =
1631 params.find(name);
1632 if (found == params.end()) {
1633 return false;
1634 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001635 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001636 return false;
1637 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001638 return true;
1639}
1640
1641void BuildRtpMap(const MediaContentDescription* media_desc,
1642 const MediaType media_type,
1643 std::string* message) {
1644 ASSERT(message != NULL);
1645 ASSERT(media_desc != NULL);
1646 std::ostringstream os;
1647 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1648 const VideoContentDescription* video_desc =
1649 static_cast<const VideoContentDescription*>(media_desc);
1650 for (std::vector<cricket::VideoCodec>::const_iterator it =
1651 video_desc->codecs().begin();
1652 it != video_desc->codecs().end(); ++it) {
1653 // RFC 4566
1654 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1655 // [/<encodingparameters>]
1656 if (it->id != kWildcardPayloadType) {
1657 InitAttrLine(kAttributeRtpmap, &os);
1658 os << kSdpDelimiterColon << it->id << " " << it->name
1659 << "/" << kDefaultVideoClockrate;
1660 AddLine(os.str(), message);
1661 }
1662 AddRtcpFbLines(*it, message);
1663 AddFmtpLine(*it, message);
1664 }
1665 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1666 const AudioContentDescription* audio_desc =
1667 static_cast<const AudioContentDescription*>(media_desc);
1668 std::vector<int> ptimes;
1669 std::vector<int> maxptimes;
1670 int max_minptime = 0;
1671 for (std::vector<cricket::AudioCodec>::const_iterator it =
1672 audio_desc->codecs().begin();
1673 it != audio_desc->codecs().end(); ++it) {
1674 ASSERT(!it->name.empty());
1675 // RFC 4566
1676 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1677 // [/<encodingparameters>]
1678 InitAttrLine(kAttributeRtpmap, &os);
1679 os << kSdpDelimiterColon << it->id << " ";
1680 os << it->name << "/" << it->clockrate;
1681 if (it->channels != 1) {
1682 os << "/" << it->channels;
1683 }
1684 AddLine(os.str(), message);
1685 AddRtcpFbLines(*it, message);
1686 AddFmtpLine(*it, message);
1687 int minptime = 0;
1688 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1689 max_minptime = std::max(minptime, max_minptime);
1690 }
1691 int ptime;
1692 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1693 ptimes.push_back(ptime);
1694 }
1695 int maxptime;
1696 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1697 maxptimes.push_back(maxptime);
1698 }
1699 }
1700 // Populate the maxptime attribute with the smallest maxptime of all codecs
1701 // under the same m-line.
1702 int min_maxptime = INT_MAX;
1703 if (GetMinValue(maxptimes, &min_maxptime)) {
1704 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1705 }
1706 ASSERT(min_maxptime > max_minptime);
1707 // Populate the ptime attribute with the smallest ptime or the largest
1708 // minptime, whichever is the largest, for all codecs under the same m-line.
1709 int ptime = INT_MAX;
1710 if (GetMinValue(ptimes, &ptime)) {
1711 ptime = std::min(ptime, min_maxptime);
1712 ptime = std::max(ptime, max_minptime);
1713 AddAttributeLine(kCodecParamPTime, ptime, message);
1714 }
1715 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1716 const DataContentDescription* data_desc =
1717 static_cast<const DataContentDescription*>(media_desc);
1718 for (std::vector<cricket::DataCodec>::const_iterator it =
1719 data_desc->codecs().begin();
1720 it != data_desc->codecs().end(); ++it) {
1721 // RFC 4566
1722 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1723 // [/<encodingparameters>]
1724 InitAttrLine(kAttributeRtpmap, &os);
1725 os << kSdpDelimiterColon << it->id << " "
1726 << it->name << "/" << it->clockrate;
1727 AddLine(os.str(), message);
1728 }
1729 }
1730}
1731
1732void BuildCandidate(const std::vector<Candidate>& candidates,
1733 std::string* message) {
1734 std::ostringstream os;
1735
1736 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1737 it != candidates.end(); ++it) {
1738 // RFC 5245
1739 // a=candidate:<foundation> <component-id> <transport> <priority>
1740 // <connection-address> <port> typ <candidate-types>
1741 // [raddr <connection-address>] [rport <port>]
1742 // *(SP extension-att-name SP extension-att-value)
1743 std::string type;
1744 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1745 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1746 type = kCandidateHost;
1747 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1748 type = kCandidateSrflx;
1749 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1750 type = kCandidateRelay;
1751 } else {
1752 ASSERT(false);
1753 }
1754
1755 InitAttrLine(kAttributeCandidate, &os);
1756 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001757 << it->foundation() << " "
1758 << it->component() << " "
1759 << it->protocol() << " "
1760 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001761 << it->address().ipaddr().ToString() << " "
1762 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001763 << kAttributeCandidateTyp << " "
1764 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001765
1766 // Related address
1767 if (!it->related_address().IsNil()) {
1768 os << kAttributeCandidateRaddr << " "
1769 << it->related_address().ipaddr().ToString() << " "
1770 << kAttributeCandidateRport << " "
1771 << it->related_address().PortAsString() << " ";
1772 }
1773
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001774 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001775 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001776 }
1777
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001778 // Extensions
1779 os << kAttributeCandidateGeneration << " " << it->generation();
1780
1781 AddLine(os.str(), message);
1782 }
1783}
1784
1785void BuildIceOptions(const std::vector<std::string>& transport_options,
1786 std::string* message) {
1787 if (!transport_options.empty()) {
1788 std::ostringstream os;
1789 InitAttrLine(kAttributeIceOption, &os);
1790 os << kSdpDelimiterColon << transport_options[0];
1791 for (size_t i = 1; i < transport_options.size(); ++i) {
1792 os << kSdpDelimiterSpace << transport_options[i];
1793 }
1794 AddLine(os.str(), message);
1795 }
1796}
1797
1798bool ParseSessionDescription(const std::string& message, size_t* pos,
1799 std::string* session_id,
1800 std::string* session_version,
1801 bool* supports_msid,
1802 TransportDescription* session_td,
1803 RtpHeaderExtensions* session_extmaps,
1804 cricket::SessionDescription* desc,
1805 SdpParseError* error) {
1806 std::string line;
1807
1808 // RFC 4566
1809 // v= (protocol version)
1810 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1811 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1812 std::string(), error);
1813 }
1814 // RFC 4566
1815 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1816 // <unicast-address>
1817 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1818 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1819 std::string(), error);
1820 }
1821 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001822 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001823 kSdpDelimiterSpace, &fields);
1824 const size_t expected_fields = 6;
1825 if (fields.size() != expected_fields) {
1826 return ParseFailedExpectFieldNum(line, expected_fields, error);
1827 }
1828 *session_id = fields[1];
1829 *session_version = fields[2];
1830
1831 // RFC 4566
1832 // s= (session name)
1833 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1834 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1835 std::string(), error);
1836 }
1837
1838 // Optional lines
1839 // Those are the optional lines, so shouldn't return false if not present.
1840 // RFC 4566
1841 // i=* (session information)
1842 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1843
1844 // RFC 4566
1845 // u=* (URI of description)
1846 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1847
1848 // RFC 4566
1849 // e=* (email address)
1850 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1851
1852 // RFC 4566
1853 // p=* (phone number)
1854 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1855
1856 // RFC 4566
1857 // c=* (connection information -- not required if included in
1858 // all media)
1859 GetLineWithType(message, pos, &line, kLineTypeConnection);
1860
1861 // RFC 4566
1862 // b=* (zero or more bandwidth information lines)
1863 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1864 // By pass zero or more b lines.
1865 }
1866
1867 // RFC 4566
1868 // One or more time descriptions ("t=" and "r=" lines; see below)
1869 // t= (time the session is active)
1870 // r=* (zero or more repeat times)
1871 // Ensure there's at least one time description
1872 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1873 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1874 error);
1875 }
1876
1877 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1878 // By pass zero or more r lines.
1879 }
1880
1881 // Go through the rest of the time descriptions
1882 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1883 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1884 // By pass zero or more r lines.
1885 }
1886 }
1887
1888 // RFC 4566
1889 // z=* (time zone adjustments)
1890 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1891
1892 // RFC 4566
1893 // k=* (encryption key)
1894 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1895
1896 // RFC 4566
1897 // a=* (zero or more session attribute lines)
1898 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1899 if (HasAttribute(line, kAttributeGroup)) {
1900 if (!ParseGroupAttribute(line, desc, error)) {
1901 return false;
1902 }
1903 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1904 if (!GetValue(line, kAttributeIceUfrag,
1905 &(session_td->ice_ufrag), error)) {
1906 return false;
1907 }
1908 } else if (HasAttribute(line, kAttributeIcePwd)) {
1909 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1910 return false;
1911 }
1912 } else if (HasAttribute(line, kAttributeIceLite)) {
1913 session_td->ice_mode = cricket::ICEMODE_LITE;
1914 } else if (HasAttribute(line, kAttributeIceOption)) {
1915 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1916 return false;
1917 }
1918 } else if (HasAttribute(line, kAttributeFingerprint)) {
1919 if (session_td->identity_fingerprint.get()) {
1920 return ParseFailed(
1921 line,
1922 "Can't have multiple fingerprint attributes at the same level.",
1923 error);
1924 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001925 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1927 return false;
1928 }
1929 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001930 } else if (HasAttribute(line, kAttributeSetup)) {
1931 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1932 return false;
1933 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001934 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1935 std::string semantics;
1936 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1937 return false;
1938 }
1939 *supports_msid = CaseInsensitiveFind(semantics, kMediaStreamSemantic);
1940 } else if (HasAttribute(line, kAttributeExtmap)) {
1941 RtpHeaderExtension extmap;
1942 if (!ParseExtmap(line, &extmap, error)) {
1943 return false;
1944 }
1945 session_extmaps->push_back(extmap);
1946 }
1947 }
1948
1949 return true;
1950}
1951
1952bool ParseGroupAttribute(const std::string& line,
1953 cricket::SessionDescription* desc,
1954 SdpParseError* error) {
1955 ASSERT(desc != NULL);
1956
1957 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1958 // a=group:BUNDLE video voice
1959 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001960 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001961 kSdpDelimiterSpace, &fields);
1962 std::string semantics;
1963 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1964 return false;
1965 }
1966 cricket::ContentGroup group(semantics);
1967 for (size_t i = 1; i < fields.size(); ++i) {
1968 group.AddContentName(fields[i]);
1969 }
1970 desc->AddGroup(group);
1971 return true;
1972}
1973
1974static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001975 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001976 SdpParseError* error) {
1977 if (!IsLineType(line, kLineTypeAttributes) ||
1978 !HasAttribute(line, kAttributeFingerprint)) {
1979 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1980 kAttributeFingerprint, error);
1981 }
1982
1983 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001984 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985 kSdpDelimiterSpace, &fields);
1986 const size_t expected_fields = 2;
1987 if (fields.size() != expected_fields) {
1988 return ParseFailedExpectFieldNum(line, expected_fields, error);
1989 }
1990
1991 // The first field here is "fingerprint:<hash>.
1992 std::string algorithm;
1993 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
1994 return false;
1995 }
1996
1997 // Downcase the algorithm. Note that we don't need to downcase the
1998 // fingerprint because hex_decode can handle upper-case.
1999 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2000 ::tolower);
2001
2002 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002003 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002004 algorithm, fields[1]);
2005 if (!*fingerprint) {
2006 return ParseFailed(line,
2007 "Failed to create fingerprint from the digest.",
2008 error);
2009 }
2010
2011 return true;
2012}
2013
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002014static bool ParseDtlsSetup(const std::string& line,
2015 cricket::ConnectionRole* role,
2016 SdpParseError* error) {
2017 // setup-attr = "a=setup:" role
2018 // role = "active" / "passive" / "actpass" / "holdconn"
2019 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002020 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002021 const size_t expected_fields = 2;
2022 if (fields.size() != expected_fields) {
2023 return ParseFailedExpectFieldNum(line, expected_fields, error);
2024 }
2025 std::string role_str = fields[1];
2026 if (!cricket::StringToConnectionRole(role_str, role)) {
2027 return ParseFailed(line, "Invalid attribute value.", error);
2028 }
2029 return true;
2030}
2031
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002032// RFC 3551
2033// PT encoding media type clock rate channels
2034// name (Hz)
2035// 0 PCMU A 8,000 1
2036// 1 reserved A
2037// 2 reserved A
2038// 3 GSM A 8,000 1
2039// 4 G723 A 8,000 1
2040// 5 DVI4 A 8,000 1
2041// 6 DVI4 A 16,000 1
2042// 7 LPC A 8,000 1
2043// 8 PCMA A 8,000 1
2044// 9 G722 A 8,000 1
2045// 10 L16 A 44,100 2
2046// 11 L16 A 44,100 1
2047// 12 QCELP A 8,000 1
2048// 13 CN A 8,000 1
2049// 14 MPA A 90,000 (see text)
2050// 15 G728 A 8,000 1
2051// 16 DVI4 A 11,025 1
2052// 17 DVI4 A 22,050 1
2053// 18 G729 A 8,000 1
2054struct StaticPayloadAudioCodec {
2055 const char* name;
2056 int clockrate;
2057 int channels;
2058};
2059static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2060 { "PCMU", 8000, 1 },
2061 { "reserved", 0, 0 },
2062 { "reserved", 0, 0 },
2063 { "GSM", 8000, 1 },
2064 { "G723", 8000, 1 },
2065 { "DVI4", 8000, 1 },
2066 { "DVI4", 16000, 1 },
2067 { "LPC", 8000, 1 },
2068 { "PCMA", 8000, 1 },
2069 { "G722", 8000, 1 },
2070 { "L16", 44100, 2 },
2071 { "L16", 44100, 1 },
2072 { "QCELP", 8000, 1 },
2073 { "CN", 8000, 1 },
2074 { "MPA", 90000, 1 },
2075 { "G728", 8000, 1 },
2076 { "DVI4", 11025, 1 },
2077 { "DVI4", 22050, 1 },
2078 { "G729", 8000, 1 },
2079};
2080
2081void MaybeCreateStaticPayloadAudioCodecs(
2082 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2083 if (!media_desc) {
2084 return;
2085 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002086 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002087 std::vector<int>::const_iterator it = fmts.begin();
2088 bool add_new_codec = false;
2089 for (; it != fmts.end(); ++it) {
2090 int payload_type = *it;
2091 if (!media_desc->HasCodec(payload_type) &&
2092 payload_type >= 0 &&
2093 payload_type < ARRAY_SIZE(kStaticPayloadAudioCodecs)) {
2094 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2095 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2096 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2097 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2098 clock_rate, 0, channels,
2099 preference));
2100 add_new_codec = true;
2101 }
2102 --preference;
2103 }
2104 if (add_new_codec) {
2105 media_desc->SortCodecs();
2106 }
2107}
2108
2109template <class C>
2110static C* ParseContentDescription(const std::string& message,
2111 const MediaType media_type,
2112 int mline_index,
2113 const std::string& protocol,
2114 const std::vector<int>& codec_preference,
2115 size_t* pos,
2116 std::string* content_name,
2117 TransportDescription* transport,
2118 std::vector<JsepIceCandidate*>* candidates,
2119 webrtc::SdpParseError* error) {
2120 C* media_desc = new C();
2121 switch (media_type) {
2122 case cricket::MEDIA_TYPE_AUDIO:
2123 *content_name = cricket::CN_AUDIO;
2124 break;
2125 case cricket::MEDIA_TYPE_VIDEO:
2126 *content_name = cricket::CN_VIDEO;
2127 break;
2128 case cricket::MEDIA_TYPE_DATA:
2129 *content_name = cricket::CN_DATA;
2130 break;
2131 default:
2132 ASSERT(false);
2133 break;
2134 }
2135 if (!ParseContent(message, media_type, mline_index, protocol,
2136 codec_preference, pos, content_name,
2137 media_desc, transport, candidates, error)) {
2138 delete media_desc;
2139 return NULL;
2140 }
2141 // Sort the codecs according to the m-line fmt list.
2142 media_desc->SortCodecs();
2143 return media_desc;
2144}
2145
2146bool ParseMediaDescription(const std::string& message,
2147 const TransportDescription& session_td,
2148 const RtpHeaderExtensions& session_extmaps,
2149 bool supports_msid,
2150 size_t* pos,
2151 cricket::SessionDescription* desc,
2152 std::vector<JsepIceCandidate*>* candidates,
2153 SdpParseError* error) {
2154 ASSERT(desc != NULL);
2155 std::string line;
2156 int mline_index = -1;
2157
2158 // Zero or more media descriptions
2159 // RFC 4566
2160 // m=<media> <port> <proto> <fmt>
2161 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2162 ++mline_index;
2163
2164 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002165 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166 kSdpDelimiterSpace, &fields);
2167 const size_t expected_min_fields = 4;
2168 if (fields.size() < expected_min_fields) {
2169 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2170 }
2171 bool rejected = false;
2172 // RFC 3264
2173 // To reject an offered stream, the port number in the corresponding stream
2174 // in the answer MUST be set to zero.
2175 if (fields[1] == kMediaPortRejected) {
2176 rejected = true;
2177 }
2178
2179 std::string protocol = fields[2];
2180 bool is_sctp = (protocol == cricket::kMediaProtocolDtlsSctp);
2181
2182 // <fmt>
2183 std::vector<int> codec_preference;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002184 if (!is_sctp) {
2185 for (size_t j = 3 ; j < fields.size(); ++j) {
2186 // TODO(wu): Remove when below bug is fixed.
2187 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
2188 if (fields[j] == "" && j == fields.size() - 1) {
2189 continue;
2190 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002191
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002192 int pl = 0;
2193 if (!GetValueFromString(line, fields[j], &pl, error)) {
2194 return false;
2195 }
2196 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002197 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002198 }
2199
2200 // Make a temporary TransportDescription based on |session_td|.
2201 // Some of this gets overwritten by ParseContent.
2202 TransportDescription transport(NS_JINGLE_ICE_UDP,
2203 session_td.transport_options,
2204 session_td.ice_ufrag,
2205 session_td.ice_pwd,
2206 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002207 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002208 session_td.identity_fingerprint.get(),
2209 Candidates());
2210
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002211 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002212 std::string content_name;
2213 if (HasAttribute(line, kMediaTypeVideo)) {
2214 content.reset(ParseContentDescription<VideoContentDescription>(
2215 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2216 codec_preference, pos, &content_name,
2217 &transport, candidates, error));
2218 } else if (HasAttribute(line, kMediaTypeAudio)) {
2219 content.reset(ParseContentDescription<AudioContentDescription>(
2220 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2221 codec_preference, pos, &content_name,
2222 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002224 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002225 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002226 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2227 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002228 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002229 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002230
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002231 int p;
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002232 if (data_desc && protocol == cricket::kMediaProtocolDtlsSctp &&
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002233 rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002234 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002235 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002236 }
2237
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002238 // We should always use the default bandwidth for RTP-based data
2239 // channels. Don't allow SDP to set the bandwidth, because that
2240 // would give JS the opportunity to "break the Internet".
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002241 // TODO(pthatcher): But we need to temporarily allow the SDP to control
2242 // this for backwards-compatibility. Once we don't need that any
2243 // more, remove this.
2244 bool support_dc_sdp_bandwidth_temporarily = true;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00002245 if (content.get() && !support_dc_sdp_bandwidth_temporarily) {
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002246 content->set_bandwidth(cricket::kAutoBandwidth);
2247 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002248 } else {
2249 LOG(LS_WARNING) << "Unsupported media type: " << line;
2250 continue;
2251 }
2252 if (!content.get()) {
2253 // ParseContentDescription returns NULL if failed.
2254 return false;
2255 }
2256
2257 if (!is_sctp) {
2258 // Make sure to set the media direction correctly. If the direction is not
2259 // MD_RECVONLY or Inactive and no streams are parsed,
2260 // a default MediaStream will be created to prepare for receiving media.
2261 if (supports_msid && content->streams().empty() &&
2262 content->direction() == cricket::MD_SENDRECV) {
2263 content->set_direction(cricket::MD_RECVONLY);
2264 }
2265
2266 // Set the extmap.
2267 if (!session_extmaps.empty() &&
2268 !content->rtp_header_extensions().empty()) {
2269 return ParseFailed("",
2270 "The a=extmap MUST be either all session level or "
2271 "all media level.",
2272 error);
2273 }
2274 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2275 content->AddRtpHeaderExtension(session_extmaps[i]);
2276 }
2277 }
2278 content->set_protocol(protocol);
2279 desc->AddContent(content_name,
2280 is_sctp ? cricket::NS_JINGLE_DRAFT_SCTP :
2281 cricket::NS_JINGLE_RTP,
2282 rejected,
2283 content.release());
2284 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2285 TransportInfo transport_info(content_name, transport);
2286
2287 if (!desc->AddTransportInfo(transport_info)) {
2288 std::ostringstream description;
2289 description << "Failed to AddTransportInfo with content name: "
2290 << content_name;
2291 return ParseFailed("", description.str(), error);
2292 }
2293 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002294
2295 size_t end_of_message = message.size();
2296 if (mline_index == -1 && *pos != end_of_message) {
2297 ParseFailed(message, *pos, "Expects m line.", error);
2298 return false;
2299 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 return true;
2301}
2302
2303bool VerifyCodec(const cricket::Codec& codec) {
2304 // Codec has not been populated correctly unless the name has been set. This
2305 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2306 // have a corresponding "rtpmap" line.
2307 cricket::Codec default_codec;
2308 return default_codec.name != codec.name;
2309}
2310
2311bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2312 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2313 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2314 iter != codecs.end(); ++iter) {
2315 if (!VerifyCodec(*iter)) {
2316 return false;
2317 }
2318 }
2319 return true;
2320}
2321
2322bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2323 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2324 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2325 iter != codecs.end(); ++iter) {
2326 if (!VerifyCodec(*iter)) {
2327 return false;
2328 }
2329 }
2330 return true;
2331}
2332
2333void AddParameters(const cricket::CodecParameterMap& parameters,
2334 cricket::Codec* codec) {
2335 for (cricket::CodecParameterMap::const_iterator iter =
2336 parameters.begin(); iter != parameters.end(); ++iter) {
2337 codec->SetParam(iter->first, iter->second);
2338 }
2339}
2340
2341void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2342 cricket::Codec* codec) {
2343 codec->AddFeedbackParam(feedback_param);
2344}
2345
2346void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2347 cricket::Codec* codec) {
2348 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2349 feedback_params.params().begin();
2350 iter != feedback_params.params().end(); ++iter) {
2351 codec->AddFeedbackParam(*iter);
2352 }
2353}
2354
2355// Gets the current codec setting associated with |payload_type|. If there
2356// is no AudioCodec associated with that payload type it returns an empty codec
2357// with that payload type.
2358template <class T>
2359T GetCodec(const std::vector<T>& codecs, int payload_type) {
2360 for (typename std::vector<T>::const_iterator codec = codecs.begin();
2361 codec != codecs.end(); ++codec) {
2362 if (codec->id == payload_type) {
2363 return *codec;
2364 }
2365 }
2366 T ret_val = T();
2367 ret_val.id = payload_type;
2368 return ret_val;
2369}
2370
2371// Updates or creates a new codec entry in the audio description.
2372template <class T, class U>
2373void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2374 T* desc = static_cast<T*>(content_desc);
2375 std::vector<U> codecs = desc->codecs();
2376 bool found = false;
2377
2378 typename std::vector<U>::iterator iter;
2379 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2380 if (iter->id == codec.id) {
2381 *iter = codec;
2382 found = true;
2383 break;
2384 }
2385 }
2386 if (!found) {
2387 desc->AddCodec(codec);
2388 return;
2389 }
2390 desc->set_codecs(codecs);
2391}
2392
2393// Adds or updates existing codec corresponding to |payload_type| according
2394// to |parameters|.
2395template <class T, class U>
2396void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2397 const cricket::CodecParameterMap& parameters) {
2398 // Codec might already have been populated (from rtpmap).
2399 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2400 AddParameters(parameters, &new_codec);
2401 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2402}
2403
2404// Adds or updates existing codec corresponding to |payload_type| according
2405// to |feedback_param|.
2406template <class T, class U>
2407void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2408 const cricket::FeedbackParam& feedback_param) {
2409 // Codec might already have been populated (from rtpmap).
2410 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2411 AddFeedbackParameter(feedback_param, &new_codec);
2412 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2413}
2414
2415bool PopWildcardCodec(std::vector<cricket::VideoCodec>* codecs,
2416 cricket::VideoCodec* wildcard_codec) {
2417 for (std::vector<cricket::VideoCodec>::iterator iter = codecs->begin();
2418 iter != codecs->end(); ++iter) {
2419 if (iter->id == kWildcardPayloadType) {
2420 *wildcard_codec = *iter;
2421 codecs->erase(iter);
2422 return true;
2423 }
2424 }
2425 return false;
2426}
2427
2428void UpdateFromWildcardVideoCodecs(VideoContentDescription* video_desc) {
2429 std::vector<cricket::VideoCodec> codecs = video_desc->codecs();
2430 cricket::VideoCodec wildcard_codec;
2431 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2432 return;
2433 }
2434 for (std::vector<cricket::VideoCodec>::iterator iter = codecs.begin();
2435 iter != codecs.end(); ++iter) {
2436 cricket::VideoCodec& codec = *iter;
2437 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2438 }
2439 video_desc->set_codecs(codecs);
2440}
2441
2442void AddAudioAttribute(const std::string& name, const std::string& value,
2443 AudioContentDescription* audio_desc) {
2444 if (value.empty()) {
2445 return;
2446 }
2447 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2448 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2449 iter != codecs.end(); ++iter) {
2450 iter->params[name] = value;
2451 }
2452 audio_desc->set_codecs(codecs);
2453}
2454
2455bool ParseContent(const std::string& message,
2456 const MediaType media_type,
2457 int mline_index,
2458 const std::string& protocol,
2459 const std::vector<int>& codec_preference,
2460 size_t* pos,
2461 std::string* content_name,
2462 MediaContentDescription* media_desc,
2463 TransportDescription* transport,
2464 std::vector<JsepIceCandidate*>* candidates,
2465 SdpParseError* error) {
2466 ASSERT(media_desc != NULL);
2467 ASSERT(content_name != NULL);
2468 ASSERT(transport != NULL);
2469
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002470 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2471 MaybeCreateStaticPayloadAudioCodecs(
2472 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2473 }
2474
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002475 // The media level "ice-ufrag" and "ice-pwd".
2476 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2477 Candidates candidates_orig;
2478 std::string line;
2479 std::string mline_id;
2480 // Tracks created out of the ssrc attributes.
2481 StreamParamsVec tracks;
2482 SsrcInfoVec ssrc_infos;
2483 SsrcGroupVec ssrc_groups;
2484 std::string maxptime_as_string;
2485 std::string ptime_as_string;
2486
2487 bool is_rtp =
2488 protocol.empty() ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002489 rtc::starts_with(protocol.data(),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002490 cricket::kMediaProtocolRtpPrefix);
2491
2492 // Loop until the next m line
2493 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2494 if (!GetLine(message, pos, &line)) {
2495 if (*pos >= message.size()) {
2496 break; // Done parsing
2497 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002498 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002499 }
2500 }
2501
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002502 // RFC 4566
2503 // b=* (zero or more bandwidth information lines)
2504 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2505 std::string bandwidth;
2506 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2507 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2508 return false;
2509 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002510 int b = 0;
2511 if (!GetValueFromString(line, bandwidth, &b, error)) {
2512 return false;
2513 }
2514 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002515 }
2516 }
2517 continue;
2518 }
2519
2520 if (!IsLineType(line, kLineTypeAttributes)) {
2521 // TODO: Handle other lines if needed.
2522 LOG(LS_INFO) << "Ignored line: " << line;
2523 continue;
2524 }
2525
2526 // Handle attributes common to SCTP and RTP.
2527 if (HasAttribute(line, kAttributeMid)) {
2528 // RFC 3388
2529 // mid-attribute = "a=mid:" identification-tag
2530 // identification-tag = token
2531 // Use the mid identification-tag as the content name.
2532 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2533 return false;
2534 }
2535 *content_name = mline_id;
2536 } else if (HasAttribute(line, kAttributeCandidate)) {
2537 Candidate candidate;
2538 if (!ParseCandidate(line, &candidate, error, false)) {
2539 return false;
2540 }
2541 candidates_orig.push_back(candidate);
2542 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2543 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2544 return false;
2545 }
2546 } else if (HasAttribute(line, kAttributeIcePwd)) {
2547 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2548 return false;
2549 }
2550 } else if (HasAttribute(line, kAttributeIceOption)) {
2551 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2552 return false;
2553 }
2554 } else if (HasAttribute(line, kAttributeFmtp)) {
2555 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2556 return false;
2557 }
2558 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002559 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002560
2561 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2562 return false;
2563 }
2564 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002565 } else if (HasAttribute(line, kAttributeSetup)) {
2566 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2567 return false;
2568 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002569 } else if (HasAttribute(line, kAttributeSctpPort)) {
2570 int sctp_port;
2571 if (!ParseSctpPort(line, &sctp_port, error)) {
2572 return false;
2573 }
2574 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2575 sctp_port)) {
2576 return false;
2577 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002578 } else if (is_rtp) {
2579 //
2580 // RTP specific attrubtes
2581 //
2582 if (HasAttribute(line, kAttributeRtcpMux)) {
2583 media_desc->set_rtcp_mux(true);
2584 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2585 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2586 return false;
2587 }
2588 } else if (HasAttribute(line, kAttributeSsrc)) {
2589 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2590 return false;
2591 }
2592 } else if (HasAttribute(line, kAttributeCrypto)) {
2593 if (!ParseCryptoAttribute(line, media_desc, error)) {
2594 return false;
2595 }
2596 } else if (HasAttribute(line, kAttributeRtpmap)) {
2597 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2598 media_desc, error)) {
2599 return false;
2600 }
2601 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2602 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2603 return false;
2604 }
2605 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2606 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2607 return false;
2608 }
2609 } else if (HasAttribute(line, kCodecParamPTime)) {
2610 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2611 return false;
2612 }
2613 } else if (HasAttribute(line, kAttributeSendOnly)) {
2614 media_desc->set_direction(cricket::MD_SENDONLY);
2615 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2616 media_desc->set_direction(cricket::MD_RECVONLY);
2617 } else if (HasAttribute(line, kAttributeInactive)) {
2618 media_desc->set_direction(cricket::MD_INACTIVE);
2619 } else if (HasAttribute(line, kAttributeSendRecv)) {
2620 media_desc->set_direction(cricket::MD_SENDRECV);
2621 } else if (HasAttribute(line, kAttributeExtmap)) {
2622 RtpHeaderExtension extmap;
2623 if (!ParseExtmap(line, &extmap, error)) {
2624 return false;
2625 }
2626 media_desc->AddRtpHeaderExtension(extmap);
2627 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2628 // Experimental attribute. Conference mode activates more aggressive
2629 // AEC and NS settings.
2630 // TODO: expose API to set these directly.
2631 std::string flag_value;
2632 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2633 return false;
2634 }
2635 if (flag_value.compare(kValueConference) == 0)
2636 media_desc->set_conference_mode(true);
2637 } else if (HasAttribute(line, kAttributeXGoogleBufferLatency)) {
2638 // Experimental attribute.
2639 // TODO: expose API to set this directly.
2640 std::string flag_value;
2641 if (!GetValue(line, kAttributeXGoogleBufferLatency, &flag_value,
2642 error)) {
2643 return false;
2644 }
2645 int buffer_latency = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002646 if (!GetValueFromString(line, flag_value, &buffer_latency, error)) {
2647 return false;
2648 }
2649 if (buffer_latency < 0) {
2650 return ParseFailed(line, "Buffer latency less than 0.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002651 }
2652 media_desc->set_buffered_mode_latency(buffer_latency);
2653 }
2654 } else {
2655 // Only parse lines that we are interested of.
2656 LOG(LS_INFO) << "Ignored line: " << line;
2657 continue;
2658 }
2659 }
2660
2661 // Create tracks from the |ssrc_infos|.
2662 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2663
2664 // Add the ssrc group to the track.
2665 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2666 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2667 if (ssrc_group->ssrcs.empty()) {
2668 continue;
2669 }
2670 uint32 ssrc = ssrc_group->ssrcs.front();
2671 for (StreamParamsVec::iterator track = tracks.begin();
2672 track != tracks.end(); ++track) {
2673 if (track->has_ssrc(ssrc)) {
2674 track->ssrc_groups.push_back(*ssrc_group);
2675 }
2676 }
2677 }
2678
2679 // Add the new tracks to the |media_desc|.
2680 for (StreamParamsVec::iterator track = tracks.begin();
2681 track != tracks.end(); ++track) {
2682 media_desc->AddStream(*track);
2683 }
2684
2685 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2686 AudioContentDescription* audio_desc =
2687 static_cast<AudioContentDescription*>(media_desc);
2688 // Verify audio codec ensures that no audio codec has been populated with
2689 // only fmtp.
2690 if (!VerifyAudioCodecs(audio_desc)) {
2691 return ParseFailed("Failed to parse audio codecs correctly.", error);
2692 }
2693 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2694 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2695 }
2696
2697 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2698 VideoContentDescription* video_desc =
2699 static_cast<VideoContentDescription*>(media_desc);
2700 UpdateFromWildcardVideoCodecs(video_desc);
2701 // Verify video codec ensures that no video codec has been populated with
2702 // only rtcp-fb.
2703 if (!VerifyVideoCodecs(video_desc)) {
2704 return ParseFailed("Failed to parse video codecs correctly.", error);
2705 }
2706 }
2707
2708 // RFC 5245
2709 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2710 for (Candidates::iterator it = candidates_orig.begin();
2711 it != candidates_orig.end(); ++it) {
2712 ASSERT((*it).username().empty());
2713 (*it).set_username(transport->ice_ufrag);
2714 ASSERT((*it).password().empty());
2715 (*it).set_password(transport->ice_pwd);
2716 candidates->push_back(
2717 new JsepIceCandidate(mline_id, mline_index, *it));
2718 }
2719 return true;
2720}
2721
2722bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2723 SdpParseError* error) {
2724 ASSERT(ssrc_infos != NULL);
2725 // RFC 5576
2726 // a=ssrc:<ssrc-id> <attribute>
2727 // a=ssrc:<ssrc-id> <attribute>:<value>
2728 std::string field1, field2;
2729 if (!SplitByDelimiter(line.substr(kLinePrefixLength),
2730 kSdpDelimiterSpace,
2731 &field1,
2732 &field2)) {
2733 const size_t expected_fields = 2;
2734 return ParseFailedExpectFieldNum(line, expected_fields, error);
2735 }
2736
2737 // ssrc:<ssrc-id>
2738 std::string ssrc_id_s;
2739 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2740 return false;
2741 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002742 uint32 ssrc_id = 0;
2743 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2744 return false;
2745 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002746
2747 std::string attribute;
2748 std::string value;
2749 if (!SplitByDelimiter(field2, kSdpDelimiterColon,
2750 &attribute, &value)) {
2751 std::ostringstream description;
2752 description << "Failed to get the ssrc attribute value from " << field2
2753 << ". Expected format <attribute>:<value>.";
2754 return ParseFailed(line, description.str(), error);
2755 }
2756
2757 // Check if there's already an item for this |ssrc_id|. Create a new one if
2758 // there isn't.
2759 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2760 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2761 if (ssrc_info->ssrc_id == ssrc_id) {
2762 break;
2763 }
2764 }
2765 if (ssrc_info == ssrc_infos->end()) {
2766 SsrcInfo info;
2767 info.ssrc_id = ssrc_id;
2768 ssrc_infos->push_back(info);
2769 ssrc_info = ssrc_infos->end() - 1;
2770 }
2771
2772 // Store the info to the |ssrc_info|.
2773 if (attribute == kSsrcAttributeCname) {
2774 // RFC 5576
2775 // cname:<value>
2776 ssrc_info->cname = value;
2777 } else if (attribute == kSsrcAttributeMsid) {
2778 // draft-alvestrand-mmusic-msid-00
2779 // "msid:" identifier [ " " appdata ]
2780 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002781 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002782 if (fields.size() < 1 || fields.size() > 2) {
2783 return ParseFailed(line,
2784 "Expected format \"msid:<identifier>[ <appdata>]\".",
2785 error);
2786 }
2787 ssrc_info->msid_identifier = fields[0];
2788 if (fields.size() == 2) {
2789 ssrc_info->msid_appdata = fields[1];
2790 }
2791 } else if (attribute == kSsrcAttributeMslabel) {
2792 // draft-alvestrand-rtcweb-mid-01
2793 // mslabel:<value>
2794 ssrc_info->mslabel = value;
2795 } else if (attribute == kSSrcAttributeLabel) {
2796 // The label isn't defined.
2797 // label:<value>
2798 ssrc_info->label = value;
2799 }
2800 return true;
2801}
2802
2803bool ParseSsrcGroupAttribute(const std::string& line,
2804 SsrcGroupVec* ssrc_groups,
2805 SdpParseError* error) {
2806 ASSERT(ssrc_groups != NULL);
2807 // RFC 5576
2808 // a=ssrc-group:<semantics> <ssrc-id> ...
2809 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002810 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002811 kSdpDelimiterSpace, &fields);
2812 const size_t expected_min_fields = 2;
2813 if (fields.size() < expected_min_fields) {
2814 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2815 }
2816 std::string semantics;
2817 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2818 return false;
2819 }
2820 std::vector<uint32> ssrcs;
2821 for (size_t i = 1; i < fields.size(); ++i) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002822 uint32 ssrc = 0;
2823 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2824 return false;
2825 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002826 ssrcs.push_back(ssrc);
2827 }
2828 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2829 return true;
2830}
2831
2832bool ParseCryptoAttribute(const std::string& line,
2833 MediaContentDescription* media_desc,
2834 SdpParseError* error) {
2835 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002836 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002837 kSdpDelimiterSpace, &fields);
2838 // RFC 4568
2839 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2840 const size_t expected_min_fields = 3;
2841 if (fields.size() < expected_min_fields) {
2842 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2843 }
2844 std::string tag_value;
2845 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2846 return false;
2847 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002848 int tag = 0;
2849 if (!GetValueFromString(line, tag_value, &tag, error)) {
2850 return false;
2851 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002852 const std::string crypto_suite = fields[1];
2853 const std::string key_params = fields[2];
2854 std::string session_params;
2855 if (fields.size() > 3) {
2856 session_params = fields[3];
2857 }
2858 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2859 session_params));
2860 return true;
2861}
2862
2863// Updates or creates a new codec entry in the audio description with according
2864// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2865void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2866 int bitrate, int channels, int preference,
2867 AudioContentDescription* audio_desc) {
2868 // Codec may already be populated with (only) optional parameters
2869 // (from an fmtp).
2870 cricket::AudioCodec codec = GetCodec(audio_desc->codecs(), payload_type);
2871 codec.name = name;
2872 codec.clockrate = clockrate;
2873 codec.bitrate = bitrate;
2874 codec.channels = channels;
2875 codec.preference = preference;
2876 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2877 codec);
2878}
2879
2880// Updates or creates a new codec entry in the video description according to
2881// |name|, |width|, |height|, |framerate| and |preference|.
2882void UpdateCodec(int payload_type, const std::string& name, int width,
2883 int height, int framerate, int preference,
2884 VideoContentDescription* video_desc) {
2885 // Codec may already be populated with (only) optional parameters
2886 // (from an fmtp).
2887 cricket::VideoCodec codec = GetCodec(video_desc->codecs(), payload_type);
2888 codec.name = name;
2889 codec.width = width;
2890 codec.height = height;
2891 codec.framerate = framerate;
2892 codec.preference = preference;
2893 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2894 codec);
2895}
2896
2897bool ParseRtpmapAttribute(const std::string& line,
2898 const MediaType media_type,
2899 const std::vector<int>& codec_preference,
2900 MediaContentDescription* media_desc,
2901 SdpParseError* error) {
2902 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002903 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002904 kSdpDelimiterSpace, &fields);
2905 // RFC 4566
2906 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2907 const size_t expected_min_fields = 2;
2908 if (fields.size() < expected_min_fields) {
2909 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2910 }
2911 std::string payload_type_value;
2912 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2913 return false;
2914 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002915 int payload_type = 0;
2916 if (!GetValueFromString(line, payload_type_value, &payload_type, error)) {
2917 return false;
2918 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002919
2920 // Set the preference order depending on the order of the pl type in the
2921 // <fmt> of the m-line.
2922 const int preference = codec_preference.end() -
2923 std::find(codec_preference.begin(), codec_preference.end(),
2924 payload_type);
2925 if (preference == 0) {
2926 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2927 << "<fmt> of the m-line: " << line;
2928 return true;
2929 }
2930 const std::string encoder = fields[1];
2931 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002932 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002933 // <encoding name>/<clock rate>[/<encodingparameters>]
2934 // 2 mandatory fields
2935 if (codec_params.size() < 2 || codec_params.size() > 3) {
2936 return ParseFailed(line,
2937 "Expected format \"<encoding name>/<clock rate>"
2938 "[/<encodingparameters>]\".",
2939 error);
2940 }
2941 const std::string encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002942 int clock_rate = 0;
2943 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2944 return false;
2945 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002946 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2947 VideoContentDescription* video_desc =
2948 static_cast<VideoContentDescription*>(media_desc);
2949 // TODO: We will send resolution in SDP. For now use
2950 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2951 UpdateCodec(payload_type, encoding_name,
2952 JsepSessionDescription::kMaxVideoCodecWidth,
2953 JsepSessionDescription::kMaxVideoCodecHeight,
2954 JsepSessionDescription::kDefaultVideoCodecFramerate,
2955 preference, video_desc);
2956 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2957 // RFC 4566
2958 // For audio streams, <encoding parameters> indicates the number
2959 // of audio channels. This parameter is OPTIONAL and may be
2960 // omitted if the number of channels is one, provided that no
2961 // additional parameters are needed.
2962 int channels = 1;
2963 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002964 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2965 return false;
2966 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002967 }
2968 int bitrate = 0;
2969 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2970 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2971 // The bandwidth adaptation doesn't always work well, so this code
2972 // sets a fixed target bitrate instead.
2973 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2974 if (clock_rate <= 16000) {
2975 bitrate = kIsacWbDefaultRate;
2976 } else {
2977 bitrate = kIsacSwbDefaultRate;
2978 }
2979 }
2980 AudioContentDescription* audio_desc =
2981 static_cast<AudioContentDescription*>(media_desc);
2982 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2983 preference, audio_desc);
2984 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2985 DataContentDescription* data_desc =
2986 static_cast<DataContentDescription*>(media_desc);
2987 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2988 preference));
2989 }
2990 return true;
2991}
2992
2993void PruneRight(const char delimiter, std::string* message) {
2994 size_t trailing = message->find(delimiter);
2995 if (trailing != std::string::npos) {
2996 *message = message->substr(0, trailing);
2997 }
2998}
2999
3000bool ParseFmtpParam(const std::string& line, std::string* parameter,
3001 std::string* value, SdpParseError* error) {
3002 if (!SplitByDelimiter(line, kSdpDelimiterEqual, parameter, value)) {
3003 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
3004 return false;
3005 }
3006 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
3007 // When parsing the values the trailing ";" gets picked up. Remove them.
3008 PruneRight(kSdpDelimiterSemicolon, value);
3009 return true;
3010}
3011
3012bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
3013 MediaContentDescription* media_desc,
3014 SdpParseError* error) {
3015 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3016 media_type != cricket::MEDIA_TYPE_VIDEO) {
3017 return true;
3018 }
3019 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003020 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003021 kSdpDelimiterSpace, &fields);
3022
3023 // RFC 5576
3024 // a=fmtp:<format> <format specific parameters>
3025 // At least two fields, whereas the second one is any of the optional
3026 // parameters.
3027 if (fields.size() < 2) {
3028 ParseFailedExpectMinFieldNum(line, 2, error);
3029 return false;
3030 }
3031
3032 std::string payload_type;
3033 if (!GetValue(fields[0], kAttributeFmtp, &payload_type, error)) {
3034 return false;
3035 }
3036
3037 cricket::CodecParameterMap codec_params;
3038 for (std::vector<std::string>::const_iterator iter = fields.begin() + 1;
3039 iter != fields.end(); ++iter) {
3040 std::string name;
3041 std::string value;
3042 if (iter->find(kSdpDelimiterEqual) == std::string::npos) {
3043 // Only fmtps with equals are currently supported. Other fmtp types
3044 // should be ignored. Unknown fmtps do not constitute an error.
3045 continue;
3046 }
3047 if (!ParseFmtpParam(*iter, &name, &value, error)) {
3048 return false;
3049 }
3050 codec_params[name] = value;
3051 }
3052
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003053 int int_payload_type = 0;
3054 if (!GetValueFromString(line, payload_type, &int_payload_type, error)) {
3055 return false;
3056 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003057 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3058 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3059 media_desc, int_payload_type, codec_params);
3060 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3061 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3062 media_desc, int_payload_type, codec_params);
3063 }
3064 return true;
3065}
3066
3067bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3068 MediaContentDescription* media_desc,
3069 SdpParseError* error) {
3070 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3071 media_type != cricket::MEDIA_TYPE_VIDEO) {
3072 return true;
3073 }
3074 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003075 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003076 if (rtcp_fb_fields.size() < 2) {
3077 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3078 }
3079 std::string payload_type_string;
3080 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3081 error)) {
3082 return false;
3083 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003084 int payload_type = kWildcardPayloadType;
3085 if (payload_type_string != "*") {
3086 if (!GetValueFromString(line, payload_type_string, &payload_type, error)) {
3087 return false;
3088 }
3089 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003090 std::string id = rtcp_fb_fields[1];
3091 std::string param = "";
3092 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3093 iter != rtcp_fb_fields.end(); ++iter) {
3094 param.append(*iter);
3095 }
3096 const cricket::FeedbackParam feedback_param(id, param);
3097
3098 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3099 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(media_desc,
3100 payload_type,
3101 feedback_param);
3102 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3103 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(media_desc,
3104 payload_type,
3105 feedback_param);
3106 }
3107 return true;
3108}
3109
3110} // namespace webrtc