blob: 2eb5fb32bd6cacbe989e6c2fb3370fb73d070ca5 [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"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000038#include "webrtc/base/common.h"
39#include "webrtc/base/logging.h"
40#include "webrtc/base/messagedigest.h"
41#include "webrtc/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000042#include "talk/media/base/codec.h"
43#include "talk/media/base/constants.h"
44#include "talk/media/base/cryptoparams.h"
mallinath@webrtc.org1112c302013-09-23 20:34:45 +000045#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000046#include "talk/p2p/base/candidate.h"
47#include "talk/p2p/base/constants.h"
48#include "talk/p2p/base/port.h"
49#include "talk/session/media/mediasession.h"
50#include "talk/session/media/mediasessionclient.h"
51
52using cricket::AudioContentDescription;
53using cricket::Candidate;
54using cricket::Candidates;
55using cricket::ContentDescription;
56using cricket::ContentInfo;
57using cricket::CryptoParams;
58using cricket::DataContentDescription;
59using cricket::ICE_CANDIDATE_COMPONENT_RTP;
60using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
61using cricket::kCodecParamMaxBitrate;
62using cricket::kCodecParamMaxPTime;
63using cricket::kCodecParamMaxQuantization;
64using cricket::kCodecParamMinBitrate;
65using cricket::kCodecParamMinPTime;
66using cricket::kCodecParamPTime;
67using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000068using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069using cricket::kCodecParamStereo;
70using cricket::kCodecParamUseInbandFec;
71using cricket::kCodecParamSctpProtocol;
72using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000073using cricket::kCodecParamMaxAverageBitrate;
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";
158
159// Experimental flags
160static const char kAttributeXGoogleFlag[] = "x-google-flag";
161static const char kValueConference[] = "conference";
162static const char kAttributeXGoogleBufferLatency[] =
163 "x-google-buffer-latency";
164
165// Candidate
166static const char kCandidateHost[] = "host";
167static const char kCandidateSrflx[] = "srflx";
168// TODO: How to map the prflx with circket candidate type
169// static const char kCandidatePrflx[] = "prflx";
170static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000171static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000172
173static const char kSdpDelimiterEqual = '=';
174static const char kSdpDelimiterSpace = ' ';
175static const char kSdpDelimiterColon = ':';
176static const char kSdpDelimiterSemicolon = ';';
177static const char kSdpDelimiterSlash = '/';
178static const char kNewLine = '\n';
179static const char kReturn = '\r';
180static const char kLineBreak[] = "\r\n";
181
182// TODO: Generate the Session and Time description
183// instead of hardcoding.
184static const char kSessionVersion[] = "v=0";
185// RFC 4566
186static const char kSessionOriginUsername[] = "-";
187static const char kSessionOriginSessionId[] = "0";
188static const char kSessionOriginSessionVersion[] = "0";
189static const char kSessionOriginNettype[] = "IN";
190static const char kSessionOriginAddrtype[] = "IP4";
191static const char kSessionOriginAddress[] = "127.0.0.1";
192static const char kSessionName[] = "s=-";
193static const char kTimeDescription[] = "t=0 0";
194static const char kAttrGroup[] = "a=group:BUNDLE";
195static const char kConnectionNettype[] = "IN";
196static const char kConnectionAddrtype[] = "IP4";
197static const char kMediaTypeVideo[] = "video";
198static const char kMediaTypeAudio[] = "audio";
199static const char kMediaTypeData[] = "application";
200static const char kMediaPortRejected[] = "0";
201static const char kDefaultAddress[] = "0.0.0.0";
202static const char kDefaultPort[] = "1";
203// RFC 3556
204static const char kApplicationSpecificMaximum[] = "AS";
205
206static const int kDefaultVideoClockrate = 90000;
207
208// ISAC special-case.
209static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
210static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
211static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
212
wu@webrtc.org78187522013-10-07 23:32:02 +0000213static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000214
215struct SsrcInfo {
216 SsrcInfo()
217 : msid_identifier(kDefaultMsid),
218 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
219 // Create random string (which will be used as track label later)?
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000220 msid_appdata(rtc::CreateRandomString(8)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000221 }
222 uint32 ssrc_id;
223 std::string cname;
224 std::string msid_identifier;
225 std::string msid_appdata;
226
227 // For backward compatibility.
228 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
229 std::string label;
230 std::string mslabel;
231};
232typedef std::vector<SsrcInfo> SsrcInfoVec;
233typedef std::vector<SsrcGroup> SsrcGroupVec;
234
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000235template <class T>
236static void AddFmtpLine(const T& codec, std::string* message);
237static void BuildMediaDescription(const ContentInfo* content_info,
238 const TransportInfo* transport_info,
239 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000240 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000241 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000242static void BuildSctpContentAttributes(std::string* message, int sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000243static void BuildRtpContentAttributes(
244 const MediaContentDescription* media_desc,
245 const MediaType media_type,
246 std::string* message);
247static void BuildRtpMap(const MediaContentDescription* media_desc,
248 const MediaType media_type,
249 std::string* message);
250static void BuildCandidate(const std::vector<Candidate>& candidates,
251 std::string* message);
252static void BuildIceOptions(const std::vector<std::string>& transport_options,
253 std::string* message);
254
255static bool ParseSessionDescription(const std::string& message, size_t* pos,
256 std::string* session_id,
257 std::string* session_version,
258 bool* supports_msid,
259 TransportDescription* session_td,
260 RtpHeaderExtensions* session_extmaps,
261 cricket::SessionDescription* desc,
262 SdpParseError* error);
263static bool ParseGroupAttribute(const std::string& line,
264 cricket::SessionDescription* desc,
265 SdpParseError* error);
266static bool ParseMediaDescription(
267 const std::string& message,
268 const TransportDescription& session_td,
269 const RtpHeaderExtensions& session_extmaps,
270 bool supports_msid,
271 size_t* pos, cricket::SessionDescription* desc,
272 std::vector<JsepIceCandidate*>* candidates,
273 SdpParseError* error);
274static bool ParseContent(const std::string& message,
275 const MediaType media_type,
276 int mline_index,
277 const std::string& protocol,
278 const std::vector<int>& codec_preference,
279 size_t* pos,
280 std::string* content_name,
281 MediaContentDescription* media_desc,
282 TransportDescription* transport,
283 std::vector<JsepIceCandidate*>* candidates,
284 SdpParseError* error);
285static bool ParseSsrcAttribute(const std::string& line,
286 SsrcInfoVec* ssrc_infos,
287 SdpParseError* error);
288static bool ParseSsrcGroupAttribute(const std::string& line,
289 SsrcGroupVec* ssrc_groups,
290 SdpParseError* error);
291static bool ParseCryptoAttribute(const std::string& line,
292 MediaContentDescription* media_desc,
293 SdpParseError* error);
294static bool ParseRtpmapAttribute(const std::string& line,
295 const MediaType media_type,
296 const std::vector<int>& codec_preference,
297 MediaContentDescription* media_desc,
298 SdpParseError* error);
299static bool ParseFmtpAttributes(const std::string& line,
300 const MediaType media_type,
301 MediaContentDescription* media_desc,
302 SdpParseError* error);
303static bool ParseFmtpParam(const std::string& line, std::string* parameter,
304 std::string* value, SdpParseError* error);
305static bool ParseCandidate(const std::string& message, Candidate* candidate,
306 SdpParseError* error, bool is_raw);
307static bool ParseRtcpFbAttribute(const std::string& line,
308 const MediaType media_type,
309 MediaContentDescription* media_desc,
310 SdpParseError* error);
311static bool ParseIceOptions(const std::string& line,
312 std::vector<std::string>* transport_options,
313 SdpParseError* error);
314static bool ParseExtmap(const std::string& line,
315 RtpHeaderExtension* extmap,
316 SdpParseError* error);
317static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000318 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000319 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000320static bool ParseDtlsSetup(const std::string& line,
321 cricket::ConnectionRole* role,
322 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000323
324// Helper functions
325
326// Below ParseFailed*** functions output the line that caused the parsing
327// failure and the detailed reason (|description|) of the failure to |error|.
328// The functions always return false so that they can be used directly in the
329// following way when error happens:
330// "return ParseFailed***(...);"
331
332// The line starting at |line_start| of |message| is the failing line.
333// The reason for the failure should be provided in the |description|.
334// An example of a description could be "unknown character".
335static bool ParseFailed(const std::string& message,
336 size_t line_start,
337 const std::string& description,
338 SdpParseError* error) {
339 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000340 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000341 size_t line_end = message.find(kNewLine, line_start);
342 if (line_end != std::string::npos) {
343 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
344 --line_end;
345 }
346 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000347 } else {
348 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000349 }
350
351 if (error) {
352 error->line = first_line;
353 error->description = description;
354 }
355 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
356 << "\". Reason: " << description;
357 return false;
358}
359
360// |line| is the failing line. The reason for the failure should be
361// provided in the |description|.
362static bool ParseFailed(const std::string& line,
363 const std::string& description,
364 SdpParseError* error) {
365 return ParseFailed(line, 0, description, error);
366}
367
368// Parses failure where the failing SDP line isn't know or there are multiple
369// failing lines.
370static bool ParseFailed(const std::string& description,
371 SdpParseError* error) {
372 return ParseFailed("", description, error);
373}
374
375// |line| is the failing line. The failure is due to the fact that |line|
376// doesn't have |expected_fields| fields.
377static bool ParseFailedExpectFieldNum(const std::string& line,
378 int expected_fields,
379 SdpParseError* error) {
380 std::ostringstream description;
381 description << "Expects " << expected_fields << " fields.";
382 return ParseFailed(line, description.str(), error);
383}
384
385// |line| is the failing line. The failure is due to the fact that |line| has
386// less than |expected_min_fields| fields.
387static bool ParseFailedExpectMinFieldNum(const std::string& line,
388 int expected_min_fields,
389 SdpParseError* error) {
390 std::ostringstream description;
391 description << "Expects at least " << expected_min_fields << " fields.";
392 return ParseFailed(line, description.str(), error);
393}
394
395// |line| is the failing line. The failure is due to the fact that it failed to
396// get the value of |attribute|.
397static bool ParseFailedGetValue(const std::string& line,
398 const std::string& attribute,
399 SdpParseError* error) {
400 std::ostringstream description;
401 description << "Failed to get the value of attribute: " << attribute;
402 return ParseFailed(line, description.str(), error);
403}
404
405// The line starting at |line_start| of |message| is the failing line. The
406// failure is due to the line type (e.g. the "m" part of the "m-line")
407// not matching what is expected. The expected line type should be
408// provided as |line_type|.
409static bool ParseFailedExpectLine(const std::string& message,
410 size_t line_start,
411 const char line_type,
412 const std::string& line_value,
413 SdpParseError* error) {
414 std::ostringstream description;
415 description << "Expect line: " << line_type << "=" << line_value;
416 return ParseFailed(message, line_start, description.str(), error);
417}
418
419static bool AddLine(const std::string& line, std::string* message) {
420 if (!message)
421 return false;
422
423 message->append(line);
424 message->append(kLineBreak);
425 return true;
426}
427
428static bool GetLine(const std::string& message,
429 size_t* pos,
430 std::string* line) {
431 size_t line_begin = *pos;
432 size_t line_end = message.find(kNewLine, line_begin);
433 if (line_end == std::string::npos) {
434 return false;
435 }
436 // Update the new start position
437 *pos = line_end + 1;
438 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
439 --line_end;
440 }
441 *line = message.substr(line_begin, (line_end - line_begin));
442 const char* cline = line->c_str();
443 // RFC 4566
444 // An SDP session description consists of a number of lines of text of
445 // the form:
446 // <type>=<value>
447 // where <type> MUST be exactly one case-significant character and
448 // <value> is structured text whose format depends on <type>.
449 // Whitespace MUST NOT be used on either side of the "=" sign.
450 if (cline[0] == kSdpDelimiterSpace ||
451 cline[1] != kSdpDelimiterEqual ||
452 cline[2] == kSdpDelimiterSpace) {
453 *pos = line_begin;
454 return false;
455 }
456 return true;
457}
458
459// Init |os| to "|type|=|value|".
460static void InitLine(const char type,
461 const std::string& value,
462 std::ostringstream* os) {
463 os->str("");
464 *os << type << kSdpDelimiterEqual << value;
465}
466
467// Init |os| to "a=|attribute|".
468static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
469 InitLine(kLineTypeAttributes, attribute, os);
470}
471
472// Writes a SDP attribute line based on |attribute| and |value| to |message|.
473static void AddAttributeLine(const std::string& attribute, int value,
474 std::string* message) {
475 std::ostringstream os;
476 InitAttrLine(attribute, &os);
477 os << kSdpDelimiterColon << value;
478 AddLine(os.str(), message);
479}
480
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000481static bool IsLineType(const std::string& message,
482 const char type,
483 size_t line_start) {
484 if (message.size() < line_start + kLinePrefixLength) {
485 return false;
486 }
487 const char* cmessage = message.c_str();
488 return (cmessage[line_start] == type &&
489 cmessage[line_start + 1] == kSdpDelimiterEqual);
490}
491
492static bool IsLineType(const std::string& line,
493 const char type) {
494 return IsLineType(line, type, 0);
495}
496
497static bool GetLineWithType(const std::string& message, size_t* pos,
498 std::string* line, const char type) {
499 if (!IsLineType(message, type, *pos)) {
500 return false;
501 }
502
503 if (!GetLine(message, pos, line))
504 return false;
505
506 return true;
507}
508
509static bool HasAttribute(const std::string& line,
510 const std::string& attribute) {
511 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
512}
513
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000514static bool AddSsrcLine(uint32 ssrc_id, const std::string& attribute,
515 const std::string& value, std::string* message) {
516 // RFC 5576
517 // a=ssrc:<ssrc-id> <attribute>:<value>
518 std::ostringstream os;
519 InitAttrLine(kAttributeSsrc, &os);
520 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
521 << attribute << kSdpDelimiterColon << value;
522 return AddLine(os.str(), message);
523}
524
525// Split the message into two parts by the first delimiter.
526static bool SplitByDelimiter(const std::string& message,
527 const char delimiter,
528 std::string* field1,
529 std::string* field2) {
530 // Find the first delimiter
531 size_t pos = message.find(delimiter);
532 if (pos == std::string::npos) {
533 return false;
534 }
535 *field1 = message.substr(0, pos);
536 // The rest is the value.
537 *field2 = message.substr(pos + 1);
538 return true;
539}
540
541// Get value only from <attribute>:<value>.
542static bool GetValue(const std::string& message, const std::string& attribute,
543 std::string* value, SdpParseError* error) {
544 std::string leftpart;
545 if (!SplitByDelimiter(message, kSdpDelimiterColon, &leftpart, value)) {
546 return ParseFailedGetValue(message, attribute, error);
547 }
548 // The left part should end with the expected attribute.
549 if (leftpart.length() < attribute.length() ||
550 leftpart.compare(leftpart.length() - attribute.length(),
551 attribute.length(), attribute) != 0) {
552 return ParseFailedGetValue(message, attribute, error);
553 }
554 return true;
555}
556
557static bool CaseInsensitiveFind(std::string str1, std::string str2) {
558 std::transform(str1.begin(), str1.end(), str1.begin(),
559 ::tolower);
560 std::transform(str2.begin(), str2.end(), str2.begin(),
561 ::tolower);
562 return str1.find(str2) != std::string::npos;
563}
564
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000565template <class T>
566static bool GetValueFromString(const std::string& line,
567 const std::string& s,
568 T* t,
569 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000570 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000571 std::ostringstream description;
572 description << "Invalid value: " << s << ".";
573 return ParseFailed(line, description.str(), error);
574 }
575 return true;
576}
577
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000578void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
579 StreamParamsVec* tracks) {
580 ASSERT(tracks != NULL);
581 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
582 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
583 if (ssrc_info->cname.empty()) {
584 continue;
585 }
586
587 std::string sync_label;
588 std::string track_id;
589 if (ssrc_info->msid_identifier == kDefaultMsid &&
590 !ssrc_info->mslabel.empty()) {
591 // If there's no msid and there's mslabel, we consider this is a sdp from
592 // a older version of client that doesn't support msid.
593 // In that case, we use the mslabel and label to construct the track.
594 sync_label = ssrc_info->mslabel;
595 track_id = ssrc_info->label;
596 } else {
597 sync_label = ssrc_info->msid_identifier;
598 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
599 // is corresponding to the "id" attribute of StreamParams.
600 track_id = ssrc_info->msid_appdata;
601 }
602 if (sync_label.empty() || track_id.empty()) {
603 ASSERT(false);
604 continue;
605 }
606
607 StreamParamsVec::iterator track = tracks->begin();
608 for (; track != tracks->end(); ++track) {
609 if (track->id == track_id) {
610 break;
611 }
612 }
613 if (track == tracks->end()) {
614 // If we don't find an existing track, create a new one.
615 tracks->push_back(StreamParams());
616 track = tracks->end() - 1;
617 }
618 track->add_ssrc(ssrc_info->ssrc_id);
619 track->cname = ssrc_info->cname;
620 track->sync_label = sync_label;
621 track->id = track_id;
622 }
623}
624
625void GetMediaStreamLabels(const ContentInfo* content,
626 std::set<std::string>* labels) {
627 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000628 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000629 content->description);
630 const cricket::StreamParamsVec& streams = media_desc->streams();
631 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
632 it != streams.end(); ++it) {
633 labels->insert(it->sync_label);
634 }
635}
636
637// RFC 5245
638// It is RECOMMENDED that default candidates be chosen based on the
639// likelihood of those candidates to work with the peer that is being
640// contacted. It is RECOMMENDED that relayed > reflexive > host.
641static const int kPreferenceUnknown = 0;
642static const int kPreferenceHost = 1;
643static const int kPreferenceReflexive = 2;
644static const int kPreferenceRelayed = 3;
645
646static int GetCandidatePreferenceFromType(const std::string& type) {
647 int preference = kPreferenceUnknown;
648 if (type == cricket::LOCAL_PORT_TYPE) {
649 preference = kPreferenceHost;
650 } else if (type == cricket::STUN_PORT_TYPE) {
651 preference = kPreferenceReflexive;
652 } else if (type == cricket::RELAY_PORT_TYPE) {
653 preference = kPreferenceRelayed;
654 } else {
655 ASSERT(false);
656 }
657 return preference;
658}
659
660// Get ip and port of the default destination from the |candidates| with
661// the given value of |component_id|.
662// RFC 5245
663// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
664// TODO: Decide the default destination in webrtcsession and
665// pass it down via SessionDescription.
666static bool GetDefaultDestination(const std::vector<Candidate>& candidates,
667 int component_id, std::string* port, std::string* ip) {
668 *port = kDefaultPort;
669 *ip = kDefaultAddress;
670 int current_preference = kPreferenceUnknown;
671 for (std::vector<Candidate>::const_iterator it = candidates.begin();
672 it != candidates.end(); ++it) {
673 if (it->component() != component_id) {
674 continue;
675 }
676 const int preference = GetCandidatePreferenceFromType(it->type());
677 // See if this candidate is more preferable then the current one.
678 if (preference <= current_preference) {
679 continue;
680 }
681 current_preference = preference;
682 *port = it->address().PortAsString();
683 *ip = it->address().ipaddr().ToString();
684 }
685 return true;
686}
687
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000688// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000690 const std::vector<Candidate>& candidates,
691 const std::string mline,
692 std::string* message) {
693 std::string new_lines;
694 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695 // RFC 4566
696 // m=<media> <port> <proto> <fmt> ...
697 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000698 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000699 if (fields.size() < 3) {
700 return;
701 }
702
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000703 std::ostringstream os;
704 std::string rtp_port, rtp_ip;
705 if (GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
706 &rtp_port, &rtp_ip)) {
707 // Found default RTP candidate.
708 // RFC 5245
709 // The default candidates are added to the SDP as the default
710 // destination for media. For streams based on RTP, this is done by
711 // placing the IP address and port of the RTP candidate into the c and m
712 // lines, respectively.
713
714 // Update the port in the m line.
715 // If this is a m-line with port equal to 0, we don't change it.
716 if (fields[1] != kMediaPortRejected) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000717 new_lines.replace(fields[0].size() + 1,
718 fields[1].size(),
719 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000720 }
721 // Add the c line.
722 // RFC 4566
723 // c=<nettype> <addrtype> <connection-address>
724 InitLine(kLineTypeConnection, kConnectionNettype, &os);
725 os << " " << kConnectionAddrtype << " " << rtp_ip;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000726 AddLine(os.str(), &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727 }
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000728 message->append(new_lines);
729}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000731// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
732static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
733 std::string rtcp_line, rtcp_port, rtcp_ip;
734 if (GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
735 &rtcp_port, &rtcp_ip)) {
736 // Found default RTCP candidate.
737 // RFC 5245
738 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
739 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000741 // RFC 3605
742 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
743 // connection-address] CRLF
744 std::ostringstream os;
745 InitAttrLine(kAttributeRtcp, &os);
746 os << kSdpDelimiterColon
747 << rtcp_port << " "
748 << kConnectionNettype << " "
749 << kConnectionAddrtype << " "
750 << rtcp_ip;
751 rtcp_line = os.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000752 }
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000753 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000754}
755
756// Get candidates according to the mline index from SessionDescriptionInterface.
757static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
758 int mline_index,
759 std::vector<Candidate>* candidates) {
760 if (!candidates) {
761 return;
762 }
763 const IceCandidateCollection* cc = desci.candidates(mline_index);
764 for (size_t i = 0; i < cc->count(); ++i) {
765 const IceCandidateInterface* candidate = cc->at(i);
766 candidates->push_back(candidate->candidate());
767 }
768}
769
770std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771 const cricket::SessionDescription* desc = jdesc.description();
772 if (!desc) {
773 return "";
774 }
775
776 std::string message;
777
778 // Session Description.
779 AddLine(kSessionVersion, &message);
780 // Session Origin
781 // RFC 4566
782 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
783 // <unicast-address>
784 std::ostringstream os;
785 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
786 const std::string session_id = jdesc.session_id().empty() ?
787 kSessionOriginSessionId : jdesc.session_id();
788 const std::string session_version = jdesc.session_version().empty() ?
789 kSessionOriginSessionVersion : jdesc.session_version();
790 os << " " << session_id << " " << session_version << " "
791 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
792 << kSessionOriginAddress;
793 AddLine(os.str(), &message);
794 AddLine(kSessionName, &message);
795
796 // Time Description.
797 AddLine(kTimeDescription, &message);
798
799 // Group
800 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
801 std::string group_line = kAttrGroup;
802 const cricket::ContentGroup* group =
803 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
804 ASSERT(group != NULL);
805 const cricket::ContentNames& content_names = group->content_names();
806 for (cricket::ContentNames::const_iterator it = content_names.begin();
807 it != content_names.end(); ++it) {
808 group_line.append(" ");
809 group_line.append(*it);
810 }
811 AddLine(group_line, &message);
812 }
813
814 // MediaStream semantics
815 InitAttrLine(kAttributeMsidSemantics, &os);
816 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000817
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818 std::set<std::string> media_stream_labels;
819 const ContentInfo* audio_content = GetFirstAudioContent(desc);
820 if (audio_content)
821 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000822
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823 const ContentInfo* video_content = GetFirstVideoContent(desc);
824 if (video_content)
825 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000826
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827 for (std::set<std::string>::const_iterator it =
828 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
829 os << " " << *it;
830 }
831 AddLine(os.str(), &message);
832
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000833 // Preserve the order of the media contents.
834 int mline_index = -1;
835 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
836 it != desc->contents().end(); ++it) {
837 const MediaContentDescription* mdesc =
838 static_cast<const MediaContentDescription*>(it->description);
839 std::vector<Candidate> candidates;
840 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
841 BuildMediaDescription(&*it,
842 desc->GetTransportInfoByName(it->name),
843 mdesc->type(),
844 candidates,
845 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000847 return message;
848}
849
850// Serializes the passed in IceCandidateInterface to a SDP string.
851// candidate - The candidate to be serialized.
852std::string SdpSerializeCandidate(
853 const IceCandidateInterface& candidate) {
854 std::string message;
855 std::vector<cricket::Candidate> candidates;
856 candidates.push_back(candidate.candidate());
857 BuildCandidate(candidates, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000858 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
859 // just candidate:<candidate> not a=candidate:<blah>CRLF
860 ASSERT(message.find("a=") == 0);
861 message.erase(0, 2);
862 ASSERT(message.find(kLineBreak) == message.size() - 2);
863 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000864 return message;
865}
866
867bool SdpDeserialize(const std::string& message,
868 JsepSessionDescription* jdesc,
869 SdpParseError* error) {
870 std::string session_id;
871 std::string session_version;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000872 TransportDescription session_td(NS_JINGLE_ICE_UDP,
873 std::string(), std::string());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874 RtpHeaderExtensions session_extmaps;
875 cricket::SessionDescription* desc = new cricket::SessionDescription();
876 std::vector<JsepIceCandidate*> candidates;
877 size_t current_pos = 0;
878 bool supports_msid = false;
879
880 // Session Description
881 if (!ParseSessionDescription(message, &current_pos, &session_id,
882 &session_version, &supports_msid, &session_td,
883 &session_extmaps, desc, error)) {
884 delete desc;
885 return false;
886 }
887
888 // Media Description
889 if (!ParseMediaDescription(message, session_td, session_extmaps,
890 supports_msid, &current_pos, desc, &candidates,
891 error)) {
892 delete desc;
893 for (std::vector<JsepIceCandidate*>::const_iterator
894 it = candidates.begin(); it != candidates.end(); ++it) {
895 delete *it;
896 }
897 return false;
898 }
899
900 jdesc->Initialize(desc, session_id, session_version);
901
902 for (std::vector<JsepIceCandidate*>::const_iterator
903 it = candidates.begin(); it != candidates.end(); ++it) {
904 jdesc->AddCandidate(*it);
905 delete *it;
906 }
907 return true;
908}
909
910bool SdpDeserializeCandidate(const std::string& message,
911 JsepIceCandidate* jcandidate,
912 SdpParseError* error) {
913 ASSERT(jcandidate != NULL);
914 Candidate candidate;
915 if (!ParseCandidate(message, &candidate, error, true)) {
916 return false;
917 }
918 jcandidate->SetCandidate(candidate);
919 return true;
920}
921
922bool ParseCandidate(const std::string& message, Candidate* candidate,
923 SdpParseError* error, bool is_raw) {
924 ASSERT(candidate != NULL);
925
926 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000927 std::string first_line = message;
928 size_t pos = 0;
929 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000931 // Makes sure |message| contains only one line.
932 if (message.size() > first_line.size()) {
933 std::string left, right;
934 if (SplitByDelimiter(message, kNewLine, &left, &right) && !right.empty()) {
935 return ParseFailed(message, 0, "Expect one line only", error);
936 }
937 }
938
939 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
940 // candidate:<candidate> when trickled, but we still support
941 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
942 // from the SDP.
943 if (IsLineType(first_line, kLineTypeAttributes)) {
944 first_line = first_line.substr(kLinePrefixLength);
945 }
946
947 std::string attribute_candidate;
948 std::string candidate_value;
949
950 // |first_line| must be in the form of "candidate:<value>".
951 if (!SplitByDelimiter(first_line, kSdpDelimiterColon,
952 &attribute_candidate, &candidate_value) ||
953 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954 if (is_raw) {
955 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000956 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000957 << ":" << "<candidate-str>";
958 return ParseFailed(first_line, 0, description.str(), error);
959 } else {
960 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
961 kAttributeCandidate, error);
962 }
963 }
964
965 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000966 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
967
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000968 // RFC 5245
969 // a=candidate:<foundation> <component-id> <transport> <priority>
970 // <connection-address> <port> typ <candidate-types>
971 // [raddr <connection-address>] [rport <port>]
972 // *(SP extension-att-name SP extension-att-value)
973 const size_t expected_min_fields = 8;
974 if (fields.size() < expected_min_fields ||
975 (fields[6] != kAttributeCandidateTyp)) {
976 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
977 }
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000978 std::string foundation = fields[0];
979
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000980 int component_id = 0;
981 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
982 return false;
983 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984 const std::string transport = fields[2];
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000985 uint32 priority = 0;
986 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
987 return false;
988 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989 const std::string connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000990 int port = 0;
991 if (!GetValueFromString(first_line, fields[5], &port, error)) {
992 return false;
993 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994 SocketAddress address(connection_address, port);
995
996 cricket::ProtocolType protocol;
997 if (!StringToProto(transport.c_str(), &protocol)) {
998 return ParseFailed(first_line, "Unsupported transport type.", error);
999 }
1000
1001 std::string candidate_type;
1002 const std::string type = fields[7];
1003 if (type == kCandidateHost) {
1004 candidate_type = cricket::LOCAL_PORT_TYPE;
1005 } else if (type == kCandidateSrflx) {
1006 candidate_type = cricket::STUN_PORT_TYPE;
1007 } else if (type == kCandidateRelay) {
1008 candidate_type = cricket::RELAY_PORT_TYPE;
1009 } else {
1010 return ParseFailed(first_line, "Unsupported candidate type.", error);
1011 }
1012
1013 size_t current_position = expected_min_fields;
1014 SocketAddress related_address;
1015 // The 2 optional fields for related address
1016 // [raddr <connection-address>] [rport <port>]
1017 if (fields.size() >= (current_position + 2) &&
1018 fields[current_position] == kAttributeCandidateRaddr) {
1019 related_address.SetIP(fields[++current_position]);
1020 ++current_position;
1021 }
1022 if (fields.size() >= (current_position + 2) &&
1023 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001024 int port = 0;
1025 if (!GetValueFromString(
1026 first_line, fields[++current_position], &port, error)) {
1027 return false;
1028 }
1029 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030 ++current_position;
1031 }
1032
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001033 // If this is a TCP candidate, it has additional extension as defined in
1034 // RFC 6544.
1035 std::string tcptype;
1036 if (fields.size() >= (current_position + 2) &&
1037 fields[current_position] == kTcpCandidateType) {
1038 tcptype = fields[++current_position];
1039 ++current_position;
1040
1041 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1042 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1043 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1044 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1045 }
1046
1047 if (protocol != cricket::PROTO_TCP) {
1048 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1049 }
1050 }
1051
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052 // Extension
1053 // Empty string as the candidate username and password.
1054 // Will be updated later with the ice-ufrag and ice-pwd.
1055 // TODO: Remove the username/password extension, which is currently
1056 // kept for backwards compatibility.
1057 std::string username;
1058 std::string password;
1059 uint32 generation = 0;
1060 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1061 // RFC 5245
1062 // *(SP extension-att-name SP extension-att-value)
1063 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001064 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1065 return false;
1066 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001067 } else if (fields[i] == kAttributeCandidateUsername) {
1068 username = fields[++i];
1069 } else if (fields[i] == kAttributeCandidatePassword) {
1070 password = fields[++i];
1071 } else {
1072 // Skip the unknown extension.
1073 ++i;
1074 }
1075 }
1076
1077 // Empty string as the candidate id and network name.
1078 const std::string id;
1079 const std::string network_name;
1080 *candidate = Candidate(id, component_id, cricket::ProtoToString(protocol),
1081 address, priority, username, password, candidate_type, network_name,
1082 generation, foundation);
1083 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001084 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001085 return true;
1086}
1087
1088bool ParseIceOptions(const std::string& line,
1089 std::vector<std::string>* transport_options,
1090 SdpParseError* error) {
1091 std::string ice_options;
1092 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1093 return false;
1094 }
1095 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001096 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001097 for (size_t i = 0; i < fields.size(); ++i) {
1098 transport_options->push_back(fields[i]);
1099 }
1100 return true;
1101}
1102
1103bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1104 SdpParseError* error) {
1105 // RFC 5285
1106 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1107 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001108 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001109 kSdpDelimiterSpace, &fields);
1110 const size_t expected_min_fields = 2;
1111 if (fields.size() < expected_min_fields) {
1112 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1113 }
1114 std::string uri = fields[1];
1115
1116 std::string value_direction;
1117 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1118 return false;
1119 }
1120 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001121 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001122 int value = 0;
1123 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1124 return false;
1125 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001126
1127 *extmap = RtpHeaderExtension(uri, value);
1128 return true;
1129}
1130
1131void BuildMediaDescription(const ContentInfo* content_info,
1132 const TransportInfo* transport_info,
1133 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001134 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001135 std::string* message) {
1136 ASSERT(message != NULL);
1137 if (content_info == NULL || message == NULL) {
1138 return;
1139 }
1140 // TODO: Rethink if we should use sprintfn instead of stringstream.
1141 // According to the style guide, streams should only be used for logging.
1142 // http://google-styleguide.googlecode.com/svn/
1143 // trunk/cppguide.xml?showone=Streams#Streams
1144 std::ostringstream os;
1145 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001146 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001147 content_info->description);
1148 ASSERT(media_desc != NULL);
1149
1150 bool is_sctp = (media_desc->protocol() == cricket::kMediaProtocolDtlsSctp);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001151 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152
1153 // RFC 4566
1154 // m=<media> <port> <proto> <fmt>
1155 // fmt is a list of payload type numbers that MAY be used in the session.
1156 const char* type = NULL;
1157 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1158 type = kMediaTypeAudio;
1159 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1160 type = kMediaTypeVideo;
1161 else if (media_type == cricket::MEDIA_TYPE_DATA)
1162 type = kMediaTypeData;
1163 else
1164 ASSERT(false);
1165
1166 std::string fmt;
1167 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1168 const VideoContentDescription* video_desc =
1169 static_cast<const VideoContentDescription*>(media_desc);
1170 for (std::vector<cricket::VideoCodec>::const_iterator it =
1171 video_desc->codecs().begin();
1172 it != video_desc->codecs().end(); ++it) {
1173 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001174 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001175 }
1176 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1177 const AudioContentDescription* audio_desc =
1178 static_cast<const AudioContentDescription*>(media_desc);
1179 for (std::vector<cricket::AudioCodec>::const_iterator it =
1180 audio_desc->codecs().begin();
1181 it != audio_desc->codecs().end(); ++it) {
1182 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001183 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001184 }
1185 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001186 const DataContentDescription* data_desc =
1187 static_cast<const DataContentDescription*>(media_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188 if (is_sctp) {
1189 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001190
1191 for (std::vector<cricket::DataCodec>::const_iterator it =
1192 data_desc->codecs().begin();
1193 it != data_desc->codecs().end(); ++it) {
1194 if (it->id == cricket::kGoogleSctpDataCodecId &&
1195 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1196 break;
1197 }
1198 }
1199
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001200 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001201 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001202 for (std::vector<cricket::DataCodec>::const_iterator it =
1203 data_desc->codecs().begin();
1204 it != data_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 }
1209 }
1210 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1211 // to 0.
1212 if (fmt.empty()) {
1213 fmt = " 0";
1214 }
1215
1216 // The port number in the m line will be updated later when associate with
1217 // the candidates.
1218 // RFC 3264
1219 // To reject an offered stream, the port number in the corresponding stream in
1220 // the answer MUST be set to zero.
1221 const std::string port = content_info->rejected ?
1222 kMediaPortRejected : kDefaultPort;
1223
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001224 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001225 transport_info->description.identity_fingerprint.get() : NULL;
1226
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001227 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228 InitLine(kLineTypeMedia, type, &os);
1229 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001230 std::string mline = os.str();
1231 UpdateMediaDefaultDestination(candidates, mline, message);
1232
1233 // RFC 4566
1234 // b=AS:<bandwidth>
1235 // We should always use the default bandwidth for RTP-based data
1236 // channels. Don't allow SDP to set the bandwidth, because that
1237 // would give JS the opportunity to "break the Internet".
1238 // TODO(pthatcher): But we need to temporarily allow the SDP to control
1239 // this for backwards-compatibility. Once we don't need that any
1240 // more, remove this.
1241 bool support_dc_sdp_bandwidth_temporarily = true;
1242 if (media_desc->bandwidth() >= 1000 &&
1243 (media_type != cricket::MEDIA_TYPE_DATA ||
1244 support_dc_sdp_bandwidth_temporarily)) {
1245 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1246 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1247 AddLine(os.str(), message);
1248 }
1249
1250 // Add the a=rtcp line.
1251 bool is_rtp =
1252 media_desc->protocol().empty() ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001253 rtc::starts_with(media_desc->protocol().data(),
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001254 cricket::kMediaProtocolRtpPrefix);
1255 if (is_rtp) {
1256 std::string rtcp_line = GetRtcpLine(candidates);
1257 if (!rtcp_line.empty()) {
1258 AddLine(rtcp_line, message);
1259 }
1260 }
1261
1262 // Build the a=candidate lines.
1263 BuildCandidate(candidates, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001264
1265 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1266 if (transport_info) {
1267 // RFC 5245
1268 // ice-pwd-att = "ice-pwd" ":" password
1269 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1270 // ice-ufrag
1271 InitAttrLine(kAttributeIceUfrag, &os);
1272 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1273 AddLine(os.str(), message);
1274 // ice-pwd
1275 InitAttrLine(kAttributeIcePwd, &os);
1276 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1277 AddLine(os.str(), message);
1278
1279 // draft-petithuguenin-mmusic-ice-attributes-level-03
1280 BuildIceOptions(transport_info->description.transport_options, message);
1281
1282 // RFC 4572
1283 // fingerprint-attribute =
1284 // "fingerprint" ":" hash-func SP fingerprint
1285 if (fp) {
1286 // Insert the fingerprint attribute.
1287 InitAttrLine(kAttributeFingerprint, &os);
1288 os << kSdpDelimiterColon
1289 << fp->algorithm << kSdpDelimiterSpace
1290 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001292
1293 // Inserting setup attribute.
1294 if (transport_info->description.connection_role !=
1295 cricket::CONNECTIONROLE_NONE) {
1296 // Making sure we are not using "passive" mode.
1297 cricket::ConnectionRole role =
1298 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001299 std::string dtls_role_str;
1300 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001301 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001302 os << kSdpDelimiterColon << dtls_role_str;
1303 AddLine(os.str(), message);
1304 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305 }
1306 }
1307
1308 // RFC 3388
1309 // mid-attribute = "a=mid:" identification-tag
1310 // identification-tag = token
1311 // Use the content name as the mid identification-tag.
1312 InitAttrLine(kAttributeMid, &os);
1313 os << kSdpDelimiterColon << content_info->name;
1314 AddLine(os.str(), message);
1315
1316 if (is_sctp) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001317 BuildSctpContentAttributes(message, sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001318 } else {
1319 BuildRtpContentAttributes(media_desc, media_type, message);
1320 }
1321}
1322
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001323void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001324 // draft-ietf-mmusic-sctp-sdp-04
1325 // a=sctpmap:sctpmap-number protocol [streams]
1326 std::ostringstream os;
1327 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001328 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001329 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1330 << (cricket::kMaxSctpSid + 1);
1331 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332}
1333
1334void BuildRtpContentAttributes(
1335 const MediaContentDescription* media_desc,
1336 const MediaType media_type,
1337 std::string* message) {
1338 std::ostringstream os;
1339 // RFC 5285
1340 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1341 // The definitions MUST be either all session level or all media level. This
1342 // implementation uses all media level.
1343 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1344 InitAttrLine(kAttributeExtmap, &os);
1345 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1346 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1347 AddLine(os.str(), message);
1348 }
1349
1350 // RFC 3264
1351 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
1352
1353 cricket::MediaContentDirection direction = media_desc->direction();
1354 if (media_desc->streams().empty() && direction == cricket::MD_SENDRECV) {
1355 direction = cricket::MD_RECVONLY;
1356 }
1357
1358 switch (direction) {
1359 case cricket::MD_INACTIVE:
1360 InitAttrLine(kAttributeInactive, &os);
1361 break;
1362 case cricket::MD_SENDONLY:
1363 InitAttrLine(kAttributeSendOnly, &os);
1364 break;
1365 case cricket::MD_RECVONLY:
1366 InitAttrLine(kAttributeRecvOnly, &os);
1367 break;
1368 case cricket::MD_SENDRECV:
1369 default:
1370 InitAttrLine(kAttributeSendRecv, &os);
1371 break;
1372 }
1373 AddLine(os.str(), message);
1374
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375 // RFC 5761
1376 // a=rtcp-mux
1377 if (media_desc->rtcp_mux()) {
1378 InitAttrLine(kAttributeRtcpMux, &os);
1379 AddLine(os.str(), message);
1380 }
1381
1382 // RFC 4568
1383 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1384 for (std::vector<CryptoParams>::const_iterator it =
1385 media_desc->cryptos().begin();
1386 it != media_desc->cryptos().end(); ++it) {
1387 InitAttrLine(kAttributeCrypto, &os);
1388 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1389 << it->key_params;
1390 if (!it->session_params.empty()) {
1391 os << " " << it->session_params;
1392 }
1393 AddLine(os.str(), message);
1394 }
1395
1396 // RFC 4566
1397 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1398 // [/<encodingparameters>]
1399 BuildRtpMap(media_desc, media_type, message);
1400
1401 // Specify latency for buffered mode.
1402 // a=x-google-buffer-latency:<value>
1403 if (media_desc->buffered_mode_latency() != cricket::kBufferedModeDisabled) {
1404 std::ostringstream os;
1405 InitAttrLine(kAttributeXGoogleBufferLatency, &os);
1406 os << kSdpDelimiterColon << media_desc->buffered_mode_latency();
1407 AddLine(os.str(), message);
1408 }
1409
1410 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1411 track != media_desc->streams().end(); ++track) {
1412 // Require that the track belongs to a media stream,
1413 // ie the sync_label is set. This extra check is necessary since the
1414 // MediaContentDescription always contains a streamparam with an ssrc even
1415 // if no track or media stream have been created.
1416 if (track->sync_label.empty()) continue;
1417
1418 // Build the ssrc-group lines.
1419 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1420 // RFC 5576
1421 // a=ssrc-group:<semantics> <ssrc-id> ...
1422 if (track->ssrc_groups[i].ssrcs.empty()) {
1423 continue;
1424 }
1425 std::ostringstream os;
1426 InitAttrLine(kAttributeSsrcGroup, &os);
1427 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
1428 std::vector<uint32>::const_iterator ssrc =
1429 track->ssrc_groups[i].ssrcs.begin();
1430 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001431 os << kSdpDelimiterSpace << rtc::ToString<uint32>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432 }
1433 AddLine(os.str(), message);
1434 }
1435 // Build the ssrc lines for each ssrc.
1436 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
1437 uint32 ssrc = track->ssrcs[i];
1438 // RFC 5576
1439 // a=ssrc:<ssrc-id> cname:<value>
1440 AddSsrcLine(ssrc, kSsrcAttributeCname,
1441 track->cname, message);
1442
1443 // draft-alvestrand-mmusic-msid-00
1444 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1445 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1446 // is corresponding to the "name" attribute of StreamParams.
1447 std::string appdata = track->id;
1448 std::ostringstream os;
1449 InitAttrLine(kAttributeSsrc, &os);
1450 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1451 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1452 << kSdpDelimiterSpace << appdata;
1453 AddLine(os.str(), message);
1454
1455 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1456 // draft-alvestrand-rtcweb-mid-01
1457 // a=ssrc:<ssrc-id> mslabel:<value>
1458 // The label isn't yet defined.
1459 // a=ssrc:<ssrc-id> label:<value>
1460 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1461 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1462 }
1463 }
1464}
1465
1466void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1467 // fmtp header: a=fmtp:|payload_type| <parameters>
1468 // Add a=fmtp
1469 InitAttrLine(kAttributeFmtp, os);
1470 // Add :|payload_type|
1471 *os << kSdpDelimiterColon << payload_type;
1472}
1473
1474void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1475 // rtcp-fb header: a=rtcp-fb:|payload_type|
1476 // <parameters>/<ccm <ccm_parameters>>
1477 // Add a=rtcp-fb
1478 InitAttrLine(kAttributeRtcpFb, os);
1479 // Add :
1480 *os << kSdpDelimiterColon;
1481 if (payload_type == kWildcardPayloadType) {
1482 *os << "*";
1483 } else {
1484 *os << payload_type;
1485 }
1486}
1487
1488void WriteFmtpParameter(const std::string& parameter_name,
1489 const std::string& parameter_value,
1490 std::ostringstream* os) {
1491 // fmtp parameters: |parameter_name|=|parameter_value|
1492 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1493}
1494
1495void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1496 std::ostringstream* os) {
1497 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1498 fmtp != parameters.end(); ++fmtp) {
1499 // Each new parameter, except the first one starts with ";" and " ".
1500 if (fmtp != parameters.begin()) {
1501 *os << kSdpDelimiterSemicolon;
1502 }
1503 *os << kSdpDelimiterSpace;
1504 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1505 }
1506}
1507
1508bool IsFmtpParam(const std::string& name) {
1509 const char* kFmtpParams[] = {
1510 kCodecParamMinPTime, kCodecParamSPropStereo,
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +00001511 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamStartBitrate,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001512 kCodecParamMaxBitrate, kCodecParamMinBitrate, kCodecParamMaxQuantization,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001513 kCodecParamSctpProtocol, kCodecParamSctpStreams,
stefan@webrtc.org85d27942014-06-09 12:51:39 +00001514 kCodecParamMaxAverageBitrate, kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001515 };
1516 for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
1517 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1518 return true;
1519 }
1520 }
1521 return false;
1522}
1523
1524// Retreives fmtp parameters from |params|, which may contain other parameters
1525// as well, and puts them in |fmtp_parameters|.
1526void GetFmtpParams(const cricket::CodecParameterMap& params,
1527 cricket::CodecParameterMap* fmtp_parameters) {
1528 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1529 iter != params.end(); ++iter) {
1530 if (IsFmtpParam(iter->first)) {
1531 (*fmtp_parameters)[iter->first] = iter->second;
1532 }
1533 }
1534}
1535
1536template <class T>
1537void AddFmtpLine(const T& codec, std::string* message) {
1538 cricket::CodecParameterMap fmtp_parameters;
1539 GetFmtpParams(codec.params, &fmtp_parameters);
1540 if (fmtp_parameters.empty()) {
1541 // No need to add an fmtp if it will have no (optional) parameters.
1542 return;
1543 }
1544 std::ostringstream os;
1545 WriteFmtpHeader(codec.id, &os);
1546 WriteFmtpParameters(fmtp_parameters, &os);
1547 AddLine(os.str(), message);
1548 return;
1549}
1550
1551template <class T>
1552void AddRtcpFbLines(const T& codec, std::string* message) {
1553 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1554 codec.feedback_params.params().begin();
1555 iter != codec.feedback_params.params().end(); ++iter) {
1556 std::ostringstream os;
1557 WriteRtcpFbHeader(codec.id, &os);
1558 os << " " << iter->id();
1559 if (!iter->param().empty()) {
1560 os << " " << iter->param();
1561 }
1562 AddLine(os.str(), message);
1563 }
1564}
1565
1566bool GetMinValue(const std::vector<int>& values, int* value) {
1567 if (values.empty()) {
1568 return false;
1569 }
1570 std::vector<int>::const_iterator found =
1571 std::min_element(values.begin(), values.end());
1572 *value = *found;
1573 return true;
1574}
1575
1576bool GetParameter(const std::string& name,
1577 const cricket::CodecParameterMap& params, int* value) {
1578 std::map<std::string, std::string>::const_iterator found =
1579 params.find(name);
1580 if (found == params.end()) {
1581 return false;
1582 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001583 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001584 return false;
1585 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586 return true;
1587}
1588
1589void BuildRtpMap(const MediaContentDescription* media_desc,
1590 const MediaType media_type,
1591 std::string* message) {
1592 ASSERT(message != NULL);
1593 ASSERT(media_desc != NULL);
1594 std::ostringstream os;
1595 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1596 const VideoContentDescription* video_desc =
1597 static_cast<const VideoContentDescription*>(media_desc);
1598 for (std::vector<cricket::VideoCodec>::const_iterator it =
1599 video_desc->codecs().begin();
1600 it != video_desc->codecs().end(); ++it) {
1601 // RFC 4566
1602 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1603 // [/<encodingparameters>]
1604 if (it->id != kWildcardPayloadType) {
1605 InitAttrLine(kAttributeRtpmap, &os);
1606 os << kSdpDelimiterColon << it->id << " " << it->name
1607 << "/" << kDefaultVideoClockrate;
1608 AddLine(os.str(), message);
1609 }
1610 AddRtcpFbLines(*it, message);
1611 AddFmtpLine(*it, message);
1612 }
1613 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1614 const AudioContentDescription* audio_desc =
1615 static_cast<const AudioContentDescription*>(media_desc);
1616 std::vector<int> ptimes;
1617 std::vector<int> maxptimes;
1618 int max_minptime = 0;
1619 for (std::vector<cricket::AudioCodec>::const_iterator it =
1620 audio_desc->codecs().begin();
1621 it != audio_desc->codecs().end(); ++it) {
1622 ASSERT(!it->name.empty());
1623 // RFC 4566
1624 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1625 // [/<encodingparameters>]
1626 InitAttrLine(kAttributeRtpmap, &os);
1627 os << kSdpDelimiterColon << it->id << " ";
1628 os << it->name << "/" << it->clockrate;
1629 if (it->channels != 1) {
1630 os << "/" << it->channels;
1631 }
1632 AddLine(os.str(), message);
1633 AddRtcpFbLines(*it, message);
1634 AddFmtpLine(*it, message);
1635 int minptime = 0;
1636 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1637 max_minptime = std::max(minptime, max_minptime);
1638 }
1639 int ptime;
1640 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1641 ptimes.push_back(ptime);
1642 }
1643 int maxptime;
1644 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1645 maxptimes.push_back(maxptime);
1646 }
1647 }
1648 // Populate the maxptime attribute with the smallest maxptime of all codecs
1649 // under the same m-line.
1650 int min_maxptime = INT_MAX;
1651 if (GetMinValue(maxptimes, &min_maxptime)) {
1652 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1653 }
1654 ASSERT(min_maxptime > max_minptime);
1655 // Populate the ptime attribute with the smallest ptime or the largest
1656 // minptime, whichever is the largest, for all codecs under the same m-line.
1657 int ptime = INT_MAX;
1658 if (GetMinValue(ptimes, &ptime)) {
1659 ptime = std::min(ptime, min_maxptime);
1660 ptime = std::max(ptime, max_minptime);
1661 AddAttributeLine(kCodecParamPTime, ptime, message);
1662 }
1663 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1664 const DataContentDescription* data_desc =
1665 static_cast<const DataContentDescription*>(media_desc);
1666 for (std::vector<cricket::DataCodec>::const_iterator it =
1667 data_desc->codecs().begin();
1668 it != data_desc->codecs().end(); ++it) {
1669 // RFC 4566
1670 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1671 // [/<encodingparameters>]
1672 InitAttrLine(kAttributeRtpmap, &os);
1673 os << kSdpDelimiterColon << it->id << " "
1674 << it->name << "/" << it->clockrate;
1675 AddLine(os.str(), message);
1676 }
1677 }
1678}
1679
1680void BuildCandidate(const std::vector<Candidate>& candidates,
1681 std::string* message) {
1682 std::ostringstream os;
1683
1684 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1685 it != candidates.end(); ++it) {
1686 // RFC 5245
1687 // a=candidate:<foundation> <component-id> <transport> <priority>
1688 // <connection-address> <port> typ <candidate-types>
1689 // [raddr <connection-address>] [rport <port>]
1690 // *(SP extension-att-name SP extension-att-value)
1691 std::string type;
1692 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1693 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1694 type = kCandidateHost;
1695 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1696 type = kCandidateSrflx;
1697 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1698 type = kCandidateRelay;
1699 } else {
1700 ASSERT(false);
1701 }
1702
1703 InitAttrLine(kAttributeCandidate, &os);
1704 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001705 << it->foundation() << " "
1706 << it->component() << " "
1707 << it->protocol() << " "
1708 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001709 << it->address().ipaddr().ToString() << " "
1710 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001711 << kAttributeCandidateTyp << " "
1712 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001713
1714 // Related address
1715 if (!it->related_address().IsNil()) {
1716 os << kAttributeCandidateRaddr << " "
1717 << it->related_address().ipaddr().ToString() << " "
1718 << kAttributeCandidateRport << " "
1719 << it->related_address().PortAsString() << " ";
1720 }
1721
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001722 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
1723 // In case of WebRTC, candidate must be always "active" only. That means
1724 // it should have port number either 0 or 9.
1725 ASSERT(it->address().port() == 0 ||
1726 it->address().port() == cricket::DISCARD_PORT);
1727 ASSERT(it->tcptype() == cricket::TCPTYPE_ACTIVE_STR);
1728 // TODO(mallinath) : Uncomment below line once WebRTCSdp capable of
1729 // parsing RFC 6544.
1730 // os << kTcpCandidateType << " " << it->tcptype() << " ";
1731 }
1732
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001733 // Extensions
1734 os << kAttributeCandidateGeneration << " " << it->generation();
1735
1736 AddLine(os.str(), message);
1737 }
1738}
1739
1740void BuildIceOptions(const std::vector<std::string>& transport_options,
1741 std::string* message) {
1742 if (!transport_options.empty()) {
1743 std::ostringstream os;
1744 InitAttrLine(kAttributeIceOption, &os);
1745 os << kSdpDelimiterColon << transport_options[0];
1746 for (size_t i = 1; i < transport_options.size(); ++i) {
1747 os << kSdpDelimiterSpace << transport_options[i];
1748 }
1749 AddLine(os.str(), message);
1750 }
1751}
1752
1753bool ParseSessionDescription(const std::string& message, size_t* pos,
1754 std::string* session_id,
1755 std::string* session_version,
1756 bool* supports_msid,
1757 TransportDescription* session_td,
1758 RtpHeaderExtensions* session_extmaps,
1759 cricket::SessionDescription* desc,
1760 SdpParseError* error) {
1761 std::string line;
1762
1763 // RFC 4566
1764 // v= (protocol version)
1765 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1766 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1767 std::string(), error);
1768 }
1769 // RFC 4566
1770 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1771 // <unicast-address>
1772 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1773 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1774 std::string(), error);
1775 }
1776 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001777 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001778 kSdpDelimiterSpace, &fields);
1779 const size_t expected_fields = 6;
1780 if (fields.size() != expected_fields) {
1781 return ParseFailedExpectFieldNum(line, expected_fields, error);
1782 }
1783 *session_id = fields[1];
1784 *session_version = fields[2];
1785
1786 // RFC 4566
1787 // s= (session name)
1788 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1789 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1790 std::string(), error);
1791 }
1792
1793 // Optional lines
1794 // Those are the optional lines, so shouldn't return false if not present.
1795 // RFC 4566
1796 // i=* (session information)
1797 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1798
1799 // RFC 4566
1800 // u=* (URI of description)
1801 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1802
1803 // RFC 4566
1804 // e=* (email address)
1805 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1806
1807 // RFC 4566
1808 // p=* (phone number)
1809 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1810
1811 // RFC 4566
1812 // c=* (connection information -- not required if included in
1813 // all media)
1814 GetLineWithType(message, pos, &line, kLineTypeConnection);
1815
1816 // RFC 4566
1817 // b=* (zero or more bandwidth information lines)
1818 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1819 // By pass zero or more b lines.
1820 }
1821
1822 // RFC 4566
1823 // One or more time descriptions ("t=" and "r=" lines; see below)
1824 // t= (time the session is active)
1825 // r=* (zero or more repeat times)
1826 // Ensure there's at least one time description
1827 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1828 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1829 error);
1830 }
1831
1832 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1833 // By pass zero or more r lines.
1834 }
1835
1836 // Go through the rest of the time descriptions
1837 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1838 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1839 // By pass zero or more r lines.
1840 }
1841 }
1842
1843 // RFC 4566
1844 // z=* (time zone adjustments)
1845 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1846
1847 // RFC 4566
1848 // k=* (encryption key)
1849 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1850
1851 // RFC 4566
1852 // a=* (zero or more session attribute lines)
1853 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1854 if (HasAttribute(line, kAttributeGroup)) {
1855 if (!ParseGroupAttribute(line, desc, error)) {
1856 return false;
1857 }
1858 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1859 if (!GetValue(line, kAttributeIceUfrag,
1860 &(session_td->ice_ufrag), error)) {
1861 return false;
1862 }
1863 } else if (HasAttribute(line, kAttributeIcePwd)) {
1864 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1865 return false;
1866 }
1867 } else if (HasAttribute(line, kAttributeIceLite)) {
1868 session_td->ice_mode = cricket::ICEMODE_LITE;
1869 } else if (HasAttribute(line, kAttributeIceOption)) {
1870 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1871 return false;
1872 }
1873 } else if (HasAttribute(line, kAttributeFingerprint)) {
1874 if (session_td->identity_fingerprint.get()) {
1875 return ParseFailed(
1876 line,
1877 "Can't have multiple fingerprint attributes at the same level.",
1878 error);
1879 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001880 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001881 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1882 return false;
1883 }
1884 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001885 } else if (HasAttribute(line, kAttributeSetup)) {
1886 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1887 return false;
1888 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001889 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1890 std::string semantics;
1891 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1892 return false;
1893 }
1894 *supports_msid = CaseInsensitiveFind(semantics, kMediaStreamSemantic);
1895 } else if (HasAttribute(line, kAttributeExtmap)) {
1896 RtpHeaderExtension extmap;
1897 if (!ParseExtmap(line, &extmap, error)) {
1898 return false;
1899 }
1900 session_extmaps->push_back(extmap);
1901 }
1902 }
1903
1904 return true;
1905}
1906
1907bool ParseGroupAttribute(const std::string& line,
1908 cricket::SessionDescription* desc,
1909 SdpParseError* error) {
1910 ASSERT(desc != NULL);
1911
1912 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1913 // a=group:BUNDLE video voice
1914 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001915 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001916 kSdpDelimiterSpace, &fields);
1917 std::string semantics;
1918 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1919 return false;
1920 }
1921 cricket::ContentGroup group(semantics);
1922 for (size_t i = 1; i < fields.size(); ++i) {
1923 group.AddContentName(fields[i]);
1924 }
1925 desc->AddGroup(group);
1926 return true;
1927}
1928
1929static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001930 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001931 SdpParseError* error) {
1932 if (!IsLineType(line, kLineTypeAttributes) ||
1933 !HasAttribute(line, kAttributeFingerprint)) {
1934 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1935 kAttributeFingerprint, error);
1936 }
1937
1938 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001939 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001940 kSdpDelimiterSpace, &fields);
1941 const size_t expected_fields = 2;
1942 if (fields.size() != expected_fields) {
1943 return ParseFailedExpectFieldNum(line, expected_fields, error);
1944 }
1945
1946 // The first field here is "fingerprint:<hash>.
1947 std::string algorithm;
1948 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
1949 return false;
1950 }
1951
1952 // Downcase the algorithm. Note that we don't need to downcase the
1953 // fingerprint because hex_decode can handle upper-case.
1954 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
1955 ::tolower);
1956
1957 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001958 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001959 algorithm, fields[1]);
1960 if (!*fingerprint) {
1961 return ParseFailed(line,
1962 "Failed to create fingerprint from the digest.",
1963 error);
1964 }
1965
1966 return true;
1967}
1968
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001969static bool ParseDtlsSetup(const std::string& line,
1970 cricket::ConnectionRole* role,
1971 SdpParseError* error) {
1972 // setup-attr = "a=setup:" role
1973 // role = "active" / "passive" / "actpass" / "holdconn"
1974 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001975 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001976 const size_t expected_fields = 2;
1977 if (fields.size() != expected_fields) {
1978 return ParseFailedExpectFieldNum(line, expected_fields, error);
1979 }
1980 std::string role_str = fields[1];
1981 if (!cricket::StringToConnectionRole(role_str, role)) {
1982 return ParseFailed(line, "Invalid attribute value.", error);
1983 }
1984 return true;
1985}
1986
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987// RFC 3551
1988// PT encoding media type clock rate channels
1989// name (Hz)
1990// 0 PCMU A 8,000 1
1991// 1 reserved A
1992// 2 reserved A
1993// 3 GSM A 8,000 1
1994// 4 G723 A 8,000 1
1995// 5 DVI4 A 8,000 1
1996// 6 DVI4 A 16,000 1
1997// 7 LPC A 8,000 1
1998// 8 PCMA A 8,000 1
1999// 9 G722 A 8,000 1
2000// 10 L16 A 44,100 2
2001// 11 L16 A 44,100 1
2002// 12 QCELP A 8,000 1
2003// 13 CN A 8,000 1
2004// 14 MPA A 90,000 (see text)
2005// 15 G728 A 8,000 1
2006// 16 DVI4 A 11,025 1
2007// 17 DVI4 A 22,050 1
2008// 18 G729 A 8,000 1
2009struct StaticPayloadAudioCodec {
2010 const char* name;
2011 int clockrate;
2012 int channels;
2013};
2014static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2015 { "PCMU", 8000, 1 },
2016 { "reserved", 0, 0 },
2017 { "reserved", 0, 0 },
2018 { "GSM", 8000, 1 },
2019 { "G723", 8000, 1 },
2020 { "DVI4", 8000, 1 },
2021 { "DVI4", 16000, 1 },
2022 { "LPC", 8000, 1 },
2023 { "PCMA", 8000, 1 },
2024 { "G722", 8000, 1 },
2025 { "L16", 44100, 2 },
2026 { "L16", 44100, 1 },
2027 { "QCELP", 8000, 1 },
2028 { "CN", 8000, 1 },
2029 { "MPA", 90000, 1 },
2030 { "G728", 8000, 1 },
2031 { "DVI4", 11025, 1 },
2032 { "DVI4", 22050, 1 },
2033 { "G729", 8000, 1 },
2034};
2035
2036void MaybeCreateStaticPayloadAudioCodecs(
2037 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2038 if (!media_desc) {
2039 return;
2040 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002041 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002042 std::vector<int>::const_iterator it = fmts.begin();
2043 bool add_new_codec = false;
2044 for (; it != fmts.end(); ++it) {
2045 int payload_type = *it;
2046 if (!media_desc->HasCodec(payload_type) &&
2047 payload_type >= 0 &&
2048 payload_type < ARRAY_SIZE(kStaticPayloadAudioCodecs)) {
2049 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2050 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2051 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2052 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2053 clock_rate, 0, channels,
2054 preference));
2055 add_new_codec = true;
2056 }
2057 --preference;
2058 }
2059 if (add_new_codec) {
2060 media_desc->SortCodecs();
2061 }
2062}
2063
2064template <class C>
2065static C* ParseContentDescription(const std::string& message,
2066 const MediaType media_type,
2067 int mline_index,
2068 const std::string& protocol,
2069 const std::vector<int>& codec_preference,
2070 size_t* pos,
2071 std::string* content_name,
2072 TransportDescription* transport,
2073 std::vector<JsepIceCandidate*>* candidates,
2074 webrtc::SdpParseError* error) {
2075 C* media_desc = new C();
2076 switch (media_type) {
2077 case cricket::MEDIA_TYPE_AUDIO:
2078 *content_name = cricket::CN_AUDIO;
2079 break;
2080 case cricket::MEDIA_TYPE_VIDEO:
2081 *content_name = cricket::CN_VIDEO;
2082 break;
2083 case cricket::MEDIA_TYPE_DATA:
2084 *content_name = cricket::CN_DATA;
2085 break;
2086 default:
2087 ASSERT(false);
2088 break;
2089 }
2090 if (!ParseContent(message, media_type, mline_index, protocol,
2091 codec_preference, pos, content_name,
2092 media_desc, transport, candidates, error)) {
2093 delete media_desc;
2094 return NULL;
2095 }
2096 // Sort the codecs according to the m-line fmt list.
2097 media_desc->SortCodecs();
2098 return media_desc;
2099}
2100
2101bool ParseMediaDescription(const std::string& message,
2102 const TransportDescription& session_td,
2103 const RtpHeaderExtensions& session_extmaps,
2104 bool supports_msid,
2105 size_t* pos,
2106 cricket::SessionDescription* desc,
2107 std::vector<JsepIceCandidate*>* candidates,
2108 SdpParseError* error) {
2109 ASSERT(desc != NULL);
2110 std::string line;
2111 int mline_index = -1;
2112
2113 // Zero or more media descriptions
2114 // RFC 4566
2115 // m=<media> <port> <proto> <fmt>
2116 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2117 ++mline_index;
2118
2119 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002120 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002121 kSdpDelimiterSpace, &fields);
2122 const size_t expected_min_fields = 4;
2123 if (fields.size() < expected_min_fields) {
2124 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2125 }
2126 bool rejected = false;
2127 // RFC 3264
2128 // To reject an offered stream, the port number in the corresponding stream
2129 // in the answer MUST be set to zero.
2130 if (fields[1] == kMediaPortRejected) {
2131 rejected = true;
2132 }
2133
2134 std::string protocol = fields[2];
2135 bool is_sctp = (protocol == cricket::kMediaProtocolDtlsSctp);
2136
2137 // <fmt>
2138 std::vector<int> codec_preference;
2139 for (size_t j = 3 ; j < fields.size(); ++j) {
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002140 // TODO(wu): Remove when below bug is fixed.
2141 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
2142 if (fields[j] == "" && j == fields.size() - 1) {
2143 continue;
2144 }
2145
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002146 int pl = 0;
2147 if (!GetValueFromString(line, fields[j], &pl, error)) {
2148 return false;
2149 }
2150 codec_preference.push_back(pl);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002151 }
2152
2153 // Make a temporary TransportDescription based on |session_td|.
2154 // Some of this gets overwritten by ParseContent.
2155 TransportDescription transport(NS_JINGLE_ICE_UDP,
2156 session_td.transport_options,
2157 session_td.ice_ufrag,
2158 session_td.ice_pwd,
2159 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002160 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002161 session_td.identity_fingerprint.get(),
2162 Candidates());
2163
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002164 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002165 std::string content_name;
2166 if (HasAttribute(line, kMediaTypeVideo)) {
2167 content.reset(ParseContentDescription<VideoContentDescription>(
2168 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2169 codec_preference, pos, &content_name,
2170 &transport, candidates, error));
2171 } else if (HasAttribute(line, kMediaTypeAudio)) {
2172 content.reset(ParseContentDescription<AudioContentDescription>(
2173 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2174 codec_preference, pos, &content_name,
2175 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002176 } else if (HasAttribute(line, kMediaTypeData)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002177 DataContentDescription* desc =
2178 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002179 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2180 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002181 &transport, candidates, error);
2182
henrike@webrtc.org571df2d2014-02-19 23:04:26 +00002183 if (desc && protocol == cricket::kMediaProtocolDtlsSctp) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002184 // Add the SCTP Port number as a pseudo-codec "port" parameter
2185 cricket::DataCodec codec_port(
2186 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
2187 0);
2188 codec_port.SetParam(cricket::kCodecParamPort, fields[3]);
2189 LOG(INFO) << "ParseMediaDescription: Got SCTP Port Number "
2190 << fields[3];
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00002191 ASSERT(!desc->HasCodec(cricket::kGoogleSctpDataCodecId));
wu@webrtc.org78187522013-10-07 23:32:02 +00002192 desc->AddCodec(codec_port);
2193 }
2194
2195 content.reset(desc);
2196
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002197 // We should always use the default bandwidth for RTP-based data
2198 // channels. Don't allow SDP to set the bandwidth, because that
2199 // would give JS the opportunity to "break the Internet".
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002200 // TODO(pthatcher): But we need to temporarily allow the SDP to control
2201 // this for backwards-compatibility. Once we don't need that any
2202 // more, remove this.
2203 bool support_dc_sdp_bandwidth_temporarily = true;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00002204 if (content.get() && !support_dc_sdp_bandwidth_temporarily) {
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002205 content->set_bandwidth(cricket::kAutoBandwidth);
2206 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002207 } else {
2208 LOG(LS_WARNING) << "Unsupported media type: " << line;
2209 continue;
2210 }
2211 if (!content.get()) {
2212 // ParseContentDescription returns NULL if failed.
2213 return false;
2214 }
2215
2216 if (!is_sctp) {
2217 // Make sure to set the media direction correctly. If the direction is not
2218 // MD_RECVONLY or Inactive and no streams are parsed,
2219 // a default MediaStream will be created to prepare for receiving media.
2220 if (supports_msid && content->streams().empty() &&
2221 content->direction() == cricket::MD_SENDRECV) {
2222 content->set_direction(cricket::MD_RECVONLY);
2223 }
2224
2225 // Set the extmap.
2226 if (!session_extmaps.empty() &&
2227 !content->rtp_header_extensions().empty()) {
2228 return ParseFailed("",
2229 "The a=extmap MUST be either all session level or "
2230 "all media level.",
2231 error);
2232 }
2233 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2234 content->AddRtpHeaderExtension(session_extmaps[i]);
2235 }
2236 }
2237 content->set_protocol(protocol);
2238 desc->AddContent(content_name,
2239 is_sctp ? cricket::NS_JINGLE_DRAFT_SCTP :
2240 cricket::NS_JINGLE_RTP,
2241 rejected,
2242 content.release());
2243 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2244 TransportInfo transport_info(content_name, transport);
2245
2246 if (!desc->AddTransportInfo(transport_info)) {
2247 std::ostringstream description;
2248 description << "Failed to AddTransportInfo with content name: "
2249 << content_name;
2250 return ParseFailed("", description.str(), error);
2251 }
2252 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002253
2254 size_t end_of_message = message.size();
2255 if (mline_index == -1 && *pos != end_of_message) {
2256 ParseFailed(message, *pos, "Expects m line.", error);
2257 return false;
2258 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 return true;
2260}
2261
2262bool VerifyCodec(const cricket::Codec& codec) {
2263 // Codec has not been populated correctly unless the name has been set. This
2264 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2265 // have a corresponding "rtpmap" line.
2266 cricket::Codec default_codec;
2267 return default_codec.name != codec.name;
2268}
2269
2270bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2271 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2272 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2273 iter != codecs.end(); ++iter) {
2274 if (!VerifyCodec(*iter)) {
2275 return false;
2276 }
2277 }
2278 return true;
2279}
2280
2281bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2282 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2283 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2284 iter != codecs.end(); ++iter) {
2285 if (!VerifyCodec(*iter)) {
2286 return false;
2287 }
2288 }
2289 return true;
2290}
2291
2292void AddParameters(const cricket::CodecParameterMap& parameters,
2293 cricket::Codec* codec) {
2294 for (cricket::CodecParameterMap::const_iterator iter =
2295 parameters.begin(); iter != parameters.end(); ++iter) {
2296 codec->SetParam(iter->first, iter->second);
2297 }
2298}
2299
2300void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2301 cricket::Codec* codec) {
2302 codec->AddFeedbackParam(feedback_param);
2303}
2304
2305void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2306 cricket::Codec* codec) {
2307 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2308 feedback_params.params().begin();
2309 iter != feedback_params.params().end(); ++iter) {
2310 codec->AddFeedbackParam(*iter);
2311 }
2312}
2313
2314// Gets the current codec setting associated with |payload_type|. If there
2315// is no AudioCodec associated with that payload type it returns an empty codec
2316// with that payload type.
2317template <class T>
2318T GetCodec(const std::vector<T>& codecs, int payload_type) {
2319 for (typename std::vector<T>::const_iterator codec = codecs.begin();
2320 codec != codecs.end(); ++codec) {
2321 if (codec->id == payload_type) {
2322 return *codec;
2323 }
2324 }
2325 T ret_val = T();
2326 ret_val.id = payload_type;
2327 return ret_val;
2328}
2329
2330// Updates or creates a new codec entry in the audio description.
2331template <class T, class U>
2332void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2333 T* desc = static_cast<T*>(content_desc);
2334 std::vector<U> codecs = desc->codecs();
2335 bool found = false;
2336
2337 typename std::vector<U>::iterator iter;
2338 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2339 if (iter->id == codec.id) {
2340 *iter = codec;
2341 found = true;
2342 break;
2343 }
2344 }
2345 if (!found) {
2346 desc->AddCodec(codec);
2347 return;
2348 }
2349 desc->set_codecs(codecs);
2350}
2351
2352// Adds or updates existing codec corresponding to |payload_type| according
2353// to |parameters|.
2354template <class T, class U>
2355void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2356 const cricket::CodecParameterMap& parameters) {
2357 // Codec might already have been populated (from rtpmap).
2358 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2359 AddParameters(parameters, &new_codec);
2360 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2361}
2362
2363// Adds or updates existing codec corresponding to |payload_type| according
2364// to |feedback_param|.
2365template <class T, class U>
2366void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2367 const cricket::FeedbackParam& feedback_param) {
2368 // Codec might already have been populated (from rtpmap).
2369 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2370 AddFeedbackParameter(feedback_param, &new_codec);
2371 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2372}
2373
2374bool PopWildcardCodec(std::vector<cricket::VideoCodec>* codecs,
2375 cricket::VideoCodec* wildcard_codec) {
2376 for (std::vector<cricket::VideoCodec>::iterator iter = codecs->begin();
2377 iter != codecs->end(); ++iter) {
2378 if (iter->id == kWildcardPayloadType) {
2379 *wildcard_codec = *iter;
2380 codecs->erase(iter);
2381 return true;
2382 }
2383 }
2384 return false;
2385}
2386
2387void UpdateFromWildcardVideoCodecs(VideoContentDescription* video_desc) {
2388 std::vector<cricket::VideoCodec> codecs = video_desc->codecs();
2389 cricket::VideoCodec wildcard_codec;
2390 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2391 return;
2392 }
2393 for (std::vector<cricket::VideoCodec>::iterator iter = codecs.begin();
2394 iter != codecs.end(); ++iter) {
2395 cricket::VideoCodec& codec = *iter;
2396 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2397 }
2398 video_desc->set_codecs(codecs);
2399}
2400
2401void AddAudioAttribute(const std::string& name, const std::string& value,
2402 AudioContentDescription* audio_desc) {
2403 if (value.empty()) {
2404 return;
2405 }
2406 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2407 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2408 iter != codecs.end(); ++iter) {
2409 iter->params[name] = value;
2410 }
2411 audio_desc->set_codecs(codecs);
2412}
2413
2414bool ParseContent(const std::string& message,
2415 const MediaType media_type,
2416 int mline_index,
2417 const std::string& protocol,
2418 const std::vector<int>& codec_preference,
2419 size_t* pos,
2420 std::string* content_name,
2421 MediaContentDescription* media_desc,
2422 TransportDescription* transport,
2423 std::vector<JsepIceCandidate*>* candidates,
2424 SdpParseError* error) {
2425 ASSERT(media_desc != NULL);
2426 ASSERT(content_name != NULL);
2427 ASSERT(transport != NULL);
2428
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002429 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2430 MaybeCreateStaticPayloadAudioCodecs(
2431 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2432 }
2433
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002434 // The media level "ice-ufrag" and "ice-pwd".
2435 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2436 Candidates candidates_orig;
2437 std::string line;
2438 std::string mline_id;
2439 // Tracks created out of the ssrc attributes.
2440 StreamParamsVec tracks;
2441 SsrcInfoVec ssrc_infos;
2442 SsrcGroupVec ssrc_groups;
2443 std::string maxptime_as_string;
2444 std::string ptime_as_string;
2445
2446 bool is_rtp =
2447 protocol.empty() ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002448 rtc::starts_with(protocol.data(),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002449 cricket::kMediaProtocolRtpPrefix);
2450
2451 // Loop until the next m line
2452 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2453 if (!GetLine(message, pos, &line)) {
2454 if (*pos >= message.size()) {
2455 break; // Done parsing
2456 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002457 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002458 }
2459 }
2460
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002461 // RFC 4566
2462 // b=* (zero or more bandwidth information lines)
2463 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2464 std::string bandwidth;
2465 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2466 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2467 return false;
2468 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002469 int b = 0;
2470 if (!GetValueFromString(line, bandwidth, &b, error)) {
2471 return false;
2472 }
2473 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002474 }
2475 }
2476 continue;
2477 }
2478
2479 if (!IsLineType(line, kLineTypeAttributes)) {
2480 // TODO: Handle other lines if needed.
2481 LOG(LS_INFO) << "Ignored line: " << line;
2482 continue;
2483 }
2484
2485 // Handle attributes common to SCTP and RTP.
2486 if (HasAttribute(line, kAttributeMid)) {
2487 // RFC 3388
2488 // mid-attribute = "a=mid:" identification-tag
2489 // identification-tag = token
2490 // Use the mid identification-tag as the content name.
2491 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2492 return false;
2493 }
2494 *content_name = mline_id;
2495 } else if (HasAttribute(line, kAttributeCandidate)) {
2496 Candidate candidate;
2497 if (!ParseCandidate(line, &candidate, error, false)) {
2498 return false;
2499 }
2500 candidates_orig.push_back(candidate);
2501 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2502 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2503 return false;
2504 }
2505 } else if (HasAttribute(line, kAttributeIcePwd)) {
2506 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2507 return false;
2508 }
2509 } else if (HasAttribute(line, kAttributeIceOption)) {
2510 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2511 return false;
2512 }
2513 } else if (HasAttribute(line, kAttributeFmtp)) {
2514 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2515 return false;
2516 }
2517 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002518 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002519
2520 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2521 return false;
2522 }
2523 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002524 } else if (HasAttribute(line, kAttributeSetup)) {
2525 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2526 return false;
2527 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002528 } else if (is_rtp) {
2529 //
2530 // RTP specific attrubtes
2531 //
2532 if (HasAttribute(line, kAttributeRtcpMux)) {
2533 media_desc->set_rtcp_mux(true);
2534 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2535 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2536 return false;
2537 }
2538 } else if (HasAttribute(line, kAttributeSsrc)) {
2539 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2540 return false;
2541 }
2542 } else if (HasAttribute(line, kAttributeCrypto)) {
2543 if (!ParseCryptoAttribute(line, media_desc, error)) {
2544 return false;
2545 }
2546 } else if (HasAttribute(line, kAttributeRtpmap)) {
2547 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2548 media_desc, error)) {
2549 return false;
2550 }
2551 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2552 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2553 return false;
2554 }
2555 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2556 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2557 return false;
2558 }
2559 } else if (HasAttribute(line, kCodecParamPTime)) {
2560 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2561 return false;
2562 }
2563 } else if (HasAttribute(line, kAttributeSendOnly)) {
2564 media_desc->set_direction(cricket::MD_SENDONLY);
2565 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2566 media_desc->set_direction(cricket::MD_RECVONLY);
2567 } else if (HasAttribute(line, kAttributeInactive)) {
2568 media_desc->set_direction(cricket::MD_INACTIVE);
2569 } else if (HasAttribute(line, kAttributeSendRecv)) {
2570 media_desc->set_direction(cricket::MD_SENDRECV);
2571 } else if (HasAttribute(line, kAttributeExtmap)) {
2572 RtpHeaderExtension extmap;
2573 if (!ParseExtmap(line, &extmap, error)) {
2574 return false;
2575 }
2576 media_desc->AddRtpHeaderExtension(extmap);
2577 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2578 // Experimental attribute. Conference mode activates more aggressive
2579 // AEC and NS settings.
2580 // TODO: expose API to set these directly.
2581 std::string flag_value;
2582 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2583 return false;
2584 }
2585 if (flag_value.compare(kValueConference) == 0)
2586 media_desc->set_conference_mode(true);
2587 } else if (HasAttribute(line, kAttributeXGoogleBufferLatency)) {
2588 // Experimental attribute.
2589 // TODO: expose API to set this directly.
2590 std::string flag_value;
2591 if (!GetValue(line, kAttributeXGoogleBufferLatency, &flag_value,
2592 error)) {
2593 return false;
2594 }
2595 int buffer_latency = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002596 if (!GetValueFromString(line, flag_value, &buffer_latency, error)) {
2597 return false;
2598 }
2599 if (buffer_latency < 0) {
2600 return ParseFailed(line, "Buffer latency less than 0.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002601 }
2602 media_desc->set_buffered_mode_latency(buffer_latency);
2603 }
2604 } else {
2605 // Only parse lines that we are interested of.
2606 LOG(LS_INFO) << "Ignored line: " << line;
2607 continue;
2608 }
2609 }
2610
2611 // Create tracks from the |ssrc_infos|.
2612 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2613
2614 // Add the ssrc group to the track.
2615 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2616 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2617 if (ssrc_group->ssrcs.empty()) {
2618 continue;
2619 }
2620 uint32 ssrc = ssrc_group->ssrcs.front();
2621 for (StreamParamsVec::iterator track = tracks.begin();
2622 track != tracks.end(); ++track) {
2623 if (track->has_ssrc(ssrc)) {
2624 track->ssrc_groups.push_back(*ssrc_group);
2625 }
2626 }
2627 }
2628
2629 // Add the new tracks to the |media_desc|.
2630 for (StreamParamsVec::iterator track = tracks.begin();
2631 track != tracks.end(); ++track) {
2632 media_desc->AddStream(*track);
2633 }
2634
2635 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2636 AudioContentDescription* audio_desc =
2637 static_cast<AudioContentDescription*>(media_desc);
2638 // Verify audio codec ensures that no audio codec has been populated with
2639 // only fmtp.
2640 if (!VerifyAudioCodecs(audio_desc)) {
2641 return ParseFailed("Failed to parse audio codecs correctly.", error);
2642 }
2643 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2644 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2645 }
2646
2647 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2648 VideoContentDescription* video_desc =
2649 static_cast<VideoContentDescription*>(media_desc);
2650 UpdateFromWildcardVideoCodecs(video_desc);
2651 // Verify video codec ensures that no video codec has been populated with
2652 // only rtcp-fb.
2653 if (!VerifyVideoCodecs(video_desc)) {
2654 return ParseFailed("Failed to parse video codecs correctly.", error);
2655 }
2656 }
2657
2658 // RFC 5245
2659 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2660 for (Candidates::iterator it = candidates_orig.begin();
2661 it != candidates_orig.end(); ++it) {
2662 ASSERT((*it).username().empty());
2663 (*it).set_username(transport->ice_ufrag);
2664 ASSERT((*it).password().empty());
2665 (*it).set_password(transport->ice_pwd);
2666 candidates->push_back(
2667 new JsepIceCandidate(mline_id, mline_index, *it));
2668 }
2669 return true;
2670}
2671
2672bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2673 SdpParseError* error) {
2674 ASSERT(ssrc_infos != NULL);
2675 // RFC 5576
2676 // a=ssrc:<ssrc-id> <attribute>
2677 // a=ssrc:<ssrc-id> <attribute>:<value>
2678 std::string field1, field2;
2679 if (!SplitByDelimiter(line.substr(kLinePrefixLength),
2680 kSdpDelimiterSpace,
2681 &field1,
2682 &field2)) {
2683 const size_t expected_fields = 2;
2684 return ParseFailedExpectFieldNum(line, expected_fields, error);
2685 }
2686
2687 // ssrc:<ssrc-id>
2688 std::string ssrc_id_s;
2689 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2690 return false;
2691 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002692 uint32 ssrc_id = 0;
2693 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2694 return false;
2695 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002696
2697 std::string attribute;
2698 std::string value;
2699 if (!SplitByDelimiter(field2, kSdpDelimiterColon,
2700 &attribute, &value)) {
2701 std::ostringstream description;
2702 description << "Failed to get the ssrc attribute value from " << field2
2703 << ". Expected format <attribute>:<value>.";
2704 return ParseFailed(line, description.str(), error);
2705 }
2706
2707 // Check if there's already an item for this |ssrc_id|. Create a new one if
2708 // there isn't.
2709 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2710 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2711 if (ssrc_info->ssrc_id == ssrc_id) {
2712 break;
2713 }
2714 }
2715 if (ssrc_info == ssrc_infos->end()) {
2716 SsrcInfo info;
2717 info.ssrc_id = ssrc_id;
2718 ssrc_infos->push_back(info);
2719 ssrc_info = ssrc_infos->end() - 1;
2720 }
2721
2722 // Store the info to the |ssrc_info|.
2723 if (attribute == kSsrcAttributeCname) {
2724 // RFC 5576
2725 // cname:<value>
2726 ssrc_info->cname = value;
2727 } else if (attribute == kSsrcAttributeMsid) {
2728 // draft-alvestrand-mmusic-msid-00
2729 // "msid:" identifier [ " " appdata ]
2730 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002731 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002732 if (fields.size() < 1 || fields.size() > 2) {
2733 return ParseFailed(line,
2734 "Expected format \"msid:<identifier>[ <appdata>]\".",
2735 error);
2736 }
2737 ssrc_info->msid_identifier = fields[0];
2738 if (fields.size() == 2) {
2739 ssrc_info->msid_appdata = fields[1];
2740 }
2741 } else if (attribute == kSsrcAttributeMslabel) {
2742 // draft-alvestrand-rtcweb-mid-01
2743 // mslabel:<value>
2744 ssrc_info->mslabel = value;
2745 } else if (attribute == kSSrcAttributeLabel) {
2746 // The label isn't defined.
2747 // label:<value>
2748 ssrc_info->label = value;
2749 }
2750 return true;
2751}
2752
2753bool ParseSsrcGroupAttribute(const std::string& line,
2754 SsrcGroupVec* ssrc_groups,
2755 SdpParseError* error) {
2756 ASSERT(ssrc_groups != NULL);
2757 // RFC 5576
2758 // a=ssrc-group:<semantics> <ssrc-id> ...
2759 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002760 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002761 kSdpDelimiterSpace, &fields);
2762 const size_t expected_min_fields = 2;
2763 if (fields.size() < expected_min_fields) {
2764 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2765 }
2766 std::string semantics;
2767 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2768 return false;
2769 }
2770 std::vector<uint32> ssrcs;
2771 for (size_t i = 1; i < fields.size(); ++i) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002772 uint32 ssrc = 0;
2773 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2774 return false;
2775 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002776 ssrcs.push_back(ssrc);
2777 }
2778 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2779 return true;
2780}
2781
2782bool ParseCryptoAttribute(const std::string& line,
2783 MediaContentDescription* media_desc,
2784 SdpParseError* error) {
2785 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002786 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002787 kSdpDelimiterSpace, &fields);
2788 // RFC 4568
2789 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2790 const size_t expected_min_fields = 3;
2791 if (fields.size() < expected_min_fields) {
2792 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2793 }
2794 std::string tag_value;
2795 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2796 return false;
2797 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002798 int tag = 0;
2799 if (!GetValueFromString(line, tag_value, &tag, error)) {
2800 return false;
2801 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002802 const std::string crypto_suite = fields[1];
2803 const std::string key_params = fields[2];
2804 std::string session_params;
2805 if (fields.size() > 3) {
2806 session_params = fields[3];
2807 }
2808 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2809 session_params));
2810 return true;
2811}
2812
2813// Updates or creates a new codec entry in the audio description with according
2814// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2815void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2816 int bitrate, int channels, int preference,
2817 AudioContentDescription* audio_desc) {
2818 // Codec may already be populated with (only) optional parameters
2819 // (from an fmtp).
2820 cricket::AudioCodec codec = GetCodec(audio_desc->codecs(), payload_type);
2821 codec.name = name;
2822 codec.clockrate = clockrate;
2823 codec.bitrate = bitrate;
2824 codec.channels = channels;
2825 codec.preference = preference;
2826 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2827 codec);
2828}
2829
2830// Updates or creates a new codec entry in the video description according to
2831// |name|, |width|, |height|, |framerate| and |preference|.
2832void UpdateCodec(int payload_type, const std::string& name, int width,
2833 int height, int framerate, int preference,
2834 VideoContentDescription* video_desc) {
2835 // Codec may already be populated with (only) optional parameters
2836 // (from an fmtp).
2837 cricket::VideoCodec codec = GetCodec(video_desc->codecs(), payload_type);
2838 codec.name = name;
2839 codec.width = width;
2840 codec.height = height;
2841 codec.framerate = framerate;
2842 codec.preference = preference;
2843 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2844 codec);
2845}
2846
2847bool ParseRtpmapAttribute(const std::string& line,
2848 const MediaType media_type,
2849 const std::vector<int>& codec_preference,
2850 MediaContentDescription* media_desc,
2851 SdpParseError* error) {
2852 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002853 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002854 kSdpDelimiterSpace, &fields);
2855 // RFC 4566
2856 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2857 const size_t expected_min_fields = 2;
2858 if (fields.size() < expected_min_fields) {
2859 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2860 }
2861 std::string payload_type_value;
2862 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2863 return false;
2864 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002865 int payload_type = 0;
2866 if (!GetValueFromString(line, payload_type_value, &payload_type, error)) {
2867 return false;
2868 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002869
2870 // Set the preference order depending on the order of the pl type in the
2871 // <fmt> of the m-line.
2872 const int preference = codec_preference.end() -
2873 std::find(codec_preference.begin(), codec_preference.end(),
2874 payload_type);
2875 if (preference == 0) {
2876 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2877 << "<fmt> of the m-line: " << line;
2878 return true;
2879 }
2880 const std::string encoder = fields[1];
2881 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002882 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002883 // <encoding name>/<clock rate>[/<encodingparameters>]
2884 // 2 mandatory fields
2885 if (codec_params.size() < 2 || codec_params.size() > 3) {
2886 return ParseFailed(line,
2887 "Expected format \"<encoding name>/<clock rate>"
2888 "[/<encodingparameters>]\".",
2889 error);
2890 }
2891 const std::string encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002892 int clock_rate = 0;
2893 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2894 return false;
2895 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002896 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2897 VideoContentDescription* video_desc =
2898 static_cast<VideoContentDescription*>(media_desc);
2899 // TODO: We will send resolution in SDP. For now use
2900 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2901 UpdateCodec(payload_type, encoding_name,
2902 JsepSessionDescription::kMaxVideoCodecWidth,
2903 JsepSessionDescription::kMaxVideoCodecHeight,
2904 JsepSessionDescription::kDefaultVideoCodecFramerate,
2905 preference, video_desc);
2906 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2907 // RFC 4566
2908 // For audio streams, <encoding parameters> indicates the number
2909 // of audio channels. This parameter is OPTIONAL and may be
2910 // omitted if the number of channels is one, provided that no
2911 // additional parameters are needed.
2912 int channels = 1;
2913 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002914 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2915 return false;
2916 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002917 }
2918 int bitrate = 0;
2919 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2920 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2921 // The bandwidth adaptation doesn't always work well, so this code
2922 // sets a fixed target bitrate instead.
2923 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2924 if (clock_rate <= 16000) {
2925 bitrate = kIsacWbDefaultRate;
2926 } else {
2927 bitrate = kIsacSwbDefaultRate;
2928 }
2929 }
2930 AudioContentDescription* audio_desc =
2931 static_cast<AudioContentDescription*>(media_desc);
2932 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2933 preference, audio_desc);
2934 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2935 DataContentDescription* data_desc =
2936 static_cast<DataContentDescription*>(media_desc);
2937 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2938 preference));
2939 }
2940 return true;
2941}
2942
2943void PruneRight(const char delimiter, std::string* message) {
2944 size_t trailing = message->find(delimiter);
2945 if (trailing != std::string::npos) {
2946 *message = message->substr(0, trailing);
2947 }
2948}
2949
2950bool ParseFmtpParam(const std::string& line, std::string* parameter,
2951 std::string* value, SdpParseError* error) {
2952 if (!SplitByDelimiter(line, kSdpDelimiterEqual, parameter, value)) {
2953 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2954 return false;
2955 }
2956 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
2957 // When parsing the values the trailing ";" gets picked up. Remove them.
2958 PruneRight(kSdpDelimiterSemicolon, value);
2959 return true;
2960}
2961
2962bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
2963 MediaContentDescription* media_desc,
2964 SdpParseError* error) {
2965 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2966 media_type != cricket::MEDIA_TYPE_VIDEO) {
2967 return true;
2968 }
2969 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002970 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002971 kSdpDelimiterSpace, &fields);
2972
2973 // RFC 5576
2974 // a=fmtp:<format> <format specific parameters>
2975 // At least two fields, whereas the second one is any of the optional
2976 // parameters.
2977 if (fields.size() < 2) {
2978 ParseFailedExpectMinFieldNum(line, 2, error);
2979 return false;
2980 }
2981
2982 std::string payload_type;
2983 if (!GetValue(fields[0], kAttributeFmtp, &payload_type, error)) {
2984 return false;
2985 }
2986
2987 cricket::CodecParameterMap codec_params;
2988 for (std::vector<std::string>::const_iterator iter = fields.begin() + 1;
2989 iter != fields.end(); ++iter) {
2990 std::string name;
2991 std::string value;
2992 if (iter->find(kSdpDelimiterEqual) == std::string::npos) {
2993 // Only fmtps with equals are currently supported. Other fmtp types
2994 // should be ignored. Unknown fmtps do not constitute an error.
2995 continue;
2996 }
2997 if (!ParseFmtpParam(*iter, &name, &value, error)) {
2998 return false;
2999 }
3000 codec_params[name] = value;
3001 }
3002
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003003 int int_payload_type = 0;
3004 if (!GetValueFromString(line, payload_type, &int_payload_type, error)) {
3005 return false;
3006 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003007 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3008 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3009 media_desc, int_payload_type, codec_params);
3010 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3011 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3012 media_desc, int_payload_type, codec_params);
3013 }
3014 return true;
3015}
3016
3017bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3018 MediaContentDescription* media_desc,
3019 SdpParseError* error) {
3020 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3021 media_type != cricket::MEDIA_TYPE_VIDEO) {
3022 return true;
3023 }
3024 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003025 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003026 if (rtcp_fb_fields.size() < 2) {
3027 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3028 }
3029 std::string payload_type_string;
3030 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3031 error)) {
3032 return false;
3033 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003034 int payload_type = kWildcardPayloadType;
3035 if (payload_type_string != "*") {
3036 if (!GetValueFromString(line, payload_type_string, &payload_type, error)) {
3037 return false;
3038 }
3039 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003040 std::string id = rtcp_fb_fields[1];
3041 std::string param = "";
3042 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3043 iter != rtcp_fb_fields.end(); ++iter) {
3044 param.append(*iter);
3045 }
3046 const cricket::FeedbackParam feedback_param(id, param);
3047
3048 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3049 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(media_desc,
3050 payload_type,
3051 feedback_param);
3052 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3053 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(media_desc,
3054 payload_type,
3055 feedback_param);
3056 }
3057 return true;
3058}
3059
3060} // namespace webrtc