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

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

Issue 2510583002: Reland #2 of Issue 2434073003: Extract bitrate allocation ... (Closed)
Patch Set: Addressed comments Created 4 years, 1 month 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
« no previous file with comments | « webrtc/video/vie_encoder.h ('k') | webrtc/video/vie_encoder_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 /* 1 /*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. 2 * Copyright (c) 2012 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 10
11 #include "webrtc/video/vie_encoder.h" 11 #include "webrtc/video/vie_encoder.h"
12 12
13 #include <algorithm> 13 #include <algorithm>
14 #include <limits> 14 #include <limits>
15 #include <utility> 15 #include <utility>
16 16
17 #include "webrtc/modules/video_coding/include/video_codec_initializer.h"
17 #include "webrtc/base/checks.h" 18 #include "webrtc/base/checks.h"
18 #include "webrtc/base/logging.h" 19 #include "webrtc/base/logging.h"
19 #include "webrtc/base/trace_event.h" 20 #include "webrtc/base/trace_event.h"
20 #include "webrtc/base/timeutils.h" 21 #include "webrtc/base/timeutils.h"
21 #include "webrtc/modules/pacing/paced_sender.h" 22 #include "webrtc/modules/pacing/paced_sender.h"
23 #include "webrtc/modules/video_coding/codecs/vp8/temporal_layers.h"
22 #include "webrtc/modules/video_coding/include/video_coding.h" 24 #include "webrtc/modules/video_coding/include/video_coding.h"
23 #include "webrtc/modules/video_coding/include/video_coding_defines.h" 25 #include "webrtc/modules/video_coding/include/video_coding_defines.h"
24 #include "webrtc/video/overuse_frame_detector.h" 26 #include "webrtc/video/overuse_frame_detector.h"
25 #include "webrtc/video/send_statistics_proxy.h" 27 #include "webrtc/video/send_statistics_proxy.h"
26 #include "webrtc/video_frame.h" 28 #include "webrtc/video_frame.h"
27 29
28 namespace webrtc { 30 namespace webrtc {
29 31
30 namespace { 32 namespace {
31 // Time interval for logging frame counts. 33 // Time interval for logging frame counts.
32 const int64_t kFrameLogIntervalMs = 60000; 34 const int64_t kFrameLogIntervalMs = 60000;
33 35
34 VideoCodecType PayloadNameToCodecType(const std::string& payload_name) {
35 if (payload_name == "VP8")
36 return kVideoCodecVP8;
37 if (payload_name == "VP9")
38 return kVideoCodecVP9;
39 if (payload_name == "H264")
40 return kVideoCodecH264;
41 return kVideoCodecGeneric;
42 }
43
44 VideoCodec VideoEncoderConfigToVideoCodec(
45 const VideoEncoderConfig& config,
46 const std::vector<VideoStream>& streams,
47 const std::string& payload_name,
48 int payload_type) {
49 static const int kEncoderMinBitrateKbps = 30;
50 RTC_DCHECK(!streams.empty());
51 RTC_DCHECK_GE(config.min_transmit_bitrate_bps, 0);
52
53 VideoCodec video_codec;
54 memset(&video_codec, 0, sizeof(video_codec));
55 video_codec.codecType = PayloadNameToCodecType(payload_name);
56
57 switch (config.content_type) {
58 case VideoEncoderConfig::ContentType::kRealtimeVideo:
59 video_codec.mode = kRealtimeVideo;
60 break;
61 case VideoEncoderConfig::ContentType::kScreen:
62 video_codec.mode = kScreensharing;
63 if (streams.size() == 1 &&
64 streams[0].temporal_layer_thresholds_bps.size() == 1) {
65 video_codec.targetBitrate =
66 streams[0].temporal_layer_thresholds_bps[0] / 1000;
67 }
68 break;
69 }
70
71 if (config.encoder_specific_settings)
72 config.encoder_specific_settings->FillEncoderSpecificSettings(&video_codec);
73
74 switch (video_codec.codecType) {
75 case kVideoCodecVP8: {
76 if (!config.encoder_specific_settings)
77 video_codec.codecSpecific.VP8 = VideoEncoder::GetDefaultVp8Settings();
78 video_codec.codecSpecific.VP8.numberOfTemporalLayers =
79 static_cast<unsigned char>(
80 streams.back().temporal_layer_thresholds_bps.size() + 1);
81 break;
82 }
83 case kVideoCodecVP9: {
84 if (!config.encoder_specific_settings)
85 video_codec.codecSpecific.VP9 = VideoEncoder::GetDefaultVp9Settings();
86 if (video_codec.mode == kScreensharing &&
87 config.encoder_specific_settings) {
88 video_codec.codecSpecific.VP9.flexibleMode = true;
89 // For now VP9 screensharing use 1 temporal and 2 spatial layers.
90 RTC_DCHECK_EQ(1, video_codec.codecSpecific.VP9.numberOfTemporalLayers);
91 RTC_DCHECK_EQ(2, video_codec.codecSpecific.VP9.numberOfSpatialLayers);
92 }
93 video_codec.codecSpecific.VP9.numberOfTemporalLayers =
94 static_cast<unsigned char>(
95 streams.back().temporal_layer_thresholds_bps.size() + 1);
96 break;
97 }
98 case kVideoCodecH264: {
99 if (!config.encoder_specific_settings)
100 video_codec.codecSpecific.H264 = VideoEncoder::GetDefaultH264Settings();
101 break;
102 }
103 default:
104 // TODO(pbos): Support encoder_settings codec-agnostically.
105 RTC_DCHECK(!config.encoder_specific_settings)
106 << "Encoder-specific settings for codec type not wired up.";
107 break;
108 }
109
110 strncpy(video_codec.plName, payload_name.c_str(), kPayloadNameSize - 1);
111 video_codec.plName[kPayloadNameSize - 1] = '\0';
112 video_codec.plType = payload_type;
113 video_codec.numberOfSimulcastStreams =
114 static_cast<unsigned char>(streams.size());
115 video_codec.minBitrate = streams[0].min_bitrate_bps / 1000;
116 if (video_codec.minBitrate < kEncoderMinBitrateKbps)
117 video_codec.minBitrate = kEncoderMinBitrateKbps;
118 RTC_DCHECK_LE(streams.size(), static_cast<size_t>(kMaxSimulcastStreams));
119 if (video_codec.codecType == kVideoCodecVP9) {
120 // If the vector is empty, bitrates will be configured automatically.
121 RTC_DCHECK(config.spatial_layers.empty() ||
122 config.spatial_layers.size() ==
123 video_codec.codecSpecific.VP9.numberOfSpatialLayers);
124 RTC_DCHECK_LE(video_codec.codecSpecific.VP9.numberOfSpatialLayers,
125 kMaxSimulcastStreams);
126 for (size_t i = 0; i < config.spatial_layers.size(); ++i)
127 video_codec.spatialLayers[i] = config.spatial_layers[i];
128 }
129 for (size_t i = 0; i < streams.size(); ++i) {
130 SimulcastStream* sim_stream = &video_codec.simulcastStream[i];
131 RTC_DCHECK_GT(streams[i].width, 0u);
132 RTC_DCHECK_GT(streams[i].height, 0u);
133 RTC_DCHECK_GT(streams[i].max_framerate, 0);
134 // Different framerates not supported per stream at the moment.
135 RTC_DCHECK_EQ(streams[i].max_framerate, streams[0].max_framerate);
136 RTC_DCHECK_GE(streams[i].min_bitrate_bps, 0);
137 RTC_DCHECK_GE(streams[i].target_bitrate_bps, streams[i].min_bitrate_bps);
138 RTC_DCHECK_GE(streams[i].max_bitrate_bps, streams[i].target_bitrate_bps);
139 RTC_DCHECK_GE(streams[i].max_qp, 0);
140
141 sim_stream->width = static_cast<uint16_t>(streams[i].width);
142 sim_stream->height = static_cast<uint16_t>(streams[i].height);
143 sim_stream->minBitrate = streams[i].min_bitrate_bps / 1000;
144 sim_stream->targetBitrate = streams[i].target_bitrate_bps / 1000;
145 sim_stream->maxBitrate = streams[i].max_bitrate_bps / 1000;
146 sim_stream->qpMax = streams[i].max_qp;
147 sim_stream->numberOfTemporalLayers = static_cast<unsigned char>(
148 streams[i].temporal_layer_thresholds_bps.size() + 1);
149
150 video_codec.width = std::max(video_codec.width,
151 static_cast<uint16_t>(streams[i].width));
152 video_codec.height = std::max(
153 video_codec.height, static_cast<uint16_t>(streams[i].height));
154 video_codec.minBitrate =
155 std::min(static_cast<uint16_t>(video_codec.minBitrate),
156 static_cast<uint16_t>(streams[i].min_bitrate_bps / 1000));
157 video_codec.maxBitrate += streams[i].max_bitrate_bps / 1000;
158 video_codec.qpMax = std::max(video_codec.qpMax,
159 static_cast<unsigned int>(streams[i].max_qp));
160 }
161
162 if (video_codec.maxBitrate == 0) {
163 // Unset max bitrate -> cap to one bit per pixel.
164 video_codec.maxBitrate =
165 (video_codec.width * video_codec.height * video_codec.maxFramerate) /
166 1000;
167 }
168 if (video_codec.maxBitrate < kEncoderMinBitrateKbps)
169 video_codec.maxBitrate = kEncoderMinBitrateKbps;
170
171 RTC_DCHECK_GT(streams[0].max_framerate, 0);
172 video_codec.maxFramerate = streams[0].max_framerate;
173 return video_codec;
174 }
175
176 // TODO(pbos): Lower these thresholds (to closer to 100%) when we handle 36 // TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
177 // pipelining encoders better (multiple input frames before something comes 37 // pipelining encoders better (multiple input frames before something comes
178 // out). This should effectively turn off CPU adaptations for systems that 38 // out). This should effectively turn off CPU adaptations for systems that
179 // remotely cope with the load right now. 39 // remotely cope with the load right now.
180 CpuOveruseOptions GetCpuOveruseOptions(bool full_overuse_time) { 40 CpuOveruseOptions GetCpuOveruseOptions(bool full_overuse_time) {
181 CpuOveruseOptions options; 41 CpuOveruseOptions options;
182 if (full_overuse_time) { 42 if (full_overuse_time) {
183 options.low_encode_usage_threshold_percent = 150; 43 options.low_encode_usage_threshold_percent = 150;
184 options.high_encode_usage_threshold_percent = 200; 44 options.high_encode_usage_threshold_percent = 200;
185 } 45 }
(...skipping 179 matching lines...) Expand 10 before | Expand all | Expand 10 after
365 ViEEncoder::ViEEncoder(uint32_t number_of_cores, 225 ViEEncoder::ViEEncoder(uint32_t number_of_cores,
366 SendStatisticsProxy* stats_proxy, 226 SendStatisticsProxy* stats_proxy,
367 const VideoSendStream::Config::EncoderSettings& settings, 227 const VideoSendStream::Config::EncoderSettings& settings,
368 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback, 228 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback,
369 EncodedFrameObserver* encoder_timing) 229 EncodedFrameObserver* encoder_timing)
370 : shutdown_event_(true /* manual_reset */, false), 230 : shutdown_event_(true /* manual_reset */, false),
371 number_of_cores_(number_of_cores), 231 number_of_cores_(number_of_cores),
372 source_proxy_(new VideoSourceProxy(this)), 232 source_proxy_(new VideoSourceProxy(this)),
373 sink_(nullptr), 233 sink_(nullptr),
374 settings_(settings), 234 settings_(settings),
375 codec_type_(PayloadNameToCodecType(settings.payload_name)), 235 codec_type_(PayloadNameToCodecType(settings.payload_name)
236 .value_or(VideoCodecType::kVideoCodecUnknown)),
376 video_sender_(Clock::GetRealTimeClock(), this, this), 237 video_sender_(Clock::GetRealTimeClock(), this, this),
377 overuse_detector_(Clock::GetRealTimeClock(), 238 overuse_detector_(Clock::GetRealTimeClock(),
378 GetCpuOveruseOptions(settings.full_overuse_time), 239 GetCpuOveruseOptions(settings.full_overuse_time),
379 this, 240 this,
380 encoder_timing, 241 encoder_timing,
381 stats_proxy), 242 stats_proxy),
382 stats_proxy_(stats_proxy), 243 stats_proxy_(stats_proxy),
383 pre_encode_callback_(pre_encode_callback), 244 pre_encode_callback_(pre_encode_callback),
384 module_process_thread_(nullptr), 245 module_process_thread_(nullptr),
385 pending_encoder_reconfiguration_(false), 246 pending_encoder_reconfiguration_(false),
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
417 RTC_DCHECK(shutdown_event_.Wait(0)) 278 RTC_DCHECK(shutdown_event_.Wait(0))
418 << "Must call ::Stop() before destruction."; 279 << "Must call ::Stop() before destruction.";
419 } 280 }
420 281
421 void ViEEncoder::Stop() { 282 void ViEEncoder::Stop() {
422 RTC_DCHECK_RUN_ON(&thread_checker_); 283 RTC_DCHECK_RUN_ON(&thread_checker_);
423 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference()); 284 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference());
424 encoder_queue_.PostTask([this] { 285 encoder_queue_.PostTask([this] {
425 RTC_DCHECK_RUN_ON(&encoder_queue_); 286 RTC_DCHECK_RUN_ON(&encoder_queue_);
426 overuse_detector_.StopCheckForOveruse(); 287 overuse_detector_.StopCheckForOveruse();
288 rate_allocator_.reset();
427 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type, 289 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type,
428 false); 290 false);
429 shutdown_event_.Set(); 291 shutdown_event_.Set();
430 }); 292 });
431 293
432 shutdown_event_.Wait(rtc::Event::kForever); 294 shutdown_event_.Wait(rtc::Event::kForever);
433 } 295 }
434 296
435 void ViEEncoder::RegisterProcessThread(ProcessThread* module_process_thread) { 297 void ViEEncoder::RegisterProcessThread(ProcessThread* module_process_thread) {
436 RTC_DCHECK_RUN_ON(&thread_checker_); 298 RTC_DCHECK_RUN_ON(&thread_checker_);
(...skipping 74 matching lines...) Expand 10 before | Expand all | Expand 10 after
511 } 373 }
512 } 374 }
513 375
514 void ViEEncoder::ReconfigureEncoder() { 376 void ViEEncoder::ReconfigureEncoder() {
515 RTC_DCHECK_RUN_ON(&encoder_queue_); 377 RTC_DCHECK_RUN_ON(&encoder_queue_);
516 RTC_DCHECK(pending_encoder_reconfiguration_); 378 RTC_DCHECK(pending_encoder_reconfiguration_);
517 std::vector<VideoStream> streams = 379 std::vector<VideoStream> streams =
518 encoder_config_.video_stream_factory->CreateEncoderStreams( 380 encoder_config_.video_stream_factory->CreateEncoderStreams(
519 last_frame_info_->width, last_frame_info_->height, encoder_config_); 381 last_frame_info_->width, last_frame_info_->height, encoder_config_);
520 382
521 VideoCodec codec = VideoEncoderConfigToVideoCodec( 383 VideoCodec codec;
522 encoder_config_, streams, settings_.payload_name, settings_.payload_type); 384 if (!VideoCodecInitializer::SetupCodec(encoder_config_, settings_, streams,
385 &codec, &rate_allocator_)) {
386 LOG(LS_ERROR) << "Failed to create encoder configuration.";
387 }
523 388
524 codec.startBitrate = 389 codec.startBitrate =
525 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate); 390 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
526 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate); 391 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
527 codec.expect_encode_from_texture = last_frame_info_->is_texture; 392 codec.expect_encode_from_texture = last_frame_info_->is_texture;
528 393
529 bool success = video_sender_.RegisterSendCodec( 394 bool success = video_sender_.RegisterSendCodec(
530 &codec, number_of_cores_, 395 &codec, number_of_cores_,
531 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK; 396 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
532 if (!success) { 397 if (!success) {
533 LOG(LS_ERROR) << "Failed to configure encoder."; 398 LOG(LS_ERROR) << "Failed to configure encoder.";
534 RTC_DCHECK(success); 399 RTC_DCHECK(success);
535 } 400 }
536 401
537 rate_allocator_.reset(new SimulcastRateAllocator(codec)); 402 video_sender_.UpdateChannelParemeters(rate_allocator_.get());
538 if (stats_proxy_) { 403 if (stats_proxy_) {
539 stats_proxy_->OnEncoderReconfigured(encoder_config_, 404 int framerate = stats_proxy_->GetSendFrameRate();
540 rate_allocator_->GetPreferedBitrate()); 405 if (framerate == 0)
406 framerate = codec.maxFramerate;
407 stats_proxy_->OnEncoderReconfigured(
408 encoder_config_, rate_allocator_->GetPreferredBitrateBps(framerate));
541 } 409 }
542 410
543 pending_encoder_reconfiguration_ = false; 411 pending_encoder_reconfiguration_ = false;
544 if (stats_proxy_) { 412
545 stats_proxy_->OnEncoderReconfigured(encoder_config_,
546 rate_allocator_->GetPreferedBitrate());
547 }
548 sink_->OnEncoderConfigurationChanged( 413 sink_->OnEncoderConfigurationChanged(
549 std::move(streams), encoder_config_.min_transmit_bitrate_bps); 414 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
550 } 415 }
551 416
552 void ViEEncoder::OnFrame(const VideoFrame& video_frame) { 417 void ViEEncoder::OnFrame(const VideoFrame& video_frame) {
553 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_); 418 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
554 VideoFrame incoming_frame = video_frame; 419 VideoFrame incoming_frame = video_frame;
555 420
556 // Local time in webrtc time base. 421 // Local time in webrtc time base.
557 int64_t current_time = clock_->TimeInMilliseconds(); 422 int64_t current_time = clock_->TimeInMilliseconds();
(...skipping 205 matching lines...) Expand 10 before | Expand all | Expand 10 after
763 return; 628 return;
764 } 629 }
765 RTC_DCHECK_RUN_ON(&encoder_queue_); 630 RTC_DCHECK_RUN_ON(&encoder_queue_);
766 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active."; 631 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
767 632
768 LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps 633 LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
769 << " packet loss " << static_cast<int>(fraction_lost) 634 << " packet loss " << static_cast<int>(fraction_lost)
770 << " rtt " << round_trip_time_ms; 635 << " rtt " << round_trip_time_ms;
771 636
772 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost, 637 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost,
773 round_trip_time_ms); 638 round_trip_time_ms, rate_allocator_.get());
774 639
775 encoder_start_bitrate_bps_ = 640 encoder_start_bitrate_bps_ =
776 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_; 641 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
777 bool video_is_suspended = bitrate_bps == 0; 642 bool video_is_suspended = bitrate_bps == 0;
778 bool video_suspension_changed = 643 bool video_suspension_changed = video_is_suspended != EncoderPaused();
779 video_is_suspended != (last_observed_bitrate_bps_ == 0);
780 last_observed_bitrate_bps_ = bitrate_bps; 644 last_observed_bitrate_bps_ = bitrate_bps;
781 645
782 if (stats_proxy_ && video_suspension_changed) { 646 if (stats_proxy_ && video_suspension_changed) {
783 LOG(LS_INFO) << "Video suspend state changed to: " 647 LOG(LS_INFO) << "Video suspend state changed to: "
784 << (video_is_suspended ? "suspended" : "not suspended"); 648 << (video_is_suspended ? "suspended" : "not suspended");
785 stats_proxy_->OnSuspendChange(video_is_suspended); 649 stats_proxy_->OnSuspendChange(video_is_suspended);
786 } 650 }
787 } 651 }
788 652
789 void ViEEncoder::OveruseDetected() { 653 void ViEEncoder::OveruseDetected() {
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
824 current_pixel_count > *max_pixel_count_step_up_) { 688 current_pixel_count > *max_pixel_count_step_up_) {
825 max_pixel_count_ = rtc::Optional<int>(); 689 max_pixel_count_ = rtc::Optional<int>();
826 max_pixel_count_step_up_ = rtc::Optional<int>(current_pixel_count); 690 max_pixel_count_step_up_ = rtc::Optional<int>(current_pixel_count);
827 --cpu_restricted_counter_; 691 --cpu_restricted_counter_;
828 stats_proxy_->OnCpuRestrictedResolutionChanged(cpu_restricted_counter_ > 0); 692 stats_proxy_->OnCpuRestrictedResolutionChanged(cpu_restricted_counter_ > 0);
829 source_proxy_->RequestHigherResolutionThan(current_pixel_count); 693 source_proxy_->RequestHigherResolutionThan(current_pixel_count);
830 } 694 }
831 } 695 }
832 696
833 } // namespace webrtc 697 } // namespace webrtc
OLDNEW
« no previous file with comments | « webrtc/video/vie_encoder.h ('k') | webrtc/video/vie_encoder_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698