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

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

Issue 2489843002: Revert of Extract bitrate allocation of spatial/temporal layers out of codec impl. (Closed)
Patch Set: 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"
18 #include "webrtc/base/checks.h" 17 #include "webrtc/base/checks.h"
19 #include "webrtc/base/logging.h" 18 #include "webrtc/base/logging.h"
20 #include "webrtc/base/trace_event.h" 19 #include "webrtc/base/trace_event.h"
21 #include "webrtc/base/timeutils.h" 20 #include "webrtc/base/timeutils.h"
22 #include "webrtc/modules/pacing/paced_sender.h" 21 #include "webrtc/modules/pacing/paced_sender.h"
23 #include "webrtc/modules/video_coding/codecs/vp8/temporal_layers.h"
24 #include "webrtc/modules/video_coding/include/video_coding.h" 22 #include "webrtc/modules/video_coding/include/video_coding.h"
25 #include "webrtc/modules/video_coding/include/video_coding_defines.h" 23 #include "webrtc/modules/video_coding/include/video_coding_defines.h"
26 #include "webrtc/video/overuse_frame_detector.h" 24 #include "webrtc/video/overuse_frame_detector.h"
27 #include "webrtc/video/send_statistics_proxy.h" 25 #include "webrtc/video/send_statistics_proxy.h"
28 #include "webrtc/video_frame.h" 26 #include "webrtc/video_frame.h"
29 27
30 namespace webrtc { 28 namespace webrtc {
31 29
32 namespace { 30 namespace {
33 // Time interval for logging frame counts. 31 // Time interval for logging frame counts.
34 const int64_t kFrameLogIntervalMs = 60000; 32 const int64_t kFrameLogIntervalMs = 60000;
35 33
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
36 // TODO(pbos): Lower these thresholds (to closer to 100%) when we handle 176 // TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
37 // pipelining encoders better (multiple input frames before something comes 177 // pipelining encoders better (multiple input frames before something comes
38 // out). This should effectively turn off CPU adaptations for systems that 178 // out). This should effectively turn off CPU adaptations for systems that
39 // remotely cope with the load right now. 179 // remotely cope with the load right now.
40 CpuOveruseOptions GetCpuOveruseOptions(bool full_overuse_time) { 180 CpuOveruseOptions GetCpuOveruseOptions(bool full_overuse_time) {
41 CpuOveruseOptions options; 181 CpuOveruseOptions options;
42 if (full_overuse_time) { 182 if (full_overuse_time) {
43 options.low_encode_usage_threshold_percent = 150; 183 options.low_encode_usage_threshold_percent = 150;
44 options.high_encode_usage_threshold_percent = 200; 184 options.high_encode_usage_threshold_percent = 200;
45 } 185 }
(...skipping 179 matching lines...) Expand 10 before | Expand all | Expand 10 after
225 ViEEncoder::ViEEncoder(uint32_t number_of_cores, 365 ViEEncoder::ViEEncoder(uint32_t number_of_cores,
226 SendStatisticsProxy* stats_proxy, 366 SendStatisticsProxy* stats_proxy,
227 const VideoSendStream::Config::EncoderSettings& settings, 367 const VideoSendStream::Config::EncoderSettings& settings,
228 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback, 368 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback,
229 EncodedFrameObserver* encoder_timing) 369 EncodedFrameObserver* encoder_timing)
230 : shutdown_event_(true /* manual_reset */, false), 370 : shutdown_event_(true /* manual_reset */, false),
231 number_of_cores_(number_of_cores), 371 number_of_cores_(number_of_cores),
232 source_proxy_(new VideoSourceProxy(this)), 372 source_proxy_(new VideoSourceProxy(this)),
233 sink_(nullptr), 373 sink_(nullptr),
234 settings_(settings), 374 settings_(settings),
235 codec_type_(PayloadNameToCodecType(settings.payload_name) 375 codec_type_(PayloadNameToCodecType(settings.payload_name)),
236 .value_or(VideoCodecType::kVideoCodecUnknown)),
237 video_sender_(Clock::GetRealTimeClock(), this, this), 376 video_sender_(Clock::GetRealTimeClock(), this, this),
238 overuse_detector_(Clock::GetRealTimeClock(), 377 overuse_detector_(Clock::GetRealTimeClock(),
239 GetCpuOveruseOptions(settings.full_overuse_time), 378 GetCpuOveruseOptions(settings.full_overuse_time),
240 this, 379 this,
241 encoder_timing, 380 encoder_timing,
242 stats_proxy), 381 stats_proxy),
243 stats_proxy_(stats_proxy), 382 stats_proxy_(stats_proxy),
244 pre_encode_callback_(pre_encode_callback), 383 pre_encode_callback_(pre_encode_callback),
245 module_process_thread_(nullptr), 384 module_process_thread_(nullptr),
246 pending_encoder_reconfiguration_(false), 385 pending_encoder_reconfiguration_(false),
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
278 RTC_DCHECK(shutdown_event_.Wait(0)) 417 RTC_DCHECK(shutdown_event_.Wait(0))
279 << "Must call ::Stop() before destruction."; 418 << "Must call ::Stop() before destruction.";
280 } 419 }
281 420
282 void ViEEncoder::Stop() { 421 void ViEEncoder::Stop() {
283 RTC_DCHECK_RUN_ON(&thread_checker_); 422 RTC_DCHECK_RUN_ON(&thread_checker_);
284 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference()); 423 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference());
285 encoder_queue_.PostTask([this] { 424 encoder_queue_.PostTask([this] {
286 RTC_DCHECK_RUN_ON(&encoder_queue_); 425 RTC_DCHECK_RUN_ON(&encoder_queue_);
287 overuse_detector_.StopCheckForOveruse(); 426 overuse_detector_.StopCheckForOveruse();
288 rate_allocator_.reset();
289 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type, 427 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type,
290 false); 428 false);
291 shutdown_event_.Set(); 429 shutdown_event_.Set();
292 }); 430 });
293 431
294 shutdown_event_.Wait(rtc::Event::kForever); 432 shutdown_event_.Wait(rtc::Event::kForever);
295 } 433 }
296 434
297 void ViEEncoder::RegisterProcessThread(ProcessThread* module_process_thread) { 435 void ViEEncoder::RegisterProcessThread(ProcessThread* module_process_thread) {
298 RTC_DCHECK_RUN_ON(&thread_checker_); 436 RTC_DCHECK_RUN_ON(&thread_checker_);
(...skipping 74 matching lines...) Expand 10 before | Expand all | Expand 10 after
373 } 511 }
374 } 512 }
375 513
376 void ViEEncoder::ReconfigureEncoder() { 514 void ViEEncoder::ReconfigureEncoder() {
377 RTC_DCHECK_RUN_ON(&encoder_queue_); 515 RTC_DCHECK_RUN_ON(&encoder_queue_);
378 RTC_DCHECK(pending_encoder_reconfiguration_); 516 RTC_DCHECK(pending_encoder_reconfiguration_);
379 std::vector<VideoStream> streams = 517 std::vector<VideoStream> streams =
380 encoder_config_.video_stream_factory->CreateEncoderStreams( 518 encoder_config_.video_stream_factory->CreateEncoderStreams(
381 last_frame_info_->width, last_frame_info_->height, encoder_config_); 519 last_frame_info_->width, last_frame_info_->height, encoder_config_);
382 520
383 VideoCodec codec; 521 VideoCodec codec = VideoEncoderConfigToVideoCodec(
384 if (!VideoCodecInitializer::SetupCodec(encoder_config_, settings_, streams, 522 encoder_config_, streams, settings_.payload_name, settings_.payload_type);
385 &codec, &rate_allocator_)) {
386 LOG(LS_ERROR) << "Failed to create encoder configuration.";
387 }
388 523
389 codec.startBitrate = 524 codec.startBitrate =
390 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate); 525 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
391 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate); 526 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
392 codec.expect_encode_from_texture = last_frame_info_->is_texture; 527 codec.expect_encode_from_texture = last_frame_info_->is_texture;
393 528
394 bool success = video_sender_.RegisterSendCodec( 529 bool success = video_sender_.RegisterSendCodec(
395 &codec, number_of_cores_, 530 &codec, number_of_cores_,
396 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK; 531 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
397 if (!success) { 532 if (!success) {
398 LOG(LS_ERROR) << "Failed to configure encoder."; 533 LOG(LS_ERROR) << "Failed to configure encoder.";
399 RTC_DCHECK(success); 534 RTC_DCHECK(success);
400 } 535 }
401 536
402 video_sender_.UpdateChannelParemeters(rate_allocator_.get()); 537 rate_allocator_.reset(new SimulcastRateAllocator(codec));
403
404 if (stats_proxy_) { 538 if (stats_proxy_) {
405 int framerate = stats_proxy_->GetSendFrameRate(); 539 stats_proxy_->OnEncoderReconfigured(encoder_config_,
406 if (framerate == 0) 540 rate_allocator_->GetPreferedBitrate());
407 framerate = codec.maxFramerate;
408 stats_proxy_->OnEncoderReconfigured(
409 encoder_config_, rate_allocator_->GetPreferredBitrateBps(framerate));
410 } 541 }
411 542
412 pending_encoder_reconfiguration_ = false; 543 pending_encoder_reconfiguration_ = false;
413 544 if (stats_proxy_) {
545 stats_proxy_->OnEncoderReconfigured(encoder_config_,
546 rate_allocator_->GetPreferedBitrate());
547 }
414 sink_->OnEncoderConfigurationChanged( 548 sink_->OnEncoderConfigurationChanged(
415 std::move(streams), encoder_config_.min_transmit_bitrate_bps); 549 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
416 } 550 }
417 551
418 void ViEEncoder::OnFrame(const VideoFrame& video_frame) { 552 void ViEEncoder::OnFrame(const VideoFrame& video_frame) {
419 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_); 553 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
420 VideoFrame incoming_frame = video_frame; 554 VideoFrame incoming_frame = video_frame;
421 555
422 // Local time in webrtc time base. 556 // Local time in webrtc time base.
423 int64_t current_time = clock_->TimeInMilliseconds(); 557 int64_t current_time = clock_->TimeInMilliseconds();
(...skipping 205 matching lines...) Expand 10 before | Expand all | Expand 10 after
629 return; 763 return;
630 } 764 }
631 RTC_DCHECK_RUN_ON(&encoder_queue_); 765 RTC_DCHECK_RUN_ON(&encoder_queue_);
632 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active."; 766 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
633 767
634 LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps 768 LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
635 << " packet loss " << static_cast<int>(fraction_lost) 769 << " packet loss " << static_cast<int>(fraction_lost)
636 << " rtt " << round_trip_time_ms; 770 << " rtt " << round_trip_time_ms;
637 771
638 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost, 772 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost,
639 round_trip_time_ms, rate_allocator_.get()); 773 round_trip_time_ms);
640 774
641 encoder_start_bitrate_bps_ = 775 encoder_start_bitrate_bps_ =
642 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_; 776 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
643 bool video_is_suspended = bitrate_bps == 0; 777 bool video_is_suspended = bitrate_bps == 0;
644 bool video_suspension_changed = video_is_suspended != EncoderPaused(); 778 bool video_suspension_changed =
779 video_is_suspended != (last_observed_bitrate_bps_ == 0);
645 last_observed_bitrate_bps_ = bitrate_bps; 780 last_observed_bitrate_bps_ = bitrate_bps;
646 781
647 if (stats_proxy_ && video_suspension_changed) { 782 if (stats_proxy_ && video_suspension_changed) {
648 LOG(LS_INFO) << "Video suspend state changed to: " 783 LOG(LS_INFO) << "Video suspend state changed to: "
649 << (video_is_suspended ? "suspended" : "not suspended"); 784 << (video_is_suspended ? "suspended" : "not suspended");
650 stats_proxy_->OnSuspendChange(video_is_suspended); 785 stats_proxy_->OnSuspendChange(video_is_suspended);
651 } 786 }
652 } 787 }
653 788
654 void ViEEncoder::OveruseDetected() { 789 void ViEEncoder::OveruseDetected() {
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
689 current_pixel_count > *max_pixel_count_step_up_) { 824 current_pixel_count > *max_pixel_count_step_up_) {
690 max_pixel_count_ = rtc::Optional<int>(); 825 max_pixel_count_ = rtc::Optional<int>();
691 max_pixel_count_step_up_ = rtc::Optional<int>(current_pixel_count); 826 max_pixel_count_step_up_ = rtc::Optional<int>(current_pixel_count);
692 --cpu_restricted_counter_; 827 --cpu_restricted_counter_;
693 stats_proxy_->OnCpuRestrictedResolutionChanged(cpu_restricted_counter_ > 0); 828 stats_proxy_->OnCpuRestrictedResolutionChanged(cpu_restricted_counter_ > 0);
694 source_proxy_->RequestHigherResolutionThan(current_pixel_count); 829 source_proxy_->RequestHigherResolutionThan(current_pixel_count);
695 } 830 }
696 } 831 }
697 832
698 } // namespace webrtc 833 } // 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