blob: 30db437b8123d274db38456607975d2119e91e0a [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,
jbauch083b73f2015-07-16 02:46:32 -0700719 const std::string& mline,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000720 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);
jbauch083b73f2015-07-16 02:46:32 -0700811 const std::string& session_id = jdesc.session_id().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812 kSessionOriginSessionId : jdesc.session_id();
jbauch083b73f2015-07-16 02:46:32 -0700813 const std::string& session_version = jdesc.session_version().empty() ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000814 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 }
jbauch083b73f2015-07-16 02:46:32 -07001004 const std::string& foundation = fields[0];
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +00001005
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 }
jbauch083b73f2015-07-16 02:46:32 -07001010 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 }
jbauch083b73f2015-07-16 02:46:32 -07001015 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;
jbauch083b73f2015-07-16 02:46:32 -07001028 const std::string& type = fields[7];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001029 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.
jbauch083b73f2015-07-16 02:46:32 -07001263 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>
Peter Thatcherc0c3a862015-06-24 15:31:25 -07001277 if (media_desc->bandwidth() >= 1000) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001278 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1279 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1280 AddLine(os.str(), message);
1281 }
1282
1283 // Add the a=rtcp line.
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001284 if (IsRtp(media_desc->protocol())) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001285 std::string rtcp_line = GetRtcpLine(candidates);
1286 if (!rtcp_line.empty()) {
1287 AddLine(rtcp_line, message);
1288 }
1289 }
1290
1291 // Build the a=candidate lines.
1292 BuildCandidate(candidates, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293
1294 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1295 if (transport_info) {
1296 // RFC 5245
1297 // ice-pwd-att = "ice-pwd" ":" password
1298 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1299 // ice-ufrag
1300 InitAttrLine(kAttributeIceUfrag, &os);
1301 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1302 AddLine(os.str(), message);
1303 // ice-pwd
1304 InitAttrLine(kAttributeIcePwd, &os);
1305 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1306 AddLine(os.str(), message);
1307
1308 // draft-petithuguenin-mmusic-ice-attributes-level-03
1309 BuildIceOptions(transport_info->description.transport_options, message);
1310
1311 // RFC 4572
1312 // fingerprint-attribute =
1313 // "fingerprint" ":" hash-func SP fingerprint
1314 if (fp) {
1315 // Insert the fingerprint attribute.
1316 InitAttrLine(kAttributeFingerprint, &os);
1317 os << kSdpDelimiterColon
1318 << fp->algorithm << kSdpDelimiterSpace
1319 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001321
1322 // Inserting setup attribute.
1323 if (transport_info->description.connection_role !=
1324 cricket::CONNECTIONROLE_NONE) {
1325 // Making sure we are not using "passive" mode.
1326 cricket::ConnectionRole role =
1327 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001328 std::string dtls_role_str;
1329 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001330 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001331 os << kSdpDelimiterColon << dtls_role_str;
1332 AddLine(os.str(), message);
1333 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001334 }
1335 }
1336
1337 // RFC 3388
1338 // mid-attribute = "a=mid:" identification-tag
1339 // identification-tag = token
1340 // Use the content name as the mid identification-tag.
1341 InitAttrLine(kAttributeMid, &os);
1342 os << kSdpDelimiterColon << content_info->name;
1343 AddLine(os.str(), message);
1344
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001345 if (IsDtlsSctp(media_desc->protocol())) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001346 BuildSctpContentAttributes(message, sctp_port);
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001347 } else if (IsRtp(media_desc->protocol())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001348 BuildRtpContentAttributes(media_desc, media_type, message);
1349 }
1350}
1351
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001352void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001353 // draft-ietf-mmusic-sctp-sdp-04
1354 // a=sctpmap:sctpmap-number protocol [streams]
1355 std::ostringstream os;
1356 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001357 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001358 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1359 << (cricket::kMaxSctpSid + 1);
1360 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361}
1362
1363void BuildRtpContentAttributes(
1364 const MediaContentDescription* media_desc,
1365 const MediaType media_type,
1366 std::string* message) {
1367 std::ostringstream os;
1368 // RFC 5285
1369 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1370 // The definitions MUST be either all session level or all media level. This
1371 // implementation uses all media level.
1372 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1373 InitAttrLine(kAttributeExtmap, &os);
1374 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1375 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1376 AddLine(os.str(), message);
1377 }
1378
1379 // RFC 3264
1380 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
1381
1382 cricket::MediaContentDirection direction = media_desc->direction();
1383 if (media_desc->streams().empty() && direction == cricket::MD_SENDRECV) {
1384 direction = cricket::MD_RECVONLY;
1385 }
1386
1387 switch (direction) {
1388 case cricket::MD_INACTIVE:
1389 InitAttrLine(kAttributeInactive, &os);
1390 break;
1391 case cricket::MD_SENDONLY:
1392 InitAttrLine(kAttributeSendOnly, &os);
1393 break;
1394 case cricket::MD_RECVONLY:
1395 InitAttrLine(kAttributeRecvOnly, &os);
1396 break;
1397 case cricket::MD_SENDRECV:
1398 default:
1399 InitAttrLine(kAttributeSendRecv, &os);
1400 break;
1401 }
1402 AddLine(os.str(), message);
1403
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404 // RFC 5761
1405 // a=rtcp-mux
1406 if (media_desc->rtcp_mux()) {
1407 InitAttrLine(kAttributeRtcpMux, &os);
1408 AddLine(os.str(), message);
1409 }
1410
1411 // RFC 4568
1412 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1413 for (std::vector<CryptoParams>::const_iterator it =
1414 media_desc->cryptos().begin();
1415 it != media_desc->cryptos().end(); ++it) {
1416 InitAttrLine(kAttributeCrypto, &os);
1417 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1418 << it->key_params;
1419 if (!it->session_params.empty()) {
1420 os << " " << it->session_params;
1421 }
1422 AddLine(os.str(), message);
1423 }
1424
1425 // RFC 4566
1426 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1427 // [/<encodingparameters>]
1428 BuildRtpMap(media_desc, media_type, message);
1429
1430 // Specify latency for buffered mode.
1431 // a=x-google-buffer-latency:<value>
1432 if (media_desc->buffered_mode_latency() != cricket::kBufferedModeDisabled) {
1433 std::ostringstream os;
1434 InitAttrLine(kAttributeXGoogleBufferLatency, &os);
1435 os << kSdpDelimiterColon << media_desc->buffered_mode_latency();
1436 AddLine(os.str(), message);
1437 }
1438
1439 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1440 track != media_desc->streams().end(); ++track) {
1441 // Require that the track belongs to a media stream,
1442 // ie the sync_label is set. This extra check is necessary since the
1443 // MediaContentDescription always contains a streamparam with an ssrc even
1444 // if no track or media stream have been created.
1445 if (track->sync_label.empty()) continue;
1446
1447 // Build the ssrc-group lines.
1448 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1449 // RFC 5576
1450 // a=ssrc-group:<semantics> <ssrc-id> ...
1451 if (track->ssrc_groups[i].ssrcs.empty()) {
1452 continue;
1453 }
1454 std::ostringstream os;
1455 InitAttrLine(kAttributeSsrcGroup, &os);
1456 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
1457 std::vector<uint32>::const_iterator ssrc =
1458 track->ssrc_groups[i].ssrcs.begin();
1459 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001460 os << kSdpDelimiterSpace << rtc::ToString<uint32>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001461 }
1462 AddLine(os.str(), message);
1463 }
1464 // Build the ssrc lines for each ssrc.
1465 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
1466 uint32 ssrc = track->ssrcs[i];
1467 // RFC 5576
1468 // a=ssrc:<ssrc-id> cname:<value>
1469 AddSsrcLine(ssrc, kSsrcAttributeCname,
1470 track->cname, message);
1471
1472 // draft-alvestrand-mmusic-msid-00
1473 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1474 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1475 // is corresponding to the "name" attribute of StreamParams.
1476 std::string appdata = track->id;
1477 std::ostringstream os;
1478 InitAttrLine(kAttributeSsrc, &os);
1479 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1480 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1481 << kSdpDelimiterSpace << appdata;
1482 AddLine(os.str(), message);
1483
1484 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1485 // draft-alvestrand-rtcweb-mid-01
1486 // a=ssrc:<ssrc-id> mslabel:<value>
1487 // The label isn't yet defined.
1488 // a=ssrc:<ssrc-id> label:<value>
1489 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1490 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1491 }
1492 }
1493}
1494
1495void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1496 // fmtp header: a=fmtp:|payload_type| <parameters>
1497 // Add a=fmtp
1498 InitAttrLine(kAttributeFmtp, os);
1499 // Add :|payload_type|
1500 *os << kSdpDelimiterColon << payload_type;
1501}
1502
1503void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1504 // rtcp-fb header: a=rtcp-fb:|payload_type|
1505 // <parameters>/<ccm <ccm_parameters>>
1506 // Add a=rtcp-fb
1507 InitAttrLine(kAttributeRtcpFb, os);
1508 // Add :
1509 *os << kSdpDelimiterColon;
1510 if (payload_type == kWildcardPayloadType) {
1511 *os << "*";
1512 } else {
1513 *os << payload_type;
1514 }
1515}
1516
1517void WriteFmtpParameter(const std::string& parameter_name,
1518 const std::string& parameter_value,
1519 std::ostringstream* os) {
1520 // fmtp parameters: |parameter_name|=|parameter_value|
1521 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1522}
1523
1524void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1525 std::ostringstream* os) {
1526 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1527 fmtp != parameters.end(); ++fmtp) {
1528 // Each new parameter, except the first one starts with ";" and " ".
1529 if (fmtp != parameters.begin()) {
1530 *os << kSdpDelimiterSemicolon;
1531 }
1532 *os << kSdpDelimiterSpace;
1533 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1534 }
1535}
1536
1537bool IsFmtpParam(const std::string& name) {
1538 const char* kFmtpParams[] = {
1539 kCodecParamMinPTime, kCodecParamSPropStereo,
Minyue Li7100dcd2015-03-27 05:05:59 +01001540 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamUseDtx,
1541 kCodecParamStartBitrate, kCodecParamMaxBitrate, kCodecParamMinBitrate,
1542 kCodecParamMaxQuantization, kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001543 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1544 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545 };
1546 for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
1547 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1548 return true;
1549 }
1550 }
1551 return false;
1552}
1553
1554// Retreives fmtp parameters from |params|, which may contain other parameters
1555// as well, and puts them in |fmtp_parameters|.
1556void GetFmtpParams(const cricket::CodecParameterMap& params,
1557 cricket::CodecParameterMap* fmtp_parameters) {
1558 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1559 iter != params.end(); ++iter) {
1560 if (IsFmtpParam(iter->first)) {
1561 (*fmtp_parameters)[iter->first] = iter->second;
1562 }
1563 }
1564}
1565
1566template <class T>
1567void AddFmtpLine(const T& codec, std::string* message) {
1568 cricket::CodecParameterMap fmtp_parameters;
1569 GetFmtpParams(codec.params, &fmtp_parameters);
1570 if (fmtp_parameters.empty()) {
1571 // No need to add an fmtp if it will have no (optional) parameters.
1572 return;
1573 }
1574 std::ostringstream os;
1575 WriteFmtpHeader(codec.id, &os);
1576 WriteFmtpParameters(fmtp_parameters, &os);
1577 AddLine(os.str(), message);
1578 return;
1579}
1580
1581template <class T>
1582void AddRtcpFbLines(const T& codec, std::string* message) {
1583 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1584 codec.feedback_params.params().begin();
1585 iter != codec.feedback_params.params().end(); ++iter) {
1586 std::ostringstream os;
1587 WriteRtcpFbHeader(codec.id, &os);
1588 os << " " << iter->id();
1589 if (!iter->param().empty()) {
1590 os << " " << iter->param();
1591 }
1592 AddLine(os.str(), message);
1593 }
1594}
1595
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001596bool AddSctpDataCodec(DataContentDescription* media_desc,
1597 int sctp_port) {
1598 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1599 return ParseFailed("",
1600 "Can't have multiple sctp port attributes.",
1601 NULL);
1602 }
1603 // Add the SCTP Port number as a pseudo-codec "port" parameter
1604 cricket::DataCodec codec_port(
1605 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1606 0);
1607 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1608 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1609 << sctp_port;
1610 media_desc->AddCodec(codec_port);
1611 return true;
1612}
1613
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001614bool GetMinValue(const std::vector<int>& values, int* value) {
1615 if (values.empty()) {
1616 return false;
1617 }
1618 std::vector<int>::const_iterator found =
1619 std::min_element(values.begin(), values.end());
1620 *value = *found;
1621 return true;
1622}
1623
1624bool GetParameter(const std::string& name,
1625 const cricket::CodecParameterMap& params, int* value) {
1626 std::map<std::string, std::string>::const_iterator found =
1627 params.find(name);
1628 if (found == params.end()) {
1629 return false;
1630 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001631 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001632 return false;
1633 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001634 return true;
1635}
1636
1637void BuildRtpMap(const MediaContentDescription* media_desc,
1638 const MediaType media_type,
1639 std::string* message) {
1640 ASSERT(message != NULL);
1641 ASSERT(media_desc != NULL);
1642 std::ostringstream os;
1643 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1644 const VideoContentDescription* video_desc =
1645 static_cast<const VideoContentDescription*>(media_desc);
1646 for (std::vector<cricket::VideoCodec>::const_iterator it =
1647 video_desc->codecs().begin();
1648 it != video_desc->codecs().end(); ++it) {
1649 // RFC 4566
1650 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1651 // [/<encodingparameters>]
1652 if (it->id != kWildcardPayloadType) {
1653 InitAttrLine(kAttributeRtpmap, &os);
1654 os << kSdpDelimiterColon << it->id << " " << it->name
1655 << "/" << kDefaultVideoClockrate;
1656 AddLine(os.str(), message);
1657 }
1658 AddRtcpFbLines(*it, message);
1659 AddFmtpLine(*it, message);
1660 }
1661 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1662 const AudioContentDescription* audio_desc =
1663 static_cast<const AudioContentDescription*>(media_desc);
1664 std::vector<int> ptimes;
1665 std::vector<int> maxptimes;
1666 int max_minptime = 0;
1667 for (std::vector<cricket::AudioCodec>::const_iterator it =
1668 audio_desc->codecs().begin();
1669 it != audio_desc->codecs().end(); ++it) {
1670 ASSERT(!it->name.empty());
1671 // RFC 4566
1672 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1673 // [/<encodingparameters>]
1674 InitAttrLine(kAttributeRtpmap, &os);
1675 os << kSdpDelimiterColon << it->id << " ";
1676 os << it->name << "/" << it->clockrate;
1677 if (it->channels != 1) {
1678 os << "/" << it->channels;
1679 }
1680 AddLine(os.str(), message);
1681 AddRtcpFbLines(*it, message);
1682 AddFmtpLine(*it, message);
1683 int minptime = 0;
1684 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1685 max_minptime = std::max(minptime, max_minptime);
1686 }
1687 int ptime;
1688 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1689 ptimes.push_back(ptime);
1690 }
1691 int maxptime;
1692 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1693 maxptimes.push_back(maxptime);
1694 }
1695 }
1696 // Populate the maxptime attribute with the smallest maxptime of all codecs
1697 // under the same m-line.
1698 int min_maxptime = INT_MAX;
1699 if (GetMinValue(maxptimes, &min_maxptime)) {
1700 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1701 }
1702 ASSERT(min_maxptime > max_minptime);
1703 // Populate the ptime attribute with the smallest ptime or the largest
1704 // minptime, whichever is the largest, for all codecs under the same m-line.
1705 int ptime = INT_MAX;
1706 if (GetMinValue(ptimes, &ptime)) {
1707 ptime = std::min(ptime, min_maxptime);
1708 ptime = std::max(ptime, max_minptime);
1709 AddAttributeLine(kCodecParamPTime, ptime, message);
1710 }
1711 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1712 const DataContentDescription* data_desc =
1713 static_cast<const DataContentDescription*>(media_desc);
1714 for (std::vector<cricket::DataCodec>::const_iterator it =
1715 data_desc->codecs().begin();
1716 it != data_desc->codecs().end(); ++it) {
1717 // RFC 4566
1718 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1719 // [/<encodingparameters>]
1720 InitAttrLine(kAttributeRtpmap, &os);
1721 os << kSdpDelimiterColon << it->id << " "
1722 << it->name << "/" << it->clockrate;
1723 AddLine(os.str(), message);
1724 }
1725 }
1726}
1727
1728void BuildCandidate(const std::vector<Candidate>& candidates,
1729 std::string* message) {
1730 std::ostringstream os;
1731
1732 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1733 it != candidates.end(); ++it) {
1734 // RFC 5245
1735 // a=candidate:<foundation> <component-id> <transport> <priority>
1736 // <connection-address> <port> typ <candidate-types>
1737 // [raddr <connection-address>] [rport <port>]
1738 // *(SP extension-att-name SP extension-att-value)
1739 std::string type;
1740 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1741 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1742 type = kCandidateHost;
1743 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1744 type = kCandidateSrflx;
1745 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1746 type = kCandidateRelay;
1747 } else {
1748 ASSERT(false);
Peter Thatcher019087f2015-04-28 09:06:26 -07001749 // Never write out candidates if we don't know the type.
1750 continue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001751 }
1752
1753 InitAttrLine(kAttributeCandidate, &os);
1754 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001755 << it->foundation() << " "
1756 << it->component() << " "
1757 << it->protocol() << " "
1758 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001759 << it->address().ipaddr().ToString() << " "
1760 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001761 << kAttributeCandidateTyp << " "
1762 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001763
1764 // Related address
1765 if (!it->related_address().IsNil()) {
1766 os << kAttributeCandidateRaddr << " "
1767 << it->related_address().ipaddr().ToString() << " "
1768 << kAttributeCandidateRport << " "
1769 << it->related_address().PortAsString() << " ";
1770 }
1771
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001772 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001773 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001774 }
1775
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001776 // Extensions
1777 os << kAttributeCandidateGeneration << " " << it->generation();
1778
1779 AddLine(os.str(), message);
1780 }
1781}
1782
1783void BuildIceOptions(const std::vector<std::string>& transport_options,
1784 std::string* message) {
1785 if (!transport_options.empty()) {
1786 std::ostringstream os;
1787 InitAttrLine(kAttributeIceOption, &os);
1788 os << kSdpDelimiterColon << transport_options[0];
1789 for (size_t i = 1; i < transport_options.size(); ++i) {
1790 os << kSdpDelimiterSpace << transport_options[i];
1791 }
1792 AddLine(os.str(), message);
1793 }
1794}
1795
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001796bool IsRtp(const std::string& protocol) {
1797 return protocol.empty() ||
1798 (protocol.find(cricket::kMediaProtocolRtpPrefix) != std::string::npos);
1799}
1800
1801bool IsDtlsSctp(const std::string& protocol) {
1802 // This intentionally excludes "SCTP" and "SCTP/DTLS".
lally@webrtc.orga7470932015-02-24 20:19:21 +00001803 return protocol.find(cricket::kMediaProtocolDtlsSctp) != std::string::npos;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00001804}
1805
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001806bool ParseSessionDescription(const std::string& message, size_t* pos,
1807 std::string* session_id,
1808 std::string* session_version,
1809 bool* supports_msid,
1810 TransportDescription* session_td,
1811 RtpHeaderExtensions* session_extmaps,
1812 cricket::SessionDescription* desc,
1813 SdpParseError* error) {
1814 std::string line;
1815
1816 // RFC 4566
1817 // v= (protocol version)
1818 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1819 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1820 std::string(), error);
1821 }
1822 // RFC 4566
1823 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1824 // <unicast-address>
1825 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1826 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1827 std::string(), error);
1828 }
1829 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001830 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001831 kSdpDelimiterSpace, &fields);
1832 const size_t expected_fields = 6;
1833 if (fields.size() != expected_fields) {
1834 return ParseFailedExpectFieldNum(line, expected_fields, error);
1835 }
1836 *session_id = fields[1];
1837 *session_version = fields[2];
1838
1839 // RFC 4566
1840 // s= (session name)
1841 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1842 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1843 std::string(), error);
1844 }
1845
1846 // Optional lines
1847 // Those are the optional lines, so shouldn't return false if not present.
1848 // RFC 4566
1849 // i=* (session information)
1850 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1851
1852 // RFC 4566
1853 // u=* (URI of description)
1854 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1855
1856 // RFC 4566
1857 // e=* (email address)
1858 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1859
1860 // RFC 4566
1861 // p=* (phone number)
1862 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1863
1864 // RFC 4566
1865 // c=* (connection information -- not required if included in
1866 // all media)
1867 GetLineWithType(message, pos, &line, kLineTypeConnection);
1868
1869 // RFC 4566
1870 // b=* (zero or more bandwidth information lines)
1871 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1872 // By pass zero or more b lines.
1873 }
1874
1875 // RFC 4566
1876 // One or more time descriptions ("t=" and "r=" lines; see below)
1877 // t= (time the session is active)
1878 // r=* (zero or more repeat times)
1879 // Ensure there's at least one time description
1880 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1881 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1882 error);
1883 }
1884
1885 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1886 // By pass zero or more r lines.
1887 }
1888
1889 // Go through the rest of the time descriptions
1890 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1891 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1892 // By pass zero or more r lines.
1893 }
1894 }
1895
1896 // RFC 4566
1897 // z=* (time zone adjustments)
1898 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1899
1900 // RFC 4566
1901 // k=* (encryption key)
1902 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1903
1904 // RFC 4566
1905 // a=* (zero or more session attribute lines)
1906 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1907 if (HasAttribute(line, kAttributeGroup)) {
1908 if (!ParseGroupAttribute(line, desc, error)) {
1909 return false;
1910 }
1911 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1912 if (!GetValue(line, kAttributeIceUfrag,
1913 &(session_td->ice_ufrag), error)) {
1914 return false;
1915 }
1916 } else if (HasAttribute(line, kAttributeIcePwd)) {
1917 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1918 return false;
1919 }
1920 } else if (HasAttribute(line, kAttributeIceLite)) {
1921 session_td->ice_mode = cricket::ICEMODE_LITE;
1922 } else if (HasAttribute(line, kAttributeIceOption)) {
1923 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1924 return false;
1925 }
1926 } else if (HasAttribute(line, kAttributeFingerprint)) {
1927 if (session_td->identity_fingerprint.get()) {
1928 return ParseFailed(
1929 line,
1930 "Can't have multiple fingerprint attributes at the same level.",
1931 error);
1932 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001933 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001934 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1935 return false;
1936 }
1937 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001938 } else if (HasAttribute(line, kAttributeSetup)) {
1939 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1940 return false;
1941 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001942 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1943 std::string semantics;
1944 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1945 return false;
1946 }
1947 *supports_msid = CaseInsensitiveFind(semantics, kMediaStreamSemantic);
1948 } else if (HasAttribute(line, kAttributeExtmap)) {
1949 RtpHeaderExtension extmap;
1950 if (!ParseExtmap(line, &extmap, error)) {
1951 return false;
1952 }
1953 session_extmaps->push_back(extmap);
1954 }
1955 }
1956
1957 return true;
1958}
1959
1960bool ParseGroupAttribute(const std::string& line,
1961 cricket::SessionDescription* desc,
1962 SdpParseError* error) {
1963 ASSERT(desc != NULL);
1964
1965 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1966 // a=group:BUNDLE video voice
1967 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001968 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001969 kSdpDelimiterSpace, &fields);
1970 std::string semantics;
1971 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1972 return false;
1973 }
1974 cricket::ContentGroup group(semantics);
1975 for (size_t i = 1; i < fields.size(); ++i) {
1976 group.AddContentName(fields[i]);
1977 }
1978 desc->AddGroup(group);
1979 return true;
1980}
1981
1982static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001983 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001984 SdpParseError* error) {
1985 if (!IsLineType(line, kLineTypeAttributes) ||
1986 !HasAttribute(line, kAttributeFingerprint)) {
1987 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1988 kAttributeFingerprint, error);
1989 }
1990
1991 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001992 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993 kSdpDelimiterSpace, &fields);
1994 const size_t expected_fields = 2;
1995 if (fields.size() != expected_fields) {
1996 return ParseFailedExpectFieldNum(line, expected_fields, error);
1997 }
1998
1999 // The first field here is "fingerprint:<hash>.
2000 std::string algorithm;
2001 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2002 return false;
2003 }
2004
2005 // Downcase the algorithm. Note that we don't need to downcase the
2006 // fingerprint because hex_decode can handle upper-case.
2007 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2008 ::tolower);
2009
2010 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002011 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002012 algorithm, fields[1]);
2013 if (!*fingerprint) {
2014 return ParseFailed(line,
2015 "Failed to create fingerprint from the digest.",
2016 error);
2017 }
2018
2019 return true;
2020}
2021
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002022static bool ParseDtlsSetup(const std::string& line,
2023 cricket::ConnectionRole* role,
2024 SdpParseError* error) {
2025 // setup-attr = "a=setup:" role
2026 // role = "active" / "passive" / "actpass" / "holdconn"
2027 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002028 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002029 const size_t expected_fields = 2;
2030 if (fields.size() != expected_fields) {
2031 return ParseFailedExpectFieldNum(line, expected_fields, error);
2032 }
2033 std::string role_str = fields[1];
2034 if (!cricket::StringToConnectionRole(role_str, role)) {
2035 return ParseFailed(line, "Invalid attribute value.", error);
2036 }
2037 return true;
2038}
2039
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002040// RFC 3551
2041// PT encoding media type clock rate channels
2042// name (Hz)
2043// 0 PCMU A 8,000 1
2044// 1 reserved A
2045// 2 reserved A
2046// 3 GSM A 8,000 1
2047// 4 G723 A 8,000 1
2048// 5 DVI4 A 8,000 1
2049// 6 DVI4 A 16,000 1
2050// 7 LPC A 8,000 1
2051// 8 PCMA A 8,000 1
2052// 9 G722 A 8,000 1
2053// 10 L16 A 44,100 2
2054// 11 L16 A 44,100 1
2055// 12 QCELP A 8,000 1
2056// 13 CN A 8,000 1
2057// 14 MPA A 90,000 (see text)
2058// 15 G728 A 8,000 1
2059// 16 DVI4 A 11,025 1
2060// 17 DVI4 A 22,050 1
2061// 18 G729 A 8,000 1
2062struct StaticPayloadAudioCodec {
2063 const char* name;
2064 int clockrate;
2065 int channels;
2066};
2067static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2068 { "PCMU", 8000, 1 },
2069 { "reserved", 0, 0 },
2070 { "reserved", 0, 0 },
2071 { "GSM", 8000, 1 },
2072 { "G723", 8000, 1 },
2073 { "DVI4", 8000, 1 },
2074 { "DVI4", 16000, 1 },
2075 { "LPC", 8000, 1 },
2076 { "PCMA", 8000, 1 },
2077 { "G722", 8000, 1 },
2078 { "L16", 44100, 2 },
2079 { "L16", 44100, 1 },
2080 { "QCELP", 8000, 1 },
2081 { "CN", 8000, 1 },
2082 { "MPA", 90000, 1 },
2083 { "G728", 8000, 1 },
2084 { "DVI4", 11025, 1 },
2085 { "DVI4", 22050, 1 },
2086 { "G729", 8000, 1 },
2087};
2088
2089void MaybeCreateStaticPayloadAudioCodecs(
2090 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2091 if (!media_desc) {
2092 return;
2093 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002094 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002095 std::vector<int>::const_iterator it = fmts.begin();
2096 bool add_new_codec = false;
2097 for (; it != fmts.end(); ++it) {
2098 int payload_type = *it;
2099 if (!media_desc->HasCodec(payload_type) &&
2100 payload_type >= 0 &&
2101 payload_type < ARRAY_SIZE(kStaticPayloadAudioCodecs)) {
2102 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2103 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2104 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2105 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2106 clock_rate, 0, channels,
2107 preference));
2108 add_new_codec = true;
2109 }
2110 --preference;
2111 }
2112 if (add_new_codec) {
2113 media_desc->SortCodecs();
2114 }
2115}
2116
2117template <class C>
2118static C* ParseContentDescription(const std::string& message,
2119 const MediaType media_type,
2120 int mline_index,
2121 const std::string& protocol,
2122 const std::vector<int>& codec_preference,
2123 size_t* pos,
2124 std::string* content_name,
2125 TransportDescription* transport,
2126 std::vector<JsepIceCandidate*>* candidates,
2127 webrtc::SdpParseError* error) {
2128 C* media_desc = new C();
2129 switch (media_type) {
2130 case cricket::MEDIA_TYPE_AUDIO:
2131 *content_name = cricket::CN_AUDIO;
2132 break;
2133 case cricket::MEDIA_TYPE_VIDEO:
2134 *content_name = cricket::CN_VIDEO;
2135 break;
2136 case cricket::MEDIA_TYPE_DATA:
2137 *content_name = cricket::CN_DATA;
2138 break;
2139 default:
2140 ASSERT(false);
2141 break;
2142 }
2143 if (!ParseContent(message, media_type, mline_index, protocol,
2144 codec_preference, pos, content_name,
2145 media_desc, transport, candidates, error)) {
2146 delete media_desc;
2147 return NULL;
2148 }
2149 // Sort the codecs according to the m-line fmt list.
2150 media_desc->SortCodecs();
2151 return media_desc;
2152}
2153
2154bool ParseMediaDescription(const std::string& message,
2155 const TransportDescription& session_td,
2156 const RtpHeaderExtensions& session_extmaps,
2157 bool supports_msid,
2158 size_t* pos,
2159 cricket::SessionDescription* desc,
2160 std::vector<JsepIceCandidate*>* candidates,
2161 SdpParseError* error) {
2162 ASSERT(desc != NULL);
2163 std::string line;
2164 int mline_index = -1;
2165
2166 // Zero or more media descriptions
2167 // RFC 4566
2168 // m=<media> <port> <proto> <fmt>
2169 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2170 ++mline_index;
2171
2172 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002173 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002174 kSdpDelimiterSpace, &fields);
2175 const size_t expected_min_fields = 4;
2176 if (fields.size() < expected_min_fields) {
2177 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2178 }
2179 bool rejected = false;
2180 // RFC 3264
2181 // To reject an offered stream, the port number in the corresponding stream
2182 // in the answer MUST be set to zero.
2183 if (fields[1] == kMediaPortRejected) {
2184 rejected = true;
2185 }
2186
2187 std::string protocol = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002188
2189 // <fmt>
2190 std::vector<int> codec_preference;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002191 if (IsRtp(protocol)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002192 for (size_t j = 3 ; j < fields.size(); ++j) {
2193 // TODO(wu): Remove when below bug is fixed.
2194 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
pbosbb36fdf2015-07-09 07:48:14 -07002195 if (fields[j].empty() && j == fields.size() - 1) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002196 continue;
2197 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002198
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002199 int pl = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002200 if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002201 return false;
2202 }
2203 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002204 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002205 }
2206
2207 // Make a temporary TransportDescription based on |session_td|.
2208 // Some of this gets overwritten by ParseContent.
2209 TransportDescription transport(NS_JINGLE_ICE_UDP,
2210 session_td.transport_options,
2211 session_td.ice_ufrag,
2212 session_td.ice_pwd,
2213 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002214 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002215 session_td.identity_fingerprint.get(),
2216 Candidates());
2217
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002218 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219 std::string content_name;
2220 if (HasAttribute(line, kMediaTypeVideo)) {
2221 content.reset(ParseContentDescription<VideoContentDescription>(
2222 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2223 codec_preference, pos, &content_name,
2224 &transport, candidates, error));
2225 } else if (HasAttribute(line, kMediaTypeAudio)) {
2226 content.reset(ParseContentDescription<AudioContentDescription>(
2227 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2228 codec_preference, pos, &content_name,
2229 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002231 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002232 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002233 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2234 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002235 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002236 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002237
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002238 int p;
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002239 if (data_desc && IsDtlsSctp(protocol) && rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002240 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002241 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002242 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002243 } else {
2244 LOG(LS_WARNING) << "Unsupported media type: " << line;
2245 continue;
2246 }
2247 if (!content.get()) {
2248 // ParseContentDescription returns NULL if failed.
2249 return false;
2250 }
2251
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002252 if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002253 // Make sure to set the media direction correctly. If the direction is not
2254 // MD_RECVONLY or Inactive and no streams are parsed,
2255 // a default MediaStream will be created to prepare for receiving media.
2256 if (supports_msid && content->streams().empty() &&
2257 content->direction() == cricket::MD_SENDRECV) {
2258 content->set_direction(cricket::MD_RECVONLY);
2259 }
2260
2261 // Set the extmap.
2262 if (!session_extmaps.empty() &&
2263 !content->rtp_header_extensions().empty()) {
2264 return ParseFailed("",
2265 "The a=extmap MUST be either all session level or "
2266 "all media level.",
2267 error);
2268 }
2269 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2270 content->AddRtpHeaderExtension(session_extmaps[i]);
2271 }
2272 }
2273 content->set_protocol(protocol);
2274 desc->AddContent(content_name,
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002275 IsDtlsSctp(protocol) ? cricket::NS_JINGLE_DRAFT_SCTP :
2276 cricket::NS_JINGLE_RTP,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002277 rejected,
2278 content.release());
2279 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2280 TransportInfo transport_info(content_name, transport);
2281
2282 if (!desc->AddTransportInfo(transport_info)) {
2283 std::ostringstream description;
2284 description << "Failed to AddTransportInfo with content name: "
2285 << content_name;
2286 return ParseFailed("", description.str(), error);
2287 }
2288 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002289
2290 size_t end_of_message = message.size();
2291 if (mline_index == -1 && *pos != end_of_message) {
2292 ParseFailed(message, *pos, "Expects m line.", error);
2293 return false;
2294 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002295 return true;
2296}
2297
2298bool VerifyCodec(const cricket::Codec& codec) {
2299 // Codec has not been populated correctly unless the name has been set. This
2300 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2301 // have a corresponding "rtpmap" line.
2302 cricket::Codec default_codec;
2303 return default_codec.name != codec.name;
2304}
2305
2306bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2307 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2308 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2309 iter != codecs.end(); ++iter) {
2310 if (!VerifyCodec(*iter)) {
2311 return false;
2312 }
2313 }
2314 return true;
2315}
2316
2317bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2318 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2319 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2320 iter != codecs.end(); ++iter) {
2321 if (!VerifyCodec(*iter)) {
2322 return false;
2323 }
2324 }
2325 return true;
2326}
2327
2328void AddParameters(const cricket::CodecParameterMap& parameters,
2329 cricket::Codec* codec) {
2330 for (cricket::CodecParameterMap::const_iterator iter =
2331 parameters.begin(); iter != parameters.end(); ++iter) {
2332 codec->SetParam(iter->first, iter->second);
2333 }
2334}
2335
2336void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2337 cricket::Codec* codec) {
2338 codec->AddFeedbackParam(feedback_param);
2339}
2340
2341void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2342 cricket::Codec* codec) {
2343 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2344 feedback_params.params().begin();
2345 iter != feedback_params.params().end(); ++iter) {
2346 codec->AddFeedbackParam(*iter);
2347 }
2348}
2349
2350// Gets the current codec setting associated with |payload_type|. If there
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002351// is no Codec associated with that payload type it returns an empty codec
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002352// with that payload type.
2353template <class T>
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002354T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2355 T ret_val;
2356 if (!FindCodecById(codecs, payload_type, &ret_val)) {
2357 ret_val.id = payload_type;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002358 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002359 return ret_val;
2360}
2361
2362// Updates or creates a new codec entry in the audio description.
2363template <class T, class U>
2364void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2365 T* desc = static_cast<T*>(content_desc);
2366 std::vector<U> codecs = desc->codecs();
2367 bool found = false;
2368
2369 typename std::vector<U>::iterator iter;
2370 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2371 if (iter->id == codec.id) {
2372 *iter = codec;
2373 found = true;
2374 break;
2375 }
2376 }
2377 if (!found) {
2378 desc->AddCodec(codec);
2379 return;
2380 }
2381 desc->set_codecs(codecs);
2382}
2383
2384// Adds or updates existing codec corresponding to |payload_type| according
2385// to |parameters|.
2386template <class T, class U>
2387void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2388 const cricket::CodecParameterMap& parameters) {
2389 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002390 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2391 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002392 AddParameters(parameters, &new_codec);
2393 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2394}
2395
2396// Adds or updates existing codec corresponding to |payload_type| according
2397// to |feedback_param|.
2398template <class T, class U>
2399void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2400 const cricket::FeedbackParam& feedback_param) {
2401 // Codec might already have been populated (from rtpmap).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002402 U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2403 payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002404 AddFeedbackParameter(feedback_param, &new_codec);
2405 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2406}
2407
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002408template <class T>
2409bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2410 for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002411 if (iter->id == kWildcardPayloadType) {
2412 *wildcard_codec = *iter;
2413 codecs->erase(iter);
2414 return true;
2415 }
2416 }
2417 return false;
2418}
2419
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002420template<class T>
2421void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2422 auto codecs = desc->codecs();
2423 T wildcard_codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002424 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2425 return;
2426 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002427 for (auto& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002428 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2429 }
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002430 desc->set_codecs(codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002431}
2432
2433void AddAudioAttribute(const std::string& name, const std::string& value,
2434 AudioContentDescription* audio_desc) {
2435 if (value.empty()) {
2436 return;
2437 }
2438 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2439 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2440 iter != codecs.end(); ++iter) {
2441 iter->params[name] = value;
2442 }
2443 audio_desc->set_codecs(codecs);
2444}
2445
2446bool ParseContent(const std::string& message,
2447 const MediaType media_type,
2448 int mline_index,
2449 const std::string& protocol,
2450 const std::vector<int>& codec_preference,
2451 size_t* pos,
2452 std::string* content_name,
2453 MediaContentDescription* media_desc,
2454 TransportDescription* transport,
2455 std::vector<JsepIceCandidate*>* candidates,
2456 SdpParseError* error) {
2457 ASSERT(media_desc != NULL);
2458 ASSERT(content_name != NULL);
2459 ASSERT(transport != NULL);
2460
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002461 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2462 MaybeCreateStaticPayloadAudioCodecs(
2463 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2464 }
2465
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002466 // The media level "ice-ufrag" and "ice-pwd".
2467 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2468 Candidates candidates_orig;
2469 std::string line;
2470 std::string mline_id;
2471 // Tracks created out of the ssrc attributes.
2472 StreamParamsVec tracks;
2473 SsrcInfoVec ssrc_infos;
2474 SsrcGroupVec ssrc_groups;
2475 std::string maxptime_as_string;
2476 std::string ptime_as_string;
2477
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002478 // Loop until the next m line
2479 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2480 if (!GetLine(message, pos, &line)) {
2481 if (*pos >= message.size()) {
2482 break; // Done parsing
2483 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002484 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002485 }
2486 }
2487
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002488 // RFC 4566
2489 // b=* (zero or more bandwidth information lines)
2490 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2491 std::string bandwidth;
2492 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2493 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2494 return false;
2495 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002496 int b = 0;
2497 if (!GetValueFromString(line, bandwidth, &b, error)) {
2498 return false;
2499 }
Peter Thatcherc0c3a862015-06-24 15:31:25 -07002500 // We should never use more than the default bandwidth for RTP-based
2501 // data channels. Don't allow SDP to set the bandwidth, because
2502 // that would give JS the opportunity to "break the Internet".
2503 // See: https://code.google.com/p/chromium/issues/detail?id=280726
2504 if (media_type == cricket::MEDIA_TYPE_DATA && IsRtp(protocol) &&
2505 b > cricket::kDataMaxBandwidth / 1000) {
2506 std::ostringstream description;
2507 description << "RTP-based data channels may not send more than "
2508 << cricket::kDataMaxBandwidth / 1000 << "kbps.";
2509 return ParseFailed(line, description.str(), error);
2510 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002511 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002512 }
2513 }
2514 continue;
2515 }
2516
2517 if (!IsLineType(line, kLineTypeAttributes)) {
2518 // TODO: Handle other lines if needed.
2519 LOG(LS_INFO) << "Ignored line: " << line;
2520 continue;
2521 }
2522
2523 // Handle attributes common to SCTP and RTP.
2524 if (HasAttribute(line, kAttributeMid)) {
2525 // RFC 3388
2526 // mid-attribute = "a=mid:" identification-tag
2527 // identification-tag = token
2528 // Use the mid identification-tag as the content name.
2529 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2530 return false;
2531 }
2532 *content_name = mline_id;
2533 } else if (HasAttribute(line, kAttributeCandidate)) {
2534 Candidate candidate;
2535 if (!ParseCandidate(line, &candidate, error, false)) {
2536 return false;
2537 }
2538 candidates_orig.push_back(candidate);
2539 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2540 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2541 return false;
2542 }
2543 } else if (HasAttribute(line, kAttributeIcePwd)) {
2544 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2545 return false;
2546 }
2547 } else if (HasAttribute(line, kAttributeIceOption)) {
2548 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2549 return false;
2550 }
2551 } else if (HasAttribute(line, kAttributeFmtp)) {
2552 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2553 return false;
2554 }
2555 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002556 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002557
2558 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2559 return false;
2560 }
2561 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002562 } else if (HasAttribute(line, kAttributeSetup)) {
2563 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2564 return false;
2565 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002566 } else if (IsDtlsSctp(protocol) && HasAttribute(line, kAttributeSctpPort)) {
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002567 int sctp_port;
2568 if (!ParseSctpPort(line, &sctp_port, error)) {
2569 return false;
2570 }
2571 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2572 sctp_port)) {
2573 return false;
2574 }
pthatcher@webrtc.org3341b402015-02-13 21:14:22 +00002575 } else if (IsRtp(protocol)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002576 //
2577 // RTP specific attrubtes
2578 //
2579 if (HasAttribute(line, kAttributeRtcpMux)) {
2580 media_desc->set_rtcp_mux(true);
2581 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2582 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2583 return false;
2584 }
2585 } else if (HasAttribute(line, kAttributeSsrc)) {
2586 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2587 return false;
2588 }
2589 } else if (HasAttribute(line, kAttributeCrypto)) {
2590 if (!ParseCryptoAttribute(line, media_desc, error)) {
2591 return false;
2592 }
2593 } else if (HasAttribute(line, kAttributeRtpmap)) {
2594 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2595 media_desc, error)) {
2596 return false;
2597 }
2598 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2599 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2600 return false;
2601 }
2602 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2603 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2604 return false;
2605 }
2606 } else if (HasAttribute(line, kCodecParamPTime)) {
2607 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2608 return false;
2609 }
2610 } else if (HasAttribute(line, kAttributeSendOnly)) {
2611 media_desc->set_direction(cricket::MD_SENDONLY);
2612 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2613 media_desc->set_direction(cricket::MD_RECVONLY);
2614 } else if (HasAttribute(line, kAttributeInactive)) {
2615 media_desc->set_direction(cricket::MD_INACTIVE);
2616 } else if (HasAttribute(line, kAttributeSendRecv)) {
2617 media_desc->set_direction(cricket::MD_SENDRECV);
2618 } else if (HasAttribute(line, kAttributeExtmap)) {
2619 RtpHeaderExtension extmap;
2620 if (!ParseExtmap(line, &extmap, error)) {
2621 return false;
2622 }
2623 media_desc->AddRtpHeaderExtension(extmap);
2624 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2625 // Experimental attribute. Conference mode activates more aggressive
2626 // AEC and NS settings.
2627 // TODO: expose API to set these directly.
2628 std::string flag_value;
2629 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2630 return false;
2631 }
2632 if (flag_value.compare(kValueConference) == 0)
2633 media_desc->set_conference_mode(true);
2634 } else if (HasAttribute(line, kAttributeXGoogleBufferLatency)) {
2635 // Experimental attribute.
2636 // TODO: expose API to set this directly.
2637 std::string flag_value;
2638 if (!GetValue(line, kAttributeXGoogleBufferLatency, &flag_value,
2639 error)) {
2640 return false;
2641 }
2642 int buffer_latency = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002643 if (!GetValueFromString(line, flag_value, &buffer_latency, error)) {
2644 return false;
2645 }
2646 if (buffer_latency < 0) {
2647 return ParseFailed(line, "Buffer latency less than 0.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002648 }
2649 media_desc->set_buffered_mode_latency(buffer_latency);
2650 }
2651 } else {
2652 // Only parse lines that we are interested of.
2653 LOG(LS_INFO) << "Ignored line: " << line;
2654 continue;
2655 }
2656 }
2657
2658 // Create tracks from the |ssrc_infos|.
2659 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2660
2661 // Add the ssrc group to the track.
2662 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2663 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2664 if (ssrc_group->ssrcs.empty()) {
2665 continue;
2666 }
2667 uint32 ssrc = ssrc_group->ssrcs.front();
2668 for (StreamParamsVec::iterator track = tracks.begin();
2669 track != tracks.end(); ++track) {
2670 if (track->has_ssrc(ssrc)) {
2671 track->ssrc_groups.push_back(*ssrc_group);
2672 }
2673 }
2674 }
2675
2676 // Add the new tracks to the |media_desc|.
2677 for (StreamParamsVec::iterator track = tracks.begin();
2678 track != tracks.end(); ++track) {
2679 media_desc->AddStream(*track);
2680 }
2681
2682 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2683 AudioContentDescription* audio_desc =
2684 static_cast<AudioContentDescription*>(media_desc);
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002685 UpdateFromWildcardCodecs(audio_desc);
2686
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002687 // Verify audio codec ensures that no audio codec has been populated with
2688 // only fmtp.
2689 if (!VerifyAudioCodecs(audio_desc)) {
2690 return ParseFailed("Failed to parse audio codecs correctly.", error);
2691 }
2692 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2693 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2694 }
2695
2696 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
jlmiller@webrtc.orga744a282015-02-18 21:37:46 +00002697 VideoContentDescription* video_desc =
2698 static_cast<VideoContentDescription*>(media_desc);
2699 UpdateFromWildcardCodecs(video_desc);
2700 // Verify video codec ensures that no video codec has been populated with
2701 // only rtcp-fb.
2702 if (!VerifyVideoCodecs(video_desc)) {
2703 return ParseFailed("Failed to parse video codecs correctly.", error);
2704 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002705 }
2706
2707 // RFC 5245
2708 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2709 for (Candidates::iterator it = candidates_orig.begin();
2710 it != candidates_orig.end(); ++it) {
2711 ASSERT((*it).username().empty());
2712 (*it).set_username(transport->ice_ufrag);
2713 ASSERT((*it).password().empty());
2714 (*it).set_password(transport->ice_pwd);
2715 candidates->push_back(
2716 new JsepIceCandidate(mline_id, mline_index, *it));
2717 }
2718 return true;
2719}
2720
2721bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2722 SdpParseError* error) {
2723 ASSERT(ssrc_infos != NULL);
2724 // RFC 5576
2725 // a=ssrc:<ssrc-id> <attribute>
2726 // a=ssrc:<ssrc-id> <attribute>:<value>
2727 std::string field1, field2;
Donald Curtis144d0182015-05-15 13:14:24 -07002728 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
2729 &field1, &field2)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002730 const size_t expected_fields = 2;
2731 return ParseFailedExpectFieldNum(line, expected_fields, error);
2732 }
2733
2734 // ssrc:<ssrc-id>
2735 std::string ssrc_id_s;
2736 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2737 return false;
2738 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002739 uint32 ssrc_id = 0;
2740 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2741 return false;
2742 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002743
2744 std::string attribute;
2745 std::string value;
Donald Curtis144d0182015-05-15 13:14:24 -07002746 if (!rtc::tokenize_first(field2, kSdpDelimiterColon, &attribute, &value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002747 std::ostringstream description;
2748 description << "Failed to get the ssrc attribute value from " << field2
2749 << ". Expected format <attribute>:<value>.";
2750 return ParseFailed(line, description.str(), error);
2751 }
2752
2753 // Check if there's already an item for this |ssrc_id|. Create a new one if
2754 // there isn't.
2755 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2756 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2757 if (ssrc_info->ssrc_id == ssrc_id) {
2758 break;
2759 }
2760 }
2761 if (ssrc_info == ssrc_infos->end()) {
2762 SsrcInfo info;
2763 info.ssrc_id = ssrc_id;
2764 ssrc_infos->push_back(info);
2765 ssrc_info = ssrc_infos->end() - 1;
2766 }
2767
2768 // Store the info to the |ssrc_info|.
2769 if (attribute == kSsrcAttributeCname) {
2770 // RFC 5576
2771 // cname:<value>
2772 ssrc_info->cname = value;
2773 } else if (attribute == kSsrcAttributeMsid) {
2774 // draft-alvestrand-mmusic-msid-00
2775 // "msid:" identifier [ " " appdata ]
2776 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002777 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002778 if (fields.size() < 1 || fields.size() > 2) {
2779 return ParseFailed(line,
2780 "Expected format \"msid:<identifier>[ <appdata>]\".",
2781 error);
2782 }
2783 ssrc_info->msid_identifier = fields[0];
2784 if (fields.size() == 2) {
2785 ssrc_info->msid_appdata = fields[1];
2786 }
2787 } else if (attribute == kSsrcAttributeMslabel) {
2788 // draft-alvestrand-rtcweb-mid-01
2789 // mslabel:<value>
2790 ssrc_info->mslabel = value;
2791 } else if (attribute == kSSrcAttributeLabel) {
2792 // The label isn't defined.
2793 // label:<value>
2794 ssrc_info->label = value;
2795 }
2796 return true;
2797}
2798
2799bool ParseSsrcGroupAttribute(const std::string& line,
2800 SsrcGroupVec* ssrc_groups,
2801 SdpParseError* error) {
2802 ASSERT(ssrc_groups != NULL);
2803 // RFC 5576
2804 // a=ssrc-group:<semantics> <ssrc-id> ...
2805 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002806 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002807 kSdpDelimiterSpace, &fields);
2808 const size_t expected_min_fields = 2;
2809 if (fields.size() < expected_min_fields) {
2810 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2811 }
2812 std::string semantics;
2813 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2814 return false;
2815 }
2816 std::vector<uint32> ssrcs;
2817 for (size_t i = 1; i < fields.size(); ++i) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002818 uint32 ssrc = 0;
2819 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2820 return false;
2821 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002822 ssrcs.push_back(ssrc);
2823 }
2824 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2825 return true;
2826}
2827
2828bool ParseCryptoAttribute(const std::string& line,
2829 MediaContentDescription* media_desc,
2830 SdpParseError* error) {
2831 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002832 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002833 kSdpDelimiterSpace, &fields);
2834 // RFC 4568
2835 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2836 const size_t expected_min_fields = 3;
2837 if (fields.size() < expected_min_fields) {
2838 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2839 }
2840 std::string tag_value;
2841 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2842 return false;
2843 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002844 int tag = 0;
2845 if (!GetValueFromString(line, tag_value, &tag, error)) {
2846 return false;
2847 }
jbauch083b73f2015-07-16 02:46:32 -07002848 const std::string& crypto_suite = fields[1];
2849 const std::string& key_params = fields[2];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002850 std::string session_params;
2851 if (fields.size() > 3) {
2852 session_params = fields[3];
2853 }
2854 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2855 session_params));
2856 return true;
2857}
2858
2859// Updates or creates a new codec entry in the audio description with according
2860// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2861void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2862 int bitrate, int channels, int preference,
2863 AudioContentDescription* audio_desc) {
2864 // Codec may already be populated with (only) optional parameters
2865 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002866 cricket::AudioCodec codec =
2867 GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002868 codec.name = name;
2869 codec.clockrate = clockrate;
2870 codec.bitrate = bitrate;
2871 codec.channels = channels;
2872 codec.preference = preference;
2873 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2874 codec);
2875}
2876
2877// Updates or creates a new codec entry in the video description according to
2878// |name|, |width|, |height|, |framerate| and |preference|.
2879void UpdateCodec(int payload_type, const std::string& name, int width,
2880 int height, int framerate, int preference,
2881 VideoContentDescription* video_desc) {
2882 // Codec may already be populated with (only) optional parameters
2883 // (from an fmtp).
changbin.shao@webrtc.org2d25b442015-03-16 04:14:34 +00002884 cricket::VideoCodec codec =
2885 GetCodecWithPayloadType(video_desc->codecs(), payload_type);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002886 codec.name = name;
2887 codec.width = width;
2888 codec.height = height;
2889 codec.framerate = framerate;
2890 codec.preference = preference;
2891 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2892 codec);
2893}
2894
2895bool ParseRtpmapAttribute(const std::string& line,
2896 const MediaType media_type,
2897 const std::vector<int>& codec_preference,
2898 MediaContentDescription* media_desc,
2899 SdpParseError* error) {
2900 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002901 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002902 kSdpDelimiterSpace, &fields);
2903 // RFC 4566
2904 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2905 const size_t expected_min_fields = 2;
2906 if (fields.size() < expected_min_fields) {
2907 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2908 }
2909 std::string payload_type_value;
2910 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2911 return false;
2912 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002913 int payload_type = 0;
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00002914 if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
2915 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002916 return false;
2917 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002918
2919 // Set the preference order depending on the order of the pl type in the
2920 // <fmt> of the m-line.
2921 const int preference = codec_preference.end() -
2922 std::find(codec_preference.begin(), codec_preference.end(),
2923 payload_type);
2924 if (preference == 0) {
2925 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2926 << "<fmt> of the m-line: " << line;
2927 return true;
2928 }
jbauch083b73f2015-07-16 02:46:32 -07002929 const std::string& encoder = fields[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002930 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002931 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002932 // <encoding name>/<clock rate>[/<encodingparameters>]
2933 // 2 mandatory fields
2934 if (codec_params.size() < 2 || codec_params.size() > 3) {
2935 return ParseFailed(line,
2936 "Expected format \"<encoding name>/<clock rate>"
2937 "[/<encodingparameters>]\".",
2938 error);
2939 }
jbauch083b73f2015-07-16 02:46:32 -07002940 const std::string& encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002941 int clock_rate = 0;
2942 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2943 return false;
2944 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002945 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2946 VideoContentDescription* video_desc =
2947 static_cast<VideoContentDescription*>(media_desc);
2948 // TODO: We will send resolution in SDP. For now use
2949 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2950 UpdateCodec(payload_type, encoding_name,
2951 JsepSessionDescription::kMaxVideoCodecWidth,
2952 JsepSessionDescription::kMaxVideoCodecHeight,
2953 JsepSessionDescription::kDefaultVideoCodecFramerate,
2954 preference, video_desc);
2955 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2956 // RFC 4566
2957 // For audio streams, <encoding parameters> indicates the number
2958 // of audio channels. This parameter is OPTIONAL and may be
2959 // omitted if the number of channels is one, provided that no
2960 // additional parameters are needed.
2961 int channels = 1;
2962 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002963 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2964 return false;
2965 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002966 }
2967 int bitrate = 0;
2968 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2969 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2970 // The bandwidth adaptation doesn't always work well, so this code
2971 // sets a fixed target bitrate instead.
2972 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2973 if (clock_rate <= 16000) {
2974 bitrate = kIsacWbDefaultRate;
2975 } else {
2976 bitrate = kIsacSwbDefaultRate;
2977 }
2978 }
2979 AudioContentDescription* audio_desc =
2980 static_cast<AudioContentDescription*>(media_desc);
2981 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2982 preference, audio_desc);
2983 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2984 DataContentDescription* data_desc =
2985 static_cast<DataContentDescription*>(media_desc);
2986 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2987 preference));
2988 }
2989 return true;
2990}
2991
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002992bool ParseFmtpParam(const std::string& line, std::string* parameter,
2993 std::string* value, SdpParseError* error) {
Donald Curtis0e07f922015-05-15 09:21:23 -07002994 if (!rtc::tokenize_first(line, kSdpDelimiterEqual, parameter, value)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002995 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2996 return false;
2997 }
2998 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002999 return true;
3000}
3001
3002bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
3003 MediaContentDescription* media_desc,
3004 SdpParseError* error) {
3005 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3006 media_type != cricket::MEDIA_TYPE_VIDEO) {
3007 return true;
3008 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003009
3010 std::string line_payload;
3011 std::string line_params;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003012
3013 // RFC 5576
3014 // a=fmtp:<format> <format specific parameters>
3015 // At least two fields, whereas the second one is any of the optional
3016 // parameters.
Donald Curtis144d0182015-05-15 13:14:24 -07003017 if (!rtc::tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpace,
3018 &line_payload, &line_params)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003019 ParseFailedExpectMinFieldNum(line, 2, error);
3020 return false;
3021 }
3022
Donald Curtis0e07f922015-05-15 09:21:23 -07003023 // Parse out the payload information.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003024 std::string payload_type_str;
Donald Curtis0e07f922015-05-15 09:21:23 -07003025 if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003026 return false;
3027 }
3028
Donald Curtis0e07f922015-05-15 09:21:23 -07003029 int payload_type = 0;
Donald Curtis144d0182015-05-15 13:14:24 -07003030 if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3031 error)) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003032 return false;
3033 }
3034
3035 // Parse out format specific parameters.
3036 std::vector<std::string> fields;
3037 rtc::split(line_params, kSdpDelimiterSemicolon, &fields);
3038
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003039 cricket::CodecParameterMap codec_params;
Donald Curtis144d0182015-05-15 13:14:24 -07003040 for (auto& iter : fields) {
Donald Curtis0e07f922015-05-15 09:21:23 -07003041 if (iter.find(kSdpDelimiterEqual) == std::string::npos) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003042 // Only fmtps with equals are currently supported. Other fmtp types
3043 // should be ignored. Unknown fmtps do not constitute an error.
3044 continue;
3045 }
Donald Curtis0e07f922015-05-15 09:21:23 -07003046
3047 std::string name;
3048 std::string value;
3049 if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003050 return false;
3051 }
3052 codec_params[name] = value;
3053 }
3054
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003055 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3056 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003057 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3059 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003060 media_desc, payload_type, codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003061 }
3062 return true;
3063}
3064
3065bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3066 MediaContentDescription* media_desc,
3067 SdpParseError* error) {
3068 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3069 media_type != cricket::MEDIA_TYPE_VIDEO) {
3070 return true;
3071 }
3072 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003073 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003074 if (rtcp_fb_fields.size() < 2) {
3075 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3076 }
3077 std::string payload_type_string;
3078 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3079 error)) {
3080 return false;
3081 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003082 int payload_type = kWildcardPayloadType;
3083 if (payload_type_string != "*") {
pkasting@chromium.orge9facf82015-02-17 20:36:28 +00003084 if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3085 error)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003086 return false;
3087 }
3088 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003089 std::string id = rtcp_fb_fields[1];
3090 std::string param = "";
3091 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3092 iter != rtcp_fb_fields.end(); ++iter) {
3093 param.append(*iter);
3094 }
3095 const cricket::FeedbackParam feedback_param(id, param);
3096
3097 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003098 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3099 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003100 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
pkasting@chromium.orgd3245462015-02-23 21:28:22 +00003101 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3102 media_desc, payload_type, feedback_param);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003103 }
3104 return true;
3105}
3106
3107} // namespace webrtc