blob: 09e5cbd9c39cb95760a3e3e7fd02ea0d07c95092 [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"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000038#include "webrtc/base/common.h"
39#include "webrtc/base/logging.h"
40#include "webrtc/base/messagedigest.h"
41#include "webrtc/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000042#include "talk/media/base/codec.h"
43#include "talk/media/base/constants.h"
44#include "talk/media/base/cryptoparams.h"
mallinath@webrtc.org1112c302013-09-23 20:34:45 +000045#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000046#include "talk/p2p/base/candidate.h"
47#include "talk/p2p/base/constants.h"
48#include "talk/p2p/base/port.h"
49#include "talk/session/media/mediasession.h"
50#include "talk/session/media/mediasessionclient.h"
51
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;
stefan@webrtc.org85d27942014-06-09 12:51:39 +000074using cricket::kCodecParamAssociatedPayloadType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075using cricket::kWildcardPayloadType;
76using cricket::MediaContentDescription;
77using cricket::MediaType;
78using cricket::NS_JINGLE_ICE_UDP;
79using cricket::RtpHeaderExtension;
80using cricket::SsrcGroup;
81using cricket::StreamParams;
82using cricket::StreamParamsVec;
83using cricket::TransportDescription;
84using cricket::TransportInfo;
85using cricket::VideoContentDescription;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000086using rtc::SocketAddress;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000087
88typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
89
90namespace cricket {
91class SessionDescription;
92}
93
94namespace webrtc {
95
96// Line type
97// RFC 4566
98// An SDP session description consists of a number of lines of text of
99// the form:
100// <type>=<value>
101// where <type> MUST be exactly one case-significant character.
102static const int kLinePrefixLength = 2; // Lenght of <type>=
103static const char kLineTypeVersion = 'v';
104static const char kLineTypeOrigin = 'o';
105static const char kLineTypeSessionName = 's';
106static const char kLineTypeSessionInfo = 'i';
107static const char kLineTypeSessionUri = 'u';
108static const char kLineTypeSessionEmail = 'e';
109static const char kLineTypeSessionPhone = 'p';
110static const char kLineTypeSessionBandwidth = 'b';
111static const char kLineTypeTiming = 't';
112static const char kLineTypeRepeatTimes = 'r';
113static const char kLineTypeTimeZone = 'z';
114static const char kLineTypeEncryptionKey = 'k';
115static const char kLineTypeMedia = 'm';
116static const char kLineTypeConnection = 'c';
117static const char kLineTypeAttributes = 'a';
118
119// Attributes
120static const char kAttributeGroup[] = "group";
121static const char kAttributeMid[] = "mid";
122static const char kAttributeRtcpMux[] = "rtcp-mux";
123static const char kAttributeSsrc[] = "ssrc";
124static const char kSsrcAttributeCname[] = "cname";
125static const char kAttributeExtmap[] = "extmap";
126// draft-alvestrand-mmusic-msid-01
127// a=msid-semantic: WMS
128static const char kAttributeMsidSemantics[] = "msid-semantic";
129static const char kMediaStreamSemantic[] = "WMS";
130static const char kSsrcAttributeMsid[] = "msid";
131static const char kDefaultMsid[] = "default";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000132static const char kSsrcAttributeMslabel[] = "mslabel";
133static const char kSSrcAttributeLabel[] = "label";
134static const char kAttributeSsrcGroup[] = "ssrc-group";
135static const char kAttributeCrypto[] = "crypto";
136static const char kAttributeCandidate[] = "candidate";
137static const char kAttributeCandidateTyp[] = "typ";
138static const char kAttributeCandidateRaddr[] = "raddr";
139static const char kAttributeCandidateRport[] = "rport";
140static const char kAttributeCandidateUsername[] = "username";
141static const char kAttributeCandidatePassword[] = "password";
142static const char kAttributeCandidateGeneration[] = "generation";
143static const char kAttributeFingerprint[] = "fingerprint";
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000144static const char kAttributeSetup[] = "setup";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000145static const char kAttributeFmtp[] = "fmtp";
146static const char kAttributeRtpmap[] = "rtpmap";
wu@webrtc.org78187522013-10-07 23:32:02 +0000147static const char kAttributeSctpmap[] = "sctpmap";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000148static const char kAttributeRtcp[] = "rtcp";
149static const char kAttributeIceUfrag[] = "ice-ufrag";
150static const char kAttributeIcePwd[] = "ice-pwd";
151static const char kAttributeIceLite[] = "ice-lite";
152static const char kAttributeIceOption[] = "ice-options";
153static const char kAttributeSendOnly[] = "sendonly";
154static const char kAttributeRecvOnly[] = "recvonly";
155static const char kAttributeRtcpFb[] = "rtcp-fb";
156static const char kAttributeSendRecv[] = "sendrecv";
157static const char kAttributeInactive[] = "inactive";
158
159// Experimental flags
160static const char kAttributeXGoogleFlag[] = "x-google-flag";
161static const char kValueConference[] = "conference";
162static const char kAttributeXGoogleBufferLatency[] =
163 "x-google-buffer-latency";
164
165// Candidate
166static const char kCandidateHost[] = "host";
167static const char kCandidateSrflx[] = "srflx";
168// TODO: How to map the prflx with circket candidate type
169// static const char kCandidatePrflx[] = "prflx";
170static const char kCandidateRelay[] = "relay";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +0000171static const char kTcpCandidateType[] = "tcptype";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000172
173static const char kSdpDelimiterEqual = '=';
174static const char kSdpDelimiterSpace = ' ';
175static const char kSdpDelimiterColon = ':';
176static const char kSdpDelimiterSemicolon = ';';
177static const char kSdpDelimiterSlash = '/';
178static const char kNewLine = '\n';
179static const char kReturn = '\r';
180static const char kLineBreak[] = "\r\n";
181
182// TODO: Generate the Session and Time description
183// instead of hardcoding.
184static const char kSessionVersion[] = "v=0";
185// RFC 4566
186static const char kSessionOriginUsername[] = "-";
187static const char kSessionOriginSessionId[] = "0";
188static const char kSessionOriginSessionVersion[] = "0";
189static const char kSessionOriginNettype[] = "IN";
190static const char kSessionOriginAddrtype[] = "IP4";
191static const char kSessionOriginAddress[] = "127.0.0.1";
192static const char kSessionName[] = "s=-";
193static const char kTimeDescription[] = "t=0 0";
194static const char kAttrGroup[] = "a=group:BUNDLE";
195static const char kConnectionNettype[] = "IN";
196static const char kConnectionAddrtype[] = "IP4";
197static const char kMediaTypeVideo[] = "video";
198static const char kMediaTypeAudio[] = "audio";
199static const char kMediaTypeData[] = "application";
200static const char kMediaPortRejected[] = "0";
201static const char kDefaultAddress[] = "0.0.0.0";
202static const char kDefaultPort[] = "1";
203// RFC 3556
204static const char kApplicationSpecificMaximum[] = "AS";
205
206static const int kDefaultVideoClockrate = 90000;
207
208// ISAC special-case.
209static const char kIsacCodecName[] = "ISAC"; // From webrtcvoiceengine.cc
210static const int kIsacWbDefaultRate = 32000; // From acm_common_defs.h
211static const int kIsacSwbDefaultRate = 56000; // From acm_common_defs.h
212
wu@webrtc.org78187522013-10-07 23:32:02 +0000213static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000214
215struct SsrcInfo {
216 SsrcInfo()
217 : msid_identifier(kDefaultMsid),
218 // TODO(ronghuawu): What should we do if the appdata doesn't appear?
219 // Create random string (which will be used as track label later)?
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000220 msid_appdata(rtc::CreateRandomString(8)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000221 }
222 uint32 ssrc_id;
223 std::string cname;
224 std::string msid_identifier;
225 std::string msid_appdata;
226
227 // For backward compatibility.
228 // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
229 std::string label;
230 std::string mslabel;
231};
232typedef std::vector<SsrcInfo> SsrcInfoVec;
233typedef std::vector<SsrcGroup> SsrcGroupVec;
234
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000235template <class T>
236static void AddFmtpLine(const T& codec, std::string* message);
237static void BuildMediaDescription(const ContentInfo* content_info,
238 const TransportInfo* transport_info,
239 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000240 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000241 std::string* message);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000242static void BuildSctpContentAttributes(std::string* message, int sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000243static void BuildRtpContentAttributes(
244 const MediaContentDescription* media_desc,
245 const MediaType media_type,
246 std::string* message);
247static void BuildRtpMap(const MediaContentDescription* media_desc,
248 const MediaType media_type,
249 std::string* message);
250static void BuildCandidate(const std::vector<Candidate>& candidates,
251 std::string* message);
252static void BuildIceOptions(const std::vector<std::string>& transport_options,
253 std::string* message);
254
255static bool ParseSessionDescription(const std::string& message, size_t* pos,
256 std::string* session_id,
257 std::string* session_version,
258 bool* supports_msid,
259 TransportDescription* session_td,
260 RtpHeaderExtensions* session_extmaps,
261 cricket::SessionDescription* desc,
262 SdpParseError* error);
263static bool ParseGroupAttribute(const std::string& line,
264 cricket::SessionDescription* desc,
265 SdpParseError* error);
266static bool ParseMediaDescription(
267 const std::string& message,
268 const TransportDescription& session_td,
269 const RtpHeaderExtensions& session_extmaps,
270 bool supports_msid,
271 size_t* pos, cricket::SessionDescription* desc,
272 std::vector<JsepIceCandidate*>* candidates,
273 SdpParseError* error);
274static bool ParseContent(const std::string& message,
275 const MediaType media_type,
276 int mline_index,
277 const std::string& protocol,
278 const std::vector<int>& codec_preference,
279 size_t* pos,
280 std::string* content_name,
281 MediaContentDescription* media_desc,
282 TransportDescription* transport,
283 std::vector<JsepIceCandidate*>* candidates,
284 SdpParseError* error);
285static bool ParseSsrcAttribute(const std::string& line,
286 SsrcInfoVec* ssrc_infos,
287 SdpParseError* error);
288static bool ParseSsrcGroupAttribute(const std::string& line,
289 SsrcGroupVec* ssrc_groups,
290 SdpParseError* error);
291static bool ParseCryptoAttribute(const std::string& line,
292 MediaContentDescription* media_desc,
293 SdpParseError* error);
294static bool ParseRtpmapAttribute(const std::string& line,
295 const MediaType media_type,
296 const std::vector<int>& codec_preference,
297 MediaContentDescription* media_desc,
298 SdpParseError* error);
299static bool ParseFmtpAttributes(const std::string& line,
300 const MediaType media_type,
301 MediaContentDescription* media_desc,
302 SdpParseError* error);
303static bool ParseFmtpParam(const std::string& line, std::string* parameter,
304 std::string* value, SdpParseError* error);
305static bool ParseCandidate(const std::string& message, Candidate* candidate,
306 SdpParseError* error, bool is_raw);
307static bool ParseRtcpFbAttribute(const std::string& line,
308 const MediaType media_type,
309 MediaContentDescription* media_desc,
310 SdpParseError* error);
311static bool ParseIceOptions(const std::string& line,
312 std::vector<std::string>* transport_options,
313 SdpParseError* error);
314static bool ParseExtmap(const std::string& line,
315 RtpHeaderExtension* extmap,
316 SdpParseError* error);
317static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000318 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000319 SdpParseError* error);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000320static bool ParseDtlsSetup(const std::string& line,
321 cricket::ConnectionRole* role,
322 SdpParseError* error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000323
324// Helper functions
325
326// Below ParseFailed*** functions output the line that caused the parsing
327// failure and the detailed reason (|description|) of the failure to |error|.
328// The functions always return false so that they can be used directly in the
329// following way when error happens:
330// "return ParseFailed***(...);"
331
332// The line starting at |line_start| of |message| is the failing line.
333// The reason for the failure should be provided in the |description|.
334// An example of a description could be "unknown character".
335static bool ParseFailed(const std::string& message,
336 size_t line_start,
337 const std::string& description,
338 SdpParseError* error) {
339 // Get the first line of |message| from |line_start|.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000340 std::string first_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000341 size_t line_end = message.find(kNewLine, line_start);
342 if (line_end != std::string::npos) {
343 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
344 --line_end;
345 }
346 first_line = message.substr(line_start, (line_end - line_start));
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000347 } else {
348 first_line = message.substr(line_start);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000349 }
350
351 if (error) {
352 error->line = first_line;
353 error->description = description;
354 }
355 LOG(LS_ERROR) << "Failed to parse: \"" << first_line
356 << "\". Reason: " << description;
357 return false;
358}
359
360// |line| is the failing line. The reason for the failure should be
361// provided in the |description|.
362static bool ParseFailed(const std::string& line,
363 const std::string& description,
364 SdpParseError* error) {
365 return ParseFailed(line, 0, description, error);
366}
367
368// Parses failure where the failing SDP line isn't know or there are multiple
369// failing lines.
370static bool ParseFailed(const std::string& description,
371 SdpParseError* error) {
372 return ParseFailed("", description, error);
373}
374
375// |line| is the failing line. The failure is due to the fact that |line|
376// doesn't have |expected_fields| fields.
377static bool ParseFailedExpectFieldNum(const std::string& line,
378 int expected_fields,
379 SdpParseError* error) {
380 std::ostringstream description;
381 description << "Expects " << expected_fields << " fields.";
382 return ParseFailed(line, description.str(), error);
383}
384
385// |line| is the failing line. The failure is due to the fact that |line| has
386// less than |expected_min_fields| fields.
387static bool ParseFailedExpectMinFieldNum(const std::string& line,
388 int expected_min_fields,
389 SdpParseError* error) {
390 std::ostringstream description;
391 description << "Expects at least " << expected_min_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 it failed to
396// get the value of |attribute|.
397static bool ParseFailedGetValue(const std::string& line,
398 const std::string& attribute,
399 SdpParseError* error) {
400 std::ostringstream description;
401 description << "Failed to get the value of attribute: " << attribute;
402 return ParseFailed(line, description.str(), error);
403}
404
405// The line starting at |line_start| of |message| is the failing line. The
406// failure is due to the line type (e.g. the "m" part of the "m-line")
407// not matching what is expected. The expected line type should be
408// provided as |line_type|.
409static bool ParseFailedExpectLine(const std::string& message,
410 size_t line_start,
411 const char line_type,
412 const std::string& line_value,
413 SdpParseError* error) {
414 std::ostringstream description;
415 description << "Expect line: " << line_type << "=" << line_value;
416 return ParseFailed(message, line_start, description.str(), error);
417}
418
419static bool AddLine(const std::string& line, std::string* message) {
420 if (!message)
421 return false;
422
423 message->append(line);
424 message->append(kLineBreak);
425 return true;
426}
427
428static bool GetLine(const std::string& message,
429 size_t* pos,
430 std::string* line) {
431 size_t line_begin = *pos;
432 size_t line_end = message.find(kNewLine, line_begin);
433 if (line_end == std::string::npos) {
434 return false;
435 }
436 // Update the new start position
437 *pos = line_end + 1;
438 if (line_end > 0 && (message.at(line_end - 1) == kReturn)) {
439 --line_end;
440 }
441 *line = message.substr(line_begin, (line_end - line_begin));
442 const char* cline = line->c_str();
443 // RFC 4566
444 // An SDP session description consists of a number of lines of text of
445 // the form:
446 // <type>=<value>
447 // where <type> MUST be exactly one case-significant character and
448 // <value> is structured text whose format depends on <type>.
449 // Whitespace MUST NOT be used on either side of the "=" sign.
450 if (cline[0] == kSdpDelimiterSpace ||
451 cline[1] != kSdpDelimiterEqual ||
452 cline[2] == kSdpDelimiterSpace) {
453 *pos = line_begin;
454 return false;
455 }
456 return true;
457}
458
459// Init |os| to "|type|=|value|".
460static void InitLine(const char type,
461 const std::string& value,
462 std::ostringstream* os) {
463 os->str("");
464 *os << type << kSdpDelimiterEqual << value;
465}
466
467// Init |os| to "a=|attribute|".
468static void InitAttrLine(const std::string& attribute, std::ostringstream* os) {
469 InitLine(kLineTypeAttributes, attribute, os);
470}
471
472// Writes a SDP attribute line based on |attribute| and |value| to |message|.
473static void AddAttributeLine(const std::string& attribute, int value,
474 std::string* message) {
475 std::ostringstream os;
476 InitAttrLine(attribute, &os);
477 os << kSdpDelimiterColon << value;
478 AddLine(os.str(), message);
479}
480
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000481static bool IsLineType(const std::string& message,
482 const char type,
483 size_t line_start) {
484 if (message.size() < line_start + kLinePrefixLength) {
485 return false;
486 }
487 const char* cmessage = message.c_str();
488 return (cmessage[line_start] == type &&
489 cmessage[line_start + 1] == kSdpDelimiterEqual);
490}
491
492static bool IsLineType(const std::string& line,
493 const char type) {
494 return IsLineType(line, type, 0);
495}
496
497static bool GetLineWithType(const std::string& message, size_t* pos,
498 std::string* line, const char type) {
499 if (!IsLineType(message, type, *pos)) {
500 return false;
501 }
502
503 if (!GetLine(message, pos, line))
504 return false;
505
506 return true;
507}
508
509static bool HasAttribute(const std::string& line,
510 const std::string& attribute) {
511 return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
512}
513
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000514static bool AddSsrcLine(uint32 ssrc_id, const std::string& attribute,
515 const std::string& value, std::string* message) {
516 // RFC 5576
517 // a=ssrc:<ssrc-id> <attribute>:<value>
518 std::ostringstream os;
519 InitAttrLine(kAttributeSsrc, &os);
520 os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace
521 << attribute << kSdpDelimiterColon << value;
522 return AddLine(os.str(), message);
523}
524
525// Split the message into two parts by the first delimiter.
526static bool SplitByDelimiter(const std::string& message,
527 const char delimiter,
528 std::string* field1,
529 std::string* field2) {
530 // Find the first delimiter
531 size_t pos = message.find(delimiter);
532 if (pos == std::string::npos) {
533 return false;
534 }
535 *field1 = message.substr(0, pos);
536 // The rest is the value.
537 *field2 = message.substr(pos + 1);
538 return true;
539}
540
541// Get value only from <attribute>:<value>.
542static bool GetValue(const std::string& message, const std::string& attribute,
543 std::string* value, SdpParseError* error) {
544 std::string leftpart;
545 if (!SplitByDelimiter(message, kSdpDelimiterColon, &leftpart, value)) {
546 return ParseFailedGetValue(message, attribute, error);
547 }
548 // The left part should end with the expected attribute.
549 if (leftpart.length() < attribute.length() ||
550 leftpart.compare(leftpart.length() - attribute.length(),
551 attribute.length(), attribute) != 0) {
552 return ParseFailedGetValue(message, attribute, error);
553 }
554 return true;
555}
556
557static bool CaseInsensitiveFind(std::string str1, std::string str2) {
558 std::transform(str1.begin(), str1.end(), str1.begin(),
559 ::tolower);
560 std::transform(str2.begin(), str2.end(), str2.begin(),
561 ::tolower);
562 return str1.find(str2) != std::string::npos;
563}
564
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000565template <class T>
566static bool GetValueFromString(const std::string& line,
567 const std::string& s,
568 T* t,
569 SdpParseError* error) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000570 if (!rtc::FromString(s, t)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000571 std::ostringstream description;
572 description << "Invalid value: " << s << ".";
573 return ParseFailed(line, description.str(), error);
574 }
575 return true;
576}
577
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000578void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
579 StreamParamsVec* tracks) {
580 ASSERT(tracks != NULL);
581 for (SsrcInfoVec::const_iterator ssrc_info = ssrc_infos.begin();
582 ssrc_info != ssrc_infos.end(); ++ssrc_info) {
583 if (ssrc_info->cname.empty()) {
584 continue;
585 }
586
587 std::string sync_label;
588 std::string track_id;
589 if (ssrc_info->msid_identifier == kDefaultMsid &&
590 !ssrc_info->mslabel.empty()) {
591 // If there's no msid and there's mslabel, we consider this is a sdp from
592 // a older version of client that doesn't support msid.
593 // In that case, we use the mslabel and label to construct the track.
594 sync_label = ssrc_info->mslabel;
595 track_id = ssrc_info->label;
596 } else {
597 sync_label = ssrc_info->msid_identifier;
598 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
599 // is corresponding to the "id" attribute of StreamParams.
600 track_id = ssrc_info->msid_appdata;
601 }
602 if (sync_label.empty() || track_id.empty()) {
603 ASSERT(false);
604 continue;
605 }
606
607 StreamParamsVec::iterator track = tracks->begin();
608 for (; track != tracks->end(); ++track) {
609 if (track->id == track_id) {
610 break;
611 }
612 }
613 if (track == tracks->end()) {
614 // If we don't find an existing track, create a new one.
615 tracks->push_back(StreamParams());
616 track = tracks->end() - 1;
617 }
618 track->add_ssrc(ssrc_info->ssrc_id);
619 track->cname = ssrc_info->cname;
620 track->sync_label = sync_label;
621 track->id = track_id;
622 }
623}
624
625void GetMediaStreamLabels(const ContentInfo* content,
626 std::set<std::string>* labels) {
627 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000628 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000629 content->description);
630 const cricket::StreamParamsVec& streams = media_desc->streams();
631 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
632 it != streams.end(); ++it) {
633 labels->insert(it->sync_label);
634 }
635}
636
637// RFC 5245
638// It is RECOMMENDED that default candidates be chosen based on the
639// likelihood of those candidates to work with the peer that is being
640// contacted. It is RECOMMENDED that relayed > reflexive > host.
641static const int kPreferenceUnknown = 0;
642static const int kPreferenceHost = 1;
643static const int kPreferenceReflexive = 2;
644static const int kPreferenceRelayed = 3;
645
646static int GetCandidatePreferenceFromType(const std::string& type) {
647 int preference = kPreferenceUnknown;
648 if (type == cricket::LOCAL_PORT_TYPE) {
649 preference = kPreferenceHost;
650 } else if (type == cricket::STUN_PORT_TYPE) {
651 preference = kPreferenceReflexive;
652 } else if (type == cricket::RELAY_PORT_TYPE) {
653 preference = kPreferenceRelayed;
654 } else {
655 ASSERT(false);
656 }
657 return preference;
658}
659
660// Get ip and port of the default destination from the |candidates| with
661// the given value of |component_id|.
662// RFC 5245
663// The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
664// TODO: Decide the default destination in webrtcsession and
665// pass it down via SessionDescription.
666static bool GetDefaultDestination(const std::vector<Candidate>& candidates,
667 int component_id, std::string* port, std::string* ip) {
668 *port = kDefaultPort;
669 *ip = kDefaultAddress;
670 int current_preference = kPreferenceUnknown;
671 for (std::vector<Candidate>::const_iterator it = candidates.begin();
672 it != candidates.end(); ++it) {
673 if (it->component() != component_id) {
674 continue;
675 }
676 const int preference = GetCandidatePreferenceFromType(it->type());
677 // See if this candidate is more preferable then the current one.
678 if (preference <= current_preference) {
679 continue;
680 }
681 current_preference = preference;
682 *port = it->address().PortAsString();
683 *ip = it->address().ipaddr().ToString();
684 }
685 return true;
686}
687
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000688// Update |mline|'s default destination and append a c line after it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689static void UpdateMediaDefaultDestination(
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000690 const std::vector<Candidate>& candidates,
691 const std::string mline,
692 std::string* message) {
693 std::string new_lines;
694 AddLine(mline, &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695 // RFC 4566
696 // m=<media> <port> <proto> <fmt> ...
697 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000698 rtc::split(mline, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000699 if (fields.size() < 3) {
700 return;
701 }
702
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000703 std::ostringstream os;
704 std::string rtp_port, rtp_ip;
705 if (GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
706 &rtp_port, &rtp_ip)) {
707 // Found default RTP candidate.
708 // RFC 5245
709 // The default candidates are added to the SDP as the default
710 // destination for media. For streams based on RTP, this is done by
711 // placing the IP address and port of the RTP candidate into the c and m
712 // lines, respectively.
713
714 // Update the port in the m line.
715 // If this is a m-line with port equal to 0, we don't change it.
716 if (fields[1] != kMediaPortRejected) {
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000717 new_lines.replace(fields[0].size() + 1,
718 fields[1].size(),
719 rtp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000720 }
721 // Add the c line.
722 // RFC 4566
723 // c=<nettype> <addrtype> <connection-address>
724 InitLine(kLineTypeConnection, kConnectionNettype, &os);
725 os << " " << kConnectionAddrtype << " " << rtp_ip;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000726 AddLine(os.str(), &new_lines);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727 }
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000728 message->append(new_lines);
729}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000731// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
732static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
733 std::string rtcp_line, rtcp_port, rtcp_ip;
734 if (GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
735 &rtcp_port, &rtcp_ip)) {
736 // Found default RTCP candidate.
737 // RFC 5245
738 // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
739 // using the a=rtcp attribute as defined in RFC 3605.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000741 // RFC 3605
742 // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
743 // connection-address] CRLF
744 std::ostringstream os;
745 InitAttrLine(kAttributeRtcp, &os);
746 os << kSdpDelimiterColon
747 << rtcp_port << " "
748 << kConnectionNettype << " "
749 << kConnectionAddrtype << " "
750 << rtcp_ip;
751 rtcp_line = os.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000752 }
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000753 return rtcp_line;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000754}
755
756// Get candidates according to the mline index from SessionDescriptionInterface.
757static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
758 int mline_index,
759 std::vector<Candidate>* candidates) {
760 if (!candidates) {
761 return;
762 }
763 const IceCandidateCollection* cc = desci.candidates(mline_index);
764 for (size_t i = 0; i < cc->count(); ++i) {
765 const IceCandidateInterface* candidate = cc->at(i);
766 candidates->push_back(candidate->candidate());
767 }
768}
769
770std::string SdpSerialize(const JsepSessionDescription& jdesc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771 const cricket::SessionDescription* desc = jdesc.description();
772 if (!desc) {
773 return "";
774 }
775
776 std::string message;
777
778 // Session Description.
779 AddLine(kSessionVersion, &message);
780 // Session Origin
781 // RFC 4566
782 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
783 // <unicast-address>
784 std::ostringstream os;
785 InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
786 const std::string session_id = jdesc.session_id().empty() ?
787 kSessionOriginSessionId : jdesc.session_id();
788 const std::string session_version = jdesc.session_version().empty() ?
789 kSessionOriginSessionVersion : jdesc.session_version();
790 os << " " << session_id << " " << session_version << " "
791 << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
792 << kSessionOriginAddress;
793 AddLine(os.str(), &message);
794 AddLine(kSessionName, &message);
795
796 // Time Description.
797 AddLine(kTimeDescription, &message);
798
799 // Group
800 if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
801 std::string group_line = kAttrGroup;
802 const cricket::ContentGroup* group =
803 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
804 ASSERT(group != NULL);
805 const cricket::ContentNames& content_names = group->content_names();
806 for (cricket::ContentNames::const_iterator it = content_names.begin();
807 it != content_names.end(); ++it) {
808 group_line.append(" ");
809 group_line.append(*it);
810 }
811 AddLine(group_line, &message);
812 }
813
814 // MediaStream semantics
815 InitAttrLine(kAttributeMsidSemantics, &os);
816 os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000817
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818 std::set<std::string> media_stream_labels;
819 const ContentInfo* audio_content = GetFirstAudioContent(desc);
820 if (audio_content)
821 GetMediaStreamLabels(audio_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000822
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823 const ContentInfo* video_content = GetFirstVideoContent(desc);
824 if (video_content)
825 GetMediaStreamLabels(video_content, &media_stream_labels);
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000826
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827 for (std::set<std::string>::const_iterator it =
828 media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
829 os << " " << *it;
830 }
831 AddLine(os.str(), &message);
832
wu@webrtc.org4c3e9912014-07-16 21:03:13 +0000833 // Preserve the order of the media contents.
834 int mline_index = -1;
835 for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
836 it != desc->contents().end(); ++it) {
837 const MediaContentDescription* mdesc =
838 static_cast<const MediaContentDescription*>(it->description);
839 std::vector<Candidate> candidates;
840 GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
841 BuildMediaDescription(&*it,
842 desc->GetTransportInfoByName(it->name),
843 mdesc->type(),
844 candidates,
845 &message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000847 return message;
848}
849
850// Serializes the passed in IceCandidateInterface to a SDP string.
851// candidate - The candidate to be serialized.
852std::string SdpSerializeCandidate(
853 const IceCandidateInterface& candidate) {
854 std::string message;
855 std::vector<cricket::Candidate> candidates;
856 candidates.push_back(candidate.candidate());
857 BuildCandidate(candidates, &message);
wu@webrtc.orgec9f5fb2014-06-24 17:05:10 +0000858 // From WebRTC draft section 4.8.1.1 candidate-attribute will be
859 // just candidate:<candidate> not a=candidate:<blah>CRLF
860 ASSERT(message.find("a=") == 0);
861 message.erase(0, 2);
862 ASSERT(message.find(kLineBreak) == message.size() - 2);
863 message.resize(message.size() - 2);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000864 return message;
865}
866
867bool SdpDeserialize(const std::string& message,
868 JsepSessionDescription* jdesc,
869 SdpParseError* error) {
870 std::string session_id;
871 std::string session_version;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000872 TransportDescription session_td(NS_JINGLE_ICE_UDP,
873 std::string(), std::string());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874 RtpHeaderExtensions session_extmaps;
875 cricket::SessionDescription* desc = new cricket::SessionDescription();
876 std::vector<JsepIceCandidate*> candidates;
877 size_t current_pos = 0;
878 bool supports_msid = false;
879
880 // Session Description
881 if (!ParseSessionDescription(message, &current_pos, &session_id,
882 &session_version, &supports_msid, &session_td,
883 &session_extmaps, desc, error)) {
884 delete desc;
885 return false;
886 }
887
888 // Media Description
889 if (!ParseMediaDescription(message, session_td, session_extmaps,
890 supports_msid, &current_pos, desc, &candidates,
891 error)) {
892 delete desc;
893 for (std::vector<JsepIceCandidate*>::const_iterator
894 it = candidates.begin(); it != candidates.end(); ++it) {
895 delete *it;
896 }
897 return false;
898 }
899
900 jdesc->Initialize(desc, session_id, session_version);
901
902 for (std::vector<JsepIceCandidate*>::const_iterator
903 it = candidates.begin(); it != candidates.end(); ++it) {
904 jdesc->AddCandidate(*it);
905 delete *it;
906 }
907 return true;
908}
909
910bool SdpDeserializeCandidate(const std::string& message,
911 JsepIceCandidate* jcandidate,
912 SdpParseError* error) {
913 ASSERT(jcandidate != NULL);
914 Candidate candidate;
915 if (!ParseCandidate(message, &candidate, error, true)) {
916 return false;
917 }
918 jcandidate->SetCandidate(candidate);
919 return true;
920}
921
922bool ParseCandidate(const std::string& message, Candidate* candidate,
923 SdpParseError* error, bool is_raw) {
924 ASSERT(candidate != NULL);
925
926 // Get the first line from |message|.
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000927 std::string first_line = message;
928 size_t pos = 0;
929 GetLine(message, &pos, &first_line);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000931 // Makes sure |message| contains only one line.
932 if (message.size() > first_line.size()) {
933 std::string left, right;
934 if (SplitByDelimiter(message, kNewLine, &left, &right) && !right.empty()) {
935 return ParseFailed(message, 0, "Expect one line only", error);
936 }
937 }
938
939 // From WebRTC draft section 4.8.1.1 candidate-attribute should be
940 // candidate:<candidate> when trickled, but we still support
941 // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
942 // from the SDP.
943 if (IsLineType(first_line, kLineTypeAttributes)) {
944 first_line = first_line.substr(kLinePrefixLength);
945 }
946
947 std::string attribute_candidate;
948 std::string candidate_value;
949
950 // |first_line| must be in the form of "candidate:<value>".
951 if (!SplitByDelimiter(first_line, kSdpDelimiterColon,
952 &attribute_candidate, &candidate_value) ||
953 attribute_candidate != kAttributeCandidate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954 if (is_raw) {
955 std::ostringstream description;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000956 description << "Expect line: " << kAttributeCandidate
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000957 << ":" << "<candidate-str>";
958 return ParseFailed(first_line, 0, description.str(), error);
959 } else {
960 return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
961 kAttributeCandidate, error);
962 }
963 }
964
965 std::vector<std::string> fields;
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000966 rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
967
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000968 // RFC 5245
969 // a=candidate:<foundation> <component-id> <transport> <priority>
970 // <connection-address> <port> typ <candidate-types>
971 // [raddr <connection-address>] [rport <port>]
972 // *(SP extension-att-name SP extension-att-value)
973 const size_t expected_min_fields = 8;
974 if (fields.size() < expected_min_fields ||
975 (fields[6] != kAttributeCandidateTyp)) {
976 return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
977 }
jiayl@webrtc.org7ec3f9f2014-08-08 23:09:15 +0000978 std::string foundation = fields[0];
979
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000980 int component_id = 0;
981 if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
982 return false;
983 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984 const std::string transport = fields[2];
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000985 uint32 priority = 0;
986 if (!GetValueFromString(first_line, fields[3], &priority, error)) {
987 return false;
988 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989 const std::string connection_address = fields[4];
wu@webrtc.org5e760e72014-04-02 23:19:09 +0000990 int port = 0;
991 if (!GetValueFromString(first_line, fields[5], &port, error)) {
992 return false;
993 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994 SocketAddress address(connection_address, port);
995
996 cricket::ProtocolType protocol;
997 if (!StringToProto(transport.c_str(), &protocol)) {
998 return ParseFailed(first_line, "Unsupported transport type.", error);
999 }
1000
1001 std::string candidate_type;
1002 const std::string type = fields[7];
1003 if (type == kCandidateHost) {
1004 candidate_type = cricket::LOCAL_PORT_TYPE;
1005 } else if (type == kCandidateSrflx) {
1006 candidate_type = cricket::STUN_PORT_TYPE;
1007 } else if (type == kCandidateRelay) {
1008 candidate_type = cricket::RELAY_PORT_TYPE;
1009 } else {
1010 return ParseFailed(first_line, "Unsupported candidate type.", error);
1011 }
1012
1013 size_t current_position = expected_min_fields;
1014 SocketAddress related_address;
1015 // The 2 optional fields for related address
1016 // [raddr <connection-address>] [rport <port>]
1017 if (fields.size() >= (current_position + 2) &&
1018 fields[current_position] == kAttributeCandidateRaddr) {
1019 related_address.SetIP(fields[++current_position]);
1020 ++current_position;
1021 }
1022 if (fields.size() >= (current_position + 2) &&
1023 fields[current_position] == kAttributeCandidateRport) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001024 int port = 0;
1025 if (!GetValueFromString(
1026 first_line, fields[++current_position], &port, error)) {
1027 return false;
1028 }
1029 related_address.SetPort(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030 ++current_position;
1031 }
1032
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001033 // If this is a TCP candidate, it has additional extension as defined in
1034 // RFC 6544.
1035 std::string tcptype;
1036 if (fields.size() >= (current_position + 2) &&
1037 fields[current_position] == kTcpCandidateType) {
1038 tcptype = fields[++current_position];
1039 ++current_position;
1040
1041 if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1042 tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1043 tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1044 return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1045 }
1046
1047 if (protocol != cricket::PROTO_TCP) {
1048 return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1049 }
1050 }
1051
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052 // Extension
1053 // Empty string as the candidate username and password.
1054 // Will be updated later with the ice-ufrag and ice-pwd.
1055 // TODO: Remove the username/password extension, which is currently
1056 // kept for backwards compatibility.
1057 std::string username;
1058 std::string password;
1059 uint32 generation = 0;
1060 for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1061 // RFC 5245
1062 // *(SP extension-att-name SP extension-att-value)
1063 if (fields[i] == kAttributeCandidateGeneration) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001064 if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1065 return false;
1066 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001067 } else if (fields[i] == kAttributeCandidateUsername) {
1068 username = fields[++i];
1069 } else if (fields[i] == kAttributeCandidatePassword) {
1070 password = fields[++i];
1071 } else {
1072 // Skip the unknown extension.
1073 ++i;
1074 }
1075 }
1076
1077 // Empty string as the candidate id and network name.
1078 const std::string id;
1079 const std::string network_name;
1080 *candidate = Candidate(id, component_id, cricket::ProtoToString(protocol),
1081 address, priority, username, password, candidate_type, network_name,
1082 generation, foundation);
1083 candidate->set_related_address(related_address);
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001084 candidate->set_tcptype(tcptype);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001085 return true;
1086}
1087
1088bool ParseIceOptions(const std::string& line,
1089 std::vector<std::string>* transport_options,
1090 SdpParseError* error) {
1091 std::string ice_options;
1092 if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1093 return false;
1094 }
1095 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001096 rtc::split(ice_options, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001097 for (size_t i = 0; i < fields.size(); ++i) {
1098 transport_options->push_back(fields[i]);
1099 }
1100 return true;
1101}
1102
1103bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
1104 SdpParseError* error) {
1105 // RFC 5285
1106 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1107 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001108 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001109 kSdpDelimiterSpace, &fields);
1110 const size_t expected_min_fields = 2;
1111 if (fields.size() < expected_min_fields) {
1112 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1113 }
1114 std::string uri = fields[1];
1115
1116 std::string value_direction;
1117 if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1118 return false;
1119 }
1120 std::vector<std::string> sub_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001121 rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001122 int value = 0;
1123 if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1124 return false;
1125 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001126
1127 *extmap = RtpHeaderExtension(uri, value);
1128 return true;
1129}
1130
1131void BuildMediaDescription(const ContentInfo* content_info,
1132 const TransportInfo* transport_info,
1133 const MediaType media_type,
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001134 const std::vector<Candidate>& candidates,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001135 std::string* message) {
1136 ASSERT(message != NULL);
1137 if (content_info == NULL || message == NULL) {
1138 return;
1139 }
1140 // TODO: Rethink if we should use sprintfn instead of stringstream.
1141 // According to the style guide, streams should only be used for logging.
1142 // http://google-styleguide.googlecode.com/svn/
1143 // trunk/cppguide.xml?showone=Streams#Streams
1144 std::ostringstream os;
1145 const MediaContentDescription* media_desc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001146 static_cast<const MediaContentDescription*>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001147 content_info->description);
1148 ASSERT(media_desc != NULL);
1149
1150 bool is_sctp = (media_desc->protocol() == cricket::kMediaProtocolDtlsSctp);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001151 int sctp_port = cricket::kSctpDefaultPort;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152
1153 // RFC 4566
1154 // m=<media> <port> <proto> <fmt>
1155 // fmt is a list of payload type numbers that MAY be used in the session.
1156 const char* type = NULL;
1157 if (media_type == cricket::MEDIA_TYPE_AUDIO)
1158 type = kMediaTypeAudio;
1159 else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1160 type = kMediaTypeVideo;
1161 else if (media_type == cricket::MEDIA_TYPE_DATA)
1162 type = kMediaTypeData;
1163 else
1164 ASSERT(false);
1165
1166 std::string fmt;
1167 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1168 const VideoContentDescription* video_desc =
1169 static_cast<const VideoContentDescription*>(media_desc);
1170 for (std::vector<cricket::VideoCodec>::const_iterator it =
1171 video_desc->codecs().begin();
1172 it != video_desc->codecs().end(); ++it) {
1173 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001174 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001175 }
1176 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1177 const AudioContentDescription* audio_desc =
1178 static_cast<const AudioContentDescription*>(media_desc);
1179 for (std::vector<cricket::AudioCodec>::const_iterator it =
1180 audio_desc->codecs().begin();
1181 it != audio_desc->codecs().end(); ++it) {
1182 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001183 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001184 }
1185 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001186 const DataContentDescription* data_desc =
1187 static_cast<const DataContentDescription*>(media_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188 if (is_sctp) {
1189 fmt.append(" ");
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001190
1191 for (std::vector<cricket::DataCodec>::const_iterator it =
1192 data_desc->codecs().begin();
1193 it != data_desc->codecs().end(); ++it) {
1194 if (it->id == cricket::kGoogleSctpDataCodecId &&
1195 it->GetParam(cricket::kCodecParamPort, &sctp_port)) {
1196 break;
1197 }
1198 }
1199
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001200 fmt.append(rtc::ToString<int>(sctp_port));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001201 } else {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001202 for (std::vector<cricket::DataCodec>::const_iterator it =
1203 data_desc->codecs().begin();
1204 it != data_desc->codecs().end(); ++it) {
1205 fmt.append(" ");
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001206 fmt.append(rtc::ToString<int>(it->id));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001207 }
1208 }
1209 }
1210 // The fmt must never be empty. If no codecs are found, set the fmt attribute
1211 // to 0.
1212 if (fmt.empty()) {
1213 fmt = " 0";
1214 }
1215
1216 // The port number in the m line will be updated later when associate with
1217 // the candidates.
1218 // RFC 3264
1219 // To reject an offered stream, the port number in the corresponding stream in
1220 // the answer MUST be set to zero.
1221 const std::string port = content_info->rejected ?
1222 kMediaPortRejected : kDefaultPort;
1223
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001224 rtc::SSLFingerprint* fp = (transport_info) ?
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001225 transport_info->description.identity_fingerprint.get() : NULL;
1226
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001227 // Add the m and c lines.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228 InitLine(kLineTypeMedia, type, &os);
1229 os << " " << port << " " << media_desc->protocol() << fmt;
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001230 std::string mline = os.str();
1231 UpdateMediaDefaultDestination(candidates, mline, message);
1232
1233 // RFC 4566
1234 // b=AS:<bandwidth>
1235 // We should always use the default bandwidth for RTP-based data
1236 // channels. Don't allow SDP to set the bandwidth, because that
1237 // would give JS the opportunity to "break the Internet".
1238 // TODO(pthatcher): But we need to temporarily allow the SDP to control
1239 // this for backwards-compatibility. Once we don't need that any
1240 // more, remove this.
1241 bool support_dc_sdp_bandwidth_temporarily = true;
1242 if (media_desc->bandwidth() >= 1000 &&
1243 (media_type != cricket::MEDIA_TYPE_DATA ||
1244 support_dc_sdp_bandwidth_temporarily)) {
1245 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1246 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1247 AddLine(os.str(), message);
1248 }
1249
1250 // Add the a=rtcp line.
1251 bool is_rtp =
1252 media_desc->protocol().empty() ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001253 rtc::starts_with(media_desc->protocol().data(),
wu@webrtc.org4c3e9912014-07-16 21:03:13 +00001254 cricket::kMediaProtocolRtpPrefix);
1255 if (is_rtp) {
1256 std::string rtcp_line = GetRtcpLine(candidates);
1257 if (!rtcp_line.empty()) {
1258 AddLine(rtcp_line, message);
1259 }
1260 }
1261
1262 // Build the a=candidate lines.
1263 BuildCandidate(candidates, message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001264
1265 // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1266 if (transport_info) {
1267 // RFC 5245
1268 // ice-pwd-att = "ice-pwd" ":" password
1269 // ice-ufrag-att = "ice-ufrag" ":" ufrag
1270 // ice-ufrag
1271 InitAttrLine(kAttributeIceUfrag, &os);
1272 os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1273 AddLine(os.str(), message);
1274 // ice-pwd
1275 InitAttrLine(kAttributeIcePwd, &os);
1276 os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1277 AddLine(os.str(), message);
1278
1279 // draft-petithuguenin-mmusic-ice-attributes-level-03
1280 BuildIceOptions(transport_info->description.transport_options, message);
1281
1282 // RFC 4572
1283 // fingerprint-attribute =
1284 // "fingerprint" ":" hash-func SP fingerprint
1285 if (fp) {
1286 // Insert the fingerprint attribute.
1287 InitAttrLine(kAttributeFingerprint, &os);
1288 os << kSdpDelimiterColon
1289 << fp->algorithm << kSdpDelimiterSpace
1290 << fp->GetRfc4572Fingerprint();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291 AddLine(os.str(), message);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001292
1293 // Inserting setup attribute.
1294 if (transport_info->description.connection_role !=
1295 cricket::CONNECTIONROLE_NONE) {
1296 // Making sure we are not using "passive" mode.
1297 cricket::ConnectionRole role =
1298 transport_info->description.connection_role;
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001299 std::string dtls_role_str;
1300 VERIFY(cricket::ConnectionRoleToString(role, &dtls_role_str));
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001301 InitAttrLine(kAttributeSetup, &os);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001302 os << kSdpDelimiterColon << dtls_role_str;
1303 AddLine(os.str(), message);
1304 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305 }
1306 }
1307
1308 // RFC 3388
1309 // mid-attribute = "a=mid:" identification-tag
1310 // identification-tag = token
1311 // Use the content name as the mid identification-tag.
1312 InitAttrLine(kAttributeMid, &os);
1313 os << kSdpDelimiterColon << content_info->name;
1314 AddLine(os.str(), message);
1315
1316 if (is_sctp) {
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001317 BuildSctpContentAttributes(message, sctp_port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001318 } else {
1319 BuildRtpContentAttributes(media_desc, media_type, message);
1320 }
1321}
1322
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001323void BuildSctpContentAttributes(std::string* message, int sctp_port) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001324 // draft-ietf-mmusic-sctp-sdp-04
1325 // a=sctpmap:sctpmap-number protocol [streams]
1326 std::ostringstream os;
1327 InitAttrLine(kAttributeSctpmap, &os);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00001328 os << kSdpDelimiterColon << sctp_port << kSdpDelimiterSpace
wu@webrtc.org78187522013-10-07 23:32:02 +00001329 << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1330 << (cricket::kMaxSctpSid + 1);
1331 AddLine(os.str(), message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332}
1333
1334void BuildRtpContentAttributes(
1335 const MediaContentDescription* media_desc,
1336 const MediaType media_type,
1337 std::string* message) {
1338 std::ostringstream os;
1339 // RFC 5285
1340 // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1341 // The definitions MUST be either all session level or all media level. This
1342 // implementation uses all media level.
1343 for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1344 InitAttrLine(kAttributeExtmap, &os);
1345 os << kSdpDelimiterColon << media_desc->rtp_header_extensions()[i].id
1346 << kSdpDelimiterSpace << media_desc->rtp_header_extensions()[i].uri;
1347 AddLine(os.str(), message);
1348 }
1349
1350 // RFC 3264
1351 // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
1352
1353 cricket::MediaContentDirection direction = media_desc->direction();
1354 if (media_desc->streams().empty() && direction == cricket::MD_SENDRECV) {
1355 direction = cricket::MD_RECVONLY;
1356 }
1357
1358 switch (direction) {
1359 case cricket::MD_INACTIVE:
1360 InitAttrLine(kAttributeInactive, &os);
1361 break;
1362 case cricket::MD_SENDONLY:
1363 InitAttrLine(kAttributeSendOnly, &os);
1364 break;
1365 case cricket::MD_RECVONLY:
1366 InitAttrLine(kAttributeRecvOnly, &os);
1367 break;
1368 case cricket::MD_SENDRECV:
1369 default:
1370 InitAttrLine(kAttributeSendRecv, &os);
1371 break;
1372 }
1373 AddLine(os.str(), message);
1374
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375 // RFC 5761
1376 // a=rtcp-mux
1377 if (media_desc->rtcp_mux()) {
1378 InitAttrLine(kAttributeRtcpMux, &os);
1379 AddLine(os.str(), message);
1380 }
1381
1382 // RFC 4568
1383 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1384 for (std::vector<CryptoParams>::const_iterator it =
1385 media_desc->cryptos().begin();
1386 it != media_desc->cryptos().end(); ++it) {
1387 InitAttrLine(kAttributeCrypto, &os);
1388 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1389 << it->key_params;
1390 if (!it->session_params.empty()) {
1391 os << " " << it->session_params;
1392 }
1393 AddLine(os.str(), message);
1394 }
1395
1396 // RFC 4566
1397 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1398 // [/<encodingparameters>]
1399 BuildRtpMap(media_desc, media_type, message);
1400
1401 // Specify latency for buffered mode.
1402 // a=x-google-buffer-latency:<value>
1403 if (media_desc->buffered_mode_latency() != cricket::kBufferedModeDisabled) {
1404 std::ostringstream os;
1405 InitAttrLine(kAttributeXGoogleBufferLatency, &os);
1406 os << kSdpDelimiterColon << media_desc->buffered_mode_latency();
1407 AddLine(os.str(), message);
1408 }
1409
1410 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1411 track != media_desc->streams().end(); ++track) {
1412 // Require that the track belongs to a media stream,
1413 // ie the sync_label is set. This extra check is necessary since the
1414 // MediaContentDescription always contains a streamparam with an ssrc even
1415 // if no track or media stream have been created.
1416 if (track->sync_label.empty()) continue;
1417
1418 // Build the ssrc-group lines.
1419 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1420 // RFC 5576
1421 // a=ssrc-group:<semantics> <ssrc-id> ...
1422 if (track->ssrc_groups[i].ssrcs.empty()) {
1423 continue;
1424 }
1425 std::ostringstream os;
1426 InitAttrLine(kAttributeSsrcGroup, &os);
1427 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
1428 std::vector<uint32>::const_iterator ssrc =
1429 track->ssrc_groups[i].ssrcs.begin();
1430 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001431 os << kSdpDelimiterSpace << rtc::ToString<uint32>(*ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432 }
1433 AddLine(os.str(), message);
1434 }
1435 // Build the ssrc lines for each ssrc.
1436 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
1437 uint32 ssrc = track->ssrcs[i];
1438 // RFC 5576
1439 // a=ssrc:<ssrc-id> cname:<value>
1440 AddSsrcLine(ssrc, kSsrcAttributeCname,
1441 track->cname, message);
1442
1443 // draft-alvestrand-mmusic-msid-00
1444 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1445 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1446 // is corresponding to the "name" attribute of StreamParams.
1447 std::string appdata = track->id;
1448 std::ostringstream os;
1449 InitAttrLine(kAttributeSsrc, &os);
1450 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1451 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1452 << kSdpDelimiterSpace << appdata;
1453 AddLine(os.str(), message);
1454
1455 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1456 // draft-alvestrand-rtcweb-mid-01
1457 // a=ssrc:<ssrc-id> mslabel:<value>
1458 // The label isn't yet defined.
1459 // a=ssrc:<ssrc-id> label:<value>
1460 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1461 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1462 }
1463 }
1464}
1465
1466void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1467 // fmtp header: a=fmtp:|payload_type| <parameters>
1468 // Add a=fmtp
1469 InitAttrLine(kAttributeFmtp, os);
1470 // Add :|payload_type|
1471 *os << kSdpDelimiterColon << payload_type;
1472}
1473
1474void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1475 // rtcp-fb header: a=rtcp-fb:|payload_type|
1476 // <parameters>/<ccm <ccm_parameters>>
1477 // Add a=rtcp-fb
1478 InitAttrLine(kAttributeRtcpFb, os);
1479 // Add :
1480 *os << kSdpDelimiterColon;
1481 if (payload_type == kWildcardPayloadType) {
1482 *os << "*";
1483 } else {
1484 *os << payload_type;
1485 }
1486}
1487
1488void WriteFmtpParameter(const std::string& parameter_name,
1489 const std::string& parameter_value,
1490 std::ostringstream* os) {
1491 // fmtp parameters: |parameter_name|=|parameter_value|
1492 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1493}
1494
1495void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1496 std::ostringstream* os) {
1497 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1498 fmtp != parameters.end(); ++fmtp) {
1499 // Each new parameter, except the first one starts with ";" and " ".
1500 if (fmtp != parameters.begin()) {
1501 *os << kSdpDelimiterSemicolon;
1502 }
1503 *os << kSdpDelimiterSpace;
1504 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1505 }
1506}
1507
1508bool IsFmtpParam(const std::string& name) {
1509 const char* kFmtpParams[] = {
1510 kCodecParamMinPTime, kCodecParamSPropStereo,
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +00001511 kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamStartBitrate,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001512 kCodecParamMaxBitrate, kCodecParamMinBitrate, kCodecParamMaxQuantization,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001513 kCodecParamSctpProtocol, kCodecParamSctpStreams,
stefan@webrtc.org85d27942014-06-09 12:51:39 +00001514 kCodecParamMaxAverageBitrate, kCodecParamAssociatedPayloadType
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001515 };
1516 for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
1517 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1518 return true;
1519 }
1520 }
1521 return false;
1522}
1523
1524// Retreives fmtp parameters from |params|, which may contain other parameters
1525// as well, and puts them in |fmtp_parameters|.
1526void GetFmtpParams(const cricket::CodecParameterMap& params,
1527 cricket::CodecParameterMap* fmtp_parameters) {
1528 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1529 iter != params.end(); ++iter) {
1530 if (IsFmtpParam(iter->first)) {
1531 (*fmtp_parameters)[iter->first] = iter->second;
1532 }
1533 }
1534}
1535
1536template <class T>
1537void AddFmtpLine(const T& codec, std::string* message) {
1538 cricket::CodecParameterMap fmtp_parameters;
1539 GetFmtpParams(codec.params, &fmtp_parameters);
1540 if (fmtp_parameters.empty()) {
1541 // No need to add an fmtp if it will have no (optional) parameters.
1542 return;
1543 }
1544 std::ostringstream os;
1545 WriteFmtpHeader(codec.id, &os);
1546 WriteFmtpParameters(fmtp_parameters, &os);
1547 AddLine(os.str(), message);
1548 return;
1549}
1550
1551template <class T>
1552void AddRtcpFbLines(const T& codec, std::string* message) {
1553 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1554 codec.feedback_params.params().begin();
1555 iter != codec.feedback_params.params().end(); ++iter) {
1556 std::ostringstream os;
1557 WriteRtcpFbHeader(codec.id, &os);
1558 os << " " << iter->id();
1559 if (!iter->param().empty()) {
1560 os << " " << iter->param();
1561 }
1562 AddLine(os.str(), message);
1563 }
1564}
1565
1566bool GetMinValue(const std::vector<int>& values, int* value) {
1567 if (values.empty()) {
1568 return false;
1569 }
1570 std::vector<int>::const_iterator found =
1571 std::min_element(values.begin(), values.end());
1572 *value = *found;
1573 return true;
1574}
1575
1576bool GetParameter(const std::string& name,
1577 const cricket::CodecParameterMap& params, int* value) {
1578 std::map<std::string, std::string>::const_iterator found =
1579 params.find(name);
1580 if (found == params.end()) {
1581 return false;
1582 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001583 if (!rtc::FromString(found->second, value)) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00001584 return false;
1585 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586 return true;
1587}
1588
1589void BuildRtpMap(const MediaContentDescription* media_desc,
1590 const MediaType media_type,
1591 std::string* message) {
1592 ASSERT(message != NULL);
1593 ASSERT(media_desc != NULL);
1594 std::ostringstream os;
1595 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1596 const VideoContentDescription* video_desc =
1597 static_cast<const VideoContentDescription*>(media_desc);
1598 for (std::vector<cricket::VideoCodec>::const_iterator it =
1599 video_desc->codecs().begin();
1600 it != video_desc->codecs().end(); ++it) {
1601 // RFC 4566
1602 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1603 // [/<encodingparameters>]
1604 if (it->id != kWildcardPayloadType) {
1605 InitAttrLine(kAttributeRtpmap, &os);
1606 os << kSdpDelimiterColon << it->id << " " << it->name
1607 << "/" << kDefaultVideoClockrate;
1608 AddLine(os.str(), message);
1609 }
1610 AddRtcpFbLines(*it, message);
1611 AddFmtpLine(*it, message);
1612 }
1613 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1614 const AudioContentDescription* audio_desc =
1615 static_cast<const AudioContentDescription*>(media_desc);
1616 std::vector<int> ptimes;
1617 std::vector<int> maxptimes;
1618 int max_minptime = 0;
1619 for (std::vector<cricket::AudioCodec>::const_iterator it =
1620 audio_desc->codecs().begin();
1621 it != audio_desc->codecs().end(); ++it) {
1622 ASSERT(!it->name.empty());
1623 // RFC 4566
1624 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1625 // [/<encodingparameters>]
1626 InitAttrLine(kAttributeRtpmap, &os);
1627 os << kSdpDelimiterColon << it->id << " ";
1628 os << it->name << "/" << it->clockrate;
1629 if (it->channels != 1) {
1630 os << "/" << it->channels;
1631 }
1632 AddLine(os.str(), message);
1633 AddRtcpFbLines(*it, message);
1634 AddFmtpLine(*it, message);
1635 int minptime = 0;
1636 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1637 max_minptime = std::max(minptime, max_minptime);
1638 }
1639 int ptime;
1640 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1641 ptimes.push_back(ptime);
1642 }
1643 int maxptime;
1644 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1645 maxptimes.push_back(maxptime);
1646 }
1647 }
1648 // Populate the maxptime attribute with the smallest maxptime of all codecs
1649 // under the same m-line.
1650 int min_maxptime = INT_MAX;
1651 if (GetMinValue(maxptimes, &min_maxptime)) {
1652 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1653 }
1654 ASSERT(min_maxptime > max_minptime);
1655 // Populate the ptime attribute with the smallest ptime or the largest
1656 // minptime, whichever is the largest, for all codecs under the same m-line.
1657 int ptime = INT_MAX;
1658 if (GetMinValue(ptimes, &ptime)) {
1659 ptime = std::min(ptime, min_maxptime);
1660 ptime = std::max(ptime, max_minptime);
1661 AddAttributeLine(kCodecParamPTime, ptime, message);
1662 }
1663 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1664 const DataContentDescription* data_desc =
1665 static_cast<const DataContentDescription*>(media_desc);
1666 for (std::vector<cricket::DataCodec>::const_iterator it =
1667 data_desc->codecs().begin();
1668 it != data_desc->codecs().end(); ++it) {
1669 // RFC 4566
1670 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1671 // [/<encodingparameters>]
1672 InitAttrLine(kAttributeRtpmap, &os);
1673 os << kSdpDelimiterColon << it->id << " "
1674 << it->name << "/" << it->clockrate;
1675 AddLine(os.str(), message);
1676 }
1677 }
1678}
1679
1680void BuildCandidate(const std::vector<Candidate>& candidates,
1681 std::string* message) {
1682 std::ostringstream os;
1683
1684 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1685 it != candidates.end(); ++it) {
1686 // RFC 5245
1687 // a=candidate:<foundation> <component-id> <transport> <priority>
1688 // <connection-address> <port> typ <candidate-types>
1689 // [raddr <connection-address>] [rport <port>]
1690 // *(SP extension-att-name SP extension-att-value)
1691 std::string type;
1692 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1693 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1694 type = kCandidateHost;
1695 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1696 type = kCandidateSrflx;
1697 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1698 type = kCandidateRelay;
1699 } else {
1700 ASSERT(false);
1701 }
1702
1703 InitAttrLine(kAttributeCandidate, &os);
1704 os << kSdpDelimiterColon
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001705 << it->foundation() << " "
1706 << it->component() << " "
1707 << it->protocol() << " "
1708 << it->priority() << " "
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001709 << it->address().ipaddr().ToString() << " "
1710 << it->address().PortAsString() << " "
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001711 << kAttributeCandidateTyp << " "
1712 << type << " ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001713
1714 // Related address
1715 if (!it->related_address().IsNil()) {
1716 os << kAttributeCandidateRaddr << " "
1717 << it->related_address().ipaddr().ToString() << " "
1718 << kAttributeCandidateRport << " "
1719 << it->related_address().PortAsString() << " ";
1720 }
1721
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001722 if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
mallinath@webrtc.orge999bd02014-08-13 06:05:55 +00001723 os << kTcpCandidateType << " " << it->tcptype() << " ";
mallinath@webrtc.org2d60c5e2014-08-08 22:29:20 +00001724 }
1725
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001726 // Extensions
1727 os << kAttributeCandidateGeneration << " " << it->generation();
1728
1729 AddLine(os.str(), message);
1730 }
1731}
1732
1733void BuildIceOptions(const std::vector<std::string>& transport_options,
1734 std::string* message) {
1735 if (!transport_options.empty()) {
1736 std::ostringstream os;
1737 InitAttrLine(kAttributeIceOption, &os);
1738 os << kSdpDelimiterColon << transport_options[0];
1739 for (size_t i = 1; i < transport_options.size(); ++i) {
1740 os << kSdpDelimiterSpace << transport_options[i];
1741 }
1742 AddLine(os.str(), message);
1743 }
1744}
1745
1746bool ParseSessionDescription(const std::string& message, size_t* pos,
1747 std::string* session_id,
1748 std::string* session_version,
1749 bool* supports_msid,
1750 TransportDescription* session_td,
1751 RtpHeaderExtensions* session_extmaps,
1752 cricket::SessionDescription* desc,
1753 SdpParseError* error) {
1754 std::string line;
1755
1756 // RFC 4566
1757 // v= (protocol version)
1758 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1759 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1760 std::string(), error);
1761 }
1762 // RFC 4566
1763 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1764 // <unicast-address>
1765 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1766 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1767 std::string(), error);
1768 }
1769 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001770 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001771 kSdpDelimiterSpace, &fields);
1772 const size_t expected_fields = 6;
1773 if (fields.size() != expected_fields) {
1774 return ParseFailedExpectFieldNum(line, expected_fields, error);
1775 }
1776 *session_id = fields[1];
1777 *session_version = fields[2];
1778
1779 // RFC 4566
1780 // s= (session name)
1781 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1782 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1783 std::string(), error);
1784 }
1785
1786 // Optional lines
1787 // Those are the optional lines, so shouldn't return false if not present.
1788 // RFC 4566
1789 // i=* (session information)
1790 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1791
1792 // RFC 4566
1793 // u=* (URI of description)
1794 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1795
1796 // RFC 4566
1797 // e=* (email address)
1798 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1799
1800 // RFC 4566
1801 // p=* (phone number)
1802 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1803
1804 // RFC 4566
1805 // c=* (connection information -- not required if included in
1806 // all media)
1807 GetLineWithType(message, pos, &line, kLineTypeConnection);
1808
1809 // RFC 4566
1810 // b=* (zero or more bandwidth information lines)
1811 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1812 // By pass zero or more b lines.
1813 }
1814
1815 // RFC 4566
1816 // One or more time descriptions ("t=" and "r=" lines; see below)
1817 // t= (time the session is active)
1818 // r=* (zero or more repeat times)
1819 // Ensure there's at least one time description
1820 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1821 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1822 error);
1823 }
1824
1825 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1826 // By pass zero or more r lines.
1827 }
1828
1829 // Go through the rest of the time descriptions
1830 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1831 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1832 // By pass zero or more r lines.
1833 }
1834 }
1835
1836 // RFC 4566
1837 // z=* (time zone adjustments)
1838 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1839
1840 // RFC 4566
1841 // k=* (encryption key)
1842 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1843
1844 // RFC 4566
1845 // a=* (zero or more session attribute lines)
1846 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1847 if (HasAttribute(line, kAttributeGroup)) {
1848 if (!ParseGroupAttribute(line, desc, error)) {
1849 return false;
1850 }
1851 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1852 if (!GetValue(line, kAttributeIceUfrag,
1853 &(session_td->ice_ufrag), error)) {
1854 return false;
1855 }
1856 } else if (HasAttribute(line, kAttributeIcePwd)) {
1857 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1858 return false;
1859 }
1860 } else if (HasAttribute(line, kAttributeIceLite)) {
1861 session_td->ice_mode = cricket::ICEMODE_LITE;
1862 } else if (HasAttribute(line, kAttributeIceOption)) {
1863 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1864 return false;
1865 }
1866 } else if (HasAttribute(line, kAttributeFingerprint)) {
1867 if (session_td->identity_fingerprint.get()) {
1868 return ParseFailed(
1869 line,
1870 "Can't have multiple fingerprint attributes at the same level.",
1871 error);
1872 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001873 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001874 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1875 return false;
1876 }
1877 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001878 } else if (HasAttribute(line, kAttributeSetup)) {
1879 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1880 return false;
1881 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001882 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1883 std::string semantics;
1884 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1885 return false;
1886 }
1887 *supports_msid = CaseInsensitiveFind(semantics, kMediaStreamSemantic);
1888 } else if (HasAttribute(line, kAttributeExtmap)) {
1889 RtpHeaderExtension extmap;
1890 if (!ParseExtmap(line, &extmap, error)) {
1891 return false;
1892 }
1893 session_extmaps->push_back(extmap);
1894 }
1895 }
1896
1897 return true;
1898}
1899
1900bool ParseGroupAttribute(const std::string& line,
1901 cricket::SessionDescription* desc,
1902 SdpParseError* error) {
1903 ASSERT(desc != NULL);
1904
1905 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1906 // a=group:BUNDLE video voice
1907 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001908 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001909 kSdpDelimiterSpace, &fields);
1910 std::string semantics;
1911 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1912 return false;
1913 }
1914 cricket::ContentGroup group(semantics);
1915 for (size_t i = 1; i < fields.size(); ++i) {
1916 group.AddContentName(fields[i]);
1917 }
1918 desc->AddGroup(group);
1919 return true;
1920}
1921
1922static bool ParseFingerprintAttribute(const std::string& line,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001923 rtc::SSLFingerprint** fingerprint,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001924 SdpParseError* error) {
1925 if (!IsLineType(line, kLineTypeAttributes) ||
1926 !HasAttribute(line, kAttributeFingerprint)) {
1927 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1928 kAttributeFingerprint, error);
1929 }
1930
1931 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001932 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933 kSdpDelimiterSpace, &fields);
1934 const size_t expected_fields = 2;
1935 if (fields.size() != expected_fields) {
1936 return ParseFailedExpectFieldNum(line, expected_fields, error);
1937 }
1938
1939 // The first field here is "fingerprint:<hash>.
1940 std::string algorithm;
1941 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
1942 return false;
1943 }
1944
1945 // Downcase the algorithm. Note that we don't need to downcase the
1946 // fingerprint because hex_decode can handle upper-case.
1947 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
1948 ::tolower);
1949
1950 // The second field is the digest value. De-hexify it.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001951 *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001952 algorithm, fields[1]);
1953 if (!*fingerprint) {
1954 return ParseFailed(line,
1955 "Failed to create fingerprint from the digest.",
1956 error);
1957 }
1958
1959 return true;
1960}
1961
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001962static bool ParseDtlsSetup(const std::string& line,
1963 cricket::ConnectionRole* role,
1964 SdpParseError* error) {
1965 // setup-attr = "a=setup:" role
1966 // role = "active" / "passive" / "actpass" / "holdconn"
1967 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001968 rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001969 const size_t expected_fields = 2;
1970 if (fields.size() != expected_fields) {
1971 return ParseFailedExpectFieldNum(line, expected_fields, error);
1972 }
1973 std::string role_str = fields[1];
1974 if (!cricket::StringToConnectionRole(role_str, role)) {
1975 return ParseFailed(line, "Invalid attribute value.", error);
1976 }
1977 return true;
1978}
1979
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001980// RFC 3551
1981// PT encoding media type clock rate channels
1982// name (Hz)
1983// 0 PCMU A 8,000 1
1984// 1 reserved A
1985// 2 reserved A
1986// 3 GSM A 8,000 1
1987// 4 G723 A 8,000 1
1988// 5 DVI4 A 8,000 1
1989// 6 DVI4 A 16,000 1
1990// 7 LPC A 8,000 1
1991// 8 PCMA A 8,000 1
1992// 9 G722 A 8,000 1
1993// 10 L16 A 44,100 2
1994// 11 L16 A 44,100 1
1995// 12 QCELP A 8,000 1
1996// 13 CN A 8,000 1
1997// 14 MPA A 90,000 (see text)
1998// 15 G728 A 8,000 1
1999// 16 DVI4 A 11,025 1
2000// 17 DVI4 A 22,050 1
2001// 18 G729 A 8,000 1
2002struct StaticPayloadAudioCodec {
2003 const char* name;
2004 int clockrate;
2005 int channels;
2006};
2007static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2008 { "PCMU", 8000, 1 },
2009 { "reserved", 0, 0 },
2010 { "reserved", 0, 0 },
2011 { "GSM", 8000, 1 },
2012 { "G723", 8000, 1 },
2013 { "DVI4", 8000, 1 },
2014 { "DVI4", 16000, 1 },
2015 { "LPC", 8000, 1 },
2016 { "PCMA", 8000, 1 },
2017 { "G722", 8000, 1 },
2018 { "L16", 44100, 2 },
2019 { "L16", 44100, 1 },
2020 { "QCELP", 8000, 1 },
2021 { "CN", 8000, 1 },
2022 { "MPA", 90000, 1 },
2023 { "G728", 8000, 1 },
2024 { "DVI4", 11025, 1 },
2025 { "DVI4", 22050, 1 },
2026 { "G729", 8000, 1 },
2027};
2028
2029void MaybeCreateStaticPayloadAudioCodecs(
2030 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
2031 if (!media_desc) {
2032 return;
2033 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002034 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002035 std::vector<int>::const_iterator it = fmts.begin();
2036 bool add_new_codec = false;
2037 for (; it != fmts.end(); ++it) {
2038 int payload_type = *it;
2039 if (!media_desc->HasCodec(payload_type) &&
2040 payload_type >= 0 &&
2041 payload_type < ARRAY_SIZE(kStaticPayloadAudioCodecs)) {
2042 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2043 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2044 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
2045 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2046 clock_rate, 0, channels,
2047 preference));
2048 add_new_codec = true;
2049 }
2050 --preference;
2051 }
2052 if (add_new_codec) {
2053 media_desc->SortCodecs();
2054 }
2055}
2056
2057template <class C>
2058static C* ParseContentDescription(const std::string& message,
2059 const MediaType media_type,
2060 int mline_index,
2061 const std::string& protocol,
2062 const std::vector<int>& codec_preference,
2063 size_t* pos,
2064 std::string* content_name,
2065 TransportDescription* transport,
2066 std::vector<JsepIceCandidate*>* candidates,
2067 webrtc::SdpParseError* error) {
2068 C* media_desc = new C();
2069 switch (media_type) {
2070 case cricket::MEDIA_TYPE_AUDIO:
2071 *content_name = cricket::CN_AUDIO;
2072 break;
2073 case cricket::MEDIA_TYPE_VIDEO:
2074 *content_name = cricket::CN_VIDEO;
2075 break;
2076 case cricket::MEDIA_TYPE_DATA:
2077 *content_name = cricket::CN_DATA;
2078 break;
2079 default:
2080 ASSERT(false);
2081 break;
2082 }
2083 if (!ParseContent(message, media_type, mline_index, protocol,
2084 codec_preference, pos, content_name,
2085 media_desc, transport, candidates, error)) {
2086 delete media_desc;
2087 return NULL;
2088 }
2089 // Sort the codecs according to the m-line fmt list.
2090 media_desc->SortCodecs();
2091 return media_desc;
2092}
2093
2094bool ParseMediaDescription(const std::string& message,
2095 const TransportDescription& session_td,
2096 const RtpHeaderExtensions& session_extmaps,
2097 bool supports_msid,
2098 size_t* pos,
2099 cricket::SessionDescription* desc,
2100 std::vector<JsepIceCandidate*>* candidates,
2101 SdpParseError* error) {
2102 ASSERT(desc != NULL);
2103 std::string line;
2104 int mline_index = -1;
2105
2106 // Zero or more media descriptions
2107 // RFC 4566
2108 // m=<media> <port> <proto> <fmt>
2109 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2110 ++mline_index;
2111
2112 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002113 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002114 kSdpDelimiterSpace, &fields);
2115 const size_t expected_min_fields = 4;
2116 if (fields.size() < expected_min_fields) {
2117 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2118 }
2119 bool rejected = false;
2120 // RFC 3264
2121 // To reject an offered stream, the port number in the corresponding stream
2122 // in the answer MUST be set to zero.
2123 if (fields[1] == kMediaPortRejected) {
2124 rejected = true;
2125 }
2126
2127 std::string protocol = fields[2];
2128 bool is_sctp = (protocol == cricket::kMediaProtocolDtlsSctp);
2129
2130 // <fmt>
2131 std::vector<int> codec_preference;
2132 for (size_t j = 3 ; j < fields.size(); ++j) {
wu@webrtc.org36eda7c2014-04-15 20:37:30 +00002133 // TODO(wu): Remove when below bug is fixed.
2134 // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
2135 if (fields[j] == "" && j == fields.size() - 1) {
2136 continue;
2137 }
2138
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002139 int pl = 0;
2140 if (!GetValueFromString(line, fields[j], &pl, error)) {
2141 return false;
2142 }
2143 codec_preference.push_back(pl);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002144 }
2145
2146 // Make a temporary TransportDescription based on |session_td|.
2147 // Some of this gets overwritten by ParseContent.
2148 TransportDescription transport(NS_JINGLE_ICE_UDP,
2149 session_td.transport_options,
2150 session_td.ice_ufrag,
2151 session_td.ice_pwd,
2152 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002153 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002154 session_td.identity_fingerprint.get(),
2155 Candidates());
2156
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002157 rtc::scoped_ptr<MediaContentDescription> content;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002158 std::string content_name;
2159 if (HasAttribute(line, kMediaTypeVideo)) {
2160 content.reset(ParseContentDescription<VideoContentDescription>(
2161 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2162 codec_preference, pos, &content_name,
2163 &transport, candidates, error));
2164 } else if (HasAttribute(line, kMediaTypeAudio)) {
2165 content.reset(ParseContentDescription<AudioContentDescription>(
2166 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2167 codec_preference, pos, &content_name,
2168 &transport, candidates, error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002169 } else if (HasAttribute(line, kMediaTypeData)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002170 DataContentDescription* desc =
2171 ParseContentDescription<DataContentDescription>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002172 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2173 codec_preference, pos, &content_name,
wu@webrtc.org78187522013-10-07 23:32:02 +00002174 &transport, candidates, error);
2175
henrike@webrtc.org571df2d2014-02-19 23:04:26 +00002176 if (desc && protocol == cricket::kMediaProtocolDtlsSctp) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002177 // Add the SCTP Port number as a pseudo-codec "port" parameter
2178 cricket::DataCodec codec_port(
2179 cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
2180 0);
2181 codec_port.SetParam(cricket::kCodecParamPort, fields[3]);
2182 LOG(INFO) << "ParseMediaDescription: Got SCTP Port Number "
2183 << fields[3];
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +00002184 ASSERT(!desc->HasCodec(cricket::kGoogleSctpDataCodecId));
wu@webrtc.org78187522013-10-07 23:32:02 +00002185 desc->AddCodec(codec_port);
2186 }
2187
2188 content.reset(desc);
2189
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002190 // We should always use the default bandwidth for RTP-based data
2191 // channels. Don't allow SDP to set the bandwidth, because that
2192 // would give JS the opportunity to "break the Internet".
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002193 // TODO(pthatcher): But we need to temporarily allow the SDP to control
2194 // this for backwards-compatibility. Once we don't need that any
2195 // more, remove this.
2196 bool support_dc_sdp_bandwidth_temporarily = true;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00002197 if (content.get() && !support_dc_sdp_bandwidth_temporarily) {
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002198 content->set_bandwidth(cricket::kAutoBandwidth);
2199 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002200 } else {
2201 LOG(LS_WARNING) << "Unsupported media type: " << line;
2202 continue;
2203 }
2204 if (!content.get()) {
2205 // ParseContentDescription returns NULL if failed.
2206 return false;
2207 }
2208
2209 if (!is_sctp) {
2210 // Make sure to set the media direction correctly. If the direction is not
2211 // MD_RECVONLY or Inactive and no streams are parsed,
2212 // a default MediaStream will be created to prepare for receiving media.
2213 if (supports_msid && content->streams().empty() &&
2214 content->direction() == cricket::MD_SENDRECV) {
2215 content->set_direction(cricket::MD_RECVONLY);
2216 }
2217
2218 // Set the extmap.
2219 if (!session_extmaps.empty() &&
2220 !content->rtp_header_extensions().empty()) {
2221 return ParseFailed("",
2222 "The a=extmap MUST be either all session level or "
2223 "all media level.",
2224 error);
2225 }
2226 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2227 content->AddRtpHeaderExtension(session_extmaps[i]);
2228 }
2229 }
2230 content->set_protocol(protocol);
2231 desc->AddContent(content_name,
2232 is_sctp ? cricket::NS_JINGLE_DRAFT_SCTP :
2233 cricket::NS_JINGLE_RTP,
2234 rejected,
2235 content.release());
2236 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2237 TransportInfo transport_info(content_name, transport);
2238
2239 if (!desc->AddTransportInfo(transport_info)) {
2240 std::ostringstream description;
2241 description << "Failed to AddTransportInfo with content name: "
2242 << content_name;
2243 return ParseFailed("", description.str(), error);
2244 }
2245 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002246
2247 size_t end_of_message = message.size();
2248 if (mline_index == -1 && *pos != end_of_message) {
2249 ParseFailed(message, *pos, "Expects m line.", error);
2250 return false;
2251 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 return true;
2253}
2254
2255bool VerifyCodec(const cricket::Codec& codec) {
2256 // Codec has not been populated correctly unless the name has been set. This
2257 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2258 // have a corresponding "rtpmap" line.
2259 cricket::Codec default_codec;
2260 return default_codec.name != codec.name;
2261}
2262
2263bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2264 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2265 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2266 iter != codecs.end(); ++iter) {
2267 if (!VerifyCodec(*iter)) {
2268 return false;
2269 }
2270 }
2271 return true;
2272}
2273
2274bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2275 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2276 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2277 iter != codecs.end(); ++iter) {
2278 if (!VerifyCodec(*iter)) {
2279 return false;
2280 }
2281 }
2282 return true;
2283}
2284
2285void AddParameters(const cricket::CodecParameterMap& parameters,
2286 cricket::Codec* codec) {
2287 for (cricket::CodecParameterMap::const_iterator iter =
2288 parameters.begin(); iter != parameters.end(); ++iter) {
2289 codec->SetParam(iter->first, iter->second);
2290 }
2291}
2292
2293void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2294 cricket::Codec* codec) {
2295 codec->AddFeedbackParam(feedback_param);
2296}
2297
2298void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2299 cricket::Codec* codec) {
2300 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2301 feedback_params.params().begin();
2302 iter != feedback_params.params().end(); ++iter) {
2303 codec->AddFeedbackParam(*iter);
2304 }
2305}
2306
2307// Gets the current codec setting associated with |payload_type|. If there
2308// is no AudioCodec associated with that payload type it returns an empty codec
2309// with that payload type.
2310template <class T>
2311T GetCodec(const std::vector<T>& codecs, int payload_type) {
2312 for (typename std::vector<T>::const_iterator codec = codecs.begin();
2313 codec != codecs.end(); ++codec) {
2314 if (codec->id == payload_type) {
2315 return *codec;
2316 }
2317 }
2318 T ret_val = T();
2319 ret_val.id = payload_type;
2320 return ret_val;
2321}
2322
2323// Updates or creates a new codec entry in the audio description.
2324template <class T, class U>
2325void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2326 T* desc = static_cast<T*>(content_desc);
2327 std::vector<U> codecs = desc->codecs();
2328 bool found = false;
2329
2330 typename std::vector<U>::iterator iter;
2331 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2332 if (iter->id == codec.id) {
2333 *iter = codec;
2334 found = true;
2335 break;
2336 }
2337 }
2338 if (!found) {
2339 desc->AddCodec(codec);
2340 return;
2341 }
2342 desc->set_codecs(codecs);
2343}
2344
2345// Adds or updates existing codec corresponding to |payload_type| according
2346// to |parameters|.
2347template <class T, class U>
2348void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2349 const cricket::CodecParameterMap& parameters) {
2350 // Codec might already have been populated (from rtpmap).
2351 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2352 AddParameters(parameters, &new_codec);
2353 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2354}
2355
2356// Adds or updates existing codec corresponding to |payload_type| according
2357// to |feedback_param|.
2358template <class T, class U>
2359void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2360 const cricket::FeedbackParam& feedback_param) {
2361 // Codec might already have been populated (from rtpmap).
2362 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2363 AddFeedbackParameter(feedback_param, &new_codec);
2364 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2365}
2366
2367bool PopWildcardCodec(std::vector<cricket::VideoCodec>* codecs,
2368 cricket::VideoCodec* wildcard_codec) {
2369 for (std::vector<cricket::VideoCodec>::iterator iter = codecs->begin();
2370 iter != codecs->end(); ++iter) {
2371 if (iter->id == kWildcardPayloadType) {
2372 *wildcard_codec = *iter;
2373 codecs->erase(iter);
2374 return true;
2375 }
2376 }
2377 return false;
2378}
2379
2380void UpdateFromWildcardVideoCodecs(VideoContentDescription* video_desc) {
2381 std::vector<cricket::VideoCodec> codecs = video_desc->codecs();
2382 cricket::VideoCodec wildcard_codec;
2383 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2384 return;
2385 }
2386 for (std::vector<cricket::VideoCodec>::iterator iter = codecs.begin();
2387 iter != codecs.end(); ++iter) {
2388 cricket::VideoCodec& codec = *iter;
2389 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2390 }
2391 video_desc->set_codecs(codecs);
2392}
2393
2394void AddAudioAttribute(const std::string& name, const std::string& value,
2395 AudioContentDescription* audio_desc) {
2396 if (value.empty()) {
2397 return;
2398 }
2399 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2400 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2401 iter != codecs.end(); ++iter) {
2402 iter->params[name] = value;
2403 }
2404 audio_desc->set_codecs(codecs);
2405}
2406
2407bool ParseContent(const std::string& message,
2408 const MediaType media_type,
2409 int mline_index,
2410 const std::string& protocol,
2411 const std::vector<int>& codec_preference,
2412 size_t* pos,
2413 std::string* content_name,
2414 MediaContentDescription* media_desc,
2415 TransportDescription* transport,
2416 std::vector<JsepIceCandidate*>* candidates,
2417 SdpParseError* error) {
2418 ASSERT(media_desc != NULL);
2419 ASSERT(content_name != NULL);
2420 ASSERT(transport != NULL);
2421
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002422 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2423 MaybeCreateStaticPayloadAudioCodecs(
2424 codec_preference, static_cast<AudioContentDescription*>(media_desc));
2425 }
2426
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002427 // The media level "ice-ufrag" and "ice-pwd".
2428 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2429 Candidates candidates_orig;
2430 std::string line;
2431 std::string mline_id;
2432 // Tracks created out of the ssrc attributes.
2433 StreamParamsVec tracks;
2434 SsrcInfoVec ssrc_infos;
2435 SsrcGroupVec ssrc_groups;
2436 std::string maxptime_as_string;
2437 std::string ptime_as_string;
2438
2439 bool is_rtp =
2440 protocol.empty() ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002441 rtc::starts_with(protocol.data(),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002442 cricket::kMediaProtocolRtpPrefix);
2443
2444 // Loop until the next m line
2445 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2446 if (!GetLine(message, pos, &line)) {
2447 if (*pos >= message.size()) {
2448 break; // Done parsing
2449 } else {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002450 return ParseFailed(message, *pos, "Invalid SDP line.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002451 }
2452 }
2453
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002454 // RFC 4566
2455 // b=* (zero or more bandwidth information lines)
2456 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2457 std::string bandwidth;
2458 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2459 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2460 return false;
2461 } else {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002462 int b = 0;
2463 if (!GetValueFromString(line, bandwidth, &b, error)) {
2464 return false;
2465 }
2466 media_desc->set_bandwidth(b * 1000);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002467 }
2468 }
2469 continue;
2470 }
2471
2472 if (!IsLineType(line, kLineTypeAttributes)) {
2473 // TODO: Handle other lines if needed.
2474 LOG(LS_INFO) << "Ignored line: " << line;
2475 continue;
2476 }
2477
2478 // Handle attributes common to SCTP and RTP.
2479 if (HasAttribute(line, kAttributeMid)) {
2480 // RFC 3388
2481 // mid-attribute = "a=mid:" identification-tag
2482 // identification-tag = token
2483 // Use the mid identification-tag as the content name.
2484 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2485 return false;
2486 }
2487 *content_name = mline_id;
2488 } else if (HasAttribute(line, kAttributeCandidate)) {
2489 Candidate candidate;
2490 if (!ParseCandidate(line, &candidate, error, false)) {
2491 return false;
2492 }
2493 candidates_orig.push_back(candidate);
2494 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2495 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2496 return false;
2497 }
2498 } else if (HasAttribute(line, kAttributeIcePwd)) {
2499 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2500 return false;
2501 }
2502 } else if (HasAttribute(line, kAttributeIceOption)) {
2503 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2504 return false;
2505 }
2506 } else if (HasAttribute(line, kAttributeFmtp)) {
2507 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2508 return false;
2509 }
2510 } else if (HasAttribute(line, kAttributeFingerprint)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002511 rtc::SSLFingerprint* fingerprint = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002512
2513 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2514 return false;
2515 }
2516 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002517 } else if (HasAttribute(line, kAttributeSetup)) {
2518 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2519 return false;
2520 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002521 } else if (is_rtp) {
2522 //
2523 // RTP specific attrubtes
2524 //
2525 if (HasAttribute(line, kAttributeRtcpMux)) {
2526 media_desc->set_rtcp_mux(true);
2527 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2528 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2529 return false;
2530 }
2531 } else if (HasAttribute(line, kAttributeSsrc)) {
2532 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2533 return false;
2534 }
2535 } else if (HasAttribute(line, kAttributeCrypto)) {
2536 if (!ParseCryptoAttribute(line, media_desc, error)) {
2537 return false;
2538 }
2539 } else if (HasAttribute(line, kAttributeRtpmap)) {
2540 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2541 media_desc, error)) {
2542 return false;
2543 }
2544 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2545 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2546 return false;
2547 }
2548 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2549 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2550 return false;
2551 }
2552 } else if (HasAttribute(line, kCodecParamPTime)) {
2553 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2554 return false;
2555 }
2556 } else if (HasAttribute(line, kAttributeSendOnly)) {
2557 media_desc->set_direction(cricket::MD_SENDONLY);
2558 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2559 media_desc->set_direction(cricket::MD_RECVONLY);
2560 } else if (HasAttribute(line, kAttributeInactive)) {
2561 media_desc->set_direction(cricket::MD_INACTIVE);
2562 } else if (HasAttribute(line, kAttributeSendRecv)) {
2563 media_desc->set_direction(cricket::MD_SENDRECV);
2564 } else if (HasAttribute(line, kAttributeExtmap)) {
2565 RtpHeaderExtension extmap;
2566 if (!ParseExtmap(line, &extmap, error)) {
2567 return false;
2568 }
2569 media_desc->AddRtpHeaderExtension(extmap);
2570 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2571 // Experimental attribute. Conference mode activates more aggressive
2572 // AEC and NS settings.
2573 // TODO: expose API to set these directly.
2574 std::string flag_value;
2575 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2576 return false;
2577 }
2578 if (flag_value.compare(kValueConference) == 0)
2579 media_desc->set_conference_mode(true);
2580 } else if (HasAttribute(line, kAttributeXGoogleBufferLatency)) {
2581 // Experimental attribute.
2582 // TODO: expose API to set this directly.
2583 std::string flag_value;
2584 if (!GetValue(line, kAttributeXGoogleBufferLatency, &flag_value,
2585 error)) {
2586 return false;
2587 }
2588 int buffer_latency = 0;
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002589 if (!GetValueFromString(line, flag_value, &buffer_latency, error)) {
2590 return false;
2591 }
2592 if (buffer_latency < 0) {
2593 return ParseFailed(line, "Buffer latency less than 0.", error);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002594 }
2595 media_desc->set_buffered_mode_latency(buffer_latency);
2596 }
2597 } else {
2598 // Only parse lines that we are interested of.
2599 LOG(LS_INFO) << "Ignored line: " << line;
2600 continue;
2601 }
2602 }
2603
2604 // Create tracks from the |ssrc_infos|.
2605 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2606
2607 // Add the ssrc group to the track.
2608 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2609 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2610 if (ssrc_group->ssrcs.empty()) {
2611 continue;
2612 }
2613 uint32 ssrc = ssrc_group->ssrcs.front();
2614 for (StreamParamsVec::iterator track = tracks.begin();
2615 track != tracks.end(); ++track) {
2616 if (track->has_ssrc(ssrc)) {
2617 track->ssrc_groups.push_back(*ssrc_group);
2618 }
2619 }
2620 }
2621
2622 // Add the new tracks to the |media_desc|.
2623 for (StreamParamsVec::iterator track = tracks.begin();
2624 track != tracks.end(); ++track) {
2625 media_desc->AddStream(*track);
2626 }
2627
2628 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2629 AudioContentDescription* audio_desc =
2630 static_cast<AudioContentDescription*>(media_desc);
2631 // Verify audio codec ensures that no audio codec has been populated with
2632 // only fmtp.
2633 if (!VerifyAudioCodecs(audio_desc)) {
2634 return ParseFailed("Failed to parse audio codecs correctly.", error);
2635 }
2636 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2637 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2638 }
2639
2640 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2641 VideoContentDescription* video_desc =
2642 static_cast<VideoContentDescription*>(media_desc);
2643 UpdateFromWildcardVideoCodecs(video_desc);
2644 // Verify video codec ensures that no video codec has been populated with
2645 // only rtcp-fb.
2646 if (!VerifyVideoCodecs(video_desc)) {
2647 return ParseFailed("Failed to parse video codecs correctly.", error);
2648 }
2649 }
2650
2651 // RFC 5245
2652 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2653 for (Candidates::iterator it = candidates_orig.begin();
2654 it != candidates_orig.end(); ++it) {
2655 ASSERT((*it).username().empty());
2656 (*it).set_username(transport->ice_ufrag);
2657 ASSERT((*it).password().empty());
2658 (*it).set_password(transport->ice_pwd);
2659 candidates->push_back(
2660 new JsepIceCandidate(mline_id, mline_index, *it));
2661 }
2662 return true;
2663}
2664
2665bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2666 SdpParseError* error) {
2667 ASSERT(ssrc_infos != NULL);
2668 // RFC 5576
2669 // a=ssrc:<ssrc-id> <attribute>
2670 // a=ssrc:<ssrc-id> <attribute>:<value>
2671 std::string field1, field2;
2672 if (!SplitByDelimiter(line.substr(kLinePrefixLength),
2673 kSdpDelimiterSpace,
2674 &field1,
2675 &field2)) {
2676 const size_t expected_fields = 2;
2677 return ParseFailedExpectFieldNum(line, expected_fields, error);
2678 }
2679
2680 // ssrc:<ssrc-id>
2681 std::string ssrc_id_s;
2682 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2683 return false;
2684 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002685 uint32 ssrc_id = 0;
2686 if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
2687 return false;
2688 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002689
2690 std::string attribute;
2691 std::string value;
2692 if (!SplitByDelimiter(field2, kSdpDelimiterColon,
2693 &attribute, &value)) {
2694 std::ostringstream description;
2695 description << "Failed to get the ssrc attribute value from " << field2
2696 << ". Expected format <attribute>:<value>.";
2697 return ParseFailed(line, description.str(), error);
2698 }
2699
2700 // Check if there's already an item for this |ssrc_id|. Create a new one if
2701 // there isn't.
2702 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2703 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2704 if (ssrc_info->ssrc_id == ssrc_id) {
2705 break;
2706 }
2707 }
2708 if (ssrc_info == ssrc_infos->end()) {
2709 SsrcInfo info;
2710 info.ssrc_id = ssrc_id;
2711 ssrc_infos->push_back(info);
2712 ssrc_info = ssrc_infos->end() - 1;
2713 }
2714
2715 // Store the info to the |ssrc_info|.
2716 if (attribute == kSsrcAttributeCname) {
2717 // RFC 5576
2718 // cname:<value>
2719 ssrc_info->cname = value;
2720 } else if (attribute == kSsrcAttributeMsid) {
2721 // draft-alvestrand-mmusic-msid-00
2722 // "msid:" identifier [ " " appdata ]
2723 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002724 rtc::split(value, kSdpDelimiterSpace, &fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002725 if (fields.size() < 1 || fields.size() > 2) {
2726 return ParseFailed(line,
2727 "Expected format \"msid:<identifier>[ <appdata>]\".",
2728 error);
2729 }
2730 ssrc_info->msid_identifier = fields[0];
2731 if (fields.size() == 2) {
2732 ssrc_info->msid_appdata = fields[1];
2733 }
2734 } else if (attribute == kSsrcAttributeMslabel) {
2735 // draft-alvestrand-rtcweb-mid-01
2736 // mslabel:<value>
2737 ssrc_info->mslabel = value;
2738 } else if (attribute == kSSrcAttributeLabel) {
2739 // The label isn't defined.
2740 // label:<value>
2741 ssrc_info->label = value;
2742 }
2743 return true;
2744}
2745
2746bool ParseSsrcGroupAttribute(const std::string& line,
2747 SsrcGroupVec* ssrc_groups,
2748 SdpParseError* error) {
2749 ASSERT(ssrc_groups != NULL);
2750 // RFC 5576
2751 // a=ssrc-group:<semantics> <ssrc-id> ...
2752 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002753 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002754 kSdpDelimiterSpace, &fields);
2755 const size_t expected_min_fields = 2;
2756 if (fields.size() < expected_min_fields) {
2757 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2758 }
2759 std::string semantics;
2760 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2761 return false;
2762 }
2763 std::vector<uint32> ssrcs;
2764 for (size_t i = 1; i < fields.size(); ++i) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002765 uint32 ssrc = 0;
2766 if (!GetValueFromString(line, fields[i], &ssrc, error)) {
2767 return false;
2768 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002769 ssrcs.push_back(ssrc);
2770 }
2771 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2772 return true;
2773}
2774
2775bool ParseCryptoAttribute(const std::string& line,
2776 MediaContentDescription* media_desc,
2777 SdpParseError* error) {
2778 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002779 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002780 kSdpDelimiterSpace, &fields);
2781 // RFC 4568
2782 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2783 const size_t expected_min_fields = 3;
2784 if (fields.size() < expected_min_fields) {
2785 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2786 }
2787 std::string tag_value;
2788 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2789 return false;
2790 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002791 int tag = 0;
2792 if (!GetValueFromString(line, tag_value, &tag, error)) {
2793 return false;
2794 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002795 const std::string crypto_suite = fields[1];
2796 const std::string key_params = fields[2];
2797 std::string session_params;
2798 if (fields.size() > 3) {
2799 session_params = fields[3];
2800 }
2801 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2802 session_params));
2803 return true;
2804}
2805
2806// Updates or creates a new codec entry in the audio description with according
2807// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2808void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2809 int bitrate, int channels, int preference,
2810 AudioContentDescription* audio_desc) {
2811 // Codec may already be populated with (only) optional parameters
2812 // (from an fmtp).
2813 cricket::AudioCodec codec = GetCodec(audio_desc->codecs(), payload_type);
2814 codec.name = name;
2815 codec.clockrate = clockrate;
2816 codec.bitrate = bitrate;
2817 codec.channels = channels;
2818 codec.preference = preference;
2819 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2820 codec);
2821}
2822
2823// Updates or creates a new codec entry in the video description according to
2824// |name|, |width|, |height|, |framerate| and |preference|.
2825void UpdateCodec(int payload_type, const std::string& name, int width,
2826 int height, int framerate, int preference,
2827 VideoContentDescription* video_desc) {
2828 // Codec may already be populated with (only) optional parameters
2829 // (from an fmtp).
2830 cricket::VideoCodec codec = GetCodec(video_desc->codecs(), payload_type);
2831 codec.name = name;
2832 codec.width = width;
2833 codec.height = height;
2834 codec.framerate = framerate;
2835 codec.preference = preference;
2836 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2837 codec);
2838}
2839
2840bool ParseRtpmapAttribute(const std::string& line,
2841 const MediaType media_type,
2842 const std::vector<int>& codec_preference,
2843 MediaContentDescription* media_desc,
2844 SdpParseError* error) {
2845 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002846 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002847 kSdpDelimiterSpace, &fields);
2848 // RFC 4566
2849 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2850 const size_t expected_min_fields = 2;
2851 if (fields.size() < expected_min_fields) {
2852 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2853 }
2854 std::string payload_type_value;
2855 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2856 return false;
2857 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002858 int payload_type = 0;
2859 if (!GetValueFromString(line, payload_type_value, &payload_type, error)) {
2860 return false;
2861 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002862
2863 // Set the preference order depending on the order of the pl type in the
2864 // <fmt> of the m-line.
2865 const int preference = codec_preference.end() -
2866 std::find(codec_preference.begin(), codec_preference.end(),
2867 payload_type);
2868 if (preference == 0) {
2869 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2870 << "<fmt> of the m-line: " << line;
2871 return true;
2872 }
2873 const std::string encoder = fields[1];
2874 std::vector<std::string> codec_params;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002875 rtc::split(encoder, '/', &codec_params);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002876 // <encoding name>/<clock rate>[/<encodingparameters>]
2877 // 2 mandatory fields
2878 if (codec_params.size() < 2 || codec_params.size() > 3) {
2879 return ParseFailed(line,
2880 "Expected format \"<encoding name>/<clock rate>"
2881 "[/<encodingparameters>]\".",
2882 error);
2883 }
2884 const std::string encoding_name = codec_params[0];
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002885 int clock_rate = 0;
2886 if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
2887 return false;
2888 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002889 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2890 VideoContentDescription* video_desc =
2891 static_cast<VideoContentDescription*>(media_desc);
2892 // TODO: We will send resolution in SDP. For now use
2893 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2894 UpdateCodec(payload_type, encoding_name,
2895 JsepSessionDescription::kMaxVideoCodecWidth,
2896 JsepSessionDescription::kMaxVideoCodecHeight,
2897 JsepSessionDescription::kDefaultVideoCodecFramerate,
2898 preference, video_desc);
2899 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2900 // RFC 4566
2901 // For audio streams, <encoding parameters> indicates the number
2902 // of audio channels. This parameter is OPTIONAL and may be
2903 // omitted if the number of channels is one, provided that no
2904 // additional parameters are needed.
2905 int channels = 1;
2906 if (codec_params.size() == 3) {
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002907 if (!GetValueFromString(line, codec_params[2], &channels, error)) {
2908 return false;
2909 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002910 }
2911 int bitrate = 0;
2912 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2913 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2914 // The bandwidth adaptation doesn't always work well, so this code
2915 // sets a fixed target bitrate instead.
2916 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2917 if (clock_rate <= 16000) {
2918 bitrate = kIsacWbDefaultRate;
2919 } else {
2920 bitrate = kIsacSwbDefaultRate;
2921 }
2922 }
2923 AudioContentDescription* audio_desc =
2924 static_cast<AudioContentDescription*>(media_desc);
2925 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2926 preference, audio_desc);
2927 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2928 DataContentDescription* data_desc =
2929 static_cast<DataContentDescription*>(media_desc);
2930 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2931 preference));
2932 }
2933 return true;
2934}
2935
2936void PruneRight(const char delimiter, std::string* message) {
2937 size_t trailing = message->find(delimiter);
2938 if (trailing != std::string::npos) {
2939 *message = message->substr(0, trailing);
2940 }
2941}
2942
2943bool ParseFmtpParam(const std::string& line, std::string* parameter,
2944 std::string* value, SdpParseError* error) {
2945 if (!SplitByDelimiter(line, kSdpDelimiterEqual, parameter, value)) {
2946 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2947 return false;
2948 }
2949 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
2950 // When parsing the values the trailing ";" gets picked up. Remove them.
2951 PruneRight(kSdpDelimiterSemicolon, value);
2952 return true;
2953}
2954
2955bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
2956 MediaContentDescription* media_desc,
2957 SdpParseError* error) {
2958 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2959 media_type != cricket::MEDIA_TYPE_VIDEO) {
2960 return true;
2961 }
2962 std::vector<std::string> fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002963 rtc::split(line.substr(kLinePrefixLength),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002964 kSdpDelimiterSpace, &fields);
2965
2966 // RFC 5576
2967 // a=fmtp:<format> <format specific parameters>
2968 // At least two fields, whereas the second one is any of the optional
2969 // parameters.
2970 if (fields.size() < 2) {
2971 ParseFailedExpectMinFieldNum(line, 2, error);
2972 return false;
2973 }
2974
2975 std::string payload_type;
2976 if (!GetValue(fields[0], kAttributeFmtp, &payload_type, error)) {
2977 return false;
2978 }
2979
2980 cricket::CodecParameterMap codec_params;
2981 for (std::vector<std::string>::const_iterator iter = fields.begin() + 1;
2982 iter != fields.end(); ++iter) {
2983 std::string name;
2984 std::string value;
2985 if (iter->find(kSdpDelimiterEqual) == std::string::npos) {
2986 // Only fmtps with equals are currently supported. Other fmtp types
2987 // should be ignored. Unknown fmtps do not constitute an error.
2988 continue;
2989 }
2990 if (!ParseFmtpParam(*iter, &name, &value, error)) {
2991 return false;
2992 }
2993 codec_params[name] = value;
2994 }
2995
wu@webrtc.org5e760e72014-04-02 23:19:09 +00002996 int int_payload_type = 0;
2997 if (!GetValueFromString(line, payload_type, &int_payload_type, error)) {
2998 return false;
2999 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003000 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3001 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3002 media_desc, int_payload_type, codec_params);
3003 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3004 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3005 media_desc, int_payload_type, codec_params);
3006 }
3007 return true;
3008}
3009
3010bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
3011 MediaContentDescription* media_desc,
3012 SdpParseError* error) {
3013 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3014 media_type != cricket::MEDIA_TYPE_VIDEO) {
3015 return true;
3016 }
3017 std::vector<std::string> rtcp_fb_fields;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003018 rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003019 if (rtcp_fb_fields.size() < 2) {
3020 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3021 }
3022 std::string payload_type_string;
3023 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3024 error)) {
3025 return false;
3026 }
wu@webrtc.org5e760e72014-04-02 23:19:09 +00003027 int payload_type = kWildcardPayloadType;
3028 if (payload_type_string != "*") {
3029 if (!GetValueFromString(line, payload_type_string, &payload_type, error)) {
3030 return false;
3031 }
3032 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003033 std::string id = rtcp_fb_fields[1];
3034 std::string param = "";
3035 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3036 iter != rtcp_fb_fields.end(); ++iter) {
3037 param.append(*iter);
3038 }
3039 const cricket::FeedbackParam feedback_param(id, param);
3040
3041 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3042 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(media_desc,
3043 payload_type,
3044 feedback_param);
3045 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3046 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(media_desc,
3047 payload_type,
3048 feedback_param);
3049 }
3050 return true;
3051}
3052
3053} // namespace webrtc