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