EnrollmentScreen source code cosmetics.
[chromium-blink-merge.git] / cc / resources / tile_manager.cc
blobbf10d9504150aab4e26657a70055f52fad30f463
1 // Copyright 2012 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.
5 #include "cc/resources/tile_manager.h"
7 #include <algorithm>
8 #include <limits>
9 #include <string>
11 #include "base/bind.h"
12 #include "base/json/json_writer.h"
13 #include "base/logging.h"
14 #include "base/metrics/histogram.h"
15 #include "cc/debug/devtools_instrumentation.h"
16 #include "cc/debug/frame_viewer_instrumentation.h"
17 #include "cc/debug/traced_value.h"
18 #include "cc/layers/picture_layer_impl.h"
19 #include "cc/resources/raster_worker_pool.h"
20 #include "cc/resources/tile.h"
21 #include "skia/ext/paint_simplifier.h"
22 #include "third_party/skia/include/core/SkBitmap.h"
23 #include "third_party/skia/include/core/SkPixelRef.h"
24 #include "ui/gfx/rect_conversions.h"
26 namespace cc {
27 namespace {
29 // Flag to indicate whether we should try and detect that
30 // a tile is of solid color.
31 const bool kUseColorEstimator = true;
33 class RasterTaskImpl : public RasterTask {
34 public:
35 RasterTaskImpl(
36 const Resource* resource,
37 PicturePileImpl* picture_pile,
38 const gfx::Rect& content_rect,
39 float contents_scale,
40 RasterMode raster_mode,
41 TileResolution tile_resolution,
42 int layer_id,
43 const void* tile_id,
44 int source_frame_number,
45 bool analyze_picture,
46 RenderingStatsInstrumentation* rendering_stats,
47 const base::Callback<void(const PicturePileImpl::Analysis&, bool)>& reply,
48 ImageDecodeTask::Vector* dependencies)
49 : RasterTask(resource, dependencies),
50 picture_pile_(picture_pile),
51 content_rect_(content_rect),
52 contents_scale_(contents_scale),
53 raster_mode_(raster_mode),
54 tile_resolution_(tile_resolution),
55 layer_id_(layer_id),
56 tile_id_(tile_id),
57 source_frame_number_(source_frame_number),
58 analyze_picture_(analyze_picture),
59 rendering_stats_(rendering_stats),
60 reply_(reply),
61 canvas_(NULL) {}
63 // Overridden from Task:
64 virtual void RunOnWorkerThread() OVERRIDE {
65 TRACE_EVENT0("cc", "RasterizerTaskImpl::RunOnWorkerThread");
67 DCHECK(picture_pile_);
68 if (canvas_) {
69 AnalyzeAndRaster(picture_pile_->GetCloneForDrawingOnThread(
70 RasterWorkerPool::GetPictureCloneIndexForCurrentThread()));
74 // Overridden from RasterizerTask:
75 virtual void ScheduleOnOriginThread(RasterizerTaskClient* client) OVERRIDE {
76 DCHECK(!canvas_);
77 canvas_ = client->AcquireCanvasForRaster(this);
79 virtual void CompleteOnOriginThread(RasterizerTaskClient* client) OVERRIDE {
80 canvas_ = NULL;
81 client->ReleaseCanvasForRaster(this);
83 virtual void RunReplyOnOriginThread() OVERRIDE {
84 DCHECK(!canvas_);
85 reply_.Run(analysis_, !HasFinishedRunning());
88 protected:
89 virtual ~RasterTaskImpl() { DCHECK(!canvas_); }
91 private:
92 void AnalyzeAndRaster(PicturePileImpl* picture_pile) {
93 DCHECK(picture_pile);
94 DCHECK(canvas_);
96 if (analyze_picture_) {
97 Analyze(picture_pile);
98 if (analysis_.is_solid_color)
99 return;
102 Raster(picture_pile);
105 void Analyze(PicturePileImpl* picture_pile) {
106 frame_viewer_instrumentation::ScopedAnalyzeTask analyze_task(
107 tile_id_, tile_resolution_, source_frame_number_, layer_id_);
109 DCHECK(picture_pile);
111 picture_pile->AnalyzeInRect(
112 content_rect_, contents_scale_, &analysis_, rendering_stats_);
114 // Record the solid color prediction.
115 UMA_HISTOGRAM_BOOLEAN("Renderer4.SolidColorTilesAnalyzed",
116 analysis_.is_solid_color);
118 // Clear the flag if we're not using the estimator.
119 analysis_.is_solid_color &= kUseColorEstimator;
122 void Raster(PicturePileImpl* picture_pile) {
123 frame_viewer_instrumentation::ScopedRasterTask raster_task(
124 tile_id_,
125 tile_resolution_,
126 source_frame_number_,
127 layer_id_,
128 raster_mode_);
129 devtools_instrumentation::ScopedLayerTask layer_task(
130 devtools_instrumentation::kRasterTask, layer_id_);
132 skia::RefPtr<SkDrawFilter> draw_filter;
133 switch (raster_mode_) {
134 case LOW_QUALITY_RASTER_MODE:
135 draw_filter = skia::AdoptRef(new skia::PaintSimplifier);
136 break;
137 case HIGH_QUALITY_RASTER_MODE:
138 break;
139 case NUM_RASTER_MODES:
140 default:
141 NOTREACHED();
143 canvas_->setDrawFilter(draw_filter.get());
145 base::TimeDelta prev_rasterize_time =
146 rendering_stats_->impl_thread_rendering_stats().rasterize_time;
148 // Only record rasterization time for highres tiles, because
149 // lowres tiles are not required for activation and therefore
150 // introduce noise in the measurement (sometimes they get rasterized
151 // before we draw and sometimes they aren't)
152 RenderingStatsInstrumentation* stats =
153 tile_resolution_ == HIGH_RESOLUTION ? rendering_stats_ : NULL;
154 DCHECK(picture_pile);
155 picture_pile->RasterToBitmap(
156 canvas_, content_rect_, contents_scale_, stats);
158 if (rendering_stats_->record_rendering_stats()) {
159 base::TimeDelta current_rasterize_time =
160 rendering_stats_->impl_thread_rendering_stats().rasterize_time;
161 HISTOGRAM_CUSTOM_COUNTS(
162 "Renderer4.PictureRasterTimeUS",
163 (current_rasterize_time - prev_rasterize_time).InMicroseconds(),
165 100000,
166 100);
170 PicturePileImpl::Analysis analysis_;
171 scoped_refptr<PicturePileImpl> picture_pile_;
172 gfx::Rect content_rect_;
173 float contents_scale_;
174 RasterMode raster_mode_;
175 TileResolution tile_resolution_;
176 int layer_id_;
177 const void* tile_id_;
178 int source_frame_number_;
179 bool analyze_picture_;
180 RenderingStatsInstrumentation* rendering_stats_;
181 const base::Callback<void(const PicturePileImpl::Analysis&, bool)> reply_;
182 SkCanvas* canvas_;
184 DISALLOW_COPY_AND_ASSIGN(RasterTaskImpl);
187 class ImageDecodeTaskImpl : public ImageDecodeTask {
188 public:
189 ImageDecodeTaskImpl(SkPixelRef* pixel_ref,
190 int layer_id,
191 RenderingStatsInstrumentation* rendering_stats,
192 const base::Callback<void(bool was_canceled)>& reply)
193 : pixel_ref_(skia::SharePtr(pixel_ref)),
194 layer_id_(layer_id),
195 rendering_stats_(rendering_stats),
196 reply_(reply) {}
198 // Overridden from Task:
199 virtual void RunOnWorkerThread() OVERRIDE {
200 TRACE_EVENT0("cc", "ImageDecodeTaskImpl::RunOnWorkerThread");
202 devtools_instrumentation::ScopedImageDecodeTask image_decode_task(
203 pixel_ref_.get());
204 // This will cause the image referred to by pixel ref to be decoded.
205 pixel_ref_->lockPixels();
206 pixel_ref_->unlockPixels();
209 // Overridden from RasterizerTask:
210 virtual void ScheduleOnOriginThread(RasterizerTaskClient* client) OVERRIDE {}
211 virtual void CompleteOnOriginThread(RasterizerTaskClient* client) OVERRIDE {}
212 virtual void RunReplyOnOriginThread() OVERRIDE {
213 reply_.Run(!HasFinishedRunning());
216 protected:
217 virtual ~ImageDecodeTaskImpl() {}
219 private:
220 skia::RefPtr<SkPixelRef> pixel_ref_;
221 int layer_id_;
222 RenderingStatsInstrumentation* rendering_stats_;
223 const base::Callback<void(bool was_canceled)> reply_;
225 DISALLOW_COPY_AND_ASSIGN(ImageDecodeTaskImpl);
228 const size_t kScheduledRasterTasksLimit = 32u;
230 // Memory limit policy works by mapping some bin states to the NEVER bin.
231 const ManagedTileBin kBinPolicyMap[NUM_TILE_MEMORY_LIMIT_POLICIES][NUM_BINS] = {
232 // [ALLOW_NOTHING]
233 {NEVER_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
234 NEVER_BIN, // [NOW_BIN]
235 NEVER_BIN, // [SOON_BIN]
236 NEVER_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
237 NEVER_BIN, // [EVENTUALLY_BIN]
238 NEVER_BIN, // [AT_LAST_AND_ACTIVE_BIN]
239 NEVER_BIN, // [AT_LAST_BIN]
240 NEVER_BIN // [NEVER_BIN]
242 // [ALLOW_ABSOLUTE_MINIMUM]
243 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
244 NOW_BIN, // [NOW_BIN]
245 NEVER_BIN, // [SOON_BIN]
246 NEVER_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
247 NEVER_BIN, // [EVENTUALLY_BIN]
248 NEVER_BIN, // [AT_LAST_AND_ACTIVE_BIN]
249 NEVER_BIN, // [AT_LAST_BIN]
250 NEVER_BIN // [NEVER_BIN]
252 // [ALLOW_PREPAINT_ONLY]
253 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
254 NOW_BIN, // [NOW_BIN]
255 SOON_BIN, // [SOON_BIN]
256 NEVER_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
257 NEVER_BIN, // [EVENTUALLY_BIN]
258 NEVER_BIN, // [AT_LAST_AND_ACTIVE_BIN]
259 NEVER_BIN, // [AT_LAST_BIN]
260 NEVER_BIN // [NEVER_BIN]
262 // [ALLOW_ANYTHING]
263 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
264 NOW_BIN, // [NOW_BIN]
265 SOON_BIN, // [SOON_BIN]
266 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
267 EVENTUALLY_BIN, // [EVENTUALLY_BIN]
268 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_AND_ACTIVE_BIN]
269 AT_LAST_BIN, // [AT_LAST_BIN]
270 NEVER_BIN // [NEVER_BIN]
273 // Ready to draw works by mapping NOW_BIN to NOW_AND_READY_TO_DRAW_BIN.
274 const ManagedTileBin kBinReadyToDrawMap[2][NUM_BINS] = {
275 // Not ready
276 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
277 NOW_BIN, // [NOW_BIN]
278 SOON_BIN, // [SOON_BIN]
279 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
280 EVENTUALLY_BIN, // [EVENTUALLY_BIN]
281 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_AND_ACTIVE_BIN]
282 AT_LAST_BIN, // [AT_LAST_BIN]
283 NEVER_BIN // [NEVER_BIN]
285 // Ready
286 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
287 NOW_AND_READY_TO_DRAW_BIN, // [NOW_BIN]
288 SOON_BIN, // [SOON_BIN]
289 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
290 EVENTUALLY_BIN, // [EVENTUALLY_BIN]
291 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_AND_ACTIVE_BIN]
292 AT_LAST_BIN, // [AT_LAST_BIN]
293 NEVER_BIN // [NEVER_BIN]
296 // Active works by mapping some bin stats to equivalent _ACTIVE_BIN state.
297 const ManagedTileBin kBinIsActiveMap[2][NUM_BINS] = {
298 // Inactive
299 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
300 NOW_BIN, // [NOW_BIN]
301 SOON_BIN, // [SOON_BIN]
302 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
303 EVENTUALLY_BIN, // [EVENTUALLY_BIN]
304 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_AND_ACTIVE_BIN]
305 AT_LAST_BIN, // [AT_LAST_BIN]
306 NEVER_BIN // [NEVER_BIN]
308 // Active
309 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
310 NOW_BIN, // [NOW_BIN]
311 SOON_BIN, // [SOON_BIN]
312 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
313 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_BIN]
314 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_AND_ACTIVE_BIN]
315 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_BIN]
316 NEVER_BIN // [NEVER_BIN]
319 // Determine bin based on three categories of tiles: things we need now,
320 // things we need soon, and eventually.
321 inline ManagedTileBin BinFromTilePriority(const TilePriority& prio) {
322 if (prio.priority_bin == TilePriority::NOW)
323 return NOW_BIN;
325 if (prio.priority_bin == TilePriority::SOON)
326 return SOON_BIN;
328 if (prio.distance_to_visible == std::numeric_limits<float>::infinity())
329 return NEVER_BIN;
331 return EVENTUALLY_BIN;
334 } // namespace
336 RasterTaskCompletionStats::RasterTaskCompletionStats()
337 : completed_count(0u), canceled_count(0u) {}
339 scoped_ptr<base::Value> RasterTaskCompletionStatsAsValue(
340 const RasterTaskCompletionStats& stats) {
341 scoped_ptr<base::DictionaryValue> state(new base::DictionaryValue());
342 state->SetInteger("completed_count", stats.completed_count);
343 state->SetInteger("canceled_count", stats.canceled_count);
344 return state.PassAs<base::Value>();
347 // static
348 scoped_ptr<TileManager> TileManager::Create(
349 TileManagerClient* client,
350 base::SequencedTaskRunner* task_runner,
351 ResourcePool* resource_pool,
352 Rasterizer* rasterizer,
353 RenderingStatsInstrumentation* rendering_stats_instrumentation) {
354 return make_scoped_ptr(new TileManager(client,
355 task_runner,
356 resource_pool,
357 rasterizer,
358 rendering_stats_instrumentation));
361 TileManager::TileManager(
362 TileManagerClient* client,
363 base::SequencedTaskRunner* task_runner,
364 ResourcePool* resource_pool,
365 Rasterizer* rasterizer,
366 RenderingStatsInstrumentation* rendering_stats_instrumentation)
367 : client_(client),
368 task_runner_(task_runner),
369 resource_pool_(resource_pool),
370 rasterizer_(rasterizer),
371 prioritized_tiles_dirty_(false),
372 all_tiles_that_need_to_be_rasterized_have_memory_(true),
373 all_tiles_required_for_activation_have_memory_(true),
374 bytes_releasable_(0),
375 resources_releasable_(0),
376 ever_exceeded_memory_budget_(false),
377 rendering_stats_instrumentation_(rendering_stats_instrumentation),
378 did_initialize_visible_tile_(false),
379 did_check_for_completed_tasks_since_last_schedule_tasks_(true),
380 ready_to_activate_check_notifier_(
381 task_runner_,
382 base::Bind(&TileManager::CheckIfReadyToActivate,
383 base::Unretained(this))) {
384 rasterizer_->SetClient(this);
387 TileManager::~TileManager() {
388 // Reset global state and manage. This should cause
389 // our memory usage to drop to zero.
390 global_state_ = GlobalStateThatImpactsTilePriority();
392 CleanUpReleasedTiles();
393 DCHECK_EQ(0u, tiles_.size());
395 RasterTaskQueue empty;
396 rasterizer_->ScheduleTasks(&empty);
397 orphan_raster_tasks_.clear();
399 // This should finish all pending tasks and release any uninitialized
400 // resources.
401 rasterizer_->Shutdown();
402 rasterizer_->CheckForCompletedTasks();
404 DCHECK_EQ(0u, bytes_releasable_);
405 DCHECK_EQ(0u, resources_releasable_);
408 void TileManager::Release(Tile* tile) {
409 prioritized_tiles_dirty_ = true;
410 released_tiles_.push_back(tile);
413 void TileManager::DidChangeTilePriority(Tile* tile) {
414 prioritized_tiles_dirty_ = true;
417 bool TileManager::ShouldForceTasksRequiredForActivationToComplete() const {
418 return global_state_.tree_priority != SMOOTHNESS_TAKES_PRIORITY;
421 void TileManager::CleanUpReleasedTiles() {
422 for (std::vector<Tile*>::iterator it = released_tiles_.begin();
423 it != released_tiles_.end();
424 ++it) {
425 Tile* tile = *it;
426 ManagedTileState& mts = tile->managed_state();
428 for (int mode = 0; mode < NUM_RASTER_MODES; ++mode) {
429 FreeResourceForTile(tile, static_cast<RasterMode>(mode));
430 orphan_raster_tasks_.push_back(mts.tile_versions[mode].raster_task_);
433 DCHECK(tiles_.find(tile->id()) != tiles_.end());
434 tiles_.erase(tile->id());
436 LayerCountMap::iterator layer_it =
437 used_layer_counts_.find(tile->layer_id());
438 DCHECK_GT(layer_it->second, 0);
439 if (--layer_it->second == 0) {
440 used_layer_counts_.erase(layer_it);
441 image_decode_tasks_.erase(tile->layer_id());
444 delete tile;
447 released_tiles_.clear();
450 void TileManager::UpdatePrioritizedTileSetIfNeeded() {
451 if (!prioritized_tiles_dirty_)
452 return;
454 CleanUpReleasedTiles();
456 prioritized_tiles_.Clear();
457 GetTilesWithAssignedBins(&prioritized_tiles_);
458 prioritized_tiles_dirty_ = false;
461 void TileManager::DidFinishRunningTasks() {
462 TRACE_EVENT0("cc", "TileManager::DidFinishRunningTasks");
464 bool memory_usage_above_limit = resource_pool_->total_memory_usage_bytes() >
465 global_state_.soft_memory_limit_in_bytes;
467 // When OOM, keep re-assigning memory until we reach a steady state
468 // where top-priority tiles are initialized.
469 if (all_tiles_that_need_to_be_rasterized_have_memory_ &&
470 !memory_usage_above_limit)
471 return;
473 rasterizer_->CheckForCompletedTasks();
474 did_check_for_completed_tasks_since_last_schedule_tasks_ = true;
476 TileVector tiles_that_need_to_be_rasterized;
477 AssignGpuMemoryToTiles(&prioritized_tiles_,
478 &tiles_that_need_to_be_rasterized);
480 // |tiles_that_need_to_be_rasterized| will be empty when we reach a
481 // steady memory state. Keep scheduling tasks until we reach this state.
482 if (!tiles_that_need_to_be_rasterized.empty()) {
483 ScheduleTasks(tiles_that_need_to_be_rasterized);
484 return;
487 resource_pool_->ReduceResourceUsage();
489 // We don't reserve memory for required-for-activation tiles during
490 // accelerated gestures, so we just postpone activation when we don't
491 // have these tiles, and activate after the accelerated gesture.
492 bool allow_rasterize_on_demand =
493 global_state_.tree_priority != SMOOTHNESS_TAKES_PRIORITY;
495 // Use on-demand raster for any required-for-activation tiles that have not
496 // been been assigned memory after reaching a steady memory state. This
497 // ensures that we activate even when OOM.
498 for (TileMap::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
499 Tile* tile = it->second;
500 ManagedTileState& mts = tile->managed_state();
501 ManagedTileState::TileVersion& tile_version =
502 mts.tile_versions[mts.raster_mode];
504 if (tile->required_for_activation() && !tile_version.IsReadyToDraw()) {
505 // If we can't raster on demand, give up early (and don't activate).
506 if (!allow_rasterize_on_demand)
507 return;
509 tile_version.set_rasterize_on_demand();
510 client_->NotifyTileStateChanged(tile);
514 DCHECK(IsReadyToActivate());
515 ready_to_activate_check_notifier_.Schedule();
518 void TileManager::DidFinishRunningTasksRequiredForActivation() {
519 // This is only a true indication that all tiles required for
520 // activation are initialized when no tiles are OOM. We need to
521 // wait for DidFinishRunningTasks() to be called, try to re-assign
522 // memory and in worst case use on-demand raster when tiles
523 // required for activation are OOM.
524 if (!all_tiles_required_for_activation_have_memory_)
525 return;
527 ready_to_activate_check_notifier_.Schedule();
530 void TileManager::GetTilesWithAssignedBins(PrioritizedTileSet* tiles) {
531 TRACE_EVENT0("cc", "TileManager::GetTilesWithAssignedBins");
533 const TileMemoryLimitPolicy memory_policy = global_state_.memory_limit_policy;
534 const TreePriority tree_priority = global_state_.tree_priority;
536 // For each tree, bin into different categories of tiles.
537 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
538 Tile* tile = it->second;
539 ManagedTileState& mts = tile->managed_state();
541 const ManagedTileState::TileVersion& tile_version =
542 tile->GetTileVersionForDrawing();
543 bool tile_is_ready_to_draw = tile_version.IsReadyToDraw();
544 bool tile_is_active = tile_is_ready_to_draw ||
545 mts.tile_versions[mts.raster_mode].raster_task_;
547 // Get the active priority and bin.
548 TilePriority active_priority = tile->priority(ACTIVE_TREE);
549 ManagedTileBin active_bin = BinFromTilePriority(active_priority);
551 // Get the pending priority and bin.
552 TilePriority pending_priority = tile->priority(PENDING_TREE);
553 ManagedTileBin pending_bin = BinFromTilePriority(pending_priority);
555 bool pending_is_low_res = pending_priority.resolution == LOW_RESOLUTION;
556 bool pending_is_non_ideal =
557 pending_priority.resolution == NON_IDEAL_RESOLUTION;
558 bool active_is_non_ideal =
559 active_priority.resolution == NON_IDEAL_RESOLUTION;
561 // Adjust bin state based on if ready to draw.
562 active_bin = kBinReadyToDrawMap[tile_is_ready_to_draw][active_bin];
563 pending_bin = kBinReadyToDrawMap[tile_is_ready_to_draw][pending_bin];
565 // Adjust bin state based on if active.
566 active_bin = kBinIsActiveMap[tile_is_active][active_bin];
567 pending_bin = kBinIsActiveMap[tile_is_active][pending_bin];
569 // We never want to paint new non-ideal tiles, as we always have
570 // a high-res tile covering that content (paint that instead).
571 if (!tile_is_ready_to_draw && active_is_non_ideal)
572 active_bin = NEVER_BIN;
573 if (!tile_is_ready_to_draw && pending_is_non_ideal)
574 pending_bin = NEVER_BIN;
576 ManagedTileBin tree_bin[NUM_TREES];
577 tree_bin[ACTIVE_TREE] = kBinPolicyMap[memory_policy][active_bin];
578 tree_bin[PENDING_TREE] = kBinPolicyMap[memory_policy][pending_bin];
580 // Adjust pending bin state for low res tiles. This prevents pending tree
581 // low-res tiles from being initialized before high-res tiles.
582 if (pending_is_low_res)
583 tree_bin[PENDING_TREE] = std::max(tree_bin[PENDING_TREE], EVENTUALLY_BIN);
585 TilePriority tile_priority;
586 switch (tree_priority) {
587 case SAME_PRIORITY_FOR_BOTH_TREES:
588 mts.bin = std::min(tree_bin[ACTIVE_TREE], tree_bin[PENDING_TREE]);
589 tile_priority = tile->combined_priority();
590 break;
591 case SMOOTHNESS_TAKES_PRIORITY:
592 mts.bin = tree_bin[ACTIVE_TREE];
593 tile_priority = active_priority;
594 break;
595 case NEW_CONTENT_TAKES_PRIORITY:
596 mts.bin = tree_bin[PENDING_TREE];
597 tile_priority = pending_priority;
598 break;
599 default:
600 NOTREACHED();
603 // Bump up the priority if we determined it's NEVER_BIN on one tree,
604 // but is still required on the other tree.
605 bool is_in_never_bin_on_both_trees = tree_bin[ACTIVE_TREE] == NEVER_BIN &&
606 tree_bin[PENDING_TREE] == NEVER_BIN;
608 if (mts.bin == NEVER_BIN && !is_in_never_bin_on_both_trees)
609 mts.bin = tile_is_active ? AT_LAST_AND_ACTIVE_BIN : AT_LAST_BIN;
611 mts.resolution = tile_priority.resolution;
612 mts.priority_bin = tile_priority.priority_bin;
613 mts.distance_to_visible = tile_priority.distance_to_visible;
614 mts.required_for_activation = tile_priority.required_for_activation;
616 mts.visible_and_ready_to_draw =
617 tree_bin[ACTIVE_TREE] == NOW_AND_READY_TO_DRAW_BIN;
619 // Tiles that are required for activation shouldn't be in NEVER_BIN unless
620 // smoothness takes priority or memory policy allows nothing to be
621 // initialized.
622 DCHECK(!mts.required_for_activation || mts.bin != NEVER_BIN ||
623 tree_priority == SMOOTHNESS_TAKES_PRIORITY ||
624 memory_policy == ALLOW_NOTHING);
626 // If the tile is in NEVER_BIN and it does not have an active task, then we
627 // can release the resources early. If it does have the task however, we
628 // should keep it in the prioritized tile set to ensure that AssignGpuMemory
629 // can visit it.
630 if (mts.bin == NEVER_BIN &&
631 !mts.tile_versions[mts.raster_mode].raster_task_) {
632 FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(tile);
633 continue;
636 // Insert the tile into a priority set.
637 tiles->InsertTile(tile, mts.bin);
641 void TileManager::ManageTiles(const GlobalStateThatImpactsTilePriority& state) {
642 TRACE_EVENT0("cc", "TileManager::ManageTiles");
644 // Update internal state.
645 if (state != global_state_) {
646 global_state_ = state;
647 prioritized_tiles_dirty_ = true;
650 // We need to call CheckForCompletedTasks() once in-between each call
651 // to ScheduleTasks() to prevent canceled tasks from being scheduled.
652 if (!did_check_for_completed_tasks_since_last_schedule_tasks_) {
653 rasterizer_->CheckForCompletedTasks();
654 did_check_for_completed_tasks_since_last_schedule_tasks_ = true;
657 UpdatePrioritizedTileSetIfNeeded();
659 TileVector tiles_that_need_to_be_rasterized;
660 AssignGpuMemoryToTiles(&prioritized_tiles_,
661 &tiles_that_need_to_be_rasterized);
663 // Finally, schedule rasterizer tasks.
664 ScheduleTasks(tiles_that_need_to_be_rasterized);
666 TRACE_EVENT_INSTANT1("cc",
667 "DidManage",
668 TRACE_EVENT_SCOPE_THREAD,
669 "state",
670 TracedValue::FromValue(BasicStateAsValue().release()));
672 TRACE_COUNTER_ID1("cc",
673 "unused_memory_bytes",
674 this,
675 resource_pool_->total_memory_usage_bytes() -
676 resource_pool_->acquired_memory_usage_bytes());
679 bool TileManager::UpdateVisibleTiles() {
680 TRACE_EVENT0("cc", "TileManager::UpdateVisibleTiles");
682 rasterizer_->CheckForCompletedTasks();
683 did_check_for_completed_tasks_since_last_schedule_tasks_ = true;
685 TRACE_EVENT_INSTANT1(
686 "cc",
687 "DidUpdateVisibleTiles",
688 TRACE_EVENT_SCOPE_THREAD,
689 "stats",
690 TracedValue::FromValue(RasterTaskCompletionStatsAsValue(
691 update_visible_tiles_stats_).release()));
692 update_visible_tiles_stats_ = RasterTaskCompletionStats();
694 bool did_initialize_visible_tile = did_initialize_visible_tile_;
695 did_initialize_visible_tile_ = false;
696 return did_initialize_visible_tile;
699 scoped_ptr<base::Value> TileManager::BasicStateAsValue() const {
700 scoped_ptr<base::DictionaryValue> state(new base::DictionaryValue());
701 state->SetInteger("tile_count", tiles_.size());
702 state->Set("global_state", global_state_.AsValue().release());
703 return state.PassAs<base::Value>();
706 scoped_ptr<base::Value> TileManager::AllTilesAsValue() const {
707 scoped_ptr<base::ListValue> state(new base::ListValue());
708 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it)
709 state->Append(it->second->AsValue().release());
711 return state.PassAs<base::Value>();
714 void TileManager::AssignGpuMemoryToTiles(
715 PrioritizedTileSet* tiles,
716 TileVector* tiles_that_need_to_be_rasterized) {
717 TRACE_EVENT0("cc", "TileManager::AssignGpuMemoryToTiles");
719 // Maintain the list of released resources that can potentially be re-used
720 // or deleted.
721 // If this operation becomes expensive too, only do this after some
722 // resource(s) was returned. Note that in that case, one also need to
723 // invalidate when releasing some resource from the pool.
724 resource_pool_->CheckBusyResources();
726 // Now give memory out to the tiles until we're out, and build
727 // the needs-to-be-rasterized queue.
728 all_tiles_that_need_to_be_rasterized_have_memory_ = true;
729 all_tiles_required_for_activation_have_memory_ = true;
731 // Cast to prevent overflow.
732 int64 soft_bytes_available =
733 static_cast<int64>(bytes_releasable_) +
734 static_cast<int64>(global_state_.soft_memory_limit_in_bytes) -
735 static_cast<int64>(resource_pool_->acquired_memory_usage_bytes());
736 int64 hard_bytes_available =
737 static_cast<int64>(bytes_releasable_) +
738 static_cast<int64>(global_state_.hard_memory_limit_in_bytes) -
739 static_cast<int64>(resource_pool_->acquired_memory_usage_bytes());
740 int resources_available = resources_releasable_ +
741 global_state_.num_resources_limit -
742 resource_pool_->acquired_resource_count();
743 size_t soft_bytes_allocatable =
744 std::max(static_cast<int64>(0), soft_bytes_available);
745 size_t hard_bytes_allocatable =
746 std::max(static_cast<int64>(0), hard_bytes_available);
747 size_t resources_allocatable = std::max(0, resources_available);
749 size_t bytes_that_exceeded_memory_budget = 0;
750 size_t soft_bytes_left = soft_bytes_allocatable;
751 size_t hard_bytes_left = hard_bytes_allocatable;
753 size_t resources_left = resources_allocatable;
754 bool oomed_soft = false;
755 bool oomed_hard = false;
756 bool have_hit_soft_memory = false; // Soft memory comes after hard.
758 unsigned schedule_priority = 1u;
759 for (PrioritizedTileSet::Iterator it(tiles, true); it; ++it) {
760 Tile* tile = *it;
761 ManagedTileState& mts = tile->managed_state();
763 mts.scheduled_priority = schedule_priority++;
765 mts.raster_mode = tile->DetermineOverallRasterMode();
767 ManagedTileState::TileVersion& tile_version =
768 mts.tile_versions[mts.raster_mode];
770 // If this tile doesn't need a resource, then nothing to do.
771 if (!tile_version.requires_resource())
772 continue;
774 // If the tile is not needed, free it up.
775 if (mts.bin == NEVER_BIN) {
776 FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(tile);
777 continue;
780 const bool tile_uses_hard_limit = mts.bin <= NOW_BIN;
781 const size_t bytes_if_allocated = BytesConsumedIfAllocated(tile);
782 const size_t tile_bytes_left =
783 (tile_uses_hard_limit) ? hard_bytes_left : soft_bytes_left;
785 // Hard-limit is reserved for tiles that would cause a calamity
786 // if they were to go away, so by definition they are the highest
787 // priority memory, and must be at the front of the list.
788 DCHECK(!(have_hit_soft_memory && tile_uses_hard_limit));
789 have_hit_soft_memory |= !tile_uses_hard_limit;
791 size_t tile_bytes = 0;
792 size_t tile_resources = 0;
794 // It costs to maintain a resource.
795 for (int mode = 0; mode < NUM_RASTER_MODES; ++mode) {
796 if (mts.tile_versions[mode].resource_) {
797 tile_bytes += bytes_if_allocated;
798 tile_resources++;
802 // Allow lower priority tiles with initialized resources to keep
803 // their memory by only assigning memory to new raster tasks if
804 // they can be scheduled.
805 bool reached_scheduled_raster_tasks_limit =
806 tiles_that_need_to_be_rasterized->size() >= kScheduledRasterTasksLimit;
807 if (!reached_scheduled_raster_tasks_limit) {
808 // If we don't have the required version, and it's not in flight
809 // then we'll have to pay to create a new task.
810 if (!tile_version.resource_ && !tile_version.raster_task_) {
811 tile_bytes += bytes_if_allocated;
812 tile_resources++;
816 // Tile is OOM.
817 if (tile_bytes > tile_bytes_left || tile_resources > resources_left) {
818 bool was_ready_to_draw = tile->IsReadyToDraw();
820 FreeResourcesForTile(tile);
822 // This tile was already on screen and now its resources have been
823 // released. In order to prevent checkerboarding, set this tile as
824 // rasterize on demand immediately.
825 if (mts.visible_and_ready_to_draw)
826 tile_version.set_rasterize_on_demand();
828 if (was_ready_to_draw)
829 client_->NotifyTileStateChanged(tile);
831 oomed_soft = true;
832 if (tile_uses_hard_limit) {
833 oomed_hard = true;
834 bytes_that_exceeded_memory_budget += tile_bytes;
836 } else {
837 resources_left -= tile_resources;
838 hard_bytes_left -= tile_bytes;
839 soft_bytes_left =
840 (soft_bytes_left > tile_bytes) ? soft_bytes_left - tile_bytes : 0;
841 if (tile_version.resource_)
842 continue;
845 DCHECK(!tile_version.resource_);
847 // Tile shouldn't be rasterized if |tiles_that_need_to_be_rasterized|
848 // has reached it's limit or we've failed to assign gpu memory to this
849 // or any higher priority tile. Preventing tiles that fit into memory
850 // budget to be rasterized when higher priority tile is oom is
851 // important for two reasons:
852 // 1. Tile size should not impact raster priority.
853 // 2. Tiles with existing raster task could otherwise incorrectly
854 // be added as they are not affected by |bytes_allocatable|.
855 bool can_schedule_tile =
856 !oomed_soft && !reached_scheduled_raster_tasks_limit;
858 if (!can_schedule_tile) {
859 all_tiles_that_need_to_be_rasterized_have_memory_ = false;
860 if (tile->required_for_activation())
861 all_tiles_required_for_activation_have_memory_ = false;
862 it.DisablePriorityOrdering();
863 continue;
866 tiles_that_need_to_be_rasterized->push_back(tile);
869 // OOM reporting uses hard-limit, soft-OOM is normal depending on limit.
870 ever_exceeded_memory_budget_ |= oomed_hard;
871 if (ever_exceeded_memory_budget_) {
872 TRACE_COUNTER_ID2("cc",
873 "over_memory_budget",
874 this,
875 "budget",
876 global_state_.hard_memory_limit_in_bytes,
877 "over",
878 bytes_that_exceeded_memory_budget);
880 UMA_HISTOGRAM_BOOLEAN("TileManager.ExceededMemoryBudget", oomed_hard);
881 memory_stats_from_last_assign_.total_budget_in_bytes =
882 global_state_.hard_memory_limit_in_bytes;
883 memory_stats_from_last_assign_.bytes_allocated =
884 hard_bytes_allocatable - hard_bytes_left;
885 memory_stats_from_last_assign_.bytes_unreleasable =
886 resource_pool_->acquired_memory_usage_bytes() - bytes_releasable_;
887 memory_stats_from_last_assign_.bytes_over = bytes_that_exceeded_memory_budget;
890 void TileManager::FreeResourceForTile(Tile* tile, RasterMode mode) {
891 ManagedTileState& mts = tile->managed_state();
892 if (mts.tile_versions[mode].resource_) {
893 resource_pool_->ReleaseResource(mts.tile_versions[mode].resource_.Pass());
895 DCHECK_GE(bytes_releasable_, BytesConsumedIfAllocated(tile));
896 DCHECK_GE(resources_releasable_, 1u);
898 bytes_releasable_ -= BytesConsumedIfAllocated(tile);
899 --resources_releasable_;
903 void TileManager::FreeResourcesForTile(Tile* tile) {
904 for (int mode = 0; mode < NUM_RASTER_MODES; ++mode) {
905 FreeResourceForTile(tile, static_cast<RasterMode>(mode));
909 void TileManager::FreeUnusedResourcesForTile(Tile* tile) {
910 DCHECK(tile->IsReadyToDraw());
911 ManagedTileState& mts = tile->managed_state();
912 RasterMode used_mode = LOW_QUALITY_RASTER_MODE;
913 for (int mode = 0; mode < NUM_RASTER_MODES; ++mode) {
914 if (mts.tile_versions[mode].IsReadyToDraw()) {
915 used_mode = static_cast<RasterMode>(mode);
916 break;
920 for (int mode = 0; mode < NUM_RASTER_MODES; ++mode) {
921 if (mode != used_mode)
922 FreeResourceForTile(tile, static_cast<RasterMode>(mode));
926 void TileManager::FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(
927 Tile* tile) {
928 bool was_ready_to_draw = tile->IsReadyToDraw();
929 FreeResourcesForTile(tile);
930 if (was_ready_to_draw)
931 client_->NotifyTileStateChanged(tile);
934 void TileManager::ScheduleTasks(
935 const TileVector& tiles_that_need_to_be_rasterized) {
936 TRACE_EVENT1("cc",
937 "TileManager::ScheduleTasks",
938 "count",
939 tiles_that_need_to_be_rasterized.size());
941 DCHECK(did_check_for_completed_tasks_since_last_schedule_tasks_);
943 raster_queue_.Reset();
945 // Build a new task queue containing all task currently needed. Tasks
946 // are added in order of priority, highest priority task first.
947 for (TileVector::const_iterator it = tiles_that_need_to_be_rasterized.begin();
948 it != tiles_that_need_to_be_rasterized.end();
949 ++it) {
950 Tile* tile = *it;
951 ManagedTileState& mts = tile->managed_state();
952 ManagedTileState::TileVersion& tile_version =
953 mts.tile_versions[mts.raster_mode];
955 DCHECK(tile_version.requires_resource());
956 DCHECK(!tile_version.resource_);
958 if (!tile_version.raster_task_)
959 tile_version.raster_task_ = CreateRasterTask(tile);
961 raster_queue_.items.push_back(RasterTaskQueue::Item(
962 tile_version.raster_task_.get(), tile->required_for_activation()));
963 raster_queue_.required_for_activation_count +=
964 tile->required_for_activation();
967 // We must reduce the amount of unused resoruces before calling
968 // ScheduleTasks to prevent usage from rising above limits.
969 resource_pool_->ReduceResourceUsage();
971 // Schedule running of |raster_tasks_|. This replaces any previously
972 // scheduled tasks and effectively cancels all tasks not present
973 // in |raster_tasks_|.
974 rasterizer_->ScheduleTasks(&raster_queue_);
976 // It's now safe to clean up orphan tasks as raster worker pool is not
977 // allowed to keep around unreferenced raster tasks after ScheduleTasks() has
978 // been called.
979 orphan_raster_tasks_.clear();
981 did_check_for_completed_tasks_since_last_schedule_tasks_ = false;
984 scoped_refptr<ImageDecodeTask> TileManager::CreateImageDecodeTask(
985 Tile* tile,
986 SkPixelRef* pixel_ref) {
987 return make_scoped_refptr(new ImageDecodeTaskImpl(
988 pixel_ref,
989 tile->layer_id(),
990 rendering_stats_instrumentation_,
991 base::Bind(&TileManager::OnImageDecodeTaskCompleted,
992 base::Unretained(this),
993 tile->layer_id(),
994 base::Unretained(pixel_ref))));
997 scoped_refptr<RasterTask> TileManager::CreateRasterTask(Tile* tile) {
998 ManagedTileState& mts = tile->managed_state();
1000 scoped_ptr<ScopedResource> resource =
1001 resource_pool_->AcquireResource(tile->tile_size_.size());
1002 const ScopedResource* const_resource = resource.get();
1004 // Create and queue all image decode tasks that this tile depends on.
1005 ImageDecodeTask::Vector decode_tasks;
1006 PixelRefTaskMap& existing_pixel_refs = image_decode_tasks_[tile->layer_id()];
1007 for (PicturePileImpl::PixelRefIterator iter(
1008 tile->content_rect(), tile->contents_scale(), tile->picture_pile());
1009 iter;
1010 ++iter) {
1011 SkPixelRef* pixel_ref = *iter;
1012 uint32_t id = pixel_ref->getGenerationID();
1014 // Append existing image decode task if available.
1015 PixelRefTaskMap::iterator decode_task_it = existing_pixel_refs.find(id);
1016 if (decode_task_it != existing_pixel_refs.end()) {
1017 decode_tasks.push_back(decode_task_it->second);
1018 continue;
1021 // Create and append new image decode task for this pixel ref.
1022 scoped_refptr<ImageDecodeTask> decode_task =
1023 CreateImageDecodeTask(tile, pixel_ref);
1024 decode_tasks.push_back(decode_task);
1025 existing_pixel_refs[id] = decode_task;
1028 return make_scoped_refptr(
1029 new RasterTaskImpl(const_resource,
1030 tile->picture_pile(),
1031 tile->content_rect(),
1032 tile->contents_scale(),
1033 mts.raster_mode,
1034 mts.resolution,
1035 tile->layer_id(),
1036 static_cast<const void*>(tile),
1037 tile->source_frame_number(),
1038 tile->use_picture_analysis(),
1039 rendering_stats_instrumentation_,
1040 base::Bind(&TileManager::OnRasterTaskCompleted,
1041 base::Unretained(this),
1042 tile->id(),
1043 base::Passed(&resource),
1044 mts.raster_mode),
1045 &decode_tasks));
1048 void TileManager::OnImageDecodeTaskCompleted(int layer_id,
1049 SkPixelRef* pixel_ref,
1050 bool was_canceled) {
1051 // If the task was canceled, we need to clean it up
1052 // from |image_decode_tasks_|.
1053 if (!was_canceled)
1054 return;
1056 LayerPixelRefTaskMap::iterator layer_it = image_decode_tasks_.find(layer_id);
1057 if (layer_it == image_decode_tasks_.end())
1058 return;
1060 PixelRefTaskMap& pixel_ref_tasks = layer_it->second;
1061 PixelRefTaskMap::iterator task_it =
1062 pixel_ref_tasks.find(pixel_ref->getGenerationID());
1064 if (task_it != pixel_ref_tasks.end())
1065 pixel_ref_tasks.erase(task_it);
1068 void TileManager::OnRasterTaskCompleted(
1069 Tile::Id tile_id,
1070 scoped_ptr<ScopedResource> resource,
1071 RasterMode raster_mode,
1072 const PicturePileImpl::Analysis& analysis,
1073 bool was_canceled) {
1074 TileMap::iterator it = tiles_.find(tile_id);
1075 if (it == tiles_.end()) {
1076 ++update_visible_tiles_stats_.canceled_count;
1077 resource_pool_->ReleaseResource(resource.Pass());
1078 return;
1081 Tile* tile = it->second;
1082 ManagedTileState& mts = tile->managed_state();
1083 ManagedTileState::TileVersion& tile_version = mts.tile_versions[raster_mode];
1084 DCHECK(tile_version.raster_task_);
1085 orphan_raster_tasks_.push_back(tile_version.raster_task_);
1086 tile_version.raster_task_ = NULL;
1088 if (was_canceled) {
1089 ++update_visible_tiles_stats_.canceled_count;
1090 resource_pool_->ReleaseResource(resource.Pass());
1091 return;
1094 ++update_visible_tiles_stats_.completed_count;
1096 if (analysis.is_solid_color) {
1097 tile_version.set_solid_color(analysis.solid_color);
1098 resource_pool_->ReleaseResource(resource.Pass());
1099 } else {
1100 tile_version.set_use_resource();
1101 tile_version.resource_ = resource.Pass();
1103 bytes_releasable_ += BytesConsumedIfAllocated(tile);
1104 ++resources_releasable_;
1107 FreeUnusedResourcesForTile(tile);
1108 if (tile->priority(ACTIVE_TREE).distance_to_visible == 0.f)
1109 did_initialize_visible_tile_ = true;
1111 client_->NotifyTileStateChanged(tile);
1114 scoped_refptr<Tile> TileManager::CreateTile(PicturePileImpl* picture_pile,
1115 const gfx::Size& tile_size,
1116 const gfx::Rect& content_rect,
1117 const gfx::Rect& opaque_rect,
1118 float contents_scale,
1119 int layer_id,
1120 int source_frame_number,
1121 int flags) {
1122 scoped_refptr<Tile> tile = make_scoped_refptr(new Tile(this,
1123 picture_pile,
1124 tile_size,
1125 content_rect,
1126 opaque_rect,
1127 contents_scale,
1128 layer_id,
1129 source_frame_number,
1130 flags));
1131 DCHECK(tiles_.find(tile->id()) == tiles_.end());
1133 tiles_[tile->id()] = tile;
1134 used_layer_counts_[tile->layer_id()]++;
1135 prioritized_tiles_dirty_ = true;
1136 return tile;
1139 void TileManager::SetRasterizerForTesting(Rasterizer* rasterizer) {
1140 rasterizer_ = rasterizer;
1141 rasterizer_->SetClient(this);
1144 bool TileManager::IsReadyToActivate() const {
1145 const std::vector<PictureLayerImpl*>& layers = client_->GetPictureLayers();
1147 for (std::vector<PictureLayerImpl*>::const_iterator it = layers.begin();
1148 it != layers.end();
1149 ++it) {
1150 if (!(*it)->AllTilesRequiredForActivationAreReadyToDraw())
1151 return false;
1154 return true;
1157 void TileManager::CheckIfReadyToActivate() {
1158 TRACE_EVENT0("cc", "TileManager::CheckIfReadyToActivate");
1160 rasterizer_->CheckForCompletedTasks();
1161 did_check_for_completed_tasks_since_last_schedule_tasks_ = true;
1163 if (IsReadyToActivate())
1164 client_->NotifyReadyToActivate();
1167 } // namespace cc