Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(209)

Side by Side Diff: webrtc/video/video_send_stream.cc

Issue 2060403002: Add task queue to Call. (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@move_getpadding
Patch Set: Fix audio thread check when adding audio to bitrateallocator. Created 4 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. 2 * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
3 * 3 *
4 * Use of this source code is governed by a BSD-style license 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 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 6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may 7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree. 8 * be found in the AUTHORS file in the root of the source tree.
9 */ 9 */
10
11 #include "webrtc/video/video_send_stream.h" 10 #include "webrtc/video/video_send_stream.h"
12 11
13 #include <algorithm> 12 #include <algorithm>
14 #include <sstream> 13 #include <sstream>
15 #include <string> 14 #include <string>
16 #include <utility> 15 #include <utility>
17 #include <vector> 16 #include <vector>
18 17
19 #include "webrtc/base/checks.h" 18 #include "webrtc/base/checks.h"
20 #include "webrtc/base/logging.h" 19 #include "webrtc/base/logging.h"
21 #include "webrtc/base/trace_event.h" 20 #include "webrtc/base/trace_event.h"
22 #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
23 #include "webrtc/modules/bitrate_controller/include/bitrate_controller.h" 21 #include "webrtc/modules/bitrate_controller/include/bitrate_controller.h"
24 #include "webrtc/modules/congestion_controller/include/congestion_controller.h" 22 #include "webrtc/modules/congestion_controller/include/congestion_controller.h"
25 #include "webrtc/modules/pacing/packet_router.h" 23 #include "webrtc/modules/pacing/packet_router.h"
26 #include "webrtc/modules/rtp_rtcp/include/rtp_rtcp.h" 24 #include "webrtc/modules/rtp_rtcp/include/rtp_rtcp.h"
27 #include "webrtc/modules/utility/include/process_thread.h" 25 #include "webrtc/modules/utility/include/process_thread.h"
28 #include "webrtc/modules/video_coding/utility/ivf_file_writer.h" 26 #include "webrtc/modules/video_coding/utility/ivf_file_writer.h"
29 #include "webrtc/video/call_stats.h" 27 #include "webrtc/video/call_stats.h"
30 #include "webrtc/video/video_capture_input.h"
31 #include "webrtc/video/vie_remb.h" 28 #include "webrtc/video/vie_remb.h"
32 #include "webrtc/video_send_stream.h" 29 #include "webrtc/video_send_stream.h"
33 30
34 namespace webrtc { 31 namespace webrtc {
35 32
36 class RtcpIntraFrameObserver;
37 class TransportFeedbackObserver;
38
39 static const int kMinSendSidePacketHistorySize = 600; 33 static const int kMinSendSidePacketHistorySize = 600;
40 static const int kEncoderTimeOutMs = 2000;
41
42 namespace { 34 namespace {
43 35
44 std::vector<RtpRtcp*> CreateRtpRtcpModules( 36 std::vector<RtpRtcp*> CreateRtpRtcpModules(
45 Transport* outgoing_transport, 37 Transport* outgoing_transport,
46 RtcpIntraFrameObserver* intra_frame_callback, 38 RtcpIntraFrameObserver* intra_frame_callback,
47 RtcpBandwidthObserver* bandwidth_callback, 39 RtcpBandwidthObserver* bandwidth_callback,
48 TransportFeedbackObserver* transport_feedback_callback, 40 TransportFeedbackObserver* transport_feedback_callback,
49 RtcpRttStats* rtt_stats, 41 RtcpRttStats* rtt_stats,
50 RtpPacketSender* paced_sender, 42 RtpPacketSender* paced_sender,
51 TransportSequenceNumberAllocator* transport_sequence_number_allocator, 43 TransportSequenceNumberAllocator* transport_sequence_number_allocator,
(...skipping 93 matching lines...) Expand 10 before | Expand all | Expand 10 after
145 } 137 }
146 138
147 std::string VideoSendStream::Config::ToString() const { 139 std::string VideoSendStream::Config::ToString() const {
148 std::stringstream ss; 140 std::stringstream ss;
149 ss << "{encoder_settings: " << encoder_settings.ToString(); 141 ss << "{encoder_settings: " << encoder_settings.ToString();
150 ss << ", rtp: " << rtp.ToString(); 142 ss << ", rtp: " << rtp.ToString();
151 ss << ", pre_encode_callback: " 143 ss << ", pre_encode_callback: "
152 << (pre_encode_callback ? "(I420FrameCallback)" : "nullptr"); 144 << (pre_encode_callback ? "(I420FrameCallback)" : "nullptr");
153 ss << ", post_encode_callback: " 145 ss << ", post_encode_callback: "
154 << (post_encode_callback ? "(EncodedFrameObserver)" : "nullptr"); 146 << (post_encode_callback ? "(EncodedFrameObserver)" : "nullptr");
155 ss << ", local_renderer: "
156 << (local_renderer ? "(VideoRenderer)" : "nullptr");
157 ss << ", render_delay_ms: " << render_delay_ms; 147 ss << ", render_delay_ms: " << render_delay_ms;
158 ss << ", target_delay_ms: " << target_delay_ms; 148 ss << ", target_delay_ms: " << target_delay_ms;
159 ss << ", suspend_below_min_bitrate: " << (suspend_below_min_bitrate ? "on" 149 ss << ", suspend_below_min_bitrate: " << (suspend_below_min_bitrate ? "on"
160 : "off"); 150 : "off");
161 ss << '}'; 151 ss << '}';
162 return ss.str(); 152 return ss.str();
163 } 153 }
164 154
165 std::string VideoSendStream::Stats::ToString(int64_t time_ms) const { 155 std::string VideoSendStream::Stats::ToString(int64_t time_ms) const {
166 std::stringstream ss; 156 std::stringstream ss;
(...skipping 30 matching lines...) Expand all
197 ss << "cum_loss: " << rtcp_stats.cumulative_lost << ", "; 187 ss << "cum_loss: " << rtcp_stats.cumulative_lost << ", ";
198 ss << "max_ext_seq: " << rtcp_stats.extended_max_sequence_number << ", "; 188 ss << "max_ext_seq: " << rtcp_stats.extended_max_sequence_number << ", ";
199 ss << "nack: " << rtcp_packet_type_counts.nack_packets << ", "; 189 ss << "nack: " << rtcp_packet_type_counts.nack_packets << ", ";
200 ss << "fir: " << rtcp_packet_type_counts.fir_packets << ", "; 190 ss << "fir: " << rtcp_packet_type_counts.fir_packets << ", ";
201 ss << "pli: " << rtcp_packet_type_counts.pli_packets; 191 ss << "pli: " << rtcp_packet_type_counts.pli_packets;
202 return ss.str(); 192 return ss.str();
203 } 193 }
204 194
205 namespace { 195 namespace {
206 196
207 VideoCodecType PayloadNameToCodecType(const std::string& payload_name) {
208 if (payload_name == "VP8")
209 return kVideoCodecVP8;
210 if (payload_name == "VP9")
211 return kVideoCodecVP9;
212 if (payload_name == "H264")
213 return kVideoCodecH264;
214 return kVideoCodecGeneric;
215 }
216
217 bool PayloadTypeSupportsSkippingFecPackets(const std::string& payload_name) { 197 bool PayloadTypeSupportsSkippingFecPackets(const std::string& payload_name) {
218 switch (PayloadNameToCodecType(payload_name)) { 198 if (payload_name == "VP8" || payload_name == "VP9")
219 case kVideoCodecVP8: 199 return true;
220 case kVideoCodecVP9: 200 RTC_DCHECK(payload_name == "H264" || payload_name == "FAKE")
221 return true; 201 << "unknown payload_name " << payload_name;
222 case kVideoCodecH264:
223 case kVideoCodecGeneric:
224 return false;
225 case kVideoCodecI420:
226 case kVideoCodecRED:
227 case kVideoCodecULPFEC:
228 case kVideoCodecUnknown:
229 RTC_NOTREACHED();
230 return false;
231 }
232 RTC_NOTREACHED();
233 return false; 202 return false;
234 } 203 }
235 204
236 // TODO(pbos): Lower these thresholds (to closer to 100%) when we handle 205 int CalculateMaxPadBitrateBps(const VideoEncoderConfig& config,
237 // pipelining encoders better (multiple input frames before something comes
238 // out). This should effectively turn off CPU adaptations for systems that
239 // remotely cope with the load right now.
240 CpuOveruseOptions GetCpuOveruseOptions(bool full_overuse_time) {
241 CpuOveruseOptions options;
242 if (full_overuse_time) {
243 options.low_encode_usage_threshold_percent = 150;
244 options.high_encode_usage_threshold_percent = 200;
245 }
246 return options;
247 }
248
249 VideoCodec VideoEncoderConfigToVideoCodec(const VideoEncoderConfig& config,
250 const std::string& payload_name,
251 int payload_type) {
252 const std::vector<VideoStream>& streams = config.streams;
253 static const int kEncoderMinBitrateKbps = 30;
254 RTC_DCHECK(!streams.empty());
255 RTC_DCHECK_GE(config.min_transmit_bitrate_bps, 0);
256
257 VideoCodec video_codec;
258 memset(&video_codec, 0, sizeof(video_codec));
259 video_codec.codecType = PayloadNameToCodecType(payload_name);
260
261 switch (config.content_type) {
262 case VideoEncoderConfig::ContentType::kRealtimeVideo:
263 video_codec.mode = kRealtimeVideo;
264 break;
265 case VideoEncoderConfig::ContentType::kScreen:
266 video_codec.mode = kScreensharing;
267 if (config.streams.size() == 1 &&
268 config.streams[0].temporal_layer_thresholds_bps.size() == 1) {
269 video_codec.targetBitrate =
270 config.streams[0].temporal_layer_thresholds_bps[0] / 1000;
271 }
272 break;
273 }
274
275 switch (video_codec.codecType) {
276 case kVideoCodecVP8: {
277 if (config.encoder_specific_settings) {
278 video_codec.codecSpecific.VP8 = *reinterpret_cast<const VideoCodecVP8*>(
279 config.encoder_specific_settings);
280 } else {
281 video_codec.codecSpecific.VP8 = VideoEncoder::GetDefaultVp8Settings();
282 }
283 video_codec.codecSpecific.VP8.numberOfTemporalLayers =
284 static_cast<unsigned char>(
285 streams.back().temporal_layer_thresholds_bps.size() + 1);
286 break;
287 }
288 case kVideoCodecVP9: {
289 if (config.encoder_specific_settings) {
290 video_codec.codecSpecific.VP9 = *reinterpret_cast<const VideoCodecVP9*>(
291 config.encoder_specific_settings);
292 if (video_codec.mode == kScreensharing) {
293 video_codec.codecSpecific.VP9.flexibleMode = true;
294 // For now VP9 screensharing use 1 temporal and 2 spatial layers.
295 RTC_DCHECK_EQ(video_codec.codecSpecific.VP9.numberOfTemporalLayers,
296 1);
297 RTC_DCHECK_EQ(video_codec.codecSpecific.VP9.numberOfSpatialLayers, 2);
298 }
299 } else {
300 video_codec.codecSpecific.VP9 = VideoEncoder::GetDefaultVp9Settings();
301 }
302 video_codec.codecSpecific.VP9.numberOfTemporalLayers =
303 static_cast<unsigned char>(
304 streams.back().temporal_layer_thresholds_bps.size() + 1);
305 break;
306 }
307 case kVideoCodecH264: {
308 if (config.encoder_specific_settings) {
309 video_codec.codecSpecific.H264 =
310 *reinterpret_cast<const VideoCodecH264*>(
311 config.encoder_specific_settings);
312 } else {
313 video_codec.codecSpecific.H264 = VideoEncoder::GetDefaultH264Settings();
314 }
315 break;
316 }
317 default:
318 // TODO(pbos): Support encoder_settings codec-agnostically.
319 RTC_DCHECK(!config.encoder_specific_settings)
320 << "Encoder-specific settings for codec type not wired up.";
321 break;
322 }
323
324 strncpy(video_codec.plName, payload_name.c_str(), kPayloadNameSize - 1);
325 video_codec.plName[kPayloadNameSize - 1] = '\0';
326 video_codec.plType = payload_type;
327 video_codec.numberOfSimulcastStreams =
328 static_cast<unsigned char>(streams.size());
329 video_codec.minBitrate = streams[0].min_bitrate_bps / 1000;
330 if (video_codec.minBitrate < kEncoderMinBitrateKbps)
331 video_codec.minBitrate = kEncoderMinBitrateKbps;
332 RTC_DCHECK_LE(streams.size(), static_cast<size_t>(kMaxSimulcastStreams));
333 if (video_codec.codecType == kVideoCodecVP9) {
334 // If the vector is empty, bitrates will be configured automatically.
335 RTC_DCHECK(config.spatial_layers.empty() ||
336 config.spatial_layers.size() ==
337 video_codec.codecSpecific.VP9.numberOfSpatialLayers);
338 RTC_DCHECK_LE(video_codec.codecSpecific.VP9.numberOfSpatialLayers,
339 kMaxSimulcastStreams);
340 for (size_t i = 0; i < config.spatial_layers.size(); ++i)
341 video_codec.spatialLayers[i] = config.spatial_layers[i];
342 }
343 for (size_t i = 0; i < streams.size(); ++i) {
344 SimulcastStream* sim_stream = &video_codec.simulcastStream[i];
345 RTC_DCHECK_GT(streams[i].width, 0u);
346 RTC_DCHECK_GT(streams[i].height, 0u);
347 RTC_DCHECK_GT(streams[i].max_framerate, 0);
348 // Different framerates not supported per stream at the moment.
349 RTC_DCHECK_EQ(streams[i].max_framerate, streams[0].max_framerate);
350 RTC_DCHECK_GE(streams[i].min_bitrate_bps, 0);
351 RTC_DCHECK_GE(streams[i].target_bitrate_bps, streams[i].min_bitrate_bps);
352 RTC_DCHECK_GE(streams[i].max_bitrate_bps, streams[i].target_bitrate_bps);
353 RTC_DCHECK_GE(streams[i].max_qp, 0);
354
355 sim_stream->width = static_cast<uint16_t>(streams[i].width);
356 sim_stream->height = static_cast<uint16_t>(streams[i].height);
357 sim_stream->minBitrate = streams[i].min_bitrate_bps / 1000;
358 sim_stream->targetBitrate = streams[i].target_bitrate_bps / 1000;
359 sim_stream->maxBitrate = streams[i].max_bitrate_bps / 1000;
360 sim_stream->qpMax = streams[i].max_qp;
361 sim_stream->numberOfTemporalLayers = static_cast<unsigned char>(
362 streams[i].temporal_layer_thresholds_bps.size() + 1);
363
364 video_codec.width = std::max(video_codec.width,
365 static_cast<uint16_t>(streams[i].width));
366 video_codec.height = std::max(
367 video_codec.height, static_cast<uint16_t>(streams[i].height));
368 video_codec.minBitrate =
369 std::min(static_cast<uint16_t>(video_codec.minBitrate),
370 static_cast<uint16_t>(streams[i].min_bitrate_bps / 1000));
371 video_codec.maxBitrate += streams[i].max_bitrate_bps / 1000;
372 video_codec.qpMax = std::max(video_codec.qpMax,
373 static_cast<unsigned int>(streams[i].max_qp));
374 }
375
376 if (video_codec.maxBitrate == 0) {
377 // Unset max bitrate -> cap to one bit per pixel.
378 video_codec.maxBitrate =
379 (video_codec.width * video_codec.height * video_codec.maxFramerate) /
380 1000;
381 }
382 if (video_codec.maxBitrate < kEncoderMinBitrateKbps)
383 video_codec.maxBitrate = kEncoderMinBitrateKbps;
384
385 RTC_DCHECK_GT(streams[0].max_framerate, 0);
386 video_codec.maxFramerate = streams[0].max_framerate;
387 video_codec.expect_encode_from_texture = config.expect_encode_from_texture;
388
389 return video_codec;
390 }
391
392 int CalulcateMaxPadBitrateBps(const VideoEncoderConfig& config,
393 bool pad_to_min_bitrate) { 206 bool pad_to_min_bitrate) {
394 int pad_up_to_bitrate_bps = 0; 207 int pad_up_to_bitrate_bps = 0;
395 // Calculate max padding bitrate for a multi layer codec. 208 // Calculate max padding bitrate for a multi layer codec.
396 if (config.streams.size() > 1) { 209 if (config.streams.size() > 1) {
397 // Pad to min bitrate of the highest layer. 210 // Pad to min bitrate of the highest layer.
398 pad_up_to_bitrate_bps = 211 pad_up_to_bitrate_bps =
399 config.streams[config.streams.size() - 1].min_bitrate_bps; 212 config.streams[config.streams.size() - 1].min_bitrate_bps;
400 // Add target_bitrate_bps of the lower layers. 213 // Add target_bitrate_bps of the lower layers.
401 for (size_t i = 0; i < config.streams.size() - 1; ++i) 214 for (size_t i = 0; i < config.streams.size() - 1; ++i)
402 pad_up_to_bitrate_bps += config.streams[i].target_bitrate_bps; 215 pad_up_to_bitrate_bps += config.streams[i].target_bitrate_bps;
403 } else if (pad_to_min_bitrate) { 216 } else if (pad_to_min_bitrate) {
404 pad_up_to_bitrate_bps = config.streams[0].min_bitrate_bps; 217 pad_up_to_bitrate_bps = config.streams[0].min_bitrate_bps;
405 } 218 }
406 219
407 pad_up_to_bitrate_bps = 220 pad_up_to_bitrate_bps =
408 std::max(pad_up_to_bitrate_bps, config.min_transmit_bitrate_bps); 221 std::max(pad_up_to_bitrate_bps, config.min_transmit_bitrate_bps);
409 222
410 return pad_up_to_bitrate_bps; 223 return pad_up_to_bitrate_bps;
411 } 224 }
412 225
413 } // namespace 226 } // namespace
414 227
415 namespace internal { 228 namespace internal {
229
230 // VideoSendStreamImpl implements internal::VideoSendStream.
231 // It is created and destroyed on |worker_queue|. The intent is to decrease the
232 // need for locking and to ensure methods are called in sequence.
233 // Public methods except |DeliverRtcp| must be called on |worker_queue|.
234 // DeliverRtcp is called on the libjingle worker thread or a network thread.
235 // An encoder may deliver frames through the EncodedImageCallback on an
236 // arbitrary thread.
237 class VideoSendStreamImpl : public webrtc::BitrateAllocatorObserver,
238 public webrtc::VCMProtectionCallback,
239 public EncodedImageCallback {
240 public:
241 VideoSendStreamImpl(SendStatisticsProxy* stats_proxy,
242 rtc::TaskQueue* worker_queue,
243 CallStats* call_stats,
244 CongestionController* congestion_controller,
245 BitrateAllocator* bitrate_allocator,
246 SendDelayStats* send_delay_stats,
247 VieRemb* remb,
248 ViEEncoder* vie_encoder,
249 RtcEventLog* event_log,
250 const VideoSendStream::Config* config,
251 std::map<uint32_t, RtpState> suspended_ssrcs);
252 ~VideoSendStreamImpl() override;
253
254 // RegisterProcessThread register |module_process_thread| with those objects
255 // that use it. Registration has to happen on the thread were
256 // |module_process_thread| was created (libjingle's worker thread).
257 // TODO(perkj): Replace the use of |module_process_thread| with a TaskQueue,
258 // maybe |worker_queue|.
259 void RegisterProcessThread(ProcessThread* module_process_thread);
260 void DeRegisterProcessThread();
261
262 void SignalNetworkState(NetworkState state);
263 bool DeliverRtcp(const uint8_t* packet, size_t length);
264 void Start();
265 void Stop();
266
267 void SignalEncoderConfigurationChanged(const VideoEncoderConfig& config);
268 VideoSendStream::RtpStateMap GetRtpStates() const;
269
270 private:
271 class CheckEncoderActivityTask;
272
273 // Implements BitrateAllocatorObserver.
274 uint32_t OnBitrateUpdated(uint32_t bitrate_bps,
275 uint8_t fraction_loss,
276 int64_t rtt) override;
277
278 // Implements webrtc::VCMProtectionCallback.
279 int ProtectionRequest(const FecProtectionParams* delta_params,
280 const FecProtectionParams* key_params,
281 uint32_t* sent_video_rate_bps,
282 uint32_t* sent_nack_rate_bps,
283 uint32_t* sent_fec_rate_bps) override;
284
285 // Implements EncodedImageCallback. The implementation routes encoded frames
286 // to the |payload_router_| and |config.pre_encode_callback| if set.
287 // Called on an arbitrary encoder callback thread.
288 EncodedImageCallback::Result OnEncodedImage(
289 const EncodedImage& encoded_image,
290 const CodecSpecificInfo* codec_specific_info,
291 const RTPFragmentationHeader* fragmentation) override;
292
293 void ConfigureProtection();
294 void ConfigureSsrcs();
295 void SignalEncoderTimedOut();
296 void SignalEncoderActive();
297
298 SendStatisticsProxy* const stats_proxy_;
299 const VideoSendStream::Config* const config_;
300 std::map<uint32_t, RtpState> suspended_ssrcs_;
301
302 ProcessThread* module_process_thread_;
303 rtc::ThreadChecker module_process_thread_checker_;
304 rtc::TaskQueue* const worker_queue_;
305
306 rtc::CriticalSection encoder_activity_crit_sect_;
307 CheckEncoderActivityTask* check_encoder_activity_task_
308 GUARDED_BY(encoder_activity_crit_sect_);
309 CallStats* const call_stats_;
310 CongestionController* const congestion_controller_;
311 BitrateAllocator* const bitrate_allocator_;
312 VieRemb* const remb_;
313
314 static const bool kEnableFrameRecording = false;
315 static const int kMaxLayers = 3;
316 std::unique_ptr<IvfFileWriter> file_writers_[kMaxLayers];
317
318 int max_padding_bitrate_;
319 int encoder_min_bitrate_bps_;
320 uint32_t encoder_max_bitrate_bps_;
321 uint32_t encoder_target_rate_bps_;
322
323 ViEEncoder* const vie_encoder_;
324 EncoderStateFeedback encoder_feedback_;
325 ProtectionBitrateCalculator protection_bitrate_calculator_;
326
327 const std::unique_ptr<RtcpBandwidthObserver> bandwidth_observer_;
328 // RtpRtcp modules, declared here as they use other members on construction.
329 const std::vector<RtpRtcp*> rtp_rtcp_modules_;
330 PayloadRouter payload_router_;
331 };
332
333 // TODO(tommi): See if there's a more elegant way to create a task that creates
334 // an object on the correct task queue.
335 class VideoSendStream::ConstructionTask : public rtc::QueuedTask {
336 public:
337 ConstructionTask(std::unique_ptr<VideoSendStreamImpl>* send_stream,
338 rtc::Event* done_event,
339 SendStatisticsProxy* stats_proxy,
340 ViEEncoder* vie_encoder,
341 ProcessThread* module_process_thread,
342 CallStats* call_stats,
343 CongestionController* congestion_controller,
344 BitrateAllocator* bitrate_allocator,
345 SendDelayStats* send_delay_stats,
346 VieRemb* remb,
347 RtcEventLog* event_log,
348 const VideoSendStream::Config* config,
349 const std::map<uint32_t, RtpState>& suspended_ssrcs)
350 : send_stream_(send_stream),
351 done_event_(done_event),
352 stats_proxy_(stats_proxy),
353 vie_encoder_(vie_encoder),
354 call_stats_(call_stats),
355 congestion_controller_(congestion_controller),
356 bitrate_allocator_(bitrate_allocator),
357 send_delay_stats_(send_delay_stats),
358 remb_(remb),
359 event_log_(event_log),
360 config_(config),
361 suspended_ssrcs_(suspended_ssrcs) {}
362
363 ~ConstructionTask() override { done_event_->Set(); }
364
365 private:
366 bool Run() override {
367 send_stream_->reset(new VideoSendStreamImpl(
368 stats_proxy_, rtc::TaskQueue::Current(), call_stats_,
369 congestion_controller_, bitrate_allocator_, send_delay_stats_, remb_,
370 vie_encoder_, event_log_, config_, std::move(suspended_ssrcs_)));
371 return true;
372 }
373
374 std::unique_ptr<VideoSendStreamImpl>* const send_stream_;
375 rtc::Event* const done_event_;
376 SendStatisticsProxy* const stats_proxy_;
377 ViEEncoder* const vie_encoder_;
378 CallStats* const call_stats_;
379 CongestionController* const congestion_controller_;
380 BitrateAllocator* const bitrate_allocator_;
381 SendDelayStats* const send_delay_stats_;
382 VieRemb* const remb_;
383 RtcEventLog* const event_log_;
384 const VideoSendStream::Config* config_;
385 std::map<uint32_t, RtpState> suspended_ssrcs_;
386 };
387
388 class VideoSendStream::DestructAndGetRtpStateTask : public rtc::QueuedTask {
389 public:
390 DestructAndGetRtpStateTask(VideoSendStream::RtpStateMap* state_map,
391 std::unique_ptr<VideoSendStreamImpl> send_stream,
392 rtc::Event* done_event)
393 : state_map_(state_map),
394 send_stream_(std::move(send_stream)),
395 done_event_(done_event) {}
396
397 ~DestructAndGetRtpStateTask() override { RTC_CHECK(!send_stream_); }
398
399 private:
400 bool Run() override {
401 send_stream_->Stop();
402 *state_map_ = send_stream_->GetRtpStates();
403 send_stream_.reset();
404 done_event_->Set();
405 return true;
406 }
407
408 VideoSendStream::RtpStateMap* state_map_;
409 std::unique_ptr<VideoSendStreamImpl> send_stream_;
410 rtc::Event* done_event_;
411 };
412
413 // CheckEncoderActivityTask is used for tracking when the encoder last produced
414 // and encoded video frame. If the encoder has not produced anything the last
415 // kEncoderTimeOutMs we also want to stop sending padding.
416 class VideoSendStreamImpl::CheckEncoderActivityTask : public rtc::QueuedTask {
417 public:
418 static const int kEncoderTimeOutMs = 2000;
419 explicit CheckEncoderActivityTask(VideoSendStreamImpl* send_stream)
420 : activity_(0), send_stream_(send_stream), timed_out_(false) {}
421
422 void Stop() {
423 RTC_CHECK(task_checker_.CalledSequentially());
424 send_stream_ = nullptr;
425 }
426
427 void UpdateEncoderActivity() {
428 // UpdateEncoderActivity is called from VideoSendStreamImpl::Encoded on
429 // whatever thread the real encoder implementation run on. In the case of
430 // hardware encoders, there might be several encoders
431 // running in parallel on different threads.
432 rtc::AtomicOps::ReleaseStore(&activity_, 1);
433 }
434
435 private:
436 bool Run() override {
437 RTC_CHECK(task_checker_.CalledSequentially());
438 if (!send_stream_)
439 return true;
440 if (!rtc::AtomicOps::AcquireLoad(&activity_)) {
441 if (!timed_out_) {
442 send_stream_->SignalEncoderTimedOut();
443 }
444 timed_out_ = true;
445 } else if (timed_out_) {
446 send_stream_->SignalEncoderActive();
447 timed_out_ = false;
448 }
449 rtc::AtomicOps::ReleaseStore(&activity_, 0);
450
451 rtc::TaskQueue::Current()->PostDelayedTask(
452 std::unique_ptr<rtc::QueuedTask>(this), kEncoderTimeOutMs);
453 // Return false to prevent this task from being deleted. Ownership has been
454 // transferred to the task queue when PostDelayedTask was called.
455 return false;
456 }
457 volatile int activity_;
458
459 rtc::SequencedTaskChecker task_checker_;
460 VideoSendStreamImpl* send_stream_;
461 bool timed_out_;
462 };
463
464 class ReconfigureVideoEncoderTask : public rtc::QueuedTask {
465 public:
466 ReconfigureVideoEncoderTask(VideoSendStreamImpl* send_stream,
467 VideoEncoderConfig config)
468 : send_stream_(send_stream), config_(std::move(config)) {}
469
470 private:
471 bool Run() override {
472 send_stream_->SignalEncoderConfigurationChanged(std::move(config_));
473 return true;
474 }
475
476 VideoSendStreamImpl* send_stream_;
477 VideoEncoderConfig config_;
478 };
479
416 VideoSendStream::VideoSendStream( 480 VideoSendStream::VideoSendStream(
417 int num_cpu_cores, 481 int num_cpu_cores,
418 ProcessThread* module_process_thread, 482 ProcessThread* module_process_thread,
483 rtc::TaskQueue* worker_queue,
419 CallStats* call_stats, 484 CallStats* call_stats,
420 CongestionController* congestion_controller, 485 CongestionController* congestion_controller,
421 BitrateAllocator* bitrate_allocator, 486 BitrateAllocator* bitrate_allocator,
422 SendDelayStats* send_delay_stats, 487 SendDelayStats* send_delay_stats,
423 VieRemb* remb, 488 VieRemb* remb,
424 RtcEventLog* event_log, 489 RtcEventLog* event_log,
425 const VideoSendStream::Config& config, 490 VideoSendStream::Config config,
426 const VideoEncoderConfig& encoder_config, 491 VideoEncoderConfig encoder_config,
427 const std::map<uint32_t, RtpState>& suspended_ssrcs) 492 const std::map<uint32_t, RtpState>& suspended_ssrcs)
428 : stats_proxy_(Clock::GetRealTimeClock(), 493 : worker_queue_(worker_queue),
494 thread_sync_event_(false /* manual_reset */, false),
495 stats_proxy_(Clock::GetRealTimeClock(),
429 config, 496 config,
430 encoder_config.content_type), 497 encoder_config.content_type),
498 config_(std::move(config)) {
499 vie_encoder_.reset(
500 new ViEEncoder(num_cpu_cores, &stats_proxy_, config_.encoder_settings,
501 config_.pre_encode_callback, config_.overuse_callback,
502 config_.post_encode_callback));
503
504 worker_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(new ConstructionTask(
505 &send_stream_, &thread_sync_event_, &stats_proxy_, vie_encoder_.get(),
506 module_process_thread, call_stats, congestion_controller,
507 bitrate_allocator, send_delay_stats, remb, event_log, &config_,
508 suspended_ssrcs)));
509
510 // Wait for ConstructionTask to complete so that |send_stream_| can be used.
511 // |module_process_thread| must be registered and deregistered on the thread
512 // it was created on.
513 thread_sync_event_.Wait(rtc::Event::kForever);
514 send_stream_->RegisterProcessThread(module_process_thread);
515
516 vie_encoder_->RegisterProcessThread(module_process_thread);
517
518 ReconfigureVideoEncoder(std::move(encoder_config));
519 }
520
521 VideoSendStream::~VideoSendStream() {
522 RTC_DCHECK_RUN_ON(&thread_checker_);
523 RTC_DCHECK(!send_stream_);
524 }
525
526 void VideoSendStream::Start() {
527 RTC_DCHECK_RUN_ON(&thread_checker_);
528 LOG(LS_INFO) << "VideoSendStream::Start";
529 VideoSendStreamImpl* send_stream = send_stream_.get();
530 worker_queue_->PostTask([this, send_stream] {
531 send_stream->Start();
532 thread_sync_event_.Set();
533 });
534
535 // It is expected that after VideoSendStream::Start has been called, incoming
536 // frames are not dropped in ViEEncoder. To ensure this, Start has to be
537 // synchronized.
538 thread_sync_event_.Wait(rtc::Event::kForever);
539 }
540
541 void VideoSendStream::Stop() {
542 RTC_DCHECK_RUN_ON(&thread_checker_);
543 LOG(LS_INFO) << "VideoSendStream::Stop";
544 VideoSendStreamImpl* send_stream = send_stream_.get();
545 worker_queue_->PostTask([send_stream] { send_stream->Stop(); });
546 }
547
548 VideoCaptureInput* VideoSendStream::Input() {
549 // Input() will be called on the thread that deliverers video frames from
550 // libjingle.
551 // TODO(perkj): Refactor ViEEncoder to register directly as a VideoSink to the
552 // VideoSource.
553 return vie_encoder_.get();
554 }
555
556 void VideoSendStream::ReconfigureVideoEncoder(VideoEncoderConfig config) {
557 // ReconfigureVideoEncoder will be called on the thread that deliverers video
558 // frames. We must change the encoder settings immediately so that
559 // the codec settings matches the next frame.
560 // TODO(perkj): Move logic for reconfiguration the encoder due to frame size
561 // change from WebRtcVideoChannel2::WebRtcVideoSendStream::OnFrame to
562 // be internally handled by ViEEncoder.
563 vie_encoder_->ConfigureEncoder(config, config_.rtp.max_packet_size);
564
565 worker_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
566 new ReconfigureVideoEncoderTask(send_stream_.get(), std::move(config))));
567 }
568
569 VideoSendStream::Stats VideoSendStream::GetStats() {
570 // TODO(perkj, solenberg): Some test cases in EndToEndTest call GetStats from
571 // a network thread. See comment in Call::GetStats().
572 // RTC_DCHECK_RUN_ON(&thread_checker_);
573 return stats_proxy_.GetStats();
574 }
575
576 void VideoSendStream::SignalNetworkState(NetworkState state) {
577 RTC_DCHECK_RUN_ON(&thread_checker_);
578 VideoSendStreamImpl* send_stream = send_stream_.get();
579 worker_queue_->PostTask(
580 [send_stream, state] { send_stream->SignalNetworkState(state); });
581 }
582
583 VideoSendStream::RtpStateMap VideoSendStream::StopPermanentlyAndGetRtpStates() {
584 RTC_DCHECK_RUN_ON(&thread_checker_);
585 vie_encoder_->Stop();
586 vie_encoder_->DeRegisterProcessThread();
587 VideoSendStream::RtpStateMap state_map;
588 send_stream_->DeRegisterProcessThread();
589 worker_queue_->PostTask(
590 std::unique_ptr<rtc::QueuedTask>(new DestructAndGetRtpStateTask(
591 &state_map, std::move(send_stream_), &thread_sync_event_)));
592 thread_sync_event_.Wait(rtc::Event::kForever);
593 return state_map;
594 }
595
596 bool VideoSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
597 // Called on a network thread.
598 return send_stream_->DeliverRtcp(packet, length);
599 }
600
601 VideoSendStreamImpl::VideoSendStreamImpl(
602 SendStatisticsProxy* stats_proxy,
603 rtc::TaskQueue* worker_queue,
604 CallStats* call_stats,
605 CongestionController* congestion_controller,
606 BitrateAllocator* bitrate_allocator,
607 SendDelayStats* send_delay_stats,
608 VieRemb* remb,
609 ViEEncoder* vie_encoder,
610 RtcEventLog* event_log,
611 const VideoSendStream::Config* config,
612 std::map<uint32_t, RtpState> suspended_ssrcs)
613 : stats_proxy_(stats_proxy),
431 config_(config), 614 config_(config),
432 suspended_ssrcs_(suspended_ssrcs), 615 suspended_ssrcs_(std::move(suspended_ssrcs)),
433 module_process_thread_(module_process_thread), 616 module_process_thread_(nullptr),
617 worker_queue_(worker_queue),
618 check_encoder_activity_task_(nullptr),
434 call_stats_(call_stats), 619 call_stats_(call_stats),
435 congestion_controller_(congestion_controller), 620 congestion_controller_(congestion_controller),
436 bitrate_allocator_(bitrate_allocator), 621 bitrate_allocator_(bitrate_allocator),
437 remb_(remb), 622 remb_(remb),
438 encoder_thread_(EncoderThreadFunction, this, "EncoderThread"), 623 max_padding_bitrate_(0),
439 encoder_wakeup_event_(false, false), 624 encoder_min_bitrate_bps_(0),
440 stop_encoder_thread_(0),
441 encoder_max_bitrate_bps_(0), 625 encoder_max_bitrate_bps_(0),
442 encoder_target_rate_bps_(0), 626 encoder_target_rate_bps_(0),
443 state_(State::kStopped), 627 vie_encoder_(vie_encoder),
444 overuse_detector_(
445 Clock::GetRealTimeClock(),
446 GetCpuOveruseOptions(config.encoder_settings.full_overuse_time),
447 this,
448 config.post_encode_callback,
449 &stats_proxy_),
450 vie_encoder_(num_cpu_cores,
451 module_process_thread_,
452 &stats_proxy_,
453 &overuse_detector_,
454 this),
455 encoder_feedback_(Clock::GetRealTimeClock(), 628 encoder_feedback_(Clock::GetRealTimeClock(),
456 config.rtp.ssrcs, 629 config_->rtp.ssrcs,
457 &vie_encoder_), 630 vie_encoder),
458 protection_bitrate_calculator_(Clock::GetRealTimeClock(), this), 631 protection_bitrate_calculator_(Clock::GetRealTimeClock(), this),
459 video_sender_(vie_encoder_.video_sender()),
460 bandwidth_observer_(congestion_controller_->GetBitrateController() 632 bandwidth_observer_(congestion_controller_->GetBitrateController()
461 ->CreateRtcpBandwidthObserver()), 633 ->CreateRtcpBandwidthObserver()),
462 rtp_rtcp_modules_(CreateRtpRtcpModules( 634 rtp_rtcp_modules_(CreateRtpRtcpModules(
463 config.send_transport, 635 config_->send_transport,
464 &encoder_feedback_, 636 &encoder_feedback_,
465 bandwidth_observer_.get(), 637 bandwidth_observer_.get(),
466 congestion_controller_->GetTransportFeedbackObserver(), 638 congestion_controller_->GetTransportFeedbackObserver(),
467 call_stats_->rtcp_rtt_stats(), 639 call_stats_->rtcp_rtt_stats(),
468 congestion_controller_->pacer(), 640 congestion_controller_->pacer(),
469 congestion_controller_->packet_router(), 641 congestion_controller_->packet_router(),
470 &stats_proxy_, 642 stats_proxy_,
471 send_delay_stats, 643 send_delay_stats,
472 event_log, 644 event_log,
473 congestion_controller_->GetRetransmissionRateLimiter(), 645 congestion_controller_->GetRetransmissionRateLimiter(),
474 config_.rtp.ssrcs.size())), 646 config_->rtp.ssrcs.size())),
475 payload_router_(rtp_rtcp_modules_, config.encoder_settings.payload_type), 647 payload_router_(rtp_rtcp_modules_,
476 input_(&encoder_wakeup_event_, 648 config_->encoder_settings.payload_type) {
477 config_.local_renderer, 649 RTC_DCHECK_RUN_ON(worker_queue_);
478 &stats_proxy_, 650 LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
479 &overuse_detector_) { 651 module_process_thread_checker_.DetachFromThread();
480 LOG(LS_INFO) << "VideoSendStream: " << config_.ToString(); 652
481 653 RTC_DCHECK(!config_->rtp.ssrcs.empty());
482 RTC_DCHECK(!config_.rtp.ssrcs.empty());
483 RTC_DCHECK(module_process_thread_);
484 RTC_DCHECK(call_stats_); 654 RTC_DCHECK(call_stats_);
485 RTC_DCHECK(congestion_controller_); 655 RTC_DCHECK(congestion_controller_);
486 RTC_DCHECK(remb_); 656 RTC_DCHECK(remb_);
487 657
488 // RTP/RTCP initialization. 658 // RTP/RTCP initialization.
489 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) { 659 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) {
490 module_process_thread_->RegisterModule(rtp_rtcp);
491 congestion_controller_->packet_router()->AddRtpModule(rtp_rtcp); 660 congestion_controller_->packet_router()->AddRtpModule(rtp_rtcp);
492 } 661 }
493 662
494 for (size_t i = 0; i < config_.rtp.extensions.size(); ++i) { 663 for (size_t i = 0; i < config_->rtp.extensions.size(); ++i) {
495 const std::string& extension = config_.rtp.extensions[i].uri; 664 const std::string& extension = config_->rtp.extensions[i].uri;
496 int id = config_.rtp.extensions[i].id; 665 int id = config_->rtp.extensions[i].id;
497 // One-byte-extension local identifiers are in the range 1-14 inclusive. 666 // One-byte-extension local identifiers are in the range 1-14 inclusive.
498 RTC_DCHECK_GE(id, 1); 667 RTC_DCHECK_GE(id, 1);
499 RTC_DCHECK_LE(id, 14); 668 RTC_DCHECK_LE(id, 14);
500 RTC_DCHECK(RtpExtension::IsSupportedForVideo(extension)); 669 RTC_DCHECK(RtpExtension::IsSupportedForVideo(extension));
501 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) { 670 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) {
502 RTC_CHECK_EQ(0, rtp_rtcp->RegisterSendRtpHeaderExtension( 671 RTC_CHECK_EQ(0, rtp_rtcp->RegisterSendRtpHeaderExtension(
503 StringToRtpExtensionType(extension), id)); 672 StringToRtpExtensionType(extension), id));
504 } 673 }
505 } 674 }
506 675
507 remb_->AddRembSender(rtp_rtcp_modules_[0]); 676 remb_->AddRembSender(rtp_rtcp_modules_[0]);
508 rtp_rtcp_modules_[0]->SetREMBStatus(true); 677 rtp_rtcp_modules_[0]->SetREMBStatus(true);
509 678
510 ConfigureProtection(); 679 ConfigureProtection();
511 ConfigureSsrcs(); 680 ConfigureSsrcs();
512 681
513 // TODO(pbos): Should we set CNAME on all RTP modules? 682 // TODO(pbos): Should we set CNAME on all RTP modules?
514 rtp_rtcp_modules_.front()->SetCNAME(config_.rtp.c_name.c_str()); 683 rtp_rtcp_modules_.front()->SetCNAME(config_->rtp.c_name.c_str());
515 // 28 to match packet overhead in ModuleRtpRtcpImpl. 684 // 28 to match packet overhead in ModuleRtpRtcpImpl.
516 static const size_t kRtpPacketSizeOverhead = 28; 685 static const size_t kRtpPacketSizeOverhead = 28;
517 RTC_DCHECK_LE(config_.rtp.max_packet_size, 0xFFFFu + kRtpPacketSizeOverhead); 686 RTC_DCHECK_LE(config_->rtp.max_packet_size, 0xFFFFu + kRtpPacketSizeOverhead);
518 const uint16_t mtu = static_cast<uint16_t>(config_.rtp.max_packet_size + 687 const uint16_t mtu = static_cast<uint16_t>(config_->rtp.max_packet_size +
519 kRtpPacketSizeOverhead); 688 kRtpPacketSizeOverhead);
520 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) { 689 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) {
521 rtp_rtcp->RegisterRtcpStatisticsCallback(&stats_proxy_); 690 rtp_rtcp->RegisterRtcpStatisticsCallback(stats_proxy_);
522 rtp_rtcp->RegisterSendChannelRtpStatisticsCallback(&stats_proxy_); 691 rtp_rtcp->RegisterSendChannelRtpStatisticsCallback(stats_proxy_);
523 rtp_rtcp->SetMaxTransferUnit(mtu); 692 rtp_rtcp->SetMaxTransferUnit(mtu);
524 rtp_rtcp->RegisterVideoSendPayload( 693 rtp_rtcp->RegisterVideoSendPayload(
525 config_.encoder_settings.payload_type, 694 config_->encoder_settings.payload_type,
526 config_.encoder_settings.payload_name.c_str()); 695 config_->encoder_settings.payload_name.c_str());
527 } 696 }
528 697
529 RTC_DCHECK(config.encoder_settings.encoder); 698 RTC_DCHECK(config_->encoder_settings.encoder);
530 RTC_DCHECK_GE(config.encoder_settings.payload_type, 0); 699 RTC_DCHECK_GE(config_->encoder_settings.payload_type, 0);
531 RTC_DCHECK_LE(config.encoder_settings.payload_type, 127); 700 RTC_DCHECK_LE(config_->encoder_settings.payload_type, 127);
532 ReconfigureVideoEncoder(encoder_config);
533 701
534 module_process_thread_->RegisterModule(&overuse_detector_); 702 vie_encoder_->SetStartBitrate(bitrate_allocator_->GetStartBitrate(this));
535 703 vie_encoder_->SetSink(this);
536 encoder_thread_checker_.DetachFromThread();
537 encoder_thread_.Start();
538 encoder_thread_.SetPriority(rtc::kHighPriority);
539 } 704 }
540 705
541 VideoSendStream::~VideoSendStream() { 706 void VideoSendStreamImpl::RegisterProcessThread(
542 LOG(LS_INFO) << "~VideoSendStream: " << config_.ToString(); 707 ProcessThread* module_process_thread) {
708 RTC_DCHECK_RUN_ON(&module_process_thread_checker_);
709 RTC_DCHECK(!module_process_thread_);
710 module_process_thread_ = module_process_thread;
543 711
544 Stop(); 712 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_)
713 module_process_thread_->RegisterModule(rtp_rtcp);
714 }
545 715
546 // Stop the encoder thread permanently. 716 void VideoSendStreamImpl::DeRegisterProcessThread() {
547 rtc::AtomicOps::ReleaseStore(&stop_encoder_thread_, 1); 717 RTC_DCHECK_RUN_ON(&module_process_thread_checker_);
548 encoder_wakeup_event_.Set(); 718 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_)
549 encoder_thread_.Stop(); 719 module_process_thread_->DeRegisterModule(rtp_rtcp);
720 }
550 721
551 // This needs to happen after stopping the encoder thread, 722 VideoSendStreamImpl::~VideoSendStreamImpl() {
552 // since the encoder thread calls AddObserver. 723 RTC_DCHECK_RUN_ON(worker_queue_);
553 bitrate_allocator_->RemoveObserver(this); 724 RTC_DCHECK(!payload_router_.active())
554 725 << "VideoSendStreamImpl::Stop not called";
555 module_process_thread_->DeRegisterModule(&overuse_detector_); 726 LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
556 727
557 rtp_rtcp_modules_[0]->SetREMBStatus(false); 728 rtp_rtcp_modules_[0]->SetREMBStatus(false);
558 remb_->RemoveRembSender(rtp_rtcp_modules_[0]); 729 remb_->RemoveRembSender(rtp_rtcp_modules_[0]);
559 730
560 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) { 731 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) {
561 congestion_controller_->packet_router()->RemoveRtpModule(rtp_rtcp); 732 congestion_controller_->packet_router()->RemoveRtpModule(rtp_rtcp);
562 module_process_thread_->DeRegisterModule(rtp_rtcp);
563 delete rtp_rtcp; 733 delete rtp_rtcp;
564 } 734 }
565 } 735 }
566 736
567 bool VideoSendStream::DeliverRtcp(const uint8_t* packet, size_t length) { 737 bool VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
738 // Runs on a network thread.
739 RTC_DCHECK(!worker_queue_->IsCurrent());
568 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) 740 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_)
569 rtp_rtcp->IncomingRtcpPacket(packet, length); 741 rtp_rtcp->IncomingRtcpPacket(packet, length);
570 return true; 742 return true;
571 } 743 }
572 744
573 void VideoSendStream::Start() { 745 void VideoSendStreamImpl::Start() {
746 RTC_DCHECK_RUN_ON(worker_queue_);
574 LOG(LS_INFO) << "VideoSendStream::Start"; 747 LOG(LS_INFO) << "VideoSendStream::Start";
575 if (payload_router_.active()) 748 if (payload_router_.active())
576 return; 749 return;
577 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start"); 750 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
578 payload_router_.set_active(true); 751 payload_router_.set_active(true);
752
753 bitrate_allocator_->AddObserver(
754 this, encoder_min_bitrate_bps_, encoder_max_bitrate_bps_,
755 max_padding_bitrate_, !config_->suspend_below_min_bitrate);
756
757 // Start monitoring encoder activity.
579 { 758 {
580 rtc::CritScope lock(&encoder_settings_crit_); 759 rtc::CritScope lock(&encoder_activity_crit_sect_);
581 pending_state_change_ = rtc::Optional<State>(State::kStarted); 760 RTC_DCHECK(!check_encoder_activity_task_);
761 check_encoder_activity_task_ = new CheckEncoderActivityTask(this);
762 worker_queue_->PostDelayedTask(
763 std::unique_ptr<rtc::QueuedTask>(check_encoder_activity_task_),
764 CheckEncoderActivityTask::kEncoderTimeOutMs);
582 } 765 }
583 encoder_wakeup_event_.Set(); 766
767 vie_encoder_->SendKeyFrame();
584 } 768 }
585 769
586 void VideoSendStream::Stop() { 770 void VideoSendStreamImpl::Stop() {
771 RTC_DCHECK_RUN_ON(worker_queue_);
587 LOG(LS_INFO) << "VideoSendStream::Stop"; 772 LOG(LS_INFO) << "VideoSendStream::Stop";
588 if (!payload_router_.active()) 773 if (!payload_router_.active())
589 return; 774 return;
590 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop"); 775 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
591 payload_router_.set_active(false); 776 payload_router_.set_active(false);
777 bitrate_allocator_->RemoveObserver(this);
592 { 778 {
593 rtc::CritScope lock(&encoder_settings_crit_); 779 rtc::CritScope lock(&encoder_activity_crit_sect_);
594 pending_state_change_ = rtc::Optional<State>(State::kStopped); 780 check_encoder_activity_task_->Stop();
781 check_encoder_activity_task_ = nullptr;
595 } 782 }
596 encoder_wakeup_event_.Set(); 783 vie_encoder_->OnBitrateUpdated(0, 0, 0);
784 stats_proxy_->OnSetEncoderTargetRate(0);
597 } 785 }
598 786
599 VideoCaptureInput* VideoSendStream::Input() { 787 void VideoSendStreamImpl::SignalEncoderTimedOut() {
600 return &input_; 788 RTC_DCHECK_RUN_ON(worker_queue_);
789 // If the encoder has not produced anything the last kEncoderTimeOutMs and it
790 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
791 // if a camera stops producing frames.
792 if (encoder_target_rate_bps_ > 0) {
793 LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
794 bitrate_allocator_->RemoveObserver(this);
795 }
601 } 796 }
602 797
603 bool VideoSendStream::EncoderThreadFunction(void* obj) { 798 void VideoSendStreamImpl::SignalEncoderActive() {
604 static_cast<VideoSendStream*>(obj)->EncoderProcess(); 799 RTC_DCHECK_RUN_ON(worker_queue_);
605 // We're done, return false to abort. 800 LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
606 return false; 801 bitrate_allocator_->AddObserver(
802 this, encoder_min_bitrate_bps_, encoder_max_bitrate_bps_,
803 max_padding_bitrate_, !config_->suspend_below_min_bitrate);
607 } 804 }
608 805
609 void VideoSendStream::EncoderProcess() { 806 void VideoSendStreamImpl::SignalEncoderConfigurationChanged(
610 RTC_CHECK_EQ(0, vie_encoder_.RegisterExternalEncoder( 807 const VideoEncoderConfig& config) {
611 config_.encoder_settings.encoder, 808 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), config.streams.size());
612 config_.encoder_settings.payload_type, 809 TRACE_EVENT0("webrtc", "VideoSendStream::SignalEncoderConfigurationChanged");
613 config_.encoder_settings.internal_source)); 810 LOG(LS_INFO) << "SignalEncoderConfigurationChanged: " << config.ToString();
614 RTC_DCHECK_RUN_ON(&encoder_thread_checker_); 811 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), config.streams.size());
615 while (true) { 812 RTC_DCHECK_RUN_ON(worker_queue_);
616 // Wake up every kEncodeCheckForActivityPeriodMs to check if the encoder is
617 // active. If not, deregister as BitrateAllocatorObserver.
618 const int kEncodeCheckForActivityPeriodMs = 1000;
619 encoder_wakeup_event_.Wait(kEncodeCheckForActivityPeriodMs);
620 if (rtc::AtomicOps::AcquireLoad(&stop_encoder_thread_))
621 break;
622 bool change_settings = false;
623 rtc::Optional<State> pending_state_change;
624 {
625 rtc::CritScope lock(&encoder_settings_crit_);
626 if (pending_encoder_settings_) {
627 std::swap(current_encoder_settings_, pending_encoder_settings_);
628 pending_encoder_settings_.reset();
629 change_settings = true;
630 } else if (pending_state_change_) {
631 swap(pending_state_change, pending_state_change_);
632 }
633 }
634 if (change_settings) {
635 current_encoder_settings_->video_codec.startBitrate = std::max(
636 bitrate_allocator_->GetStartBitrate(this) / 1000,
637 static_cast<int>(current_encoder_settings_->video_codec.minBitrate));
638 813
639 if (state_ == State::kStarted) { 814 const int kEncoderMinBitrateBps = 30000;
640 bitrate_allocator_->AddObserver( 815 encoder_min_bitrate_bps_ =
641 this, current_encoder_settings_->video_codec.minBitrate * 1000, 816 std::max(config.streams[0].min_bitrate_bps, kEncoderMinBitrateBps);
642 current_encoder_settings_->video_codec.maxBitrate * 1000, 817 encoder_max_bitrate_bps_ = 0;
643 CalulcateMaxPadBitrateBps(current_encoder_settings_->config, 818 for (const auto& stream : config.streams)
644 config_.suspend_below_min_bitrate), 819 encoder_max_bitrate_bps_ += stream.max_bitrate_bps;
645 !config_.suspend_below_min_bitrate); 820 max_padding_bitrate_ =
646 } 821 CalculateMaxPadBitrateBps(config, config_->suspend_below_min_bitrate);
647 822
648 payload_router_.SetSendStreams(current_encoder_settings_->config.streams); 823 payload_router_.SetSendStreams(config.streams);
649 vie_encoder_.SetEncoder(current_encoder_settings_->video_codec,
650 payload_router_.MaxPayloadLength());
651 824
652 // Clear stats for disabled layers. 825 // Clear stats for disabled layers.
653 for (size_t i = current_encoder_settings_->config.streams.size(); 826 for (size_t i = config.streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
654 i < config_.rtp.ssrcs.size(); ++i) { 827 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
655 stats_proxy_.OnInactiveSsrc(config_.rtp.ssrcs[i]); 828 }
656 }
657 829
658 size_t number_of_temporal_layers = 830 size_t number_of_temporal_layers =
659 current_encoder_settings_->config.streams.back() 831 config.streams.back().temporal_layer_thresholds_bps.size() + 1;
660 .temporal_layer_thresholds_bps.size() + 832 protection_bitrate_calculator_.SetEncodingData(
661 1; 833 config.streams[0].width, config.streams[0].height,
662 protection_bitrate_calculator_.SetEncodingData( 834 number_of_temporal_layers, config_->rtp.max_packet_size);
663 current_encoder_settings_->video_codec.width,
664 current_encoder_settings_->video_codec.height,
665 number_of_temporal_layers, payload_router_.MaxPayloadLength());
666 835
667 // We might've gotten new settings while configuring the encoder settings, 836 if (payload_router_.active()) {
668 // restart from the top to see if that's the case before trying to encode 837 // The send stream is started already. Update the allocator with new bitrate
669 // a frame (which might correspond to the last frame size). 838 // limits.
670 encoder_wakeup_event_.Set(); 839 bitrate_allocator_->AddObserver(
671 continue; 840 this, encoder_min_bitrate_bps_, encoder_max_bitrate_bps_,
672 } 841 max_padding_bitrate_, !config_->suspend_below_min_bitrate);
673
674 if (pending_state_change) {
675 if (*pending_state_change == State::kStarted &&
676 state_ == State::kStopped) {
677 bitrate_allocator_->AddObserver(
678 this, current_encoder_settings_->video_codec.minBitrate * 1000,
679 current_encoder_settings_->video_codec.maxBitrate * 1000,
680 CalulcateMaxPadBitrateBps(current_encoder_settings_->config,
681 config_.suspend_below_min_bitrate),
682 !config_.suspend_below_min_bitrate);
683 vie_encoder_.SendKeyFrame();
684 state_ = State::kStarted;
685 LOG_F(LS_INFO) << "Encoder started.";
686 } else if (*pending_state_change == State::kStopped) {
687 bitrate_allocator_->RemoveObserver(this);
688 vie_encoder_.OnBitrateUpdated(0, 0, 0);
689 stats_proxy_.OnSetEncoderTargetRate(0);
690 state_ = State::kStopped;
691 LOG_F(LS_INFO) << "Encoder stopped.";
692 }
693 encoder_wakeup_event_.Set();
694 continue;
695 }
696
697 // Check if the encoder has produced anything the last kEncoderTimeOutMs.
698 // If not, deregister as BitrateAllocatorObserver.
699 if (state_ == State::kStarted &&
700 vie_encoder_.time_of_last_frame_activity_ms() <
701 rtc::TimeMillis() - kEncoderTimeOutMs) {
702 // The encoder has timed out.
703 LOG_F(LS_INFO) << "Encoder timed out.";
704 bitrate_allocator_->RemoveObserver(this);
705 state_ = State::kEncoderTimedOut;
706 }
707 if (state_ == State::kEncoderTimedOut &&
708 vie_encoder_.time_of_last_frame_activity_ms() >
709 rtc::TimeMillis() - kEncoderTimeOutMs) {
710 LOG_F(LS_INFO) << "Encoder is active.";
711 bitrate_allocator_->AddObserver(
712 this, current_encoder_settings_->video_codec.minBitrate * 1000,
713 current_encoder_settings_->video_codec.maxBitrate * 1000,
714 CalulcateMaxPadBitrateBps(current_encoder_settings_->config,
715 config_.suspend_below_min_bitrate),
716 !config_.suspend_below_min_bitrate);
717 state_ = State::kStarted;
718 }
719
720 VideoFrame frame;
721 if (input_.GetVideoFrame(&frame)) {
722 // TODO(perkj): |pre_encode_callback| is only used by tests. Tests should
723 // register as a sink to the VideoSource instead.
724 if (config_.pre_encode_callback) {
725 config_.pre_encode_callback->OnFrame(frame);
726 }
727 vie_encoder_.EncodeVideoFrame(frame);
728 }
729 } 842 }
730 vie_encoder_.DeRegisterExternalEncoder(config_.encoder_settings.payload_type);
731 } 843 }
732 844
733 void VideoSendStream::ReconfigureVideoEncoder( 845 EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
734 const VideoEncoderConfig& config) {
735 TRACE_EVENT0("webrtc", "VideoSendStream::(Re)configureVideoEncoder");
736 LOG(LS_INFO) << "(Re)configureVideoEncoder: " << config.ToString();
737 RTC_DCHECK_GE(config_.rtp.ssrcs.size(), config.streams.size());
738 VideoCodec video_codec = VideoEncoderConfigToVideoCodec(
739 config, config_.encoder_settings.payload_name,
740 config_.encoder_settings.payload_type);
741 {
742 rtc::CritScope lock(&encoder_settings_crit_);
743 encoder_max_bitrate_bps_ = video_codec.maxBitrate * 1000;
744 pending_encoder_settings_.reset(new EncoderSettings({video_codec, config}));
745 }
746 encoder_wakeup_event_.Set();
747 }
748
749 VideoSendStream::Stats VideoSendStream::GetStats() {
750 return stats_proxy_.GetStats();
751 }
752
753 void VideoSendStream::OveruseDetected() {
754 if (config_.overuse_callback)
755 config_.overuse_callback->OnLoadUpdate(LoadObserver::kOveruse);
756 }
757
758 void VideoSendStream::NormalUsage() {
759 if (config_.overuse_callback)
760 config_.overuse_callback->OnLoadUpdate(LoadObserver::kUnderuse);
761 }
762
763 EncodedImageCallback::Result VideoSendStream::OnEncodedImage(
764 const EncodedImage& encoded_image, 846 const EncodedImage& encoded_image,
765 const CodecSpecificInfo* codec_specific_info, 847 const CodecSpecificInfo* codec_specific_info,
766 const RTPFragmentationHeader* fragmentation) { 848 const RTPFragmentationHeader* fragmentation) {
767 if (config_.post_encode_callback) { 849 // Encoded is called on whatever thread the real encoder implementation run
768 config_.post_encode_callback->EncodedFrameCallback( 850 // on. In the case of hardware encoders, there might be several encoders
851 // running in parallel on different threads.
852 if (config_->post_encode_callback) {
853 config_->post_encode_callback->EncodedFrameCallback(
769 EncodedFrame(encoded_image._buffer, encoded_image._length, 854 EncodedFrame(encoded_image._buffer, encoded_image._length,
770 encoded_image._frameType)); 855 encoded_image._frameType));
771 } 856 }
857 {
858 rtc::CritScope lock(&encoder_activity_crit_sect_);
859 if (check_encoder_activity_task_)
860 check_encoder_activity_task_->UpdateEncoderActivity();
861 }
772 862
773 protection_bitrate_calculator_.UpdateWithEncodedData(encoded_image); 863 protection_bitrate_calculator_.UpdateWithEncodedData(encoded_image);
774 EncodedImageCallback::Result result = payload_router_.OnEncodedImage( 864 EncodedImageCallback::Result result = payload_router_.OnEncodedImage(
775 encoded_image, codec_specific_info, fragmentation); 865 encoded_image, codec_specific_info, fragmentation);
776 866
777 if (kEnableFrameRecording) { 867 if (kEnableFrameRecording) {
778 int layer = codec_specific_info->codecType == kVideoCodecVP8 868 int layer = codec_specific_info->codecType == kVideoCodecVP8
779 ? codec_specific_info->codecSpecific.VP8.simulcastIdx 869 ? codec_specific_info->codecSpecific.VP8.simulcastIdx
780 : 0; 870 : 0;
781 IvfFileWriter* file_writer; 871 IvfFileWriter* file_writer;
782 { 872 {
783 if (file_writers_[layer] == nullptr) { 873 if (file_writers_[layer] == nullptr) {
784 std::ostringstream oss; 874 std::ostringstream oss;
785 oss << "send_bitstream_ssrc"; 875 oss << "send_bitstream_ssrc";
786 for (uint32_t ssrc : config_.rtp.ssrcs) 876 for (uint32_t ssrc : config_->rtp.ssrcs)
787 oss << "_" << ssrc; 877 oss << "_" << ssrc;
788 oss << "_layer" << layer << ".ivf"; 878 oss << "_layer" << layer << ".ivf";
789 file_writers_[layer] = 879 file_writers_[layer] =
790 IvfFileWriter::Open(oss.str(), codec_specific_info->codecType); 880 IvfFileWriter::Open(oss.str(), codec_specific_info->codecType);
791 } 881 }
792 file_writer = file_writers_[layer].get(); 882 file_writer = file_writers_[layer].get();
793 } 883 }
794 if (file_writer) { 884 if (file_writer) {
795 bool ok = file_writer->WriteFrame(encoded_image); 885 bool ok = file_writer->WriteFrame(encoded_image);
796 RTC_DCHECK(ok); 886 RTC_DCHECK(ok);
797 } 887 }
798 } 888 }
799 889
800 return result; 890 return result;
801 } 891 }
802 892
803 void VideoSendStream::ConfigureProtection() { 893 void VideoSendStreamImpl::ConfigureProtection() {
894 RTC_DCHECK_RUN_ON(worker_queue_);
804 // Enable NACK, FEC or both. 895 // Enable NACK, FEC or both.
805 const bool enable_protection_nack = config_.rtp.nack.rtp_history_ms > 0; 896 const bool enable_protection_nack = config_->rtp.nack.rtp_history_ms > 0;
806 bool enable_protection_fec = config_.rtp.fec.ulpfec_payload_type != -1; 897 bool enable_protection_fec = config_->rtp.fec.ulpfec_payload_type != -1;
807 // Payload types without picture ID cannot determine that a stream is complete 898 // Payload types without picture ID cannot determine that a stream is complete
808 // without retransmitting FEC, so using FEC + NACK for H.264 (for instance) is 899 // without retransmitting FEC, so using FEC + NACK for H.264 (for instance) is
809 // a waste of bandwidth since FEC packets still have to be transmitted. Note 900 // a waste of bandwidth since FEC packets still have to be transmitted. Note
810 // that this is not the case with FLEXFEC. 901 // that this is not the case with FLEXFEC.
811 if (enable_protection_nack && 902 if (enable_protection_nack &&
812 !PayloadTypeSupportsSkippingFecPackets( 903 !PayloadTypeSupportsSkippingFecPackets(
813 config_.encoder_settings.payload_name)) { 904 config_->encoder_settings.payload_name)) {
814 LOG(LS_WARNING) << "Transmitting payload type without picture ID using" 905 LOG(LS_WARNING) << "Transmitting payload type without picture ID using"
815 "NACK+FEC is a waste of bandwidth since FEC packets " 906 "NACK+FEC is a waste of bandwidth since FEC packets "
816 "also have to be retransmitted. Disabling FEC."; 907 "also have to be retransmitted. Disabling FEC.";
817 enable_protection_fec = false; 908 enable_protection_fec = false;
818 } 909 }
819 910
820 // Set to valid uint8_ts to be castable later without signed overflows. 911 // Set to valid uint8_ts to be castable later without signed overflows.
821 uint8_t payload_type_red = 0; 912 uint8_t payload_type_red = 0;
822 uint8_t payload_type_fec = 0; 913 uint8_t payload_type_fec = 0;
823 914
824 // TODO(changbin): Should set RTX for RED mapping in RTP sender in future. 915 // TODO(changbin): Should set RTX for RED mapping in RTP sender in future.
825 // Validate payload types. If either RED or FEC payload types are set then 916 // Validate payload types. If either RED or FEC payload types are set then
826 // both should be. If FEC is enabled then they both have to be set. 917 // both should be. If FEC is enabled then they both have to be set.
827 if (config_.rtp.fec.red_payload_type != -1) { 918 if (config_->rtp.fec.red_payload_type != -1) {
828 RTC_DCHECK_GE(config_.rtp.fec.red_payload_type, 0); 919 RTC_DCHECK_GE(config_->rtp.fec.red_payload_type, 0);
829 RTC_DCHECK_LE(config_.rtp.fec.red_payload_type, 127); 920 RTC_DCHECK_LE(config_->rtp.fec.red_payload_type, 127);
830 // TODO(holmer): We should only enable red if ulpfec is also enabled, but 921 // TODO(holmer): We should only enable red if ulpfec is also enabled, but
831 // but due to an incompatibility issue with previous versions the receiver 922 // but due to an incompatibility issue with previous versions the receiver
832 // assumes rtx packets are containing red if it has been configured to 923 // assumes rtx packets are containing red if it has been configured to
833 // receive red. Remove this in a few versions once the incompatibility 924 // receive red. Remove this in a few versions once the incompatibility
834 // issue is resolved (M53 timeframe). 925 // issue is resolved (M53 timeframe).
835 payload_type_red = static_cast<uint8_t>(config_.rtp.fec.red_payload_type); 926 payload_type_red = static_cast<uint8_t>(config_->rtp.fec.red_payload_type);
836 } 927 }
837 if (config_.rtp.fec.ulpfec_payload_type != -1) { 928 if (config_->rtp.fec.ulpfec_payload_type != -1) {
838 RTC_DCHECK_GE(config_.rtp.fec.ulpfec_payload_type, 0); 929 RTC_DCHECK_GE(config_->rtp.fec.ulpfec_payload_type, 0);
839 RTC_DCHECK_LE(config_.rtp.fec.ulpfec_payload_type, 127); 930 RTC_DCHECK_LE(config_->rtp.fec.ulpfec_payload_type, 127);
840 payload_type_fec = 931 payload_type_fec =
841 static_cast<uint8_t>(config_.rtp.fec.ulpfec_payload_type); 932 static_cast<uint8_t>(config_->rtp.fec.ulpfec_payload_type);
842 } 933 }
843 934
844 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) { 935 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) {
845 // Set NACK. 936 // Set NACK.
846 rtp_rtcp->SetStorePacketsStatus( 937 rtp_rtcp->SetStorePacketsStatus(
847 enable_protection_nack || congestion_controller_->pacer(), 938 enable_protection_nack || congestion_controller_->pacer(),
848 kMinSendSidePacketHistorySize); 939 kMinSendSidePacketHistorySize);
849 // Set FEC. 940 // Set FEC.
850 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) { 941 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) {
851 rtp_rtcp->SetGenericFECStatus(enable_protection_fec, payload_type_red, 942 rtp_rtcp->SetGenericFECStatus(enable_protection_fec, payload_type_red,
852 payload_type_fec); 943 payload_type_fec);
853 } 944 }
854 } 945 }
855 946
856 protection_bitrate_calculator_.SetProtectionMethod(enable_protection_fec, 947 protection_bitrate_calculator_.SetProtectionMethod(enable_protection_fec,
857 enable_protection_nack); 948 enable_protection_nack);
858 } 949 }
859 950
860 void VideoSendStream::ConfigureSsrcs() { 951 void VideoSendStreamImpl::ConfigureSsrcs() {
952 RTC_DCHECK_RUN_ON(worker_queue_);
861 // Configure regular SSRCs. 953 // Configure regular SSRCs.
862 for (size_t i = 0; i < config_.rtp.ssrcs.size(); ++i) { 954 for (size_t i = 0; i < config_->rtp.ssrcs.size(); ++i) {
863 uint32_t ssrc = config_.rtp.ssrcs[i]; 955 uint32_t ssrc = config_->rtp.ssrcs[i];
864 RtpRtcp* const rtp_rtcp = rtp_rtcp_modules_[i]; 956 RtpRtcp* const rtp_rtcp = rtp_rtcp_modules_[i];
865 rtp_rtcp->SetSSRC(ssrc); 957 rtp_rtcp->SetSSRC(ssrc);
866 958
867 // Restore RTP state if previous existed. 959 // Restore RTP state if previous existed.
868 RtpStateMap::iterator it = suspended_ssrcs_.find(ssrc); 960 VideoSendStream::RtpStateMap::iterator it = suspended_ssrcs_.find(ssrc);
869 if (it != suspended_ssrcs_.end()) 961 if (it != suspended_ssrcs_.end())
870 rtp_rtcp->SetRtpState(it->second); 962 rtp_rtcp->SetRtpState(it->second);
871 } 963 }
872 964
873 // Set up RTX if available. 965 // Set up RTX if available.
874 if (config_.rtp.rtx.ssrcs.empty()) 966 if (config_->rtp.rtx.ssrcs.empty())
875 return; 967 return;
876 968
877 // Configure RTX SSRCs. 969 // Configure RTX SSRCs.
878 RTC_DCHECK_EQ(config_.rtp.rtx.ssrcs.size(), config_.rtp.ssrcs.size()); 970 RTC_DCHECK_EQ(config_->rtp.rtx.ssrcs.size(), config_->rtp.ssrcs.size());
879 for (size_t i = 0; i < config_.rtp.rtx.ssrcs.size(); ++i) { 971 for (size_t i = 0; i < config_->rtp.rtx.ssrcs.size(); ++i) {
880 uint32_t ssrc = config_.rtp.rtx.ssrcs[i]; 972 uint32_t ssrc = config_->rtp.rtx.ssrcs[i];
881 RtpRtcp* const rtp_rtcp = rtp_rtcp_modules_[i]; 973 RtpRtcp* const rtp_rtcp = rtp_rtcp_modules_[i];
882 rtp_rtcp->SetRtxSsrc(ssrc); 974 rtp_rtcp->SetRtxSsrc(ssrc);
883 RtpStateMap::iterator it = suspended_ssrcs_.find(ssrc); 975 VideoSendStream::RtpStateMap::iterator it = suspended_ssrcs_.find(ssrc);
884 if (it != suspended_ssrcs_.end()) 976 if (it != suspended_ssrcs_.end())
885 rtp_rtcp->SetRtxState(it->second); 977 rtp_rtcp->SetRtxState(it->second);
886 } 978 }
887 979
888 // Configure RTX payload types. 980 // Configure RTX payload types.
889 RTC_DCHECK_GE(config_.rtp.rtx.payload_type, 0); 981 RTC_DCHECK_GE(config_->rtp.rtx.payload_type, 0);
890 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) { 982 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) {
891 rtp_rtcp->SetRtxSendPayloadType(config_.rtp.rtx.payload_type, 983 rtp_rtcp->SetRtxSendPayloadType(config_->rtp.rtx.payload_type,
892 config_.encoder_settings.payload_type); 984 config_->encoder_settings.payload_type);
893 rtp_rtcp->SetRtxSendStatus(kRtxRetransmitted | kRtxRedundantPayloads); 985 rtp_rtcp->SetRtxSendStatus(kRtxRetransmitted | kRtxRedundantPayloads);
894 } 986 }
895 if (config_.rtp.fec.red_payload_type != -1 && 987 if (config_->rtp.fec.red_payload_type != -1 &&
896 config_.rtp.fec.red_rtx_payload_type != -1) { 988 config_->rtp.fec.red_rtx_payload_type != -1) {
897 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) { 989 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) {
898 rtp_rtcp->SetRtxSendPayloadType(config_.rtp.fec.red_rtx_payload_type, 990 rtp_rtcp->SetRtxSendPayloadType(config_->rtp.fec.red_rtx_payload_type,
899 config_.rtp.fec.red_payload_type); 991 config_->rtp.fec.red_payload_type);
900 } 992 }
901 } 993 }
902 } 994 }
903 995
904 std::map<uint32_t, RtpState> VideoSendStream::GetRtpStates() const { 996 std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
997 RTC_DCHECK_RUN_ON(worker_queue_);
905 std::map<uint32_t, RtpState> rtp_states; 998 std::map<uint32_t, RtpState> rtp_states;
906 for (size_t i = 0; i < config_.rtp.ssrcs.size(); ++i) { 999 for (size_t i = 0; i < config_->rtp.ssrcs.size(); ++i) {
907 uint32_t ssrc = config_.rtp.ssrcs[i]; 1000 uint32_t ssrc = config_->rtp.ssrcs[i];
908 RTC_DCHECK_EQ(ssrc, rtp_rtcp_modules_[i]->SSRC()); 1001 RTC_DCHECK_EQ(ssrc, rtp_rtcp_modules_[i]->SSRC());
909 rtp_states[ssrc] = rtp_rtcp_modules_[i]->GetRtpState(); 1002 rtp_states[ssrc] = rtp_rtcp_modules_[i]->GetRtpState();
910 } 1003 }
911 1004
912 for (size_t i = 0; i < config_.rtp.rtx.ssrcs.size(); ++i) { 1005 for (size_t i = 0; i < config_->rtp.rtx.ssrcs.size(); ++i) {
913 uint32_t ssrc = config_.rtp.rtx.ssrcs[i]; 1006 uint32_t ssrc = config_->rtp.rtx.ssrcs[i];
914 rtp_states[ssrc] = rtp_rtcp_modules_[i]->GetRtxState(); 1007 rtp_states[ssrc] = rtp_rtcp_modules_[i]->GetRtxState();
915 } 1008 }
916 1009
917 return rtp_states; 1010 return rtp_states;
918 } 1011 }
919 1012
920 void VideoSendStream::SignalNetworkState(NetworkState state) { 1013 void VideoSendStreamImpl::SignalNetworkState(NetworkState state) {
1014 RTC_DCHECK_RUN_ON(worker_queue_);
921 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) { 1015 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) {
922 rtp_rtcp->SetRTCPStatus(state == kNetworkUp ? config_.rtp.rtcp_mode 1016 rtp_rtcp->SetRTCPStatus(state == kNetworkUp ? config_->rtp.rtcp_mode
923 : RtcpMode::kOff); 1017 : RtcpMode::kOff);
924 } 1018 }
925 } 1019 }
926 1020
927 uint32_t VideoSendStream::OnBitrateUpdated(uint32_t bitrate_bps, 1021 uint32_t VideoSendStreamImpl::OnBitrateUpdated(uint32_t bitrate_bps,
928 uint8_t fraction_loss, 1022 uint8_t fraction_loss,
929 int64_t rtt) { 1023 int64_t rtt) {
1024 RTC_DCHECK_RUN_ON(worker_queue_);
1025 RTC_DCHECK(payload_router_.active())
1026 << "VideoSendStream::Start has not been called.";
930 // Get the encoder target rate. It is the estimated network rate - 1027 // Get the encoder target rate. It is the estimated network rate -
931 // protection overhead. 1028 // protection overhead.
932 uint32_t encoder_target_rate_bps = 1029 encoder_target_rate_bps_ = protection_bitrate_calculator_.SetTargetRates(
933 protection_bitrate_calculator_.SetTargetRates( 1030 bitrate_bps, stats_proxy_->GetSendFrameRate(), fraction_loss, rtt);
934 bitrate_bps, stats_proxy_.GetSendFrameRate(), fraction_loss, rtt); 1031 uint32_t protection_bitrate = bitrate_bps - encoder_target_rate_bps_;
935 1032
936 uint32_t protection_bitrate = bitrate_bps - encoder_target_rate_bps; 1033 encoder_target_rate_bps_ =
937 { 1034 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
938 // Limit the target bitrate to the configured max bitrate. 1035 vie_encoder_->OnBitrateUpdated(encoder_target_rate_bps_, fraction_loss, rtt);
939 rtc::CritScope lock(&encoder_settings_crit_); 1036 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
940 encoder_target_rate_bps =
941 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps);
942 if ((encoder_target_rate_bps_ == 0 && encoder_target_rate_bps > 0) ||
943 (encoder_target_rate_bps_ > 0 && encoder_target_rate_bps == 0)) {
944 LOG(LS_INFO)
945 << "OnBitrateUpdated: Encoder state changed, target bitrate "
946 << encoder_target_rate_bps << " bps.";
947 }
948 encoder_target_rate_bps_ = encoder_target_rate_bps;
949 }
950 vie_encoder_.OnBitrateUpdated(encoder_target_rate_bps, fraction_loss, rtt);
951 stats_proxy_.OnSetEncoderTargetRate(encoder_target_rate_bps);
952
953 return protection_bitrate; 1037 return protection_bitrate;
954 } 1038 }
955 1039
956 int VideoSendStream::ProtectionRequest(const FecProtectionParams* delta_params, 1040 int VideoSendStreamImpl::ProtectionRequest(
957 const FecProtectionParams* key_params, 1041 const FecProtectionParams* delta_params,
958 uint32_t* sent_video_rate_bps, 1042 const FecProtectionParams* key_params,
959 uint32_t* sent_nack_rate_bps, 1043 uint32_t* sent_video_rate_bps,
960 uint32_t* sent_fec_rate_bps) { 1044 uint32_t* sent_nack_rate_bps,
1045 uint32_t* sent_fec_rate_bps) {
1046 RTC_DCHECK_RUN_ON(worker_queue_);
961 *sent_video_rate_bps = 0; 1047 *sent_video_rate_bps = 0;
962 *sent_nack_rate_bps = 0; 1048 *sent_nack_rate_bps = 0;
963 *sent_fec_rate_bps = 0; 1049 *sent_fec_rate_bps = 0;
964 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) { 1050 for (RtpRtcp* rtp_rtcp : rtp_rtcp_modules_) {
965 uint32_t not_used = 0; 1051 uint32_t not_used = 0;
966 uint32_t module_video_rate = 0; 1052 uint32_t module_video_rate = 0;
967 uint32_t module_fec_rate = 0; 1053 uint32_t module_fec_rate = 0;
968 uint32_t module_nack_rate = 0; 1054 uint32_t module_nack_rate = 0;
969 rtp_rtcp->SetFecParameters(delta_params, key_params); 1055 rtp_rtcp->SetFecParameters(delta_params, key_params);
970 rtp_rtcp->BitrateSent(&not_used, &module_video_rate, &module_fec_rate, 1056 rtp_rtcp->BitrateSent(&not_used, &module_video_rate, &module_fec_rate,
971 &module_nack_rate); 1057 &module_nack_rate);
972 *sent_video_rate_bps += module_video_rate; 1058 *sent_video_rate_bps += module_video_rate;
973 *sent_nack_rate_bps += module_nack_rate; 1059 *sent_nack_rate_bps += module_nack_rate;
974 *sent_fec_rate_bps += module_fec_rate; 1060 *sent_fec_rate_bps += module_fec_rate;
975 } 1061 }
976 return 0; 1062 return 0;
977 } 1063 }
978 1064
979 } // namespace internal 1065 } // namespace internal
980 } // namespace webrtc 1066 } // namespace webrtc
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698