blob: ae171178e4c6c487f81d52bb2dadf3141830deb6 [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;
1244 ASSERT(role == cricket::CONNECTIONROLE_ACTIVE ||
1245 role == cricket::CONNECTIONROLE_ACTPASS);
1246 InitAttrLine(kAttributeSetup, &os);
1247 std::string dtls_role_str = role == cricket::CONNECTIONROLE_ACTPASS ?
1248 cricket::CONNECTIONROLE_ACTPASS_STR :
1249 cricket::CONNECTIONROLE_ACTIVE_STR;
1250 os << kSdpDelimiterColon << dtls_role_str;
1251 AddLine(os.str(), message);
1252 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001253 }
1254 }
1255
1256 // RFC 3388
1257 // mid-attribute = "a=mid:" identification-tag
1258 // identification-tag = token
1259 // Use the content name as the mid identification-tag.
1260 InitAttrLine(kAttributeMid, &os);
1261 os << kSdpDelimiterColon << content_info->name;
1262 AddLine(os.str(), message);
1263
1264 if (is_sctp) {
1265 BuildSctpContentAttributes(message);
1266 } else {
1267 BuildRtpContentAttributes(media_desc, media_type, message);
1268 }
1269}
1270
1271void BuildSctpContentAttributes(std::string* message) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001272 // draft-ietf-mmusic-sctp-sdp-04
1273 // a=sctpmap:sctpmap-number protocol [streams]
1274 std::ostringstream os;
1275 InitAttrLine(kAttributeSctpmap, &os);
1276 os << kSdpDelimiterColon << kDefaultSctpFmt << kSdpDelimiterSpace
1277 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1278 << (cricket::kMaxSctpSid + 1);
1279 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280}
1281
1282void BuildRtpContentAttributes(
1283 const MediaContentDescription* media_desc,
1284 const MediaType media_type,
1285 std::string* message) {
1286 std::ostringstream os;
1287 // RFC 5285
1288 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1289 // The definitions MUST be either all session level or all media level. This
1290 // implementation uses all media level.
1291 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1292 InitAttrLine(kAttributeExtmap, &os);
1293 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1294 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1295 AddLine(os.str(), message);
1296 }
1297
1298 // RFC 3264
1299 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
1300
1301 cricket::MediaContentDirection direction = media_desc->direction();
1302 if (media_desc->streams().empty() && direction == cricket::MD_SENDRECV) {
1303 direction = cricket::MD_RECVONLY;
1304 }
1305
1306 switch (direction) {
1307 case cricket::MD_INACTIVE:
1308 InitAttrLine(kAttributeInactive, &os);
1309 break;
1310 case cricket::MD_SENDONLY:
1311 InitAttrLine(kAttributeSendOnly, &os);
1312 break;
1313 case cricket::MD_RECVONLY:
1314 InitAttrLine(kAttributeRecvOnly, &os);
1315 break;
1316 case cricket::MD_SENDRECV:
1317 default:
1318 InitAttrLine(kAttributeSendRecv, &os);
1319 break;
1320 }
1321 AddLine(os.str(), message);
1322
1323 // RFC 4566
1324 // b=AS:<bandwidth>
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001325 // We should always use the default bandwidth for RTP-based data
1326 // channels. Don't allow SDP to set the bandwidth, because that
1327 // would give JS the opportunity to "break the Internet".
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00001328 // TODO(pthatcher): But we need to temporarily allow the SDP to control
1329 // this for backwards-compatibility. Once we don't need that any
1330 // more, remove this.
1331 bool support_dc_sdp_bandwidth_temporarily = true;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001332 if (media_desc->bandwidth() >= 1000 &&
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00001333 (media_type != cricket::MEDIA_TYPE_DATA ||
1334 support_dc_sdp_bandwidth_temporarily)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001335 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1336 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1337 AddLine(os.str(), message);
1338 }
1339
1340 // RFC 5761
1341 // a=rtcp-mux
1342 if (media_desc->rtcp_mux()) {
1343 InitAttrLine(kAttributeRtcpMux, &os);
1344 AddLine(os.str(), message);
1345 }
1346
1347 // RFC 4568
1348 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1349 for (std::vector<CryptoParams>::const_iterator it =
1350 media_desc->cryptos().begin();
1351 it != media_desc->cryptos().end(); ++it) {
1352 InitAttrLine(kAttributeCrypto, &os);
1353 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1354 << it->key_params;
1355 if (!it->session_params.empty()) {
1356 os << " " << it->session_params;
1357 }
1358 AddLine(os.str(), message);
1359 }
1360
1361 // RFC 4566
1362 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1363 // [/<encodingparameters>]
1364 BuildRtpMap(media_desc, media_type, message);
1365
1366 // Specify latency for buffered mode.
1367 // a=x-google-buffer-latency:<value>
1368 if (media_desc->buffered_mode_latency() != cricket::kBufferedModeDisabled) {
1369 std::ostringstream os;
1370 InitAttrLine(kAttributeXGoogleBufferLatency, &os);
1371 os << kSdpDelimiterColon << media_desc->buffered_mode_latency();
1372 AddLine(os.str(), message);
1373 }
1374
1375 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1376 track != media_desc->streams().end(); ++track) {
1377 // Require that the track belongs to a media stream,
1378 // ie the sync_label is set. This extra check is necessary since the
1379 // MediaContentDescription always contains a streamparam with an ssrc even
1380 // if no track or media stream have been created.
1381 if (track->sync_label.empty()) continue;
1382
1383 // Build the ssrc-group lines.
1384 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1385 // RFC 5576
1386 // a=ssrc-group:<semantics> <ssrc-id> ...
1387 if (track->ssrc_groups[i].ssrcs.empty()) {
1388 continue;
1389 }
1390 std::ostringstream os;
1391 InitAttrLine(kAttributeSsrcGroup, &os);
1392 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
1393 std::vector<uint32>::const_iterator ssrc =
1394 track->ssrc_groups[i].ssrcs.begin();
1395 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
1396 os << kSdpDelimiterSpace << talk_base::ToString<uint32>(*ssrc);
1397 }
1398 AddLine(os.str(), message);
1399 }
1400 // Build the ssrc lines for each ssrc.
1401 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
1402 uint32 ssrc = track->ssrcs[i];
1403 // RFC 5576
1404 // a=ssrc:<ssrc-id> cname:<value>
1405 AddSsrcLine(ssrc, kSsrcAttributeCname,
1406 track->cname, message);
1407
1408 // draft-alvestrand-mmusic-msid-00
1409 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1410 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1411 // is corresponding to the "name" attribute of StreamParams.
1412 std::string appdata = track->id;
1413 std::ostringstream os;
1414 InitAttrLine(kAttributeSsrc, &os);
1415 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1416 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1417 << kSdpDelimiterSpace << appdata;
1418 AddLine(os.str(), message);
1419
1420 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1421 // draft-alvestrand-rtcweb-mid-01
1422 // a=ssrc:<ssrc-id> mslabel:<value>
1423 // The label isn't yet defined.
1424 // a=ssrc:<ssrc-id> label:<value>
1425 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1426 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1427 }
1428 }
1429}
1430
1431void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1432 // fmtp header: a=fmtp:|payload_type| <parameters>
1433 // Add a=fmtp
1434 InitAttrLine(kAttributeFmtp, os);
1435 // Add :|payload_type|
1436 *os << kSdpDelimiterColon << payload_type;
1437}
1438
1439void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1440 // rtcp-fb header: a=rtcp-fb:|payload_type|
1441 // <parameters>/<ccm <ccm_parameters>>
1442 // Add a=rtcp-fb
1443 InitAttrLine(kAttributeRtcpFb, os);
1444 // Add :
1445 *os << kSdpDelimiterColon;
1446 if (payload_type == kWildcardPayloadType) {
1447 *os << "*";
1448 } else {
1449 *os << payload_type;
1450 }
1451}
1452
1453void WriteFmtpParameter(const std::string& parameter_name,
1454 const std::string& parameter_value,
1455 std::ostringstream* os) {
1456 // fmtp parameters: |parameter_name|=|parameter_value|
1457 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1458}
1459
1460void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1461 std::ostringstream* os) {
1462 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1463 fmtp != parameters.end(); ++fmtp) {
1464 // Each new parameter, except the first one starts with ";" and " ".
1465 if (fmtp != parameters.begin()) {
1466 *os << kSdpDelimiterSemicolon;
1467 }
1468 *os << kSdpDelimiterSpace;
1469 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1470 }
1471}
1472
1473bool IsFmtpParam(const std::string& name) {
1474 const char* kFmtpParams[] = {
1475 kCodecParamMinPTime, kCodecParamSPropStereo,
1476 kCodecParamStereo, kCodecParamUseInbandFec,
1477 kCodecParamMaxBitrate, kCodecParamMinBitrate, kCodecParamMaxQuantization,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001478 kCodecParamSctpProtocol, kCodecParamSctpStreams,
1479 kCodecParamMaxAverageBitrate
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480 };
1481 for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
1482 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1483 return true;
1484 }
1485 }
1486 return false;
1487}
1488
1489// Retreives fmtp parameters from |params|, which may contain other parameters
1490// as well, and puts them in |fmtp_parameters|.
1491void GetFmtpParams(const cricket::CodecParameterMap& params,
1492 cricket::CodecParameterMap* fmtp_parameters) {
1493 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1494 iter != params.end(); ++iter) {
1495 if (IsFmtpParam(iter->first)) {
1496 (*fmtp_parameters)[iter->first] = iter->second;
1497 }
1498 }
1499}
1500
1501template <class T>
1502void AddFmtpLine(const T& codec, std::string* message) {
1503 cricket::CodecParameterMap fmtp_parameters;
1504 GetFmtpParams(codec.params, &fmtp_parameters);
1505 if (fmtp_parameters.empty()) {
1506 // No need to add an fmtp if it will have no (optional) parameters.
1507 return;
1508 }
1509 std::ostringstream os;
1510 WriteFmtpHeader(codec.id, &os);
1511 WriteFmtpParameters(fmtp_parameters, &os);
1512 AddLine(os.str(), message);
1513 return;
1514}
1515
1516template <class T>
1517void AddRtcpFbLines(const T& codec, std::string* message) {
1518 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1519 codec.feedback_params.params().begin();
1520 iter != codec.feedback_params.params().end(); ++iter) {
1521 std::ostringstream os;
1522 WriteRtcpFbHeader(codec.id, &os);
1523 os << " " << iter->id();
1524 if (!iter->param().empty()) {
1525 os << " " << iter->param();
1526 }
1527 AddLine(os.str(), message);
1528 }
1529}
1530
1531bool GetMinValue(const std::vector<int>& values, int* value) {
1532 if (values.empty()) {
1533 return false;
1534 }
1535 std::vector<int>::const_iterator found =
1536 std::min_element(values.begin(), values.end());
1537 *value = *found;
1538 return true;
1539}
1540
1541bool GetParameter(const std::string& name,
1542 const cricket::CodecParameterMap& params, int* value) {
1543 std::map<std::string, std::string>::const_iterator found =
1544 params.find(name);
1545 if (found == params.end()) {
1546 return false;
1547 }
1548 *value = talk_base::FromString<int>(found->second);
1549 return true;
1550}
1551
1552void BuildRtpMap(const MediaContentDescription* media_desc,
1553 const MediaType media_type,
1554 std::string* message) {
1555 ASSERT(message != NULL);
1556 ASSERT(media_desc != NULL);
1557 std::ostringstream os;
1558 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1559 const VideoContentDescription* video_desc =
1560 static_cast<const VideoContentDescription*>(media_desc);
1561 for (std::vector<cricket::VideoCodec>::const_iterator it =
1562 video_desc->codecs().begin();
1563 it != video_desc->codecs().end(); ++it) {
1564 // RFC 4566
1565 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1566 // [/<encodingparameters>]
1567 if (it->id != kWildcardPayloadType) {
1568 InitAttrLine(kAttributeRtpmap, &os);
1569 os << kSdpDelimiterColon << it->id << " " << it->name
1570 << "/" << kDefaultVideoClockrate;
1571 AddLine(os.str(), message);
1572 }
1573 AddRtcpFbLines(*it, message);
1574 AddFmtpLine(*it, message);
1575 }
1576 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1577 const AudioContentDescription* audio_desc =
1578 static_cast<const AudioContentDescription*>(media_desc);
1579 std::vector<int> ptimes;
1580 std::vector<int> maxptimes;
1581 int max_minptime = 0;
1582 for (std::vector<cricket::AudioCodec>::const_iterator it =
1583 audio_desc->codecs().begin();
1584 it != audio_desc->codecs().end(); ++it) {
1585 ASSERT(!it->name.empty());
1586 // RFC 4566
1587 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1588 // [/<encodingparameters>]
1589 InitAttrLine(kAttributeRtpmap, &os);
1590 os << kSdpDelimiterColon << it->id << " ";
1591 os << it->name << "/" << it->clockrate;
1592 if (it->channels != 1) {
1593 os << "/" << it->channels;
1594 }
1595 AddLine(os.str(), message);
1596 AddRtcpFbLines(*it, message);
1597 AddFmtpLine(*it, message);
1598 int minptime = 0;
1599 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1600 max_minptime = std::max(minptime, max_minptime);
1601 }
1602 int ptime;
1603 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1604 ptimes.push_back(ptime);
1605 }
1606 int maxptime;
1607 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1608 maxptimes.push_back(maxptime);
1609 }
1610 }
1611 // Populate the maxptime attribute with the smallest maxptime of all codecs
1612 // under the same m-line.
1613 int min_maxptime = INT_MAX;
1614 if (GetMinValue(maxptimes, &min_maxptime)) {
1615 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1616 }
1617 ASSERT(min_maxptime > max_minptime);
1618 // Populate the ptime attribute with the smallest ptime or the largest
1619 // minptime, whichever is the largest, for all codecs under the same m-line.
1620 int ptime = INT_MAX;
1621 if (GetMinValue(ptimes, &ptime)) {
1622 ptime = std::min(ptime, min_maxptime);
1623 ptime = std::max(ptime, max_minptime);
1624 AddAttributeLine(kCodecParamPTime, ptime, message);
1625 }
1626 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1627 const DataContentDescription* data_desc =
1628 static_cast<const DataContentDescription*>(media_desc);
1629 for (std::vector<cricket::DataCodec>::const_iterator it =
1630 data_desc->codecs().begin();
1631 it != data_desc->codecs().end(); ++it) {
1632 // RFC 4566
1633 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1634 // [/<encodingparameters>]
1635 InitAttrLine(kAttributeRtpmap, &os);
1636 os << kSdpDelimiterColon << it->id << " "
1637 << it->name << "/" << it->clockrate;
1638 AddLine(os.str(), message);
1639 }
1640 }
1641}
1642
1643void BuildCandidate(const std::vector<Candidate>& candidates,
1644 std::string* message) {
1645 std::ostringstream os;
1646
1647 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1648 it != candidates.end(); ++it) {
1649 // RFC 5245
1650 // a=candidate:<foundation> <component-id> <transport> <priority>
1651 // <connection-address> <port> typ <candidate-types>
1652 // [raddr <connection-address>] [rport <port>]
1653 // *(SP extension-att-name SP extension-att-value)
1654 std::string type;
1655 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1656 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1657 type = kCandidateHost;
1658 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1659 type = kCandidateSrflx;
1660 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1661 type = kCandidateRelay;
1662 } else {
1663 ASSERT(false);
1664 }
1665
1666 InitAttrLine(kAttributeCandidate, &os);
1667 os << kSdpDelimiterColon
1668 << it->foundation() << " " << it->component() << " "
1669 << it->protocol() << " " << it->priority() << " "
1670 << it->address().ipaddr().ToString() << " "
1671 << it->address().PortAsString() << " "
1672 << kAttributeCandidateTyp << " " << type << " ";
1673
1674 // Related address
1675 if (!it->related_address().IsNil()) {
1676 os << kAttributeCandidateRaddr << " "
1677 << it->related_address().ipaddr().ToString() << " "
1678 << kAttributeCandidateRport << " "
1679 << it->related_address().PortAsString() << " ";
1680 }
1681
1682 // Extensions
1683 os << kAttributeCandidateGeneration << " " << it->generation();
1684
1685 AddLine(os.str(), message);
1686 }
1687}
1688
1689void BuildIceOptions(const std::vector<std::string>& transport_options,
1690 std::string* message) {
1691 if (!transport_options.empty()) {
1692 std::ostringstream os;
1693 InitAttrLine(kAttributeIceOption, &os);
1694 os << kSdpDelimiterColon << transport_options[0];
1695 for (size_t i = 1; i < transport_options.size(); ++i) {
1696 os << kSdpDelimiterSpace << transport_options[i];
1697 }
1698 AddLine(os.str(), message);
1699 }
1700}
1701
1702bool ParseSessionDescription(const std::string& message, size_t* pos,
1703 std::string* session_id,
1704 std::string* session_version,
1705 bool* supports_msid,
1706 TransportDescription* session_td,
1707 RtpHeaderExtensions* session_extmaps,
1708 cricket::SessionDescription* desc,
1709 SdpParseError* error) {
1710 std::string line;
1711
1712 // RFC 4566
1713 // v= (protocol version)
1714 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1715 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1716 std::string(), error);
1717 }
1718 // RFC 4566
1719 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1720 // <unicast-address>
1721 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1722 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1723 std::string(), error);
1724 }
1725 std::vector<std::string> fields;
1726 talk_base::split(line.substr(kLinePrefixLength),
1727 kSdpDelimiterSpace, &fields);
1728 const size_t expected_fields = 6;
1729 if (fields.size() != expected_fields) {
1730 return ParseFailedExpectFieldNum(line, expected_fields, error);
1731 }
1732 *session_id = fields[1];
1733 *session_version = fields[2];
1734
1735 // RFC 4566
1736 // s= (session name)
1737 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1738 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1739 std::string(), error);
1740 }
1741
1742 // Optional lines
1743 // Those are the optional lines, so shouldn't return false if not present.
1744 // RFC 4566
1745 // i=* (session information)
1746 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1747
1748 // RFC 4566
1749 // u=* (URI of description)
1750 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1751
1752 // RFC 4566
1753 // e=* (email address)
1754 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1755
1756 // RFC 4566
1757 // p=* (phone number)
1758 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1759
1760 // RFC 4566
1761 // c=* (connection information -- not required if included in
1762 // all media)
1763 GetLineWithType(message, pos, &line, kLineTypeConnection);
1764
1765 // RFC 4566
1766 // b=* (zero or more bandwidth information lines)
1767 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1768 // By pass zero or more b lines.
1769 }
1770
1771 // RFC 4566
1772 // One or more time descriptions ("t=" and "r=" lines; see below)
1773 // t= (time the session is active)
1774 // r=* (zero or more repeat times)
1775 // Ensure there's at least one time description
1776 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1777 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1778 error);
1779 }
1780
1781 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1782 // By pass zero or more r lines.
1783 }
1784
1785 // Go through the rest of the time descriptions
1786 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1787 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1788 // By pass zero or more r lines.
1789 }
1790 }
1791
1792 // RFC 4566
1793 // z=* (time zone adjustments)
1794 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1795
1796 // RFC 4566
1797 // k=* (encryption key)
1798 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1799
1800 // RFC 4566
1801 // a=* (zero or more session attribute lines)
1802 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1803 if (HasAttribute(line, kAttributeGroup)) {
1804 if (!ParseGroupAttribute(line, desc, error)) {
1805 return false;
1806 }
1807 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1808 if (!GetValue(line, kAttributeIceUfrag,
1809 &(session_td->ice_ufrag), error)) {
1810 return false;
1811 }
1812 } else if (HasAttribute(line, kAttributeIcePwd)) {
1813 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1814 return false;
1815 }
1816 } else if (HasAttribute(line, kAttributeIceLite)) {
1817 session_td->ice_mode = cricket::ICEMODE_LITE;
1818 } else if (HasAttribute(line, kAttributeIceOption)) {
1819 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1820 return false;
1821 }
1822 } else if (HasAttribute(line, kAttributeFingerprint)) {
1823 if (session_td->identity_fingerprint.get()) {
1824 return ParseFailed(
1825 line,
1826 "Can't have multiple fingerprint attributes at the same level.",
1827 error);
1828 }
1829 talk_base::SSLFingerprint* fingerprint = NULL;
1830 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1831 return false;
1832 }
1833 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001834 } else if (HasAttribute(line, kAttributeSetup)) {
1835 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1836 return false;
1837 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001838 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1839 std::string semantics;
1840 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1841 return false;
1842 }
1843 *supports_msid = CaseInsensitiveFind(semantics, kMediaStreamSemantic);
1844 } else if (HasAttribute(line, kAttributeExtmap)) {
1845 RtpHeaderExtension extmap;
1846 if (!ParseExtmap(line, &extmap, error)) {
1847 return false;
1848 }
1849 session_extmaps->push_back(extmap);
1850 }
1851 }
1852
1853 return true;
1854}
1855
1856bool ParseGroupAttribute(const std::string& line,
1857 cricket::SessionDescription* desc,
1858 SdpParseError* error) {
1859 ASSERT(desc != NULL);
1860
1861 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1862 // a=group:BUNDLE video voice
1863 std::vector<std::string> fields;
1864 talk_base::split(line.substr(kLinePrefixLength),
1865 kSdpDelimiterSpace, &fields);
1866 std::string semantics;
1867 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1868 return false;
1869 }
1870 cricket::ContentGroup group(semantics);
1871 for (size_t i = 1; i < fields.size(); ++i) {
1872 group.AddContentName(fields[i]);
1873 }
1874 desc->AddGroup(group);
1875 return true;
1876}
1877
1878static bool ParseFingerprintAttribute(const std::string& line,
1879 talk_base::SSLFingerprint** fingerprint,
1880 SdpParseError* error) {
1881 if (!IsLineType(line, kLineTypeAttributes) ||
1882 !HasAttribute(line, kAttributeFingerprint)) {
1883 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1884 kAttributeFingerprint, error);
1885 }
1886
1887 std::vector<std::string> fields;
1888 talk_base::split(line.substr(kLinePrefixLength),
1889 kSdpDelimiterSpace, &fields);
1890 const size_t expected_fields = 2;
1891 if (fields.size() != expected_fields) {
1892 return ParseFailedExpectFieldNum(line, expected_fields, error);
1893 }
1894
1895 // The first field here is "fingerprint:<hash>.
1896 std::string algorithm;
1897 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
1898 return false;
1899 }
1900
1901 // Downcase the algorithm. Note that we don't need to downcase the
1902 // fingerprint because hex_decode can handle upper-case.
1903 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
1904 ::tolower);
1905
1906 // The second field is the digest value. De-hexify it.
1907 *fingerprint = talk_base::SSLFingerprint::CreateFromRfc4572(
1908 algorithm, fields[1]);
1909 if (!*fingerprint) {
1910 return ParseFailed(line,
1911 "Failed to create fingerprint from the digest.",
1912 error);
1913 }
1914
1915 return true;
1916}
1917
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001918static bool ParseDtlsSetup(const std::string& line,
1919 cricket::ConnectionRole* role,
1920 SdpParseError* error) {
1921 // setup-attr = "a=setup:" role
1922 // role = "active" / "passive" / "actpass" / "holdconn"
1923 std::vector<std::string> fields;
1924 talk_base::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1925 const size_t expected_fields = 2;
1926 if (fields.size() != expected_fields) {
1927 return ParseFailedExpectFieldNum(line, expected_fields, error);
1928 }
1929 std::string role_str = fields[1];
1930 if (!cricket::StringToConnectionRole(role_str, role)) {
1931 return ParseFailed(line, "Invalid attribute value.", error);
1932 }
1933 return true;
1934}
1935
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001936// RFC 3551
1937// PT encoding media type clock rate channels
1938// name (Hz)
1939// 0 PCMU A 8,000 1
1940// 1 reserved A
1941// 2 reserved A
1942// 3 GSM A 8,000 1
1943// 4 G723 A 8,000 1
1944// 5 DVI4 A 8,000 1
1945// 6 DVI4 A 16,000 1
1946// 7 LPC A 8,000 1
1947// 8 PCMA A 8,000 1
1948// 9 G722 A 8,000 1
1949// 10 L16 A 44,100 2
1950// 11 L16 A 44,100 1
1951// 12 QCELP A 8,000 1
1952// 13 CN A 8,000 1
1953// 14 MPA A 90,000 (see text)
1954// 15 G728 A 8,000 1
1955// 16 DVI4 A 11,025 1
1956// 17 DVI4 A 22,050 1
1957// 18 G729 A 8,000 1
1958struct StaticPayloadAudioCodec {
1959 const char* name;
1960 int clockrate;
1961 int channels;
1962};
1963static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
1964 { "PCMU", 8000, 1 },
1965 { "reserved", 0, 0 },
1966 { "reserved", 0, 0 },
1967 { "GSM", 8000, 1 },
1968 { "G723", 8000, 1 },
1969 { "DVI4", 8000, 1 },
1970 { "DVI4", 16000, 1 },
1971 { "LPC", 8000, 1 },
1972 { "PCMA", 8000, 1 },
1973 { "G722", 8000, 1 },
1974 { "L16", 44100, 2 },
1975 { "L16", 44100, 1 },
1976 { "QCELP", 8000, 1 },
1977 { "CN", 8000, 1 },
1978 { "MPA", 90000, 1 },
1979 { "G728", 8000, 1 },
1980 { "DVI4", 11025, 1 },
1981 { "DVI4", 22050, 1 },
1982 { "G729", 8000, 1 },
1983};
1984
1985void MaybeCreateStaticPayloadAudioCodecs(
1986 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
1987 if (!media_desc) {
1988 return;
1989 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001990 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991 std::vector<int>::const_iterator it = fmts.begin();
1992 bool add_new_codec = false;
1993 for (; it != fmts.end(); ++it) {
1994 int payload_type = *it;
1995 if (!media_desc->HasCodec(payload_type) &&
1996 payload_type >= 0 &&
1997 payload_type < ARRAY_SIZE(kStaticPayloadAudioCodecs)) {
1998 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
1999 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2000 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2001 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2002 clock_rate, 0, channels,
2003 preference));
2004 add_new_codec = true;
2005 }
2006 --preference;
2007 }
2008 if (add_new_codec) {
2009 media_desc->SortCodecs();
2010 }
2011}
2012
2013template <class C>
2014static C* ParseContentDescription(const std::string& message,
2015 const MediaType media_type,
2016 int mline_index,
2017 const std::string& protocol,
2018 const std::vector<int>& codec_preference,
2019 size_t* pos,
2020 std::string* content_name,
2021 TransportDescription* transport,
2022 std::vector<JsepIceCandidate*>* candidates,
2023 webrtc::SdpParseError* error) {
2024 C* media_desc = new C();
2025 switch (media_type) {
2026 case cricket::MEDIA_TYPE_AUDIO:
2027 *content_name = cricket::CN_AUDIO;
2028 break;
2029 case cricket::MEDIA_TYPE_VIDEO:
2030 *content_name = cricket::CN_VIDEO;
2031 break;
2032 case cricket::MEDIA_TYPE_DATA:
2033 *content_name = cricket::CN_DATA;
2034 break;
2035 default:
2036 ASSERT(false);
2037 break;
2038 }
2039 if (!ParseContent(message, media_type, mline_index, protocol,
2040 codec_preference, pos, content_name,
2041 media_desc, transport, candidates, error)) {
2042 delete media_desc;
2043 return NULL;
2044 }
2045 // Sort the codecs according to the m-line fmt list.
2046 media_desc->SortCodecs();
2047 return media_desc;
2048}
2049
2050bool ParseMediaDescription(const std::string& message,
2051 const TransportDescription& session_td,
2052 const RtpHeaderExtensions& session_extmaps,
2053 bool supports_msid,
2054 size_t* pos,
2055 cricket::SessionDescription* desc,
2056 std::vector<JsepIceCandidate*>* candidates,
2057 SdpParseError* error) {
2058 ASSERT(desc != NULL);
2059 std::string line;
2060 int mline_index = -1;
2061
2062 // Zero or more media descriptions
2063 // RFC 4566
2064 // m=<media> <port> <proto> <fmt>
2065 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2066 ++mline_index;
2067
2068 std::vector<std::string> fields;
2069 talk_base::split(line.substr(kLinePrefixLength),
2070 kSdpDelimiterSpace, &fields);
2071 const size_t expected_min_fields = 4;
2072 if (fields.size() < expected_min_fields) {
2073 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2074 }
2075 bool rejected = false;
2076 // RFC 3264
2077 // To reject an offered stream, the port number in the corresponding stream
2078 // in the answer MUST be set to zero.
2079 if (fields[1] == kMediaPortRejected) {
2080 rejected = true;
2081 }
2082
2083 std::string protocol = fields[2];
2084 bool is_sctp = (protocol == cricket::kMediaProtocolDtlsSctp);
2085
2086 // <fmt>
2087 std::vector<int> codec_preference;
2088 for (size_t j = 3 ; j < fields.size(); ++j) {
2089 codec_preference.push_back(talk_base::FromString<int>(fields[j]));
2090 }
2091
2092 // Make a temporary TransportDescription based on |session_td|.
2093 // Some of this gets overwritten by ParseContent.
2094 TransportDescription transport(NS_JINGLE_ICE_UDP,
2095 session_td.transport_options,
2096 session_td.ice_ufrag,
2097 session_td.ice_pwd,
2098 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002099 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002100 session_td.identity_fingerprint.get(),
2101 Candidates());
2102
2103 talk_base::scoped_ptr<MediaContentDescription> content;
2104 std::string content_name;
2105 if (HasAttribute(line, kMediaTypeVideo)) {
2106 content.reset(ParseContentDescription<VideoContentDescription>(
2107 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2108 codec_preference, pos, &content_name,
2109 &transport, candidates, error));
2110 } else if (HasAttribute(line, kMediaTypeAudio)) {
2111 content.reset(ParseContentDescription<AudioContentDescription>(
2112 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2113 codec_preference, pos, &content_name,
2114 &transport, candidates, error));
2115 MaybeCreateStaticPayloadAudioCodecs(
2116 codec_preference,
2117 static_cast<AudioContentDescription*>(content.get()));
2118 } else if (HasAttribute(line, kMediaTypeData)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002119 DataContentDescription* desc =
2120 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002121 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2122 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002123 &transport, candidates, error);
2124
2125 if (protocol == cricket::kMediaProtocolDtlsSctp) {
2126 // Add the SCTP Port number as a pseudo-codec "port" parameter
2127 cricket::DataCodec codec_port(
2128 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
2129 0);
2130 codec_port.SetParam(cricket::kCodecParamPort, fields[3]);
2131 LOG(INFO) << "ParseMediaDescription: Got SCTP Port Number "
2132 << fields[3];
2133 desc->AddCodec(codec_port);
2134 }
2135
2136 content.reset(desc);
2137
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002138 // We should always use the default bandwidth for RTP-based data
2139 // channels. Don't allow SDP to set the bandwidth, because that
2140 // would give JS the opportunity to "break the Internet".
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002141 // TODO(pthatcher): But we need to temporarily allow the SDP to control
2142 // this for backwards-compatibility. Once we don't need that any
2143 // more, remove this.
2144 bool support_dc_sdp_bandwidth_temporarily = true;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00002145 if (content.get() && !support_dc_sdp_bandwidth_temporarily) {
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002146 content->set_bandwidth(cricket::kAutoBandwidth);
2147 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002148 } else {
2149 LOG(LS_WARNING) << "Unsupported media type: " << line;
2150 continue;
2151 }
2152 if (!content.get()) {
2153 // ParseContentDescription returns NULL if failed.
2154 return false;
2155 }
2156
2157 if (!is_sctp) {
2158 // Make sure to set the media direction correctly. If the direction is not
2159 // MD_RECVONLY or Inactive and no streams are parsed,
2160 // a default MediaStream will be created to prepare for receiving media.
2161 if (supports_msid && content->streams().empty() &&
2162 content->direction() == cricket::MD_SENDRECV) {
2163 content->set_direction(cricket::MD_RECVONLY);
2164 }
2165
2166 // Set the extmap.
2167 if (!session_extmaps.empty() &&
2168 !content->rtp_header_extensions().empty()) {
2169 return ParseFailed("",
2170 "The a=extmap MUST be either all session level or "
2171 "all media level.",
2172 error);
2173 }
2174 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2175 content->AddRtpHeaderExtension(session_extmaps[i]);
2176 }
2177 }
2178 content->set_protocol(protocol);
2179 desc->AddContent(content_name,
2180 is_sctp ? cricket::NS_JINGLE_DRAFT_SCTP :
2181 cricket::NS_JINGLE_RTP,
2182 rejected,
2183 content.release());
2184 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2185 TransportInfo transport_info(content_name, transport);
2186
2187 if (!desc->AddTransportInfo(transport_info)) {
2188 std::ostringstream description;
2189 description << "Failed to AddTransportInfo with content name: "
2190 << content_name;
2191 return ParseFailed("", description.str(), error);
2192 }
2193 }
2194 return true;
2195}
2196
2197bool VerifyCodec(const cricket::Codec& codec) {
2198 // Codec has not been populated correctly unless the name has been set. This
2199 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2200 // have a corresponding "rtpmap" line.
2201 cricket::Codec default_codec;
2202 return default_codec.name != codec.name;
2203}
2204
2205bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2206 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2207 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2208 iter != codecs.end(); ++iter) {
2209 if (!VerifyCodec(*iter)) {
2210 return false;
2211 }
2212 }
2213 return true;
2214}
2215
2216bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2217 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2218 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2219 iter != codecs.end(); ++iter) {
2220 if (!VerifyCodec(*iter)) {
2221 return false;
2222 }
2223 }
2224 return true;
2225}
2226
2227void AddParameters(const cricket::CodecParameterMap& parameters,
2228 cricket::Codec* codec) {
2229 for (cricket::CodecParameterMap::const_iterator iter =
2230 parameters.begin(); iter != parameters.end(); ++iter) {
2231 codec->SetParam(iter->first, iter->second);
2232 }
2233}
2234
2235void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2236 cricket::Codec* codec) {
2237 codec->AddFeedbackParam(feedback_param);
2238}
2239
2240void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2241 cricket::Codec* codec) {
2242 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2243 feedback_params.params().begin();
2244 iter != feedback_params.params().end(); ++iter) {
2245 codec->AddFeedbackParam(*iter);
2246 }
2247}
2248
2249// Gets the current codec setting associated with |payload_type|. If there
2250// is no AudioCodec associated with that payload type it returns an empty codec
2251// with that payload type.
2252template <class T>
2253T GetCodec(const std::vector<T>& codecs, int payload_type) {
2254 for (typename std::vector<T>::const_iterator codec = codecs.begin();
2255 codec != codecs.end(); ++codec) {
2256 if (codec->id == payload_type) {
2257 return *codec;
2258 }
2259 }
2260 T ret_val = T();
2261 ret_val.id = payload_type;
2262 return ret_val;
2263}
2264
2265// Updates or creates a new codec entry in the audio description.
2266template <class T, class U>
2267void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2268 T* desc = static_cast<T*>(content_desc);
2269 std::vector<U> codecs = desc->codecs();
2270 bool found = false;
2271
2272 typename std::vector<U>::iterator iter;
2273 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2274 if (iter->id == codec.id) {
2275 *iter = codec;
2276 found = true;
2277 break;
2278 }
2279 }
2280 if (!found) {
2281 desc->AddCodec(codec);
2282 return;
2283 }
2284 desc->set_codecs(codecs);
2285}
2286
2287// Adds or updates existing codec corresponding to |payload_type| according
2288// to |parameters|.
2289template <class T, class U>
2290void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2291 const cricket::CodecParameterMap& parameters) {
2292 // Codec might already have been populated (from rtpmap).
2293 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2294 AddParameters(parameters, &new_codec);
2295 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2296}
2297
2298// Adds or updates existing codec corresponding to |payload_type| according
2299// to |feedback_param|.
2300template <class T, class U>
2301void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2302 const cricket::FeedbackParam& feedback_param) {
2303 // Codec might already have been populated (from rtpmap).
2304 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2305 AddFeedbackParameter(feedback_param, &new_codec);
2306 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2307}
2308
2309bool PopWildcardCodec(std::vector<cricket::VideoCodec>* codecs,
2310 cricket::VideoCodec* wildcard_codec) {
2311 for (std::vector<cricket::VideoCodec>::iterator iter = codecs->begin();
2312 iter != codecs->end(); ++iter) {
2313 if (iter->id == kWildcardPayloadType) {
2314 *wildcard_codec = *iter;
2315 codecs->erase(iter);
2316 return true;
2317 }
2318 }
2319 return false;
2320}
2321
2322void UpdateFromWildcardVideoCodecs(VideoContentDescription* video_desc) {
2323 std::vector<cricket::VideoCodec> codecs = video_desc->codecs();
2324 cricket::VideoCodec wildcard_codec;
2325 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2326 return;
2327 }
2328 for (std::vector<cricket::VideoCodec>::iterator iter = codecs.begin();
2329 iter != codecs.end(); ++iter) {
2330 cricket::VideoCodec& codec = *iter;
2331 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2332 }
2333 video_desc->set_codecs(codecs);
2334}
2335
2336void AddAudioAttribute(const std::string& name, const std::string& value,
2337 AudioContentDescription* audio_desc) {
2338 if (value.empty()) {
2339 return;
2340 }
2341 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2342 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2343 iter != codecs.end(); ++iter) {
2344 iter->params[name] = value;
2345 }
2346 audio_desc->set_codecs(codecs);
2347}
2348
2349bool ParseContent(const std::string& message,
2350 const MediaType media_type,
2351 int mline_index,
2352 const std::string& protocol,
2353 const std::vector<int>& codec_preference,
2354 size_t* pos,
2355 std::string* content_name,
2356 MediaContentDescription* media_desc,
2357 TransportDescription* transport,
2358 std::vector<JsepIceCandidate*>* candidates,
2359 SdpParseError* error) {
2360 ASSERT(media_desc != NULL);
2361 ASSERT(content_name != NULL);
2362 ASSERT(transport != NULL);
2363
2364 // The media level "ice-ufrag" and "ice-pwd".
2365 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2366 Candidates candidates_orig;
2367 std::string line;
2368 std::string mline_id;
2369 // Tracks created out of the ssrc attributes.
2370 StreamParamsVec tracks;
2371 SsrcInfoVec ssrc_infos;
2372 SsrcGroupVec ssrc_groups;
2373 std::string maxptime_as_string;
2374 std::string ptime_as_string;
2375
2376 bool is_rtp =
2377 protocol.empty() ||
2378 talk_base::starts_with(protocol.data(),
2379 cricket::kMediaProtocolRtpPrefix);
2380
2381 // Loop until the next m line
2382 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2383 if (!GetLine(message, pos, &line)) {
2384 if (*pos >= message.size()) {
2385 break; // Done parsing
2386 } else {
2387 return ParseFailed(message, *pos, "Can't find valid SDP line.", error);
2388 }
2389 }
2390
2391 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2392 std::string bandwidth;
2393 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2394 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2395 return false;
2396 } else {
2397 media_desc->set_bandwidth(
2398 talk_base::FromString<int>(bandwidth) * 1000);
2399 }
2400 }
2401 continue;
2402 }
2403
2404 // RFC 4566
2405 // b=* (zero or more bandwidth information lines)
2406 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2407 std::string bandwidth;
2408 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2409 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2410 return false;
2411 } else {
2412 media_desc->set_bandwidth(
2413 talk_base::FromString<int>(bandwidth) * 1000);
2414 }
2415 }
2416 continue;
2417 }
2418
2419 if (!IsLineType(line, kLineTypeAttributes)) {
2420 // TODO: Handle other lines if needed.
2421 LOG(LS_INFO) << "Ignored line: " << line;
2422 continue;
2423 }
2424
2425 // Handle attributes common to SCTP and RTP.
2426 if (HasAttribute(line, kAttributeMid)) {
2427 // RFC 3388
2428 // mid-attribute = "a=mid:" identification-tag
2429 // identification-tag = token
2430 // Use the mid identification-tag as the content name.
2431 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2432 return false;
2433 }
2434 *content_name = mline_id;
2435 } else if (HasAttribute(line, kAttributeCandidate)) {
2436 Candidate candidate;
2437 if (!ParseCandidate(line, &candidate, error, false)) {
2438 return false;
2439 }
2440 candidates_orig.push_back(candidate);
2441 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2442 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2443 return false;
2444 }
2445 } else if (HasAttribute(line, kAttributeIcePwd)) {
2446 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2447 return false;
2448 }
2449 } else if (HasAttribute(line, kAttributeIceOption)) {
2450 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2451 return false;
2452 }
2453 } else if (HasAttribute(line, kAttributeFmtp)) {
2454 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2455 return false;
2456 }
2457 } else if (HasAttribute(line, kAttributeFingerprint)) {
2458 talk_base::SSLFingerprint* fingerprint = NULL;
2459
2460 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2461 return false;
2462 }
2463 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002464 } else if (HasAttribute(line, kAttributeSetup)) {
2465 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2466 return false;
2467 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002468 } else if (is_rtp) {
2469 //
2470 // RTP specific attrubtes
2471 //
2472 if (HasAttribute(line, kAttributeRtcpMux)) {
2473 media_desc->set_rtcp_mux(true);
2474 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2475 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2476 return false;
2477 }
2478 } else if (HasAttribute(line, kAttributeSsrc)) {
2479 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2480 return false;
2481 }
2482 } else if (HasAttribute(line, kAttributeCrypto)) {
2483 if (!ParseCryptoAttribute(line, media_desc, error)) {
2484 return false;
2485 }
2486 } else if (HasAttribute(line, kAttributeRtpmap)) {
2487 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2488 media_desc, error)) {
2489 return false;
2490 }
2491 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2492 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2493 return false;
2494 }
2495 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2496 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2497 return false;
2498 }
2499 } else if (HasAttribute(line, kCodecParamPTime)) {
2500 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2501 return false;
2502 }
2503 } else if (HasAttribute(line, kAttributeSendOnly)) {
2504 media_desc->set_direction(cricket::MD_SENDONLY);
2505 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2506 media_desc->set_direction(cricket::MD_RECVONLY);
2507 } else if (HasAttribute(line, kAttributeInactive)) {
2508 media_desc->set_direction(cricket::MD_INACTIVE);
2509 } else if (HasAttribute(line, kAttributeSendRecv)) {
2510 media_desc->set_direction(cricket::MD_SENDRECV);
2511 } else if (HasAttribute(line, kAttributeExtmap)) {
2512 RtpHeaderExtension extmap;
2513 if (!ParseExtmap(line, &extmap, error)) {
2514 return false;
2515 }
2516 media_desc->AddRtpHeaderExtension(extmap);
2517 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2518 // Experimental attribute. Conference mode activates more aggressive
2519 // AEC and NS settings.
2520 // TODO: expose API to set these directly.
2521 std::string flag_value;
2522 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2523 return false;
2524 }
2525 if (flag_value.compare(kValueConference) == 0)
2526 media_desc->set_conference_mode(true);
2527 } else if (HasAttribute(line, kAttributeXGoogleBufferLatency)) {
2528 // Experimental attribute.
2529 // TODO: expose API to set this directly.
2530 std::string flag_value;
2531 if (!GetValue(line, kAttributeXGoogleBufferLatency, &flag_value,
2532 error)) {
2533 return false;
2534 }
2535 int buffer_latency = 0;
2536 if (!talk_base::FromString(flag_value, &buffer_latency) ||
2537 buffer_latency < 0) {
2538 return ParseFailed(message, "Invalid buffer latency.", error);
2539 }
2540 media_desc->set_buffered_mode_latency(buffer_latency);
2541 }
2542 } else {
2543 // Only parse lines that we are interested of.
2544 LOG(LS_INFO) << "Ignored line: " << line;
2545 continue;
2546 }
2547 }
2548
2549 // Create tracks from the |ssrc_infos|.
2550 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2551
2552 // Add the ssrc group to the track.
2553 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2554 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2555 if (ssrc_group->ssrcs.empty()) {
2556 continue;
2557 }
2558 uint32 ssrc = ssrc_group->ssrcs.front();
2559 for (StreamParamsVec::iterator track = tracks.begin();
2560 track != tracks.end(); ++track) {
2561 if (track->has_ssrc(ssrc)) {
2562 track->ssrc_groups.push_back(*ssrc_group);
2563 }
2564 }
2565 }
2566
2567 // Add the new tracks to the |media_desc|.
2568 for (StreamParamsVec::iterator track = tracks.begin();
2569 track != tracks.end(); ++track) {
2570 media_desc->AddStream(*track);
2571 }
2572
2573 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2574 AudioContentDescription* audio_desc =
2575 static_cast<AudioContentDescription*>(media_desc);
2576 // Verify audio codec ensures that no audio codec has been populated with
2577 // only fmtp.
2578 if (!VerifyAudioCodecs(audio_desc)) {
2579 return ParseFailed("Failed to parse audio codecs correctly.", error);
2580 }
2581 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2582 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2583 }
2584
2585 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2586 VideoContentDescription* video_desc =
2587 static_cast<VideoContentDescription*>(media_desc);
2588 UpdateFromWildcardVideoCodecs(video_desc);
2589 // Verify video codec ensures that no video codec has been populated with
2590 // only rtcp-fb.
2591 if (!VerifyVideoCodecs(video_desc)) {
2592 return ParseFailed("Failed to parse video codecs correctly.", error);
2593 }
2594 }
2595
2596 // RFC 5245
2597 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2598 for (Candidates::iterator it = candidates_orig.begin();
2599 it != candidates_orig.end(); ++it) {
2600 ASSERT((*it).username().empty());
2601 (*it).set_username(transport->ice_ufrag);
2602 ASSERT((*it).password().empty());
2603 (*it).set_password(transport->ice_pwd);
2604 candidates->push_back(
2605 new JsepIceCandidate(mline_id, mline_index, *it));
2606 }
2607 return true;
2608}
2609
2610bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2611 SdpParseError* error) {
2612 ASSERT(ssrc_infos != NULL);
2613 // RFC 5576
2614 // a=ssrc:<ssrc-id> <attribute>
2615 // a=ssrc:<ssrc-id> <attribute>:<value>
2616 std::string field1, field2;
2617 if (!SplitByDelimiter(line.substr(kLinePrefixLength),
2618 kSdpDelimiterSpace,
2619 &field1,
2620 &field2)) {
2621 const size_t expected_fields = 2;
2622 return ParseFailedExpectFieldNum(line, expected_fields, error);
2623 }
2624
2625 // ssrc:<ssrc-id>
2626 std::string ssrc_id_s;
2627 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2628 return false;
2629 }
2630 uint32 ssrc_id = talk_base::FromString<uint32>(ssrc_id_s);
2631
2632 std::string attribute;
2633 std::string value;
2634 if (!SplitByDelimiter(field2, kSdpDelimiterColon,
2635 &attribute, &value)) {
2636 std::ostringstream description;
2637 description << "Failed to get the ssrc attribute value from " << field2
2638 << ". Expected format <attribute>:<value>.";
2639 return ParseFailed(line, description.str(), error);
2640 }
2641
2642 // Check if there's already an item for this |ssrc_id|. Create a new one if
2643 // there isn't.
2644 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2645 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2646 if (ssrc_info->ssrc_id == ssrc_id) {
2647 break;
2648 }
2649 }
2650 if (ssrc_info == ssrc_infos->end()) {
2651 SsrcInfo info;
2652 info.ssrc_id = ssrc_id;
2653 ssrc_infos->push_back(info);
2654 ssrc_info = ssrc_infos->end() - 1;
2655 }
2656
2657 // Store the info to the |ssrc_info|.
2658 if (attribute == kSsrcAttributeCname) {
2659 // RFC 5576
2660 // cname:<value>
2661 ssrc_info->cname = value;
2662 } else if (attribute == kSsrcAttributeMsid) {
2663 // draft-alvestrand-mmusic-msid-00
2664 // "msid:" identifier [ " " appdata ]
2665 std::vector<std::string> fields;
2666 talk_base::split(value, kSdpDelimiterSpace, &fields);
2667 if (fields.size() < 1 || fields.size() > 2) {
2668 return ParseFailed(line,
2669 "Expected format \"msid:<identifier>[ <appdata>]\".",
2670 error);
2671 }
2672 ssrc_info->msid_identifier = fields[0];
2673 if (fields.size() == 2) {
2674 ssrc_info->msid_appdata = fields[1];
2675 }
2676 } else if (attribute == kSsrcAttributeMslabel) {
2677 // draft-alvestrand-rtcweb-mid-01
2678 // mslabel:<value>
2679 ssrc_info->mslabel = value;
2680 } else if (attribute == kSSrcAttributeLabel) {
2681 // The label isn't defined.
2682 // label:<value>
2683 ssrc_info->label = value;
2684 }
2685 return true;
2686}
2687
2688bool ParseSsrcGroupAttribute(const std::string& line,
2689 SsrcGroupVec* ssrc_groups,
2690 SdpParseError* error) {
2691 ASSERT(ssrc_groups != NULL);
2692 // RFC 5576
2693 // a=ssrc-group:<semantics> <ssrc-id> ...
2694 std::vector<std::string> fields;
2695 talk_base::split(line.substr(kLinePrefixLength),
2696 kSdpDelimiterSpace, &fields);
2697 const size_t expected_min_fields = 2;
2698 if (fields.size() < expected_min_fields) {
2699 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2700 }
2701 std::string semantics;
2702 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2703 return false;
2704 }
2705 std::vector<uint32> ssrcs;
2706 for (size_t i = 1; i < fields.size(); ++i) {
2707 uint32 ssrc = talk_base::FromString<uint32>(fields[i]);
2708 ssrcs.push_back(ssrc);
2709 }
2710 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2711 return true;
2712}
2713
2714bool ParseCryptoAttribute(const std::string& line,
2715 MediaContentDescription* media_desc,
2716 SdpParseError* error) {
2717 std::vector<std::string> fields;
2718 talk_base::split(line.substr(kLinePrefixLength),
2719 kSdpDelimiterSpace, &fields);
2720 // RFC 4568
2721 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2722 const size_t expected_min_fields = 3;
2723 if (fields.size() < expected_min_fields) {
2724 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2725 }
2726 std::string tag_value;
2727 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2728 return false;
2729 }
2730 int tag = talk_base::FromString<int>(tag_value);
2731 const std::string crypto_suite = fields[1];
2732 const std::string key_params = fields[2];
2733 std::string session_params;
2734 if (fields.size() > 3) {
2735 session_params = fields[3];
2736 }
2737 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2738 session_params));
2739 return true;
2740}
2741
2742// Updates or creates a new codec entry in the audio description with according
2743// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2744void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2745 int bitrate, int channels, int preference,
2746 AudioContentDescription* audio_desc) {
2747 // Codec may already be populated with (only) optional parameters
2748 // (from an fmtp).
2749 cricket::AudioCodec codec = GetCodec(audio_desc->codecs(), payload_type);
2750 codec.name = name;
2751 codec.clockrate = clockrate;
2752 codec.bitrate = bitrate;
2753 codec.channels = channels;
2754 codec.preference = preference;
2755 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2756 codec);
2757}
2758
2759// Updates or creates a new codec entry in the video description according to
2760// |name|, |width|, |height|, |framerate| and |preference|.
2761void UpdateCodec(int payload_type, const std::string& name, int width,
2762 int height, int framerate, int preference,
2763 VideoContentDescription* video_desc) {
2764 // Codec may already be populated with (only) optional parameters
2765 // (from an fmtp).
2766 cricket::VideoCodec codec = GetCodec(video_desc->codecs(), payload_type);
2767 codec.name = name;
2768 codec.width = width;
2769 codec.height = height;
2770 codec.framerate = framerate;
2771 codec.preference = preference;
2772 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2773 codec);
2774}
2775
2776bool ParseRtpmapAttribute(const std::string& line,
2777 const MediaType media_type,
2778 const std::vector<int>& codec_preference,
2779 MediaContentDescription* media_desc,
2780 SdpParseError* error) {
2781 std::vector<std::string> fields;
2782 talk_base::split(line.substr(kLinePrefixLength),
2783 kSdpDelimiterSpace, &fields);
2784 // RFC 4566
2785 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2786 const size_t expected_min_fields = 2;
2787 if (fields.size() < expected_min_fields) {
2788 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2789 }
2790 std::string payload_type_value;
2791 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2792 return false;
2793 }
2794 const int payload_type = talk_base::FromString<int>(payload_type_value);
2795
2796 // Set the preference order depending on the order of the pl type in the
2797 // <fmt> of the m-line.
2798 const int preference = codec_preference.end() -
2799 std::find(codec_preference.begin(), codec_preference.end(),
2800 payload_type);
2801 if (preference == 0) {
2802 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2803 << "<fmt> of the m-line: " << line;
2804 return true;
2805 }
2806 const std::string encoder = fields[1];
2807 std::vector<std::string> codec_params;
2808 talk_base::split(encoder, '/', &codec_params);
2809 // <encoding name>/<clock rate>[/<encodingparameters>]
2810 // 2 mandatory fields
2811 if (codec_params.size() < 2 || codec_params.size() > 3) {
2812 return ParseFailed(line,
2813 "Expected format \"<encoding name>/<clock rate>"
2814 "[/<encodingparameters>]\".",
2815 error);
2816 }
2817 const std::string encoding_name = codec_params[0];
2818 const int clock_rate = talk_base::FromString<int>(codec_params[1]);
2819 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2820 VideoContentDescription* video_desc =
2821 static_cast<VideoContentDescription*>(media_desc);
2822 // TODO: We will send resolution in SDP. For now use
2823 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2824 UpdateCodec(payload_type, encoding_name,
2825 JsepSessionDescription::kMaxVideoCodecWidth,
2826 JsepSessionDescription::kMaxVideoCodecHeight,
2827 JsepSessionDescription::kDefaultVideoCodecFramerate,
2828 preference, video_desc);
2829 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2830 // RFC 4566
2831 // For audio streams, <encoding parameters> indicates the number
2832 // of audio channels. This parameter is OPTIONAL and may be
2833 // omitted if the number of channels is one, provided that no
2834 // additional parameters are needed.
2835 int channels = 1;
2836 if (codec_params.size() == 3) {
2837 channels = talk_base::FromString<int>(codec_params[2]);
2838 }
2839 int bitrate = 0;
2840 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2841 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2842 // The bandwidth adaptation doesn't always work well, so this code
2843 // sets a fixed target bitrate instead.
2844 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2845 if (clock_rate <= 16000) {
2846 bitrate = kIsacWbDefaultRate;
2847 } else {
2848 bitrate = kIsacSwbDefaultRate;
2849 }
2850 }
2851 AudioContentDescription* audio_desc =
2852 static_cast<AudioContentDescription*>(media_desc);
2853 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2854 preference, audio_desc);
2855 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2856 DataContentDescription* data_desc =
2857 static_cast<DataContentDescription*>(media_desc);
2858 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2859 preference));
2860 }
2861 return true;
2862}
2863
2864void PruneRight(const char delimiter, std::string* message) {
2865 size_t trailing = message->find(delimiter);
2866 if (trailing != std::string::npos) {
2867 *message = message->substr(0, trailing);
2868 }
2869}
2870
2871bool ParseFmtpParam(const std::string& line, std::string* parameter,
2872 std::string* value, SdpParseError* error) {
2873 if (!SplitByDelimiter(line, kSdpDelimiterEqual, parameter, value)) {
2874 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2875 return false;
2876 }
2877 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
2878 // When parsing the values the trailing ";" gets picked up. Remove them.
2879 PruneRight(kSdpDelimiterSemicolon, value);
2880 return true;
2881}
2882
2883bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
2884 MediaContentDescription* media_desc,
2885 SdpParseError* error) {
2886 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2887 media_type != cricket::MEDIA_TYPE_VIDEO) {
2888 return true;
2889 }
2890 std::vector<std::string> fields;
2891 talk_base::split(line.substr(kLinePrefixLength),
2892 kSdpDelimiterSpace, &fields);
2893
2894 // RFC 5576
2895 // a=fmtp:<format> <format specific parameters>
2896 // At least two fields, whereas the second one is any of the optional
2897 // parameters.
2898 if (fields.size() < 2) {
2899 ParseFailedExpectMinFieldNum(line, 2, error);
2900 return false;
2901 }
2902
2903 std::string payload_type;
2904 if (!GetValue(fields[0], kAttributeFmtp, &payload_type, error)) {
2905 return false;
2906 }
2907
2908 cricket::CodecParameterMap codec_params;
2909 for (std::vector<std::string>::const_iterator iter = fields.begin() + 1;
2910 iter != fields.end(); ++iter) {
2911 std::string name;
2912 std::string value;
2913 if (iter->find(kSdpDelimiterEqual) == std::string::npos) {
2914 // Only fmtps with equals are currently supported. Other fmtp types
2915 // should be ignored. Unknown fmtps do not constitute an error.
2916 continue;
2917 }
2918 if (!ParseFmtpParam(*iter, &name, &value, error)) {
2919 return false;
2920 }
2921 codec_params[name] = value;
2922 }
2923
2924 int int_payload_type = talk_base::FromString<int>(payload_type);
2925 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2926 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
2927 media_desc, int_payload_type, codec_params);
2928 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2929 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
2930 media_desc, int_payload_type, codec_params);
2931 }
2932 return true;
2933}
2934
2935bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
2936 MediaContentDescription* media_desc,
2937 SdpParseError* error) {
2938 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2939 media_type != cricket::MEDIA_TYPE_VIDEO) {
2940 return true;
2941 }
2942 std::vector<std::string> rtcp_fb_fields;
2943 talk_base::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
2944 if (rtcp_fb_fields.size() < 2) {
2945 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
2946 }
2947 std::string payload_type_string;
2948 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
2949 error)) {
2950 return false;
2951 }
2952 int payload_type = (payload_type_string == "*") ?
2953 kWildcardPayloadType : talk_base::FromString<int>(payload_type_string);
2954 std::string id = rtcp_fb_fields[1];
2955 std::string param = "";
2956 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
2957 iter != rtcp_fb_fields.end(); ++iter) {
2958 param.append(*iter);
2959 }
2960 const cricket::FeedbackParam feedback_param(id, param);
2961
2962 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2963 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(media_desc,
2964 payload_type,
2965 feedback_param);
2966 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2967 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(media_desc,
2968 payload_type,
2969 feedback_param);
2970 }
2971 return true;
2972}
2973
2974} // namespace webrtc