blob: 516b015955d54c38e675c6e5a681dc849a700738 [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>
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001319 // We should always use the default bandwidth for RTP-based data
1320 // channels. Don't allow SDP to set the bandwidth, because that
1321 // would give JS the opportunity to "break the Internet".
1322 if (media_desc->bandwidth() >= 1000 &&
1323 media_type != cricket::MEDIA_TYPE_DATA) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1325 os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1326 AddLine(os.str(), message);
1327 }
1328
1329 // RFC 5761
1330 // a=rtcp-mux
1331 if (media_desc->rtcp_mux()) {
1332 InitAttrLine(kAttributeRtcpMux, &os);
1333 AddLine(os.str(), message);
1334 }
1335
1336 // RFC 4568
1337 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1338 for (std::vector<CryptoParams>::const_iterator it =
1339 media_desc->cryptos().begin();
1340 it != media_desc->cryptos().end(); ++it) {
1341 InitAttrLine(kAttributeCrypto, &os);
1342 os << kSdpDelimiterColon << it->tag << " " << it->cipher_suite << " "
1343 << it->key_params;
1344 if (!it->session_params.empty()) {
1345 os << " " << it->session_params;
1346 }
1347 AddLine(os.str(), message);
1348 }
1349
1350 // RFC 4566
1351 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1352 // [/<encodingparameters>]
1353 BuildRtpMap(media_desc, media_type, message);
1354
1355 // Specify latency for buffered mode.
1356 // a=x-google-buffer-latency:<value>
1357 if (media_desc->buffered_mode_latency() != cricket::kBufferedModeDisabled) {
1358 std::ostringstream os;
1359 InitAttrLine(kAttributeXGoogleBufferLatency, &os);
1360 os << kSdpDelimiterColon << media_desc->buffered_mode_latency();
1361 AddLine(os.str(), message);
1362 }
1363
1364 for (StreamParamsVec::const_iterator track = media_desc->streams().begin();
1365 track != media_desc->streams().end(); ++track) {
1366 // Require that the track belongs to a media stream,
1367 // ie the sync_label is set. This extra check is necessary since the
1368 // MediaContentDescription always contains a streamparam with an ssrc even
1369 // if no track or media stream have been created.
1370 if (track->sync_label.empty()) continue;
1371
1372 // Build the ssrc-group lines.
1373 for (size_t i = 0; i < track->ssrc_groups.size(); ++i) {
1374 // RFC 5576
1375 // a=ssrc-group:<semantics> <ssrc-id> ...
1376 if (track->ssrc_groups[i].ssrcs.empty()) {
1377 continue;
1378 }
1379 std::ostringstream os;
1380 InitAttrLine(kAttributeSsrcGroup, &os);
1381 os << kSdpDelimiterColon << track->ssrc_groups[i].semantics;
1382 std::vector<uint32>::const_iterator ssrc =
1383 track->ssrc_groups[i].ssrcs.begin();
1384 for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
1385 os << kSdpDelimiterSpace << talk_base::ToString<uint32>(*ssrc);
1386 }
1387 AddLine(os.str(), message);
1388 }
1389 // Build the ssrc lines for each ssrc.
1390 for (size_t i = 0; i < track->ssrcs.size(); ++i) {
1391 uint32 ssrc = track->ssrcs[i];
1392 // RFC 5576
1393 // a=ssrc:<ssrc-id> cname:<value>
1394 AddSsrcLine(ssrc, kSsrcAttributeCname,
1395 track->cname, message);
1396
1397 // draft-alvestrand-mmusic-msid-00
1398 // a=ssrc:<ssrc-id> msid:identifier [appdata]
1399 // The appdata consists of the "id" attribute of a MediaStreamTrack, which
1400 // is corresponding to the "name" attribute of StreamParams.
1401 std::string appdata = track->id;
1402 std::ostringstream os;
1403 InitAttrLine(kAttributeSsrc, &os);
1404 os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1405 << kSsrcAttributeMsid << kSdpDelimiterColon << track->sync_label
1406 << kSdpDelimiterSpace << appdata;
1407 AddLine(os.str(), message);
1408
1409 // TODO(ronghuawu): Remove below code which is for backward compatibility.
1410 // draft-alvestrand-rtcweb-mid-01
1411 // a=ssrc:<ssrc-id> mslabel:<value>
1412 // The label isn't yet defined.
1413 // a=ssrc:<ssrc-id> label:<value>
1414 AddSsrcLine(ssrc, kSsrcAttributeMslabel, track->sync_label, message);
1415 AddSsrcLine(ssrc, kSSrcAttributeLabel, track->id, message);
1416 }
1417 }
1418}
1419
1420void WriteFmtpHeader(int payload_type, std::ostringstream* os) {
1421 // fmtp header: a=fmtp:|payload_type| <parameters>
1422 // Add a=fmtp
1423 InitAttrLine(kAttributeFmtp, os);
1424 // Add :|payload_type|
1425 *os << kSdpDelimiterColon << payload_type;
1426}
1427
1428void WriteRtcpFbHeader(int payload_type, std::ostringstream* os) {
1429 // rtcp-fb header: a=rtcp-fb:|payload_type|
1430 // <parameters>/<ccm <ccm_parameters>>
1431 // Add a=rtcp-fb
1432 InitAttrLine(kAttributeRtcpFb, os);
1433 // Add :
1434 *os << kSdpDelimiterColon;
1435 if (payload_type == kWildcardPayloadType) {
1436 *os << "*";
1437 } else {
1438 *os << payload_type;
1439 }
1440}
1441
1442void WriteFmtpParameter(const std::string& parameter_name,
1443 const std::string& parameter_value,
1444 std::ostringstream* os) {
1445 // fmtp parameters: |parameter_name|=|parameter_value|
1446 *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1447}
1448
1449void WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1450 std::ostringstream* os) {
1451 for (cricket::CodecParameterMap::const_iterator fmtp = parameters.begin();
1452 fmtp != parameters.end(); ++fmtp) {
1453 // Each new parameter, except the first one starts with ";" and " ".
1454 if (fmtp != parameters.begin()) {
1455 *os << kSdpDelimiterSemicolon;
1456 }
1457 *os << kSdpDelimiterSpace;
1458 WriteFmtpParameter(fmtp->first, fmtp->second, os);
1459 }
1460}
1461
1462bool IsFmtpParam(const std::string& name) {
1463 const char* kFmtpParams[] = {
1464 kCodecParamMinPTime, kCodecParamSPropStereo,
1465 kCodecParamStereo, kCodecParamUseInbandFec,
1466 kCodecParamMaxBitrate, kCodecParamMinBitrate, kCodecParamMaxQuantization,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001467 kCodecParamSctpProtocol, kCodecParamSctpStreams,
1468 kCodecParamMaxAverageBitrate
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469 };
1470 for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
1471 if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
1472 return true;
1473 }
1474 }
1475 return false;
1476}
1477
1478// Retreives fmtp parameters from |params|, which may contain other parameters
1479// as well, and puts them in |fmtp_parameters|.
1480void GetFmtpParams(const cricket::CodecParameterMap& params,
1481 cricket::CodecParameterMap* fmtp_parameters) {
1482 for (cricket::CodecParameterMap::const_iterator iter = params.begin();
1483 iter != params.end(); ++iter) {
1484 if (IsFmtpParam(iter->first)) {
1485 (*fmtp_parameters)[iter->first] = iter->second;
1486 }
1487 }
1488}
1489
1490template <class T>
1491void AddFmtpLine(const T& codec, std::string* message) {
1492 cricket::CodecParameterMap fmtp_parameters;
1493 GetFmtpParams(codec.params, &fmtp_parameters);
1494 if (fmtp_parameters.empty()) {
1495 // No need to add an fmtp if it will have no (optional) parameters.
1496 return;
1497 }
1498 std::ostringstream os;
1499 WriteFmtpHeader(codec.id, &os);
1500 WriteFmtpParameters(fmtp_parameters, &os);
1501 AddLine(os.str(), message);
1502 return;
1503}
1504
1505template <class T>
1506void AddRtcpFbLines(const T& codec, std::string* message) {
1507 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
1508 codec.feedback_params.params().begin();
1509 iter != codec.feedback_params.params().end(); ++iter) {
1510 std::ostringstream os;
1511 WriteRtcpFbHeader(codec.id, &os);
1512 os << " " << iter->id();
1513 if (!iter->param().empty()) {
1514 os << " " << iter->param();
1515 }
1516 AddLine(os.str(), message);
1517 }
1518}
1519
1520bool GetMinValue(const std::vector<int>& values, int* value) {
1521 if (values.empty()) {
1522 return false;
1523 }
1524 std::vector<int>::const_iterator found =
1525 std::min_element(values.begin(), values.end());
1526 *value = *found;
1527 return true;
1528}
1529
1530bool GetParameter(const std::string& name,
1531 const cricket::CodecParameterMap& params, int* value) {
1532 std::map<std::string, std::string>::const_iterator found =
1533 params.find(name);
1534 if (found == params.end()) {
1535 return false;
1536 }
1537 *value = talk_base::FromString<int>(found->second);
1538 return true;
1539}
1540
1541void BuildRtpMap(const MediaContentDescription* media_desc,
1542 const MediaType media_type,
1543 std::string* message) {
1544 ASSERT(message != NULL);
1545 ASSERT(media_desc != NULL);
1546 std::ostringstream os;
1547 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1548 const VideoContentDescription* video_desc =
1549 static_cast<const VideoContentDescription*>(media_desc);
1550 for (std::vector<cricket::VideoCodec>::const_iterator it =
1551 video_desc->codecs().begin();
1552 it != video_desc->codecs().end(); ++it) {
1553 // RFC 4566
1554 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1555 // [/<encodingparameters>]
1556 if (it->id != kWildcardPayloadType) {
1557 InitAttrLine(kAttributeRtpmap, &os);
1558 os << kSdpDelimiterColon << it->id << " " << it->name
1559 << "/" << kDefaultVideoClockrate;
1560 AddLine(os.str(), message);
1561 }
1562 AddRtcpFbLines(*it, message);
1563 AddFmtpLine(*it, message);
1564 }
1565 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1566 const AudioContentDescription* audio_desc =
1567 static_cast<const AudioContentDescription*>(media_desc);
1568 std::vector<int> ptimes;
1569 std::vector<int> maxptimes;
1570 int max_minptime = 0;
1571 for (std::vector<cricket::AudioCodec>::const_iterator it =
1572 audio_desc->codecs().begin();
1573 it != audio_desc->codecs().end(); ++it) {
1574 ASSERT(!it->name.empty());
1575 // RFC 4566
1576 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1577 // [/<encodingparameters>]
1578 InitAttrLine(kAttributeRtpmap, &os);
1579 os << kSdpDelimiterColon << it->id << " ";
1580 os << it->name << "/" << it->clockrate;
1581 if (it->channels != 1) {
1582 os << "/" << it->channels;
1583 }
1584 AddLine(os.str(), message);
1585 AddRtcpFbLines(*it, message);
1586 AddFmtpLine(*it, message);
1587 int minptime = 0;
1588 if (GetParameter(kCodecParamMinPTime, it->params, &minptime)) {
1589 max_minptime = std::max(minptime, max_minptime);
1590 }
1591 int ptime;
1592 if (GetParameter(kCodecParamPTime, it->params, &ptime)) {
1593 ptimes.push_back(ptime);
1594 }
1595 int maxptime;
1596 if (GetParameter(kCodecParamMaxPTime, it->params, &maxptime)) {
1597 maxptimes.push_back(maxptime);
1598 }
1599 }
1600 // Populate the maxptime attribute with the smallest maxptime of all codecs
1601 // under the same m-line.
1602 int min_maxptime = INT_MAX;
1603 if (GetMinValue(maxptimes, &min_maxptime)) {
1604 AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1605 }
1606 ASSERT(min_maxptime > max_minptime);
1607 // Populate the ptime attribute with the smallest ptime or the largest
1608 // minptime, whichever is the largest, for all codecs under the same m-line.
1609 int ptime = INT_MAX;
1610 if (GetMinValue(ptimes, &ptime)) {
1611 ptime = std::min(ptime, min_maxptime);
1612 ptime = std::max(ptime, max_minptime);
1613 AddAttributeLine(kCodecParamPTime, ptime, message);
1614 }
1615 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1616 const DataContentDescription* data_desc =
1617 static_cast<const DataContentDescription*>(media_desc);
1618 for (std::vector<cricket::DataCodec>::const_iterator it =
1619 data_desc->codecs().begin();
1620 it != data_desc->codecs().end(); ++it) {
1621 // RFC 4566
1622 // a=rtpmap:<payload type> <encoding name>/<clock rate>
1623 // [/<encodingparameters>]
1624 InitAttrLine(kAttributeRtpmap, &os);
1625 os << kSdpDelimiterColon << it->id << " "
1626 << it->name << "/" << it->clockrate;
1627 AddLine(os.str(), message);
1628 }
1629 }
1630}
1631
1632void BuildCandidate(const std::vector<Candidate>& candidates,
1633 std::string* message) {
1634 std::ostringstream os;
1635
1636 for (std::vector<Candidate>::const_iterator it = candidates.begin();
1637 it != candidates.end(); ++it) {
1638 // RFC 5245
1639 // a=candidate:<foundation> <component-id> <transport> <priority>
1640 // <connection-address> <port> typ <candidate-types>
1641 // [raddr <connection-address>] [rport <port>]
1642 // *(SP extension-att-name SP extension-att-value)
1643 std::string type;
1644 // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1645 if (it->type() == cricket::LOCAL_PORT_TYPE) {
1646 type = kCandidateHost;
1647 } else if (it->type() == cricket::STUN_PORT_TYPE) {
1648 type = kCandidateSrflx;
1649 } else if (it->type() == cricket::RELAY_PORT_TYPE) {
1650 type = kCandidateRelay;
1651 } else {
1652 ASSERT(false);
1653 }
1654
1655 InitAttrLine(kAttributeCandidate, &os);
1656 os << kSdpDelimiterColon
1657 << it->foundation() << " " << it->component() << " "
1658 << it->protocol() << " " << it->priority() << " "
1659 << it->address().ipaddr().ToString() << " "
1660 << it->address().PortAsString() << " "
1661 << kAttributeCandidateTyp << " " << type << " ";
1662
1663 // Related address
1664 if (!it->related_address().IsNil()) {
1665 os << kAttributeCandidateRaddr << " "
1666 << it->related_address().ipaddr().ToString() << " "
1667 << kAttributeCandidateRport << " "
1668 << it->related_address().PortAsString() << " ";
1669 }
1670
1671 // Extensions
1672 os << kAttributeCandidateGeneration << " " << it->generation();
1673
1674 AddLine(os.str(), message);
1675 }
1676}
1677
1678void BuildIceOptions(const std::vector<std::string>& transport_options,
1679 std::string* message) {
1680 if (!transport_options.empty()) {
1681 std::ostringstream os;
1682 InitAttrLine(kAttributeIceOption, &os);
1683 os << kSdpDelimiterColon << transport_options[0];
1684 for (size_t i = 1; i < transport_options.size(); ++i) {
1685 os << kSdpDelimiterSpace << transport_options[i];
1686 }
1687 AddLine(os.str(), message);
1688 }
1689}
1690
1691bool ParseSessionDescription(const std::string& message, size_t* pos,
1692 std::string* session_id,
1693 std::string* session_version,
1694 bool* supports_msid,
1695 TransportDescription* session_td,
1696 RtpHeaderExtensions* session_extmaps,
1697 cricket::SessionDescription* desc,
1698 SdpParseError* error) {
1699 std::string line;
1700
1701 // RFC 4566
1702 // v= (protocol version)
1703 if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
1704 return ParseFailedExpectLine(message, *pos, kLineTypeVersion,
1705 std::string(), error);
1706 }
1707 // RFC 4566
1708 // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
1709 // <unicast-address>
1710 if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
1711 return ParseFailedExpectLine(message, *pos, kLineTypeOrigin,
1712 std::string(), error);
1713 }
1714 std::vector<std::string> fields;
1715 talk_base::split(line.substr(kLinePrefixLength),
1716 kSdpDelimiterSpace, &fields);
1717 const size_t expected_fields = 6;
1718 if (fields.size() != expected_fields) {
1719 return ParseFailedExpectFieldNum(line, expected_fields, error);
1720 }
1721 *session_id = fields[1];
1722 *session_version = fields[2];
1723
1724 // RFC 4566
1725 // s= (session name)
1726 if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
1727 return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
1728 std::string(), error);
1729 }
1730
1731 // Optional lines
1732 // Those are the optional lines, so shouldn't return false if not present.
1733 // RFC 4566
1734 // i=* (session information)
1735 GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
1736
1737 // RFC 4566
1738 // u=* (URI of description)
1739 GetLineWithType(message, pos, &line, kLineTypeSessionUri);
1740
1741 // RFC 4566
1742 // e=* (email address)
1743 GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
1744
1745 // RFC 4566
1746 // p=* (phone number)
1747 GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
1748
1749 // RFC 4566
1750 // c=* (connection information -- not required if included in
1751 // all media)
1752 GetLineWithType(message, pos, &line, kLineTypeConnection);
1753
1754 // RFC 4566
1755 // b=* (zero or more bandwidth information lines)
1756 while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
1757 // By pass zero or more b lines.
1758 }
1759
1760 // RFC 4566
1761 // One or more time descriptions ("t=" and "r=" lines; see below)
1762 // t= (time the session is active)
1763 // r=* (zero or more repeat times)
1764 // Ensure there's at least one time description
1765 if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1766 return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
1767 error);
1768 }
1769
1770 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1771 // By pass zero or more r lines.
1772 }
1773
1774 // Go through the rest of the time descriptions
1775 while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
1776 while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
1777 // By pass zero or more r lines.
1778 }
1779 }
1780
1781 // RFC 4566
1782 // z=* (time zone adjustments)
1783 GetLineWithType(message, pos, &line, kLineTypeTimeZone);
1784
1785 // RFC 4566
1786 // k=* (encryption key)
1787 GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
1788
1789 // RFC 4566
1790 // a=* (zero or more session attribute lines)
1791 while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
1792 if (HasAttribute(line, kAttributeGroup)) {
1793 if (!ParseGroupAttribute(line, desc, error)) {
1794 return false;
1795 }
1796 } else if (HasAttribute(line, kAttributeIceUfrag)) {
1797 if (!GetValue(line, kAttributeIceUfrag,
1798 &(session_td->ice_ufrag), error)) {
1799 return false;
1800 }
1801 } else if (HasAttribute(line, kAttributeIcePwd)) {
1802 if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
1803 return false;
1804 }
1805 } else if (HasAttribute(line, kAttributeIceLite)) {
1806 session_td->ice_mode = cricket::ICEMODE_LITE;
1807 } else if (HasAttribute(line, kAttributeIceOption)) {
1808 if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
1809 return false;
1810 }
1811 } else if (HasAttribute(line, kAttributeFingerprint)) {
1812 if (session_td->identity_fingerprint.get()) {
1813 return ParseFailed(
1814 line,
1815 "Can't have multiple fingerprint attributes at the same level.",
1816 error);
1817 }
1818 talk_base::SSLFingerprint* fingerprint = NULL;
1819 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
1820 return false;
1821 }
1822 session_td->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001823 } else if (HasAttribute(line, kAttributeSetup)) {
1824 if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
1825 return false;
1826 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001827 } else if (HasAttribute(line, kAttributeMsidSemantics)) {
1828 std::string semantics;
1829 if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
1830 return false;
1831 }
1832 *supports_msid = CaseInsensitiveFind(semantics, kMediaStreamSemantic);
1833 } else if (HasAttribute(line, kAttributeExtmap)) {
1834 RtpHeaderExtension extmap;
1835 if (!ParseExtmap(line, &extmap, error)) {
1836 return false;
1837 }
1838 session_extmaps->push_back(extmap);
1839 }
1840 }
1841
1842 return true;
1843}
1844
1845bool ParseGroupAttribute(const std::string& line,
1846 cricket::SessionDescription* desc,
1847 SdpParseError* error) {
1848 ASSERT(desc != NULL);
1849
1850 // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
1851 // a=group:BUNDLE video voice
1852 std::vector<std::string> fields;
1853 talk_base::split(line.substr(kLinePrefixLength),
1854 kSdpDelimiterSpace, &fields);
1855 std::string semantics;
1856 if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
1857 return false;
1858 }
1859 cricket::ContentGroup group(semantics);
1860 for (size_t i = 1; i < fields.size(); ++i) {
1861 group.AddContentName(fields[i]);
1862 }
1863 desc->AddGroup(group);
1864 return true;
1865}
1866
1867static bool ParseFingerprintAttribute(const std::string& line,
1868 talk_base::SSLFingerprint** fingerprint,
1869 SdpParseError* error) {
1870 if (!IsLineType(line, kLineTypeAttributes) ||
1871 !HasAttribute(line, kAttributeFingerprint)) {
1872 return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
1873 kAttributeFingerprint, error);
1874 }
1875
1876 std::vector<std::string> fields;
1877 talk_base::split(line.substr(kLinePrefixLength),
1878 kSdpDelimiterSpace, &fields);
1879 const size_t expected_fields = 2;
1880 if (fields.size() != expected_fields) {
1881 return ParseFailedExpectFieldNum(line, expected_fields, error);
1882 }
1883
1884 // The first field here is "fingerprint:<hash>.
1885 std::string algorithm;
1886 if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
1887 return false;
1888 }
1889
1890 // Downcase the algorithm. Note that we don't need to downcase the
1891 // fingerprint because hex_decode can handle upper-case.
1892 std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
1893 ::tolower);
1894
1895 // The second field is the digest value. De-hexify it.
1896 *fingerprint = talk_base::SSLFingerprint::CreateFromRfc4572(
1897 algorithm, fields[1]);
1898 if (!*fingerprint) {
1899 return ParseFailed(line,
1900 "Failed to create fingerprint from the digest.",
1901 error);
1902 }
1903
1904 return true;
1905}
1906
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001907static bool ParseDtlsSetup(const std::string& line,
1908 cricket::ConnectionRole* role,
1909 SdpParseError* error) {
1910 // setup-attr = "a=setup:" role
1911 // role = "active" / "passive" / "actpass" / "holdconn"
1912 std::vector<std::string> fields;
1913 talk_base::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
1914 const size_t expected_fields = 2;
1915 if (fields.size() != expected_fields) {
1916 return ParseFailedExpectFieldNum(line, expected_fields, error);
1917 }
1918 std::string role_str = fields[1];
1919 if (!cricket::StringToConnectionRole(role_str, role)) {
1920 return ParseFailed(line, "Invalid attribute value.", error);
1921 }
1922 return true;
1923}
1924
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001925// RFC 3551
1926// PT encoding media type clock rate channels
1927// name (Hz)
1928// 0 PCMU A 8,000 1
1929// 1 reserved A
1930// 2 reserved A
1931// 3 GSM A 8,000 1
1932// 4 G723 A 8,000 1
1933// 5 DVI4 A 8,000 1
1934// 6 DVI4 A 16,000 1
1935// 7 LPC A 8,000 1
1936// 8 PCMA A 8,000 1
1937// 9 G722 A 8,000 1
1938// 10 L16 A 44,100 2
1939// 11 L16 A 44,100 1
1940// 12 QCELP A 8,000 1
1941// 13 CN A 8,000 1
1942// 14 MPA A 90,000 (see text)
1943// 15 G728 A 8,000 1
1944// 16 DVI4 A 11,025 1
1945// 17 DVI4 A 22,050 1
1946// 18 G729 A 8,000 1
1947struct StaticPayloadAudioCodec {
1948 const char* name;
1949 int clockrate;
1950 int channels;
1951};
1952static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
1953 { "PCMU", 8000, 1 },
1954 { "reserved", 0, 0 },
1955 { "reserved", 0, 0 },
1956 { "GSM", 8000, 1 },
1957 { "G723", 8000, 1 },
1958 { "DVI4", 8000, 1 },
1959 { "DVI4", 16000, 1 },
1960 { "LPC", 8000, 1 },
1961 { "PCMA", 8000, 1 },
1962 { "G722", 8000, 1 },
1963 { "L16", 44100, 2 },
1964 { "L16", 44100, 1 },
1965 { "QCELP", 8000, 1 },
1966 { "CN", 8000, 1 },
1967 { "MPA", 90000, 1 },
1968 { "G728", 8000, 1 },
1969 { "DVI4", 11025, 1 },
1970 { "DVI4", 22050, 1 },
1971 { "G729", 8000, 1 },
1972};
1973
1974void MaybeCreateStaticPayloadAudioCodecs(
1975 const std::vector<int>& fmts, AudioContentDescription* media_desc) {
1976 if (!media_desc) {
1977 return;
1978 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001979 int preference = static_cast<int>(fmts.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001980 std::vector<int>::const_iterator it = fmts.begin();
1981 bool add_new_codec = false;
1982 for (; it != fmts.end(); ++it) {
1983 int payload_type = *it;
1984 if (!media_desc->HasCodec(payload_type) &&
1985 payload_type >= 0 &&
1986 payload_type < ARRAY_SIZE(kStaticPayloadAudioCodecs)) {
1987 std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
1988 int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
1989 int channels = kStaticPayloadAudioCodecs[payload_type].channels;
1990 media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
1991 clock_rate, 0, channels,
1992 preference));
1993 add_new_codec = true;
1994 }
1995 --preference;
1996 }
1997 if (add_new_codec) {
1998 media_desc->SortCodecs();
1999 }
2000}
2001
2002template <class C>
2003static C* ParseContentDescription(const std::string& message,
2004 const MediaType media_type,
2005 int mline_index,
2006 const std::string& protocol,
2007 const std::vector<int>& codec_preference,
2008 size_t* pos,
2009 std::string* content_name,
2010 TransportDescription* transport,
2011 std::vector<JsepIceCandidate*>* candidates,
2012 webrtc::SdpParseError* error) {
2013 C* media_desc = new C();
2014 switch (media_type) {
2015 case cricket::MEDIA_TYPE_AUDIO:
2016 *content_name = cricket::CN_AUDIO;
2017 break;
2018 case cricket::MEDIA_TYPE_VIDEO:
2019 *content_name = cricket::CN_VIDEO;
2020 break;
2021 case cricket::MEDIA_TYPE_DATA:
2022 *content_name = cricket::CN_DATA;
2023 break;
2024 default:
2025 ASSERT(false);
2026 break;
2027 }
2028 if (!ParseContent(message, media_type, mline_index, protocol,
2029 codec_preference, pos, content_name,
2030 media_desc, transport, candidates, error)) {
2031 delete media_desc;
2032 return NULL;
2033 }
2034 // Sort the codecs according to the m-line fmt list.
2035 media_desc->SortCodecs();
2036 return media_desc;
2037}
2038
2039bool ParseMediaDescription(const std::string& message,
2040 const TransportDescription& session_td,
2041 const RtpHeaderExtensions& session_extmaps,
2042 bool supports_msid,
2043 size_t* pos,
2044 cricket::SessionDescription* desc,
2045 std::vector<JsepIceCandidate*>* candidates,
2046 SdpParseError* error) {
2047 ASSERT(desc != NULL);
2048 std::string line;
2049 int mline_index = -1;
2050
2051 // Zero or more media descriptions
2052 // RFC 4566
2053 // m=<media> <port> <proto> <fmt>
2054 while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2055 ++mline_index;
2056
2057 std::vector<std::string> fields;
2058 talk_base::split(line.substr(kLinePrefixLength),
2059 kSdpDelimiterSpace, &fields);
2060 const size_t expected_min_fields = 4;
2061 if (fields.size() < expected_min_fields) {
2062 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2063 }
2064 bool rejected = false;
2065 // RFC 3264
2066 // To reject an offered stream, the port number in the corresponding stream
2067 // in the answer MUST be set to zero.
2068 if (fields[1] == kMediaPortRejected) {
2069 rejected = true;
2070 }
2071
2072 std::string protocol = fields[2];
2073 bool is_sctp = (protocol == cricket::kMediaProtocolDtlsSctp);
2074
2075 // <fmt>
2076 std::vector<int> codec_preference;
2077 for (size_t j = 3 ; j < fields.size(); ++j) {
2078 codec_preference.push_back(talk_base::FromString<int>(fields[j]));
2079 }
2080
2081 // Make a temporary TransportDescription based on |session_td|.
2082 // Some of this gets overwritten by ParseContent.
2083 TransportDescription transport(NS_JINGLE_ICE_UDP,
2084 session_td.transport_options,
2085 session_td.ice_ufrag,
2086 session_td.ice_pwd,
2087 session_td.ice_mode,
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002088 session_td.connection_role,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002089 session_td.identity_fingerprint.get(),
2090 Candidates());
2091
2092 talk_base::scoped_ptr<MediaContentDescription> content;
2093 std::string content_name;
2094 if (HasAttribute(line, kMediaTypeVideo)) {
2095 content.reset(ParseContentDescription<VideoContentDescription>(
2096 message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2097 codec_preference, pos, &content_name,
2098 &transport, candidates, error));
2099 } else if (HasAttribute(line, kMediaTypeAudio)) {
2100 content.reset(ParseContentDescription<AudioContentDescription>(
2101 message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2102 codec_preference, pos, &content_name,
2103 &transport, candidates, error));
2104 MaybeCreateStaticPayloadAudioCodecs(
2105 codec_preference,
2106 static_cast<AudioContentDescription*>(content.get()));
2107 } else if (HasAttribute(line, kMediaTypeData)) {
2108 content.reset(ParseContentDescription<DataContentDescription>(
2109 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2110 codec_preference, pos, &content_name,
2111 &transport, candidates, error));
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002112 // We should always use the default bandwidth for RTP-based data
2113 // channels. Don't allow SDP to set the bandwidth, because that
2114 // would give JS the opportunity to "break the Internet".
2115 content->set_bandwidth(cricket::kAutoBandwidth);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002116 } else {
2117 LOG(LS_WARNING) << "Unsupported media type: " << line;
2118 continue;
2119 }
2120 if (!content.get()) {
2121 // ParseContentDescription returns NULL if failed.
2122 return false;
2123 }
2124
2125 if (!is_sctp) {
2126 // Make sure to set the media direction correctly. If the direction is not
2127 // MD_RECVONLY or Inactive and no streams are parsed,
2128 // a default MediaStream will be created to prepare for receiving media.
2129 if (supports_msid && content->streams().empty() &&
2130 content->direction() == cricket::MD_SENDRECV) {
2131 content->set_direction(cricket::MD_RECVONLY);
2132 }
2133
2134 // Set the extmap.
2135 if (!session_extmaps.empty() &&
2136 !content->rtp_header_extensions().empty()) {
2137 return ParseFailed("",
2138 "The a=extmap MUST be either all session level or "
2139 "all media level.",
2140 error);
2141 }
2142 for (size_t i = 0; i < session_extmaps.size(); ++i) {
2143 content->AddRtpHeaderExtension(session_extmaps[i]);
2144 }
2145 }
2146 content->set_protocol(protocol);
2147 desc->AddContent(content_name,
2148 is_sctp ? cricket::NS_JINGLE_DRAFT_SCTP :
2149 cricket::NS_JINGLE_RTP,
2150 rejected,
2151 content.release());
2152 // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2153 TransportInfo transport_info(content_name, transport);
2154
2155 if (!desc->AddTransportInfo(transport_info)) {
2156 std::ostringstream description;
2157 description << "Failed to AddTransportInfo with content name: "
2158 << content_name;
2159 return ParseFailed("", description.str(), error);
2160 }
2161 }
2162 return true;
2163}
2164
2165bool VerifyCodec(const cricket::Codec& codec) {
2166 // Codec has not been populated correctly unless the name has been set. This
2167 // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2168 // have a corresponding "rtpmap" line.
2169 cricket::Codec default_codec;
2170 return default_codec.name != codec.name;
2171}
2172
2173bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2174 const std::vector<cricket::AudioCodec>& codecs = audio_desc->codecs();
2175 for (std::vector<cricket::AudioCodec>::const_iterator iter = codecs.begin();
2176 iter != codecs.end(); ++iter) {
2177 if (!VerifyCodec(*iter)) {
2178 return false;
2179 }
2180 }
2181 return true;
2182}
2183
2184bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2185 const std::vector<cricket::VideoCodec>& codecs = video_desc->codecs();
2186 for (std::vector<cricket::VideoCodec>::const_iterator iter = codecs.begin();
2187 iter != codecs.end(); ++iter) {
2188 if (!VerifyCodec(*iter)) {
2189 return false;
2190 }
2191 }
2192 return true;
2193}
2194
2195void AddParameters(const cricket::CodecParameterMap& parameters,
2196 cricket::Codec* codec) {
2197 for (cricket::CodecParameterMap::const_iterator iter =
2198 parameters.begin(); iter != parameters.end(); ++iter) {
2199 codec->SetParam(iter->first, iter->second);
2200 }
2201}
2202
2203void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2204 cricket::Codec* codec) {
2205 codec->AddFeedbackParam(feedback_param);
2206}
2207
2208void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2209 cricket::Codec* codec) {
2210 for (std::vector<cricket::FeedbackParam>::const_iterator iter =
2211 feedback_params.params().begin();
2212 iter != feedback_params.params().end(); ++iter) {
2213 codec->AddFeedbackParam(*iter);
2214 }
2215}
2216
2217// Gets the current codec setting associated with |payload_type|. If there
2218// is no AudioCodec associated with that payload type it returns an empty codec
2219// with that payload type.
2220template <class T>
2221T GetCodec(const std::vector<T>& codecs, int payload_type) {
2222 for (typename std::vector<T>::const_iterator codec = codecs.begin();
2223 codec != codecs.end(); ++codec) {
2224 if (codec->id == payload_type) {
2225 return *codec;
2226 }
2227 }
2228 T ret_val = T();
2229 ret_val.id = payload_type;
2230 return ret_val;
2231}
2232
2233// Updates or creates a new codec entry in the audio description.
2234template <class T, class U>
2235void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2236 T* desc = static_cast<T*>(content_desc);
2237 std::vector<U> codecs = desc->codecs();
2238 bool found = false;
2239
2240 typename std::vector<U>::iterator iter;
2241 for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
2242 if (iter->id == codec.id) {
2243 *iter = codec;
2244 found = true;
2245 break;
2246 }
2247 }
2248 if (!found) {
2249 desc->AddCodec(codec);
2250 return;
2251 }
2252 desc->set_codecs(codecs);
2253}
2254
2255// Adds or updates existing codec corresponding to |payload_type| according
2256// to |parameters|.
2257template <class T, class U>
2258void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2259 const cricket::CodecParameterMap& parameters) {
2260 // Codec might already have been populated (from rtpmap).
2261 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2262 AddParameters(parameters, &new_codec);
2263 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2264}
2265
2266// Adds or updates existing codec corresponding to |payload_type| according
2267// to |feedback_param|.
2268template <class T, class U>
2269void UpdateCodec(MediaContentDescription* content_desc, int payload_type,
2270 const cricket::FeedbackParam& feedback_param) {
2271 // Codec might already have been populated (from rtpmap).
2272 U new_codec = GetCodec(static_cast<T*>(content_desc)->codecs(), payload_type);
2273 AddFeedbackParameter(feedback_param, &new_codec);
2274 AddOrReplaceCodec<T, U>(content_desc, new_codec);
2275}
2276
2277bool PopWildcardCodec(std::vector<cricket::VideoCodec>* codecs,
2278 cricket::VideoCodec* wildcard_codec) {
2279 for (std::vector<cricket::VideoCodec>::iterator iter = codecs->begin();
2280 iter != codecs->end(); ++iter) {
2281 if (iter->id == kWildcardPayloadType) {
2282 *wildcard_codec = *iter;
2283 codecs->erase(iter);
2284 return true;
2285 }
2286 }
2287 return false;
2288}
2289
2290void UpdateFromWildcardVideoCodecs(VideoContentDescription* video_desc) {
2291 std::vector<cricket::VideoCodec> codecs = video_desc->codecs();
2292 cricket::VideoCodec wildcard_codec;
2293 if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2294 return;
2295 }
2296 for (std::vector<cricket::VideoCodec>::iterator iter = codecs.begin();
2297 iter != codecs.end(); ++iter) {
2298 cricket::VideoCodec& codec = *iter;
2299 AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2300 }
2301 video_desc->set_codecs(codecs);
2302}
2303
2304void AddAudioAttribute(const std::string& name, const std::string& value,
2305 AudioContentDescription* audio_desc) {
2306 if (value.empty()) {
2307 return;
2308 }
2309 std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2310 for (std::vector<cricket::AudioCodec>::iterator iter = codecs.begin();
2311 iter != codecs.end(); ++iter) {
2312 iter->params[name] = value;
2313 }
2314 audio_desc->set_codecs(codecs);
2315}
2316
2317bool ParseContent(const std::string& message,
2318 const MediaType media_type,
2319 int mline_index,
2320 const std::string& protocol,
2321 const std::vector<int>& codec_preference,
2322 size_t* pos,
2323 std::string* content_name,
2324 MediaContentDescription* media_desc,
2325 TransportDescription* transport,
2326 std::vector<JsepIceCandidate*>* candidates,
2327 SdpParseError* error) {
2328 ASSERT(media_desc != NULL);
2329 ASSERT(content_name != NULL);
2330 ASSERT(transport != NULL);
2331
2332 // The media level "ice-ufrag" and "ice-pwd".
2333 // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2334 Candidates candidates_orig;
2335 std::string line;
2336 std::string mline_id;
2337 // Tracks created out of the ssrc attributes.
2338 StreamParamsVec tracks;
2339 SsrcInfoVec ssrc_infos;
2340 SsrcGroupVec ssrc_groups;
2341 std::string maxptime_as_string;
2342 std::string ptime_as_string;
2343
2344 bool is_rtp =
2345 protocol.empty() ||
2346 talk_base::starts_with(protocol.data(),
2347 cricket::kMediaProtocolRtpPrefix);
2348
2349 // Loop until the next m line
2350 while (!IsLineType(message, kLineTypeMedia, *pos)) {
2351 if (!GetLine(message, pos, &line)) {
2352 if (*pos >= message.size()) {
2353 break; // Done parsing
2354 } else {
2355 return ParseFailed(message, *pos, "Can't find valid SDP line.", error);
2356 }
2357 }
2358
2359 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2360 std::string bandwidth;
2361 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2362 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2363 return false;
2364 } else {
2365 media_desc->set_bandwidth(
2366 talk_base::FromString<int>(bandwidth) * 1000);
2367 }
2368 }
2369 continue;
2370 }
2371
2372 // RFC 4566
2373 // b=* (zero or more bandwidth information lines)
2374 if (IsLineType(line, kLineTypeSessionBandwidth)) {
2375 std::string bandwidth;
2376 if (HasAttribute(line, kApplicationSpecificMaximum)) {
2377 if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2378 return false;
2379 } else {
2380 media_desc->set_bandwidth(
2381 talk_base::FromString<int>(bandwidth) * 1000);
2382 }
2383 }
2384 continue;
2385 }
2386
2387 if (!IsLineType(line, kLineTypeAttributes)) {
2388 // TODO: Handle other lines if needed.
2389 LOG(LS_INFO) << "Ignored line: " << line;
2390 continue;
2391 }
2392
2393 // Handle attributes common to SCTP and RTP.
2394 if (HasAttribute(line, kAttributeMid)) {
2395 // RFC 3388
2396 // mid-attribute = "a=mid:" identification-tag
2397 // identification-tag = token
2398 // Use the mid identification-tag as the content name.
2399 if (!GetValue(line, kAttributeMid, &mline_id, error)) {
2400 return false;
2401 }
2402 *content_name = mline_id;
2403 } else if (HasAttribute(line, kAttributeCandidate)) {
2404 Candidate candidate;
2405 if (!ParseCandidate(line, &candidate, error, false)) {
2406 return false;
2407 }
2408 candidates_orig.push_back(candidate);
2409 } else if (HasAttribute(line, kAttributeIceUfrag)) {
2410 if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
2411 return false;
2412 }
2413 } else if (HasAttribute(line, kAttributeIcePwd)) {
2414 if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
2415 return false;
2416 }
2417 } else if (HasAttribute(line, kAttributeIceOption)) {
2418 if (!ParseIceOptions(line, &transport->transport_options, error)) {
2419 return false;
2420 }
2421 } else if (HasAttribute(line, kAttributeFmtp)) {
2422 if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
2423 return false;
2424 }
2425 } else if (HasAttribute(line, kAttributeFingerprint)) {
2426 talk_base::SSLFingerprint* fingerprint = NULL;
2427
2428 if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2429 return false;
2430 }
2431 transport->identity_fingerprint.reset(fingerprint);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00002432 } else if (HasAttribute(line, kAttributeSetup)) {
2433 if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
2434 return false;
2435 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002436 } else if (is_rtp) {
2437 //
2438 // RTP specific attrubtes
2439 //
2440 if (HasAttribute(line, kAttributeRtcpMux)) {
2441 media_desc->set_rtcp_mux(true);
2442 } else if (HasAttribute(line, kAttributeSsrcGroup)) {
2443 if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
2444 return false;
2445 }
2446 } else if (HasAttribute(line, kAttributeSsrc)) {
2447 if (!ParseSsrcAttribute(line, &ssrc_infos, error)) {
2448 return false;
2449 }
2450 } else if (HasAttribute(line, kAttributeCrypto)) {
2451 if (!ParseCryptoAttribute(line, media_desc, error)) {
2452 return false;
2453 }
2454 } else if (HasAttribute(line, kAttributeRtpmap)) {
2455 if (!ParseRtpmapAttribute(line, media_type, codec_preference,
2456 media_desc, error)) {
2457 return false;
2458 }
2459 } else if (HasAttribute(line, kCodecParamMaxPTime)) {
2460 if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
2461 return false;
2462 }
2463 } else if (HasAttribute(line, kAttributeRtcpFb)) {
2464 if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
2465 return false;
2466 }
2467 } else if (HasAttribute(line, kCodecParamPTime)) {
2468 if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
2469 return false;
2470 }
2471 } else if (HasAttribute(line, kAttributeSendOnly)) {
2472 media_desc->set_direction(cricket::MD_SENDONLY);
2473 } else if (HasAttribute(line, kAttributeRecvOnly)) {
2474 media_desc->set_direction(cricket::MD_RECVONLY);
2475 } else if (HasAttribute(line, kAttributeInactive)) {
2476 media_desc->set_direction(cricket::MD_INACTIVE);
2477 } else if (HasAttribute(line, kAttributeSendRecv)) {
2478 media_desc->set_direction(cricket::MD_SENDRECV);
2479 } else if (HasAttribute(line, kAttributeExtmap)) {
2480 RtpHeaderExtension extmap;
2481 if (!ParseExtmap(line, &extmap, error)) {
2482 return false;
2483 }
2484 media_desc->AddRtpHeaderExtension(extmap);
2485 } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
2486 // Experimental attribute. Conference mode activates more aggressive
2487 // AEC and NS settings.
2488 // TODO: expose API to set these directly.
2489 std::string flag_value;
2490 if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
2491 return false;
2492 }
2493 if (flag_value.compare(kValueConference) == 0)
2494 media_desc->set_conference_mode(true);
2495 } else if (HasAttribute(line, kAttributeXGoogleBufferLatency)) {
2496 // Experimental attribute.
2497 // TODO: expose API to set this directly.
2498 std::string flag_value;
2499 if (!GetValue(line, kAttributeXGoogleBufferLatency, &flag_value,
2500 error)) {
2501 return false;
2502 }
2503 int buffer_latency = 0;
2504 if (!talk_base::FromString(flag_value, &buffer_latency) ||
2505 buffer_latency < 0) {
2506 return ParseFailed(message, "Invalid buffer latency.", error);
2507 }
2508 media_desc->set_buffered_mode_latency(buffer_latency);
2509 }
2510 } else {
2511 // Only parse lines that we are interested of.
2512 LOG(LS_INFO) << "Ignored line: " << line;
2513 continue;
2514 }
2515 }
2516
2517 // Create tracks from the |ssrc_infos|.
2518 CreateTracksFromSsrcInfos(ssrc_infos, &tracks);
2519
2520 // Add the ssrc group to the track.
2521 for (SsrcGroupVec::iterator ssrc_group = ssrc_groups.begin();
2522 ssrc_group != ssrc_groups.end(); ++ssrc_group) {
2523 if (ssrc_group->ssrcs.empty()) {
2524 continue;
2525 }
2526 uint32 ssrc = ssrc_group->ssrcs.front();
2527 for (StreamParamsVec::iterator track = tracks.begin();
2528 track != tracks.end(); ++track) {
2529 if (track->has_ssrc(ssrc)) {
2530 track->ssrc_groups.push_back(*ssrc_group);
2531 }
2532 }
2533 }
2534
2535 // Add the new tracks to the |media_desc|.
2536 for (StreamParamsVec::iterator track = tracks.begin();
2537 track != tracks.end(); ++track) {
2538 media_desc->AddStream(*track);
2539 }
2540
2541 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2542 AudioContentDescription* audio_desc =
2543 static_cast<AudioContentDescription*>(media_desc);
2544 // Verify audio codec ensures that no audio codec has been populated with
2545 // only fmtp.
2546 if (!VerifyAudioCodecs(audio_desc)) {
2547 return ParseFailed("Failed to parse audio codecs correctly.", error);
2548 }
2549 AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
2550 AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
2551 }
2552
2553 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2554 VideoContentDescription* video_desc =
2555 static_cast<VideoContentDescription*>(media_desc);
2556 UpdateFromWildcardVideoCodecs(video_desc);
2557 // Verify video codec ensures that no video codec has been populated with
2558 // only rtcp-fb.
2559 if (!VerifyVideoCodecs(video_desc)) {
2560 return ParseFailed("Failed to parse video codecs correctly.", error);
2561 }
2562 }
2563
2564 // RFC 5245
2565 // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
2566 for (Candidates::iterator it = candidates_orig.begin();
2567 it != candidates_orig.end(); ++it) {
2568 ASSERT((*it).username().empty());
2569 (*it).set_username(transport->ice_ufrag);
2570 ASSERT((*it).password().empty());
2571 (*it).set_password(transport->ice_pwd);
2572 candidates->push_back(
2573 new JsepIceCandidate(mline_id, mline_index, *it));
2574 }
2575 return true;
2576}
2577
2578bool ParseSsrcAttribute(const std::string& line, SsrcInfoVec* ssrc_infos,
2579 SdpParseError* error) {
2580 ASSERT(ssrc_infos != NULL);
2581 // RFC 5576
2582 // a=ssrc:<ssrc-id> <attribute>
2583 // a=ssrc:<ssrc-id> <attribute>:<value>
2584 std::string field1, field2;
2585 if (!SplitByDelimiter(line.substr(kLinePrefixLength),
2586 kSdpDelimiterSpace,
2587 &field1,
2588 &field2)) {
2589 const size_t expected_fields = 2;
2590 return ParseFailedExpectFieldNum(line, expected_fields, error);
2591 }
2592
2593 // ssrc:<ssrc-id>
2594 std::string ssrc_id_s;
2595 if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
2596 return false;
2597 }
2598 uint32 ssrc_id = talk_base::FromString<uint32>(ssrc_id_s);
2599
2600 std::string attribute;
2601 std::string value;
2602 if (!SplitByDelimiter(field2, kSdpDelimiterColon,
2603 &attribute, &value)) {
2604 std::ostringstream description;
2605 description << "Failed to get the ssrc attribute value from " << field2
2606 << ". Expected format <attribute>:<value>.";
2607 return ParseFailed(line, description.str(), error);
2608 }
2609
2610 // Check if there's already an item for this |ssrc_id|. Create a new one if
2611 // there isn't.
2612 SsrcInfoVec::iterator ssrc_info = ssrc_infos->begin();
2613 for (; ssrc_info != ssrc_infos->end(); ++ssrc_info) {
2614 if (ssrc_info->ssrc_id == ssrc_id) {
2615 break;
2616 }
2617 }
2618 if (ssrc_info == ssrc_infos->end()) {
2619 SsrcInfo info;
2620 info.ssrc_id = ssrc_id;
2621 ssrc_infos->push_back(info);
2622 ssrc_info = ssrc_infos->end() - 1;
2623 }
2624
2625 // Store the info to the |ssrc_info|.
2626 if (attribute == kSsrcAttributeCname) {
2627 // RFC 5576
2628 // cname:<value>
2629 ssrc_info->cname = value;
2630 } else if (attribute == kSsrcAttributeMsid) {
2631 // draft-alvestrand-mmusic-msid-00
2632 // "msid:" identifier [ " " appdata ]
2633 std::vector<std::string> fields;
2634 talk_base::split(value, kSdpDelimiterSpace, &fields);
2635 if (fields.size() < 1 || fields.size() > 2) {
2636 return ParseFailed(line,
2637 "Expected format \"msid:<identifier>[ <appdata>]\".",
2638 error);
2639 }
2640 ssrc_info->msid_identifier = fields[0];
2641 if (fields.size() == 2) {
2642 ssrc_info->msid_appdata = fields[1];
2643 }
2644 } else if (attribute == kSsrcAttributeMslabel) {
2645 // draft-alvestrand-rtcweb-mid-01
2646 // mslabel:<value>
2647 ssrc_info->mslabel = value;
2648 } else if (attribute == kSSrcAttributeLabel) {
2649 // The label isn't defined.
2650 // label:<value>
2651 ssrc_info->label = value;
2652 }
2653 return true;
2654}
2655
2656bool ParseSsrcGroupAttribute(const std::string& line,
2657 SsrcGroupVec* ssrc_groups,
2658 SdpParseError* error) {
2659 ASSERT(ssrc_groups != NULL);
2660 // RFC 5576
2661 // a=ssrc-group:<semantics> <ssrc-id> ...
2662 std::vector<std::string> fields;
2663 talk_base::split(line.substr(kLinePrefixLength),
2664 kSdpDelimiterSpace, &fields);
2665 const size_t expected_min_fields = 2;
2666 if (fields.size() < expected_min_fields) {
2667 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2668 }
2669 std::string semantics;
2670 if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
2671 return false;
2672 }
2673 std::vector<uint32> ssrcs;
2674 for (size_t i = 1; i < fields.size(); ++i) {
2675 uint32 ssrc = talk_base::FromString<uint32>(fields[i]);
2676 ssrcs.push_back(ssrc);
2677 }
2678 ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
2679 return true;
2680}
2681
2682bool ParseCryptoAttribute(const std::string& line,
2683 MediaContentDescription* media_desc,
2684 SdpParseError* error) {
2685 std::vector<std::string> fields;
2686 talk_base::split(line.substr(kLinePrefixLength),
2687 kSdpDelimiterSpace, &fields);
2688 // RFC 4568
2689 // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
2690 const size_t expected_min_fields = 3;
2691 if (fields.size() < expected_min_fields) {
2692 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2693 }
2694 std::string tag_value;
2695 if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
2696 return false;
2697 }
2698 int tag = talk_base::FromString<int>(tag_value);
2699 const std::string crypto_suite = fields[1];
2700 const std::string key_params = fields[2];
2701 std::string session_params;
2702 if (fields.size() > 3) {
2703 session_params = fields[3];
2704 }
2705 media_desc->AddCrypto(CryptoParams(tag, crypto_suite, key_params,
2706 session_params));
2707 return true;
2708}
2709
2710// Updates or creates a new codec entry in the audio description with according
2711// to |name|, |clockrate|, |bitrate|, |channels| and |preference|.
2712void UpdateCodec(int payload_type, const std::string& name, int clockrate,
2713 int bitrate, int channels, int preference,
2714 AudioContentDescription* audio_desc) {
2715 // Codec may already be populated with (only) optional parameters
2716 // (from an fmtp).
2717 cricket::AudioCodec codec = GetCodec(audio_desc->codecs(), payload_type);
2718 codec.name = name;
2719 codec.clockrate = clockrate;
2720 codec.bitrate = bitrate;
2721 codec.channels = channels;
2722 codec.preference = preference;
2723 AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
2724 codec);
2725}
2726
2727// Updates or creates a new codec entry in the video description according to
2728// |name|, |width|, |height|, |framerate| and |preference|.
2729void UpdateCodec(int payload_type, const std::string& name, int width,
2730 int height, int framerate, int preference,
2731 VideoContentDescription* video_desc) {
2732 // Codec may already be populated with (only) optional parameters
2733 // (from an fmtp).
2734 cricket::VideoCodec codec = GetCodec(video_desc->codecs(), payload_type);
2735 codec.name = name;
2736 codec.width = width;
2737 codec.height = height;
2738 codec.framerate = framerate;
2739 codec.preference = preference;
2740 AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2741 codec);
2742}
2743
2744bool ParseRtpmapAttribute(const std::string& line,
2745 const MediaType media_type,
2746 const std::vector<int>& codec_preference,
2747 MediaContentDescription* media_desc,
2748 SdpParseError* error) {
2749 std::vector<std::string> fields;
2750 talk_base::split(line.substr(kLinePrefixLength),
2751 kSdpDelimiterSpace, &fields);
2752 // RFC 4566
2753 // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
2754 const size_t expected_min_fields = 2;
2755 if (fields.size() < expected_min_fields) {
2756 return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2757 }
2758 std::string payload_type_value;
2759 if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
2760 return false;
2761 }
2762 const int payload_type = talk_base::FromString<int>(payload_type_value);
2763
2764 // Set the preference order depending on the order of the pl type in the
2765 // <fmt> of the m-line.
2766 const int preference = codec_preference.end() -
2767 std::find(codec_preference.begin(), codec_preference.end(),
2768 payload_type);
2769 if (preference == 0) {
2770 LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
2771 << "<fmt> of the m-line: " << line;
2772 return true;
2773 }
2774 const std::string encoder = fields[1];
2775 std::vector<std::string> codec_params;
2776 talk_base::split(encoder, '/', &codec_params);
2777 // <encoding name>/<clock rate>[/<encodingparameters>]
2778 // 2 mandatory fields
2779 if (codec_params.size() < 2 || codec_params.size() > 3) {
2780 return ParseFailed(line,
2781 "Expected format \"<encoding name>/<clock rate>"
2782 "[/<encodingparameters>]\".",
2783 error);
2784 }
2785 const std::string encoding_name = codec_params[0];
2786 const int clock_rate = talk_base::FromString<int>(codec_params[1]);
2787 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2788 VideoContentDescription* video_desc =
2789 static_cast<VideoContentDescription*>(media_desc);
2790 // TODO: We will send resolution in SDP. For now use
2791 // JsepSessionDescription::kMaxVideoCodecWidth and kMaxVideoCodecHeight.
2792 UpdateCodec(payload_type, encoding_name,
2793 JsepSessionDescription::kMaxVideoCodecWidth,
2794 JsepSessionDescription::kMaxVideoCodecHeight,
2795 JsepSessionDescription::kDefaultVideoCodecFramerate,
2796 preference, video_desc);
2797 } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2798 // RFC 4566
2799 // For audio streams, <encoding parameters> indicates the number
2800 // of audio channels. This parameter is OPTIONAL and may be
2801 // omitted if the number of channels is one, provided that no
2802 // additional parameters are needed.
2803 int channels = 1;
2804 if (codec_params.size() == 3) {
2805 channels = talk_base::FromString<int>(codec_params[2]);
2806 }
2807 int bitrate = 0;
2808 // The default behavior for ISAC (bitrate == 0) in webrtcvoiceengine.cc
2809 // (specifically FindWebRtcCodec) is bandwidth-adaptive variable bitrate.
2810 // The bandwidth adaptation doesn't always work well, so this code
2811 // sets a fixed target bitrate instead.
2812 if (_stricmp(encoding_name.c_str(), kIsacCodecName) == 0) {
2813 if (clock_rate <= 16000) {
2814 bitrate = kIsacWbDefaultRate;
2815 } else {
2816 bitrate = kIsacSwbDefaultRate;
2817 }
2818 }
2819 AudioContentDescription* audio_desc =
2820 static_cast<AudioContentDescription*>(media_desc);
2821 UpdateCodec(payload_type, encoding_name, clock_rate, bitrate, channels,
2822 preference, audio_desc);
2823 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2824 DataContentDescription* data_desc =
2825 static_cast<DataContentDescription*>(media_desc);
2826 data_desc->AddCodec(cricket::DataCodec(payload_type, encoding_name,
2827 preference));
2828 }
2829 return true;
2830}
2831
2832void PruneRight(const char delimiter, std::string* message) {
2833 size_t trailing = message->find(delimiter);
2834 if (trailing != std::string::npos) {
2835 *message = message->substr(0, trailing);
2836 }
2837}
2838
2839bool ParseFmtpParam(const std::string& line, std::string* parameter,
2840 std::string* value, SdpParseError* error) {
2841 if (!SplitByDelimiter(line, kSdpDelimiterEqual, parameter, value)) {
2842 ParseFailed(line, "Unable to parse fmtp parameter. \'=\' missing.", error);
2843 return false;
2844 }
2845 // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
2846 // When parsing the values the trailing ";" gets picked up. Remove them.
2847 PruneRight(kSdpDelimiterSemicolon, value);
2848 return true;
2849}
2850
2851bool ParseFmtpAttributes(const std::string& line, const MediaType media_type,
2852 MediaContentDescription* media_desc,
2853 SdpParseError* error) {
2854 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2855 media_type != cricket::MEDIA_TYPE_VIDEO) {
2856 return true;
2857 }
2858 std::vector<std::string> fields;
2859 talk_base::split(line.substr(kLinePrefixLength),
2860 kSdpDelimiterSpace, &fields);
2861
2862 // RFC 5576
2863 // a=fmtp:<format> <format specific parameters>
2864 // At least two fields, whereas the second one is any of the optional
2865 // parameters.
2866 if (fields.size() < 2) {
2867 ParseFailedExpectMinFieldNum(line, 2, error);
2868 return false;
2869 }
2870
2871 std::string payload_type;
2872 if (!GetValue(fields[0], kAttributeFmtp, &payload_type, error)) {
2873 return false;
2874 }
2875
2876 cricket::CodecParameterMap codec_params;
2877 for (std::vector<std::string>::const_iterator iter = fields.begin() + 1;
2878 iter != fields.end(); ++iter) {
2879 std::string name;
2880 std::string value;
2881 if (iter->find(kSdpDelimiterEqual) == std::string::npos) {
2882 // Only fmtps with equals are currently supported. Other fmtp types
2883 // should be ignored. Unknown fmtps do not constitute an error.
2884 continue;
2885 }
2886 if (!ParseFmtpParam(*iter, &name, &value, error)) {
2887 return false;
2888 }
2889 codec_params[name] = value;
2890 }
2891
2892 int int_payload_type = talk_base::FromString<int>(payload_type);
2893 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2894 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
2895 media_desc, int_payload_type, codec_params);
2896 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2897 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
2898 media_desc, int_payload_type, codec_params);
2899 }
2900 return true;
2901}
2902
2903bool ParseRtcpFbAttribute(const std::string& line, const MediaType media_type,
2904 MediaContentDescription* media_desc,
2905 SdpParseError* error) {
2906 if (media_type != cricket::MEDIA_TYPE_AUDIO &&
2907 media_type != cricket::MEDIA_TYPE_VIDEO) {
2908 return true;
2909 }
2910 std::vector<std::string> rtcp_fb_fields;
2911 talk_base::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
2912 if (rtcp_fb_fields.size() < 2) {
2913 return ParseFailedGetValue(line, kAttributeRtcpFb, error);
2914 }
2915 std::string payload_type_string;
2916 if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
2917 error)) {
2918 return false;
2919 }
2920 int payload_type = (payload_type_string == "*") ?
2921 kWildcardPayloadType : talk_base::FromString<int>(payload_type_string);
2922 std::string id = rtcp_fb_fields[1];
2923 std::string param = "";
2924 for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
2925 iter != rtcp_fb_fields.end(); ++iter) {
2926 param.append(*iter);
2927 }
2928 const cricket::FeedbackParam feedback_param(id, param);
2929
2930 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2931 UpdateCodec<AudioContentDescription, cricket::AudioCodec>(media_desc,
2932 payload_type,
2933 feedback_param);
2934 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
2935 UpdateCodec<VideoContentDescription, cricket::VideoCodec>(media_desc,
2936 payload_type,
2937 feedback_param);
2938 }
2939 return true;
2940}
2941
2942} // namespace webrtc