blob: aaf9d71940b2670f70c99db638c6d96c69c8747c [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00003 * Copyright 2011 Google Inc.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/app/webrtc/webrtcsdp.h"
29
30#include <limits.h>
31#include <stdio.h>
32#include <algorithm>
33#include <string>
34#include <vector>
decurtis@webrtc.org8af11042015-01-07 19:15:51 +000035#include <ctype.h>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000036
37#include "talk/app/webrtc/jsepicecandidate.h"
38#include "talk/app/webrtc/jsepsessiondescription.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000039#include "talk/media/base/codec.h"
40#include "talk/media/base/constants.h"
41#include "talk/media/base/cryptoparams.h"
pkasting@chromium.orge9facf82015-02-17 20:36:28 +000042#include "talk/media/base/rtputils.h"
mallinath@webrtc.org1112c302013-09-23 20:34:45 +000043#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000044#include "webrtc/p2p/base/candidate.h"
45#include "webrtc/p2p/base/constants.h"
46#include "webrtc/p2p/base/port.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000047#include "talk/session/media/mediasession.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000048#include "webrtc/base/common.h"
49#include "webrtc/base/logging.h"
50#include "webrtc/base/messagedigest.h"
51#include "webrtc/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052
53using cricket::AudioContentDescription;
54using cricket::Candidate;
55using cricket::Candidates;
56using cricket::ContentDescription;
57using cricket::ContentInfo;
58using cricket::CryptoParams;
59using cricket::DataContentDescription;
60using cricket::ICE_CANDIDATE_COMPONENT_RTP;
61using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
62using cricket::kCodecParamMaxBitrate;
63using cricket::kCodecParamMaxPTime;
64using cricket::kCodecParamMaxQuantization;
65using cricket::kCodecParamMinBitrate;
66using cricket::kCodecParamMinPTime;
67using cricket::kCodecParamPTime;
68using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000069using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070using cricket::kCodecParamStereo;
71using cricket::kCodecParamUseInbandFec;
Minyue Li7100dcd2015-03-27 05:05:59 +010072using cricket::kCodecParamUseDtx;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073using cricket::kCodecParamSctpProtocol;
74using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000075using cricket::kCodecParamMaxAverageBitrate;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000076using cricket::kCodecParamMaxPlaybackRate;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000077using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000078using cricket::MediaContentDescription;
79using cricket::MediaType;
80using cricket::NS_JINGLE_ICE_UDP;
81using cricket::RtpHeaderExtension;
82using cricket::SsrcGroup;
83using cricket::StreamParams;
84using cricket::StreamParamsVec;
85using cricket::TransportDescription;
86using cricket::TransportInfo;
87using cricket::VideoContentDescription;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000088using rtc::SocketAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089
90typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
91
92namespace cricket {
93class SessionDescription;
94}
95
96namespace webrtc {
97
98// Line type
99// RFC 4566
100// An SDP session description consists of a number of lines of text of
101// the form:
102// <type>=<value>
103// where <type> MUST be exactly one case-significant character.
104static const int kLinePrefixLength = 2; // Lenght of <type>=
105static const char kLineTypeVersion = 'v';
106static const char kLineTypeOrigin = 'o';
107static const char kLineTypeSessionName = 's';
108static const char kLineTypeSessionInfo = 'i';
109static const char kLineTypeSessionUri = 'u';
110static const char kLineTypeSessionEmail = 'e';
111static const char kLineTypeSessionPhone = 'p';
112static const char kLineTypeSessionBandwidth = 'b';
113static const char kLineTypeTiming = 't';
114static const char kLineTypeRepeatTimes = 'r';
115static const char kLineTypeTimeZone = 'z';
116static const char kLineTypeEncryptionKey = 'k';
117static const char kLineTypeMedia = 'm';
118static const char kLineTypeConnection = 'c';
119static const char kLineTypeAttributes = 'a';
120
121// Attributes
122static const char kAttributeGroup[] = "group";
123static const char kAttributeMid[] = "mid";
124static const char kAttributeRtcpMux[] = "rtcp-mux";
125static const char kAttributeSsrc[] = "ssrc";
126static const char kSsrcAttributeCname[] = "cname";
127static const char kAttributeExtmap[] = "extmap";
128// draft-alvestrand-mmusic-msid-01
129// a=msid-semantic: WMS
130static const char kAttributeMsidSemantics[] = "msid-semantic";
131static const char kMediaStreamSemantic[] = "WMS";
132static const char kSsrcAttributeMsid[] = "msid";
133static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134static const char kSsrcAttributeMslabel[] = "mslabel";
135static const char kSSrcAttributeLabel[] = "label";
136static const char kAttributeSsrcGroup[] = "ssrc-group";
137static const char kAttributeCrypto[] = "crypto";
138static const char kAttributeCandidate[] = "candidate";
139static const char kAttributeCandidateTyp[] = "typ";
140static const char kAttributeCandidateRaddr[] = "raddr";
141static const char kAttributeCandidateRport[] = "rport";
142static const char kAttributeCandidateUsername[] = "username";
143static const char kAttributeCandidatePassword[] = "password";
144static const char kAttributeCandidateGeneration[] = "generation";
145static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000146static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000147static const char kAttributeFmtp[] = "fmtp";
148static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000149static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000150static const char kAttributeRtcp[] = "rtcp";
151static const char kAttributeIceUfrag[] = "ice-ufrag";
152static const char kAttributeIcePwd[] = "ice-pwd";
153static const char kAttributeIceLite[] = "ice-lite";
154static const char kAttributeIceOption[] = "ice-options";
155static const char kAttributeSendOnly[] = "sendonly";
156static const char kAttributeRecvOnly[] = "recvonly";
157static const char kAttributeRtcpFb[] = "rtcp-fb";
158static const char kAttributeSendRecv[] = "sendrecv";
159static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000160// draft-ietf-mmusic-sctp-sdp-07
161// a=sctp-port
162static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000163
164// Experimental flags
165static const char kAttributeXGoogleFlag[] = "x-google-flag";
166static const char kValueConference[] = "conference";
167static const char kAttributeXGoogleBufferLatency[] =
168 "x-google-buffer-latency";
169
170// Candidate
171static const char kCandidateHost[] = "host";
172static const char kCandidateSrflx[] = "srflx";
173// TODO: How to map the prflx with circket candidate type
174// static const char kCandidatePrflx[] = "prflx";
175static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000176static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000177
178static const char kSdpDelimiterEqual = '=';
179static const char kSdpDelimiterSpace = ' ';
180static const char kSdpDelimiterColon = ':';
181static const char kSdpDelimiterSemicolon = ';';
182static const char kSdpDelimiterSlash = '/';
183static const char kNewLine = '\n';
184static const char kReturn = '\r';
185static const char kLineBreak[] = "\r\n";
186
187// TODO: Generate the Session and Time description
188// instead of hardcoding.
189static const char kSessionVersion[] = "v=0";
190// RFC 4566
191static const char kSessionOriginUsername[] = "-";
192static const char kSessionOriginSessionId[] = "0";
193static const char kSessionOriginSessionVersion[] = "0";
194static const char kSessionOriginNettype[] = "IN";
195static const char kSessionOriginAddrtype[] = "IP4";
196static const char kSessionOriginAddress[] = "127.0.0.1";
197static const char kSessionName[] = "s=-";
198static const char kTimeDescription[] = "t=0 0";
199static const char kAttrGroup[] = "a=group:BUNDLE";
200static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000201static const char kConnectionIpv4Addrtype[] = "IP4";
202static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000203static const char kMediaTypeVideo[] = "video";
204static const char kMediaTypeAudio[] = "audio";
205static const char kMediaTypeData[] = "application";
206static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000207// draft-ietf-mmusic-trickle-ice-01
208// When no candidates have been gathered, set the connection
209// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000210// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
211// Use IPV4 per default.
212static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000213static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000214// RFC 3556
215static const char kApplicationSpecificMaximum[] = "AS";
216
217static const int kDefaultVideoClockrate = 90000;
218
219// ISAC special-case.
220static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
221static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
222static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
223
wu@webrtc.org78187522013-10-07 23:32:02 +0000224static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000225
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000226// RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
227// types.
228const int kWildcardPayloadType = -1;
229
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000230struct SsrcInfo {
231 SsrcInfo()
232 : msid_identifier(kDefaultMsid),
233 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
234 // Create random string (which will be used as track label later)?
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000235 msid_appdata(rtc::CreateRandomString(8)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000236 }
237 uint32 ssrc_id;
238 std::string cname;
239 std::string msid_identifier;
240 std::string msid_appdata;
241
242 // For backward compatibility.
243 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
244 std::string label;
245 std::string mslabel;
246};
247typedef std::vector<SsrcInfo> SsrcInfoVec;
248typedef std::vector<SsrcGroup> SsrcGroupVec;
249
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000250template <class T>
251static void AddFmtpLine(const T& codec, std::string* message);
252static void BuildMediaDescription(const ContentInfo* content_info,
253 const TransportInfo* transport_info,
254 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000255 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000256 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000257static void BuildSctpContentAttributes(std::string* message, int sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258static void BuildRtpContentAttributes(
259 const MediaContentDescription* media_desc,
260 const MediaType media_type,
261 std::string* message);
262static void BuildRtpMap(const MediaContentDescription* media_desc,
263 const MediaType media_type,
264 std::string* message);
265static void BuildCandidate(const std::vector<Candidate>& candidates,
266 std::string* message);
267static void BuildIceOptions(const std::vector<std::string>& transport_options,
268 std::string* message);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +0000269static bool IsRtp(const std::string& protocol);
270static bool IsDtlsSctp(const std::string& protocol);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271static bool ParseSessionDescription(const std::string& message, size_t* pos,
272 std::string* session_id,
273 std::string* session_version,
274 bool* supports_msid,
275 TransportDescription* session_td,
276 RtpHeaderExtensions* session_extmaps,
277 cricket::SessionDescription* desc,
278 SdpParseError* error);
279static bool ParseGroupAttribute(const std::string& line,
280 cricket::SessionDescription* desc,
281 SdpParseError* error);
282static bool ParseMediaDescription(
283 const std::string& message,
284 const TransportDescription& session_td,
285 const RtpHeaderExtensions& session_extmaps,
286 bool supports_msid,
287 size_t* pos, cricket::SessionDescription* desc,
288 std::vector<JsepIceCandidate*>* candidates,
289 SdpParseError* error);
290static bool ParseContent(const std::string& message,
291 const MediaType media_type,
292 int mline_index,
293 const std::string& protocol,
294 const std::vector<int>& codec_preference,
295 size_t* pos,
296 std::string* content_name,
297 MediaContentDescription* media_desc,
298 TransportDescription* transport,
299 std::vector<JsepIceCandidate*>* candidates,
300 SdpParseError* error);
301static bool ParseSsrcAttribute(const std::string& line,
302 SsrcInfoVec* ssrc_infos,
303 SdpParseError* error);
304static bool ParseSsrcGroupAttribute(const std::string& line,
305 SsrcGroupVec* ssrc_groups,
306 SdpParseError* error);
307static bool ParseCryptoAttribute(const std::string& line,
308 MediaContentDescription* media_desc,
309 SdpParseError* error);
310static bool ParseRtpmapAttribute(const std::string& line,
311 const MediaType media_type,
312 const std::vector<int>& codec_preference,
313 MediaContentDescription* media_desc,
314 SdpParseError* error);
315static bool ParseFmtpAttributes(const std::string& line,
316 const MediaType media_type,
317 MediaContentDescription* media_desc,
318 SdpParseError* error);
319static bool ParseFmtpParam(const std::string& line, std::string* parameter,
320 std::string* value, SdpParseError* error);
321static bool ParseCandidate(const std::string& message, Candidate* candidate,
322 SdpParseError* error, bool is_raw);
323static bool ParseRtcpFbAttribute(const std::string& line,
324 const MediaType media_type,
325 MediaContentDescription* media_desc,
326 SdpParseError* error);
327static bool ParseIceOptions(const std::string& line,
328 std::vector<std::string>* transport_options,
329 SdpParseError* error);
330static bool ParseExtmap(const std::string& line,
331 RtpHeaderExtension* extmap,
332 SdpParseError* error);
333static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000334 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000335 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000336static bool ParseDtlsSetup(const std::string& line,
337 cricket::ConnectionRole* role,
338 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000339
340// Helper functions
341
342// Below ParseFailed*** functions output the line that caused the parsing
343// failure and the detailed reason (|description|) of the failure to |error|.
344// The functions always return false so that they can be used directly in the
345// following way when error happens:
346// "return ParseFailed***(...);"
347
348// The line starting at |line_start| of |message| is the failing line.
349// The reason for the failure should be provided in the |description|.
350// An example of a description could be "unknown character".
351static bool ParseFailed(const std::string& message,
352 size_t line_start,
353 const std::string& description,
354 SdpParseError* error) {
355 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000356 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000357 size_t line_end = message.find(kNewLine, line_start);
358 if (line_end != std::string::npos) {
359 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
360 --line_end;
361 }
362 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000363 } else {
364 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000365 }
366
367 if (error) {
368 error->line = first_line;
369 error->description = description;
370 }
371 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
372 << "\". Reason: " << description;
373 return false;
374}
375
376// |line| is the failing line. The reason for the failure should be
377// provided in the |description|.
378static bool ParseFailed(const std::string& line,
379 const std::string& description,
380 SdpParseError* error) {
381 return ParseFailed(line, 0, description, error);
382}
383
384// Parses failure where the failing SDP line isn't know or there are multiple
385// failing lines.
386static bool ParseFailed(const std::string& description,
387 SdpParseError* error) {
388 return ParseFailed("", description, error);
389}
390
391// |line| is the failing line. The failure is due to the fact that |line|
392// doesn't have |expected_fields| fields.
393static bool ParseFailedExpectFieldNum(const std::string& line,
394 int expected_fields,
395 SdpParseError* error) {
396 std::ostringstream description;
397 description << "Expects " << expected_fields << " fields.";
398 return ParseFailed(line, description.str(), error);
399}
400
401// |line| is the failing line. The failure is due to the fact that |line| has
402// less than |expected_min_fields| fields.
403static bool ParseFailedExpectMinFieldNum(const std::string& line,
404 int expected_min_fields,
405 SdpParseError* error) {
406 std::ostringstream description;
407 description << "Expects at least " << expected_min_fields << " fields.";
408 return ParseFailed(line, description.str(), error);
409}
410
411// |line| is the failing line. The failure is due to the fact that it failed to
412// get the value of |attribute|.
413static bool ParseFailedGetValue(const std::string& line,
414 const std::string& attribute,
415 SdpParseError* error) {
416 std::ostringstream description;
417 description << "Failed to get the value of attribute: " << attribute;
418 return ParseFailed(line, description.str(), error);
419}
420
421// The line starting at |line_start| of |message| is the failing line. The
422// failure is due to the line type (e.g. the "m" part of the "m-line")
423// not matching what is expected. The expected line type should be
424// provided as |line_type|.
425static bool ParseFailedExpectLine(const std::string& message,
426 size_t line_start,
427 const char line_type,
428 const std::string& line_value,
429 SdpParseError* error) {
430 std::ostringstream description;
431 description << "Expect line: " << line_type << "=" << line_value;
432 return ParseFailed(message, line_start, description.str(), error);
433}
434
435static bool AddLine(const std::string& line, std::string* message) {
436 if (!message)
437 return false;
438
439 message->append(line);
440 message->append(kLineBreak);
441 return true;
442}
443
444static bool GetLine(const std::string& message,
445 size_t* pos,
446 std::string* line) {
447 size_t line_begin = *pos;
448 size_t line_end = message.find(kNewLine, line_begin);
449 if (line_end == std::string::npos) {
450 return false;
451 }
452 // Update the new start position
453 *pos = line_end + 1;
454 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
455 --line_end;
456 }
457 *line = message.substr(line_begin, (line_end - line_begin));
458 const char* cline = line->c_str();
459 // RFC 4566
460 // An SDP session description consists of a number of lines of text of
461 // the form:
462 // <type>=<value>
463 // where <type> MUST be exactly one case-significant character and
464 // <value> is structured text whose format depends on <type>.
465 // Whitespace MUST NOT be used on either side of the "=" sign.
decurtis@webrtc.org8af11042015-01-07 19:15:51 +0000466 if (line->length() < 3 ||
467 !islower(cline[0]) ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000468 cline[1] != kSdpDelimiterEqual ||
469 cline[2] == kSdpDelimiterSpace) {
470 *pos = line_begin;
471 return false;
472 }
473 return true;
474}
475
476// Init |os| to "|type|=|value|".
477static void InitLine(const char type,
478 const std::string& value,
479 std::ostringstream* os) {
480 os->str("");
481 *os << type << kSdpDelimiterEqual << value;
482}
483
484// Init |os| to "a=|attribute|".
485static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
486 InitLine(kLineTypeAttributes, attribute, os);
487}
488
489// Writes a SDP attribute line based on |attribute| and |value| to |message|.
490static void AddAttributeLine(const std::string& attribute, int value,
491 std::string* message) {
492 std::ostringstream os;
493 InitAttrLine(attribute, &os);
494 os << kSdpDelimiterColon << value;
495 AddLine(os.str(), message);
496}
497
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000498static bool IsLineType(const std::string& message,
499 const char type,
500 size_t line_start) {
501 if (message.size() < line_start + kLinePrefixLength) {
502 return false;
503 }
504 const char* cmessage = message.c_str();
505 return (cmessage[line_start] == type &&
506 cmessage[line_start + 1] == kSdpDelimiterEqual);
507}
508
509static bool IsLineType(const std::string& line,
510 const char type) {
511 return IsLineType(line, type, 0);
512}
513
514static bool GetLineWithType(const std::string& message, size_t* pos,
515 std::string* line, const char type) {
516 if (!IsLineType(message, type, *pos)) {
517 return false;
518 }
519
520 if (!GetLine(message, pos, line))
521 return false;
522
523 return true;
524}
525
526static bool HasAttribute(const std::string& line,
527 const std::string& attribute) {
528 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
529}
530
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000531static bool AddSsrcLine(uint32 ssrc_id, const std::string& attribute,
532 const std::string& value, std::string* message) {
533 // RFC 5576
534 // a=ssrc:<ssrc-id> <attribute>:<value>
535 std::ostringstream os;
536 InitAttrLine(kAttributeSsrc, &os);
537 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
538 << attribute << kSdpDelimiterColon << value;
539 return AddLine(os.str(), message);
540}
541
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000542// Get value only from <attribute>:<value>.
543static bool GetValue(const std::string& message, const std::string& attribute,
544 std::string* value, SdpParseError* error) {
545 std::string leftpart;
Donald Curtis0e07f922015-05-15 09:21:23 -0700546 if (!rtc::tokenize_first(message, kSdpDelimiterColon, &leftpart, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000547 return ParseFailedGetValue(message, attribute, error);
548 }
549 // The left part should end with the expected attribute.
550 if (leftpart.length() < attribute.length() ||
551 leftpart.compare(leftpart.length() - attribute.length(),
552 attribute.length(), attribute) != 0) {
553 return ParseFailedGetValue(message, attribute, error);
554 }
555 return true;
556}
557
558static bool CaseInsensitiveFind(std::string str1, std::string str2) {
559 std::transform(str1.begin(), str1.end(), str1.begin(),
560 ::tolower);
561 std::transform(str2.begin(), str2.end(), str2.begin(),
562 ::tolower);
563 return str1.find(str2) != std::string::npos;
564}
565
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000566template <class T>
567static bool GetValueFromString(const std::string& line,
568 const std::string& s,
569 T* t,
570 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000571 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000572 std::ostringstream description;
573 description << "Invalid value: " << s << ".";
574 return ParseFailed(line, description.str(), error);
575 }
576 return true;
577}
578
pkasting@chromium.orge9facf82015-02-17 20:36:28 +0000579static bool GetPayloadTypeFromString(const std::string& line,
580 const std::string& s,
581 int* payload_type,
582 SdpParseError* error) {
583 return GetValueFromString(line, s, payload_type, error) &&
584 cricket::IsValidRtpPayloadType(*payload_type);
585}
586
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
588 StreamParamsVec* tracks) {
589 ASSERT(tracks != NULL);
590 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
591 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
592 if (ssrc_info->cname.empty()) {
593 continue;
594 }
595
596 std::string sync_label;
597 std::string track_id;
598 if (ssrc_info->msid_identifier == kDefaultMsid &&
599 !ssrc_info->mslabel.empty()) {
600 // If there's no msid and there's mslabel, we consider this is a sdp from
601 // a older version of client that doesn't support msid.
602 // In that case, we use the mslabel and label to construct the track.
603 sync_label = ssrc_info->mslabel;
604 track_id = ssrc_info->label;
605 } else {
606 sync_label = ssrc_info->msid_identifier;
607 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
608 // is corresponding to the "id" attribute of StreamParams.
609 track_id = ssrc_info->msid_appdata;
610 }
611 if (sync_label.empty() || track_id.empty()) {
612 ASSERT(false);
613 continue;
614 }
615
616 StreamParamsVec::iterator track = tracks->begin();
617 for (; track != tracks->end(); ++track) {
618 if (track->id == track_id) {
619 break;
620 }
621 }
622 if (track == tracks->end()) {
623 // If we don't find an existing track, create a new one.
624 tracks->push_back(StreamParams());
625 track = tracks->end() - 1;
626 }
627 track->add_ssrc(ssrc_info->ssrc_id);
628 track->cname = ssrc_info->cname;
629 track->sync_label = sync_label;
630 track->id = track_id;
631 }
632}
633
634void GetMediaStreamLabels(const ContentInfo* content,
635 std::set<std::string>* labels) {
636 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000637 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000638 content->description);
639 const cricket::StreamParamsVec& streams = media_desc->streams();
640 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
641 it != streams.end(); ++it) {
642 labels->insert(it->sync_label);
643 }
644}
645
646// RFC 5245
647// It is RECOMMENDED that default candidates be chosen based on the
648// likelihood of those candidates to work with the peer that is being
649// contacted. It is RECOMMENDED that relayed > reflexive > host.
650static const int kPreferenceUnknown = 0;
651static const int kPreferenceHost = 1;
652static const int kPreferenceReflexive = 2;
653static const int kPreferenceRelayed = 3;
654
655static int GetCandidatePreferenceFromType(const std::string& type) {
656 int preference = kPreferenceUnknown;
657 if (type == cricket::LOCAL_PORT_TYPE) {
658 preference = kPreferenceHost;
659 } else if (type == cricket::STUN_PORT_TYPE) {
660 preference = kPreferenceReflexive;
661 } else if (type == cricket::RELAY_PORT_TYPE) {
662 preference = kPreferenceRelayed;
663 } else {
664 ASSERT(false);
665 }
666 return preference;
667}
668
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000669// Get ip and port of the default destination from the |candidates| with the
670// given value of |component_id|. The default candidate should be the one most
671// likely to work, typically IPv4 relay.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672// RFC 5245
673// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
674// TODO: Decide the default destination in webrtcsession and
675// pass it down via SessionDescription.
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000676static void GetDefaultDestination(
677 const std::vector<Candidate>& candidates,
678 int component_id, std::string* port,
679 std::string* ip, std::string* addr_type) {
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000680 *addr_type = kConnectionIpv4Addrtype;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000681 *port = kDummyPort;
682 *ip = kDummyAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000683 int current_preference = kPreferenceUnknown;
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000684 int current_family = AF_UNSPEC;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685 for (std::vector<Candidate>::const_iterator it = candidates.begin();
686 it != candidates.end(); ++it) {
687 if (it->component() != component_id) {
688 continue;
689 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000690 // Default destination should be UDP only.
691 if (it->protocol() != cricket::UDP_PROTOCOL_NAME) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000692 continue;
693 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000694 const int preference = GetCandidatePreferenceFromType(it->type());
695 const int family = it->address().ipaddr().family();
696 // See if this candidate is more preferable then the current one if it's the
697 // same family. Or if the current family is IPv4 already so we could safely
698 // ignore all IPv6 ones. WebRTC bug 4269.
699 // http://code.google.com/p/webrtc/issues/detail?id=4269
700 if ((preference <= current_preference && current_family == family) ||
701 (current_family == AF_INET && family == AF_INET6)) {
702 continue;
703 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000704 if (family == AF_INET) {
705 addr_type->assign(kConnectionIpv4Addrtype);
706 } else if (family == AF_INET6) {
707 addr_type->assign(kConnectionIpv6Addrtype);
708 }
guoweis@webrtc.org57ac2c82015-02-06 00:45:13 +0000709 current_preference = preference;
710 current_family = family;
711 *port = it->address().PortAsString();
712 *ip = it->address().ipaddr().ToString();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000713 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000714}
715
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000716// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000717static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000718 const std::vector<Candidate>& candidates,
719 const std::string mline,
720 std::string* message) {
721 std::string new_lines;
722 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723 // RFC 4566
724 // m=<media> <port> <proto> <fmt> ...
725 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000726 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727 if (fields.size() < 3) {
728 return;
729 }
730
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000732 std::string rtp_port, rtp_ip, addr_type;
733 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
734 &rtp_port, &rtp_ip, &addr_type);
735 // Found default RTP candidate.
736 // RFC 5245
737 // The default candidates are added to the SDP as the default
738 // destination for media. For streams based on RTP, this is done by
739 // placing the IP address and port of the RTP candidate into the c and m
740 // lines, respectively.
741 // Update the port in the m line.
742 // If this is a m-line with port equal to 0, we don't change it.
743 if (fields[1] != kMediaPortRejected) {
744 new_lines.replace(fields[0].size() + 1,
745 fields[1].size(),
746 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000747 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000748 // Add the c line.
749 // RFC 4566
750 // c=<nettype> <addrtype> <connection-address>
751 InitLine(kLineTypeConnection, kConnectionNettype, &os);
752 os << " " << addr_type << " " << rtp_ip;
753 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000754 message->append(new_lines);
755}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000757// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
758static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000759 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
760 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
761 &rtcp_port, &rtcp_ip, &addr_type);
762 // Found default RTCP candidate.
763 // RFC 5245
764 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
765 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000766
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000767 // RFC 3605
768 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
769 // connection-address] CRLF
770 std::ostringstream os;
771 InitAttrLine(kAttributeRtcp, &os);
772 os << kSdpDelimiterColon
773 << rtcp_port << " "
774 << kConnectionNettype << " "
775 << addr_type << " "
776 << rtcp_ip;
777 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000778 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000779}
780
781// Get candidates according to the mline index from SessionDescriptionInterface.
782static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
783 int mline_index,
784 std::vector<Candidate>* candidates) {
785 if (!candidates) {
786 return;
787 }
788 const IceCandidateCollection* cc = desci.candidates(mline_index);
789 for (size_t i = 0; i < cc->count(); ++i) {
790 const IceCandidateInterface* candidate = cc->at(i);
791 candidates->push_back(candidate->candidate());
792 }
793}
794
795std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796 const cricket::SessionDescription* desc = jdesc.description();
797 if (!desc) {
798 return "";
799 }
800
801 std::string message;
802
803 // Session Description.
804 AddLine(kSessionVersion, &message);
805 // Session Origin
806 // RFC 4566
807 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
808 // <unicast-address>
809 std::ostringstream os;
810 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
811 const std::string session_id = jdesc.session_id().empty() ?
812 kSessionOriginSessionId : jdesc.session_id();
813 const std::string session_version = jdesc.session_version().empty() ?
814 kSessionOriginSessionVersion : jdesc.session_version();
815 os << " " << session_id << " " << session_version << " "
816 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
817 << kSessionOriginAddress;
818 AddLine(os.str(), &message);
819 AddLine(kSessionName, &message);
820
821 // Time Description.
822 AddLine(kTimeDescription, &message);
823
824 // Group
825 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
826 std::string group_line = kAttrGroup;
827 const cricket::ContentGroup* group =
828 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
829 ASSERT(group != NULL);
830 const cricket::ContentNames& content_names = group->content_names();
831 for (cricket::ContentNames::const_iterator it = content_names.begin();
832 it != content_names.end(); ++it) {
833 group_line.append(" ");
834 group_line.append(*it);
835 }
836 AddLine(group_line, &message);
837 }
838
839 // MediaStream semantics
840 InitAttrLine(kAttributeMsidSemantics, &os);
841 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000842
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843 std::set<std::string> media_stream_labels;
844 const ContentInfo* audio_content = GetFirstAudioContent(desc);
845 if (audio_content)
846 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000847
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848 const ContentInfo* video_content = GetFirstVideoContent(desc);
849 if (video_content)
850 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000851
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000852 for (std::set<std::string>::const_iterator it =
853 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
854 os << " " << *it;
855 }
856 AddLine(os.str(), &message);
857
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000858 // Preserve the order of the media contents.
859 int mline_index = -1;
860 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
861 it != desc->contents().end(); ++it) {
862 const MediaContentDescription* mdesc =
863 static_cast<const MediaContentDescription*>(it->description);
864 std::vector<Candidate> candidates;
865 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
866 BuildMediaDescription(&*it,
867 desc->GetTransportInfoByName(it->name),
868 mdesc->type(),
869 candidates,
870 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000871 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872 return message;
873}
874
875// Serializes the passed in IceCandidateInterface to a SDP string.
876// candidate - The candidate to be serialized.
877std::string SdpSerializeCandidate(
878 const IceCandidateInterface& candidate) {
879 std::string message;
880 std::vector<cricket::Candidate> candidates;
881 candidates.push_back(candidate.candidate());
882 BuildCandidate(candidates, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000883 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
884 // just candidate:<candidate> not a=candidate:<blah>CRLF
885 ASSERT(message.find("a=") == 0);
886 message.erase(0, 2);
887 ASSERT(message.find(kLineBreak) == message.size() - 2);
888 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000889 return message;
890}
891
892bool SdpDeserialize(const std::string& message,
893 JsepSessionDescription* jdesc,
894 SdpParseError* error) {
895 std::string session_id;
896 std::string session_version;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000897 TransportDescription session_td(NS_JINGLE_ICE_UDP,
898 std::string(), std::string());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899 RtpHeaderExtensions session_extmaps;
900 cricket::SessionDescription* desc = new cricket::SessionDescription();
901 std::vector<JsepIceCandidate*> candidates;
902 size_t current_pos = 0;
903 bool supports_msid = false;
904
905 // Session Description
906 if (!ParseSessionDescription(message, &current_pos, &session_id,
907 &session_version, &supports_msid, &session_td,
908 &session_extmaps, desc, error)) {
909 delete desc;
910 return false;
911 }
912
913 // Media Description
914 if (!ParseMediaDescription(message, session_td, session_extmaps,
915 supports_msid, &current_pos, desc, &candidates,
916 error)) {
917 delete desc;
918 for (std::vector<JsepIceCandidate*>::const_iterator
919 it = candidates.begin(); it != candidates.end(); ++it) {
920 delete *it;
921 }
922 return false;
923 }
924
925 jdesc->Initialize(desc, session_id, session_version);
926
927 for (std::vector<JsepIceCandidate*>::const_iterator
928 it = candidates.begin(); it != candidates.end(); ++it) {
929 jdesc->AddCandidate(*it);
930 delete *it;
931 }
932 return true;
933}
934
935bool SdpDeserializeCandidate(const std::string& message,
936 JsepIceCandidate* jcandidate,
937 SdpParseError* error) {
938 ASSERT(jcandidate != NULL);
939 Candidate candidate;
940 if (!ParseCandidate(message, &candidate, error, true)) {
941 return false;
942 }
943 jcandidate->SetCandidate(candidate);
944 return true;
945}
946
947bool ParseCandidate(const std::string& message, Candidate* candidate,
948 SdpParseError* error, bool is_raw) {
949 ASSERT(candidate != NULL);
950
951 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000952 std::string first_line = message;
953 size_t pos = 0;
954 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000956 // Makes sure |message| contains only one line.
957 if (message.size() > first_line.size()) {
958 std::string left, right;
Donald Curtis0e07f922015-05-15 09:21:23 -0700959 if (rtc::tokenize_first(message, kNewLine, &left, &right) &&
960 !right.empty()) {
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000961 return ParseFailed(message, 0, "Expect one line only", error);
962 }
963 }
964
965 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
966 // candidate:<candidate> when trickled, but we still support
967 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
968 // from the SDP.
969 if (IsLineType(first_line, kLineTypeAttributes)) {
970 first_line = first_line.substr(kLinePrefixLength);
971 }
972
973 std::string attribute_candidate;
974 std::string candidate_value;
975
976 // |first_line| must be in the form of "candidate:<value>".
Donald Curtis144d0182015-05-15 13:14:24 -0700977 if (!rtc::tokenize_first(first_line, kSdpDelimiterColon, &attribute_candidate,
978 &candidate_value) ||
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000979 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000980 if (is_raw) {
981 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000982 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000983 << ":" << "<candidate-str>";
984 return ParseFailed(first_line, 0, description.str(), error);
985 } else {
986 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
987 kAttributeCandidate, error);
988 }
989 }
990
991 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000992 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
993
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994 // RFC 5245
995 // a=candidate:<foundation> <component-id> <transport> <priority>
996 // <connection-address> <port> typ <candidate-types>
997 // [raddr <connection-address>] [rport <port>]
998 // *(SP extension-att-name SP extension-att-value)
999 const size_t expected_min_fields = 8;
1000 if (fields.size() < expected_min_fields ||
1001 (fields[6] != kAttributeCandidateTyp)) {
1002 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
1003 }
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001004 std::string foundation = fields[0];
1005
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001006 int component_id = 0;
1007 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1008 return false;
1009 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001010 const std::string transport = fields[2];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001011 uint32 priority = 0;
1012 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1013 return false;
1014 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015 const std::string connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001016 int port = 0;
1017 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1018 return false;
1019 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020 SocketAddress address(connection_address, port);
1021
1022 cricket::ProtocolType protocol;
1023 if (!StringToProto(transport.c_str(), &protocol)) {
1024 return ParseFailed(first_line, "Unsupported transport type.", error);
1025 }
1026
1027 std::string candidate_type;
1028 const std::string type = fields[7];
1029 if (type == kCandidateHost) {
1030 candidate_type = cricket::LOCAL_PORT_TYPE;
1031 } else if (type == kCandidateSrflx) {
1032 candidate_type = cricket::STUN_PORT_TYPE;
1033 } else if (type == kCandidateRelay) {
1034 candidate_type = cricket::RELAY_PORT_TYPE;
1035 } else {
1036 return ParseFailed(first_line, "Unsupported candidate type.", error);
1037 }
1038
1039 size_t current_position = expected_min_fields;
1040 SocketAddress related_address;
1041 // The 2 optional fields for related address
1042 // [raddr <connection-address>] [rport <port>]
1043 if (fields.size() >= (current_position + 2) &&
1044 fields[current_position] == kAttributeCandidateRaddr) {
1045 related_address.SetIP(fields[++current_position]);
1046 ++current_position;
1047 }
1048 if (fields.size() >= (current_position + 2) &&
1049 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001050 int port = 0;
1051 if (!GetValueFromString(
1052 first_line, fields[++current_position], &port, error)) {
1053 return false;
1054 }
1055 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056 ++current_position;
1057 }
1058
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001059 // If this is a TCP candidate, it has additional extension as defined in
1060 // RFC 6544.
1061 std::string tcptype;
1062 if (fields.size() >= (current_position + 2) &&
1063 fields[current_position] == kTcpCandidateType) {
1064 tcptype = fields[++current_position];
1065 ++current_position;
1066
1067 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1068 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1069 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1070 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1071 }
1072
1073 if (protocol != cricket::PROTO_TCP) {
1074 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1075 }
1076 }
1077
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078 // Extension
1079 // Empty string as the candidate username and password.
1080 // Will be updated later with the ice-ufrag and ice-pwd.
1081 // TODO: Remove the username/password extension, which is currently
1082 // kept for backwards compatibility.
1083 std::string username;
1084 std::string password;
1085 uint32 generation = 0;
1086 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1087 // RFC 5245
1088 // *(SP extension-att-name SP extension-att-value)
1089 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001090 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1091 return false;
1092 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093 } else if (fields[i] == kAttributeCandidateUsername) {
1094 username = fields[++i];
1095 } else if (fields[i] == kAttributeCandidatePassword) {
1096 password = fields[++i];
1097 } else {
1098 // Skip the unknown extension.
1099 ++i;
1100 }
1101 }
1102
guoweis@webrtc.org61c12472015-01-15 06:53:07 +00001103 *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001104 address, priority, username, password, candidate_type,
1105 generation, foundation);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001106 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001107 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001108 return true;
1109}
1110
1111bool ParseIceOptions(const std::string& line,
1112 std::vector<std::string>* transport_options,
1113 SdpParseError* error) {
1114 std::string ice_options;
1115 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1116 return false;
1117 }
1118 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001119 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001120 for (size_t i = 0; i < fields.size(); ++i) {
1121 transport_options->push_back(fields[i]);
1122 }
1123 return true;
1124}
1125
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001126bool ParseSctpPort(const std::string& line,
1127 int* sctp_port,
1128 SdpParseError* error) {
1129 // draft-ietf-mmusic-sctp-sdp-07
1130 // a=sctp-port
1131 std::vector<std::string> fields;
1132 rtc::split(line.substr(kLinePrefixLength),
1133 kSdpDelimiterSpace, &fields);
1134 const size_t expected_min_fields = 2;
1135 if (fields.size() < expected_min_fields) {
1136 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1137 }
1138 if (!rtc::FromString(fields[1], sctp_port)) {
1139 return ParseFailed(line,
1140 "Invalid sctp port value.",
1141 error);
1142 }
1143 return true;
1144}
1145
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1147 SdpParseError* error) {
1148 // RFC 5285
1149 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1150 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001151 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152 kSdpDelimiterSpace, &fields);
1153 const size_t expected_min_fields = 2;
1154 if (fields.size() < expected_min_fields) {
1155 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1156 }
1157 std::string uri = fields[1];
1158
1159 std::string value_direction;
1160 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1161 return false;
1162 }
1163 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001164 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001165 int value = 0;
1166 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1167 return false;
1168 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001169
1170 *extmap = RtpHeaderExtension(uri, value);
1171 return true;
1172}
1173
1174void BuildMediaDescription(const ContentInfo* content_info,
1175 const TransportInfo* transport_info,
1176 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001177 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001178 std::string* message) {
1179 ASSERT(message != NULL);
1180 if (content_info == NULL || message == NULL) {
1181 return;
1182 }
1183 // TODO: Rethink if we should use sprintfn instead of stringstream.
1184 // According to the style guide, streams should only be used for logging.
1185 // http://google-styleguide.googlecode.com/svn/
1186 // trunk/cppguide.xml?showone=Streams#Streams
1187 std::ostringstream os;
1188 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001189 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001190 content_info->description);
1191 ASSERT(media_desc != NULL);
1192
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001193 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001194
1195 // RFC 4566
1196 // m=<media> <port> <proto> <fmt>
1197 // fmt is a list of payload type numbers that MAY be used in the session.
1198 const char* type = NULL;
1199 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1200 type = kMediaTypeAudio;
1201 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1202 type = kMediaTypeVideo;
1203 else if (media_type == cricket::MEDIA_TYPE_DATA)
1204 type = kMediaTypeData;
1205 else
1206 ASSERT(false);
1207
1208 std::string fmt;
1209 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1210 const VideoContentDescription* video_desc =
1211 static_cast<const VideoContentDescription*>(media_desc);
1212 for (std::vector<cricket::VideoCodec>::const_iterator it =
1213 video_desc->codecs().begin();
1214 it != video_desc->codecs().end(); ++it) {
1215 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001216 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217 }
1218 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1219 const AudioContentDescription* audio_desc =
1220 static_cast<const AudioContentDescription*>(media_desc);
1221 for (std::vector<cricket::AudioCodec>::const_iterator it =
1222 audio_desc->codecs().begin();
1223 it != audio_desc->codecs().end(); ++it) {
1224 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001225 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001226 }
1227 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001228 const DataContentDescription* data_desc =
1229 static_cast<const DataContentDescription*>(media_desc);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001230 if (IsDtlsSctp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001231 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001232
1233 for (std::vector<cricket::DataCodec>::const_iterator it =
1234 data_desc->codecs().begin();
1235 it != data_desc->codecs().end(); ++it) {
1236 if (it->id == cricket::kGoogleSctpDataCodecId &&
1237 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1238 break;
1239 }
1240 }
1241
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001242 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001243 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001244 for (std::vector<cricket::DataCodec>::const_iterator it =
1245 data_desc->codecs().begin();
1246 it != data_desc->codecs().end(); ++it) {
1247 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001248 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001249 }
1250 }
1251 }
1252 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1253 // to 0.
1254 if (fmt.empty()) {
1255 fmt = " 0";
1256 }
1257
1258 // The port number in the m line will be updated later when associate with
1259 // the candidates.
1260 // RFC 3264
1261 // To reject an offered stream, the port number in the corresponding stream in
1262 // the answer MUST be set to zero.
1263 const std::string port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001264 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001265
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001266 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001267 transport_info->description.identity_fingerprint.get() : NULL;
1268
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001269 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001270 InitLine(kLineTypeMedia, type, &os);
1271 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001272 std::string mline = os.str();
1273 UpdateMediaDefaultDestination(candidates, mline, message);
1274
1275 // RFC 4566
1276 // b=AS:<bandwidth>
1277 // We should always use the default bandwidth for RTP-based data
1278 // channels. Don't allow SDP to set the bandwidth, because that
1279 // would give JS the opportunity to "break the Internet".
1280 // TODO(pthatcher): But we need to temporarily allow the SDP to control
1281 // this for backwards-compatibility. Once we don't need that any
1282 // more, remove this.
1283 bool support_dc_sdp_bandwidth_temporarily = true;
1284 if (media_desc->bandwidth() >= 1000 &&
1285 (media_type != cricket::MEDIA_TYPE_DATA ||
1286 support_dc_sdp_bandwidth_temporarily)) {
1287 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1288 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1289 AddLine(os.str(), message);
1290 }
1291
1292 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001293 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001294 std::string rtcp_line = GetRtcpLine(candidates);
1295 if (!rtcp_line.empty()) {
1296 AddLine(rtcp_line, message);
1297 }
1298 }
1299
1300 // Build the a=candidate lines.
1301 BuildCandidate(candidates, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302
1303 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1304 if (transport_info) {
1305 // RFC 5245
1306 // ice-pwd-att = "ice-pwd" ":" password
1307 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1308 // ice-ufrag
1309 InitAttrLine(kAttributeIceUfrag, &os);
1310 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1311 AddLine(os.str(), message);
1312 // ice-pwd
1313 InitAttrLine(kAttributeIcePwd, &os);
1314 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1315 AddLine(os.str(), message);
1316
1317 // draft-petithuguenin-mmusic-ice-attributes-level-03
1318 BuildIceOptions(transport_info->description.transport_options, message);
1319
1320 // RFC 4572
1321 // fingerprint-attribute =
1322 // "fingerprint" ":" hash-func SP fingerprint
1323 if (fp) {
1324 // Insert the fingerprint attribute.
1325 InitAttrLine(kAttributeFingerprint, &os);
1326 os << kSdpDelimiterColon
1327 << fp->algorithm << kSdpDelimiterSpace
1328 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001330
1331 // Inserting setup attribute.
1332 if (transport_info->description.connection_role !=
1333 cricket::CONNECTIONROLE_NONE) {
1334 // Making sure we are not using "passive" mode.
1335 cricket::ConnectionRole role =
1336 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001337 std::string dtls_role_str;
1338 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001339 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001340 os << kSdpDelimiterColon << dtls_role_str;
1341 AddLine(os.str(), message);
1342 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343 }
1344 }
1345
1346 // RFC 3388
1347 // mid-attribute = "a=mid:" identification-tag
1348 // identification-tag = token
1349 // Use the content name as the mid identification-tag.
1350 InitAttrLine(kAttributeMid, &os);
1351 os << kSdpDelimiterColon << content_info->name;
1352 AddLine(os.str(), message);
1353
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001354 if (IsDtlsSctp(media_desc->protocol())) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001355 BuildSctpContentAttributes(message, sctp_port);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001356 } else if (IsRtp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357 BuildRtpContentAttributes(media_desc, media_type, message);
1358 }
1359}
1360
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001361void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001362 // draft-ietf-mmusic-sctp-sdp-04
1363 // a=sctpmap:sctpmap-number protocol [streams]
1364 std::ostringstream os;
1365 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001366 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001367 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1368 << (cricket::kMaxSctpSid + 1);
1369 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370}
1371
1372void BuildRtpContentAttributes(
1373 const MediaContentDescription* media_desc,
1374 const MediaType media_type,
1375 std::string* message) {
1376 std::ostringstream os;
1377 // RFC 5285
1378 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1379 // The definitions MUST be either all session level or all media level. This
1380 // implementation uses all media level.
1381 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1382 InitAttrLine(kAttributeExtmap, &os);
1383 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1384 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1385 AddLine(os.str(), message);
1386 }
1387
1388 // RFC 3264
1389 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
1390
1391 cricket::MediaContentDirection direction = media_desc->direction();
1392 if (media_desc->streams().empty() && direction == cricket::MD_SENDRECV) {
1393 direction = cricket::MD_RECVONLY;
1394 }
1395
1396 switch (direction) {
1397 case cricket::MD_INACTIVE:
1398 InitAttrLine(kAttributeInactive, &os);
1399 break;
1400 case cricket::MD_SENDONLY:
1401 InitAttrLine(kAttributeSendOnly, &os);
1402 break;
1403 case cricket::MD_RECVONLY:
1404 InitAttrLine(kAttributeRecvOnly, &os);
1405 break;
1406 case cricket::MD_SENDRECV:
1407 default:
1408 InitAttrLine(kAttributeSendRecv, &os);
1409 break;
1410 }
1411 AddLine(os.str(), message);
1412
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 // RFC 5761
1414 // a=rtcp-mux
1415 if (media_desc->rtcp_mux()) {
1416 InitAttrLine(kAttributeRtcpMux, &os);
1417 AddLine(os.str(), message);
1418 }
1419
1420 // RFC 4568
1421 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1422 for (std::vector<CryptoParams>::const_iterator it =
1423 media_desc->cryptos().begin();
1424 it != media_desc->cryptos().end(); ++it) {
1425 InitAttrLine(kAttributeCrypto, &os);
1426 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1427 << it->key_params;
1428 if (!it->session_params.empty()) {
1429 os << " " << it->session_params;
1430 }
1431 AddLine(os.str(), message);
1432 }
1433
1434 // RFC 4566
1435 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1436 // [/<encodingparameters>]
1437 BuildRtpMap(media_desc, media_type, message);
1438
1439 // Specify latency for buffered mode.
1440 // a=x-google-buffer-latency:<value>
1441 if (media_desc->buffered_mode_latency() != cricket::kBufferedModeDisabled) {
1442 std::ostringstream os;
1443 InitAttrLine(kAttributeXGoogleBufferLatency, &os);
1444 os << kSdpDelimiterColon << media_desc->buffered_mode_latency();
1445 AddLine(os.str(), message);
1446 }
1447
1448 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1449 track != media_desc->streams().end(); ++track) {
1450 // Require that the track belongs to a media stream,
1451 // ie the sync_label is set. This extra check is necessary since the
1452 // MediaContentDescription always contains a streamparam with an ssrc even
1453 // if no track or media stream have been created.
1454 if (track->sync_label.empty()) continue;
1455
1456 // Build the ssrc-group lines.
1457 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1458 // RFC 5576
1459 // a=ssrc-group:<semantics> <ssrc-id> ...
1460 if (track->ssrc_groups[i].ssrcs.empty()) {
1461 continue;
1462 }
1463 std::ostringstream os;
1464 InitAttrLine(kAttributeSsrcGroup, &os);
1465 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
1466 std::vector<uint32>::const_iterator ssrc =
1467 track->ssrc_groups[i].ssrcs.begin();
1468 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001469 os << kSdpDelimiterSpace << rtc::ToString<uint32>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001470 }
1471 AddLine(os.str(), message);
1472 }
1473 // Build the ssrc lines for each ssrc.
1474 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
1475 uint32 ssrc = track->ssrcs[i];
1476 // RFC 5576
1477 // a=ssrc:<ssrc-id> cname:<value>
1478 AddSsrcLine(ssrc, kSsrcAttributeCname,
1479 track->cname, message);
1480
1481 // draft-alvestrand-mmusic-msid-00
1482 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1483 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1484 // is corresponding to the "name" attribute of StreamParams.
1485 std::string appdata = track->id;
1486 std::ostringstream os;
1487 InitAttrLine(kAttributeSsrc, &os);
1488 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1489 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1490 << kSdpDelimiterSpace << appdata;
1491 AddLine(os.str(), message);
1492
1493 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1494 // draft-alvestrand-rtcweb-mid-01
1495 // a=ssrc:<ssrc-id> mslabel:<value>
1496 // The label isn't yet defined.
1497 // a=ssrc:<ssrc-id> label:<value>
1498 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1499 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1500 }
1501 }
1502}
1503
1504void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1505 // fmtp header: a=fmtp:|payload_type| <parameters>
1506 // Add a=fmtp
1507 InitAttrLine(kAttributeFmtp, os);
1508 // Add :|payload_type|
1509 *os << kSdpDelimiterColon << payload_type;
1510}
1511
1512void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1513 // rtcp-fb header: a=rtcp-fb:|payload_type|
1514 // <parameters>/<ccm <ccm_parameters>>
1515 // Add a=rtcp-fb
1516 InitAttrLine(kAttributeRtcpFb, os);
1517 // Add :
1518 *os << kSdpDelimiterColon;
1519 if (payload_type == kWildcardPayloadType) {
1520 *os << "*";
1521 } else {
1522 *os << payload_type;
1523 }
1524}
1525
1526void WriteFmtpParameter(const std::string& parameter_name,
1527 const std::string& parameter_value,
1528 std::ostringstream* os) {
1529 // fmtp parameters: |parameter_name|=|parameter_value|
1530 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1531}
1532
1533void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1534 std::ostringstream* os) {
1535 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1536 fmtp != parameters.end(); ++fmtp) {
1537 // Each new parameter, except the first one starts with ";" and " ".
1538 if (fmtp != parameters.begin()) {
1539 *os << kSdpDelimiterSemicolon;
1540 }
1541 *os << kSdpDelimiterSpace;
1542 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1543 }
1544}
1545
1546bool IsFmtpParam(const std::string& name) {
1547 const char* kFmtpParams[] = {
1548 kCodecParamMinPTime, kCodecParamSPropStereo,
Minyue Li7100dcd2015-03-27 05:05:59 +01001549 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamUseDtx,
1550 kCodecParamStartBitrate, kCodecParamMaxBitrate, kCodecParamMinBitrate,
1551 kCodecParamMaxQuantization, kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001552 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1553 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001554 };
1555 for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
1556 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1557 return true;
1558 }
1559 }
1560 return false;
1561}
1562
1563// Retreives fmtp parameters from |params|, which may contain other parameters
1564// as well, and puts them in |fmtp_parameters|.
1565void GetFmtpParams(const cricket::CodecParameterMap& params,
1566 cricket::CodecParameterMap* fmtp_parameters) {
1567 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1568 iter != params.end(); ++iter) {
1569 if (IsFmtpParam(iter->first)) {
1570 (*fmtp_parameters)[iter->first] = iter->second;
1571 }
1572 }
1573}
1574
1575template <class T>
1576void AddFmtpLine(const T& codec, std::string* message) {
1577 cricket::CodecParameterMap fmtp_parameters;
1578 GetFmtpParams(codec.params, &fmtp_parameters);
1579 if (fmtp_parameters.empty()) {
1580 // No need to add an fmtp if it will have no (optional) parameters.
1581 return;
1582 }
1583 std::ostringstream os;
1584 WriteFmtpHeader(codec.id, &os);
1585 WriteFmtpParameters(fmtp_parameters, &os);
1586 AddLine(os.str(), message);
1587 return;
1588}
1589
1590template <class T>
1591void AddRtcpFbLines(const T& codec, std::string* message) {
1592 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1593 codec.feedback_params.params().begin();
1594 iter != codec.feedback_params.params().end(); ++iter) {
1595 std::ostringstream os;
1596 WriteRtcpFbHeader(codec.id, &os);
1597 os << " " << iter->id();
1598 if (!iter->param().empty()) {
1599 os << " " << iter->param();
1600 }
1601 AddLine(os.str(), message);
1602 }
1603}
1604
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001605bool AddSctpDataCodec(DataContentDescription* media_desc,
1606 int sctp_port) {
1607 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1608 return ParseFailed("",
1609 "Can't have multiple sctp port attributes.",
1610 NULL);
1611 }
1612 // Add the SCTP Port number as a pseudo-codec "port" parameter
1613 cricket::DataCodec codec_port(
1614 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1615 0);
1616 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1617 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1618 << sctp_port;
1619 media_desc->AddCodec(codec_port);
1620 return true;
1621}
1622
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001623bool GetMinValue(const std::vector<int>& values, int* value) {
1624 if (values.empty()) {
1625 return false;
1626 }
1627 std::vector<int>::const_iterator found =
1628 std::min_element(values.begin(), values.end());
1629 *value = *found;
1630 return true;
1631}
1632
1633bool GetParameter(const std::string& name,
1634 const cricket::CodecParameterMap& params, int* value) {
1635 std::map<std::string, std::string>::const_iterator found =
1636 params.find(name);
1637 if (found == params.end()) {
1638 return false;
1639 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001640 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001641 return false;
1642 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001643 return true;
1644}
1645
1646void BuildRtpMap(const MediaContentDescription* media_desc,
1647 const MediaType media_type,
1648 std::string* message) {
1649 ASSERT(message != NULL);
1650 ASSERT(media_desc != NULL);
1651 std::ostringstream os;
1652 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1653 const VideoContentDescription* video_desc =
1654 static_cast<const VideoContentDescription*>(media_desc);
1655 for (std::vector<cricket::VideoCodec>::const_iterator it =
1656 video_desc->codecs().begin();
1657 it != video_desc->codecs().end(); ++it) {
1658 // RFC 4566
1659 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1660 // [/<encodingparameters>]
1661 if (it->id != kWildcardPayloadType) {
1662 InitAttrLine(kAttributeRtpmap, &os);
1663 os << kSdpDelimiterColon << it->id << " " << it->name
1664 << "/" << kDefaultVideoClockrate;
1665 AddLine(os.str(), message);
1666 }
1667 AddRtcpFbLines(*it, message);
1668 AddFmtpLine(*it, message);
1669 }
1670 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1671 const AudioContentDescription* audio_desc =
1672 static_cast<const AudioContentDescription*>(media_desc);
1673 std::vector<int> ptimes;
1674 std::vector<int> maxptimes;
1675 int max_minptime = 0;
1676 for (std::vector<cricket::AudioCodec>::const_iterator it =
1677 audio_desc->codecs().begin();
1678 it != audio_desc->codecs().end(); ++it) {
1679 ASSERT(!it->name.empty());
1680 // RFC 4566
1681 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1682 // [/<encodingparameters>]
1683 InitAttrLine(kAttributeRtpmap, &os);
1684 os << kSdpDelimiterColon << it->id << " ";
1685 os << it->name << "/" << it->clockrate;
1686 if (it->channels != 1) {
1687 os << "/" << it->channels;
1688 }
1689 AddLine(os.str(), message);
1690 AddRtcpFbLines(*it, message);
1691 AddFmtpLine(*it, message);
1692 int minptime = 0;
1693 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1694 max_minptime = std::max(minptime, max_minptime);
1695 }
1696 int ptime;
1697 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1698 ptimes.push_back(ptime);
1699 }
1700 int maxptime;
1701 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1702 maxptimes.push_back(maxptime);
1703 }
1704 }
1705 // Populate the maxptime attribute with the smallest maxptime of all codecs
1706 // under the same m-line.
1707 int min_maxptime = INT_MAX;
1708 if (GetMinValue(maxptimes, &min_maxptime)) {
1709 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1710 }
1711 ASSERT(min_maxptime > max_minptime);
1712 // Populate the ptime attribute with the smallest ptime or the largest
1713 // minptime, whichever is the largest, for all codecs under the same m-line.
1714 int ptime = INT_MAX;
1715 if (GetMinValue(ptimes, &ptime)) {
1716 ptime = std::min(ptime, min_maxptime);
1717 ptime = std::max(ptime, max_minptime);
1718 AddAttributeLine(kCodecParamPTime, ptime, message);
1719 }
1720 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1721 const DataContentDescription* data_desc =
1722 static_cast<const DataContentDescription*>(media_desc);
1723 for (std::vector<cricket::DataCodec>::const_iterator it =
1724 data_desc->codecs().begin();
1725 it != data_desc->codecs().end(); ++it) {
1726 // RFC 4566
1727 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1728 // [/<encodingparameters>]
1729 InitAttrLine(kAttributeRtpmap, &os);
1730 os << kSdpDelimiterColon << it->id << " "
1731 << it->name << "/" << it->clockrate;
1732 AddLine(os.str(), message);
1733 }
1734 }
1735}
1736
1737void BuildCandidate(const std::vector<Candidate>& candidates,
1738 std::string* message) {
1739 std::ostringstream os;
1740
1741 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1742 it != candidates.end(); ++it) {
1743 // RFC 5245
1744 // a=candidate:<foundation> <component-id> <transport> <priority>
1745 // <connection-address> <port> typ <candidate-types>
1746 // [raddr <connection-address>] [rport <port>]
1747 // *(SP extension-att-name SP extension-att-value)
1748 std::string type;
1749 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1750 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1751 type = kCandidateHost;
1752 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1753 type = kCandidateSrflx;
1754 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1755 type = kCandidateRelay;
1756 } else {
1757 ASSERT(false);
Peter Thatcher019087f2015-04-28 09:06:26 -07001758 // Never write out candidates if we don't know the type.
1759 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001760 }
1761
1762 InitAttrLine(kAttributeCandidate, &os);
1763 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001764 << it->foundation() << " "
1765 << it->component() << " "
1766 << it->protocol() << " "
1767 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001768 << it->address().ipaddr().ToString() << " "
1769 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001770 << kAttributeCandidateTyp << " "
1771 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001772
1773 // Related address
1774 if (!it->related_address().IsNil()) {
1775 os << kAttributeCandidateRaddr << " "
1776 << it->related_address().ipaddr().ToString() << " "
1777 << kAttributeCandidateRport << " "
1778 << it->related_address().PortAsString() << " ";
1779 }
1780
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001781 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001782 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001783 }
1784
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001785 // Extensions
1786 os << kAttributeCandidateGeneration << " " << it->generation();
1787
1788 AddLine(os.str(), message);
1789 }
1790}
1791
1792void BuildIceOptions(const std::vector<std::string>& transport_options,
1793 std::string* message) {
1794 if (!transport_options.empty()) {
1795 std::ostringstream os;
1796 InitAttrLine(kAttributeIceOption, &os);
1797 os << kSdpDelimiterColon << transport_options[0];
1798 for (size_t i = 1; i < transport_options.size(); ++i) {
1799 os << kSdpDelimiterSpace << transport_options[i];
1800 }
1801 AddLine(os.str(), message);
1802 }
1803}
1804
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001805bool IsRtp(const std::string& protocol) {
1806 return protocol.empty() ||
1807 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1808}
1809
1810bool IsDtlsSctp(const std::string& protocol) {
1811 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001812 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001813}
1814
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001815bool ParseSessionDescription(const std::string& message, size_t* pos,
1816 std::string* session_id,
1817 std::string* session_version,
1818 bool* supports_msid,
1819 TransportDescription* session_td,
1820 RtpHeaderExtensions* session_extmaps,
1821 cricket::SessionDescription* desc,
1822 SdpParseError* error) {
1823 std::string line;
1824
1825 // RFC 4566
1826 // v= (protocol version)
1827 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1828 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1829 std::string(), error);
1830 }
1831 // RFC 4566
1832 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1833 // <unicast-address>
1834 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1835 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1836 std::string(), error);
1837 }
1838 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001839 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001840 kSdpDelimiterSpace, &fields);
1841 const size_t expected_fields = 6;
1842 if (fields.size() != expected_fields) {
1843 return ParseFailedExpectFieldNum(line, expected_fields, error);
1844 }
1845 *session_id = fields[1];
1846 *session_version = fields[2];
1847
1848 // RFC 4566
1849 // s= (session name)
1850 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1851 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1852 std::string(), error);
1853 }
1854
1855 // Optional lines
1856 // Those are the optional lines, so shouldn't return false if not present.
1857 // RFC 4566
1858 // i=* (session information)
1859 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1860
1861 // RFC 4566
1862 // u=* (URI of description)
1863 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1864
1865 // RFC 4566
1866 // e=* (email address)
1867 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1868
1869 // RFC 4566
1870 // p=* (phone number)
1871 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1872
1873 // RFC 4566
1874 // c=* (connection information -- not required if included in
1875 // all media)
1876 GetLineWithType(message, pos, &line, kLineTypeConnection);
1877
1878 // RFC 4566
1879 // b=* (zero or more bandwidth information lines)
1880 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1881 // By pass zero or more b lines.
1882 }
1883
1884 // RFC 4566
1885 // One or more time descriptions ("t=" and "r=" lines; see below)
1886 // t= (time the session is active)
1887 // r=* (zero or more repeat times)
1888 // Ensure there's at least one time description
1889 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1890 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1891 error);
1892 }
1893
1894 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1895 // By pass zero or more r lines.
1896 }
1897
1898 // Go through the rest of the time descriptions
1899 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1900 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1901 // By pass zero or more r lines.
1902 }
1903 }
1904
1905 // RFC 4566
1906 // z=* (time zone adjustments)
1907 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1908
1909 // RFC 4566
1910 // k=* (encryption key)
1911 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1912
1913 // RFC 4566
1914 // a=* (zero or more session attribute lines)
1915 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1916 if (HasAttribute(line, kAttributeGroup)) {
1917 if (!ParseGroupAttribute(line, desc, error)) {
1918 return false;
1919 }
1920 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1921 if (!GetValue(line, kAttributeIceUfrag,
1922 &(session_td->ice_ufrag), error)) {
1923 return false;
1924 }
1925 } else if (HasAttribute(line, kAttributeIcePwd)) {
1926 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1927 return false;
1928 }
1929 } else if (HasAttribute(line, kAttributeIceLite)) {
1930 session_td->ice_mode = cricket::ICEMODE_LITE;
1931 } else if (HasAttribute(line, kAttributeIceOption)) {
1932 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1933 return false;
1934 }
1935 } else if (HasAttribute(line, kAttributeFingerprint)) {
1936 if (session_td->identity_fingerprint.get()) {
1937 return ParseFailed(
1938 line,
1939 "Can't have multiple fingerprint attributes at the same level.",
1940 error);
1941 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001942 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001943 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1944 return false;
1945 }
1946 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001947 } else if (HasAttribute(line, kAttributeSetup)) {
1948 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1949 return false;
1950 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001951 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1952 std::string semantics;
1953 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1954 return false;
1955 }
1956 *supports_msid = CaseInsensitiveFind(semantics, kMediaStreamSemantic);
1957 } else if (HasAttribute(line, kAttributeExtmap)) {
1958 RtpHeaderExtension extmap;
1959 if (!ParseExtmap(line, &extmap, error)) {
1960 return false;
1961 }
1962 session_extmaps->push_back(extmap);
1963 }
1964 }
1965
1966 return true;
1967}
1968
1969bool ParseGroupAttribute(const std::string& line,
1970 cricket::SessionDescription* desc,
1971 SdpParseError* error) {
1972 ASSERT(desc != NULL);
1973
1974 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1975 // a=group:BUNDLE video voice
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 std::string semantics;
1980 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1981 return false;
1982 }
1983 cricket::ContentGroup group(semantics);
1984 for (size_t i = 1; i < fields.size(); ++i) {
1985 group.AddContentName(fields[i]);
1986 }
1987 desc->AddGroup(group);
1988 return true;
1989}
1990
1991static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001992 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993 SdpParseError* error) {
1994 if (!IsLineType(line, kLineTypeAttributes) ||
1995 !HasAttribute(line, kAttributeFingerprint)) {
1996 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1997 kAttributeFingerprint, error);
1998 }
1999
2000 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002001 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002002 kSdpDelimiterSpace, &fields);
2003 const size_t expected_fields = 2;
2004 if (fields.size() != expected_fields) {
2005 return ParseFailedExpectFieldNum(line, expected_fields, error);
2006 }
2007
2008 // The first field here is "fingerprint:<hash>.
2009 std::string algorithm;
2010 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2011 return false;
2012 }
2013
2014 // Downcase the algorithm. Note that we don't need to downcase the
2015 // fingerprint because hex_decode can handle upper-case.
2016 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2017 ::tolower);
2018
2019 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002020 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002021 algorithm, fields[1]);
2022 if (!*fingerprint) {
2023 return ParseFailed(line,
2024 "Failed to create fingerprint from the digest.",
2025 error);
2026 }
2027
2028 return true;
2029}
2030
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002031static bool ParseDtlsSetup(const std::string& line,
2032 cricket::ConnectionRole* role,
2033 SdpParseError* error) {
2034 // setup-attr = "a=setup:" role
2035 // role = "active" / "passive" / "actpass" / "holdconn"
2036 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002037 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002038 const size_t expected_fields = 2;
2039 if (fields.size() != expected_fields) {
2040 return ParseFailedExpectFieldNum(line, expected_fields, error);
2041 }
2042 std::string role_str = fields[1];
2043 if (!cricket::StringToConnectionRole(role_str, role)) {
2044 return ParseFailed(line, "Invalid attribute value.", error);
2045 }
2046 return true;
2047}
2048
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002049// RFC 3551
2050// PT encoding media type clock rate channels
2051// name (Hz)
2052// 0 PCMU A 8,000 1
2053// 1 reserved A
2054// 2 reserved A
2055// 3 GSM A 8,000 1
2056// 4 G723 A 8,000 1
2057// 5 DVI4 A 8,000 1
2058// 6 DVI4 A 16,000 1
2059// 7 LPC A 8,000 1
2060// 8 PCMA A 8,000 1
2061// 9 G722 A 8,000 1
2062// 10 L16 A 44,100 2
2063// 11 L16 A 44,100 1
2064// 12 QCELP A 8,000 1
2065// 13 CN A 8,000 1
2066// 14 MPA A 90,000 (see text)
2067// 15 G728 A 8,000 1
2068// 16 DVI4 A 11,025 1
2069// 17 DVI4 A 22,050 1
2070// 18 G729 A 8,000 1
2071struct StaticPayloadAudioCodec {
2072 const char* name;
2073 int clockrate;
2074 int channels;
2075};
2076static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2077 { "PCMU", 8000, 1 },
2078 { "reserved", 0, 0 },
2079 { "reserved", 0, 0 },
2080 { "GSM", 8000, 1 },
2081 { "G723", 8000, 1 },
2082 { "DVI4", 8000, 1 },
2083 { "DVI4", 16000, 1 },
2084 { "LPC", 8000, 1 },
2085 { "PCMA", 8000, 1 },
2086 { "G722", 8000, 1 },
2087 { "L16", 44100, 2 },
2088 { "L16", 44100, 1 },
2089 { "QCELP", 8000, 1 },
2090 { "CN", 8000, 1 },
2091 { "MPA", 90000, 1 },
2092 { "G728", 8000, 1 },
2093 { "DVI4", 11025, 1 },
2094 { "DVI4", 22050, 1 },
2095 { "G729", 8000, 1 },
2096};
2097
2098void MaybeCreateStaticPayloadAudioCodecs(
2099 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2100 if (!media_desc) {
2101 return;
2102 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002103 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002104 std::vector<int>::const_iterator it = fmts.begin();
2105 bool add_new_codec = false;
2106 for (; it != fmts.end(); ++it) {
2107 int payload_type = *it;
2108 if (!media_desc->HasCodec(payload_type) &&
2109 payload_type >= 0 &&
2110 payload_type < ARRAY_SIZE(kStaticPayloadAudioCodecs)) {
2111 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2112 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2113 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2114 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2115 clock_rate, 0, channels,
2116 preference));
2117 add_new_codec = true;
2118 }
2119 --preference;
2120 }
2121 if (add_new_codec) {
2122 media_desc->SortCodecs();
2123 }
2124}
2125
2126template <class C>
2127static C* ParseContentDescription(const std::string& message,
2128 const MediaType media_type,
2129 int mline_index,
2130 const std::string& protocol,
2131 const std::vector<int>& codec_preference,
2132 size_t* pos,
2133 std::string* content_name,
2134 TransportDescription* transport,
2135 std::vector<JsepIceCandidate*>* candidates,
2136 webrtc::SdpParseError* error) {
2137 C* media_desc = new C();
2138 switch (media_type) {
2139 case cricket::MEDIA_TYPE_AUDIO:
2140 *content_name = cricket::CN_AUDIO;
2141 break;
2142 case cricket::MEDIA_TYPE_VIDEO:
2143 *content_name = cricket::CN_VIDEO;
2144 break;
2145 case cricket::MEDIA_TYPE_DATA:
2146 *content_name = cricket::CN_DATA;
2147 break;
2148 default:
2149 ASSERT(false);
2150 break;
2151 }
2152 if (!ParseContent(message, media_type, mline_index, protocol,
2153 codec_preference, pos, content_name,
2154 media_desc, transport, candidates, error)) {
2155 delete media_desc;
2156 return NULL;
2157 }
2158 // Sort the codecs according to the m-line fmt list.
2159 media_desc->SortCodecs();
2160 return media_desc;
2161}
2162
2163bool ParseMediaDescription(const std::string& message,
2164 const TransportDescription& session_td,
2165 const RtpHeaderExtensions& session_extmaps,
2166 bool supports_msid,
2167 size_t* pos,
2168 cricket::SessionDescription* desc,
2169 std::vector<JsepIceCandidate*>* candidates,
2170 SdpParseError* error) {
2171 ASSERT(desc != NULL);
2172 std::string line;
2173 int mline_index = -1;
2174
2175 // Zero or more media descriptions
2176 // RFC 4566
2177 // m=<media> <port> <proto> <fmt>
2178 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2179 ++mline_index;
2180
2181 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002182 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002183 kSdpDelimiterSpace, &fields);
2184 const size_t expected_min_fields = 4;
2185 if (fields.size() < expected_min_fields) {
2186 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2187 }
2188 bool rejected = false;
2189 // RFC 3264
2190 // To reject an offered stream, the port number in the corresponding stream
2191 // in the answer MUST be set to zero.
2192 if (fields[1] == kMediaPortRejected) {
2193 rejected = true;
2194 }
2195
2196 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002197
2198 // <fmt>
2199 std::vector<int> codec_preference;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002200 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002201 for (size_t j = 3 ; j < fields.size(); ++j) {
2202 // TODO(wu): Remove when below bug is fixed.
2203 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
2204 if (fields[j] == "" && j == fields.size() - 1) {
2205 continue;
2206 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002207
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002208 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002209 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002210 return false;
2211 }
2212 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002213 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002214 }
2215
2216 // Make a temporary TransportDescription based on |session_td|.
2217 // Some of this gets overwritten by ParseContent.
2218 TransportDescription transport(NS_JINGLE_ICE_UDP,
2219 session_td.transport_options,
2220 session_td.ice_ufrag,
2221 session_td.ice_pwd,
2222 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002223 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002224 session_td.identity_fingerprint.get(),
2225 Candidates());
2226
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002227 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002228 std::string content_name;
2229 if (HasAttribute(line, kMediaTypeVideo)) {
2230 content.reset(ParseContentDescription<VideoContentDescription>(
2231 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2232 codec_preference, pos, &content_name,
2233 &transport, candidates, error));
2234 } else if (HasAttribute(line, kMediaTypeAudio)) {
2235 content.reset(ParseContentDescription<AudioContentDescription>(
2236 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2237 codec_preference, pos, &content_name,
2238 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002239 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002240 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002241 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002242 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2243 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002244 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002245 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002246
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002247 int p;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002248 if (data_desc && IsDtlsSctp(protocol) && rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002249 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002250 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002251 }
2252
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002253 // We should always use the default bandwidth for RTP-based data
2254 // channels. Don't allow SDP to set the bandwidth, because that
2255 // would give JS the opportunity to "break the Internet".
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002256 // TODO(pthatcher): But we need to temporarily allow the SDP to control
2257 // this for backwards-compatibility. Once we don't need that any
2258 // more, remove this.
2259 bool support_dc_sdp_bandwidth_temporarily = true;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00002260 if (content.get() && !support_dc_sdp_bandwidth_temporarily) {
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002261 content->set_bandwidth(cricket::kAutoBandwidth);
2262 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002263 } else {
2264 LOG(LS_WARNING) << "Unsupported media type: " << line;
2265 continue;
2266 }
2267 if (!content.get()) {
2268 // ParseContentDescription returns NULL if failed.
2269 return false;
2270 }
2271
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002272 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002273 // Make sure to set the media direction correctly. If the direction is not
2274 // MD_RECVONLY or Inactive and no streams are parsed,
2275 // a default MediaStream will be created to prepare for receiving media.
2276 if (supports_msid && content->streams().empty() &&
2277 content->direction() == cricket::MD_SENDRECV) {
2278 content->set_direction(cricket::MD_RECVONLY);
2279 }
2280
2281 // Set the extmap.
2282 if (!session_extmaps.empty() &&
2283 !content->rtp_header_extensions().empty()) {
2284 return ParseFailed("",
2285 "The a=extmap MUST be either all session level or "
2286 "all media level.",
2287 error);
2288 }
2289 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2290 content->AddRtpHeaderExtension(session_extmaps[i]);
2291 }
2292 }
2293 content->set_protocol(protocol);
2294 desc->AddContent(content_name,
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002295 IsDtlsSctp(protocol) ? cricket::NS_JINGLE_DRAFT_SCTP :
2296 cricket::NS_JINGLE_RTP,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002297 rejected,
2298 content.release());
2299 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2300 TransportInfo transport_info(content_name, transport);
2301
2302 if (!desc->AddTransportInfo(transport_info)) {
2303 std::ostringstream description;
2304 description << "Failed to AddTransportInfo with content name: "
2305 << content_name;
2306 return ParseFailed("", description.str(), error);
2307 }
2308 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002309
2310 size_t end_of_message = message.size();
2311 if (mline_index == -1 && *pos != end_of_message) {
2312 ParseFailed(message, *pos, "Expects m line.", error);
2313 return false;
2314 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002315 return true;
2316}
2317
2318bool VerifyCodec(const cricket::Codec& codec) {
2319 // Codec has not been populated correctly unless the name has been set. This
2320 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2321 // have a corresponding "rtpmap" line.
2322 cricket::Codec default_codec;
2323 return default_codec.name != codec.name;
2324}
2325
2326bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2327 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2328 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2329 iter != codecs.end(); ++iter) {
2330 if (!VerifyCodec(*iter)) {
2331 return false;
2332 }
2333 }
2334 return true;
2335}
2336
2337bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2338 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2339 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2340 iter != codecs.end(); ++iter) {
2341 if (!VerifyCodec(*iter)) {
2342 return false;
2343 }
2344 }
2345 return true;
2346}
2347
2348void AddParameters(const cricket::CodecParameterMap& parameters,
2349 cricket::Codec* codec) {
2350 for (cricket::CodecParameterMap::const_iterator iter =
2351 parameters.begin(); iter != parameters.end(); ++iter) {
2352 codec->SetParam(iter->first, iter->second);
2353 }
2354}
2355
2356void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2357 cricket::Codec* codec) {
2358 codec->AddFeedbackParam(feedback_param);
2359}
2360
2361void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2362 cricket::Codec* codec) {
2363 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2364 feedback_params.params().begin();
2365 iter != feedback_params.params().end(); ++iter) {
2366 codec->AddFeedbackParam(*iter);
2367 }
2368}
2369
2370// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002371// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002372// with that payload type.
2373template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002374T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2375 T ret_val;
2376 if (!FindCodecById(codecs, payload_type, &ret_val)) {
2377 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002379 return ret_val;
2380}
2381
2382// Updates or creates a new codec entry in the audio description.
2383template <class T, class U>
2384void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2385 T* desc = static_cast<T*>(content_desc);
2386 std::vector<U> codecs = desc->codecs();
2387 bool found = false;
2388
2389 typename std::vector<U>::iterator iter;
2390 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2391 if (iter->id == codec.id) {
2392 *iter = codec;
2393 found = true;
2394 break;
2395 }
2396 }
2397 if (!found) {
2398 desc->AddCodec(codec);
2399 return;
2400 }
2401 desc->set_codecs(codecs);
2402}
2403
2404// Adds or updates existing codec corresponding to |payload_type| according
2405// to |parameters|.
2406template <class T, class U>
2407void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2408 const cricket::CodecParameterMap& parameters) {
2409 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002410 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2411 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002412 AddParameters(parameters, &new_codec);
2413 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2414}
2415
2416// Adds or updates existing codec corresponding to |payload_type| according
2417// to |feedback_param|.
2418template <class T, class U>
2419void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2420 const cricket::FeedbackParam& feedback_param) {
2421 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002422 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2423 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002424 AddFeedbackParameter(feedback_param, &new_codec);
2425 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2426}
2427
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002428template <class T>
2429bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2430 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002431 if (iter->id == kWildcardPayloadType) {
2432 *wildcard_codec = *iter;
2433 codecs->erase(iter);
2434 return true;
2435 }
2436 }
2437 return false;
2438}
2439
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002440template<class T>
2441void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2442 auto codecs = desc->codecs();
2443 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002444 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2445 return;
2446 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002447 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002448 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2449 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002450 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002451}
2452
2453void AddAudioAttribute(const std::string& name, const std::string& value,
2454 AudioContentDescription* audio_desc) {
2455 if (value.empty()) {
2456 return;
2457 }
2458 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2459 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2460 iter != codecs.end(); ++iter) {
2461 iter->params[name] = value;
2462 }
2463 audio_desc->set_codecs(codecs);
2464}
2465
2466bool ParseContent(const std::string& message,
2467 const MediaType media_type,
2468 int mline_index,
2469 const std::string& protocol,
2470 const std::vector<int>& codec_preference,
2471 size_t* pos,
2472 std::string* content_name,
2473 MediaContentDescription* media_desc,
2474 TransportDescription* transport,
2475 std::vector<JsepIceCandidate*>* candidates,
2476 SdpParseError* error) {
2477 ASSERT(media_desc != NULL);
2478 ASSERT(content_name != NULL);
2479 ASSERT(transport != NULL);
2480
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002481 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2482 MaybeCreateStaticPayloadAudioCodecs(
2483 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2484 }
2485
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002486 // The media level "ice-ufrag" and "ice-pwd".
2487 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2488 Candidates candidates_orig;
2489 std::string line;
2490 std::string mline_id;
2491 // Tracks created out of the ssrc attributes.
2492 StreamParamsVec tracks;
2493 SsrcInfoVec ssrc_infos;
2494 SsrcGroupVec ssrc_groups;
2495 std::string maxptime_as_string;
2496 std::string ptime_as_string;
2497
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002498 // Loop until the next m line
2499 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2500 if (!GetLine(message, pos, &line)) {
2501 if (*pos >= message.size()) {
2502 break; // Done parsing
2503 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002504 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002505 }
2506 }
2507
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002508 // RFC 4566
2509 // b=* (zero or more bandwidth information lines)
2510 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2511 std::string bandwidth;
2512 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2513 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2514 return false;
2515 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002516 int b = 0;
2517 if (!GetValueFromString(line, bandwidth, &b, error)) {
2518 return false;
2519 }
2520 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002521 }
2522 }
2523 continue;
2524 }
2525
2526 if (!IsLineType(line, kLineTypeAttributes)) {
2527 // TODO: Handle other lines if needed.
2528 LOG(LS_INFO) << "Ignored line: " << line;
2529 continue;
2530 }
2531
2532 // Handle attributes common to SCTP and RTP.
2533 if (HasAttribute(line, kAttributeMid)) {
2534 // RFC 3388
2535 // mid-attribute = "a=mid:" identification-tag
2536 // identification-tag = token
2537 // Use the mid identification-tag as the content name.
2538 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2539 return false;
2540 }
2541 *content_name = mline_id;
2542 } else if (HasAttribute(line, kAttributeCandidate)) {
2543 Candidate candidate;
2544 if (!ParseCandidate(line, &candidate, error, false)) {
2545 return false;
2546 }
2547 candidates_orig.push_back(candidate);
2548 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2549 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2550 return false;
2551 }
2552 } else if (HasAttribute(line, kAttributeIcePwd)) {
2553 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2554 return false;
2555 }
2556 } else if (HasAttribute(line, kAttributeIceOption)) {
2557 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2558 return false;
2559 }
2560 } else if (HasAttribute(line, kAttributeFmtp)) {
2561 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2562 return false;
2563 }
2564 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002565 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002566
2567 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2568 return false;
2569 }
2570 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002571 } else if (HasAttribute(line, kAttributeSetup)) {
2572 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2573 return false;
2574 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002575 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002576 int sctp_port;
2577 if (!ParseSctpPort(line, &sctp_port, error)) {
2578 return false;
2579 }
2580 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2581 sctp_port)) {
2582 return false;
2583 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002584 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002585 //
2586 // RTP specific attrubtes
2587 //
2588 if (HasAttribute(line, kAttributeRtcpMux)) {
2589 media_desc->set_rtcp_mux(true);
2590 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2591 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2592 return false;
2593 }
2594 } else if (HasAttribute(line, kAttributeSsrc)) {
2595 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2596 return false;
2597 }
2598 } else if (HasAttribute(line, kAttributeCrypto)) {
2599 if (!ParseCryptoAttribute(line, media_desc, error)) {
2600 return false;
2601 }
2602 } else if (HasAttribute(line, kAttributeRtpmap)) {
2603 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2604 media_desc, error)) {
2605 return false;
2606 }
2607 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2608 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2609 return false;
2610 }
2611 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2612 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2613 return false;
2614 }
2615 } else if (HasAttribute(line, kCodecParamPTime)) {
2616 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2617 return false;
2618 }
2619 } else if (HasAttribute(line, kAttributeSendOnly)) {
2620 media_desc->set_direction(cricket::MD_SENDONLY);
2621 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2622 media_desc->set_direction(cricket::MD_RECVONLY);
2623 } else if (HasAttribute(line, kAttributeInactive)) {
2624 media_desc->set_direction(cricket::MD_INACTIVE);
2625 } else if (HasAttribute(line, kAttributeSendRecv)) {
2626 media_desc->set_direction(cricket::MD_SENDRECV);
2627 } else if (HasAttribute(line, kAttributeExtmap)) {
2628 RtpHeaderExtension extmap;
2629 if (!ParseExtmap(line, &extmap, error)) {
2630 return false;
2631 }
2632 media_desc->AddRtpHeaderExtension(extmap);
2633 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2634 // Experimental attribute. Conference mode activates more aggressive
2635 // AEC and NS settings.
2636 // TODO: expose API to set these directly.
2637 std::string flag_value;
2638 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2639 return false;
2640 }
2641 if (flag_value.compare(kValueConference) == 0)
2642 media_desc->set_conference_mode(true);
2643 } else if (HasAttribute(line, kAttributeXGoogleBufferLatency)) {
2644 // Experimental attribute.
2645 // TODO: expose API to set this directly.
2646 std::string flag_value;
2647 if (!GetValue(line, kAttributeXGoogleBufferLatency, &flag_value,
2648 error)) {
2649 return false;
2650 }
2651 int buffer_latency = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002652 if (!GetValueFromString(line, flag_value, &buffer_latency, error)) {
2653 return false;
2654 }
2655 if (buffer_latency < 0) {
2656 return ParseFailed(line, "Buffer latency less than 0.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002657 }
2658 media_desc->set_buffered_mode_latency(buffer_latency);
2659 }
2660 } else {
2661 // Only parse lines that we are interested of.
2662 LOG(LS_INFO) << "Ignored line: " << line;
2663 continue;
2664 }
2665 }
2666
2667 // Create tracks from the |ssrc_infos|.
2668 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2669
2670 // Add the ssrc group to the track.
2671 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2672 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2673 if (ssrc_group->ssrcs.empty()) {
2674 continue;
2675 }
2676 uint32 ssrc = ssrc_group->ssrcs.front();
2677 for (StreamParamsVec::iterator track = tracks.begin();
2678 track != tracks.end(); ++track) {
2679 if (track->has_ssrc(ssrc)) {
2680 track->ssrc_groups.push_back(*ssrc_group);
2681 }
2682 }
2683 }
2684
2685 // Add the new tracks to the |media_desc|.
2686 for (StreamParamsVec::iterator track = tracks.begin();
2687 track != tracks.end(); ++track) {
2688 media_desc->AddStream(*track);
2689 }
2690
2691 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2692 AudioContentDescription* audio_desc =
2693 static_cast<AudioContentDescription*>(media_desc);
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002694 UpdateFromWildcardCodecs(audio_desc);
2695
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002696 // Verify audio codec ensures that no audio codec has been populated with
2697 // only fmtp.
2698 if (!VerifyAudioCodecs(audio_desc)) {
2699 return ParseFailed("Failed to parse audio codecs correctly.", error);
2700 }
2701 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2702 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2703 }
2704
2705 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002706 VideoContentDescription* video_desc =
2707 static_cast<VideoContentDescription*>(media_desc);
2708 UpdateFromWildcardCodecs(video_desc);
2709 // Verify video codec ensures that no video codec has been populated with
2710 // only rtcp-fb.
2711 if (!VerifyVideoCodecs(video_desc)) {
2712 return ParseFailed("Failed to parse video codecs correctly.", error);
2713 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002714 }
2715
2716 // RFC 5245
2717 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2718 for (Candidates::iterator it = candidates_orig.begin();
2719 it != candidates_orig.end(); ++it) {
2720 ASSERT((*it).username().empty());
2721 (*it).set_username(transport->ice_ufrag);
2722 ASSERT((*it).password().empty());
2723 (*it).set_password(transport->ice_pwd);
2724 candidates->push_back(
2725 new JsepIceCandidate(mline_id, mline_index, *it));
2726 }
2727 return true;
2728}
2729
2730bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2731 SdpParseError* error) {
2732 ASSERT(ssrc_infos != NULL);
2733 // RFC 5576
2734 // a=ssrc:<ssrc-id> <attribute>
2735 // a=ssrc:<ssrc-id> <attribute>:<value>
2736 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07002737 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2738 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002739 const size_t expected_fields = 2;
2740 return ParseFailedExpectFieldNum(line, expected_fields, error);
2741 }
2742
2743 // ssrc:<ssrc-id>
2744 std::string ssrc_id_s;
2745 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2746 return false;
2747 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002748 uint32 ssrc_id = 0;
2749 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2750 return false;
2751 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002752
2753 std::string attribute;
2754 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07002755 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002756 std::ostringstream description;
2757 description << "Failed to get the ssrc attribute value from " << field2
2758 << ". Expected format <attribute>:<value>.";
2759 return ParseFailed(line, description.str(), error);
2760 }
2761
2762 // Check if there's already an item for this |ssrc_id|. Create a new one if
2763 // there isn't.
2764 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2765 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2766 if (ssrc_info->ssrc_id == ssrc_id) {
2767 break;
2768 }
2769 }
2770 if (ssrc_info == ssrc_infos->end()) {
2771 SsrcInfo info;
2772 info.ssrc_id = ssrc_id;
2773 ssrc_infos->push_back(info);
2774 ssrc_info = ssrc_infos->end() - 1;
2775 }
2776
2777 // Store the info to the |ssrc_info|.
2778 if (attribute == kSsrcAttributeCname) {
2779 // RFC 5576
2780 // cname:<value>
2781 ssrc_info->cname = value;
2782 } else if (attribute == kSsrcAttributeMsid) {
2783 // draft-alvestrand-mmusic-msid-00
2784 // "msid:" identifier [ " " appdata ]
2785 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002786 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002787 if (fields.size() < 1 || fields.size() > 2) {
2788 return ParseFailed(line,
2789 "Expected format \"msid:<identifier>[ <appdata>]\".",
2790 error);
2791 }
2792 ssrc_info->msid_identifier = fields[0];
2793 if (fields.size() == 2) {
2794 ssrc_info->msid_appdata = fields[1];
2795 }
2796 } else if (attribute == kSsrcAttributeMslabel) {
2797 // draft-alvestrand-rtcweb-mid-01
2798 // mslabel:<value>
2799 ssrc_info->mslabel = value;
2800 } else if (attribute == kSSrcAttributeLabel) {
2801 // The label isn't defined.
2802 // label:<value>
2803 ssrc_info->label = value;
2804 }
2805 return true;
2806}
2807
2808bool ParseSsrcGroupAttribute(const std::string& line,
2809 SsrcGroupVec* ssrc_groups,
2810 SdpParseError* error) {
2811 ASSERT(ssrc_groups != NULL);
2812 // RFC 5576
2813 // a=ssrc-group:<semantics> <ssrc-id> ...
2814 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002815 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002816 kSdpDelimiterSpace, &fields);
2817 const size_t expected_min_fields = 2;
2818 if (fields.size() < expected_min_fields) {
2819 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2820 }
2821 std::string semantics;
2822 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2823 return false;
2824 }
2825 std::vector<uint32> ssrcs;
2826 for (size_t i = 1; i < fields.size(); ++i) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002827 uint32 ssrc = 0;
2828 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2829 return false;
2830 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002831 ssrcs.push_back(ssrc);
2832 }
2833 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2834 return true;
2835}
2836
2837bool ParseCryptoAttribute(const std::string& line,
2838 MediaContentDescription* media_desc,
2839 SdpParseError* error) {
2840 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002841 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002842 kSdpDelimiterSpace, &fields);
2843 // RFC 4568
2844 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2845 const size_t expected_min_fields = 3;
2846 if (fields.size() < expected_min_fields) {
2847 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2848 }
2849 std::string tag_value;
2850 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2851 return false;
2852 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002853 int tag = 0;
2854 if (!GetValueFromString(line, tag_value, &tag, error)) {
2855 return false;
2856 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002857 const std::string crypto_suite = fields[1];
2858 const std::string key_params = fields[2];
2859 std::string session_params;
2860 if (fields.size() > 3) {
2861 session_params = fields[3];
2862 }
2863 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2864 session_params));
2865 return true;
2866}
2867
2868// Updates or creates a new codec entry in the audio description with according
2869// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2870void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2871 int bitrate, int channels, int preference,
2872 AudioContentDescription* audio_desc) {
2873 // Codec may already be populated with (only) optional parameters
2874 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002875 cricket::AudioCodec codec =
2876 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002877 codec.name = name;
2878 codec.clockrate = clockrate;
2879 codec.bitrate = bitrate;
2880 codec.channels = channels;
2881 codec.preference = preference;
2882 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2883 codec);
2884}
2885
2886// Updates or creates a new codec entry in the video description according to
2887// |name|, |width|, |height|, |framerate| and |preference|.
2888void UpdateCodec(int payload_type, const std::string& name, int width,
2889 int height, int framerate, int preference,
2890 VideoContentDescription* video_desc) {
2891 // Codec may already be populated with (only) optional parameters
2892 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002893 cricket::VideoCodec codec =
2894 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002895 codec.name = name;
2896 codec.width = width;
2897 codec.height = height;
2898 codec.framerate = framerate;
2899 codec.preference = preference;
2900 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2901 codec);
2902}
2903
2904bool ParseRtpmapAttribute(const std::string& line,
2905 const MediaType media_type,
2906 const std::vector<int>& codec_preference,
2907 MediaContentDescription* media_desc,
2908 SdpParseError* error) {
2909 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002910 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002911 kSdpDelimiterSpace, &fields);
2912 // RFC 4566
2913 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2914 const size_t expected_min_fields = 2;
2915 if (fields.size() < expected_min_fields) {
2916 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2917 }
2918 std::string payload_type_value;
2919 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2920 return false;
2921 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002922 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002923 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
2924 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002925 return false;
2926 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002927
2928 // Set the preference order depending on the order of the pl type in the
2929 // <fmt> of the m-line.
2930 const int preference = codec_preference.end() -
2931 std::find(codec_preference.begin(), codec_preference.end(),
2932 payload_type);
2933 if (preference == 0) {
2934 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2935 << "<fmt> of the m-line: " << line;
2936 return true;
2937 }
2938 const std::string encoder = fields[1];
2939 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002940 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002941 // <encoding name>/<clock rate>[/<encodingparameters>]
2942 // 2 mandatory fields
2943 if (codec_params.size() < 2 || codec_params.size() > 3) {
2944 return ParseFailed(line,
2945 "Expected format \"<encoding name>/<clock rate>"
2946 "[/<encodingparameters>]\".",
2947 error);
2948 }
2949 const std::string encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002950 int clock_rate = 0;
2951 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2952 return false;
2953 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002954 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2955 VideoContentDescription* video_desc =
2956 static_cast<VideoContentDescription*>(media_desc);
2957 // TODO: We will send resolution in SDP. For now use
2958 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2959 UpdateCodec(payload_type, encoding_name,
2960 JsepSessionDescription::kMaxVideoCodecWidth,
2961 JsepSessionDescription::kMaxVideoCodecHeight,
2962 JsepSessionDescription::kDefaultVideoCodecFramerate,
2963 preference, video_desc);
2964 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2965 // RFC 4566
2966 // For audio streams, <encoding parameters> indicates the number
2967 // of audio channels. This parameter is OPTIONAL and may be
2968 // omitted if the number of channels is one, provided that no
2969 // additional parameters are needed.
2970 int channels = 1;
2971 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002972 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2973 return false;
2974 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002975 }
2976 int bitrate = 0;
2977 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2978 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2979 // The bandwidth adaptation doesn't always work well, so this code
2980 // sets a fixed target bitrate instead.
2981 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2982 if (clock_rate <= 16000) {
2983 bitrate = kIsacWbDefaultRate;
2984 } else {
2985 bitrate = kIsacSwbDefaultRate;
2986 }
2987 }
2988 AudioContentDescription* audio_desc =
2989 static_cast<AudioContentDescription*>(media_desc);
2990 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2991 preference, audio_desc);
2992 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2993 DataContentDescription* data_desc =
2994 static_cast<DataContentDescription*>(media_desc);
2995 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2996 preference));
2997 }
2998 return true;
2999}
3000
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003001bool ParseFmtpParam(const std::string& line, std::string* parameter,
3002 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003003 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003004 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
3005 return false;
3006 }
3007 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003008 return true;
3009}
3010
3011bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
3012 MediaContentDescription* media_desc,
3013 SdpParseError* error) {
3014 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3015 media_type != cricket::MEDIA_TYPE_VIDEO) {
3016 return true;
3017 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003018
3019 std::string line_payload;
3020 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003021
3022 // RFC 5576
3023 // a=fmtp:<format> <format specific parameters>
3024 // At least two fields, whereas the second one is any of the optional
3025 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07003026 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
3027 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003028 ParseFailedExpectMinFieldNum(line, 2, error);
3029 return false;
3030 }
3031
Donald Curtis0e07f922015-05-15 09:21:23 -07003032 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003033 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07003034 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003035 return false;
3036 }
3037
Donald Curtis0e07f922015-05-15 09:21:23 -07003038 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07003039 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3040 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003041 return false;
3042 }
3043
3044 // Parse out format specific parameters.
3045 std::vector<std::string> fields;
3046 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
3047
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003048 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07003049 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003050 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003051 // Only fmtps with equals are currently supported. Other fmtp types
3052 // should be ignored. Unknown fmtps do not constitute an error.
3053 continue;
3054 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003055
3056 std::string name;
3057 std::string value;
3058 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003059 return false;
3060 }
3061 codec_params[name] = value;
3062 }
3063
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003064 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3065 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003066 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003067 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3068 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003069 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003070 }
3071 return true;
3072}
3073
3074bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3075 MediaContentDescription* media_desc,
3076 SdpParseError* error) {
3077 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3078 media_type != cricket::MEDIA_TYPE_VIDEO) {
3079 return true;
3080 }
3081 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003082 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003083 if (rtcp_fb_fields.size() < 2) {
3084 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3085 }
3086 std::string payload_type_string;
3087 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3088 error)) {
3089 return false;
3090 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003091 int payload_type = kWildcardPayloadType;
3092 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003093 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3094 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003095 return false;
3096 }
3097 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003098 std::string id = rtcp_fb_fields[1];
3099 std::string param = "";
3100 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3101 iter != rtcp_fb_fields.end(); ++iter) {
3102 param.append(*iter);
3103 }
3104 const cricket::FeedbackParam feedback_param(id, param);
3105
3106 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003107 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3108 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003109 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003110 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3111 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003112 }
3113 return true;
3114}
3115
3116} // namespace webrtc