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

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

Issue 2434073003: Extract bitrate allocation of spatial/temporal layers out of codec impl. (Closed)
Patch Set: Addressed comments. Moved VideoCodec creation to factory class. 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
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 111 matching lines...) Expand 10 before | Expand all | Expand 10 after
297 SendStatisticsProxy* stats_proxy, 157 SendStatisticsProxy* stats_proxy,
298 const VideoSendStream::Config::EncoderSettings& settings, 158 const VideoSendStream::Config::EncoderSettings& settings,
299 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback, 159 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback,
300 LoadObserver* overuse_callback, 160 LoadObserver* overuse_callback,
301 EncodedFrameObserver* encoder_timing) 161 EncodedFrameObserver* encoder_timing)
302 : shutdown_event_(true /* manual_reset */, false), 162 : shutdown_event_(true /* manual_reset */, false),
303 number_of_cores_(number_of_cores), 163 number_of_cores_(number_of_cores),
304 source_proxy_(new VideoSourceProxy(this)), 164 source_proxy_(new VideoSourceProxy(this)),
305 sink_(nullptr), 165 sink_(nullptr),
306 settings_(settings), 166 settings_(settings),
307 codec_type_(PayloadNameToCodecType(settings.payload_name)), 167 codec_type_(PayloadNameToCodecType(settings.payload_name)
168 .value_or(VideoCodecType::kVideoCodecUnknown)),
stefan-webrtc 2016/11/02 10:26:36 I guess unknown should generate a warning?
sprang_webrtc 2016/11/02 13:28:34 It's probably the fake encoder. Do we always want
308 video_sender_(Clock::GetRealTimeClock(), this, this), 169 video_sender_(Clock::GetRealTimeClock(), this, this),
309 overuse_detector_(Clock::GetRealTimeClock(), 170 overuse_detector_(Clock::GetRealTimeClock(),
310 GetCpuOveruseOptions(settings.full_overuse_time), 171 GetCpuOveruseOptions(settings.full_overuse_time),
311 this, 172 this,
312 encoder_timing, 173 encoder_timing,
313 stats_proxy), 174 stats_proxy),
314 load_observer_(overuse_callback), 175 load_observer_(overuse_callback),
315 stats_proxy_(stats_proxy), 176 stats_proxy_(stats_proxy),
316 pre_encode_callback_(pre_encode_callback), 177 pre_encode_callback_(pre_encode_callback),
317 module_process_thread_(nullptr), 178 module_process_thread_(nullptr),
(...skipping 26 matching lines...) Expand all
344 RTC_DCHECK_RUN_ON(&thread_checker_); 205 RTC_DCHECK_RUN_ON(&thread_checker_);
345 RTC_DCHECK(shutdown_event_.Wait(0)) 206 RTC_DCHECK(shutdown_event_.Wait(0))
346 << "Must call ::Stop() before destruction."; 207 << "Must call ::Stop() before destruction.";
347 } 208 }
348 209
349 void ViEEncoder::Stop() { 210 void ViEEncoder::Stop() {
350 RTC_DCHECK_RUN_ON(&thread_checker_); 211 RTC_DCHECK_RUN_ON(&thread_checker_);
351 source_proxy_->SetSource(nullptr); 212 source_proxy_->SetSource(nullptr);
352 encoder_queue_.PostTask([this] { 213 encoder_queue_.PostTask([this] {
353 RTC_DCHECK_RUN_ON(&encoder_queue_); 214 RTC_DCHECK_RUN_ON(&encoder_queue_);
215 rate_allocator_.reset();
354 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type, 216 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type,
355 false); 217 false);
356 overuse_detector_.StopCheckForOveruse(); 218 overuse_detector_.StopCheckForOveruse();
357 shutdown_event_.Set(); 219 shutdown_event_.Set();
358 }); 220 });
359 221
360 shutdown_event_.Wait(rtc::Event::kForever); 222 shutdown_event_.Wait(rtc::Event::kForever);
361 } 223 }
362 224
363 void ViEEncoder::RegisterProcessThread(ProcessThread* module_process_thread) { 225 void ViEEncoder::RegisterProcessThread(ProcessThread* module_process_thread) {
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after
422 } 284 }
423 } 285 }
424 286
425 void ViEEncoder::ReconfigureEncoder() { 287 void ViEEncoder::ReconfigureEncoder() {
426 RTC_DCHECK_RUN_ON(&encoder_queue_); 288 RTC_DCHECK_RUN_ON(&encoder_queue_);
427 RTC_DCHECK(pending_encoder_reconfiguration_); 289 RTC_DCHECK(pending_encoder_reconfiguration_);
428 std::vector<VideoStream> streams = 290 std::vector<VideoStream> streams =
429 encoder_config_.video_stream_factory->CreateEncoderStreams( 291 encoder_config_.video_stream_factory->CreateEncoderStreams(
430 last_frame_info_->width, last_frame_info_->height, encoder_config_); 292 last_frame_info_->width, last_frame_info_->height, encoder_config_);
431 293
432 VideoCodec codec = VideoEncoderConfigToVideoCodec( 294 VideoCodec codec;
433 encoder_config_, streams, settings_.payload_name, settings_.payload_type); 295 if (!VideoCodecInitializer::SetupCodec(encoder_config_, settings_, streams,
296 &codec, &rate_allocator_)) {
297 LOG(LS_ERROR) << "Failed to create encoder configuration.";
298 }
434 299
435 codec.startBitrate = 300 codec.startBitrate =
436 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate); 301 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
437 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate); 302 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
438 codec.expect_encode_from_texture = last_frame_info_->is_texture; 303 codec.expect_encode_from_texture = last_frame_info_->is_texture;
439 304
440 bool success = video_sender_.RegisterSendCodec( 305 bool success = video_sender_.RegisterSendCodec(
441 &codec, number_of_cores_, 306 &codec, number_of_cores_,
442 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK; 307 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
443 if (!success) { 308 if (!success) {
444 LOG(LS_ERROR) << "Failed to configure encoder."; 309 LOG(LS_ERROR) << "Failed to configure encoder.";
445 RTC_DCHECK(success); 310 RTC_DCHECK(success);
446 } 311 }
447 312
448 rate_allocator_.reset(new SimulcastRateAllocator(codec));
449 if (stats_proxy_) { 313 if (stats_proxy_) {
450 stats_proxy_->OnEncoderReconfigured(encoder_config_, 314 int frame_rate = stats_proxy_->GetSendFrameRate();
stefan-webrtc 2016/11/02 10:26:36 framerate
sprang_webrtc 2016/11/02 13:28:33 Done.
451 rate_allocator_->GetPreferedBitrate()); 315 if (frame_rate == 0)
316 frame_rate = codec.maxFramerate;
317 stats_proxy_->OnEncoderReconfigured(
318 encoder_config_, rate_allocator_->GetPreferedBitrate(frame_rate));
452 } 319 }
453 320
454 pending_encoder_reconfiguration_ = false; 321 pending_encoder_reconfiguration_ = false;
455 if (stats_proxy_) { 322
456 stats_proxy_->OnEncoderReconfigured(encoder_config_,
457 rate_allocator_->GetPreferedBitrate());
458 }
459 sink_->OnEncoderConfigurationChanged( 323 sink_->OnEncoderConfigurationChanged(
460 std::move(streams), encoder_config_.min_transmit_bitrate_bps); 324 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
461 } 325 }
462 326
463 void ViEEncoder::OnFrame(const VideoFrame& video_frame) { 327 void ViEEncoder::OnFrame(const VideoFrame& video_frame) {
464 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_); 328 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
465 if (stats_proxy_) { 329 if (stats_proxy_) {
466 stats_proxy_->OnIncomingFrame(video_frame.width(), video_frame.height()); 330 stats_proxy_->OnIncomingFrame(video_frame.width(), video_frame.height());
467 } 331 }
468 VideoFrame incoming_frame = video_frame; 332 VideoFrame incoming_frame = video_frame;
(...skipping 203 matching lines...) Expand 10 before | Expand all | Expand 10 after
672 return; 536 return;
673 } 537 }
674 RTC_DCHECK_RUN_ON(&encoder_queue_); 538 RTC_DCHECK_RUN_ON(&encoder_queue_);
675 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active."; 539 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
676 540
677 LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps 541 LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
678 << " packet loss " << static_cast<int>(fraction_lost) 542 << " packet loss " << static_cast<int>(fraction_lost)
679 << " rtt " << round_trip_time_ms; 543 << " rtt " << round_trip_time_ms;
680 544
681 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost, 545 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost,
682 round_trip_time_ms); 546 round_trip_time_ms, rate_allocator_.get());
683 547
684 encoder_start_bitrate_bps_ = 548 encoder_start_bitrate_bps_ =
685 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_; 549 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
686 bool video_is_suspended = bitrate_bps == 0; 550 bool video_is_suspended = bitrate_bps == 0;
687 bool video_suspension_changed = 551 bool video_suspension_changed =
688 video_is_suspended != (last_observed_bitrate_bps_ == 0); 552 video_is_suspended != (last_observed_bitrate_bps_ == 0);
689 last_observed_bitrate_bps_ = bitrate_bps; 553 last_observed_bitrate_bps_ = bitrate_bps;
690 554
691 if (stats_proxy_ && video_suspension_changed) { 555 if (stats_proxy_ && video_suspension_changed) {
692 LOG(LS_INFO) << "Video suspend state changed to: " 556 LOG(LS_INFO) << "Video suspend state changed to: "
(...skipping 11 matching lines...) Expand all
704 load_observer_->OnLoadUpdate(LoadObserver::kOveruse); 568 load_observer_->OnLoadUpdate(LoadObserver::kOveruse);
705 } 569 }
706 570
707 void ViEEncoder::NormalUsage() { 571 void ViEEncoder::NormalUsage() {
708 RTC_DCHECK_RUN_ON(&encoder_queue_); 572 RTC_DCHECK_RUN_ON(&encoder_queue_);
709 if (load_observer_) 573 if (load_observer_)
710 load_observer_->OnLoadUpdate(LoadObserver::kUnderuse); 574 load_observer_->OnLoadUpdate(LoadObserver::kUnderuse);
711 } 575 }
712 576
713 } // namespace webrtc 577 } // namespace webrtc
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698