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