• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2011 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "pc/webrtc_sdp.h"
12 
13 #include <ctype.h>
14 #include <limits.h>
15 #include <stdio.h>
16 
17 #include <algorithm>
18 #include <map>
19 #include <memory>
20 #include <set>
21 #include <string>
22 #include <unordered_map>
23 #include <utility>
24 #include <vector>
25 
26 #include "absl/algorithm/container.h"
27 #include "absl/strings/match.h"
28 #include "api/candidate.h"
29 #include "api/crypto_params.h"
30 #include "api/jsep_ice_candidate.h"
31 #include "api/jsep_session_description.h"
32 #include "api/media_types.h"
33 // for RtpExtension
34 #include "api/rtp_parameters.h"
35 #include "media/base/codec.h"
36 #include "media/base/media_constants.h"
37 #include "media/base/rtp_utils.h"
38 #include "media/sctp/sctp_transport_internal.h"
39 #include "p2p/base/p2p_constants.h"
40 #include "p2p/base/port.h"
41 #include "pc/media_session.h"
42 #include "pc/sdp_serializer.h"
43 #include "rtc_base/arraysize.h"
44 #include "rtc_base/checks.h"
45 #include "rtc_base/logging.h"
46 #include "rtc_base/message_digest.h"
47 #include "rtc_base/string_utils.h"
48 #include "rtc_base/strings/string_builder.h"
49 #include "rtc_base/third_party/base64/base64.h"
50 
51 using cricket::AudioContentDescription;
52 using cricket::Candidate;
53 using cricket::Candidates;
54 using cricket::ContentInfo;
55 using cricket::CryptoParams;
56 using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
57 using cricket::ICE_CANDIDATE_COMPONENT_RTP;
58 using cricket::kCodecParamMaxPTime;
59 using cricket::kCodecParamMinPTime;
60 using cricket::kCodecParamPTime;
61 using cricket::MediaContentDescription;
62 using cricket::MediaProtocolType;
63 using cricket::MediaType;
64 using cricket::RidDescription;
65 using cricket::RtpDataContentDescription;
66 using cricket::RtpHeaderExtensions;
67 using cricket::SctpDataContentDescription;
68 using cricket::SimulcastDescription;
69 using cricket::SimulcastLayer;
70 using cricket::SimulcastLayerList;
71 using cricket::SsrcGroup;
72 using cricket::StreamParams;
73 using cricket::StreamParamsVec;
74 using cricket::TransportDescription;
75 using cricket::TransportInfo;
76 using cricket::VideoContentDescription;
77 using rtc::SocketAddress;
78 
79 namespace cricket {
80 class SessionDescription;
81 }
82 
83 // TODO(deadbeef): Switch to using anonymous namespace rather than declaring
84 // everything "static".
85 namespace webrtc {
86 
87 // Line type
88 // RFC 4566
89 // An SDP session description consists of a number of lines of text of
90 // the form:
91 // <type>=<value>
92 // where <type> MUST be exactly one case-significant character.
93 static const int kLinePrefixLength = 2;  // Length of <type>=
94 static const char kLineTypeVersion = 'v';
95 static const char kLineTypeOrigin = 'o';
96 static const char kLineTypeSessionName = 's';
97 static const char kLineTypeSessionInfo = 'i';
98 static const char kLineTypeSessionUri = 'u';
99 static const char kLineTypeSessionEmail = 'e';
100 static const char kLineTypeSessionPhone = 'p';
101 static const char kLineTypeSessionBandwidth = 'b';
102 static const char kLineTypeTiming = 't';
103 static const char kLineTypeRepeatTimes = 'r';
104 static const char kLineTypeTimeZone = 'z';
105 static const char kLineTypeEncryptionKey = 'k';
106 static const char kLineTypeMedia = 'm';
107 static const char kLineTypeConnection = 'c';
108 static const char kLineTypeAttributes = 'a';
109 
110 // Attributes
111 static const char kAttributeGroup[] = "group";
112 static const char kAttributeMid[] = "mid";
113 static const char kAttributeMsid[] = "msid";
114 static const char kAttributeBundleOnly[] = "bundle-only";
115 static const char kAttributeRtcpMux[] = "rtcp-mux";
116 static const char kAttributeRtcpReducedSize[] = "rtcp-rsize";
117 static const char kAttributeSsrc[] = "ssrc";
118 static const char kSsrcAttributeCname[] = "cname";
119 static const char kAttributeExtmapAllowMixed[] = "extmap-allow-mixed";
120 static const char kAttributeExtmap[] = "extmap";
121 // draft-alvestrand-mmusic-msid-01
122 // a=msid-semantic: WMS
123 // This is a legacy field supported only for Plan B semantics.
124 static const char kAttributeMsidSemantics[] = "msid-semantic";
125 static const char kMediaStreamSemantic[] = "WMS";
126 static const char kSsrcAttributeMsid[] = "msid";
127 static const char kDefaultMsid[] = "default";
128 static const char kNoStreamMsid[] = "-";
129 static const char kSsrcAttributeMslabel[] = "mslabel";
130 static const char kSSrcAttributeLabel[] = "label";
131 static const char kAttributeSsrcGroup[] = "ssrc-group";
132 static const char kAttributeCrypto[] = "crypto";
133 static const char kAttributeCandidate[] = "candidate";
134 static const char kAttributeCandidateTyp[] = "typ";
135 static const char kAttributeCandidateRaddr[] = "raddr";
136 static const char kAttributeCandidateRport[] = "rport";
137 static const char kAttributeCandidateUfrag[] = "ufrag";
138 static const char kAttributeCandidatePwd[] = "pwd";
139 static const char kAttributeCandidateGeneration[] = "generation";
140 static const char kAttributeCandidateNetworkId[] = "network-id";
141 static const char kAttributeCandidateNetworkCost[] = "network-cost";
142 static const char kAttributeFingerprint[] = "fingerprint";
143 static const char kAttributeSetup[] = "setup";
144 static const char kAttributeFmtp[] = "fmtp";
145 static const char kAttributeRtpmap[] = "rtpmap";
146 static const char kAttributeSctpmap[] = "sctpmap";
147 static const char kAttributeRtcp[] = "rtcp";
148 static const char kAttributeIceUfrag[] = "ice-ufrag";
149 static const char kAttributeIcePwd[] = "ice-pwd";
150 static const char kAttributeIceLite[] = "ice-lite";
151 static const char kAttributeIceOption[] = "ice-options";
152 static const char kAttributeSendOnly[] = "sendonly";
153 static const char kAttributeRecvOnly[] = "recvonly";
154 static const char kAttributeRtcpFb[] = "rtcp-fb";
155 static const char kAttributeSendRecv[] = "sendrecv";
156 static const char kAttributeInactive[] = "inactive";
157 // draft-ietf-mmusic-sctp-sdp-26
158 // a=sctp-port, a=max-message-size
159 static const char kAttributeSctpPort[] = "sctp-port";
160 static const char kAttributeMaxMessageSize[] = "max-message-size";
161 static const int kDefaultSctpMaxMessageSize = 65536;
162 // draft-ietf-mmusic-sdp-simulcast-13
163 // a=simulcast
164 static const char kAttributeSimulcast[] = "simulcast";
165 // draft-ietf-mmusic-rid-15
166 // a=rid
167 static const char kAttributeRid[] = "rid";
168 static const char kAttributePacketization[] = "packetization";
169 
170 // Experimental flags
171 static const char kAttributeXGoogleFlag[] = "x-google-flag";
172 static const char kValueConference[] = "conference";
173 
174 static const char kAttributeRtcpRemoteEstimate[] = "remote-net-estimate";
175 
176 // Candidate
177 static const char kCandidateHost[] = "host";
178 static const char kCandidateSrflx[] = "srflx";
179 static const char kCandidatePrflx[] = "prflx";
180 static const char kCandidateRelay[] = "relay";
181 static const char kTcpCandidateType[] = "tcptype";
182 
183 // rtc::StringBuilder doesn't have a << overload for chars, while rtc::split and
184 // rtc::tokenize_first both take a char delimiter. To handle both cases these
185 // constants come in pairs of a chars and length-one strings.
186 static const char kSdpDelimiterEqual[] = "=";
187 static const char kSdpDelimiterEqualChar = '=';
188 static const char kSdpDelimiterSpace[] = " ";
189 static const char kSdpDelimiterSpaceChar = ' ';
190 static const char kSdpDelimiterColon[] = ":";
191 static const char kSdpDelimiterColonChar = ':';
192 static const char kSdpDelimiterSemicolon[] = ";";
193 static const char kSdpDelimiterSemicolonChar = ';';
194 static const char kSdpDelimiterSlashChar = '/';
195 static const char kNewLine[] = "\n";
196 static const char kNewLineChar = '\n';
197 static const char kReturnChar = '\r';
198 static const char kLineBreak[] = "\r\n";
199 
200 // TODO(deadbeef): Generate the Session and Time description
201 // instead of hardcoding.
202 static const char kSessionVersion[] = "v=0";
203 // RFC 4566
204 static const char kSessionOriginUsername[] = "-";
205 static const char kSessionOriginSessionId[] = "0";
206 static const char kSessionOriginSessionVersion[] = "0";
207 static const char kSessionOriginNettype[] = "IN";
208 static const char kSessionOriginAddrtype[] = "IP4";
209 static const char kSessionOriginAddress[] = "127.0.0.1";
210 static const char kSessionName[] = "s=-";
211 static const char kTimeDescription[] = "t=0 0";
212 static const char kAttrGroup[] = "a=group:BUNDLE";
213 static const char kConnectionNettype[] = "IN";
214 static const char kConnectionIpv4Addrtype[] = "IP4";
215 static const char kConnectionIpv6Addrtype[] = "IP6";
216 static const char kMediaTypeVideo[] = "video";
217 static const char kMediaTypeAudio[] = "audio";
218 static const char kMediaTypeData[] = "application";
219 static const char kMediaPortRejected[] = "0";
220 // draft-ietf-mmusic-trickle-ice-01
221 // When no candidates have been gathered, set the connection
222 // address to IP6 ::.
223 // TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
224 // Use IPV4 per default.
225 static const char kDummyAddress[] = "0.0.0.0";
226 static const char kDummyPort[] = "9";
227 // RFC 3556
228 static const char kApplicationSpecificMaximum[] = "AS";
229 
230 static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
231 
232 // RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
233 // types.
234 const int kWildcardPayloadType = -1;
235 
236 struct SsrcInfo {
237   uint32_t ssrc_id;
238   std::string cname;
239   std::string stream_id;
240   std::string track_id;
241 
242   // For backward compatibility.
243   // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
244   std::string label;
245   std::string mslabel;
246 };
247 typedef std::vector<SsrcInfo> SsrcInfoVec;
248 typedef std::vector<SsrcGroup> SsrcGroupVec;
249 
250 template <class T>
251 static void AddFmtpLine(const T& codec, std::string* message);
252 static void BuildMediaDescription(const ContentInfo* content_info,
253                                   const TransportInfo* transport_info,
254                                   const cricket::MediaType media_type,
255                                   const std::vector<Candidate>& candidates,
256                                   int msid_signaling,
257                                   std::string* message);
258 static void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
259                                       const cricket::MediaType media_type,
260                                       int msid_signaling,
261                                       std::string* message);
262 static void BuildRtpMap(const MediaContentDescription* media_desc,
263                         const cricket::MediaType media_type,
264                         std::string* message);
265 static void BuildCandidate(const std::vector<Candidate>& candidates,
266                            bool include_ufrag,
267                            std::string* message);
268 static void BuildIceOptions(const std::vector<std::string>& transport_options,
269                             std::string* message);
270 static bool ParseSessionDescription(const std::string& message,
271                                     size_t* pos,
272                                     std::string* session_id,
273                                     std::string* session_version,
274                                     TransportDescription* session_td,
275                                     RtpHeaderExtensions* session_extmaps,
276                                     rtc::SocketAddress* connection_addr,
277                                     cricket::SessionDescription* desc,
278                                     SdpParseError* error);
279 static bool ParseGroupAttribute(const std::string& line,
280                                 cricket::SessionDescription* desc,
281                                 SdpParseError* error);
282 static bool ParseMediaDescription(
283     const std::string& message,
284     const TransportDescription& session_td,
285     const RtpHeaderExtensions& session_extmaps,
286     size_t* pos,
287     const rtc::SocketAddress& session_connection_addr,
288     cricket::SessionDescription* desc,
289     std::vector<std::unique_ptr<JsepIceCandidate>>* candidates,
290     SdpParseError* error);
291 static bool ParseContent(
292     const std::string& message,
293     const cricket::MediaType media_type,
294     int mline_index,
295     const std::string& protocol,
296     const std::vector<int>& payload_types,
297     size_t* pos,
298     std::string* content_name,
299     bool* bundle_only,
300     int* msid_signaling,
301     MediaContentDescription* media_desc,
302     TransportDescription* transport,
303     std::vector<std::unique_ptr<JsepIceCandidate>>* candidates,
304     SdpParseError* error);
305 static bool ParseSsrcAttribute(const std::string& line,
306                                SsrcInfoVec* ssrc_infos,
307                                int* msid_signaling,
308                                SdpParseError* error);
309 static bool ParseSsrcGroupAttribute(const std::string& line,
310                                     SsrcGroupVec* ssrc_groups,
311                                     SdpParseError* error);
312 static bool ParseCryptoAttribute(const std::string& line,
313                                  MediaContentDescription* media_desc,
314                                  SdpParseError* error);
315 static bool ParseRtpmapAttribute(const std::string& line,
316                                  const cricket::MediaType media_type,
317                                  const std::vector<int>& payload_types,
318                                  MediaContentDescription* media_desc,
319                                  SdpParseError* error);
320 static bool ParseFmtpAttributes(const std::string& line,
321                                 const cricket::MediaType media_type,
322                                 MediaContentDescription* media_desc,
323                                 SdpParseError* error);
324 static bool ParseFmtpParam(const std::string& line,
325                            std::string* parameter,
326                            std::string* value,
327                            SdpParseError* error);
328 static bool ParsePacketizationAttribute(const std::string& line,
329                                         const cricket::MediaType media_type,
330                                         MediaContentDescription* media_desc,
331                                         SdpParseError* error);
332 static bool ParseRtcpFbAttribute(const std::string& line,
333                                  const cricket::MediaType media_type,
334                                  MediaContentDescription* media_desc,
335                                  SdpParseError* error);
336 static bool ParseIceOptions(const std::string& line,
337                             std::vector<std::string>* transport_options,
338                             SdpParseError* error);
339 static bool ParseExtmap(const std::string& line,
340                         RtpExtension* extmap,
341                         SdpParseError* error);
342 static bool ParseFingerprintAttribute(
343     const std::string& line,
344     std::unique_ptr<rtc::SSLFingerprint>* fingerprint,
345     SdpParseError* error);
346 static bool ParseDtlsSetup(const std::string& line,
347                            cricket::ConnectionRole* role,
348                            SdpParseError* error);
349 static bool ParseMsidAttribute(const std::string& line,
350                                std::vector<std::string>* stream_ids,
351                                std::string* track_id,
352                                SdpParseError* error);
353 
354 static void RemoveInvalidRidDescriptions(const std::vector<int>& payload_types,
355                                          std::vector<RidDescription>* rids);
356 
357 static SimulcastLayerList RemoveRidsFromSimulcastLayerList(
358     const std::set<std::string>& to_remove,
359     const SimulcastLayerList& layers);
360 
361 static void RemoveInvalidRidsFromSimulcast(
362     const std::vector<RidDescription>& rids,
363     SimulcastDescription* simulcast);
364 
365 // Helper functions
366 
367 // Below ParseFailed*** functions output the line that caused the parsing
368 // failure and the detailed reason (|description|) of the failure to |error|.
369 // The functions always return false so that they can be used directly in the
370 // following way when error happens:
371 // "return ParseFailed***(...);"
372 
373 // The line starting at |line_start| of |message| is the failing line.
374 // The reason for the failure should be provided in the |description|.
375 // An example of a description could be "unknown character".
ParseFailed(const std::string & message,size_t line_start,const std::string & description,SdpParseError * error)376 static bool ParseFailed(const std::string& message,
377                         size_t line_start,
378                         const std::string& description,
379                         SdpParseError* error) {
380   // Get the first line of |message| from |line_start|.
381   std::string first_line;
382   size_t line_end = message.find(kNewLine, line_start);
383   if (line_end != std::string::npos) {
384     if (line_end > 0 && (message.at(line_end - 1) == kReturnChar)) {
385       --line_end;
386     }
387     first_line = message.substr(line_start, (line_end - line_start));
388   } else {
389     first_line = message.substr(line_start);
390   }
391 
392   if (error) {
393     error->line = first_line;
394     error->description = description;
395   }
396   RTC_LOG(LS_ERROR) << "Failed to parse: \"" << first_line
397                     << "\". Reason: " << description;
398   return false;
399 }
400 
401 // |line| is the failing line. The reason for the failure should be
402 // provided in the |description|.
ParseFailed(const std::string & line,const std::string & description,SdpParseError * error)403 static bool ParseFailed(const std::string& line,
404                         const std::string& description,
405                         SdpParseError* error) {
406   return ParseFailed(line, 0, description, error);
407 }
408 
409 // Parses failure where the failing SDP line isn't know or there are multiple
410 // failing lines.
ParseFailed(const std::string & description,SdpParseError * error)411 static bool ParseFailed(const std::string& description, SdpParseError* error) {
412   return ParseFailed("", description, error);
413 }
414 
415 // |line| is the failing line. The failure is due to the fact that |line|
416 // doesn't have |expected_fields| fields.
ParseFailedExpectFieldNum(const std::string & line,int expected_fields,SdpParseError * error)417 static bool ParseFailedExpectFieldNum(const std::string& line,
418                                       int expected_fields,
419                                       SdpParseError* error) {
420   rtc::StringBuilder description;
421   description << "Expects " << expected_fields << " fields.";
422   return ParseFailed(line, description.str(), error);
423 }
424 
425 // |line| is the failing line. The failure is due to the fact that |line| has
426 // less than |expected_min_fields| fields.
ParseFailedExpectMinFieldNum(const std::string & line,int expected_min_fields,SdpParseError * error)427 static bool ParseFailedExpectMinFieldNum(const std::string& line,
428                                          int expected_min_fields,
429                                          SdpParseError* error) {
430   rtc::StringBuilder description;
431   description << "Expects at least " << expected_min_fields << " fields.";
432   return ParseFailed(line, description.str(), error);
433 }
434 
435 // |line| is the failing line. The failure is due to the fact that it failed to
436 // get the value of |attribute|.
ParseFailedGetValue(const std::string & line,const std::string & attribute,SdpParseError * error)437 static bool ParseFailedGetValue(const std::string& line,
438                                 const std::string& attribute,
439                                 SdpParseError* error) {
440   rtc::StringBuilder description;
441   description << "Failed to get the value of attribute: " << attribute;
442   return ParseFailed(line, description.str(), error);
443 }
444 
445 // The line starting at |line_start| of |message| is the failing line. The
446 // failure is due to the line type (e.g. the "m" part of the "m-line")
447 // not matching what is expected. The expected line type should be
448 // provided as |line_type|.
ParseFailedExpectLine(const std::string & message,size_t line_start,const char line_type,const std::string & line_value,SdpParseError * error)449 static bool ParseFailedExpectLine(const std::string& message,
450                                   size_t line_start,
451                                   const char line_type,
452                                   const std::string& line_value,
453                                   SdpParseError* error) {
454   rtc::StringBuilder description;
455   description << "Expect line: " << std::string(1, line_type) << "="
456               << line_value;
457   return ParseFailed(message, line_start, description.str(), error);
458 }
459 
AddLine(const std::string & line,std::string * message)460 static bool AddLine(const std::string& line, std::string* message) {
461   if (!message)
462     return false;
463 
464   message->append(line);
465   message->append(kLineBreak);
466   return true;
467 }
468 
GetLine(const std::string & message,size_t * pos,std::string * line)469 static bool GetLine(const std::string& message,
470                     size_t* pos,
471                     std::string* line) {
472   size_t line_begin = *pos;
473   size_t line_end = message.find(kNewLine, line_begin);
474   if (line_end == std::string::npos) {
475     return false;
476   }
477   // Update the new start position
478   *pos = line_end + 1;
479   if (line_end > 0 && (message.at(line_end - 1) == kReturnChar)) {
480     --line_end;
481   }
482   *line = message.substr(line_begin, (line_end - line_begin));
483   const char* cline = line->c_str();
484   // RFC 4566
485   // An SDP session description consists of a number of lines of text of
486   // the form:
487   // <type>=<value>
488   // where <type> MUST be exactly one case-significant character and
489   // <value> is structured text whose format depends on <type>.
490   // Whitespace MUST NOT be used on either side of the "=" sign.
491   //
492   // However, an exception to the whitespace rule is made for "s=", since
493   // RFC4566 also says:
494   //
495   //   If a session has no meaningful name, the value "s= " SHOULD be used
496   //   (i.e., a single space as the session name).
497   if (line->length() < 3 || !islower(cline[0]) ||
498       cline[1] != kSdpDelimiterEqualChar ||
499       (cline[0] != kLineTypeSessionName &&
500        cline[2] == kSdpDelimiterSpaceChar)) {
501     *pos = line_begin;
502     return false;
503   }
504   return true;
505 }
506 
507 // Init |os| to "|type|=|value|".
InitLine(const char type,const std::string & value,rtc::StringBuilder * os)508 static void InitLine(const char type,
509                      const std::string& value,
510                      rtc::StringBuilder* os) {
511   os->Clear();
512   *os << std::string(1, type) << kSdpDelimiterEqual << value;
513 }
514 
515 // Init |os| to "a=|attribute|".
InitAttrLine(const std::string & attribute,rtc::StringBuilder * os)516 static void InitAttrLine(const std::string& attribute, rtc::StringBuilder* os) {
517   InitLine(kLineTypeAttributes, attribute, os);
518 }
519 
520 // Writes a SDP attribute line based on |attribute| and |value| to |message|.
AddAttributeLine(const std::string & attribute,int value,std::string * message)521 static void AddAttributeLine(const std::string& attribute,
522                              int value,
523                              std::string* message) {
524   rtc::StringBuilder os;
525   InitAttrLine(attribute, &os);
526   os << kSdpDelimiterColon << value;
527   AddLine(os.str(), message);
528 }
529 
IsLineType(const std::string & message,const char type,size_t line_start)530 static bool IsLineType(const std::string& message,
531                        const char type,
532                        size_t line_start) {
533   if (message.size() < line_start + kLinePrefixLength) {
534     return false;
535   }
536   const char* cmessage = message.c_str();
537   return (cmessage[line_start] == type &&
538           cmessage[line_start + 1] == kSdpDelimiterEqualChar);
539 }
540 
IsLineType(const std::string & line,const char type)541 static bool IsLineType(const std::string& line, const char type) {
542   return IsLineType(line, type, 0);
543 }
544 
GetLineWithType(const std::string & message,size_t * pos,std::string * line,const char type)545 static bool GetLineWithType(const std::string& message,
546                             size_t* pos,
547                             std::string* line,
548                             const char type) {
549   if (!IsLineType(message, type, *pos)) {
550     return false;
551   }
552 
553   if (!GetLine(message, pos, line))
554     return false;
555 
556   return true;
557 }
558 
HasAttribute(const std::string & line,const std::string & attribute)559 static bool HasAttribute(const std::string& line,
560                          const std::string& attribute) {
561   if (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0) {
562     // Make sure that the match is not only a partial match. If length of
563     // strings doesn't match, the next character of the line must be ':' or ' '.
564     // This function is also used for media descriptions (e.g., "m=audio 9..."),
565     // hence the need to also allow space in the end.
566     RTC_CHECK_LE(kLinePrefixLength + attribute.size(), line.size());
567     if ((kLinePrefixLength + attribute.size()) == line.size() ||
568         line[kLinePrefixLength + attribute.size()] == kSdpDelimiterColonChar ||
569         line[kLinePrefixLength + attribute.size()] == kSdpDelimiterSpaceChar) {
570       return true;
571     }
572   }
573   return false;
574 }
575 
AddSsrcLine(uint32_t ssrc_id,const std::string & attribute,const std::string & value,std::string * message)576 static bool AddSsrcLine(uint32_t ssrc_id,
577                         const std::string& attribute,
578                         const std::string& value,
579                         std::string* message) {
580   // RFC 5576
581   // a=ssrc:<ssrc-id> <attribute>:<value>
582   rtc::StringBuilder os;
583   InitAttrLine(kAttributeSsrc, &os);
584   os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace << attribute
585      << kSdpDelimiterColon << value;
586   return AddLine(os.str(), message);
587 }
588 
589 // Get value only from <attribute>:<value>.
GetValue(const std::string & message,const std::string & attribute,std::string * value,SdpParseError * error)590 static bool GetValue(const std::string& message,
591                      const std::string& attribute,
592                      std::string* value,
593                      SdpParseError* error) {
594   std::string leftpart;
595   if (!rtc::tokenize_first(message, kSdpDelimiterColonChar, &leftpart, value)) {
596     return ParseFailedGetValue(message, attribute, error);
597   }
598   // The left part should end with the expected attribute.
599   if (leftpart.length() < attribute.length() ||
600       leftpart.compare(leftpart.length() - attribute.length(),
601                        attribute.length(), attribute) != 0) {
602     return ParseFailedGetValue(message, attribute, error);
603   }
604   return true;
605 }
606 
CaseInsensitiveFind(std::string str1,std::string str2)607 static bool CaseInsensitiveFind(std::string str1, std::string str2) {
608   absl::c_transform(str1, str1.begin(), ::tolower);
609   absl::c_transform(str2, str2.begin(), ::tolower);
610   return str1.find(str2) != std::string::npos;
611 }
612 
613 template <class T>
GetValueFromString(const std::string & line,const std::string & s,T * t,SdpParseError * error)614 static bool GetValueFromString(const std::string& line,
615                                const std::string& s,
616                                T* t,
617                                SdpParseError* error) {
618   if (!rtc::FromString(s, t)) {
619     rtc::StringBuilder description;
620     description << "Invalid value: " << s << ".";
621     return ParseFailed(line, description.str(), error);
622   }
623   return true;
624 }
625 
GetPayloadTypeFromString(const std::string & line,const std::string & s,int * payload_type,SdpParseError * error)626 static bool GetPayloadTypeFromString(const std::string& line,
627                                      const std::string& s,
628                                      int* payload_type,
629                                      SdpParseError* error) {
630   return GetValueFromString(line, s, payload_type, error) &&
631          cricket::IsValidRtpPayloadType(*payload_type);
632 }
633 
634 // Creates a StreamParams track in the case when no SSRC lines are signaled.
635 // This is a track that does not contain SSRCs and only contains
636 // stream_ids/track_id if it's signaled with a=msid lines.
CreateTrackWithNoSsrcs(const std::vector<std::string> & msid_stream_ids,const std::string & msid_track_id,const std::vector<RidDescription> & rids,StreamParamsVec * tracks)637 void CreateTrackWithNoSsrcs(const std::vector<std::string>& msid_stream_ids,
638                             const std::string& msid_track_id,
639                             const std::vector<RidDescription>& rids,
640                             StreamParamsVec* tracks) {
641   StreamParams track;
642   if (msid_track_id.empty() && rids.empty()) {
643     // We only create an unsignaled track if a=msid lines were signaled.
644     RTC_LOG(LS_INFO) << "MSID not signaled, skipping creation of StreamParams";
645     return;
646   }
647   track.set_stream_ids(msid_stream_ids);
648   track.id = msid_track_id;
649   track.set_rids(rids);
650   tracks->push_back(track);
651 }
652 
653 // Creates the StreamParams tracks, for the case when SSRC lines are signaled.
654 // |msid_stream_ids| and |msid_track_id| represent the stream/track ID from the
655 // "a=msid" attribute, if it exists. They are empty if the attribute does not
656 // exist. We prioritize getting stream_ids/track_ids signaled in a=msid lines.
CreateTracksFromSsrcInfos(const SsrcInfoVec & ssrc_infos,const std::vector<std::string> & msid_stream_ids,const std::string & msid_track_id,StreamParamsVec * tracks,int msid_signaling)657 void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
658                                const std::vector<std::string>& msid_stream_ids,
659                                const std::string& msid_track_id,
660                                StreamParamsVec* tracks,
661                                int msid_signaling) {
662   RTC_DCHECK(tracks != NULL);
663   for (const SsrcInfo& ssrc_info : ssrc_infos) {
664     // According to https://tools.ietf.org/html/rfc5576#section-6.1, the CNAME
665     // attribute is mandatory, but we relax that restriction.
666     if (ssrc_info.cname.empty()) {
667       RTC_LOG(LS_WARNING) << "CNAME attribute missing for SSRC "
668                           << ssrc_info.ssrc_id;
669     }
670     std::vector<std::string> stream_ids;
671     std::string track_id;
672     if (msid_signaling & cricket::kMsidSignalingMediaSection) {
673       // This is the case with Unified Plan SDP msid signaling.
674       stream_ids = msid_stream_ids;
675       track_id = msid_track_id;
676     } else if (msid_signaling & cricket::kMsidSignalingSsrcAttribute) {
677       // This is the case with Plan B SDP msid signaling.
678       stream_ids.push_back(ssrc_info.stream_id);
679       track_id = ssrc_info.track_id;
680     } else if (!ssrc_info.mslabel.empty()) {
681       // Since there's no a=msid or a=ssrc msid signaling, this is a sdp from
682       // an older version of client that doesn't support msid.
683       // In that case, we use the mslabel and label to construct the track.
684       stream_ids.push_back(ssrc_info.mslabel);
685       track_id = ssrc_info.label;
686     } else {
687       // Since no media streams isn't supported with older SDP signaling, we
688       // use a default a stream id.
689       stream_ids.push_back(kDefaultMsid);
690     }
691     // If a track ID wasn't populated from the SSRC attributes OR the
692     // msid attribute, use default/random values.
693     if (track_id.empty()) {
694       // TODO(ronghuawu): What should we do if the track id doesn't appear?
695       // Create random string (which will be used as track label later)?
696       track_id = rtc::CreateRandomString(8);
697     }
698 
699     auto track_it = absl::c_find_if(
700         *tracks,
701         [track_id](const StreamParams& track) { return track.id == track_id; });
702     if (track_it == tracks->end()) {
703       // If we don't find an existing track, create a new one.
704       tracks->push_back(StreamParams());
705       track_it = tracks->end() - 1;
706     }
707     StreamParams& track = *track_it;
708     track.add_ssrc(ssrc_info.ssrc_id);
709     track.cname = ssrc_info.cname;
710     track.set_stream_ids(stream_ids);
711     track.id = track_id;
712   }
713 }
714 
GetMediaStreamIds(const ContentInfo * content,std::set<std::string> * labels)715 void GetMediaStreamIds(const ContentInfo* content,
716                        std::set<std::string>* labels) {
717   for (const StreamParams& stream_params :
718        content->media_description()->streams()) {
719     for (const std::string& stream_id : stream_params.stream_ids()) {
720       labels->insert(stream_id);
721     }
722   }
723 }
724 
725 // RFC 5245
726 // It is RECOMMENDED that default candidates be chosen based on the
727 // likelihood of those candidates to work with the peer that is being
728 // contacted.  It is RECOMMENDED that relayed > reflexive > host.
729 static const int kPreferenceUnknown = 0;
730 static const int kPreferenceHost = 1;
731 static const int kPreferenceReflexive = 2;
732 static const int kPreferenceRelayed = 3;
733 
GetCandidatePreferenceFromType(const std::string & type)734 static int GetCandidatePreferenceFromType(const std::string& type) {
735   int preference = kPreferenceUnknown;
736   if (type == cricket::LOCAL_PORT_TYPE) {
737     preference = kPreferenceHost;
738   } else if (type == cricket::STUN_PORT_TYPE) {
739     preference = kPreferenceReflexive;
740   } else if (type == cricket::RELAY_PORT_TYPE) {
741     preference = kPreferenceRelayed;
742   } else {
743     RTC_NOTREACHED();
744   }
745   return preference;
746 }
747 
748 // Get ip and port of the default destination from the |candidates| with the
749 // given value of |component_id|. The default candidate should be the one most
750 // likely to work, typically IPv4 relay.
751 // RFC 5245
752 // The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
753 // TODO(deadbeef): Decide the default destination in webrtcsession and
754 // pass it down via SessionDescription.
GetDefaultDestination(const std::vector<Candidate> & candidates,int component_id,std::string * port,std::string * ip,std::string * addr_type)755 static void GetDefaultDestination(const std::vector<Candidate>& candidates,
756                                   int component_id,
757                                   std::string* port,
758                                   std::string* ip,
759                                   std::string* addr_type) {
760   *addr_type = kConnectionIpv4Addrtype;
761   *port = kDummyPort;
762   *ip = kDummyAddress;
763   int current_preference = kPreferenceUnknown;
764   int current_family = AF_UNSPEC;
765   for (const Candidate& candidate : candidates) {
766     if (candidate.component() != component_id) {
767       continue;
768     }
769     // Default destination should be UDP only.
770     if (candidate.protocol() != cricket::UDP_PROTOCOL_NAME) {
771       continue;
772     }
773     const int preference = GetCandidatePreferenceFromType(candidate.type());
774     const int family = candidate.address().ipaddr().family();
775     // See if this candidate is more preferable then the current one if it's the
776     // same family. Or if the current family is IPv4 already so we could safely
777     // ignore all IPv6 ones. WebRTC bug 4269.
778     // http://code.google.com/p/webrtc/issues/detail?id=4269
779     if ((preference <= current_preference && current_family == family) ||
780         (current_family == AF_INET && family == AF_INET6)) {
781       continue;
782     }
783     if (family == AF_INET) {
784       addr_type->assign(kConnectionIpv4Addrtype);
785     } else if (family == AF_INET6) {
786       addr_type->assign(kConnectionIpv6Addrtype);
787     }
788     current_preference = preference;
789     current_family = family;
790     *port = candidate.address().PortAsString();
791     *ip = candidate.address().ipaddr().ToString();
792   }
793 }
794 
795 // Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
GetRtcpLine(const std::vector<Candidate> & candidates)796 static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
797   std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
798   GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP, &rtcp_port,
799                         &rtcp_ip, &addr_type);
800   // Found default RTCP candidate.
801   // RFC 5245
802   // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
803   // using the a=rtcp attribute as defined in RFC 3605.
804 
805   // RFC 3605
806   // rtcp-attribute =  "a=rtcp:" port  [nettype space addrtype space
807   // connection-address] CRLF
808   rtc::StringBuilder os;
809   InitAttrLine(kAttributeRtcp, &os);
810   os << kSdpDelimiterColon << rtcp_port << " " << kConnectionNettype << " "
811      << addr_type << " " << rtcp_ip;
812   rtcp_line = os.str();
813   return rtcp_line;
814 }
815 
816 // Get candidates according to the mline index from SessionDescriptionInterface.
GetCandidatesByMindex(const SessionDescriptionInterface & desci,int mline_index,std::vector<Candidate> * candidates)817 static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
818                                   int mline_index,
819                                   std::vector<Candidate>* candidates) {
820   if (!candidates) {
821     return;
822   }
823   const IceCandidateCollection* cc = desci.candidates(mline_index);
824   for (size_t i = 0; i < cc->count(); ++i) {
825     const IceCandidateInterface* candidate = cc->at(i);
826     candidates->push_back(candidate->candidate());
827   }
828 }
829 
IsValidPort(int port)830 static bool IsValidPort(int port) {
831   return port >= 0 && port <= 65535;
832 }
833 
SdpSerialize(const JsepSessionDescription & jdesc)834 std::string SdpSerialize(const JsepSessionDescription& jdesc) {
835   const cricket::SessionDescription* desc = jdesc.description();
836   if (!desc) {
837     return "";
838   }
839 
840   std::string message;
841 
842   // Session Description.
843   AddLine(kSessionVersion, &message);
844   // Session Origin
845   // RFC 4566
846   // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
847   // <unicast-address>
848   rtc::StringBuilder os;
849   InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
850   const std::string& session_id =
851       jdesc.session_id().empty() ? kSessionOriginSessionId : jdesc.session_id();
852   const std::string& session_version = jdesc.session_version().empty()
853                                            ? kSessionOriginSessionVersion
854                                            : jdesc.session_version();
855   os << " " << session_id << " " << session_version << " "
856      << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
857      << kSessionOriginAddress;
858   AddLine(os.str(), &message);
859   AddLine(kSessionName, &message);
860 
861   // Time Description.
862   AddLine(kTimeDescription, &message);
863 
864   // Group
865   if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
866     std::string group_line = kAttrGroup;
867     const cricket::ContentGroup* group =
868         desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
869     RTC_DCHECK(group != NULL);
870     for (const std::string& content_name : group->content_names()) {
871       group_line.append(" ");
872       group_line.append(content_name);
873     }
874     AddLine(group_line, &message);
875   }
876 
877   // Mixed one- and two-byte header extension.
878   if (desc->extmap_allow_mixed()) {
879     InitAttrLine(kAttributeExtmapAllowMixed, &os);
880     AddLine(os.str(), &message);
881   }
882 
883   // MediaStream semantics
884   InitAttrLine(kAttributeMsidSemantics, &os);
885   os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
886 
887   std::set<std::string> media_stream_ids;
888   const ContentInfo* audio_content = GetFirstAudioContent(desc);
889   if (audio_content)
890     GetMediaStreamIds(audio_content, &media_stream_ids);
891 
892   const ContentInfo* video_content = GetFirstVideoContent(desc);
893   if (video_content)
894     GetMediaStreamIds(video_content, &media_stream_ids);
895 
896   for (const std::string& id : media_stream_ids) {
897     os << " " << id;
898   }
899   AddLine(os.str(), &message);
900 
901   // a=ice-lite
902   //
903   // TODO(deadbeef): It's weird that we need to iterate TransportInfos for
904   // this, when it's a session-level attribute. It really should be moved to a
905   // session-level structure like SessionDescription.
906   for (const cricket::TransportInfo& transport : desc->transport_infos()) {
907     if (transport.description.ice_mode == cricket::ICEMODE_LITE) {
908       InitAttrLine(kAttributeIceLite, &os);
909       AddLine(os.str(), &message);
910       break;
911     }
912   }
913 
914   // Preserve the order of the media contents.
915   int mline_index = -1;
916   for (const ContentInfo& content : desc->contents()) {
917     std::vector<Candidate> candidates;
918     GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
919     BuildMediaDescription(&content, desc->GetTransportInfoByName(content.name),
920                           content.media_description()->type(), candidates,
921                           desc->msid_signaling(), &message);
922   }
923   return message;
924 }
925 
926 // Serializes the passed in IceCandidateInterface to a SDP string.
927 // candidate - The candidate to be serialized.
SdpSerializeCandidate(const IceCandidateInterface & candidate)928 std::string SdpSerializeCandidate(const IceCandidateInterface& candidate) {
929   return SdpSerializeCandidate(candidate.candidate());
930 }
931 
932 // Serializes a cricket Candidate.
SdpSerializeCandidate(const cricket::Candidate & candidate)933 std::string SdpSerializeCandidate(const cricket::Candidate& candidate) {
934   std::string message;
935   std::vector<cricket::Candidate> candidates(1, candidate);
936   BuildCandidate(candidates, true, &message);
937   // From WebRTC draft section 4.8.1.1 candidate-attribute will be
938   // just candidate:<candidate> not a=candidate:<blah>CRLF
939   RTC_DCHECK(message.find("a=") == 0);
940   message.erase(0, 2);
941   RTC_DCHECK(message.find(kLineBreak) == message.size() - 2);
942   message.resize(message.size() - 2);
943   return message;
944 }
945 
SdpDeserialize(const std::string & message,JsepSessionDescription * jdesc,SdpParseError * error)946 bool SdpDeserialize(const std::string& message,
947                     JsepSessionDescription* jdesc,
948                     SdpParseError* error) {
949   std::string session_id;
950   std::string session_version;
951   TransportDescription session_td("", "");
952   RtpHeaderExtensions session_extmaps;
953   rtc::SocketAddress session_connection_addr;
954   auto desc = std::make_unique<cricket::SessionDescription>();
955   size_t current_pos = 0;
956 
957   // Session Description
958   if (!ParseSessionDescription(message, &current_pos, &session_id,
959                                &session_version, &session_td, &session_extmaps,
960                                &session_connection_addr, desc.get(), error)) {
961     return false;
962   }
963 
964   // Media Description
965   std::vector<std::unique_ptr<JsepIceCandidate>> candidates;
966   if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
967                              session_connection_addr, desc.get(), &candidates,
968                              error)) {
969     return false;
970   }
971 
972   jdesc->Initialize(std::move(desc), session_id, session_version);
973 
974   for (const auto& candidate : candidates) {
975     jdesc->AddCandidate(candidate.get());
976   }
977   return true;
978 }
979 
SdpDeserializeCandidate(const std::string & message,JsepIceCandidate * jcandidate,SdpParseError * error)980 bool SdpDeserializeCandidate(const std::string& message,
981                              JsepIceCandidate* jcandidate,
982                              SdpParseError* error) {
983   RTC_DCHECK(jcandidate != NULL);
984   Candidate candidate;
985   if (!ParseCandidate(message, &candidate, error, true)) {
986     return false;
987   }
988   jcandidate->SetCandidate(candidate);
989   return true;
990 }
991 
SdpDeserializeCandidate(const std::string & transport_name,const std::string & message,cricket::Candidate * candidate,SdpParseError * error)992 bool SdpDeserializeCandidate(const std::string& transport_name,
993                              const std::string& message,
994                              cricket::Candidate* candidate,
995                              SdpParseError* error) {
996   RTC_DCHECK(candidate != nullptr);
997   if (!ParseCandidate(message, candidate, error, true)) {
998     return false;
999   }
1000   candidate->set_transport_name(transport_name);
1001   return true;
1002 }
1003 
ParseCandidate(const std::string & message,Candidate * candidate,SdpParseError * error,bool is_raw)1004 bool ParseCandidate(const std::string& message,
1005                     Candidate* candidate,
1006                     SdpParseError* error,
1007                     bool is_raw) {
1008   RTC_DCHECK(candidate != NULL);
1009 
1010   // Get the first line from |message|.
1011   std::string first_line = message;
1012   size_t pos = 0;
1013   GetLine(message, &pos, &first_line);
1014 
1015   // Makes sure |message| contains only one line.
1016   if (message.size() > first_line.size()) {
1017     std::string left, right;
1018     if (rtc::tokenize_first(message, kNewLineChar, &left, &right) &&
1019         !right.empty()) {
1020       return ParseFailed(message, 0, "Expect one line only", error);
1021     }
1022   }
1023 
1024   // From WebRTC draft section 4.8.1.1 candidate-attribute should be
1025   // candidate:<candidate> when trickled, but we still support
1026   // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
1027   // from the SDP.
1028   if (IsLineType(first_line, kLineTypeAttributes)) {
1029     first_line = first_line.substr(kLinePrefixLength);
1030   }
1031 
1032   std::string attribute_candidate;
1033   std::string candidate_value;
1034 
1035   // |first_line| must be in the form of "candidate:<value>".
1036   if (!rtc::tokenize_first(first_line, kSdpDelimiterColonChar,
1037                            &attribute_candidate, &candidate_value) ||
1038       attribute_candidate != kAttributeCandidate) {
1039     if (is_raw) {
1040       rtc::StringBuilder description;
1041       description << "Expect line: " << kAttributeCandidate
1042                   << ":"
1043                      "<candidate-str>";
1044       return ParseFailed(first_line, 0, description.str(), error);
1045     } else {
1046       return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
1047                                    kAttributeCandidate, error);
1048     }
1049   }
1050 
1051   std::vector<std::string> fields;
1052   rtc::split(candidate_value, kSdpDelimiterSpaceChar, &fields);
1053 
1054   // RFC 5245
1055   // a=candidate:<foundation> <component-id> <transport> <priority>
1056   // <connection-address> <port> typ <candidate-types>
1057   // [raddr <connection-address>] [rport <port>]
1058   // *(SP extension-att-name SP extension-att-value)
1059   const size_t expected_min_fields = 8;
1060   if (fields.size() < expected_min_fields ||
1061       (fields[6] != kAttributeCandidateTyp)) {
1062     return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
1063   }
1064   const std::string& foundation = fields[0];
1065 
1066   int component_id = 0;
1067   if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1068     return false;
1069   }
1070   const std::string& transport = fields[2];
1071   uint32_t priority = 0;
1072   if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1073     return false;
1074   }
1075   const std::string& connection_address = fields[4];
1076   int port = 0;
1077   if (!GetValueFromString(first_line, fields[5], &port, error)) {
1078     return false;
1079   }
1080   if (!IsValidPort(port)) {
1081     return ParseFailed(first_line, "Invalid port number.", error);
1082   }
1083   SocketAddress address(connection_address, port);
1084 
1085   cricket::ProtocolType protocol;
1086   if (!StringToProto(transport.c_str(), &protocol)) {
1087     return ParseFailed(first_line, "Unsupported transport type.", error);
1088   }
1089   bool tcp_protocol = false;
1090   switch (protocol) {
1091     // Supported protocols.
1092     case cricket::PROTO_UDP:
1093       break;
1094     case cricket::PROTO_TCP:
1095     case cricket::PROTO_SSLTCP:
1096       tcp_protocol = true;
1097       break;
1098     default:
1099       return ParseFailed(first_line, "Unsupported transport type.", error);
1100   }
1101 
1102   std::string candidate_type;
1103   const std::string& type = fields[7];
1104   if (type == kCandidateHost) {
1105     candidate_type = cricket::LOCAL_PORT_TYPE;
1106   } else if (type == kCandidateSrflx) {
1107     candidate_type = cricket::STUN_PORT_TYPE;
1108   } else if (type == kCandidateRelay) {
1109     candidate_type = cricket::RELAY_PORT_TYPE;
1110   } else if (type == kCandidatePrflx) {
1111     candidate_type = cricket::PRFLX_PORT_TYPE;
1112   } else {
1113     return ParseFailed(first_line, "Unsupported candidate type.", error);
1114   }
1115 
1116   size_t current_position = expected_min_fields;
1117   SocketAddress related_address;
1118   // The 2 optional fields for related address
1119   // [raddr <connection-address>] [rport <port>]
1120   if (fields.size() >= (current_position + 2) &&
1121       fields[current_position] == kAttributeCandidateRaddr) {
1122     related_address.SetIP(fields[++current_position]);
1123     ++current_position;
1124   }
1125   if (fields.size() >= (current_position + 2) &&
1126       fields[current_position] == kAttributeCandidateRport) {
1127     int port = 0;
1128     if (!GetValueFromString(first_line, fields[++current_position], &port,
1129                             error)) {
1130       return false;
1131     }
1132     if (!IsValidPort(port)) {
1133       return ParseFailed(first_line, "Invalid port number.", error);
1134     }
1135     related_address.SetPort(port);
1136     ++current_position;
1137   }
1138 
1139   // If this is a TCP candidate, it has additional extension as defined in
1140   // RFC 6544.
1141   std::string tcptype;
1142   if (fields.size() >= (current_position + 2) &&
1143       fields[current_position] == kTcpCandidateType) {
1144     tcptype = fields[++current_position];
1145     ++current_position;
1146 
1147     if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1148         tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1149         tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1150       return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1151     }
1152 
1153     if (!tcp_protocol) {
1154       return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1155     }
1156   } else if (tcp_protocol) {
1157     // We allow the tcptype to be missing, for backwards compatibility,
1158     // treating it as a passive candidate.
1159     // TODO(bugs.webrtc.org/11466): Treat a missing tcptype as an error?
1160     tcptype = cricket::TCPTYPE_PASSIVE_STR;
1161   }
1162 
1163   // Extension
1164   // Though non-standard, we support the ICE ufrag and pwd being signaled on
1165   // the candidate to avoid issues with confusing which generation a candidate
1166   // belongs to when trickling multiple generations at the same time.
1167   std::string username;
1168   std::string password;
1169   uint32_t generation = 0;
1170   uint16_t network_id = 0;
1171   uint16_t network_cost = 0;
1172   for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1173     // RFC 5245
1174     // *(SP extension-att-name SP extension-att-value)
1175     if (fields[i] == kAttributeCandidateGeneration) {
1176       if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1177         return false;
1178       }
1179     } else if (fields[i] == kAttributeCandidateUfrag) {
1180       username = fields[++i];
1181     } else if (fields[i] == kAttributeCandidatePwd) {
1182       password = fields[++i];
1183     } else if (fields[i] == kAttributeCandidateNetworkId) {
1184       if (!GetValueFromString(first_line, fields[++i], &network_id, error)) {
1185         return false;
1186       }
1187     } else if (fields[i] == kAttributeCandidateNetworkCost) {
1188       if (!GetValueFromString(first_line, fields[++i], &network_cost, error)) {
1189         return false;
1190       }
1191       network_cost = std::min(network_cost, rtc::kNetworkCostMax);
1192     } else {
1193       // Skip the unknown extension.
1194       ++i;
1195     }
1196   }
1197 
1198   *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
1199                          address, priority, username, password, candidate_type,
1200                          generation, foundation, network_id, network_cost);
1201   candidate->set_related_address(related_address);
1202   candidate->set_tcptype(tcptype);
1203   return true;
1204 }
1205 
ParseIceOptions(const std::string & line,std::vector<std::string> * transport_options,SdpParseError * error)1206 bool ParseIceOptions(const std::string& line,
1207                      std::vector<std::string>* transport_options,
1208                      SdpParseError* error) {
1209   std::string ice_options;
1210   if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1211     return false;
1212   }
1213   std::vector<std::string> fields;
1214   rtc::split(ice_options, kSdpDelimiterSpaceChar, &fields);
1215   for (size_t i = 0; i < fields.size(); ++i) {
1216     transport_options->push_back(fields[i]);
1217   }
1218   return true;
1219 }
1220 
ParseSctpPort(const std::string & line,int * sctp_port,SdpParseError * error)1221 bool ParseSctpPort(const std::string& line,
1222                    int* sctp_port,
1223                    SdpParseError* error) {
1224   // draft-ietf-mmusic-sctp-sdp-26
1225   // a=sctp-port
1226   std::vector<std::string> fields;
1227   const size_t expected_min_fields = 2;
1228   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar, &fields);
1229   if (fields.size() < expected_min_fields) {
1230     fields.resize(0);
1231     rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
1232   }
1233   if (fields.size() < expected_min_fields) {
1234     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1235   }
1236   if (!rtc::FromString(fields[1], sctp_port)) {
1237     return ParseFailed(line, "Invalid sctp port value.", error);
1238   }
1239   return true;
1240 }
1241 
ParseSctpMaxMessageSize(const std::string & line,int * max_message_size,SdpParseError * error)1242 bool ParseSctpMaxMessageSize(const std::string& line,
1243                              int* max_message_size,
1244                              SdpParseError* error) {
1245   // draft-ietf-mmusic-sctp-sdp-26
1246   // a=max-message-size:199999
1247   std::vector<std::string> fields;
1248   const size_t expected_min_fields = 2;
1249   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar, &fields);
1250   if (fields.size() < expected_min_fields) {
1251     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1252   }
1253   if (!rtc::FromString(fields[1], max_message_size)) {
1254     return ParseFailed(line, "Invalid SCTP max message size.", error);
1255   }
1256   return true;
1257 }
1258 
ParseExtmap(const std::string & line,RtpExtension * extmap,SdpParseError * error)1259 bool ParseExtmap(const std::string& line,
1260                  RtpExtension* extmap,
1261                  SdpParseError* error) {
1262   // RFC 5285
1263   // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1264   std::vector<std::string> fields;
1265   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
1266   const size_t expected_min_fields = 2;
1267   if (fields.size() < expected_min_fields) {
1268     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1269   }
1270   std::string uri = fields[1];
1271 
1272   std::string value_direction;
1273   if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1274     return false;
1275   }
1276   std::vector<std::string> sub_fields;
1277   rtc::split(value_direction, kSdpDelimiterSlashChar, &sub_fields);
1278   int value = 0;
1279   if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1280     return false;
1281   }
1282 
1283   bool encrypted = false;
1284   if (uri == RtpExtension::kEncryptHeaderExtensionsUri) {
1285     // RFC 6904
1286     // a=extmap:<value["/"<direction>] urn:ietf:params:rtp-hdrext:encrypt <URI>
1287     //     <extensionattributes>
1288     const size_t expected_min_fields_encrypted = expected_min_fields + 1;
1289     if (fields.size() < expected_min_fields_encrypted) {
1290       return ParseFailedExpectMinFieldNum(line, expected_min_fields_encrypted,
1291                                           error);
1292     }
1293 
1294     encrypted = true;
1295     uri = fields[2];
1296     if (uri == RtpExtension::kEncryptHeaderExtensionsUri) {
1297       return ParseFailed(line, "Recursive encrypted header.", error);
1298     }
1299   }
1300 
1301   *extmap = RtpExtension(uri, value, encrypted);
1302   return true;
1303 }
1304 
BuildSctpContentAttributes(std::string * message,const cricket::SctpDataContentDescription * data_desc)1305 static void BuildSctpContentAttributes(
1306     std::string* message,
1307     const cricket::SctpDataContentDescription* data_desc) {
1308   rtc::StringBuilder os;
1309   if (data_desc->use_sctpmap()) {
1310     // draft-ietf-mmusic-sctp-sdp-04
1311     // a=sctpmap:sctpmap-number  protocol  [streams]
1312     rtc::StringBuilder os;
1313     InitAttrLine(kAttributeSctpmap, &os);
1314     os << kSdpDelimiterColon << data_desc->port() << kSdpDelimiterSpace
1315        << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1316        << cricket::kMaxSctpStreams;
1317     AddLine(os.str(), message);
1318   } else {
1319     // draft-ietf-mmusic-sctp-sdp-23
1320     // a=sctp-port:<port>
1321     InitAttrLine(kAttributeSctpPort, &os);
1322     os << kSdpDelimiterColon << data_desc->port();
1323     AddLine(os.str(), message);
1324     if (data_desc->max_message_size() != kDefaultSctpMaxMessageSize) {
1325       InitAttrLine(kAttributeMaxMessageSize, &os);
1326       os << kSdpDelimiterColon << data_desc->max_message_size();
1327       AddLine(os.str(), message);
1328     }
1329   }
1330 }
1331 
BuildMediaDescription(const ContentInfo * content_info,const TransportInfo * transport_info,const cricket::MediaType media_type,const std::vector<Candidate> & candidates,int msid_signaling,std::string * message)1332 void BuildMediaDescription(const ContentInfo* content_info,
1333                            const TransportInfo* transport_info,
1334                            const cricket::MediaType media_type,
1335                            const std::vector<Candidate>& candidates,
1336                            int msid_signaling,
1337                            std::string* message) {
1338   RTC_DCHECK(message != NULL);
1339   if (content_info == NULL || message == NULL) {
1340     return;
1341   }
1342   rtc::StringBuilder os;
1343   const MediaContentDescription* media_desc = content_info->media_description();
1344   RTC_DCHECK(media_desc);
1345 
1346   // RFC 4566
1347   // m=<media> <port> <proto> <fmt>
1348   // fmt is a list of payload type numbers that MAY be used in the session.
1349   const char* type = NULL;
1350   if (media_type == cricket::MEDIA_TYPE_AUDIO)
1351     type = kMediaTypeAudio;
1352   else if (media_type == cricket::MEDIA_TYPE_VIDEO)
1353     type = kMediaTypeVideo;
1354   else if (media_type == cricket::MEDIA_TYPE_DATA)
1355     type = kMediaTypeData;
1356   else
1357     RTC_NOTREACHED();
1358 
1359   std::string fmt;
1360   if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1361     const VideoContentDescription* video_desc = media_desc->as_video();
1362     for (const cricket::VideoCodec& codec : video_desc->codecs()) {
1363       fmt.append(" ");
1364       fmt.append(rtc::ToString(codec.id));
1365     }
1366   } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1367     const AudioContentDescription* audio_desc = media_desc->as_audio();
1368     for (const cricket::AudioCodec& codec : audio_desc->codecs()) {
1369       fmt.append(" ");
1370       fmt.append(rtc::ToString(codec.id));
1371     }
1372   } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1373     const cricket::SctpDataContentDescription* sctp_data_desc =
1374         media_desc->as_sctp();
1375     if (sctp_data_desc) {
1376       fmt.append(" ");
1377 
1378       if (sctp_data_desc->use_sctpmap()) {
1379         fmt.append(rtc::ToString(sctp_data_desc->port()));
1380       } else {
1381         fmt.append(kDefaultSctpmapProtocol);
1382       }
1383     } else {
1384       const RtpDataContentDescription* rtp_data_desc =
1385           media_desc->as_rtp_data();
1386       for (const cricket::RtpDataCodec& codec : rtp_data_desc->codecs()) {
1387         fmt.append(" ");
1388         fmt.append(rtc::ToString(codec.id));
1389       }
1390     }
1391   }
1392   // The fmt must never be empty. If no codecs are found, set the fmt attribute
1393   // to 0.
1394   if (fmt.empty()) {
1395     fmt = " 0";
1396   }
1397 
1398   // The port number in the m line will be updated later when associated with
1399   // the candidates.
1400   //
1401   // A port value of 0 indicates that the m= section is rejected.
1402   // RFC 3264
1403   // To reject an offered stream, the port number in the corresponding stream in
1404   // the answer MUST be set to zero.
1405   //
1406   // However, the BUNDLE draft adds a new meaning to port zero, when used along
1407   // with a=bundle-only.
1408   std::string port = kDummyPort;
1409   if (content_info->rejected || content_info->bundle_only) {
1410     port = kMediaPortRejected;
1411   } else if (!media_desc->connection_address().IsNil()) {
1412     port = rtc::ToString(media_desc->connection_address().port());
1413   }
1414 
1415   rtc::SSLFingerprint* fp =
1416       (transport_info) ? transport_info->description.identity_fingerprint.get()
1417                        : NULL;
1418 
1419   // Add the m and c lines.
1420   InitLine(kLineTypeMedia, type, &os);
1421   os << " " << port << " " << media_desc->protocol() << fmt;
1422   AddLine(os.str(), message);
1423 
1424   InitLine(kLineTypeConnection, kConnectionNettype, &os);
1425   if (media_desc->connection_address().IsNil()) {
1426     os << " " << kConnectionIpv4Addrtype << " " << kDummyAddress;
1427   } else if (media_desc->connection_address().family() == AF_INET) {
1428     os << " " << kConnectionIpv4Addrtype << " "
1429        << media_desc->connection_address().ipaddr().ToString();
1430   } else if (media_desc->connection_address().family() == AF_INET6) {
1431     os << " " << kConnectionIpv6Addrtype << " "
1432        << media_desc->connection_address().ipaddr().ToString();
1433   } else {
1434     os << " " << kConnectionIpv4Addrtype << " " << kDummyAddress;
1435   }
1436   AddLine(os.str(), message);
1437 
1438   // RFC 4566
1439   // b=AS:<bandwidth>
1440   if (media_desc->bandwidth() >= 1000) {
1441     InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
1442     os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
1443     AddLine(os.str(), message);
1444   }
1445 
1446   // Add the a=bundle-only line.
1447   if (content_info->bundle_only) {
1448     InitAttrLine(kAttributeBundleOnly, &os);
1449     AddLine(os.str(), message);
1450   }
1451 
1452   // Add the a=rtcp line.
1453   if (cricket::IsRtpProtocol(media_desc->protocol())) {
1454     std::string rtcp_line = GetRtcpLine(candidates);
1455     if (!rtcp_line.empty()) {
1456       AddLine(rtcp_line, message);
1457     }
1458   }
1459 
1460   // Build the a=candidate lines. We don't include ufrag and pwd in the
1461   // candidates in the SDP to avoid redundancy.
1462   BuildCandidate(candidates, false, message);
1463 
1464   // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1465   if (transport_info) {
1466     // RFC 5245
1467     // ice-pwd-att           = "ice-pwd" ":" password
1468     // ice-ufrag-att         = "ice-ufrag" ":" ufrag
1469     // ice-ufrag
1470     if (!transport_info->description.ice_ufrag.empty()) {
1471       InitAttrLine(kAttributeIceUfrag, &os);
1472       os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1473       AddLine(os.str(), message);
1474     }
1475     // ice-pwd
1476     if (!transport_info->description.ice_pwd.empty()) {
1477       InitAttrLine(kAttributeIcePwd, &os);
1478       os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1479       AddLine(os.str(), message);
1480     }
1481 
1482     // draft-petithuguenin-mmusic-ice-attributes-level-03
1483     BuildIceOptions(transport_info->description.transport_options, message);
1484 
1485     // RFC 4572
1486     // fingerprint-attribute  =
1487     //   "fingerprint" ":" hash-func SP fingerprint
1488     if (fp) {
1489       // Insert the fingerprint attribute.
1490       InitAttrLine(kAttributeFingerprint, &os);
1491       os << kSdpDelimiterColon << fp->algorithm << kSdpDelimiterSpace
1492          << fp->GetRfc4572Fingerprint();
1493       AddLine(os.str(), message);
1494 
1495       // Inserting setup attribute.
1496       if (transport_info->description.connection_role !=
1497           cricket::CONNECTIONROLE_NONE) {
1498         // Making sure we are not using "passive" mode.
1499         cricket::ConnectionRole role =
1500             transport_info->description.connection_role;
1501         std::string dtls_role_str;
1502         const bool success =
1503             cricket::ConnectionRoleToString(role, &dtls_role_str);
1504         RTC_DCHECK(success);
1505         InitAttrLine(kAttributeSetup, &os);
1506         os << kSdpDelimiterColon << dtls_role_str;
1507         AddLine(os.str(), message);
1508       }
1509     }
1510   }
1511 
1512   // RFC 3388
1513   // mid-attribute      = "a=mid:" identification-tag
1514   // identification-tag = token
1515   // Use the content name as the mid identification-tag.
1516   InitAttrLine(kAttributeMid, &os);
1517   os << kSdpDelimiterColon << content_info->name;
1518   AddLine(os.str(), message);
1519 
1520   if (cricket::IsDtlsSctp(media_desc->protocol())) {
1521     const cricket::SctpDataContentDescription* data_desc =
1522         media_desc->as_sctp();
1523     BuildSctpContentAttributes(message, data_desc);
1524   } else if (cricket::IsRtpProtocol(media_desc->protocol())) {
1525     BuildRtpContentAttributes(media_desc, media_type, msid_signaling, message);
1526   }
1527 }
1528 
BuildRtpContentAttributes(const MediaContentDescription * media_desc,const cricket::MediaType media_type,int msid_signaling,std::string * message)1529 void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
1530                                const cricket::MediaType media_type,
1531                                int msid_signaling,
1532                                std::string* message) {
1533   SdpSerializer serializer;
1534   rtc::StringBuilder os;
1535   // RFC 8285
1536   // a=extmap-allow-mixed
1537   // The attribute MUST be either on session level or media level. We support
1538   // responding on both levels, however, we don't respond on media level if it's
1539   // set on session level.
1540   if (media_desc->extmap_allow_mixed_enum() ==
1541       MediaContentDescription::kMedia) {
1542     InitAttrLine(kAttributeExtmapAllowMixed, &os);
1543     AddLine(os.str(), message);
1544   }
1545   // RFC 8285
1546   // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1547   // The definitions MUST be either all session level or all media level. This
1548   // implementation uses all media level.
1549   for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1550     const RtpExtension& extension = media_desc->rtp_header_extensions()[i];
1551     InitAttrLine(kAttributeExtmap, &os);
1552     os << kSdpDelimiterColon << extension.id;
1553     if (extension.encrypt) {
1554       os << kSdpDelimiterSpace << RtpExtension::kEncryptHeaderExtensionsUri;
1555     }
1556     os << kSdpDelimiterSpace << extension.uri;
1557     AddLine(os.str(), message);
1558   }
1559 
1560   // RFC 3264
1561   // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
1562   switch (media_desc->direction()) {
1563     case RtpTransceiverDirection::kInactive:
1564       InitAttrLine(kAttributeInactive, &os);
1565       break;
1566     case RtpTransceiverDirection::kSendOnly:
1567       InitAttrLine(kAttributeSendOnly, &os);
1568       break;
1569     case RtpTransceiverDirection::kRecvOnly:
1570       InitAttrLine(kAttributeRecvOnly, &os);
1571       break;
1572     case RtpTransceiverDirection::kSendRecv:
1573       InitAttrLine(kAttributeSendRecv, &os);
1574       break;
1575     case RtpTransceiverDirection::kStopped:
1576     default:
1577       // kStopped shouldn't be used in signalling.
1578       RTC_NOTREACHED();
1579       InitAttrLine(kAttributeSendRecv, &os);
1580       break;
1581   }
1582   AddLine(os.str(), message);
1583 
1584   // Specified in https://datatracker.ietf.org/doc/draft-ietf-mmusic-msid/16/
1585   // a=msid:<msid-id> <msid-appdata>
1586   // The msid-id is a 1*64 token char representing the media stream id, and the
1587   // msid-appdata is a 1*64 token char representing the track id. There is a
1588   // line for every media stream, with a special msid-id value of "-"
1589   // representing no streams. The value of "msid-appdata" MUST be identical for
1590   // all lines.
1591   if (msid_signaling & cricket::kMsidSignalingMediaSection) {
1592     const StreamParamsVec& streams = media_desc->streams();
1593     if (streams.size() == 1u) {
1594       const StreamParams& track = streams[0];
1595       std::vector<std::string> stream_ids = track.stream_ids();
1596       if (stream_ids.empty()) {
1597         stream_ids.push_back(kNoStreamMsid);
1598       }
1599       for (const std::string& stream_id : stream_ids) {
1600         InitAttrLine(kAttributeMsid, &os);
1601         os << kSdpDelimiterColon << stream_id << kSdpDelimiterSpace << track.id;
1602         AddLine(os.str(), message);
1603       }
1604     } else if (streams.size() > 1u) {
1605       RTC_LOG(LS_WARNING)
1606           << "Trying to serialize Unified Plan SDP with more than "
1607              "one track in a media section. Omitting 'a=msid'.";
1608     }
1609   }
1610 
1611   // RFC 5761
1612   // a=rtcp-mux
1613   if (media_desc->rtcp_mux()) {
1614     InitAttrLine(kAttributeRtcpMux, &os);
1615     AddLine(os.str(), message);
1616   }
1617 
1618   // RFC 5506
1619   // a=rtcp-rsize
1620   if (media_desc->rtcp_reduced_size()) {
1621     InitAttrLine(kAttributeRtcpReducedSize, &os);
1622     AddLine(os.str(), message);
1623   }
1624 
1625   if (media_desc->conference_mode()) {
1626     InitAttrLine(kAttributeXGoogleFlag, &os);
1627     os << kSdpDelimiterColon << kValueConference;
1628     AddLine(os.str(), message);
1629   }
1630 
1631   if (media_desc->remote_estimate()) {
1632     InitAttrLine(kAttributeRtcpRemoteEstimate, &os);
1633     AddLine(os.str(), message);
1634   }
1635 
1636   // RFC 4568
1637   // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1638   for (const CryptoParams& crypto_params : media_desc->cryptos()) {
1639     InitAttrLine(kAttributeCrypto, &os);
1640     os << kSdpDelimiterColon << crypto_params.tag << " "
1641        << crypto_params.cipher_suite << " " << crypto_params.key_params;
1642     if (!crypto_params.session_params.empty()) {
1643       os << " " << crypto_params.session_params;
1644     }
1645     AddLine(os.str(), message);
1646   }
1647 
1648   // RFC 4566
1649   // a=rtpmap:<payload type> <encoding name>/<clock rate>
1650   // [/<encodingparameters>]
1651   BuildRtpMap(media_desc, media_type, message);
1652 
1653   for (const StreamParams& track : media_desc->streams()) {
1654     // Build the ssrc-group lines.
1655     for (const SsrcGroup& ssrc_group : track.ssrc_groups) {
1656       // RFC 5576
1657       // a=ssrc-group:<semantics> <ssrc-id> ...
1658       if (ssrc_group.ssrcs.empty()) {
1659         continue;
1660       }
1661       InitAttrLine(kAttributeSsrcGroup, &os);
1662       os << kSdpDelimiterColon << ssrc_group.semantics;
1663       for (uint32_t ssrc : ssrc_group.ssrcs) {
1664         os << kSdpDelimiterSpace << rtc::ToString(ssrc);
1665       }
1666       AddLine(os.str(), message);
1667     }
1668     // Build the ssrc lines for each ssrc.
1669     for (uint32_t ssrc : track.ssrcs) {
1670       // RFC 5576
1671       // a=ssrc:<ssrc-id> cname:<value>
1672       AddSsrcLine(ssrc, kSsrcAttributeCname, track.cname, message);
1673 
1674       if (msid_signaling & cricket::kMsidSignalingSsrcAttribute) {
1675         // draft-alvestrand-mmusic-msid-00
1676         // a=ssrc:<ssrc-id> msid:identifier [appdata]
1677         // The appdata consists of the "id" attribute of a MediaStreamTrack,
1678         // which corresponds to the "id" attribute of StreamParams.
1679         // Since a=ssrc msid signaling is used in Plan B SDP semantics, and
1680         // multiple stream ids are not supported for Plan B, we are only adding
1681         // a line for the first media stream id here.
1682         const std::string& track_stream_id = track.first_stream_id();
1683         // We use a special msid-id value of "-" to represent no streams,
1684         // for Unified Plan compatibility. Plan B will always have a
1685         // track_stream_id.
1686         const std::string& stream_id =
1687             track_stream_id.empty() ? kNoStreamMsid : track_stream_id;
1688         InitAttrLine(kAttributeSsrc, &os);
1689         os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1690            << kSsrcAttributeMsid << kSdpDelimiterColon << stream_id
1691            << kSdpDelimiterSpace << track.id;
1692         AddLine(os.str(), message);
1693 
1694         // TODO(ronghuawu): Remove below code which is for backward
1695         // compatibility.
1696         // draft-alvestrand-rtcweb-mid-01
1697         // a=ssrc:<ssrc-id> mslabel:<value>
1698         // The label isn't yet defined.
1699         // a=ssrc:<ssrc-id> label:<value>
1700         AddSsrcLine(ssrc, kSsrcAttributeMslabel, stream_id, message);
1701         AddSsrcLine(ssrc, kSSrcAttributeLabel, track.id, message);
1702       }
1703     }
1704 
1705     // Build the rid lines for each layer of the track
1706     for (const RidDescription& rid_description : track.rids()) {
1707       InitAttrLine(kAttributeRid, &os);
1708       os << kSdpDelimiterColon
1709          << serializer.SerializeRidDescription(rid_description);
1710       AddLine(os.str(), message);
1711     }
1712   }
1713 
1714   for (const RidDescription& rid_description : media_desc->receive_rids()) {
1715     InitAttrLine(kAttributeRid, &os);
1716     os << kSdpDelimiterColon
1717        << serializer.SerializeRidDescription(rid_description);
1718     AddLine(os.str(), message);
1719   }
1720 
1721   // Simulcast (a=simulcast)
1722   // https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-13#section-5.1
1723   if (media_desc->HasSimulcast()) {
1724     const auto& simulcast = media_desc->simulcast_description();
1725     InitAttrLine(kAttributeSimulcast, &os);
1726     os << kSdpDelimiterColon
1727        << serializer.SerializeSimulcastDescription(simulcast);
1728     AddLine(os.str(), message);
1729   }
1730 }
1731 
WriteFmtpHeader(int payload_type,rtc::StringBuilder * os)1732 void WriteFmtpHeader(int payload_type, rtc::StringBuilder* os) {
1733   // fmtp header: a=fmtp:|payload_type| <parameters>
1734   // Add a=fmtp
1735   InitAttrLine(kAttributeFmtp, os);
1736   // Add :|payload_type|
1737   *os << kSdpDelimiterColon << payload_type;
1738 }
1739 
WritePacketizationHeader(int payload_type,rtc::StringBuilder * os)1740 void WritePacketizationHeader(int payload_type, rtc::StringBuilder* os) {
1741   // packetization header: a=packetization:|payload_type| <packetization_format>
1742   // Add a=packetization
1743   InitAttrLine(kAttributePacketization, os);
1744   // Add :|payload_type|
1745   *os << kSdpDelimiterColon << payload_type;
1746 }
1747 
WriteRtcpFbHeader(int payload_type,rtc::StringBuilder * os)1748 void WriteRtcpFbHeader(int payload_type, rtc::StringBuilder* os) {
1749   // rtcp-fb header: a=rtcp-fb:|payload_type|
1750   // <parameters>/<ccm <ccm_parameters>>
1751   // Add a=rtcp-fb
1752   InitAttrLine(kAttributeRtcpFb, os);
1753   // Add :
1754   *os << kSdpDelimiterColon;
1755   if (payload_type == kWildcardPayloadType) {
1756     *os << "*";
1757   } else {
1758     *os << payload_type;
1759   }
1760 }
1761 
WriteFmtpParameter(const std::string & parameter_name,const std::string & parameter_value,rtc::StringBuilder * os)1762 void WriteFmtpParameter(const std::string& parameter_name,
1763                         const std::string& parameter_value,
1764                         rtc::StringBuilder* os) {
1765   if (parameter_name == "") {
1766     // RFC 2198 and RFC 4733 don't use key-value pairs.
1767     *os << parameter_value;
1768   } else {
1769     // fmtp parameters: |parameter_name|=|parameter_value|
1770     *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1771   }
1772 }
1773 
IsFmtpParam(const std::string & name)1774 bool IsFmtpParam(const std::string& name) {
1775   // RFC 4855, section 3 specifies the mapping of media format parameters to SDP
1776   // parameters. Only ptime, maxptime, channels and rate are placed outside of
1777   // the fmtp line. In WebRTC, channels and rate are already handled separately
1778   // and thus not included in the CodecParameterMap.
1779   return name != kCodecParamPTime && name != kCodecParamMaxPTime;
1780 }
1781 
WriteFmtpParameters(const cricket::CodecParameterMap & parameters,rtc::StringBuilder * os)1782 bool WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1783                          rtc::StringBuilder* os) {
1784   bool empty = true;
1785   const char* delimiter = "";  // No delimiter before first parameter.
1786   for (const auto& entry : parameters) {
1787     const std::string& key = entry.first;
1788     const std::string& value = entry.second;
1789 
1790     if (IsFmtpParam(key)) {
1791       *os << delimiter;
1792       // A semicolon before each subsequent parameter.
1793       delimiter = kSdpDelimiterSemicolon;
1794       WriteFmtpParameter(key, value, os);
1795       empty = false;
1796     }
1797   }
1798 
1799   return !empty;
1800 }
1801 
1802 template <class T>
AddFmtpLine(const T & codec,std::string * message)1803 void AddFmtpLine(const T& codec, std::string* message) {
1804   rtc::StringBuilder os;
1805   WriteFmtpHeader(codec.id, &os);
1806   os << kSdpDelimiterSpace;
1807   // Create FMTP line and check that it's nonempty.
1808   if (WriteFmtpParameters(codec.params, &os)) {
1809     AddLine(os.str(), message);
1810   }
1811   return;
1812 }
1813 
1814 template <class T>
AddPacketizationLine(const T & codec,std::string * message)1815 void AddPacketizationLine(const T& codec, std::string* message) {
1816   if (!codec.packetization) {
1817     return;
1818   }
1819   rtc::StringBuilder os;
1820   WritePacketizationHeader(codec.id, &os);
1821   os << " " << *codec.packetization;
1822   AddLine(os.str(), message);
1823 }
1824 
1825 template <class T>
AddRtcpFbLines(const T & codec,std::string * message)1826 void AddRtcpFbLines(const T& codec, std::string* message) {
1827   for (const cricket::FeedbackParam& param : codec.feedback_params.params()) {
1828     rtc::StringBuilder os;
1829     WriteRtcpFbHeader(codec.id, &os);
1830     os << " " << param.id();
1831     if (!param.param().empty()) {
1832       os << " " << param.param();
1833     }
1834     AddLine(os.str(), message);
1835   }
1836 }
1837 
GetMinValue(const std::vector<int> & values,int * value)1838 bool GetMinValue(const std::vector<int>& values, int* value) {
1839   if (values.empty()) {
1840     return false;
1841   }
1842   auto it = absl::c_min_element(values);
1843   *value = *it;
1844   return true;
1845 }
1846 
GetParameter(const std::string & name,const cricket::CodecParameterMap & params,int * value)1847 bool GetParameter(const std::string& name,
1848                   const cricket::CodecParameterMap& params,
1849                   int* value) {
1850   std::map<std::string, std::string>::const_iterator found = params.find(name);
1851   if (found == params.end()) {
1852     return false;
1853   }
1854   if (!rtc::FromString(found->second, value)) {
1855     return false;
1856   }
1857   return true;
1858 }
1859 
BuildRtpMap(const MediaContentDescription * media_desc,const cricket::MediaType media_type,std::string * message)1860 void BuildRtpMap(const MediaContentDescription* media_desc,
1861                  const cricket::MediaType media_type,
1862                  std::string* message) {
1863   RTC_DCHECK(message != NULL);
1864   RTC_DCHECK(media_desc != NULL);
1865   rtc::StringBuilder os;
1866   if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1867     for (const cricket::VideoCodec& codec : media_desc->as_video()->codecs()) {
1868       // RFC 4566
1869       // a=rtpmap:<payload type> <encoding name>/<clock rate>
1870       // [/<encodingparameters>]
1871       if (codec.id != kWildcardPayloadType) {
1872         InitAttrLine(kAttributeRtpmap, &os);
1873         os << kSdpDelimiterColon << codec.id << " " << codec.name << "/"
1874            << cricket::kVideoCodecClockrate;
1875         AddLine(os.str(), message);
1876       }
1877       AddPacketizationLine(codec, message);
1878       AddRtcpFbLines(codec, message);
1879       AddFmtpLine(codec, message);
1880     }
1881   } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1882     std::vector<int> ptimes;
1883     std::vector<int> maxptimes;
1884     int max_minptime = 0;
1885     for (const cricket::AudioCodec& codec : media_desc->as_audio()->codecs()) {
1886       RTC_DCHECK(!codec.name.empty());
1887       // RFC 4566
1888       // a=rtpmap:<payload type> <encoding name>/<clock rate>
1889       // [/<encodingparameters>]
1890       InitAttrLine(kAttributeRtpmap, &os);
1891       os << kSdpDelimiterColon << codec.id << " ";
1892       os << codec.name << "/" << codec.clockrate;
1893       if (codec.channels != 1) {
1894         os << "/" << codec.channels;
1895       }
1896       AddLine(os.str(), message);
1897       AddRtcpFbLines(codec, message);
1898       AddFmtpLine(codec, message);
1899       int minptime = 0;
1900       if (GetParameter(kCodecParamMinPTime, codec.params, &minptime)) {
1901         max_minptime = std::max(minptime, max_minptime);
1902       }
1903       int ptime;
1904       if (GetParameter(kCodecParamPTime, codec.params, &ptime)) {
1905         ptimes.push_back(ptime);
1906       }
1907       int maxptime;
1908       if (GetParameter(kCodecParamMaxPTime, codec.params, &maxptime)) {
1909         maxptimes.push_back(maxptime);
1910       }
1911     }
1912     // Populate the maxptime attribute with the smallest maxptime of all codecs
1913     // under the same m-line.
1914     int min_maxptime = INT_MAX;
1915     if (GetMinValue(maxptimes, &min_maxptime)) {
1916       AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1917     }
1918     RTC_DCHECK(min_maxptime > max_minptime);
1919     // Populate the ptime attribute with the smallest ptime or the largest
1920     // minptime, whichever is the largest, for all codecs under the same m-line.
1921     int ptime = INT_MAX;
1922     if (GetMinValue(ptimes, &ptime)) {
1923       ptime = std::min(ptime, min_maxptime);
1924       ptime = std::max(ptime, max_minptime);
1925       AddAttributeLine(kCodecParamPTime, ptime, message);
1926     }
1927   } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1928     if (media_desc->as_rtp_data()) {
1929       for (const cricket::RtpDataCodec& codec :
1930            media_desc->as_rtp_data()->codecs()) {
1931         // RFC 4566
1932         // a=rtpmap:<payload type> <encoding name>/<clock rate>
1933         // [/<encodingparameters>]
1934         InitAttrLine(kAttributeRtpmap, &os);
1935         os << kSdpDelimiterColon << codec.id << " " << codec.name << "/"
1936            << codec.clockrate;
1937         AddLine(os.str(), message);
1938       }
1939     }
1940   }
1941 }
1942 
BuildCandidate(const std::vector<Candidate> & candidates,bool include_ufrag,std::string * message)1943 void BuildCandidate(const std::vector<Candidate>& candidates,
1944                     bool include_ufrag,
1945                     std::string* message) {
1946   rtc::StringBuilder os;
1947 
1948   for (const Candidate& candidate : candidates) {
1949     // RFC 5245
1950     // a=candidate:<foundation> <component-id> <transport> <priority>
1951     // <connection-address> <port> typ <candidate-types>
1952     // [raddr <connection-address>] [rport <port>]
1953     // *(SP extension-att-name SP extension-att-value)
1954     std::string type;
1955     // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
1956     if (candidate.type() == cricket::LOCAL_PORT_TYPE) {
1957       type = kCandidateHost;
1958     } else if (candidate.type() == cricket::STUN_PORT_TYPE) {
1959       type = kCandidateSrflx;
1960     } else if (candidate.type() == cricket::RELAY_PORT_TYPE) {
1961       type = kCandidateRelay;
1962     } else if (candidate.type() == cricket::PRFLX_PORT_TYPE) {
1963       type = kCandidatePrflx;
1964       // Peer reflexive candidate may be signaled for being removed.
1965     } else {
1966       RTC_NOTREACHED();
1967       // Never write out candidates if we don't know the type.
1968       continue;
1969     }
1970 
1971     InitAttrLine(kAttributeCandidate, &os);
1972     os << kSdpDelimiterColon << candidate.foundation() << " "
1973        << candidate.component() << " " << candidate.protocol() << " "
1974        << candidate.priority() << " "
1975        << (candidate.address().ipaddr().IsNil()
1976                ? candidate.address().hostname()
1977                : candidate.address().ipaddr().ToString())
1978        << " " << candidate.address().PortAsString() << " "
1979        << kAttributeCandidateTyp << " " << type << " ";
1980 
1981     // Related address
1982     if (!candidate.related_address().IsNil()) {
1983       os << kAttributeCandidateRaddr << " "
1984          << candidate.related_address().ipaddr().ToString() << " "
1985          << kAttributeCandidateRport << " "
1986          << candidate.related_address().PortAsString() << " ";
1987     }
1988 
1989     // Note that we allow the tcptype to be missing, for backwards
1990     // compatibility; the implementation treats this as a passive candidate.
1991     // TODO(bugs.webrtc.org/11466): Treat a missing tcptype as an error?
1992     if (candidate.protocol() == cricket::TCP_PROTOCOL_NAME &&
1993         !candidate.tcptype().empty()) {
1994       os << kTcpCandidateType << " " << candidate.tcptype() << " ";
1995     }
1996 
1997     // Extensions
1998     os << kAttributeCandidateGeneration << " " << candidate.generation();
1999     if (include_ufrag && !candidate.username().empty()) {
2000       os << " " << kAttributeCandidateUfrag << " " << candidate.username();
2001     }
2002     if (candidate.network_id() > 0) {
2003       os << " " << kAttributeCandidateNetworkId << " "
2004          << candidate.network_id();
2005     }
2006     if (candidate.network_cost() > 0) {
2007       os << " " << kAttributeCandidateNetworkCost << " "
2008          << candidate.network_cost();
2009     }
2010 
2011     AddLine(os.str(), message);
2012   }
2013 }
2014 
BuildIceOptions(const std::vector<std::string> & transport_options,std::string * message)2015 void BuildIceOptions(const std::vector<std::string>& transport_options,
2016                      std::string* message) {
2017   if (!transport_options.empty()) {
2018     rtc::StringBuilder os;
2019     InitAttrLine(kAttributeIceOption, &os);
2020     os << kSdpDelimiterColon << transport_options[0];
2021     for (size_t i = 1; i < transport_options.size(); ++i) {
2022       os << kSdpDelimiterSpace << transport_options[i];
2023     }
2024     AddLine(os.str(), message);
2025   }
2026 }
2027 
ParseConnectionData(const std::string & line,rtc::SocketAddress * addr,SdpParseError * error)2028 bool ParseConnectionData(const std::string& line,
2029                          rtc::SocketAddress* addr,
2030                          SdpParseError* error) {
2031   // Parse the line from left to right.
2032   std::string token;
2033   std::string rightpart;
2034   // RFC 4566
2035   // c=<nettype> <addrtype> <connection-address>
2036   // Skip the "c="
2037   if (!rtc::tokenize_first(line, kSdpDelimiterEqualChar, &token, &rightpart)) {
2038     return ParseFailed(line, "Failed to parse the network type.", error);
2039   }
2040 
2041   // Extract and verify the <nettype>
2042   if (!rtc::tokenize_first(rightpart, kSdpDelimiterSpaceChar, &token,
2043                            &rightpart) ||
2044       token != kConnectionNettype) {
2045     return ParseFailed(line,
2046                        "Failed to parse the connection data. The network type "
2047                        "is not currently supported.",
2048                        error);
2049   }
2050 
2051   // Extract the "<addrtype>" and "<connection-address>".
2052   if (!rtc::tokenize_first(rightpart, kSdpDelimiterSpaceChar, &token,
2053                            &rightpart)) {
2054     return ParseFailed(line, "Failed to parse the address type.", error);
2055   }
2056 
2057   // The rightpart part should be the IP address without the slash which is used
2058   // for multicast.
2059   if (rightpart.find('/') != std::string::npos) {
2060     return ParseFailed(line,
2061                        "Failed to parse the connection data. Multicast is not "
2062                        "currently supported.",
2063                        error);
2064   }
2065   addr->SetIP(rightpart);
2066 
2067   // Verify that the addrtype matches the type of the parsed address.
2068   if ((addr->family() == AF_INET && token != "IP4") ||
2069       (addr->family() == AF_INET6 && token != "IP6")) {
2070     addr->Clear();
2071     return ParseFailed(
2072         line,
2073         "Failed to parse the connection data. The address type is mismatching.",
2074         error);
2075   }
2076   return true;
2077 }
2078 
ParseSessionDescription(const std::string & message,size_t * pos,std::string * session_id,std::string * session_version,TransportDescription * session_td,RtpHeaderExtensions * session_extmaps,rtc::SocketAddress * connection_addr,cricket::SessionDescription * desc,SdpParseError * error)2079 bool ParseSessionDescription(const std::string& message,
2080                              size_t* pos,
2081                              std::string* session_id,
2082                              std::string* session_version,
2083                              TransportDescription* session_td,
2084                              RtpHeaderExtensions* session_extmaps,
2085                              rtc::SocketAddress* connection_addr,
2086                              cricket::SessionDescription* desc,
2087                              SdpParseError* error) {
2088   std::string line;
2089 
2090   desc->set_msid_supported(false);
2091   desc->set_extmap_allow_mixed(false);
2092   // RFC 4566
2093   // v=  (protocol version)
2094   if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
2095     return ParseFailedExpectLine(message, *pos, kLineTypeVersion, std::string(),
2096                                  error);
2097   }
2098   // RFC 4566
2099   // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
2100   // <unicast-address>
2101   if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
2102     return ParseFailedExpectLine(message, *pos, kLineTypeOrigin, std::string(),
2103                                  error);
2104   }
2105   std::vector<std::string> fields;
2106   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
2107   const size_t expected_fields = 6;
2108   if (fields.size() != expected_fields) {
2109     return ParseFailedExpectFieldNum(line, expected_fields, error);
2110   }
2111   *session_id = fields[1];
2112   *session_version = fields[2];
2113 
2114   // RFC 4566
2115   // s=  (session name)
2116   if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
2117     return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
2118                                  std::string(), error);
2119   }
2120 
2121   // absl::optional lines
2122   // Those are the optional lines, so shouldn't return false if not present.
2123   // RFC 4566
2124   // i=* (session information)
2125   GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
2126 
2127   // RFC 4566
2128   // u=* (URI of description)
2129   GetLineWithType(message, pos, &line, kLineTypeSessionUri);
2130 
2131   // RFC 4566
2132   // e=* (email address)
2133   GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
2134 
2135   // RFC 4566
2136   // p=* (phone number)
2137   GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
2138 
2139   // RFC 4566
2140   // c=* (connection information -- not required if included in
2141   //      all media)
2142   if (GetLineWithType(message, pos, &line, kLineTypeConnection)) {
2143     if (!ParseConnectionData(line, connection_addr, error)) {
2144       return false;
2145     }
2146   }
2147 
2148   // RFC 4566
2149   // b=* (zero or more bandwidth information lines)
2150   while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
2151     // By pass zero or more b lines.
2152   }
2153 
2154   // RFC 4566
2155   // One or more time descriptions ("t=" and "r=" lines; see below)
2156   // t=  (time the session is active)
2157   // r=* (zero or more repeat times)
2158   // Ensure there's at least one time description
2159   if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
2160     return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
2161                                  error);
2162   }
2163 
2164   while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
2165     // By pass zero or more r lines.
2166   }
2167 
2168   // Go through the rest of the time descriptions
2169   while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
2170     while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
2171       // By pass zero or more r lines.
2172     }
2173   }
2174 
2175   // RFC 4566
2176   // z=* (time zone adjustments)
2177   GetLineWithType(message, pos, &line, kLineTypeTimeZone);
2178 
2179   // RFC 4566
2180   // k=* (encryption key)
2181   GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
2182 
2183   // RFC 4566
2184   // a=* (zero or more session attribute lines)
2185   while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
2186     if (HasAttribute(line, kAttributeGroup)) {
2187       if (!ParseGroupAttribute(line, desc, error)) {
2188         return false;
2189       }
2190     } else if (HasAttribute(line, kAttributeIceUfrag)) {
2191       if (!GetValue(line, kAttributeIceUfrag, &(session_td->ice_ufrag),
2192                     error)) {
2193         return false;
2194       }
2195     } else if (HasAttribute(line, kAttributeIcePwd)) {
2196       if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
2197         return false;
2198       }
2199     } else if (HasAttribute(line, kAttributeIceLite)) {
2200       session_td->ice_mode = cricket::ICEMODE_LITE;
2201     } else if (HasAttribute(line, kAttributeIceOption)) {
2202       if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
2203         return false;
2204       }
2205     } else if (HasAttribute(line, kAttributeFingerprint)) {
2206       if (session_td->identity_fingerprint.get()) {
2207         return ParseFailed(
2208             line,
2209             "Can't have multiple fingerprint attributes at the same level.",
2210             error);
2211       }
2212       std::unique_ptr<rtc::SSLFingerprint> fingerprint;
2213       if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2214         return false;
2215       }
2216       session_td->identity_fingerprint = std::move(fingerprint);
2217     } else if (HasAttribute(line, kAttributeSetup)) {
2218       if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
2219         return false;
2220       }
2221     } else if (HasAttribute(line, kAttributeMsidSemantics)) {
2222       std::string semantics;
2223       if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
2224         return false;
2225       }
2226       desc->set_msid_supported(
2227           CaseInsensitiveFind(semantics, kMediaStreamSemantic));
2228     } else if (HasAttribute(line, kAttributeExtmapAllowMixed)) {
2229       desc->set_extmap_allow_mixed(true);
2230     } else if (HasAttribute(line, kAttributeExtmap)) {
2231       RtpExtension extmap;
2232       if (!ParseExtmap(line, &extmap, error)) {
2233         return false;
2234       }
2235       session_extmaps->push_back(extmap);
2236     }
2237   }
2238 
2239   return true;
2240 }
2241 
ParseGroupAttribute(const std::string & line,cricket::SessionDescription * desc,SdpParseError * error)2242 bool ParseGroupAttribute(const std::string& line,
2243                          cricket::SessionDescription* desc,
2244                          SdpParseError* error) {
2245   RTC_DCHECK(desc != NULL);
2246 
2247   // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
2248   // a=group:BUNDLE video voice
2249   std::vector<std::string> fields;
2250   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
2251   std::string semantics;
2252   if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
2253     return false;
2254   }
2255   cricket::ContentGroup group(semantics);
2256   for (size_t i = 1; i < fields.size(); ++i) {
2257     group.AddContentName(fields[i]);
2258   }
2259   desc->AddGroup(group);
2260   return true;
2261 }
2262 
ParseFingerprintAttribute(const std::string & line,std::unique_ptr<rtc::SSLFingerprint> * fingerprint,SdpParseError * error)2263 static bool ParseFingerprintAttribute(
2264     const std::string& line,
2265     std::unique_ptr<rtc::SSLFingerprint>* fingerprint,
2266     SdpParseError* error) {
2267   if (!IsLineType(line, kLineTypeAttributes) ||
2268       !HasAttribute(line, kAttributeFingerprint)) {
2269     return ParseFailedExpectLine(line, 0, kLineTypeAttributes,
2270                                  kAttributeFingerprint, error);
2271   }
2272 
2273   std::vector<std::string> fields;
2274   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
2275   const size_t expected_fields = 2;
2276   if (fields.size() != expected_fields) {
2277     return ParseFailedExpectFieldNum(line, expected_fields, error);
2278   }
2279 
2280   // The first field here is "fingerprint:<hash>.
2281   std::string algorithm;
2282   if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2283     return false;
2284   }
2285 
2286   // Downcase the algorithm. Note that we don't need to downcase the
2287   // fingerprint because hex_decode can handle upper-case.
2288   absl::c_transform(algorithm, algorithm.begin(), ::tolower);
2289 
2290   // The second field is the digest value. De-hexify it.
2291   *fingerprint =
2292       rtc::SSLFingerprint::CreateUniqueFromRfc4572(algorithm, fields[1]);
2293   if (!*fingerprint) {
2294     return ParseFailed(line, "Failed to create fingerprint from the digest.",
2295                        error);
2296   }
2297 
2298   return true;
2299 }
2300 
ParseDtlsSetup(const std::string & line,cricket::ConnectionRole * role,SdpParseError * error)2301 static bool ParseDtlsSetup(const std::string& line,
2302                            cricket::ConnectionRole* role,
2303                            SdpParseError* error) {
2304   // setup-attr           =  "a=setup:" role
2305   // role                 =  "active" / "passive" / "actpass" / "holdconn"
2306   std::vector<std::string> fields;
2307   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar, &fields);
2308   const size_t expected_fields = 2;
2309   if (fields.size() != expected_fields) {
2310     return ParseFailedExpectFieldNum(line, expected_fields, error);
2311   }
2312   std::string role_str = fields[1];
2313   if (!cricket::StringToConnectionRole(role_str, role)) {
2314     return ParseFailed(line, "Invalid attribute value.", error);
2315   }
2316   return true;
2317 }
2318 
ParseMsidAttribute(const std::string & line,std::vector<std::string> * stream_ids,std::string * track_id,SdpParseError * error)2319 static bool ParseMsidAttribute(const std::string& line,
2320                                std::vector<std::string>* stream_ids,
2321                                std::string* track_id,
2322                                SdpParseError* error) {
2323   // https://datatracker.ietf.org/doc/draft-ietf-mmusic-msid/16/
2324   // a=msid:<stream id> <track id>
2325   // msid-value = msid-id [ SP msid-appdata ]
2326   // msid-id = 1*64token-char ; see RFC 4566
2327   // msid-appdata = 1*64token-char  ; see RFC 4566
2328   std::string field1;
2329   std::string new_stream_id;
2330   std::string new_track_id;
2331   if (!rtc::tokenize_first(line.substr(kLinePrefixLength),
2332                            kSdpDelimiterSpaceChar, &field1, &new_track_id)) {
2333     const size_t expected_fields = 2;
2334     return ParseFailedExpectFieldNum(line, expected_fields, error);
2335   }
2336 
2337   if (new_track_id.empty()) {
2338     return ParseFailed(line, "Missing track ID in msid attribute.", error);
2339   }
2340   // All track ids should be the same within an m section in a Unified Plan SDP.
2341   if (!track_id->empty() && new_track_id.compare(*track_id) != 0) {
2342     return ParseFailed(
2343         line, "Two different track IDs in msid attribute in one m= section",
2344         error);
2345   }
2346   *track_id = new_track_id;
2347 
2348   // msid:<msid-id>
2349   if (!GetValue(field1, kAttributeMsid, &new_stream_id, error)) {
2350     return false;
2351   }
2352   if (new_stream_id.empty()) {
2353     return ParseFailed(line, "Missing stream ID in msid attribute.", error);
2354   }
2355   // The special value "-" indicates "no MediaStream".
2356   if (new_stream_id.compare(kNoStreamMsid) != 0) {
2357     stream_ids->push_back(new_stream_id);
2358   }
2359   return true;
2360 }
2361 
RemoveInvalidRidDescriptions(const std::vector<int> & payload_types,std::vector<RidDescription> * rids)2362 static void RemoveInvalidRidDescriptions(const std::vector<int>& payload_types,
2363                                          std::vector<RidDescription>* rids) {
2364   RTC_DCHECK(rids);
2365   std::set<std::string> to_remove;
2366   std::set<std::string> unique_rids;
2367 
2368   // Check the rids to see which ones should be removed.
2369   for (RidDescription& rid : *rids) {
2370     // In the case of a duplicate, the entire "a=rid" line, and all "a=rid"
2371     // lines with rid-ids that duplicate this line, are discarded and MUST NOT
2372     // be included in the SDP Answer.
2373     auto pair = unique_rids.insert(rid.rid);
2374     // Insert will "fail" if element already exists.
2375     if (!pair.second) {
2376       to_remove.insert(rid.rid);
2377       continue;
2378     }
2379 
2380     // If the "a=rid" line contains a "pt=", the list of payload types
2381     // is verified against the list of valid payload types for the media
2382     // section (that is, those listed on the "m=" line).  Any PT missing
2383     // from the "m=" line is discarded from the set of values in the
2384     // "pt=".  If no values are left in the "pt=" parameter after this
2385     // processing, then the "a=rid" line is discarded.
2386     if (rid.payload_types.empty()) {
2387       // If formats were not specified, rid should not be removed.
2388       continue;
2389     }
2390 
2391     // Note: Spec does not mention how to handle duplicate formats.
2392     // Media section does not handle duplicates either.
2393     std::set<int> removed_formats;
2394     for (int payload_type : rid.payload_types) {
2395       if (!absl::c_linear_search(payload_types, payload_type)) {
2396         removed_formats.insert(payload_type);
2397       }
2398     }
2399 
2400     rid.payload_types.erase(
2401         std::remove_if(rid.payload_types.begin(), rid.payload_types.end(),
2402                        [&removed_formats](int format) {
2403                          return removed_formats.count(format) > 0;
2404                        }),
2405         rid.payload_types.end());
2406 
2407     // If all formats were removed then remove the rid alogether.
2408     if (rid.payload_types.empty()) {
2409       to_remove.insert(rid.rid);
2410     }
2411   }
2412 
2413   // Remove every rid description that appears in the to_remove list.
2414   if (!to_remove.empty()) {
2415     rids->erase(std::remove_if(rids->begin(), rids->end(),
2416                                [&to_remove](const RidDescription& rid) {
2417                                  return to_remove.count(rid.rid) > 0;
2418                                }),
2419                 rids->end());
2420   }
2421 }
2422 
2423 // Create a new list (because SimulcastLayerList is immutable) without any
2424 // layers that have a rid in the to_remove list.
2425 // If a group of alternatives is empty after removing layers, the group should
2426 // be removed altogether.
RemoveRidsFromSimulcastLayerList(const std::set<std::string> & to_remove,const SimulcastLayerList & layers)2427 static SimulcastLayerList RemoveRidsFromSimulcastLayerList(
2428     const std::set<std::string>& to_remove,
2429     const SimulcastLayerList& layers) {
2430   SimulcastLayerList result;
2431   for (const std::vector<SimulcastLayer>& vector : layers) {
2432     std::vector<SimulcastLayer> new_layers;
2433     for (const SimulcastLayer& layer : vector) {
2434       if (to_remove.find(layer.rid) == to_remove.end()) {
2435         new_layers.push_back(layer);
2436       }
2437     }
2438     // If all layers were removed, do not add an entry.
2439     if (!new_layers.empty()) {
2440       result.AddLayerWithAlternatives(new_layers);
2441     }
2442   }
2443 
2444   return result;
2445 }
2446 
2447 // Will remove Simulcast Layers if:
2448 // 1. They appear in both send and receive directions.
2449 // 2. They do not appear in the list of |valid_rids|.
RemoveInvalidRidsFromSimulcast(const std::vector<RidDescription> & valid_rids,SimulcastDescription * simulcast)2450 static void RemoveInvalidRidsFromSimulcast(
2451     const std::vector<RidDescription>& valid_rids,
2452     SimulcastDescription* simulcast) {
2453   RTC_DCHECK(simulcast);
2454   std::set<std::string> to_remove;
2455   std::vector<SimulcastLayer> all_send_layers =
2456       simulcast->send_layers().GetAllLayers();
2457   std::vector<SimulcastLayer> all_receive_layers =
2458       simulcast->receive_layers().GetAllLayers();
2459 
2460   // If a rid appears in both send and receive directions, remove it from both.
2461   // This algorithm runs in O(n^2) time, but for small n (as is the case with
2462   // simulcast layers) it should still perform well.
2463   for (const SimulcastLayer& send_layer : all_send_layers) {
2464     if (absl::c_any_of(all_receive_layers,
2465                        [&send_layer](const SimulcastLayer& layer) {
2466                          return layer.rid == send_layer.rid;
2467                        })) {
2468       to_remove.insert(send_layer.rid);
2469     }
2470   }
2471 
2472   // Add any rid that is not in the valid list to the remove set.
2473   for (const SimulcastLayer& send_layer : all_send_layers) {
2474     if (absl::c_none_of(valid_rids, [&send_layer](const RidDescription& rid) {
2475           return send_layer.rid == rid.rid &&
2476                  rid.direction == cricket::RidDirection::kSend;
2477         })) {
2478       to_remove.insert(send_layer.rid);
2479     }
2480   }
2481 
2482   // Add any rid that is not in the valid list to the remove set.
2483   for (const SimulcastLayer& receive_layer : all_receive_layers) {
2484     if (absl::c_none_of(
2485             valid_rids, [&receive_layer](const RidDescription& rid) {
2486               return receive_layer.rid == rid.rid &&
2487                      rid.direction == cricket::RidDirection::kReceive;
2488             })) {
2489       to_remove.insert(receive_layer.rid);
2490     }
2491   }
2492 
2493   simulcast->send_layers() =
2494       RemoveRidsFromSimulcastLayerList(to_remove, simulcast->send_layers());
2495   simulcast->receive_layers() =
2496       RemoveRidsFromSimulcastLayerList(to_remove, simulcast->receive_layers());
2497 }
2498 
2499 // RFC 3551
2500 //  PT   encoding    media type  clock rate   channels
2501 //                      name                    (Hz)
2502 //  0    PCMU        A            8,000       1
2503 //  1    reserved    A
2504 //  2    reserved    A
2505 //  3    GSM         A            8,000       1
2506 //  4    G723        A            8,000       1
2507 //  5    DVI4        A            8,000       1
2508 //  6    DVI4        A           16,000       1
2509 //  7    LPC         A            8,000       1
2510 //  8    PCMA        A            8,000       1
2511 //  9    G722        A            8,000       1
2512 //  10   L16         A           44,100       2
2513 //  11   L16         A           44,100       1
2514 //  12   QCELP       A            8,000       1
2515 //  13   CN          A            8,000       1
2516 //  14   MPA         A           90,000       (see text)
2517 //  15   G728        A            8,000       1
2518 //  16   DVI4        A           11,025       1
2519 //  17   DVI4        A           22,050       1
2520 //  18   G729        A            8,000       1
2521 struct StaticPayloadAudioCodec {
2522   const char* name;
2523   int clockrate;
2524   size_t channels;
2525 };
2526 static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2527     {"PCMU", 8000, 1},  {"reserved", 0, 0}, {"reserved", 0, 0},
2528     {"GSM", 8000, 1},   {"G723", 8000, 1},  {"DVI4", 8000, 1},
2529     {"DVI4", 16000, 1}, {"LPC", 8000, 1},   {"PCMA", 8000, 1},
2530     {"G722", 8000, 1},  {"L16", 44100, 2},  {"L16", 44100, 1},
2531     {"QCELP", 8000, 1}, {"CN", 8000, 1},    {"MPA", 90000, 1},
2532     {"G728", 8000, 1},  {"DVI4", 11025, 1}, {"DVI4", 22050, 1},
2533     {"G729", 8000, 1},
2534 };
2535 
MaybeCreateStaticPayloadAudioCodecs(const std::vector<int> & fmts,AudioContentDescription * media_desc)2536 void MaybeCreateStaticPayloadAudioCodecs(const std::vector<int>& fmts,
2537                                          AudioContentDescription* media_desc) {
2538   if (!media_desc) {
2539     return;
2540   }
2541   RTC_DCHECK(media_desc->codecs().empty());
2542   for (int payload_type : fmts) {
2543     if (!media_desc->HasCodec(payload_type) && payload_type >= 0 &&
2544         static_cast<uint32_t>(payload_type) <
2545             arraysize(kStaticPayloadAudioCodecs)) {
2546       std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2547       int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2548       size_t channels = kStaticPayloadAudioCodecs[payload_type].channels;
2549       media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2550                                                clock_rate, 0, channels));
2551     }
2552   }
2553 }
2554 
2555 template <class C>
ParseContentDescription(const std::string & message,const cricket::MediaType media_type,int mline_index,const std::string & protocol,const std::vector<int> & payload_types,size_t * pos,std::string * content_name,bool * bundle_only,int * msid_signaling,TransportDescription * transport,std::vector<std::unique_ptr<JsepIceCandidate>> * candidates,webrtc::SdpParseError * error)2556 static std::unique_ptr<C> ParseContentDescription(
2557     const std::string& message,
2558     const cricket::MediaType media_type,
2559     int mline_index,
2560     const std::string& protocol,
2561     const std::vector<int>& payload_types,
2562     size_t* pos,
2563     std::string* content_name,
2564     bool* bundle_only,
2565     int* msid_signaling,
2566     TransportDescription* transport,
2567     std::vector<std::unique_ptr<JsepIceCandidate>>* candidates,
2568     webrtc::SdpParseError* error) {
2569   auto media_desc = std::make_unique<C>();
2570   if (!ParseContent(message, media_type, mline_index, protocol, payload_types,
2571                     pos, content_name, bundle_only, msid_signaling,
2572                     media_desc.get(), transport, candidates, error)) {
2573     return nullptr;
2574   }
2575   // Sort the codecs according to the m-line fmt list.
2576   std::unordered_map<int, int> payload_type_preferences;
2577   // "size + 1" so that the lowest preference payload type has a preference of
2578   // 1, which is greater than the default (0) for payload types not in the fmt
2579   // list.
2580   int preference = static_cast<int>(payload_types.size() + 1);
2581   for (int pt : payload_types) {
2582     payload_type_preferences[pt] = preference--;
2583   }
2584   std::vector<typename C::CodecType> codecs = media_desc->codecs();
2585   absl::c_sort(
2586       codecs, [&payload_type_preferences](const typename C::CodecType& a,
2587                                           const typename C::CodecType& b) {
2588         return payload_type_preferences[a.id] > payload_type_preferences[b.id];
2589       });
2590   media_desc->set_codecs(codecs);
2591   return media_desc;
2592 }
2593 
ParseMediaDescription(const std::string & message,const TransportDescription & session_td,const RtpHeaderExtensions & session_extmaps,size_t * pos,const rtc::SocketAddress & session_connection_addr,cricket::SessionDescription * desc,std::vector<std::unique_ptr<JsepIceCandidate>> * candidates,SdpParseError * error)2594 bool ParseMediaDescription(
2595     const std::string& message,
2596     const TransportDescription& session_td,
2597     const RtpHeaderExtensions& session_extmaps,
2598     size_t* pos,
2599     const rtc::SocketAddress& session_connection_addr,
2600     cricket::SessionDescription* desc,
2601     std::vector<std::unique_ptr<JsepIceCandidate>>* candidates,
2602     SdpParseError* error) {
2603   RTC_DCHECK(desc != NULL);
2604   std::string line;
2605   int mline_index = -1;
2606   int msid_signaling = 0;
2607 
2608   // Zero or more media descriptions
2609   // RFC 4566
2610   // m=<media> <port> <proto> <fmt>
2611   while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2612     ++mline_index;
2613 
2614     std::vector<std::string> fields;
2615     rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
2616 
2617     const size_t expected_min_fields = 4;
2618     if (fields.size() < expected_min_fields) {
2619       return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2620     }
2621     bool port_rejected = false;
2622     // RFC 3264
2623     // To reject an offered stream, the port number in the corresponding stream
2624     // in the answer MUST be set to zero.
2625     if (fields[1] == kMediaPortRejected) {
2626       port_rejected = true;
2627     }
2628 
2629     int port = 0;
2630     if (!rtc::FromString<int>(fields[1], &port) || !IsValidPort(port)) {
2631       return ParseFailed(line, "The port number is invalid", error);
2632     }
2633     const std::string& protocol = fields[2];
2634 
2635     // <fmt>
2636     std::vector<int> payload_types;
2637     if (cricket::IsRtpProtocol(protocol)) {
2638       for (size_t j = 3; j < fields.size(); ++j) {
2639         int pl = 0;
2640         if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
2641           return false;
2642         }
2643         payload_types.push_back(pl);
2644       }
2645     }
2646 
2647     // Make a temporary TransportDescription based on |session_td|.
2648     // Some of this gets overwritten by ParseContent.
2649     TransportDescription transport(
2650         session_td.transport_options, session_td.ice_ufrag, session_td.ice_pwd,
2651         session_td.ice_mode, session_td.connection_role,
2652         session_td.identity_fingerprint.get());
2653 
2654     std::unique_ptr<MediaContentDescription> content;
2655     std::string content_name;
2656     bool bundle_only = false;
2657     int section_msid_signaling = 0;
2658     const std::string& media_type = fields[0];
2659     if (media_type == kMediaTypeVideo) {
2660       content = ParseContentDescription<VideoContentDescription>(
2661           message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2662           payload_types, pos, &content_name, &bundle_only,
2663           &section_msid_signaling, &transport, candidates, error);
2664     } else if (media_type == kMediaTypeAudio) {
2665       content = ParseContentDescription<AudioContentDescription>(
2666           message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2667           payload_types, pos, &content_name, &bundle_only,
2668           &section_msid_signaling, &transport, candidates, error);
2669     } else if (media_type == kMediaTypeData) {
2670       if (cricket::IsDtlsSctp(protocol)) {
2671         // The draft-03 format is:
2672         // m=application <port> DTLS/SCTP <sctp-port>...
2673         // use_sctpmap should be false.
2674         // The draft-26 format is:
2675         // m=application <port> UDP/DTLS/SCTP webrtc-datachannel
2676         // use_sctpmap should be false.
2677         auto data_desc = std::make_unique<SctpDataContentDescription>();
2678         // Default max message size is 64K
2679         // according to draft-ietf-mmusic-sctp-sdp-26
2680         data_desc->set_max_message_size(kDefaultSctpMaxMessageSize);
2681         int p;
2682         if (rtc::FromString(fields[3], &p)) {
2683           data_desc->set_port(p);
2684         } else if (fields[3] == kDefaultSctpmapProtocol) {
2685           data_desc->set_use_sctpmap(false);
2686         }
2687         if (!ParseContent(message, cricket::MEDIA_TYPE_DATA, mline_index,
2688                           protocol, payload_types, pos, &content_name,
2689                           &bundle_only, &section_msid_signaling,
2690                           data_desc.get(), &transport, candidates, error)) {
2691           return false;
2692         }
2693         data_desc->set_protocol(protocol);
2694         content = std::move(data_desc);
2695       } else {
2696         // RTP
2697         std::unique_ptr<RtpDataContentDescription> data_desc =
2698             ParseContentDescription<RtpDataContentDescription>(
2699                 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2700                 payload_types, pos, &content_name, &bundle_only,
2701                 &section_msid_signaling, &transport, candidates, error);
2702         content = std::move(data_desc);
2703       }
2704     } else {
2705       RTC_LOG(LS_WARNING) << "Unsupported media type: " << line;
2706       continue;
2707     }
2708     if (!content.get()) {
2709       // ParseContentDescription returns NULL if failed.
2710       return false;
2711     }
2712 
2713     msid_signaling |= section_msid_signaling;
2714 
2715     bool content_rejected = false;
2716     // A port of 0 is not interpreted as a rejected m= section when it's
2717     // used along with a=bundle-only.
2718     if (bundle_only) {
2719       if (!port_rejected) {
2720         // Usage of bundle-only with a nonzero port is unspecified. So just
2721         // ignore bundle-only if we see this.
2722         bundle_only = false;
2723         RTC_LOG(LS_WARNING)
2724             << "a=bundle-only attribute observed with a nonzero "
2725                "port; this usage is unspecified so the attribute is being "
2726                "ignored.";
2727       }
2728     } else {
2729       // If not using bundle-only, interpret port 0 in the normal way; the m=
2730       // section is being rejected.
2731       content_rejected = port_rejected;
2732     }
2733 
2734     if (cricket::IsRtpProtocol(protocol) && !content->as_sctp()) {
2735       content->set_protocol(protocol);
2736       // Set the extmap.
2737       if (!session_extmaps.empty() &&
2738           !content->rtp_header_extensions().empty()) {
2739         return ParseFailed("",
2740                            "The a=extmap MUST be either all session level or "
2741                            "all media level.",
2742                            error);
2743       }
2744       for (size_t i = 0; i < session_extmaps.size(); ++i) {
2745         content->AddRtpHeaderExtension(session_extmaps[i]);
2746       }
2747     } else if (content->as_sctp()) {
2748       // Do nothing, it's OK
2749     } else {
2750       RTC_LOG(LS_WARNING) << "Parse failed with unknown protocol " << protocol;
2751       return false;
2752     }
2753 
2754     // Use the session level connection address if the media level addresses are
2755     // not specified.
2756     rtc::SocketAddress address;
2757     address = content->connection_address().IsNil()
2758                   ? session_connection_addr
2759                   : content->connection_address();
2760     address.SetPort(port);
2761     content->set_connection_address(address);
2762 
2763     desc->AddContent(content_name,
2764                      cricket::IsDtlsSctp(protocol) ? MediaProtocolType::kSctp
2765                                                    : MediaProtocolType::kRtp,
2766                      content_rejected, bundle_only, std::move(content));
2767     // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2768     desc->AddTransportInfo(TransportInfo(content_name, transport));
2769   }
2770 
2771   desc->set_msid_signaling(msid_signaling);
2772 
2773   size_t end_of_message = message.size();
2774   if (mline_index == -1 && *pos != end_of_message) {
2775     ParseFailed(message, *pos, "Expects m line.", error);
2776     return false;
2777   }
2778   return true;
2779 }
2780 
VerifyCodec(const cricket::Codec & codec)2781 bool VerifyCodec(const cricket::Codec& codec) {
2782   // Codec has not been populated correctly unless the name has been set. This
2783   // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2784   // have a corresponding "rtpmap" line.
2785   return !codec.name.empty();
2786 }
2787 
VerifyAudioCodecs(const AudioContentDescription * audio_desc)2788 bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2789   return absl::c_all_of(audio_desc->codecs(), &VerifyCodec);
2790 }
2791 
VerifyVideoCodecs(const VideoContentDescription * video_desc)2792 bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2793   return absl::c_all_of(video_desc->codecs(), &VerifyCodec);
2794 }
2795 
AddParameters(const cricket::CodecParameterMap & parameters,cricket::Codec * codec)2796 void AddParameters(const cricket::CodecParameterMap& parameters,
2797                    cricket::Codec* codec) {
2798   for (const auto& entry : parameters) {
2799     const std::string& key = entry.first;
2800     const std::string& value = entry.second;
2801     codec->SetParam(key, value);
2802   }
2803 }
2804 
AddFeedbackParameter(const cricket::FeedbackParam & feedback_param,cricket::Codec * codec)2805 void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2806                           cricket::Codec* codec) {
2807   codec->AddFeedbackParam(feedback_param);
2808 }
2809 
AddFeedbackParameters(const cricket::FeedbackParams & feedback_params,cricket::Codec * codec)2810 void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2811                            cricket::Codec* codec) {
2812   for (const cricket::FeedbackParam& param : feedback_params.params()) {
2813     codec->AddFeedbackParam(param);
2814   }
2815 }
2816 
2817 // Gets the current codec setting associated with |payload_type|. If there
2818 // is no Codec associated with that payload type it returns an empty codec
2819 // with that payload type.
2820 template <class T>
GetCodecWithPayloadType(const std::vector<T> & codecs,int payload_type)2821 T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2822   const T* codec = FindCodecById(codecs, payload_type);
2823   if (codec)
2824     return *codec;
2825   // Return empty codec with |payload_type|.
2826   T ret_val;
2827   ret_val.id = payload_type;
2828   return ret_val;
2829 }
2830 
2831 // Updates or creates a new codec entry in the audio description.
2832 template <class T, class U>
AddOrReplaceCodec(MediaContentDescription * content_desc,const U & codec)2833 void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2834   T* desc = static_cast<T*>(content_desc);
2835   std::vector<U> codecs = desc->codecs();
2836   bool found = false;
2837   for (U& existing_codec : codecs) {
2838     if (codec.id == existing_codec.id) {
2839       // Overwrite existing codec with the new codec.
2840       existing_codec = codec;
2841       found = true;
2842       break;
2843     }
2844   }
2845   if (!found) {
2846     desc->AddCodec(codec);
2847     return;
2848   }
2849   desc->set_codecs(codecs);
2850 }
2851 
2852 // Adds or updates existing codec corresponding to |payload_type| according
2853 // to |parameters|.
2854 template <class T, class U>
UpdateCodec(MediaContentDescription * content_desc,int payload_type,const cricket::CodecParameterMap & parameters)2855 void UpdateCodec(MediaContentDescription* content_desc,
2856                  int payload_type,
2857                  const cricket::CodecParameterMap& parameters) {
2858   // Codec might already have been populated (from rtpmap).
2859   U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2860                                         payload_type);
2861   AddParameters(parameters, &new_codec);
2862   AddOrReplaceCodec<T, U>(content_desc, new_codec);
2863 }
2864 
2865 // Adds or updates existing codec corresponding to |payload_type| according
2866 // to |feedback_param|.
2867 template <class T, class U>
UpdateCodec(MediaContentDescription * content_desc,int payload_type,const cricket::FeedbackParam & feedback_param)2868 void UpdateCodec(MediaContentDescription* content_desc,
2869                  int payload_type,
2870                  const cricket::FeedbackParam& feedback_param) {
2871   // Codec might already have been populated (from rtpmap).
2872   U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2873                                         payload_type);
2874   AddFeedbackParameter(feedback_param, &new_codec);
2875   AddOrReplaceCodec<T, U>(content_desc, new_codec);
2876 }
2877 
2878 // Adds or updates existing video codec corresponding to |payload_type|
2879 // according to |packetization|.
UpdateVideoCodecPacketization(VideoContentDescription * video_desc,int payload_type,const std::string & packetization)2880 void UpdateVideoCodecPacketization(VideoContentDescription* video_desc,
2881                                    int payload_type,
2882                                    const std::string& packetization) {
2883   if (packetization != cricket::kPacketizationParamRaw) {
2884     // Ignore unsupported packetization attribute.
2885     return;
2886   }
2887 
2888   // Codec might already have been populated (from rtpmap).
2889   cricket::VideoCodec codec =
2890       GetCodecWithPayloadType(video_desc->codecs(), payload_type);
2891   codec.packetization = packetization;
2892   AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2893                                                                   codec);
2894 }
2895 
2896 template <class T>
PopWildcardCodec(std::vector<T> * codecs,T * wildcard_codec)2897 bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2898   for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
2899     if (iter->id == kWildcardPayloadType) {
2900       *wildcard_codec = *iter;
2901       codecs->erase(iter);
2902       return true;
2903     }
2904   }
2905   return false;
2906 }
2907 
2908 template <class T>
UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T> * desc)2909 void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2910   auto codecs = desc->codecs();
2911   T wildcard_codec;
2912   if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2913     return;
2914   }
2915   for (auto& codec : codecs) {
2916     AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2917   }
2918   desc->set_codecs(codecs);
2919 }
2920 
AddAudioAttribute(const std::string & name,const std::string & value,AudioContentDescription * audio_desc)2921 void AddAudioAttribute(const std::string& name,
2922                        const std::string& value,
2923                        AudioContentDescription* audio_desc) {
2924   if (value.empty()) {
2925     return;
2926   }
2927   std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2928   for (cricket::AudioCodec& codec : codecs) {
2929     codec.params[name] = value;
2930   }
2931   audio_desc->set_codecs(codecs);
2932 }
2933 
ParseContent(const std::string & message,const cricket::MediaType media_type,int mline_index,const std::string & protocol,const std::vector<int> & payload_types,size_t * pos,std::string * content_name,bool * bundle_only,int * msid_signaling,MediaContentDescription * media_desc,TransportDescription * transport,std::vector<std::unique_ptr<JsepIceCandidate>> * candidates,SdpParseError * error)2934 bool ParseContent(const std::string& message,
2935                   const cricket::MediaType media_type,
2936                   int mline_index,
2937                   const std::string& protocol,
2938                   const std::vector<int>& payload_types,
2939                   size_t* pos,
2940                   std::string* content_name,
2941                   bool* bundle_only,
2942                   int* msid_signaling,
2943                   MediaContentDescription* media_desc,
2944                   TransportDescription* transport,
2945                   std::vector<std::unique_ptr<JsepIceCandidate>>* candidates,
2946                   SdpParseError* error) {
2947   RTC_DCHECK(media_desc != NULL);
2948   RTC_DCHECK(content_name != NULL);
2949   RTC_DCHECK(transport != NULL);
2950 
2951   if (media_type == cricket::MEDIA_TYPE_AUDIO) {
2952     MaybeCreateStaticPayloadAudioCodecs(payload_types, media_desc->as_audio());
2953   }
2954 
2955   // The media level "ice-ufrag" and "ice-pwd".
2956   // The candidates before update the media level "ice-pwd" and "ice-ufrag".
2957   Candidates candidates_orig;
2958   std::string line;
2959   std::string mline_id;
2960   // Tracks created out of the ssrc attributes.
2961   StreamParamsVec tracks;
2962   SsrcInfoVec ssrc_infos;
2963   SsrcGroupVec ssrc_groups;
2964   std::string maxptime_as_string;
2965   std::string ptime_as_string;
2966   std::vector<std::string> stream_ids;
2967   std::string track_id;
2968   SdpSerializer deserializer;
2969   std::vector<RidDescription> rids;
2970   SimulcastDescription simulcast;
2971 
2972   // Loop until the next m line
2973   while (!IsLineType(message, kLineTypeMedia, *pos)) {
2974     if (!GetLine(message, pos, &line)) {
2975       if (*pos >= message.size()) {
2976         break;  // Done parsing
2977       } else {
2978         return ParseFailed(message, *pos, "Invalid SDP line.", error);
2979       }
2980     }
2981 
2982     // RFC 4566
2983     // b=* (zero or more bandwidth information lines)
2984     if (IsLineType(line, kLineTypeSessionBandwidth)) {
2985       std::string bandwidth;
2986       if (HasAttribute(line, kApplicationSpecificMaximum)) {
2987         if (!GetValue(line, kApplicationSpecificMaximum, &bandwidth, error)) {
2988           return false;
2989         } else {
2990           int b = 0;
2991           if (!GetValueFromString(line, bandwidth, &b, error)) {
2992             return false;
2993           }
2994           // TODO(deadbeef): Historically, applications may be setting a value
2995           // of -1 to mean "unset any previously set bandwidth limit", even
2996           // though ommitting the "b=AS" entirely will do just that. Once we've
2997           // transitioned applications to doing the right thing, it would be
2998           // better to treat this as a hard error instead of just ignoring it.
2999           if (b == -1) {
3000             RTC_LOG(LS_WARNING)
3001                 << "Ignoring \"b=AS:-1\"; will be treated as \"no "
3002                    "bandwidth limit\".";
3003             continue;
3004           }
3005           if (b < 0) {
3006             return ParseFailed(line, "b=AS value can't be negative.", error);
3007           }
3008           // We should never use more than the default bandwidth for RTP-based
3009           // data channels. Don't allow SDP to set the bandwidth, because
3010           // that would give JS the opportunity to "break the Internet".
3011           // See: https://code.google.com/p/chromium/issues/detail?id=280726
3012           if (media_type == cricket::MEDIA_TYPE_DATA &&
3013               cricket::IsRtpProtocol(protocol) &&
3014               b > cricket::kDataMaxBandwidth / 1000) {
3015             rtc::StringBuilder description;
3016             description << "RTP-based data channels may not send more than "
3017                         << cricket::kDataMaxBandwidth / 1000 << "kbps.";
3018             return ParseFailed(line, description.str(), error);
3019           }
3020           // Prevent integer overflow.
3021           b = std::min(b, INT_MAX / 1000);
3022           media_desc->set_bandwidth(b * 1000);
3023         }
3024       }
3025       continue;
3026     }
3027 
3028     // Parse the media level connection data.
3029     if (IsLineType(line, kLineTypeConnection)) {
3030       rtc::SocketAddress addr;
3031       if (!ParseConnectionData(line, &addr, error)) {
3032         return false;
3033       }
3034       media_desc->set_connection_address(addr);
3035       continue;
3036     }
3037 
3038     if (!IsLineType(line, kLineTypeAttributes)) {
3039       // TODO(deadbeef): Handle other lines if needed.
3040       RTC_LOG(LS_INFO) << "Ignored line: " << line;
3041       continue;
3042     }
3043 
3044     // Handle attributes common to SCTP and RTP.
3045     if (HasAttribute(line, kAttributeMid)) {
3046       // RFC 3388
3047       // mid-attribute      = "a=mid:" identification-tag
3048       // identification-tag = token
3049       // Use the mid identification-tag as the content name.
3050       if (!GetValue(line, kAttributeMid, &mline_id, error)) {
3051         return false;
3052       }
3053       *content_name = mline_id;
3054     } else if (HasAttribute(line, kAttributeBundleOnly)) {
3055       *bundle_only = true;
3056     } else if (HasAttribute(line, kAttributeCandidate)) {
3057       Candidate candidate;
3058       if (!ParseCandidate(line, &candidate, error, false)) {
3059         return false;
3060       }
3061       // ParseCandidate will parse non-standard ufrag and password attributes,
3062       // since it's used for candidate trickling, but we only want to process
3063       // the "a=ice-ufrag"/"a=ice-pwd" values in a session description, so
3064       // strip them off at this point.
3065       candidate.set_username(std::string());
3066       candidate.set_password(std::string());
3067       candidates_orig.push_back(candidate);
3068     } else if (HasAttribute(line, kAttributeIceUfrag)) {
3069       if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
3070         return false;
3071       }
3072     } else if (HasAttribute(line, kAttributeIcePwd)) {
3073       if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
3074         return false;
3075       }
3076     } else if (HasAttribute(line, kAttributeIceOption)) {
3077       if (!ParseIceOptions(line, &transport->transport_options, error)) {
3078         return false;
3079       }
3080     } else if (HasAttribute(line, kAttributeFmtp)) {
3081       if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
3082         return false;
3083       }
3084     } else if (HasAttribute(line, kAttributeFingerprint)) {
3085       std::unique_ptr<rtc::SSLFingerprint> fingerprint;
3086       if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
3087         return false;
3088       }
3089       transport->identity_fingerprint = std::move(fingerprint);
3090     } else if (HasAttribute(line, kAttributeSetup)) {
3091       if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
3092         return false;
3093       }
3094     } else if (cricket::IsDtlsSctp(protocol) &&
3095                HasAttribute(line, kAttributeSctpPort)) {
3096       if (media_type != cricket::MEDIA_TYPE_DATA) {
3097         return ParseFailed(
3098             line, "sctp-port attribute found in non-data media description.",
3099             error);
3100       }
3101       if (media_desc->as_sctp()->use_sctpmap()) {
3102         return ParseFailed(
3103             line, "sctp-port attribute can't be used with sctpmap.", error);
3104       }
3105       int sctp_port;
3106       if (!ParseSctpPort(line, &sctp_port, error)) {
3107         return false;
3108       }
3109       media_desc->as_sctp()->set_port(sctp_port);
3110     } else if (cricket::IsDtlsSctp(protocol) &&
3111                HasAttribute(line, kAttributeMaxMessageSize)) {
3112       if (media_type != cricket::MEDIA_TYPE_DATA) {
3113         return ParseFailed(
3114             line,
3115             "max-message-size attribute found in non-data media description.",
3116             error);
3117       }
3118       int max_message_size;
3119       if (!ParseSctpMaxMessageSize(line, &max_message_size, error)) {
3120         return false;
3121       }
3122       media_desc->as_sctp()->set_max_message_size(max_message_size);
3123     } else if (cricket::IsRtpProtocol(protocol)) {
3124       //
3125       // RTP specific attrubtes
3126       //
3127       if (HasAttribute(line, kAttributeRtcpMux)) {
3128         media_desc->set_rtcp_mux(true);
3129       } else if (HasAttribute(line, kAttributeRtcpReducedSize)) {
3130         media_desc->set_rtcp_reduced_size(true);
3131       } else if (HasAttribute(line, kAttributeRtcpRemoteEstimate)) {
3132         media_desc->set_remote_estimate(true);
3133       } else if (HasAttribute(line, kAttributeSsrcGroup)) {
3134         if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
3135           return false;
3136         }
3137       } else if (HasAttribute(line, kAttributeSsrc)) {
3138         if (!ParseSsrcAttribute(line, &ssrc_infos, msid_signaling, error)) {
3139           return false;
3140         }
3141       } else if (HasAttribute(line, kAttributeCrypto)) {
3142         if (!ParseCryptoAttribute(line, media_desc, error)) {
3143           return false;
3144         }
3145       } else if (HasAttribute(line, kAttributeRtpmap)) {
3146         if (!ParseRtpmapAttribute(line, media_type, payload_types, media_desc,
3147                                   error)) {
3148           return false;
3149         }
3150       } else if (HasAttribute(line, kCodecParamMaxPTime)) {
3151         if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
3152           return false;
3153         }
3154       } else if (HasAttribute(line, kAttributePacketization)) {
3155         if (!ParsePacketizationAttribute(line, media_type, media_desc, error)) {
3156           return false;
3157         }
3158       } else if (HasAttribute(line, kAttributeRtcpFb)) {
3159         if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
3160           return false;
3161         }
3162       } else if (HasAttribute(line, kCodecParamPTime)) {
3163         if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
3164           return false;
3165         }
3166       } else if (HasAttribute(line, kAttributeSendOnly)) {
3167         media_desc->set_direction(RtpTransceiverDirection::kSendOnly);
3168       } else if (HasAttribute(line, kAttributeRecvOnly)) {
3169         media_desc->set_direction(RtpTransceiverDirection::kRecvOnly);
3170       } else if (HasAttribute(line, kAttributeInactive)) {
3171         media_desc->set_direction(RtpTransceiverDirection::kInactive);
3172       } else if (HasAttribute(line, kAttributeSendRecv)) {
3173         media_desc->set_direction(RtpTransceiverDirection::kSendRecv);
3174       } else if (HasAttribute(line, kAttributeExtmapAllowMixed)) {
3175         media_desc->set_extmap_allow_mixed_enum(
3176             MediaContentDescription::kMedia);
3177       } else if (HasAttribute(line, kAttributeExtmap)) {
3178         RtpExtension extmap;
3179         if (!ParseExtmap(line, &extmap, error)) {
3180           return false;
3181         }
3182         media_desc->AddRtpHeaderExtension(extmap);
3183       } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
3184         // Experimental attribute.  Conference mode activates more aggressive
3185         // AEC and NS settings.
3186         // TODO(deadbeef): expose API to set these directly.
3187         std::string flag_value;
3188         if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
3189           return false;
3190         }
3191         if (flag_value.compare(kValueConference) == 0)
3192           media_desc->set_conference_mode(true);
3193       } else if (HasAttribute(line, kAttributeMsid)) {
3194         if (!ParseMsidAttribute(line, &stream_ids, &track_id, error)) {
3195           return false;
3196         }
3197         *msid_signaling |= cricket::kMsidSignalingMediaSection;
3198       } else if (HasAttribute(line, kAttributeRid)) {
3199         const size_t kRidPrefixLength =
3200             kLinePrefixLength + arraysize(kAttributeRid);
3201         if (line.size() <= kRidPrefixLength) {
3202           RTC_LOG(LS_INFO) << "Ignoring empty RID attribute: " << line;
3203           continue;
3204         }
3205         RTCErrorOr<RidDescription> error_or_rid_description =
3206             deserializer.DeserializeRidDescription(
3207                 line.substr(kRidPrefixLength));
3208 
3209         // Malformed a=rid lines are discarded.
3210         if (!error_or_rid_description.ok()) {
3211           RTC_LOG(LS_INFO) << "Ignoring malformed RID line: '" << line
3212                            << "'. Error: "
3213                            << error_or_rid_description.error().message();
3214           continue;
3215         }
3216 
3217         rids.push_back(error_or_rid_description.MoveValue());
3218       } else if (HasAttribute(line, kAttributeSimulcast)) {
3219         const size_t kSimulcastPrefixLength =
3220             kLinePrefixLength + arraysize(kAttributeSimulcast);
3221         if (line.size() <= kSimulcastPrefixLength) {
3222           return ParseFailed(line, "Simulcast attribute is empty.", error);
3223         }
3224 
3225         if (!simulcast.empty()) {
3226           return ParseFailed(line, "Multiple Simulcast attributes specified.",
3227                              error);
3228         }
3229 
3230         RTCErrorOr<SimulcastDescription> error_or_simulcast =
3231             deserializer.DeserializeSimulcastDescription(
3232                 line.substr(kSimulcastPrefixLength));
3233         if (!error_or_simulcast.ok()) {
3234           return ParseFailed(line,
3235                              std::string("Malformed simulcast line: ") +
3236                                  error_or_simulcast.error().message(),
3237                              error);
3238         }
3239 
3240         simulcast = error_or_simulcast.value();
3241       } else {
3242         // Unrecognized attribute in RTP protocol.
3243         RTC_LOG(LS_INFO) << "Ignored line: " << line;
3244         continue;
3245       }
3246     } else {
3247       // Only parse lines that we are interested of.
3248       RTC_LOG(LS_INFO) << "Ignored line: " << line;
3249       continue;
3250     }
3251   }
3252 
3253   // Remove duplicate or inconsistent rids.
3254   RemoveInvalidRidDescriptions(payload_types, &rids);
3255 
3256   // If simulcast is specifed, split the rids into send and receive.
3257   // Rids that do not appear in simulcast attribute will be removed.
3258   // If it is not specified, we assume that all rids are for send layers.
3259   std::vector<RidDescription> send_rids;
3260   std::vector<RidDescription> receive_rids;
3261   if (!simulcast.empty()) {
3262     // Verify that the rids in simulcast match rids in sdp.
3263     RemoveInvalidRidsFromSimulcast(rids, &simulcast);
3264 
3265     // Use simulcast description to figure out Send / Receive RIDs.
3266     std::map<std::string, RidDescription> rid_map;
3267     for (const RidDescription& rid : rids) {
3268       rid_map[rid.rid] = rid;
3269     }
3270 
3271     for (const auto& layer : simulcast.send_layers().GetAllLayers()) {
3272       auto iter = rid_map.find(layer.rid);
3273       RTC_DCHECK(iter != rid_map.end());
3274       send_rids.push_back(iter->second);
3275     }
3276 
3277     for (const auto& layer : simulcast.receive_layers().GetAllLayers()) {
3278       auto iter = rid_map.find(layer.rid);
3279       RTC_DCHECK(iter != rid_map.end());
3280       receive_rids.push_back(iter->second);
3281     }
3282 
3283     media_desc->set_simulcast_description(simulcast);
3284   } else {
3285     send_rids = rids;
3286   }
3287 
3288   media_desc->set_receive_rids(receive_rids);
3289 
3290   // Create tracks from the |ssrc_infos|.
3291   // If the stream_id/track_id for all SSRCS are identical, one StreamParams
3292   // will be created in CreateTracksFromSsrcInfos, containing all the SSRCs from
3293   // the m= section.
3294   if (!ssrc_infos.empty()) {
3295     CreateTracksFromSsrcInfos(ssrc_infos, stream_ids, track_id, &tracks,
3296                               *msid_signaling);
3297   } else if (media_type != cricket::MEDIA_TYPE_DATA &&
3298              (*msid_signaling & cricket::kMsidSignalingMediaSection)) {
3299     // If the stream_ids/track_id was signaled but SSRCs were unsignaled we
3300     // still create a track. This isn't done for data media types because
3301     // StreamParams aren't used for SCTP streams, and RTP data channels don't
3302     // support unsignaled SSRCs.
3303     CreateTrackWithNoSsrcs(stream_ids, track_id, send_rids, &tracks);
3304   }
3305 
3306   // Add the ssrc group to the track.
3307   for (const SsrcGroup& ssrc_group : ssrc_groups) {
3308     if (ssrc_group.ssrcs.empty()) {
3309       continue;
3310     }
3311     uint32_t ssrc = ssrc_group.ssrcs.front();
3312     for (StreamParams& track : tracks) {
3313       if (track.has_ssrc(ssrc)) {
3314         track.ssrc_groups.push_back(ssrc_group);
3315       }
3316     }
3317   }
3318 
3319   // Add the new tracks to the |media_desc|.
3320   for (StreamParams& track : tracks) {
3321     media_desc->AddStream(track);
3322   }
3323 
3324   if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3325     AudioContentDescription* audio_desc = media_desc->as_audio();
3326     UpdateFromWildcardCodecs(audio_desc);
3327 
3328     // Verify audio codec ensures that no audio codec has been populated with
3329     // only fmtp.
3330     if (!VerifyAudioCodecs(audio_desc)) {
3331       return ParseFailed("Failed to parse audio codecs correctly.", error);
3332     }
3333     AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
3334     AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
3335   }
3336 
3337   if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3338     VideoContentDescription* video_desc = media_desc->as_video();
3339     UpdateFromWildcardCodecs(video_desc);
3340     // Verify video codec ensures that no video codec has been populated with
3341     // only rtcp-fb.
3342     if (!VerifyVideoCodecs(video_desc)) {
3343       return ParseFailed("Failed to parse video codecs correctly.", error);
3344     }
3345   }
3346 
3347   // RFC 5245
3348   // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
3349   for (Candidate& candidate : candidates_orig) {
3350     RTC_DCHECK(candidate.username().empty() ||
3351                candidate.username() == transport->ice_ufrag);
3352     candidate.set_username(transport->ice_ufrag);
3353     RTC_DCHECK(candidate.password().empty());
3354     candidate.set_password(transport->ice_pwd);
3355     candidates->push_back(
3356         std::make_unique<JsepIceCandidate>(mline_id, mline_index, candidate));
3357   }
3358 
3359   return true;
3360 }
3361 
ParseSsrcAttribute(const std::string & line,SsrcInfoVec * ssrc_infos,int * msid_signaling,SdpParseError * error)3362 bool ParseSsrcAttribute(const std::string& line,
3363                         SsrcInfoVec* ssrc_infos,
3364                         int* msid_signaling,
3365                         SdpParseError* error) {
3366   RTC_DCHECK(ssrc_infos != NULL);
3367   // RFC 5576
3368   // a=ssrc:<ssrc-id> <attribute>
3369   // a=ssrc:<ssrc-id> <attribute>:<value>
3370   std::string field1, field2;
3371   if (!rtc::tokenize_first(line.substr(kLinePrefixLength),
3372                            kSdpDelimiterSpaceChar, &field1, &field2)) {
3373     const size_t expected_fields = 2;
3374     return ParseFailedExpectFieldNum(line, expected_fields, error);
3375   }
3376 
3377   // ssrc:<ssrc-id>
3378   std::string ssrc_id_s;
3379   if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
3380     return false;
3381   }
3382   uint32_t ssrc_id = 0;
3383   if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
3384     return false;
3385   }
3386 
3387   std::string attribute;
3388   std::string value;
3389   if (!rtc::tokenize_first(field2, kSdpDelimiterColonChar, &attribute,
3390                            &value)) {
3391     rtc::StringBuilder description;
3392     description << "Failed to get the ssrc attribute value from " << field2
3393                 << ". Expected format <attribute>:<value>.";
3394     return ParseFailed(line, description.str(), error);
3395   }
3396 
3397   // Check if there's already an item for this |ssrc_id|. Create a new one if
3398   // there isn't.
3399   auto ssrc_info_it =
3400       absl::c_find_if(*ssrc_infos, [ssrc_id](const SsrcInfo& ssrc_info) {
3401         return ssrc_info.ssrc_id == ssrc_id;
3402       });
3403   if (ssrc_info_it == ssrc_infos->end()) {
3404     SsrcInfo info;
3405     info.ssrc_id = ssrc_id;
3406     ssrc_infos->push_back(info);
3407     ssrc_info_it = ssrc_infos->end() - 1;
3408   }
3409   SsrcInfo& ssrc_info = *ssrc_info_it;
3410 
3411   // Store the info to the |ssrc_info|.
3412   if (attribute == kSsrcAttributeCname) {
3413     // RFC 5576
3414     // cname:<value>
3415     ssrc_info.cname = value;
3416   } else if (attribute == kSsrcAttributeMsid) {
3417     // draft-alvestrand-mmusic-msid-00
3418     // msid:identifier [appdata]
3419     std::vector<std::string> fields;
3420     rtc::split(value, kSdpDelimiterSpaceChar, &fields);
3421     if (fields.size() < 1 || fields.size() > 2) {
3422       return ParseFailed(
3423           line, "Expected format \"msid:<identifier>[ <appdata>]\".", error);
3424     }
3425     ssrc_info.stream_id = fields[0];
3426     if (fields.size() == 2) {
3427       ssrc_info.track_id = fields[1];
3428     }
3429     *msid_signaling |= cricket::kMsidSignalingSsrcAttribute;
3430   } else if (attribute == kSsrcAttributeMslabel) {
3431     // draft-alvestrand-rtcweb-mid-01
3432     // mslabel:<value>
3433     ssrc_info.mslabel = value;
3434   } else if (attribute == kSSrcAttributeLabel) {
3435     // The label isn't defined.
3436     // label:<value>
3437     ssrc_info.label = value;
3438   }
3439   return true;
3440 }
3441 
ParseSsrcGroupAttribute(const std::string & line,SsrcGroupVec * ssrc_groups,SdpParseError * error)3442 bool ParseSsrcGroupAttribute(const std::string& line,
3443                              SsrcGroupVec* ssrc_groups,
3444                              SdpParseError* error) {
3445   RTC_DCHECK(ssrc_groups != NULL);
3446   // RFC 5576
3447   // a=ssrc-group:<semantics> <ssrc-id> ...
3448   std::vector<std::string> fields;
3449   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
3450   const size_t expected_min_fields = 2;
3451   if (fields.size() < expected_min_fields) {
3452     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3453   }
3454   std::string semantics;
3455   if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
3456     return false;
3457   }
3458   std::vector<uint32_t> ssrcs;
3459   for (size_t i = 1; i < fields.size(); ++i) {
3460     uint32_t ssrc = 0;
3461     if (!GetValueFromString(line, fields[i], &ssrc, error)) {
3462       return false;
3463     }
3464     ssrcs.push_back(ssrc);
3465   }
3466   ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
3467   return true;
3468 }
3469 
ParseCryptoAttribute(const std::string & line,MediaContentDescription * media_desc,SdpParseError * error)3470 bool ParseCryptoAttribute(const std::string& line,
3471                           MediaContentDescription* media_desc,
3472                           SdpParseError* error) {
3473   std::vector<std::string> fields;
3474   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
3475   // RFC 4568
3476   // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
3477   const size_t expected_min_fields = 3;
3478   if (fields.size() < expected_min_fields) {
3479     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3480   }
3481   std::string tag_value;
3482   if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
3483     return false;
3484   }
3485   int tag = 0;
3486   if (!GetValueFromString(line, tag_value, &tag, error)) {
3487     return false;
3488   }
3489   const std::string& crypto_suite = fields[1];
3490   const std::string& key_params = fields[2];
3491   std::string session_params;
3492   if (fields.size() > 3) {
3493     session_params = fields[3];
3494   }
3495   media_desc->AddCrypto(
3496       CryptoParams(tag, crypto_suite, key_params, session_params));
3497   return true;
3498 }
3499 
3500 // Updates or creates a new codec entry in the audio description with according
3501 // to |name|, |clockrate|, |bitrate|, and |channels|.
UpdateCodec(int payload_type,const std::string & name,int clockrate,int bitrate,size_t channels,AudioContentDescription * audio_desc)3502 void UpdateCodec(int payload_type,
3503                  const std::string& name,
3504                  int clockrate,
3505                  int bitrate,
3506                  size_t channels,
3507                  AudioContentDescription* audio_desc) {
3508   // Codec may already be populated with (only) optional parameters
3509   // (from an fmtp).
3510   cricket::AudioCodec codec =
3511       GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
3512   codec.name = name;
3513   codec.clockrate = clockrate;
3514   codec.bitrate = bitrate;
3515   codec.channels = channels;
3516   AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
3517                                                                   codec);
3518 }
3519 
3520 // Updates or creates a new codec entry in the video description according to
3521 // |name|, |width|, |height|, and |framerate|.
UpdateCodec(int payload_type,const std::string & name,VideoContentDescription * video_desc)3522 void UpdateCodec(int payload_type,
3523                  const std::string& name,
3524                  VideoContentDescription* video_desc) {
3525   // Codec may already be populated with (only) optional parameters
3526   // (from an fmtp).
3527   cricket::VideoCodec codec =
3528       GetCodecWithPayloadType(video_desc->codecs(), payload_type);
3529   codec.name = name;
3530   AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
3531                                                                   codec);
3532 }
3533 
ParseRtpmapAttribute(const std::string & line,const cricket::MediaType media_type,const std::vector<int> & payload_types,MediaContentDescription * media_desc,SdpParseError * error)3534 bool ParseRtpmapAttribute(const std::string& line,
3535                           const cricket::MediaType media_type,
3536                           const std::vector<int>& payload_types,
3537                           MediaContentDescription* media_desc,
3538                           SdpParseError* error) {
3539   std::vector<std::string> fields;
3540   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
3541   // RFC 4566
3542   // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
3543   const size_t expected_min_fields = 2;
3544   if (fields.size() < expected_min_fields) {
3545     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3546   }
3547   std::string payload_type_value;
3548   if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
3549     return false;
3550   }
3551   int payload_type = 0;
3552   if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
3553                                 error)) {
3554     return false;
3555   }
3556 
3557   if (!absl::c_linear_search(payload_types, payload_type)) {
3558     RTC_LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
3559                            "<fmt> of the m-line: "
3560                         << line;
3561     return true;
3562   }
3563   const std::string& encoder = fields[1];
3564   std::vector<std::string> codec_params;
3565   rtc::split(encoder, '/', &codec_params);
3566   // <encoding name>/<clock rate>[/<encodingparameters>]
3567   // 2 mandatory fields
3568   if (codec_params.size() < 2 || codec_params.size() > 3) {
3569     return ParseFailed(line,
3570                        "Expected format \"<encoding name>/<clock rate>"
3571                        "[/<encodingparameters>]\".",
3572                        error);
3573   }
3574   const std::string& encoding_name = codec_params[0];
3575   int clock_rate = 0;
3576   if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
3577     return false;
3578   }
3579   if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3580     VideoContentDescription* video_desc = media_desc->as_video();
3581     UpdateCodec(payload_type, encoding_name, video_desc);
3582   } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3583     // RFC 4566
3584     // For audio streams, <encoding parameters> indicates the number
3585     // of audio channels.  This parameter is OPTIONAL and may be
3586     // omitted if the number of channels is one, provided that no
3587     // additional parameters are needed.
3588     size_t channels = 1;
3589     if (codec_params.size() == 3) {
3590       if (!GetValueFromString(line, codec_params[2], &channels, error)) {
3591         return false;
3592       }
3593     }
3594     AudioContentDescription* audio_desc = media_desc->as_audio();
3595     UpdateCodec(payload_type, encoding_name, clock_rate, 0, channels,
3596                 audio_desc);
3597   } else if (media_type == cricket::MEDIA_TYPE_DATA) {
3598     RtpDataContentDescription* data_desc = media_desc->as_rtp_data();
3599     if (data_desc) {
3600       data_desc->AddCodec(cricket::RtpDataCodec(payload_type, encoding_name));
3601     }
3602   }
3603   return true;
3604 }
3605 
ParseFmtpParam(const std::string & line,std::string * parameter,std::string * value,SdpParseError * error)3606 bool ParseFmtpParam(const std::string& line,
3607                     std::string* parameter,
3608                     std::string* value,
3609                     SdpParseError* error) {
3610   if (!rtc::tokenize_first(line, kSdpDelimiterEqualChar, parameter, value)) {
3611     // Support for non-key-value lines like RFC 2198 or RFC 4733.
3612     *parameter = "";
3613     *value = line;
3614     return true;
3615   }
3616   // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
3617   return true;
3618 }
3619 
ParseFmtpAttributes(const std::string & line,const cricket::MediaType media_type,MediaContentDescription * media_desc,SdpParseError * error)3620 bool ParseFmtpAttributes(const std::string& line,
3621                          const cricket::MediaType media_type,
3622                          MediaContentDescription* media_desc,
3623                          SdpParseError* error) {
3624   if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3625       media_type != cricket::MEDIA_TYPE_VIDEO) {
3626     return true;
3627   }
3628 
3629   std::string line_payload;
3630   std::string line_params;
3631 
3632   // https://tools.ietf.org/html/rfc4566#section-6
3633   // a=fmtp:<format> <format specific parameters>
3634   // At least two fields, whereas the second one is any of the optional
3635   // parameters.
3636   if (!rtc::tokenize_first(line.substr(kLinePrefixLength),
3637                            kSdpDelimiterSpaceChar, &line_payload,
3638                            &line_params)) {
3639     ParseFailedExpectMinFieldNum(line, 2, error);
3640     return false;
3641   }
3642 
3643   // Parse out the payload information.
3644   std::string payload_type_str;
3645   if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
3646     return false;
3647   }
3648 
3649   int payload_type = 0;
3650   if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3651                                 error)) {
3652     return false;
3653   }
3654 
3655   // Parse out format specific parameters.
3656   std::vector<std::string> fields;
3657   rtc::split(line_params, kSdpDelimiterSemicolonChar, &fields);
3658 
3659   cricket::CodecParameterMap codec_params;
3660   for (auto& iter : fields) {
3661     std::string name;
3662     std::string value;
3663     if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
3664       return false;
3665     }
3666     if (codec_params.find(name) != codec_params.end()) {
3667       RTC_LOG(LS_INFO) << "Overwriting duplicate fmtp parameter with key \""
3668                        << name << "\".";
3669     }
3670     codec_params[name] = value;
3671   }
3672 
3673   if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3674     UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3675         media_desc, payload_type, codec_params);
3676   } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3677     UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3678         media_desc, payload_type, codec_params);
3679   }
3680   return true;
3681 }
3682 
ParsePacketizationAttribute(const std::string & line,const cricket::MediaType media_type,MediaContentDescription * media_desc,SdpParseError * error)3683 bool ParsePacketizationAttribute(const std::string& line,
3684                                  const cricket::MediaType media_type,
3685                                  MediaContentDescription* media_desc,
3686                                  SdpParseError* error) {
3687   if (media_type != cricket::MEDIA_TYPE_VIDEO) {
3688     return true;
3689   }
3690   std::vector<std::string> packetization_fields;
3691   rtc::split(line.c_str(), kSdpDelimiterSpaceChar, &packetization_fields);
3692   if (packetization_fields.size() < 2) {
3693     return ParseFailedGetValue(line, kAttributePacketization, error);
3694   }
3695   std::string payload_type_string;
3696   if (!GetValue(packetization_fields[0], kAttributePacketization,
3697                 &payload_type_string, error)) {
3698     return false;
3699   }
3700   int payload_type;
3701   if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3702                                 error)) {
3703     return false;
3704   }
3705   std::string packetization = packetization_fields[1];
3706   UpdateVideoCodecPacketization(media_desc->as_video(), payload_type,
3707                                 packetization);
3708   return true;
3709 }
3710 
ParseRtcpFbAttribute(const std::string & line,const cricket::MediaType media_type,MediaContentDescription * media_desc,SdpParseError * error)3711 bool ParseRtcpFbAttribute(const std::string& line,
3712                           const cricket::MediaType media_type,
3713                           MediaContentDescription* media_desc,
3714                           SdpParseError* error) {
3715   if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3716       media_type != cricket::MEDIA_TYPE_VIDEO) {
3717     return true;
3718   }
3719   std::vector<std::string> rtcp_fb_fields;
3720   rtc::split(line.c_str(), kSdpDelimiterSpaceChar, &rtcp_fb_fields);
3721   if (rtcp_fb_fields.size() < 2) {
3722     return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3723   }
3724   std::string payload_type_string;
3725   if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3726                 error)) {
3727     return false;
3728   }
3729   int payload_type = kWildcardPayloadType;
3730   if (payload_type_string != "*") {
3731     if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3732                                   error)) {
3733       return false;
3734     }
3735   }
3736   std::string id = rtcp_fb_fields[1];
3737   std::string param = "";
3738   for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3739        iter != rtcp_fb_fields.end(); ++iter) {
3740     param.append(*iter);
3741   }
3742   const cricket::FeedbackParam feedback_param(id, param);
3743 
3744   if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3745     UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3746         media_desc, payload_type, feedback_param);
3747   } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3748     UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3749         media_desc, payload_type, feedback_param);
3750   }
3751   return true;
3752 }
3753 
3754 }  // namespace webrtc
3755