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