blob: a93977d6d984310cf154643dcdd4715f46a55529 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00003 * Copyright 2011 Google Inc.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/app/webrtc/webrtcsdp.h"
29
30#include <limits.h>
31#include <stdio.h>
32#include <algorithm>
33#include <string>
34#include <vector>
decurtis@webrtc.org8af11042015-01-07 19:15:51 +000035#include <ctype.h>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000036
37#include "talk/app/webrtc/jsepicecandidate.h"
38#include "talk/app/webrtc/jsepsessiondescription.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000039#include "talk/media/base/codec.h"
40#include "talk/media/base/constants.h"
41#include "talk/media/base/cryptoparams.h"
pkasting@chromium.orge9facf82015-02-17 20:36:28 +000042#include "talk/media/base/rtputils.h"
mallinath@webrtc.org1112c302013-09-23 20:34:45 +000043#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000044#include "webrtc/p2p/base/candidate.h"
45#include "webrtc/p2p/base/constants.h"
46#include "webrtc/p2p/base/port.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000047#include "talk/session/media/mediasession.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000048#include "webrtc/base/common.h"
49#include "webrtc/base/logging.h"
50#include "webrtc/base/messagedigest.h"
51#include "webrtc/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052
53using cricket::AudioContentDescription;
54using cricket::Candidate;
55using cricket::Candidates;
56using cricket::ContentDescription;
57using cricket::ContentInfo;
58using cricket::CryptoParams;
59using cricket::DataContentDescription;
60using cricket::ICE_CANDIDATE_COMPONENT_RTP;
61using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
62using cricket::kCodecParamMaxBitrate;
63using cricket::kCodecParamMaxPTime;
64using cricket::kCodecParamMaxQuantization;
65using cricket::kCodecParamMinBitrate;
66using cricket::kCodecParamMinPTime;
67using cricket::kCodecParamPTime;
68using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000069using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070using cricket::kCodecParamStereo;
71using cricket::kCodecParamUseInbandFec;
Minyue Li7100dcd2015-03-27 05:05:59 +010072using cricket::kCodecParamUseDtx;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073using cricket::kCodecParamSctpProtocol;
74using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000075using cricket::kCodecParamMaxAverageBitrate;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000076using cricket::kCodecParamMaxPlaybackRate;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000077using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000078using cricket::MediaContentDescription;
79using cricket::MediaType;
80using cricket::NS_JINGLE_ICE_UDP;
81using cricket::RtpHeaderExtension;
82using cricket::SsrcGroup;
83using cricket::StreamParams;
84using cricket::StreamParamsVec;
85using cricket::TransportDescription;
86using cricket::TransportInfo;
87using cricket::VideoContentDescription;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000088using rtc::SocketAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089
90typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
91
92namespace cricket {
93class SessionDescription;
94}
95
96namespace webrtc {
97
98// Line type
99// RFC 4566
100// An SDP session description consists of a number of lines of text of
101// the form:
102// <type>=<value>
103// where <type> MUST be exactly one case-significant character.
104static const int kLinePrefixLength = 2; // Lenght of <type>=
105static const char kLineTypeVersion = 'v';
106static const char kLineTypeOrigin = 'o';
107static const char kLineTypeSessionName = 's';
108static const char kLineTypeSessionInfo = 'i';
109static const char kLineTypeSessionUri = 'u';
110static const char kLineTypeSessionEmail = 'e';
111static const char kLineTypeSessionPhone = 'p';
112static const char kLineTypeSessionBandwidth = 'b';
113static const char kLineTypeTiming = 't';
114static const char kLineTypeRepeatTimes = 'r';
115static const char kLineTypeTimeZone = 'z';
116static const char kLineTypeEncryptionKey = 'k';
117static const char kLineTypeMedia = 'm';
118static const char kLineTypeConnection = 'c';
119static const char kLineTypeAttributes = 'a';
120
121// Attributes
122static const char kAttributeGroup[] = "group";
123static const char kAttributeMid[] = "mid";
124static const char kAttributeRtcpMux[] = "rtcp-mux";
125static const char kAttributeSsrc[] = "ssrc";
126static const char kSsrcAttributeCname[] = "cname";
127static const char kAttributeExtmap[] = "extmap";
128// draft-alvestrand-mmusic-msid-01
129// a=msid-semantic: WMS
130static const char kAttributeMsidSemantics[] = "msid-semantic";
131static const char kMediaStreamSemantic[] = "WMS";
132static const char kSsrcAttributeMsid[] = "msid";
133static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134static const char kSsrcAttributeMslabel[] = "mslabel";
135static const char kSSrcAttributeLabel[] = "label";
136static const char kAttributeSsrcGroup[] = "ssrc-group";
137static const char kAttributeCrypto[] = "crypto";
138static const char kAttributeCandidate[] = "candidate";
139static const char kAttributeCandidateTyp[] = "typ";
140static const char kAttributeCandidateRaddr[] = "raddr";
141static const char kAttributeCandidateRport[] = "rport";
142static const char kAttributeCandidateUsername[] = "username";
143static const char kAttributeCandidatePassword[] = "password";
144static const char kAttributeCandidateGeneration[] = "generation";
145static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000146static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000147static const char kAttributeFmtp[] = "fmtp";
148static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000149static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000150static const char kAttributeRtcp[] = "rtcp";
151static const char kAttributeIceUfrag[] = "ice-ufrag";
152static const char kAttributeIcePwd[] = "ice-pwd";
153static const char kAttributeIceLite[] = "ice-lite";
154static const char kAttributeIceOption[] = "ice-options";
155static const char kAttributeSendOnly[] = "sendonly";
156static const char kAttributeRecvOnly[] = "recvonly";
157static const char kAttributeRtcpFb[] = "rtcp-fb";
158static const char kAttributeSendRecv[] = "sendrecv";
159static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000160// draft-ietf-mmusic-sctp-sdp-07
161// a=sctp-port
162static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000163
164// Experimental flags
165static const char kAttributeXGoogleFlag[] = "x-google-flag";
166static const char kValueConference[] = "conference";
167static const char kAttributeXGoogleBufferLatency[] =
168 "x-google-buffer-latency";
169
170// Candidate
171static const char kCandidateHost[] = "host";
172static const char kCandidateSrflx[] = "srflx";
173// TODO: How to map the prflx with circket candidate type
174// static const char kCandidatePrflx[] = "prflx";
175static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000176static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000177
178static const char kSdpDelimiterEqual = '=';
179static const char kSdpDelimiterSpace = ' ';
180static const char kSdpDelimiterColon = ':';
181static const char kSdpDelimiterSemicolon = ';';
182static const char kSdpDelimiterSlash = '/';
183static const char kNewLine = '\n';
184static const char kReturn = '\r';
185static const char kLineBreak[] = "\r\n";
186
187// TODO: Generate the Session and Time description
188// instead of hardcoding.
189static const char kSessionVersion[] = "v=0";
190// RFC 4566
191static const char kSessionOriginUsername[] = "-";
192static const char kSessionOriginSessionId[] = "0";
193static const char kSessionOriginSessionVersion[] = "0";
194static const char kSessionOriginNettype[] = "IN";
195static const char kSessionOriginAddrtype[] = "IP4";
196static const char kSessionOriginAddress[] = "127.0.0.1";
197static const char kSessionName[] = "s=-";
198static const char kTimeDescription[] = "t=0 0";
199static const char kAttrGroup[] = "a=group:BUNDLE";
200static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000201static const char kConnectionIpv4Addrtype[] = "IP4";
202static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000203static const char kMediaTypeVideo[] = "video";
204static const char kMediaTypeAudio[] = "audio";
205static const char kMediaTypeData[] = "application";
206static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000207// draft-ietf-mmusic-trickle-ice-01
208// When no candidates have been gathered, set the connection
209// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000210// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
211// Use IPV4 per default.
212static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000213static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000214// RFC 3556
215static const char kApplicationSpecificMaximum[] = "AS";
216
217static const int kDefaultVideoClockrate = 90000;
218
219// ISAC special-case.
220static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
221static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
222static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
223
wu@webrtc.org78187522013-10-07 23:32:02 +0000224static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000225
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000226// RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
227// types.
228const int kWildcardPayloadType = -1;
229
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000230struct SsrcInfo {
231 SsrcInfo()
232 : msid_identifier(kDefaultMsid),
233 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
234 // Create random string (which will be used as track label later)?
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000235 msid_appdata(rtc::CreateRandomString(8)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000236 }
237 uint32 ssrc_id;
238 std::string cname;
239 std::string msid_identifier;
240 std::string msid_appdata;
241
242 // For backward compatibility.
243 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
244 std::string label;
245 std::string mslabel;
246};
247typedef std::vector<SsrcInfo> SsrcInfoVec;
248typedef std::vector<SsrcGroup> SsrcGroupVec;
249
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000250template <class T>
251static void AddFmtpLine(const T& codec, std::string* message);
252static void BuildMediaDescription(const ContentInfo* content_info,
253 const TransportInfo* transport_info,
254 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000255 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000256 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000257static void BuildSctpContentAttributes(std::string* message, int sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258static void BuildRtpContentAttributes(
259 const MediaContentDescription* media_desc,
260 const MediaType media_type,
261 std::string* message);
262static void BuildRtpMap(const MediaContentDescription* media_desc,
263 const MediaType media_type,
264 std::string* message);
265static void BuildCandidate(const std::vector<Candidate>& candidates,
266 std::string* message);
267static void BuildIceOptions(const std::vector<std::string>& transport_options,
268 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000269static bool IsRtp(const std::string& protocol);
270static bool IsDtlsSctp(const std::string& protocol);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271static bool ParseSessionDescription(const std::string& message, size_t* pos,
272 std::string* session_id,
273 std::string* session_version,
274 bool* supports_msid,
275 TransportDescription* session_td,
276 RtpHeaderExtensions* session_extmaps,
277 cricket::SessionDescription* desc,
278 SdpParseError* error);
279static bool ParseGroupAttribute(const std::string& line,
280 cricket::SessionDescription* desc,
281 SdpParseError* error);
282static bool ParseMediaDescription(
283 const std::string& message,
284 const TransportDescription& session_td,
285 const RtpHeaderExtensions& session_extmaps,
286 bool supports_msid,
287 size_t* pos, cricket::SessionDescription* desc,
288 std::vector<JsepIceCandidate*>* candidates,
289 SdpParseError* error);
290static bool ParseContent(const std::string& message,
291 const MediaType media_type,
292 int mline_index,
293 const std::string& protocol,
294 const std::vector<int>& codec_preference,
295 size_t* pos,
296 std::string* content_name,
297 MediaContentDescription* media_desc,
298 TransportDescription* transport,
299 std::vector<JsepIceCandidate*>* candidates,
300 SdpParseError* error);
301static bool ParseSsrcAttribute(const std::string& line,
302 SsrcInfoVec* ssrc_infos,
303 SdpParseError* error);
304static bool ParseSsrcGroupAttribute(const std::string& line,
305 SsrcGroupVec* ssrc_groups,
306 SdpParseError* error);
307static bool ParseCryptoAttribute(const std::string& line,
308 MediaContentDescription* media_desc,
309 SdpParseError* error);
310static bool ParseRtpmapAttribute(const std::string& line,
311 const MediaType media_type,
312 const std::vector<int>& codec_preference,
313 MediaContentDescription* media_desc,
314 SdpParseError* error);
315static bool ParseFmtpAttributes(const std::string& line,
316 const MediaType media_type,
317 MediaContentDescription* media_desc,
318 SdpParseError* error);
319static bool ParseFmtpParam(const std::string& line, std::string* parameter,
320 std::string* value, SdpParseError* error);
321static bool ParseCandidate(const std::string& message, Candidate* candidate,
322 SdpParseError* error, bool is_raw);
323static bool ParseRtcpFbAttribute(const std::string& line,
324 const MediaType media_type,
325 MediaContentDescription* media_desc,
326 SdpParseError* error);
327static bool ParseIceOptions(const std::string& line,
328 std::vector<std::string>* transport_options,
329 SdpParseError* error);
330static bool ParseExtmap(const std::string& line,
331 RtpHeaderExtension* extmap,
332 SdpParseError* error);
333static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000334 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000335 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000336static bool ParseDtlsSetup(const std::string& line,
337 cricket::ConnectionRole* role,
338 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000339
340// Helper functions
341
342// Below ParseFailed*** functions output the line that caused the parsing
343// failure and the detailed reason (|description|) of the failure to |error|.
344// The functions always return false so that they can be used directly in the
345// following way when error happens:
346// "return ParseFailed***(...);"
347
348// The line starting at |line_start| of |message| is the failing line.
349// The reason for the failure should be provided in the |description|.
350// An example of a description could be "unknown character".
351static bool ParseFailed(const std::string& message,
352 size_t line_start,
353 const std::string& description,
354 SdpParseError* error) {
355 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000356 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000357 size_t line_end = message.find(kNewLine, line_start);
358 if (line_end != std::string::npos) {
359 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
360 --line_end;
361 }
362 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000363 } else {
364 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000365 }
366
367 if (error) {
368 error->line = first_line;
369 error->description = description;
370 }
371 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
372 << "\". Reason: " << description;
373 return false;
374}
375
376// |line| is the failing line. The reason for the failure should be
377// provided in the |description|.
378static bool ParseFailed(const std::string& line,
379 const std::string& description,
380 SdpParseError* error) {
381 return ParseFailed(line, 0, description, error);
382}
383
384// Parses failure where the failing SDP line isn't know or there are multiple
385// failing lines.
386static bool ParseFailed(const std::string& description,
387 SdpParseError* error) {
388 return ParseFailed("", description, error);
389}
390
391// |line| is the failing line. The failure is due to the fact that |line|
392// doesn't have |expected_fields| fields.
393static bool ParseFailedExpectFieldNum(const std::string& line,
394 int expected_fields,
395 SdpParseError* error) {
396 std::ostringstream description;
397 description << "Expects " << expected_fields << " fields.";
398 return ParseFailed(line, description.str(), error);
399}
400
401// |line| is the failing line. The failure is due to the fact that |line| has
402// less than |expected_min_fields| fields.
403static bool ParseFailedExpectMinFieldNum(const std::string& line,
404 int expected_min_fields,
405 SdpParseError* error) {
406 std::ostringstream description;
407 description << "Expects at least " << expected_min_fields << " fields.";
408 return ParseFailed(line, description.str(), error);
409}
410
411// |line| is the failing line. The failure is due to the fact that it failed to
412// get the value of |attribute|.
413static bool ParseFailedGetValue(const std::string& line,
414 const std::string& attribute,
415 SdpParseError* error) {
416 std::ostringstream description;
417 description << "Failed to get the value of attribute: " << attribute;
418 return ParseFailed(line, description.str(), error);
419}
420
421// The line starting at |line_start| of |message| is the failing line. The
422// failure is due to the line type (e.g. the "m" part of the "m-line")
423// not matching what is expected. The expected line type should be
424// provided as |line_type|.
425static bool ParseFailedExpectLine(const std::string& message,
426 size_t line_start,
427 const char line_type,
428 const std::string& line_value,
429 SdpParseError* error) {
430 std::ostringstream description;
431 description << "Expect line: " << line_type << "=" << line_value;
432 return ParseFailed(message, line_start, description.str(), error);
433}
434
435static bool AddLine(const std::string& line, std::string* message) {
436 if (!message)
437 return false;
438
439 message->append(line);
440 message->append(kLineBreak);
441 return true;
442}
443
444static bool GetLine(const std::string& message,
445 size_t* pos,
446 std::string* line) {
447 size_t line_begin = *pos;
448 size_t line_end = message.find(kNewLine, line_begin);
449 if (line_end == std::string::npos) {
450 return false;
451 }
452 // Update the new start position
453 *pos = line_end + 1;
454 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
455 --line_end;
456 }
457 *line = message.substr(line_begin, (line_end - line_begin));
458 const char* cline = line->c_str();
459 // RFC 4566
460 // An SDP session description consists of a number of lines of text of
461 // the form:
462 // <type>=<value>
463 // where <type> MUST be exactly one case-significant character and
464 // <value> is structured text whose format depends on <type>.
465 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000466 if (line->length() < 3 ||
467 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000468 cline[1] != kSdpDelimiterEqual ||
469 cline[2] == kSdpDelimiterSpace) {
470 *pos = line_begin;
471 return false;
472 }
473 return true;
474}
475
476// Init |os| to "|type|=|value|".
477static void InitLine(const char type,
478 const std::string& value,
479 std::ostringstream* os) {
480 os->str("");
481 *os << type << kSdpDelimiterEqual << value;
482}
483
484// Init |os| to "a=|attribute|".
485static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
486 InitLine(kLineTypeAttributes, attribute, os);
487}
488
489// Writes a SDP attribute line based on |attribute| and |value| to |message|.
490static void AddAttributeLine(const std::string& attribute, int value,
491 std::string* message) {
492 std::ostringstream os;
493 InitAttrLine(attribute, &os);
494 os << kSdpDelimiterColon << value;
495 AddLine(os.str(), message);
496}
497
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000498static bool IsLineType(const std::string& message,
499 const char type,
500 size_t line_start) {
501 if (message.size() < line_start + kLinePrefixLength) {
502 return false;
503 }
504 const char* cmessage = message.c_str();
505 return (cmessage[line_start] == type &&
506 cmessage[line_start + 1] == kSdpDelimiterEqual);
507}
508
509static bool IsLineType(const std::string& line,
510 const char type) {
511 return IsLineType(line, type, 0);
512}
513
514static bool GetLineWithType(const std::string& message, size_t* pos,
515 std::string* line, const char type) {
516 if (!IsLineType(message, type, *pos)) {
517 return false;
518 }
519
520 if (!GetLine(message, pos, line))
521 return false;
522
523 return true;
524}
525
526static bool HasAttribute(const std::string& line,
527 const std::string& attribute) {
528 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
529}
530
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000531static bool AddSsrcLine(uint32 ssrc_id, const std::string& attribute,
532 const std::string& value, std::string* message) {
533 // RFC 5576
534 // a=ssrc:<ssrc-id> <attribute>:<value>
535 std::ostringstream os;
536 InitAttrLine(kAttributeSsrc, &os);
537 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
538 << attribute << kSdpDelimiterColon << value;
539 return AddLine(os.str(), message);
540}
541
542// Split the message into two parts by the first delimiter.
543static bool SplitByDelimiter(const std::string& message,
544 const char delimiter,
545 std::string* field1,
546 std::string* field2) {
547 // Find the first delimiter
548 size_t pos = message.find(delimiter);
549 if (pos == std::string::npos) {
550 return false;
551 }
552 *field1 = message.substr(0, pos);
553 // The rest is the value.
554 *field2 = message.substr(pos + 1);
555 return true;
556}
557
558// Get value only from <attribute>:<value>.
559static bool GetValue(const std::string& message, const std::string& attribute,
560 std::string* value, SdpParseError* error) {
561 std::string leftpart;
562 if (!SplitByDelimiter(message, kSdpDelimiterColon, &leftpart, value)) {
563 return ParseFailedGetValue(message, attribute, error);
564 }
565 // The left part should end with the expected attribute.
566 if (leftpart.length() < attribute.length() ||
567 leftpart.compare(leftpart.length() - attribute.length(),
568 attribute.length(), attribute) != 0) {
569 return ParseFailedGetValue(message, attribute, error);
570 }
571 return true;
572}
573
574static bool CaseInsensitiveFind(std::string str1, std::string str2) {
575 std::transform(str1.begin(), str1.end(), str1.begin(),
576 ::tolower);
577 std::transform(str2.begin(), str2.end(), str2.begin(),
578 ::tolower);
579 return str1.find(str2) != std::string::npos;
580}
581
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000582template <class T>
583static bool GetValueFromString(const std::string& line,
584 const std::string& s,
585 T* t,
586 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000587 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000588 std::ostringstream description;
589 description << "Invalid value: " << s << ".";
590 return ParseFailed(line, description.str(), error);
591 }
592 return true;
593}
594
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000595static bool GetPayloadTypeFromString(const std::string& line,
596 const std::string& s,
597 int* payload_type,
598 SdpParseError* error) {
599 return GetValueFromString(line, s, payload_type, error) &&
600 cricket::IsValidRtpPayloadType(*payload_type);
601}
602
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000603void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
604 StreamParamsVec* tracks) {
605 ASSERT(tracks != NULL);
606 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
607 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
608 if (ssrc_info->cname.empty()) {
609 continue;
610 }
611
612 std::string sync_label;
613 std::string track_id;
614 if (ssrc_info->msid_identifier == kDefaultMsid &&
615 !ssrc_info->mslabel.empty()) {
616 // If there's no msid and there's mslabel, we consider this is a sdp from
617 // a older version of client that doesn't support msid.
618 // In that case, we use the mslabel and label to construct the track.
619 sync_label = ssrc_info->mslabel;
620 track_id = ssrc_info->label;
621 } else {
622 sync_label = ssrc_info->msid_identifier;
623 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
624 // is corresponding to the "id" attribute of StreamParams.
625 track_id = ssrc_info->msid_appdata;
626 }
627 if (sync_label.empty() || track_id.empty()) {
628 ASSERT(false);
629 continue;
630 }
631
632 StreamParamsVec::iterator track = tracks->begin();
633 for (; track != tracks->end(); ++track) {
634 if (track->id == track_id) {
635 break;
636 }
637 }
638 if (track == tracks->end()) {
639 // If we don't find an existing track, create a new one.
640 tracks->push_back(StreamParams());
641 track = tracks->end() - 1;
642 }
643 track->add_ssrc(ssrc_info->ssrc_id);
644 track->cname = ssrc_info->cname;
645 track->sync_label = sync_label;
646 track->id = track_id;
647 }
648}
649
650void GetMediaStreamLabels(const ContentInfo* content,
651 std::set<std::string>* labels) {
652 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000653 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000654 content->description);
655 const cricket::StreamParamsVec& streams = media_desc->streams();
656 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
657 it != streams.end(); ++it) {
658 labels->insert(it->sync_label);
659 }
660}
661
662// RFC 5245
663// It is RECOMMENDED that default candidates be chosen based on the
664// likelihood of those candidates to work with the peer that is being
665// contacted. It is RECOMMENDED that relayed > reflexive > host.
666static const int kPreferenceUnknown = 0;
667static const int kPreferenceHost = 1;
668static const int kPreferenceReflexive = 2;
669static const int kPreferenceRelayed = 3;
670
671static int GetCandidatePreferenceFromType(const std::string& type) {
672 int preference = kPreferenceUnknown;
673 if (type == cricket::LOCAL_PORT_TYPE) {
674 preference = kPreferenceHost;
675 } else if (type == cricket::STUN_PORT_TYPE) {
676 preference = kPreferenceReflexive;
677 } else if (type == cricket::RELAY_PORT_TYPE) {
678 preference = kPreferenceRelayed;
679 } else {
680 ASSERT(false);
681 }
682 return preference;
683}
684
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000685// Get ip and port of the default destination from the |candidates| with the
686// given value of |component_id|. The default candidate should be the one most
687// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000688// RFC 5245
689// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
690// TODO: Decide the default destination in webrtcsession and
691// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000692static void GetDefaultDestination(
693 const std::vector<Candidate>& candidates,
694 int component_id, std::string* port,
695 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000696 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000697 *port = kDummyPort;
698 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000699 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000700 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000701 for (std::vector<Candidate>::const_iterator it = candidates.begin();
702 it != candidates.end(); ++it) {
703 if (it->component() != component_id) {
704 continue;
705 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000706 // Default destination should be UDP only.
707 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000708 continue;
709 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000710 const int preference = GetCandidatePreferenceFromType(it->type());
711 const int family = it->address().ipaddr().family();
712 // See if this candidate is more preferable then the current one if it's the
713 // same family. Or if the current family is IPv4 already so we could safely
714 // ignore all IPv6 ones. WebRTC bug 4269.
715 // http://code.google.com/p/webrtc/issues/detail?id=4269
716 if ((preference <= current_preference && current_family == family) ||
717 (current_family == AF_INET && family == AF_INET6)) {
718 continue;
719 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000720 if (family == AF_INET) {
721 addr_type->assign(kConnectionIpv4Addrtype);
722 } else if (family == AF_INET6) {
723 addr_type->assign(kConnectionIpv6Addrtype);
724 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000725 current_preference = preference;
726 current_family = family;
727 *port = it->address().PortAsString();
728 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000729 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730}
731
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000732// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000734 const std::vector<Candidate>& candidates,
735 const std::string mline,
736 std::string* message) {
737 std::string new_lines;
738 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000739 // RFC 4566
740 // m=<media> <port> <proto> <fmt> ...
741 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000742 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000743 if (fields.size() < 3) {
744 return;
745 }
746
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000747 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000748 std::string rtp_port, rtp_ip, addr_type;
749 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
750 &rtp_port, &rtp_ip, &addr_type);
751 // Found default RTP candidate.
752 // RFC 5245
753 // The default candidates are added to the SDP as the default
754 // destination for media. For streams based on RTP, this is done by
755 // placing the IP address and port of the RTP candidate into the c and m
756 // lines, respectively.
757 // Update the port in the m line.
758 // If this is a m-line with port equal to 0, we don't change it.
759 if (fields[1] != kMediaPortRejected) {
760 new_lines.replace(fields[0].size() + 1,
761 fields[1].size(),
762 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000763 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000764 // Add the c line.
765 // RFC 4566
766 // c=<nettype> <addrtype> <connection-address>
767 InitLine(kLineTypeConnection, kConnectionNettype, &os);
768 os << " " << addr_type << " " << rtp_ip;
769 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000770 message->append(new_lines);
771}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000772
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000773// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
774static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000775 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
776 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
777 &rtcp_port, &rtcp_ip, &addr_type);
778 // Found default RTCP candidate.
779 // RFC 5245
780 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
781 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000782
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000783 // RFC 3605
784 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
785 // connection-address] CRLF
786 std::ostringstream os;
787 InitAttrLine(kAttributeRtcp, &os);
788 os << kSdpDelimiterColon
789 << rtcp_port << " "
790 << kConnectionNettype << " "
791 << addr_type << " "
792 << rtcp_ip;
793 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000794 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000795}
796
797// Get candidates according to the mline index from SessionDescriptionInterface.
798static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
799 int mline_index,
800 std::vector<Candidate>* candidates) {
801 if (!candidates) {
802 return;
803 }
804 const IceCandidateCollection* cc = desci.candidates(mline_index);
805 for (size_t i = 0; i < cc->count(); ++i) {
806 const IceCandidateInterface* candidate = cc->at(i);
807 candidates->push_back(candidate->candidate());
808 }
809}
810
811std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812 const cricket::SessionDescription* desc = jdesc.description();
813 if (!desc) {
814 return "";
815 }
816
817 std::string message;
818
819 // Session Description.
820 AddLine(kSessionVersion, &message);
821 // Session Origin
822 // RFC 4566
823 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
824 // <unicast-address>
825 std::ostringstream os;
826 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
827 const std::string session_id = jdesc.session_id().empty() ?
828 kSessionOriginSessionId : jdesc.session_id();
829 const std::string session_version = jdesc.session_version().empty() ?
830 kSessionOriginSessionVersion : jdesc.session_version();
831 os << " " << session_id << " " << session_version << " "
832 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
833 << kSessionOriginAddress;
834 AddLine(os.str(), &message);
835 AddLine(kSessionName, &message);
836
837 // Time Description.
838 AddLine(kTimeDescription, &message);
839
840 // Group
841 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
842 std::string group_line = kAttrGroup;
843 const cricket::ContentGroup* group =
844 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
845 ASSERT(group != NULL);
846 const cricket::ContentNames& content_names = group->content_names();
847 for (cricket::ContentNames::const_iterator it = content_names.begin();
848 it != content_names.end(); ++it) {
849 group_line.append(" ");
850 group_line.append(*it);
851 }
852 AddLine(group_line, &message);
853 }
854
855 // MediaStream semantics
856 InitAttrLine(kAttributeMsidSemantics, &os);
857 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000858
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000859 std::set<std::string> media_stream_labels;
860 const ContentInfo* audio_content = GetFirstAudioContent(desc);
861 if (audio_content)
862 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000863
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000864 const ContentInfo* video_content = GetFirstVideoContent(desc);
865 if (video_content)
866 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000867
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000868 for (std::set<std::string>::const_iterator it =
869 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
870 os << " " << *it;
871 }
872 AddLine(os.str(), &message);
873
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000874 // Preserve the order of the media contents.
875 int mline_index = -1;
876 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
877 it != desc->contents().end(); ++it) {
878 const MediaContentDescription* mdesc =
879 static_cast<const MediaContentDescription*>(it->description);
880 std::vector<Candidate> candidates;
881 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
882 BuildMediaDescription(&*it,
883 desc->GetTransportInfoByName(it->name),
884 mdesc->type(),
885 candidates,
886 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000888 return message;
889}
890
891// Serializes the passed in IceCandidateInterface to a SDP string.
892// candidate - The candidate to be serialized.
893std::string SdpSerializeCandidate(
894 const IceCandidateInterface& candidate) {
895 std::string message;
896 std::vector<cricket::Candidate> candidates;
897 candidates.push_back(candidate.candidate());
898 BuildCandidate(candidates, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000899 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
900 // just candidate:<candidate> not a=candidate:<blah>CRLF
901 ASSERT(message.find("a=") == 0);
902 message.erase(0, 2);
903 ASSERT(message.find(kLineBreak) == message.size() - 2);
904 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905 return message;
906}
907
908bool SdpDeserialize(const std::string& message,
909 JsepSessionDescription* jdesc,
910 SdpParseError* error) {
911 std::string session_id;
912 std::string session_version;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000913 TransportDescription session_td(NS_JINGLE_ICE_UDP,
914 std::string(), std::string());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915 RtpHeaderExtensions session_extmaps;
916 cricket::SessionDescription* desc = new cricket::SessionDescription();
917 std::vector<JsepIceCandidate*> candidates;
918 size_t current_pos = 0;
919 bool supports_msid = false;
920
921 // Session Description
922 if (!ParseSessionDescription(message, &current_pos, &session_id,
923 &session_version, &supports_msid, &session_td,
924 &session_extmaps, desc, error)) {
925 delete desc;
926 return false;
927 }
928
929 // Media Description
930 if (!ParseMediaDescription(message, session_td, session_extmaps,
931 supports_msid, &current_pos, desc, &candidates,
932 error)) {
933 delete desc;
934 for (std::vector<JsepIceCandidate*>::const_iterator
935 it = candidates.begin(); it != candidates.end(); ++it) {
936 delete *it;
937 }
938 return false;
939 }
940
941 jdesc->Initialize(desc, session_id, session_version);
942
943 for (std::vector<JsepIceCandidate*>::const_iterator
944 it = candidates.begin(); it != candidates.end(); ++it) {
945 jdesc->AddCandidate(*it);
946 delete *it;
947 }
948 return true;
949}
950
951bool SdpDeserializeCandidate(const std::string& message,
952 JsepIceCandidate* jcandidate,
953 SdpParseError* error) {
954 ASSERT(jcandidate != NULL);
955 Candidate candidate;
956 if (!ParseCandidate(message, &candidate, error, true)) {
957 return false;
958 }
959 jcandidate->SetCandidate(candidate);
960 return true;
961}
962
963bool ParseCandidate(const std::string& message, Candidate* candidate,
964 SdpParseError* error, bool is_raw) {
965 ASSERT(candidate != NULL);
966
967 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000968 std::string first_line = message;
969 size_t pos = 0;
970 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000971
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000972 // Makes sure |message| contains only one line.
973 if (message.size() > first_line.size()) {
974 std::string left, right;
975 if (SplitByDelimiter(message, kNewLine, &left, &right) && !right.empty()) {
976 return ParseFailed(message, 0, "Expect one line only", error);
977 }
978 }
979
980 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
981 // candidate:<candidate> when trickled, but we still support
982 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
983 // from the SDP.
984 if (IsLineType(first_line, kLineTypeAttributes)) {
985 first_line = first_line.substr(kLinePrefixLength);
986 }
987
988 std::string attribute_candidate;
989 std::string candidate_value;
990
991 // |first_line| must be in the form of "candidate:<value>".
992 if (!SplitByDelimiter(first_line, kSdpDelimiterColon,
993 &attribute_candidate, &candidate_value) ||
994 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000995 if (is_raw) {
996 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000997 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000998 << ":" << "<candidate-str>";
999 return ParseFailed(first_line, 0, description.str(), error);
1000 } else {
1001 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
1002 kAttributeCandidate, error);
1003 }
1004 }
1005
1006 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001007 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
1008
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009 // RFC 5245
1010 // a=candidate:<foundation> <component-id> <transport> <priority>
1011 // <connection-address> <port> typ <candidate-types>
1012 // [raddr <connection-address>] [rport <port>]
1013 // *(SP extension-att-name SP extension-att-value)
1014 const size_t expected_min_fields = 8;
1015 if (fields.size() < expected_min_fields ||
1016 (fields[6] != kAttributeCandidateTyp)) {
1017 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
1018 }
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001019 std::string foundation = fields[0];
1020
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001021 int component_id = 0;
1022 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1023 return false;
1024 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001025 const std::string transport = fields[2];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001026 uint32 priority = 0;
1027 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1028 return false;
1029 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030 const std::string connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001031 int port = 0;
1032 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1033 return false;
1034 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035 SocketAddress address(connection_address, port);
1036
1037 cricket::ProtocolType protocol;
1038 if (!StringToProto(transport.c_str(), &protocol)) {
1039 return ParseFailed(first_line, "Unsupported transport type.", error);
1040 }
1041
1042 std::string candidate_type;
1043 const std::string type = fields[7];
1044 if (type == kCandidateHost) {
1045 candidate_type = cricket::LOCAL_PORT_TYPE;
1046 } else if (type == kCandidateSrflx) {
1047 candidate_type = cricket::STUN_PORT_TYPE;
1048 } else if (type == kCandidateRelay) {
1049 candidate_type = cricket::RELAY_PORT_TYPE;
1050 } else {
1051 return ParseFailed(first_line, "Unsupported candidate type.", error);
1052 }
1053
1054 size_t current_position = expected_min_fields;
1055 SocketAddress related_address;
1056 // The 2 optional fields for related address
1057 // [raddr <connection-address>] [rport <port>]
1058 if (fields.size() >= (current_position + 2) &&
1059 fields[current_position] == kAttributeCandidateRaddr) {
1060 related_address.SetIP(fields[++current_position]);
1061 ++current_position;
1062 }
1063 if (fields.size() >= (current_position + 2) &&
1064 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001065 int port = 0;
1066 if (!GetValueFromString(
1067 first_line, fields[++current_position], &port, error)) {
1068 return false;
1069 }
1070 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071 ++current_position;
1072 }
1073
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001074 // If this is a TCP candidate, it has additional extension as defined in
1075 // RFC 6544.
1076 std::string tcptype;
1077 if (fields.size() >= (current_position + 2) &&
1078 fields[current_position] == kTcpCandidateType) {
1079 tcptype = fields[++current_position];
1080 ++current_position;
1081
1082 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1083 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1084 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1085 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1086 }
1087
1088 if (protocol != cricket::PROTO_TCP) {
1089 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1090 }
1091 }
1092
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093 // Extension
1094 // Empty string as the candidate username and password.
1095 // Will be updated later with the ice-ufrag and ice-pwd.
1096 // TODO: Remove the username/password extension, which is currently
1097 // kept for backwards compatibility.
1098 std::string username;
1099 std::string password;
1100 uint32 generation = 0;
1101 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1102 // RFC 5245
1103 // *(SP extension-att-name SP extension-att-value)
1104 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001105 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1106 return false;
1107 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001108 } else if (fields[i] == kAttributeCandidateUsername) {
1109 username = fields[++i];
1110 } else if (fields[i] == kAttributeCandidatePassword) {
1111 password = fields[++i];
1112 } else {
1113 // Skip the unknown extension.
1114 ++i;
1115 }
1116 }
1117
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001118 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001119 address, priority, username, password, candidate_type,
1120 generation, foundation);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001121 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001122 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001123 return true;
1124}
1125
1126bool ParseIceOptions(const std::string& line,
1127 std::vector<std::string>* transport_options,
1128 SdpParseError* error) {
1129 std::string ice_options;
1130 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1131 return false;
1132 }
1133 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001134 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001135 for (size_t i = 0; i < fields.size(); ++i) {
1136 transport_options->push_back(fields[i]);
1137 }
1138 return true;
1139}
1140
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001141bool ParseSctpPort(const std::string& line,
1142 int* sctp_port,
1143 SdpParseError* error) {
1144 // draft-ietf-mmusic-sctp-sdp-07
1145 // a=sctp-port
1146 std::vector<std::string> fields;
1147 rtc::split(line.substr(kLinePrefixLength),
1148 kSdpDelimiterSpace, &fields);
1149 const size_t expected_min_fields = 2;
1150 if (fields.size() < expected_min_fields) {
1151 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1152 }
1153 if (!rtc::FromString(fields[1], sctp_port)) {
1154 return ParseFailed(line,
1155 "Invalid sctp port value.",
1156 error);
1157 }
1158 return true;
1159}
1160
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001161bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1162 SdpParseError* error) {
1163 // RFC 5285
1164 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1165 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001166 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001167 kSdpDelimiterSpace, &fields);
1168 const size_t expected_min_fields = 2;
1169 if (fields.size() < expected_min_fields) {
1170 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1171 }
1172 std::string uri = fields[1];
1173
1174 std::string value_direction;
1175 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1176 return false;
1177 }
1178 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001179 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001180 int value = 0;
1181 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1182 return false;
1183 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001184
1185 *extmap = RtpHeaderExtension(uri, value);
1186 return true;
1187}
1188
1189void BuildMediaDescription(const ContentInfo* content_info,
1190 const TransportInfo* transport_info,
1191 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001192 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001193 std::string* message) {
1194 ASSERT(message != NULL);
1195 if (content_info == NULL || message == NULL) {
1196 return;
1197 }
1198 // TODO: Rethink if we should use sprintfn instead of stringstream.
1199 // According to the style guide, streams should only be used for logging.
1200 // http://google-styleguide.googlecode.com/svn/
1201 // trunk/cppguide.xml?showone=Streams#Streams
1202 std::ostringstream os;
1203 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001204 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001205 content_info->description);
1206 ASSERT(media_desc != NULL);
1207
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001208 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001209
1210 // RFC 4566
1211 // m=<media> <port> <proto> <fmt>
1212 // fmt is a list of payload type numbers that MAY be used in the session.
1213 const char* type = NULL;
1214 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1215 type = kMediaTypeAudio;
1216 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1217 type = kMediaTypeVideo;
1218 else if (media_type == cricket::MEDIA_TYPE_DATA)
1219 type = kMediaTypeData;
1220 else
1221 ASSERT(false);
1222
1223 std::string fmt;
1224 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1225 const VideoContentDescription* video_desc =
1226 static_cast<const VideoContentDescription*>(media_desc);
1227 for (std::vector<cricket::VideoCodec>::const_iterator it =
1228 video_desc->codecs().begin();
1229 it != video_desc->codecs().end(); ++it) {
1230 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001231 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001232 }
1233 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1234 const AudioContentDescription* audio_desc =
1235 static_cast<const AudioContentDescription*>(media_desc);
1236 for (std::vector<cricket::AudioCodec>::const_iterator it =
1237 audio_desc->codecs().begin();
1238 it != audio_desc->codecs().end(); ++it) {
1239 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001240 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241 }
1242 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001243 const DataContentDescription* data_desc =
1244 static_cast<const DataContentDescription*>(media_desc);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001245 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001246 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001247
1248 for (std::vector<cricket::DataCodec>::const_iterator it =
1249 data_desc->codecs().begin();
1250 it != data_desc->codecs().end(); ++it) {
1251 if (it->id == cricket::kGoogleSctpDataCodecId &&
1252 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1253 break;
1254 }
1255 }
1256
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001257 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001259 for (std::vector<cricket::DataCodec>::const_iterator it =
1260 data_desc->codecs().begin();
1261 it != data_desc->codecs().end(); ++it) {
1262 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001263 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001264 }
1265 }
1266 }
1267 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1268 // to 0.
1269 if (fmt.empty()) {
1270 fmt = " 0";
1271 }
1272
1273 // The port number in the m line will be updated later when associate with
1274 // the candidates.
1275 // RFC 3264
1276 // To reject an offered stream, the port number in the corresponding stream in
1277 // the answer MUST be set to zero.
1278 const std::string port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001279 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001281 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282 transport_info->description.identity_fingerprint.get() : NULL;
1283
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001284 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001285 InitLine(kLineTypeMedia, type, &os);
1286 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001287 std::string mline = os.str();
1288 UpdateMediaDefaultDestination(candidates, mline, message);
1289
1290 // RFC 4566
1291 // b=AS:<bandwidth>
1292 // We should always use the default bandwidth for RTP-based data
1293 // channels. Don't allow SDP to set the bandwidth, because that
1294 // would give JS the opportunity to "break the Internet".
1295 // TODO(pthatcher): But we need to temporarily allow the SDP to control
1296 // this for backwards-compatibility. Once we don't need that any
1297 // more, remove this.
1298 bool support_dc_sdp_bandwidth_temporarily = true;
1299 if (media_desc->bandwidth() >= 1000 &&
1300 (media_type != cricket::MEDIA_TYPE_DATA ||
1301 support_dc_sdp_bandwidth_temporarily)) {
1302 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1303 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1304 AddLine(os.str(), message);
1305 }
1306
1307 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001308 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001309 std::string rtcp_line = GetRtcpLine(candidates);
1310 if (!rtcp_line.empty()) {
1311 AddLine(rtcp_line, message);
1312 }
1313 }
1314
1315 // Build the a=candidate lines.
1316 BuildCandidate(candidates, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317
1318 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1319 if (transport_info) {
1320 // RFC 5245
1321 // ice-pwd-att = "ice-pwd" ":" password
1322 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1323 // ice-ufrag
1324 InitAttrLine(kAttributeIceUfrag, &os);
1325 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1326 AddLine(os.str(), message);
1327 // ice-pwd
1328 InitAttrLine(kAttributeIcePwd, &os);
1329 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1330 AddLine(os.str(), message);
1331
1332 // draft-petithuguenin-mmusic-ice-attributes-level-03
1333 BuildIceOptions(transport_info->description.transport_options, message);
1334
1335 // RFC 4572
1336 // fingerprint-attribute =
1337 // "fingerprint" ":" hash-func SP fingerprint
1338 if (fp) {
1339 // Insert the fingerprint attribute.
1340 InitAttrLine(kAttributeFingerprint, &os);
1341 os << kSdpDelimiterColon
1342 << fp->algorithm << kSdpDelimiterSpace
1343 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001345
1346 // Inserting setup attribute.
1347 if (transport_info->description.connection_role !=
1348 cricket::CONNECTIONROLE_NONE) {
1349 // Making sure we are not using "passive" mode.
1350 cricket::ConnectionRole role =
1351 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001352 std::string dtls_role_str;
1353 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001354 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001355 os << kSdpDelimiterColon << dtls_role_str;
1356 AddLine(os.str(), message);
1357 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358 }
1359 }
1360
1361 // RFC 3388
1362 // mid-attribute = "a=mid:" identification-tag
1363 // identification-tag = token
1364 // Use the content name as the mid identification-tag.
1365 InitAttrLine(kAttributeMid, &os);
1366 os << kSdpDelimiterColon << content_info->name;
1367 AddLine(os.str(), message);
1368
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001369 if (IsDtlsSctp(media_desc->protocol())) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001370 BuildSctpContentAttributes(message, sctp_port);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001371 } else if (IsRtp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372 BuildRtpContentAttributes(media_desc, media_type, message);
1373 }
1374}
1375
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001376void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001377 // draft-ietf-mmusic-sctp-sdp-04
1378 // a=sctpmap:sctpmap-number protocol [streams]
1379 std::ostringstream os;
1380 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001381 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001382 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1383 << (cricket::kMaxSctpSid + 1);
1384 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001385}
1386
1387void BuildRtpContentAttributes(
1388 const MediaContentDescription* media_desc,
1389 const MediaType media_type,
1390 std::string* message) {
1391 std::ostringstream os;
1392 // RFC 5285
1393 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1394 // The definitions MUST be either all session level or all media level. This
1395 // implementation uses all media level.
1396 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1397 InitAttrLine(kAttributeExtmap, &os);
1398 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1399 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1400 AddLine(os.str(), message);
1401 }
1402
1403 // RFC 3264
1404 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
1405
1406 cricket::MediaContentDirection direction = media_desc->direction();
1407 if (media_desc->streams().empty() && direction == cricket::MD_SENDRECV) {
1408 direction = cricket::MD_RECVONLY;
1409 }
1410
1411 switch (direction) {
1412 case cricket::MD_INACTIVE:
1413 InitAttrLine(kAttributeInactive, &os);
1414 break;
1415 case cricket::MD_SENDONLY:
1416 InitAttrLine(kAttributeSendOnly, &os);
1417 break;
1418 case cricket::MD_RECVONLY:
1419 InitAttrLine(kAttributeRecvOnly, &os);
1420 break;
1421 case cricket::MD_SENDRECV:
1422 default:
1423 InitAttrLine(kAttributeSendRecv, &os);
1424 break;
1425 }
1426 AddLine(os.str(), message);
1427
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001428 // RFC 5761
1429 // a=rtcp-mux
1430 if (media_desc->rtcp_mux()) {
1431 InitAttrLine(kAttributeRtcpMux, &os);
1432 AddLine(os.str(), message);
1433 }
1434
1435 // RFC 4568
1436 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1437 for (std::vector<CryptoParams>::const_iterator it =
1438 media_desc->cryptos().begin();
1439 it != media_desc->cryptos().end(); ++it) {
1440 InitAttrLine(kAttributeCrypto, &os);
1441 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1442 << it->key_params;
1443 if (!it->session_params.empty()) {
1444 os << " " << it->session_params;
1445 }
1446 AddLine(os.str(), message);
1447 }
1448
1449 // RFC 4566
1450 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1451 // [/<encodingparameters>]
1452 BuildRtpMap(media_desc, media_type, message);
1453
1454 // Specify latency for buffered mode.
1455 // a=x-google-buffer-latency:<value>
1456 if (media_desc->buffered_mode_latency() != cricket::kBufferedModeDisabled) {
1457 std::ostringstream os;
1458 InitAttrLine(kAttributeXGoogleBufferLatency, &os);
1459 os << kSdpDelimiterColon << media_desc->buffered_mode_latency();
1460 AddLine(os.str(), message);
1461 }
1462
1463 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1464 track != media_desc->streams().end(); ++track) {
1465 // Require that the track belongs to a media stream,
1466 // ie the sync_label is set. This extra check is necessary since the
1467 // MediaContentDescription always contains a streamparam with an ssrc even
1468 // if no track or media stream have been created.
1469 if (track->sync_label.empty()) continue;
1470
1471 // Build the ssrc-group lines.
1472 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1473 // RFC 5576
1474 // a=ssrc-group:<semantics> <ssrc-id> ...
1475 if (track->ssrc_groups[i].ssrcs.empty()) {
1476 continue;
1477 }
1478 std::ostringstream os;
1479 InitAttrLine(kAttributeSsrcGroup, &os);
1480 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
1481 std::vector<uint32>::const_iterator ssrc =
1482 track->ssrc_groups[i].ssrcs.begin();
1483 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001484 os << kSdpDelimiterSpace << rtc::ToString<uint32>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001485 }
1486 AddLine(os.str(), message);
1487 }
1488 // Build the ssrc lines for each ssrc.
1489 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
1490 uint32 ssrc = track->ssrcs[i];
1491 // RFC 5576
1492 // a=ssrc:<ssrc-id> cname:<value>
1493 AddSsrcLine(ssrc, kSsrcAttributeCname,
1494 track->cname, message);
1495
1496 // draft-alvestrand-mmusic-msid-00
1497 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1498 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1499 // is corresponding to the "name" attribute of StreamParams.
1500 std::string appdata = track->id;
1501 std::ostringstream os;
1502 InitAttrLine(kAttributeSsrc, &os);
1503 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1504 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1505 << kSdpDelimiterSpace << appdata;
1506 AddLine(os.str(), message);
1507
1508 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1509 // draft-alvestrand-rtcweb-mid-01
1510 // a=ssrc:<ssrc-id> mslabel:<value>
1511 // The label isn't yet defined.
1512 // a=ssrc:<ssrc-id> label:<value>
1513 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1514 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1515 }
1516 }
1517}
1518
1519void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1520 // fmtp header: a=fmtp:|payload_type| <parameters>
1521 // Add a=fmtp
1522 InitAttrLine(kAttributeFmtp, os);
1523 // Add :|payload_type|
1524 *os << kSdpDelimiterColon << payload_type;
1525}
1526
1527void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1528 // rtcp-fb header: a=rtcp-fb:|payload_type|
1529 // <parameters>/<ccm <ccm_parameters>>
1530 // Add a=rtcp-fb
1531 InitAttrLine(kAttributeRtcpFb, os);
1532 // Add :
1533 *os << kSdpDelimiterColon;
1534 if (payload_type == kWildcardPayloadType) {
1535 *os << "*";
1536 } else {
1537 *os << payload_type;
1538 }
1539}
1540
1541void WriteFmtpParameter(const std::string& parameter_name,
1542 const std::string& parameter_value,
1543 std::ostringstream* os) {
1544 // fmtp parameters: |parameter_name|=|parameter_value|
1545 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1546}
1547
1548void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1549 std::ostringstream* os) {
1550 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1551 fmtp != parameters.end(); ++fmtp) {
1552 // Each new parameter, except the first one starts with ";" and " ".
1553 if (fmtp != parameters.begin()) {
1554 *os << kSdpDelimiterSemicolon;
1555 }
1556 *os << kSdpDelimiterSpace;
1557 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1558 }
1559}
1560
1561bool IsFmtpParam(const std::string& name) {
1562 const char* kFmtpParams[] = {
1563 kCodecParamMinPTime, kCodecParamSPropStereo,
Minyue Li7100dcd2015-03-27 05:05:59 +01001564 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamUseDtx,
1565 kCodecParamStartBitrate, kCodecParamMaxBitrate, kCodecParamMinBitrate,
1566 kCodecParamMaxQuantization, kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001567 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1568 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001569 };
1570 for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
1571 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1572 return true;
1573 }
1574 }
1575 return false;
1576}
1577
1578// Retreives fmtp parameters from |params|, which may contain other parameters
1579// as well, and puts them in |fmtp_parameters|.
1580void GetFmtpParams(const cricket::CodecParameterMap& params,
1581 cricket::CodecParameterMap* fmtp_parameters) {
1582 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1583 iter != params.end(); ++iter) {
1584 if (IsFmtpParam(iter->first)) {
1585 (*fmtp_parameters)[iter->first] = iter->second;
1586 }
1587 }
1588}
1589
1590template <class T>
1591void AddFmtpLine(const T& codec, std::string* message) {
1592 cricket::CodecParameterMap fmtp_parameters;
1593 GetFmtpParams(codec.params, &fmtp_parameters);
1594 if (fmtp_parameters.empty()) {
1595 // No need to add an fmtp if it will have no (optional) parameters.
1596 return;
1597 }
1598 std::ostringstream os;
1599 WriteFmtpHeader(codec.id, &os);
1600 WriteFmtpParameters(fmtp_parameters, &os);
1601 AddLine(os.str(), message);
1602 return;
1603}
1604
1605template <class T>
1606void AddRtcpFbLines(const T& codec, std::string* message) {
1607 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1608 codec.feedback_params.params().begin();
1609 iter != codec.feedback_params.params().end(); ++iter) {
1610 std::ostringstream os;
1611 WriteRtcpFbHeader(codec.id, &os);
1612 os << " " << iter->id();
1613 if (!iter->param().empty()) {
1614 os << " " << iter->param();
1615 }
1616 AddLine(os.str(), message);
1617 }
1618}
1619
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001620bool AddSctpDataCodec(DataContentDescription* media_desc,
1621 int sctp_port) {
1622 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1623 return ParseFailed("",
1624 "Can't have multiple sctp port attributes.",
1625 NULL);
1626 }
1627 // Add the SCTP Port number as a pseudo-codec "port" parameter
1628 cricket::DataCodec codec_port(
1629 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1630 0);
1631 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1632 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1633 << sctp_port;
1634 media_desc->AddCodec(codec_port);
1635 return true;
1636}
1637
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001638bool GetMinValue(const std::vector<int>& values, int* value) {
1639 if (values.empty()) {
1640 return false;
1641 }
1642 std::vector<int>::const_iterator found =
1643 std::min_element(values.begin(), values.end());
1644 *value = *found;
1645 return true;
1646}
1647
1648bool GetParameter(const std::string& name,
1649 const cricket::CodecParameterMap& params, int* value) {
1650 std::map<std::string, std::string>::const_iterator found =
1651 params.find(name);
1652 if (found == params.end()) {
1653 return false;
1654 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001655 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001656 return false;
1657 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001658 return true;
1659}
1660
1661void BuildRtpMap(const MediaContentDescription* media_desc,
1662 const MediaType media_type,
1663 std::string* message) {
1664 ASSERT(message != NULL);
1665 ASSERT(media_desc != NULL);
1666 std::ostringstream os;
1667 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1668 const VideoContentDescription* video_desc =
1669 static_cast<const VideoContentDescription*>(media_desc);
1670 for (std::vector<cricket::VideoCodec>::const_iterator it =
1671 video_desc->codecs().begin();
1672 it != video_desc->codecs().end(); ++it) {
1673 // RFC 4566
1674 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1675 // [/<encodingparameters>]
1676 if (it->id != kWildcardPayloadType) {
1677 InitAttrLine(kAttributeRtpmap, &os);
1678 os << kSdpDelimiterColon << it->id << " " << it->name
1679 << "/" << kDefaultVideoClockrate;
1680 AddLine(os.str(), message);
1681 }
1682 AddRtcpFbLines(*it, message);
1683 AddFmtpLine(*it, message);
1684 }
1685 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1686 const AudioContentDescription* audio_desc =
1687 static_cast<const AudioContentDescription*>(media_desc);
1688 std::vector<int> ptimes;
1689 std::vector<int> maxptimes;
1690 int max_minptime = 0;
1691 for (std::vector<cricket::AudioCodec>::const_iterator it =
1692 audio_desc->codecs().begin();
1693 it != audio_desc->codecs().end(); ++it) {
1694 ASSERT(!it->name.empty());
1695 // RFC 4566
1696 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1697 // [/<encodingparameters>]
1698 InitAttrLine(kAttributeRtpmap, &os);
1699 os << kSdpDelimiterColon << it->id << " ";
1700 os << it->name << "/" << it->clockrate;
1701 if (it->channels != 1) {
1702 os << "/" << it->channels;
1703 }
1704 AddLine(os.str(), message);
1705 AddRtcpFbLines(*it, message);
1706 AddFmtpLine(*it, message);
1707 int minptime = 0;
1708 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1709 max_minptime = std::max(minptime, max_minptime);
1710 }
1711 int ptime;
1712 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1713 ptimes.push_back(ptime);
1714 }
1715 int maxptime;
1716 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1717 maxptimes.push_back(maxptime);
1718 }
1719 }
1720 // Populate the maxptime attribute with the smallest maxptime of all codecs
1721 // under the same m-line.
1722 int min_maxptime = INT_MAX;
1723 if (GetMinValue(maxptimes, &min_maxptime)) {
1724 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1725 }
1726 ASSERT(min_maxptime > max_minptime);
1727 // Populate the ptime attribute with the smallest ptime or the largest
1728 // minptime, whichever is the largest, for all codecs under the same m-line.
1729 int ptime = INT_MAX;
1730 if (GetMinValue(ptimes, &ptime)) {
1731 ptime = std::min(ptime, min_maxptime);
1732 ptime = std::max(ptime, max_minptime);
1733 AddAttributeLine(kCodecParamPTime, ptime, message);
1734 }
1735 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1736 const DataContentDescription* data_desc =
1737 static_cast<const DataContentDescription*>(media_desc);
1738 for (std::vector<cricket::DataCodec>::const_iterator it =
1739 data_desc->codecs().begin();
1740 it != data_desc->codecs().end(); ++it) {
1741 // RFC 4566
1742 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1743 // [/<encodingparameters>]
1744 InitAttrLine(kAttributeRtpmap, &os);
1745 os << kSdpDelimiterColon << it->id << " "
1746 << it->name << "/" << it->clockrate;
1747 AddLine(os.str(), message);
1748 }
1749 }
1750}
1751
1752void BuildCandidate(const std::vector<Candidate>& candidates,
1753 std::string* message) {
1754 std::ostringstream os;
1755
1756 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1757 it != candidates.end(); ++it) {
1758 // RFC 5245
1759 // a=candidate:<foundation> <component-id> <transport> <priority>
1760 // <connection-address> <port> typ <candidate-types>
1761 // [raddr <connection-address>] [rport <port>]
1762 // *(SP extension-att-name SP extension-att-value)
1763 std::string type;
1764 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1765 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1766 type = kCandidateHost;
1767 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1768 type = kCandidateSrflx;
1769 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1770 type = kCandidateRelay;
1771 } else {
1772 ASSERT(false);
Peter Thatcher019087f2015-04-28 09:06:26 -07001773 // Never write out candidates if we don't know the type.
1774 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001775 }
1776
1777 InitAttrLine(kAttributeCandidate, &os);
1778 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001779 << it->foundation() << " "
1780 << it->component() << " "
1781 << it->protocol() << " "
1782 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001783 << it->address().ipaddr().ToString() << " "
1784 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001785 << kAttributeCandidateTyp << " "
1786 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001787
1788 // Related address
1789 if (!it->related_address().IsNil()) {
1790 os << kAttributeCandidateRaddr << " "
1791 << it->related_address().ipaddr().ToString() << " "
1792 << kAttributeCandidateRport << " "
1793 << it->related_address().PortAsString() << " ";
1794 }
1795
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001796 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001797 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001798 }
1799
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001800 // Extensions
1801 os << kAttributeCandidateGeneration << " " << it->generation();
1802
1803 AddLine(os.str(), message);
1804 }
1805}
1806
1807void BuildIceOptions(const std::vector<std::string>& transport_options,
1808 std::string* message) {
1809 if (!transport_options.empty()) {
1810 std::ostringstream os;
1811 InitAttrLine(kAttributeIceOption, &os);
1812 os << kSdpDelimiterColon << transport_options[0];
1813 for (size_t i = 1; i < transport_options.size(); ++i) {
1814 os << kSdpDelimiterSpace << transport_options[i];
1815 }
1816 AddLine(os.str(), message);
1817 }
1818}
1819
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001820bool IsRtp(const std::string& protocol) {
1821 return protocol.empty() ||
1822 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1823}
1824
1825bool IsDtlsSctp(const std::string& protocol) {
1826 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001827 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001828}
1829
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830bool ParseSessionDescription(const std::string& message, size_t* pos,
1831 std::string* session_id,
1832 std::string* session_version,
1833 bool* supports_msid,
1834 TransportDescription* session_td,
1835 RtpHeaderExtensions* session_extmaps,
1836 cricket::SessionDescription* desc,
1837 SdpParseError* error) {
1838 std::string line;
1839
1840 // RFC 4566
1841 // v= (protocol version)
1842 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1843 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1844 std::string(), error);
1845 }
1846 // RFC 4566
1847 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1848 // <unicast-address>
1849 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1850 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1851 std::string(), error);
1852 }
1853 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001854 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001855 kSdpDelimiterSpace, &fields);
1856 const size_t expected_fields = 6;
1857 if (fields.size() != expected_fields) {
1858 return ParseFailedExpectFieldNum(line, expected_fields, error);
1859 }
1860 *session_id = fields[1];
1861 *session_version = fields[2];
1862
1863 // RFC 4566
1864 // s= (session name)
1865 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1866 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1867 std::string(), error);
1868 }
1869
1870 // Optional lines
1871 // Those are the optional lines, so shouldn't return false if not present.
1872 // RFC 4566
1873 // i=* (session information)
1874 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1875
1876 // RFC 4566
1877 // u=* (URI of description)
1878 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1879
1880 // RFC 4566
1881 // e=* (email address)
1882 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1883
1884 // RFC 4566
1885 // p=* (phone number)
1886 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1887
1888 // RFC 4566
1889 // c=* (connection information -- not required if included in
1890 // all media)
1891 GetLineWithType(message, pos, &line, kLineTypeConnection);
1892
1893 // RFC 4566
1894 // b=* (zero or more bandwidth information lines)
1895 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1896 // By pass zero or more b lines.
1897 }
1898
1899 // RFC 4566
1900 // One or more time descriptions ("t=" and "r=" lines; see below)
1901 // t= (time the session is active)
1902 // r=* (zero or more repeat times)
1903 // Ensure there's at least one time description
1904 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1905 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1906 error);
1907 }
1908
1909 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1910 // By pass zero or more r lines.
1911 }
1912
1913 // Go through the rest of the time descriptions
1914 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1915 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1916 // By pass zero or more r lines.
1917 }
1918 }
1919
1920 // RFC 4566
1921 // z=* (time zone adjustments)
1922 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1923
1924 // RFC 4566
1925 // k=* (encryption key)
1926 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1927
1928 // RFC 4566
1929 // a=* (zero or more session attribute lines)
1930 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1931 if (HasAttribute(line, kAttributeGroup)) {
1932 if (!ParseGroupAttribute(line, desc, error)) {
1933 return false;
1934 }
1935 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1936 if (!GetValue(line, kAttributeIceUfrag,
1937 &(session_td->ice_ufrag), error)) {
1938 return false;
1939 }
1940 } else if (HasAttribute(line, kAttributeIcePwd)) {
1941 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1942 return false;
1943 }
1944 } else if (HasAttribute(line, kAttributeIceLite)) {
1945 session_td->ice_mode = cricket::ICEMODE_LITE;
1946 } else if (HasAttribute(line, kAttributeIceOption)) {
1947 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1948 return false;
1949 }
1950 } else if (HasAttribute(line, kAttributeFingerprint)) {
1951 if (session_td->identity_fingerprint.get()) {
1952 return ParseFailed(
1953 line,
1954 "Can't have multiple fingerprint attributes at the same level.",
1955 error);
1956 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001957 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001958 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1959 return false;
1960 }
1961 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001962 } else if (HasAttribute(line, kAttributeSetup)) {
1963 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1964 return false;
1965 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001966 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1967 std::string semantics;
1968 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1969 return false;
1970 }
1971 *supports_msid = CaseInsensitiveFind(semantics, kMediaStreamSemantic);
1972 } else if (HasAttribute(line, kAttributeExtmap)) {
1973 RtpHeaderExtension extmap;
1974 if (!ParseExtmap(line, &extmap, error)) {
1975 return false;
1976 }
1977 session_extmaps->push_back(extmap);
1978 }
1979 }
1980
1981 return true;
1982}
1983
1984bool ParseGroupAttribute(const std::string& line,
1985 cricket::SessionDescription* desc,
1986 SdpParseError* error) {
1987 ASSERT(desc != NULL);
1988
1989 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1990 // a=group:BUNDLE video voice
1991 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001992 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993 kSdpDelimiterSpace, &fields);
1994 std::string semantics;
1995 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1996 return false;
1997 }
1998 cricket::ContentGroup group(semantics);
1999 for (size_t i = 1; i < fields.size(); ++i) {
2000 group.AddContentName(fields[i]);
2001 }
2002 desc->AddGroup(group);
2003 return true;
2004}
2005
2006static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002007 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002008 SdpParseError* error) {
2009 if (!IsLineType(line, kLineTypeAttributes) ||
2010 !HasAttribute(line, kAttributeFingerprint)) {
2011 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
2012 kAttributeFingerprint, error);
2013 }
2014
2015 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002016 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002017 kSdpDelimiterSpace, &fields);
2018 const size_t expected_fields = 2;
2019 if (fields.size() != expected_fields) {
2020 return ParseFailedExpectFieldNum(line, expected_fields, error);
2021 }
2022
2023 // The first field here is "fingerprint:<hash>.
2024 std::string algorithm;
2025 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2026 return false;
2027 }
2028
2029 // Downcase the algorithm. Note that we don't need to downcase the
2030 // fingerprint because hex_decode can handle upper-case.
2031 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2032 ::tolower);
2033
2034 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002035 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002036 algorithm, fields[1]);
2037 if (!*fingerprint) {
2038 return ParseFailed(line,
2039 "Failed to create fingerprint from the digest.",
2040 error);
2041 }
2042
2043 return true;
2044}
2045
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002046static bool ParseDtlsSetup(const std::string& line,
2047 cricket::ConnectionRole* role,
2048 SdpParseError* error) {
2049 // setup-attr = "a=setup:" role
2050 // role = "active" / "passive" / "actpass" / "holdconn"
2051 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002052 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002053 const size_t expected_fields = 2;
2054 if (fields.size() != expected_fields) {
2055 return ParseFailedExpectFieldNum(line, expected_fields, error);
2056 }
2057 std::string role_str = fields[1];
2058 if (!cricket::StringToConnectionRole(role_str, role)) {
2059 return ParseFailed(line, "Invalid attribute value.", error);
2060 }
2061 return true;
2062}
2063
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002064// RFC 3551
2065// PT encoding media type clock rate channels
2066// name (Hz)
2067// 0 PCMU A 8,000 1
2068// 1 reserved A
2069// 2 reserved A
2070// 3 GSM A 8,000 1
2071// 4 G723 A 8,000 1
2072// 5 DVI4 A 8,000 1
2073// 6 DVI4 A 16,000 1
2074// 7 LPC A 8,000 1
2075// 8 PCMA A 8,000 1
2076// 9 G722 A 8,000 1
2077// 10 L16 A 44,100 2
2078// 11 L16 A 44,100 1
2079// 12 QCELP A 8,000 1
2080// 13 CN A 8,000 1
2081// 14 MPA A 90,000 (see text)
2082// 15 G728 A 8,000 1
2083// 16 DVI4 A 11,025 1
2084// 17 DVI4 A 22,050 1
2085// 18 G729 A 8,000 1
2086struct StaticPayloadAudioCodec {
2087 const char* name;
2088 int clockrate;
2089 int channels;
2090};
2091static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2092 { "PCMU", 8000, 1 },
2093 { "reserved", 0, 0 },
2094 { "reserved", 0, 0 },
2095 { "GSM", 8000, 1 },
2096 { "G723", 8000, 1 },
2097 { "DVI4", 8000, 1 },
2098 { "DVI4", 16000, 1 },
2099 { "LPC", 8000, 1 },
2100 { "PCMA", 8000, 1 },
2101 { "G722", 8000, 1 },
2102 { "L16", 44100, 2 },
2103 { "L16", 44100, 1 },
2104 { "QCELP", 8000, 1 },
2105 { "CN", 8000, 1 },
2106 { "MPA", 90000, 1 },
2107 { "G728", 8000, 1 },
2108 { "DVI4", 11025, 1 },
2109 { "DVI4", 22050, 1 },
2110 { "G729", 8000, 1 },
2111};
2112
2113void MaybeCreateStaticPayloadAudioCodecs(
2114 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2115 if (!media_desc) {
2116 return;
2117 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002118 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002119 std::vector<int>::const_iterator it = fmts.begin();
2120 bool add_new_codec = false;
2121 for (; it != fmts.end(); ++it) {
2122 int payload_type = *it;
2123 if (!media_desc->HasCodec(payload_type) &&
2124 payload_type >= 0 &&
2125 payload_type < ARRAY_SIZE(kStaticPayloadAudioCodecs)) {
2126 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2127 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2128 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2129 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2130 clock_rate, 0, channels,
2131 preference));
2132 add_new_codec = true;
2133 }
2134 --preference;
2135 }
2136 if (add_new_codec) {
2137 media_desc->SortCodecs();
2138 }
2139}
2140
2141template <class C>
2142static C* ParseContentDescription(const std::string& message,
2143 const MediaType media_type,
2144 int mline_index,
2145 const std::string& protocol,
2146 const std::vector<int>& codec_preference,
2147 size_t* pos,
2148 std::string* content_name,
2149 TransportDescription* transport,
2150 std::vector<JsepIceCandidate*>* candidates,
2151 webrtc::SdpParseError* error) {
2152 C* media_desc = new C();
2153 switch (media_type) {
2154 case cricket::MEDIA_TYPE_AUDIO:
2155 *content_name = cricket::CN_AUDIO;
2156 break;
2157 case cricket::MEDIA_TYPE_VIDEO:
2158 *content_name = cricket::CN_VIDEO;
2159 break;
2160 case cricket::MEDIA_TYPE_DATA:
2161 *content_name = cricket::CN_DATA;
2162 break;
2163 default:
2164 ASSERT(false);
2165 break;
2166 }
2167 if (!ParseContent(message, media_type, mline_index, protocol,
2168 codec_preference, pos, content_name,
2169 media_desc, transport, candidates, error)) {
2170 delete media_desc;
2171 return NULL;
2172 }
2173 // Sort the codecs according to the m-line fmt list.
2174 media_desc->SortCodecs();
2175 return media_desc;
2176}
2177
2178bool ParseMediaDescription(const std::string& message,
2179 const TransportDescription& session_td,
2180 const RtpHeaderExtensions& session_extmaps,
2181 bool supports_msid,
2182 size_t* pos,
2183 cricket::SessionDescription* desc,
2184 std::vector<JsepIceCandidate*>* candidates,
2185 SdpParseError* error) {
2186 ASSERT(desc != NULL);
2187 std::string line;
2188 int mline_index = -1;
2189
2190 // Zero or more media descriptions
2191 // RFC 4566
2192 // m=<media> <port> <proto> <fmt>
2193 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2194 ++mline_index;
2195
2196 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002197 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002198 kSdpDelimiterSpace, &fields);
2199 const size_t expected_min_fields = 4;
2200 if (fields.size() < expected_min_fields) {
2201 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2202 }
2203 bool rejected = false;
2204 // RFC 3264
2205 // To reject an offered stream, the port number in the corresponding stream
2206 // in the answer MUST be set to zero.
2207 if (fields[1] == kMediaPortRejected) {
2208 rejected = true;
2209 }
2210
2211 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002212
2213 // <fmt>
2214 std::vector<int> codec_preference;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002215 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002216 for (size_t j = 3 ; j < fields.size(); ++j) {
2217 // TODO(wu): Remove when below bug is fixed.
2218 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
2219 if (fields[j] == "" && j == fields.size() - 1) {
2220 continue;
2221 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002222
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002223 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002224 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002225 return false;
2226 }
2227 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002228 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002229 }
2230
2231 // Make a temporary TransportDescription based on |session_td|.
2232 // Some of this gets overwritten by ParseContent.
2233 TransportDescription transport(NS_JINGLE_ICE_UDP,
2234 session_td.transport_options,
2235 session_td.ice_ufrag,
2236 session_td.ice_pwd,
2237 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002238 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002239 session_td.identity_fingerprint.get(),
2240 Candidates());
2241
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002242 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002243 std::string content_name;
2244 if (HasAttribute(line, kMediaTypeVideo)) {
2245 content.reset(ParseContentDescription<VideoContentDescription>(
2246 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2247 codec_preference, pos, &content_name,
2248 &transport, candidates, error));
2249 } else if (HasAttribute(line, kMediaTypeAudio)) {
2250 content.reset(ParseContentDescription<AudioContentDescription>(
2251 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2252 codec_preference, pos, &content_name,
2253 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002254 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002255 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002256 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002257 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2258 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002259 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002260 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002261
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002262 int p;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002263 if (data_desc && IsDtlsSctp(protocol) && rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002264 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002265 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002266 }
2267
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002268 // We should always use the default bandwidth for RTP-based data
2269 // channels. Don't allow SDP to set the bandwidth, because that
2270 // would give JS the opportunity to "break the Internet".
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002271 // TODO(pthatcher): But we need to temporarily allow the SDP to control
2272 // this for backwards-compatibility. Once we don't need that any
2273 // more, remove this.
2274 bool support_dc_sdp_bandwidth_temporarily = true;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00002275 if (content.get() && !support_dc_sdp_bandwidth_temporarily) {
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002276 content->set_bandwidth(cricket::kAutoBandwidth);
2277 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002278 } else {
2279 LOG(LS_WARNING) << "Unsupported media type: " << line;
2280 continue;
2281 }
2282 if (!content.get()) {
2283 // ParseContentDescription returns NULL if failed.
2284 return false;
2285 }
2286
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002287 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002288 // Make sure to set the media direction correctly. If the direction is not
2289 // MD_RECVONLY or Inactive and no streams are parsed,
2290 // a default MediaStream will be created to prepare for receiving media.
2291 if (supports_msid && content->streams().empty() &&
2292 content->direction() == cricket::MD_SENDRECV) {
2293 content->set_direction(cricket::MD_RECVONLY);
2294 }
2295
2296 // Set the extmap.
2297 if (!session_extmaps.empty() &&
2298 !content->rtp_header_extensions().empty()) {
2299 return ParseFailed("",
2300 "The a=extmap MUST be either all session level or "
2301 "all media level.",
2302 error);
2303 }
2304 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2305 content->AddRtpHeaderExtension(session_extmaps[i]);
2306 }
2307 }
2308 content->set_protocol(protocol);
2309 desc->AddContent(content_name,
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002310 IsDtlsSctp(protocol) ? cricket::NS_JINGLE_DRAFT_SCTP :
2311 cricket::NS_JINGLE_RTP,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002312 rejected,
2313 content.release());
2314 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2315 TransportInfo transport_info(content_name, transport);
2316
2317 if (!desc->AddTransportInfo(transport_info)) {
2318 std::ostringstream description;
2319 description << "Failed to AddTransportInfo with content name: "
2320 << content_name;
2321 return ParseFailed("", description.str(), error);
2322 }
2323 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002324
2325 size_t end_of_message = message.size();
2326 if (mline_index == -1 && *pos != end_of_message) {
2327 ParseFailed(message, *pos, "Expects m line.", error);
2328 return false;
2329 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002330 return true;
2331}
2332
2333bool VerifyCodec(const cricket::Codec& codec) {
2334 // Codec has not been populated correctly unless the name has been set. This
2335 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2336 // have a corresponding "rtpmap" line.
2337 cricket::Codec default_codec;
2338 return default_codec.name != codec.name;
2339}
2340
2341bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2342 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2343 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2344 iter != codecs.end(); ++iter) {
2345 if (!VerifyCodec(*iter)) {
2346 return false;
2347 }
2348 }
2349 return true;
2350}
2351
2352bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2353 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2354 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2355 iter != codecs.end(); ++iter) {
2356 if (!VerifyCodec(*iter)) {
2357 return false;
2358 }
2359 }
2360 return true;
2361}
2362
2363void AddParameters(const cricket::CodecParameterMap& parameters,
2364 cricket::Codec* codec) {
2365 for (cricket::CodecParameterMap::const_iterator iter =
2366 parameters.begin(); iter != parameters.end(); ++iter) {
2367 codec->SetParam(iter->first, iter->second);
2368 }
2369}
2370
2371void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2372 cricket::Codec* codec) {
2373 codec->AddFeedbackParam(feedback_param);
2374}
2375
2376void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2377 cricket::Codec* codec) {
2378 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2379 feedback_params.params().begin();
2380 iter != feedback_params.params().end(); ++iter) {
2381 codec->AddFeedbackParam(*iter);
2382 }
2383}
2384
2385// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002386// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002387// with that payload type.
2388template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002389T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2390 T ret_val;
2391 if (!FindCodecById(codecs, payload_type, &ret_val)) {
2392 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002393 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002394 return ret_val;
2395}
2396
2397// Updates or creates a new codec entry in the audio description.
2398template <class T, class U>
2399void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2400 T* desc = static_cast<T*>(content_desc);
2401 std::vector<U> codecs = desc->codecs();
2402 bool found = false;
2403
2404 typename std::vector<U>::iterator iter;
2405 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2406 if (iter->id == codec.id) {
2407 *iter = codec;
2408 found = true;
2409 break;
2410 }
2411 }
2412 if (!found) {
2413 desc->AddCodec(codec);
2414 return;
2415 }
2416 desc->set_codecs(codecs);
2417}
2418
2419// Adds or updates existing codec corresponding to |payload_type| according
2420// to |parameters|.
2421template <class T, class U>
2422void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2423 const cricket::CodecParameterMap& parameters) {
2424 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002425 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2426 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002427 AddParameters(parameters, &new_codec);
2428 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2429}
2430
2431// Adds or updates existing codec corresponding to |payload_type| according
2432// to |feedback_param|.
2433template <class T, class U>
2434void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2435 const cricket::FeedbackParam& feedback_param) {
2436 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002437 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2438 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002439 AddFeedbackParameter(feedback_param, &new_codec);
2440 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2441}
2442
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002443template <class T>
2444bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2445 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002446 if (iter->id == kWildcardPayloadType) {
2447 *wildcard_codec = *iter;
2448 codecs->erase(iter);
2449 return true;
2450 }
2451 }
2452 return false;
2453}
2454
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002455template<class T>
2456void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2457 auto codecs = desc->codecs();
2458 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002459 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2460 return;
2461 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002462 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002463 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2464 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002465 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002466}
2467
2468void AddAudioAttribute(const std::string& name, const std::string& value,
2469 AudioContentDescription* audio_desc) {
2470 if (value.empty()) {
2471 return;
2472 }
2473 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2474 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2475 iter != codecs.end(); ++iter) {
2476 iter->params[name] = value;
2477 }
2478 audio_desc->set_codecs(codecs);
2479}
2480
2481bool ParseContent(const std::string& message,
2482 const MediaType media_type,
2483 int mline_index,
2484 const std::string& protocol,
2485 const std::vector<int>& codec_preference,
2486 size_t* pos,
2487 std::string* content_name,
2488 MediaContentDescription* media_desc,
2489 TransportDescription* transport,
2490 std::vector<JsepIceCandidate*>* candidates,
2491 SdpParseError* error) {
2492 ASSERT(media_desc != NULL);
2493 ASSERT(content_name != NULL);
2494 ASSERT(transport != NULL);
2495
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002496 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2497 MaybeCreateStaticPayloadAudioCodecs(
2498 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2499 }
2500
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002501 // The media level "ice-ufrag" and "ice-pwd".
2502 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2503 Candidates candidates_orig;
2504 std::string line;
2505 std::string mline_id;
2506 // Tracks created out of the ssrc attributes.
2507 StreamParamsVec tracks;
2508 SsrcInfoVec ssrc_infos;
2509 SsrcGroupVec ssrc_groups;
2510 std::string maxptime_as_string;
2511 std::string ptime_as_string;
2512
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002513 // Loop until the next m line
2514 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2515 if (!GetLine(message, pos, &line)) {
2516 if (*pos >= message.size()) {
2517 break; // Done parsing
2518 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002519 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002520 }
2521 }
2522
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002523 // RFC 4566
2524 // b=* (zero or more bandwidth information lines)
2525 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2526 std::string bandwidth;
2527 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2528 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2529 return false;
2530 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002531 int b = 0;
2532 if (!GetValueFromString(line, bandwidth, &b, error)) {
2533 return false;
2534 }
2535 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002536 }
2537 }
2538 continue;
2539 }
2540
2541 if (!IsLineType(line, kLineTypeAttributes)) {
2542 // TODO: Handle other lines if needed.
2543 LOG(LS_INFO) << "Ignored line: " << line;
2544 continue;
2545 }
2546
2547 // Handle attributes common to SCTP and RTP.
2548 if (HasAttribute(line, kAttributeMid)) {
2549 // RFC 3388
2550 // mid-attribute = "a=mid:" identification-tag
2551 // identification-tag = token
2552 // Use the mid identification-tag as the content name.
2553 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2554 return false;
2555 }
2556 *content_name = mline_id;
2557 } else if (HasAttribute(line, kAttributeCandidate)) {
2558 Candidate candidate;
2559 if (!ParseCandidate(line, &candidate, error, false)) {
2560 return false;
2561 }
2562 candidates_orig.push_back(candidate);
2563 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2564 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2565 return false;
2566 }
2567 } else if (HasAttribute(line, kAttributeIcePwd)) {
2568 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2569 return false;
2570 }
2571 } else if (HasAttribute(line, kAttributeIceOption)) {
2572 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2573 return false;
2574 }
2575 } else if (HasAttribute(line, kAttributeFmtp)) {
2576 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2577 return false;
2578 }
2579 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002580 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002581
2582 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2583 return false;
2584 }
2585 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002586 } else if (HasAttribute(line, kAttributeSetup)) {
2587 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2588 return false;
2589 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002590 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002591 int sctp_port;
2592 if (!ParseSctpPort(line, &sctp_port, error)) {
2593 return false;
2594 }
2595 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2596 sctp_port)) {
2597 return false;
2598 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002599 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002600 //
2601 // RTP specific attrubtes
2602 //
2603 if (HasAttribute(line, kAttributeRtcpMux)) {
2604 media_desc->set_rtcp_mux(true);
2605 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2606 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2607 return false;
2608 }
2609 } else if (HasAttribute(line, kAttributeSsrc)) {
2610 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2611 return false;
2612 }
2613 } else if (HasAttribute(line, kAttributeCrypto)) {
2614 if (!ParseCryptoAttribute(line, media_desc, error)) {
2615 return false;
2616 }
2617 } else if (HasAttribute(line, kAttributeRtpmap)) {
2618 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2619 media_desc, error)) {
2620 return false;
2621 }
2622 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2623 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2624 return false;
2625 }
2626 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2627 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2628 return false;
2629 }
2630 } else if (HasAttribute(line, kCodecParamPTime)) {
2631 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2632 return false;
2633 }
2634 } else if (HasAttribute(line, kAttributeSendOnly)) {
2635 media_desc->set_direction(cricket::MD_SENDONLY);
2636 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2637 media_desc->set_direction(cricket::MD_RECVONLY);
2638 } else if (HasAttribute(line, kAttributeInactive)) {
2639 media_desc->set_direction(cricket::MD_INACTIVE);
2640 } else if (HasAttribute(line, kAttributeSendRecv)) {
2641 media_desc->set_direction(cricket::MD_SENDRECV);
2642 } else if (HasAttribute(line, kAttributeExtmap)) {
2643 RtpHeaderExtension extmap;
2644 if (!ParseExtmap(line, &extmap, error)) {
2645 return false;
2646 }
2647 media_desc->AddRtpHeaderExtension(extmap);
2648 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2649 // Experimental attribute. Conference mode activates more aggressive
2650 // AEC and NS settings.
2651 // TODO: expose API to set these directly.
2652 std::string flag_value;
2653 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2654 return false;
2655 }
2656 if (flag_value.compare(kValueConference) == 0)
2657 media_desc->set_conference_mode(true);
2658 } else if (HasAttribute(line, kAttributeXGoogleBufferLatency)) {
2659 // Experimental attribute.
2660 // TODO: expose API to set this directly.
2661 std::string flag_value;
2662 if (!GetValue(line, kAttributeXGoogleBufferLatency, &flag_value,
2663 error)) {
2664 return false;
2665 }
2666 int buffer_latency = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002667 if (!GetValueFromString(line, flag_value, &buffer_latency, error)) {
2668 return false;
2669 }
2670 if (buffer_latency < 0) {
2671 return ParseFailed(line, "Buffer latency less than 0.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002672 }
2673 media_desc->set_buffered_mode_latency(buffer_latency);
2674 }
2675 } else {
2676 // Only parse lines that we are interested of.
2677 LOG(LS_INFO) << "Ignored line: " << line;
2678 continue;
2679 }
2680 }
2681
2682 // Create tracks from the |ssrc_infos|.
2683 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2684
2685 // Add the ssrc group to the track.
2686 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2687 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2688 if (ssrc_group->ssrcs.empty()) {
2689 continue;
2690 }
2691 uint32 ssrc = ssrc_group->ssrcs.front();
2692 for (StreamParamsVec::iterator track = tracks.begin();
2693 track != tracks.end(); ++track) {
2694 if (track->has_ssrc(ssrc)) {
2695 track->ssrc_groups.push_back(*ssrc_group);
2696 }
2697 }
2698 }
2699
2700 // Add the new tracks to the |media_desc|.
2701 for (StreamParamsVec::iterator track = tracks.begin();
2702 track != tracks.end(); ++track) {
2703 media_desc->AddStream(*track);
2704 }
2705
2706 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2707 AudioContentDescription* audio_desc =
2708 static_cast<AudioContentDescription*>(media_desc);
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002709 UpdateFromWildcardCodecs(audio_desc);
2710
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002711 // Verify audio codec ensures that no audio codec has been populated with
2712 // only fmtp.
2713 if (!VerifyAudioCodecs(audio_desc)) {
2714 return ParseFailed("Failed to parse audio codecs correctly.", error);
2715 }
2716 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2717 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2718 }
2719
2720 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002721 VideoContentDescription* video_desc =
2722 static_cast<VideoContentDescription*>(media_desc);
2723 UpdateFromWildcardCodecs(video_desc);
2724 // Verify video codec ensures that no video codec has been populated with
2725 // only rtcp-fb.
2726 if (!VerifyVideoCodecs(video_desc)) {
2727 return ParseFailed("Failed to parse video codecs correctly.", error);
2728 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002729 }
2730
2731 // RFC 5245
2732 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2733 for (Candidates::iterator it = candidates_orig.begin();
2734 it != candidates_orig.end(); ++it) {
2735 ASSERT((*it).username().empty());
2736 (*it).set_username(transport->ice_ufrag);
2737 ASSERT((*it).password().empty());
2738 (*it).set_password(transport->ice_pwd);
2739 candidates->push_back(
2740 new JsepIceCandidate(mline_id, mline_index, *it));
2741 }
2742 return true;
2743}
2744
2745bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2746 SdpParseError* error) {
2747 ASSERT(ssrc_infos != NULL);
2748 // RFC 5576
2749 // a=ssrc:<ssrc-id> <attribute>
2750 // a=ssrc:<ssrc-id> <attribute>:<value>
2751 std::string field1, field2;
2752 if (!SplitByDelimiter(line.substr(kLinePrefixLength),
2753 kSdpDelimiterSpace,
2754 &field1,
2755 &field2)) {
2756 const size_t expected_fields = 2;
2757 return ParseFailedExpectFieldNum(line, expected_fields, error);
2758 }
2759
2760 // ssrc:<ssrc-id>
2761 std::string ssrc_id_s;
2762 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2763 return false;
2764 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002765 uint32 ssrc_id = 0;
2766 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2767 return false;
2768 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002769
2770 std::string attribute;
2771 std::string value;
2772 if (!SplitByDelimiter(field2, kSdpDelimiterColon,
2773 &attribute, &value)) {
2774 std::ostringstream description;
2775 description << "Failed to get the ssrc attribute value from " << field2
2776 << ". Expected format <attribute>:<value>.";
2777 return ParseFailed(line, description.str(), error);
2778 }
2779
2780 // Check if there's already an item for this |ssrc_id|. Create a new one if
2781 // there isn't.
2782 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2783 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2784 if (ssrc_info->ssrc_id == ssrc_id) {
2785 break;
2786 }
2787 }
2788 if (ssrc_info == ssrc_infos->end()) {
2789 SsrcInfo info;
2790 info.ssrc_id = ssrc_id;
2791 ssrc_infos->push_back(info);
2792 ssrc_info = ssrc_infos->end() - 1;
2793 }
2794
2795 // Store the info to the |ssrc_info|.
2796 if (attribute == kSsrcAttributeCname) {
2797 // RFC 5576
2798 // cname:<value>
2799 ssrc_info->cname = value;
2800 } else if (attribute == kSsrcAttributeMsid) {
2801 // draft-alvestrand-mmusic-msid-00
2802 // "msid:" identifier [ " " appdata ]
2803 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002804 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002805 if (fields.size() < 1 || fields.size() > 2) {
2806 return ParseFailed(line,
2807 "Expected format \"msid:<identifier>[ <appdata>]\".",
2808 error);
2809 }
2810 ssrc_info->msid_identifier = fields[0];
2811 if (fields.size() == 2) {
2812 ssrc_info->msid_appdata = fields[1];
2813 }
2814 } else if (attribute == kSsrcAttributeMslabel) {
2815 // draft-alvestrand-rtcweb-mid-01
2816 // mslabel:<value>
2817 ssrc_info->mslabel = value;
2818 } else if (attribute == kSSrcAttributeLabel) {
2819 // The label isn't defined.
2820 // label:<value>
2821 ssrc_info->label = value;
2822 }
2823 return true;
2824}
2825
2826bool ParseSsrcGroupAttribute(const std::string& line,
2827 SsrcGroupVec* ssrc_groups,
2828 SdpParseError* error) {
2829 ASSERT(ssrc_groups != NULL);
2830 // RFC 5576
2831 // a=ssrc-group:<semantics> <ssrc-id> ...
2832 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002833 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002834 kSdpDelimiterSpace, &fields);
2835 const size_t expected_min_fields = 2;
2836 if (fields.size() < expected_min_fields) {
2837 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2838 }
2839 std::string semantics;
2840 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2841 return false;
2842 }
2843 std::vector<uint32> ssrcs;
2844 for (size_t i = 1; i < fields.size(); ++i) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002845 uint32 ssrc = 0;
2846 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2847 return false;
2848 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002849 ssrcs.push_back(ssrc);
2850 }
2851 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2852 return true;
2853}
2854
2855bool ParseCryptoAttribute(const std::string& line,
2856 MediaContentDescription* media_desc,
2857 SdpParseError* error) {
2858 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002859 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002860 kSdpDelimiterSpace, &fields);
2861 // RFC 4568
2862 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2863 const size_t expected_min_fields = 3;
2864 if (fields.size() < expected_min_fields) {
2865 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2866 }
2867 std::string tag_value;
2868 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2869 return false;
2870 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002871 int tag = 0;
2872 if (!GetValueFromString(line, tag_value, &tag, error)) {
2873 return false;
2874 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002875 const std::string crypto_suite = fields[1];
2876 const std::string key_params = fields[2];
2877 std::string session_params;
2878 if (fields.size() > 3) {
2879 session_params = fields[3];
2880 }
2881 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2882 session_params));
2883 return true;
2884}
2885
2886// Updates or creates a new codec entry in the audio description with according
2887// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2888void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2889 int bitrate, int channels, int preference,
2890 AudioContentDescription* audio_desc) {
2891 // Codec may already be populated with (only) optional parameters
2892 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002893 cricket::AudioCodec codec =
2894 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002895 codec.name = name;
2896 codec.clockrate = clockrate;
2897 codec.bitrate = bitrate;
2898 codec.channels = channels;
2899 codec.preference = preference;
2900 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2901 codec);
2902}
2903
2904// Updates or creates a new codec entry in the video description according to
2905// |name|, |width|, |height|, |framerate| and |preference|.
2906void UpdateCodec(int payload_type, const std::string& name, int width,
2907 int height, int framerate, int preference,
2908 VideoContentDescription* video_desc) {
2909 // Codec may already be populated with (only) optional parameters
2910 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002911 cricket::VideoCodec codec =
2912 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002913 codec.name = name;
2914 codec.width = width;
2915 codec.height = height;
2916 codec.framerate = framerate;
2917 codec.preference = preference;
2918 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2919 codec);
2920}
2921
2922bool ParseRtpmapAttribute(const std::string& line,
2923 const MediaType media_type,
2924 const std::vector<int>& codec_preference,
2925 MediaContentDescription* media_desc,
2926 SdpParseError* error) {
2927 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002928 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002929 kSdpDelimiterSpace, &fields);
2930 // RFC 4566
2931 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2932 const size_t expected_min_fields = 2;
2933 if (fields.size() < expected_min_fields) {
2934 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2935 }
2936 std::string payload_type_value;
2937 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2938 return false;
2939 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002940 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002941 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
2942 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002943 return false;
2944 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002945
2946 // Set the preference order depending on the order of the pl type in the
2947 // <fmt> of the m-line.
2948 const int preference = codec_preference.end() -
2949 std::find(codec_preference.begin(), codec_preference.end(),
2950 payload_type);
2951 if (preference == 0) {
2952 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2953 << "<fmt> of the m-line: " << line;
2954 return true;
2955 }
2956 const std::string encoder = fields[1];
2957 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002958 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002959 // <encoding name>/<clock rate>[/<encodingparameters>]
2960 // 2 mandatory fields
2961 if (codec_params.size() < 2 || codec_params.size() > 3) {
2962 return ParseFailed(line,
2963 "Expected format \"<encoding name>/<clock rate>"
2964 "[/<encodingparameters>]\".",
2965 error);
2966 }
2967 const std::string encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002968 int clock_rate = 0;
2969 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2970 return false;
2971 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002972 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2973 VideoContentDescription* video_desc =
2974 static_cast<VideoContentDescription*>(media_desc);
2975 // TODO: We will send resolution in SDP. For now use
2976 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2977 UpdateCodec(payload_type, encoding_name,
2978 JsepSessionDescription::kMaxVideoCodecWidth,
2979 JsepSessionDescription::kMaxVideoCodecHeight,
2980 JsepSessionDescription::kDefaultVideoCodecFramerate,
2981 preference, video_desc);
2982 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2983 // RFC 4566
2984 // For audio streams, <encoding parameters> indicates the number
2985 // of audio channels. This parameter is OPTIONAL and may be
2986 // omitted if the number of channels is one, provided that no
2987 // additional parameters are needed.
2988 int channels = 1;
2989 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002990 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2991 return false;
2992 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002993 }
2994 int bitrate = 0;
2995 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2996 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2997 // The bandwidth adaptation doesn't always work well, so this code
2998 // sets a fixed target bitrate instead.
2999 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
3000 if (clock_rate <= 16000) {
3001 bitrate = kIsacWbDefaultRate;
3002 } else {
3003 bitrate = kIsacSwbDefaultRate;
3004 }
3005 }
3006 AudioContentDescription* audio_desc =
3007 static_cast<AudioContentDescription*>(media_desc);
3008 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
3009 preference, audio_desc);
3010 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
3011 DataContentDescription* data_desc =
3012 static_cast<DataContentDescription*>(media_desc);
3013 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
3014 preference));
3015 }
3016 return true;
3017}
3018
3019void PruneRight(const char delimiter, std::string* message) {
3020 size_t trailing = message->find(delimiter);
3021 if (trailing != std::string::npos) {
3022 *message = message->substr(0, trailing);
3023 }
3024}
3025
3026bool ParseFmtpParam(const std::string& line, std::string* parameter,
3027 std::string* value, SdpParseError* error) {
3028 if (!SplitByDelimiter(line, kSdpDelimiterEqual, parameter, value)) {
3029 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
3030 return false;
3031 }
3032 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
3033 // When parsing the values the trailing ";" gets picked up. Remove them.
3034 PruneRight(kSdpDelimiterSemicolon, value);
3035 return true;
3036}
3037
3038bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
3039 MediaContentDescription* media_desc,
3040 SdpParseError* error) {
3041 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3042 media_type != cricket::MEDIA_TYPE_VIDEO) {
3043 return true;
3044 }
3045 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003046 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003047 kSdpDelimiterSpace, &fields);
3048
3049 // RFC 5576
3050 // a=fmtp:<format> <format specific parameters>
3051 // At least two fields, whereas the second one is any of the optional
3052 // parameters.
3053 if (fields.size() < 2) {
3054 ParseFailedExpectMinFieldNum(line, 2, error);
3055 return false;
3056 }
3057
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003058 std::string payload_type_str;
3059 if (!GetValue(fields[0], kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003060 return false;
3061 }
3062
3063 cricket::CodecParameterMap codec_params;
3064 for (std::vector<std::string>::const_iterator iter = fields.begin() + 1;
3065 iter != fields.end(); ++iter) {
3066 std::string name;
3067 std::string value;
3068 if (iter->find(kSdpDelimiterEqual) == std::string::npos) {
3069 // Only fmtps with equals are currently supported. Other fmtp types
3070 // should be ignored. Unknown fmtps do not constitute an error.
3071 continue;
3072 }
3073 if (!ParseFmtpParam(*iter, &name, &value, error)) {
3074 return false;
3075 }
3076 codec_params[name] = value;
3077 }
3078
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003079 int payload_type = 0;
3080 if (!GetPayloadTypeFromString(line, payload_type_str, &payload_type, error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003081 return false;
3082 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003083 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3084 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003085 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003086 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3087 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003088 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003089 }
3090 return true;
3091}
3092
3093bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3094 MediaContentDescription* media_desc,
3095 SdpParseError* error) {
3096 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3097 media_type != cricket::MEDIA_TYPE_VIDEO) {
3098 return true;
3099 }
3100 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003101 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003102 if (rtcp_fb_fields.size() < 2) {
3103 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3104 }
3105 std::string payload_type_string;
3106 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3107 error)) {
3108 return false;
3109 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003110 int payload_type = kWildcardPayloadType;
3111 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003112 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3113 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003114 return false;
3115 }
3116 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003117 std::string id = rtcp_fb_fields[1];
3118 std::string param = "";
3119 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3120 iter != rtcp_fb_fields.end(); ++iter) {
3121 param.append(*iter);
3122 }
3123 const cricket::FeedbackParam feedback_param(id, param);
3124
3125 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003126 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3127 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003128 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003129 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3130 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003131 }
3132 return true;
3133}
3134
3135} // namespace webrtc