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