3 * Copyright 2011, Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
28 #include "talk/app/webrtc/webrtcsdp.h"
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"
45 #include "talk/media/sctp/sctpdataengine.h"
46 #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"
52 using cricket::AudioContentDescription;
53 using cricket::Candidate;
54 using cricket::Candidates;
55 using cricket::ContentDescription;
56 using cricket::ContentInfo;
57 using cricket::CryptoParams;
58 using cricket::DataContentDescription;
59 using cricket::ICE_CANDIDATE_COMPONENT_RTP;
60 using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
61 using cricket::kCodecParamMaxBitrate;
62 using cricket::kCodecParamMaxPTime;
63 using cricket::kCodecParamMaxQuantization;
64 using cricket::kCodecParamMinBitrate;
65 using cricket::kCodecParamMinPTime;
66 using cricket::kCodecParamPTime;
67 using cricket::kCodecParamSPropStereo;
68 using cricket::kCodecParamStartBitrate;
69 using cricket::kCodecParamStereo;
70 using cricket::kCodecParamUseInbandFec;
71 using cricket::kCodecParamSctpProtocol;
72 using cricket::kCodecParamSctpStreams;
73 using cricket::kCodecParamMaxAverageBitrate;
74 using cricket::kWildcardPayloadType;
75 using cricket::MediaContentDescription;
76 using cricket::MediaType;
77 using cricket::NS_JINGLE_ICE_UDP;
78 using cricket::RtpHeaderExtension;
79 using cricket::SsrcGroup;
80 using cricket::StreamParams;
81 using cricket::StreamParamsVec;
82 using cricket::TransportDescription;
83 using cricket::TransportInfo;
84 using cricket::VideoContentDescription;
85 using talk_base::SocketAddress;
87 typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
90 class SessionDescription;
97 // An SDP session description consists of a number of lines of text of
100 // where <type> MUST be exactly one case-significant character.
101 static const int kLinePrefixLength = 2; // Lenght of <type>=
102 static const char kLineTypeVersion = 'v';
103 static const char kLineTypeOrigin = 'o';
104 static const char kLineTypeSessionName = 's';
105 static const char kLineTypeSessionInfo = 'i';
106 static const char kLineTypeSessionUri = 'u';
107 static const char kLineTypeSessionEmail = 'e';
108 static const char kLineTypeSessionPhone = 'p';
109 static const char kLineTypeSessionBandwidth = 'b';
110 static const char kLineTypeTiming = 't';
111 static const char kLineTypeRepeatTimes = 'r';
112 static const char kLineTypeTimeZone = 'z';
113 static const char kLineTypeEncryptionKey = 'k';
114 static const char kLineTypeMedia = 'm';
115 static const char kLineTypeConnection = 'c';
116 static const char kLineTypeAttributes = 'a';
119 static const char kAttributeGroup[] = "group";
120 static const char kAttributeMid[] = "mid";
121 static const char kAttributeRtcpMux[] = "rtcp-mux";
122 static const char kAttributeSsrc[] = "ssrc";
123 static const char kSsrcAttributeCname[] = "cname";
124 static const char kAttributeExtmap[] = "extmap";
125 // draft-alvestrand-mmusic-msid-01
126 // a=msid-semantic: WMS
127 static const char kAttributeMsidSemantics[] = "msid-semantic";
128 static const char kMediaStreamSemantic[] = "WMS";
129 static const char kSsrcAttributeMsid[] = "msid";
130 static const char kDefaultMsid[] = "default";
131 static const char kSsrcAttributeMslabel[] = "mslabel";
132 static const char kSSrcAttributeLabel[] = "label";
133 static const char kAttributeSsrcGroup[] = "ssrc-group";
134 static const char kAttributeCrypto[] = "crypto";
135 static const char kAttributeCandidate[] = "candidate";
136 static const char kAttributeCandidateTyp[] = "typ";
137 static const char kAttributeCandidateRaddr[] = "raddr";
138 static const char kAttributeCandidateRport[] = "rport";
139 static const char kAttributeCandidateUsername[] = "username";
140 static const char kAttributeCandidatePassword[] = "password";
141 static const char kAttributeCandidateGeneration[] = "generation";
142 static const char kAttributeFingerprint[] = "fingerprint";
143 static const char kAttributeSetup[] = "setup";
144 static const char kAttributeFmtp[] = "fmtp";
145 static const char kAttributeRtpmap[] = "rtpmap";
146 static const char kAttributeSctpmap[] = "sctpmap";
147 static const char kAttributeRtcp[] = "rtcp";
148 static const char kAttributeIceUfrag[] = "ice-ufrag";
149 static const char kAttributeIcePwd[] = "ice-pwd";
150 static const char kAttributeIceLite[] = "ice-lite";
151 static const char kAttributeIceOption[] = "ice-options";
152 static const char kAttributeSendOnly[] = "sendonly";
153 static const char kAttributeRecvOnly[] = "recvonly";
154 static const char kAttributeRtcpFb[] = "rtcp-fb";
155 static const char kAttributeSendRecv[] = "sendrecv";
156 static const char kAttributeInactive[] = "inactive";
158 // Experimental flags
159 static const char kAttributeXGoogleFlag[] = "x-google-flag";
160 static const char kValueConference[] = "conference";
161 static const char kAttributeXGoogleBufferLatency[] =
162 "x-google-buffer-latency";
165 static const char kCandidateHost[] = "host";
166 static const char kCandidateSrflx[] = "srflx";
167 // TODO: How to map the prflx with circket candidate type
168 // static const char kCandidatePrflx[] = "prflx";
169 static const char kCandidateRelay[] = "relay";
171 static const char kSdpDelimiterEqual = '=';
172 static const char kSdpDelimiterSpace = ' ';
173 static const char kSdpDelimiterColon = ':';
174 static const char kSdpDelimiterSemicolon = ';';
175 static const char kSdpDelimiterSlash = '/';
176 static const char kNewLine = '\n';
177 static const char kReturn = '\r';
178 static const char kLineBreak[] = "\r\n";
180 // TODO: Generate the Session and Time description
181 // instead of hardcoding.
182 static const char kSessionVersion[] = "v=0";
184 static const char kSessionOriginUsername[] = "-";
185 static const char kSessionOriginSessionId[] = "0";
186 static const char kSessionOriginSessionVersion[] = "0";
187 static const char kSessionOriginNettype[] = "IN";
188 static const char kSessionOriginAddrtype[] = "IP4";
189 static const char kSessionOriginAddress[] = "127.0.0.1";
190 static const char kSessionName[] = "s=-";
191 static const char kTimeDescription[] = "t=0 0";
192 static const char kAttrGroup[] = "a=group:BUNDLE";
193 static const char kConnectionNettype[] = "IN";
194 static const char kConnectionAddrtype[] = "IP4";
195 static const char kMediaTypeVideo[] = "video";
196 static const char kMediaTypeAudio[] = "audio";
197 static const char kMediaTypeData[] = "application";
198 static const char kMediaPortRejected[] = "0";
199 static const char kDefaultAddress[] = "0.0.0.0";
200 static const char kDefaultPort[] = "1";
202 static const char kApplicationSpecificMaximum[] = "AS";
204 static const int kDefaultVideoClockrate = 90000;
206 // ISAC special-case.
207 static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
208 static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
209 static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
211 static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
215 : msid_identifier(kDefaultMsid),
216 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
217 // Create random string (which will be used as track label later)?
218 msid_appdata(talk_base::CreateRandomString(8)) {
222 std::string msid_identifier;
223 std::string msid_appdata;
225 // For backward compatibility.
226 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
230 typedef std::vector<SsrcInfo> SsrcInfoVec;
231 typedef std::vector<SsrcGroup> SsrcGroupVec;
233 // Serializes the passed in SessionDescription to a SDP string.
234 // desc - The SessionDescription object to be serialized.
235 static std::string SdpSerializeSessionDescription(
236 const JsepSessionDescription& jdesc);
238 static void AddFmtpLine(const T& codec, std::string* message);
239 static void BuildMediaDescription(const ContentInfo* content_info,
240 const TransportInfo* transport_info,
241 const MediaType media_type,
242 std::string* message);
243 static void BuildSctpContentAttributes(std::string* message, int sctp_port);
244 static void BuildRtpContentAttributes(
245 const MediaContentDescription* media_desc,
246 const MediaType media_type,
247 std::string* message);
248 static void BuildRtpMap(const MediaContentDescription* media_desc,
249 const MediaType media_type,
250 std::string* message);
251 static void BuildCandidate(const std::vector<Candidate>& candidates,
252 std::string* message);
253 static void BuildIceOptions(const std::vector<std::string>& transport_options,
254 std::string* message);
256 static bool ParseSessionDescription(const std::string& message, size_t* pos,
257 std::string* session_id,
258 std::string* session_version,
260 TransportDescription* session_td,
261 RtpHeaderExtensions* session_extmaps,
262 cricket::SessionDescription* desc,
263 SdpParseError* error);
264 static bool ParseGroupAttribute(const std::string& line,
265 cricket::SessionDescription* desc,
266 SdpParseError* error);
267 static bool ParseMediaDescription(
268 const std::string& message,
269 const TransportDescription& session_td,
270 const RtpHeaderExtensions& session_extmaps,
272 size_t* pos, cricket::SessionDescription* desc,
273 std::vector<JsepIceCandidate*>* candidates,
274 SdpParseError* error);
275 static bool ParseContent(const std::string& message,
276 const MediaType media_type,
278 const std::string& protocol,
279 const std::vector<int>& codec_preference,
281 std::string* content_name,
282 MediaContentDescription* media_desc,
283 TransportDescription* transport,
284 std::vector<JsepIceCandidate*>* candidates,
285 SdpParseError* error);
286 static bool ParseSsrcAttribute(const std::string& line,
287 SsrcInfoVec* ssrc_infos,
288 SdpParseError* error);
289 static bool ParseSsrcGroupAttribute(const std::string& line,
290 SsrcGroupVec* ssrc_groups,
291 SdpParseError* error);
292 static bool ParseCryptoAttribute(const std::string& line,
293 MediaContentDescription* media_desc,
294 SdpParseError* error);
295 static bool ParseRtpmapAttribute(const std::string& line,
296 const MediaType media_type,
297 const std::vector<int>& codec_preference,
298 MediaContentDescription* media_desc,
299 SdpParseError* error);
300 static bool ParseFmtpAttributes(const std::string& line,
301 const MediaType media_type,
302 MediaContentDescription* media_desc,
303 SdpParseError* error);
304 static bool ParseFmtpParam(const std::string& line, std::string* parameter,
305 std::string* value, SdpParseError* error);
306 static bool ParseCandidate(const std::string& message, Candidate* candidate,
307 SdpParseError* error, bool is_raw);
308 static bool ParseRtcpFbAttribute(const std::string& line,
309 const MediaType media_type,
310 MediaContentDescription* media_desc,
311 SdpParseError* error);
312 static bool ParseIceOptions(const std::string& line,
313 std::vector<std::string>* transport_options,
314 SdpParseError* error);
315 static bool ParseExtmap(const std::string& line,
316 RtpHeaderExtension* extmap,
317 SdpParseError* error);
318 static bool ParseFingerprintAttribute(const std::string& line,
319 talk_base::SSLFingerprint** fingerprint,
320 SdpParseError* error);
321 static bool ParseDtlsSetup(const std::string& line,
322 cricket::ConnectionRole* role,
323 SdpParseError* error);
327 // Below ParseFailed*** functions output the line that caused the parsing
328 // failure and the detailed reason (|description|) of the failure to |error|.
329 // The functions always return false so that they can be used directly in the
330 // following way when error happens:
331 // "return ParseFailed***(...);"
333 // The line starting at |line_start| of |message| is the failing line.
334 // The reason for the failure should be provided in the |description|.
335 // An example of a description could be "unknown character".
336 static bool ParseFailed(const std::string& message,
338 const std::string& description,
339 SdpParseError* error) {
340 // Get the first line of |message| from |line_start|.
341 std::string first_line;
342 size_t line_end = message.find(kNewLine, line_start);
343 if (line_end != std::string::npos) {
344 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
347 first_line = message.substr(line_start, (line_end - line_start));
349 first_line = message.substr(line_start);
353 error->line = first_line;
354 error->description = description;
356 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
357 << "\". Reason: " << description;
361 // |line| is the failing line. The reason for the failure should be
362 // provided in the |description|.
363 static bool ParseFailed(const std::string& line,
364 const std::string& description,
365 SdpParseError* error) {
366 return ParseFailed(line, 0, description, error);
369 // Parses failure where the failing SDP line isn't know or there are multiple
371 static bool ParseFailed(const std::string& description,
372 SdpParseError* error) {
373 return ParseFailed("", description, error);
376 // |line| is the failing line. The failure is due to the fact that |line|
377 // doesn't have |expected_fields| fields.
378 static bool ParseFailedExpectFieldNum(const std::string& line,
380 SdpParseError* error) {
381 std::ostringstream description;
382 description << "Expects " << expected_fields << " fields.";
383 return ParseFailed(line, description.str(), error);
386 // |line| is the failing line. The failure is due to the fact that |line| has
387 // less than |expected_min_fields| fields.
388 static bool ParseFailedExpectMinFieldNum(const std::string& line,
389 int expected_min_fields,
390 SdpParseError* error) {
391 std::ostringstream description;
392 description << "Expects at least " << expected_min_fields << " fields.";
393 return ParseFailed(line, description.str(), error);
396 // |line| is the failing line. The failure is due to the fact that it failed to
397 // get the value of |attribute|.
398 static bool ParseFailedGetValue(const std::string& line,
399 const std::string& attribute,
400 SdpParseError* error) {
401 std::ostringstream description;
402 description << "Failed to get the value of attribute: " << attribute;
403 return ParseFailed(line, description.str(), error);
406 // The line starting at |line_start| of |message| is the failing line. The
407 // failure is due to the line type (e.g. the "m" part of the "m-line")
408 // not matching what is expected. The expected line type should be
409 // provided as |line_type|.
410 static bool ParseFailedExpectLine(const std::string& message,
412 const char line_type,
413 const std::string& line_value,
414 SdpParseError* error) {
415 std::ostringstream description;
416 description << "Expect line: " << line_type << "=" << line_value;
417 return ParseFailed(message, line_start, description.str(), error);
420 static bool AddLine(const std::string& line, std::string* message) {
424 message->append(line);
425 message->append(kLineBreak);
429 static bool GetLine(const std::string& message,
432 size_t line_begin = *pos;
433 size_t line_end = message.find(kNewLine, line_begin);
434 if (line_end == std::string::npos) {
437 // Update the new start position
439 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
442 *line = message.substr(line_begin, (line_end - line_begin));
443 const char* cline = line->c_str();
445 // An SDP session description consists of a number of lines of text of
448 // where <type> MUST be exactly one case-significant character and
449 // <value> is structured text whose format depends on <type>.
450 // Whitespace MUST NOT be used on either side of the "=" sign.
451 if (cline[0] == kSdpDelimiterSpace ||
452 cline[1] != kSdpDelimiterEqual ||
453 cline[2] == kSdpDelimiterSpace) {
460 // Init |os| to "|type|=|value|".
461 static void InitLine(const char type,
462 const std::string& value,
463 std::ostringstream* os) {
465 *os << type << kSdpDelimiterEqual << value;
468 // Init |os| to "a=|attribute|".
469 static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
470 InitLine(kLineTypeAttributes, attribute, os);
473 // Writes a SDP attribute line based on |attribute| and |value| to |message|.
474 static void AddAttributeLine(const std::string& attribute, int value,
475 std::string* message) {
476 std::ostringstream os;
477 InitAttrLine(attribute, &os);
478 os << kSdpDelimiterColon << value;
479 AddLine(os.str(), message);
482 // Returns the first line of the message without the line breaker.
483 static bool GetFirstLine(const std::string& message, std::string* line) {
485 if (!GetLine(message, &pos, line)) {
486 // If GetLine failed, just return the full |message|.
492 static bool IsLineType(const std::string& message,
495 if (message.size() < line_start + kLinePrefixLength) {
498 const char* cmessage = message.c_str();
499 return (cmessage[line_start] == type &&
500 cmessage[line_start + 1] == kSdpDelimiterEqual);
503 static bool IsLineType(const std::string& line,
505 return IsLineType(line, type, 0);
508 static bool GetLineWithType(const std::string& message, size_t* pos,
509 std::string* line, const char type) {
510 if (!IsLineType(message, type, *pos)) {
514 if (!GetLine(message, pos, line))
520 static bool HasAttribute(const std::string& line,
521 const std::string& attribute) {
522 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
525 // Verifies the candiate to be of the format candidate:<blah>
526 static bool IsRawCandidate(const std::string& line) {
527 // Checking candiadte-attribute is starting with "candidate" str.
528 if (line.compare(0, strlen(kAttributeCandidate), kAttributeCandidate) != 0) {
531 const size_t first_candidate = line.find(kSdpDelimiterColon);
532 if (first_candidate == std::string::npos)
534 // In this format we only expecting one candiate. If any additional
535 // candidates present, whole string will be discared.
536 const size_t any_other = line.find(kSdpDelimiterColon, first_candidate + 1);
537 return (any_other == std::string::npos);
540 static bool AddSsrcLine(uint32 ssrc_id, const std::string& attribute,
541 const std::string& value, std::string* message) {
543 // a=ssrc:<ssrc-id> <attribute>:<value>
544 std::ostringstream os;
545 InitAttrLine(kAttributeSsrc, &os);
546 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
547 << attribute << kSdpDelimiterColon << value;
548 return AddLine(os.str(), message);
551 // Split the message into two parts by the first delimiter.
552 static bool SplitByDelimiter(const std::string& message,
553 const char delimiter,
555 std::string* field2) {
556 // Find the first delimiter
557 size_t pos = message.find(delimiter);
558 if (pos == std::string::npos) {
561 *field1 = message.substr(0, pos);
562 // The rest is the value.
563 *field2 = message.substr(pos + 1);
567 // Get value only from <attribute>:<value>.
568 static bool GetValue(const std::string& message, const std::string& attribute,
569 std::string* value, SdpParseError* error) {
570 std::string leftpart;
571 if (!SplitByDelimiter(message, kSdpDelimiterColon, &leftpart, value)) {
572 return ParseFailedGetValue(message, attribute, error);
574 // The left part should end with the expected attribute.
575 if (leftpart.length() < attribute.length() ||
576 leftpart.compare(leftpart.length() - attribute.length(),
577 attribute.length(), attribute) != 0) {
578 return ParseFailedGetValue(message, attribute, error);
583 static bool CaseInsensitiveFind(std::string str1, std::string str2) {
584 std::transform(str1.begin(), str1.end(), str1.begin(),
586 std::transform(str2.begin(), str2.end(), str2.begin(),
588 return str1.find(str2) != std::string::npos;
592 static bool GetValueFromString(const std::string& line,
593 const std::string& s,
595 SdpParseError* error) {
596 if (!talk_base::FromString(s, t)) {
597 std::ostringstream description;
598 description << "Invalid value: " << s << ".";
599 return ParseFailed(line, description.str(), error);
604 void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
605 StreamParamsVec* tracks) {
606 ASSERT(tracks != NULL);
607 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
608 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
609 if (ssrc_info->cname.empty()) {
613 std::string sync_label;
614 std::string track_id;
615 if (ssrc_info->msid_identifier == kDefaultMsid &&
616 !ssrc_info->mslabel.empty()) {
617 // If there's no msid and there's mslabel, we consider this is a sdp from
618 // a older version of client that doesn't support msid.
619 // In that case, we use the mslabel and label to construct the track.
620 sync_label = ssrc_info->mslabel;
621 track_id = ssrc_info->label;
623 sync_label = ssrc_info->msid_identifier;
624 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
625 // is corresponding to the "id" attribute of StreamParams.
626 track_id = ssrc_info->msid_appdata;
628 if (sync_label.empty() || track_id.empty()) {
633 StreamParamsVec::iterator track = tracks->begin();
634 for (; track != tracks->end(); ++track) {
635 if (track->id == track_id) {
639 if (track == tracks->end()) {
640 // If we don't find an existing track, create a new one.
641 tracks->push_back(StreamParams());
642 track = tracks->end() - 1;
644 track->add_ssrc(ssrc_info->ssrc_id);
645 track->cname = ssrc_info->cname;
646 track->sync_label = sync_label;
647 track->id = track_id;
651 void GetMediaStreamLabels(const ContentInfo* content,
652 std::set<std::string>* labels) {
653 const MediaContentDescription* media_desc =
654 static_cast<const MediaContentDescription*>(
655 content->description);
656 const cricket::StreamParamsVec& streams = media_desc->streams();
657 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
658 it != streams.end(); ++it) {
659 labels->insert(it->sync_label);
664 // It is RECOMMENDED that default candidates be chosen based on the
665 // likelihood of those candidates to work with the peer that is being
666 // contacted. It is RECOMMENDED that relayed > reflexive > host.
667 static const int kPreferenceUnknown = 0;
668 static const int kPreferenceHost = 1;
669 static const int kPreferenceReflexive = 2;
670 static const int kPreferenceRelayed = 3;
672 static int GetCandidatePreferenceFromType(const std::string& type) {
673 int preference = kPreferenceUnknown;
674 if (type == cricket::LOCAL_PORT_TYPE) {
675 preference = kPreferenceHost;
676 } else if (type == cricket::STUN_PORT_TYPE) {
677 preference = kPreferenceReflexive;
678 } else if (type == cricket::RELAY_PORT_TYPE) {
679 preference = kPreferenceRelayed;
686 // Get ip and port of the default destination from the |candidates| with
687 // the given value of |component_id|.
689 // The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
690 // TODO: Decide the default destination in webrtcsession and
691 // pass it down via SessionDescription.
692 static bool GetDefaultDestination(const std::vector<Candidate>& candidates,
693 int component_id, std::string* port, std::string* ip) {
694 *port = kDefaultPort;
695 *ip = kDefaultAddress;
696 int current_preference = kPreferenceUnknown;
697 for (std::vector<Candidate>::const_iterator it = candidates.begin();
698 it != candidates.end(); ++it) {
699 if (it->component() != component_id) {
702 const int preference = GetCandidatePreferenceFromType(it->type());
703 // See if this candidate is more preferable then the current one.
704 if (preference <= current_preference) {
707 current_preference = preference;
708 *port = it->address().PortAsString();
709 *ip = it->address().ipaddr().ToString();
714 // Update the media default destination.
715 static void UpdateMediaDefaultDestination(
716 const std::vector<Candidate>& candidates, std::string* mline) {
718 // m=<media> <port> <proto> <fmt> ...
719 std::vector<std::string> fields;
720 talk_base::split(*mline, kSdpDelimiterSpace, &fields);
721 if (fields.size() < 3) {
727 talk_base::starts_with(fields[2].data(),
728 cricket::kMediaProtocolRtpPrefix);
730 std::ostringstream os;
731 std::string rtp_port, rtp_ip;
732 if (GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
733 &rtp_port, &rtp_ip)) {
734 // Found default RTP candidate.
736 // The default candidates are added to the SDP as the default
737 // destination for media. For streams based on RTP, this is done by
738 // placing the IP address and port of the RTP candidate into the c and m
739 // lines, respectively.
741 // Update the port in the m line.
742 // If this is a m-line with port equal to 0, we don't change it.
743 if (fields[1] != kMediaPortRejected) {
744 mline->replace(fields[0].size() + 1,
750 // c=<nettype> <addrtype> <connection-address>
751 InitLine(kLineTypeConnection, kConnectionNettype, &os);
752 os << " " << kConnectionAddrtype << " " << rtp_ip;
753 AddLine(os.str(), mline);
757 std::string rtcp_port, rtcp_ip;
758 if (GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
759 &rtcp_port, &rtcp_ip)) {
760 // Found default RTCP candidate.
762 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
763 // using the a=rtcp attribute as defined in RFC 3605.
766 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
767 // connection-address] CRLF
768 InitAttrLine(kAttributeRtcp, &os);
769 os << kSdpDelimiterColon
771 << kConnectionNettype << " "
772 << kConnectionAddrtype << " "
774 AddLine(os.str(), mline);
779 // Get candidates according to the mline index from SessionDescriptionInterface.
780 static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
782 std::vector<Candidate>* candidates) {
786 const IceCandidateCollection* cc = desci.candidates(mline_index);
787 for (size_t i = 0; i < cc->count(); ++i) {
788 const IceCandidateInterface* candidate = cc->at(i);
789 candidates->push_back(candidate->candidate());
793 std::string SdpSerialize(const JsepSessionDescription& jdesc) {
794 std::string sdp = SdpSerializeSessionDescription(jdesc);
796 std::string sdp_with_candidates;
799 int mline_index = -1;
800 while (GetLine(sdp, &pos, &line)) {
801 if (IsLineType(line, kLineTypeMedia)) {
803 std::vector<Candidate> candidates;
804 GetCandidatesByMindex(jdesc, mline_index, &candidates);
805 // Media line may append other lines inside the
806 // UpdateMediaDefaultDestination call, so add the kLineBreak here first.
807 line.append(kLineBreak);
808 UpdateMediaDefaultDestination(candidates, &line);
809 sdp_with_candidates.append(line);
810 // Build the a=candidate lines.
811 BuildCandidate(candidates, &sdp_with_candidates);
813 // Copy old line to new sdp without change.
814 AddLine(line, &sdp_with_candidates);
817 sdp = sdp_with_candidates;
822 std::string SdpSerializeSessionDescription(
823 const JsepSessionDescription& jdesc) {
824 const cricket::SessionDescription* desc = jdesc.description();
831 // Session Description.
832 AddLine(kSessionVersion, &message);
835 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
837 std::ostringstream os;
838 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
839 const std::string session_id = jdesc.session_id().empty() ?
840 kSessionOriginSessionId : jdesc.session_id();
841 const std::string session_version = jdesc.session_version().empty() ?
842 kSessionOriginSessionVersion : jdesc.session_version();
843 os << " " << session_id << " " << session_version << " "
844 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
845 << kSessionOriginAddress;
846 AddLine(os.str(), &message);
847 AddLine(kSessionName, &message);
850 AddLine(kTimeDescription, &message);
853 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
854 std::string group_line = kAttrGroup;
855 const cricket::ContentGroup* group =
856 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
857 ASSERT(group != NULL);
858 const cricket::ContentNames& content_names = group->content_names();
859 for (cricket::ContentNames::const_iterator it = content_names.begin();
860 it != content_names.end(); ++it) {
861 group_line.append(" ");
862 group_line.append(*it);
864 AddLine(group_line, &message);
867 // MediaStream semantics
868 InitAttrLine(kAttributeMsidSemantics, &os);
869 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
870 std::set<std::string> media_stream_labels;
871 const ContentInfo* audio_content = GetFirstAudioContent(desc);
873 GetMediaStreamLabels(audio_content, &media_stream_labels);
874 const ContentInfo* video_content = GetFirstVideoContent(desc);
876 GetMediaStreamLabels(video_content, &media_stream_labels);
877 for (std::set<std::string>::const_iterator it =
878 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
881 AddLine(os.str(), &message);
884 BuildMediaDescription(audio_content,
885 desc->GetTransportInfoByName(audio_content->name),
886 cricket::MEDIA_TYPE_AUDIO, &message);
891 BuildMediaDescription(video_content,
892 desc->GetTransportInfoByName(video_content->name),
893 cricket::MEDIA_TYPE_VIDEO, &message);
896 const ContentInfo* data_content = GetFirstDataContent(desc);
898 BuildMediaDescription(data_content,
899 desc->GetTransportInfoByName(data_content->name),
900 cricket::MEDIA_TYPE_DATA, &message);
907 // Serializes the passed in IceCandidateInterface to a SDP string.
908 // candidate - The candidate to be serialized.
909 std::string SdpSerializeCandidate(
910 const IceCandidateInterface& candidate) {
912 std::vector<cricket::Candidate> candidates;
913 candidates.push_back(candidate.candidate());
914 BuildCandidate(candidates, &message);
918 bool SdpDeserialize(const std::string& message,
919 JsepSessionDescription* jdesc,
920 SdpParseError* error) {
921 std::string session_id;
922 std::string session_version;
923 TransportDescription session_td(NS_JINGLE_ICE_UDP,
924 std::string(), std::string());
925 RtpHeaderExtensions session_extmaps;
926 cricket::SessionDescription* desc = new cricket::SessionDescription();
927 std::vector<JsepIceCandidate*> candidates;
928 size_t current_pos = 0;
929 bool supports_msid = false;
931 // Session Description
932 if (!ParseSessionDescription(message, ¤t_pos, &session_id,
933 &session_version, &supports_msid, &session_td,
934 &session_extmaps, desc, error)) {
940 if (!ParseMediaDescription(message, session_td, session_extmaps,
941 supports_msid, ¤t_pos, desc, &candidates,
944 for (std::vector<JsepIceCandidate*>::const_iterator
945 it = candidates.begin(); it != candidates.end(); ++it) {
951 jdesc->Initialize(desc, session_id, session_version);
953 for (std::vector<JsepIceCandidate*>::const_iterator
954 it = candidates.begin(); it != candidates.end(); ++it) {
955 jdesc->AddCandidate(*it);
961 bool SdpDeserializeCandidate(const std::string& message,
962 JsepIceCandidate* jcandidate,
963 SdpParseError* error) {
964 ASSERT(jcandidate != NULL);
966 if (!ParseCandidate(message, &candidate, error, true)) {
969 jcandidate->SetCandidate(candidate);
973 bool ParseCandidate(const std::string& message, Candidate* candidate,
974 SdpParseError* error, bool is_raw) {
975 ASSERT(candidate != NULL);
977 // Get the first line from |message|.
978 std::string first_line;
979 GetFirstLine(message, &first_line);
981 size_t start_pos = kLinePrefixLength; // Starting position to parse.
982 if (IsRawCandidate(first_line)) {
983 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
984 // just candidate:<candidate> not a=candidate:<blah>CRLF
986 } else if (!IsLineType(first_line, kLineTypeAttributes) ||
987 !HasAttribute(first_line, kAttributeCandidate)) {
988 // Must start with a=candidate line.
989 // Expecting to be of the format a=candidate:<blah>CRLF.
991 std::ostringstream description;
992 description << "Expect line: "
993 << kAttributeCandidate
994 << ":" << "<candidate-str>";
995 return ParseFailed(first_line, 0, description.str(), error);
997 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
998 kAttributeCandidate, error);
1002 std::vector<std::string> fields;
1003 talk_base::split(first_line.substr(start_pos),
1004 kSdpDelimiterSpace, &fields);
1006 // a=candidate:<foundation> <component-id> <transport> <priority>
1007 // <connection-address> <port> typ <candidate-types>
1008 // [raddr <connection-address>] [rport <port>]
1009 // *(SP extension-att-name SP extension-att-value)
1010 const size_t expected_min_fields = 8;
1011 if (fields.size() < expected_min_fields ||
1012 (fields[6] != kAttributeCandidateTyp)) {
1013 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
1015 std::string foundation;
1016 if (!GetValue(fields[0], kAttributeCandidate, &foundation, error)) {
1019 int component_id = 0;
1020 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1023 const std::string transport = fields[2];
1024 uint32 priority = 0;
1025 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1028 const std::string connection_address = fields[4];
1030 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1033 SocketAddress address(connection_address, port);
1035 cricket::ProtocolType protocol;
1036 if (!StringToProto(transport.c_str(), &protocol)) {
1037 return ParseFailed(first_line, "Unsupported transport type.", error);
1040 std::string candidate_type;
1041 const std::string type = fields[7];
1042 if (type == kCandidateHost) {
1043 candidate_type = cricket::LOCAL_PORT_TYPE;
1044 } else if (type == kCandidateSrflx) {
1045 candidate_type = cricket::STUN_PORT_TYPE;
1046 } else if (type == kCandidateRelay) {
1047 candidate_type = cricket::RELAY_PORT_TYPE;
1049 return ParseFailed(first_line, "Unsupported candidate type.", error);
1052 size_t current_position = expected_min_fields;
1053 SocketAddress related_address;
1054 // The 2 optional fields for related address
1055 // [raddr <connection-address>] [rport <port>]
1056 if (fields.size() >= (current_position + 2) &&
1057 fields[current_position] == kAttributeCandidateRaddr) {
1058 related_address.SetIP(fields[++current_position]);
1061 if (fields.size() >= (current_position + 2) &&
1062 fields[current_position] == kAttributeCandidateRport) {
1064 if (!GetValueFromString(
1065 first_line, fields[++current_position], &port, error)) {
1068 related_address.SetPort(port);
1073 // Empty string as the candidate username and password.
1074 // Will be updated later with the ice-ufrag and ice-pwd.
1075 // TODO: Remove the username/password extension, which is currently
1076 // kept for backwards compatibility.
1077 std::string username;
1078 std::string password;
1079 uint32 generation = 0;
1080 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1082 // *(SP extension-att-name SP extension-att-value)
1083 if (fields[i] == kAttributeCandidateGeneration) {
1084 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1087 } else if (fields[i] == kAttributeCandidateUsername) {
1088 username = fields[++i];
1089 } else if (fields[i] == kAttributeCandidatePassword) {
1090 password = fields[++i];
1092 // Skip the unknown extension.
1097 // Empty string as the candidate id and network name.
1098 const std::string id;
1099 const std::string network_name;
1100 *candidate = Candidate(id, component_id, cricket::ProtoToString(protocol),
1101 address, priority, username, password, candidate_type, network_name,
1102 generation, foundation);
1103 candidate->set_related_address(related_address);
1107 bool ParseIceOptions(const std::string& line,
1108 std::vector<std::string>* transport_options,
1109 SdpParseError* error) {
1110 std::string ice_options;
1111 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1114 std::vector<std::string> fields;
1115 talk_base::split(ice_options, kSdpDelimiterSpace, &fields);
1116 for (size_t i = 0; i < fields.size(); ++i) {
1117 transport_options->push_back(fields[i]);
1122 bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1123 SdpParseError* error) {
1125 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1126 std::vector<std::string> fields;
1127 talk_base::split(line.substr(kLinePrefixLength),
1128 kSdpDelimiterSpace, &fields);
1129 const size_t expected_min_fields = 2;
1130 if (fields.size() < expected_min_fields) {
1131 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1133 std::string uri = fields[1];
1135 std::string value_direction;
1136 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1139 std::vector<std::string> sub_fields;
1140 talk_base::split(value_direction, kSdpDelimiterSlash, &sub_fields);
1142 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1146 *extmap = RtpHeaderExtension(uri, value);
1150 void BuildMediaDescription(const ContentInfo* content_info,
1151 const TransportInfo* transport_info,
1152 const MediaType media_type,
1153 std::string* message) {
1154 ASSERT(message != NULL);
1155 if (content_info == NULL || message == NULL) {
1158 // TODO: Rethink if we should use sprintfn instead of stringstream.
1159 // According to the style guide, streams should only be used for logging.
1160 // http://google-styleguide.googlecode.com/svn/
1161 // trunk/cppguide.xml?showone=Streams#Streams
1162 std::ostringstream os;
1163 const MediaContentDescription* media_desc =
1164 static_cast<const MediaContentDescription*>(
1165 content_info->description);
1166 ASSERT(media_desc != NULL);
1168 bool is_sctp = (media_desc->protocol() == cricket::kMediaProtocolDtlsSctp);
1169 int sctp_port = cricket::kSctpDefaultPort;
1172 // m=<media> <port> <proto> <fmt>
1173 // fmt is a list of payload type numbers that MAY be used in the session.
1174 const char* type = NULL;
1175 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1176 type = kMediaTypeAudio;
1177 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1178 type = kMediaTypeVideo;
1179 else if (media_type == cricket::MEDIA_TYPE_DATA)
1180 type = kMediaTypeData;
1185 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1186 const VideoContentDescription* video_desc =
1187 static_cast<const VideoContentDescription*>(media_desc);
1188 for (std::vector<cricket::VideoCodec>::const_iterator it =
1189 video_desc->codecs().begin();
1190 it != video_desc->codecs().end(); ++it) {
1192 fmt.append(talk_base::ToString<int>(it->id));
1194 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1195 const AudioContentDescription* audio_desc =
1196 static_cast<const AudioContentDescription*>(media_desc);
1197 for (std::vector<cricket::AudioCodec>::const_iterator it =
1198 audio_desc->codecs().begin();
1199 it != audio_desc->codecs().end(); ++it) {
1201 fmt.append(talk_base::ToString<int>(it->id));
1203 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1204 const DataContentDescription* data_desc =
1205 static_cast<const DataContentDescription*>(media_desc);
1209 for (std::vector<cricket::DataCodec>::const_iterator it =
1210 data_desc->codecs().begin();
1211 it != data_desc->codecs().end(); ++it) {
1212 if (it->id == cricket::kGoogleSctpDataCodecId &&
1213 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1218 fmt.append(talk_base::ToString<int>(sctp_port));
1220 for (std::vector<cricket::DataCodec>::const_iterator it =
1221 data_desc->codecs().begin();
1222 it != data_desc->codecs().end(); ++it) {
1224 fmt.append(talk_base::ToString<int>(it->id));
1228 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1234 // The port number in the m line will be updated later when associate with
1237 // To reject an offered stream, the port number in the corresponding stream in
1238 // the answer MUST be set to zero.
1239 const std::string port = content_info->rejected ?
1240 kMediaPortRejected : kDefaultPort;
1242 talk_base::SSLFingerprint* fp = (transport_info) ?
1243 transport_info->description.identity_fingerprint.get() : NULL;
1245 InitLine(kLineTypeMedia, type, &os);
1246 os << " " << port << " " << media_desc->protocol() << fmt;
1247 AddLine(os.str(), message);
1249 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1250 if (transport_info) {
1252 // ice-pwd-att = "ice-pwd" ":" password
1253 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1255 InitAttrLine(kAttributeIceUfrag, &os);
1256 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1257 AddLine(os.str(), message);
1259 InitAttrLine(kAttributeIcePwd, &os);
1260 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1261 AddLine(os.str(), message);
1263 // draft-petithuguenin-mmusic-ice-attributes-level-03
1264 BuildIceOptions(transport_info->description.transport_options, message);
1267 // fingerprint-attribute =
1268 // "fingerprint" ":" hash-func SP fingerprint
1270 // Insert the fingerprint attribute.
1271 InitAttrLine(kAttributeFingerprint, &os);
1272 os << kSdpDelimiterColon
1273 << fp->algorithm << kSdpDelimiterSpace
1274 << fp->GetRfc4572Fingerprint();
1275 AddLine(os.str(), message);
1277 // Inserting setup attribute.
1278 if (transport_info->description.connection_role !=
1279 cricket::CONNECTIONROLE_NONE) {
1280 // Making sure we are not using "passive" mode.
1281 cricket::ConnectionRole role =
1282 transport_info->description.connection_role;
1283 std::string dtls_role_str;
1284 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
1285 InitAttrLine(kAttributeSetup, &os);
1286 os << kSdpDelimiterColon << dtls_role_str;
1287 AddLine(os.str(), message);
1293 // mid-attribute = "a=mid:" identification-tag
1294 // identification-tag = token
1295 // Use the content name as the mid identification-tag.
1296 InitAttrLine(kAttributeMid, &os);
1297 os << kSdpDelimiterColon << content_info->name;
1298 AddLine(os.str(), message);
1301 BuildSctpContentAttributes(message, sctp_port);
1303 BuildRtpContentAttributes(media_desc, media_type, message);
1307 void BuildSctpContentAttributes(std::string* message, int sctp_port) {
1308 // draft-ietf-mmusic-sctp-sdp-04
1309 // a=sctpmap:sctpmap-number protocol [streams]
1310 std::ostringstream os;
1311 InitAttrLine(kAttributeSctpmap, &os);
1312 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
1313 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1314 << (cricket::kMaxSctpSid + 1);
1315 AddLine(os.str(), message);
1318 void BuildRtpContentAttributes(
1319 const MediaContentDescription* media_desc,
1320 const MediaType media_type,
1321 std::string* message) {
1322 std::ostringstream os;
1324 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1325 // The definitions MUST be either all session level or all media level. This
1326 // implementation uses all media level.
1327 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1328 InitAttrLine(kAttributeExtmap, &os);
1329 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1330 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1331 AddLine(os.str(), message);
1335 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
1337 cricket::MediaContentDirection direction = media_desc->direction();
1338 if (media_desc->streams().empty() && direction == cricket::MD_SENDRECV) {
1339 direction = cricket::MD_RECVONLY;
1342 switch (direction) {
1343 case cricket::MD_INACTIVE:
1344 InitAttrLine(kAttributeInactive, &os);
1346 case cricket::MD_SENDONLY:
1347 InitAttrLine(kAttributeSendOnly, &os);
1349 case cricket::MD_RECVONLY:
1350 InitAttrLine(kAttributeRecvOnly, &os);
1352 case cricket::MD_SENDRECV:
1354 InitAttrLine(kAttributeSendRecv, &os);
1357 AddLine(os.str(), message);
1361 // We should always use the default bandwidth for RTP-based data
1362 // channels. Don't allow SDP to set the bandwidth, because that
1363 // would give JS the opportunity to "break the Internet".
1364 // TODO(pthatcher): But we need to temporarily allow the SDP to control
1365 // this for backwards-compatibility. Once we don't need that any
1366 // more, remove this.
1367 bool support_dc_sdp_bandwidth_temporarily = true;
1368 if (media_desc->bandwidth() >= 1000 &&
1369 (media_type != cricket::MEDIA_TYPE_DATA ||
1370 support_dc_sdp_bandwidth_temporarily)) {
1371 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1372 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1373 AddLine(os.str(), message);
1378 if (media_desc->rtcp_mux()) {
1379 InitAttrLine(kAttributeRtcpMux, &os);
1380 AddLine(os.str(), message);
1384 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1385 for (std::vector<CryptoParams>::const_iterator it =
1386 media_desc->cryptos().begin();
1387 it != media_desc->cryptos().end(); ++it) {
1388 InitAttrLine(kAttributeCrypto, &os);
1389 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1391 if (!it->session_params.empty()) {
1392 os << " " << it->session_params;
1394 AddLine(os.str(), message);
1398 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1399 // [/<encodingparameters>]
1400 BuildRtpMap(media_desc, media_type, message);
1402 // Specify latency for buffered mode.
1403 // a=x-google-buffer-latency:<value>
1404 if (media_desc->buffered_mode_latency() != cricket::kBufferedModeDisabled) {
1405 std::ostringstream os;
1406 InitAttrLine(kAttributeXGoogleBufferLatency, &os);
1407 os << kSdpDelimiterColon << media_desc->buffered_mode_latency();
1408 AddLine(os.str(), message);
1411 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1412 track != media_desc->streams().end(); ++track) {
1413 // Require that the track belongs to a media stream,
1414 // ie the sync_label is set. This extra check is necessary since the
1415 // MediaContentDescription always contains a streamparam with an ssrc even
1416 // if no track or media stream have been created.
1417 if (track->sync_label.empty()) continue;
1419 // Build the ssrc-group lines.
1420 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1422 // a=ssrc-group:<semantics> <ssrc-id> ...
1423 if (track->ssrc_groups[i].ssrcs.empty()) {
1426 std::ostringstream os;
1427 InitAttrLine(kAttributeSsrcGroup, &os);
1428 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
1429 std::vector<uint32>::const_iterator ssrc =
1430 track->ssrc_groups[i].ssrcs.begin();
1431 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
1432 os << kSdpDelimiterSpace << talk_base::ToString<uint32>(*ssrc);
1434 AddLine(os.str(), message);
1436 // Build the ssrc lines for each ssrc.
1437 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
1438 uint32 ssrc = track->ssrcs[i];
1440 // a=ssrc:<ssrc-id> cname:<value>
1441 AddSsrcLine(ssrc, kSsrcAttributeCname,
1442 track->cname, message);
1444 // draft-alvestrand-mmusic-msid-00
1445 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1446 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1447 // is corresponding to the "name" attribute of StreamParams.
1448 std::string appdata = track->id;
1449 std::ostringstream os;
1450 InitAttrLine(kAttributeSsrc, &os);
1451 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1452 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1453 << kSdpDelimiterSpace << appdata;
1454 AddLine(os.str(), message);
1456 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1457 // draft-alvestrand-rtcweb-mid-01
1458 // a=ssrc:<ssrc-id> mslabel:<value>
1459 // The label isn't yet defined.
1460 // a=ssrc:<ssrc-id> label:<value>
1461 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1462 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1467 void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1468 // fmtp header: a=fmtp:|payload_type| <parameters>
1470 InitAttrLine(kAttributeFmtp, os);
1471 // Add :|payload_type|
1472 *os << kSdpDelimiterColon << payload_type;
1475 void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1476 // rtcp-fb header: a=rtcp-fb:|payload_type|
1477 // <parameters>/<ccm <ccm_parameters>>
1479 InitAttrLine(kAttributeRtcpFb, os);
1481 *os << kSdpDelimiterColon;
1482 if (payload_type == kWildcardPayloadType) {
1485 *os << payload_type;
1489 void WriteFmtpParameter(const std::string& parameter_name,
1490 const std::string& parameter_value,
1491 std::ostringstream* os) {
1492 // fmtp parameters: |parameter_name|=|parameter_value|
1493 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1496 void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1497 std::ostringstream* os) {
1498 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1499 fmtp != parameters.end(); ++fmtp) {
1500 // Each new parameter, except the first one starts with ";" and " ".
1501 if (fmtp != parameters.begin()) {
1502 *os << kSdpDelimiterSemicolon;
1504 *os << kSdpDelimiterSpace;
1505 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1509 bool IsFmtpParam(const std::string& name) {
1510 const char* kFmtpParams[] = {
1511 kCodecParamMinPTime, kCodecParamSPropStereo,
1512 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamStartBitrate,
1513 kCodecParamMaxBitrate, kCodecParamMinBitrate, kCodecParamMaxQuantization,
1514 kCodecParamSctpProtocol, kCodecParamSctpStreams,
1515 kCodecParamMaxAverageBitrate
1517 for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
1518 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1525 // Retreives fmtp parameters from |params|, which may contain other parameters
1526 // as well, and puts them in |fmtp_parameters|.
1527 void GetFmtpParams(const cricket::CodecParameterMap& params,
1528 cricket::CodecParameterMap* fmtp_parameters) {
1529 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1530 iter != params.end(); ++iter) {
1531 if (IsFmtpParam(iter->first)) {
1532 (*fmtp_parameters)[iter->first] = iter->second;
1538 void AddFmtpLine(const T& codec, std::string* message) {
1539 cricket::CodecParameterMap fmtp_parameters;
1540 GetFmtpParams(codec.params, &fmtp_parameters);
1541 if (fmtp_parameters.empty()) {
1542 // No need to add an fmtp if it will have no (optional) parameters.
1545 std::ostringstream os;
1546 WriteFmtpHeader(codec.id, &os);
1547 WriteFmtpParameters(fmtp_parameters, &os);
1548 AddLine(os.str(), message);
1553 void AddRtcpFbLines(const T& codec, std::string* message) {
1554 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1555 codec.feedback_params.params().begin();
1556 iter != codec.feedback_params.params().end(); ++iter) {
1557 std::ostringstream os;
1558 WriteRtcpFbHeader(codec.id, &os);
1559 os << " " << iter->id();
1560 if (!iter->param().empty()) {
1561 os << " " << iter->param();
1563 AddLine(os.str(), message);
1567 bool GetMinValue(const std::vector<int>& values, int* value) {
1568 if (values.empty()) {
1571 std::vector<int>::const_iterator found =
1572 std::min_element(values.begin(), values.end());
1577 bool GetParameter(const std::string& name,
1578 const cricket::CodecParameterMap& params, int* value) {
1579 std::map<std::string, std::string>::const_iterator found =
1581 if (found == params.end()) {
1584 if (!talk_base::FromString(found->second, value)) {
1590 void BuildRtpMap(const MediaContentDescription* media_desc,
1591 const MediaType media_type,
1592 std::string* message) {
1593 ASSERT(message != NULL);
1594 ASSERT(media_desc != NULL);
1595 std::ostringstream os;
1596 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1597 const VideoContentDescription* video_desc =
1598 static_cast<const VideoContentDescription*>(media_desc);
1599 for (std::vector<cricket::VideoCodec>::const_iterator it =
1600 video_desc->codecs().begin();
1601 it != video_desc->codecs().end(); ++it) {
1603 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1604 // [/<encodingparameters>]
1605 if (it->id != kWildcardPayloadType) {
1606 InitAttrLine(kAttributeRtpmap, &os);
1607 os << kSdpDelimiterColon << it->id << " " << it->name
1608 << "/" << kDefaultVideoClockrate;
1609 AddLine(os.str(), message);
1611 AddRtcpFbLines(*it, message);
1612 AddFmtpLine(*it, message);
1614 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1615 const AudioContentDescription* audio_desc =
1616 static_cast<const AudioContentDescription*>(media_desc);
1617 std::vector<int> ptimes;
1618 std::vector<int> maxptimes;
1619 int max_minptime = 0;
1620 for (std::vector<cricket::AudioCodec>::const_iterator it =
1621 audio_desc->codecs().begin();
1622 it != audio_desc->codecs().end(); ++it) {
1623 ASSERT(!it->name.empty());
1625 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1626 // [/<encodingparameters>]
1627 InitAttrLine(kAttributeRtpmap, &os);
1628 os << kSdpDelimiterColon << it->id << " ";
1629 os << it->name << "/" << it->clockrate;
1630 if (it->channels != 1) {
1631 os << "/" << it->channels;
1633 AddLine(os.str(), message);
1634 AddRtcpFbLines(*it, message);
1635 AddFmtpLine(*it, message);
1637 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1638 max_minptime = std::max(minptime, max_minptime);
1641 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1642 ptimes.push_back(ptime);
1645 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1646 maxptimes.push_back(maxptime);
1649 // Populate the maxptime attribute with the smallest maxptime of all codecs
1650 // under the same m-line.
1651 int min_maxptime = INT_MAX;
1652 if (GetMinValue(maxptimes, &min_maxptime)) {
1653 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1655 ASSERT(min_maxptime > max_minptime);
1656 // Populate the ptime attribute with the smallest ptime or the largest
1657 // minptime, whichever is the largest, for all codecs under the same m-line.
1658 int ptime = INT_MAX;
1659 if (GetMinValue(ptimes, &ptime)) {
1660 ptime = std::min(ptime, min_maxptime);
1661 ptime = std::max(ptime, max_minptime);
1662 AddAttributeLine(kCodecParamPTime, ptime, message);
1664 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1665 const DataContentDescription* data_desc =
1666 static_cast<const DataContentDescription*>(media_desc);
1667 for (std::vector<cricket::DataCodec>::const_iterator it =
1668 data_desc->codecs().begin();
1669 it != data_desc->codecs().end(); ++it) {
1671 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1672 // [/<encodingparameters>]
1673 InitAttrLine(kAttributeRtpmap, &os);
1674 os << kSdpDelimiterColon << it->id << " "
1675 << it->name << "/" << it->clockrate;
1676 AddLine(os.str(), message);
1681 void BuildCandidate(const std::vector<Candidate>& candidates,
1682 std::string* message) {
1683 std::ostringstream os;
1685 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1686 it != candidates.end(); ++it) {
1688 // a=candidate:<foundation> <component-id> <transport> <priority>
1689 // <connection-address> <port> typ <candidate-types>
1690 // [raddr <connection-address>] [rport <port>]
1691 // *(SP extension-att-name SP extension-att-value)
1693 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1694 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1695 type = kCandidateHost;
1696 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1697 type = kCandidateSrflx;
1698 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1699 type = kCandidateRelay;
1704 InitAttrLine(kAttributeCandidate, &os);
1705 os << kSdpDelimiterColon
1706 << it->foundation() << " " << it->component() << " "
1707 << it->protocol() << " " << it->priority() << " "
1708 << it->address().ipaddr().ToString() << " "
1709 << it->address().PortAsString() << " "
1710 << kAttributeCandidateTyp << " " << type << " ";
1713 if (!it->related_address().IsNil()) {
1714 os << kAttributeCandidateRaddr << " "
1715 << it->related_address().ipaddr().ToString() << " "
1716 << kAttributeCandidateRport << " "
1717 << it->related_address().PortAsString() << " ";
1721 os << kAttributeCandidateGeneration << " " << it->generation();
1723 AddLine(os.str(), message);
1727 void BuildIceOptions(const std::vector<std::string>& transport_options,
1728 std::string* message) {
1729 if (!transport_options.empty()) {
1730 std::ostringstream os;
1731 InitAttrLine(kAttributeIceOption, &os);
1732 os << kSdpDelimiterColon << transport_options[0];
1733 for (size_t i = 1; i < transport_options.size(); ++i) {
1734 os << kSdpDelimiterSpace << transport_options[i];
1736 AddLine(os.str(), message);
1740 bool ParseSessionDescription(const std::string& message, size_t* pos,
1741 std::string* session_id,
1742 std::string* session_version,
1743 bool* supports_msid,
1744 TransportDescription* session_td,
1745 RtpHeaderExtensions* session_extmaps,
1746 cricket::SessionDescription* desc,
1747 SdpParseError* error) {
1751 // v= (protocol version)
1752 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1753 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1754 std::string(), error);
1757 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1758 // <unicast-address>
1759 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1760 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1761 std::string(), error);
1763 std::vector<std::string> fields;
1764 talk_base::split(line.substr(kLinePrefixLength),
1765 kSdpDelimiterSpace, &fields);
1766 const size_t expected_fields = 6;
1767 if (fields.size() != expected_fields) {
1768 return ParseFailedExpectFieldNum(line, expected_fields, error);
1770 *session_id = fields[1];
1771 *session_version = fields[2];
1774 // s= (session name)
1775 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1776 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1777 std::string(), error);
1781 // Those are the optional lines, so shouldn't return false if not present.
1783 // i=* (session information)
1784 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1787 // u=* (URI of description)
1788 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1791 // e=* (email address)
1792 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1795 // p=* (phone number)
1796 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1799 // c=* (connection information -- not required if included in
1801 GetLineWithType(message, pos, &line, kLineTypeConnection);
1804 // b=* (zero or more bandwidth information lines)
1805 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1806 // By pass zero or more b lines.
1810 // One or more time descriptions ("t=" and "r=" lines; see below)
1811 // t= (time the session is active)
1812 // r=* (zero or more repeat times)
1813 // Ensure there's at least one time description
1814 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1815 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1819 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1820 // By pass zero or more r lines.
1823 // Go through the rest of the time descriptions
1824 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1825 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1826 // By pass zero or more r lines.
1831 // z=* (time zone adjustments)
1832 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1835 // k=* (encryption key)
1836 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1839 // a=* (zero or more session attribute lines)
1840 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1841 if (HasAttribute(line, kAttributeGroup)) {
1842 if (!ParseGroupAttribute(line, desc, error)) {
1845 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1846 if (!GetValue(line, kAttributeIceUfrag,
1847 &(session_td->ice_ufrag), error)) {
1850 } else if (HasAttribute(line, kAttributeIcePwd)) {
1851 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1854 } else if (HasAttribute(line, kAttributeIceLite)) {
1855 session_td->ice_mode = cricket::ICEMODE_LITE;
1856 } else if (HasAttribute(line, kAttributeIceOption)) {
1857 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1860 } else if (HasAttribute(line, kAttributeFingerprint)) {
1861 if (session_td->identity_fingerprint.get()) {
1864 "Can't have multiple fingerprint attributes at the same level.",
1867 talk_base::SSLFingerprint* fingerprint = NULL;
1868 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1871 session_td->identity_fingerprint.reset(fingerprint);
1872 } else if (HasAttribute(line, kAttributeSetup)) {
1873 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1876 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1877 std::string semantics;
1878 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1881 *supports_msid = CaseInsensitiveFind(semantics, kMediaStreamSemantic);
1882 } else if (HasAttribute(line, kAttributeExtmap)) {
1883 RtpHeaderExtension extmap;
1884 if (!ParseExtmap(line, &extmap, error)) {
1887 session_extmaps->push_back(extmap);
1894 bool ParseGroupAttribute(const std::string& line,
1895 cricket::SessionDescription* desc,
1896 SdpParseError* error) {
1897 ASSERT(desc != NULL);
1899 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1900 // a=group:BUNDLE video voice
1901 std::vector<std::string> fields;
1902 talk_base::split(line.substr(kLinePrefixLength),
1903 kSdpDelimiterSpace, &fields);
1904 std::string semantics;
1905 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1908 cricket::ContentGroup group(semantics);
1909 for (size_t i = 1; i < fields.size(); ++i) {
1910 group.AddContentName(fields[i]);
1912 desc->AddGroup(group);
1916 static bool ParseFingerprintAttribute(const std::string& line,
1917 talk_base::SSLFingerprint** fingerprint,
1918 SdpParseError* error) {
1919 if (!IsLineType(line, kLineTypeAttributes) ||
1920 !HasAttribute(line, kAttributeFingerprint)) {
1921 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1922 kAttributeFingerprint, error);
1925 std::vector<std::string> fields;
1926 talk_base::split(line.substr(kLinePrefixLength),
1927 kSdpDelimiterSpace, &fields);
1928 const size_t expected_fields = 2;
1929 if (fields.size() != expected_fields) {
1930 return ParseFailedExpectFieldNum(line, expected_fields, error);
1933 // The first field here is "fingerprint:<hash>.
1934 std::string algorithm;
1935 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
1939 // Downcase the algorithm. Note that we don't need to downcase the
1940 // fingerprint because hex_decode can handle upper-case.
1941 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
1944 // The second field is the digest value. De-hexify it.
1945 *fingerprint = talk_base::SSLFingerprint::CreateFromRfc4572(
1946 algorithm, fields[1]);
1947 if (!*fingerprint) {
1948 return ParseFailed(line,
1949 "Failed to create fingerprint from the digest.",
1956 static bool ParseDtlsSetup(const std::string& line,
1957 cricket::ConnectionRole* role,
1958 SdpParseError* error) {
1959 // setup-attr = "a=setup:" role
1960 // role = "active" / "passive" / "actpass" / "holdconn"
1961 std::vector<std::string> fields;
1962 talk_base::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1963 const size_t expected_fields = 2;
1964 if (fields.size() != expected_fields) {
1965 return ParseFailedExpectFieldNum(line, expected_fields, error);
1967 std::string role_str = fields[1];
1968 if (!cricket::StringToConnectionRole(role_str, role)) {
1969 return ParseFailed(line, "Invalid attribute value.", error);
1975 // PT encoding media type clock rate channels
1983 // 6 DVI4 A 16,000 1
1987 // 10 L16 A 44,100 2
1988 // 11 L16 A 44,100 1
1989 // 12 QCELP A 8,000 1
1991 // 14 MPA A 90,000 (see text)
1992 // 15 G728 A 8,000 1
1993 // 16 DVI4 A 11,025 1
1994 // 17 DVI4 A 22,050 1
1995 // 18 G729 A 8,000 1
1996 struct StaticPayloadAudioCodec {
2001 static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2002 { "PCMU", 8000, 1 },
2003 { "reserved", 0, 0 },
2004 { "reserved", 0, 0 },
2006 { "G723", 8000, 1 },
2007 { "DVI4", 8000, 1 },
2008 { "DVI4", 16000, 1 },
2010 { "PCMA", 8000, 1 },
2011 { "G722", 8000, 1 },
2012 { "L16", 44100, 2 },
2013 { "L16", 44100, 1 },
2014 { "QCELP", 8000, 1 },
2016 { "MPA", 90000, 1 },
2017 { "G728", 8000, 1 },
2018 { "DVI4", 11025, 1 },
2019 { "DVI4", 22050, 1 },
2020 { "G729", 8000, 1 },
2023 void MaybeCreateStaticPayloadAudioCodecs(
2024 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2028 int preference = static_cast<int>(fmts.size());
2029 std::vector<int>::const_iterator it = fmts.begin();
2030 bool add_new_codec = false;
2031 for (; it != fmts.end(); ++it) {
2032 int payload_type = *it;
2033 if (!media_desc->HasCodec(payload_type) &&
2034 payload_type >= 0 &&
2035 payload_type < ARRAY_SIZE(kStaticPayloadAudioCodecs)) {
2036 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2037 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2038 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2039 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2040 clock_rate, 0, channels,
2042 add_new_codec = true;
2046 if (add_new_codec) {
2047 media_desc->SortCodecs();
2052 static C* ParseContentDescription(const std::string& message,
2053 const MediaType media_type,
2055 const std::string& protocol,
2056 const std::vector<int>& codec_preference,
2058 std::string* content_name,
2059 TransportDescription* transport,
2060 std::vector<JsepIceCandidate*>* candidates,
2061 webrtc::SdpParseError* error) {
2062 C* media_desc = new C();
2063 switch (media_type) {
2064 case cricket::MEDIA_TYPE_AUDIO:
2065 *content_name = cricket::CN_AUDIO;
2067 case cricket::MEDIA_TYPE_VIDEO:
2068 *content_name = cricket::CN_VIDEO;
2070 case cricket::MEDIA_TYPE_DATA:
2071 *content_name = cricket::CN_DATA;
2077 if (!ParseContent(message, media_type, mline_index, protocol,
2078 codec_preference, pos, content_name,
2079 media_desc, transport, candidates, error)) {
2083 // Sort the codecs according to the m-line fmt list.
2084 media_desc->SortCodecs();
2088 bool ParseMediaDescription(const std::string& message,
2089 const TransportDescription& session_td,
2090 const RtpHeaderExtensions& session_extmaps,
2093 cricket::SessionDescription* desc,
2094 std::vector<JsepIceCandidate*>* candidates,
2095 SdpParseError* error) {
2096 ASSERT(desc != NULL);
2098 int mline_index = -1;
2100 // Zero or more media descriptions
2102 // m=<media> <port> <proto> <fmt>
2103 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2106 std::vector<std::string> fields;
2107 talk_base::split(line.substr(kLinePrefixLength),
2108 kSdpDelimiterSpace, &fields);
2109 const size_t expected_min_fields = 4;
2110 if (fields.size() < expected_min_fields) {
2111 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2113 bool rejected = false;
2115 // To reject an offered stream, the port number in the corresponding stream
2116 // in the answer MUST be set to zero.
2117 if (fields[1] == kMediaPortRejected) {
2121 std::string protocol = fields[2];
2122 bool is_sctp = (protocol == cricket::kMediaProtocolDtlsSctp);
2125 std::vector<int> codec_preference;
2126 for (size_t j = 3 ; j < fields.size(); ++j) {
2127 // TODO(wu): Remove when below bug is fixed.
2128 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
2129 if (fields[j] == "" && j == fields.size() - 1) {
2134 if (!GetValueFromString(line, fields[j], &pl, error)) {
2137 codec_preference.push_back(pl);
2140 // Make a temporary TransportDescription based on |session_td|.
2141 // Some of this gets overwritten by ParseContent.
2142 TransportDescription transport(NS_JINGLE_ICE_UDP,
2143 session_td.transport_options,
2144 session_td.ice_ufrag,
2146 session_td.ice_mode,
2147 session_td.connection_role,
2148 session_td.identity_fingerprint.get(),
2151 talk_base::scoped_ptr<MediaContentDescription> content;
2152 std::string content_name;
2153 if (HasAttribute(line, kMediaTypeVideo)) {
2154 content.reset(ParseContentDescription<VideoContentDescription>(
2155 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2156 codec_preference, pos, &content_name,
2157 &transport, candidates, error));
2158 } else if (HasAttribute(line, kMediaTypeAudio)) {
2159 content.reset(ParseContentDescription<AudioContentDescription>(
2160 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2161 codec_preference, pos, &content_name,
2162 &transport, candidates, error));
2163 } else if (HasAttribute(line, kMediaTypeData)) {
2164 DataContentDescription* desc =
2165 ParseContentDescription<DataContentDescription>(
2166 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2167 codec_preference, pos, &content_name,
2168 &transport, candidates, error);
2170 if (desc && protocol == cricket::kMediaProtocolDtlsSctp) {
2171 // Add the SCTP Port number as a pseudo-codec "port" parameter
2172 cricket::DataCodec codec_port(
2173 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
2175 codec_port.SetParam(cricket::kCodecParamPort, fields[3]);
2176 LOG(INFO) << "ParseMediaDescription: Got SCTP Port Number "
2178 ASSERT(!desc->HasCodec(cricket::kGoogleSctpDataCodecId));
2179 desc->AddCodec(codec_port);
2182 content.reset(desc);
2184 // We should always use the default bandwidth for RTP-based data
2185 // channels. Don't allow SDP to set the bandwidth, because that
2186 // would give JS the opportunity to "break the Internet".
2187 // TODO(pthatcher): But we need to temporarily allow the SDP to control
2188 // this for backwards-compatibility. Once we don't need that any
2189 // more, remove this.
2190 bool support_dc_sdp_bandwidth_temporarily = true;
2191 if (content.get() && !support_dc_sdp_bandwidth_temporarily) {
2192 content->set_bandwidth(cricket::kAutoBandwidth);
2195 LOG(LS_WARNING) << "Unsupported media type: " << line;
2198 if (!content.get()) {
2199 // ParseContentDescription returns NULL if failed.
2204 // Make sure to set the media direction correctly. If the direction is not
2205 // MD_RECVONLY or Inactive and no streams are parsed,
2206 // a default MediaStream will be created to prepare for receiving media.
2207 if (supports_msid && content->streams().empty() &&
2208 content->direction() == cricket::MD_SENDRECV) {
2209 content->set_direction(cricket::MD_RECVONLY);
2213 if (!session_extmaps.empty() &&
2214 !content->rtp_header_extensions().empty()) {
2215 return ParseFailed("",
2216 "The a=extmap MUST be either all session level or "
2220 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2221 content->AddRtpHeaderExtension(session_extmaps[i]);
2224 content->set_protocol(protocol);
2225 desc->AddContent(content_name,
2226 is_sctp ? cricket::NS_JINGLE_DRAFT_SCTP :
2227 cricket::NS_JINGLE_RTP,
2230 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2231 TransportInfo transport_info(content_name, transport);
2233 if (!desc->AddTransportInfo(transport_info)) {
2234 std::ostringstream description;
2235 description << "Failed to AddTransportInfo with content name: "
2237 return ParseFailed("", description.str(), error);
2241 size_t end_of_message = message.size();
2242 if (mline_index == -1 && *pos != end_of_message) {
2243 ParseFailed(message, *pos, "Expects m line.", error);
2249 bool VerifyCodec(const cricket::Codec& codec) {
2250 // Codec has not been populated correctly unless the name has been set. This
2251 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2252 // have a corresponding "rtpmap" line.
2253 cricket::Codec default_codec;
2254 return default_codec.name != codec.name;
2257 bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2258 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2259 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2260 iter != codecs.end(); ++iter) {
2261 if (!VerifyCodec(*iter)) {
2268 bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2269 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2270 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2271 iter != codecs.end(); ++iter) {
2272 if (!VerifyCodec(*iter)) {
2279 void AddParameters(const cricket::CodecParameterMap& parameters,
2280 cricket::Codec* codec) {
2281 for (cricket::CodecParameterMap::const_iterator iter =
2282 parameters.begin(); iter != parameters.end(); ++iter) {
2283 codec->SetParam(iter->first, iter->second);
2287 void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2288 cricket::Codec* codec) {
2289 codec->AddFeedbackParam(feedback_param);
2292 void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2293 cricket::Codec* codec) {
2294 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2295 feedback_params.params().begin();
2296 iter != feedback_params.params().end(); ++iter) {
2297 codec->AddFeedbackParam(*iter);
2301 // Gets the current codec setting associated with |payload_type|. If there
2302 // is no AudioCodec associated with that payload type it returns an empty codec
2303 // with that payload type.
2305 T GetCodec(const std::vector<T>& codecs, int payload_type) {
2306 for (typename std::vector<T>::const_iterator codec = codecs.begin();
2307 codec != codecs.end(); ++codec) {
2308 if (codec->id == payload_type) {
2313 ret_val.id = payload_type;
2317 // Updates or creates a new codec entry in the audio description.
2318 template <class T, class U>
2319 void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2320 T* desc = static_cast<T*>(content_desc);
2321 std::vector<U> codecs = desc->codecs();
2324 typename std::vector<U>::iterator iter;
2325 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2326 if (iter->id == codec.id) {
2333 desc->AddCodec(codec);
2336 desc->set_codecs(codecs);
2339 // Adds or updates existing codec corresponding to |payload_type| according
2341 template <class T, class U>
2342 void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2343 const cricket::CodecParameterMap& parameters) {
2344 // Codec might already have been populated (from rtpmap).
2345 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2346 AddParameters(parameters, &new_codec);
2347 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2350 // Adds or updates existing codec corresponding to |payload_type| according
2351 // to |feedback_param|.
2352 template <class T, class U>
2353 void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2354 const cricket::FeedbackParam& feedback_param) {
2355 // Codec might already have been populated (from rtpmap).
2356 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2357 AddFeedbackParameter(feedback_param, &new_codec);
2358 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2361 bool PopWildcardCodec(std::vector<cricket::VideoCodec>* codecs,
2362 cricket::VideoCodec* wildcard_codec) {
2363 for (std::vector<cricket::VideoCodec>::iterator iter = codecs->begin();
2364 iter != codecs->end(); ++iter) {
2365 if (iter->id == kWildcardPayloadType) {
2366 *wildcard_codec = *iter;
2367 codecs->erase(iter);
2374 void UpdateFromWildcardVideoCodecs(VideoContentDescription* video_desc) {
2375 std::vector<cricket::VideoCodec> codecs = video_desc->codecs();
2376 cricket::VideoCodec wildcard_codec;
2377 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2380 for (std::vector<cricket::VideoCodec>::iterator iter = codecs.begin();
2381 iter != codecs.end(); ++iter) {
2382 cricket::VideoCodec& codec = *iter;
2383 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2385 video_desc->set_codecs(codecs);
2388 void AddAudioAttribute(const std::string& name, const std::string& value,
2389 AudioContentDescription* audio_desc) {
2390 if (value.empty()) {
2393 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2394 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2395 iter != codecs.end(); ++iter) {
2396 iter->params[name] = value;
2398 audio_desc->set_codecs(codecs);
2401 bool ParseContent(const std::string& message,
2402 const MediaType media_type,
2404 const std::string& protocol,
2405 const std::vector<int>& codec_preference,
2407 std::string* content_name,
2408 MediaContentDescription* media_desc,
2409 TransportDescription* transport,
2410 std::vector<JsepIceCandidate*>* candidates,
2411 SdpParseError* error) {
2412 ASSERT(media_desc != NULL);
2413 ASSERT(content_name != NULL);
2414 ASSERT(transport != NULL);
2416 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2417 MaybeCreateStaticPayloadAudioCodecs(
2418 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2421 // The media level "ice-ufrag" and "ice-pwd".
2422 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2423 Candidates candidates_orig;
2425 std::string mline_id;
2426 // Tracks created out of the ssrc attributes.
2427 StreamParamsVec tracks;
2428 SsrcInfoVec ssrc_infos;
2429 SsrcGroupVec ssrc_groups;
2430 std::string maxptime_as_string;
2431 std::string ptime_as_string;
2435 talk_base::starts_with(protocol.data(),
2436 cricket::kMediaProtocolRtpPrefix);
2438 // Loop until the next m line
2439 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2440 if (!GetLine(message, pos, &line)) {
2441 if (*pos >= message.size()) {
2442 break; // Done parsing
2444 return ParseFailed(message, *pos, "Invalid SDP line.", error);
2449 // b=* (zero or more bandwidth information lines)
2450 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2451 std::string bandwidth;
2452 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2453 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2457 if (!GetValueFromString(line, bandwidth, &b, error)) {
2460 media_desc->set_bandwidth(b * 1000);
2466 if (!IsLineType(line, kLineTypeAttributes)) {
2467 // TODO: Handle other lines if needed.
2468 LOG(LS_INFO) << "Ignored line: " << line;
2472 // Handle attributes common to SCTP and RTP.
2473 if (HasAttribute(line, kAttributeMid)) {
2475 // mid-attribute = "a=mid:" identification-tag
2476 // identification-tag = token
2477 // Use the mid identification-tag as the content name.
2478 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2481 *content_name = mline_id;
2482 } else if (HasAttribute(line, kAttributeCandidate)) {
2483 Candidate candidate;
2484 if (!ParseCandidate(line, &candidate, error, false)) {
2487 candidates_orig.push_back(candidate);
2488 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2489 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2492 } else if (HasAttribute(line, kAttributeIcePwd)) {
2493 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2496 } else if (HasAttribute(line, kAttributeIceOption)) {
2497 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2500 } else if (HasAttribute(line, kAttributeFmtp)) {
2501 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2504 } else if (HasAttribute(line, kAttributeFingerprint)) {
2505 talk_base::SSLFingerprint* fingerprint = NULL;
2507 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2510 transport->identity_fingerprint.reset(fingerprint);
2511 } else if (HasAttribute(line, kAttributeSetup)) {
2512 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2515 } else if (is_rtp) {
2517 // RTP specific attrubtes
2519 if (HasAttribute(line, kAttributeRtcpMux)) {
2520 media_desc->set_rtcp_mux(true);
2521 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2522 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2525 } else if (HasAttribute(line, kAttributeSsrc)) {
2526 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2529 } else if (HasAttribute(line, kAttributeCrypto)) {
2530 if (!ParseCryptoAttribute(line, media_desc, error)) {
2533 } else if (HasAttribute(line, kAttributeRtpmap)) {
2534 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2535 media_desc, error)) {
2538 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2539 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2542 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2543 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2546 } else if (HasAttribute(line, kCodecParamPTime)) {
2547 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2550 } else if (HasAttribute(line, kAttributeSendOnly)) {
2551 media_desc->set_direction(cricket::MD_SENDONLY);
2552 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2553 media_desc->set_direction(cricket::MD_RECVONLY);
2554 } else if (HasAttribute(line, kAttributeInactive)) {
2555 media_desc->set_direction(cricket::MD_INACTIVE);
2556 } else if (HasAttribute(line, kAttributeSendRecv)) {
2557 media_desc->set_direction(cricket::MD_SENDRECV);
2558 } else if (HasAttribute(line, kAttributeExtmap)) {
2559 RtpHeaderExtension extmap;
2560 if (!ParseExtmap(line, &extmap, error)) {
2563 media_desc->AddRtpHeaderExtension(extmap);
2564 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2565 // Experimental attribute. Conference mode activates more aggressive
2566 // AEC and NS settings.
2567 // TODO: expose API to set these directly.
2568 std::string flag_value;
2569 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2572 if (flag_value.compare(kValueConference) == 0)
2573 media_desc->set_conference_mode(true);
2574 } else if (HasAttribute(line, kAttributeXGoogleBufferLatency)) {
2575 // Experimental attribute.
2576 // TODO: expose API to set this directly.
2577 std::string flag_value;
2578 if (!GetValue(line, kAttributeXGoogleBufferLatency, &flag_value,
2582 int buffer_latency = 0;
2583 if (!GetValueFromString(line, flag_value, &buffer_latency, error)) {
2586 if (buffer_latency < 0) {
2587 return ParseFailed(line, "Buffer latency less than 0.", error);
2589 media_desc->set_buffered_mode_latency(buffer_latency);
2592 // Only parse lines that we are interested of.
2593 LOG(LS_INFO) << "Ignored line: " << line;
2598 // Create tracks from the |ssrc_infos|.
2599 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2601 // Add the ssrc group to the track.
2602 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2603 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2604 if (ssrc_group->ssrcs.empty()) {
2607 uint32 ssrc = ssrc_group->ssrcs.front();
2608 for (StreamParamsVec::iterator track = tracks.begin();
2609 track != tracks.end(); ++track) {
2610 if (track->has_ssrc(ssrc)) {
2611 track->ssrc_groups.push_back(*ssrc_group);
2616 // Add the new tracks to the |media_desc|.
2617 for (StreamParamsVec::iterator track = tracks.begin();
2618 track != tracks.end(); ++track) {
2619 media_desc->AddStream(*track);
2622 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2623 AudioContentDescription* audio_desc =
2624 static_cast<AudioContentDescription*>(media_desc);
2625 // Verify audio codec ensures that no audio codec has been populated with
2627 if (!VerifyAudioCodecs(audio_desc)) {
2628 return ParseFailed("Failed to parse audio codecs correctly.", error);
2630 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2631 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2634 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2635 VideoContentDescription* video_desc =
2636 static_cast<VideoContentDescription*>(media_desc);
2637 UpdateFromWildcardVideoCodecs(video_desc);
2638 // Verify video codec ensures that no video codec has been populated with
2640 if (!VerifyVideoCodecs(video_desc)) {
2641 return ParseFailed("Failed to parse video codecs correctly.", error);
2646 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2647 for (Candidates::iterator it = candidates_orig.begin();
2648 it != candidates_orig.end(); ++it) {
2649 ASSERT((*it).username().empty());
2650 (*it).set_username(transport->ice_ufrag);
2651 ASSERT((*it).password().empty());
2652 (*it).set_password(transport->ice_pwd);
2653 candidates->push_back(
2654 new JsepIceCandidate(mline_id, mline_index, *it));
2659 bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2660 SdpParseError* error) {
2661 ASSERT(ssrc_infos != NULL);
2663 // a=ssrc:<ssrc-id> <attribute>
2664 // a=ssrc:<ssrc-id> <attribute>:<value>
2665 std::string field1, field2;
2666 if (!SplitByDelimiter(line.substr(kLinePrefixLength),
2670 const size_t expected_fields = 2;
2671 return ParseFailedExpectFieldNum(line, expected_fields, error);
2675 std::string ssrc_id_s;
2676 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2680 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2684 std::string attribute;
2686 if (!SplitByDelimiter(field2, kSdpDelimiterColon,
2687 &attribute, &value)) {
2688 std::ostringstream description;
2689 description << "Failed to get the ssrc attribute value from " << field2
2690 << ". Expected format <attribute>:<value>.";
2691 return ParseFailed(line, description.str(), error);
2694 // Check if there's already an item for this |ssrc_id|. Create a new one if
2696 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2697 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2698 if (ssrc_info->ssrc_id == ssrc_id) {
2702 if (ssrc_info == ssrc_infos->end()) {
2704 info.ssrc_id = ssrc_id;
2705 ssrc_infos->push_back(info);
2706 ssrc_info = ssrc_infos->end() - 1;
2709 // Store the info to the |ssrc_info|.
2710 if (attribute == kSsrcAttributeCname) {
2713 ssrc_info->cname = value;
2714 } else if (attribute == kSsrcAttributeMsid) {
2715 // draft-alvestrand-mmusic-msid-00
2716 // "msid:" identifier [ " " appdata ]
2717 std::vector<std::string> fields;
2718 talk_base::split(value, kSdpDelimiterSpace, &fields);
2719 if (fields.size() < 1 || fields.size() > 2) {
2720 return ParseFailed(line,
2721 "Expected format \"msid:<identifier>[ <appdata>]\".",
2724 ssrc_info->msid_identifier = fields[0];
2725 if (fields.size() == 2) {
2726 ssrc_info->msid_appdata = fields[1];
2728 } else if (attribute == kSsrcAttributeMslabel) {
2729 // draft-alvestrand-rtcweb-mid-01
2731 ssrc_info->mslabel = value;
2732 } else if (attribute == kSSrcAttributeLabel) {
2733 // The label isn't defined.
2735 ssrc_info->label = value;
2740 bool ParseSsrcGroupAttribute(const std::string& line,
2741 SsrcGroupVec* ssrc_groups,
2742 SdpParseError* error) {
2743 ASSERT(ssrc_groups != NULL);
2745 // a=ssrc-group:<semantics> <ssrc-id> ...
2746 std::vector<std::string> fields;
2747 talk_base::split(line.substr(kLinePrefixLength),
2748 kSdpDelimiterSpace, &fields);
2749 const size_t expected_min_fields = 2;
2750 if (fields.size() < expected_min_fields) {
2751 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2753 std::string semantics;
2754 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2757 std::vector<uint32> ssrcs;
2758 for (size_t i = 1; i < fields.size(); ++i) {
2760 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2763 ssrcs.push_back(ssrc);
2765 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2769 bool ParseCryptoAttribute(const std::string& line,
2770 MediaContentDescription* media_desc,
2771 SdpParseError* error) {
2772 std::vector<std::string> fields;
2773 talk_base::split(line.substr(kLinePrefixLength),
2774 kSdpDelimiterSpace, &fields);
2776 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2777 const size_t expected_min_fields = 3;
2778 if (fields.size() < expected_min_fields) {
2779 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2781 std::string tag_value;
2782 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2786 if (!GetValueFromString(line, tag_value, &tag, error)) {
2789 const std::string crypto_suite = fields[1];
2790 const std::string key_params = fields[2];
2791 std::string session_params;
2792 if (fields.size() > 3) {
2793 session_params = fields[3];
2795 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2800 // Updates or creates a new codec entry in the audio description with according
2801 // to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2802 void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2803 int bitrate, int channels, int preference,
2804 AudioContentDescription* audio_desc) {
2805 // Codec may already be populated with (only) optional parameters
2807 cricket::AudioCodec codec = GetCodec(audio_desc->codecs(), payload_type);
2809 codec.clockrate = clockrate;
2810 codec.bitrate = bitrate;
2811 codec.channels = channels;
2812 codec.preference = preference;
2813 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2817 // Updates or creates a new codec entry in the video description according to
2818 // |name|, |width|, |height|, |framerate| and |preference|.
2819 void UpdateCodec(int payload_type, const std::string& name, int width,
2820 int height, int framerate, int preference,
2821 VideoContentDescription* video_desc) {
2822 // Codec may already be populated with (only) optional parameters
2824 cricket::VideoCodec codec = GetCodec(video_desc->codecs(), payload_type);
2826 codec.width = width;
2827 codec.height = height;
2828 codec.framerate = framerate;
2829 codec.preference = preference;
2830 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2834 bool ParseRtpmapAttribute(const std::string& line,
2835 const MediaType media_type,
2836 const std::vector<int>& codec_preference,
2837 MediaContentDescription* media_desc,
2838 SdpParseError* error) {
2839 std::vector<std::string> fields;
2840 talk_base::split(line.substr(kLinePrefixLength),
2841 kSdpDelimiterSpace, &fields);
2843 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2844 const size_t expected_min_fields = 2;
2845 if (fields.size() < expected_min_fields) {
2846 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2848 std::string payload_type_value;
2849 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2852 int payload_type = 0;
2853 if (!GetValueFromString(line, payload_type_value, &payload_type, error)) {
2857 // Set the preference order depending on the order of the pl type in the
2858 // <fmt> of the m-line.
2859 const int preference = codec_preference.end() -
2860 std::find(codec_preference.begin(), codec_preference.end(),
2862 if (preference == 0) {
2863 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2864 << "<fmt> of the m-line: " << line;
2867 const std::string encoder = fields[1];
2868 std::vector<std::string> codec_params;
2869 talk_base::split(encoder, '/', &codec_params);
2870 // <encoding name>/<clock rate>[/<encodingparameters>]
2871 // 2 mandatory fields
2872 if (codec_params.size() < 2 || codec_params.size() > 3) {
2873 return ParseFailed(line,
2874 "Expected format \"<encoding name>/<clock rate>"
2875 "[/<encodingparameters>]\".",
2878 const std::string encoding_name = codec_params[0];
2880 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2883 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2884 VideoContentDescription* video_desc =
2885 static_cast<VideoContentDescription*>(media_desc);
2886 // TODO: We will send resolution in SDP. For now use
2887 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2888 UpdateCodec(payload_type, encoding_name,
2889 JsepSessionDescription::kMaxVideoCodecWidth,
2890 JsepSessionDescription::kMaxVideoCodecHeight,
2891 JsepSessionDescription::kDefaultVideoCodecFramerate,
2892 preference, video_desc);
2893 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2895 // For audio streams, <encoding parameters> indicates the number
2896 // of audio channels. This parameter is OPTIONAL and may be
2897 // omitted if the number of channels is one, provided that no
2898 // additional parameters are needed.
2900 if (codec_params.size() == 3) {
2901 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2906 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2907 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2908 // The bandwidth adaptation doesn't always work well, so this code
2909 // sets a fixed target bitrate instead.
2910 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2911 if (clock_rate <= 16000) {
2912 bitrate = kIsacWbDefaultRate;
2914 bitrate = kIsacSwbDefaultRate;
2917 AudioContentDescription* audio_desc =
2918 static_cast<AudioContentDescription*>(media_desc);
2919 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2920 preference, audio_desc);
2921 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2922 DataContentDescription* data_desc =
2923 static_cast<DataContentDescription*>(media_desc);
2924 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2930 void PruneRight(const char delimiter, std::string* message) {
2931 size_t trailing = message->find(delimiter);
2932 if (trailing != std::string::npos) {
2933 *message = message->substr(0, trailing);
2937 bool ParseFmtpParam(const std::string& line, std::string* parameter,
2938 std::string* value, SdpParseError* error) {
2939 if (!SplitByDelimiter(line, kSdpDelimiterEqual, parameter, value)) {
2940 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2943 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
2944 // When parsing the values the trailing ";" gets picked up. Remove them.
2945 PruneRight(kSdpDelimiterSemicolon, value);
2949 bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
2950 MediaContentDescription* media_desc,
2951 SdpParseError* error) {
2952 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2953 media_type != cricket::MEDIA_TYPE_VIDEO) {
2956 std::vector<std::string> fields;
2957 talk_base::split(line.substr(kLinePrefixLength),
2958 kSdpDelimiterSpace, &fields);
2961 // a=fmtp:<format> <format specific parameters>
2962 // At least two fields, whereas the second one is any of the optional
2964 if (fields.size() < 2) {
2965 ParseFailedExpectMinFieldNum(line, 2, error);
2969 std::string payload_type;
2970 if (!GetValue(fields[0], kAttributeFmtp, &payload_type, error)) {
2974 cricket::CodecParameterMap codec_params;
2975 for (std::vector<std::string>::const_iterator iter = fields.begin() + 1;
2976 iter != fields.end(); ++iter) {
2979 if (iter->find(kSdpDelimiterEqual) == std::string::npos) {
2980 // Only fmtps with equals are currently supported. Other fmtp types
2981 // should be ignored. Unknown fmtps do not constitute an error.
2984 if (!ParseFmtpParam(*iter, &name, &value, error)) {
2987 codec_params[name] = value;
2990 int int_payload_type = 0;
2991 if (!GetValueFromString(line, payload_type, &int_payload_type, error)) {
2994 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2995 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
2996 media_desc, int_payload_type, codec_params);
2997 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2998 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
2999 media_desc, int_payload_type, codec_params);
3004 bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3005 MediaContentDescription* media_desc,
3006 SdpParseError* error) {
3007 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3008 media_type != cricket::MEDIA_TYPE_VIDEO) {
3011 std::vector<std::string> rtcp_fb_fields;
3012 talk_base::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
3013 if (rtcp_fb_fields.size() < 2) {
3014 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3016 std::string payload_type_string;
3017 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3021 int payload_type = kWildcardPayloadType;
3022 if (payload_type_string != "*") {
3023 if (!GetValueFromString(line, payload_type_string, &payload_type, error)) {
3027 std::string id = rtcp_fb_fields[1];
3028 std::string param = "";
3029 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3030 iter != rtcp_fb_fields.end(); ++iter) {
3031 param.append(*iter);
3033 const cricket::FeedbackParam feedback_param(id, param);
3035 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3036 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(media_desc,
3039 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3040 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(media_desc,
3047 } // namespace webrtc