blob: fceaaf4e32e3b63f444d364061e9fafbb6875cf8 [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";
125static const char kAttributeSsrc[] = "ssrc";
126static const char kSsrcAttributeCname[] = "cname";
127static const char kAttributeExtmap[] = "extmap";
128// draft-alvestrand-mmusic-msid-01
129// a=msid-semantic: WMS
130static const char kAttributeMsidSemantics[] = "msid-semantic";
131static const char kMediaStreamSemantic[] = "WMS";
132static const char kSsrcAttributeMsid[] = "msid";
133static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134static const char kSsrcAttributeMslabel[] = "mslabel";
135static const char kSSrcAttributeLabel[] = "label";
136static const char kAttributeSsrcGroup[] = "ssrc-group";
137static const char kAttributeCrypto[] = "crypto";
138static const char kAttributeCandidate[] = "candidate";
139static const char kAttributeCandidateTyp[] = "typ";
140static const char kAttributeCandidateRaddr[] = "raddr";
141static const char kAttributeCandidateRport[] = "rport";
142static const char kAttributeCandidateUsername[] = "username";
143static const char kAttributeCandidatePassword[] = "password";
144static const char kAttributeCandidateGeneration[] = "generation";
145static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000146static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000147static const char kAttributeFmtp[] = "fmtp";
148static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000149static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000150static const char kAttributeRtcp[] = "rtcp";
151static const char kAttributeIceUfrag[] = "ice-ufrag";
152static const char kAttributeIcePwd[] = "ice-pwd";
153static const char kAttributeIceLite[] = "ice-lite";
154static const char kAttributeIceOption[] = "ice-options";
155static const char kAttributeSendOnly[] = "sendonly";
156static const char kAttributeRecvOnly[] = "recvonly";
157static const char kAttributeRtcpFb[] = "rtcp-fb";
158static const char kAttributeSendRecv[] = "sendrecv";
159static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000160// draft-ietf-mmusic-sctp-sdp-07
161// a=sctp-port
162static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000163
164// Experimental flags
165static const char kAttributeXGoogleFlag[] = "x-google-flag";
166static const char kValueConference[] = "conference";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000167
168// Candidate
169static const char kCandidateHost[] = "host";
170static const char kCandidateSrflx[] = "srflx";
171// TODO: How to map the prflx with circket candidate type
172// static const char kCandidatePrflx[] = "prflx";
173static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000174static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000175
176static const char kSdpDelimiterEqual = '=';
177static const char kSdpDelimiterSpace = ' ';
178static const char kSdpDelimiterColon = ':';
179static const char kSdpDelimiterSemicolon = ';';
180static const char kSdpDelimiterSlash = '/';
181static const char kNewLine = '\n';
182static const char kReturn = '\r';
183static const char kLineBreak[] = "\r\n";
184
185// TODO: Generate the Session and Time description
186// instead of hardcoding.
187static const char kSessionVersion[] = "v=0";
188// RFC 4566
189static const char kSessionOriginUsername[] = "-";
190static const char kSessionOriginSessionId[] = "0";
191static const char kSessionOriginSessionVersion[] = "0";
192static const char kSessionOriginNettype[] = "IN";
193static const char kSessionOriginAddrtype[] = "IP4";
194static const char kSessionOriginAddress[] = "127.0.0.1";
195static const char kSessionName[] = "s=-";
196static const char kTimeDescription[] = "t=0 0";
197static const char kAttrGroup[] = "a=group:BUNDLE";
198static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000199static const char kConnectionIpv4Addrtype[] = "IP4";
200static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000201static const char kMediaTypeVideo[] = "video";
202static const char kMediaTypeAudio[] = "audio";
203static const char kMediaTypeData[] = "application";
204static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000205// draft-ietf-mmusic-trickle-ice-01
206// When no candidates have been gathered, set the connection
207// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000208// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
209// Use IPV4 per default.
210static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000211static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000212// RFC 3556
213static const char kApplicationSpecificMaximum[] = "AS";
214
215static const int kDefaultVideoClockrate = 90000;
216
217// ISAC special-case.
218static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
219static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
220static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
221
wu@webrtc.org78187522013-10-07 23:32:02 +0000222static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000223
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000224// RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
225// types.
226const int kWildcardPayloadType = -1;
227
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000228struct SsrcInfo {
229 SsrcInfo()
230 : msid_identifier(kDefaultMsid),
231 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
232 // Create random string (which will be used as track label later)?
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000233 msid_appdata(rtc::CreateRandomString(8)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000234 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200235 uint32_t ssrc_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000236 std::string cname;
237 std::string msid_identifier;
238 std::string msid_appdata;
239
240 // For backward compatibility.
241 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
242 std::string label;
243 std::string mslabel;
244};
245typedef std::vector<SsrcInfo> SsrcInfoVec;
246typedef std::vector<SsrcGroup> SsrcGroupVec;
247
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000248template <class T>
249static void AddFmtpLine(const T& codec, std::string* message);
250static void BuildMediaDescription(const ContentInfo* content_info,
251 const TransportInfo* transport_info,
252 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000253 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000254 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000255static void BuildSctpContentAttributes(std::string* message, int sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000256static void BuildRtpContentAttributes(
257 const MediaContentDescription* media_desc,
258 const MediaType media_type,
259 std::string* message);
260static void BuildRtpMap(const MediaContentDescription* media_desc,
261 const MediaType media_type,
262 std::string* message);
263static void BuildCandidate(const std::vector<Candidate>& candidates,
264 std::string* message);
265static void BuildIceOptions(const std::vector<std::string>& transport_options,
266 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000267static bool IsRtp(const std::string& protocol);
268static bool IsDtlsSctp(const std::string& protocol);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000269static bool ParseSessionDescription(const std::string& message, size_t* pos,
270 std::string* session_id,
271 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000272 TransportDescription* session_td,
273 RtpHeaderExtensions* session_extmaps,
274 cricket::SessionDescription* desc,
275 SdpParseError* error);
276static bool ParseGroupAttribute(const std::string& line,
277 cricket::SessionDescription* desc,
278 SdpParseError* error);
279static bool ParseMediaDescription(
280 const std::string& message,
281 const TransportDescription& session_td,
282 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000283 size_t* pos, cricket::SessionDescription* desc,
284 std::vector<JsepIceCandidate*>* candidates,
285 SdpParseError* error);
286static bool ParseContent(const std::string& message,
287 const MediaType media_type,
288 int mline_index,
289 const std::string& protocol,
290 const std::vector<int>& codec_preference,
291 size_t* pos,
292 std::string* content_name,
293 MediaContentDescription* media_desc,
294 TransportDescription* transport,
295 std::vector<JsepIceCandidate*>* candidates,
296 SdpParseError* error);
297static bool ParseSsrcAttribute(const std::string& line,
298 SsrcInfoVec* ssrc_infos,
299 SdpParseError* error);
300static bool ParseSsrcGroupAttribute(const std::string& line,
301 SsrcGroupVec* ssrc_groups,
302 SdpParseError* error);
303static bool ParseCryptoAttribute(const std::string& line,
304 MediaContentDescription* media_desc,
305 SdpParseError* error);
306static bool ParseRtpmapAttribute(const std::string& line,
307 const MediaType media_type,
308 const std::vector<int>& codec_preference,
309 MediaContentDescription* media_desc,
310 SdpParseError* error);
311static bool ParseFmtpAttributes(const std::string& line,
312 const MediaType media_type,
313 MediaContentDescription* media_desc,
314 SdpParseError* error);
315static bool ParseFmtpParam(const std::string& line, std::string* parameter,
316 std::string* value, SdpParseError* error);
317static bool ParseCandidate(const std::string& message, Candidate* candidate,
318 SdpParseError* error, bool is_raw);
319static bool ParseRtcpFbAttribute(const std::string& line,
320 const MediaType media_type,
321 MediaContentDescription* media_desc,
322 SdpParseError* error);
323static bool ParseIceOptions(const std::string& line,
324 std::vector<std::string>* transport_options,
325 SdpParseError* error);
326static bool ParseExtmap(const std::string& line,
327 RtpHeaderExtension* extmap,
328 SdpParseError* error);
329static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000330 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000331 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000332static bool ParseDtlsSetup(const std::string& line,
333 cricket::ConnectionRole* role,
334 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000335
336// Helper functions
337
338// Below ParseFailed*** functions output the line that caused the parsing
339// failure and the detailed reason (|description|) of the failure to |error|.
340// The functions always return false so that they can be used directly in the
341// following way when error happens:
342// "return ParseFailed***(...);"
343
344// The line starting at |line_start| of |message| is the failing line.
345// The reason for the failure should be provided in the |description|.
346// An example of a description could be "unknown character".
347static bool ParseFailed(const std::string& message,
348 size_t line_start,
349 const std::string& description,
350 SdpParseError* error) {
351 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000352 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000353 size_t line_end = message.find(kNewLine, line_start);
354 if (line_end != std::string::npos) {
355 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
356 --line_end;
357 }
358 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000359 } else {
360 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000361 }
362
363 if (error) {
364 error->line = first_line;
365 error->description = description;
366 }
367 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
368 << "\". Reason: " << description;
369 return false;
370}
371
372// |line| is the failing line. The reason for the failure should be
373// provided in the |description|.
374static bool ParseFailed(const std::string& line,
375 const std::string& description,
376 SdpParseError* error) {
377 return ParseFailed(line, 0, description, error);
378}
379
380// Parses failure where the failing SDP line isn't know or there are multiple
381// failing lines.
382static bool ParseFailed(const std::string& description,
383 SdpParseError* error) {
384 return ParseFailed("", description, error);
385}
386
387// |line| is the failing line. The failure is due to the fact that |line|
388// doesn't have |expected_fields| fields.
389static bool ParseFailedExpectFieldNum(const std::string& line,
390 int expected_fields,
391 SdpParseError* error) {
392 std::ostringstream description;
393 description << "Expects " << expected_fields << " fields.";
394 return ParseFailed(line, description.str(), error);
395}
396
397// |line| is the failing line. The failure is due to the fact that |line| has
398// less than |expected_min_fields| fields.
399static bool ParseFailedExpectMinFieldNum(const std::string& line,
400 int expected_min_fields,
401 SdpParseError* error) {
402 std::ostringstream description;
403 description << "Expects at least " << expected_min_fields << " fields.";
404 return ParseFailed(line, description.str(), error);
405}
406
407// |line| is the failing line. The failure is due to the fact that it failed to
408// get the value of |attribute|.
409static bool ParseFailedGetValue(const std::string& line,
410 const std::string& attribute,
411 SdpParseError* error) {
412 std::ostringstream description;
413 description << "Failed to get the value of attribute: " << attribute;
414 return ParseFailed(line, description.str(), error);
415}
416
417// The line starting at |line_start| of |message| is the failing line. The
418// failure is due to the line type (e.g. the "m" part of the "m-line")
419// not matching what is expected. The expected line type should be
420// provided as |line_type|.
421static bool ParseFailedExpectLine(const std::string& message,
422 size_t line_start,
423 const char line_type,
424 const std::string& line_value,
425 SdpParseError* error) {
426 std::ostringstream description;
427 description << "Expect line: " << line_type << "=" << line_value;
428 return ParseFailed(message, line_start, description.str(), error);
429}
430
431static bool AddLine(const std::string& line, std::string* message) {
432 if (!message)
433 return false;
434
435 message->append(line);
436 message->append(kLineBreak);
437 return true;
438}
439
440static bool GetLine(const std::string& message,
441 size_t* pos,
442 std::string* line) {
443 size_t line_begin = *pos;
444 size_t line_end = message.find(kNewLine, line_begin);
445 if (line_end == std::string::npos) {
446 return false;
447 }
448 // Update the new start position
449 *pos = line_end + 1;
450 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
451 --line_end;
452 }
453 *line = message.substr(line_begin, (line_end - line_begin));
454 const char* cline = line->c_str();
455 // RFC 4566
456 // An SDP session description consists of a number of lines of text of
457 // the form:
458 // <type>=<value>
459 // where <type> MUST be exactly one case-significant character and
460 // <value> is structured text whose format depends on <type>.
461 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000462 if (line->length() < 3 ||
463 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000464 cline[1] != kSdpDelimiterEqual ||
465 cline[2] == kSdpDelimiterSpace) {
466 *pos = line_begin;
467 return false;
468 }
469 return true;
470}
471
472// Init |os| to "|type|=|value|".
473static void InitLine(const char type,
474 const std::string& value,
475 std::ostringstream* os) {
476 os->str("");
477 *os << type << kSdpDelimiterEqual << value;
478}
479
480// Init |os| to "a=|attribute|".
481static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
482 InitLine(kLineTypeAttributes, attribute, os);
483}
484
485// Writes a SDP attribute line based on |attribute| and |value| to |message|.
486static void AddAttributeLine(const std::string& attribute, int value,
487 std::string* message) {
488 std::ostringstream os;
489 InitAttrLine(attribute, &os);
490 os << kSdpDelimiterColon << value;
491 AddLine(os.str(), message);
492}
493
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000494static bool IsLineType(const std::string& message,
495 const char type,
496 size_t line_start) {
497 if (message.size() < line_start + kLinePrefixLength) {
498 return false;
499 }
500 const char* cmessage = message.c_str();
501 return (cmessage[line_start] == type &&
502 cmessage[line_start + 1] == kSdpDelimiterEqual);
503}
504
505static bool IsLineType(const std::string& line,
506 const char type) {
507 return IsLineType(line, type, 0);
508}
509
510static bool GetLineWithType(const std::string& message, size_t* pos,
511 std::string* line, const char type) {
512 if (!IsLineType(message, type, *pos)) {
513 return false;
514 }
515
516 if (!GetLine(message, pos, line))
517 return false;
518
519 return true;
520}
521
522static bool HasAttribute(const std::string& line,
523 const std::string& attribute) {
524 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
525}
526
Peter Boström0c4e06b2015-10-07 12:23:21 +0200527static bool AddSsrcLine(uint32_t ssrc_id,
528 const std::string& attribute,
529 const std::string& value,
530 std::string* message) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000531 // RFC 5576
532 // a=ssrc:<ssrc-id> <attribute>:<value>
533 std::ostringstream os;
534 InitAttrLine(kAttributeSsrc, &os);
535 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
536 << attribute << kSdpDelimiterColon << value;
537 return AddLine(os.str(), message);
538}
539
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000540// Get value only from <attribute>:<value>.
541static bool GetValue(const std::string& message, const std::string& attribute,
542 std::string* value, SdpParseError* error) {
543 std::string leftpart;
Donald Curtis0e07f922015-05-15 09:21:23 -0700544 if (!rtc::tokenize_first(message, kSdpDelimiterColon, &leftpart, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000545 return ParseFailedGetValue(message, attribute, error);
546 }
547 // The left part should end with the expected attribute.
548 if (leftpart.length() < attribute.length() ||
549 leftpart.compare(leftpart.length() - attribute.length(),
550 attribute.length(), attribute) != 0) {
551 return ParseFailedGetValue(message, attribute, error);
552 }
553 return true;
554}
555
556static bool CaseInsensitiveFind(std::string str1, std::string str2) {
557 std::transform(str1.begin(), str1.end(), str1.begin(),
558 ::tolower);
559 std::transform(str2.begin(), str2.end(), str2.begin(),
560 ::tolower);
561 return str1.find(str2) != std::string::npos;
562}
563
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000564template <class T>
565static bool GetValueFromString(const std::string& line,
566 const std::string& s,
567 T* t,
568 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000569 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000570 std::ostringstream description;
571 description << "Invalid value: " << s << ".";
572 return ParseFailed(line, description.str(), error);
573 }
574 return true;
575}
576
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000577static bool GetPayloadTypeFromString(const std::string& line,
578 const std::string& s,
579 int* payload_type,
580 SdpParseError* error) {
581 return GetValueFromString(line, s, payload_type, error) &&
582 cricket::IsValidRtpPayloadType(*payload_type);
583}
584
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000585void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
586 StreamParamsVec* tracks) {
587 ASSERT(tracks != NULL);
588 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
589 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
590 if (ssrc_info->cname.empty()) {
591 continue;
592 }
593
594 std::string sync_label;
595 std::string track_id;
596 if (ssrc_info->msid_identifier == kDefaultMsid &&
597 !ssrc_info->mslabel.empty()) {
598 // If there's no msid and there's mslabel, we consider this is a sdp from
599 // a older version of client that doesn't support msid.
600 // In that case, we use the mslabel and label to construct the track.
601 sync_label = ssrc_info->mslabel;
602 track_id = ssrc_info->label;
603 } else {
604 sync_label = ssrc_info->msid_identifier;
605 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
606 // is corresponding to the "id" attribute of StreamParams.
607 track_id = ssrc_info->msid_appdata;
608 }
609 if (sync_label.empty() || track_id.empty()) {
610 ASSERT(false);
611 continue;
612 }
613
614 StreamParamsVec::iterator track = tracks->begin();
615 for (; track != tracks->end(); ++track) {
616 if (track->id == track_id) {
617 break;
618 }
619 }
620 if (track == tracks->end()) {
621 // If we don't find an existing track, create a new one.
622 tracks->push_back(StreamParams());
623 track = tracks->end() - 1;
624 }
625 track->add_ssrc(ssrc_info->ssrc_id);
626 track->cname = ssrc_info->cname;
627 track->sync_label = sync_label;
628 track->id = track_id;
629 }
630}
631
632void GetMediaStreamLabels(const ContentInfo* content,
633 std::set<std::string>* labels) {
634 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000635 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000636 content->description);
637 const cricket::StreamParamsVec& streams = media_desc->streams();
638 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
639 it != streams.end(); ++it) {
640 labels->insert(it->sync_label);
641 }
642}
643
644// RFC 5245
645// It is RECOMMENDED that default candidates be chosen based on the
646// likelihood of those candidates to work with the peer that is being
647// contacted. It is RECOMMENDED that relayed > reflexive > host.
648static const int kPreferenceUnknown = 0;
649static const int kPreferenceHost = 1;
650static const int kPreferenceReflexive = 2;
651static const int kPreferenceRelayed = 3;
652
653static int GetCandidatePreferenceFromType(const std::string& type) {
654 int preference = kPreferenceUnknown;
655 if (type == cricket::LOCAL_PORT_TYPE) {
656 preference = kPreferenceHost;
657 } else if (type == cricket::STUN_PORT_TYPE) {
658 preference = kPreferenceReflexive;
659 } else if (type == cricket::RELAY_PORT_TYPE) {
660 preference = kPreferenceRelayed;
661 } else {
662 ASSERT(false);
663 }
664 return preference;
665}
666
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000667// Get ip and port of the default destination from the |candidates| with the
668// given value of |component_id|. The default candidate should be the one most
669// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000670// RFC 5245
671// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
672// TODO: Decide the default destination in webrtcsession and
673// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000674static void GetDefaultDestination(
675 const std::vector<Candidate>& candidates,
676 int component_id, std::string* port,
677 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000678 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000679 *port = kDummyPort;
680 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000681 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000682 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000683 for (std::vector<Candidate>::const_iterator it = candidates.begin();
684 it != candidates.end(); ++it) {
685 if (it->component() != component_id) {
686 continue;
687 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000688 // Default destination should be UDP only.
689 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000690 continue;
691 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000692 const int preference = GetCandidatePreferenceFromType(it->type());
693 const int family = it->address().ipaddr().family();
694 // See if this candidate is more preferable then the current one if it's the
695 // same family. Or if the current family is IPv4 already so we could safely
696 // ignore all IPv6 ones. WebRTC bug 4269.
697 // http://code.google.com/p/webrtc/issues/detail?id=4269
698 if ((preference <= current_preference && current_family == family) ||
699 (current_family == AF_INET && family == AF_INET6)) {
700 continue;
701 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000702 if (family == AF_INET) {
703 addr_type->assign(kConnectionIpv4Addrtype);
704 } else if (family == AF_INET6) {
705 addr_type->assign(kConnectionIpv6Addrtype);
706 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000707 current_preference = preference;
708 current_family = family;
709 *port = it->address().PortAsString();
710 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000711 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000712}
713
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000714// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000715static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000716 const std::vector<Candidate>& candidates,
jbauch083b73f2015-07-16 02:46:32 -0700717 const std::string& mline,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000718 std::string* message) {
719 std::string new_lines;
720 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000721 // RFC 4566
722 // m=<media> <port> <proto> <fmt> ...
723 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000724 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725 if (fields.size() < 3) {
726 return;
727 }
728
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000729 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000730 std::string rtp_port, rtp_ip, addr_type;
731 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
732 &rtp_port, &rtp_ip, &addr_type);
733 // Found default RTP candidate.
734 // RFC 5245
735 // The default candidates are added to the SDP as the default
736 // destination for media. For streams based on RTP, this is done by
737 // placing the IP address and port of the RTP candidate into the c and m
738 // lines, respectively.
739 // Update the port in the m line.
740 // If this is a m-line with port equal to 0, we don't change it.
741 if (fields[1] != kMediaPortRejected) {
742 new_lines.replace(fields[0].size() + 1,
743 fields[1].size(),
744 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000745 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000746 // Add the c line.
747 // RFC 4566
748 // c=<nettype> <addrtype> <connection-address>
749 InitLine(kLineTypeConnection, kConnectionNettype, &os);
750 os << " " << addr_type << " " << rtp_ip;
751 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000752 message->append(new_lines);
753}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000754
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000755// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
756static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000757 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
758 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
759 &rtcp_port, &rtcp_ip, &addr_type);
760 // Found default RTCP candidate.
761 // RFC 5245
762 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
763 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000764
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000765 // RFC 3605
766 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
767 // connection-address] CRLF
768 std::ostringstream os;
769 InitAttrLine(kAttributeRtcp, &os);
770 os << kSdpDelimiterColon
771 << rtcp_port << " "
772 << kConnectionNettype << " "
773 << addr_type << " "
774 << rtcp_ip;
775 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000776 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000777}
778
779// Get candidates according to the mline index from SessionDescriptionInterface.
780static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
781 int mline_index,
782 std::vector<Candidate>* candidates) {
783 if (!candidates) {
784 return;
785 }
786 const IceCandidateCollection* cc = desci.candidates(mline_index);
787 for (size_t i = 0; i < cc->count(); ++i) {
788 const IceCandidateInterface* candidate = cc->at(i);
789 candidates->push_back(candidate->candidate());
790 }
791}
792
793std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794 const cricket::SessionDescription* desc = jdesc.description();
795 if (!desc) {
796 return "";
797 }
798
799 std::string message;
800
801 // Session Description.
802 AddLine(kSessionVersion, &message);
803 // Session Origin
804 // RFC 4566
805 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
806 // <unicast-address>
807 std::ostringstream os;
808 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
jbauch083b73f2015-07-16 02:46:32 -0700809 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000810 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700811 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812 kSessionOriginSessionVersion : jdesc.session_version();
813 os << " " << session_id << " " << session_version << " "
814 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
815 << kSessionOriginAddress;
816 AddLine(os.str(), &message);
817 AddLine(kSessionName, &message);
818
819 // Time Description.
820 AddLine(kTimeDescription, &message);
821
822 // Group
823 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
824 std::string group_line = kAttrGroup;
825 const cricket::ContentGroup* group =
826 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
827 ASSERT(group != NULL);
828 const cricket::ContentNames& content_names = group->content_names();
829 for (cricket::ContentNames::const_iterator it = content_names.begin();
830 it != content_names.end(); ++it) {
831 group_line.append(" ");
832 group_line.append(*it);
833 }
834 AddLine(group_line, &message);
835 }
836
837 // MediaStream semantics
838 InitAttrLine(kAttributeMsidSemantics, &os);
839 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000840
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000841 std::set<std::string> media_stream_labels;
842 const ContentInfo* audio_content = GetFirstAudioContent(desc);
843 if (audio_content)
844 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000845
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846 const ContentInfo* video_content = GetFirstVideoContent(desc);
847 if (video_content)
848 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000849
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000850 for (std::set<std::string>::const_iterator it =
851 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
852 os << " " << *it;
853 }
854 AddLine(os.str(), &message);
855
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000856 // Preserve the order of the media contents.
857 int mline_index = -1;
858 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
859 it != desc->contents().end(); ++it) {
860 const MediaContentDescription* mdesc =
861 static_cast<const MediaContentDescription*>(it->description);
862 std::vector<Candidate> candidates;
863 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
864 BuildMediaDescription(&*it,
865 desc->GetTransportInfoByName(it->name),
866 mdesc->type(),
867 candidates,
868 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000869 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000870 return message;
871}
872
873// Serializes the passed in IceCandidateInterface to a SDP string.
874// candidate - The candidate to be serialized.
875std::string SdpSerializeCandidate(
876 const IceCandidateInterface& candidate) {
877 std::string message;
878 std::vector<cricket::Candidate> candidates;
879 candidates.push_back(candidate.candidate());
880 BuildCandidate(candidates, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000881 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
882 // just candidate:<candidate> not a=candidate:<blah>CRLF
883 ASSERT(message.find("a=") == 0);
884 message.erase(0, 2);
885 ASSERT(message.find(kLineBreak) == message.size() - 2);
886 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887 return message;
888}
889
890bool SdpDeserialize(const std::string& message,
891 JsepSessionDescription* jdesc,
892 SdpParseError* error) {
893 std::string session_id;
894 std::string session_version;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700895 TransportDescription session_td("", "");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000896 RtpHeaderExtensions session_extmaps;
897 cricket::SessionDescription* desc = new cricket::SessionDescription();
898 std::vector<JsepIceCandidate*> candidates;
899 size_t current_pos = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000900
901 // Session Description
902 if (!ParseSessionDescription(message, &current_pos, &session_id,
deadbeefc80741f2015-10-22 13:14:45 -0700903 &session_version, &session_td, &session_extmaps,
904 desc, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905 delete desc;
906 return false;
907 }
908
909 // Media Description
deadbeefc80741f2015-10-22 13:14:45 -0700910 if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
911 desc, &candidates, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000912 delete desc;
913 for (std::vector<JsepIceCandidate*>::const_iterator
914 it = candidates.begin(); it != candidates.end(); ++it) {
915 delete *it;
916 }
917 return false;
918 }
919
920 jdesc->Initialize(desc, session_id, session_version);
921
922 for (std::vector<JsepIceCandidate*>::const_iterator
923 it = candidates.begin(); it != candidates.end(); ++it) {
924 jdesc->AddCandidate(*it);
925 delete *it;
926 }
927 return true;
928}
929
930bool SdpDeserializeCandidate(const std::string& message,
931 JsepIceCandidate* jcandidate,
932 SdpParseError* error) {
933 ASSERT(jcandidate != NULL);
934 Candidate candidate;
935 if (!ParseCandidate(message, &candidate, error, true)) {
936 return false;
937 }
938 jcandidate->SetCandidate(candidate);
939 return true;
940}
941
942bool ParseCandidate(const std::string& message, Candidate* candidate,
943 SdpParseError* error, bool is_raw) {
944 ASSERT(candidate != NULL);
945
946 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000947 std::string first_line = message;
948 size_t pos = 0;
949 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000951 // Makes sure |message| contains only one line.
952 if (message.size() > first_line.size()) {
953 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700954 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
955 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000956 return ParseFailed(message, 0, "Expect one line only", error);
957 }
958 }
959
960 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
961 // candidate:<candidate> when trickled, but we still support
962 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
963 // from the SDP.
964 if (IsLineType(first_line, kLineTypeAttributes)) {
965 first_line = first_line.substr(kLinePrefixLength);
966 }
967
968 std::string attribute_candidate;
969 std::string candidate_value;
970
971 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700972 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
973 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000974 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000975 if (is_raw) {
976 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000977 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000978 << ":" << "<candidate-str>";
979 return ParseFailed(first_line, 0, description.str(), error);
980 } else {
981 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
982 kAttributeCandidate, error);
983 }
984 }
985
986 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000987 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
988
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989 // RFC 5245
990 // a=candidate:<foundation> <component-id> <transport> <priority>
991 // <connection-address> <port> typ <candidate-types>
992 // [raddr <connection-address>] [rport <port>]
993 // *(SP extension-att-name SP extension-att-value)
994 const size_t expected_min_fields = 8;
995 if (fields.size() < expected_min_fields ||
996 (fields[6] != kAttributeCandidateTyp)) {
997 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
998 }
jbauch083b73f2015-07-16 02:46:32 -0700999 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001000
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001001 int component_id = 0;
1002 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1003 return false;
1004 }
jbauch083b73f2015-07-16 02:46:32 -07001005 const std::string& transport = fields[2];
Peter Boström0c4e06b2015-10-07 12:23:21 +02001006 uint32_t priority = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001007 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1008 return false;
1009 }
jbauch083b73f2015-07-16 02:46:32 -07001010 const std::string& connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001011 int port = 0;
1012 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1013 return false;
1014 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015 SocketAddress address(connection_address, port);
1016
1017 cricket::ProtocolType protocol;
1018 if (!StringToProto(transport.c_str(), &protocol)) {
1019 return ParseFailed(first_line, "Unsupported transport type.", error);
1020 }
1021
1022 std::string candidate_type;
jbauch083b73f2015-07-16 02:46:32 -07001023 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001024 if (type == kCandidateHost) {
1025 candidate_type = cricket::LOCAL_PORT_TYPE;
1026 } else if (type == kCandidateSrflx) {
1027 candidate_type = cricket::STUN_PORT_TYPE;
1028 } else if (type == kCandidateRelay) {
1029 candidate_type = cricket::RELAY_PORT_TYPE;
1030 } else {
1031 return ParseFailed(first_line, "Unsupported candidate type.", error);
1032 }
1033
1034 size_t current_position = expected_min_fields;
1035 SocketAddress related_address;
1036 // The 2 optional fields for related address
1037 // [raddr <connection-address>] [rport <port>]
1038 if (fields.size() >= (current_position + 2) &&
1039 fields[current_position] == kAttributeCandidateRaddr) {
1040 related_address.SetIP(fields[++current_position]);
1041 ++current_position;
1042 }
1043 if (fields.size() >= (current_position + 2) &&
1044 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001045 int port = 0;
1046 if (!GetValueFromString(
1047 first_line, fields[++current_position], &port, error)) {
1048 return false;
1049 }
1050 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001051 ++current_position;
1052 }
1053
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001054 // If this is a TCP candidate, it has additional extension as defined in
1055 // RFC 6544.
1056 std::string tcptype;
1057 if (fields.size() >= (current_position + 2) &&
1058 fields[current_position] == kTcpCandidateType) {
1059 tcptype = fields[++current_position];
1060 ++current_position;
1061
1062 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1063 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1064 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1065 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1066 }
1067
1068 if (protocol != cricket::PROTO_TCP) {
1069 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1070 }
1071 }
1072
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001073 // Extension
1074 // Empty string as the candidate username and password.
1075 // Will be updated later with the ice-ufrag and ice-pwd.
1076 // TODO: Remove the username/password extension, which is currently
1077 // kept for backwards compatibility.
1078 std::string username;
1079 std::string password;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001080 uint32_t generation = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1082 // RFC 5245
1083 // *(SP extension-att-name SP extension-att-value)
1084 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001085 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1086 return false;
1087 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088 } else if (fields[i] == kAttributeCandidateUsername) {
1089 username = fields[++i];
1090 } else if (fields[i] == kAttributeCandidatePassword) {
1091 password = fields[++i];
1092 } else {
1093 // Skip the unknown extension.
1094 ++i;
1095 }
1096 }
1097
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001098 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001099 address, priority, username, password, candidate_type,
1100 generation, foundation);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001102 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001103 return true;
1104}
1105
1106bool ParseIceOptions(const std::string& line,
1107 std::vector<std::string>* transport_options,
1108 SdpParseError* error) {
1109 std::string ice_options;
1110 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1111 return false;
1112 }
1113 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001114 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001115 for (size_t i = 0; i < fields.size(); ++i) {
1116 transport_options->push_back(fields[i]);
1117 }
1118 return true;
1119}
1120
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001121bool ParseSctpPort(const std::string& line,
1122 int* sctp_port,
1123 SdpParseError* error) {
1124 // draft-ietf-mmusic-sctp-sdp-07
1125 // a=sctp-port
1126 std::vector<std::string> fields;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001127 const size_t expected_min_fields = 2;
lally69f57602015-10-08 10:15:04 -07001128 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1129 if (fields.size() < expected_min_fields) {
1130 fields.resize(0);
1131 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpace, &fields);
1132 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001133 if (fields.size() < expected_min_fields) {
1134 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1135 }
1136 if (!rtc::FromString(fields[1], sctp_port)) {
lally69f57602015-10-08 10:15:04 -07001137 return ParseFailed(line, "Invalid sctp port value.", error);
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001138 }
1139 return true;
1140}
1141
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001142bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1143 SdpParseError* error) {
1144 // RFC 5285
1145 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1146 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001147 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001148 kSdpDelimiterSpace, &fields);
1149 const size_t expected_min_fields = 2;
1150 if (fields.size() < expected_min_fields) {
1151 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1152 }
1153 std::string uri = fields[1];
1154
1155 std::string value_direction;
1156 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1157 return false;
1158 }
1159 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001160 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001161 int value = 0;
1162 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1163 return false;
1164 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165
1166 *extmap = RtpHeaderExtension(uri, value);
1167 return true;
1168}
1169
1170void BuildMediaDescription(const ContentInfo* content_info,
1171 const TransportInfo* transport_info,
1172 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001173 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001174 std::string* message) {
1175 ASSERT(message != NULL);
1176 if (content_info == NULL || message == NULL) {
1177 return;
1178 }
1179 // TODO: Rethink if we should use sprintfn instead of stringstream.
1180 // According to the style guide, streams should only be used for logging.
1181 // http://google-styleguide.googlecode.com/svn/
1182 // trunk/cppguide.xml?showone=Streams#Streams
1183 std::ostringstream os;
1184 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001185 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001186 content_info->description);
1187 ASSERT(media_desc != NULL);
1188
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001189 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001190
1191 // RFC 4566
1192 // m=<media> <port> <proto> <fmt>
1193 // fmt is a list of payload type numbers that MAY be used in the session.
1194 const char* type = NULL;
1195 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1196 type = kMediaTypeAudio;
1197 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1198 type = kMediaTypeVideo;
1199 else if (media_type == cricket::MEDIA_TYPE_DATA)
1200 type = kMediaTypeData;
1201 else
1202 ASSERT(false);
1203
1204 std::string fmt;
1205 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1206 const VideoContentDescription* video_desc =
1207 static_cast<const VideoContentDescription*>(media_desc);
1208 for (std::vector<cricket::VideoCodec>::const_iterator it =
1209 video_desc->codecs().begin();
1210 it != video_desc->codecs().end(); ++it) {
1211 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001212 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001213 }
1214 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1215 const AudioContentDescription* audio_desc =
1216 static_cast<const AudioContentDescription*>(media_desc);
1217 for (std::vector<cricket::AudioCodec>::const_iterator it =
1218 audio_desc->codecs().begin();
1219 it != audio_desc->codecs().end(); ++it) {
1220 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001221 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001222 }
1223 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001224 const DataContentDescription* data_desc =
1225 static_cast<const DataContentDescription*>(media_desc);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001226 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001227 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001228
1229 for (std::vector<cricket::DataCodec>::const_iterator it =
1230 data_desc->codecs().begin();
1231 it != data_desc->codecs().end(); ++it) {
1232 if (it->id == cricket::kGoogleSctpDataCodecId &&
1233 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1234 break;
1235 }
1236 }
1237
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001238 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001239 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001240 for (std::vector<cricket::DataCodec>::const_iterator it =
1241 data_desc->codecs().begin();
1242 it != data_desc->codecs().end(); ++it) {
1243 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001244 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001245 }
1246 }
1247 }
1248 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1249 // to 0.
1250 if (fmt.empty()) {
1251 fmt = " 0";
1252 }
1253
1254 // The port number in the m line will be updated later when associate with
1255 // the candidates.
1256 // RFC 3264
1257 // To reject an offered stream, the port number in the corresponding stream in
1258 // the answer MUST be set to zero.
jbauch083b73f2015-07-16 02:46:32 -07001259 const std::string& port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001260 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001261
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001262 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001263 transport_info->description.identity_fingerprint.get() : NULL;
1264
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001265 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001266 InitLine(kLineTypeMedia, type, &os);
1267 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001268 std::string mline = os.str();
1269 UpdateMediaDefaultDestination(candidates, mline, message);
1270
1271 // RFC 4566
1272 // b=AS:<bandwidth>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001273 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001274 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1275 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1276 AddLine(os.str(), message);
1277 }
1278
1279 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001280 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001281 std::string rtcp_line = GetRtcpLine(candidates);
1282 if (!rtcp_line.empty()) {
1283 AddLine(rtcp_line, message);
1284 }
1285 }
1286
1287 // Build the a=candidate lines.
1288 BuildCandidate(candidates, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289
1290 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1291 if (transport_info) {
1292 // RFC 5245
1293 // ice-pwd-att = "ice-pwd" ":" password
1294 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1295 // ice-ufrag
1296 InitAttrLine(kAttributeIceUfrag, &os);
1297 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1298 AddLine(os.str(), message);
1299 // ice-pwd
1300 InitAttrLine(kAttributeIcePwd, &os);
1301 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1302 AddLine(os.str(), message);
1303
1304 // draft-petithuguenin-mmusic-ice-attributes-level-03
1305 BuildIceOptions(transport_info->description.transport_options, message);
1306
1307 // RFC 4572
1308 // fingerprint-attribute =
1309 // "fingerprint" ":" hash-func SP fingerprint
1310 if (fp) {
1311 // Insert the fingerprint attribute.
1312 InitAttrLine(kAttributeFingerprint, &os);
1313 os << kSdpDelimiterColon
1314 << fp->algorithm << kSdpDelimiterSpace
1315 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001317
1318 // Inserting setup attribute.
1319 if (transport_info->description.connection_role !=
1320 cricket::CONNECTIONROLE_NONE) {
1321 // Making sure we are not using "passive" mode.
1322 cricket::ConnectionRole role =
1323 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001324 std::string dtls_role_str;
1325 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001326 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001327 os << kSdpDelimiterColon << dtls_role_str;
1328 AddLine(os.str(), message);
1329 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001330 }
1331 }
1332
1333 // RFC 3388
1334 // mid-attribute = "a=mid:" identification-tag
1335 // identification-tag = token
1336 // Use the content name as the mid identification-tag.
1337 InitAttrLine(kAttributeMid, &os);
1338 os << kSdpDelimiterColon << content_info->name;
1339 AddLine(os.str(), message);
1340
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001341 if (IsDtlsSctp(media_desc->protocol())) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001342 BuildSctpContentAttributes(message, sctp_port);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001343 } else if (IsRtp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 BuildRtpContentAttributes(media_desc, media_type, message);
1345 }
1346}
1347
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001348void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001349 // draft-ietf-mmusic-sctp-sdp-04
1350 // a=sctpmap:sctpmap-number protocol [streams]
lally69f57602015-10-08 10:15:04 -07001351 // TODO(lally): switch this over to mmusic-sctp-sdp-12 (or later), with
1352 // 'a=sctp-port:'
wu@webrtc.org78187522013-10-07 23:32:02 +00001353 std::ostringstream os;
1354 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001355 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001356 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1357 << (cricket::kMaxSctpSid + 1);
1358 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001359}
1360
1361void BuildRtpContentAttributes(
1362 const MediaContentDescription* media_desc,
1363 const MediaType media_type,
1364 std::string* message) {
1365 std::ostringstream os;
1366 // RFC 5285
1367 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1368 // The definitions MUST be either all session level or all media level. This
1369 // implementation uses all media level.
1370 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1371 InitAttrLine(kAttributeExtmap, &os);
1372 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1373 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1374 AddLine(os.str(), message);
1375 }
1376
1377 // RFC 3264
1378 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
deadbeefc80741f2015-10-22 13:14:45 -07001379 switch (media_desc->direction()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001380 case cricket::MD_INACTIVE:
1381 InitAttrLine(kAttributeInactive, &os);
1382 break;
1383 case cricket::MD_SENDONLY:
1384 InitAttrLine(kAttributeSendOnly, &os);
1385 break;
1386 case cricket::MD_RECVONLY:
1387 InitAttrLine(kAttributeRecvOnly, &os);
1388 break;
1389 case cricket::MD_SENDRECV:
1390 default:
1391 InitAttrLine(kAttributeSendRecv, &os);
1392 break;
1393 }
1394 AddLine(os.str(), message);
1395
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001396 // RFC 5761
1397 // a=rtcp-mux
1398 if (media_desc->rtcp_mux()) {
1399 InitAttrLine(kAttributeRtcpMux, &os);
1400 AddLine(os.str(), message);
1401 }
1402
1403 // RFC 4568
1404 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1405 for (std::vector<CryptoParams>::const_iterator it =
1406 media_desc->cryptos().begin();
1407 it != media_desc->cryptos().end(); ++it) {
1408 InitAttrLine(kAttributeCrypto, &os);
1409 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1410 << it->key_params;
1411 if (!it->session_params.empty()) {
1412 os << " " << it->session_params;
1413 }
1414 AddLine(os.str(), message);
1415 }
1416
1417 // RFC 4566
1418 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1419 // [/<encodingparameters>]
1420 BuildRtpMap(media_desc, media_type, message);
1421
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001422 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1423 track != media_desc->streams().end(); ++track) {
1424 // Require that the track belongs to a media stream,
1425 // ie the sync_label is set. This extra check is necessary since the
1426 // MediaContentDescription always contains a streamparam with an ssrc even
1427 // if no track or media stream have been created.
1428 if (track->sync_label.empty()) continue;
1429
1430 // Build the ssrc-group lines.
1431 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1432 // RFC 5576
1433 // a=ssrc-group:<semantics> <ssrc-id> ...
1434 if (track->ssrc_groups[i].ssrcs.empty()) {
1435 continue;
1436 }
1437 std::ostringstream os;
1438 InitAttrLine(kAttributeSsrcGroup, &os);
1439 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001440 std::vector<uint32_t>::const_iterator ssrc =
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001441 track->ssrc_groups[i].ssrcs.begin();
1442 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001443 os << kSdpDelimiterSpace << rtc::ToString<uint32_t>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444 }
1445 AddLine(os.str(), message);
1446 }
1447 // Build the ssrc lines for each ssrc.
1448 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001449 uint32_t ssrc = track->ssrcs[i];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450 // RFC 5576
1451 // a=ssrc:<ssrc-id> cname:<value>
1452 AddSsrcLine(ssrc, kSsrcAttributeCname,
1453 track->cname, message);
1454
1455 // draft-alvestrand-mmusic-msid-00
1456 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1457 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1458 // is corresponding to the "name" attribute of StreamParams.
1459 std::string appdata = track->id;
1460 std::ostringstream os;
1461 InitAttrLine(kAttributeSsrc, &os);
1462 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1463 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1464 << kSdpDelimiterSpace << appdata;
1465 AddLine(os.str(), message);
1466
1467 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1468 // draft-alvestrand-rtcweb-mid-01
1469 // a=ssrc:<ssrc-id> mslabel:<value>
1470 // The label isn't yet defined.
1471 // a=ssrc:<ssrc-id> label:<value>
1472 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1473 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1474 }
1475 }
1476}
1477
1478void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1479 // fmtp header: a=fmtp:|payload_type| <parameters>
1480 // Add a=fmtp
1481 InitAttrLine(kAttributeFmtp, os);
1482 // Add :|payload_type|
1483 *os << kSdpDelimiterColon << payload_type;
1484}
1485
1486void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1487 // rtcp-fb header: a=rtcp-fb:|payload_type|
1488 // <parameters>/<ccm <ccm_parameters>>
1489 // Add a=rtcp-fb
1490 InitAttrLine(kAttributeRtcpFb, os);
1491 // Add :
1492 *os << kSdpDelimiterColon;
1493 if (payload_type == kWildcardPayloadType) {
1494 *os << "*";
1495 } else {
1496 *os << payload_type;
1497 }
1498}
1499
1500void WriteFmtpParameter(const std::string& parameter_name,
1501 const std::string& parameter_value,
1502 std::ostringstream* os) {
1503 // fmtp parameters: |parameter_name|=|parameter_value|
1504 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1505}
1506
1507void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1508 std::ostringstream* os) {
1509 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1510 fmtp != parameters.end(); ++fmtp) {
1511 // Each new parameter, except the first one starts with ";" and " ".
1512 if (fmtp != parameters.begin()) {
1513 *os << kSdpDelimiterSemicolon;
1514 }
1515 *os << kSdpDelimiterSpace;
1516 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1517 }
1518}
1519
1520bool IsFmtpParam(const std::string& name) {
1521 const char* kFmtpParams[] = {
1522 kCodecParamMinPTime, kCodecParamSPropStereo,
Minyue Li7100dcd2015-03-27 05:05:59 +01001523 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamUseDtx,
1524 kCodecParamStartBitrate, kCodecParamMaxBitrate, kCodecParamMinBitrate,
1525 kCodecParamMaxQuantization, kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001526 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1527 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528 };
tfarina5237aaf2015-11-10 23:44:30 -08001529 for (size_t i = 0; i < arraysize(kFmtpParams); ++i) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001530 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1531 return true;
1532 }
1533 }
1534 return false;
1535}
1536
1537// Retreives fmtp parameters from |params|, which may contain other parameters
1538// as well, and puts them in |fmtp_parameters|.
1539void GetFmtpParams(const cricket::CodecParameterMap& params,
1540 cricket::CodecParameterMap* fmtp_parameters) {
1541 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1542 iter != params.end(); ++iter) {
1543 if (IsFmtpParam(iter->first)) {
1544 (*fmtp_parameters)[iter->first] = iter->second;
1545 }
1546 }
1547}
1548
1549template <class T>
1550void AddFmtpLine(const T& codec, std::string* message) {
1551 cricket::CodecParameterMap fmtp_parameters;
1552 GetFmtpParams(codec.params, &fmtp_parameters);
1553 if (fmtp_parameters.empty()) {
1554 // No need to add an fmtp if it will have no (optional) parameters.
1555 return;
1556 }
1557 std::ostringstream os;
1558 WriteFmtpHeader(codec.id, &os);
1559 WriteFmtpParameters(fmtp_parameters, &os);
1560 AddLine(os.str(), message);
1561 return;
1562}
1563
1564template <class T>
1565void AddRtcpFbLines(const T& codec, std::string* message) {
1566 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1567 codec.feedback_params.params().begin();
1568 iter != codec.feedback_params.params().end(); ++iter) {
1569 std::ostringstream os;
1570 WriteRtcpFbHeader(codec.id, &os);
1571 os << " " << iter->id();
1572 if (!iter->param().empty()) {
1573 os << " " << iter->param();
1574 }
1575 AddLine(os.str(), message);
1576 }
1577}
1578
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001579bool AddSctpDataCodec(DataContentDescription* media_desc,
1580 int sctp_port) {
1581 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1582 return ParseFailed("",
1583 "Can't have multiple sctp port attributes.",
1584 NULL);
1585 }
1586 // Add the SCTP Port number as a pseudo-codec "port" parameter
1587 cricket::DataCodec codec_port(
1588 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1589 0);
1590 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1591 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1592 << sctp_port;
1593 media_desc->AddCodec(codec_port);
1594 return true;
1595}
1596
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001597bool GetMinValue(const std::vector<int>& values, int* value) {
1598 if (values.empty()) {
1599 return false;
1600 }
1601 std::vector<int>::const_iterator found =
1602 std::min_element(values.begin(), values.end());
1603 *value = *found;
1604 return true;
1605}
1606
1607bool GetParameter(const std::string& name,
1608 const cricket::CodecParameterMap& params, int* value) {
1609 std::map<std::string, std::string>::const_iterator found =
1610 params.find(name);
1611 if (found == params.end()) {
1612 return false;
1613 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001614 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001615 return false;
1616 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001617 return true;
1618}
1619
1620void BuildRtpMap(const MediaContentDescription* media_desc,
1621 const MediaType media_type,
1622 std::string* message) {
1623 ASSERT(message != NULL);
1624 ASSERT(media_desc != NULL);
1625 std::ostringstream os;
1626 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1627 const VideoContentDescription* video_desc =
1628 static_cast<const VideoContentDescription*>(media_desc);
1629 for (std::vector<cricket::VideoCodec>::const_iterator it =
1630 video_desc->codecs().begin();
1631 it != video_desc->codecs().end(); ++it) {
1632 // RFC 4566
1633 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1634 // [/<encodingparameters>]
1635 if (it->id != kWildcardPayloadType) {
1636 InitAttrLine(kAttributeRtpmap, &os);
1637 os << kSdpDelimiterColon << it->id << " " << it->name
1638 << "/" << kDefaultVideoClockrate;
1639 AddLine(os.str(), message);
1640 }
1641 AddRtcpFbLines(*it, message);
1642 AddFmtpLine(*it, message);
1643 }
1644 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1645 const AudioContentDescription* audio_desc =
1646 static_cast<const AudioContentDescription*>(media_desc);
1647 std::vector<int> ptimes;
1648 std::vector<int> maxptimes;
1649 int max_minptime = 0;
1650 for (std::vector<cricket::AudioCodec>::const_iterator it =
1651 audio_desc->codecs().begin();
1652 it != audio_desc->codecs().end(); ++it) {
1653 ASSERT(!it->name.empty());
1654 // RFC 4566
1655 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1656 // [/<encodingparameters>]
1657 InitAttrLine(kAttributeRtpmap, &os);
1658 os << kSdpDelimiterColon << it->id << " ";
1659 os << it->name << "/" << it->clockrate;
1660 if (it->channels != 1) {
1661 os << "/" << it->channels;
1662 }
1663 AddLine(os.str(), message);
1664 AddRtcpFbLines(*it, message);
1665 AddFmtpLine(*it, message);
1666 int minptime = 0;
1667 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1668 max_minptime = std::max(minptime, max_minptime);
1669 }
1670 int ptime;
1671 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1672 ptimes.push_back(ptime);
1673 }
1674 int maxptime;
1675 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1676 maxptimes.push_back(maxptime);
1677 }
1678 }
1679 // Populate the maxptime attribute with the smallest maxptime of all codecs
1680 // under the same m-line.
1681 int min_maxptime = INT_MAX;
1682 if (GetMinValue(maxptimes, &min_maxptime)) {
1683 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1684 }
1685 ASSERT(min_maxptime > max_minptime);
1686 // Populate the ptime attribute with the smallest ptime or the largest
1687 // minptime, whichever is the largest, for all codecs under the same m-line.
1688 int ptime = INT_MAX;
1689 if (GetMinValue(ptimes, &ptime)) {
1690 ptime = std::min(ptime, min_maxptime);
1691 ptime = std::max(ptime, max_minptime);
1692 AddAttributeLine(kCodecParamPTime, ptime, message);
1693 }
1694 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1695 const DataContentDescription* data_desc =
1696 static_cast<const DataContentDescription*>(media_desc);
1697 for (std::vector<cricket::DataCodec>::const_iterator it =
1698 data_desc->codecs().begin();
1699 it != data_desc->codecs().end(); ++it) {
1700 // RFC 4566
1701 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1702 // [/<encodingparameters>]
1703 InitAttrLine(kAttributeRtpmap, &os);
1704 os << kSdpDelimiterColon << it->id << " "
1705 << it->name << "/" << it->clockrate;
1706 AddLine(os.str(), message);
1707 }
1708 }
1709}
1710
1711void BuildCandidate(const std::vector<Candidate>& candidates,
1712 std::string* message) {
1713 std::ostringstream os;
1714
1715 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1716 it != candidates.end(); ++it) {
1717 // RFC 5245
1718 // a=candidate:<foundation> <component-id> <transport> <priority>
1719 // <connection-address> <port> typ <candidate-types>
1720 // [raddr <connection-address>] [rport <port>]
1721 // *(SP extension-att-name SP extension-att-value)
1722 std::string type;
1723 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1724 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1725 type = kCandidateHost;
1726 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1727 type = kCandidateSrflx;
1728 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1729 type = kCandidateRelay;
1730 } else {
1731 ASSERT(false);
Peter Thatcher019087f2015-04-28 09:06:26 -07001732 // Never write out candidates if we don't know the type.
1733 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734 }
1735
1736 InitAttrLine(kAttributeCandidate, &os);
1737 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001738 << it->foundation() << " "
1739 << it->component() << " "
1740 << it->protocol() << " "
1741 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001742 << it->address().ipaddr().ToString() << " "
1743 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001744 << kAttributeCandidateTyp << " "
1745 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001746
1747 // Related address
1748 if (!it->related_address().IsNil()) {
1749 os << kAttributeCandidateRaddr << " "
1750 << it->related_address().ipaddr().ToString() << " "
1751 << kAttributeCandidateRport << " "
1752 << it->related_address().PortAsString() << " ";
1753 }
1754
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001755 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001756 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001757 }
1758
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001759 // Extensions
1760 os << kAttributeCandidateGeneration << " " << it->generation();
1761
1762 AddLine(os.str(), message);
1763 }
1764}
1765
1766void BuildIceOptions(const std::vector<std::string>& transport_options,
1767 std::string* message) {
1768 if (!transport_options.empty()) {
1769 std::ostringstream os;
1770 InitAttrLine(kAttributeIceOption, &os);
1771 os << kSdpDelimiterColon << transport_options[0];
1772 for (size_t i = 1; i < transport_options.size(); ++i) {
1773 os << kSdpDelimiterSpace << transport_options[i];
1774 }
1775 AddLine(os.str(), message);
1776 }
1777}
1778
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001779bool IsRtp(const std::string& protocol) {
1780 return protocol.empty() ||
1781 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1782}
1783
1784bool IsDtlsSctp(const std::string& protocol) {
1785 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001786 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001787}
1788
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001789bool ParseSessionDescription(const std::string& message, size_t* pos,
1790 std::string* session_id,
1791 std::string* session_version,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001792 TransportDescription* session_td,
1793 RtpHeaderExtensions* session_extmaps,
1794 cricket::SessionDescription* desc,
1795 SdpParseError* error) {
1796 std::string line;
1797
deadbeefc80741f2015-10-22 13:14:45 -07001798 desc->set_msid_supported(false);
1799
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001800 // RFC 4566
1801 // v= (protocol version)
1802 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1803 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1804 std::string(), error);
1805 }
1806 // RFC 4566
1807 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1808 // <unicast-address>
1809 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1810 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1811 std::string(), error);
1812 }
1813 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001814 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001815 kSdpDelimiterSpace, &fields);
1816 const size_t expected_fields = 6;
1817 if (fields.size() != expected_fields) {
1818 return ParseFailedExpectFieldNum(line, expected_fields, error);
1819 }
1820 *session_id = fields[1];
1821 *session_version = fields[2];
1822
1823 // RFC 4566
1824 // s= (session name)
1825 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1826 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1827 std::string(), error);
1828 }
1829
1830 // Optional lines
1831 // Those are the optional lines, so shouldn't return false if not present.
1832 // RFC 4566
1833 // i=* (session information)
1834 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1835
1836 // RFC 4566
1837 // u=* (URI of description)
1838 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1839
1840 // RFC 4566
1841 // e=* (email address)
1842 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1843
1844 // RFC 4566
1845 // p=* (phone number)
1846 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1847
1848 // RFC 4566
1849 // c=* (connection information -- not required if included in
1850 // all media)
1851 GetLineWithType(message, pos, &line, kLineTypeConnection);
1852
1853 // RFC 4566
1854 // b=* (zero or more bandwidth information lines)
1855 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1856 // By pass zero or more b lines.
1857 }
1858
1859 // RFC 4566
1860 // One or more time descriptions ("t=" and "r=" lines; see below)
1861 // t= (time the session is active)
1862 // r=* (zero or more repeat times)
1863 // Ensure there's at least one time description
1864 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1865 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1866 error);
1867 }
1868
1869 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1870 // By pass zero or more r lines.
1871 }
1872
1873 // Go through the rest of the time descriptions
1874 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1875 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1876 // By pass zero or more r lines.
1877 }
1878 }
1879
1880 // RFC 4566
1881 // z=* (time zone adjustments)
1882 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1883
1884 // RFC 4566
1885 // k=* (encryption key)
1886 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1887
1888 // RFC 4566
1889 // a=* (zero or more session attribute lines)
1890 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1891 if (HasAttribute(line, kAttributeGroup)) {
1892 if (!ParseGroupAttribute(line, desc, error)) {
1893 return false;
1894 }
1895 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1896 if (!GetValue(line, kAttributeIceUfrag,
1897 &(session_td->ice_ufrag), error)) {
1898 return false;
1899 }
1900 } else if (HasAttribute(line, kAttributeIcePwd)) {
1901 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1902 return false;
1903 }
1904 } else if (HasAttribute(line, kAttributeIceLite)) {
1905 session_td->ice_mode = cricket::ICEMODE_LITE;
1906 } else if (HasAttribute(line, kAttributeIceOption)) {
1907 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1908 return false;
1909 }
1910 } else if (HasAttribute(line, kAttributeFingerprint)) {
1911 if (session_td->identity_fingerprint.get()) {
1912 return ParseFailed(
1913 line,
1914 "Can't have multiple fingerprint attributes at the same level.",
1915 error);
1916 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001917 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1919 return false;
1920 }
1921 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001922 } else if (HasAttribute(line, kAttributeSetup)) {
1923 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1924 return false;
1925 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1927 std::string semantics;
1928 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1929 return false;
1930 }
deadbeefc80741f2015-10-22 13:14:45 -07001931 desc->set_msid_supported(
1932 CaseInsensitiveFind(semantics, kMediaStreamSemantic));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933 } else if (HasAttribute(line, kAttributeExtmap)) {
1934 RtpHeaderExtension extmap;
1935 if (!ParseExtmap(line, &extmap, error)) {
1936 return false;
1937 }
1938 session_extmaps->push_back(extmap);
1939 }
1940 }
1941
1942 return true;
1943}
1944
1945bool ParseGroupAttribute(const std::string& line,
1946 cricket::SessionDescription* desc,
1947 SdpParseError* error) {
1948 ASSERT(desc != NULL);
1949
1950 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1951 // a=group:BUNDLE video voice
1952 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001953 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001954 kSdpDelimiterSpace, &fields);
1955 std::string semantics;
1956 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1957 return false;
1958 }
1959 cricket::ContentGroup group(semantics);
1960 for (size_t i = 1; i < fields.size(); ++i) {
1961 group.AddContentName(fields[i]);
1962 }
1963 desc->AddGroup(group);
1964 return true;
1965}
1966
1967static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001968 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001969 SdpParseError* error) {
1970 if (!IsLineType(line, kLineTypeAttributes) ||
1971 !HasAttribute(line, kAttributeFingerprint)) {
1972 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1973 kAttributeFingerprint, error);
1974 }
1975
1976 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001977 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001978 kSdpDelimiterSpace, &fields);
1979 const size_t expected_fields = 2;
1980 if (fields.size() != expected_fields) {
1981 return ParseFailedExpectFieldNum(line, expected_fields, error);
1982 }
1983
1984 // The first field here is "fingerprint:<hash>.
1985 std::string algorithm;
1986 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
1987 return false;
1988 }
1989
1990 // Downcase the algorithm. Note that we don't need to downcase the
1991 // fingerprint because hex_decode can handle upper-case.
1992 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
1993 ::tolower);
1994
1995 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001996 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001997 algorithm, fields[1]);
1998 if (!*fingerprint) {
1999 return ParseFailed(line,
2000 "Failed to create fingerprint from the digest.",
2001 error);
2002 }
2003
2004 return true;
2005}
2006
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002007static bool ParseDtlsSetup(const std::string& line,
2008 cricket::ConnectionRole* role,
2009 SdpParseError* error) {
2010 // setup-attr = "a=setup:" role
2011 // role = "active" / "passive" / "actpass" / "holdconn"
2012 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002013 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002014 const size_t expected_fields = 2;
2015 if (fields.size() != expected_fields) {
2016 return ParseFailedExpectFieldNum(line, expected_fields, error);
2017 }
2018 std::string role_str = fields[1];
2019 if (!cricket::StringToConnectionRole(role_str, role)) {
2020 return ParseFailed(line, "Invalid attribute value.", error);
2021 }
2022 return true;
2023}
2024
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002025// RFC 3551
2026// PT encoding media type clock rate channels
2027// name (Hz)
2028// 0 PCMU A 8,000 1
2029// 1 reserved A
2030// 2 reserved A
2031// 3 GSM A 8,000 1
2032// 4 G723 A 8,000 1
2033// 5 DVI4 A 8,000 1
2034// 6 DVI4 A 16,000 1
2035// 7 LPC A 8,000 1
2036// 8 PCMA A 8,000 1
2037// 9 G722 A 8,000 1
2038// 10 L16 A 44,100 2
2039// 11 L16 A 44,100 1
2040// 12 QCELP A 8,000 1
2041// 13 CN A 8,000 1
2042// 14 MPA A 90,000 (see text)
2043// 15 G728 A 8,000 1
2044// 16 DVI4 A 11,025 1
2045// 17 DVI4 A 22,050 1
2046// 18 G729 A 8,000 1
2047struct StaticPayloadAudioCodec {
2048 const char* name;
2049 int clockrate;
2050 int channels;
2051};
2052static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2053 { "PCMU", 8000, 1 },
2054 { "reserved", 0, 0 },
2055 { "reserved", 0, 0 },
2056 { "GSM", 8000, 1 },
2057 { "G723", 8000, 1 },
2058 { "DVI4", 8000, 1 },
2059 { "DVI4", 16000, 1 },
2060 { "LPC", 8000, 1 },
2061 { "PCMA", 8000, 1 },
2062 { "G722", 8000, 1 },
2063 { "L16", 44100, 2 },
2064 { "L16", 44100, 1 },
2065 { "QCELP", 8000, 1 },
2066 { "CN", 8000, 1 },
2067 { "MPA", 90000, 1 },
2068 { "G728", 8000, 1 },
2069 { "DVI4", 11025, 1 },
2070 { "DVI4", 22050, 1 },
2071 { "G729", 8000, 1 },
2072};
2073
2074void MaybeCreateStaticPayloadAudioCodecs(
2075 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2076 if (!media_desc) {
2077 return;
2078 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002079 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002080 std::vector<int>::const_iterator it = fmts.begin();
2081 bool add_new_codec = false;
2082 for (; it != fmts.end(); ++it) {
2083 int payload_type = *it;
2084 if (!media_desc->HasCodec(payload_type) &&
2085 payload_type >= 0 &&
tfarina5237aaf2015-11-10 23:44:30 -08002086 payload_type < arraysize(kStaticPayloadAudioCodecs)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002087 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2088 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2089 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2090 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2091 clock_rate, 0, channels,
2092 preference));
2093 add_new_codec = true;
2094 }
2095 --preference;
2096 }
2097 if (add_new_codec) {
2098 media_desc->SortCodecs();
2099 }
2100}
2101
2102template <class C>
2103static C* ParseContentDescription(const std::string& message,
2104 const MediaType media_type,
2105 int mline_index,
2106 const std::string& protocol,
2107 const std::vector<int>& codec_preference,
2108 size_t* pos,
2109 std::string* content_name,
2110 TransportDescription* transport,
2111 std::vector<JsepIceCandidate*>* candidates,
2112 webrtc::SdpParseError* error) {
2113 C* media_desc = new C();
2114 switch (media_type) {
2115 case cricket::MEDIA_TYPE_AUDIO:
2116 *content_name = cricket::CN_AUDIO;
2117 break;
2118 case cricket::MEDIA_TYPE_VIDEO:
2119 *content_name = cricket::CN_VIDEO;
2120 break;
2121 case cricket::MEDIA_TYPE_DATA:
2122 *content_name = cricket::CN_DATA;
2123 break;
2124 default:
2125 ASSERT(false);
2126 break;
2127 }
2128 if (!ParseContent(message, media_type, mline_index, protocol,
2129 codec_preference, pos, content_name,
2130 media_desc, transport, candidates, error)) {
2131 delete media_desc;
2132 return NULL;
2133 }
2134 // Sort the codecs according to the m-line fmt list.
2135 media_desc->SortCodecs();
2136 return media_desc;
2137}
2138
2139bool ParseMediaDescription(const std::string& message,
2140 const TransportDescription& session_td,
2141 const RtpHeaderExtensions& session_extmaps,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002142 size_t* pos,
2143 cricket::SessionDescription* desc,
2144 std::vector<JsepIceCandidate*>* candidates,
2145 SdpParseError* error) {
2146 ASSERT(desc != NULL);
2147 std::string line;
2148 int mline_index = -1;
2149
2150 // Zero or more media descriptions
2151 // RFC 4566
2152 // m=<media> <port> <proto> <fmt>
2153 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2154 ++mline_index;
2155
2156 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002157 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002158 kSdpDelimiterSpace, &fields);
2159 const size_t expected_min_fields = 4;
2160 if (fields.size() < expected_min_fields) {
2161 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2162 }
2163 bool rejected = false;
2164 // RFC 3264
2165 // To reject an offered stream, the port number in the corresponding stream
2166 // in the answer MUST be set to zero.
2167 if (fields[1] == kMediaPortRejected) {
2168 rejected = true;
2169 }
2170
2171 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002172
2173 // <fmt>
2174 std::vector<int> codec_preference;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002175 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002176 for (size_t j = 3 ; j < fields.size(); ++j) {
2177 // TODO(wu): Remove when below bug is fixed.
2178 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002179 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002180 continue;
2181 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002182
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002183 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002184 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002185 return false;
2186 }
2187 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002188 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002189 }
2190
2191 // Make a temporary TransportDescription based on |session_td|.
2192 // Some of this gets overwritten by ParseContent.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002193 TransportDescription transport(session_td.transport_options,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002194 session_td.ice_ufrag,
2195 session_td.ice_pwd,
2196 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002197 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002198 session_td.identity_fingerprint.get(),
2199 Candidates());
2200
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002201 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202 std::string content_name;
2203 if (HasAttribute(line, kMediaTypeVideo)) {
2204 content.reset(ParseContentDescription<VideoContentDescription>(
2205 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2206 codec_preference, pos, &content_name,
2207 &transport, candidates, error));
2208 } else if (HasAttribute(line, kMediaTypeAudio)) {
2209 content.reset(ParseContentDescription<AudioContentDescription>(
2210 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2211 codec_preference, pos, &content_name,
2212 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002213 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002214 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002215 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002216 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2217 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002218 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002219 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002220
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002221 int p;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002222 if (data_desc && IsDtlsSctp(protocol) && rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002223 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002224 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002225 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002226 } else {
2227 LOG(LS_WARNING) << "Unsupported media type: " << line;
2228 continue;
2229 }
2230 if (!content.get()) {
2231 // ParseContentDescription returns NULL if failed.
2232 return false;
2233 }
2234
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002235 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002236 // Set the extmap.
2237 if (!session_extmaps.empty() &&
2238 !content->rtp_header_extensions().empty()) {
2239 return ParseFailed("",
2240 "The a=extmap MUST be either all session level or "
2241 "all media level.",
2242 error);
2243 }
2244 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2245 content->AddRtpHeaderExtension(session_extmaps[i]);
2246 }
2247 }
2248 content->set_protocol(protocol);
2249 desc->AddContent(content_name,
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002250 IsDtlsSctp(protocol) ? cricket::NS_JINGLE_DRAFT_SCTP :
2251 cricket::NS_JINGLE_RTP,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 rejected,
2253 content.release());
2254 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2255 TransportInfo transport_info(content_name, transport);
2256
2257 if (!desc->AddTransportInfo(transport_info)) {
2258 std::ostringstream description;
2259 description << "Failed to AddTransportInfo with content name: "
2260 << content_name;
2261 return ParseFailed("", description.str(), error);
2262 }
2263 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002264
2265 size_t end_of_message = message.size();
2266 if (mline_index == -1 && *pos != end_of_message) {
2267 ParseFailed(message, *pos, "Expects m line.", error);
2268 return false;
2269 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002270 return true;
2271}
2272
2273bool VerifyCodec(const cricket::Codec& codec) {
2274 // Codec has not been populated correctly unless the name has been set. This
2275 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2276 // have a corresponding "rtpmap" line.
2277 cricket::Codec default_codec;
2278 return default_codec.name != codec.name;
2279}
2280
2281bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2282 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2283 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2284 iter != codecs.end(); ++iter) {
2285 if (!VerifyCodec(*iter)) {
2286 return false;
2287 }
2288 }
2289 return true;
2290}
2291
2292bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2293 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2294 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2295 iter != codecs.end(); ++iter) {
2296 if (!VerifyCodec(*iter)) {
2297 return false;
2298 }
2299 }
2300 return true;
2301}
2302
2303void AddParameters(const cricket::CodecParameterMap& parameters,
2304 cricket::Codec* codec) {
2305 for (cricket::CodecParameterMap::const_iterator iter =
2306 parameters.begin(); iter != parameters.end(); ++iter) {
2307 codec->SetParam(iter->first, iter->second);
2308 }
2309}
2310
2311void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2312 cricket::Codec* codec) {
2313 codec->AddFeedbackParam(feedback_param);
2314}
2315
2316void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2317 cricket::Codec* codec) {
2318 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2319 feedback_params.params().begin();
2320 iter != feedback_params.params().end(); ++iter) {
2321 codec->AddFeedbackParam(*iter);
2322 }
2323}
2324
2325// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002326// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002327// with that payload type.
2328template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002329T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2330 T ret_val;
2331 if (!FindCodecById(codecs, payload_type, &ret_val)) {
2332 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002333 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002334 return ret_val;
2335}
2336
2337// Updates or creates a new codec entry in the audio description.
2338template <class T, class U>
2339void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2340 T* desc = static_cast<T*>(content_desc);
2341 std::vector<U> codecs = desc->codecs();
2342 bool found = false;
2343
2344 typename std::vector<U>::iterator iter;
2345 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2346 if (iter->id == codec.id) {
2347 *iter = codec;
2348 found = true;
2349 break;
2350 }
2351 }
2352 if (!found) {
2353 desc->AddCodec(codec);
2354 return;
2355 }
2356 desc->set_codecs(codecs);
2357}
2358
2359// Adds or updates existing codec corresponding to |payload_type| according
2360// to |parameters|.
2361template <class T, class U>
2362void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2363 const cricket::CodecParameterMap& parameters) {
2364 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002365 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2366 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002367 AddParameters(parameters, &new_codec);
2368 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2369}
2370
2371// Adds or updates existing codec corresponding to |payload_type| according
2372// to |feedback_param|.
2373template <class T, class U>
2374void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2375 const cricket::FeedbackParam& feedback_param) {
2376 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002377 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2378 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002379 AddFeedbackParameter(feedback_param, &new_codec);
2380 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2381}
2382
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002383template <class T>
2384bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2385 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002386 if (iter->id == kWildcardPayloadType) {
2387 *wildcard_codec = *iter;
2388 codecs->erase(iter);
2389 return true;
2390 }
2391 }
2392 return false;
2393}
2394
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002395template<class T>
2396void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2397 auto codecs = desc->codecs();
2398 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002399 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2400 return;
2401 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002402 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002403 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2404 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002405 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002406}
2407
2408void AddAudioAttribute(const std::string& name, const std::string& value,
2409 AudioContentDescription* audio_desc) {
2410 if (value.empty()) {
2411 return;
2412 }
2413 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2414 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2415 iter != codecs.end(); ++iter) {
2416 iter->params[name] = value;
2417 }
2418 audio_desc->set_codecs(codecs);
2419}
2420
2421bool ParseContent(const std::string& message,
2422 const MediaType media_type,
2423 int mline_index,
2424 const std::string& protocol,
2425 const std::vector<int>& codec_preference,
2426 size_t* pos,
2427 std::string* content_name,
2428 MediaContentDescription* media_desc,
2429 TransportDescription* transport,
2430 std::vector<JsepIceCandidate*>* candidates,
2431 SdpParseError* error) {
2432 ASSERT(media_desc != NULL);
2433 ASSERT(content_name != NULL);
2434 ASSERT(transport != NULL);
2435
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002436 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2437 MaybeCreateStaticPayloadAudioCodecs(
2438 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2439 }
2440
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002441 // The media level "ice-ufrag" and "ice-pwd".
2442 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2443 Candidates candidates_orig;
2444 std::string line;
2445 std::string mline_id;
2446 // Tracks created out of the ssrc attributes.
2447 StreamParamsVec tracks;
2448 SsrcInfoVec ssrc_infos;
2449 SsrcGroupVec ssrc_groups;
2450 std::string maxptime_as_string;
2451 std::string ptime_as_string;
2452
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002453 // Loop until the next m line
2454 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2455 if (!GetLine(message, pos, &line)) {
2456 if (*pos >= message.size()) {
2457 break; // Done parsing
2458 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002459 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002460 }
2461 }
2462
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002463 // RFC 4566
2464 // b=* (zero or more bandwidth information lines)
2465 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2466 std::string bandwidth;
2467 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2468 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2469 return false;
2470 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002471 int b = 0;
2472 if (!GetValueFromString(line, bandwidth, &b, error)) {
2473 return false;
2474 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002475 // We should never use more than the default bandwidth for RTP-based
2476 // data channels. Don't allow SDP to set the bandwidth, because
2477 // that would give JS the opportunity to "break the Internet".
2478 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2479 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2480 b > cricket::kDataMaxBandwidth / 1000) {
2481 std::ostringstream description;
2482 description << "RTP-based data channels may not send more than "
2483 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2484 return ParseFailed(line, description.str(), error);
2485 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002486 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002487 }
2488 }
2489 continue;
2490 }
2491
2492 if (!IsLineType(line, kLineTypeAttributes)) {
2493 // TODO: Handle other lines if needed.
2494 LOG(LS_INFO) << "Ignored line: " << line;
2495 continue;
2496 }
2497
2498 // Handle attributes common to SCTP and RTP.
2499 if (HasAttribute(line, kAttributeMid)) {
2500 // RFC 3388
2501 // mid-attribute = "a=mid:" identification-tag
2502 // identification-tag = token
2503 // Use the mid identification-tag as the content name.
2504 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2505 return false;
2506 }
2507 *content_name = mline_id;
2508 } else if (HasAttribute(line, kAttributeCandidate)) {
2509 Candidate candidate;
2510 if (!ParseCandidate(line, &candidate, error, false)) {
2511 return false;
2512 }
2513 candidates_orig.push_back(candidate);
2514 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2515 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2516 return false;
2517 }
2518 } else if (HasAttribute(line, kAttributeIcePwd)) {
2519 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2520 return false;
2521 }
2522 } else if (HasAttribute(line, kAttributeIceOption)) {
2523 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2524 return false;
2525 }
2526 } else if (HasAttribute(line, kAttributeFmtp)) {
2527 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2528 return false;
2529 }
2530 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002531 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002532
2533 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2534 return false;
2535 }
2536 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002537 } else if (HasAttribute(line, kAttributeSetup)) {
2538 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2539 return false;
2540 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002541 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002542 int sctp_port;
2543 if (!ParseSctpPort(line, &sctp_port, error)) {
2544 return false;
2545 }
2546 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2547 sctp_port)) {
2548 return false;
2549 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002550 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002551 //
2552 // RTP specific attrubtes
2553 //
2554 if (HasAttribute(line, kAttributeRtcpMux)) {
2555 media_desc->set_rtcp_mux(true);
2556 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2557 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2558 return false;
2559 }
2560 } else if (HasAttribute(line, kAttributeSsrc)) {
2561 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2562 return false;
2563 }
2564 } else if (HasAttribute(line, kAttributeCrypto)) {
2565 if (!ParseCryptoAttribute(line, media_desc, error)) {
2566 return false;
2567 }
2568 } else if (HasAttribute(line, kAttributeRtpmap)) {
2569 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2570 media_desc, error)) {
2571 return false;
2572 }
2573 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2574 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2575 return false;
2576 }
2577 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2578 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2579 return false;
2580 }
2581 } else if (HasAttribute(line, kCodecParamPTime)) {
2582 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2583 return false;
2584 }
2585 } else if (HasAttribute(line, kAttributeSendOnly)) {
2586 media_desc->set_direction(cricket::MD_SENDONLY);
2587 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2588 media_desc->set_direction(cricket::MD_RECVONLY);
2589 } else if (HasAttribute(line, kAttributeInactive)) {
2590 media_desc->set_direction(cricket::MD_INACTIVE);
2591 } else if (HasAttribute(line, kAttributeSendRecv)) {
2592 media_desc->set_direction(cricket::MD_SENDRECV);
2593 } else if (HasAttribute(line, kAttributeExtmap)) {
2594 RtpHeaderExtension extmap;
2595 if (!ParseExtmap(line, &extmap, error)) {
2596 return false;
2597 }
2598 media_desc->AddRtpHeaderExtension(extmap);
2599 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2600 // Experimental attribute. Conference mode activates more aggressive
2601 // AEC and NS settings.
2602 // TODO: expose API to set these directly.
2603 std::string flag_value;
2604 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2605 return false;
2606 }
2607 if (flag_value.compare(kValueConference) == 0)
2608 media_desc->set_conference_mode(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002609 }
2610 } else {
2611 // Only parse lines that we are interested of.
2612 LOG(LS_INFO) << "Ignored line: " << line;
2613 continue;
2614 }
2615 }
2616
2617 // Create tracks from the |ssrc_infos|.
2618 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2619
2620 // Add the ssrc group to the track.
2621 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2622 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2623 if (ssrc_group->ssrcs.empty()) {
2624 continue;
2625 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002626 uint32_t ssrc = ssrc_group->ssrcs.front();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002627 for (StreamParamsVec::iterator track = tracks.begin();
2628 track != tracks.end(); ++track) {
2629 if (track->has_ssrc(ssrc)) {
2630 track->ssrc_groups.push_back(*ssrc_group);
2631 }
2632 }
2633 }
2634
2635 // Add the new tracks to the |media_desc|.
2636 for (StreamParamsVec::iterator track = tracks.begin();
2637 track != tracks.end(); ++track) {
2638 media_desc->AddStream(*track);
2639 }
2640
2641 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2642 AudioContentDescription* audio_desc =
2643 static_cast<AudioContentDescription*>(media_desc);
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002644 UpdateFromWildcardCodecs(audio_desc);
2645
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002646 // Verify audio codec ensures that no audio codec has been populated with
2647 // only fmtp.
2648 if (!VerifyAudioCodecs(audio_desc)) {
2649 return ParseFailed("Failed to parse audio codecs correctly.", error);
2650 }
2651 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2652 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2653 }
2654
2655 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002656 VideoContentDescription* video_desc =
2657 static_cast<VideoContentDescription*>(media_desc);
2658 UpdateFromWildcardCodecs(video_desc);
2659 // Verify video codec ensures that no video codec has been populated with
2660 // only rtcp-fb.
2661 if (!VerifyVideoCodecs(video_desc)) {
2662 return ParseFailed("Failed to parse video codecs correctly.", error);
2663 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002664 }
2665
2666 // RFC 5245
2667 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2668 for (Candidates::iterator it = candidates_orig.begin();
2669 it != candidates_orig.end(); ++it) {
2670 ASSERT((*it).username().empty());
2671 (*it).set_username(transport->ice_ufrag);
2672 ASSERT((*it).password().empty());
2673 (*it).set_password(transport->ice_pwd);
2674 candidates->push_back(
2675 new JsepIceCandidate(mline_id, mline_index, *it));
2676 }
2677 return true;
2678}
2679
2680bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2681 SdpParseError* error) {
2682 ASSERT(ssrc_infos != NULL);
2683 // RFC 5576
2684 // a=ssrc:<ssrc-id> <attribute>
2685 // a=ssrc:<ssrc-id> <attribute>:<value>
2686 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07002687 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2688 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002689 const size_t expected_fields = 2;
2690 return ParseFailedExpectFieldNum(line, expected_fields, error);
2691 }
2692
2693 // ssrc:<ssrc-id>
2694 std::string ssrc_id_s;
2695 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2696 return false;
2697 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002698 uint32_t ssrc_id = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002699 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2700 return false;
2701 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002702
2703 std::string attribute;
2704 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07002705 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002706 std::ostringstream description;
2707 description << "Failed to get the ssrc attribute value from " << field2
2708 << ". Expected format <attribute>:<value>.";
2709 return ParseFailed(line, description.str(), error);
2710 }
2711
2712 // Check if there's already an item for this |ssrc_id|. Create a new one if
2713 // there isn't.
2714 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2715 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2716 if (ssrc_info->ssrc_id == ssrc_id) {
2717 break;
2718 }
2719 }
2720 if (ssrc_info == ssrc_infos->end()) {
2721 SsrcInfo info;
2722 info.ssrc_id = ssrc_id;
2723 ssrc_infos->push_back(info);
2724 ssrc_info = ssrc_infos->end() - 1;
2725 }
2726
2727 // Store the info to the |ssrc_info|.
2728 if (attribute == kSsrcAttributeCname) {
2729 // RFC 5576
2730 // cname:<value>
2731 ssrc_info->cname = value;
2732 } else if (attribute == kSsrcAttributeMsid) {
2733 // draft-alvestrand-mmusic-msid-00
2734 // "msid:" identifier [ " " appdata ]
2735 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002736 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002737 if (fields.size() < 1 || fields.size() > 2) {
2738 return ParseFailed(line,
2739 "Expected format \"msid:<identifier>[ <appdata>]\".",
2740 error);
2741 }
2742 ssrc_info->msid_identifier = fields[0];
2743 if (fields.size() == 2) {
2744 ssrc_info->msid_appdata = fields[1];
2745 }
2746 } else if (attribute == kSsrcAttributeMslabel) {
2747 // draft-alvestrand-rtcweb-mid-01
2748 // mslabel:<value>
2749 ssrc_info->mslabel = value;
2750 } else if (attribute == kSSrcAttributeLabel) {
2751 // The label isn't defined.
2752 // label:<value>
2753 ssrc_info->label = value;
2754 }
2755 return true;
2756}
2757
2758bool ParseSsrcGroupAttribute(const std::string& line,
2759 SsrcGroupVec* ssrc_groups,
2760 SdpParseError* error) {
2761 ASSERT(ssrc_groups != NULL);
2762 // RFC 5576
2763 // a=ssrc-group:<semantics> <ssrc-id> ...
2764 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002765 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002766 kSdpDelimiterSpace, &fields);
2767 const size_t expected_min_fields = 2;
2768 if (fields.size() < expected_min_fields) {
2769 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2770 }
2771 std::string semantics;
2772 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2773 return false;
2774 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002775 std::vector<uint32_t> ssrcs;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002776 for (size_t i = 1; i < fields.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02002777 uint32_t ssrc = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002778 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2779 return false;
2780 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002781 ssrcs.push_back(ssrc);
2782 }
2783 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2784 return true;
2785}
2786
2787bool ParseCryptoAttribute(const std::string& line,
2788 MediaContentDescription* media_desc,
2789 SdpParseError* error) {
2790 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002791 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002792 kSdpDelimiterSpace, &fields);
2793 // RFC 4568
2794 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2795 const size_t expected_min_fields = 3;
2796 if (fields.size() < expected_min_fields) {
2797 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2798 }
2799 std::string tag_value;
2800 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2801 return false;
2802 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002803 int tag = 0;
2804 if (!GetValueFromString(line, tag_value, &tag, error)) {
2805 return false;
2806 }
jbauch083b73f2015-07-16 02:46:32 -07002807 const std::string& crypto_suite = fields[1];
2808 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002809 std::string session_params;
2810 if (fields.size() > 3) {
2811 session_params = fields[3];
2812 }
2813 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2814 session_params));
2815 return true;
2816}
2817
2818// Updates or creates a new codec entry in the audio description with according
2819// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2820void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2821 int bitrate, int channels, int preference,
2822 AudioContentDescription* audio_desc) {
2823 // Codec may already be populated with (only) optional parameters
2824 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002825 cricket::AudioCodec codec =
2826 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002827 codec.name = name;
2828 codec.clockrate = clockrate;
2829 codec.bitrate = bitrate;
2830 codec.channels = channels;
2831 codec.preference = preference;
2832 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2833 codec);
2834}
2835
2836// Updates or creates a new codec entry in the video description according to
2837// |name|, |width|, |height|, |framerate| and |preference|.
2838void UpdateCodec(int payload_type, const std::string& name, int width,
2839 int height, int framerate, int preference,
2840 VideoContentDescription* video_desc) {
2841 // Codec may already be populated with (only) optional parameters
2842 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002843 cricket::VideoCodec codec =
2844 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002845 codec.name = name;
2846 codec.width = width;
2847 codec.height = height;
2848 codec.framerate = framerate;
2849 codec.preference = preference;
2850 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2851 codec);
2852}
2853
2854bool ParseRtpmapAttribute(const std::string& line,
2855 const MediaType media_type,
2856 const std::vector<int>& codec_preference,
2857 MediaContentDescription* media_desc,
2858 SdpParseError* error) {
2859 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002860 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002861 kSdpDelimiterSpace, &fields);
2862 // RFC 4566
2863 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2864 const size_t expected_min_fields = 2;
2865 if (fields.size() < expected_min_fields) {
2866 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2867 }
2868 std::string payload_type_value;
2869 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2870 return false;
2871 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002872 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002873 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
2874 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002875 return false;
2876 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002877
2878 // Set the preference order depending on the order of the pl type in the
2879 // <fmt> of the m-line.
2880 const int preference = codec_preference.end() -
2881 std::find(codec_preference.begin(), codec_preference.end(),
2882 payload_type);
2883 if (preference == 0) {
2884 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2885 << "<fmt> of the m-line: " << line;
2886 return true;
2887 }
jbauch083b73f2015-07-16 02:46:32 -07002888 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002889 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002890 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002891 // <encoding name>/<clock rate>[/<encodingparameters>]
2892 // 2 mandatory fields
2893 if (codec_params.size() < 2 || codec_params.size() > 3) {
2894 return ParseFailed(line,
2895 "Expected format \"<encoding name>/<clock rate>"
2896 "[/<encodingparameters>]\".",
2897 error);
2898 }
jbauch083b73f2015-07-16 02:46:32 -07002899 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002900 int clock_rate = 0;
2901 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2902 return false;
2903 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002904 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2905 VideoContentDescription* video_desc =
2906 static_cast<VideoContentDescription*>(media_desc);
2907 // TODO: We will send resolution in SDP. For now use
2908 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2909 UpdateCodec(payload_type, encoding_name,
2910 JsepSessionDescription::kMaxVideoCodecWidth,
2911 JsepSessionDescription::kMaxVideoCodecHeight,
2912 JsepSessionDescription::kDefaultVideoCodecFramerate,
2913 preference, video_desc);
2914 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2915 // RFC 4566
2916 // For audio streams, <encoding parameters> indicates the number
2917 // of audio channels. This parameter is OPTIONAL and may be
2918 // omitted if the number of channels is one, provided that no
2919 // additional parameters are needed.
2920 int channels = 1;
2921 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002922 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2923 return false;
2924 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002925 }
2926 int bitrate = 0;
2927 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2928 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2929 // The bandwidth adaptation doesn't always work well, so this code
2930 // sets a fixed target bitrate instead.
2931 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2932 if (clock_rate <= 16000) {
2933 bitrate = kIsacWbDefaultRate;
2934 } else {
2935 bitrate = kIsacSwbDefaultRate;
2936 }
2937 }
2938 AudioContentDescription* audio_desc =
2939 static_cast<AudioContentDescription*>(media_desc);
2940 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2941 preference, audio_desc);
2942 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2943 DataContentDescription* data_desc =
2944 static_cast<DataContentDescription*>(media_desc);
2945 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2946 preference));
2947 }
2948 return true;
2949}
2950
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002951bool ParseFmtpParam(const std::string& line, std::string* parameter,
2952 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07002953 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002954 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2955 return false;
2956 }
2957 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002958 return true;
2959}
2960
2961bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
2962 MediaContentDescription* media_desc,
2963 SdpParseError* error) {
2964 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2965 media_type != cricket::MEDIA_TYPE_VIDEO) {
2966 return true;
2967 }
Donald Curtis0e07f922015-05-15 09:21:23 -07002968
2969 std::string line_payload;
2970 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002971
2972 // RFC 5576
2973 // a=fmtp:<format> <format specific parameters>
2974 // At least two fields, whereas the second one is any of the optional
2975 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07002976 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2977 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002978 ParseFailedExpectMinFieldNum(line, 2, error);
2979 return false;
2980 }
2981
Donald Curtis0e07f922015-05-15 09:21:23 -07002982 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00002983 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07002984 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002985 return false;
2986 }
2987
Donald Curtis0e07f922015-05-15 09:21:23 -07002988 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07002989 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
2990 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07002991 return false;
2992 }
2993
2994 // Parse out format specific parameters.
2995 std::vector<std::string> fields;
2996 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
2997
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002998 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07002999 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003000 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003001 // Only fmtps with equals are currently supported. Other fmtp types
3002 // should be ignored. Unknown fmtps do not constitute an error.
3003 continue;
3004 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003005
3006 std::string name;
3007 std::string value;
3008 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003009 return false;
3010 }
3011 codec_params[name] = value;
3012 }
3013
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003014 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3015 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003016 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003017 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3018 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003019 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003020 }
3021 return true;
3022}
3023
3024bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3025 MediaContentDescription* media_desc,
3026 SdpParseError* error) {
3027 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3028 media_type != cricket::MEDIA_TYPE_VIDEO) {
3029 return true;
3030 }
3031 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003032 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003033 if (rtcp_fb_fields.size() < 2) {
3034 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3035 }
3036 std::string payload_type_string;
3037 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3038 error)) {
3039 return false;
3040 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003041 int payload_type = kWildcardPayloadType;
3042 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003043 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3044 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003045 return false;
3046 }
3047 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003048 std::string id = rtcp_fb_fields[1];
3049 std::string param = "";
3050 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3051 iter != rtcp_fb_fields.end(); ++iter) {
3052 param.append(*iter);
3053 }
3054 const cricket::FeedbackParam feedback_param(id, param);
3055
3056 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003057 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3058 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003059 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003060 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3061 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003062 }
3063 return true;
3064}
3065
3066} // namespace webrtc