You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

664 lines
24 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
  3. *
  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
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include "media/engine/simulcast_encoder_adapter.h"
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <algorithm>
  14. #include <cstdint>
  15. #include <string>
  16. #include <utility>
  17. #include "api/scoped_refptr.h"
  18. #include "api/video/i420_buffer.h"
  19. #include "api/video/video_codec_constants.h"
  20. #include "api/video/video_frame_buffer.h"
  21. #include "api/video/video_rotation.h"
  22. #include "api/video_codecs/video_encoder.h"
  23. #include "api/video_codecs/video_encoder_factory.h"
  24. #include "api/video_codecs/video_encoder_software_fallback_wrapper.h"
  25. #include "modules/video_coding/include/video_error_codes.h"
  26. #include "modules/video_coding/utility/simulcast_rate_allocator.h"
  27. #include "rtc_base/atomic_ops.h"
  28. #include "rtc_base/checks.h"
  29. #include "rtc_base/experiments/rate_control_settings.h"
  30. #include "rtc_base/logging.h"
  31. #include "system_wrappers/include/field_trial.h"
  32. #include "third_party/libyuv/include/libyuv/scale.h"
  33. namespace {
  34. const unsigned int kDefaultMinQp = 2;
  35. const unsigned int kDefaultMaxQp = 56;
  36. // Max qp for lowest spatial resolution when doing simulcast.
  37. const unsigned int kLowestResMaxQp = 45;
  38. absl::optional<unsigned int> GetScreenshareBoostedQpValue() {
  39. std::string experiment_group =
  40. webrtc::field_trial::FindFullName("WebRTC-BoostedScreenshareQp");
  41. unsigned int qp;
  42. if (sscanf(experiment_group.c_str(), "%u", &qp) != 1)
  43. return absl::nullopt;
  44. qp = std::min(qp, 63u);
  45. qp = std::max(qp, 1u);
  46. return qp;
  47. }
  48. uint32_t SumStreamMaxBitrate(int streams, const webrtc::VideoCodec& codec) {
  49. uint32_t bitrate_sum = 0;
  50. for (int i = 0; i < streams; ++i) {
  51. bitrate_sum += codec.simulcastStream[i].maxBitrate;
  52. }
  53. return bitrate_sum;
  54. }
  55. int NumberOfStreams(const webrtc::VideoCodec& codec) {
  56. int streams =
  57. codec.numberOfSimulcastStreams < 1 ? 1 : codec.numberOfSimulcastStreams;
  58. uint32_t simulcast_max_bitrate = SumStreamMaxBitrate(streams, codec);
  59. if (simulcast_max_bitrate == 0) {
  60. streams = 1;
  61. }
  62. return streams;
  63. }
  64. int NumActiveStreams(const webrtc::VideoCodec& codec) {
  65. int num_configured_streams = NumberOfStreams(codec);
  66. int num_active_streams = 0;
  67. for (int i = 0; i < num_configured_streams; ++i) {
  68. if (codec.simulcastStream[i].active) {
  69. ++num_active_streams;
  70. }
  71. }
  72. return num_active_streams;
  73. }
  74. int VerifyCodec(const webrtc::VideoCodec* inst) {
  75. if (inst == nullptr) {
  76. return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
  77. }
  78. if (inst->maxFramerate < 1) {
  79. return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
  80. }
  81. // allow zero to represent an unspecified maxBitRate
  82. if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
  83. return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
  84. }
  85. if (inst->width <= 1 || inst->height <= 1) {
  86. return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
  87. }
  88. if (inst->codecType == webrtc::kVideoCodecVP8 &&
  89. inst->VP8().automaticResizeOn && inst->numberOfSimulcastStreams > 1) {
  90. return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
  91. }
  92. return WEBRTC_VIDEO_CODEC_OK;
  93. }
  94. bool StreamResolutionCompare(const webrtc::SimulcastStream& a,
  95. const webrtc::SimulcastStream& b) {
  96. return std::tie(a.height, a.width, a.maxBitrate, a.maxFramerate) <
  97. std::tie(b.height, b.width, b.maxBitrate, b.maxFramerate);
  98. }
  99. // An EncodedImageCallback implementation that forwards on calls to a
  100. // SimulcastEncoderAdapter, but with the stream index it's registered with as
  101. // the first parameter to Encoded.
  102. class AdapterEncodedImageCallback : public webrtc::EncodedImageCallback {
  103. public:
  104. AdapterEncodedImageCallback(webrtc::SimulcastEncoderAdapter* adapter,
  105. size_t stream_idx)
  106. : adapter_(adapter), stream_idx_(stream_idx) {}
  107. EncodedImageCallback::Result OnEncodedImage(
  108. const webrtc::EncodedImage& encoded_image,
  109. const webrtc::CodecSpecificInfo* codec_specific_info,
  110. const webrtc::RTPFragmentationHeader* fragmentation) override {
  111. return adapter_->OnEncodedImage(stream_idx_, encoded_image,
  112. codec_specific_info, fragmentation);
  113. }
  114. private:
  115. webrtc::SimulcastEncoderAdapter* const adapter_;
  116. const size_t stream_idx_;
  117. };
  118. } // namespace
  119. namespace webrtc {
  120. SimulcastEncoderAdapter::SimulcastEncoderAdapter(VideoEncoderFactory* factory,
  121. const SdpVideoFormat& format)
  122. : SimulcastEncoderAdapter(factory, nullptr, format) {}
  123. SimulcastEncoderAdapter::SimulcastEncoderAdapter(
  124. VideoEncoderFactory* primary_factory,
  125. VideoEncoderFactory* fallback_factory,
  126. const SdpVideoFormat& format)
  127. : inited_(0),
  128. primary_encoder_factory_(primary_factory),
  129. fallback_encoder_factory_(fallback_factory),
  130. video_format_(format),
  131. encoded_complete_callback_(nullptr),
  132. experimental_boosted_screenshare_qp_(GetScreenshareBoostedQpValue()),
  133. boost_base_layer_quality_(RateControlSettings::ParseFromFieldTrials()
  134. .Vp8BoostBaseLayerQuality()) {
  135. RTC_DCHECK(primary_factory);
  136. encoder_info_.implementation_name = "SimulcastEncoderAdapter";
  137. // The adapter is typically created on the worker thread, but operated on
  138. // the encoder task queue.
  139. encoder_queue_.Detach();
  140. memset(&codec_, 0, sizeof(webrtc::VideoCodec));
  141. }
  142. SimulcastEncoderAdapter::~SimulcastEncoderAdapter() {
  143. RTC_DCHECK(!Initialized());
  144. DestroyStoredEncoders();
  145. }
  146. void SimulcastEncoderAdapter::SetFecControllerOverride(
  147. FecControllerOverride* fec_controller_override) {
  148. // Ignored.
  149. }
  150. int SimulcastEncoderAdapter::Release() {
  151. RTC_DCHECK_RUN_ON(&encoder_queue_);
  152. while (!streaminfos_.empty()) {
  153. std::unique_ptr<VideoEncoder> encoder =
  154. std::move(streaminfos_.back().encoder);
  155. // Even though it seems very unlikely, there are no guarantees that the
  156. // encoder will not call back after being Release()'d. Therefore, we first
  157. // disable the callbacks here.
  158. encoder->RegisterEncodeCompleteCallback(nullptr);
  159. encoder->Release();
  160. streaminfos_.pop_back(); // Deletes callback adapter.
  161. stored_encoders_.push(std::move(encoder));
  162. }
  163. // It's legal to move the encoder to another queue now.
  164. encoder_queue_.Detach();
  165. rtc::AtomicOps::ReleaseStore(&inited_, 0);
  166. return WEBRTC_VIDEO_CODEC_OK;
  167. }
  168. // TODO(eladalon): s/inst/codec_settings/g.
  169. int SimulcastEncoderAdapter::InitEncode(
  170. const VideoCodec* inst,
  171. const VideoEncoder::Settings& settings) {
  172. RTC_DCHECK_RUN_ON(&encoder_queue_);
  173. if (settings.number_of_cores < 1) {
  174. return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
  175. }
  176. int ret = VerifyCodec(inst);
  177. if (ret < 0) {
  178. return ret;
  179. }
  180. ret = Release();
  181. if (ret < 0) {
  182. return ret;
  183. }
  184. int number_of_streams = NumberOfStreams(*inst);
  185. RTC_DCHECK_LE(number_of_streams, kMaxSimulcastStreams);
  186. bool doing_simulcast_using_adapter = (number_of_streams > 1);
  187. int num_active_streams = NumActiveStreams(*inst);
  188. codec_ = *inst;
  189. SimulcastRateAllocator rate_allocator(codec_);
  190. VideoBitrateAllocation allocation =
  191. rate_allocator.Allocate(VideoBitrateAllocationParameters(
  192. codec_.startBitrate * 1000, codec_.maxFramerate));
  193. std::vector<uint32_t> start_bitrates;
  194. for (int i = 0; i < kMaxSimulcastStreams; ++i) {
  195. uint32_t stream_bitrate = allocation.GetSpatialLayerSum(i) / 1000;
  196. start_bitrates.push_back(stream_bitrate);
  197. }
  198. encoder_info_.supports_native_handle = true;
  199. encoder_info_.scaling_settings.thresholds = absl::nullopt;
  200. // Create |number_of_streams| of encoder instances and init them.
  201. const auto minmax = std::minmax_element(
  202. std::begin(codec_.simulcastStream),
  203. std::begin(codec_.simulcastStream) + number_of_streams,
  204. StreamResolutionCompare);
  205. const auto lowest_resolution_stream_index =
  206. std::distance(std::begin(codec_.simulcastStream), minmax.first);
  207. const auto highest_resolution_stream_index =
  208. std::distance(std::begin(codec_.simulcastStream), minmax.second);
  209. RTC_DCHECK_LT(lowest_resolution_stream_index, number_of_streams);
  210. RTC_DCHECK_LT(highest_resolution_stream_index, number_of_streams);
  211. const SdpVideoFormat format(
  212. codec_.codecType == webrtc::kVideoCodecVP8 ? "VP8" : "H264");
  213. for (int i = 0; i < number_of_streams; ++i) {
  214. // If an existing encoder instance exists, reuse it.
  215. // TODO(brandtr): Set initial RTP state (e.g., picture_id/tl0_pic_idx) here,
  216. // when we start storing that state outside the encoder wrappers.
  217. std::unique_ptr<VideoEncoder> encoder;
  218. if (!stored_encoders_.empty()) {
  219. encoder = std::move(stored_encoders_.top());
  220. stored_encoders_.pop();
  221. } else {
  222. encoder = primary_encoder_factory_->CreateVideoEncoder(format);
  223. if (fallback_encoder_factory_ != nullptr) {
  224. encoder = CreateVideoEncoderSoftwareFallbackWrapper(
  225. fallback_encoder_factory_->CreateVideoEncoder(format),
  226. std::move(encoder));
  227. }
  228. }
  229. bool encoder_initialized = false;
  230. if (doing_simulcast_using_adapter && i == 0 &&
  231. encoder->GetEncoderInfo().supports_simulcast) {
  232. ret = encoder->InitEncode(&codec_, settings);
  233. if (ret < 0) {
  234. encoder->Release();
  235. } else {
  236. doing_simulcast_using_adapter = false;
  237. number_of_streams = 1;
  238. encoder_initialized = true;
  239. }
  240. }
  241. VideoCodec stream_codec;
  242. uint32_t start_bitrate_kbps = start_bitrates[i];
  243. const bool send_stream = doing_simulcast_using_adapter
  244. ? start_bitrate_kbps > 0
  245. : num_active_streams > 0;
  246. if (!doing_simulcast_using_adapter) {
  247. stream_codec = codec_;
  248. stream_codec.numberOfSimulcastStreams =
  249. std::max<uint8_t>(1, stream_codec.numberOfSimulcastStreams);
  250. } else {
  251. // Cap start bitrate to the min bitrate in order to avoid strange codec
  252. // behavior. Since sending will be false, this should not matter.
  253. StreamResolution stream_resolution =
  254. i == highest_resolution_stream_index
  255. ? StreamResolution::HIGHEST
  256. : i == lowest_resolution_stream_index ? StreamResolution::LOWEST
  257. : StreamResolution::OTHER;
  258. start_bitrate_kbps =
  259. std::max(codec_.simulcastStream[i].minBitrate, start_bitrate_kbps);
  260. PopulateStreamCodec(codec_, i, start_bitrate_kbps, stream_resolution,
  261. &stream_codec);
  262. }
  263. // TODO(ronghuawu): Remove once this is handled in LibvpxVp8Encoder.
  264. if (stream_codec.qpMax < kDefaultMinQp) {
  265. stream_codec.qpMax = kDefaultMaxQp;
  266. }
  267. if (!encoder_initialized) {
  268. ret = encoder->InitEncode(&stream_codec, settings);
  269. if (ret < 0) {
  270. // Explicitly destroy the current encoder; because we haven't registered
  271. // a StreamInfo for it yet, Release won't do anything about it.
  272. encoder.reset();
  273. Release();
  274. return ret;
  275. }
  276. }
  277. if (!doing_simulcast_using_adapter) {
  278. // Without simulcast, just pass through the encoder info from the one
  279. // active encoder.
  280. encoder_info_ = encoder->GetEncoderInfo();
  281. encoder->RegisterEncodeCompleteCallback(encoded_complete_callback_);
  282. streaminfos_.emplace_back(std::move(encoder), nullptr, stream_codec.width,
  283. stream_codec.height, send_stream);
  284. } else {
  285. std::unique_ptr<EncodedImageCallback> callback(
  286. new AdapterEncodedImageCallback(this, i));
  287. encoder->RegisterEncodeCompleteCallback(callback.get());
  288. streaminfos_.emplace_back(std::move(encoder), std::move(callback),
  289. stream_codec.width, stream_codec.height,
  290. send_stream);
  291. const EncoderInfo encoder_impl_info =
  292. streaminfos_[i].encoder->GetEncoderInfo();
  293. if (i == 0) {
  294. // Quality scaling not enabled for simulcast.
  295. encoder_info_.scaling_settings = VideoEncoder::ScalingSettings::kOff;
  296. // Encoder name indicates names of all sub-encoders.
  297. encoder_info_.implementation_name = "SimulcastEncoderAdapter (";
  298. encoder_info_.implementation_name +=
  299. encoder_impl_info.implementation_name;
  300. encoder_info_.supports_native_handle =
  301. encoder_impl_info.supports_native_handle;
  302. encoder_info_.has_trusted_rate_controller =
  303. encoder_impl_info.has_trusted_rate_controller;
  304. encoder_info_.is_hardware_accelerated =
  305. encoder_impl_info.is_hardware_accelerated;
  306. encoder_info_.has_internal_source =
  307. encoder_impl_info.has_internal_source;
  308. } else {
  309. encoder_info_.implementation_name += ", ";
  310. encoder_info_.implementation_name +=
  311. encoder_impl_info.implementation_name;
  312. // Native handle supported only if all encoders supports it.
  313. encoder_info_.supports_native_handle &=
  314. encoder_impl_info.supports_native_handle;
  315. // Trusted rate controller only if all encoders have it.
  316. encoder_info_.has_trusted_rate_controller &=
  317. encoder_impl_info.has_trusted_rate_controller;
  318. // Uses hardware support if any of the encoders uses it.
  319. // For example, if we are having issues with down-scaling due to
  320. // pipelining delay in HW encoders we need higher encoder usage
  321. // thresholds in CPU adaptation.
  322. encoder_info_.is_hardware_accelerated |=
  323. encoder_impl_info.is_hardware_accelerated;
  324. // Has internal source only if all encoders have it.
  325. encoder_info_.has_internal_source &=
  326. encoder_impl_info.has_internal_source;
  327. }
  328. encoder_info_.fps_allocation[i] = encoder_impl_info.fps_allocation[0];
  329. }
  330. }
  331. if (doing_simulcast_using_adapter) {
  332. encoder_info_.implementation_name += ")";
  333. }
  334. // To save memory, don't store encoders that we don't use.
  335. DestroyStoredEncoders();
  336. rtc::AtomicOps::ReleaseStore(&inited_, 1);
  337. return WEBRTC_VIDEO_CODEC_OK;
  338. }
  339. int SimulcastEncoderAdapter::Encode(
  340. const VideoFrame& input_image,
  341. const std::vector<VideoFrameType>* frame_types) {
  342. RTC_DCHECK_RUN_ON(&encoder_queue_);
  343. if (!Initialized()) {
  344. return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
  345. }
  346. if (encoded_complete_callback_ == nullptr) {
  347. return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
  348. }
  349. // All active streams should generate a key frame if
  350. // a key frame is requested by any stream.
  351. bool send_key_frame = false;
  352. if (frame_types) {
  353. for (size_t i = 0; i < frame_types->size(); ++i) {
  354. if (frame_types->at(i) == VideoFrameType::kVideoFrameKey) {
  355. send_key_frame = true;
  356. break;
  357. }
  358. }
  359. }
  360. for (size_t stream_idx = 0; stream_idx < streaminfos_.size(); ++stream_idx) {
  361. if (streaminfos_[stream_idx].key_frame_request &&
  362. streaminfos_[stream_idx].send_stream) {
  363. send_key_frame = true;
  364. break;
  365. }
  366. }
  367. int src_width = input_image.width();
  368. int src_height = input_image.height();
  369. for (size_t stream_idx = 0; stream_idx < streaminfos_.size(); ++stream_idx) {
  370. // Don't encode frames in resolutions that we don't intend to send.
  371. if (!streaminfos_[stream_idx].send_stream) {
  372. continue;
  373. }
  374. std::vector<VideoFrameType> stream_frame_types;
  375. if (send_key_frame) {
  376. stream_frame_types.push_back(VideoFrameType::kVideoFrameKey);
  377. streaminfos_[stream_idx].key_frame_request = false;
  378. } else {
  379. stream_frame_types.push_back(VideoFrameType::kVideoFrameDelta);
  380. }
  381. int dst_width = streaminfos_[stream_idx].width;
  382. int dst_height = streaminfos_[stream_idx].height;
  383. // If scaling isn't required, because the input resolution
  384. // matches the destination or the input image is empty (e.g.
  385. // a keyframe request for encoders with internal camera
  386. // sources) or the source image has a native handle, pass the image on
  387. // directly. Otherwise, we'll scale it to match what the encoder expects
  388. // (below).
  389. // For texture frames, the underlying encoder is expected to be able to
  390. // correctly sample/scale the source texture.
  391. // TODO(perkj): ensure that works going forward, and figure out how this
  392. // affects webrtc:5683.
  393. if ((dst_width == src_width && dst_height == src_height) ||
  394. input_image.video_frame_buffer()->type() ==
  395. VideoFrameBuffer::Type::kNative) {
  396. int ret = streaminfos_[stream_idx].encoder->Encode(input_image,
  397. &stream_frame_types);
  398. if (ret != WEBRTC_VIDEO_CODEC_OK) {
  399. return ret;
  400. }
  401. } else {
  402. rtc::scoped_refptr<I420Buffer> dst_buffer =
  403. I420Buffer::Create(dst_width, dst_height);
  404. rtc::scoped_refptr<I420BufferInterface> src_buffer =
  405. input_image.video_frame_buffer()->ToI420();
  406. libyuv::I420Scale(src_buffer->DataY(), src_buffer->StrideY(),
  407. src_buffer->DataU(), src_buffer->StrideU(),
  408. src_buffer->DataV(), src_buffer->StrideV(), src_width,
  409. src_height, dst_buffer->MutableDataY(),
  410. dst_buffer->StrideY(), dst_buffer->MutableDataU(),
  411. dst_buffer->StrideU(), dst_buffer->MutableDataV(),
  412. dst_buffer->StrideV(), dst_width, dst_height,
  413. libyuv::kFilterBilinear);
  414. // UpdateRect is not propagated to lower simulcast layers currently.
  415. // TODO(ilnik): Consider scaling UpdateRect together with the buffer.
  416. VideoFrame frame(input_image);
  417. frame.set_video_frame_buffer(dst_buffer);
  418. frame.set_rotation(webrtc::kVideoRotation_0);
  419. frame.set_update_rect(
  420. VideoFrame::UpdateRect{0, 0, frame.width(), frame.height()});
  421. int ret =
  422. streaminfos_[stream_idx].encoder->Encode(frame, &stream_frame_types);
  423. if (ret != WEBRTC_VIDEO_CODEC_OK) {
  424. return ret;
  425. }
  426. }
  427. }
  428. return WEBRTC_VIDEO_CODEC_OK;
  429. }
  430. int SimulcastEncoderAdapter::RegisterEncodeCompleteCallback(
  431. EncodedImageCallback* callback) {
  432. RTC_DCHECK_RUN_ON(&encoder_queue_);
  433. encoded_complete_callback_ = callback;
  434. if (streaminfos_.size() == 1) {
  435. streaminfos_[0].encoder->RegisterEncodeCompleteCallback(callback);
  436. }
  437. return WEBRTC_VIDEO_CODEC_OK;
  438. }
  439. void SimulcastEncoderAdapter::SetRates(
  440. const RateControlParameters& parameters) {
  441. RTC_DCHECK_RUN_ON(&encoder_queue_);
  442. if (!Initialized()) {
  443. RTC_LOG(LS_WARNING) << "SetRates while not initialized";
  444. return;
  445. }
  446. if (parameters.framerate_fps < 1.0) {
  447. RTC_LOG(LS_WARNING) << "Invalid framerate: " << parameters.framerate_fps;
  448. return;
  449. }
  450. codec_.maxFramerate = static_cast<uint32_t>(parameters.framerate_fps + 0.5);
  451. if (streaminfos_.size() == 1) {
  452. // Not doing simulcast.
  453. streaminfos_[0].encoder->SetRates(parameters);
  454. return;
  455. }
  456. for (size_t stream_idx = 0; stream_idx < streaminfos_.size(); ++stream_idx) {
  457. uint32_t stream_bitrate_kbps =
  458. parameters.bitrate.GetSpatialLayerSum(stream_idx) / 1000;
  459. // Need a key frame if we have not sent this stream before.
  460. if (stream_bitrate_kbps > 0 && !streaminfos_[stream_idx].send_stream) {
  461. streaminfos_[stream_idx].key_frame_request = true;
  462. }
  463. streaminfos_[stream_idx].send_stream = stream_bitrate_kbps > 0;
  464. // Slice the temporal layers out of the full allocation and pass it on to
  465. // the encoder handling the current simulcast stream.
  466. RateControlParameters stream_parameters = parameters;
  467. stream_parameters.bitrate = VideoBitrateAllocation();
  468. for (int i = 0; i < kMaxTemporalStreams; ++i) {
  469. if (parameters.bitrate.HasBitrate(stream_idx, i)) {
  470. stream_parameters.bitrate.SetBitrate(
  471. 0, i, parameters.bitrate.GetBitrate(stream_idx, i));
  472. }
  473. }
  474. // Assign link allocation proportionally to spatial layer allocation.
  475. if (parameters.bandwidth_allocation != DataRate::Zero()) {
  476. stream_parameters.bandwidth_allocation =
  477. DataRate::bps((parameters.bandwidth_allocation.bps() *
  478. stream_parameters.bitrate.get_sum_bps()) /
  479. parameters.bitrate.get_sum_bps());
  480. // Make sure we don't allocate bandwidth lower than target bitrate.
  481. if (stream_parameters.bandwidth_allocation.bps() <
  482. stream_parameters.bitrate.get_sum_bps()) {
  483. stream_parameters.bandwidth_allocation =
  484. DataRate::bps(stream_parameters.bitrate.get_sum_bps());
  485. }
  486. }
  487. streaminfos_[stream_idx].encoder->SetRates(stream_parameters);
  488. }
  489. }
  490. void SimulcastEncoderAdapter::OnPacketLossRateUpdate(float packet_loss_rate) {
  491. for (StreamInfo& info : streaminfos_) {
  492. info.encoder->OnPacketLossRateUpdate(packet_loss_rate);
  493. }
  494. }
  495. void SimulcastEncoderAdapter::OnRttUpdate(int64_t rtt_ms) {
  496. for (StreamInfo& info : streaminfos_) {
  497. info.encoder->OnRttUpdate(rtt_ms);
  498. }
  499. }
  500. void SimulcastEncoderAdapter::OnLossNotification(
  501. const LossNotification& loss_notification) {
  502. for (StreamInfo& info : streaminfos_) {
  503. info.encoder->OnLossNotification(loss_notification);
  504. }
  505. }
  506. // TODO(brandtr): Add task checker to this member function, when all encoder
  507. // callbacks are coming in on the encoder queue.
  508. EncodedImageCallback::Result SimulcastEncoderAdapter::OnEncodedImage(
  509. size_t stream_idx,
  510. const EncodedImage& encodedImage,
  511. const CodecSpecificInfo* codecSpecificInfo,
  512. const RTPFragmentationHeader* fragmentation) {
  513. EncodedImage stream_image(encodedImage);
  514. CodecSpecificInfo stream_codec_specific = *codecSpecificInfo;
  515. stream_image.SetSpatialIndex(stream_idx);
  516. return encoded_complete_callback_->OnEncodedImage(
  517. stream_image, &stream_codec_specific, fragmentation);
  518. }
  519. void SimulcastEncoderAdapter::PopulateStreamCodec(
  520. const webrtc::VideoCodec& inst,
  521. int stream_index,
  522. uint32_t start_bitrate_kbps,
  523. StreamResolution stream_resolution,
  524. webrtc::VideoCodec* stream_codec) {
  525. *stream_codec = inst;
  526. // Stream specific settings.
  527. stream_codec->numberOfSimulcastStreams = 0;
  528. stream_codec->width = inst.simulcastStream[stream_index].width;
  529. stream_codec->height = inst.simulcastStream[stream_index].height;
  530. stream_codec->maxBitrate = inst.simulcastStream[stream_index].maxBitrate;
  531. stream_codec->minBitrate = inst.simulcastStream[stream_index].minBitrate;
  532. stream_codec->qpMax = inst.simulcastStream[stream_index].qpMax;
  533. // Settings that are based on stream/resolution.
  534. if (stream_resolution == StreamResolution::LOWEST) {
  535. // Settings for lowest spatial resolutions.
  536. if (inst.mode == VideoCodecMode::kScreensharing) {
  537. if (experimental_boosted_screenshare_qp_) {
  538. stream_codec->qpMax = *experimental_boosted_screenshare_qp_;
  539. }
  540. } else if (boost_base_layer_quality_) {
  541. stream_codec->qpMax = kLowestResMaxQp;
  542. }
  543. }
  544. if (inst.codecType == webrtc::kVideoCodecVP8) {
  545. stream_codec->VP8()->numberOfTemporalLayers =
  546. inst.simulcastStream[stream_index].numberOfTemporalLayers;
  547. if (stream_resolution != StreamResolution::HIGHEST) {
  548. // For resolutions below CIF, set the codec |complexity| parameter to
  549. // kComplexityHigher, which maps to cpu_used = -4.
  550. int pixels_per_frame = stream_codec->width * stream_codec->height;
  551. if (pixels_per_frame < 352 * 288) {
  552. stream_codec->VP8()->complexity =
  553. webrtc::VideoCodecComplexity::kComplexityHigher;
  554. }
  555. // Turn off denoising for all streams but the highest resolution.
  556. stream_codec->VP8()->denoisingOn = false;
  557. }
  558. } else if (inst.codecType == webrtc::kVideoCodecH264) {
  559. stream_codec->H264()->numberOfTemporalLayers =
  560. inst.simulcastStream[stream_index].numberOfTemporalLayers;
  561. }
  562. // TODO(ronghuawu): what to do with targetBitrate.
  563. stream_codec->startBitrate = start_bitrate_kbps;
  564. }
  565. bool SimulcastEncoderAdapter::Initialized() const {
  566. return rtc::AtomicOps::AcquireLoad(&inited_) == 1;
  567. }
  568. void SimulcastEncoderAdapter::DestroyStoredEncoders() {
  569. while (!stored_encoders_.empty()) {
  570. stored_encoders_.pop();
  571. }
  572. }
  573. VideoEncoder::EncoderInfo SimulcastEncoderAdapter::GetEncoderInfo() const {
  574. return encoder_info_;
  575. }
  576. } // namespace webrtc