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