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