blob: bc5dc1d1da5caf69524b8d0d4bd4aa819640fb0f [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"
tfarina5237aaf2015-11-10 23:44:30 -080048#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000049#include "webrtc/base/common.h"
50#include "webrtc/base/logging.h"
51#include "webrtc/base/messagedigest.h"
52#include "webrtc/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000053
54using cricket::AudioContentDescription;
55using cricket::Candidate;
56using cricket::Candidates;
57using cricket::ContentDescription;
58using cricket::ContentInfo;
59using cricket::CryptoParams;
60using cricket::DataContentDescription;
61using cricket::ICE_CANDIDATE_COMPONENT_RTP;
62using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
63using cricket::kCodecParamMaxBitrate;
64using cricket::kCodecParamMaxPTime;
65using cricket::kCodecParamMaxQuantization;
66using cricket::kCodecParamMinBitrate;
67using cricket::kCodecParamMinPTime;
68using cricket::kCodecParamPTime;
69using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000070using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071using cricket::kCodecParamStereo;
72using cricket::kCodecParamUseInbandFec;
Minyue Li7100dcd2015-03-27 05:05:59 +010073using cricket::kCodecParamUseDtx;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074using cricket::kCodecParamSctpProtocol;
75using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000076using cricket::kCodecParamMaxAverageBitrate;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000077using cricket::kCodecParamMaxPlaybackRate;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000078using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000079using cricket::MediaContentDescription;
80using cricket::MediaType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000081using 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";
deadbeef13871492015-12-09 12:37:51 -0800125static const char kAttributeRtcpReducedSize[] = "rtcp-rsize";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000126static const char kAttributeSsrc[] = "ssrc";
127static const char kSsrcAttributeCname[] = "cname";
128static const char kAttributeExtmap[] = "extmap";
129// draft-alvestrand-mmusic-msid-01
130// a=msid-semantic: WMS
131static const char kAttributeMsidSemantics[] = "msid-semantic";
132static const char kMediaStreamSemantic[] = "WMS";
133static const char kSsrcAttributeMsid[] = "msid";
134static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000135static const char kSsrcAttributeMslabel[] = "mslabel";
136static const char kSSrcAttributeLabel[] = "label";
137static const char kAttributeSsrcGroup[] = "ssrc-group";
138static const char kAttributeCrypto[] = "crypto";
139static const char kAttributeCandidate[] = "candidate";
140static const char kAttributeCandidateTyp[] = "typ";
141static const char kAttributeCandidateRaddr[] = "raddr";
142static const char kAttributeCandidateRport[] = "rport";
143static const char kAttributeCandidateUsername[] = "username";
144static const char kAttributeCandidatePassword[] = "password";
145static const char kAttributeCandidateGeneration[] = "generation";
146static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000147static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000148static const char kAttributeFmtp[] = "fmtp";
149static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000150static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000151static const char kAttributeRtcp[] = "rtcp";
152static const char kAttributeIceUfrag[] = "ice-ufrag";
153static const char kAttributeIcePwd[] = "ice-pwd";
154static const char kAttributeIceLite[] = "ice-lite";
155static const char kAttributeIceOption[] = "ice-options";
156static const char kAttributeSendOnly[] = "sendonly";
157static const char kAttributeRecvOnly[] = "recvonly";
158static const char kAttributeRtcpFb[] = "rtcp-fb";
159static const char kAttributeSendRecv[] = "sendrecv";
160static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000161// draft-ietf-mmusic-sctp-sdp-07
162// a=sctp-port
163static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000164
165// Experimental flags
166static const char kAttributeXGoogleFlag[] = "x-google-flag";
167static const char kValueConference[] = "conference";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000168
169// Candidate
170static const char kCandidateHost[] = "host";
171static const char kCandidateSrflx[] = "srflx";
172// TODO: How to map the prflx with circket candidate type
173// static const char kCandidatePrflx[] = "prflx";
174static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000175static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176
177static const char kSdpDelimiterEqual = '=';
178static const char kSdpDelimiterSpace = ' ';
179static const char kSdpDelimiterColon = ':';
180static const char kSdpDelimiterSemicolon = ';';
181static const char kSdpDelimiterSlash = '/';
182static const char kNewLine = '\n';
183static const char kReturn = '\r';
184static const char kLineBreak[] = "\r\n";
185
186// TODO: Generate the Session and Time description
187// instead of hardcoding.
188static const char kSessionVersion[] = "v=0";
189// RFC 4566
190static const char kSessionOriginUsername[] = "-";
191static const char kSessionOriginSessionId[] = "0";
192static const char kSessionOriginSessionVersion[] = "0";
193static const char kSessionOriginNettype[] = "IN";
194static const char kSessionOriginAddrtype[] = "IP4";
195static const char kSessionOriginAddress[] = "127.0.0.1";
196static const char kSessionName[] = "s=-";
197static const char kTimeDescription[] = "t=0 0";
198static const char kAttrGroup[] = "a=group:BUNDLE";
199static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000200static const char kConnectionIpv4Addrtype[] = "IP4";
201static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000202static const char kMediaTypeVideo[] = "video";
203static const char kMediaTypeAudio[] = "audio";
204static const char kMediaTypeData[] = "application";
205static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000206// draft-ietf-mmusic-trickle-ice-01
207// When no candidates have been gathered, set the connection
208// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000209// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
210// Use IPV4 per default.
211static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000212static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000213// RFC 3556
214static const char kApplicationSpecificMaximum[] = "AS";
215
216static const int kDefaultVideoClockrate = 90000;
217
218// ISAC special-case.
219static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
220static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
221static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
222
wu@webrtc.org78187522013-10-07 23:32:02 +0000223static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000224
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000225// RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
226// types.
227const int kWildcardPayloadType = -1;
228
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000229struct SsrcInfo {
230 SsrcInfo()
231 : msid_identifier(kDefaultMsid),
232 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
233 // Create random string (which will be used as track label later)?
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000234 msid_appdata(rtc::CreateRandomString(8)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000235 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200236 uint32_t ssrc_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000237 std::string cname;
238 std::string msid_identifier;
239 std::string msid_appdata;
240
241 // For backward compatibility.
242 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
243 std::string label;
244 std::string mslabel;
245};
246typedef std::vector<SsrcInfo> SsrcInfoVec;
247typedef std::vector<SsrcGroup> SsrcGroupVec;
248
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249template <class T>
250static void AddFmtpLine(const T& codec, std::string* message);
251static void BuildMediaDescription(const ContentInfo* content_info,
252 const TransportInfo* transport_info,
253 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000254 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000255 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000256static void BuildSctpContentAttributes(std::string* message, int sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000257static void BuildRtpContentAttributes(
258 const MediaContentDescription* media_desc,
259 const MediaType media_type,
260 std::string* message);
261static void BuildRtpMap(const MediaContentDescription* media_desc,
262 const MediaType media_type,
263 std::string* message);
264static void BuildCandidate(const std::vector<Candidate>& candidates,
265 std::string* message);
266static void BuildIceOptions(const std::vector<std::string>& transport_options,
267 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000268static bool IsRtp(const std::string& protocol);
269static bool IsDtlsSctp(const std::string& protocol);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000270static bool ParseSessionDescription(const std::string& message, size_t* pos,
271 std::string* session_id,
272 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000273 TransportDescription* session_td,
274 RtpHeaderExtensions* session_extmaps,
275 cricket::SessionDescription* desc,
276 SdpParseError* error);
277static bool ParseGroupAttribute(const std::string& line,
278 cricket::SessionDescription* desc,
279 SdpParseError* error);
280static bool ParseMediaDescription(
281 const std::string& message,
282 const TransportDescription& session_td,
283 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000284 size_t* pos, cricket::SessionDescription* desc,
285 std::vector<JsepIceCandidate*>* candidates,
286 SdpParseError* error);
287static bool ParseContent(const std::string& message,
288 const MediaType media_type,
289 int mline_index,
290 const std::string& protocol,
291 const std::vector<int>& codec_preference,
292 size_t* pos,
293 std::string* content_name,
294 MediaContentDescription* media_desc,
295 TransportDescription* transport,
296 std::vector<JsepIceCandidate*>* candidates,
297 SdpParseError* error);
298static bool ParseSsrcAttribute(const std::string& line,
299 SsrcInfoVec* ssrc_infos,
300 SdpParseError* error);
301static bool ParseSsrcGroupAttribute(const std::string& line,
302 SsrcGroupVec* ssrc_groups,
303 SdpParseError* error);
304static bool ParseCryptoAttribute(const std::string& line,
305 MediaContentDescription* media_desc,
306 SdpParseError* error);
307static bool ParseRtpmapAttribute(const std::string& line,
308 const MediaType media_type,
309 const std::vector<int>& codec_preference,
310 MediaContentDescription* media_desc,
311 SdpParseError* error);
312static bool ParseFmtpAttributes(const std::string& line,
313 const MediaType media_type,
314 MediaContentDescription* media_desc,
315 SdpParseError* error);
316static bool ParseFmtpParam(const std::string& line, std::string* parameter,
317 std::string* value, SdpParseError* error);
318static bool ParseCandidate(const std::string& message, Candidate* candidate,
319 SdpParseError* error, bool is_raw);
320static bool ParseRtcpFbAttribute(const std::string& line,
321 const MediaType media_type,
322 MediaContentDescription* media_desc,
323 SdpParseError* error);
324static bool ParseIceOptions(const std::string& line,
325 std::vector<std::string>* transport_options,
326 SdpParseError* error);
327static bool ParseExtmap(const std::string& line,
328 RtpHeaderExtension* extmap,
329 SdpParseError* error);
330static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000331 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000332 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000333static bool ParseDtlsSetup(const std::string& line,
334 cricket::ConnectionRole* role,
335 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000336
337// Helper functions
338
339// Below ParseFailed*** functions output the line that caused the parsing
340// failure and the detailed reason (|description|) of the failure to |error|.
341// The functions always return false so that they can be used directly in the
342// following way when error happens:
343// "return ParseFailed***(...);"
344
345// The line starting at |line_start| of |message| is the failing line.
346// The reason for the failure should be provided in the |description|.
347// An example of a description could be "unknown character".
348static bool ParseFailed(const std::string& message,
349 size_t line_start,
350 const std::string& description,
351 SdpParseError* error) {
352 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000353 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000354 size_t line_end = message.find(kNewLine, line_start);
355 if (line_end != std::string::npos) {
356 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
357 --line_end;
358 }
359 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000360 } else {
361 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000362 }
363
364 if (error) {
365 error->line = first_line;
366 error->description = description;
367 }
368 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
369 << "\". Reason: " << description;
370 return false;
371}
372
373// |line| is the failing line. The reason for the failure should be
374// provided in the |description|.
375static bool ParseFailed(const std::string& line,
376 const std::string& description,
377 SdpParseError* error) {
378 return ParseFailed(line, 0, description, error);
379}
380
381// Parses failure where the failing SDP line isn't know or there are multiple
382// failing lines.
383static bool ParseFailed(const std::string& description,
384 SdpParseError* error) {
385 return ParseFailed("", description, error);
386}
387
388// |line| is the failing line. The failure is due to the fact that |line|
389// doesn't have |expected_fields| fields.
390static bool ParseFailedExpectFieldNum(const std::string& line,
391 int expected_fields,
392 SdpParseError* error) {
393 std::ostringstream description;
394 description << "Expects " << expected_fields << " fields.";
395 return ParseFailed(line, description.str(), error);
396}
397
398// |line| is the failing line. The failure is due to the fact that |line| has
399// less than |expected_min_fields| fields.
400static bool ParseFailedExpectMinFieldNum(const std::string& line,
401 int expected_min_fields,
402 SdpParseError* error) {
403 std::ostringstream description;
404 description << "Expects at least " << expected_min_fields << " fields.";
405 return ParseFailed(line, description.str(), error);
406}
407
408// |line| is the failing line. The failure is due to the fact that it failed to
409// get the value of |attribute|.
410static bool ParseFailedGetValue(const std::string& line,
411 const std::string& attribute,
412 SdpParseError* error) {
413 std::ostringstream description;
414 description << "Failed to get the value of attribute: " << attribute;
415 return ParseFailed(line, description.str(), error);
416}
417
418// The line starting at |line_start| of |message| is the failing line. The
419// failure is due to the line type (e.g. the "m" part of the "m-line")
420// not matching what is expected. The expected line type should be
421// provided as |line_type|.
422static bool ParseFailedExpectLine(const std::string& message,
423 size_t line_start,
424 const char line_type,
425 const std::string& line_value,
426 SdpParseError* error) {
427 std::ostringstream description;
428 description << "Expect line: " << line_type << "=" << line_value;
429 return ParseFailed(message, line_start, description.str(), error);
430}
431
432static bool AddLine(const std::string& line, std::string* message) {
433 if (!message)
434 return false;
435
436 message->append(line);
437 message->append(kLineBreak);
438 return true;
439}
440
441static bool GetLine(const std::string& message,
442 size_t* pos,
443 std::string* line) {
444 size_t line_begin = *pos;
445 size_t line_end = message.find(kNewLine, line_begin);
446 if (line_end == std::string::npos) {
447 return false;
448 }
449 // Update the new start position
450 *pos = line_end + 1;
451 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
452 --line_end;
453 }
454 *line = message.substr(line_begin, (line_end - line_begin));
455 const char* cline = line->c_str();
456 // RFC 4566
457 // An SDP session description consists of a number of lines of text of
458 // the form:
459 // <type>=<value>
460 // where <type> MUST be exactly one case-significant character and
461 // <value> is structured text whose format depends on <type>.
462 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000463 if (line->length() < 3 ||
464 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000465 cline[1] != kSdpDelimiterEqual ||
466 cline[2] == kSdpDelimiterSpace) {
467 *pos = line_begin;
468 return false;
469 }
470 return true;
471}
472
473// Init |os| to "|type|=|value|".
474static void InitLine(const char type,
475 const std::string& value,
476 std::ostringstream* os) {
477 os->str("");
478 *os << type << kSdpDelimiterEqual << value;
479}
480
481// Init |os| to "a=|attribute|".
482static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
483 InitLine(kLineTypeAttributes, attribute, os);
484}
485
486// Writes a SDP attribute line based on |attribute| and |value| to |message|.
487static void AddAttributeLine(const std::string& attribute, int value,
488 std::string* message) {
489 std::ostringstream os;
490 InitAttrLine(attribute, &os);
491 os << kSdpDelimiterColon << value;
492 AddLine(os.str(), message);
493}
494
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000495static bool IsLineType(const std::string& message,
496 const char type,
497 size_t line_start) {
498 if (message.size() < line_start + kLinePrefixLength) {
499 return false;
500 }
501 const char* cmessage = message.c_str();
502 return (cmessage[line_start] == type &&
503 cmessage[line_start + 1] == kSdpDelimiterEqual);
504}
505
506static bool IsLineType(const std::string& line,
507 const char type) {
508 return IsLineType(line, type, 0);
509}
510
511static bool GetLineWithType(const std::string& message, size_t* pos,
512 std::string* line, const char type) {
513 if (!IsLineType(message, type, *pos)) {
514 return false;
515 }
516
517 if (!GetLine(message, pos, line))
518 return false;
519
520 return true;
521}
522
523static bool HasAttribute(const std::string& line,
524 const std::string& attribute) {
525 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
526}
527
Peter Boström0c4e06b2015-10-07 12:23:21 +0200528static bool AddSsrcLine(uint32_t ssrc_id,
529 const std::string& attribute,
530 const std::string& value,
531 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000532 // RFC 5576
533 // a=ssrc:<ssrc-id> <attribute>:<value>
534 std::ostringstream os;
535 InitAttrLine(kAttributeSsrc, &os);
536 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
537 << attribute << kSdpDelimiterColon << value;
538 return AddLine(os.str(), message);
539}
540
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000541// Get value only from <attribute>:<value>.
542static bool GetValue(const std::string& message, const std::string& attribute,
543 std::string* value, SdpParseError* error) {
544 std::string leftpart;
Donald Curtis0e07f922015-05-15 09:21:23 -0700545 if (!rtc::tokenize_first(message, kSdpDelimiterColon, &leftpart, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000546 return ParseFailedGetValue(message, attribute, error);
547 }
548 // The left part should end with the expected attribute.
549 if (leftpart.length() < attribute.length() ||
550 leftpart.compare(leftpart.length() - attribute.length(),
551 attribute.length(), attribute) != 0) {
552 return ParseFailedGetValue(message, attribute, error);
553 }
554 return true;
555}
556
557static bool CaseInsensitiveFind(std::string str1, std::string str2) {
558 std::transform(str1.begin(), str1.end(), str1.begin(),
559 ::tolower);
560 std::transform(str2.begin(), str2.end(), str2.begin(),
561 ::tolower);
562 return str1.find(str2) != std::string::npos;
563}
564
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000565template <class T>
566static bool GetValueFromString(const std::string& line,
567 const std::string& s,
568 T* t,
569 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000570 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000571 std::ostringstream description;
572 description << "Invalid value: " << s << ".";
573 return ParseFailed(line, description.str(), error);
574 }
575 return true;
576}
577
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000578static bool GetPayloadTypeFromString(const std::string& line,
579 const std::string& s,
580 int* payload_type,
581 SdpParseError* error) {
582 return GetValueFromString(line, s, payload_type, error) &&
583 cricket::IsValidRtpPayloadType(*payload_type);
584}
585
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000586void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
587 StreamParamsVec* tracks) {
588 ASSERT(tracks != NULL);
589 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
590 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
591 if (ssrc_info->cname.empty()) {
592 continue;
593 }
594
595 std::string sync_label;
596 std::string track_id;
597 if (ssrc_info->msid_identifier == kDefaultMsid &&
598 !ssrc_info->mslabel.empty()) {
599 // If there's no msid and there's mslabel, we consider this is a sdp from
600 // a older version of client that doesn't support msid.
601 // In that case, we use the mslabel and label to construct the track.
602 sync_label = ssrc_info->mslabel;
603 track_id = ssrc_info->label;
604 } else {
605 sync_label = ssrc_info->msid_identifier;
606 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
607 // is corresponding to the "id" attribute of StreamParams.
608 track_id = ssrc_info->msid_appdata;
609 }
610 if (sync_label.empty() || track_id.empty()) {
611 ASSERT(false);
612 continue;
613 }
614
615 StreamParamsVec::iterator track = tracks->begin();
616 for (; track != tracks->end(); ++track) {
617 if (track->id == track_id) {
618 break;
619 }
620 }
621 if (track == tracks->end()) {
622 // If we don't find an existing track, create a new one.
623 tracks->push_back(StreamParams());
624 track = tracks->end() - 1;
625 }
626 track->add_ssrc(ssrc_info->ssrc_id);
627 track->cname = ssrc_info->cname;
628 track->sync_label = sync_label;
629 track->id = track_id;
630 }
631}
632
633void GetMediaStreamLabels(const ContentInfo* content,
634 std::set<std::string>* labels) {
635 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000636 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000637 content->description);
638 const cricket::StreamParamsVec& streams = media_desc->streams();
639 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
640 it != streams.end(); ++it) {
641 labels->insert(it->sync_label);
642 }
643}
644
645// RFC 5245
646// It is RECOMMENDED that default candidates be chosen based on the
647// likelihood of those candidates to work with the peer that is being
648// contacted. It is RECOMMENDED that relayed > reflexive > host.
649static const int kPreferenceUnknown = 0;
650static const int kPreferenceHost = 1;
651static const int kPreferenceReflexive = 2;
652static const int kPreferenceRelayed = 3;
653
654static int GetCandidatePreferenceFromType(const std::string& type) {
655 int preference = kPreferenceUnknown;
656 if (type == cricket::LOCAL_PORT_TYPE) {
657 preference = kPreferenceHost;
658 } else if (type == cricket::STUN_PORT_TYPE) {
659 preference = kPreferenceReflexive;
660 } else if (type == cricket::RELAY_PORT_TYPE) {
661 preference = kPreferenceRelayed;
662 } else {
663 ASSERT(false);
664 }
665 return preference;
666}
667
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000668// Get ip and port of the default destination from the |candidates| with the
669// given value of |component_id|. The default candidate should be the one most
670// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000671// RFC 5245
672// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
673// TODO: Decide the default destination in webrtcsession and
674// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000675static void GetDefaultDestination(
676 const std::vector<Candidate>& candidates,
677 int component_id, std::string* port,
678 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000679 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000680 *port = kDummyPort;
681 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000683 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684 for (std::vector<Candidate>::const_iterator it = candidates.begin();
685 it != candidates.end(); ++it) {
686 if (it->component() != component_id) {
687 continue;
688 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000689 // Default destination should be UDP only.
690 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000691 continue;
692 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000693 const int preference = GetCandidatePreferenceFromType(it->type());
694 const int family = it->address().ipaddr().family();
695 // See if this candidate is more preferable then the current one if it's the
696 // same family. Or if the current family is IPv4 already so we could safely
697 // ignore all IPv6 ones. WebRTC bug 4269.
698 // http://code.google.com/p/webrtc/issues/detail?id=4269
699 if ((preference <= current_preference && current_family == family) ||
700 (current_family == AF_INET && family == AF_INET6)) {
701 continue;
702 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000703 if (family == AF_INET) {
704 addr_type->assign(kConnectionIpv4Addrtype);
705 } else if (family == AF_INET6) {
706 addr_type->assign(kConnectionIpv6Addrtype);
707 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000708 current_preference = preference;
709 current_family = family;
710 *port = it->address().PortAsString();
711 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000712 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000713}
714
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000715// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000717 const std::vector<Candidate>& candidates,
jbauch083b73f2015-07-16 02:46:32 -0700718 const std::string& mline,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000719 std::string* message) {
720 std::string new_lines;
721 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 // RFC 4566
723 // m=<media> <port> <proto> <fmt> ...
724 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000725 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726 if (fields.size() < 3) {
727 return;
728 }
729
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000731 std::string rtp_port, rtp_ip, addr_type;
732 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
733 &rtp_port, &rtp_ip, &addr_type);
734 // Found default RTP candidate.
735 // RFC 5245
736 // The default candidates are added to the SDP as the default
737 // destination for media. For streams based on RTP, this is done by
738 // placing the IP address and port of the RTP candidate into the c and m
739 // lines, respectively.
740 // Update the port in the m line.
741 // If this is a m-line with port equal to 0, we don't change it.
742 if (fields[1] != kMediaPortRejected) {
743 new_lines.replace(fields[0].size() + 1,
744 fields[1].size(),
745 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000746 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000747 // Add the c line.
748 // RFC 4566
749 // c=<nettype> <addrtype> <connection-address>
750 InitLine(kLineTypeConnection, kConnectionNettype, &os);
751 os << " " << addr_type << " " << rtp_ip;
752 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000753 message->append(new_lines);
754}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000755
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000756// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
757static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000758 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
759 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
760 &rtcp_port, &rtcp_ip, &addr_type);
761 // Found default RTCP candidate.
762 // RFC 5245
763 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
764 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000766 // RFC 3605
767 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
768 // connection-address] CRLF
769 std::ostringstream os;
770 InitAttrLine(kAttributeRtcp, &os);
771 os << kSdpDelimiterColon
772 << rtcp_port << " "
773 << kConnectionNettype << " "
774 << addr_type << " "
775 << rtcp_ip;
776 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000777 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778}
779
780// Get candidates according to the mline index from SessionDescriptionInterface.
781static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
782 int mline_index,
783 std::vector<Candidate>* candidates) {
784 if (!candidates) {
785 return;
786 }
787 const IceCandidateCollection* cc = desci.candidates(mline_index);
788 for (size_t i = 0; i < cc->count(); ++i) {
789 const IceCandidateInterface* candidate = cc->at(i);
790 candidates->push_back(candidate->candidate());
791 }
792}
793
794std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000795 const cricket::SessionDescription* desc = jdesc.description();
796 if (!desc) {
797 return "";
798 }
799
800 std::string message;
801
802 // Session Description.
803 AddLine(kSessionVersion, &message);
804 // Session Origin
805 // RFC 4566
806 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
807 // <unicast-address>
808 std::ostringstream os;
809 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
jbauch083b73f2015-07-16 02:46:32 -0700810 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700812 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813 kSessionOriginSessionVersion : jdesc.session_version();
814 os << " " << session_id << " " << session_version << " "
815 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
816 << kSessionOriginAddress;
817 AddLine(os.str(), &message);
818 AddLine(kSessionName, &message);
819
820 // Time Description.
821 AddLine(kTimeDescription, &message);
822
823 // Group
824 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
825 std::string group_line = kAttrGroup;
826 const cricket::ContentGroup* group =
827 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
828 ASSERT(group != NULL);
829 const cricket::ContentNames& content_names = group->content_names();
830 for (cricket::ContentNames::const_iterator it = content_names.begin();
831 it != content_names.end(); ++it) {
832 group_line.append(" ");
833 group_line.append(*it);
834 }
835 AddLine(group_line, &message);
836 }
837
838 // MediaStream semantics
839 InitAttrLine(kAttributeMsidSemantics, &os);
840 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000841
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842 std::set<std::string> media_stream_labels;
843 const ContentInfo* audio_content = GetFirstAudioContent(desc);
844 if (audio_content)
845 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000846
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000847 const ContentInfo* video_content = GetFirstVideoContent(desc);
848 if (video_content)
849 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000850
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000851 for (std::set<std::string>::const_iterator it =
852 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
853 os << " " << *it;
854 }
855 AddLine(os.str(), &message);
856
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000857 // Preserve the order of the media contents.
858 int mline_index = -1;
859 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
860 it != desc->contents().end(); ++it) {
861 const MediaContentDescription* mdesc =
862 static_cast<const MediaContentDescription*>(it->description);
863 std::vector<Candidate> candidates;
864 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
865 BuildMediaDescription(&*it,
866 desc->GetTransportInfoByName(it->name),
867 mdesc->type(),
868 candidates,
869 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000870 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000871 return message;
872}
873
874// Serializes the passed in IceCandidateInterface to a SDP string.
875// candidate - The candidate to be serialized.
876std::string SdpSerializeCandidate(
877 const IceCandidateInterface& candidate) {
878 std::string message;
879 std::vector<cricket::Candidate> candidates;
880 candidates.push_back(candidate.candidate());
881 BuildCandidate(candidates, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000882 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
883 // just candidate:<candidate> not a=candidate:<blah>CRLF
884 ASSERT(message.find("a=") == 0);
885 message.erase(0, 2);
886 ASSERT(message.find(kLineBreak) == message.size() - 2);
887 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000888 return message;
889}
890
891bool SdpDeserialize(const std::string& message,
892 JsepSessionDescription* jdesc,
893 SdpParseError* error) {
894 std::string session_id;
895 std::string session_version;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700896 TransportDescription session_td("", "");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000897 RtpHeaderExtensions session_extmaps;
898 cricket::SessionDescription* desc = new cricket::SessionDescription();
899 std::vector<JsepIceCandidate*> candidates;
900 size_t current_pos = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000901
902 // Session Description
903 if (!ParseSessionDescription(message, &current_pos, &session_id,
deadbeefc80741f2015-10-22 13:14:45 -0700904 &session_version, &session_td, &session_extmaps,
905 desc, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906 delete desc;
907 return false;
908 }
909
910 // Media Description
deadbeefc80741f2015-10-22 13:14:45 -0700911 if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
912 desc, &candidates, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000913 delete desc;
914 for (std::vector<JsepIceCandidate*>::const_iterator
915 it = candidates.begin(); it != candidates.end(); ++it) {
916 delete *it;
917 }
918 return false;
919 }
920
921 jdesc->Initialize(desc, session_id, session_version);
922
923 for (std::vector<JsepIceCandidate*>::const_iterator
924 it = candidates.begin(); it != candidates.end(); ++it) {
925 jdesc->AddCandidate(*it);
926 delete *it;
927 }
928 return true;
929}
930
931bool SdpDeserializeCandidate(const std::string& message,
932 JsepIceCandidate* jcandidate,
933 SdpParseError* error) {
934 ASSERT(jcandidate != NULL);
935 Candidate candidate;
936 if (!ParseCandidate(message, &candidate, error, true)) {
937 return false;
938 }
939 jcandidate->SetCandidate(candidate);
940 return true;
941}
942
943bool ParseCandidate(const std::string& message, Candidate* candidate,
944 SdpParseError* error, bool is_raw) {
945 ASSERT(candidate != NULL);
946
947 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000948 std::string first_line = message;
949 size_t pos = 0;
950 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000952 // Makes sure |message| contains only one line.
953 if (message.size() > first_line.size()) {
954 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700955 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
956 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000957 return ParseFailed(message, 0, "Expect one line only", error);
958 }
959 }
960
961 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
962 // candidate:<candidate> when trickled, but we still support
963 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
964 // from the SDP.
965 if (IsLineType(first_line, kLineTypeAttributes)) {
966 first_line = first_line.substr(kLinePrefixLength);
967 }
968
969 std::string attribute_candidate;
970 std::string candidate_value;
971
972 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700973 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
974 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000975 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000976 if (is_raw) {
977 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000978 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000979 << ":" << "<candidate-str>";
980 return ParseFailed(first_line, 0, description.str(), error);
981 } else {
982 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
983 kAttributeCandidate, error);
984 }
985 }
986
987 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000988 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
989
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000990 // RFC 5245
991 // a=candidate:<foundation> <component-id> <transport> <priority>
992 // <connection-address> <port> typ <candidate-types>
993 // [raddr <connection-address>] [rport <port>]
994 // *(SP extension-att-name SP extension-att-value)
995 const size_t expected_min_fields = 8;
996 if (fields.size() < expected_min_fields ||
997 (fields[6] != kAttributeCandidateTyp)) {
998 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
999 }
jbauch083b73f2015-07-16 02:46:32 -07001000 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001001
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001002 int component_id = 0;
1003 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1004 return false;
1005 }
jbauch083b73f2015-07-16 02:46:32 -07001006 const std::string& transport = fields[2];
Peter Boström0c4e06b2015-10-07 12:23:21 +02001007 uint32_t priority = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001008 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1009 return false;
1010 }
jbauch083b73f2015-07-16 02:46:32 -07001011 const std::string& connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001012 int port = 0;
1013 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1014 return false;
1015 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001016 SocketAddress address(connection_address, port);
1017
1018 cricket::ProtocolType protocol;
1019 if (!StringToProto(transport.c_str(), &protocol)) {
1020 return ParseFailed(first_line, "Unsupported transport type.", error);
1021 }
1022
1023 std::string candidate_type;
jbauch083b73f2015-07-16 02:46:32 -07001024 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001025 if (type == kCandidateHost) {
1026 candidate_type = cricket::LOCAL_PORT_TYPE;
1027 } else if (type == kCandidateSrflx) {
1028 candidate_type = cricket::STUN_PORT_TYPE;
1029 } else if (type == kCandidateRelay) {
1030 candidate_type = cricket::RELAY_PORT_TYPE;
1031 } else {
1032 return ParseFailed(first_line, "Unsupported candidate type.", error);
1033 }
1034
1035 size_t current_position = expected_min_fields;
1036 SocketAddress related_address;
1037 // The 2 optional fields for related address
1038 // [raddr <connection-address>] [rport <port>]
1039 if (fields.size() >= (current_position + 2) &&
1040 fields[current_position] == kAttributeCandidateRaddr) {
1041 related_address.SetIP(fields[++current_position]);
1042 ++current_position;
1043 }
1044 if (fields.size() >= (current_position + 2) &&
1045 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001046 int port = 0;
1047 if (!GetValueFromString(
1048 first_line, fields[++current_position], &port, error)) {
1049 return false;
1050 }
1051 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052 ++current_position;
1053 }
1054
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001055 // If this is a TCP candidate, it has additional extension as defined in
1056 // RFC 6544.
1057 std::string tcptype;
1058 if (fields.size() >= (current_position + 2) &&
1059 fields[current_position] == kTcpCandidateType) {
1060 tcptype = fields[++current_position];
1061 ++current_position;
1062
1063 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1064 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1065 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1066 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1067 }
1068
1069 if (protocol != cricket::PROTO_TCP) {
1070 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1071 }
1072 }
1073
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001074 // Extension
1075 // Empty string as the candidate username and password.
1076 // Will be updated later with the ice-ufrag and ice-pwd.
1077 // TODO: Remove the username/password extension, which is currently
1078 // kept for backwards compatibility.
1079 std::string username;
1080 std::string password;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001081 uint32_t generation = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1083 // RFC 5245
1084 // *(SP extension-att-name SP extension-att-value)
1085 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001086 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1087 return false;
1088 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001089 } else if (fields[i] == kAttributeCandidateUsername) {
1090 username = fields[++i];
1091 } else if (fields[i] == kAttributeCandidatePassword) {
1092 password = fields[++i];
1093 } else {
1094 // Skip the unknown extension.
1095 ++i;
1096 }
1097 }
1098
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001099 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001100 address, priority, username, password, candidate_type,
1101 generation, foundation);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001102 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001103 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001104 return true;
1105}
1106
1107bool ParseIceOptions(const std::string& line,
1108 std::vector<std::string>* transport_options,
1109 SdpParseError* error) {
1110 std::string ice_options;
1111 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1112 return false;
1113 }
1114 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001115 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001116 for (size_t i = 0; i < fields.size(); ++i) {
1117 transport_options->push_back(fields[i]);
1118 }
1119 return true;
1120}
1121
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001122bool ParseSctpPort(const std::string& line,
1123 int* sctp_port,
1124 SdpParseError* error) {
1125 // draft-ietf-mmusic-sctp-sdp-07
1126 // a=sctp-port
1127 std::vector<std::string> fields;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001128 const size_t expected_min_fields = 2;
lally69f57602015-10-08 10:15:04 -07001129 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1130 if (fields.size() < expected_min_fields) {
1131 fields.resize(0);
1132 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpace, &fields);
1133 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001134 if (fields.size() < expected_min_fields) {
1135 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1136 }
1137 if (!rtc::FromString(fields[1], sctp_port)) {
lally69f57602015-10-08 10:15:04 -07001138 return ParseFailed(line, "Invalid sctp port value.", error);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001139 }
1140 return true;
1141}
1142
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001143bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1144 SdpParseError* error) {
1145 // RFC 5285
1146 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1147 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001148 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001149 kSdpDelimiterSpace, &fields);
1150 const size_t expected_min_fields = 2;
1151 if (fields.size() < expected_min_fields) {
1152 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1153 }
1154 std::string uri = fields[1];
1155
1156 std::string value_direction;
1157 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1158 return false;
1159 }
1160 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001161 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001162 int value = 0;
1163 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1164 return false;
1165 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001166
1167 *extmap = RtpHeaderExtension(uri, value);
1168 return true;
1169}
1170
1171void BuildMediaDescription(const ContentInfo* content_info,
1172 const TransportInfo* transport_info,
1173 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001174 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001175 std::string* message) {
1176 ASSERT(message != NULL);
1177 if (content_info == NULL || message == NULL) {
1178 return;
1179 }
1180 // TODO: Rethink if we should use sprintfn instead of stringstream.
1181 // According to the style guide, streams should only be used for logging.
1182 // http://google-styleguide.googlecode.com/svn/
1183 // trunk/cppguide.xml?showone=Streams#Streams
1184 std::ostringstream os;
1185 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001186 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001187 content_info->description);
1188 ASSERT(media_desc != NULL);
1189
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001190 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191
1192 // RFC 4566
1193 // m=<media> <port> <proto> <fmt>
1194 // fmt is a list of payload type numbers that MAY be used in the session.
1195 const char* type = NULL;
1196 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1197 type = kMediaTypeAudio;
1198 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1199 type = kMediaTypeVideo;
1200 else if (media_type == cricket::MEDIA_TYPE_DATA)
1201 type = kMediaTypeData;
1202 else
1203 ASSERT(false);
1204
1205 std::string fmt;
1206 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1207 const VideoContentDescription* video_desc =
1208 static_cast<const VideoContentDescription*>(media_desc);
1209 for (std::vector<cricket::VideoCodec>::const_iterator it =
1210 video_desc->codecs().begin();
1211 it != video_desc->codecs().end(); ++it) {
1212 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001213 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001214 }
1215 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1216 const AudioContentDescription* audio_desc =
1217 static_cast<const AudioContentDescription*>(media_desc);
1218 for (std::vector<cricket::AudioCodec>::const_iterator it =
1219 audio_desc->codecs().begin();
1220 it != audio_desc->codecs().end(); ++it) {
1221 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001222 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001223 }
1224 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001225 const DataContentDescription* data_desc =
1226 static_cast<const DataContentDescription*>(media_desc);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001227 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001229
1230 for (std::vector<cricket::DataCodec>::const_iterator it =
1231 data_desc->codecs().begin();
1232 it != data_desc->codecs().end(); ++it) {
1233 if (it->id == cricket::kGoogleSctpDataCodecId &&
1234 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1235 break;
1236 }
1237 }
1238
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001239 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001240 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241 for (std::vector<cricket::DataCodec>::const_iterator it =
1242 data_desc->codecs().begin();
1243 it != data_desc->codecs().end(); ++it) {
1244 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001245 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001246 }
1247 }
1248 }
1249 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1250 // to 0.
1251 if (fmt.empty()) {
1252 fmt = " 0";
1253 }
1254
1255 // The port number in the m line will be updated later when associate with
1256 // the candidates.
1257 // RFC 3264
1258 // To reject an offered stream, the port number in the corresponding stream in
1259 // the answer MUST be set to zero.
jbauch083b73f2015-07-16 02:46:32 -07001260 const std::string& port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001261 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001262
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001263 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001264 transport_info->description.identity_fingerprint.get() : NULL;
1265
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001266 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001267 InitLine(kLineTypeMedia, type, &os);
1268 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001269 std::string mline = os.str();
1270 UpdateMediaDefaultDestination(candidates, mline, message);
1271
1272 // RFC 4566
1273 // b=AS:<bandwidth>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001274 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001275 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1276 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1277 AddLine(os.str(), message);
1278 }
1279
1280 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001281 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001282 std::string rtcp_line = GetRtcpLine(candidates);
1283 if (!rtcp_line.empty()) {
1284 AddLine(rtcp_line, message);
1285 }
1286 }
1287
1288 // Build the a=candidate lines.
1289 BuildCandidate(candidates, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001290
1291 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1292 if (transport_info) {
1293 // RFC 5245
1294 // ice-pwd-att = "ice-pwd" ":" password
1295 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1296 // ice-ufrag
1297 InitAttrLine(kAttributeIceUfrag, &os);
1298 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1299 AddLine(os.str(), message);
1300 // ice-pwd
1301 InitAttrLine(kAttributeIcePwd, &os);
1302 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1303 AddLine(os.str(), message);
1304
1305 // draft-petithuguenin-mmusic-ice-attributes-level-03
1306 BuildIceOptions(transport_info->description.transport_options, message);
1307
1308 // RFC 4572
1309 // fingerprint-attribute =
1310 // "fingerprint" ":" hash-func SP fingerprint
1311 if (fp) {
1312 // Insert the fingerprint attribute.
1313 InitAttrLine(kAttributeFingerprint, &os);
1314 os << kSdpDelimiterColon
1315 << fp->algorithm << kSdpDelimiterSpace
1316 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001318
1319 // Inserting setup attribute.
1320 if (transport_info->description.connection_role !=
1321 cricket::CONNECTIONROLE_NONE) {
1322 // Making sure we are not using "passive" mode.
1323 cricket::ConnectionRole role =
1324 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001325 std::string dtls_role_str;
1326 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001327 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001328 os << kSdpDelimiterColon << dtls_role_str;
1329 AddLine(os.str(), message);
1330 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001331 }
1332 }
1333
1334 // RFC 3388
1335 // mid-attribute = "a=mid:" identification-tag
1336 // identification-tag = token
1337 // Use the content name as the mid identification-tag.
1338 InitAttrLine(kAttributeMid, &os);
1339 os << kSdpDelimiterColon << content_info->name;
1340 AddLine(os.str(), message);
1341
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001342 if (IsDtlsSctp(media_desc->protocol())) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001343 BuildSctpContentAttributes(message, sctp_port);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001344 } else if (IsRtp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345 BuildRtpContentAttributes(media_desc, media_type, message);
1346 }
1347}
1348
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001349void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001350 // draft-ietf-mmusic-sctp-sdp-04
1351 // a=sctpmap:sctpmap-number protocol [streams]
lally69f57602015-10-08 10:15:04 -07001352 // TODO(lally): switch this over to mmusic-sctp-sdp-12 (or later), with
1353 // 'a=sctp-port:'
wu@webrtc.org78187522013-10-07 23:32:02 +00001354 std::ostringstream os;
1355 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001356 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001357 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1358 << (cricket::kMaxSctpSid + 1);
1359 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360}
1361
1362void BuildRtpContentAttributes(
1363 const MediaContentDescription* media_desc,
1364 const MediaType media_type,
1365 std::string* message) {
1366 std::ostringstream os;
1367 // RFC 5285
1368 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1369 // The definitions MUST be either all session level or all media level. This
1370 // implementation uses all media level.
1371 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1372 InitAttrLine(kAttributeExtmap, &os);
1373 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1374 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1375 AddLine(os.str(), message);
1376 }
1377
1378 // RFC 3264
1379 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
deadbeefc80741f2015-10-22 13:14:45 -07001380 switch (media_desc->direction()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001381 case cricket::MD_INACTIVE:
1382 InitAttrLine(kAttributeInactive, &os);
1383 break;
1384 case cricket::MD_SENDONLY:
1385 InitAttrLine(kAttributeSendOnly, &os);
1386 break;
1387 case cricket::MD_RECVONLY:
1388 InitAttrLine(kAttributeRecvOnly, &os);
1389 break;
1390 case cricket::MD_SENDRECV:
1391 default:
1392 InitAttrLine(kAttributeSendRecv, &os);
1393 break;
1394 }
1395 AddLine(os.str(), message);
1396
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001397 // RFC 5761
1398 // a=rtcp-mux
1399 if (media_desc->rtcp_mux()) {
1400 InitAttrLine(kAttributeRtcpMux, &os);
1401 AddLine(os.str(), message);
1402 }
1403
deadbeef13871492015-12-09 12:37:51 -08001404 // RFC 5506
1405 // a=rtcp-rsize
1406 if (media_desc->rtcp_reduced_size()) {
1407 InitAttrLine(kAttributeRtcpReducedSize, &os);
1408 AddLine(os.str(), message);
1409 }
1410
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411 // RFC 4568
1412 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1413 for (std::vector<CryptoParams>::const_iterator it =
1414 media_desc->cryptos().begin();
1415 it != media_desc->cryptos().end(); ++it) {
1416 InitAttrLine(kAttributeCrypto, &os);
1417 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1418 << it->key_params;
1419 if (!it->session_params.empty()) {
1420 os << " " << it->session_params;
1421 }
1422 AddLine(os.str(), message);
1423 }
1424
1425 // RFC 4566
1426 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1427 // [/<encodingparameters>]
1428 BuildRtpMap(media_desc, media_type, message);
1429
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001430 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1431 track != media_desc->streams().end(); ++track) {
1432 // Require that the track belongs to a media stream,
1433 // ie the sync_label is set. This extra check is necessary since the
1434 // MediaContentDescription always contains a streamparam with an ssrc even
1435 // if no track or media stream have been created.
1436 if (track->sync_label.empty()) continue;
1437
1438 // Build the ssrc-group lines.
1439 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1440 // RFC 5576
1441 // a=ssrc-group:<semantics> <ssrc-id> ...
1442 if (track->ssrc_groups[i].ssrcs.empty()) {
1443 continue;
1444 }
1445 std::ostringstream os;
1446 InitAttrLine(kAttributeSsrcGroup, &os);
1447 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001448 std::vector<uint32_t>::const_iterator ssrc =
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001449 track->ssrc_groups[i].ssrcs.begin();
1450 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001451 os << kSdpDelimiterSpace << rtc::ToString<uint32_t>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001452 }
1453 AddLine(os.str(), message);
1454 }
1455 // Build the ssrc lines for each ssrc.
1456 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001457 uint32_t ssrc = track->ssrcs[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001458 // RFC 5576
1459 // a=ssrc:<ssrc-id> cname:<value>
1460 AddSsrcLine(ssrc, kSsrcAttributeCname,
1461 track->cname, message);
1462
1463 // draft-alvestrand-mmusic-msid-00
1464 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1465 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1466 // is corresponding to the "name" attribute of StreamParams.
1467 std::string appdata = track->id;
1468 std::ostringstream os;
1469 InitAttrLine(kAttributeSsrc, &os);
1470 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1471 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1472 << kSdpDelimiterSpace << appdata;
1473 AddLine(os.str(), message);
1474
1475 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1476 // draft-alvestrand-rtcweb-mid-01
1477 // a=ssrc:<ssrc-id> mslabel:<value>
1478 // The label isn't yet defined.
1479 // a=ssrc:<ssrc-id> label:<value>
1480 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1481 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1482 }
1483 }
1484}
1485
1486void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1487 // fmtp header: a=fmtp:|payload_type| <parameters>
1488 // Add a=fmtp
1489 InitAttrLine(kAttributeFmtp, os);
1490 // Add :|payload_type|
1491 *os << kSdpDelimiterColon << payload_type;
1492}
1493
1494void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1495 // rtcp-fb header: a=rtcp-fb:|payload_type|
1496 // <parameters>/<ccm <ccm_parameters>>
1497 // Add a=rtcp-fb
1498 InitAttrLine(kAttributeRtcpFb, os);
1499 // Add :
1500 *os << kSdpDelimiterColon;
1501 if (payload_type == kWildcardPayloadType) {
1502 *os << "*";
1503 } else {
1504 *os << payload_type;
1505 }
1506}
1507
1508void WriteFmtpParameter(const std::string& parameter_name,
1509 const std::string& parameter_value,
1510 std::ostringstream* os) {
1511 // fmtp parameters: |parameter_name|=|parameter_value|
1512 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1513}
1514
1515void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1516 std::ostringstream* os) {
1517 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1518 fmtp != parameters.end(); ++fmtp) {
1519 // Each new parameter, except the first one starts with ";" and " ".
1520 if (fmtp != parameters.begin()) {
1521 *os << kSdpDelimiterSemicolon;
1522 }
1523 *os << kSdpDelimiterSpace;
1524 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1525 }
1526}
1527
1528bool IsFmtpParam(const std::string& name) {
1529 const char* kFmtpParams[] = {
1530 kCodecParamMinPTime, kCodecParamSPropStereo,
Minyue Li7100dcd2015-03-27 05:05:59 +01001531 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamUseDtx,
1532 kCodecParamStartBitrate, kCodecParamMaxBitrate, kCodecParamMinBitrate,
1533 kCodecParamMaxQuantization, kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001534 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1535 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001536 };
tfarina5237aaf2015-11-10 23:44:30 -08001537 for (size_t i = 0; i < arraysize(kFmtpParams); ++i) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001538 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1539 return true;
1540 }
1541 }
1542 return false;
1543}
1544
1545// Retreives fmtp parameters from |params|, which may contain other parameters
1546// as well, and puts them in |fmtp_parameters|.
1547void GetFmtpParams(const cricket::CodecParameterMap& params,
1548 cricket::CodecParameterMap* fmtp_parameters) {
1549 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1550 iter != params.end(); ++iter) {
1551 if (IsFmtpParam(iter->first)) {
1552 (*fmtp_parameters)[iter->first] = iter->second;
1553 }
1554 }
1555}
1556
1557template <class T>
1558void AddFmtpLine(const T& codec, std::string* message) {
1559 cricket::CodecParameterMap fmtp_parameters;
1560 GetFmtpParams(codec.params, &fmtp_parameters);
1561 if (fmtp_parameters.empty()) {
1562 // No need to add an fmtp if it will have no (optional) parameters.
1563 return;
1564 }
1565 std::ostringstream os;
1566 WriteFmtpHeader(codec.id, &os);
1567 WriteFmtpParameters(fmtp_parameters, &os);
1568 AddLine(os.str(), message);
1569 return;
1570}
1571
1572template <class T>
1573void AddRtcpFbLines(const T& codec, std::string* message) {
1574 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1575 codec.feedback_params.params().begin();
1576 iter != codec.feedback_params.params().end(); ++iter) {
1577 std::ostringstream os;
1578 WriteRtcpFbHeader(codec.id, &os);
1579 os << " " << iter->id();
1580 if (!iter->param().empty()) {
1581 os << " " << iter->param();
1582 }
1583 AddLine(os.str(), message);
1584 }
1585}
1586
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001587bool AddSctpDataCodec(DataContentDescription* media_desc,
1588 int sctp_port) {
1589 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1590 return ParseFailed("",
1591 "Can't have multiple sctp port attributes.",
1592 NULL);
1593 }
1594 // Add the SCTP Port number as a pseudo-codec "port" parameter
1595 cricket::DataCodec codec_port(
1596 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1597 0);
1598 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1599 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1600 << sctp_port;
1601 media_desc->AddCodec(codec_port);
1602 return true;
1603}
1604
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001605bool GetMinValue(const std::vector<int>& values, int* value) {
1606 if (values.empty()) {
1607 return false;
1608 }
1609 std::vector<int>::const_iterator found =
1610 std::min_element(values.begin(), values.end());
1611 *value = *found;
1612 return true;
1613}
1614
1615bool GetParameter(const std::string& name,
1616 const cricket::CodecParameterMap& params, int* value) {
1617 std::map<std::string, std::string>::const_iterator found =
1618 params.find(name);
1619 if (found == params.end()) {
1620 return false;
1621 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001622 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001623 return false;
1624 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001625 return true;
1626}
1627
1628void BuildRtpMap(const MediaContentDescription* media_desc,
1629 const MediaType media_type,
1630 std::string* message) {
1631 ASSERT(message != NULL);
1632 ASSERT(media_desc != NULL);
1633 std::ostringstream os;
1634 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1635 const VideoContentDescription* video_desc =
1636 static_cast<const VideoContentDescription*>(media_desc);
1637 for (std::vector<cricket::VideoCodec>::const_iterator it =
1638 video_desc->codecs().begin();
1639 it != video_desc->codecs().end(); ++it) {
1640 // RFC 4566
1641 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1642 // [/<encodingparameters>]
1643 if (it->id != kWildcardPayloadType) {
1644 InitAttrLine(kAttributeRtpmap, &os);
1645 os << kSdpDelimiterColon << it->id << " " << it->name
1646 << "/" << kDefaultVideoClockrate;
1647 AddLine(os.str(), message);
1648 }
1649 AddRtcpFbLines(*it, message);
1650 AddFmtpLine(*it, message);
1651 }
1652 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1653 const AudioContentDescription* audio_desc =
1654 static_cast<const AudioContentDescription*>(media_desc);
1655 std::vector<int> ptimes;
1656 std::vector<int> maxptimes;
1657 int max_minptime = 0;
1658 for (std::vector<cricket::AudioCodec>::const_iterator it =
1659 audio_desc->codecs().begin();
1660 it != audio_desc->codecs().end(); ++it) {
1661 ASSERT(!it->name.empty());
1662 // RFC 4566
1663 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1664 // [/<encodingparameters>]
1665 InitAttrLine(kAttributeRtpmap, &os);
1666 os << kSdpDelimiterColon << it->id << " ";
1667 os << it->name << "/" << it->clockrate;
1668 if (it->channels != 1) {
1669 os << "/" << it->channels;
1670 }
1671 AddLine(os.str(), message);
1672 AddRtcpFbLines(*it, message);
1673 AddFmtpLine(*it, message);
1674 int minptime = 0;
1675 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1676 max_minptime = std::max(minptime, max_minptime);
1677 }
1678 int ptime;
1679 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1680 ptimes.push_back(ptime);
1681 }
1682 int maxptime;
1683 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1684 maxptimes.push_back(maxptime);
1685 }
1686 }
1687 // Populate the maxptime attribute with the smallest maxptime of all codecs
1688 // under the same m-line.
1689 int min_maxptime = INT_MAX;
1690 if (GetMinValue(maxptimes, &min_maxptime)) {
1691 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1692 }
1693 ASSERT(min_maxptime > max_minptime);
1694 // Populate the ptime attribute with the smallest ptime or the largest
1695 // minptime, whichever is the largest, for all codecs under the same m-line.
1696 int ptime = INT_MAX;
1697 if (GetMinValue(ptimes, &ptime)) {
1698 ptime = std::min(ptime, min_maxptime);
1699 ptime = std::max(ptime, max_minptime);
1700 AddAttributeLine(kCodecParamPTime, ptime, message);
1701 }
1702 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1703 const DataContentDescription* data_desc =
1704 static_cast<const DataContentDescription*>(media_desc);
1705 for (std::vector<cricket::DataCodec>::const_iterator it =
1706 data_desc->codecs().begin();
1707 it != data_desc->codecs().end(); ++it) {
1708 // RFC 4566
1709 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1710 // [/<encodingparameters>]
1711 InitAttrLine(kAttributeRtpmap, &os);
1712 os << kSdpDelimiterColon << it->id << " "
1713 << it->name << "/" << it->clockrate;
1714 AddLine(os.str(), message);
1715 }
1716 }
1717}
1718
1719void BuildCandidate(const std::vector<Candidate>& candidates,
1720 std::string* message) {
1721 std::ostringstream os;
1722
1723 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1724 it != candidates.end(); ++it) {
1725 // RFC 5245
1726 // a=candidate:<foundation> <component-id> <transport> <priority>
1727 // <connection-address> <port> typ <candidate-types>
1728 // [raddr <connection-address>] [rport <port>]
1729 // *(SP extension-att-name SP extension-att-value)
1730 std::string type;
1731 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1732 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1733 type = kCandidateHost;
1734 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1735 type = kCandidateSrflx;
1736 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1737 type = kCandidateRelay;
1738 } else {
1739 ASSERT(false);
Peter Thatcher019087f2015-04-28 09:06:26 -07001740 // Never write out candidates if we don't know the type.
1741 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001742 }
1743
1744 InitAttrLine(kAttributeCandidate, &os);
1745 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001746 << it->foundation() << " "
1747 << it->component() << " "
1748 << it->protocol() << " "
1749 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001750 << it->address().ipaddr().ToString() << " "
1751 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001752 << kAttributeCandidateTyp << " "
1753 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001754
1755 // Related address
1756 if (!it->related_address().IsNil()) {
1757 os << kAttributeCandidateRaddr << " "
1758 << it->related_address().ipaddr().ToString() << " "
1759 << kAttributeCandidateRport << " "
1760 << it->related_address().PortAsString() << " ";
1761 }
1762
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001763 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001764 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001765 }
1766
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001767 // Extensions
1768 os << kAttributeCandidateGeneration << " " << it->generation();
1769
1770 AddLine(os.str(), message);
1771 }
1772}
1773
1774void BuildIceOptions(const std::vector<std::string>& transport_options,
1775 std::string* message) {
1776 if (!transport_options.empty()) {
1777 std::ostringstream os;
1778 InitAttrLine(kAttributeIceOption, &os);
1779 os << kSdpDelimiterColon << transport_options[0];
1780 for (size_t i = 1; i < transport_options.size(); ++i) {
1781 os << kSdpDelimiterSpace << transport_options[i];
1782 }
1783 AddLine(os.str(), message);
1784 }
1785}
1786
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001787bool IsRtp(const std::string& protocol) {
1788 return protocol.empty() ||
1789 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1790}
1791
1792bool IsDtlsSctp(const std::string& protocol) {
1793 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001794 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001795}
1796
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001797bool ParseSessionDescription(const std::string& message, size_t* pos,
1798 std::string* session_id,
1799 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001800 TransportDescription* session_td,
1801 RtpHeaderExtensions* session_extmaps,
1802 cricket::SessionDescription* desc,
1803 SdpParseError* error) {
1804 std::string line;
1805
deadbeefc80741f2015-10-22 13:14:45 -07001806 desc->set_msid_supported(false);
1807
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001808 // RFC 4566
1809 // v= (protocol version)
1810 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1811 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1812 std::string(), error);
1813 }
1814 // RFC 4566
1815 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1816 // <unicast-address>
1817 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1818 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1819 std::string(), error);
1820 }
1821 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001822 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001823 kSdpDelimiterSpace, &fields);
1824 const size_t expected_fields = 6;
1825 if (fields.size() != expected_fields) {
1826 return ParseFailedExpectFieldNum(line, expected_fields, error);
1827 }
1828 *session_id = fields[1];
1829 *session_version = fields[2];
1830
1831 // RFC 4566
1832 // s= (session name)
1833 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1834 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1835 std::string(), error);
1836 }
1837
1838 // Optional lines
1839 // Those are the optional lines, so shouldn't return false if not present.
1840 // RFC 4566
1841 // i=* (session information)
1842 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1843
1844 // RFC 4566
1845 // u=* (URI of description)
1846 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1847
1848 // RFC 4566
1849 // e=* (email address)
1850 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1851
1852 // RFC 4566
1853 // p=* (phone number)
1854 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1855
1856 // RFC 4566
1857 // c=* (connection information -- not required if included in
1858 // all media)
1859 GetLineWithType(message, pos, &line, kLineTypeConnection);
1860
1861 // RFC 4566
1862 // b=* (zero or more bandwidth information lines)
1863 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1864 // By pass zero or more b lines.
1865 }
1866
1867 // RFC 4566
1868 // One or more time descriptions ("t=" and "r=" lines; see below)
1869 // t= (time the session is active)
1870 // r=* (zero or more repeat times)
1871 // Ensure there's at least one time description
1872 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1873 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1874 error);
1875 }
1876
1877 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1878 // By pass zero or more r lines.
1879 }
1880
1881 // Go through the rest of the time descriptions
1882 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1883 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1884 // By pass zero or more r lines.
1885 }
1886 }
1887
1888 // RFC 4566
1889 // z=* (time zone adjustments)
1890 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1891
1892 // RFC 4566
1893 // k=* (encryption key)
1894 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1895
1896 // RFC 4566
1897 // a=* (zero or more session attribute lines)
1898 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1899 if (HasAttribute(line, kAttributeGroup)) {
1900 if (!ParseGroupAttribute(line, desc, error)) {
1901 return false;
1902 }
1903 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1904 if (!GetValue(line, kAttributeIceUfrag,
1905 &(session_td->ice_ufrag), error)) {
1906 return false;
1907 }
1908 } else if (HasAttribute(line, kAttributeIcePwd)) {
1909 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1910 return false;
1911 }
1912 } else if (HasAttribute(line, kAttributeIceLite)) {
1913 session_td->ice_mode = cricket::ICEMODE_LITE;
1914 } else if (HasAttribute(line, kAttributeIceOption)) {
1915 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1916 return false;
1917 }
1918 } else if (HasAttribute(line, kAttributeFingerprint)) {
1919 if (session_td->identity_fingerprint.get()) {
1920 return ParseFailed(
1921 line,
1922 "Can't have multiple fingerprint attributes at the same level.",
1923 error);
1924 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001925 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1927 return false;
1928 }
1929 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001930 } else if (HasAttribute(line, kAttributeSetup)) {
1931 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1932 return false;
1933 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001934 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1935 std::string semantics;
1936 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1937 return false;
1938 }
deadbeefc80741f2015-10-22 13:14:45 -07001939 desc->set_msid_supported(
1940 CaseInsensitiveFind(semantics, kMediaStreamSemantic));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001941 } else if (HasAttribute(line, kAttributeExtmap)) {
1942 RtpHeaderExtension extmap;
1943 if (!ParseExtmap(line, &extmap, error)) {
1944 return false;
1945 }
1946 session_extmaps->push_back(extmap);
1947 }
1948 }
1949
1950 return true;
1951}
1952
1953bool ParseGroupAttribute(const std::string& line,
1954 cricket::SessionDescription* desc,
1955 SdpParseError* error) {
1956 ASSERT(desc != NULL);
1957
1958 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1959 // a=group:BUNDLE video voice
1960 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001961 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001962 kSdpDelimiterSpace, &fields);
1963 std::string semantics;
1964 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1965 return false;
1966 }
1967 cricket::ContentGroup group(semantics);
1968 for (size_t i = 1; i < fields.size(); ++i) {
1969 group.AddContentName(fields[i]);
1970 }
1971 desc->AddGroup(group);
1972 return true;
1973}
1974
1975static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001976 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977 SdpParseError* error) {
1978 if (!IsLineType(line, kLineTypeAttributes) ||
1979 !HasAttribute(line, kAttributeFingerprint)) {
1980 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1981 kAttributeFingerprint, error);
1982 }
1983
1984 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001985 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001986 kSdpDelimiterSpace, &fields);
1987 const size_t expected_fields = 2;
1988 if (fields.size() != expected_fields) {
1989 return ParseFailedExpectFieldNum(line, expected_fields, error);
1990 }
1991
1992 // The first field here is "fingerprint:<hash>.
1993 std::string algorithm;
1994 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
1995 return false;
1996 }
1997
1998 // Downcase the algorithm. Note that we don't need to downcase the
1999 // fingerprint because hex_decode can handle upper-case.
2000 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2001 ::tolower);
2002
2003 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002004 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002005 algorithm, fields[1]);
2006 if (!*fingerprint) {
2007 return ParseFailed(line,
2008 "Failed to create fingerprint from the digest.",
2009 error);
2010 }
2011
2012 return true;
2013}
2014
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002015static bool ParseDtlsSetup(const std::string& line,
2016 cricket::ConnectionRole* role,
2017 SdpParseError* error) {
2018 // setup-attr = "a=setup:" role
2019 // role = "active" / "passive" / "actpass" / "holdconn"
2020 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002021 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002022 const size_t expected_fields = 2;
2023 if (fields.size() != expected_fields) {
2024 return ParseFailedExpectFieldNum(line, expected_fields, error);
2025 }
2026 std::string role_str = fields[1];
2027 if (!cricket::StringToConnectionRole(role_str, role)) {
2028 return ParseFailed(line, "Invalid attribute value.", error);
2029 }
2030 return true;
2031}
2032
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002033// RFC 3551
2034// PT encoding media type clock rate channels
2035// name (Hz)
2036// 0 PCMU A 8,000 1
2037// 1 reserved A
2038// 2 reserved A
2039// 3 GSM A 8,000 1
2040// 4 G723 A 8,000 1
2041// 5 DVI4 A 8,000 1
2042// 6 DVI4 A 16,000 1
2043// 7 LPC A 8,000 1
2044// 8 PCMA A 8,000 1
2045// 9 G722 A 8,000 1
2046// 10 L16 A 44,100 2
2047// 11 L16 A 44,100 1
2048// 12 QCELP A 8,000 1
2049// 13 CN A 8,000 1
2050// 14 MPA A 90,000 (see text)
2051// 15 G728 A 8,000 1
2052// 16 DVI4 A 11,025 1
2053// 17 DVI4 A 22,050 1
2054// 18 G729 A 8,000 1
2055struct StaticPayloadAudioCodec {
2056 const char* name;
2057 int clockrate;
2058 int channels;
2059};
2060static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2061 { "PCMU", 8000, 1 },
2062 { "reserved", 0, 0 },
2063 { "reserved", 0, 0 },
2064 { "GSM", 8000, 1 },
2065 { "G723", 8000, 1 },
2066 { "DVI4", 8000, 1 },
2067 { "DVI4", 16000, 1 },
2068 { "LPC", 8000, 1 },
2069 { "PCMA", 8000, 1 },
2070 { "G722", 8000, 1 },
2071 { "L16", 44100, 2 },
2072 { "L16", 44100, 1 },
2073 { "QCELP", 8000, 1 },
2074 { "CN", 8000, 1 },
2075 { "MPA", 90000, 1 },
2076 { "G728", 8000, 1 },
2077 { "DVI4", 11025, 1 },
2078 { "DVI4", 22050, 1 },
2079 { "G729", 8000, 1 },
2080};
2081
2082void MaybeCreateStaticPayloadAudioCodecs(
2083 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2084 if (!media_desc) {
2085 return;
2086 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002087 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002088 std::vector<int>::const_iterator it = fmts.begin();
2089 bool add_new_codec = false;
2090 for (; it != fmts.end(); ++it) {
2091 int payload_type = *it;
2092 if (!media_desc->HasCodec(payload_type) &&
2093 payload_type >= 0 &&
tfarina5237aaf2015-11-10 23:44:30 -08002094 payload_type < arraysize(kStaticPayloadAudioCodecs)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002095 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2096 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2097 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2098 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2099 clock_rate, 0, channels,
2100 preference));
2101 add_new_codec = true;
2102 }
2103 --preference;
2104 }
2105 if (add_new_codec) {
2106 media_desc->SortCodecs();
2107 }
2108}
2109
2110template <class C>
2111static C* ParseContentDescription(const std::string& message,
2112 const MediaType media_type,
2113 int mline_index,
2114 const std::string& protocol,
2115 const std::vector<int>& codec_preference,
2116 size_t* pos,
2117 std::string* content_name,
2118 TransportDescription* transport,
2119 std::vector<JsepIceCandidate*>* candidates,
2120 webrtc::SdpParseError* error) {
2121 C* media_desc = new C();
2122 switch (media_type) {
2123 case cricket::MEDIA_TYPE_AUDIO:
2124 *content_name = cricket::CN_AUDIO;
2125 break;
2126 case cricket::MEDIA_TYPE_VIDEO:
2127 *content_name = cricket::CN_VIDEO;
2128 break;
2129 case cricket::MEDIA_TYPE_DATA:
2130 *content_name = cricket::CN_DATA;
2131 break;
2132 default:
2133 ASSERT(false);
2134 break;
2135 }
2136 if (!ParseContent(message, media_type, mline_index, protocol,
2137 codec_preference, pos, content_name,
2138 media_desc, transport, candidates, error)) {
2139 delete media_desc;
2140 return NULL;
2141 }
2142 // Sort the codecs according to the m-line fmt list.
2143 media_desc->SortCodecs();
2144 return media_desc;
2145}
2146
2147bool ParseMediaDescription(const std::string& message,
2148 const TransportDescription& session_td,
2149 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002150 size_t* pos,
2151 cricket::SessionDescription* desc,
2152 std::vector<JsepIceCandidate*>* candidates,
2153 SdpParseError* error) {
2154 ASSERT(desc != NULL);
2155 std::string line;
2156 int mline_index = -1;
2157
2158 // Zero or more media descriptions
2159 // RFC 4566
2160 // m=<media> <port> <proto> <fmt>
2161 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2162 ++mline_index;
2163
2164 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002165 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166 kSdpDelimiterSpace, &fields);
2167 const size_t expected_min_fields = 4;
2168 if (fields.size() < expected_min_fields) {
2169 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2170 }
2171 bool rejected = false;
2172 // RFC 3264
2173 // To reject an offered stream, the port number in the corresponding stream
2174 // in the answer MUST be set to zero.
2175 if (fields[1] == kMediaPortRejected) {
2176 rejected = true;
2177 }
2178
2179 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002180
2181 // <fmt>
2182 std::vector<int> codec_preference;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002183 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002184 for (size_t j = 3 ; j < fields.size(); ++j) {
2185 // TODO(wu): Remove when below bug is fixed.
2186 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002187 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002188 continue;
2189 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002190
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002191 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002192 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002193 return false;
2194 }
2195 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002196 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002197 }
2198
2199 // Make a temporary TransportDescription based on |session_td|.
2200 // Some of this gets overwritten by ParseContent.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002201 TransportDescription transport(session_td.transport_options,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202 session_td.ice_ufrag,
2203 session_td.ice_pwd,
2204 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002205 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002206 session_td.identity_fingerprint.get(),
2207 Candidates());
2208
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002209 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002210 std::string content_name;
2211 if (HasAttribute(line, kMediaTypeVideo)) {
2212 content.reset(ParseContentDescription<VideoContentDescription>(
2213 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2214 codec_preference, pos, &content_name,
2215 &transport, candidates, error));
2216 } else if (HasAttribute(line, kMediaTypeAudio)) {
2217 content.reset(ParseContentDescription<AudioContentDescription>(
2218 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2219 codec_preference, pos, &content_name,
2220 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002221 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002222 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002223 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002224 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2225 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002226 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002227 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002228
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002229 int p;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002230 if (data_desc && IsDtlsSctp(protocol) && rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002231 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002232 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002233 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002234 } else {
2235 LOG(LS_WARNING) << "Unsupported media type: " << line;
2236 continue;
2237 }
2238 if (!content.get()) {
2239 // ParseContentDescription returns NULL if failed.
2240 return false;
2241 }
2242
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002243 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002244 // Set the extmap.
2245 if (!session_extmaps.empty() &&
2246 !content->rtp_header_extensions().empty()) {
2247 return ParseFailed("",
2248 "The a=extmap MUST be either all session level or "
2249 "all media level.",
2250 error);
2251 }
2252 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2253 content->AddRtpHeaderExtension(session_extmaps[i]);
2254 }
2255 }
2256 content->set_protocol(protocol);
2257 desc->AddContent(content_name,
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002258 IsDtlsSctp(protocol) ? cricket::NS_JINGLE_DRAFT_SCTP :
2259 cricket::NS_JINGLE_RTP,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002260 rejected,
2261 content.release());
2262 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2263 TransportInfo transport_info(content_name, transport);
2264
2265 if (!desc->AddTransportInfo(transport_info)) {
2266 std::ostringstream description;
2267 description << "Failed to AddTransportInfo with content name: "
2268 << content_name;
2269 return ParseFailed("", description.str(), error);
2270 }
2271 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002272
2273 size_t end_of_message = message.size();
2274 if (mline_index == -1 && *pos != end_of_message) {
2275 ParseFailed(message, *pos, "Expects m line.", error);
2276 return false;
2277 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002278 return true;
2279}
2280
2281bool VerifyCodec(const cricket::Codec& codec) {
2282 // Codec has not been populated correctly unless the name has been set. This
2283 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2284 // have a corresponding "rtpmap" line.
2285 cricket::Codec default_codec;
2286 return default_codec.name != codec.name;
2287}
2288
2289bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2290 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2291 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2292 iter != codecs.end(); ++iter) {
2293 if (!VerifyCodec(*iter)) {
2294 return false;
2295 }
2296 }
2297 return true;
2298}
2299
2300bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2301 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2302 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2303 iter != codecs.end(); ++iter) {
2304 if (!VerifyCodec(*iter)) {
2305 return false;
2306 }
2307 }
2308 return true;
2309}
2310
2311void AddParameters(const cricket::CodecParameterMap& parameters,
2312 cricket::Codec* codec) {
2313 for (cricket::CodecParameterMap::const_iterator iter =
2314 parameters.begin(); iter != parameters.end(); ++iter) {
2315 codec->SetParam(iter->first, iter->second);
2316 }
2317}
2318
2319void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2320 cricket::Codec* codec) {
2321 codec->AddFeedbackParam(feedback_param);
2322}
2323
2324void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2325 cricket::Codec* codec) {
2326 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2327 feedback_params.params().begin();
2328 iter != feedback_params.params().end(); ++iter) {
2329 codec->AddFeedbackParam(*iter);
2330 }
2331}
2332
2333// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002334// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002335// with that payload type.
2336template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002337T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2338 T ret_val;
2339 if (!FindCodecById(codecs, payload_type, &ret_val)) {
2340 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002341 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002342 return ret_val;
2343}
2344
2345// Updates or creates a new codec entry in the audio description.
2346template <class T, class U>
2347void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2348 T* desc = static_cast<T*>(content_desc);
2349 std::vector<U> codecs = desc->codecs();
2350 bool found = false;
2351
2352 typename std::vector<U>::iterator iter;
2353 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2354 if (iter->id == codec.id) {
2355 *iter = codec;
2356 found = true;
2357 break;
2358 }
2359 }
2360 if (!found) {
2361 desc->AddCodec(codec);
2362 return;
2363 }
2364 desc->set_codecs(codecs);
2365}
2366
2367// Adds or updates existing codec corresponding to |payload_type| according
2368// to |parameters|.
2369template <class T, class U>
2370void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2371 const cricket::CodecParameterMap& parameters) {
2372 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002373 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2374 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002375 AddParameters(parameters, &new_codec);
2376 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2377}
2378
2379// Adds or updates existing codec corresponding to |payload_type| according
2380// to |feedback_param|.
2381template <class T, class U>
2382void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2383 const cricket::FeedbackParam& feedback_param) {
2384 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002385 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2386 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002387 AddFeedbackParameter(feedback_param, &new_codec);
2388 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2389}
2390
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002391template <class T>
2392bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2393 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002394 if (iter->id == kWildcardPayloadType) {
2395 *wildcard_codec = *iter;
2396 codecs->erase(iter);
2397 return true;
2398 }
2399 }
2400 return false;
2401}
2402
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002403template<class T>
2404void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2405 auto codecs = desc->codecs();
2406 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002407 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2408 return;
2409 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002410 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002411 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2412 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002413 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002414}
2415
2416void AddAudioAttribute(const std::string& name, const std::string& value,
2417 AudioContentDescription* audio_desc) {
2418 if (value.empty()) {
2419 return;
2420 }
2421 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2422 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2423 iter != codecs.end(); ++iter) {
2424 iter->params[name] = value;
2425 }
2426 audio_desc->set_codecs(codecs);
2427}
2428
2429bool ParseContent(const std::string& message,
2430 const MediaType media_type,
2431 int mline_index,
2432 const std::string& protocol,
2433 const std::vector<int>& codec_preference,
2434 size_t* pos,
2435 std::string* content_name,
2436 MediaContentDescription* media_desc,
2437 TransportDescription* transport,
2438 std::vector<JsepIceCandidate*>* candidates,
2439 SdpParseError* error) {
2440 ASSERT(media_desc != NULL);
2441 ASSERT(content_name != NULL);
2442 ASSERT(transport != NULL);
2443
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002444 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2445 MaybeCreateStaticPayloadAudioCodecs(
2446 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2447 }
2448
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002449 // The media level "ice-ufrag" and "ice-pwd".
2450 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2451 Candidates candidates_orig;
2452 std::string line;
2453 std::string mline_id;
2454 // Tracks created out of the ssrc attributes.
2455 StreamParamsVec tracks;
2456 SsrcInfoVec ssrc_infos;
2457 SsrcGroupVec ssrc_groups;
2458 std::string maxptime_as_string;
2459 std::string ptime_as_string;
2460
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002461 // Loop until the next m line
2462 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2463 if (!GetLine(message, pos, &line)) {
2464 if (*pos >= message.size()) {
2465 break; // Done parsing
2466 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002467 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002468 }
2469 }
2470
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002471 // RFC 4566
2472 // b=* (zero or more bandwidth information lines)
2473 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2474 std::string bandwidth;
2475 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2476 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2477 return false;
2478 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002479 int b = 0;
2480 if (!GetValueFromString(line, bandwidth, &b, error)) {
2481 return false;
2482 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002483 // We should never use more than the default bandwidth for RTP-based
2484 // data channels. Don't allow SDP to set the bandwidth, because
2485 // that would give JS the opportunity to "break the Internet".
2486 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2487 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2488 b > cricket::kDataMaxBandwidth / 1000) {
2489 std::ostringstream description;
2490 description << "RTP-based data channels may not send more than "
2491 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2492 return ParseFailed(line, description.str(), error);
2493 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002494 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002495 }
2496 }
2497 continue;
2498 }
2499
2500 if (!IsLineType(line, kLineTypeAttributes)) {
2501 // TODO: Handle other lines if needed.
2502 LOG(LS_INFO) << "Ignored line: " << line;
2503 continue;
2504 }
2505
2506 // Handle attributes common to SCTP and RTP.
2507 if (HasAttribute(line, kAttributeMid)) {
2508 // RFC 3388
2509 // mid-attribute = "a=mid:" identification-tag
2510 // identification-tag = token
2511 // Use the mid identification-tag as the content name.
2512 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2513 return false;
2514 }
2515 *content_name = mline_id;
2516 } else if (HasAttribute(line, kAttributeCandidate)) {
2517 Candidate candidate;
2518 if (!ParseCandidate(line, &candidate, error, false)) {
2519 return false;
2520 }
2521 candidates_orig.push_back(candidate);
2522 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2523 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2524 return false;
2525 }
2526 } else if (HasAttribute(line, kAttributeIcePwd)) {
2527 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2528 return false;
2529 }
2530 } else if (HasAttribute(line, kAttributeIceOption)) {
2531 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2532 return false;
2533 }
2534 } else if (HasAttribute(line, kAttributeFmtp)) {
2535 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2536 return false;
2537 }
2538 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002539 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002540
2541 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2542 return false;
2543 }
2544 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002545 } else if (HasAttribute(line, kAttributeSetup)) {
2546 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2547 return false;
2548 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002549 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002550 int sctp_port;
2551 if (!ParseSctpPort(line, &sctp_port, error)) {
2552 return false;
2553 }
2554 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2555 sctp_port)) {
2556 return false;
2557 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002558 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002559 //
2560 // RTP specific attrubtes
2561 //
2562 if (HasAttribute(line, kAttributeRtcpMux)) {
2563 media_desc->set_rtcp_mux(true);
deadbeef13871492015-12-09 12:37:51 -08002564 } else if (HasAttribute(line, kAttributeRtcpReducedSize)) {
2565 media_desc->set_rtcp_reduced_size(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002566 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2567 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2568 return false;
2569 }
2570 } else if (HasAttribute(line, kAttributeSsrc)) {
2571 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2572 return false;
2573 }
2574 } else if (HasAttribute(line, kAttributeCrypto)) {
2575 if (!ParseCryptoAttribute(line, media_desc, error)) {
2576 return false;
2577 }
2578 } else if (HasAttribute(line, kAttributeRtpmap)) {
2579 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2580 media_desc, error)) {
2581 return false;
2582 }
2583 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2584 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2585 return false;
2586 }
2587 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2588 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2589 return false;
2590 }
2591 } else if (HasAttribute(line, kCodecParamPTime)) {
2592 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2593 return false;
2594 }
2595 } else if (HasAttribute(line, kAttributeSendOnly)) {
2596 media_desc->set_direction(cricket::MD_SENDONLY);
2597 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2598 media_desc->set_direction(cricket::MD_RECVONLY);
2599 } else if (HasAttribute(line, kAttributeInactive)) {
2600 media_desc->set_direction(cricket::MD_INACTIVE);
2601 } else if (HasAttribute(line, kAttributeSendRecv)) {
2602 media_desc->set_direction(cricket::MD_SENDRECV);
2603 } else if (HasAttribute(line, kAttributeExtmap)) {
2604 RtpHeaderExtension extmap;
2605 if (!ParseExtmap(line, &extmap, error)) {
2606 return false;
2607 }
2608 media_desc->AddRtpHeaderExtension(extmap);
2609 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2610 // Experimental attribute. Conference mode activates more aggressive
2611 // AEC and NS settings.
2612 // TODO: expose API to set these directly.
2613 std::string flag_value;
2614 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2615 return false;
2616 }
2617 if (flag_value.compare(kValueConference) == 0)
2618 media_desc->set_conference_mode(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002619 }
2620 } else {
2621 // Only parse lines that we are interested of.
2622 LOG(LS_INFO) << "Ignored line: " << line;
2623 continue;
2624 }
2625 }
2626
2627 // Create tracks from the |ssrc_infos|.
2628 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2629
2630 // Add the ssrc group to the track.
2631 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2632 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2633 if (ssrc_group->ssrcs.empty()) {
2634 continue;
2635 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002636 uint32_t ssrc = ssrc_group->ssrcs.front();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002637 for (StreamParamsVec::iterator track = tracks.begin();
2638 track != tracks.end(); ++track) {
2639 if (track->has_ssrc(ssrc)) {
2640 track->ssrc_groups.push_back(*ssrc_group);
2641 }
2642 }
2643 }
2644
2645 // Add the new tracks to the |media_desc|.
2646 for (StreamParamsVec::iterator track = tracks.begin();
2647 track != tracks.end(); ++track) {
2648 media_desc->AddStream(*track);
2649 }
2650
2651 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2652 AudioContentDescription* audio_desc =
2653 static_cast<AudioContentDescription*>(media_desc);
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002654 UpdateFromWildcardCodecs(audio_desc);
2655
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002656 // Verify audio codec ensures that no audio codec has been populated with
2657 // only fmtp.
2658 if (!VerifyAudioCodecs(audio_desc)) {
2659 return ParseFailed("Failed to parse audio codecs correctly.", error);
2660 }
2661 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2662 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2663 }
2664
2665 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002666 VideoContentDescription* video_desc =
2667 static_cast<VideoContentDescription*>(media_desc);
2668 UpdateFromWildcardCodecs(video_desc);
2669 // Verify video codec ensures that no video codec has been populated with
2670 // only rtcp-fb.
2671 if (!VerifyVideoCodecs(video_desc)) {
2672 return ParseFailed("Failed to parse video codecs correctly.", error);
2673 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002674 }
2675
2676 // RFC 5245
2677 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2678 for (Candidates::iterator it = candidates_orig.begin();
2679 it != candidates_orig.end(); ++it) {
2680 ASSERT((*it).username().empty());
2681 (*it).set_username(transport->ice_ufrag);
2682 ASSERT((*it).password().empty());
2683 (*it).set_password(transport->ice_pwd);
2684 candidates->push_back(
2685 new JsepIceCandidate(mline_id, mline_index, *it));
2686 }
2687 return true;
2688}
2689
2690bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2691 SdpParseError* error) {
2692 ASSERT(ssrc_infos != NULL);
2693 // RFC 5576
2694 // a=ssrc:<ssrc-id> <attribute>
2695 // a=ssrc:<ssrc-id> <attribute>:<value>
2696 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07002697 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2698 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002699 const size_t expected_fields = 2;
2700 return ParseFailedExpectFieldNum(line, expected_fields, error);
2701 }
2702
2703 // ssrc:<ssrc-id>
2704 std::string ssrc_id_s;
2705 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2706 return false;
2707 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002708 uint32_t ssrc_id = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002709 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2710 return false;
2711 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002712
2713 std::string attribute;
2714 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07002715 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002716 std::ostringstream description;
2717 description << "Failed to get the ssrc attribute value from " << field2
2718 << ". Expected format <attribute>:<value>.";
2719 return ParseFailed(line, description.str(), error);
2720 }
2721
2722 // Check if there's already an item for this |ssrc_id|. Create a new one if
2723 // there isn't.
2724 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2725 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2726 if (ssrc_info->ssrc_id == ssrc_id) {
2727 break;
2728 }
2729 }
2730 if (ssrc_info == ssrc_infos->end()) {
2731 SsrcInfo info;
2732 info.ssrc_id = ssrc_id;
2733 ssrc_infos->push_back(info);
2734 ssrc_info = ssrc_infos->end() - 1;
2735 }
2736
2737 // Store the info to the |ssrc_info|.
2738 if (attribute == kSsrcAttributeCname) {
2739 // RFC 5576
2740 // cname:<value>
2741 ssrc_info->cname = value;
2742 } else if (attribute == kSsrcAttributeMsid) {
2743 // draft-alvestrand-mmusic-msid-00
2744 // "msid:" identifier [ " " appdata ]
2745 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002746 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002747 if (fields.size() < 1 || fields.size() > 2) {
2748 return ParseFailed(line,
2749 "Expected format \"msid:<identifier>[ <appdata>]\".",
2750 error);
2751 }
2752 ssrc_info->msid_identifier = fields[0];
2753 if (fields.size() == 2) {
2754 ssrc_info->msid_appdata = fields[1];
2755 }
2756 } else if (attribute == kSsrcAttributeMslabel) {
2757 // draft-alvestrand-rtcweb-mid-01
2758 // mslabel:<value>
2759 ssrc_info->mslabel = value;
2760 } else if (attribute == kSSrcAttributeLabel) {
2761 // The label isn't defined.
2762 // label:<value>
2763 ssrc_info->label = value;
2764 }
2765 return true;
2766}
2767
2768bool ParseSsrcGroupAttribute(const std::string& line,
2769 SsrcGroupVec* ssrc_groups,
2770 SdpParseError* error) {
2771 ASSERT(ssrc_groups != NULL);
2772 // RFC 5576
2773 // a=ssrc-group:<semantics> <ssrc-id> ...
2774 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002775 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002776 kSdpDelimiterSpace, &fields);
2777 const size_t expected_min_fields = 2;
2778 if (fields.size() < expected_min_fields) {
2779 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2780 }
2781 std::string semantics;
2782 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2783 return false;
2784 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002785 std::vector<uint32_t> ssrcs;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002786 for (size_t i = 1; i < fields.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02002787 uint32_t ssrc = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002788 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2789 return false;
2790 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002791 ssrcs.push_back(ssrc);
2792 }
2793 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2794 return true;
2795}
2796
2797bool ParseCryptoAttribute(const std::string& line,
2798 MediaContentDescription* media_desc,
2799 SdpParseError* error) {
2800 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002801 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002802 kSdpDelimiterSpace, &fields);
2803 // RFC 4568
2804 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2805 const size_t expected_min_fields = 3;
2806 if (fields.size() < expected_min_fields) {
2807 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2808 }
2809 std::string tag_value;
2810 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2811 return false;
2812 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002813 int tag = 0;
2814 if (!GetValueFromString(line, tag_value, &tag, error)) {
2815 return false;
2816 }
jbauch083b73f2015-07-16 02:46:32 -07002817 const std::string& crypto_suite = fields[1];
2818 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002819 std::string session_params;
2820 if (fields.size() > 3) {
2821 session_params = fields[3];
2822 }
2823 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2824 session_params));
2825 return true;
2826}
2827
2828// Updates or creates a new codec entry in the audio description with according
2829// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2830void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2831 int bitrate, int channels, int preference,
2832 AudioContentDescription* audio_desc) {
2833 // Codec may already be populated with (only) optional parameters
2834 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002835 cricket::AudioCodec codec =
2836 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002837 codec.name = name;
2838 codec.clockrate = clockrate;
2839 codec.bitrate = bitrate;
2840 codec.channels = channels;
2841 codec.preference = preference;
2842 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2843 codec);
2844}
2845
2846// Updates or creates a new codec entry in the video description according to
2847// |name|, |width|, |height|, |framerate| and |preference|.
2848void UpdateCodec(int payload_type, const std::string& name, int width,
2849 int height, int framerate, int preference,
2850 VideoContentDescription* video_desc) {
2851 // Codec may already be populated with (only) optional parameters
2852 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002853 cricket::VideoCodec codec =
2854 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002855 codec.name = name;
2856 codec.width = width;
2857 codec.height = height;
2858 codec.framerate = framerate;
2859 codec.preference = preference;
2860 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2861 codec);
2862}
2863
2864bool ParseRtpmapAttribute(const std::string& line,
2865 const MediaType media_type,
2866 const std::vector<int>& codec_preference,
2867 MediaContentDescription* media_desc,
2868 SdpParseError* error) {
2869 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002870 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002871 kSdpDelimiterSpace, &fields);
2872 // RFC 4566
2873 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2874 const size_t expected_min_fields = 2;
2875 if (fields.size() < expected_min_fields) {
2876 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2877 }
2878 std::string payload_type_value;
2879 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2880 return false;
2881 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002882 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002883 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
2884 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002885 return false;
2886 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002887
2888 // Set the preference order depending on the order of the pl type in the
2889 // <fmt> of the m-line.
2890 const int preference = codec_preference.end() -
2891 std::find(codec_preference.begin(), codec_preference.end(),
2892 payload_type);
2893 if (preference == 0) {
2894 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2895 << "<fmt> of the m-line: " << line;
2896 return true;
2897 }
jbauch083b73f2015-07-16 02:46:32 -07002898 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002899 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002900 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002901 // <encoding name>/<clock rate>[/<encodingparameters>]
2902 // 2 mandatory fields
2903 if (codec_params.size() < 2 || codec_params.size() > 3) {
2904 return ParseFailed(line,
2905 "Expected format \"<encoding name>/<clock rate>"
2906 "[/<encodingparameters>]\".",
2907 error);
2908 }
jbauch083b73f2015-07-16 02:46:32 -07002909 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002910 int clock_rate = 0;
2911 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2912 return false;
2913 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002914 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2915 VideoContentDescription* video_desc =
2916 static_cast<VideoContentDescription*>(media_desc);
2917 // TODO: We will send resolution in SDP. For now use
2918 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2919 UpdateCodec(payload_type, encoding_name,
2920 JsepSessionDescription::kMaxVideoCodecWidth,
2921 JsepSessionDescription::kMaxVideoCodecHeight,
2922 JsepSessionDescription::kDefaultVideoCodecFramerate,
2923 preference, video_desc);
2924 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2925 // RFC 4566
2926 // For audio streams, <encoding parameters> indicates the number
2927 // of audio channels. This parameter is OPTIONAL and may be
2928 // omitted if the number of channels is one, provided that no
2929 // additional parameters are needed.
2930 int channels = 1;
2931 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002932 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2933 return false;
2934 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002935 }
2936 int bitrate = 0;
2937 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2938 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2939 // The bandwidth adaptation doesn't always work well, so this code
2940 // sets a fixed target bitrate instead.
2941 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2942 if (clock_rate <= 16000) {
2943 bitrate = kIsacWbDefaultRate;
2944 } else {
2945 bitrate = kIsacSwbDefaultRate;
2946 }
2947 }
2948 AudioContentDescription* audio_desc =
2949 static_cast<AudioContentDescription*>(media_desc);
2950 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2951 preference, audio_desc);
2952 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2953 DataContentDescription* data_desc =
2954 static_cast<DataContentDescription*>(media_desc);
2955 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2956 preference));
2957 }
2958 return true;
2959}
2960
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002961bool ParseFmtpParam(const std::string& line, std::string* parameter,
2962 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07002963 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002964 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2965 return false;
2966 }
2967 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002968 return true;
2969}
2970
2971bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
2972 MediaContentDescription* media_desc,
2973 SdpParseError* error) {
2974 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2975 media_type != cricket::MEDIA_TYPE_VIDEO) {
2976 return true;
2977 }
Donald Curtis0e07f922015-05-15 09:21:23 -07002978
2979 std::string line_payload;
2980 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002981
2982 // RFC 5576
2983 // a=fmtp:<format> <format specific parameters>
2984 // At least two fields, whereas the second one is any of the optional
2985 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07002986 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2987 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002988 ParseFailedExpectMinFieldNum(line, 2, error);
2989 return false;
2990 }
2991
Donald Curtis0e07f922015-05-15 09:21:23 -07002992 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00002993 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07002994 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002995 return false;
2996 }
2997
Donald Curtis0e07f922015-05-15 09:21:23 -07002998 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07002999 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3000 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003001 return false;
3002 }
3003
3004 // Parse out format specific parameters.
3005 std::vector<std::string> fields;
3006 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
3007
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003008 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07003009 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003010 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003011 // Only fmtps with equals are currently supported. Other fmtp types
3012 // should be ignored. Unknown fmtps do not constitute an error.
3013 continue;
3014 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003015
3016 std::string name;
3017 std::string value;
3018 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003019 return false;
3020 }
3021 codec_params[name] = value;
3022 }
3023
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003024 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3025 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003026 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003027 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3028 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003029 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003030 }
3031 return true;
3032}
3033
3034bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3035 MediaContentDescription* media_desc,
3036 SdpParseError* error) {
3037 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3038 media_type != cricket::MEDIA_TYPE_VIDEO) {
3039 return true;
3040 }
3041 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003042 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003043 if (rtcp_fb_fields.size() < 2) {
3044 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3045 }
3046 std::string payload_type_string;
3047 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3048 error)) {
3049 return false;
3050 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003051 int payload_type = kWildcardPayloadType;
3052 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003053 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3054 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003055 return false;
3056 }
3057 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058 std::string id = rtcp_fb_fields[1];
3059 std::string param = "";
3060 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3061 iter != rtcp_fb_fields.end(); ++iter) {
3062 param.append(*iter);
3063 }
3064 const cricket::FeedbackParam feedback_param(id, param);
3065
3066 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003067 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3068 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003069 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003070 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3071 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003072 }
3073 return true;
3074}
3075
3076} // namespace webrtc