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