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