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

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

Issue 2488833004: Reland of Issue 2434073003: Extract bitrate allocation ... (Closed)
Patch Set: Rebase 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.VP8() = VideoEncoder::GetDefaultVp8Settings();
78 video_codec.VP8()->numberOfTemporalLayers = static_cast<unsigned char>(
79 streams.back().temporal_layer_thresholds_bps.size() + 1);
80 break;
81 }
82 case kVideoCodecVP9: {
83 if (!config.encoder_specific_settings)
84 *video_codec.VP9() = VideoEncoder::GetDefaultVp9Settings();
85 if (video_codec.mode == kScreensharing &&
86 config.encoder_specific_settings) {
87 video_codec.VP9()->flexibleMode = true;
88 // For now VP9 screensharing use 1 temporal and 2 spatial layers.
89 RTC_DCHECK_EQ(1, video_codec.VP9()->numberOfTemporalLayers);
90 RTC_DCHECK_EQ(2, video_codec.VP9()->numberOfSpatialLayers);
91 }
92 video_codec.VP9()->numberOfTemporalLayers = static_cast<unsigned char>(
93 streams.back().temporal_layer_thresholds_bps.size() + 1);
94 break;
95 }
96 case kVideoCodecH264: {
97 if (!config.encoder_specific_settings)
98 *video_codec.H264() = VideoEncoder::GetDefaultH264Settings();
99 break;
100 }
101 default:
102 // TODO(pbos): Support encoder_settings codec-agnostically.
103 RTC_DCHECK(!config.encoder_specific_settings)
104 << "Encoder-specific settings for codec type not wired up.";
105 break;
106 }
107
108 strncpy(video_codec.plName, payload_name.c_str(), kPayloadNameSize - 1);
109 video_codec.plName[kPayloadNameSize - 1] = '\0';
110 video_codec.plType = payload_type;
111 video_codec.numberOfSimulcastStreams =
112 static_cast<unsigned char>(streams.size());
113 video_codec.minBitrate = streams[0].min_bitrate_bps / 1000;
114 if (video_codec.minBitrate < kEncoderMinBitrateKbps)
115 video_codec.minBitrate = kEncoderMinBitrateKbps;
116 RTC_DCHECK_LE(streams.size(), static_cast<size_t>(kMaxSimulcastStreams));
117 if (video_codec.codecType == kVideoCodecVP9) {
118 // If the vector is empty, bitrates will be configured automatically.
119 RTC_DCHECK(config.spatial_layers.empty() ||
120 config.spatial_layers.size() ==
121 video_codec.VP9()->numberOfSpatialLayers);
122 RTC_DCHECK_LE(video_codec.VP9()->numberOfSpatialLayers,
123 kMaxSimulcastStreams);
124 for (size_t i = 0; i < config.spatial_layers.size(); ++i)
125 video_codec.spatialLayers[i] = config.spatial_layers[i];
126 }
127 for (size_t i = 0; i < streams.size(); ++i) {
128 SimulcastStream* sim_stream = &video_codec.simulcastStream[i];
129 RTC_DCHECK_GT(streams[i].width, 0u);
130 RTC_DCHECK_GT(streams[i].height, 0u);
131 RTC_DCHECK_GT(streams[i].max_framerate, 0);
132 // Different framerates not supported per stream at the moment.
133 RTC_DCHECK_EQ(streams[i].max_framerate, streams[0].max_framerate);
134 RTC_DCHECK_GE(streams[i].min_bitrate_bps, 0);
135 RTC_DCHECK_GE(streams[i].target_bitrate_bps, streams[i].min_bitrate_bps);
136 RTC_DCHECK_GE(streams[i].max_bitrate_bps, streams[i].target_bitrate_bps);
137 RTC_DCHECK_GE(streams[i].max_qp, 0);
138
139 sim_stream->width = static_cast<uint16_t>(streams[i].width);
140 sim_stream->height = static_cast<uint16_t>(streams[i].height);
141 sim_stream->minBitrate = streams[i].min_bitrate_bps / 1000;
142 sim_stream->targetBitrate = streams[i].target_bitrate_bps / 1000;
143 sim_stream->maxBitrate = streams[i].max_bitrate_bps / 1000;
144 sim_stream->qpMax = streams[i].max_qp;
145 sim_stream->numberOfTemporalLayers = static_cast<unsigned char>(
146 streams[i].temporal_layer_thresholds_bps.size() + 1);
147
148 video_codec.width = std::max(video_codec.width,
149 static_cast<uint16_t>(streams[i].width));
150 video_codec.height = std::max(
151 video_codec.height, static_cast<uint16_t>(streams[i].height));
152 video_codec.minBitrate =
153 std::min(static_cast<uint16_t>(video_codec.minBitrate),
154 static_cast<uint16_t>(streams[i].min_bitrate_bps / 1000));
155 video_codec.maxBitrate += streams[i].max_bitrate_bps / 1000;
156 video_codec.qpMax = std::max(video_codec.qpMax,
157 static_cast<unsigned int>(streams[i].max_qp));
158 }
159
160 if (video_codec.maxBitrate == 0) {
161 // Unset max bitrate -> cap to one bit per pixel.
162 video_codec.maxBitrate =
163 (video_codec.width * video_codec.height * video_codec.maxFramerate) /
164 1000;
165 }
166 if (video_codec.maxBitrate < kEncoderMinBitrateKbps)
167 video_codec.maxBitrate = kEncoderMinBitrateKbps;
168
169 RTC_DCHECK_GT(streams[0].max_framerate, 0);
170 video_codec.maxFramerate = streams[0].max_framerate;
171 return video_codec;
172 }
173
174 // 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
175 // pipelining encoders better (multiple input frames before something comes 37 // pipelining encoders better (multiple input frames before something comes
176 // out). This should effectively turn off CPU adaptations for systems that 38 // out). This should effectively turn off CPU adaptations for systems that
177 // remotely cope with the load right now. 39 // remotely cope with the load right now.
178 CpuOveruseOptions GetCpuOveruseOptions(bool full_overuse_time) { 40 CpuOveruseOptions GetCpuOveruseOptions(bool full_overuse_time) {
179 CpuOveruseOptions options; 41 CpuOveruseOptions options;
180 if (full_overuse_time) { 42 if (full_overuse_time) {
181 options.low_encode_usage_threshold_percent = 150; 43 options.low_encode_usage_threshold_percent = 150;
182 options.high_encode_usage_threshold_percent = 200; 44 options.high_encode_usage_threshold_percent = 200;
183 } 45 }
(...skipping 179 matching lines...) Expand 10 before | Expand all | Expand 10 after
363 ViEEncoder::ViEEncoder(uint32_t number_of_cores, 225 ViEEncoder::ViEEncoder(uint32_t number_of_cores,
364 SendStatisticsProxy* stats_proxy, 226 SendStatisticsProxy* stats_proxy,
365 const VideoSendStream::Config::EncoderSettings& settings, 227 const VideoSendStream::Config::EncoderSettings& settings,
366 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback, 228 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback,
367 EncodedFrameObserver* encoder_timing) 229 EncodedFrameObserver* encoder_timing)
368 : shutdown_event_(true /* manual_reset */, false), 230 : shutdown_event_(true /* manual_reset */, false),
369 number_of_cores_(number_of_cores), 231 number_of_cores_(number_of_cores),
370 source_proxy_(new VideoSourceProxy(this)), 232 source_proxy_(new VideoSourceProxy(this)),
371 sink_(nullptr), 233 sink_(nullptr),
372 settings_(settings), 234 settings_(settings),
373 codec_type_(PayloadNameToCodecType(settings.payload_name)), 235 codec_type_(PayloadNameToCodecType(settings.payload_name)
236 .value_or(VideoCodecType::kVideoCodecUnknown)),
374 video_sender_(Clock::GetRealTimeClock(), this, this), 237 video_sender_(Clock::GetRealTimeClock(), this, this),
375 overuse_detector_(Clock::GetRealTimeClock(), 238 overuse_detector_(Clock::GetRealTimeClock(),
376 GetCpuOveruseOptions(settings.full_overuse_time), 239 GetCpuOveruseOptions(settings.full_overuse_time),
377 this, 240 this,
378 encoder_timing, 241 encoder_timing,
379 stats_proxy), 242 stats_proxy),
380 stats_proxy_(stats_proxy), 243 stats_proxy_(stats_proxy),
381 pre_encode_callback_(pre_encode_callback), 244 pre_encode_callback_(pre_encode_callback),
382 module_process_thread_(nullptr), 245 module_process_thread_(nullptr),
383 pending_encoder_reconfiguration_(false), 246 pending_encoder_reconfiguration_(false),
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
415 RTC_DCHECK(shutdown_event_.Wait(0)) 278 RTC_DCHECK(shutdown_event_.Wait(0))
416 << "Must call ::Stop() before destruction."; 279 << "Must call ::Stop() before destruction.";
417 } 280 }
418 281
419 void ViEEncoder::Stop() { 282 void ViEEncoder::Stop() {
420 RTC_DCHECK_RUN_ON(&thread_checker_); 283 RTC_DCHECK_RUN_ON(&thread_checker_);
421 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference()); 284 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference());
422 encoder_queue_.PostTask([this] { 285 encoder_queue_.PostTask([this] {
423 RTC_DCHECK_RUN_ON(&encoder_queue_); 286 RTC_DCHECK_RUN_ON(&encoder_queue_);
424 overuse_detector_.StopCheckForOveruse(); 287 overuse_detector_.StopCheckForOveruse();
288 rate_allocator_.reset();
425 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type, 289 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type,
426 false); 290 false);
427 shutdown_event_.Set(); 291 shutdown_event_.Set();
428 }); 292 });
429 293
430 shutdown_event_.Wait(rtc::Event::kForever); 294 shutdown_event_.Wait(rtc::Event::kForever);
431 } 295 }
432 296
433 void ViEEncoder::RegisterProcessThread(ProcessThread* module_process_thread) { 297 void ViEEncoder::RegisterProcessThread(ProcessThread* module_process_thread) {
434 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
509 } 373 }
510 } 374 }
511 375
512 void ViEEncoder::ReconfigureEncoder() { 376 void ViEEncoder::ReconfigureEncoder() {
513 RTC_DCHECK_RUN_ON(&encoder_queue_); 377 RTC_DCHECK_RUN_ON(&encoder_queue_);
514 RTC_DCHECK(pending_encoder_reconfiguration_); 378 RTC_DCHECK(pending_encoder_reconfiguration_);
515 std::vector<VideoStream> streams = 379 std::vector<VideoStream> streams =
516 encoder_config_.video_stream_factory->CreateEncoderStreams( 380 encoder_config_.video_stream_factory->CreateEncoderStreams(
517 last_frame_info_->width, last_frame_info_->height, encoder_config_); 381 last_frame_info_->width, last_frame_info_->height, encoder_config_);
518 382
519 VideoCodec codec = VideoEncoderConfigToVideoCodec( 383 VideoCodec codec;
520 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 }
521 388
522 codec.startBitrate = 389 codec.startBitrate =
523 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate); 390 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
524 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate); 391 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
525 codec.expect_encode_from_texture = last_frame_info_->is_texture; 392 codec.expect_encode_from_texture = last_frame_info_->is_texture;
526 393
527 bool success = video_sender_.RegisterSendCodec( 394 bool success = video_sender_.RegisterSendCodec(
528 &codec, number_of_cores_, 395 &codec, number_of_cores_,
529 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK; 396 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
530 if (!success) { 397 if (!success) {
531 LOG(LS_ERROR) << "Failed to configure encoder."; 398 LOG(LS_ERROR) << "Failed to configure encoder.";
532 RTC_DCHECK(success); 399 RTC_DCHECK(success);
533 } 400 }
534 401
535 rate_allocator_.reset(new SimulcastRateAllocator(codec)); 402 video_sender_.UpdateChannelParemeters(rate_allocator_.get());
403
536 if (stats_proxy_) { 404 if (stats_proxy_) {
537 stats_proxy_->OnEncoderReconfigured(encoder_config_, 405 int framerate = stats_proxy_->GetSendFrameRate();
538 rate_allocator_->GetPreferedBitrate()); 406 if (framerate == 0)
407 framerate = codec.maxFramerate;
408 stats_proxy_->OnEncoderReconfigured(
409 encoder_config_, rate_allocator_->GetPreferredBitrateBps(framerate));
539 } 410 }
540 411
541 pending_encoder_reconfiguration_ = false; 412 pending_encoder_reconfiguration_ = false;
542 if (stats_proxy_) { 413
543 stats_proxy_->OnEncoderReconfigured(encoder_config_,
544 rate_allocator_->GetPreferedBitrate());
545 }
546 sink_->OnEncoderConfigurationChanged( 414 sink_->OnEncoderConfigurationChanged(
547 std::move(streams), encoder_config_.min_transmit_bitrate_bps); 415 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
548 } 416 }
549 417
550 void ViEEncoder::OnFrame(const VideoFrame& video_frame) { 418 void ViEEncoder::OnFrame(const VideoFrame& video_frame) {
551 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_); 419 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
552 VideoFrame incoming_frame = video_frame; 420 VideoFrame incoming_frame = video_frame;
553 421
554 // Local time in webrtc time base. 422 // Local time in webrtc time base.
555 int64_t current_time = clock_->TimeInMilliseconds(); 423 int64_t current_time = clock_->TimeInMilliseconds();
(...skipping 201 matching lines...) Expand 10 before | Expand all | Expand 10 after
757 return; 625 return;
758 } 626 }
759 RTC_DCHECK_RUN_ON(&encoder_queue_); 627 RTC_DCHECK_RUN_ON(&encoder_queue_);
760 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active."; 628 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
761 629
762 LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps 630 LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
763 << " packet loss " << static_cast<int>(fraction_lost) 631 << " packet loss " << static_cast<int>(fraction_lost)
764 << " rtt " << round_trip_time_ms; 632 << " rtt " << round_trip_time_ms;
765 633
766 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost, 634 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost,
767 round_trip_time_ms); 635 round_trip_time_ms, rate_allocator_.get());
768 636
769 encoder_start_bitrate_bps_ = 637 encoder_start_bitrate_bps_ =
770 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_; 638 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
771 bool video_is_suspended = bitrate_bps == 0; 639 bool video_is_suspended = bitrate_bps == 0;
772 bool video_suspension_changed = 640 bool video_suspension_changed = video_is_suspended != EncoderPaused();
773 video_is_suspended != (last_observed_bitrate_bps_ == 0);
774 last_observed_bitrate_bps_ = bitrate_bps; 641 last_observed_bitrate_bps_ = bitrate_bps;
775 642
776 if (stats_proxy_ && video_suspension_changed) { 643 if (stats_proxy_ && video_suspension_changed) {
777 LOG(LS_INFO) << "Video suspend state changed to: " 644 LOG(LS_INFO) << "Video suspend state changed to: "
778 << (video_is_suspended ? "suspended" : "not suspended"); 645 << (video_is_suspended ? "suspended" : "not suspended");
779 stats_proxy_->OnSuspendChange(video_is_suspended); 646 stats_proxy_->OnSuspendChange(video_is_suspended);
780 } 647 }
781 } 648 }
782 649
783 void ViEEncoder::OveruseDetected() { 650 void ViEEncoder::OveruseDetected() {
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
818 current_pixel_count > *max_pixel_count_step_up_) { 685 current_pixel_count > *max_pixel_count_step_up_) {
819 max_pixel_count_ = rtc::Optional<int>(); 686 max_pixel_count_ = rtc::Optional<int>();
820 max_pixel_count_step_up_ = rtc::Optional<int>(current_pixel_count); 687 max_pixel_count_step_up_ = rtc::Optional<int>(current_pixel_count);
821 --cpu_restricted_counter_; 688 --cpu_restricted_counter_;
822 stats_proxy_->OnCpuRestrictedResolutionChanged(cpu_restricted_counter_ > 0); 689 stats_proxy_->OnCpuRestrictedResolutionChanged(cpu_restricted_counter_ > 0);
823 source_proxy_->RequestHigherResolutionThan(current_pixel_count); 690 source_proxy_->RequestHigherResolutionThan(current_pixel_count);
824 } 691 }
825 } 692 }
826 693
827 } // namespace webrtc 694 } // 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