blob: c7b34c484549945605f498ced7976399fa427550 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2011, Google Inc.
4 *
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>
35
36#include "talk/app/webrtc/jsepicecandidate.h"
37#include "talk/app/webrtc/jsepsessiondescription.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000038#include "talk/media/base/codec.h"
39#include "talk/media/base/constants.h"
40#include "talk/media/base/cryptoparams.h"
mallinath@webrtc.org1112c302013-09-23 20:34:45 +000041#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000042#include "webrtc/p2p/base/candidate.h"
43#include "webrtc/p2p/base/constants.h"
44#include "webrtc/p2p/base/port.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045#include "talk/session/media/mediasession.h"
46#include "talk/session/media/mediasessionclient.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000047#include "webrtc/base/common.h"
48#include "webrtc/base/logging.h"
49#include "webrtc/base/messagedigest.h"
50#include "webrtc/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051
52using cricket::AudioContentDescription;
53using cricket::Candidate;
54using cricket::Candidates;
55using cricket::ContentDescription;
56using cricket::ContentInfo;
57using cricket::CryptoParams;
58using cricket::DataContentDescription;
59using cricket::ICE_CANDIDATE_COMPONENT_RTP;
60using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
61using cricket::kCodecParamMaxBitrate;
62using cricket::kCodecParamMaxPTime;
63using cricket::kCodecParamMaxQuantization;
64using cricket::kCodecParamMinBitrate;
65using cricket::kCodecParamMinPTime;
66using cricket::kCodecParamPTime;
67using cricket::kCodecParamSPropStereo;
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +000068using cricket::kCodecParamStartBitrate;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069using cricket::kCodecParamStereo;
70using cricket::kCodecParamUseInbandFec;
71using cricket::kCodecParamSctpProtocol;
72using cricket::kCodecParamSctpStreams;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000073using cricket::kCodecParamMaxAverageBitrate;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000074using cricket::kCodecParamMaxPlaybackRate;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000075using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000076using cricket::kWildcardPayloadType;
77using cricket::MediaContentDescription;
78using cricket::MediaType;
79using cricket::NS_JINGLE_ICE_UDP;
80using cricket::RtpHeaderExtension;
81using cricket::SsrcGroup;
82using cricket::StreamParams;
83using cricket::StreamParamsVec;
84using cricket::TransportDescription;
85using cricket::TransportInfo;
86using cricket::VideoContentDescription;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000087using rtc::SocketAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088
89typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
90
91namespace cricket {
92class SessionDescription;
93}
94
95namespace webrtc {
96
97// Line type
98// RFC 4566
99// An SDP session description consists of a number of lines of text of
100// the form:
101// <type>=<value>
102// where <type> MUST be exactly one case-significant character.
103static const int kLinePrefixLength = 2; // Lenght of <type>=
104static const char kLineTypeVersion = 'v';
105static const char kLineTypeOrigin = 'o';
106static const char kLineTypeSessionName = 's';
107static const char kLineTypeSessionInfo = 'i';
108static const char kLineTypeSessionUri = 'u';
109static const char kLineTypeSessionEmail = 'e';
110static const char kLineTypeSessionPhone = 'p';
111static const char kLineTypeSessionBandwidth = 'b';
112static const char kLineTypeTiming = 't';
113static const char kLineTypeRepeatTimes = 'r';
114static const char kLineTypeTimeZone = 'z';
115static const char kLineTypeEncryptionKey = 'k';
116static const char kLineTypeMedia = 'm';
117static const char kLineTypeConnection = 'c';
118static const char kLineTypeAttributes = 'a';
119
120// Attributes
121static const char kAttributeGroup[] = "group";
122static const char kAttributeMid[] = "mid";
123static const char kAttributeRtcpMux[] = "rtcp-mux";
124static const char kAttributeSsrc[] = "ssrc";
125static const char kSsrcAttributeCname[] = "cname";
126static const char kAttributeExtmap[] = "extmap";
127// draft-alvestrand-mmusic-msid-01
128// a=msid-semantic: WMS
129static const char kAttributeMsidSemantics[] = "msid-semantic";
130static const char kMediaStreamSemantic[] = "WMS";
131static const char kSsrcAttributeMsid[] = "msid";
132static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133static const char kSsrcAttributeMslabel[] = "mslabel";
134static const char kSSrcAttributeLabel[] = "label";
135static const char kAttributeSsrcGroup[] = "ssrc-group";
136static const char kAttributeCrypto[] = "crypto";
137static const char kAttributeCandidate[] = "candidate";
138static const char kAttributeCandidateTyp[] = "typ";
139static const char kAttributeCandidateRaddr[] = "raddr";
140static const char kAttributeCandidateRport[] = "rport";
141static const char kAttributeCandidateUsername[] = "username";
142static const char kAttributeCandidatePassword[] = "password";
143static const char kAttributeCandidateGeneration[] = "generation";
144static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000145static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000146static const char kAttributeFmtp[] = "fmtp";
147static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000148static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000149static const char kAttributeRtcp[] = "rtcp";
150static const char kAttributeIceUfrag[] = "ice-ufrag";
151static const char kAttributeIcePwd[] = "ice-pwd";
152static const char kAttributeIceLite[] = "ice-lite";
153static const char kAttributeIceOption[] = "ice-options";
154static const char kAttributeSendOnly[] = "sendonly";
155static const char kAttributeRecvOnly[] = "recvonly";
156static const char kAttributeRtcpFb[] = "rtcp-fb";
157static const char kAttributeSendRecv[] = "sendrecv";
158static const char kAttributeInactive[] = "inactive";
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +0000159// draft-ietf-mmusic-sctp-sdp-07
160// a=sctp-port
161static const char kAttributeSctpPort[] = "sctp-port";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000162
163// Experimental flags
164static const char kAttributeXGoogleFlag[] = "x-google-flag";
165static const char kValueConference[] = "conference";
166static const char kAttributeXGoogleBufferLatency[] =
167 "x-google-buffer-latency";
168
169// Candidate
170static const char kCandidateHost[] = "host";
171static const char kCandidateSrflx[] = "srflx";
172// TODO: How to map the prflx with circket candidate type
173// static const char kCandidatePrflx[] = "prflx";
174static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000175static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176
177static const char kSdpDelimiterEqual = '=';
178static const char kSdpDelimiterSpace = ' ';
179static const char kSdpDelimiterColon = ':';
180static const char kSdpDelimiterSemicolon = ';';
181static const char kSdpDelimiterSlash = '/';
182static const char kNewLine = '\n';
183static const char kReturn = '\r';
184static const char kLineBreak[] = "\r\n";
185
186// TODO: Generate the Session and Time description
187// instead of hardcoding.
188static const char kSessionVersion[] = "v=0";
189// RFC 4566
190static const char kSessionOriginUsername[] = "-";
191static const char kSessionOriginSessionId[] = "0";
192static const char kSessionOriginSessionVersion[] = "0";
193static const char kSessionOriginNettype[] = "IN";
194static const char kSessionOriginAddrtype[] = "IP4";
195static const char kSessionOriginAddress[] = "127.0.0.1";
196static const char kSessionName[] = "s=-";
197static const char kTimeDescription[] = "t=0 0";
198static const char kAttrGroup[] = "a=group:BUNDLE";
199static const char kConnectionNettype[] = "IN";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000200static const char kConnectionIpv4Addrtype[] = "IP4";
201static const char kConnectionIpv6Addrtype[] = "IP6";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000202static const char kMediaTypeVideo[] = "video";
203static const char kMediaTypeAudio[] = "audio";
204static const char kMediaTypeData[] = "application";
205static const char kMediaPortRejected[] = "0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000206// draft-ietf-mmusic-trickle-ice-01
207// When no candidates have been gathered, set the connection
208// address to IP6 ::.
perkj@webrtc.orgd105cc82014-11-07 11:22:06 +0000209// TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
210// Use IPV4 per default.
211static const char kDummyAddress[] = "0.0.0.0";
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000212static const char kDummyPort[] = "9";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000213// RFC 3556
214static const char kApplicationSpecificMaximum[] = "AS";
215
216static const int kDefaultVideoClockrate = 90000;
217
218// ISAC special-case.
219static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
220static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
221static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
222
wu@webrtc.org78187522013-10-07 23:32:02 +0000223static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000224
225struct SsrcInfo {
226 SsrcInfo()
227 : msid_identifier(kDefaultMsid),
228 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
229 // Create random string (which will be used as track label later)?
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000230 msid_appdata(rtc::CreateRandomString(8)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000231 }
232 uint32 ssrc_id;
233 std::string cname;
234 std::string msid_identifier;
235 std::string msid_appdata;
236
237 // For backward compatibility.
238 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
239 std::string label;
240 std::string mslabel;
241};
242typedef std::vector<SsrcInfo> SsrcInfoVec;
243typedef std::vector<SsrcGroup> SsrcGroupVec;
244
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000245template <class T>
246static void AddFmtpLine(const T& codec, std::string* message);
247static void BuildMediaDescription(const ContentInfo* content_info,
248 const TransportInfo* transport_info,
249 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000250 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000251 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000252static void BuildSctpContentAttributes(std::string* message, int sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000253static void BuildRtpContentAttributes(
254 const MediaContentDescription* media_desc,
255 const MediaType media_type,
256 std::string* message);
257static void BuildRtpMap(const MediaContentDescription* media_desc,
258 const MediaType media_type,
259 std::string* message);
260static void BuildCandidate(const std::vector<Candidate>& candidates,
261 std::string* message);
262static void BuildIceOptions(const std::vector<std::string>& transport_options,
263 std::string* message);
264
265static bool ParseSessionDescription(const std::string& message, size_t* pos,
266 std::string* session_id,
267 std::string* session_version,
268 bool* supports_msid,
269 TransportDescription* session_td,
270 RtpHeaderExtensions* session_extmaps,
271 cricket::SessionDescription* desc,
272 SdpParseError* error);
273static bool ParseGroupAttribute(const std::string& line,
274 cricket::SessionDescription* desc,
275 SdpParseError* error);
276static bool ParseMediaDescription(
277 const std::string& message,
278 const TransportDescription& session_td,
279 const RtpHeaderExtensions& session_extmaps,
280 bool supports_msid,
281 size_t* pos, cricket::SessionDescription* desc,
282 std::vector<JsepIceCandidate*>* candidates,
283 SdpParseError* error);
284static bool ParseContent(const std::string& message,
285 const MediaType media_type,
286 int mline_index,
287 const std::string& protocol,
288 const std::vector<int>& codec_preference,
289 size_t* pos,
290 std::string* content_name,
291 MediaContentDescription* media_desc,
292 TransportDescription* transport,
293 std::vector<JsepIceCandidate*>* candidates,
294 SdpParseError* error);
295static bool ParseSsrcAttribute(const std::string& line,
296 SsrcInfoVec* ssrc_infos,
297 SdpParseError* error);
298static bool ParseSsrcGroupAttribute(const std::string& line,
299 SsrcGroupVec* ssrc_groups,
300 SdpParseError* error);
301static bool ParseCryptoAttribute(const std::string& line,
302 MediaContentDescription* media_desc,
303 SdpParseError* error);
304static bool ParseRtpmapAttribute(const std::string& line,
305 const MediaType media_type,
306 const std::vector<int>& codec_preference,
307 MediaContentDescription* media_desc,
308 SdpParseError* error);
309static bool ParseFmtpAttributes(const std::string& line,
310 const MediaType media_type,
311 MediaContentDescription* media_desc,
312 SdpParseError* error);
313static bool ParseFmtpParam(const std::string& line, std::string* parameter,
314 std::string* value, SdpParseError* error);
315static bool ParseCandidate(const std::string& message, Candidate* candidate,
316 SdpParseError* error, bool is_raw);
317static bool ParseRtcpFbAttribute(const std::string& line,
318 const MediaType media_type,
319 MediaContentDescription* media_desc,
320 SdpParseError* error);
321static bool ParseIceOptions(const std::string& line,
322 std::vector<std::string>* transport_options,
323 SdpParseError* error);
324static bool ParseExtmap(const std::string& line,
325 RtpHeaderExtension* extmap,
326 SdpParseError* error);
327static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000328 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000329 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000330static bool ParseDtlsSetup(const std::string& line,
331 cricket::ConnectionRole* role,
332 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000333
334// Helper functions
335
336// Below ParseFailed*** functions output the line that caused the parsing
337// failure and the detailed reason (|description|) of the failure to |error|.
338// The functions always return false so that they can be used directly in the
339// following way when error happens:
340// "return ParseFailed***(...);"
341
342// The line starting at |line_start| of |message| is the failing line.
343// The reason for the failure should be provided in the |description|.
344// An example of a description could be "unknown character".
345static bool ParseFailed(const std::string& message,
346 size_t line_start,
347 const std::string& description,
348 SdpParseError* error) {
349 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000350 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000351 size_t line_end = message.find(kNewLine, line_start);
352 if (line_end != std::string::npos) {
353 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
354 --line_end;
355 }
356 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000357 } else {
358 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000359 }
360
361 if (error) {
362 error->line = first_line;
363 error->description = description;
364 }
365 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
366 << "\". Reason: " << description;
367 return false;
368}
369
370// |line| is the failing line. The reason for the failure should be
371// provided in the |description|.
372static bool ParseFailed(const std::string& line,
373 const std::string& description,
374 SdpParseError* error) {
375 return ParseFailed(line, 0, description, error);
376}
377
378// Parses failure where the failing SDP line isn't know or there are multiple
379// failing lines.
380static bool ParseFailed(const std::string& description,
381 SdpParseError* error) {
382 return ParseFailed("", description, error);
383}
384
385// |line| is the failing line. The failure is due to the fact that |line|
386// doesn't have |expected_fields| fields.
387static bool ParseFailedExpectFieldNum(const std::string& line,
388 int expected_fields,
389 SdpParseError* error) {
390 std::ostringstream description;
391 description << "Expects " << expected_fields << " fields.";
392 return ParseFailed(line, description.str(), error);
393}
394
395// |line| is the failing line. The failure is due to the fact that |line| has
396// less than |expected_min_fields| fields.
397static bool ParseFailedExpectMinFieldNum(const std::string& line,
398 int expected_min_fields,
399 SdpParseError* error) {
400 std::ostringstream description;
401 description << "Expects at least " << expected_min_fields << " fields.";
402 return ParseFailed(line, description.str(), error);
403}
404
405// |line| is the failing line. The failure is due to the fact that it failed to
406// get the value of |attribute|.
407static bool ParseFailedGetValue(const std::string& line,
408 const std::string& attribute,
409 SdpParseError* error) {
410 std::ostringstream description;
411 description << "Failed to get the value of attribute: " << attribute;
412 return ParseFailed(line, description.str(), error);
413}
414
415// The line starting at |line_start| of |message| is the failing line. The
416// failure is due to the line type (e.g. the "m" part of the "m-line")
417// not matching what is expected. The expected line type should be
418// provided as |line_type|.
419static bool ParseFailedExpectLine(const std::string& message,
420 size_t line_start,
421 const char line_type,
422 const std::string& line_value,
423 SdpParseError* error) {
424 std::ostringstream description;
425 description << "Expect line: " << line_type << "=" << line_value;
426 return ParseFailed(message, line_start, description.str(), error);
427}
428
429static bool AddLine(const std::string& line, std::string* message) {
430 if (!message)
431 return false;
432
433 message->append(line);
434 message->append(kLineBreak);
435 return true;
436}
437
438static bool GetLine(const std::string& message,
439 size_t* pos,
440 std::string* line) {
441 size_t line_begin = *pos;
442 size_t line_end = message.find(kNewLine, line_begin);
443 if (line_end == std::string::npos) {
444 return false;
445 }
446 // Update the new start position
447 *pos = line_end + 1;
448 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
449 --line_end;
450 }
451 *line = message.substr(line_begin, (line_end - line_begin));
452 const char* cline = line->c_str();
453 // RFC 4566
454 // An SDP session description consists of a number of lines of text of
455 // the form:
456 // <type>=<value>
457 // where <type> MUST be exactly one case-significant character and
458 // <value> is structured text whose format depends on <type>.
459 // Whitespace MUST NOT be used on either side of the "=" sign.
460 if (cline[0] == kSdpDelimiterSpace ||
461 cline[1] != kSdpDelimiterEqual ||
462 cline[2] == kSdpDelimiterSpace) {
463 *pos = line_begin;
464 return false;
465 }
466 return true;
467}
468
469// Init |os| to "|type|=|value|".
470static void InitLine(const char type,
471 const std::string& value,
472 std::ostringstream* os) {
473 os->str("");
474 *os << type << kSdpDelimiterEqual << value;
475}
476
477// Init |os| to "a=|attribute|".
478static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
479 InitLine(kLineTypeAttributes, attribute, os);
480}
481
482// Writes a SDP attribute line based on |attribute| and |value| to |message|.
483static void AddAttributeLine(const std::string& attribute, int value,
484 std::string* message) {
485 std::ostringstream os;
486 InitAttrLine(attribute, &os);
487 os << kSdpDelimiterColon << value;
488 AddLine(os.str(), message);
489}
490
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000491static bool IsLineType(const std::string& message,
492 const char type,
493 size_t line_start) {
494 if (message.size() < line_start + kLinePrefixLength) {
495 return false;
496 }
497 const char* cmessage = message.c_str();
498 return (cmessage[line_start] == type &&
499 cmessage[line_start + 1] == kSdpDelimiterEqual);
500}
501
502static bool IsLineType(const std::string& line,
503 const char type) {
504 return IsLineType(line, type, 0);
505}
506
507static bool GetLineWithType(const std::string& message, size_t* pos,
508 std::string* line, const char type) {
509 if (!IsLineType(message, type, *pos)) {
510 return false;
511 }
512
513 if (!GetLine(message, pos, line))
514 return false;
515
516 return true;
517}
518
519static bool HasAttribute(const std::string& line,
520 const std::string& attribute) {
521 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
522}
523
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000524static bool AddSsrcLine(uint32 ssrc_id, const std::string& attribute,
525 const std::string& value, std::string* message) {
526 // RFC 5576
527 // a=ssrc:<ssrc-id> <attribute>:<value>
528 std::ostringstream os;
529 InitAttrLine(kAttributeSsrc, &os);
530 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
531 << attribute << kSdpDelimiterColon << value;
532 return AddLine(os.str(), message);
533}
534
535// Split the message into two parts by the first delimiter.
536static bool SplitByDelimiter(const std::string& message,
537 const char delimiter,
538 std::string* field1,
539 std::string* field2) {
540 // Find the first delimiter
541 size_t pos = message.find(delimiter);
542 if (pos == std::string::npos) {
543 return false;
544 }
545 *field1 = message.substr(0, pos);
546 // The rest is the value.
547 *field2 = message.substr(pos + 1);
548 return true;
549}
550
551// Get value only from <attribute>:<value>.
552static bool GetValue(const std::string& message, const std::string& attribute,
553 std::string* value, SdpParseError* error) {
554 std::string leftpart;
555 if (!SplitByDelimiter(message, kSdpDelimiterColon, &leftpart, value)) {
556 return ParseFailedGetValue(message, attribute, error);
557 }
558 // The left part should end with the expected attribute.
559 if (leftpart.length() < attribute.length() ||
560 leftpart.compare(leftpart.length() - attribute.length(),
561 attribute.length(), attribute) != 0) {
562 return ParseFailedGetValue(message, attribute, error);
563 }
564 return true;
565}
566
567static bool CaseInsensitiveFind(std::string str1, std::string str2) {
568 std::transform(str1.begin(), str1.end(), str1.begin(),
569 ::tolower);
570 std::transform(str2.begin(), str2.end(), str2.begin(),
571 ::tolower);
572 return str1.find(str2) != std::string::npos;
573}
574
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000575template <class T>
576static bool GetValueFromString(const std::string& line,
577 const std::string& s,
578 T* t,
579 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000580 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000581 std::ostringstream description;
582 description << "Invalid value: " << s << ".";
583 return ParseFailed(line, description.str(), error);
584 }
585 return true;
586}
587
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000588void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
589 StreamParamsVec* tracks) {
590 ASSERT(tracks != NULL);
591 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
592 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
593 if (ssrc_info->cname.empty()) {
594 continue;
595 }
596
597 std::string sync_label;
598 std::string track_id;
599 if (ssrc_info->msid_identifier == kDefaultMsid &&
600 !ssrc_info->mslabel.empty()) {
601 // If there's no msid and there's mslabel, we consider this is a sdp from
602 // a older version of client that doesn't support msid.
603 // In that case, we use the mslabel and label to construct the track.
604 sync_label = ssrc_info->mslabel;
605 track_id = ssrc_info->label;
606 } else {
607 sync_label = ssrc_info->msid_identifier;
608 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
609 // is corresponding to the "id" attribute of StreamParams.
610 track_id = ssrc_info->msid_appdata;
611 }
612 if (sync_label.empty() || track_id.empty()) {
613 ASSERT(false);
614 continue;
615 }
616
617 StreamParamsVec::iterator track = tracks->begin();
618 for (; track != tracks->end(); ++track) {
619 if (track->id == track_id) {
620 break;
621 }
622 }
623 if (track == tracks->end()) {
624 // If we don't find an existing track, create a new one.
625 tracks->push_back(StreamParams());
626 track = tracks->end() - 1;
627 }
628 track->add_ssrc(ssrc_info->ssrc_id);
629 track->cname = ssrc_info->cname;
630 track->sync_label = sync_label;
631 track->id = track_id;
632 }
633}
634
635void GetMediaStreamLabels(const ContentInfo* content,
636 std::set<std::string>* labels) {
637 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000638 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000639 content->description);
640 const cricket::StreamParamsVec& streams = media_desc->streams();
641 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
642 it != streams.end(); ++it) {
643 labels->insert(it->sync_label);
644 }
645}
646
647// RFC 5245
648// It is RECOMMENDED that default candidates be chosen based on the
649// likelihood of those candidates to work with the peer that is being
650// contacted. It is RECOMMENDED that relayed > reflexive > host.
651static const int kPreferenceUnknown = 0;
652static const int kPreferenceHost = 1;
653static const int kPreferenceReflexive = 2;
654static const int kPreferenceRelayed = 3;
655
656static int GetCandidatePreferenceFromType(const std::string& type) {
657 int preference = kPreferenceUnknown;
658 if (type == cricket::LOCAL_PORT_TYPE) {
659 preference = kPreferenceHost;
660 } else if (type == cricket::STUN_PORT_TYPE) {
661 preference = kPreferenceReflexive;
662 } else if (type == cricket::RELAY_PORT_TYPE) {
663 preference = kPreferenceRelayed;
664 } else {
665 ASSERT(false);
666 }
667 return preference;
668}
669
670// Get ip and port of the default destination from the |candidates| with
671// the given value of |component_id|.
672// 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;
684 for (std::vector<Candidate>::const_iterator it = candidates.begin();
685 it != candidates.end(); ++it) {
686 if (it->component() != component_id) {
687 continue;
688 }
689 const int preference = GetCandidatePreferenceFromType(it->type());
690 // See if this candidate is more preferable then the current one.
691 if (preference <= current_preference) {
692 continue;
693 }
694 current_preference = preference;
695 *port = it->address().PortAsString();
696 *ip = it->address().ipaddr().ToString();
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000697 int family = it->address().ipaddr().family();
698 if (family == AF_INET) {
699 addr_type->assign(kConnectionIpv4Addrtype);
700 } else if (family == AF_INET6) {
701 addr_type->assign(kConnectionIpv6Addrtype);
702 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000703 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704}
705
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000706// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000708 const std::vector<Candidate>& candidates,
709 const std::string mline,
710 std::string* message) {
711 std::string new_lines;
712 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000713 // RFC 4566
714 // m=<media> <port> <proto> <fmt> ...
715 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000716 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000717 if (fields.size() < 3) {
718 return;
719 }
720
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000721 std::ostringstream os;
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000722 std::string rtp_port, rtp_ip, addr_type;
723 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
724 &rtp_port, &rtp_ip, &addr_type);
725 // Found default RTP candidate.
726 // RFC 5245
727 // The default candidates are added to the SDP as the default
728 // destination for media. For streams based on RTP, this is done by
729 // placing the IP address and port of the RTP candidate into the c and m
730 // lines, respectively.
731 // Update the port in the m line.
732 // If this is a m-line with port equal to 0, we don't change it.
733 if (fields[1] != kMediaPortRejected) {
734 new_lines.replace(fields[0].size() + 1,
735 fields[1].size(),
736 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000737 }
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000738 // Add the c line.
739 // RFC 4566
740 // c=<nettype> <addrtype> <connection-address>
741 InitLine(kLineTypeConnection, kConnectionNettype, &os);
742 os << " " << addr_type << " " << rtp_ip;
743 AddLine(os.str(), &new_lines);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000744 message->append(new_lines);
745}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000746
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000747// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
748static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000749 std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
750 GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
751 &rtcp_port, &rtcp_ip, &addr_type);
752 // Found default RTCP candidate.
753 // RFC 5245
754 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
755 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +0000757 // RFC 3605
758 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
759 // connection-address] CRLF
760 std::ostringstream os;
761 InitAttrLine(kAttributeRtcp, &os);
762 os << kSdpDelimiterColon
763 << rtcp_port << " "
764 << kConnectionNettype << " "
765 << addr_type << " "
766 << rtcp_ip;
767 rtcp_line = os.str();
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000768 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000769}
770
771// Get candidates according to the mline index from SessionDescriptionInterface.
772static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
773 int mline_index,
774 std::vector<Candidate>* candidates) {
775 if (!candidates) {
776 return;
777 }
778 const IceCandidateCollection* cc = desci.candidates(mline_index);
779 for (size_t i = 0; i < cc->count(); ++i) {
780 const IceCandidateInterface* candidate = cc->at(i);
781 candidates->push_back(candidate->candidate());
782 }
783}
784
785std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000786 const cricket::SessionDescription* desc = jdesc.description();
787 if (!desc) {
788 return "";
789 }
790
791 std::string message;
792
793 // Session Description.
794 AddLine(kSessionVersion, &message);
795 // Session Origin
796 // RFC 4566
797 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
798 // <unicast-address>
799 std::ostringstream os;
800 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
801 const std::string session_id = jdesc.session_id().empty() ?
802 kSessionOriginSessionId : jdesc.session_id();
803 const std::string session_version = jdesc.session_version().empty() ?
804 kSessionOriginSessionVersion : jdesc.session_version();
805 os << " " << session_id << " " << session_version << " "
806 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
807 << kSessionOriginAddress;
808 AddLine(os.str(), &message);
809 AddLine(kSessionName, &message);
810
811 // Time Description.
812 AddLine(kTimeDescription, &message);
813
814 // Group
815 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
816 std::string group_line = kAttrGroup;
817 const cricket::ContentGroup* group =
818 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
819 ASSERT(group != NULL);
820 const cricket::ContentNames& content_names = group->content_names();
821 for (cricket::ContentNames::const_iterator it = content_names.begin();
822 it != content_names.end(); ++it) {
823 group_line.append(" ");
824 group_line.append(*it);
825 }
826 AddLine(group_line, &message);
827 }
828
829 // MediaStream semantics
830 InitAttrLine(kAttributeMsidSemantics, &os);
831 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000832
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000833 std::set<std::string> media_stream_labels;
834 const ContentInfo* audio_content = GetFirstAudioContent(desc);
835 if (audio_content)
836 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000837
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000838 const ContentInfo* video_content = GetFirstVideoContent(desc);
839 if (video_content)
840 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000841
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842 for (std::set<std::string>::const_iterator it =
843 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
844 os << " " << *it;
845 }
846 AddLine(os.str(), &message);
847
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000848 // Preserve the order of the media contents.
849 int mline_index = -1;
850 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
851 it != desc->contents().end(); ++it) {
852 const MediaContentDescription* mdesc =
853 static_cast<const MediaContentDescription*>(it->description);
854 std::vector<Candidate> candidates;
855 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
856 BuildMediaDescription(&*it,
857 desc->GetTransportInfoByName(it->name),
858 mdesc->type(),
859 candidates,
860 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000861 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000862 return message;
863}
864
865// Serializes the passed in IceCandidateInterface to a SDP string.
866// candidate - The candidate to be serialized.
867std::string SdpSerializeCandidate(
868 const IceCandidateInterface& candidate) {
869 std::string message;
870 std::vector<cricket::Candidate> candidates;
871 candidates.push_back(candidate.candidate());
872 BuildCandidate(candidates, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000873 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
874 // just candidate:<candidate> not a=candidate:<blah>CRLF
875 ASSERT(message.find("a=") == 0);
876 message.erase(0, 2);
877 ASSERT(message.find(kLineBreak) == message.size() - 2);
878 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879 return message;
880}
881
882bool SdpDeserialize(const std::string& message,
883 JsepSessionDescription* jdesc,
884 SdpParseError* error) {
885 std::string session_id;
886 std::string session_version;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000887 TransportDescription session_td(NS_JINGLE_ICE_UDP,
888 std::string(), std::string());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000889 RtpHeaderExtensions session_extmaps;
890 cricket::SessionDescription* desc = new cricket::SessionDescription();
891 std::vector<JsepIceCandidate*> candidates;
892 size_t current_pos = 0;
893 bool supports_msid = false;
894
895 // Session Description
896 if (!ParseSessionDescription(message, &current_pos, &session_id,
897 &session_version, &supports_msid, &session_td,
898 &session_extmaps, desc, error)) {
899 delete desc;
900 return false;
901 }
902
903 // Media Description
904 if (!ParseMediaDescription(message, session_td, session_extmaps,
905 supports_msid, &current_pos, desc, &candidates,
906 error)) {
907 delete desc;
908 for (std::vector<JsepIceCandidate*>::const_iterator
909 it = candidates.begin(); it != candidates.end(); ++it) {
910 delete *it;
911 }
912 return false;
913 }
914
915 jdesc->Initialize(desc, session_id, session_version);
916
917 for (std::vector<JsepIceCandidate*>::const_iterator
918 it = candidates.begin(); it != candidates.end(); ++it) {
919 jdesc->AddCandidate(*it);
920 delete *it;
921 }
922 return true;
923}
924
925bool SdpDeserializeCandidate(const std::string& message,
926 JsepIceCandidate* jcandidate,
927 SdpParseError* error) {
928 ASSERT(jcandidate != NULL);
929 Candidate candidate;
930 if (!ParseCandidate(message, &candidate, error, true)) {
931 return false;
932 }
933 jcandidate->SetCandidate(candidate);
934 return true;
935}
936
937bool ParseCandidate(const std::string& message, Candidate* candidate,
938 SdpParseError* error, bool is_raw) {
939 ASSERT(candidate != NULL);
940
941 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000942 std::string first_line = message;
943 size_t pos = 0;
944 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000946 // Makes sure |message| contains only one line.
947 if (message.size() > first_line.size()) {
948 std::string left, right;
949 if (SplitByDelimiter(message, kNewLine, &left, &right) && !right.empty()) {
950 return ParseFailed(message, 0, "Expect one line only", error);
951 }
952 }
953
954 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
955 // candidate:<candidate> when trickled, but we still support
956 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
957 // from the SDP.
958 if (IsLineType(first_line, kLineTypeAttributes)) {
959 first_line = first_line.substr(kLinePrefixLength);
960 }
961
962 std::string attribute_candidate;
963 std::string candidate_value;
964
965 // |first_line| must be in the form of "candidate:<value>".
966 if (!SplitByDelimiter(first_line, kSdpDelimiterColon,
967 &attribute_candidate, &candidate_value) ||
968 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969 if (is_raw) {
970 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000971 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000972 << ":" << "<candidate-str>";
973 return ParseFailed(first_line, 0, description.str(), error);
974 } else {
975 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
976 kAttributeCandidate, error);
977 }
978 }
979
980 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000981 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
982
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000983 // RFC 5245
984 // a=candidate:<foundation> <component-id> <transport> <priority>
985 // <connection-address> <port> typ <candidate-types>
986 // [raddr <connection-address>] [rport <port>]
987 // *(SP extension-att-name SP extension-att-value)
988 const size_t expected_min_fields = 8;
989 if (fields.size() < expected_min_fields ||
990 (fields[6] != kAttributeCandidateTyp)) {
991 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
992 }
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000993 std::string foundation = fields[0];
994
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000995 int component_id = 0;
996 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
997 return false;
998 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999 const std::string transport = fields[2];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001000 uint32 priority = 0;
1001 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1002 return false;
1003 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001004 const std::string connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001005 int port = 0;
1006 if (!GetValueFromString(first_line, fields[5], &port, error)) {
1007 return false;
1008 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009 SocketAddress address(connection_address, port);
1010
1011 cricket::ProtocolType protocol;
1012 if (!StringToProto(transport.c_str(), &protocol)) {
1013 return ParseFailed(first_line, "Unsupported transport type.", error);
1014 }
1015
1016 std::string candidate_type;
1017 const std::string type = fields[7];
1018 if (type == kCandidateHost) {
1019 candidate_type = cricket::LOCAL_PORT_TYPE;
1020 } else if (type == kCandidateSrflx) {
1021 candidate_type = cricket::STUN_PORT_TYPE;
1022 } else if (type == kCandidateRelay) {
1023 candidate_type = cricket::RELAY_PORT_TYPE;
1024 } else {
1025 return ParseFailed(first_line, "Unsupported candidate type.", error);
1026 }
1027
1028 size_t current_position = expected_min_fields;
1029 SocketAddress related_address;
1030 // The 2 optional fields for related address
1031 // [raddr <connection-address>] [rport <port>]
1032 if (fields.size() >= (current_position + 2) &&
1033 fields[current_position] == kAttributeCandidateRaddr) {
1034 related_address.SetIP(fields[++current_position]);
1035 ++current_position;
1036 }
1037 if (fields.size() >= (current_position + 2) &&
1038 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001039 int port = 0;
1040 if (!GetValueFromString(
1041 first_line, fields[++current_position], &port, error)) {
1042 return false;
1043 }
1044 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001045 ++current_position;
1046 }
1047
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001048 // If this is a TCP candidate, it has additional extension as defined in
1049 // RFC 6544.
1050 std::string tcptype;
1051 if (fields.size() >= (current_position + 2) &&
1052 fields[current_position] == kTcpCandidateType) {
1053 tcptype = fields[++current_position];
1054 ++current_position;
1055
1056 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1057 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1058 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1059 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1060 }
1061
1062 if (protocol != cricket::PROTO_TCP) {
1063 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1064 }
1065 }
1066
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001067 // Extension
1068 // Empty string as the candidate username and password.
1069 // Will be updated later with the ice-ufrag and ice-pwd.
1070 // TODO: Remove the username/password extension, which is currently
1071 // kept for backwards compatibility.
1072 std::string username;
1073 std::string password;
1074 uint32 generation = 0;
1075 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1076 // RFC 5245
1077 // *(SP extension-att-name SP extension-att-value)
1078 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001079 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1080 return false;
1081 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082 } else if (fields[i] == kAttributeCandidateUsername) {
1083 username = fields[++i];
1084 } else if (fields[i] == kAttributeCandidatePassword) {
1085 password = fields[++i];
1086 } else {
1087 // Skip the unknown extension.
1088 ++i;
1089 }
1090 }
1091
1092 // Empty string as the candidate id and network name.
1093 const std::string id;
1094 const std::string network_name;
1095 *candidate = Candidate(id, component_id, cricket::ProtoToString(protocol),
1096 address, priority, username, password, candidate_type, network_name,
1097 generation, foundation);
1098 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001099 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001100 return true;
1101}
1102
1103bool ParseIceOptions(const std::string& line,
1104 std::vector<std::string>* transport_options,
1105 SdpParseError* error) {
1106 std::string ice_options;
1107 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1108 return false;
1109 }
1110 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001111 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112 for (size_t i = 0; i < fields.size(); ++i) {
1113 transport_options->push_back(fields[i]);
1114 }
1115 return true;
1116}
1117
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001118bool ParseSctpPort(const std::string& line,
1119 int* sctp_port,
1120 SdpParseError* error) {
1121 // draft-ietf-mmusic-sctp-sdp-07
1122 // a=sctp-port
1123 std::vector<std::string> fields;
1124 rtc::split(line.substr(kLinePrefixLength),
1125 kSdpDelimiterSpace, &fields);
1126 const size_t expected_min_fields = 2;
1127 if (fields.size() < expected_min_fields) {
1128 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1129 }
1130 if (!rtc::FromString(fields[1], sctp_port)) {
1131 return ParseFailed(line,
1132 "Invalid sctp port value.",
1133 error);
1134 }
1135 return true;
1136}
1137
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001138bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1139 SdpParseError* error) {
1140 // RFC 5285
1141 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1142 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001143 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001144 kSdpDelimiterSpace, &fields);
1145 const size_t expected_min_fields = 2;
1146 if (fields.size() < expected_min_fields) {
1147 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1148 }
1149 std::string uri = fields[1];
1150
1151 std::string value_direction;
1152 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1153 return false;
1154 }
1155 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001156 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001157 int value = 0;
1158 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1159 return false;
1160 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001161
1162 *extmap = RtpHeaderExtension(uri, value);
1163 return true;
1164}
1165
1166void BuildMediaDescription(const ContentInfo* content_info,
1167 const TransportInfo* transport_info,
1168 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001169 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001170 std::string* message) {
1171 ASSERT(message != NULL);
1172 if (content_info == NULL || message == NULL) {
1173 return;
1174 }
1175 // TODO: Rethink if we should use sprintfn instead of stringstream.
1176 // According to the style guide, streams should only be used for logging.
1177 // http://google-styleguide.googlecode.com/svn/
1178 // trunk/cppguide.xml?showone=Streams#Streams
1179 std::ostringstream os;
1180 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001181 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001182 content_info->description);
1183 ASSERT(media_desc != NULL);
1184
1185 bool is_sctp = (media_desc->protocol() == cricket::kMediaProtocolDtlsSctp);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001186 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001187
1188 // RFC 4566
1189 // m=<media> <port> <proto> <fmt>
1190 // fmt is a list of payload type numbers that MAY be used in the session.
1191 const char* type = NULL;
1192 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1193 type = kMediaTypeAudio;
1194 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1195 type = kMediaTypeVideo;
1196 else if (media_type == cricket::MEDIA_TYPE_DATA)
1197 type = kMediaTypeData;
1198 else
1199 ASSERT(false);
1200
1201 std::string fmt;
1202 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1203 const VideoContentDescription* video_desc =
1204 static_cast<const VideoContentDescription*>(media_desc);
1205 for (std::vector<cricket::VideoCodec>::const_iterator it =
1206 video_desc->codecs().begin();
1207 it != video_desc->codecs().end(); ++it) {
1208 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001209 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001210 }
1211 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1212 const AudioContentDescription* audio_desc =
1213 static_cast<const AudioContentDescription*>(media_desc);
1214 for (std::vector<cricket::AudioCodec>::const_iterator it =
1215 audio_desc->codecs().begin();
1216 it != audio_desc->codecs().end(); ++it) {
1217 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001218 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001219 }
1220 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001221 const DataContentDescription* data_desc =
1222 static_cast<const DataContentDescription*>(media_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001223 if (is_sctp) {
1224 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001225
1226 for (std::vector<cricket::DataCodec>::const_iterator it =
1227 data_desc->codecs().begin();
1228 it != data_desc->codecs().end(); ++it) {
1229 if (it->id == cricket::kGoogleSctpDataCodecId &&
1230 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1231 break;
1232 }
1233 }
1234
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001235 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001236 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001237 for (std::vector<cricket::DataCodec>::const_iterator it =
1238 data_desc->codecs().begin();
1239 it != data_desc->codecs().end(); ++it) {
1240 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001241 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001242 }
1243 }
1244 }
1245 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1246 // to 0.
1247 if (fmt.empty()) {
1248 fmt = " 0";
1249 }
1250
1251 // The port number in the m line will be updated later when associate with
1252 // the candidates.
1253 // RFC 3264
1254 // To reject an offered stream, the port number in the corresponding stream in
1255 // the answer MUST be set to zero.
1256 const std::string port = content_info->rejected ?
pthatcher@webrtc.orgc9d6d142014-10-23 23:37:22 +00001257 kMediaPortRejected : kDummyPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001259 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001260 transport_info->description.identity_fingerprint.get() : NULL;
1261
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001262 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001263 InitLine(kLineTypeMedia, type, &os);
1264 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001265 std::string mline = os.str();
1266 UpdateMediaDefaultDestination(candidates, mline, message);
1267
1268 // RFC 4566
1269 // b=AS:<bandwidth>
1270 // We should always use the default bandwidth for RTP-based data
1271 // channels. Don't allow SDP to set the bandwidth, because that
1272 // would give JS the opportunity to "break the Internet".
1273 // TODO(pthatcher): But we need to temporarily allow the SDP to control
1274 // this for backwards-compatibility. Once we don't need that any
1275 // more, remove this.
1276 bool support_dc_sdp_bandwidth_temporarily = true;
1277 if (media_desc->bandwidth() >= 1000 &&
1278 (media_type != cricket::MEDIA_TYPE_DATA ||
1279 support_dc_sdp_bandwidth_temporarily)) {
1280 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1281 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1282 AddLine(os.str(), message);
1283 }
1284
1285 // Add the a=rtcp line.
1286 bool is_rtp =
1287 media_desc->protocol().empty() ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001288 rtc::starts_with(media_desc->protocol().data(),
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001289 cricket::kMediaProtocolRtpPrefix);
1290 if (is_rtp) {
1291 std::string rtcp_line = GetRtcpLine(candidates);
1292 if (!rtcp_line.empty()) {
1293 AddLine(rtcp_line, message);
1294 }
1295 }
1296
1297 // Build the a=candidate lines.
1298 BuildCandidate(candidates, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299
1300 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1301 if (transport_info) {
1302 // RFC 5245
1303 // ice-pwd-att = "ice-pwd" ":" password
1304 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1305 // ice-ufrag
1306 InitAttrLine(kAttributeIceUfrag, &os);
1307 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1308 AddLine(os.str(), message);
1309 // ice-pwd
1310 InitAttrLine(kAttributeIcePwd, &os);
1311 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1312 AddLine(os.str(), message);
1313
1314 // draft-petithuguenin-mmusic-ice-attributes-level-03
1315 BuildIceOptions(transport_info->description.transport_options, message);
1316
1317 // RFC 4572
1318 // fingerprint-attribute =
1319 // "fingerprint" ":" hash-func SP fingerprint
1320 if (fp) {
1321 // Insert the fingerprint attribute.
1322 InitAttrLine(kAttributeFingerprint, &os);
1323 os << kSdpDelimiterColon
1324 << fp->algorithm << kSdpDelimiterSpace
1325 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001327
1328 // Inserting setup attribute.
1329 if (transport_info->description.connection_role !=
1330 cricket::CONNECTIONROLE_NONE) {
1331 // Making sure we are not using "passive" mode.
1332 cricket::ConnectionRole role =
1333 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001334 std::string dtls_role_str;
1335 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001336 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001337 os << kSdpDelimiterColon << dtls_role_str;
1338 AddLine(os.str(), message);
1339 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001340 }
1341 }
1342
1343 // RFC 3388
1344 // mid-attribute = "a=mid:" identification-tag
1345 // identification-tag = token
1346 // Use the content name as the mid identification-tag.
1347 InitAttrLine(kAttributeMid, &os);
1348 os << kSdpDelimiterColon << content_info->name;
1349 AddLine(os.str(), message);
1350
1351 if (is_sctp) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001352 BuildSctpContentAttributes(message, sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353 } else {
1354 BuildRtpContentAttributes(media_desc, media_type, message);
1355 }
1356}
1357
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001358void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001359 // draft-ietf-mmusic-sctp-sdp-04
1360 // a=sctpmap:sctpmap-number protocol [streams]
1361 std::ostringstream os;
1362 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001363 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001364 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1365 << (cricket::kMaxSctpSid + 1);
1366 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001367}
1368
1369void BuildRtpContentAttributes(
1370 const MediaContentDescription* media_desc,
1371 const MediaType media_type,
1372 std::string* message) {
1373 std::ostringstream os;
1374 // RFC 5285
1375 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1376 // The definitions MUST be either all session level or all media level. This
1377 // implementation uses all media level.
1378 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1379 InitAttrLine(kAttributeExtmap, &os);
1380 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1381 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1382 AddLine(os.str(), message);
1383 }
1384
1385 // RFC 3264
1386 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
1387
1388 cricket::MediaContentDirection direction = media_desc->direction();
1389 if (media_desc->streams().empty() && direction == cricket::MD_SENDRECV) {
1390 direction = cricket::MD_RECVONLY;
1391 }
1392
1393 switch (direction) {
1394 case cricket::MD_INACTIVE:
1395 InitAttrLine(kAttributeInactive, &os);
1396 break;
1397 case cricket::MD_SENDONLY:
1398 InitAttrLine(kAttributeSendOnly, &os);
1399 break;
1400 case cricket::MD_RECVONLY:
1401 InitAttrLine(kAttributeRecvOnly, &os);
1402 break;
1403 case cricket::MD_SENDRECV:
1404 default:
1405 InitAttrLine(kAttributeSendRecv, &os);
1406 break;
1407 }
1408 AddLine(os.str(), message);
1409
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001410 // RFC 5761
1411 // a=rtcp-mux
1412 if (media_desc->rtcp_mux()) {
1413 InitAttrLine(kAttributeRtcpMux, &os);
1414 AddLine(os.str(), message);
1415 }
1416
1417 // RFC 4568
1418 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1419 for (std::vector<CryptoParams>::const_iterator it =
1420 media_desc->cryptos().begin();
1421 it != media_desc->cryptos().end(); ++it) {
1422 InitAttrLine(kAttributeCrypto, &os);
1423 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1424 << it->key_params;
1425 if (!it->session_params.empty()) {
1426 os << " " << it->session_params;
1427 }
1428 AddLine(os.str(), message);
1429 }
1430
1431 // RFC 4566
1432 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1433 // [/<encodingparameters>]
1434 BuildRtpMap(media_desc, media_type, message);
1435
1436 // Specify latency for buffered mode.
1437 // a=x-google-buffer-latency:<value>
1438 if (media_desc->buffered_mode_latency() != cricket::kBufferedModeDisabled) {
1439 std::ostringstream os;
1440 InitAttrLine(kAttributeXGoogleBufferLatency, &os);
1441 os << kSdpDelimiterColon << media_desc->buffered_mode_latency();
1442 AddLine(os.str(), message);
1443 }
1444
1445 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1446 track != media_desc->streams().end(); ++track) {
1447 // Require that the track belongs to a media stream,
1448 // ie the sync_label is set. This extra check is necessary since the
1449 // MediaContentDescription always contains a streamparam with an ssrc even
1450 // if no track or media stream have been created.
1451 if (track->sync_label.empty()) continue;
1452
1453 // Build the ssrc-group lines.
1454 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1455 // RFC 5576
1456 // a=ssrc-group:<semantics> <ssrc-id> ...
1457 if (track->ssrc_groups[i].ssrcs.empty()) {
1458 continue;
1459 }
1460 std::ostringstream os;
1461 InitAttrLine(kAttributeSsrcGroup, &os);
1462 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
1463 std::vector<uint32>::const_iterator ssrc =
1464 track->ssrc_groups[i].ssrcs.begin();
1465 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001466 os << kSdpDelimiterSpace << rtc::ToString<uint32>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001467 }
1468 AddLine(os.str(), message);
1469 }
1470 // Build the ssrc lines for each ssrc.
1471 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
1472 uint32 ssrc = track->ssrcs[i];
1473 // RFC 5576
1474 // a=ssrc:<ssrc-id> cname:<value>
1475 AddSsrcLine(ssrc, kSsrcAttributeCname,
1476 track->cname, message);
1477
1478 // draft-alvestrand-mmusic-msid-00
1479 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1480 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1481 // is corresponding to the "name" attribute of StreamParams.
1482 std::string appdata = track->id;
1483 std::ostringstream os;
1484 InitAttrLine(kAttributeSsrc, &os);
1485 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1486 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1487 << kSdpDelimiterSpace << appdata;
1488 AddLine(os.str(), message);
1489
1490 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1491 // draft-alvestrand-rtcweb-mid-01
1492 // a=ssrc:<ssrc-id> mslabel:<value>
1493 // The label isn't yet defined.
1494 // a=ssrc:<ssrc-id> label:<value>
1495 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1496 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1497 }
1498 }
1499}
1500
1501void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1502 // fmtp header: a=fmtp:|payload_type| <parameters>
1503 // Add a=fmtp
1504 InitAttrLine(kAttributeFmtp, os);
1505 // Add :|payload_type|
1506 *os << kSdpDelimiterColon << payload_type;
1507}
1508
1509void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1510 // rtcp-fb header: a=rtcp-fb:|payload_type|
1511 // <parameters>/<ccm <ccm_parameters>>
1512 // Add a=rtcp-fb
1513 InitAttrLine(kAttributeRtcpFb, os);
1514 // Add :
1515 *os << kSdpDelimiterColon;
1516 if (payload_type == kWildcardPayloadType) {
1517 *os << "*";
1518 } else {
1519 *os << payload_type;
1520 }
1521}
1522
1523void WriteFmtpParameter(const std::string& parameter_name,
1524 const std::string& parameter_value,
1525 std::ostringstream* os) {
1526 // fmtp parameters: |parameter_name|=|parameter_value|
1527 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1528}
1529
1530void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1531 std::ostringstream* os) {
1532 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1533 fmtp != parameters.end(); ++fmtp) {
1534 // Each new parameter, except the first one starts with ";" and " ".
1535 if (fmtp != parameters.begin()) {
1536 *os << kSdpDelimiterSemicolon;
1537 }
1538 *os << kSdpDelimiterSpace;
1539 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1540 }
1541}
1542
1543bool IsFmtpParam(const std::string& name) {
1544 const char* kFmtpParams[] = {
1545 kCodecParamMinPTime, kCodecParamSPropStereo,
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +00001546 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamStartBitrate,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547 kCodecParamMaxBitrate, kCodecParamMinBitrate, kCodecParamMaxQuantization,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001548 kCodecParamSctpProtocol, kCodecParamSctpStreams,
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001549 kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
1550 kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001551 };
1552 for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
1553 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1554 return true;
1555 }
1556 }
1557 return false;
1558}
1559
1560// Retreives fmtp parameters from |params|, which may contain other parameters
1561// as well, and puts them in |fmtp_parameters|.
1562void GetFmtpParams(const cricket::CodecParameterMap& params,
1563 cricket::CodecParameterMap* fmtp_parameters) {
1564 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1565 iter != params.end(); ++iter) {
1566 if (IsFmtpParam(iter->first)) {
1567 (*fmtp_parameters)[iter->first] = iter->second;
1568 }
1569 }
1570}
1571
1572template <class T>
1573void AddFmtpLine(const T& codec, std::string* message) {
1574 cricket::CodecParameterMap fmtp_parameters;
1575 GetFmtpParams(codec.params, &fmtp_parameters);
1576 if (fmtp_parameters.empty()) {
1577 // No need to add an fmtp if it will have no (optional) parameters.
1578 return;
1579 }
1580 std::ostringstream os;
1581 WriteFmtpHeader(codec.id, &os);
1582 WriteFmtpParameters(fmtp_parameters, &os);
1583 AddLine(os.str(), message);
1584 return;
1585}
1586
1587template <class T>
1588void AddRtcpFbLines(const T& codec, std::string* message) {
1589 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1590 codec.feedback_params.params().begin();
1591 iter != codec.feedback_params.params().end(); ++iter) {
1592 std::ostringstream os;
1593 WriteRtcpFbHeader(codec.id, &os);
1594 os << " " << iter->id();
1595 if (!iter->param().empty()) {
1596 os << " " << iter->param();
1597 }
1598 AddLine(os.str(), message);
1599 }
1600}
1601
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00001602bool AddSctpDataCodec(DataContentDescription* media_desc,
1603 int sctp_port) {
1604 if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
1605 return ParseFailed("",
1606 "Can't have multiple sctp port attributes.",
1607 NULL);
1608 }
1609 // Add the SCTP Port number as a pseudo-codec "port" parameter
1610 cricket::DataCodec codec_port(
1611 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
1612 0);
1613 codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
1614 LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
1615 << sctp_port;
1616 media_desc->AddCodec(codec_port);
1617 return true;
1618}
1619
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001620bool GetMinValue(const std::vector<int>& values, int* value) {
1621 if (values.empty()) {
1622 return false;
1623 }
1624 std::vector<int>::const_iterator found =
1625 std::min_element(values.begin(), values.end());
1626 *value = *found;
1627 return true;
1628}
1629
1630bool GetParameter(const std::string& name,
1631 const cricket::CodecParameterMap& params, int* value) {
1632 std::map<std::string, std::string>::const_iterator found =
1633 params.find(name);
1634 if (found == params.end()) {
1635 return false;
1636 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001637 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001638 return false;
1639 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001640 return true;
1641}
1642
1643void BuildRtpMap(const MediaContentDescription* media_desc,
1644 const MediaType media_type,
1645 std::string* message) {
1646 ASSERT(message != NULL);
1647 ASSERT(media_desc != NULL);
1648 std::ostringstream os;
1649 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1650 const VideoContentDescription* video_desc =
1651 static_cast<const VideoContentDescription*>(media_desc);
1652 for (std::vector<cricket::VideoCodec>::const_iterator it =
1653 video_desc->codecs().begin();
1654 it != video_desc->codecs().end(); ++it) {
1655 // RFC 4566
1656 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1657 // [/<encodingparameters>]
1658 if (it->id != kWildcardPayloadType) {
1659 InitAttrLine(kAttributeRtpmap, &os);
1660 os << kSdpDelimiterColon << it->id << " " << it->name
1661 << "/" << kDefaultVideoClockrate;
1662 AddLine(os.str(), message);
1663 }
1664 AddRtcpFbLines(*it, message);
1665 AddFmtpLine(*it, message);
1666 }
1667 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1668 const AudioContentDescription* audio_desc =
1669 static_cast<const AudioContentDescription*>(media_desc);
1670 std::vector<int> ptimes;
1671 std::vector<int> maxptimes;
1672 int max_minptime = 0;
1673 for (std::vector<cricket::AudioCodec>::const_iterator it =
1674 audio_desc->codecs().begin();
1675 it != audio_desc->codecs().end(); ++it) {
1676 ASSERT(!it->name.empty());
1677 // RFC 4566
1678 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1679 // [/<encodingparameters>]
1680 InitAttrLine(kAttributeRtpmap, &os);
1681 os << kSdpDelimiterColon << it->id << " ";
1682 os << it->name << "/" << it->clockrate;
1683 if (it->channels != 1) {
1684 os << "/" << it->channels;
1685 }
1686 AddLine(os.str(), message);
1687 AddRtcpFbLines(*it, message);
1688 AddFmtpLine(*it, message);
1689 int minptime = 0;
1690 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1691 max_minptime = std::max(minptime, max_minptime);
1692 }
1693 int ptime;
1694 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1695 ptimes.push_back(ptime);
1696 }
1697 int maxptime;
1698 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1699 maxptimes.push_back(maxptime);
1700 }
1701 }
1702 // Populate the maxptime attribute with the smallest maxptime of all codecs
1703 // under the same m-line.
1704 int min_maxptime = INT_MAX;
1705 if (GetMinValue(maxptimes, &min_maxptime)) {
1706 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1707 }
1708 ASSERT(min_maxptime > max_minptime);
1709 // Populate the ptime attribute with the smallest ptime or the largest
1710 // minptime, whichever is the largest, for all codecs under the same m-line.
1711 int ptime = INT_MAX;
1712 if (GetMinValue(ptimes, &ptime)) {
1713 ptime = std::min(ptime, min_maxptime);
1714 ptime = std::max(ptime, max_minptime);
1715 AddAttributeLine(kCodecParamPTime, ptime, message);
1716 }
1717 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1718 const DataContentDescription* data_desc =
1719 static_cast<const DataContentDescription*>(media_desc);
1720 for (std::vector<cricket::DataCodec>::const_iterator it =
1721 data_desc->codecs().begin();
1722 it != data_desc->codecs().end(); ++it) {
1723 // RFC 4566
1724 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1725 // [/<encodingparameters>]
1726 InitAttrLine(kAttributeRtpmap, &os);
1727 os << kSdpDelimiterColon << it->id << " "
1728 << it->name << "/" << it->clockrate;
1729 AddLine(os.str(), message);
1730 }
1731 }
1732}
1733
1734void BuildCandidate(const std::vector<Candidate>& candidates,
1735 std::string* message) {
1736 std::ostringstream os;
1737
1738 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1739 it != candidates.end(); ++it) {
1740 // RFC 5245
1741 // a=candidate:<foundation> <component-id> <transport> <priority>
1742 // <connection-address> <port> typ <candidate-types>
1743 // [raddr <connection-address>] [rport <port>]
1744 // *(SP extension-att-name SP extension-att-value)
1745 std::string type;
1746 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1747 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1748 type = kCandidateHost;
1749 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1750 type = kCandidateSrflx;
1751 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1752 type = kCandidateRelay;
1753 } else {
1754 ASSERT(false);
1755 }
1756
1757 InitAttrLine(kAttributeCandidate, &os);
1758 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001759 << it->foundation() << " "
1760 << it->component() << " "
1761 << it->protocol() << " "
1762 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001763 << it->address().ipaddr().ToString() << " "
1764 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001765 << kAttributeCandidateTyp << " "
1766 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001767
1768 // Related address
1769 if (!it->related_address().IsNil()) {
1770 os << kAttributeCandidateRaddr << " "
1771 << it->related_address().ipaddr().ToString() << " "
1772 << kAttributeCandidateRport << " "
1773 << it->related_address().PortAsString() << " ";
1774 }
1775
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001776 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001777 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001778 }
1779
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001780 // Extensions
1781 os << kAttributeCandidateGeneration << " " << it->generation();
1782
1783 AddLine(os.str(), message);
1784 }
1785}
1786
1787void BuildIceOptions(const std::vector<std::string>& transport_options,
1788 std::string* message) {
1789 if (!transport_options.empty()) {
1790 std::ostringstream os;
1791 InitAttrLine(kAttributeIceOption, &os);
1792 os << kSdpDelimiterColon << transport_options[0];
1793 for (size_t i = 1; i < transport_options.size(); ++i) {
1794 os << kSdpDelimiterSpace << transport_options[i];
1795 }
1796 AddLine(os.str(), message);
1797 }
1798}
1799
1800bool ParseSessionDescription(const std::string& message, size_t* pos,
1801 std::string* session_id,
1802 std::string* session_version,
1803 bool* supports_msid,
1804 TransportDescription* session_td,
1805 RtpHeaderExtensions* session_extmaps,
1806 cricket::SessionDescription* desc,
1807 SdpParseError* error) {
1808 std::string line;
1809
1810 // RFC 4566
1811 // v= (protocol version)
1812 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1813 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1814 std::string(), error);
1815 }
1816 // RFC 4566
1817 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1818 // <unicast-address>
1819 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1820 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1821 std::string(), error);
1822 }
1823 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001824 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001825 kSdpDelimiterSpace, &fields);
1826 const size_t expected_fields = 6;
1827 if (fields.size() != expected_fields) {
1828 return ParseFailedExpectFieldNum(line, expected_fields, error);
1829 }
1830 *session_id = fields[1];
1831 *session_version = fields[2];
1832
1833 // RFC 4566
1834 // s= (session name)
1835 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1836 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1837 std::string(), error);
1838 }
1839
1840 // Optional lines
1841 // Those are the optional lines, so shouldn't return false if not present.
1842 // RFC 4566
1843 // i=* (session information)
1844 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1845
1846 // RFC 4566
1847 // u=* (URI of description)
1848 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1849
1850 // RFC 4566
1851 // e=* (email address)
1852 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1853
1854 // RFC 4566
1855 // p=* (phone number)
1856 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1857
1858 // RFC 4566
1859 // c=* (connection information -- not required if included in
1860 // all media)
1861 GetLineWithType(message, pos, &line, kLineTypeConnection);
1862
1863 // RFC 4566
1864 // b=* (zero or more bandwidth information lines)
1865 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1866 // By pass zero or more b lines.
1867 }
1868
1869 // RFC 4566
1870 // One or more time descriptions ("t=" and "r=" lines; see below)
1871 // t= (time the session is active)
1872 // r=* (zero or more repeat times)
1873 // Ensure there's at least one time description
1874 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1875 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1876 error);
1877 }
1878
1879 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1880 // By pass zero or more r lines.
1881 }
1882
1883 // Go through the rest of the time descriptions
1884 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1885 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1886 // By pass zero or more r lines.
1887 }
1888 }
1889
1890 // RFC 4566
1891 // z=* (time zone adjustments)
1892 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1893
1894 // RFC 4566
1895 // k=* (encryption key)
1896 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1897
1898 // RFC 4566
1899 // a=* (zero or more session attribute lines)
1900 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1901 if (HasAttribute(line, kAttributeGroup)) {
1902 if (!ParseGroupAttribute(line, desc, error)) {
1903 return false;
1904 }
1905 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1906 if (!GetValue(line, kAttributeIceUfrag,
1907 &(session_td->ice_ufrag), error)) {
1908 return false;
1909 }
1910 } else if (HasAttribute(line, kAttributeIcePwd)) {
1911 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1912 return false;
1913 }
1914 } else if (HasAttribute(line, kAttributeIceLite)) {
1915 session_td->ice_mode = cricket::ICEMODE_LITE;
1916 } else if (HasAttribute(line, kAttributeIceOption)) {
1917 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1918 return false;
1919 }
1920 } else if (HasAttribute(line, kAttributeFingerprint)) {
1921 if (session_td->identity_fingerprint.get()) {
1922 return ParseFailed(
1923 line,
1924 "Can't have multiple fingerprint attributes at the same level.",
1925 error);
1926 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001927 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1929 return false;
1930 }
1931 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001932 } else if (HasAttribute(line, kAttributeSetup)) {
1933 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1934 return false;
1935 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001936 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1937 std::string semantics;
1938 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1939 return false;
1940 }
1941 *supports_msid = CaseInsensitiveFind(semantics, kMediaStreamSemantic);
1942 } else if (HasAttribute(line, kAttributeExtmap)) {
1943 RtpHeaderExtension extmap;
1944 if (!ParseExtmap(line, &extmap, error)) {
1945 return false;
1946 }
1947 session_extmaps->push_back(extmap);
1948 }
1949 }
1950
1951 return true;
1952}
1953
1954bool ParseGroupAttribute(const std::string& line,
1955 cricket::SessionDescription* desc,
1956 SdpParseError* error) {
1957 ASSERT(desc != NULL);
1958
1959 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1960 // a=group:BUNDLE video voice
1961 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001962 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001963 kSdpDelimiterSpace, &fields);
1964 std::string semantics;
1965 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1966 return false;
1967 }
1968 cricket::ContentGroup group(semantics);
1969 for (size_t i = 1; i < fields.size(); ++i) {
1970 group.AddContentName(fields[i]);
1971 }
1972 desc->AddGroup(group);
1973 return true;
1974}
1975
1976static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001977 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001978 SdpParseError* error) {
1979 if (!IsLineType(line, kLineTypeAttributes) ||
1980 !HasAttribute(line, kAttributeFingerprint)) {
1981 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1982 kAttributeFingerprint, error);
1983 }
1984
1985 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001986 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987 kSdpDelimiterSpace, &fields);
1988 const size_t expected_fields = 2;
1989 if (fields.size() != expected_fields) {
1990 return ParseFailedExpectFieldNum(line, expected_fields, error);
1991 }
1992
1993 // The first field here is "fingerprint:<hash>.
1994 std::string algorithm;
1995 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
1996 return false;
1997 }
1998
1999 // Downcase the algorithm. Note that we don't need to downcase the
2000 // fingerprint because hex_decode can handle upper-case.
2001 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
2002 ::tolower);
2003
2004 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002005 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006 algorithm, fields[1]);
2007 if (!*fingerprint) {
2008 return ParseFailed(line,
2009 "Failed to create fingerprint from the digest.",
2010 error);
2011 }
2012
2013 return true;
2014}
2015
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002016static bool ParseDtlsSetup(const std::string& line,
2017 cricket::ConnectionRole* role,
2018 SdpParseError* error) {
2019 // setup-attr = "a=setup:" role
2020 // role = "active" / "passive" / "actpass" / "holdconn"
2021 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002022 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002023 const size_t expected_fields = 2;
2024 if (fields.size() != expected_fields) {
2025 return ParseFailedExpectFieldNum(line, expected_fields, error);
2026 }
2027 std::string role_str = fields[1];
2028 if (!cricket::StringToConnectionRole(role_str, role)) {
2029 return ParseFailed(line, "Invalid attribute value.", error);
2030 }
2031 return true;
2032}
2033
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002034// RFC 3551
2035// PT encoding media type clock rate channels
2036// name (Hz)
2037// 0 PCMU A 8,000 1
2038// 1 reserved A
2039// 2 reserved A
2040// 3 GSM A 8,000 1
2041// 4 G723 A 8,000 1
2042// 5 DVI4 A 8,000 1
2043// 6 DVI4 A 16,000 1
2044// 7 LPC A 8,000 1
2045// 8 PCMA A 8,000 1
2046// 9 G722 A 8,000 1
2047// 10 L16 A 44,100 2
2048// 11 L16 A 44,100 1
2049// 12 QCELP A 8,000 1
2050// 13 CN A 8,000 1
2051// 14 MPA A 90,000 (see text)
2052// 15 G728 A 8,000 1
2053// 16 DVI4 A 11,025 1
2054// 17 DVI4 A 22,050 1
2055// 18 G729 A 8,000 1
2056struct StaticPayloadAudioCodec {
2057 const char* name;
2058 int clockrate;
2059 int channels;
2060};
2061static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2062 { "PCMU", 8000, 1 },
2063 { "reserved", 0, 0 },
2064 { "reserved", 0, 0 },
2065 { "GSM", 8000, 1 },
2066 { "G723", 8000, 1 },
2067 { "DVI4", 8000, 1 },
2068 { "DVI4", 16000, 1 },
2069 { "LPC", 8000, 1 },
2070 { "PCMA", 8000, 1 },
2071 { "G722", 8000, 1 },
2072 { "L16", 44100, 2 },
2073 { "L16", 44100, 1 },
2074 { "QCELP", 8000, 1 },
2075 { "CN", 8000, 1 },
2076 { "MPA", 90000, 1 },
2077 { "G728", 8000, 1 },
2078 { "DVI4", 11025, 1 },
2079 { "DVI4", 22050, 1 },
2080 { "G729", 8000, 1 },
2081};
2082
2083void MaybeCreateStaticPayloadAudioCodecs(
2084 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2085 if (!media_desc) {
2086 return;
2087 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002088 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002089 std::vector<int>::const_iterator it = fmts.begin();
2090 bool add_new_codec = false;
2091 for (; it != fmts.end(); ++it) {
2092 int payload_type = *it;
2093 if (!media_desc->HasCodec(payload_type) &&
2094 payload_type >= 0 &&
2095 payload_type < ARRAY_SIZE(kStaticPayloadAudioCodecs)) {
2096 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2097 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2098 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2099 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2100 clock_rate, 0, channels,
2101 preference));
2102 add_new_codec = true;
2103 }
2104 --preference;
2105 }
2106 if (add_new_codec) {
2107 media_desc->SortCodecs();
2108 }
2109}
2110
2111template <class C>
2112static C* ParseContentDescription(const std::string& message,
2113 const MediaType media_type,
2114 int mline_index,
2115 const std::string& protocol,
2116 const std::vector<int>& codec_preference,
2117 size_t* pos,
2118 std::string* content_name,
2119 TransportDescription* transport,
2120 std::vector<JsepIceCandidate*>* candidates,
2121 webrtc::SdpParseError* error) {
2122 C* media_desc = new C();
2123 switch (media_type) {
2124 case cricket::MEDIA_TYPE_AUDIO:
2125 *content_name = cricket::CN_AUDIO;
2126 break;
2127 case cricket::MEDIA_TYPE_VIDEO:
2128 *content_name = cricket::CN_VIDEO;
2129 break;
2130 case cricket::MEDIA_TYPE_DATA:
2131 *content_name = cricket::CN_DATA;
2132 break;
2133 default:
2134 ASSERT(false);
2135 break;
2136 }
2137 if (!ParseContent(message, media_type, mline_index, protocol,
2138 codec_preference, pos, content_name,
2139 media_desc, transport, candidates, error)) {
2140 delete media_desc;
2141 return NULL;
2142 }
2143 // Sort the codecs according to the m-line fmt list.
2144 media_desc->SortCodecs();
2145 return media_desc;
2146}
2147
2148bool ParseMediaDescription(const std::string& message,
2149 const TransportDescription& session_td,
2150 const RtpHeaderExtensions& session_extmaps,
2151 bool supports_msid,
2152 size_t* pos,
2153 cricket::SessionDescription* desc,
2154 std::vector<JsepIceCandidate*>* candidates,
2155 SdpParseError* error) {
2156 ASSERT(desc != NULL);
2157 std::string line;
2158 int mline_index = -1;
2159
2160 // Zero or more media descriptions
2161 // RFC 4566
2162 // m=<media> <port> <proto> <fmt>
2163 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2164 ++mline_index;
2165
2166 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002167 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002168 kSdpDelimiterSpace, &fields);
2169 const size_t expected_min_fields = 4;
2170 if (fields.size() < expected_min_fields) {
2171 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2172 }
2173 bool rejected = false;
2174 // RFC 3264
2175 // To reject an offered stream, the port number in the corresponding stream
2176 // in the answer MUST be set to zero.
2177 if (fields[1] == kMediaPortRejected) {
2178 rejected = true;
2179 }
2180
2181 std::string protocol = fields[2];
2182 bool is_sctp = (protocol == cricket::kMediaProtocolDtlsSctp);
2183
2184 // <fmt>
2185 std::vector<int> codec_preference;
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002186 if (!is_sctp) {
2187 for (size_t j = 3 ; j < fields.size(); ++j) {
2188 // TODO(wu): Remove when below bug is fixed.
2189 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
2190 if (fields[j] == "" && j == fields.size() - 1) {
2191 continue;
2192 }
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002193
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002194 int pl = 0;
2195 if (!GetValueFromString(line, fields[j], &pl, error)) {
2196 return false;
2197 }
2198 codec_preference.push_back(pl);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002199 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002200 }
2201
2202 // Make a temporary TransportDescription based on |session_td|.
2203 // Some of this gets overwritten by ParseContent.
2204 TransportDescription transport(NS_JINGLE_ICE_UDP,
2205 session_td.transport_options,
2206 session_td.ice_ufrag,
2207 session_td.ice_pwd,
2208 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002209 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002210 session_td.identity_fingerprint.get(),
2211 Candidates());
2212
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002213 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002214 std::string content_name;
2215 if (HasAttribute(line, kMediaTypeVideo)) {
2216 content.reset(ParseContentDescription<VideoContentDescription>(
2217 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2218 codec_preference, pos, &content_name,
2219 &transport, candidates, error));
2220 } else if (HasAttribute(line, kMediaTypeAudio)) {
2221 content.reset(ParseContentDescription<AudioContentDescription>(
2222 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2223 codec_preference, pos, &content_name,
2224 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225 } else if (HasAttribute(line, kMediaTypeData)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002226 DataContentDescription* data_desc =
wu@webrtc.org78187522013-10-07 23:32:02 +00002227 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002228 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2229 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002230 &transport, candidates, error);
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002231 content.reset(data_desc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002232
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002233 int p;
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002234 if (data_desc && protocol == cricket::kMediaProtocolDtlsSctp &&
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002235 rtc::FromString(fields[3], &p)) {
jiayl@webrtc.org0e527722014-09-08 21:43:43 +00002236 if (!AddSctpDataCodec(data_desc, p))
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002237 return false;
wu@webrtc.org78187522013-10-07 23:32:02 +00002238 }
2239
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002240 // We should always use the default bandwidth for RTP-based data
2241 // channels. Don't allow SDP to set the bandwidth, because that
2242 // would give JS the opportunity to "break the Internet".
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002243 // TODO(pthatcher): But we need to temporarily allow the SDP to control
2244 // this for backwards-compatibility. Once we don't need that any
2245 // more, remove this.
2246 bool support_dc_sdp_bandwidth_temporarily = true;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00002247 if (content.get() && !support_dc_sdp_bandwidth_temporarily) {
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002248 content->set_bandwidth(cricket::kAutoBandwidth);
2249 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002250 } else {
2251 LOG(LS_WARNING) << "Unsupported media type: " << line;
2252 continue;
2253 }
2254 if (!content.get()) {
2255 // ParseContentDescription returns NULL if failed.
2256 return false;
2257 }
2258
2259 if (!is_sctp) {
2260 // Make sure to set the media direction correctly. If the direction is not
2261 // MD_RECVONLY or Inactive and no streams are parsed,
2262 // a default MediaStream will be created to prepare for receiving media.
2263 if (supports_msid && content->streams().empty() &&
2264 content->direction() == cricket::MD_SENDRECV) {
2265 content->set_direction(cricket::MD_RECVONLY);
2266 }
2267
2268 // Set the extmap.
2269 if (!session_extmaps.empty() &&
2270 !content->rtp_header_extensions().empty()) {
2271 return ParseFailed("",
2272 "The a=extmap MUST be either all session level or "
2273 "all media level.",
2274 error);
2275 }
2276 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2277 content->AddRtpHeaderExtension(session_extmaps[i]);
2278 }
2279 }
2280 content->set_protocol(protocol);
2281 desc->AddContent(content_name,
2282 is_sctp ? cricket::NS_JINGLE_DRAFT_SCTP :
2283 cricket::NS_JINGLE_RTP,
2284 rejected,
2285 content.release());
2286 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2287 TransportInfo transport_info(content_name, transport);
2288
2289 if (!desc->AddTransportInfo(transport_info)) {
2290 std::ostringstream description;
2291 description << "Failed to AddTransportInfo with content name: "
2292 << content_name;
2293 return ParseFailed("", description.str(), error);
2294 }
2295 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002296
2297 size_t end_of_message = message.size();
2298 if (mline_index == -1 && *pos != end_of_message) {
2299 ParseFailed(message, *pos, "Expects m line.", error);
2300 return false;
2301 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002302 return true;
2303}
2304
2305bool VerifyCodec(const cricket::Codec& codec) {
2306 // Codec has not been populated correctly unless the name has been set. This
2307 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2308 // have a corresponding "rtpmap" line.
2309 cricket::Codec default_codec;
2310 return default_codec.name != codec.name;
2311}
2312
2313bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2314 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2315 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2316 iter != codecs.end(); ++iter) {
2317 if (!VerifyCodec(*iter)) {
2318 return false;
2319 }
2320 }
2321 return true;
2322}
2323
2324bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2325 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2326 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2327 iter != codecs.end(); ++iter) {
2328 if (!VerifyCodec(*iter)) {
2329 return false;
2330 }
2331 }
2332 return true;
2333}
2334
2335void AddParameters(const cricket::CodecParameterMap& parameters,
2336 cricket::Codec* codec) {
2337 for (cricket::CodecParameterMap::const_iterator iter =
2338 parameters.begin(); iter != parameters.end(); ++iter) {
2339 codec->SetParam(iter->first, iter->second);
2340 }
2341}
2342
2343void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2344 cricket::Codec* codec) {
2345 codec->AddFeedbackParam(feedback_param);
2346}
2347
2348void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2349 cricket::Codec* codec) {
2350 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2351 feedback_params.params().begin();
2352 iter != feedback_params.params().end(); ++iter) {
2353 codec->AddFeedbackParam(*iter);
2354 }
2355}
2356
2357// Gets the current codec setting associated with |payload_type|. If there
2358// is no AudioCodec associated with that payload type it returns an empty codec
2359// with that payload type.
2360template <class T>
2361T GetCodec(const std::vector<T>& codecs, int payload_type) {
2362 for (typename std::vector<T>::const_iterator codec = codecs.begin();
2363 codec != codecs.end(); ++codec) {
2364 if (codec->id == payload_type) {
2365 return *codec;
2366 }
2367 }
2368 T ret_val = T();
2369 ret_val.id = payload_type;
2370 return ret_val;
2371}
2372
2373// Updates or creates a new codec entry in the audio description.
2374template <class T, class U>
2375void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2376 T* desc = static_cast<T*>(content_desc);
2377 std::vector<U> codecs = desc->codecs();
2378 bool found = false;
2379
2380 typename std::vector<U>::iterator iter;
2381 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2382 if (iter->id == codec.id) {
2383 *iter = codec;
2384 found = true;
2385 break;
2386 }
2387 }
2388 if (!found) {
2389 desc->AddCodec(codec);
2390 return;
2391 }
2392 desc->set_codecs(codecs);
2393}
2394
2395// Adds or updates existing codec corresponding to |payload_type| according
2396// to |parameters|.
2397template <class T, class U>
2398void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2399 const cricket::CodecParameterMap& parameters) {
2400 // Codec might already have been populated (from rtpmap).
2401 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2402 AddParameters(parameters, &new_codec);
2403 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2404}
2405
2406// Adds or updates existing codec corresponding to |payload_type| according
2407// to |feedback_param|.
2408template <class T, class U>
2409void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2410 const cricket::FeedbackParam& feedback_param) {
2411 // Codec might already have been populated (from rtpmap).
2412 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2413 AddFeedbackParameter(feedback_param, &new_codec);
2414 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2415}
2416
2417bool PopWildcardCodec(std::vector<cricket::VideoCodec>* codecs,
2418 cricket::VideoCodec* wildcard_codec) {
2419 for (std::vector<cricket::VideoCodec>::iterator iter = codecs->begin();
2420 iter != codecs->end(); ++iter) {
2421 if (iter->id == kWildcardPayloadType) {
2422 *wildcard_codec = *iter;
2423 codecs->erase(iter);
2424 return true;
2425 }
2426 }
2427 return false;
2428}
2429
2430void UpdateFromWildcardVideoCodecs(VideoContentDescription* video_desc) {
2431 std::vector<cricket::VideoCodec> codecs = video_desc->codecs();
2432 cricket::VideoCodec wildcard_codec;
2433 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2434 return;
2435 }
2436 for (std::vector<cricket::VideoCodec>::iterator iter = codecs.begin();
2437 iter != codecs.end(); ++iter) {
2438 cricket::VideoCodec& codec = *iter;
2439 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2440 }
2441 video_desc->set_codecs(codecs);
2442}
2443
2444void AddAudioAttribute(const std::string& name, const std::string& value,
2445 AudioContentDescription* audio_desc) {
2446 if (value.empty()) {
2447 return;
2448 }
2449 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2450 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2451 iter != codecs.end(); ++iter) {
2452 iter->params[name] = value;
2453 }
2454 audio_desc->set_codecs(codecs);
2455}
2456
2457bool ParseContent(const std::string& message,
2458 const MediaType media_type,
2459 int mline_index,
2460 const std::string& protocol,
2461 const std::vector<int>& codec_preference,
2462 size_t* pos,
2463 std::string* content_name,
2464 MediaContentDescription* media_desc,
2465 TransportDescription* transport,
2466 std::vector<JsepIceCandidate*>* candidates,
2467 SdpParseError* error) {
2468 ASSERT(media_desc != NULL);
2469 ASSERT(content_name != NULL);
2470 ASSERT(transport != NULL);
2471
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002472 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2473 MaybeCreateStaticPayloadAudioCodecs(
2474 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2475 }
2476
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002477 // The media level "ice-ufrag" and "ice-pwd".
2478 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2479 Candidates candidates_orig;
2480 std::string line;
2481 std::string mline_id;
2482 // Tracks created out of the ssrc attributes.
2483 StreamParamsVec tracks;
2484 SsrcInfoVec ssrc_infos;
2485 SsrcGroupVec ssrc_groups;
2486 std::string maxptime_as_string;
2487 std::string ptime_as_string;
2488
2489 bool is_rtp =
2490 protocol.empty() ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002491 rtc::starts_with(protocol.data(),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002492 cricket::kMediaProtocolRtpPrefix);
2493
2494 // Loop until the next m line
2495 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2496 if (!GetLine(message, pos, &line)) {
2497 if (*pos >= message.size()) {
2498 break; // Done parsing
2499 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002500 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002501 }
2502 }
2503
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002504 // RFC 4566
2505 // b=* (zero or more bandwidth information lines)
2506 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2507 std::string bandwidth;
2508 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2509 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2510 return false;
2511 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002512 int b = 0;
2513 if (!GetValueFromString(line, bandwidth, &b, error)) {
2514 return false;
2515 }
2516 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002517 }
2518 }
2519 continue;
2520 }
2521
2522 if (!IsLineType(line, kLineTypeAttributes)) {
2523 // TODO: Handle other lines if needed.
2524 LOG(LS_INFO) << "Ignored line: " << line;
2525 continue;
2526 }
2527
2528 // Handle attributes common to SCTP and RTP.
2529 if (HasAttribute(line, kAttributeMid)) {
2530 // RFC 3388
2531 // mid-attribute = "a=mid:" identification-tag
2532 // identification-tag = token
2533 // Use the mid identification-tag as the content name.
2534 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2535 return false;
2536 }
2537 *content_name = mline_id;
2538 } else if (HasAttribute(line, kAttributeCandidate)) {
2539 Candidate candidate;
2540 if (!ParseCandidate(line, &candidate, error, false)) {
2541 return false;
2542 }
2543 candidates_orig.push_back(candidate);
2544 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2545 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2546 return false;
2547 }
2548 } else if (HasAttribute(line, kAttributeIcePwd)) {
2549 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2550 return false;
2551 }
2552 } else if (HasAttribute(line, kAttributeIceOption)) {
2553 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2554 return false;
2555 }
2556 } else if (HasAttribute(line, kAttributeFmtp)) {
2557 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2558 return false;
2559 }
2560 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002561 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002562
2563 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2564 return false;
2565 }
2566 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002567 } else if (HasAttribute(line, kAttributeSetup)) {
2568 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2569 return false;
2570 }
jiayl@webrtc.orgddb85ab2014-09-05 16:31:56 +00002571 } else if (HasAttribute(line, kAttributeSctpPort)) {
2572 int sctp_port;
2573 if (!ParseSctpPort(line, &sctp_port, error)) {
2574 return false;
2575 }
2576 if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
2577 sctp_port)) {
2578 return false;
2579 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002580 } else if (is_rtp) {
2581 //
2582 // RTP specific attrubtes
2583 //
2584 if (HasAttribute(line, kAttributeRtcpMux)) {
2585 media_desc->set_rtcp_mux(true);
2586 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2587 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2588 return false;
2589 }
2590 } else if (HasAttribute(line, kAttributeSsrc)) {
2591 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2592 return false;
2593 }
2594 } else if (HasAttribute(line, kAttributeCrypto)) {
2595 if (!ParseCryptoAttribute(line, media_desc, error)) {
2596 return false;
2597 }
2598 } else if (HasAttribute(line, kAttributeRtpmap)) {
2599 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2600 media_desc, error)) {
2601 return false;
2602 }
2603 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2604 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2605 return false;
2606 }
2607 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2608 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2609 return false;
2610 }
2611 } else if (HasAttribute(line, kCodecParamPTime)) {
2612 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2613 return false;
2614 }
2615 } else if (HasAttribute(line, kAttributeSendOnly)) {
2616 media_desc->set_direction(cricket::MD_SENDONLY);
2617 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2618 media_desc->set_direction(cricket::MD_RECVONLY);
2619 } else if (HasAttribute(line, kAttributeInactive)) {
2620 media_desc->set_direction(cricket::MD_INACTIVE);
2621 } else if (HasAttribute(line, kAttributeSendRecv)) {
2622 media_desc->set_direction(cricket::MD_SENDRECV);
2623 } else if (HasAttribute(line, kAttributeExtmap)) {
2624 RtpHeaderExtension extmap;
2625 if (!ParseExtmap(line, &extmap, error)) {
2626 return false;
2627 }
2628 media_desc->AddRtpHeaderExtension(extmap);
2629 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2630 // Experimental attribute. Conference mode activates more aggressive
2631 // AEC and NS settings.
2632 // TODO: expose API to set these directly.
2633 std::string flag_value;
2634 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2635 return false;
2636 }
2637 if (flag_value.compare(kValueConference) == 0)
2638 media_desc->set_conference_mode(true);
2639 } else if (HasAttribute(line, kAttributeXGoogleBufferLatency)) {
2640 // Experimental attribute.
2641 // TODO: expose API to set this directly.
2642 std::string flag_value;
2643 if (!GetValue(line, kAttributeXGoogleBufferLatency, &flag_value,
2644 error)) {
2645 return false;
2646 }
2647 int buffer_latency = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002648 if (!GetValueFromString(line, flag_value, &buffer_latency, error)) {
2649 return false;
2650 }
2651 if (buffer_latency < 0) {
2652 return ParseFailed(line, "Buffer latency less than 0.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002653 }
2654 media_desc->set_buffered_mode_latency(buffer_latency);
2655 }
2656 } else {
2657 // Only parse lines that we are interested of.
2658 LOG(LS_INFO) << "Ignored line: " << line;
2659 continue;
2660 }
2661 }
2662
2663 // Create tracks from the |ssrc_infos|.
2664 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2665
2666 // Add the ssrc group to the track.
2667 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2668 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2669 if (ssrc_group->ssrcs.empty()) {
2670 continue;
2671 }
2672 uint32 ssrc = ssrc_group->ssrcs.front();
2673 for (StreamParamsVec::iterator track = tracks.begin();
2674 track != tracks.end(); ++track) {
2675 if (track->has_ssrc(ssrc)) {
2676 track->ssrc_groups.push_back(*ssrc_group);
2677 }
2678 }
2679 }
2680
2681 // Add the new tracks to the |media_desc|.
2682 for (StreamParamsVec::iterator track = tracks.begin();
2683 track != tracks.end(); ++track) {
2684 media_desc->AddStream(*track);
2685 }
2686
2687 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2688 AudioContentDescription* audio_desc =
2689 static_cast<AudioContentDescription*>(media_desc);
2690 // Verify audio codec ensures that no audio codec has been populated with
2691 // only fmtp.
2692 if (!VerifyAudioCodecs(audio_desc)) {
2693 return ParseFailed("Failed to parse audio codecs correctly.", error);
2694 }
2695 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2696 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2697 }
2698
2699 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2700 VideoContentDescription* video_desc =
2701 static_cast<VideoContentDescription*>(media_desc);
2702 UpdateFromWildcardVideoCodecs(video_desc);
2703 // Verify video codec ensures that no video codec has been populated with
2704 // only rtcp-fb.
2705 if (!VerifyVideoCodecs(video_desc)) {
2706 return ParseFailed("Failed to parse video codecs correctly.", error);
2707 }
2708 }
2709
2710 // RFC 5245
2711 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2712 for (Candidates::iterator it = candidates_orig.begin();
2713 it != candidates_orig.end(); ++it) {
2714 ASSERT((*it).username().empty());
2715 (*it).set_username(transport->ice_ufrag);
2716 ASSERT((*it).password().empty());
2717 (*it).set_password(transport->ice_pwd);
2718 candidates->push_back(
2719 new JsepIceCandidate(mline_id, mline_index, *it));
2720 }
2721 return true;
2722}
2723
2724bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2725 SdpParseError* error) {
2726 ASSERT(ssrc_infos != NULL);
2727 // RFC 5576
2728 // a=ssrc:<ssrc-id> <attribute>
2729 // a=ssrc:<ssrc-id> <attribute>:<value>
2730 std::string field1, field2;
2731 if (!SplitByDelimiter(line.substr(kLinePrefixLength),
2732 kSdpDelimiterSpace,
2733 &field1,
2734 &field2)) {
2735 const size_t expected_fields = 2;
2736 return ParseFailedExpectFieldNum(line, expected_fields, error);
2737 }
2738
2739 // ssrc:<ssrc-id>
2740 std::string ssrc_id_s;
2741 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2742 return false;
2743 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002744 uint32 ssrc_id = 0;
2745 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2746 return false;
2747 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002748
2749 std::string attribute;
2750 std::string value;
2751 if (!SplitByDelimiter(field2, kSdpDelimiterColon,
2752 &attribute, &value)) {
2753 std::ostringstream description;
2754 description << "Failed to get the ssrc attribute value from " << field2
2755 << ". Expected format <attribute>:<value>.";
2756 return ParseFailed(line, description.str(), error);
2757 }
2758
2759 // Check if there's already an item for this |ssrc_id|. Create a new one if
2760 // there isn't.
2761 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2762 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2763 if (ssrc_info->ssrc_id == ssrc_id) {
2764 break;
2765 }
2766 }
2767 if (ssrc_info == ssrc_infos->end()) {
2768 SsrcInfo info;
2769 info.ssrc_id = ssrc_id;
2770 ssrc_infos->push_back(info);
2771 ssrc_info = ssrc_infos->end() - 1;
2772 }
2773
2774 // Store the info to the |ssrc_info|.
2775 if (attribute == kSsrcAttributeCname) {
2776 // RFC 5576
2777 // cname:<value>
2778 ssrc_info->cname = value;
2779 } else if (attribute == kSsrcAttributeMsid) {
2780 // draft-alvestrand-mmusic-msid-00
2781 // "msid:" identifier [ " " appdata ]
2782 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002783 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002784 if (fields.size() < 1 || fields.size() > 2) {
2785 return ParseFailed(line,
2786 "Expected format \"msid:<identifier>[ <appdata>]\".",
2787 error);
2788 }
2789 ssrc_info->msid_identifier = fields[0];
2790 if (fields.size() == 2) {
2791 ssrc_info->msid_appdata = fields[1];
2792 }
2793 } else if (attribute == kSsrcAttributeMslabel) {
2794 // draft-alvestrand-rtcweb-mid-01
2795 // mslabel:<value>
2796 ssrc_info->mslabel = value;
2797 } else if (attribute == kSSrcAttributeLabel) {
2798 // The label isn't defined.
2799 // label:<value>
2800 ssrc_info->label = value;
2801 }
2802 return true;
2803}
2804
2805bool ParseSsrcGroupAttribute(const std::string& line,
2806 SsrcGroupVec* ssrc_groups,
2807 SdpParseError* error) {
2808 ASSERT(ssrc_groups != NULL);
2809 // RFC 5576
2810 // a=ssrc-group:<semantics> <ssrc-id> ...
2811 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002812 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002813 kSdpDelimiterSpace, &fields);
2814 const size_t expected_min_fields = 2;
2815 if (fields.size() < expected_min_fields) {
2816 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2817 }
2818 std::string semantics;
2819 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2820 return false;
2821 }
2822 std::vector<uint32> ssrcs;
2823 for (size_t i = 1; i < fields.size(); ++i) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002824 uint32 ssrc = 0;
2825 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2826 return false;
2827 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002828 ssrcs.push_back(ssrc);
2829 }
2830 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2831 return true;
2832}
2833
2834bool ParseCryptoAttribute(const std::string& line,
2835 MediaContentDescription* media_desc,
2836 SdpParseError* error) {
2837 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002838 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002839 kSdpDelimiterSpace, &fields);
2840 // RFC 4568
2841 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2842 const size_t expected_min_fields = 3;
2843 if (fields.size() < expected_min_fields) {
2844 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2845 }
2846 std::string tag_value;
2847 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2848 return false;
2849 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002850 int tag = 0;
2851 if (!GetValueFromString(line, tag_value, &tag, error)) {
2852 return false;
2853 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002854 const std::string crypto_suite = fields[1];
2855 const std::string key_params = fields[2];
2856 std::string session_params;
2857 if (fields.size() > 3) {
2858 session_params = fields[3];
2859 }
2860 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2861 session_params));
2862 return true;
2863}
2864
2865// Updates or creates a new codec entry in the audio description with according
2866// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2867void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2868 int bitrate, int channels, int preference,
2869 AudioContentDescription* audio_desc) {
2870 // Codec may already be populated with (only) optional parameters
2871 // (from an fmtp).
2872 cricket::AudioCodec codec = GetCodec(audio_desc->codecs(), payload_type);
2873 codec.name = name;
2874 codec.clockrate = clockrate;
2875 codec.bitrate = bitrate;
2876 codec.channels = channels;
2877 codec.preference = preference;
2878 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2879 codec);
2880}
2881
2882// Updates or creates a new codec entry in the video description according to
2883// |name|, |width|, |height|, |framerate| and |preference|.
2884void UpdateCodec(int payload_type, const std::string& name, int width,
2885 int height, int framerate, int preference,
2886 VideoContentDescription* video_desc) {
2887 // Codec may already be populated with (only) optional parameters
2888 // (from an fmtp).
2889 cricket::VideoCodec codec = GetCodec(video_desc->codecs(), payload_type);
2890 codec.name = name;
2891 codec.width = width;
2892 codec.height = height;
2893 codec.framerate = framerate;
2894 codec.preference = preference;
2895 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2896 codec);
2897}
2898
2899bool ParseRtpmapAttribute(const std::string& line,
2900 const MediaType media_type,
2901 const std::vector<int>& codec_preference,
2902 MediaContentDescription* media_desc,
2903 SdpParseError* error) {
2904 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002905 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002906 kSdpDelimiterSpace, &fields);
2907 // RFC 4566
2908 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2909 const size_t expected_min_fields = 2;
2910 if (fields.size() < expected_min_fields) {
2911 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2912 }
2913 std::string payload_type_value;
2914 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2915 return false;
2916 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002917 int payload_type = 0;
2918 if (!GetValueFromString(line, payload_type_value, &payload_type, error)) {
2919 return false;
2920 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002921
2922 // Set the preference order depending on the order of the pl type in the
2923 // <fmt> of the m-line.
2924 const int preference = codec_preference.end() -
2925 std::find(codec_preference.begin(), codec_preference.end(),
2926 payload_type);
2927 if (preference == 0) {
2928 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2929 << "<fmt> of the m-line: " << line;
2930 return true;
2931 }
2932 const std::string encoder = fields[1];
2933 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002934 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002935 // <encoding name>/<clock rate>[/<encodingparameters>]
2936 // 2 mandatory fields
2937 if (codec_params.size() < 2 || codec_params.size() > 3) {
2938 return ParseFailed(line,
2939 "Expected format \"<encoding name>/<clock rate>"
2940 "[/<encodingparameters>]\".",
2941 error);
2942 }
2943 const std::string encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002944 int clock_rate = 0;
2945 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2946 return false;
2947 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002948 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2949 VideoContentDescription* video_desc =
2950 static_cast<VideoContentDescription*>(media_desc);
2951 // TODO: We will send resolution in SDP. For now use
2952 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2953 UpdateCodec(payload_type, encoding_name,
2954 JsepSessionDescription::kMaxVideoCodecWidth,
2955 JsepSessionDescription::kMaxVideoCodecHeight,
2956 JsepSessionDescription::kDefaultVideoCodecFramerate,
2957 preference, video_desc);
2958 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2959 // RFC 4566
2960 // For audio streams, <encoding parameters> indicates the number
2961 // of audio channels. This parameter is OPTIONAL and may be
2962 // omitted if the number of channels is one, provided that no
2963 // additional parameters are needed.
2964 int channels = 1;
2965 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002966 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2967 return false;
2968 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002969 }
2970 int bitrate = 0;
2971 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2972 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2973 // The bandwidth adaptation doesn't always work well, so this code
2974 // sets a fixed target bitrate instead.
2975 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2976 if (clock_rate <= 16000) {
2977 bitrate = kIsacWbDefaultRate;
2978 } else {
2979 bitrate = kIsacSwbDefaultRate;
2980 }
2981 }
2982 AudioContentDescription* audio_desc =
2983 static_cast<AudioContentDescription*>(media_desc);
2984 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2985 preference, audio_desc);
2986 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2987 DataContentDescription* data_desc =
2988 static_cast<DataContentDescription*>(media_desc);
2989 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2990 preference));
2991 }
2992 return true;
2993}
2994
2995void PruneRight(const char delimiter, std::string* message) {
2996 size_t trailing = message->find(delimiter);
2997 if (trailing != std::string::npos) {
2998 *message = message->substr(0, trailing);
2999 }
3000}
3001
3002bool ParseFmtpParam(const std::string& line, std::string* parameter,
3003 std::string* value, SdpParseError* error) {
3004 if (!SplitByDelimiter(line, kSdpDelimiterEqual, parameter, value)) {
3005 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
3006 return false;
3007 }
3008 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
3009 // When parsing the values the trailing ";" gets picked up. Remove them.
3010 PruneRight(kSdpDelimiterSemicolon, value);
3011 return true;
3012}
3013
3014bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
3015 MediaContentDescription* media_desc,
3016 SdpParseError* error) {
3017 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3018 media_type != cricket::MEDIA_TYPE_VIDEO) {
3019 return true;
3020 }
3021 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003022 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003023 kSdpDelimiterSpace, &fields);
3024
3025 // RFC 5576
3026 // a=fmtp:<format> <format specific parameters>
3027 // At least two fields, whereas the second one is any of the optional
3028 // parameters.
3029 if (fields.size() < 2) {
3030 ParseFailedExpectMinFieldNum(line, 2, error);
3031 return false;
3032 }
3033
3034 std::string payload_type;
3035 if (!GetValue(fields[0], kAttributeFmtp, &payload_type, error)) {
3036 return false;
3037 }
3038
3039 cricket::CodecParameterMap codec_params;
3040 for (std::vector<std::string>::const_iterator iter = fields.begin() + 1;
3041 iter != fields.end(); ++iter) {
3042 std::string name;
3043 std::string value;
3044 if (iter->find(kSdpDelimiterEqual) == std::string::npos) {
3045 // Only fmtps with equals are currently supported. Other fmtp types
3046 // should be ignored. Unknown fmtps do not constitute an error.
3047 continue;
3048 }
3049 if (!ParseFmtpParam(*iter, &name, &value, error)) {
3050 return false;
3051 }
3052 codec_params[name] = value;
3053 }
3054
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003055 int int_payload_type = 0;
3056 if (!GetValueFromString(line, payload_type, &int_payload_type, error)) {
3057 return false;
3058 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003059 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3060 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3061 media_desc, int_payload_type, codec_params);
3062 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3063 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3064 media_desc, int_payload_type, codec_params);
3065 }
3066 return true;
3067}
3068
3069bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3070 MediaContentDescription* media_desc,
3071 SdpParseError* error) {
3072 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3073 media_type != cricket::MEDIA_TYPE_VIDEO) {
3074 return true;
3075 }
3076 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003077 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003078 if (rtcp_fb_fields.size() < 2) {
3079 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3080 }
3081 std::string payload_type_string;
3082 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3083 error)) {
3084 return false;
3085 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003086 int payload_type = kWildcardPayloadType;
3087 if (payload_type_string != "*") {
3088 if (!GetValueFromString(line, payload_type_string, &payload_type, error)) {
3089 return false;
3090 }
3091 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003092 std::string id = rtcp_fb_fields[1];
3093 std::string param = "";
3094 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3095 iter != rtcp_fb_fields.end(); ++iter) {
3096 param.append(*iter);
3097 }
3098 const cricket::FeedbackParam feedback_param(id, param);
3099
3100 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3101 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(media_desc,
3102 payload_type,
3103 feedback_param);
3104 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3105 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(media_desc,
3106 payload_type,
3107 feedback_param);
3108 }
3109 return true;
3110}
3111
3112} // namespace webrtc