• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (c) 2014 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 "media/engine/webrtc_video_engine.h"
12 
13 #include <stdio.h>
14 
15 #include <algorithm>
16 #include <set>
17 #include <string>
18 #include <utility>
19 
20 #include "absl/algorithm/container.h"
21 #include "absl/strings/match.h"
22 #include "api/media_stream_interface.h"
23 #include "api/units/data_rate.h"
24 #include "api/video/video_codec_constants.h"
25 #include "api/video/video_codec_type.h"
26 #include "api/video_codecs/sdp_video_format.h"
27 #include "api/video_codecs/video_decoder_factory.h"
28 #include "api/video_codecs/video_encoder.h"
29 #include "api/video_codecs/video_encoder_factory.h"
30 #include "call/call.h"
31 #include "media/engine/simulcast.h"
32 #include "media/engine/webrtc_media_engine.h"
33 #include "media/engine/webrtc_voice_engine.h"
34 #include "rtc_base/copy_on_write_buffer.h"
35 #include "rtc_base/experiments/field_trial_parser.h"
36 #include "rtc_base/experiments/field_trial_units.h"
37 #include "rtc_base/experiments/min_video_bitrate_experiment.h"
38 #include "rtc_base/logging.h"
39 #include "rtc_base/numerics/safe_conversions.h"
40 #include "rtc_base/strings/string_builder.h"
41 #include "rtc_base/time_utils.h"
42 #include "rtc_base/trace_event.h"
43 #include "system_wrappers/include/field_trial.h"
44 
45 namespace cricket {
46 
47 namespace {
48 
49 const int kMinLayerSize = 16;
50 
StreamTypeToString(webrtc::VideoSendStream::StreamStats::StreamType type)51 const char* StreamTypeToString(
52     webrtc::VideoSendStream::StreamStats::StreamType type) {
53   switch (type) {
54     case webrtc::VideoSendStream::StreamStats::StreamType::kMedia:
55       return "kMedia";
56     case webrtc::VideoSendStream::StreamStats::StreamType::kRtx:
57       return "kRtx";
58     case webrtc::VideoSendStream::StreamStats::StreamType::kFlexfec:
59       return "kFlexfec";
60   }
61   return nullptr;
62 }
63 
64 // If this field trial is enabled, we will enable sending FlexFEC and disable
65 // sending ULPFEC whenever the former has been negotiated in the SDPs.
IsFlexfecFieldTrialEnabled()66 bool IsFlexfecFieldTrialEnabled() {
67   return webrtc::field_trial::IsEnabled("WebRTC-FlexFEC-03");
68 }
69 
70 // If this field trial is enabled, the "flexfec-03" codec will be advertised
71 // as being supported. This means that "flexfec-03" will appear in the default
72 // SDP offer, and we therefore need to be ready to receive FlexFEC packets from
73 // the remote. It also means that FlexFEC SSRCs will be generated by
74 // MediaSession and added as "a=ssrc:" and "a=ssrc-group:" lines in the local
75 // SDP.
IsFlexfecAdvertisedFieldTrialEnabled()76 bool IsFlexfecAdvertisedFieldTrialEnabled() {
77   return webrtc::field_trial::IsEnabled("WebRTC-FlexFEC-03-Advertised");
78 }
79 
AddDefaultFeedbackParams(VideoCodec * codec)80 void AddDefaultFeedbackParams(VideoCodec* codec) {
81   // Don't add any feedback params for RED and ULPFEC.
82   if (codec->name == kRedCodecName || codec->name == kUlpfecCodecName)
83     return;
84   codec->AddFeedbackParam(FeedbackParam(kRtcpFbParamRemb, kParamValueEmpty));
85   codec->AddFeedbackParam(
86       FeedbackParam(kRtcpFbParamTransportCc, kParamValueEmpty));
87   // Don't add any more feedback params for FLEXFEC.
88   if (codec->name == kFlexfecCodecName)
89     return;
90   codec->AddFeedbackParam(FeedbackParam(kRtcpFbParamCcm, kRtcpFbCcmParamFir));
91   codec->AddFeedbackParam(FeedbackParam(kRtcpFbParamNack, kParamValueEmpty));
92   codec->AddFeedbackParam(FeedbackParam(kRtcpFbParamNack, kRtcpFbNackParamPli));
93   if (codec->name == kVp8CodecName &&
94       webrtc::field_trial::IsEnabled("WebRTC-RtcpLossNotification")) {
95     codec->AddFeedbackParam(FeedbackParam(kRtcpFbParamLntf, kParamValueEmpty));
96   }
97 }
98 
99 // This function will assign dynamic payload types (in the range [96, 127]) to
100 // the input codecs, and also add ULPFEC, RED, FlexFEC, and associated RTX
101 // codecs for recognized codecs (VP8, VP9, H264, and RED). It will also add
102 // default feedback params to the codecs.
AssignPayloadTypesAndDefaultCodecs(std::vector<webrtc::SdpVideoFormat> input_formats)103 std::vector<VideoCodec> AssignPayloadTypesAndDefaultCodecs(
104     std::vector<webrtc::SdpVideoFormat> input_formats) {
105   if (input_formats.empty())
106     return std::vector<VideoCodec>();
107   static const int kFirstDynamicPayloadType = 96;
108   static const int kLastDynamicPayloadType = 127;
109   int payload_type = kFirstDynamicPayloadType;
110 
111   input_formats.push_back(webrtc::SdpVideoFormat(kRedCodecName));
112   input_formats.push_back(webrtc::SdpVideoFormat(kUlpfecCodecName));
113 
114   if (IsFlexfecAdvertisedFieldTrialEnabled()) {
115     webrtc::SdpVideoFormat flexfec_format(kFlexfecCodecName);
116     // This value is currently arbitrarily set to 10 seconds. (The unit
117     // is microseconds.) This parameter MUST be present in the SDP, but
118     // we never use the actual value anywhere in our code however.
119     // TODO(brandtr): Consider honouring this value in the sender and receiver.
120     flexfec_format.parameters = {{kFlexfecFmtpRepairWindow, "10000000"}};
121     input_formats.push_back(flexfec_format);
122   }
123 
124   std::vector<VideoCodec> output_codecs;
125   for (const webrtc::SdpVideoFormat& format : input_formats) {
126     VideoCodec codec(format);
127     codec.id = payload_type;
128     AddDefaultFeedbackParams(&codec);
129     output_codecs.push_back(codec);
130 
131     // Increment payload type.
132     ++payload_type;
133     if (payload_type > kLastDynamicPayloadType) {
134       RTC_LOG(LS_ERROR) << "Out of dynamic payload types, skipping the rest.";
135       break;
136     }
137 
138     // Add associated RTX codec for non-FEC codecs.
139     if (!absl::EqualsIgnoreCase(codec.name, kUlpfecCodecName) &&
140         !absl::EqualsIgnoreCase(codec.name, kFlexfecCodecName)) {
141       output_codecs.push_back(
142           VideoCodec::CreateRtxCodec(payload_type, codec.id));
143 
144       // Increment payload type.
145       ++payload_type;
146       if (payload_type > kLastDynamicPayloadType) {
147         RTC_LOG(LS_ERROR) << "Out of dynamic payload types, skipping the rest.";
148         break;
149       }
150     }
151   }
152   return output_codecs;
153 }
154 
155 // is_decoder_factory is needed to keep track of the implict assumption that any
156 // H264 decoder also supports constrained base line profile.
157 // TODO(kron): Perhaps it better to move the implcit knowledge to the place
158 // where codecs are negotiated.
159 template <class T>
GetPayloadTypesAndDefaultCodecs(const T * factory,bool is_decoder_factory)160 std::vector<VideoCodec> GetPayloadTypesAndDefaultCodecs(
161     const T* factory,
162     bool is_decoder_factory) {
163   if (!factory) {
164     return {};
165   }
166 
167   std::vector<webrtc::SdpVideoFormat> supported_formats =
168       factory->GetSupportedFormats();
169   if (is_decoder_factory) {
170     AddH264ConstrainedBaselineProfileToSupportedFormats(&supported_formats);
171   }
172 
173   return AssignPayloadTypesAndDefaultCodecs(std::move(supported_formats));
174 }
175 
IsTemporalLayersSupported(const std::string & codec_name)176 bool IsTemporalLayersSupported(const std::string& codec_name) {
177   return absl::EqualsIgnoreCase(codec_name, kVp8CodecName) ||
178          absl::EqualsIgnoreCase(codec_name, kVp9CodecName);
179 }
180 
CodecVectorToString(const std::vector<VideoCodec> & codecs)181 static std::string CodecVectorToString(const std::vector<VideoCodec>& codecs) {
182   rtc::StringBuilder out;
183   out << "{";
184   for (size_t i = 0; i < codecs.size(); ++i) {
185     out << codecs[i].ToString();
186     if (i != codecs.size() - 1) {
187       out << ", ";
188     }
189   }
190   out << "}";
191   return out.Release();
192 }
193 
ValidateCodecFormats(const std::vector<VideoCodec> & codecs)194 static bool ValidateCodecFormats(const std::vector<VideoCodec>& codecs) {
195   bool has_video = false;
196   for (size_t i = 0; i < codecs.size(); ++i) {
197     if (!codecs[i].ValidateCodecFormat()) {
198       return false;
199     }
200     if (codecs[i].GetCodecType() == VideoCodec::CODEC_VIDEO) {
201       has_video = true;
202     }
203   }
204   if (!has_video) {
205     RTC_LOG(LS_ERROR) << "Setting codecs without a video codec is invalid: "
206                       << CodecVectorToString(codecs);
207     return false;
208   }
209   return true;
210 }
211 
ValidateStreamParams(const StreamParams & sp)212 static bool ValidateStreamParams(const StreamParams& sp) {
213   if (sp.ssrcs.empty()) {
214     RTC_LOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString();
215     return false;
216   }
217 
218   std::vector<uint32_t> primary_ssrcs;
219   sp.GetPrimarySsrcs(&primary_ssrcs);
220   std::vector<uint32_t> rtx_ssrcs;
221   sp.GetFidSsrcs(primary_ssrcs, &rtx_ssrcs);
222   for (uint32_t rtx_ssrc : rtx_ssrcs) {
223     bool rtx_ssrc_present = false;
224     for (uint32_t sp_ssrc : sp.ssrcs) {
225       if (sp_ssrc == rtx_ssrc) {
226         rtx_ssrc_present = true;
227         break;
228       }
229     }
230     if (!rtx_ssrc_present) {
231       RTC_LOG(LS_ERROR) << "RTX SSRC '" << rtx_ssrc
232                         << "' missing from StreamParams ssrcs: "
233                         << sp.ToString();
234       return false;
235     }
236   }
237   if (!rtx_ssrcs.empty() && primary_ssrcs.size() != rtx_ssrcs.size()) {
238     RTC_LOG(LS_ERROR)
239         << "RTX SSRCs exist, but don't cover all SSRCs (unsupported): "
240         << sp.ToString();
241     return false;
242   }
243 
244   return true;
245 }
246 
247 // Returns true if the given codec is disallowed from doing simulcast.
IsCodecDisabledForSimulcast(const std::string & codec_name)248 bool IsCodecDisabledForSimulcast(const std::string& codec_name) {
249   return !webrtc::field_trial::IsDisabled("WebRTC-H264Simulcast")
250              ? absl::EqualsIgnoreCase(codec_name, kVp9CodecName)
251              : absl::EqualsIgnoreCase(codec_name, kH264CodecName) ||
252                    absl::EqualsIgnoreCase(codec_name, kVp9CodecName);
253 }
254 
255 // The selected thresholds for QVGA and VGA corresponded to a QP around 10.
256 // The change in QP declined above the selected bitrates.
GetMaxDefaultVideoBitrateKbps(int width,int height,bool is_screenshare)257 static int GetMaxDefaultVideoBitrateKbps(int width,
258                                          int height,
259                                          bool is_screenshare) {
260   int max_bitrate;
261   if (width * height <= 320 * 240) {
262     max_bitrate = 600;
263   } else if (width * height <= 640 * 480) {
264     max_bitrate = 1700;
265   } else if (width * height <= 960 * 540) {
266     max_bitrate = 2000;
267   } else {
268     max_bitrate = 2500;
269   }
270   if (is_screenshare)
271     max_bitrate = std::max(max_bitrate, 1200);
272   return max_bitrate;
273 }
274 
GetVp9LayersFromFieldTrialGroup(size_t * num_spatial_layers,size_t * num_temporal_layers)275 bool GetVp9LayersFromFieldTrialGroup(size_t* num_spatial_layers,
276                                      size_t* num_temporal_layers) {
277   std::string group = webrtc::field_trial::FindFullName("WebRTC-SupportVP9SVC");
278   if (group.empty())
279     return false;
280 
281   if (sscanf(group.c_str(), "EnabledByFlag_%zuSL%zuTL", num_spatial_layers,
282              num_temporal_layers) != 2) {
283     return false;
284   }
285   if (*num_spatial_layers > webrtc::kMaxSpatialLayers ||
286       *num_spatial_layers < 1)
287     return false;
288 
289   const size_t kMaxTemporalLayers = 3;
290   if (*num_temporal_layers > kMaxTemporalLayers || *num_temporal_layers < 1)
291     return false;
292 
293   return true;
294 }
295 
GetVp9SpatialLayersFromFieldTrial()296 absl::optional<size_t> GetVp9SpatialLayersFromFieldTrial() {
297   size_t num_sl;
298   size_t num_tl;
299   if (GetVp9LayersFromFieldTrialGroup(&num_sl, &num_tl)) {
300     return num_sl;
301   }
302   return absl::nullopt;
303 }
304 
GetVp9TemporalLayersFromFieldTrial()305 absl::optional<size_t> GetVp9TemporalLayersFromFieldTrial() {
306   size_t num_sl;
307   size_t num_tl;
308   if (GetVp9LayersFromFieldTrialGroup(&num_sl, &num_tl)) {
309     return num_tl;
310   }
311   return absl::nullopt;
312 }
313 
314 // Returns its smallest positive argument. If neither argument is positive,
315 // returns an arbitrary nonpositive value.
MinPositive(int a,int b)316 int MinPositive(int a, int b) {
317   if (a <= 0) {
318     return b;
319   }
320   if (b <= 0) {
321     return a;
322   }
323   return std::min(a, b);
324 }
325 
IsLayerActive(const webrtc::RtpEncodingParameters & layer)326 bool IsLayerActive(const webrtc::RtpEncodingParameters& layer) {
327   return layer.active &&
328          (!layer.max_bitrate_bps || *layer.max_bitrate_bps > 0) &&
329          (!layer.max_framerate || *layer.max_framerate > 0);
330 }
331 
FindRequiredActiveLayers(const webrtc::VideoEncoderConfig & encoder_config)332 size_t FindRequiredActiveLayers(
333     const webrtc::VideoEncoderConfig& encoder_config) {
334   // Need enough layers so that at least the first active one is present.
335   for (size_t i = 0; i < encoder_config.number_of_streams; ++i) {
336     if (encoder_config.simulcast_layers[i].active) {
337       return i + 1;
338     }
339   }
340   return 0;
341 }
342 
NumActiveStreams(const webrtc::RtpParameters & rtp_parameters)343 int NumActiveStreams(const webrtc::RtpParameters& rtp_parameters) {
344   int res = 0;
345   for (size_t i = 0; i < rtp_parameters.encodings.size(); ++i) {
346     if (rtp_parameters.encodings[i].active) {
347       ++res;
348     }
349   }
350   return res;
351 }
352 
353 std::map<uint32_t, webrtc::VideoSendStream::StreamStats>
MergeInfoAboutOutboundRtpSubstreams(const std::map<uint32_t,webrtc::VideoSendStream::StreamStats> & substreams)354 MergeInfoAboutOutboundRtpSubstreams(
355     const std::map<uint32_t, webrtc::VideoSendStream::StreamStats>&
356         substreams) {
357   std::map<uint32_t, webrtc::VideoSendStream::StreamStats> rtp_substreams;
358   // Add substreams for all RTP media streams.
359   for (const auto& pair : substreams) {
360     uint32_t ssrc = pair.first;
361     const webrtc::VideoSendStream::StreamStats& substream = pair.second;
362     switch (substream.type) {
363       case webrtc::VideoSendStream::StreamStats::StreamType::kMedia:
364         break;
365       case webrtc::VideoSendStream::StreamStats::StreamType::kRtx:
366       case webrtc::VideoSendStream::StreamStats::StreamType::kFlexfec:
367         continue;
368     }
369     rtp_substreams.insert(std::make_pair(ssrc, substream));
370   }
371   // Complement the kMedia substream stats with the associated kRtx and kFlexfec
372   // substream stats.
373   for (const auto& pair : substreams) {
374     switch (pair.second.type) {
375       case webrtc::VideoSendStream::StreamStats::StreamType::kMedia:
376         continue;
377       case webrtc::VideoSendStream::StreamStats::StreamType::kRtx:
378       case webrtc::VideoSendStream::StreamStats::StreamType::kFlexfec:
379         break;
380     }
381     // The associated substream is an RTX or FlexFEC substream that is
382     // referencing an RTP media substream.
383     const webrtc::VideoSendStream::StreamStats& associated_substream =
384         pair.second;
385     RTC_DCHECK(associated_substream.referenced_media_ssrc.has_value());
386     uint32_t media_ssrc = associated_substream.referenced_media_ssrc.value();
387     if (substreams.find(media_ssrc) == substreams.end()) {
388       RTC_LOG(LS_WARNING) << "Substream [ssrc: " << pair.first << ", type: "
389                           << StreamTypeToString(associated_substream.type)
390                           << "] is associated with a media ssrc (" << media_ssrc
391                           << ") that does not have StreamStats. Ignoring its "
392                           << "RTP stats.";
393       continue;
394     }
395     webrtc::VideoSendStream::StreamStats& rtp_substream =
396         rtp_substreams[media_ssrc];
397 
398     // We only merge |rtp_stats|. All other metrics are not applicable for RTX
399     // and FlexFEC.
400     // TODO(hbos): kRtx and kFlexfec stats should use a separate struct to make
401     // it clear what is or is not applicable.
402     rtp_substream.rtp_stats.Add(associated_substream.rtp_stats);
403   }
404   return rtp_substreams;
405 }
406 
407 }  // namespace
408 
409 // This constant is really an on/off, lower-level configurable NACK history
410 // duration hasn't been implemented.
411 static const int kNackHistoryMs = 1000;
412 
413 static const int kDefaultRtcpReceiverReportSsrc = 1;
414 
415 // Minimum time interval for logging stats.
416 static const int64_t kStatsLogIntervalMs = 10000;
417 
418 std::map<uint32_t, webrtc::VideoSendStream::StreamStats>
MergeInfoAboutOutboundRtpSubstreamsForTesting(const std::map<uint32_t,webrtc::VideoSendStream::StreamStats> & substreams)419 MergeInfoAboutOutboundRtpSubstreamsForTesting(
420     const std::map<uint32_t, webrtc::VideoSendStream::StreamStats>&
421         substreams) {
422   return MergeInfoAboutOutboundRtpSubstreams(substreams);
423 }
424 
425 rtc::scoped_refptr<webrtc::VideoEncoderConfig::EncoderSpecificSettings>
ConfigureVideoEncoderSettings(const VideoCodec & codec)426 WebRtcVideoChannel::WebRtcVideoSendStream::ConfigureVideoEncoderSettings(
427     const VideoCodec& codec) {
428   RTC_DCHECK_RUN_ON(&thread_checker_);
429   bool is_screencast = parameters_.options.is_screencast.value_or(false);
430   // No automatic resizing when using simulcast or screencast.
431   bool automatic_resize =
432       !is_screencast && (parameters_.config.rtp.ssrcs.size() == 1 ||
433                          NumActiveStreams(rtp_parameters_) == 1);
434   bool frame_dropping = !is_screencast;
435   bool denoising;
436   bool codec_default_denoising = false;
437   if (is_screencast) {
438     denoising = false;
439   } else {
440     // Use codec default if video_noise_reduction is unset.
441     codec_default_denoising = !parameters_.options.video_noise_reduction;
442     denoising = parameters_.options.video_noise_reduction.value_or(false);
443   }
444 
445   if (absl::EqualsIgnoreCase(codec.name, kH264CodecName)) {
446     webrtc::VideoCodecH264 h264_settings =
447         webrtc::VideoEncoder::GetDefaultH264Settings();
448     h264_settings.frameDroppingOn = frame_dropping;
449     return new rtc::RefCountedObject<
450         webrtc::VideoEncoderConfig::H264EncoderSpecificSettings>(h264_settings);
451   }
452   if (absl::EqualsIgnoreCase(codec.name, kVp8CodecName)) {
453     webrtc::VideoCodecVP8 vp8_settings =
454         webrtc::VideoEncoder::GetDefaultVp8Settings();
455     vp8_settings.automaticResizeOn = automatic_resize;
456     // VP8 denoising is enabled by default.
457     vp8_settings.denoisingOn = codec_default_denoising ? true : denoising;
458     vp8_settings.frameDroppingOn = frame_dropping;
459     return new rtc::RefCountedObject<
460         webrtc::VideoEncoderConfig::Vp8EncoderSpecificSettings>(vp8_settings);
461   }
462   if (absl::EqualsIgnoreCase(codec.name, kVp9CodecName)) {
463     webrtc::VideoCodecVP9 vp9_settings =
464         webrtc::VideoEncoder::GetDefaultVp9Settings();
465     const size_t default_num_spatial_layers =
466         parameters_.config.rtp.ssrcs.size();
467     const size_t num_spatial_layers =
468         GetVp9SpatialLayersFromFieldTrial().value_or(
469             default_num_spatial_layers);
470 
471     const size_t default_num_temporal_layers =
472         num_spatial_layers > 1 ? kConferenceDefaultNumTemporalLayers : 1;
473     const size_t num_temporal_layers =
474         GetVp9TemporalLayersFromFieldTrial().value_or(
475             default_num_temporal_layers);
476 
477     vp9_settings.numberOfSpatialLayers = std::min<unsigned char>(
478         num_spatial_layers, kConferenceMaxNumSpatialLayers);
479     vp9_settings.numberOfTemporalLayers = std::min<unsigned char>(
480         num_temporal_layers, kConferenceMaxNumTemporalLayers);
481 
482     // VP9 denoising is disabled by default.
483     vp9_settings.denoisingOn = codec_default_denoising ? true : denoising;
484     vp9_settings.automaticResizeOn = automatic_resize;
485     // Ensure frame dropping is always enabled.
486     RTC_DCHECK(vp9_settings.frameDroppingOn);
487     if (!is_screencast) {
488       webrtc::FieldTrialFlag interlayer_pred_experiment_enabled =
489           webrtc::FieldTrialFlag("Enabled");
490       webrtc::FieldTrialEnum<webrtc::InterLayerPredMode> inter_layer_pred_mode(
491           "inter_layer_pred_mode", webrtc::InterLayerPredMode::kOnKeyPic,
492           {{"off", webrtc::InterLayerPredMode::kOff},
493            {"on", webrtc::InterLayerPredMode::kOn},
494            {"onkeypic", webrtc::InterLayerPredMode::kOnKeyPic}});
495       webrtc::ParseFieldTrial(
496           {&interlayer_pred_experiment_enabled, &inter_layer_pred_mode},
497           webrtc::field_trial::FindFullName("WebRTC-Vp9InterLayerPred"));
498       if (interlayer_pred_experiment_enabled) {
499         vp9_settings.interLayerPred = inter_layer_pred_mode;
500       } else {
501         // Limit inter-layer prediction to key pictures by default.
502         vp9_settings.interLayerPred = webrtc::InterLayerPredMode::kOnKeyPic;
503       }
504     } else {
505       // Multiple spatial layers vp9 screenshare needs flexible mode.
506       vp9_settings.flexibleMode = vp9_settings.numberOfSpatialLayers > 1;
507       vp9_settings.interLayerPred = webrtc::InterLayerPredMode::kOn;
508     }
509     return new rtc::RefCountedObject<
510         webrtc::VideoEncoderConfig::Vp9EncoderSpecificSettings>(vp9_settings);
511   }
512   return nullptr;
513 }
514 
DefaultUnsignalledSsrcHandler()515 DefaultUnsignalledSsrcHandler::DefaultUnsignalledSsrcHandler()
516     : default_sink_(nullptr) {}
517 
OnUnsignalledSsrc(WebRtcVideoChannel * channel,uint32_t ssrc)518 UnsignalledSsrcHandler::Action DefaultUnsignalledSsrcHandler::OnUnsignalledSsrc(
519     WebRtcVideoChannel* channel,
520     uint32_t ssrc) {
521   absl::optional<uint32_t> default_recv_ssrc =
522       channel->GetDefaultReceiveStreamSsrc();
523 
524   if (default_recv_ssrc) {
525     RTC_LOG(LS_INFO) << "Destroying old default receive stream for SSRC="
526                      << ssrc << ".";
527     channel->RemoveRecvStream(*default_recv_ssrc);
528   }
529 
530   StreamParams sp = channel->unsignaled_stream_params();
531   sp.ssrcs.push_back(ssrc);
532 
533   RTC_LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc
534                    << ".";
535   if (!channel->AddRecvStream(sp, /*default_stream=*/true)) {
536     RTC_LOG(LS_WARNING) << "Could not create default receive stream.";
537   }
538 
539   // SSRC 0 returns default_recv_base_minimum_delay_ms.
540   const int unsignaled_ssrc = 0;
541   int default_recv_base_minimum_delay_ms =
542       channel->GetBaseMinimumPlayoutDelayMs(unsignaled_ssrc).value_or(0);
543   // Set base minimum delay if it was set before for the default receive stream.
544   channel->SetBaseMinimumPlayoutDelayMs(ssrc,
545                                         default_recv_base_minimum_delay_ms);
546   channel->SetSink(ssrc, default_sink_);
547   return kDeliverPacket;
548 }
549 
550 rtc::VideoSinkInterface<webrtc::VideoFrame>*
GetDefaultSink() const551 DefaultUnsignalledSsrcHandler::GetDefaultSink() const {
552   return default_sink_;
553 }
554 
SetDefaultSink(WebRtcVideoChannel * channel,rtc::VideoSinkInterface<webrtc::VideoFrame> * sink)555 void DefaultUnsignalledSsrcHandler::SetDefaultSink(
556     WebRtcVideoChannel* channel,
557     rtc::VideoSinkInterface<webrtc::VideoFrame>* sink) {
558   default_sink_ = sink;
559   absl::optional<uint32_t> default_recv_ssrc =
560       channel->GetDefaultReceiveStreamSsrc();
561   if (default_recv_ssrc) {
562     channel->SetSink(*default_recv_ssrc, default_sink_);
563   }
564 }
565 
WebRtcVideoEngine(std::unique_ptr<webrtc::VideoEncoderFactory> video_encoder_factory,std::unique_ptr<webrtc::VideoDecoderFactory> video_decoder_factory)566 WebRtcVideoEngine::WebRtcVideoEngine(
567     std::unique_ptr<webrtc::VideoEncoderFactory> video_encoder_factory,
568     std::unique_ptr<webrtc::VideoDecoderFactory> video_decoder_factory)
569     : decoder_factory_(std::move(video_decoder_factory)),
570       encoder_factory_(std::move(video_encoder_factory)) {
571   RTC_LOG(LS_INFO) << "WebRtcVideoEngine::WebRtcVideoEngine()";
572 }
573 
~WebRtcVideoEngine()574 WebRtcVideoEngine::~WebRtcVideoEngine() {
575   RTC_LOG(LS_INFO) << "WebRtcVideoEngine::~WebRtcVideoEngine";
576 }
577 
CreateMediaChannel(webrtc::Call * call,const MediaConfig & config,const VideoOptions & options,const webrtc::CryptoOptions & crypto_options,webrtc::VideoBitrateAllocatorFactory * video_bitrate_allocator_factory)578 VideoMediaChannel* WebRtcVideoEngine::CreateMediaChannel(
579     webrtc::Call* call,
580     const MediaConfig& config,
581     const VideoOptions& options,
582     const webrtc::CryptoOptions& crypto_options,
583     webrtc::VideoBitrateAllocatorFactory* video_bitrate_allocator_factory) {
584   RTC_LOG(LS_INFO) << "CreateMediaChannel. Options: " << options.ToString();
585   return new WebRtcVideoChannel(call, config, options, crypto_options,
586                                 encoder_factory_.get(), decoder_factory_.get(),
587                                 video_bitrate_allocator_factory);
588 }
send_codecs() const589 std::vector<VideoCodec> WebRtcVideoEngine::send_codecs() const {
590   return GetPayloadTypesAndDefaultCodecs(encoder_factory_.get(),
591                                          /*is_decoder_factory=*/false);
592 }
593 
recv_codecs() const594 std::vector<VideoCodec> WebRtcVideoEngine::recv_codecs() const {
595   return GetPayloadTypesAndDefaultCodecs(decoder_factory_.get(),
596                                          /*is_decoder_factory=*/true);
597 }
598 
599 std::vector<webrtc::RtpHeaderExtensionCapability>
GetRtpHeaderExtensions() const600 WebRtcVideoEngine::GetRtpHeaderExtensions() const {
601   std::vector<webrtc::RtpHeaderExtensionCapability> result;
602   int id = 1;
603   for (const auto& uri :
604        {webrtc::RtpExtension::kTimestampOffsetUri,
605         webrtc::RtpExtension::kAbsSendTimeUri,
606         webrtc::RtpExtension::kVideoRotationUri,
607         webrtc::RtpExtension::kTransportSequenceNumberUri,
608         webrtc::RtpExtension::kPlayoutDelayUri,
609         webrtc::RtpExtension::kVideoContentTypeUri,
610         webrtc::RtpExtension::kVideoTimingUri,
611         webrtc::RtpExtension::kColorSpaceUri, webrtc::RtpExtension::kMidUri,
612         webrtc::RtpExtension::kRidUri, webrtc::RtpExtension::kRepairedRidUri}) {
613     result.emplace_back(uri, id++, webrtc::RtpTransceiverDirection::kSendRecv);
614   }
615   result.emplace_back(
616       webrtc::RtpExtension::kGenericFrameDescriptorUri00, id,
617       webrtc::field_trial::IsEnabled("WebRTC-GenericDescriptorAdvertised")
618           ? webrtc::RtpTransceiverDirection::kSendRecv
619           : webrtc::RtpTransceiverDirection::kStopped);
620   return result;
621 }
622 
WebRtcVideoChannel(webrtc::Call * call,const MediaConfig & config,const VideoOptions & options,const webrtc::CryptoOptions & crypto_options,webrtc::VideoEncoderFactory * encoder_factory,webrtc::VideoDecoderFactory * decoder_factory,webrtc::VideoBitrateAllocatorFactory * bitrate_allocator_factory)623 WebRtcVideoChannel::WebRtcVideoChannel(
624     webrtc::Call* call,
625     const MediaConfig& config,
626     const VideoOptions& options,
627     const webrtc::CryptoOptions& crypto_options,
628     webrtc::VideoEncoderFactory* encoder_factory,
629     webrtc::VideoDecoderFactory* decoder_factory,
630     webrtc::VideoBitrateAllocatorFactory* bitrate_allocator_factory)
631     : VideoMediaChannel(config),
632       worker_thread_(rtc::Thread::Current()),
633       call_(call),
634       unsignalled_ssrc_handler_(&default_unsignalled_ssrc_handler_),
635       video_config_(config.video),
636       encoder_factory_(encoder_factory),
637       decoder_factory_(decoder_factory),
638       bitrate_allocator_factory_(bitrate_allocator_factory),
639       default_send_options_(options),
640       last_stats_log_ms_(-1),
641       discard_unknown_ssrc_packets_(webrtc::field_trial::IsEnabled(
642           "WebRTC-Video-DiscardPacketsWithUnknownSsrc")),
643       crypto_options_(crypto_options),
644       unknown_ssrc_packet_buffer_(
645           webrtc::field_trial::IsEnabled(
646               "WebRTC-Video-BufferPacketsWithUnknownSsrc")
647               ? new UnhandledPacketsBuffer()
648               : nullptr) {
649   RTC_DCHECK(thread_checker_.IsCurrent());
650 
651   rtcp_receiver_report_ssrc_ = kDefaultRtcpReceiverReportSsrc;
652   sending_ = false;
653   recv_codecs_ = MapCodecs(GetPayloadTypesAndDefaultCodecs(
654       decoder_factory_, /*is_decoder_factory=*/true));
655   recv_flexfec_payload_type_ =
656       recv_codecs_.empty() ? 0 : recv_codecs_.front().flexfec_payload_type;
657 }
658 
~WebRtcVideoChannel()659 WebRtcVideoChannel::~WebRtcVideoChannel() {
660   for (auto& kv : send_streams_)
661     delete kv.second;
662   for (auto& kv : receive_streams_)
663     delete kv.second;
664 }
665 
666 std::vector<WebRtcVideoChannel::VideoCodecSettings>
SelectSendVideoCodecs(const std::vector<VideoCodecSettings> & remote_mapped_codecs) const667 WebRtcVideoChannel::SelectSendVideoCodecs(
668     const std::vector<VideoCodecSettings>& remote_mapped_codecs) const {
669   std::vector<webrtc::SdpVideoFormat> sdp_formats =
670       encoder_factory_ ? encoder_factory_->GetImplementations()
671                        : std::vector<webrtc::SdpVideoFormat>();
672 
673   // The returned vector holds the VideoCodecSettings in term of preference.
674   // They are orderd by receive codec preference first and local implementation
675   // preference second.
676   std::vector<VideoCodecSettings> encoders;
677   for (const VideoCodecSettings& remote_codec : remote_mapped_codecs) {
678     for (auto format_it = sdp_formats.begin();
679          format_it != sdp_formats.end();) {
680       // For H264, we will limit the encode level to the remote offered level
681       // regardless if level asymmetry is allowed or not. This is strictly not
682       // following the spec in https://tools.ietf.org/html/rfc6184#section-8.2.2
683       // since we should limit the encode level to the lower of local and remote
684       // level when level asymmetry is not allowed.
685       if (IsSameCodec(format_it->name, format_it->parameters,
686                       remote_codec.codec.name, remote_codec.codec.params)) {
687         encoders.push_back(remote_codec);
688 
689         // To allow the VideoEncoderFactory to keep information about which
690         // implementation to instantitate when CreateEncoder is called the two
691         // parmeter sets are merged.
692         encoders.back().codec.params.insert(format_it->parameters.begin(),
693                                             format_it->parameters.end());
694 
695         format_it = sdp_formats.erase(format_it);
696       } else {
697         ++format_it;
698       }
699     }
700   }
701 
702   return encoders;
703 }
704 
NonFlexfecReceiveCodecsHaveChanged(std::vector<VideoCodecSettings> before,std::vector<VideoCodecSettings> after)705 bool WebRtcVideoChannel::NonFlexfecReceiveCodecsHaveChanged(
706     std::vector<VideoCodecSettings> before,
707     std::vector<VideoCodecSettings> after) {
708   // The receive codec order doesn't matter, so we sort the codecs before
709   // comparing. This is necessary because currently the
710   // only way to change the send codec is to munge SDP, which causes
711   // the receive codec list to change order, which causes the streams
712   // to be recreates which causes a "blink" of black video.  In order
713   // to support munging the SDP in this way without recreating receive
714   // streams, we ignore the order of the received codecs so that
715   // changing the order doesn't cause this "blink".
716   auto comparison = [](const VideoCodecSettings& codec1,
717                        const VideoCodecSettings& codec2) {
718     return codec1.codec.id > codec2.codec.id;
719   };
720   absl::c_sort(before, comparison);
721   absl::c_sort(after, comparison);
722 
723   // Changes in FlexFEC payload type are handled separately in
724   // WebRtcVideoChannel::GetChangedRecvParameters, so disregard FlexFEC in the
725   // comparison here.
726   return !absl::c_equal(before, after,
727                         VideoCodecSettings::EqualsDisregardingFlexfec);
728 }
729 
GetChangedSendParameters(const VideoSendParameters & params,ChangedSendParameters * changed_params) const730 bool WebRtcVideoChannel::GetChangedSendParameters(
731     const VideoSendParameters& params,
732     ChangedSendParameters* changed_params) const {
733   if (!ValidateCodecFormats(params.codecs) ||
734       !ValidateRtpExtensions(params.extensions)) {
735     return false;
736   }
737 
738   std::vector<VideoCodecSettings> negotiated_codecs =
739       SelectSendVideoCodecs(MapCodecs(params.codecs));
740 
741   // We should only fail here if send direction is enabled.
742   if (params.is_stream_active && negotiated_codecs.empty()) {
743     RTC_LOG(LS_ERROR) << "No video codecs supported.";
744     return false;
745   }
746 
747   // Never enable sending FlexFEC, unless we are in the experiment.
748   if (!IsFlexfecFieldTrialEnabled()) {
749     RTC_LOG(LS_INFO) << "WebRTC-FlexFEC-03 field trial is not enabled.";
750     for (VideoCodecSettings& codec : negotiated_codecs)
751       codec.flexfec_payload_type = -1;
752   }
753 
754   if (negotiated_codecs_ != negotiated_codecs) {
755     if (negotiated_codecs.empty()) {
756       changed_params->send_codec = absl::nullopt;
757     } else if (send_codec_ != negotiated_codecs.front()) {
758       changed_params->send_codec = negotiated_codecs.front();
759     }
760     changed_params->negotiated_codecs = std::move(negotiated_codecs);
761   }
762 
763   // Handle RTP header extensions.
764   if (params.extmap_allow_mixed != ExtmapAllowMixed()) {
765     changed_params->extmap_allow_mixed = params.extmap_allow_mixed;
766   }
767   std::vector<webrtc::RtpExtension> filtered_extensions = FilterRtpExtensions(
768       params.extensions, webrtc::RtpExtension::IsSupportedForVideo, true);
769   if (!send_rtp_extensions_ || (*send_rtp_extensions_ != filtered_extensions)) {
770     changed_params->rtp_header_extensions =
771         absl::optional<std::vector<webrtc::RtpExtension>>(filtered_extensions);
772   }
773 
774   if (params.mid != send_params_.mid) {
775     changed_params->mid = params.mid;
776   }
777 
778   // Handle max bitrate.
779   if (params.max_bandwidth_bps != send_params_.max_bandwidth_bps &&
780       params.max_bandwidth_bps >= -1) {
781     // 0 or -1 uncaps max bitrate.
782     // TODO(pbos): Reconsider how 0 should be treated. It is not mentioned as a
783     // special value and might very well be used for stopping sending.
784     changed_params->max_bandwidth_bps =
785         params.max_bandwidth_bps == 0 ? -1 : params.max_bandwidth_bps;
786   }
787 
788   // Handle conference mode.
789   if (params.conference_mode != send_params_.conference_mode) {
790     changed_params->conference_mode = params.conference_mode;
791   }
792 
793   // Handle RTCP mode.
794   if (params.rtcp.reduced_size != send_params_.rtcp.reduced_size) {
795     changed_params->rtcp_mode = params.rtcp.reduced_size
796                                     ? webrtc::RtcpMode::kReducedSize
797                                     : webrtc::RtcpMode::kCompound;
798   }
799 
800   return true;
801 }
802 
SetSendParameters(const VideoSendParameters & params)803 bool WebRtcVideoChannel::SetSendParameters(const VideoSendParameters& params) {
804   RTC_DCHECK_RUN_ON(&thread_checker_);
805   TRACE_EVENT0("webrtc", "WebRtcVideoChannel::SetSendParameters");
806   RTC_LOG(LS_INFO) << "SetSendParameters: " << params.ToString();
807   ChangedSendParameters changed_params;
808   if (!GetChangedSendParameters(params, &changed_params)) {
809     return false;
810   }
811 
812   if (changed_params.negotiated_codecs) {
813     for (const auto& send_codec : *changed_params.negotiated_codecs)
814       RTC_LOG(LS_INFO) << "Negotiated codec: " << send_codec.codec.ToString();
815   }
816 
817   send_params_ = params;
818   return ApplyChangedParams(changed_params);
819 }
820 
RequestEncoderFallback()821 void WebRtcVideoChannel::RequestEncoderFallback() {
822   invoker_.AsyncInvoke<void>(
823       RTC_FROM_HERE, worker_thread_, [this] {
824         RTC_DCHECK_RUN_ON(&thread_checker_);
825         if (negotiated_codecs_.size() <= 1) {
826           RTC_LOG(LS_WARNING)
827               << "Encoder failed but no fallback codec is available";
828           return;
829         }
830 
831         ChangedSendParameters params;
832         params.negotiated_codecs = negotiated_codecs_;
833         params.negotiated_codecs->erase(params.negotiated_codecs->begin());
834         params.send_codec = params.negotiated_codecs->front();
835         ApplyChangedParams(params);
836       });
837 }
838 
RequestEncoderSwitch(const EncoderSwitchRequestCallback::Config & conf)839 void WebRtcVideoChannel::RequestEncoderSwitch(
840     const EncoderSwitchRequestCallback::Config& conf) {
841   invoker_.AsyncInvoke<void>(RTC_FROM_HERE, worker_thread_, [this, conf] {
842     RTC_DCHECK_RUN_ON(&thread_checker_);
843 
844     if (!allow_codec_switching_) {
845       RTC_LOG(LS_INFO) << "Encoder switch requested but codec switching has"
846                           " not been enabled yet.";
847       requested_encoder_switch_ = conf;
848       return;
849     }
850 
851     for (const VideoCodecSettings& codec_setting : negotiated_codecs_) {
852       if (codec_setting.codec.name == conf.codec_name) {
853         if (conf.param) {
854           auto it = codec_setting.codec.params.find(*conf.param);
855 
856           if (it == codec_setting.codec.params.end()) {
857             continue;
858           }
859 
860           if (conf.value && it->second != *conf.value) {
861             continue;
862           }
863         }
864 
865         if (send_codec_ == codec_setting) {
866           // Already using this codec, no switch required.
867           return;
868         }
869 
870         ChangedSendParameters params;
871         params.send_codec = codec_setting;
872         ApplyChangedParams(params);
873         return;
874       }
875     }
876 
877     RTC_LOG(LS_WARNING) << "Requested encoder with codec_name:"
878                         << conf.codec_name
879                         << ", param:" << conf.param.value_or("none")
880                         << " and value:" << conf.value.value_or("none")
881                         << "not found. No switch performed.";
882   });
883 }
884 
RequestEncoderSwitch(const webrtc::SdpVideoFormat & format)885 void WebRtcVideoChannel::RequestEncoderSwitch(
886     const webrtc::SdpVideoFormat& format) {
887   invoker_.AsyncInvoke<void>(RTC_FROM_HERE, worker_thread_, [this, format] {
888     RTC_DCHECK_RUN_ON(&thread_checker_);
889 
890     for (const VideoCodecSettings& codec_setting : negotiated_codecs_) {
891       if (IsSameCodec(format.name, format.parameters, codec_setting.codec.name,
892                       codec_setting.codec.params)) {
893         VideoCodecSettings new_codec_setting = codec_setting;
894         for (const auto& kv : format.parameters) {
895           new_codec_setting.codec.params[kv.first] = kv.second;
896         }
897 
898         if (send_codec_ == new_codec_setting) {
899           // Already using this codec, no switch required.
900           return;
901         }
902 
903         ChangedSendParameters params;
904         params.send_codec = new_codec_setting;
905         ApplyChangedParams(params);
906         return;
907       }
908     }
909 
910     RTC_LOG(LS_WARNING) << "Encoder switch failed: SdpVideoFormat "
911                         << format.ToString() << " not negotiated.";
912   });
913 }
914 
ApplyChangedParams(const ChangedSendParameters & changed_params)915 bool WebRtcVideoChannel::ApplyChangedParams(
916     const ChangedSendParameters& changed_params) {
917   RTC_DCHECK_RUN_ON(&thread_checker_);
918   if (changed_params.negotiated_codecs)
919     negotiated_codecs_ = *changed_params.negotiated_codecs;
920 
921   if (changed_params.send_codec)
922     send_codec_ = changed_params.send_codec;
923 
924   if (changed_params.extmap_allow_mixed) {
925     SetExtmapAllowMixed(*changed_params.extmap_allow_mixed);
926   }
927   if (changed_params.rtp_header_extensions) {
928     send_rtp_extensions_ = changed_params.rtp_header_extensions;
929   }
930 
931   if (changed_params.send_codec || changed_params.max_bandwidth_bps) {
932     if (send_params_.max_bandwidth_bps == -1) {
933       // Unset the global max bitrate (max_bitrate_bps) if max_bandwidth_bps is
934       // -1, which corresponds to no "b=AS" attribute in SDP. Note that the
935       // global max bitrate may be set below in GetBitrateConfigForCodec, from
936       // the codec max bitrate.
937       // TODO(pbos): This should be reconsidered (codec max bitrate should
938       // probably not affect global call max bitrate).
939       bitrate_config_.max_bitrate_bps = -1;
940     }
941 
942     if (send_codec_) {
943       // TODO(holmer): Changing the codec parameters shouldn't necessarily mean
944       // that we change the min/max of bandwidth estimation. Reevaluate this.
945       bitrate_config_ = GetBitrateConfigForCodec(send_codec_->codec);
946       if (!changed_params.send_codec) {
947         // If the codec isn't changing, set the start bitrate to -1 which means
948         // "unchanged" so that BWE isn't affected.
949         bitrate_config_.start_bitrate_bps = -1;
950       }
951     }
952 
953     if (send_params_.max_bandwidth_bps >= 0) {
954       // Note that max_bandwidth_bps intentionally takes priority over the
955       // bitrate config for the codec. This allows FEC to be applied above the
956       // codec target bitrate.
957       // TODO(pbos): Figure out whether b=AS means max bitrate for this
958       // WebRtcVideoChannel (in which case we're good), or per sender (SSRC),
959       // in which case this should not set a BitrateConstraints but rather
960       // reconfigure all senders.
961       bitrate_config_.max_bitrate_bps = send_params_.max_bandwidth_bps == 0
962                                             ? -1
963                                             : send_params_.max_bandwidth_bps;
964     }
965 
966     call_->GetTransportControllerSend()->SetSdpBitrateParameters(
967         bitrate_config_);
968   }
969 
970   for (auto& kv : send_streams_) {
971     kv.second->SetSendParameters(changed_params);
972   }
973   if (changed_params.send_codec || changed_params.rtcp_mode) {
974     // Update receive feedback parameters from new codec or RTCP mode.
975     RTC_LOG(LS_INFO)
976         << "SetFeedbackOptions on all the receive streams because the send "
977            "codec or RTCP mode has changed.";
978     for (auto& kv : receive_streams_) {
979       RTC_DCHECK(kv.second != nullptr);
980       kv.second->SetFeedbackParameters(
981           HasLntf(send_codec_->codec), HasNack(send_codec_->codec),
982           HasTransportCc(send_codec_->codec),
983           send_params_.rtcp.reduced_size ? webrtc::RtcpMode::kReducedSize
984                                          : webrtc::RtcpMode::kCompound);
985     }
986   }
987   return true;
988 }
989 
GetRtpSendParameters(uint32_t ssrc) const990 webrtc::RtpParameters WebRtcVideoChannel::GetRtpSendParameters(
991     uint32_t ssrc) const {
992   RTC_DCHECK_RUN_ON(&thread_checker_);
993   auto it = send_streams_.find(ssrc);
994   if (it == send_streams_.end()) {
995     RTC_LOG(LS_WARNING) << "Attempting to get RTP send parameters for stream "
996                            "with ssrc "
997                         << ssrc << " which doesn't exist.";
998     return webrtc::RtpParameters();
999   }
1000 
1001   webrtc::RtpParameters rtp_params = it->second->GetRtpParameters();
1002   // Need to add the common list of codecs to the send stream-specific
1003   // RTP parameters.
1004   for (const VideoCodec& codec : send_params_.codecs) {
1005     rtp_params.codecs.push_back(codec.ToCodecParameters());
1006   }
1007   return rtp_params;
1008 }
1009 
SetRtpSendParameters(uint32_t ssrc,const webrtc::RtpParameters & parameters)1010 webrtc::RTCError WebRtcVideoChannel::SetRtpSendParameters(
1011     uint32_t ssrc,
1012     const webrtc::RtpParameters& parameters) {
1013   RTC_DCHECK_RUN_ON(&thread_checker_);
1014   TRACE_EVENT0("webrtc", "WebRtcVideoChannel::SetRtpSendParameters");
1015   auto it = send_streams_.find(ssrc);
1016   if (it == send_streams_.end()) {
1017     RTC_LOG(LS_ERROR) << "Attempting to set RTP send parameters for stream "
1018                          "with ssrc "
1019                       << ssrc << " which doesn't exist.";
1020     return webrtc::RTCError(webrtc::RTCErrorType::INTERNAL_ERROR);
1021   }
1022 
1023   // TODO(deadbeef): Handle setting parameters with a list of codecs in a
1024   // different order (which should change the send codec).
1025   webrtc::RtpParameters current_parameters = GetRtpSendParameters(ssrc);
1026   if (current_parameters.codecs != parameters.codecs) {
1027     RTC_DLOG(LS_ERROR) << "Using SetParameters to change the set of codecs "
1028                           "is not currently supported.";
1029     return webrtc::RTCError(webrtc::RTCErrorType::INTERNAL_ERROR);
1030   }
1031 
1032   if (!parameters.encodings.empty()) {
1033     // Note that these values come from:
1034     // https://tools.ietf.org/html/draft-ietf-tsvwg-rtcweb-qos-16#section-5
1035     // TODO(deadbeef): Change values depending on whether we are sending a
1036     // keyframe or non-keyframe.
1037     rtc::DiffServCodePoint new_dscp = rtc::DSCP_DEFAULT;
1038     switch (parameters.encodings[0].network_priority) {
1039       case webrtc::Priority::kVeryLow:
1040         new_dscp = rtc::DSCP_CS1;
1041         break;
1042       case webrtc::Priority::kLow:
1043         new_dscp = rtc::DSCP_DEFAULT;
1044         break;
1045       case webrtc::Priority::kMedium:
1046         new_dscp = rtc::DSCP_AF42;
1047         break;
1048       case webrtc::Priority::kHigh:
1049         new_dscp = rtc::DSCP_AF41;
1050         break;
1051     }
1052     SetPreferredDscp(new_dscp);
1053   }
1054 
1055   return it->second->SetRtpParameters(parameters);
1056 }
1057 
GetRtpReceiveParameters(uint32_t ssrc) const1058 webrtc::RtpParameters WebRtcVideoChannel::GetRtpReceiveParameters(
1059     uint32_t ssrc) const {
1060   RTC_DCHECK_RUN_ON(&thread_checker_);
1061   webrtc::RtpParameters rtp_params;
1062   auto it = receive_streams_.find(ssrc);
1063   if (it == receive_streams_.end()) {
1064     RTC_LOG(LS_WARNING)
1065         << "Attempting to get RTP receive parameters for stream "
1066            "with SSRC "
1067         << ssrc << " which doesn't exist.";
1068     return webrtc::RtpParameters();
1069   }
1070   rtp_params = it->second->GetRtpParameters();
1071 
1072   // Add codecs, which any stream is prepared to receive.
1073   for (const VideoCodec& codec : recv_params_.codecs) {
1074     rtp_params.codecs.push_back(codec.ToCodecParameters());
1075   }
1076 
1077   return rtp_params;
1078 }
1079 
GetDefaultRtpReceiveParameters() const1080 webrtc::RtpParameters WebRtcVideoChannel::GetDefaultRtpReceiveParameters()
1081     const {
1082   RTC_DCHECK_RUN_ON(&thread_checker_);
1083   webrtc::RtpParameters rtp_params;
1084   if (!default_unsignalled_ssrc_handler_.GetDefaultSink()) {
1085     RTC_LOG(LS_WARNING) << "Attempting to get RTP parameters for the default, "
1086                            "unsignaled video receive stream, but not yet "
1087                            "configured to receive such a stream.";
1088     return rtp_params;
1089   }
1090   rtp_params.encodings.emplace_back();
1091 
1092   // Add codecs, which any stream is prepared to receive.
1093   for (const VideoCodec& codec : recv_params_.codecs) {
1094     rtp_params.codecs.push_back(codec.ToCodecParameters());
1095   }
1096 
1097   return rtp_params;
1098 }
1099 
GetChangedRecvParameters(const VideoRecvParameters & params,ChangedRecvParameters * changed_params) const1100 bool WebRtcVideoChannel::GetChangedRecvParameters(
1101     const VideoRecvParameters& params,
1102     ChangedRecvParameters* changed_params) const {
1103   if (!ValidateCodecFormats(params.codecs) ||
1104       !ValidateRtpExtensions(params.extensions)) {
1105     return false;
1106   }
1107 
1108   // Handle receive codecs.
1109   const std::vector<VideoCodecSettings> mapped_codecs =
1110       MapCodecs(params.codecs);
1111   if (mapped_codecs.empty()) {
1112     RTC_LOG(LS_ERROR) << "SetRecvParameters called without any video codecs.";
1113     return false;
1114   }
1115 
1116   // Verify that every mapped codec is supported locally.
1117   if (params.is_stream_active) {
1118     const std::vector<VideoCodec> local_supported_codecs =
1119         GetPayloadTypesAndDefaultCodecs(decoder_factory_,
1120                                         /*is_decoder_factory=*/true);
1121     for (const VideoCodecSettings& mapped_codec : mapped_codecs) {
1122       if (!FindMatchingCodec(local_supported_codecs, mapped_codec.codec)) {
1123         RTC_LOG(LS_ERROR)
1124             << "SetRecvParameters called with unsupported video codec: "
1125             << mapped_codec.codec.ToString();
1126         return false;
1127       }
1128     }
1129   }
1130 
1131   if (NonFlexfecReceiveCodecsHaveChanged(recv_codecs_, mapped_codecs)) {
1132     changed_params->codec_settings =
1133         absl::optional<std::vector<VideoCodecSettings>>(mapped_codecs);
1134   }
1135 
1136   // Handle RTP header extensions.
1137   std::vector<webrtc::RtpExtension> filtered_extensions = FilterRtpExtensions(
1138       params.extensions, webrtc::RtpExtension::IsSupportedForVideo, false);
1139   if (filtered_extensions != recv_rtp_extensions_) {
1140     changed_params->rtp_header_extensions =
1141         absl::optional<std::vector<webrtc::RtpExtension>>(filtered_extensions);
1142   }
1143 
1144   int flexfec_payload_type = mapped_codecs.front().flexfec_payload_type;
1145   if (flexfec_payload_type != recv_flexfec_payload_type_) {
1146     changed_params->flexfec_payload_type = flexfec_payload_type;
1147   }
1148 
1149   return true;
1150 }
1151 
SetRecvParameters(const VideoRecvParameters & params)1152 bool WebRtcVideoChannel::SetRecvParameters(const VideoRecvParameters& params) {
1153   RTC_DCHECK_RUN_ON(&thread_checker_);
1154   TRACE_EVENT0("webrtc", "WebRtcVideoChannel::SetRecvParameters");
1155   RTC_LOG(LS_INFO) << "SetRecvParameters: " << params.ToString();
1156   ChangedRecvParameters changed_params;
1157   if (!GetChangedRecvParameters(params, &changed_params)) {
1158     return false;
1159   }
1160   if (changed_params.flexfec_payload_type) {
1161     RTC_LOG(LS_INFO) << "Changing FlexFEC payload type (recv) from "
1162                      << recv_flexfec_payload_type_ << " to "
1163                      << *changed_params.flexfec_payload_type;
1164     recv_flexfec_payload_type_ = *changed_params.flexfec_payload_type;
1165   }
1166   if (changed_params.rtp_header_extensions) {
1167     recv_rtp_extensions_ = *changed_params.rtp_header_extensions;
1168   }
1169   if (changed_params.codec_settings) {
1170     RTC_LOG(LS_INFO) << "Changing recv codecs from "
1171                      << CodecSettingsVectorToString(recv_codecs_) << " to "
1172                      << CodecSettingsVectorToString(
1173                             *changed_params.codec_settings);
1174     recv_codecs_ = *changed_params.codec_settings;
1175   }
1176 
1177   for (auto& kv : receive_streams_) {
1178     kv.second->SetRecvParameters(changed_params);
1179   }
1180   recv_params_ = params;
1181   return true;
1182 }
1183 
CodecSettingsVectorToString(const std::vector<VideoCodecSettings> & codecs)1184 std::string WebRtcVideoChannel::CodecSettingsVectorToString(
1185     const std::vector<VideoCodecSettings>& codecs) {
1186   rtc::StringBuilder out;
1187   out << "{";
1188   for (size_t i = 0; i < codecs.size(); ++i) {
1189     out << codecs[i].codec.ToString();
1190     if (i != codecs.size() - 1) {
1191       out << ", ";
1192     }
1193   }
1194   out << "}";
1195   return out.Release();
1196 }
1197 
GetSendCodec(VideoCodec * codec)1198 bool WebRtcVideoChannel::GetSendCodec(VideoCodec* codec) {
1199   RTC_DCHECK_RUN_ON(&thread_checker_);
1200   if (!send_codec_) {
1201     RTC_LOG(LS_VERBOSE) << "GetSendCodec: No send codec set.";
1202     return false;
1203   }
1204   *codec = send_codec_->codec;
1205   return true;
1206 }
1207 
SetSend(bool send)1208 bool WebRtcVideoChannel::SetSend(bool send) {
1209   RTC_DCHECK_RUN_ON(&thread_checker_);
1210   TRACE_EVENT0("webrtc", "WebRtcVideoChannel::SetSend");
1211   RTC_LOG(LS_VERBOSE) << "SetSend: " << (send ? "true" : "false");
1212   if (send && !send_codec_) {
1213     RTC_DLOG(LS_ERROR) << "SetSend(true) called before setting codec.";
1214     return false;
1215   }
1216   for (const auto& kv : send_streams_) {
1217     kv.second->SetSend(send);
1218   }
1219   sending_ = send;
1220   return true;
1221 }
1222 
SetVideoSend(uint32_t ssrc,const VideoOptions * options,rtc::VideoSourceInterface<webrtc::VideoFrame> * source)1223 bool WebRtcVideoChannel::SetVideoSend(
1224     uint32_t ssrc,
1225     const VideoOptions* options,
1226     rtc::VideoSourceInterface<webrtc::VideoFrame>* source) {
1227   RTC_DCHECK_RUN_ON(&thread_checker_);
1228   TRACE_EVENT0("webrtc", "SetVideoSend");
1229   RTC_DCHECK(ssrc != 0);
1230   RTC_LOG(LS_INFO) << "SetVideoSend (ssrc= " << ssrc << ", options: "
1231                    << (options ? options->ToString() : "nullptr")
1232                    << ", source = " << (source ? "(source)" : "nullptr") << ")";
1233 
1234   const auto& kv = send_streams_.find(ssrc);
1235   if (kv == send_streams_.end()) {
1236     // Allow unknown ssrc only if source is null.
1237     RTC_CHECK(source == nullptr);
1238     RTC_LOG(LS_ERROR) << "No sending stream on ssrc " << ssrc;
1239     return false;
1240   }
1241 
1242   return kv->second->SetVideoSend(options, source);
1243 }
1244 
ValidateSendSsrcAvailability(const StreamParams & sp) const1245 bool WebRtcVideoChannel::ValidateSendSsrcAvailability(
1246     const StreamParams& sp) const {
1247   for (uint32_t ssrc : sp.ssrcs) {
1248     if (send_ssrcs_.find(ssrc) != send_ssrcs_.end()) {
1249       RTC_LOG(LS_ERROR) << "Send stream with SSRC '" << ssrc
1250                         << "' already exists.";
1251       return false;
1252     }
1253   }
1254   return true;
1255 }
1256 
ValidateReceiveSsrcAvailability(const StreamParams & sp) const1257 bool WebRtcVideoChannel::ValidateReceiveSsrcAvailability(
1258     const StreamParams& sp) const {
1259   for (uint32_t ssrc : sp.ssrcs) {
1260     if (receive_ssrcs_.find(ssrc) != receive_ssrcs_.end()) {
1261       RTC_LOG(LS_ERROR) << "Receive stream with SSRC '" << ssrc
1262                         << "' already exists.";
1263       return false;
1264     }
1265   }
1266   return true;
1267 }
1268 
AddSendStream(const StreamParams & sp)1269 bool WebRtcVideoChannel::AddSendStream(const StreamParams& sp) {
1270   RTC_DCHECK_RUN_ON(&thread_checker_);
1271   RTC_LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
1272   if (!ValidateStreamParams(sp))
1273     return false;
1274 
1275   if (!ValidateSendSsrcAvailability(sp))
1276     return false;
1277 
1278   for (uint32_t used_ssrc : sp.ssrcs)
1279     send_ssrcs_.insert(used_ssrc);
1280 
1281   webrtc::VideoSendStream::Config config(this);
1282 
1283   for (const RidDescription& rid : sp.rids()) {
1284     config.rtp.rids.push_back(rid.rid);
1285   }
1286 
1287   config.suspend_below_min_bitrate = video_config_.suspend_below_min_bitrate;
1288   config.periodic_alr_bandwidth_probing =
1289       video_config_.periodic_alr_bandwidth_probing;
1290   config.encoder_settings.experiment_cpu_load_estimator =
1291       video_config_.experiment_cpu_load_estimator;
1292   config.encoder_settings.encoder_factory = encoder_factory_;
1293   config.encoder_settings.bitrate_allocator_factory =
1294       bitrate_allocator_factory_;
1295   config.encoder_settings.encoder_switch_request_callback = this;
1296   config.crypto_options = crypto_options_;
1297   config.rtp.extmap_allow_mixed = ExtmapAllowMixed();
1298   config.rtcp_report_interval_ms = video_config_.rtcp_report_interval_ms;
1299 
1300   WebRtcVideoSendStream* stream = new WebRtcVideoSendStream(
1301       call_, sp, std::move(config), default_send_options_,
1302       video_config_.enable_cpu_adaptation, bitrate_config_.max_bitrate_bps,
1303       send_codec_, send_rtp_extensions_, send_params_);
1304 
1305   uint32_t ssrc = sp.first_ssrc();
1306   RTC_DCHECK(ssrc != 0);
1307   send_streams_[ssrc] = stream;
1308 
1309   if (rtcp_receiver_report_ssrc_ == kDefaultRtcpReceiverReportSsrc) {
1310     rtcp_receiver_report_ssrc_ = ssrc;
1311     RTC_LOG(LS_INFO)
1312         << "SetLocalSsrc on all the receive streams because we added "
1313            "a send stream.";
1314     for (auto& kv : receive_streams_)
1315       kv.second->SetLocalSsrc(ssrc);
1316   }
1317   if (sending_) {
1318     stream->SetSend(true);
1319   }
1320 
1321   return true;
1322 }
1323 
RemoveSendStream(uint32_t ssrc)1324 bool WebRtcVideoChannel::RemoveSendStream(uint32_t ssrc) {
1325   RTC_DCHECK_RUN_ON(&thread_checker_);
1326   RTC_LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
1327 
1328   WebRtcVideoSendStream* removed_stream;
1329   std::map<uint32_t, WebRtcVideoSendStream*>::iterator it =
1330       send_streams_.find(ssrc);
1331   if (it == send_streams_.end()) {
1332     return false;
1333   }
1334 
1335   for (uint32_t old_ssrc : it->second->GetSsrcs())
1336     send_ssrcs_.erase(old_ssrc);
1337 
1338   removed_stream = it->second;
1339   send_streams_.erase(it);
1340 
1341   // Switch receiver report SSRCs, the one in use is no longer valid.
1342   if (rtcp_receiver_report_ssrc_ == ssrc) {
1343     rtcp_receiver_report_ssrc_ = send_streams_.empty()
1344                                      ? kDefaultRtcpReceiverReportSsrc
1345                                      : send_streams_.begin()->first;
1346     RTC_LOG(LS_INFO) << "SetLocalSsrc on all the receive streams because the "
1347                         "previous local SSRC was removed.";
1348 
1349     for (auto& kv : receive_streams_) {
1350       kv.second->SetLocalSsrc(rtcp_receiver_report_ssrc_);
1351     }
1352   }
1353 
1354   delete removed_stream;
1355 
1356   return true;
1357 }
1358 
DeleteReceiveStream(WebRtcVideoChannel::WebRtcVideoReceiveStream * stream)1359 void WebRtcVideoChannel::DeleteReceiveStream(
1360     WebRtcVideoChannel::WebRtcVideoReceiveStream* stream) {
1361   for (uint32_t old_ssrc : stream->GetSsrcs())
1362     receive_ssrcs_.erase(old_ssrc);
1363   delete stream;
1364 }
1365 
AddRecvStream(const StreamParams & sp)1366 bool WebRtcVideoChannel::AddRecvStream(const StreamParams& sp) {
1367   return AddRecvStream(sp, false);
1368 }
1369 
AddRecvStream(const StreamParams & sp,bool default_stream)1370 bool WebRtcVideoChannel::AddRecvStream(const StreamParams& sp,
1371                                        bool default_stream) {
1372   RTC_DCHECK_RUN_ON(&thread_checker_);
1373 
1374   RTC_LOG(LS_INFO) << "AddRecvStream"
1375                    << (default_stream ? " (default stream)" : "") << ": "
1376                    << sp.ToString();
1377   if (!sp.has_ssrcs()) {
1378     // This is a StreamParam with unsignaled SSRCs. Store it, so it can be used
1379     // later when we know the SSRC on the first packet arrival.
1380     unsignaled_stream_params_ = sp;
1381     return true;
1382   }
1383 
1384   if (!ValidateStreamParams(sp))
1385     return false;
1386 
1387   uint32_t ssrc = sp.first_ssrc();
1388 
1389   // Remove running stream if this was a default stream.
1390   const auto& prev_stream = receive_streams_.find(ssrc);
1391   if (prev_stream != receive_streams_.end()) {
1392     if (default_stream || !prev_stream->second->IsDefaultStream()) {
1393       RTC_LOG(LS_ERROR) << "Receive stream for SSRC '" << ssrc
1394                         << "' already exists.";
1395       return false;
1396     }
1397     DeleteReceiveStream(prev_stream->second);
1398     receive_streams_.erase(prev_stream);
1399   }
1400 
1401   if (!ValidateReceiveSsrcAvailability(sp))
1402     return false;
1403 
1404   for (uint32_t used_ssrc : sp.ssrcs)
1405     receive_ssrcs_.insert(used_ssrc);
1406 
1407   webrtc::VideoReceiveStream::Config config(this);
1408   webrtc::FlexfecReceiveStream::Config flexfec_config(this);
1409   ConfigureReceiverRtp(&config, &flexfec_config, sp);
1410 
1411   config.crypto_options = crypto_options_;
1412   config.enable_prerenderer_smoothing =
1413       video_config_.enable_prerenderer_smoothing;
1414   if (!sp.stream_ids().empty()) {
1415     config.sync_group = sp.stream_ids()[0];
1416   }
1417 
1418   if (unsignaled_frame_transformer_ && !config.frame_transformer)
1419     config.frame_transformer = unsignaled_frame_transformer_;
1420 
1421   receive_streams_[ssrc] = new WebRtcVideoReceiveStream(
1422       this, call_, sp, std::move(config), decoder_factory_, default_stream,
1423       recv_codecs_, flexfec_config);
1424 
1425   return true;
1426 }
1427 
ConfigureReceiverRtp(webrtc::VideoReceiveStream::Config * config,webrtc::FlexfecReceiveStream::Config * flexfec_config,const StreamParams & sp) const1428 void WebRtcVideoChannel::ConfigureReceiverRtp(
1429     webrtc::VideoReceiveStream::Config* config,
1430     webrtc::FlexfecReceiveStream::Config* flexfec_config,
1431     const StreamParams& sp) const {
1432   uint32_t ssrc = sp.first_ssrc();
1433 
1434   config->rtp.remote_ssrc = ssrc;
1435   config->rtp.local_ssrc = rtcp_receiver_report_ssrc_;
1436 
1437   // TODO(pbos): This protection is against setting the same local ssrc as
1438   // remote which is not permitted by the lower-level API. RTCP requires a
1439   // corresponding sender SSRC. Figure out what to do when we don't have
1440   // (receive-only) or know a good local SSRC.
1441   if (config->rtp.remote_ssrc == config->rtp.local_ssrc) {
1442     if (config->rtp.local_ssrc != kDefaultRtcpReceiverReportSsrc) {
1443       config->rtp.local_ssrc = kDefaultRtcpReceiverReportSsrc;
1444     } else {
1445       config->rtp.local_ssrc = kDefaultRtcpReceiverReportSsrc + 1;
1446     }
1447   }
1448 
1449   // Whether or not the receive stream sends reduced size RTCP is determined
1450   // by the send params.
1451   // TODO(deadbeef): Once we change "send_params" to "sender_params" and
1452   // "recv_params" to "receiver_params", we should get this out of
1453   // receiver_params_.
1454   config->rtp.rtcp_mode = send_params_.rtcp.reduced_size
1455                               ? webrtc::RtcpMode::kReducedSize
1456                               : webrtc::RtcpMode::kCompound;
1457 
1458   config->rtp.transport_cc =
1459       send_codec_ ? HasTransportCc(send_codec_->codec) : false;
1460 
1461   sp.GetFidSsrc(ssrc, &config->rtp.rtx_ssrc);
1462 
1463   config->rtp.extensions = recv_rtp_extensions_;
1464 
1465   // TODO(brandtr): Generalize when we add support for multistream protection.
1466   flexfec_config->payload_type = recv_flexfec_payload_type_;
1467   if (IsFlexfecAdvertisedFieldTrialEnabled() &&
1468       sp.GetFecFrSsrc(ssrc, &flexfec_config->remote_ssrc)) {
1469     flexfec_config->protected_media_ssrcs = {ssrc};
1470     flexfec_config->local_ssrc = config->rtp.local_ssrc;
1471     flexfec_config->rtcp_mode = config->rtp.rtcp_mode;
1472     // TODO(brandtr): We should be spec-compliant and set |transport_cc| here
1473     // based on the rtcp-fb for the FlexFEC codec, not the media codec.
1474     flexfec_config->transport_cc = config->rtp.transport_cc;
1475     flexfec_config->rtp_header_extensions = config->rtp.extensions;
1476   }
1477 }
1478 
RemoveRecvStream(uint32_t ssrc)1479 bool WebRtcVideoChannel::RemoveRecvStream(uint32_t ssrc) {
1480   RTC_DCHECK_RUN_ON(&thread_checker_);
1481   RTC_LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
1482 
1483   std::map<uint32_t, WebRtcVideoReceiveStream*>::iterator stream =
1484       receive_streams_.find(ssrc);
1485   if (stream == receive_streams_.end()) {
1486     RTC_LOG(LS_ERROR) << "Stream not found for ssrc: " << ssrc;
1487     return false;
1488   }
1489   DeleteReceiveStream(stream->second);
1490   receive_streams_.erase(stream);
1491 
1492   return true;
1493 }
1494 
ResetUnsignaledRecvStream()1495 void WebRtcVideoChannel::ResetUnsignaledRecvStream() {
1496   RTC_DCHECK_RUN_ON(&thread_checker_);
1497   RTC_LOG(LS_INFO) << "ResetUnsignaledRecvStream.";
1498   unsignaled_stream_params_ = StreamParams();
1499 
1500   // Delete any created default streams. This is needed to avoid SSRC collisions
1501   // in Call's RtpDemuxer, in the case that |this| has created a default video
1502   // receiver, and then some other WebRtcVideoChannel gets the SSRC signaled
1503   // in the corresponding Unified Plan "m=" section.
1504   auto it = receive_streams_.begin();
1505   while (it != receive_streams_.end()) {
1506     if (it->second->IsDefaultStream()) {
1507       DeleteReceiveStream(it->second);
1508       receive_streams_.erase(it++);
1509     } else {
1510       ++it;
1511     }
1512   }
1513 }
1514 
SetSink(uint32_t ssrc,rtc::VideoSinkInterface<webrtc::VideoFrame> * sink)1515 bool WebRtcVideoChannel::SetSink(
1516     uint32_t ssrc,
1517     rtc::VideoSinkInterface<webrtc::VideoFrame>* sink) {
1518   RTC_DCHECK_RUN_ON(&thread_checker_);
1519   RTC_LOG(LS_INFO) << "SetSink: ssrc:" << ssrc << " "
1520                    << (sink ? "(ptr)" : "nullptr");
1521 
1522   std::map<uint32_t, WebRtcVideoReceiveStream*>::iterator it =
1523       receive_streams_.find(ssrc);
1524   if (it == receive_streams_.end()) {
1525     return false;
1526   }
1527 
1528   it->second->SetSink(sink);
1529   return true;
1530 }
1531 
SetDefaultSink(rtc::VideoSinkInterface<webrtc::VideoFrame> * sink)1532 void WebRtcVideoChannel::SetDefaultSink(
1533     rtc::VideoSinkInterface<webrtc::VideoFrame>* sink) {
1534   RTC_DCHECK_RUN_ON(&thread_checker_);
1535   RTC_LOG(LS_INFO) << "SetDefaultSink: " << (sink ? "(ptr)" : "nullptr");
1536   default_unsignalled_ssrc_handler_.SetDefaultSink(this, sink);
1537 }
1538 
GetStats(VideoMediaInfo * info)1539 bool WebRtcVideoChannel::GetStats(VideoMediaInfo* info) {
1540   RTC_DCHECK_RUN_ON(&thread_checker_);
1541   TRACE_EVENT0("webrtc", "WebRtcVideoChannel::GetStats");
1542 
1543   // Log stats periodically.
1544   bool log_stats = false;
1545   int64_t now_ms = rtc::TimeMillis();
1546   if (last_stats_log_ms_ == -1 ||
1547       now_ms - last_stats_log_ms_ > kStatsLogIntervalMs) {
1548     last_stats_log_ms_ = now_ms;
1549     log_stats = true;
1550   }
1551 
1552   info->Clear();
1553   FillSenderStats(info, log_stats);
1554   FillReceiverStats(info, log_stats);
1555   FillSendAndReceiveCodecStats(info);
1556   // TODO(holmer): We should either have rtt available as a metric on
1557   // VideoSend/ReceiveStreams, or we should remove rtt from VideoSenderInfo.
1558   webrtc::Call::Stats stats = call_->GetStats();
1559   if (stats.rtt_ms != -1) {
1560     for (size_t i = 0; i < info->senders.size(); ++i) {
1561       info->senders[i].rtt_ms = stats.rtt_ms;
1562     }
1563     for (size_t i = 0; i < info->aggregated_senders.size(); ++i) {
1564       info->aggregated_senders[i].rtt_ms = stats.rtt_ms;
1565     }
1566   }
1567 
1568   if (log_stats)
1569     RTC_LOG(LS_INFO) << stats.ToString(now_ms);
1570 
1571   return true;
1572 }
1573 
FillSenderStats(VideoMediaInfo * video_media_info,bool log_stats)1574 void WebRtcVideoChannel::FillSenderStats(VideoMediaInfo* video_media_info,
1575                                          bool log_stats) {
1576   for (std::map<uint32_t, WebRtcVideoSendStream*>::iterator it =
1577            send_streams_.begin();
1578        it != send_streams_.end(); ++it) {
1579     auto infos = it->second->GetPerLayerVideoSenderInfos(log_stats);
1580     if (infos.empty())
1581       continue;
1582     video_media_info->aggregated_senders.push_back(
1583         it->second->GetAggregatedVideoSenderInfo(infos));
1584     for (auto&& info : infos) {
1585       video_media_info->senders.push_back(info);
1586     }
1587   }
1588 }
1589 
FillReceiverStats(VideoMediaInfo * video_media_info,bool log_stats)1590 void WebRtcVideoChannel::FillReceiverStats(VideoMediaInfo* video_media_info,
1591                                            bool log_stats) {
1592   for (std::map<uint32_t, WebRtcVideoReceiveStream*>::iterator it =
1593            receive_streams_.begin();
1594        it != receive_streams_.end(); ++it) {
1595     video_media_info->receivers.push_back(
1596         it->second->GetVideoReceiverInfo(log_stats));
1597   }
1598 }
1599 
FillBitrateInfo(BandwidthEstimationInfo * bwe_info)1600 void WebRtcVideoChannel::FillBitrateInfo(BandwidthEstimationInfo* bwe_info) {
1601   RTC_DCHECK_RUN_ON(&thread_checker_);
1602   for (std::map<uint32_t, WebRtcVideoSendStream*>::iterator stream =
1603            send_streams_.begin();
1604        stream != send_streams_.end(); ++stream) {
1605     stream->second->FillBitrateInfo(bwe_info);
1606   }
1607 }
1608 
FillSendAndReceiveCodecStats(VideoMediaInfo * video_media_info)1609 void WebRtcVideoChannel::FillSendAndReceiveCodecStats(
1610     VideoMediaInfo* video_media_info) {
1611   for (const VideoCodec& codec : send_params_.codecs) {
1612     webrtc::RtpCodecParameters codec_params = codec.ToCodecParameters();
1613     video_media_info->send_codecs.insert(
1614         std::make_pair(codec_params.payload_type, std::move(codec_params)));
1615   }
1616   for (const VideoCodec& codec : recv_params_.codecs) {
1617     webrtc::RtpCodecParameters codec_params = codec.ToCodecParameters();
1618     video_media_info->receive_codecs.insert(
1619         std::make_pair(codec_params.payload_type, std::move(codec_params)));
1620   }
1621 }
1622 
OnPacketReceived(rtc::CopyOnWriteBuffer packet,int64_t packet_time_us)1623 void WebRtcVideoChannel::OnPacketReceived(rtc::CopyOnWriteBuffer packet,
1624                                           int64_t packet_time_us) {
1625   RTC_DCHECK_RUN_ON(&thread_checker_);
1626   const webrtc::PacketReceiver::DeliveryStatus delivery_result =
1627       call_->Receiver()->DeliverPacket(webrtc::MediaType::VIDEO, packet,
1628                                        packet_time_us);
1629   switch (delivery_result) {
1630     case webrtc::PacketReceiver::DELIVERY_OK:
1631       return;
1632     case webrtc::PacketReceiver::DELIVERY_PACKET_ERROR:
1633       return;
1634     case webrtc::PacketReceiver::DELIVERY_UNKNOWN_SSRC:
1635       break;
1636   }
1637 
1638   uint32_t ssrc = 0;
1639   if (!GetRtpSsrc(packet.cdata(), packet.size(), &ssrc)) {
1640     return;
1641   }
1642 
1643   if (unknown_ssrc_packet_buffer_) {
1644     unknown_ssrc_packet_buffer_->AddPacket(ssrc, packet_time_us, packet);
1645     return;
1646   }
1647 
1648   if (discard_unknown_ssrc_packets_) {
1649     return;
1650   }
1651 
1652   int payload_type = 0;
1653   if (!GetRtpPayloadType(packet.cdata(), packet.size(), &payload_type)) {
1654     return;
1655   }
1656 
1657   // See if this payload_type is registered as one that usually gets its own
1658   // SSRC (RTX) or at least is safe to drop either way (FEC). If it is, and
1659   // it wasn't handled above by DeliverPacket, that means we don't know what
1660   // stream it associates with, and we shouldn't ever create an implicit channel
1661   // for these.
1662   for (auto& codec : recv_codecs_) {
1663     if (payload_type == codec.rtx_payload_type ||
1664         payload_type == codec.ulpfec.red_rtx_payload_type ||
1665         payload_type == codec.ulpfec.ulpfec_payload_type) {
1666       return;
1667     }
1668   }
1669   if (payload_type == recv_flexfec_payload_type_) {
1670     return;
1671   }
1672 
1673   switch (unsignalled_ssrc_handler_->OnUnsignalledSsrc(this, ssrc)) {
1674     case UnsignalledSsrcHandler::kDropPacket:
1675       return;
1676     case UnsignalledSsrcHandler::kDeliverPacket:
1677       break;
1678   }
1679 
1680   if (call_->Receiver()->DeliverPacket(webrtc::MediaType::VIDEO, packet,
1681                                        packet_time_us) !=
1682       webrtc::PacketReceiver::DELIVERY_OK) {
1683     RTC_LOG(LS_WARNING) << "Failed to deliver RTP packet on re-delivery.";
1684     return;
1685   }
1686 }
1687 
BackfillBufferedPackets(rtc::ArrayView<const uint32_t> ssrcs)1688 void WebRtcVideoChannel::BackfillBufferedPackets(
1689     rtc::ArrayView<const uint32_t> ssrcs) {
1690   RTC_DCHECK_RUN_ON(&thread_checker_);
1691   if (!unknown_ssrc_packet_buffer_) {
1692     return;
1693   }
1694 
1695   int delivery_ok_cnt = 0;
1696   int delivery_unknown_ssrc_cnt = 0;
1697   int delivery_packet_error_cnt = 0;
1698   webrtc::PacketReceiver* receiver = this->call_->Receiver();
1699   unknown_ssrc_packet_buffer_->BackfillPackets(
1700       ssrcs, [&](uint32_t ssrc, int64_t packet_time_us,
1701                  rtc::CopyOnWriteBuffer packet) {
1702         switch (receiver->DeliverPacket(webrtc::MediaType::VIDEO, packet,
1703                                         packet_time_us)) {
1704           case webrtc::PacketReceiver::DELIVERY_OK:
1705             delivery_ok_cnt++;
1706             break;
1707           case webrtc::PacketReceiver::DELIVERY_UNKNOWN_SSRC:
1708             delivery_unknown_ssrc_cnt++;
1709             break;
1710           case webrtc::PacketReceiver::DELIVERY_PACKET_ERROR:
1711             delivery_packet_error_cnt++;
1712             break;
1713         }
1714       });
1715   rtc::StringBuilder out;
1716   out << "[ ";
1717   for (uint32_t ssrc : ssrcs) {
1718     out << std::to_string(ssrc) << " ";
1719   }
1720   out << "]";
1721   auto level = rtc::LS_INFO;
1722   if (delivery_unknown_ssrc_cnt > 0 || delivery_packet_error_cnt > 0) {
1723     level = rtc::LS_ERROR;
1724   }
1725   int total =
1726       delivery_ok_cnt + delivery_unknown_ssrc_cnt + delivery_packet_error_cnt;
1727   RTC_LOG_V(level) << "Backfilled " << total
1728                    << " packets for ssrcs: " << out.Release()
1729                    << " ok: " << delivery_ok_cnt
1730                    << " error: " << delivery_packet_error_cnt
1731                    << " unknown: " << delivery_unknown_ssrc_cnt;
1732 }
1733 
OnReadyToSend(bool ready)1734 void WebRtcVideoChannel::OnReadyToSend(bool ready) {
1735   RTC_DCHECK_RUN_ON(&thread_checker_);
1736   RTC_LOG(LS_VERBOSE) << "OnReadyToSend: " << (ready ? "Ready." : "Not ready.");
1737   call_->SignalChannelNetworkState(
1738       webrtc::MediaType::VIDEO,
1739       ready ? webrtc::kNetworkUp : webrtc::kNetworkDown);
1740 }
1741 
OnNetworkRouteChanged(const std::string & transport_name,const rtc::NetworkRoute & network_route)1742 void WebRtcVideoChannel::OnNetworkRouteChanged(
1743     const std::string& transport_name,
1744     const rtc::NetworkRoute& network_route) {
1745   RTC_DCHECK_RUN_ON(&thread_checker_);
1746   call_->GetTransportControllerSend()->OnNetworkRouteChanged(transport_name,
1747                                                              network_route);
1748   call_->GetTransportControllerSend()->OnTransportOverheadChanged(
1749       network_route.packet_overhead);
1750 }
1751 
SetInterface(NetworkInterface * iface)1752 void WebRtcVideoChannel::SetInterface(NetworkInterface* iface) {
1753   RTC_DCHECK_RUN_ON(&thread_checker_);
1754   MediaChannel::SetInterface(iface);
1755   // Set the RTP recv/send buffer to a bigger size.
1756 
1757   // The group should be a positive integer with an explicit size, in
1758   // which case that is used as UDP recevie buffer size. All other values shall
1759   // result in the default value being used.
1760   const std::string group_name =
1761       webrtc::field_trial::FindFullName("WebRTC-IncreasedReceivebuffers");
1762   int recv_buffer_size = kVideoRtpRecvBufferSize;
1763   if (!group_name.empty() &&
1764       (sscanf(group_name.c_str(), "%d", &recv_buffer_size) != 1 ||
1765        recv_buffer_size <= 0)) {
1766     RTC_LOG(LS_WARNING) << "Invalid receive buffer size: " << group_name;
1767     recv_buffer_size = kVideoRtpRecvBufferSize;
1768   }
1769 
1770   MediaChannel::SetOption(NetworkInterface::ST_RTP, rtc::Socket::OPT_RCVBUF,
1771                           recv_buffer_size);
1772 
1773   // Speculative change to increase the outbound socket buffer size.
1774   // In b/15152257, we are seeing a significant number of packets discarded
1775   // due to lack of socket buffer space, although it's not yet clear what the
1776   // ideal value should be.
1777   MediaChannel::SetOption(NetworkInterface::ST_RTP, rtc::Socket::OPT_SNDBUF,
1778                           kVideoRtpSendBufferSize);
1779 }
1780 
SetFrameDecryptor(uint32_t ssrc,rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor)1781 void WebRtcVideoChannel::SetFrameDecryptor(
1782     uint32_t ssrc,
1783     rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor) {
1784   RTC_DCHECK_RUN_ON(&thread_checker_);
1785   auto matching_stream = receive_streams_.find(ssrc);
1786   if (matching_stream != receive_streams_.end()) {
1787     matching_stream->second->SetFrameDecryptor(frame_decryptor);
1788   }
1789 }
1790 
SetFrameEncryptor(uint32_t ssrc,rtc::scoped_refptr<webrtc::FrameEncryptorInterface> frame_encryptor)1791 void WebRtcVideoChannel::SetFrameEncryptor(
1792     uint32_t ssrc,
1793     rtc::scoped_refptr<webrtc::FrameEncryptorInterface> frame_encryptor) {
1794   RTC_DCHECK_RUN_ON(&thread_checker_);
1795   auto matching_stream = send_streams_.find(ssrc);
1796   if (matching_stream != send_streams_.end()) {
1797     matching_stream->second->SetFrameEncryptor(frame_encryptor);
1798   } else {
1799     RTC_LOG(LS_ERROR) << "No stream found to attach frame encryptor";
1800   }
1801 }
1802 
SetVideoCodecSwitchingEnabled(bool enabled)1803 void WebRtcVideoChannel::SetVideoCodecSwitchingEnabled(bool enabled) {
1804   invoker_.AsyncInvoke<void>(RTC_FROM_HERE, worker_thread_, [this, enabled] {
1805     RTC_DCHECK_RUN_ON(&thread_checker_);
1806     allow_codec_switching_ = enabled;
1807     if (allow_codec_switching_) {
1808       RTC_LOG(LS_INFO) << "Encoder switching enabled.";
1809       if (requested_encoder_switch_) {
1810         RTC_LOG(LS_INFO) << "Executing cached video encoder switch request.";
1811         RequestEncoderSwitch(*requested_encoder_switch_);
1812         requested_encoder_switch_.reset();
1813       }
1814     }
1815   });
1816 }
1817 
SetBaseMinimumPlayoutDelayMs(uint32_t ssrc,int delay_ms)1818 bool WebRtcVideoChannel::SetBaseMinimumPlayoutDelayMs(uint32_t ssrc,
1819                                                       int delay_ms) {
1820   RTC_DCHECK_RUN_ON(&thread_checker_);
1821   absl::optional<uint32_t> default_ssrc = GetDefaultReceiveStreamSsrc();
1822 
1823   // SSRC of 0 represents the default receive stream.
1824   if (ssrc == 0) {
1825     default_recv_base_minimum_delay_ms_ = delay_ms;
1826   }
1827 
1828   if (ssrc == 0 && !default_ssrc) {
1829     return true;
1830   }
1831 
1832   if (ssrc == 0 && default_ssrc) {
1833     ssrc = default_ssrc.value();
1834   }
1835 
1836   auto stream = receive_streams_.find(ssrc);
1837   if (stream != receive_streams_.end()) {
1838     stream->second->SetBaseMinimumPlayoutDelayMs(delay_ms);
1839     return true;
1840   } else {
1841     RTC_LOG(LS_ERROR) << "No stream found to set base minimum playout delay";
1842     return false;
1843   }
1844 }
1845 
GetBaseMinimumPlayoutDelayMs(uint32_t ssrc) const1846 absl::optional<int> WebRtcVideoChannel::GetBaseMinimumPlayoutDelayMs(
1847     uint32_t ssrc) const {
1848   RTC_DCHECK_RUN_ON(&thread_checker_);
1849   // SSRC of 0 represents the default receive stream.
1850   if (ssrc == 0) {
1851     return default_recv_base_minimum_delay_ms_;
1852   }
1853 
1854   auto stream = receive_streams_.find(ssrc);
1855   if (stream != receive_streams_.end()) {
1856     return stream->second->GetBaseMinimumPlayoutDelayMs();
1857   } else {
1858     RTC_LOG(LS_ERROR) << "No stream found to get base minimum playout delay";
1859     return absl::nullopt;
1860   }
1861 }
1862 
GetDefaultReceiveStreamSsrc()1863 absl::optional<uint32_t> WebRtcVideoChannel::GetDefaultReceiveStreamSsrc() {
1864   RTC_DCHECK_RUN_ON(&thread_checker_);
1865   absl::optional<uint32_t> ssrc;
1866   for (auto it = receive_streams_.begin(); it != receive_streams_.end(); ++it) {
1867     if (it->second->IsDefaultStream()) {
1868       ssrc.emplace(it->first);
1869       break;
1870     }
1871   }
1872   return ssrc;
1873 }
1874 
GetSources(uint32_t ssrc) const1875 std::vector<webrtc::RtpSource> WebRtcVideoChannel::GetSources(
1876     uint32_t ssrc) const {
1877   RTC_DCHECK_RUN_ON(&thread_checker_);
1878   auto it = receive_streams_.find(ssrc);
1879   if (it == receive_streams_.end()) {
1880     // TODO(bugs.webrtc.org/9781): Investigate standard compliance
1881     // with sources for streams that has been removed.
1882     RTC_LOG(LS_ERROR) << "Attempting to get contributing sources for SSRC:"
1883                       << ssrc << " which doesn't exist.";
1884     return {};
1885   }
1886   return it->second->GetSources();
1887 }
1888 
SendRtp(const uint8_t * data,size_t len,const webrtc::PacketOptions & options)1889 bool WebRtcVideoChannel::SendRtp(const uint8_t* data,
1890                                  size_t len,
1891                                  const webrtc::PacketOptions& options) {
1892   rtc::CopyOnWriteBuffer packet(data, len, kMaxRtpPacketLen);
1893   rtc::PacketOptions rtc_options;
1894   rtc_options.packet_id = options.packet_id;
1895   if (DscpEnabled()) {
1896     rtc_options.dscp = PreferredDscp();
1897   }
1898   rtc_options.info_signaled_after_sent.included_in_feedback =
1899       options.included_in_feedback;
1900   rtc_options.info_signaled_after_sent.included_in_allocation =
1901       options.included_in_allocation;
1902   return MediaChannel::SendPacket(&packet, rtc_options);
1903 }
1904 
SendRtcp(const uint8_t * data,size_t len)1905 bool WebRtcVideoChannel::SendRtcp(const uint8_t* data, size_t len) {
1906   rtc::CopyOnWriteBuffer packet(data, len, kMaxRtpPacketLen);
1907   rtc::PacketOptions rtc_options;
1908   if (DscpEnabled()) {
1909     rtc_options.dscp = PreferredDscp();
1910   }
1911 
1912   return MediaChannel::SendRtcp(&packet, rtc_options);
1913 }
1914 
1915 WebRtcVideoChannel::WebRtcVideoSendStream::VideoSendStreamParameters::
VideoSendStreamParameters(webrtc::VideoSendStream::Config config,const VideoOptions & options,int max_bitrate_bps,const absl::optional<VideoCodecSettings> & codec_settings)1916     VideoSendStreamParameters(
1917         webrtc::VideoSendStream::Config config,
1918         const VideoOptions& options,
1919         int max_bitrate_bps,
1920         const absl::optional<VideoCodecSettings>& codec_settings)
1921     : config(std::move(config)),
1922       options(options),
1923       max_bitrate_bps(max_bitrate_bps),
1924       conference_mode(false),
1925       codec_settings(codec_settings) {}
1926 
WebRtcVideoSendStream(webrtc::Call * call,const StreamParams & sp,webrtc::VideoSendStream::Config config,const VideoOptions & options,bool enable_cpu_overuse_detection,int max_bitrate_bps,const absl::optional<VideoCodecSettings> & codec_settings,const absl::optional<std::vector<webrtc::RtpExtension>> & rtp_extensions,const VideoSendParameters & send_params)1927 WebRtcVideoChannel::WebRtcVideoSendStream::WebRtcVideoSendStream(
1928     webrtc::Call* call,
1929     const StreamParams& sp,
1930     webrtc::VideoSendStream::Config config,
1931     const VideoOptions& options,
1932     bool enable_cpu_overuse_detection,
1933     int max_bitrate_bps,
1934     const absl::optional<VideoCodecSettings>& codec_settings,
1935     const absl::optional<std::vector<webrtc::RtpExtension>>& rtp_extensions,
1936     // TODO(deadbeef): Don't duplicate information between send_params,
1937     // rtp_extensions, options, etc.
1938     const VideoSendParameters& send_params)
1939     : worker_thread_(rtc::Thread::Current()),
1940       ssrcs_(sp.ssrcs),
1941       ssrc_groups_(sp.ssrc_groups),
1942       call_(call),
1943       enable_cpu_overuse_detection_(enable_cpu_overuse_detection),
1944       source_(nullptr),
1945       stream_(nullptr),
1946       encoder_sink_(nullptr),
1947       parameters_(std::move(config), options, max_bitrate_bps, codec_settings),
1948       rtp_parameters_(CreateRtpParametersWithEncodings(sp)),
1949       sending_(false) {
1950   // Maximum packet size may come in RtpConfig from external transport, for
1951   // example from QuicTransportInterface implementation, so do not exceed
1952   // given max_packet_size.
1953   parameters_.config.rtp.max_packet_size =
1954       std::min<size_t>(parameters_.config.rtp.max_packet_size, kVideoMtu);
1955   parameters_.conference_mode = send_params.conference_mode;
1956 
1957   sp.GetPrimarySsrcs(&parameters_.config.rtp.ssrcs);
1958 
1959   // ValidateStreamParams should prevent this from happening.
1960   RTC_CHECK(!parameters_.config.rtp.ssrcs.empty());
1961   rtp_parameters_.encodings[0].ssrc = parameters_.config.rtp.ssrcs[0];
1962 
1963   // RTX.
1964   sp.GetFidSsrcs(parameters_.config.rtp.ssrcs,
1965                  &parameters_.config.rtp.rtx.ssrcs);
1966 
1967   // FlexFEC SSRCs.
1968   // TODO(brandtr): This code needs to be generalized when we add support for
1969   // multistream protection.
1970   if (IsFlexfecFieldTrialEnabled()) {
1971     uint32_t flexfec_ssrc;
1972     bool flexfec_enabled = false;
1973     for (uint32_t primary_ssrc : parameters_.config.rtp.ssrcs) {
1974       if (sp.GetFecFrSsrc(primary_ssrc, &flexfec_ssrc)) {
1975         if (flexfec_enabled) {
1976           RTC_LOG(LS_INFO)
1977               << "Multiple FlexFEC streams in local SDP, but "
1978                  "our implementation only supports a single FlexFEC "
1979                  "stream. Will not enable FlexFEC for proposed "
1980                  "stream with SSRC: "
1981               << flexfec_ssrc << ".";
1982           continue;
1983         }
1984 
1985         flexfec_enabled = true;
1986         parameters_.config.rtp.flexfec.ssrc = flexfec_ssrc;
1987         parameters_.config.rtp.flexfec.protected_media_ssrcs = {primary_ssrc};
1988       }
1989     }
1990   }
1991 
1992   parameters_.config.rtp.c_name = sp.cname;
1993   if (rtp_extensions) {
1994     parameters_.config.rtp.extensions = *rtp_extensions;
1995     rtp_parameters_.header_extensions = *rtp_extensions;
1996   }
1997   parameters_.config.rtp.rtcp_mode = send_params.rtcp.reduced_size
1998                                          ? webrtc::RtcpMode::kReducedSize
1999                                          : webrtc::RtcpMode::kCompound;
2000   parameters_.config.rtp.mid = send_params.mid;
2001   rtp_parameters_.rtcp.reduced_size = send_params.rtcp.reduced_size;
2002 
2003   if (codec_settings) {
2004     SetCodec(*codec_settings);
2005   }
2006 }
2007 
~WebRtcVideoSendStream()2008 WebRtcVideoChannel::WebRtcVideoSendStream::~WebRtcVideoSendStream() {
2009   if (stream_ != NULL) {
2010     call_->DestroyVideoSendStream(stream_);
2011   }
2012 }
2013 
SetVideoSend(const VideoOptions * options,rtc::VideoSourceInterface<webrtc::VideoFrame> * source)2014 bool WebRtcVideoChannel::WebRtcVideoSendStream::SetVideoSend(
2015     const VideoOptions* options,
2016     rtc::VideoSourceInterface<webrtc::VideoFrame>* source) {
2017   TRACE_EVENT0("webrtc", "WebRtcVideoSendStream::SetVideoSend");
2018   RTC_DCHECK_RUN_ON(&thread_checker_);
2019 
2020   if (options) {
2021     VideoOptions old_options = parameters_.options;
2022     parameters_.options.SetAll(*options);
2023     if (parameters_.options.is_screencast.value_or(false) !=
2024             old_options.is_screencast.value_or(false) &&
2025         parameters_.codec_settings) {
2026       // If screen content settings change, we may need to recreate the codec
2027       // instance so that the correct type is used.
2028 
2029       SetCodec(*parameters_.codec_settings);
2030       // Mark screenshare parameter as being updated, then test for any other
2031       // changes that may require codec reconfiguration.
2032       old_options.is_screencast = options->is_screencast;
2033     }
2034     if (parameters_.options != old_options) {
2035       ReconfigureEncoder();
2036     }
2037   }
2038 
2039   if (source_ && stream_) {
2040     stream_->SetSource(nullptr, webrtc::DegradationPreference::DISABLED);
2041   }
2042   // Switch to the new source.
2043   source_ = source;
2044   if (source && stream_) {
2045     stream_->SetSource(this, GetDegradationPreference());
2046   }
2047   return true;
2048 }
2049 
2050 webrtc::DegradationPreference
GetDegradationPreference() const2051 WebRtcVideoChannel::WebRtcVideoSendStream::GetDegradationPreference() const {
2052   // Do not adapt resolution for screen content as this will likely
2053   // result in blurry and unreadable text.
2054   // |this| acts like a VideoSource to make sure SinkWants are handled on the
2055   // correct thread.
2056   if (!enable_cpu_overuse_detection_) {
2057     return webrtc::DegradationPreference::DISABLED;
2058   }
2059 
2060   webrtc::DegradationPreference degradation_preference;
2061   if (rtp_parameters_.degradation_preference.has_value()) {
2062     degradation_preference = *rtp_parameters_.degradation_preference;
2063   } else {
2064     if (parameters_.options.content_hint ==
2065         webrtc::VideoTrackInterface::ContentHint::kFluid) {
2066       degradation_preference =
2067           webrtc::DegradationPreference::MAINTAIN_FRAMERATE;
2068     } else if (parameters_.options.is_screencast.value_or(false) ||
2069                parameters_.options.content_hint ==
2070                    webrtc::VideoTrackInterface::ContentHint::kDetailed ||
2071                parameters_.options.content_hint ==
2072                    webrtc::VideoTrackInterface::ContentHint::kText) {
2073       degradation_preference =
2074           webrtc::DegradationPreference::MAINTAIN_RESOLUTION;
2075     } else if (webrtc::field_trial::IsEnabled(
2076                    "WebRTC-Video-BalancedDegradation")) {
2077       // Standard wants balanced by default, but it needs to be tuned first.
2078       degradation_preference = webrtc::DegradationPreference::BALANCED;
2079     } else {
2080       // Keep MAINTAIN_FRAMERATE by default until BALANCED has been tuned for
2081       // all codecs and launched.
2082       degradation_preference =
2083           webrtc::DegradationPreference::MAINTAIN_FRAMERATE;
2084     }
2085   }
2086 
2087   return degradation_preference;
2088 }
2089 
2090 const std::vector<uint32_t>&
GetSsrcs() const2091 WebRtcVideoChannel::WebRtcVideoSendStream::GetSsrcs() const {
2092   return ssrcs_;
2093 }
2094 
SetCodec(const VideoCodecSettings & codec_settings)2095 void WebRtcVideoChannel::WebRtcVideoSendStream::SetCodec(
2096     const VideoCodecSettings& codec_settings) {
2097   RTC_DCHECK_RUN_ON(&thread_checker_);
2098   parameters_.encoder_config = CreateVideoEncoderConfig(codec_settings.codec);
2099   RTC_DCHECK_GT(parameters_.encoder_config.number_of_streams, 0);
2100 
2101   parameters_.config.rtp.payload_name = codec_settings.codec.name;
2102   parameters_.config.rtp.payload_type = codec_settings.codec.id;
2103   parameters_.config.rtp.raw_payload =
2104       codec_settings.codec.packetization == kPacketizationParamRaw;
2105   parameters_.config.rtp.ulpfec = codec_settings.ulpfec;
2106   parameters_.config.rtp.flexfec.payload_type =
2107       codec_settings.flexfec_payload_type;
2108 
2109   // Set RTX payload type if RTX is enabled.
2110   if (!parameters_.config.rtp.rtx.ssrcs.empty()) {
2111     if (codec_settings.rtx_payload_type == -1) {
2112       RTC_LOG(LS_WARNING)
2113           << "RTX SSRCs configured but there's no configured RTX "
2114              "payload type. Ignoring.";
2115       parameters_.config.rtp.rtx.ssrcs.clear();
2116     } else {
2117       parameters_.config.rtp.rtx.payload_type = codec_settings.rtx_payload_type;
2118     }
2119   }
2120 
2121   const bool has_lntf = HasLntf(codec_settings.codec);
2122   parameters_.config.rtp.lntf.enabled = has_lntf;
2123   parameters_.config.encoder_settings.capabilities.loss_notification = has_lntf;
2124 
2125   parameters_.config.rtp.nack.rtp_history_ms =
2126       HasNack(codec_settings.codec) ? kNackHistoryMs : 0;
2127 
2128   parameters_.codec_settings = codec_settings;
2129 
2130   // TODO(nisse): Avoid recreation, it should be enough to call
2131   // ReconfigureEncoder.
2132   RTC_LOG(LS_INFO) << "RecreateWebRtcStream (send) because of SetCodec.";
2133   RecreateWebRtcStream();
2134 }
2135 
SetSendParameters(const ChangedSendParameters & params)2136 void WebRtcVideoChannel::WebRtcVideoSendStream::SetSendParameters(
2137     const ChangedSendParameters& params) {
2138   RTC_DCHECK_RUN_ON(&thread_checker_);
2139   // |recreate_stream| means construction-time parameters have changed and the
2140   // sending stream needs to be reset with the new config.
2141   bool recreate_stream = false;
2142   if (params.rtcp_mode) {
2143     parameters_.config.rtp.rtcp_mode = *params.rtcp_mode;
2144     rtp_parameters_.rtcp.reduced_size =
2145         parameters_.config.rtp.rtcp_mode == webrtc::RtcpMode::kReducedSize;
2146     recreate_stream = true;
2147   }
2148   if (params.extmap_allow_mixed) {
2149     parameters_.config.rtp.extmap_allow_mixed = *params.extmap_allow_mixed;
2150     recreate_stream = true;
2151   }
2152   if (params.rtp_header_extensions) {
2153     parameters_.config.rtp.extensions = *params.rtp_header_extensions;
2154     rtp_parameters_.header_extensions = *params.rtp_header_extensions;
2155     recreate_stream = true;
2156   }
2157   if (params.mid) {
2158     parameters_.config.rtp.mid = *params.mid;
2159     recreate_stream = true;
2160   }
2161   if (params.max_bandwidth_bps) {
2162     parameters_.max_bitrate_bps = *params.max_bandwidth_bps;
2163     ReconfigureEncoder();
2164   }
2165   if (params.conference_mode) {
2166     parameters_.conference_mode = *params.conference_mode;
2167   }
2168 
2169   // Set codecs and options.
2170   if (params.send_codec) {
2171     SetCodec(*params.send_codec);
2172     recreate_stream = false;  // SetCodec has already recreated the stream.
2173   } else if (params.conference_mode && parameters_.codec_settings) {
2174     SetCodec(*parameters_.codec_settings);
2175     recreate_stream = false;  // SetCodec has already recreated the stream.
2176   }
2177   if (recreate_stream) {
2178     RTC_LOG(LS_INFO)
2179         << "RecreateWebRtcStream (send) because of SetSendParameters";
2180     RecreateWebRtcStream();
2181   }
2182 }
2183 
SetRtpParameters(const webrtc::RtpParameters & new_parameters)2184 webrtc::RTCError WebRtcVideoChannel::WebRtcVideoSendStream::SetRtpParameters(
2185     const webrtc::RtpParameters& new_parameters) {
2186   RTC_DCHECK_RUN_ON(&thread_checker_);
2187   webrtc::RTCError error = CheckRtpParametersInvalidModificationAndValues(
2188       rtp_parameters_, new_parameters);
2189   if (!error.ok()) {
2190     return error;
2191   }
2192 
2193   bool new_param = false;
2194   for (size_t i = 0; i < rtp_parameters_.encodings.size(); ++i) {
2195     if ((new_parameters.encodings[i].min_bitrate_bps !=
2196          rtp_parameters_.encodings[i].min_bitrate_bps) ||
2197         (new_parameters.encodings[i].max_bitrate_bps !=
2198          rtp_parameters_.encodings[i].max_bitrate_bps) ||
2199         (new_parameters.encodings[i].max_framerate !=
2200          rtp_parameters_.encodings[i].max_framerate) ||
2201         (new_parameters.encodings[i].scale_resolution_down_by !=
2202          rtp_parameters_.encodings[i].scale_resolution_down_by) ||
2203         (new_parameters.encodings[i].num_temporal_layers !=
2204          rtp_parameters_.encodings[i].num_temporal_layers)) {
2205       new_param = true;
2206       break;
2207     }
2208   }
2209 
2210   bool new_degradation_preference = false;
2211   if (new_parameters.degradation_preference !=
2212       rtp_parameters_.degradation_preference) {
2213     new_degradation_preference = true;
2214   }
2215 
2216   // TODO(bugs.webrtc.org/8807): The bitrate priority really doesn't require an
2217   // entire encoder reconfiguration, it just needs to update the bitrate
2218   // allocator.
2219   bool reconfigure_encoder =
2220       new_param || (new_parameters.encodings[0].bitrate_priority !=
2221                     rtp_parameters_.encodings[0].bitrate_priority);
2222 
2223   // TODO(bugs.webrtc.org/8807): The active field as well should not require
2224   // a full encoder reconfiguration, but it needs to update both the bitrate
2225   // allocator and the video bitrate allocator.
2226   bool new_send_state = false;
2227   for (size_t i = 0; i < rtp_parameters_.encodings.size(); ++i) {
2228     bool new_active = IsLayerActive(new_parameters.encodings[i]);
2229     bool old_active = IsLayerActive(rtp_parameters_.encodings[i]);
2230     if (new_active != old_active) {
2231       new_send_state = true;
2232     }
2233   }
2234   rtp_parameters_ = new_parameters;
2235   // Codecs are currently handled at the WebRtcVideoChannel level.
2236   rtp_parameters_.codecs.clear();
2237   if (reconfigure_encoder || new_send_state) {
2238     ReconfigureEncoder();
2239   }
2240   if (new_send_state) {
2241     UpdateSendState();
2242   }
2243   if (new_degradation_preference) {
2244     if (source_ && stream_) {
2245       stream_->SetSource(this, GetDegradationPreference());
2246     }
2247   }
2248   return webrtc::RTCError::OK();
2249 }
2250 
2251 webrtc::RtpParameters
GetRtpParameters() const2252 WebRtcVideoChannel::WebRtcVideoSendStream::GetRtpParameters() const {
2253   RTC_DCHECK_RUN_ON(&thread_checker_);
2254   return rtp_parameters_;
2255 }
2256 
SetFrameEncryptor(rtc::scoped_refptr<webrtc::FrameEncryptorInterface> frame_encryptor)2257 void WebRtcVideoChannel::WebRtcVideoSendStream::SetFrameEncryptor(
2258     rtc::scoped_refptr<webrtc::FrameEncryptorInterface> frame_encryptor) {
2259   RTC_DCHECK_RUN_ON(&thread_checker_);
2260   parameters_.config.frame_encryptor = frame_encryptor;
2261   if (stream_) {
2262     RTC_LOG(LS_INFO)
2263         << "RecreateWebRtcStream (send) because of SetFrameEncryptor, ssrc="
2264         << parameters_.config.rtp.ssrcs[0];
2265     RecreateWebRtcStream();
2266   }
2267 }
2268 
UpdateSendState()2269 void WebRtcVideoChannel::WebRtcVideoSendStream::UpdateSendState() {
2270   RTC_DCHECK_RUN_ON(&thread_checker_);
2271   if (sending_) {
2272     RTC_DCHECK(stream_ != nullptr);
2273     size_t num_layers = rtp_parameters_.encodings.size();
2274     if (parameters_.encoder_config.number_of_streams == 1) {
2275       // SVC is used. Only one simulcast layer is present.
2276       num_layers = 1;
2277     }
2278     std::vector<bool> active_layers(num_layers);
2279     for (size_t i = 0; i < num_layers; ++i) {
2280       active_layers[i] = IsLayerActive(rtp_parameters_.encodings[i]);
2281     }
2282     if (parameters_.encoder_config.number_of_streams == 1 &&
2283         rtp_parameters_.encodings.size() > 1) {
2284       // SVC is used.
2285       // The only present simulcast layer should be active if any of the
2286       // configured SVC layers is active.
2287       active_layers[0] =
2288           absl::c_any_of(rtp_parameters_.encodings,
2289                          [](const auto& encoding) { return encoding.active; });
2290     }
2291     // This updates what simulcast layers are sending, and possibly starts
2292     // or stops the VideoSendStream.
2293     stream_->UpdateActiveSimulcastLayers(active_layers);
2294   } else {
2295     if (stream_ != nullptr) {
2296       stream_->Stop();
2297     }
2298   }
2299 }
2300 
2301 webrtc::VideoEncoderConfig
CreateVideoEncoderConfig(const VideoCodec & codec) const2302 WebRtcVideoChannel::WebRtcVideoSendStream::CreateVideoEncoderConfig(
2303     const VideoCodec& codec) const {
2304   RTC_DCHECK_RUN_ON(&thread_checker_);
2305   webrtc::VideoEncoderConfig encoder_config;
2306   encoder_config.codec_type = webrtc::PayloadStringToCodecType(codec.name);
2307   encoder_config.video_format =
2308       webrtc::SdpVideoFormat(codec.name, codec.params);
2309 
2310   bool is_screencast = parameters_.options.is_screencast.value_or(false);
2311   if (is_screencast) {
2312     encoder_config.min_transmit_bitrate_bps =
2313         1000 * parameters_.options.screencast_min_bitrate_kbps.value_or(0);
2314     encoder_config.content_type =
2315         webrtc::VideoEncoderConfig::ContentType::kScreen;
2316   } else {
2317     encoder_config.min_transmit_bitrate_bps = 0;
2318     encoder_config.content_type =
2319         webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo;
2320   }
2321 
2322   // By default, the stream count for the codec configuration should match the
2323   // number of negotiated ssrcs. But if the codec is disabled for simulcast
2324   // or a screencast (and not in simulcast screenshare experiment), only
2325   // configure a single stream.
2326   encoder_config.number_of_streams = parameters_.config.rtp.ssrcs.size();
2327   if (IsCodecDisabledForSimulcast(codec.name)) {
2328     encoder_config.number_of_streams = 1;
2329   }
2330 
2331   // parameters_.max_bitrate comes from the max bitrate set at the SDP
2332   // (m-section) level with the attribute "b=AS." Note that we override this
2333   // value below if the RtpParameters max bitrate set with
2334   // RtpSender::SetParameters has a lower value.
2335   int stream_max_bitrate = parameters_.max_bitrate_bps;
2336   // When simulcast is enabled (when there are multiple encodings),
2337   // encodings[i].max_bitrate_bps will be enforced by
2338   // encoder_config.simulcast_layers[i].max_bitrate_bps. Otherwise, it's
2339   // enforced by stream_max_bitrate, taking the minimum of the two maximums
2340   // (one coming from SDP, the other coming from RtpParameters).
2341   if (rtp_parameters_.encodings[0].max_bitrate_bps &&
2342       rtp_parameters_.encodings.size() == 1) {
2343     stream_max_bitrate =
2344         MinPositive(*(rtp_parameters_.encodings[0].max_bitrate_bps),
2345                     parameters_.max_bitrate_bps);
2346   }
2347 
2348   // The codec max bitrate comes from the "x-google-max-bitrate" parameter
2349   // attribute set in the SDP for a specific codec. As done in
2350   // WebRtcVideoChannel::SetSendParameters, this value does not override the
2351   // stream max_bitrate set above.
2352   int codec_max_bitrate_kbps;
2353   if (codec.GetParam(kCodecParamMaxBitrate, &codec_max_bitrate_kbps) &&
2354       stream_max_bitrate == -1) {
2355     stream_max_bitrate = codec_max_bitrate_kbps * 1000;
2356   }
2357   encoder_config.max_bitrate_bps = stream_max_bitrate;
2358 
2359   // The encoder config's default bitrate priority is set to 1.0,
2360   // unless it is set through the sender's encoding parameters.
2361   // The bitrate priority, which is used in the bitrate allocation, is done
2362   // on a per sender basis, so we use the first encoding's value.
2363   encoder_config.bitrate_priority =
2364       rtp_parameters_.encodings[0].bitrate_priority;
2365 
2366   // Application-controlled state is held in the encoder_config's
2367   // simulcast_layers. Currently this is used to control which simulcast layers
2368   // are active and for configuring the min/max bitrate and max framerate.
2369   // The encoder_config's simulcast_layers is also used for non-simulcast (when
2370   // there is a single layer).
2371   RTC_DCHECK_GE(rtp_parameters_.encodings.size(),
2372                 encoder_config.number_of_streams);
2373   RTC_DCHECK_GT(encoder_config.number_of_streams, 0);
2374 
2375   // Copy all provided constraints.
2376   encoder_config.simulcast_layers.resize(rtp_parameters_.encodings.size());
2377   for (size_t i = 0; i < encoder_config.simulcast_layers.size(); ++i) {
2378     encoder_config.simulcast_layers[i].active =
2379         rtp_parameters_.encodings[i].active;
2380     if (rtp_parameters_.encodings[i].min_bitrate_bps) {
2381       encoder_config.simulcast_layers[i].min_bitrate_bps =
2382           *rtp_parameters_.encodings[i].min_bitrate_bps;
2383     }
2384     if (rtp_parameters_.encodings[i].max_bitrate_bps) {
2385       encoder_config.simulcast_layers[i].max_bitrate_bps =
2386           *rtp_parameters_.encodings[i].max_bitrate_bps;
2387     }
2388     if (rtp_parameters_.encodings[i].max_framerate) {
2389       encoder_config.simulcast_layers[i].max_framerate =
2390           *rtp_parameters_.encodings[i].max_framerate;
2391     }
2392     if (rtp_parameters_.encodings[i].scale_resolution_down_by) {
2393       encoder_config.simulcast_layers[i].scale_resolution_down_by =
2394           *rtp_parameters_.encodings[i].scale_resolution_down_by;
2395     }
2396     if (rtp_parameters_.encodings[i].num_temporal_layers) {
2397       encoder_config.simulcast_layers[i].num_temporal_layers =
2398           *rtp_parameters_.encodings[i].num_temporal_layers;
2399     }
2400   }
2401 
2402   int max_qp = kDefaultQpMax;
2403   codec.GetParam(kCodecParamMaxQuantization, &max_qp);
2404   encoder_config.video_stream_factory =
2405       new rtc::RefCountedObject<EncoderStreamFactory>(
2406           codec.name, max_qp, is_screencast, parameters_.conference_mode);
2407   return encoder_config;
2408 }
2409 
ReconfigureEncoder()2410 void WebRtcVideoChannel::WebRtcVideoSendStream::ReconfigureEncoder() {
2411   RTC_DCHECK_RUN_ON(&thread_checker_);
2412   if (!stream_) {
2413     // The webrtc::VideoSendStream |stream_| has not yet been created but other
2414     // parameters has changed.
2415     return;
2416   }
2417 
2418   RTC_DCHECK_GT(parameters_.encoder_config.number_of_streams, 0);
2419 
2420   RTC_CHECK(parameters_.codec_settings);
2421   VideoCodecSettings codec_settings = *parameters_.codec_settings;
2422 
2423   webrtc::VideoEncoderConfig encoder_config =
2424       CreateVideoEncoderConfig(codec_settings.codec);
2425 
2426   encoder_config.encoder_specific_settings =
2427       ConfigureVideoEncoderSettings(codec_settings.codec);
2428 
2429   stream_->ReconfigureVideoEncoder(encoder_config.Copy());
2430 
2431   encoder_config.encoder_specific_settings = NULL;
2432 
2433   parameters_.encoder_config = std::move(encoder_config);
2434 }
2435 
SetSend(bool send)2436 void WebRtcVideoChannel::WebRtcVideoSendStream::SetSend(bool send) {
2437   RTC_DCHECK_RUN_ON(&thread_checker_);
2438   sending_ = send;
2439   UpdateSendState();
2440 }
2441 
RemoveSink(rtc::VideoSinkInterface<webrtc::VideoFrame> * sink)2442 void WebRtcVideoChannel::WebRtcVideoSendStream::RemoveSink(
2443     rtc::VideoSinkInterface<webrtc::VideoFrame>* sink) {
2444   RTC_DCHECK_RUN_ON(&thread_checker_);
2445   RTC_DCHECK(encoder_sink_ == sink);
2446   encoder_sink_ = nullptr;
2447   source_->RemoveSink(sink);
2448 }
2449 
AddOrUpdateSink(rtc::VideoSinkInterface<webrtc::VideoFrame> * sink,const rtc::VideoSinkWants & wants)2450 void WebRtcVideoChannel::WebRtcVideoSendStream::AddOrUpdateSink(
2451     rtc::VideoSinkInterface<webrtc::VideoFrame>* sink,
2452     const rtc::VideoSinkWants& wants) {
2453   if (worker_thread_ == rtc::Thread::Current()) {
2454     // AddOrUpdateSink is called on |worker_thread_| if this is the first
2455     // registration of |sink|.
2456     RTC_DCHECK_RUN_ON(&thread_checker_);
2457     encoder_sink_ = sink;
2458     source_->AddOrUpdateSink(encoder_sink_, wants);
2459   } else {
2460     // Subsequent calls to AddOrUpdateSink will happen on the encoder task
2461     // queue.
2462     invoker_.AsyncInvoke<void>(
2463         RTC_FROM_HERE, worker_thread_, [this, sink, wants] {
2464           RTC_DCHECK_RUN_ON(&thread_checker_);
2465           // |sink| may be invalidated after this task was posted since
2466           // RemoveSink is called on the worker thread.
2467           bool encoder_sink_valid = (sink == encoder_sink_);
2468           if (source_ && encoder_sink_valid) {
2469             source_->AddOrUpdateSink(encoder_sink_, wants);
2470           }
2471         });
2472   }
2473 }
2474 std::vector<VideoSenderInfo>
GetPerLayerVideoSenderInfos(bool log_stats)2475 WebRtcVideoChannel::WebRtcVideoSendStream::GetPerLayerVideoSenderInfos(
2476     bool log_stats) {
2477   RTC_DCHECK_RUN_ON(&thread_checker_);
2478   VideoSenderInfo common_info;
2479   if (parameters_.codec_settings) {
2480     common_info.codec_name = parameters_.codec_settings->codec.name;
2481     common_info.codec_payload_type = parameters_.codec_settings->codec.id;
2482   }
2483   std::vector<VideoSenderInfo> infos;
2484   webrtc::VideoSendStream::Stats stats;
2485   if (stream_ == nullptr) {
2486     for (uint32_t ssrc : parameters_.config.rtp.ssrcs) {
2487       common_info.add_ssrc(ssrc);
2488     }
2489     infos.push_back(common_info);
2490     return infos;
2491   } else {
2492     stats = stream_->GetStats();
2493     if (log_stats)
2494       RTC_LOG(LS_INFO) << stats.ToString(rtc::TimeMillis());
2495 
2496     // Metrics that are in common for all substreams.
2497     common_info.adapt_changes = stats.number_of_cpu_adapt_changes;
2498     common_info.adapt_reason =
2499         stats.cpu_limited_resolution ? ADAPTREASON_CPU : ADAPTREASON_NONE;
2500     common_info.has_entered_low_resolution = stats.has_entered_low_resolution;
2501 
2502     // Get bandwidth limitation info from stream_->GetStats().
2503     // Input resolution (output from video_adapter) can be further scaled down
2504     // or higher video layer(s) can be dropped due to bitrate constraints.
2505     // Note, adapt_changes only include changes from the video_adapter.
2506     if (stats.bw_limited_resolution)
2507       common_info.adapt_reason |= ADAPTREASON_BANDWIDTH;
2508 
2509     common_info.quality_limitation_reason = stats.quality_limitation_reason;
2510     common_info.quality_limitation_durations_ms =
2511         stats.quality_limitation_durations_ms;
2512     common_info.quality_limitation_resolution_changes =
2513         stats.quality_limitation_resolution_changes;
2514     common_info.encoder_implementation_name = stats.encoder_implementation_name;
2515     common_info.ssrc_groups = ssrc_groups_;
2516     common_info.framerate_input = stats.input_frame_rate;
2517     common_info.avg_encode_ms = stats.avg_encode_time_ms;
2518     common_info.encode_usage_percent = stats.encode_usage_percent;
2519     common_info.nominal_bitrate = stats.media_bitrate_bps;
2520     common_info.content_type = stats.content_type;
2521     common_info.aggregated_framerate_sent = stats.encode_frame_rate;
2522     common_info.aggregated_huge_frames_sent = stats.huge_frames_sent;
2523 
2524     // If we don't have any substreams, get the remaining metrics from |stats|.
2525     // Otherwise, these values are obtained from |sub_stream| below.
2526     if (stats.substreams.empty()) {
2527       for (uint32_t ssrc : parameters_.config.rtp.ssrcs) {
2528         common_info.add_ssrc(ssrc);
2529       }
2530       common_info.framerate_sent = stats.encode_frame_rate;
2531       common_info.frames_encoded = stats.frames_encoded;
2532       common_info.total_encode_time_ms = stats.total_encode_time_ms;
2533       common_info.total_encoded_bytes_target = stats.total_encoded_bytes_target;
2534       common_info.frames_sent = stats.frames_encoded;
2535       common_info.huge_frames_sent = stats.huge_frames_sent;
2536       infos.push_back(common_info);
2537       return infos;
2538     }
2539   }
2540   auto outbound_rtp_substreams =
2541       MergeInfoAboutOutboundRtpSubstreams(stats.substreams);
2542   for (const auto& pair : outbound_rtp_substreams) {
2543     auto info = common_info;
2544     info.add_ssrc(pair.first);
2545     info.rid = parameters_.config.rtp.GetRidForSsrc(pair.first);
2546     auto stream_stats = pair.second;
2547     RTC_DCHECK_EQ(stream_stats.type,
2548                   webrtc::VideoSendStream::StreamStats::StreamType::kMedia);
2549     info.payload_bytes_sent = stream_stats.rtp_stats.transmitted.payload_bytes;
2550     info.header_and_padding_bytes_sent =
2551         stream_stats.rtp_stats.transmitted.header_bytes +
2552         stream_stats.rtp_stats.transmitted.padding_bytes;
2553     info.packets_sent = stream_stats.rtp_stats.transmitted.packets;
2554     info.total_packet_send_delay_ms += stream_stats.total_packet_send_delay_ms;
2555     info.send_frame_width = stream_stats.width;
2556     info.send_frame_height = stream_stats.height;
2557     info.key_frames_encoded = stream_stats.frame_counts.key_frames;
2558     info.framerate_sent = stream_stats.encode_frame_rate;
2559     info.frames_encoded = stream_stats.frames_encoded;
2560     info.frames_sent = stream_stats.frames_encoded;
2561     info.retransmitted_bytes_sent =
2562         stream_stats.rtp_stats.retransmitted.payload_bytes;
2563     info.retransmitted_packets_sent =
2564         stream_stats.rtp_stats.retransmitted.packets;
2565     info.packets_lost = stream_stats.rtcp_stats.packets_lost;
2566     info.firs_rcvd = stream_stats.rtcp_packet_type_counts.fir_packets;
2567     info.nacks_rcvd = stream_stats.rtcp_packet_type_counts.nack_packets;
2568     info.plis_rcvd = stream_stats.rtcp_packet_type_counts.pli_packets;
2569     if (stream_stats.report_block_data.has_value()) {
2570       info.report_block_datas.push_back(stream_stats.report_block_data.value());
2571     }
2572     info.fraction_lost =
2573         static_cast<float>(stream_stats.rtcp_stats.fraction_lost) / (1 << 8);
2574     info.qp_sum = stream_stats.qp_sum;
2575     info.total_encode_time_ms = stream_stats.total_encode_time_ms;
2576     info.total_encoded_bytes_target = stream_stats.total_encoded_bytes_target;
2577     info.huge_frames_sent = stream_stats.huge_frames_sent;
2578     infos.push_back(info);
2579   }
2580   return infos;
2581 }
2582 
2583 VideoSenderInfo
GetAggregatedVideoSenderInfo(const std::vector<VideoSenderInfo> & infos) const2584 WebRtcVideoChannel::WebRtcVideoSendStream::GetAggregatedVideoSenderInfo(
2585     const std::vector<VideoSenderInfo>& infos) const {
2586   RTC_DCHECK_RUN_ON(&thread_checker_);
2587   RTC_CHECK(!infos.empty());
2588   if (infos.size() == 1) {
2589     return infos[0];
2590   }
2591   VideoSenderInfo info = infos[0];
2592   info.local_stats.clear();
2593   for (uint32_t ssrc : parameters_.config.rtp.ssrcs) {
2594     info.add_ssrc(ssrc);
2595   }
2596   info.framerate_sent = info.aggregated_framerate_sent;
2597   info.huge_frames_sent = info.aggregated_huge_frames_sent;
2598 
2599   for (size_t i = 1; i < infos.size(); i++) {
2600     info.key_frames_encoded += infos[i].key_frames_encoded;
2601     info.payload_bytes_sent += infos[i].payload_bytes_sent;
2602     info.header_and_padding_bytes_sent +=
2603         infos[i].header_and_padding_bytes_sent;
2604     info.packets_sent += infos[i].packets_sent;
2605     info.total_packet_send_delay_ms += infos[i].total_packet_send_delay_ms;
2606     info.retransmitted_bytes_sent += infos[i].retransmitted_bytes_sent;
2607     info.retransmitted_packets_sent += infos[i].retransmitted_packets_sent;
2608     info.packets_lost += infos[i].packets_lost;
2609     if (infos[i].send_frame_width > info.send_frame_width)
2610       info.send_frame_width = infos[i].send_frame_width;
2611     if (infos[i].send_frame_height > info.send_frame_height)
2612       info.send_frame_height = infos[i].send_frame_height;
2613     info.firs_rcvd += infos[i].firs_rcvd;
2614     info.nacks_rcvd += infos[i].nacks_rcvd;
2615     info.plis_rcvd += infos[i].plis_rcvd;
2616     if (infos[i].report_block_datas.size())
2617       info.report_block_datas.push_back(infos[i].report_block_datas[0]);
2618     if (infos[i].qp_sum) {
2619       if (!info.qp_sum) {
2620         info.qp_sum = 0;
2621       }
2622       info.qp_sum = *info.qp_sum + *infos[i].qp_sum;
2623     }
2624     info.frames_encoded += infos[i].frames_encoded;
2625     info.frames_sent += infos[i].frames_sent;
2626     info.total_encode_time_ms += infos[i].total_encode_time_ms;
2627     info.total_encoded_bytes_target += infos[i].total_encoded_bytes_target;
2628   }
2629   return info;
2630 }
2631 
FillBitrateInfo(BandwidthEstimationInfo * bwe_info)2632 void WebRtcVideoChannel::WebRtcVideoSendStream::FillBitrateInfo(
2633     BandwidthEstimationInfo* bwe_info) {
2634   RTC_DCHECK_RUN_ON(&thread_checker_);
2635   if (stream_ == NULL) {
2636     return;
2637   }
2638   webrtc::VideoSendStream::Stats stats = stream_->GetStats();
2639   for (std::map<uint32_t, webrtc::VideoSendStream::StreamStats>::iterator it =
2640            stats.substreams.begin();
2641        it != stats.substreams.end(); ++it) {
2642     bwe_info->transmit_bitrate += it->second.total_bitrate_bps;
2643     bwe_info->retransmit_bitrate += it->second.retransmit_bitrate_bps;
2644   }
2645   bwe_info->target_enc_bitrate += stats.target_media_bitrate_bps;
2646   bwe_info->actual_enc_bitrate += stats.media_bitrate_bps;
2647 }
2648 
2649 void WebRtcVideoChannel::WebRtcVideoSendStream::
SetEncoderToPacketizerFrameTransformer(rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)2650     SetEncoderToPacketizerFrameTransformer(
2651         rtc::scoped_refptr<webrtc::FrameTransformerInterface>
2652             frame_transformer) {
2653   RTC_DCHECK_RUN_ON(&thread_checker_);
2654   parameters_.config.frame_transformer = std::move(frame_transformer);
2655   if (stream_)
2656     RecreateWebRtcStream();
2657 }
2658 
RecreateWebRtcStream()2659 void WebRtcVideoChannel::WebRtcVideoSendStream::RecreateWebRtcStream() {
2660   RTC_DCHECK_RUN_ON(&thread_checker_);
2661   if (stream_ != NULL) {
2662     call_->DestroyVideoSendStream(stream_);
2663   }
2664 
2665   RTC_CHECK(parameters_.codec_settings);
2666   RTC_DCHECK_EQ((parameters_.encoder_config.content_type ==
2667                  webrtc::VideoEncoderConfig::ContentType::kScreen),
2668                 parameters_.options.is_screencast.value_or(false))
2669       << "encoder content type inconsistent with screencast option";
2670   parameters_.encoder_config.encoder_specific_settings =
2671       ConfigureVideoEncoderSettings(parameters_.codec_settings->codec);
2672 
2673   webrtc::VideoSendStream::Config config = parameters_.config.Copy();
2674   if (!config.rtp.rtx.ssrcs.empty() && config.rtp.rtx.payload_type == -1) {
2675     RTC_LOG(LS_WARNING) << "RTX SSRCs configured but there's no configured RTX "
2676                            "payload type the set codec. Ignoring RTX.";
2677     config.rtp.rtx.ssrcs.clear();
2678   }
2679   if (parameters_.encoder_config.number_of_streams == 1) {
2680     // SVC is used instead of simulcast. Remove unnecessary SSRCs.
2681     if (config.rtp.ssrcs.size() > 1) {
2682       config.rtp.ssrcs.resize(1);
2683       if (config.rtp.rtx.ssrcs.size() > 1) {
2684         config.rtp.rtx.ssrcs.resize(1);
2685       }
2686     }
2687   }
2688   stream_ = call_->CreateVideoSendStream(std::move(config),
2689                                          parameters_.encoder_config.Copy());
2690 
2691   parameters_.encoder_config.encoder_specific_settings = NULL;
2692 
2693   if (source_) {
2694     stream_->SetSource(this, GetDegradationPreference());
2695   }
2696 
2697   // Call stream_->Start() if necessary conditions are met.
2698   UpdateSendState();
2699 }
2700 
WebRtcVideoReceiveStream(WebRtcVideoChannel * channel,webrtc::Call * call,const StreamParams & sp,webrtc::VideoReceiveStream::Config config,webrtc::VideoDecoderFactory * decoder_factory,bool default_stream,const std::vector<VideoCodecSettings> & recv_codecs,const webrtc::FlexfecReceiveStream::Config & flexfec_config)2701 WebRtcVideoChannel::WebRtcVideoReceiveStream::WebRtcVideoReceiveStream(
2702     WebRtcVideoChannel* channel,
2703     webrtc::Call* call,
2704     const StreamParams& sp,
2705     webrtc::VideoReceiveStream::Config config,
2706     webrtc::VideoDecoderFactory* decoder_factory,
2707     bool default_stream,
2708     const std::vector<VideoCodecSettings>& recv_codecs,
2709     const webrtc::FlexfecReceiveStream::Config& flexfec_config)
2710     : channel_(channel),
2711       call_(call),
2712       stream_params_(sp),
2713       stream_(NULL),
2714       default_stream_(default_stream),
2715       config_(std::move(config)),
2716       flexfec_config_(flexfec_config),
2717       flexfec_stream_(nullptr),
2718       decoder_factory_(decoder_factory),
2719       sink_(NULL),
2720       first_frame_timestamp_(-1),
2721       estimated_remote_start_ntp_time_ms_(0) {
2722   config_.renderer = this;
2723   ConfigureCodecs(recv_codecs);
2724   ConfigureFlexfecCodec(flexfec_config.payload_type);
2725   MaybeRecreateWebRtcFlexfecStream();
2726   RecreateWebRtcVideoStream();
2727 }
2728 
~WebRtcVideoReceiveStream()2729 WebRtcVideoChannel::WebRtcVideoReceiveStream::~WebRtcVideoReceiveStream() {
2730   if (flexfec_stream_) {
2731     MaybeDissociateFlexfecFromVideo();
2732     call_->DestroyFlexfecReceiveStream(flexfec_stream_);
2733   }
2734   call_->DestroyVideoReceiveStream(stream_);
2735 }
2736 
2737 const std::vector<uint32_t>&
GetSsrcs() const2738 WebRtcVideoChannel::WebRtcVideoReceiveStream::GetSsrcs() const {
2739   return stream_params_.ssrcs;
2740 }
2741 
2742 std::vector<webrtc::RtpSource>
GetSources()2743 WebRtcVideoChannel::WebRtcVideoReceiveStream::GetSources() {
2744   RTC_DCHECK(stream_);
2745   return stream_->GetSources();
2746 }
2747 
2748 webrtc::RtpParameters
GetRtpParameters() const2749 WebRtcVideoChannel::WebRtcVideoReceiveStream::GetRtpParameters() const {
2750   webrtc::RtpParameters rtp_parameters;
2751 
2752   std::vector<uint32_t> primary_ssrcs;
2753   stream_params_.GetPrimarySsrcs(&primary_ssrcs);
2754   for (uint32_t ssrc : primary_ssrcs) {
2755     rtp_parameters.encodings.emplace_back();
2756     rtp_parameters.encodings.back().ssrc = ssrc;
2757   }
2758 
2759   rtp_parameters.header_extensions = config_.rtp.extensions;
2760   rtp_parameters.rtcp.reduced_size =
2761       config_.rtp.rtcp_mode == webrtc::RtcpMode::kReducedSize;
2762 
2763   return rtp_parameters;
2764 }
2765 
ConfigureCodecs(const std::vector<VideoCodecSettings> & recv_codecs)2766 void WebRtcVideoChannel::WebRtcVideoReceiveStream::ConfigureCodecs(
2767     const std::vector<VideoCodecSettings>& recv_codecs) {
2768   RTC_DCHECK(!recv_codecs.empty());
2769   config_.decoders.clear();
2770   config_.rtp.rtx_associated_payload_types.clear();
2771   config_.rtp.raw_payload_types.clear();
2772   for (const auto& recv_codec : recv_codecs) {
2773     webrtc::SdpVideoFormat video_format(recv_codec.codec.name,
2774                                         recv_codec.codec.params);
2775 
2776     webrtc::VideoReceiveStream::Decoder decoder;
2777     decoder.decoder_factory = decoder_factory_;
2778     decoder.video_format = video_format;
2779     decoder.payload_type = recv_codec.codec.id;
2780     decoder.video_format =
2781         webrtc::SdpVideoFormat(recv_codec.codec.name, recv_codec.codec.params);
2782     config_.decoders.push_back(decoder);
2783     config_.rtp.rtx_associated_payload_types[recv_codec.rtx_payload_type] =
2784         recv_codec.codec.id;
2785     if (recv_codec.codec.packetization == kPacketizationParamRaw) {
2786       config_.rtp.raw_payload_types.insert(recv_codec.codec.id);
2787     }
2788   }
2789 
2790   const auto& codec = recv_codecs.front();
2791   config_.rtp.ulpfec_payload_type = codec.ulpfec.ulpfec_payload_type;
2792   config_.rtp.red_payload_type = codec.ulpfec.red_payload_type;
2793 
2794   config_.rtp.lntf.enabled = HasLntf(codec.codec);
2795   config_.rtp.nack.rtp_history_ms = HasNack(codec.codec) ? kNackHistoryMs : 0;
2796   config_.rtp.rtcp_xr.receiver_reference_time_report = HasRrtr(codec.codec);
2797   if (codec.ulpfec.red_rtx_payload_type != -1) {
2798     config_.rtp
2799         .rtx_associated_payload_types[codec.ulpfec.red_rtx_payload_type] =
2800         codec.ulpfec.red_payload_type;
2801   }
2802 }
2803 
ConfigureFlexfecCodec(int flexfec_payload_type)2804 void WebRtcVideoChannel::WebRtcVideoReceiveStream::ConfigureFlexfecCodec(
2805     int flexfec_payload_type) {
2806   flexfec_config_.payload_type = flexfec_payload_type;
2807 }
2808 
SetLocalSsrc(uint32_t local_ssrc)2809 void WebRtcVideoChannel::WebRtcVideoReceiveStream::SetLocalSsrc(
2810     uint32_t local_ssrc) {
2811   // TODO(pbos): Consider turning this sanity check into a RTC_DCHECK. You
2812   // should not be able to create a sender with the same SSRC as a receiver, but
2813   // right now this can't be done due to unittests depending on receiving what
2814   // they are sending from the same MediaChannel.
2815   if (local_ssrc == config_.rtp.local_ssrc) {
2816     RTC_DLOG(LS_INFO) << "Ignoring call to SetLocalSsrc because parameters are "
2817                          "unchanged; local_ssrc="
2818                       << local_ssrc;
2819     return;
2820   }
2821 
2822   config_.rtp.local_ssrc = local_ssrc;
2823   flexfec_config_.local_ssrc = local_ssrc;
2824   RTC_LOG(LS_INFO)
2825       << "RecreateWebRtcStream (recv) because of SetLocalSsrc; local_ssrc="
2826       << local_ssrc;
2827   MaybeRecreateWebRtcFlexfecStream();
2828   RecreateWebRtcVideoStream();
2829 }
2830 
SetFeedbackParameters(bool lntf_enabled,bool nack_enabled,bool transport_cc_enabled,webrtc::RtcpMode rtcp_mode)2831 void WebRtcVideoChannel::WebRtcVideoReceiveStream::SetFeedbackParameters(
2832     bool lntf_enabled,
2833     bool nack_enabled,
2834     bool transport_cc_enabled,
2835     webrtc::RtcpMode rtcp_mode) {
2836   int nack_history_ms = nack_enabled ? kNackHistoryMs : 0;
2837   if (config_.rtp.lntf.enabled == lntf_enabled &&
2838       config_.rtp.nack.rtp_history_ms == nack_history_ms &&
2839       config_.rtp.transport_cc == transport_cc_enabled &&
2840       config_.rtp.rtcp_mode == rtcp_mode) {
2841     RTC_LOG(LS_INFO)
2842         << "Ignoring call to SetFeedbackParameters because parameters are "
2843            "unchanged; lntf="
2844         << lntf_enabled << ", nack=" << nack_enabled
2845         << ", transport_cc=" << transport_cc_enabled;
2846     return;
2847   }
2848   config_.rtp.lntf.enabled = lntf_enabled;
2849   config_.rtp.nack.rtp_history_ms = nack_history_ms;
2850   config_.rtp.transport_cc = transport_cc_enabled;
2851   config_.rtp.rtcp_mode = rtcp_mode;
2852   // TODO(brandtr): We should be spec-compliant and set |transport_cc| here
2853   // based on the rtcp-fb for the FlexFEC codec, not the media codec.
2854   flexfec_config_.transport_cc = config_.rtp.transport_cc;
2855   flexfec_config_.rtcp_mode = config_.rtp.rtcp_mode;
2856   RTC_LOG(LS_INFO)
2857       << "RecreateWebRtcStream (recv) because of SetFeedbackParameters; nack="
2858       << nack_enabled << ", transport_cc=" << transport_cc_enabled;
2859   MaybeRecreateWebRtcFlexfecStream();
2860   RecreateWebRtcVideoStream();
2861 }
2862 
SetRecvParameters(const ChangedRecvParameters & params)2863 void WebRtcVideoChannel::WebRtcVideoReceiveStream::SetRecvParameters(
2864     const ChangedRecvParameters& params) {
2865   bool video_needs_recreation = false;
2866   bool flexfec_needs_recreation = false;
2867   if (params.codec_settings) {
2868     ConfigureCodecs(*params.codec_settings);
2869     video_needs_recreation = true;
2870   }
2871   if (params.rtp_header_extensions) {
2872     config_.rtp.extensions = *params.rtp_header_extensions;
2873     flexfec_config_.rtp_header_extensions = *params.rtp_header_extensions;
2874     video_needs_recreation = true;
2875     flexfec_needs_recreation = true;
2876   }
2877   if (params.flexfec_payload_type) {
2878     ConfigureFlexfecCodec(*params.flexfec_payload_type);
2879     flexfec_needs_recreation = true;
2880   }
2881   if (flexfec_needs_recreation) {
2882     RTC_LOG(LS_INFO) << "MaybeRecreateWebRtcFlexfecStream (recv) because of "
2883                         "SetRecvParameters";
2884     MaybeRecreateWebRtcFlexfecStream();
2885   }
2886   if (video_needs_recreation) {
2887     RTC_LOG(LS_INFO)
2888         << "RecreateWebRtcVideoStream (recv) because of SetRecvParameters";
2889     RecreateWebRtcVideoStream();
2890   }
2891 }
2892 
RecreateWebRtcVideoStream()2893 void WebRtcVideoChannel::WebRtcVideoReceiveStream::RecreateWebRtcVideoStream() {
2894   absl::optional<int> base_minimum_playout_delay_ms;
2895   absl::optional<webrtc::VideoReceiveStream::RecordingState> recording_state;
2896   if (stream_) {
2897     base_minimum_playout_delay_ms = stream_->GetBaseMinimumPlayoutDelayMs();
2898     recording_state = stream_->SetAndGetRecordingState(
2899         webrtc::VideoReceiveStream::RecordingState(),
2900         /*generate_key_frame=*/false);
2901     MaybeDissociateFlexfecFromVideo();
2902     call_->DestroyVideoReceiveStream(stream_);
2903     stream_ = nullptr;
2904   }
2905   webrtc::VideoReceiveStream::Config config = config_.Copy();
2906   config.rtp.protected_by_flexfec = (flexfec_stream_ != nullptr);
2907   config.stream_id = stream_params_.id;
2908   stream_ = call_->CreateVideoReceiveStream(std::move(config));
2909   if (base_minimum_playout_delay_ms) {
2910     stream_->SetBaseMinimumPlayoutDelayMs(
2911         base_minimum_playout_delay_ms.value());
2912   }
2913   if (recording_state) {
2914     stream_->SetAndGetRecordingState(std::move(*recording_state),
2915                                      /*generate_key_frame=*/false);
2916   }
2917   MaybeAssociateFlexfecWithVideo();
2918   stream_->Start();
2919 
2920   if (webrtc::field_trial::IsEnabled(
2921           "WebRTC-Video-BufferPacketsWithUnknownSsrc")) {
2922     channel_->BackfillBufferedPackets(stream_params_.ssrcs);
2923   }
2924 }
2925 
2926 void WebRtcVideoChannel::WebRtcVideoReceiveStream::
MaybeRecreateWebRtcFlexfecStream()2927     MaybeRecreateWebRtcFlexfecStream() {
2928   if (flexfec_stream_) {
2929     MaybeDissociateFlexfecFromVideo();
2930     call_->DestroyFlexfecReceiveStream(flexfec_stream_);
2931     flexfec_stream_ = nullptr;
2932   }
2933   if (flexfec_config_.IsCompleteAndEnabled()) {
2934     flexfec_stream_ = call_->CreateFlexfecReceiveStream(flexfec_config_);
2935     MaybeAssociateFlexfecWithVideo();
2936   }
2937 }
2938 
2939 void WebRtcVideoChannel::WebRtcVideoReceiveStream::
MaybeAssociateFlexfecWithVideo()2940     MaybeAssociateFlexfecWithVideo() {
2941   if (stream_ && flexfec_stream_) {
2942     stream_->AddSecondarySink(flexfec_stream_);
2943   }
2944 }
2945 
2946 void WebRtcVideoChannel::WebRtcVideoReceiveStream::
MaybeDissociateFlexfecFromVideo()2947     MaybeDissociateFlexfecFromVideo() {
2948   if (stream_ && flexfec_stream_) {
2949     stream_->RemoveSecondarySink(flexfec_stream_);
2950   }
2951 }
2952 
OnFrame(const webrtc::VideoFrame & frame)2953 void WebRtcVideoChannel::WebRtcVideoReceiveStream::OnFrame(
2954     const webrtc::VideoFrame& frame) {
2955   webrtc::MutexLock lock(&sink_lock_);
2956 
2957   int64_t time_now_ms = rtc::TimeMillis();
2958   if (first_frame_timestamp_ < 0)
2959     first_frame_timestamp_ = time_now_ms;
2960   int64_t elapsed_time_ms = time_now_ms - first_frame_timestamp_;
2961   if (frame.ntp_time_ms() > 0)
2962     estimated_remote_start_ntp_time_ms_ = frame.ntp_time_ms() - elapsed_time_ms;
2963 
2964   if (sink_ == NULL) {
2965     RTC_LOG(LS_WARNING) << "VideoReceiveStream not connected to a VideoSink.";
2966     return;
2967   }
2968 
2969   sink_->OnFrame(frame);
2970 }
2971 
IsDefaultStream() const2972 bool WebRtcVideoChannel::WebRtcVideoReceiveStream::IsDefaultStream() const {
2973   return default_stream_;
2974 }
2975 
SetFrameDecryptor(rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor)2976 void WebRtcVideoChannel::WebRtcVideoReceiveStream::SetFrameDecryptor(
2977     rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor) {
2978   config_.frame_decryptor = frame_decryptor;
2979   if (stream_) {
2980     RTC_LOG(LS_INFO)
2981         << "Setting FrameDecryptor (recv) because of SetFrameDecryptor, "
2982            "remote_ssrc="
2983         << config_.rtp.remote_ssrc;
2984     stream_->SetFrameDecryptor(frame_decryptor);
2985   }
2986 }
2987 
SetBaseMinimumPlayoutDelayMs(int delay_ms)2988 bool WebRtcVideoChannel::WebRtcVideoReceiveStream::SetBaseMinimumPlayoutDelayMs(
2989     int delay_ms) {
2990   return stream_ ? stream_->SetBaseMinimumPlayoutDelayMs(delay_ms) : false;
2991 }
2992 
GetBaseMinimumPlayoutDelayMs() const2993 int WebRtcVideoChannel::WebRtcVideoReceiveStream::GetBaseMinimumPlayoutDelayMs()
2994     const {
2995   return stream_ ? stream_->GetBaseMinimumPlayoutDelayMs() : 0;
2996 }
2997 
SetSink(rtc::VideoSinkInterface<webrtc::VideoFrame> * sink)2998 void WebRtcVideoChannel::WebRtcVideoReceiveStream::SetSink(
2999     rtc::VideoSinkInterface<webrtc::VideoFrame>* sink) {
3000   webrtc::MutexLock lock(&sink_lock_);
3001   sink_ = sink;
3002 }
3003 
3004 std::string
GetCodecNameFromPayloadType(int payload_type)3005 WebRtcVideoChannel::WebRtcVideoReceiveStream::GetCodecNameFromPayloadType(
3006     int payload_type) {
3007   for (const webrtc::VideoReceiveStream::Decoder& decoder : config_.decoders) {
3008     if (decoder.payload_type == payload_type) {
3009       return decoder.video_format.name;
3010     }
3011   }
3012   return "";
3013 }
3014 
3015 VideoReceiverInfo
GetVideoReceiverInfo(bool log_stats)3016 WebRtcVideoChannel::WebRtcVideoReceiveStream::GetVideoReceiverInfo(
3017     bool log_stats) {
3018   VideoReceiverInfo info;
3019   info.ssrc_groups = stream_params_.ssrc_groups;
3020   info.add_ssrc(config_.rtp.remote_ssrc);
3021   webrtc::VideoReceiveStream::Stats stats = stream_->GetStats();
3022   info.decoder_implementation_name = stats.decoder_implementation_name;
3023   if (stats.current_payload_type != -1) {
3024     info.codec_payload_type = stats.current_payload_type;
3025   }
3026   info.payload_bytes_rcvd = stats.rtp_stats.packet_counter.payload_bytes;
3027   info.header_and_padding_bytes_rcvd =
3028       stats.rtp_stats.packet_counter.header_bytes +
3029       stats.rtp_stats.packet_counter.padding_bytes;
3030   info.packets_rcvd = stats.rtp_stats.packet_counter.packets;
3031   info.packets_lost = stats.rtp_stats.packets_lost;
3032 
3033   info.framerate_rcvd = stats.network_frame_rate;
3034   info.framerate_decoded = stats.decode_frame_rate;
3035   info.framerate_output = stats.render_frame_rate;
3036   info.frame_width = stats.width;
3037   info.frame_height = stats.height;
3038 
3039   {
3040     webrtc::MutexLock frame_cs(&sink_lock_);
3041     info.capture_start_ntp_time_ms = estimated_remote_start_ntp_time_ms_;
3042   }
3043 
3044   info.decode_ms = stats.decode_ms;
3045   info.max_decode_ms = stats.max_decode_ms;
3046   info.current_delay_ms = stats.current_delay_ms;
3047   info.target_delay_ms = stats.target_delay_ms;
3048   info.jitter_buffer_ms = stats.jitter_buffer_ms;
3049   info.jitter_buffer_delay_seconds = stats.jitter_buffer_delay_seconds;
3050   info.jitter_buffer_emitted_count = stats.jitter_buffer_emitted_count;
3051   info.min_playout_delay_ms = stats.min_playout_delay_ms;
3052   info.render_delay_ms = stats.render_delay_ms;
3053   info.frames_received =
3054       stats.frame_counts.key_frames + stats.frame_counts.delta_frames;
3055   info.frames_dropped = stats.frames_dropped;
3056   info.frames_decoded = stats.frames_decoded;
3057   info.key_frames_decoded = stats.frame_counts.key_frames;
3058   info.frames_rendered = stats.frames_rendered;
3059   info.qp_sum = stats.qp_sum;
3060   info.total_decode_time_ms = stats.total_decode_time_ms;
3061   info.last_packet_received_timestamp_ms =
3062       stats.rtp_stats.last_packet_received_timestamp_ms;
3063   info.estimated_playout_ntp_timestamp_ms =
3064       stats.estimated_playout_ntp_timestamp_ms;
3065   info.first_frame_received_to_decoded_ms =
3066       stats.first_frame_received_to_decoded_ms;
3067   info.total_inter_frame_delay = stats.total_inter_frame_delay;
3068   info.total_squared_inter_frame_delay = stats.total_squared_inter_frame_delay;
3069   info.interframe_delay_max_ms = stats.interframe_delay_max_ms;
3070   info.freeze_count = stats.freeze_count;
3071   info.pause_count = stats.pause_count;
3072   info.total_freezes_duration_ms = stats.total_freezes_duration_ms;
3073   info.total_pauses_duration_ms = stats.total_pauses_duration_ms;
3074   info.total_frames_duration_ms = stats.total_frames_duration_ms;
3075   info.sum_squared_frame_durations = stats.sum_squared_frame_durations;
3076 
3077   info.content_type = stats.content_type;
3078 
3079   info.codec_name = GetCodecNameFromPayloadType(stats.current_payload_type);
3080 
3081   info.firs_sent = stats.rtcp_packet_type_counts.fir_packets;
3082   info.plis_sent = stats.rtcp_packet_type_counts.pli_packets;
3083   info.nacks_sent = stats.rtcp_packet_type_counts.nack_packets;
3084   // TODO(bugs.webrtc.org/10662): Add stats for LNTF.
3085 
3086   info.timing_frame_info = stats.timing_frame_info;
3087 
3088   if (log_stats)
3089     RTC_LOG(LS_INFO) << stats.ToString(rtc::TimeMillis());
3090 
3091   return info;
3092 }
3093 
3094 void WebRtcVideoChannel::WebRtcVideoReceiveStream::
SetRecordableEncodedFrameCallback(std::function<void (const webrtc::RecordableEncodedFrame &)> callback)3095     SetRecordableEncodedFrameCallback(
3096         std::function<void(const webrtc::RecordableEncodedFrame&)> callback) {
3097   if (stream_) {
3098     stream_->SetAndGetRecordingState(
3099         webrtc::VideoReceiveStream::RecordingState(std::move(callback)),
3100         /*generate_key_frame=*/true);
3101   } else {
3102     RTC_LOG(LS_ERROR) << "Absent receive stream; ignoring setting encoded "
3103                          "frame sink";
3104   }
3105 }
3106 
3107 void WebRtcVideoChannel::WebRtcVideoReceiveStream::
ClearRecordableEncodedFrameCallback()3108     ClearRecordableEncodedFrameCallback() {
3109   if (stream_) {
3110     stream_->SetAndGetRecordingState(
3111         webrtc::VideoReceiveStream::RecordingState(),
3112         /*generate_key_frame=*/false);
3113   } else {
3114     RTC_LOG(LS_ERROR) << "Absent receive stream; ignoring clearing encoded "
3115                          "frame sink";
3116   }
3117 }
3118 
GenerateKeyFrame()3119 void WebRtcVideoChannel::WebRtcVideoReceiveStream::GenerateKeyFrame() {
3120   if (stream_) {
3121     stream_->GenerateKeyFrame();
3122   } else {
3123     RTC_LOG(LS_ERROR)
3124         << "Absent receive stream; ignoring key frame generation request.";
3125   }
3126 }
3127 
3128 void WebRtcVideoChannel::WebRtcVideoReceiveStream::
SetDepacketizerToDecoderFrameTransformer(rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)3129     SetDepacketizerToDecoderFrameTransformer(
3130         rtc::scoped_refptr<webrtc::FrameTransformerInterface>
3131             frame_transformer) {
3132   config_.frame_transformer = frame_transformer;
3133   if (stream_)
3134     stream_->SetDepacketizerToDecoderFrameTransformer(frame_transformer);
3135 }
3136 
VideoCodecSettings()3137 WebRtcVideoChannel::VideoCodecSettings::VideoCodecSettings()
3138     : flexfec_payload_type(-1), rtx_payload_type(-1) {}
3139 
operator ==(const WebRtcVideoChannel::VideoCodecSettings & other) const3140 bool WebRtcVideoChannel::VideoCodecSettings::operator==(
3141     const WebRtcVideoChannel::VideoCodecSettings& other) const {
3142   return codec == other.codec && ulpfec == other.ulpfec &&
3143          flexfec_payload_type == other.flexfec_payload_type &&
3144          rtx_payload_type == other.rtx_payload_type;
3145 }
3146 
EqualsDisregardingFlexfec(const WebRtcVideoChannel::VideoCodecSettings & a,const WebRtcVideoChannel::VideoCodecSettings & b)3147 bool WebRtcVideoChannel::VideoCodecSettings::EqualsDisregardingFlexfec(
3148     const WebRtcVideoChannel::VideoCodecSettings& a,
3149     const WebRtcVideoChannel::VideoCodecSettings& b) {
3150   return a.codec == b.codec && a.ulpfec == b.ulpfec &&
3151          a.rtx_payload_type == b.rtx_payload_type;
3152 }
3153 
operator !=(const WebRtcVideoChannel::VideoCodecSettings & other) const3154 bool WebRtcVideoChannel::VideoCodecSettings::operator!=(
3155     const WebRtcVideoChannel::VideoCodecSettings& other) const {
3156   return !(*this == other);
3157 }
3158 
3159 std::vector<WebRtcVideoChannel::VideoCodecSettings>
MapCodecs(const std::vector<VideoCodec> & codecs)3160 WebRtcVideoChannel::MapCodecs(const std::vector<VideoCodec>& codecs) {
3161   if (codecs.empty()) {
3162     return {};
3163   }
3164 
3165   std::vector<VideoCodecSettings> video_codecs;
3166   std::map<int, VideoCodec::CodecType> payload_codec_type;
3167   // |rtx_mapping| maps video payload type to rtx payload type.
3168   std::map<int, int> rtx_mapping;
3169 
3170   webrtc::UlpfecConfig ulpfec_config;
3171   absl::optional<int> flexfec_payload_type;
3172 
3173   for (const VideoCodec& in_codec : codecs) {
3174     const int payload_type = in_codec.id;
3175 
3176     if (payload_codec_type.find(payload_type) != payload_codec_type.end()) {
3177       RTC_LOG(LS_ERROR) << "Payload type already registered: "
3178                         << in_codec.ToString();
3179       return {};
3180     }
3181     payload_codec_type[payload_type] = in_codec.GetCodecType();
3182 
3183     switch (in_codec.GetCodecType()) {
3184       case VideoCodec::CODEC_RED: {
3185         if (ulpfec_config.red_payload_type != -1) {
3186           RTC_LOG(LS_ERROR)
3187               << "Duplicate RED codec: ignoring PT=" << payload_type
3188               << " in favor of PT=" << ulpfec_config.red_payload_type
3189               << " which was specified first.";
3190           break;
3191         }
3192         ulpfec_config.red_payload_type = payload_type;
3193         break;
3194       }
3195 
3196       case VideoCodec::CODEC_ULPFEC: {
3197         if (ulpfec_config.ulpfec_payload_type != -1) {
3198           RTC_LOG(LS_ERROR)
3199               << "Duplicate ULPFEC codec: ignoring PT=" << payload_type
3200               << " in favor of PT=" << ulpfec_config.ulpfec_payload_type
3201               << " which was specified first.";
3202           break;
3203         }
3204         ulpfec_config.ulpfec_payload_type = payload_type;
3205         break;
3206       }
3207 
3208       case VideoCodec::CODEC_FLEXFEC: {
3209         if (flexfec_payload_type) {
3210           RTC_LOG(LS_ERROR)
3211               << "Duplicate FLEXFEC codec: ignoring PT=" << payload_type
3212               << " in favor of PT=" << *flexfec_payload_type
3213               << " which was specified first.";
3214           break;
3215         }
3216         flexfec_payload_type = payload_type;
3217         break;
3218       }
3219 
3220       case VideoCodec::CODEC_RTX: {
3221         int associated_payload_type;
3222         if (!in_codec.GetParam(kCodecParamAssociatedPayloadType,
3223                                &associated_payload_type) ||
3224             !IsValidRtpPayloadType(associated_payload_type)) {
3225           RTC_LOG(LS_ERROR)
3226               << "RTX codec with invalid or no associated payload type: "
3227               << in_codec.ToString();
3228           return {};
3229         }
3230         rtx_mapping[associated_payload_type] = payload_type;
3231         break;
3232       }
3233 
3234       case VideoCodec::CODEC_VIDEO: {
3235         video_codecs.emplace_back();
3236         video_codecs.back().codec = in_codec;
3237         break;
3238       }
3239     }
3240   }
3241 
3242   // One of these codecs should have been a video codec. Only having FEC
3243   // parameters into this code is a logic error.
3244   RTC_DCHECK(!video_codecs.empty());
3245 
3246   for (const auto& entry : rtx_mapping) {
3247     const int associated_payload_type = entry.first;
3248     const int rtx_payload_type = entry.second;
3249     auto it = payload_codec_type.find(associated_payload_type);
3250     if (it == payload_codec_type.end()) {
3251       RTC_LOG(LS_ERROR) << "RTX codec (PT=" << rtx_payload_type
3252                         << ") mapped to PT=" << associated_payload_type
3253                         << " which is not in the codec list.";
3254       return {};
3255     }
3256     const VideoCodec::CodecType associated_codec_type = it->second;
3257     if (associated_codec_type != VideoCodec::CODEC_VIDEO &&
3258         associated_codec_type != VideoCodec::CODEC_RED) {
3259       RTC_LOG(LS_ERROR)
3260           << "RTX PT=" << rtx_payload_type
3261           << " not mapped to regular video codec or RED codec (PT="
3262           << associated_payload_type << ").";
3263       return {};
3264     }
3265 
3266     if (associated_payload_type == ulpfec_config.red_payload_type) {
3267       ulpfec_config.red_rtx_payload_type = rtx_payload_type;
3268     }
3269   }
3270 
3271   for (VideoCodecSettings& codec_settings : video_codecs) {
3272     const int payload_type = codec_settings.codec.id;
3273     codec_settings.ulpfec = ulpfec_config;
3274     codec_settings.flexfec_payload_type = flexfec_payload_type.value_or(-1);
3275     auto it = rtx_mapping.find(payload_type);
3276     if (it != rtx_mapping.end()) {
3277       const int rtx_payload_type = it->second;
3278       codec_settings.rtx_payload_type = rtx_payload_type;
3279     }
3280   }
3281 
3282   return video_codecs;
3283 }
3284 
3285 WebRtcVideoChannel::WebRtcVideoReceiveStream*
FindReceiveStream(uint32_t ssrc)3286 WebRtcVideoChannel::FindReceiveStream(uint32_t ssrc) {
3287   if (ssrc == 0) {
3288     absl::optional<uint32_t> default_ssrc = GetDefaultReceiveStreamSsrc();
3289     if (!default_ssrc) {
3290       return nullptr;
3291     }
3292     ssrc = *default_ssrc;
3293   }
3294   auto it = receive_streams_.find(ssrc);
3295   if (it != receive_streams_.end()) {
3296     return it->second;
3297   }
3298   return nullptr;
3299 }
3300 
SetRecordableEncodedFrameCallback(uint32_t ssrc,std::function<void (const webrtc::RecordableEncodedFrame &)> callback)3301 void WebRtcVideoChannel::SetRecordableEncodedFrameCallback(
3302     uint32_t ssrc,
3303     std::function<void(const webrtc::RecordableEncodedFrame&)> callback) {
3304   RTC_DCHECK_RUN_ON(&thread_checker_);
3305   WebRtcVideoReceiveStream* stream = FindReceiveStream(ssrc);
3306   if (stream) {
3307     stream->SetRecordableEncodedFrameCallback(std::move(callback));
3308   } else {
3309     RTC_LOG(LS_ERROR) << "Absent receive stream; ignoring setting encoded "
3310                          "frame sink for ssrc "
3311                       << ssrc;
3312   }
3313 }
3314 
ClearRecordableEncodedFrameCallback(uint32_t ssrc)3315 void WebRtcVideoChannel::ClearRecordableEncodedFrameCallback(uint32_t ssrc) {
3316   RTC_DCHECK_RUN_ON(&thread_checker_);
3317   WebRtcVideoReceiveStream* stream = FindReceiveStream(ssrc);
3318   if (stream) {
3319     stream->ClearRecordableEncodedFrameCallback();
3320   } else {
3321     RTC_LOG(LS_ERROR) << "Absent receive stream; ignoring clearing encoded "
3322                          "frame sink for ssrc "
3323                       << ssrc;
3324   }
3325 }
3326 
GenerateKeyFrame(uint32_t ssrc)3327 void WebRtcVideoChannel::GenerateKeyFrame(uint32_t ssrc) {
3328   RTC_DCHECK_RUN_ON(&thread_checker_);
3329   WebRtcVideoReceiveStream* stream = FindReceiveStream(ssrc);
3330   if (stream) {
3331     stream->GenerateKeyFrame();
3332   } else {
3333     RTC_LOG(LS_ERROR)
3334         << "Absent receive stream; ignoring key frame generation for ssrc "
3335         << ssrc;
3336   }
3337 }
3338 
SetEncoderToPacketizerFrameTransformer(uint32_t ssrc,rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)3339 void WebRtcVideoChannel::SetEncoderToPacketizerFrameTransformer(
3340     uint32_t ssrc,
3341     rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
3342   RTC_DCHECK_RUN_ON(&thread_checker_);
3343   auto matching_stream = send_streams_.find(ssrc);
3344   if (matching_stream != send_streams_.end()) {
3345     matching_stream->second->SetEncoderToPacketizerFrameTransformer(
3346         std::move(frame_transformer));
3347   }
3348 }
3349 
SetDepacketizerToDecoderFrameTransformer(uint32_t ssrc,rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)3350 void WebRtcVideoChannel::SetDepacketizerToDecoderFrameTransformer(
3351     uint32_t ssrc,
3352     rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
3353   RTC_DCHECK(frame_transformer);
3354   RTC_DCHECK_RUN_ON(&thread_checker_);
3355   if (ssrc == 0) {
3356     // If the receiver is unsignaled, save the frame transformer and set it when
3357     // the stream is associated with an ssrc.
3358     unsignaled_frame_transformer_ = std::move(frame_transformer);
3359     return;
3360   }
3361 
3362   auto matching_stream = receive_streams_.find(ssrc);
3363   if (matching_stream != receive_streams_.end()) {
3364     matching_stream->second->SetDepacketizerToDecoderFrameTransformer(
3365         std::move(frame_transformer));
3366   }
3367 }
3368 
3369 // TODO(bugs.webrtc.org/8785): Consider removing max_qp as member of
3370 // EncoderStreamFactory and instead set this value individually for each stream
3371 // in the VideoEncoderConfig.simulcast_layers.
EncoderStreamFactory(std::string codec_name,int max_qp,bool is_screenshare,bool conference_mode)3372 EncoderStreamFactory::EncoderStreamFactory(std::string codec_name,
3373                                            int max_qp,
3374                                            bool is_screenshare,
3375                                            bool conference_mode)
3376 
3377     : codec_name_(codec_name),
3378       max_qp_(max_qp),
3379       is_screenshare_(is_screenshare),
3380       conference_mode_(conference_mode) {}
3381 
CreateEncoderStreams(int width,int height,const webrtc::VideoEncoderConfig & encoder_config)3382 std::vector<webrtc::VideoStream> EncoderStreamFactory::CreateEncoderStreams(
3383     int width,
3384     int height,
3385     const webrtc::VideoEncoderConfig& encoder_config) {
3386   RTC_DCHECK_GT(encoder_config.number_of_streams, 0);
3387   RTC_DCHECK_GE(encoder_config.simulcast_layers.size(),
3388                 encoder_config.number_of_streams);
3389 
3390   const absl::optional<webrtc::DataRate> experimental_min_bitrate =
3391       GetExperimentalMinVideoBitrate(encoder_config.codec_type);
3392 
3393   if (encoder_config.number_of_streams > 1 ||
3394       ((absl::EqualsIgnoreCase(codec_name_, kVp8CodecName) ||
3395         absl::EqualsIgnoreCase(codec_name_, kH264CodecName)) &&
3396        is_screenshare_ && conference_mode_)) {
3397     return CreateSimulcastOrConfereceModeScreenshareStreams(
3398         width, height, encoder_config, experimental_min_bitrate);
3399   }
3400 
3401   return CreateDefaultVideoStreams(width, height, encoder_config,
3402                                    experimental_min_bitrate);
3403 }
3404 
3405 std::vector<webrtc::VideoStream>
CreateDefaultVideoStreams(int width,int height,const webrtc::VideoEncoderConfig & encoder_config,const absl::optional<webrtc::DataRate> & experimental_min_bitrate) const3406 EncoderStreamFactory::CreateDefaultVideoStreams(
3407     int width,
3408     int height,
3409     const webrtc::VideoEncoderConfig& encoder_config,
3410     const absl::optional<webrtc::DataRate>& experimental_min_bitrate) const {
3411   std::vector<webrtc::VideoStream> layers;
3412 
3413   // For unset max bitrates set default bitrate for non-simulcast.
3414   int max_bitrate_bps =
3415       (encoder_config.max_bitrate_bps > 0)
3416           ? encoder_config.max_bitrate_bps
3417           : GetMaxDefaultVideoBitrateKbps(width, height, is_screenshare_) *
3418                 1000;
3419 
3420   int min_bitrate_bps =
3421       experimental_min_bitrate
3422           ? rtc::saturated_cast<int>(experimental_min_bitrate->bps())
3423           : webrtc::kDefaultMinVideoBitrateBps;
3424   if (encoder_config.simulcast_layers[0].min_bitrate_bps > 0) {
3425     // Use set min bitrate.
3426     min_bitrate_bps = encoder_config.simulcast_layers[0].min_bitrate_bps;
3427     // If only min bitrate is configured, make sure max is above min.
3428     if (encoder_config.max_bitrate_bps <= 0)
3429       max_bitrate_bps = std::max(min_bitrate_bps, max_bitrate_bps);
3430   }
3431   int max_framerate = (encoder_config.simulcast_layers[0].max_framerate > 0)
3432                           ? encoder_config.simulcast_layers[0].max_framerate
3433                           : kDefaultVideoMaxFramerate;
3434 
3435   webrtc::VideoStream layer;
3436   layer.width = width;
3437   layer.height = height;
3438   layer.max_framerate = max_framerate;
3439 
3440   if (encoder_config.simulcast_layers[0].scale_resolution_down_by > 1.) {
3441     layer.width = std::max<size_t>(
3442         layer.width /
3443             encoder_config.simulcast_layers[0].scale_resolution_down_by,
3444         kMinLayerSize);
3445     layer.height = std::max<size_t>(
3446         layer.height /
3447             encoder_config.simulcast_layers[0].scale_resolution_down_by,
3448         kMinLayerSize);
3449   }
3450 
3451   // In the case that the application sets a max bitrate that's lower than the
3452   // min bitrate, we adjust it down (see bugs.webrtc.org/9141).
3453   layer.min_bitrate_bps = std::min(min_bitrate_bps, max_bitrate_bps);
3454   if (encoder_config.simulcast_layers[0].target_bitrate_bps <= 0) {
3455     layer.target_bitrate_bps = max_bitrate_bps;
3456   } else {
3457     layer.target_bitrate_bps =
3458         encoder_config.simulcast_layers[0].target_bitrate_bps;
3459   }
3460   layer.max_bitrate_bps = max_bitrate_bps;
3461   layer.max_qp = max_qp_;
3462   layer.bitrate_priority = encoder_config.bitrate_priority;
3463 
3464   if (absl::EqualsIgnoreCase(codec_name_, kVp9CodecName)) {
3465     RTC_DCHECK(encoder_config.encoder_specific_settings);
3466     // Use VP9 SVC layering from codec settings which might be initialized
3467     // though field trial in ConfigureVideoEncoderSettings.
3468     webrtc::VideoCodecVP9 vp9_settings;
3469     encoder_config.encoder_specific_settings->FillVideoCodecVp9(&vp9_settings);
3470     layer.num_temporal_layers = vp9_settings.numberOfTemporalLayers;
3471   }
3472 
3473   if (IsTemporalLayersSupported(codec_name_)) {
3474     // Use configured number of temporal layers if set.
3475     if (encoder_config.simulcast_layers[0].num_temporal_layers) {
3476       layer.num_temporal_layers =
3477           *encoder_config.simulcast_layers[0].num_temporal_layers;
3478     }
3479   }
3480 
3481   layers.push_back(layer);
3482   return layers;
3483 }
3484 
3485 std::vector<webrtc::VideoStream>
CreateSimulcastOrConfereceModeScreenshareStreams(int width,int height,const webrtc::VideoEncoderConfig & encoder_config,const absl::optional<webrtc::DataRate> & experimental_min_bitrate) const3486 EncoderStreamFactory::CreateSimulcastOrConfereceModeScreenshareStreams(
3487     int width,
3488     int height,
3489     const webrtc::VideoEncoderConfig& encoder_config,
3490     const absl::optional<webrtc::DataRate>& experimental_min_bitrate) const {
3491   std::vector<webrtc::VideoStream> layers;
3492 
3493   const bool temporal_layers_supported =
3494       absl::EqualsIgnoreCase(codec_name_, kVp8CodecName) ||
3495       absl::EqualsIgnoreCase(codec_name_, kH264CodecName);
3496   // Use legacy simulcast screenshare if conference mode is explicitly enabled
3497   // or use the regular simulcast configuration path which is generic.
3498   layers = GetSimulcastConfig(FindRequiredActiveLayers(encoder_config),
3499                               encoder_config.number_of_streams, width, height,
3500                               encoder_config.bitrate_priority, max_qp_,
3501                               is_screenshare_ && conference_mode_,
3502                               temporal_layers_supported);
3503   // Allow an experiment to override the minimum bitrate for the lowest
3504   // spatial layer. The experiment's configuration has the lowest priority.
3505   if (experimental_min_bitrate) {
3506     layers[0].min_bitrate_bps =
3507         rtc::saturated_cast<int>(experimental_min_bitrate->bps());
3508   }
3509   // Update the active simulcast layers and configured bitrates.
3510   bool is_highest_layer_max_bitrate_configured = false;
3511   const bool has_scale_resolution_down_by = absl::c_any_of(
3512       encoder_config.simulcast_layers, [](const webrtc::VideoStream& layer) {
3513         return layer.scale_resolution_down_by != -1.;
3514       });
3515   const int normalized_width =
3516       NormalizeSimulcastSize(width, encoder_config.number_of_streams);
3517   const int normalized_height =
3518       NormalizeSimulcastSize(height, encoder_config.number_of_streams);
3519   for (size_t i = 0; i < layers.size(); ++i) {
3520     layers[i].active = encoder_config.simulcast_layers[i].active;
3521     // Update with configured num temporal layers if supported by codec.
3522     if (encoder_config.simulcast_layers[i].num_temporal_layers &&
3523         IsTemporalLayersSupported(codec_name_)) {
3524       layers[i].num_temporal_layers =
3525           *encoder_config.simulcast_layers[i].num_temporal_layers;
3526     }
3527     if (encoder_config.simulcast_layers[i].max_framerate > 0) {
3528       layers[i].max_framerate =
3529           encoder_config.simulcast_layers[i].max_framerate;
3530     }
3531     if (has_scale_resolution_down_by) {
3532       const double scale_resolution_down_by = std::max(
3533           encoder_config.simulcast_layers[i].scale_resolution_down_by, 1.0);
3534       layers[i].width = std::max(
3535           static_cast<int>(normalized_width / scale_resolution_down_by),
3536           kMinLayerSize);
3537       layers[i].height = std::max(
3538           static_cast<int>(normalized_height / scale_resolution_down_by),
3539           kMinLayerSize);
3540     }
3541     // Update simulcast bitrates with configured min and max bitrate.
3542     if (encoder_config.simulcast_layers[i].min_bitrate_bps > 0) {
3543       layers[i].min_bitrate_bps =
3544           encoder_config.simulcast_layers[i].min_bitrate_bps;
3545     }
3546     if (encoder_config.simulcast_layers[i].max_bitrate_bps > 0) {
3547       layers[i].max_bitrate_bps =
3548           encoder_config.simulcast_layers[i].max_bitrate_bps;
3549     }
3550     if (encoder_config.simulcast_layers[i].target_bitrate_bps > 0) {
3551       layers[i].target_bitrate_bps =
3552           encoder_config.simulcast_layers[i].target_bitrate_bps;
3553     }
3554     if (encoder_config.simulcast_layers[i].min_bitrate_bps > 0 &&
3555         encoder_config.simulcast_layers[i].max_bitrate_bps > 0) {
3556       // Min and max bitrate are configured.
3557       // Set target to 3/4 of the max bitrate (or to max if below min).
3558       if (encoder_config.simulcast_layers[i].target_bitrate_bps <= 0)
3559         layers[i].target_bitrate_bps = layers[i].max_bitrate_bps * 3 / 4;
3560       if (layers[i].target_bitrate_bps < layers[i].min_bitrate_bps)
3561         layers[i].target_bitrate_bps = layers[i].max_bitrate_bps;
3562     } else if (encoder_config.simulcast_layers[i].min_bitrate_bps > 0) {
3563       // Only min bitrate is configured, make sure target/max are above min.
3564       layers[i].target_bitrate_bps =
3565           std::max(layers[i].target_bitrate_bps, layers[i].min_bitrate_bps);
3566       layers[i].max_bitrate_bps =
3567           std::max(layers[i].max_bitrate_bps, layers[i].min_bitrate_bps);
3568     } else if (encoder_config.simulcast_layers[i].max_bitrate_bps > 0) {
3569       // Only max bitrate is configured, make sure min/target are below max.
3570       layers[i].min_bitrate_bps =
3571           std::min(layers[i].min_bitrate_bps, layers[i].max_bitrate_bps);
3572       layers[i].target_bitrate_bps =
3573           std::min(layers[i].target_bitrate_bps, layers[i].max_bitrate_bps);
3574     }
3575     if (i == layers.size() - 1) {
3576       is_highest_layer_max_bitrate_configured =
3577           encoder_config.simulcast_layers[i].max_bitrate_bps > 0;
3578     }
3579   }
3580   if (!is_screenshare_ && !is_highest_layer_max_bitrate_configured &&
3581       encoder_config.max_bitrate_bps > 0) {
3582     // No application-configured maximum for the largest layer.
3583     // If there is bitrate leftover, give it to the largest layer.
3584     BoostMaxSimulcastLayer(
3585         webrtc::DataRate::BitsPerSec(encoder_config.max_bitrate_bps), &layers);
3586   }
3587   return layers;
3588 }
3589 
3590 }  // namespace cricket
3591