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