blob: 2a773b63de3e4120a1aa1bdbe6fbe198fadd1f46 [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.org36eda7c2014-04-15 20:37:30 +00002118 // TODO(wu): Remove when below bug is fixed.
2119 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
2120 if (fields[j] == "" && j == fields.size() - 1) {
2121 continue;
2122 }
2123
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002124 int pl = 0;
2125 if (!GetValueFromString(line, fields[j], &pl, error)) {
2126 return false;
2127 }
2128 codec_preference.push_back(pl);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002129 }
2130
2131 // Make a temporary TransportDescription based on |session_td|.
2132 // Some of this gets overwritten by ParseContent.
2133 TransportDescription transport(NS_JINGLE_ICE_UDP,
2134 session_td.transport_options,
2135 session_td.ice_ufrag,
2136 session_td.ice_pwd,
2137 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002138 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002139 session_td.identity_fingerprint.get(),
2140 Candidates());
2141
2142 talk_base::scoped_ptr<MediaContentDescription> content;
2143 std::string content_name;
2144 if (HasAttribute(line, kMediaTypeVideo)) {
2145 content.reset(ParseContentDescription<VideoContentDescription>(
2146 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2147 codec_preference, pos, &content_name,
2148 &transport, candidates, error));
2149 } else if (HasAttribute(line, kMediaTypeAudio)) {
2150 content.reset(ParseContentDescription<AudioContentDescription>(
2151 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2152 codec_preference, pos, &content_name,
2153 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002154 } else if (HasAttribute(line, kMediaTypeData)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002155 DataContentDescription* desc =
2156 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002157 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2158 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002159 &transport, candidates, error);
2160
henrike@webrtc.org571df2d2014-02-19 23:04:26 +00002161 if (desc && protocol == cricket::kMediaProtocolDtlsSctp) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002162 // Add the SCTP Port number as a pseudo-codec "port" parameter
2163 cricket::DataCodec codec_port(
2164 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
2165 0);
2166 codec_port.SetParam(cricket::kCodecParamPort, fields[3]);
2167 LOG(INFO) << "ParseMediaDescription: Got SCTP Port Number "
2168 << fields[3];
2169 desc->AddCodec(codec_port);
2170 }
2171
2172 content.reset(desc);
2173
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002174 // We should always use the default bandwidth for RTP-based data
2175 // channels. Don't allow SDP to set the bandwidth, because that
2176 // would give JS the opportunity to "break the Internet".
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002177 // TODO(pthatcher): But we need to temporarily allow the SDP to control
2178 // this for backwards-compatibility. Once we don't need that any
2179 // more, remove this.
2180 bool support_dc_sdp_bandwidth_temporarily = true;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00002181 if (content.get() && !support_dc_sdp_bandwidth_temporarily) {
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002182 content->set_bandwidth(cricket::kAutoBandwidth);
2183 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002184 } else {
2185 LOG(LS_WARNING) << "Unsupported media type: " << line;
2186 continue;
2187 }
2188 if (!content.get()) {
2189 // ParseContentDescription returns NULL if failed.
2190 return false;
2191 }
2192
2193 if (!is_sctp) {
2194 // Make sure to set the media direction correctly. If the direction is not
2195 // MD_RECVONLY or Inactive and no streams are parsed,
2196 // a default MediaStream will be created to prepare for receiving media.
2197 if (supports_msid && content->streams().empty() &&
2198 content->direction() == cricket::MD_SENDRECV) {
2199 content->set_direction(cricket::MD_RECVONLY);
2200 }
2201
2202 // Set the extmap.
2203 if (!session_extmaps.empty() &&
2204 !content->rtp_header_extensions().empty()) {
2205 return ParseFailed("",
2206 "The a=extmap MUST be either all session level or "
2207 "all media level.",
2208 error);
2209 }
2210 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2211 content->AddRtpHeaderExtension(session_extmaps[i]);
2212 }
2213 }
2214 content->set_protocol(protocol);
2215 desc->AddContent(content_name,
2216 is_sctp ? cricket::NS_JINGLE_DRAFT_SCTP :
2217 cricket::NS_JINGLE_RTP,
2218 rejected,
2219 content.release());
2220 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2221 TransportInfo transport_info(content_name, transport);
2222
2223 if (!desc->AddTransportInfo(transport_info)) {
2224 std::ostringstream description;
2225 description << "Failed to AddTransportInfo with content name: "
2226 << content_name;
2227 return ParseFailed("", description.str(), error);
2228 }
2229 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002230
2231 size_t end_of_message = message.size();
2232 if (mline_index == -1 && *pos != end_of_message) {
2233 ParseFailed(message, *pos, "Expects m line.", error);
2234 return false;
2235 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002236 return true;
2237}
2238
2239bool VerifyCodec(const cricket::Codec& codec) {
2240 // Codec has not been populated correctly unless the name has been set. This
2241 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2242 // have a corresponding "rtpmap" line.
2243 cricket::Codec default_codec;
2244 return default_codec.name != codec.name;
2245}
2246
2247bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2248 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2249 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2250 iter != codecs.end(); ++iter) {
2251 if (!VerifyCodec(*iter)) {
2252 return false;
2253 }
2254 }
2255 return true;
2256}
2257
2258bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2259 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2260 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2261 iter != codecs.end(); ++iter) {
2262 if (!VerifyCodec(*iter)) {
2263 return false;
2264 }
2265 }
2266 return true;
2267}
2268
2269void AddParameters(const cricket::CodecParameterMap& parameters,
2270 cricket::Codec* codec) {
2271 for (cricket::CodecParameterMap::const_iterator iter =
2272 parameters.begin(); iter != parameters.end(); ++iter) {
2273 codec->SetParam(iter->first, iter->second);
2274 }
2275}
2276
2277void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2278 cricket::Codec* codec) {
2279 codec->AddFeedbackParam(feedback_param);
2280}
2281
2282void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2283 cricket::Codec* codec) {
2284 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2285 feedback_params.params().begin();
2286 iter != feedback_params.params().end(); ++iter) {
2287 codec->AddFeedbackParam(*iter);
2288 }
2289}
2290
2291// Gets the current codec setting associated with |payload_type|. If there
2292// is no AudioCodec associated with that payload type it returns an empty codec
2293// with that payload type.
2294template <class T>
2295T GetCodec(const std::vector<T>& codecs, int payload_type) {
2296 for (typename std::vector<T>::const_iterator codec = codecs.begin();
2297 codec != codecs.end(); ++codec) {
2298 if (codec->id == payload_type) {
2299 return *codec;
2300 }
2301 }
2302 T ret_val = T();
2303 ret_val.id = payload_type;
2304 return ret_val;
2305}
2306
2307// Updates or creates a new codec entry in the audio description.
2308template <class T, class U>
2309void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2310 T* desc = static_cast<T*>(content_desc);
2311 std::vector<U> codecs = desc->codecs();
2312 bool found = false;
2313
2314 typename std::vector<U>::iterator iter;
2315 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2316 if (iter->id == codec.id) {
2317 *iter = codec;
2318 found = true;
2319 break;
2320 }
2321 }
2322 if (!found) {
2323 desc->AddCodec(codec);
2324 return;
2325 }
2326 desc->set_codecs(codecs);
2327}
2328
2329// Adds or updates existing codec corresponding to |payload_type| according
2330// to |parameters|.
2331template <class T, class U>
2332void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2333 const cricket::CodecParameterMap& parameters) {
2334 // Codec might already have been populated (from rtpmap).
2335 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2336 AddParameters(parameters, &new_codec);
2337 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2338}
2339
2340// Adds or updates existing codec corresponding to |payload_type| according
2341// to |feedback_param|.
2342template <class T, class U>
2343void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2344 const cricket::FeedbackParam& feedback_param) {
2345 // Codec might already have been populated (from rtpmap).
2346 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2347 AddFeedbackParameter(feedback_param, &new_codec);
2348 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2349}
2350
2351bool PopWildcardCodec(std::vector<cricket::VideoCodec>* codecs,
2352 cricket::VideoCodec* wildcard_codec) {
2353 for (std::vector<cricket::VideoCodec>::iterator iter = codecs->begin();
2354 iter != codecs->end(); ++iter) {
2355 if (iter->id == kWildcardPayloadType) {
2356 *wildcard_codec = *iter;
2357 codecs->erase(iter);
2358 return true;
2359 }
2360 }
2361 return false;
2362}
2363
2364void UpdateFromWildcardVideoCodecs(VideoContentDescription* video_desc) {
2365 std::vector<cricket::VideoCodec> codecs = video_desc->codecs();
2366 cricket::VideoCodec wildcard_codec;
2367 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2368 return;
2369 }
2370 for (std::vector<cricket::VideoCodec>::iterator iter = codecs.begin();
2371 iter != codecs.end(); ++iter) {
2372 cricket::VideoCodec& codec = *iter;
2373 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2374 }
2375 video_desc->set_codecs(codecs);
2376}
2377
2378void AddAudioAttribute(const std::string& name, const std::string& value,
2379 AudioContentDescription* audio_desc) {
2380 if (value.empty()) {
2381 return;
2382 }
2383 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2384 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2385 iter != codecs.end(); ++iter) {
2386 iter->params[name] = value;
2387 }
2388 audio_desc->set_codecs(codecs);
2389}
2390
2391bool ParseContent(const std::string& message,
2392 const MediaType media_type,
2393 int mline_index,
2394 const std::string& protocol,
2395 const std::vector<int>& codec_preference,
2396 size_t* pos,
2397 std::string* content_name,
2398 MediaContentDescription* media_desc,
2399 TransportDescription* transport,
2400 std::vector<JsepIceCandidate*>* candidates,
2401 SdpParseError* error) {
2402 ASSERT(media_desc != NULL);
2403 ASSERT(content_name != NULL);
2404 ASSERT(transport != NULL);
2405
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002406 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2407 MaybeCreateStaticPayloadAudioCodecs(
2408 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2409 }
2410
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002411 // The media level "ice-ufrag" and "ice-pwd".
2412 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2413 Candidates candidates_orig;
2414 std::string line;
2415 std::string mline_id;
2416 // Tracks created out of the ssrc attributes.
2417 StreamParamsVec tracks;
2418 SsrcInfoVec ssrc_infos;
2419 SsrcGroupVec ssrc_groups;
2420 std::string maxptime_as_string;
2421 std::string ptime_as_string;
2422
2423 bool is_rtp =
2424 protocol.empty() ||
2425 talk_base::starts_with(protocol.data(),
2426 cricket::kMediaProtocolRtpPrefix);
2427
2428 // Loop until the next m line
2429 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2430 if (!GetLine(message, pos, &line)) {
2431 if (*pos >= message.size()) {
2432 break; // Done parsing
2433 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002434 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002435 }
2436 }
2437
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002438 // RFC 4566
2439 // b=* (zero or more bandwidth information lines)
2440 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2441 std::string bandwidth;
2442 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2443 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2444 return false;
2445 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002446 int b = 0;
2447 if (!GetValueFromString(line, bandwidth, &b, error)) {
2448 return false;
2449 }
2450 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002451 }
2452 }
2453 continue;
2454 }
2455
2456 if (!IsLineType(line, kLineTypeAttributes)) {
2457 // TODO: Handle other lines if needed.
2458 LOG(LS_INFO) << "Ignored line: " << line;
2459 continue;
2460 }
2461
2462 // Handle attributes common to SCTP and RTP.
2463 if (HasAttribute(line, kAttributeMid)) {
2464 // RFC 3388
2465 // mid-attribute = "a=mid:" identification-tag
2466 // identification-tag = token
2467 // Use the mid identification-tag as the content name.
2468 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2469 return false;
2470 }
2471 *content_name = mline_id;
2472 } else if (HasAttribute(line, kAttributeCandidate)) {
2473 Candidate candidate;
2474 if (!ParseCandidate(line, &candidate, error, false)) {
2475 return false;
2476 }
2477 candidates_orig.push_back(candidate);
2478 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2479 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2480 return false;
2481 }
2482 } else if (HasAttribute(line, kAttributeIcePwd)) {
2483 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2484 return false;
2485 }
2486 } else if (HasAttribute(line, kAttributeIceOption)) {
2487 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2488 return false;
2489 }
2490 } else if (HasAttribute(line, kAttributeFmtp)) {
2491 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2492 return false;
2493 }
2494 } else if (HasAttribute(line, kAttributeFingerprint)) {
2495 talk_base::SSLFingerprint* fingerprint = NULL;
2496
2497 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2498 return false;
2499 }
2500 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002501 } else if (HasAttribute(line, kAttributeSetup)) {
2502 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2503 return false;
2504 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002505 } else if (is_rtp) {
2506 //
2507 // RTP specific attrubtes
2508 //
2509 if (HasAttribute(line, kAttributeRtcpMux)) {
2510 media_desc->set_rtcp_mux(true);
2511 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2512 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2513 return false;
2514 }
2515 } else if (HasAttribute(line, kAttributeSsrc)) {
2516 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2517 return false;
2518 }
2519 } else if (HasAttribute(line, kAttributeCrypto)) {
2520 if (!ParseCryptoAttribute(line, media_desc, error)) {
2521 return false;
2522 }
2523 } else if (HasAttribute(line, kAttributeRtpmap)) {
2524 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2525 media_desc, error)) {
2526 return false;
2527 }
2528 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2529 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2530 return false;
2531 }
2532 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2533 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2534 return false;
2535 }
2536 } else if (HasAttribute(line, kCodecParamPTime)) {
2537 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2538 return false;
2539 }
2540 } else if (HasAttribute(line, kAttributeSendOnly)) {
2541 media_desc->set_direction(cricket::MD_SENDONLY);
2542 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2543 media_desc->set_direction(cricket::MD_RECVONLY);
2544 } else if (HasAttribute(line, kAttributeInactive)) {
2545 media_desc->set_direction(cricket::MD_INACTIVE);
2546 } else if (HasAttribute(line, kAttributeSendRecv)) {
2547 media_desc->set_direction(cricket::MD_SENDRECV);
2548 } else if (HasAttribute(line, kAttributeExtmap)) {
2549 RtpHeaderExtension extmap;
2550 if (!ParseExtmap(line, &extmap, error)) {
2551 return false;
2552 }
2553 media_desc->AddRtpHeaderExtension(extmap);
2554 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2555 // Experimental attribute. Conference mode activates more aggressive
2556 // AEC and NS settings.
2557 // TODO: expose API to set these directly.
2558 std::string flag_value;
2559 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2560 return false;
2561 }
2562 if (flag_value.compare(kValueConference) == 0)
2563 media_desc->set_conference_mode(true);
2564 } else if (HasAttribute(line, kAttributeXGoogleBufferLatency)) {
2565 // Experimental attribute.
2566 // TODO: expose API to set this directly.
2567 std::string flag_value;
2568 if (!GetValue(line, kAttributeXGoogleBufferLatency, &flag_value,
2569 error)) {
2570 return false;
2571 }
2572 int buffer_latency = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002573 if (!GetValueFromString(line, flag_value, &buffer_latency, error)) {
2574 return false;
2575 }
2576 if (buffer_latency < 0) {
2577 return ParseFailed(line, "Buffer latency less than 0.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002578 }
2579 media_desc->set_buffered_mode_latency(buffer_latency);
2580 }
2581 } else {
2582 // Only parse lines that we are interested of.
2583 LOG(LS_INFO) << "Ignored line: " << line;
2584 continue;
2585 }
2586 }
2587
2588 // Create tracks from the |ssrc_infos|.
2589 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2590
2591 // Add the ssrc group to the track.
2592 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2593 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2594 if (ssrc_group->ssrcs.empty()) {
2595 continue;
2596 }
2597 uint32 ssrc = ssrc_group->ssrcs.front();
2598 for (StreamParamsVec::iterator track = tracks.begin();
2599 track != tracks.end(); ++track) {
2600 if (track->has_ssrc(ssrc)) {
2601 track->ssrc_groups.push_back(*ssrc_group);
2602 }
2603 }
2604 }
2605
2606 // Add the new tracks to the |media_desc|.
2607 for (StreamParamsVec::iterator track = tracks.begin();
2608 track != tracks.end(); ++track) {
2609 media_desc->AddStream(*track);
2610 }
2611
2612 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2613 AudioContentDescription* audio_desc =
2614 static_cast<AudioContentDescription*>(media_desc);
2615 // Verify audio codec ensures that no audio codec has been populated with
2616 // only fmtp.
2617 if (!VerifyAudioCodecs(audio_desc)) {
2618 return ParseFailed("Failed to parse audio codecs correctly.", error);
2619 }
2620 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2621 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2622 }
2623
2624 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2625 VideoContentDescription* video_desc =
2626 static_cast<VideoContentDescription*>(media_desc);
2627 UpdateFromWildcardVideoCodecs(video_desc);
2628 // Verify video codec ensures that no video codec has been populated with
2629 // only rtcp-fb.
2630 if (!VerifyVideoCodecs(video_desc)) {
2631 return ParseFailed("Failed to parse video codecs correctly.", error);
2632 }
2633 }
2634
2635 // RFC 5245
2636 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2637 for (Candidates::iterator it = candidates_orig.begin();
2638 it != candidates_orig.end(); ++it) {
2639 ASSERT((*it).username().empty());
2640 (*it).set_username(transport->ice_ufrag);
2641 ASSERT((*it).password().empty());
2642 (*it).set_password(transport->ice_pwd);
2643 candidates->push_back(
2644 new JsepIceCandidate(mline_id, mline_index, *it));
2645 }
2646 return true;
2647}
2648
2649bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2650 SdpParseError* error) {
2651 ASSERT(ssrc_infos != NULL);
2652 // RFC 5576
2653 // a=ssrc:<ssrc-id> <attribute>
2654 // a=ssrc:<ssrc-id> <attribute>:<value>
2655 std::string field1, field2;
2656 if (!SplitByDelimiter(line.substr(kLinePrefixLength),
2657 kSdpDelimiterSpace,
2658 &field1,
2659 &field2)) {
2660 const size_t expected_fields = 2;
2661 return ParseFailedExpectFieldNum(line, expected_fields, error);
2662 }
2663
2664 // ssrc:<ssrc-id>
2665 std::string ssrc_id_s;
2666 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2667 return false;
2668 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002669 uint32 ssrc_id = 0;
2670 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2671 return false;
2672 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673
2674 std::string attribute;
2675 std::string value;
2676 if (!SplitByDelimiter(field2, kSdpDelimiterColon,
2677 &attribute, &value)) {
2678 std::ostringstream description;
2679 description << "Failed to get the ssrc attribute value from " << field2
2680 << ". Expected format <attribute>:<value>.";
2681 return ParseFailed(line, description.str(), error);
2682 }
2683
2684 // Check if there's already an item for this |ssrc_id|. Create a new one if
2685 // there isn't.
2686 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2687 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2688 if (ssrc_info->ssrc_id == ssrc_id) {
2689 break;
2690 }
2691 }
2692 if (ssrc_info == ssrc_infos->end()) {
2693 SsrcInfo info;
2694 info.ssrc_id = ssrc_id;
2695 ssrc_infos->push_back(info);
2696 ssrc_info = ssrc_infos->end() - 1;
2697 }
2698
2699 // Store the info to the |ssrc_info|.
2700 if (attribute == kSsrcAttributeCname) {
2701 // RFC 5576
2702 // cname:<value>
2703 ssrc_info->cname = value;
2704 } else if (attribute == kSsrcAttributeMsid) {
2705 // draft-alvestrand-mmusic-msid-00
2706 // "msid:" identifier [ " " appdata ]
2707 std::vector<std::string> fields;
2708 talk_base::split(value, kSdpDelimiterSpace, &fields);
2709 if (fields.size() < 1 || fields.size() > 2) {
2710 return ParseFailed(line,
2711 "Expected format \"msid:<identifier>[ <appdata>]\".",
2712 error);
2713 }
2714 ssrc_info->msid_identifier = fields[0];
2715 if (fields.size() == 2) {
2716 ssrc_info->msid_appdata = fields[1];
2717 }
2718 } else if (attribute == kSsrcAttributeMslabel) {
2719 // draft-alvestrand-rtcweb-mid-01
2720 // mslabel:<value>
2721 ssrc_info->mslabel = value;
2722 } else if (attribute == kSSrcAttributeLabel) {
2723 // The label isn't defined.
2724 // label:<value>
2725 ssrc_info->label = value;
2726 }
2727 return true;
2728}
2729
2730bool ParseSsrcGroupAttribute(const std::string& line,
2731 SsrcGroupVec* ssrc_groups,
2732 SdpParseError* error) {
2733 ASSERT(ssrc_groups != NULL);
2734 // RFC 5576
2735 // a=ssrc-group:<semantics> <ssrc-id> ...
2736 std::vector<std::string> fields;
2737 talk_base::split(line.substr(kLinePrefixLength),
2738 kSdpDelimiterSpace, &fields);
2739 const size_t expected_min_fields = 2;
2740 if (fields.size() < expected_min_fields) {
2741 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2742 }
2743 std::string semantics;
2744 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2745 return false;
2746 }
2747 std::vector<uint32> ssrcs;
2748 for (size_t i = 1; i < fields.size(); ++i) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002749 uint32 ssrc = 0;
2750 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2751 return false;
2752 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002753 ssrcs.push_back(ssrc);
2754 }
2755 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2756 return true;
2757}
2758
2759bool ParseCryptoAttribute(const std::string& line,
2760 MediaContentDescription* media_desc,
2761 SdpParseError* error) {
2762 std::vector<std::string> fields;
2763 talk_base::split(line.substr(kLinePrefixLength),
2764 kSdpDelimiterSpace, &fields);
2765 // RFC 4568
2766 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2767 const size_t expected_min_fields = 3;
2768 if (fields.size() < expected_min_fields) {
2769 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2770 }
2771 std::string tag_value;
2772 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2773 return false;
2774 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002775 int tag = 0;
2776 if (!GetValueFromString(line, tag_value, &tag, error)) {
2777 return false;
2778 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002779 const std::string crypto_suite = fields[1];
2780 const std::string key_params = fields[2];
2781 std::string session_params;
2782 if (fields.size() > 3) {
2783 session_params = fields[3];
2784 }
2785 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2786 session_params));
2787 return true;
2788}
2789
2790// Updates or creates a new codec entry in the audio description with according
2791// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2792void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2793 int bitrate, int channels, int preference,
2794 AudioContentDescription* audio_desc) {
2795 // Codec may already be populated with (only) optional parameters
2796 // (from an fmtp).
2797 cricket::AudioCodec codec = GetCodec(audio_desc->codecs(), payload_type);
2798 codec.name = name;
2799 codec.clockrate = clockrate;
2800 codec.bitrate = bitrate;
2801 codec.channels = channels;
2802 codec.preference = preference;
2803 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2804 codec);
2805}
2806
2807// Updates or creates a new codec entry in the video description according to
2808// |name|, |width|, |height|, |framerate| and |preference|.
2809void UpdateCodec(int payload_type, const std::string& name, int width,
2810 int height, int framerate, int preference,
2811 VideoContentDescription* video_desc) {
2812 // Codec may already be populated with (only) optional parameters
2813 // (from an fmtp).
2814 cricket::VideoCodec codec = GetCodec(video_desc->codecs(), payload_type);
2815 codec.name = name;
2816 codec.width = width;
2817 codec.height = height;
2818 codec.framerate = framerate;
2819 codec.preference = preference;
2820 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2821 codec);
2822}
2823
2824bool ParseRtpmapAttribute(const std::string& line,
2825 const MediaType media_type,
2826 const std::vector<int>& codec_preference,
2827 MediaContentDescription* media_desc,
2828 SdpParseError* error) {
2829 std::vector<std::string> fields;
2830 talk_base::split(line.substr(kLinePrefixLength),
2831 kSdpDelimiterSpace, &fields);
2832 // RFC 4566
2833 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2834 const size_t expected_min_fields = 2;
2835 if (fields.size() < expected_min_fields) {
2836 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2837 }
2838 std::string payload_type_value;
2839 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2840 return false;
2841 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002842 int payload_type = 0;
2843 if (!GetValueFromString(line, payload_type_value, &payload_type, error)) {
2844 return false;
2845 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002846
2847 // Set the preference order depending on the order of the pl type in the
2848 // <fmt> of the m-line.
2849 const int preference = codec_preference.end() -
2850 std::find(codec_preference.begin(), codec_preference.end(),
2851 payload_type);
2852 if (preference == 0) {
2853 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2854 << "<fmt> of the m-line: " << line;
2855 return true;
2856 }
2857 const std::string encoder = fields[1];
2858 std::vector<std::string> codec_params;
2859 talk_base::split(encoder, '/', &codec_params);
2860 // <encoding name>/<clock rate>[/<encodingparameters>]
2861 // 2 mandatory fields
2862 if (codec_params.size() < 2 || codec_params.size() > 3) {
2863 return ParseFailed(line,
2864 "Expected format \"<encoding name>/<clock rate>"
2865 "[/<encodingparameters>]\".",
2866 error);
2867 }
2868 const std::string encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002869 int clock_rate = 0;
2870 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2871 return false;
2872 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002873 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2874 VideoContentDescription* video_desc =
2875 static_cast<VideoContentDescription*>(media_desc);
2876 // TODO: We will send resolution in SDP. For now use
2877 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2878 UpdateCodec(payload_type, encoding_name,
2879 JsepSessionDescription::kMaxVideoCodecWidth,
2880 JsepSessionDescription::kMaxVideoCodecHeight,
2881 JsepSessionDescription::kDefaultVideoCodecFramerate,
2882 preference, video_desc);
2883 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2884 // RFC 4566
2885 // For audio streams, <encoding parameters> indicates the number
2886 // of audio channels. This parameter is OPTIONAL and may be
2887 // omitted if the number of channels is one, provided that no
2888 // additional parameters are needed.
2889 int channels = 1;
2890 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002891 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2892 return false;
2893 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002894 }
2895 int bitrate = 0;
2896 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2897 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2898 // The bandwidth adaptation doesn't always work well, so this code
2899 // sets a fixed target bitrate instead.
2900 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2901 if (clock_rate <= 16000) {
2902 bitrate = kIsacWbDefaultRate;
2903 } else {
2904 bitrate = kIsacSwbDefaultRate;
2905 }
2906 }
2907 AudioContentDescription* audio_desc =
2908 static_cast<AudioContentDescription*>(media_desc);
2909 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2910 preference, audio_desc);
2911 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2912 DataContentDescription* data_desc =
2913 static_cast<DataContentDescription*>(media_desc);
2914 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2915 preference));
2916 }
2917 return true;
2918}
2919
2920void PruneRight(const char delimiter, std::string* message) {
2921 size_t trailing = message->find(delimiter);
2922 if (trailing != std::string::npos) {
2923 *message = message->substr(0, trailing);
2924 }
2925}
2926
2927bool ParseFmtpParam(const std::string& line, std::string* parameter,
2928 std::string* value, SdpParseError* error) {
2929 if (!SplitByDelimiter(line, kSdpDelimiterEqual, parameter, value)) {
2930 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2931 return false;
2932 }
2933 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
2934 // When parsing the values the trailing ";" gets picked up. Remove them.
2935 PruneRight(kSdpDelimiterSemicolon, value);
2936 return true;
2937}
2938
2939bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
2940 MediaContentDescription* media_desc,
2941 SdpParseError* error) {
2942 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2943 media_type != cricket::MEDIA_TYPE_VIDEO) {
2944 return true;
2945 }
2946 std::vector<std::string> fields;
2947 talk_base::split(line.substr(kLinePrefixLength),
2948 kSdpDelimiterSpace, &fields);
2949
2950 // RFC 5576
2951 // a=fmtp:<format> <format specific parameters>
2952 // At least two fields, whereas the second one is any of the optional
2953 // parameters.
2954 if (fields.size() < 2) {
2955 ParseFailedExpectMinFieldNum(line, 2, error);
2956 return false;
2957 }
2958
2959 std::string payload_type;
2960 if (!GetValue(fields[0], kAttributeFmtp, &payload_type, error)) {
2961 return false;
2962 }
2963
2964 cricket::CodecParameterMap codec_params;
2965 for (std::vector<std::string>::const_iterator iter = fields.begin() + 1;
2966 iter != fields.end(); ++iter) {
2967 std::string name;
2968 std::string value;
2969 if (iter->find(kSdpDelimiterEqual) == std::string::npos) {
2970 // Only fmtps with equals are currently supported. Other fmtp types
2971 // should be ignored. Unknown fmtps do not constitute an error.
2972 continue;
2973 }
2974 if (!ParseFmtpParam(*iter, &name, &value, error)) {
2975 return false;
2976 }
2977 codec_params[name] = value;
2978 }
2979
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002980 int int_payload_type = 0;
2981 if (!GetValueFromString(line, payload_type, &int_payload_type, error)) {
2982 return false;
2983 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002984 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2985 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
2986 media_desc, int_payload_type, codec_params);
2987 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2988 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
2989 media_desc, int_payload_type, codec_params);
2990 }
2991 return true;
2992}
2993
2994bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
2995 MediaContentDescription* media_desc,
2996 SdpParseError* error) {
2997 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2998 media_type != cricket::MEDIA_TYPE_VIDEO) {
2999 return true;
3000 }
3001 std::vector<std::string> rtcp_fb_fields;
3002 talk_base::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
3003 if (rtcp_fb_fields.size() < 2) {
3004 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3005 }
3006 std::string payload_type_string;
3007 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3008 error)) {
3009 return false;
3010 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003011 int payload_type = kWildcardPayloadType;
3012 if (payload_type_string != "*") {
3013 if (!GetValueFromString(line, payload_type_string, &payload_type, error)) {
3014 return false;
3015 }
3016 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003017 std::string id = rtcp_fb_fields[1];
3018 std::string param = "";
3019 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3020 iter != rtcp_fb_fields.end(); ++iter) {
3021 param.append(*iter);
3022 }
3023 const cricket::FeedbackParam feedback_param(id, param);
3024
3025 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3026 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(media_desc,
3027 payload_type,
3028 feedback_param);
3029 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3030 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(media_desc,
3031 payload_type,
3032 feedback_param);
3033 }
3034 return true;
3035}
3036
3037} // namespace webrtc