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