video_encoder_vpx.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "remoting/codec/video_encoder_vpx.h"
  5. #include <utility>
  6. #include "base/bind.h"
  7. #include "base/logging.h"
  8. #include "base/memory/ptr_util.h"
  9. #include "base/system/sys_info.h"
  10. #include "remoting/base/util.h"
  11. #include "remoting/proto/video.pb.h"
  12. #include "third_party/libvpx/source/libvpx/vpx/vp8cx.h"
  13. #include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h"
  14. #include "third_party/libyuv/include/libyuv/convert_from_argb.h"
  15. #include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
  16. #include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h"
  17. #include "third_party/webrtc/modules/desktop_capture/desktop_region.h"
  18. namespace remoting {
  19. namespace {
  20. // Number of bytes in an RGBx pixel.
  21. const int kBytesPerRgbPixel = 4;
  22. // Defines the dimension of a macro block. This is used to compute the active
  23. // map for the encoder.
  24. const int kMacroBlockSize = 16;
  25. // Magic encoder profile numbers for I420 and I444 input formats.
  26. const int kVp9I420ProfileNumber = 0;
  27. const int kVp9I444ProfileNumber = 1;
  28. // Magic encoder constants for adaptive quantization strategy.
  29. const int kVp9AqModeNone = 0;
  30. const int kVp9AqModeCyclicRefresh = 3;
  31. void SetCommonCodecParameters(vpx_codec_enc_cfg_t* config,
  32. const webrtc::DesktopSize& size) {
  33. // Use millisecond granularity time base.
  34. config->g_timebase.num = 1;
  35. config->g_timebase.den = 1000;
  36. config->g_w = size.width();
  37. config->g_h = size.height();
  38. config->g_pass = VPX_RC_ONE_PASS;
  39. // Start emitting packets immediately.
  40. config->g_lag_in_frames = 0;
  41. // Since the transport layer is reliable, keyframes should not be necessary.
  42. // However, due to crbug.com/440223, decoding fails after 30,000 non-key
  43. // frames, so take the hit of an "unnecessary" key-frame every 10,000 frames.
  44. config->kf_min_dist = 10000;
  45. config->kf_max_dist = 10000;
  46. // Using 2 threads gives a great boost in performance for most systems with
  47. // adequate processing power. NB: Going to multiple threads on low end
  48. // windows systems can really hurt performance.
  49. // http://crbug.com/99179
  50. config->g_threads = (base::SysInfo::NumberOfProcessors() > 2) ? 2 : 1;
  51. }
  52. void SetVp8CodecParameters(vpx_codec_enc_cfg_t* config,
  53. const webrtc::DesktopSize& size) {
  54. // Adjust default target bit-rate to account for actual desktop size.
  55. config->rc_target_bitrate = size.width() * size.height() *
  56. config->rc_target_bitrate / config->g_w / config->g_h;
  57. SetCommonCodecParameters(config, size);
  58. // Value of 2 means using the real time profile. This is basically a
  59. // redundant option since we explicitly select real time mode when doing
  60. // encoding.
  61. config->g_profile = 2;
  62. // Clamping the quantizer constrains the worst-case quality and CPU usage.
  63. config->rc_min_quantizer = 20;
  64. config->rc_max_quantizer = 30;
  65. }
  66. void SetVp9CodecParameters(vpx_codec_enc_cfg_t* config,
  67. const webrtc::DesktopSize& size,
  68. bool lossless_color,
  69. bool lossless_encode) {
  70. SetCommonCodecParameters(config, size);
  71. // Configure VP9 for I420 or I444 source frames.
  72. config->g_profile =
  73. lossless_color ? kVp9I444ProfileNumber : kVp9I420ProfileNumber;
  74. if (lossless_encode) {
  75. // Disable quantization entirely, putting the encoder in "lossless" mode.
  76. config->rc_min_quantizer = 0;
  77. config->rc_max_quantizer = 0;
  78. config->rc_end_usage = VPX_VBR;
  79. } else {
  80. // TODO(wez): Set quantization range to 4-40, once the libvpx encoder is
  81. // updated not to output any bits if nothing needs topping-off.
  82. config->rc_min_quantizer = 20;
  83. config->rc_max_quantizer = 30;
  84. config->rc_end_usage = VPX_CBR;
  85. // In the absence of a good bandwidth estimator set the target bitrate to a
  86. // conservative default.
  87. config->rc_target_bitrate = 500;
  88. }
  89. }
  90. void SetVp8CodecOptions(vpx_codec_ctx_t* codec) {
  91. // CPUUSED of 16 will have the smallest CPU load. This turns off sub-pixel
  92. // motion search.
  93. vpx_codec_err_t ret = vpx_codec_control(codec, VP8E_SET_CPUUSED, 16);
  94. DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set CPUUSED";
  95. // Use the lowest level of noise sensitivity so as to spend less time
  96. // on motion estimation and inter-prediction mode.
  97. ret = vpx_codec_control(codec, VP8E_SET_NOISE_SENSITIVITY, 0);
  98. DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set noise sensitivity";
  99. }
  100. void SetVp9CodecOptions(vpx_codec_ctx_t* codec, bool lossless_encode) {
  101. // Request the lowest-CPU usage that VP9 supports, which depends on whether
  102. // we are encoding lossy or lossless.
  103. // Note that this is configured via the same parameter as for VP8.
  104. int cpu_used = lossless_encode ? 5 : 6;
  105. vpx_codec_err_t ret = vpx_codec_control(codec, VP8E_SET_CPUUSED, cpu_used);
  106. DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set CPUUSED";
  107. // Use the lowest level of noise sensitivity so as to spend less time
  108. // on motion estimation and inter-prediction mode.
  109. ret = vpx_codec_control(codec, VP9E_SET_NOISE_SENSITIVITY, 0);
  110. DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set noise sensitivity";
  111. // Configure the codec to tune it for screen media.
  112. ret = vpx_codec_control(
  113. codec, VP9E_SET_TUNE_CONTENT, VP9E_CONTENT_SCREEN);
  114. DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set screen content mode";
  115. // Set cyclic refresh (aka "top-off") only for lossy encoding.
  116. int aq_mode = lossless_encode ? kVp9AqModeNone : kVp9AqModeCyclicRefresh;
  117. ret = vpx_codec_control(codec, VP9E_SET_AQ_MODE, aq_mode);
  118. DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set aq mode";
  119. }
  120. void FreeImageIfMismatched(bool use_i444,
  121. const webrtc::DesktopSize& size,
  122. std::unique_ptr<vpx_image_t>* out_image,
  123. std::unique_ptr<uint8_t[]>* out_image_buffer) {
  124. if (*out_image) {
  125. const vpx_img_fmt_t desired_fmt =
  126. use_i444 ? VPX_IMG_FMT_I444 : VPX_IMG_FMT_I420;
  127. if (!size.equals(webrtc::DesktopSize((*out_image)->w, (*out_image)->h)) ||
  128. (*out_image)->fmt != desired_fmt) {
  129. out_image_buffer->reset();
  130. out_image->reset();
  131. }
  132. }
  133. }
  134. void CreateImage(bool use_i444,
  135. const webrtc::DesktopSize& size,
  136. std::unique_ptr<vpx_image_t>* out_image,
  137. std::unique_ptr<uint8_t[]>* out_image_buffer) {
  138. DCHECK(!size.is_empty());
  139. DCHECK(!*out_image_buffer);
  140. DCHECK(!*out_image);
  141. std::unique_ptr<vpx_image_t> image(new vpx_image_t());
  142. memset(image.get(), 0, sizeof(vpx_image_t));
  143. // libvpx seems to require both to be assigned.
  144. image->d_w = size.width();
  145. image->w = size.width();
  146. image->d_h = size.height();
  147. image->h = size.height();
  148. // libvpx should derive chroma shifts from|fmt| but currently has a bug:
  149. // https://code.google.com/p/webm/issues/detail?id=627
  150. if (use_i444) {
  151. image->fmt = VPX_IMG_FMT_I444;
  152. image->x_chroma_shift = 0;
  153. image->y_chroma_shift = 0;
  154. } else { // I420
  155. image->fmt = VPX_IMG_FMT_YV12;
  156. image->x_chroma_shift = 1;
  157. image->y_chroma_shift = 1;
  158. }
  159. // libyuv's fast-path requires 16-byte aligned pointers and strides, so pad
  160. // the Y, U and V planes' strides to multiples of 16 bytes.
  161. const int y_stride = ((image->w - 1) & ~15) + 16;
  162. const int uv_unaligned_stride = y_stride >> image->x_chroma_shift;
  163. const int uv_stride = ((uv_unaligned_stride - 1) & ~15) + 16;
  164. // libvpx accesses the source image in macro blocks, and will over-read
  165. // if the image is not padded out to the next macroblock: crbug.com/119633.
  166. // Pad the Y, U and V planes' height out to compensate.
  167. // Assuming macroblocks are 16x16, aligning the planes' strides above also
  168. // macroblock aligned them.
  169. static_assert(kMacroBlockSize == 16, "macroblock_size_not_16");
  170. const int y_rows = ((image->h - 1) & ~(kMacroBlockSize-1)) + kMacroBlockSize;
  171. const int uv_rows = y_rows >> image->y_chroma_shift;
  172. // Allocate a YUV buffer large enough for the aligned data & padding.
  173. const int buffer_size = y_stride * y_rows + 2*uv_stride * uv_rows;
  174. std::unique_ptr<uint8_t[]> image_buffer(new uint8_t[buffer_size]);
  175. // Reset image value to 128 so we just need to fill in the y plane.
  176. memset(image_buffer.get(), 128, buffer_size);
  177. // Fill in the information for |image_|.
  178. unsigned char* uchar_buffer =
  179. reinterpret_cast<unsigned char*>(image_buffer.get());
  180. image->planes[0] = uchar_buffer;
  181. image->planes[1] = image->planes[0] + y_stride * y_rows;
  182. image->planes[2] = image->planes[1] + uv_stride * uv_rows;
  183. image->stride[0] = y_stride;
  184. image->stride[1] = uv_stride;
  185. image->stride[2] = uv_stride;
  186. *out_image = std::move(image);
  187. *out_image_buffer = std::move(image_buffer);
  188. }
  189. } // namespace
  190. // static
  191. std::unique_ptr<VideoEncoderVpx> VideoEncoderVpx::CreateForVP8() {
  192. return base::WrapUnique(new VideoEncoderVpx(false));
  193. }
  194. // static
  195. std::unique_ptr<VideoEncoderVpx> VideoEncoderVpx::CreateForVP9() {
  196. return base::WrapUnique(new VideoEncoderVpx(true));
  197. }
  198. VideoEncoderVpx::~VideoEncoderVpx() = default;
  199. void VideoEncoderVpx::SetTickClockForTests(const base::TickClock* tick_clock) {
  200. clock_ = tick_clock;
  201. }
  202. void VideoEncoderVpx::SetLosslessEncode(bool want_lossless) {
  203. if (use_vp9_ && (want_lossless != lossless_encode_)) {
  204. lossless_encode_ = want_lossless;
  205. if (codec_)
  206. Configure(webrtc::DesktopSize(codec_->config.enc->g_w,
  207. codec_->config.enc->g_h));
  208. }
  209. }
  210. void VideoEncoderVpx::SetLosslessColor(bool want_lossless) {
  211. if (use_vp9_ && (want_lossless != lossless_color_)) {
  212. lossless_color_ = want_lossless;
  213. // TODO(wez): Switch to ConfigureCodec() path once libvpx supports it.
  214. // See https://code.google.com/p/webm/issues/detail?id=913.
  215. // if (codec_)
  216. // Configure(webrtc::DesktopSize(codec_->config.enc->g_w,
  217. // codec_->config.enc->g_h));
  218. codec_.reset();
  219. }
  220. }
  221. std::unique_ptr<VideoPacket> VideoEncoderVpx::Encode(
  222. const webrtc::DesktopFrame& frame) {
  223. DCHECK_LE(32, frame.size().width());
  224. DCHECK_LE(32, frame.size().height());
  225. // If there is nothing to encode, and nothing to top-off, then return nothing.
  226. if (frame.updated_region().is_empty() && !encode_unchanged_frame_)
  227. return nullptr;
  228. // Create or reconfigure the codec to match the size of |frame|.
  229. if (!codec_ ||
  230. (image_ &&
  231. !frame.size().equals(webrtc::DesktopSize(image_->w, image_->h)))) {
  232. Configure(frame.size());
  233. }
  234. // Convert the updated capture data ready for encode.
  235. webrtc::DesktopRegion updated_region;
  236. PrepareImage(frame, &updated_region);
  237. // Update active map based on updated region.
  238. SetActiveMapFromRegion(updated_region);
  239. // Apply active map to the encoder.
  240. vpx_active_map_t act_map;
  241. act_map.rows = active_map_size_.height();
  242. act_map.cols = active_map_size_.width();
  243. act_map.active_map = active_map_.get();
  244. if (vpx_codec_control(codec_.get(), VP8E_SET_ACTIVEMAP, &act_map)) {
  245. LOG(ERROR) << "Unable to apply active map";
  246. }
  247. // Do the actual encoding.
  248. int timestamp = (clock_->NowTicks() - timestamp_base_).InMilliseconds();
  249. vpx_codec_err_t ret = vpx_codec_encode(
  250. codec_.get(), image_.get(), timestamp, 1, 0, VPX_DL_REALTIME);
  251. DCHECK_EQ(ret, VPX_CODEC_OK)
  252. << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n"
  253. << "Details: " << vpx_codec_error(codec_.get()) << "\n"
  254. << vpx_codec_error_detail(codec_.get());
  255. if (use_vp9_ && !lossless_encode_) {
  256. ret = vpx_codec_control(codec_.get(), VP9E_GET_ACTIVEMAP, &act_map);
  257. DCHECK_EQ(ret, VPX_CODEC_OK)
  258. << "Failed to fetch active map: "
  259. << vpx_codec_err_to_string(ret) << "\n";
  260. UpdateRegionFromActiveMap(&updated_region);
  261. // If the encoder output no changes then there's nothing left to top-off.
  262. encode_unchanged_frame_ = !updated_region.is_empty();
  263. }
  264. // Read the encoded data.
  265. vpx_codec_iter_t iter = nullptr;
  266. bool got_data = false;
  267. // TODO(hclam): Make sure we get exactly one frame from the packet.
  268. // TODO(hclam): We should provide the output buffer to avoid one copy.
  269. std::unique_ptr<VideoPacket> packet(
  270. helper_.CreateVideoPacketWithUpdatedRegion(frame, updated_region));
  271. packet->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8);
  272. while (!got_data) {
  273. const vpx_codec_cx_pkt_t* vpx_packet =
  274. vpx_codec_get_cx_data(codec_.get(), &iter);
  275. if (!vpx_packet)
  276. continue;
  277. switch (vpx_packet->kind) {
  278. case VPX_CODEC_CX_FRAME_PKT:
  279. got_data = true;
  280. packet->set_data(vpx_packet->data.frame.buf, vpx_packet->data.frame.sz);
  281. break;
  282. default:
  283. break;
  284. }
  285. }
  286. return packet;
  287. }
  288. VideoEncoderVpx::VideoEncoderVpx(bool use_vp9)
  289. : use_vp9_(use_vp9),
  290. encode_unchanged_frame_(false),
  291. clock_(base::DefaultTickClock::GetInstance()) {}
  292. void VideoEncoderVpx::Configure(const webrtc::DesktopSize& size) {
  293. DCHECK(use_vp9_ || !lossless_color_);
  294. DCHECK(use_vp9_ || !lossless_encode_);
  295. // Tear down |image_| if it no longer matches the size and color settings.
  296. // PrepareImage() will then create a new buffer of the required dimensions if
  297. // |image_| is not allocated.
  298. FreeImageIfMismatched(lossless_color_, size, &image_, &image_buffer_);
  299. // Initialize active map.
  300. active_map_size_ = webrtc::DesktopSize(
  301. (size.width() + kMacroBlockSize - 1) / kMacroBlockSize,
  302. (size.height() + kMacroBlockSize - 1) / kMacroBlockSize);
  303. active_map_.reset(
  304. new uint8_t[active_map_size_.width() * active_map_size_.height()]);
  305. // TODO(wez): Remove this hack once VPX can handle frame size reconfiguration.
  306. // See https://code.google.com/p/webm/issues/detail?id=912.
  307. if (codec_) {
  308. // If the frame size has changed then force re-creation of the codec.
  309. if (codec_->config.enc->g_w != static_cast<unsigned int>(size.width()) ||
  310. codec_->config.enc->g_h != static_cast<unsigned int>(size.height())) {
  311. codec_.reset();
  312. }
  313. }
  314. // (Re)Set the base for frame timestamps if the codec is being (re)created.
  315. if (!codec_) {
  316. timestamp_base_ = clock_->NowTicks();
  317. }
  318. // Fetch a default configuration for the desired codec.
  319. const vpx_codec_iface_t* interface =
  320. use_vp9_ ? vpx_codec_vp9_cx() : vpx_codec_vp8_cx();
  321. vpx_codec_enc_cfg_t config;
  322. vpx_codec_err_t ret = vpx_codec_enc_config_default(interface, &config, 0);
  323. DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to fetch default configuration";
  324. // Customize the default configuration to our needs.
  325. if (use_vp9_) {
  326. SetVp9CodecParameters(&config, size, lossless_color_, lossless_encode_);
  327. } else {
  328. SetVp8CodecParameters(&config, size);
  329. }
  330. // Initialize or re-configure the codec with the custom configuration.
  331. if (!codec_) {
  332. codec_.reset(new vpx_codec_ctx_t);
  333. ret = vpx_codec_enc_init(codec_.get(), interface, &config, 0);
  334. CHECK_EQ(VPX_CODEC_OK, ret) << "Failed to initialize codec";
  335. } else {
  336. ret = vpx_codec_enc_config_set(codec_.get(), &config);
  337. CHECK_EQ(VPX_CODEC_OK, ret) << "Failed to reconfigure codec";
  338. }
  339. // Apply further customizations to the codec now it's initialized.
  340. if (use_vp9_) {
  341. SetVp9CodecOptions(codec_.get(), lossless_encode_);
  342. } else {
  343. SetVp8CodecOptions(codec_.get());
  344. }
  345. }
  346. void VideoEncoderVpx::PrepareImage(const webrtc::DesktopFrame& frame,
  347. webrtc::DesktopRegion* updated_region) {
  348. if (frame.updated_region().is_empty()) {
  349. updated_region->Clear();
  350. return;
  351. }
  352. updated_region->Clear();
  353. if (image_) {
  354. // Pad each rectangle to avoid the block-artefact filters in libvpx from
  355. // introducing artefacts; VP9 includes up to 8px either side, and VP8 up to
  356. // 3px, so unchanged pixels up to that far out may still be affected by the
  357. // changes in the updated region, and so must be listed in the active map.
  358. // After padding we align each rectangle to 16x16 active-map macroblocks.
  359. // This implicitly ensures all rects have even top-left coords, which is
  360. // is required by ConvertRGBToYUVWithRect().
  361. // TODO(wez): Do we still need 16x16 align, or is even alignment sufficient?
  362. int padding = use_vp9_ ? 8 : 3;
  363. for (webrtc::DesktopRegion::Iterator r(frame.updated_region());
  364. !r.IsAtEnd(); r.Advance()) {
  365. const webrtc::DesktopRect& rect = r.rect();
  366. updated_region->AddRect(AlignRect(webrtc::DesktopRect::MakeLTRB(
  367. rect.left() - padding, rect.top() - padding, rect.right() + padding,
  368. rect.bottom() + padding)));
  369. }
  370. DCHECK(!updated_region->is_empty());
  371. // Clip back to the screen dimensions, in case they're not macroblock
  372. // aligned. The conversion routines don't require even width & height,
  373. // so this is safe even if the source dimensions are not even.
  374. updated_region->IntersectWith(
  375. webrtc::DesktopRect::MakeWH(image_->w, image_->h));
  376. } else {
  377. CreateImage(lossless_color_, frame.size(), &image_, &image_buffer_);
  378. updated_region->AddRect(webrtc::DesktopRect::MakeWH(image_->w, image_->h));
  379. }
  380. // Convert the updated region to YUV ready for encoding.
  381. const uint8_t* rgb_data = frame.data();
  382. const int rgb_stride = frame.stride();
  383. const int y_stride = image_->stride[0];
  384. DCHECK_EQ(image_->stride[1], image_->stride[2]);
  385. const int uv_stride = image_->stride[1];
  386. uint8_t* y_data = image_->planes[0];
  387. uint8_t* u_data = image_->planes[1];
  388. uint8_t* v_data = image_->planes[2];
  389. switch (image_->fmt) {
  390. case VPX_IMG_FMT_I444:
  391. for (webrtc::DesktopRegion::Iterator r(*updated_region); !r.IsAtEnd();
  392. r.Advance()) {
  393. const webrtc::DesktopRect& rect = r.rect();
  394. int rgb_offset = rgb_stride * rect.top() +
  395. rect.left() * kBytesPerRgbPixel;
  396. int yuv_offset = uv_stride * rect.top() + rect.left();
  397. libyuv::ARGBToI444(rgb_data + rgb_offset, rgb_stride,
  398. y_data + yuv_offset, y_stride,
  399. u_data + yuv_offset, uv_stride,
  400. v_data + yuv_offset, uv_stride,
  401. rect.width(), rect.height());
  402. }
  403. break;
  404. case VPX_IMG_FMT_YV12:
  405. for (webrtc::DesktopRegion::Iterator r(*updated_region); !r.IsAtEnd();
  406. r.Advance()) {
  407. const webrtc::DesktopRect& rect = r.rect();
  408. int rgb_offset = rgb_stride * rect.top() +
  409. rect.left() * kBytesPerRgbPixel;
  410. int y_offset = y_stride * rect.top() + rect.left();
  411. int uv_offset = uv_stride * rect.top() / 2 + rect.left() / 2;
  412. libyuv::ARGBToI420(rgb_data + rgb_offset, rgb_stride,
  413. y_data + y_offset, y_stride,
  414. u_data + uv_offset, uv_stride,
  415. v_data + uv_offset, uv_stride,
  416. rect.width(), rect.height());
  417. }
  418. break;
  419. default:
  420. NOTREACHED();
  421. break;
  422. }
  423. }
  424. void VideoEncoderVpx::SetActiveMapFromRegion(
  425. const webrtc::DesktopRegion& updated_region) {
  426. // Clear active map first.
  427. memset(active_map_.get(), 0,
  428. active_map_size_.width() * active_map_size_.height());
  429. // Mark updated areas active.
  430. for (webrtc::DesktopRegion::Iterator r(updated_region); !r.IsAtEnd();
  431. r.Advance()) {
  432. const webrtc::DesktopRect& rect = r.rect();
  433. int left = rect.left() / kMacroBlockSize;
  434. int right = (rect.right() - 1) / kMacroBlockSize;
  435. int top = rect.top() / kMacroBlockSize;
  436. int bottom = (rect.bottom() - 1) / kMacroBlockSize;
  437. DCHECK_LT(right, active_map_size_.width());
  438. DCHECK_LT(bottom, active_map_size_.height());
  439. uint8_t* map = active_map_.get() + top * active_map_size_.width();
  440. for (int y = top; y <= bottom; ++y) {
  441. for (int x = left; x <= right; ++x)
  442. map[x] = 1;
  443. map += active_map_size_.width();
  444. }
  445. }
  446. }
  447. void VideoEncoderVpx::UpdateRegionFromActiveMap(
  448. webrtc::DesktopRegion* updated_region) {
  449. const uint8_t* map = active_map_.get();
  450. for (int y = 0; y < active_map_size_.height(); ++y) {
  451. for (int x0 = 0; x0 < active_map_size_.width();) {
  452. int x1 = x0;
  453. for (; x1 < active_map_size_.width(); ++x1) {
  454. if (map[y * active_map_size_.width() + x1] == 0)
  455. break;
  456. }
  457. if (x1 > x0) {
  458. updated_region->AddRect(webrtc::DesktopRect::MakeLTRB(
  459. kMacroBlockSize * x0, kMacroBlockSize * y, kMacroBlockSize * x1,
  460. kMacroBlockSize * (y + 1)));
  461. }
  462. x0 = x1 + 1;
  463. }
  464. }
  465. updated_region->IntersectWith(
  466. webrtc::DesktopRect::MakeWH(image_->w, image_->h));
  467. }
  468. } // namespace remoting