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