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