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