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