[NaCl SDK]: use standard __BEGIN_DECLS macros in sys/select.h
[chromium-blink-merge.git] / cc / resources / tile_manager.cc
blob6abdc466242a4bc81cdae4d6460cb7fea7a70215
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/debug/trace_event_argument.h"
13 #include "base/json/json_writer.h"
14 #include "base/logging.h"
15 #include "base/metrics/histogram.h"
16 #include "cc/debug/devtools_instrumentation.h"
17 #include "cc/debug/frame_viewer_instrumentation.h"
18 #include "cc/debug/traced_value.h"
19 #include "cc/layers/picture_layer_impl.h"
20 #include "cc/resources/rasterizer.h"
21 #include "cc/resources/tile.h"
22 #include "skia/ext/paint_simplifier.h"
23 #include "third_party/skia/include/core/SkBitmap.h"
24 #include "third_party/skia/include/core/SkPixelRef.h"
25 #include "ui/gfx/rect_conversions.h"
27 namespace cc {
28 namespace {
30 // Flag to indicate whether we should try and detect that
31 // a tile is of solid color.
32 const bool kUseColorEstimator = true;
34 class RasterTaskImpl : public RasterTask {
35 public:
36 RasterTaskImpl(
37 const Resource* resource,
38 PicturePileImpl* picture_pile,
39 const gfx::Rect& content_rect,
40 float contents_scale,
41 RasterMode raster_mode,
42 TileResolution tile_resolution,
43 int layer_id,
44 const void* tile_id,
45 int source_frame_number,
46 bool analyze_picture,
47 RenderingStatsInstrumentation* rendering_stats,
48 const base::Callback<void(const PicturePileImpl::Analysis&, bool)>& reply,
49 ImageDecodeTask::Vector* dependencies)
50 : RasterTask(resource, dependencies),
51 picture_pile_(picture_pile),
52 content_rect_(content_rect),
53 contents_scale_(contents_scale),
54 raster_mode_(raster_mode),
55 tile_resolution_(tile_resolution),
56 layer_id_(layer_id),
57 tile_id_(tile_id),
58 source_frame_number_(source_frame_number),
59 analyze_picture_(analyze_picture),
60 rendering_stats_(rendering_stats),
61 reply_(reply),
62 raster_buffer_(NULL) {}
64 // Overridden from Task:
65 virtual void RunOnWorkerThread() OVERRIDE {
66 TRACE_EVENT0("cc", "RasterizerTaskImpl::RunOnWorkerThread");
68 DCHECK(picture_pile_.get());
69 DCHECK(raster_buffer_);
71 if (analyze_picture_) {
72 Analyze(picture_pile_.get());
73 if (analysis_.is_solid_color)
74 return;
77 Raster(picture_pile_.get());
80 // Overridden from RasterizerTask:
81 virtual void ScheduleOnOriginThread(RasterizerTaskClient* client) OVERRIDE {
82 DCHECK(!raster_buffer_);
83 raster_buffer_ = client->AcquireBufferForRaster(this);
85 virtual void CompleteOnOriginThread(RasterizerTaskClient* client) OVERRIDE {
86 raster_buffer_ = NULL;
87 client->ReleaseBufferForRaster(this);
89 virtual void RunReplyOnOriginThread() OVERRIDE {
90 DCHECK(!raster_buffer_);
91 reply_.Run(analysis_, !HasFinishedRunning());
94 protected:
95 virtual ~RasterTaskImpl() { DCHECK(!raster_buffer_); }
97 private:
98 void Analyze(const PicturePileImpl* picture_pile) {
99 frame_viewer_instrumentation::ScopedAnalyzeTask analyze_task(
100 tile_id_, tile_resolution_, source_frame_number_, layer_id_);
102 DCHECK(picture_pile);
104 picture_pile->AnalyzeInRect(
105 content_rect_, contents_scale_, &analysis_, rendering_stats_);
107 // Record the solid color prediction.
108 UMA_HISTOGRAM_BOOLEAN("Renderer4.SolidColorTilesAnalyzed",
109 analysis_.is_solid_color);
111 // Clear the flag if we're not using the estimator.
112 analysis_.is_solid_color &= kUseColorEstimator;
115 void Raster(const PicturePileImpl* picture_pile) {
116 frame_viewer_instrumentation::ScopedRasterTask raster_task(
117 tile_id_,
118 tile_resolution_,
119 source_frame_number_,
120 layer_id_,
121 raster_mode_);
122 devtools_instrumentation::ScopedLayerTask layer_task(
123 devtools_instrumentation::kRasterTask, layer_id_);
125 skia::RefPtr<SkCanvas> canvas = raster_buffer_->AcquireSkCanvas();
126 if (!canvas)
127 return;
128 canvas->save();
130 skia::RefPtr<SkDrawFilter> draw_filter;
131 switch (raster_mode_) {
132 case LOW_QUALITY_RASTER_MODE:
133 draw_filter = skia::AdoptRef(new skia::PaintSimplifier);
134 break;
135 case HIGH_QUALITY_RASTER_MODE:
136 break;
137 case NUM_RASTER_MODES:
138 default:
139 NOTREACHED();
141 canvas->setDrawFilter(draw_filter.get());
143 base::TimeDelta prev_rasterize_time =
144 rendering_stats_->impl_thread_rendering_stats().rasterize_time;
146 // Only record rasterization time for highres tiles, because
147 // lowres tiles are not required for activation and therefore
148 // introduce noise in the measurement (sometimes they get rasterized
149 // before we draw and sometimes they aren't)
150 RenderingStatsInstrumentation* stats =
151 tile_resolution_ == HIGH_RESOLUTION ? rendering_stats_ : NULL;
152 DCHECK(picture_pile);
153 picture_pile->RasterToBitmap(
154 canvas.get(), content_rect_, contents_scale_, stats);
156 if (rendering_stats_->record_rendering_stats()) {
157 base::TimeDelta current_rasterize_time =
158 rendering_stats_->impl_thread_rendering_stats().rasterize_time;
159 LOCAL_HISTOGRAM_CUSTOM_COUNTS(
160 "Renderer4.PictureRasterTimeUS",
161 (current_rasterize_time - prev_rasterize_time).InMicroseconds(),
163 100000,
164 100);
167 canvas->restore();
168 raster_buffer_->ReleaseSkCanvas(canvas);
171 PicturePileImpl::Analysis analysis_;
172 scoped_refptr<PicturePileImpl> picture_pile_;
173 gfx::Rect content_rect_;
174 float contents_scale_;
175 RasterMode raster_mode_;
176 TileResolution tile_resolution_;
177 int layer_id_;
178 const void* tile_id_;
179 int source_frame_number_;
180 bool analyze_picture_;
181 RenderingStatsInstrumentation* rendering_stats_;
182 const base::Callback<void(const PicturePileImpl::Analysis&, bool)> reply_;
183 RasterBuffer* raster_buffer_;
185 DISALLOW_COPY_AND_ASSIGN(RasterTaskImpl);
188 class ImageDecodeTaskImpl : public ImageDecodeTask {
189 public:
190 ImageDecodeTaskImpl(SkPixelRef* pixel_ref,
191 int layer_id,
192 RenderingStatsInstrumentation* rendering_stats,
193 const base::Callback<void(bool was_canceled)>& reply)
194 : pixel_ref_(skia::SharePtr(pixel_ref)),
195 layer_id_(layer_id),
196 rendering_stats_(rendering_stats),
197 reply_(reply) {}
199 // Overridden from Task:
200 virtual void RunOnWorkerThread() OVERRIDE {
201 TRACE_EVENT0("cc", "ImageDecodeTaskImpl::RunOnWorkerThread");
203 devtools_instrumentation::ScopedImageDecodeTask image_decode_task(
204 pixel_ref_.get());
205 // This will cause the image referred to by pixel ref to be decoded.
206 pixel_ref_->lockPixels();
207 pixel_ref_->unlockPixels();
210 // Overridden from RasterizerTask:
211 virtual void ScheduleOnOriginThread(RasterizerTaskClient* client) OVERRIDE {}
212 virtual void CompleteOnOriginThread(RasterizerTaskClient* client) OVERRIDE {}
213 virtual void RunReplyOnOriginThread() OVERRIDE {
214 reply_.Run(!HasFinishedRunning());
217 protected:
218 virtual ~ImageDecodeTaskImpl() {}
220 private:
221 skia::RefPtr<SkPixelRef> pixel_ref_;
222 int layer_id_;
223 RenderingStatsInstrumentation* rendering_stats_;
224 const base::Callback<void(bool was_canceled)> reply_;
226 DISALLOW_COPY_AND_ASSIGN(ImageDecodeTaskImpl);
229 const size_t kScheduledRasterTasksLimit = 32u;
231 // Memory limit policy works by mapping some bin states to the NEVER bin.
232 const ManagedTileBin kBinPolicyMap[NUM_TILE_MEMORY_LIMIT_POLICIES][NUM_BINS] = {
233 // [ALLOW_NOTHING]
234 {NEVER_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
235 NEVER_BIN, // [NOW_BIN]
236 NEVER_BIN, // [SOON_BIN]
237 NEVER_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
238 NEVER_BIN, // [EVENTUALLY_BIN]
239 NEVER_BIN, // [AT_LAST_AND_ACTIVE_BIN]
240 NEVER_BIN, // [AT_LAST_BIN]
241 NEVER_BIN // [NEVER_BIN]
243 // [ALLOW_ABSOLUTE_MINIMUM]
244 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
245 NOW_BIN, // [NOW_BIN]
246 NEVER_BIN, // [SOON_BIN]
247 NEVER_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
248 NEVER_BIN, // [EVENTUALLY_BIN]
249 NEVER_BIN, // [AT_LAST_AND_ACTIVE_BIN]
250 NEVER_BIN, // [AT_LAST_BIN]
251 NEVER_BIN // [NEVER_BIN]
253 // [ALLOW_PREPAINT_ONLY]
254 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
255 NOW_BIN, // [NOW_BIN]
256 SOON_BIN, // [SOON_BIN]
257 NEVER_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
258 NEVER_BIN, // [EVENTUALLY_BIN]
259 NEVER_BIN, // [AT_LAST_AND_ACTIVE_BIN]
260 NEVER_BIN, // [AT_LAST_BIN]
261 NEVER_BIN // [NEVER_BIN]
263 // [ALLOW_ANYTHING]
264 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
265 NOW_BIN, // [NOW_BIN]
266 SOON_BIN, // [SOON_BIN]
267 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
268 EVENTUALLY_BIN, // [EVENTUALLY_BIN]
269 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_AND_ACTIVE_BIN]
270 AT_LAST_BIN, // [AT_LAST_BIN]
271 NEVER_BIN // [NEVER_BIN]
274 // Ready to draw works by mapping NOW_BIN to NOW_AND_READY_TO_DRAW_BIN.
275 const ManagedTileBin kBinReadyToDrawMap[2][NUM_BINS] = {
276 // Not ready
277 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
278 NOW_BIN, // [NOW_BIN]
279 SOON_BIN, // [SOON_BIN]
280 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
281 EVENTUALLY_BIN, // [EVENTUALLY_BIN]
282 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_AND_ACTIVE_BIN]
283 AT_LAST_BIN, // [AT_LAST_BIN]
284 NEVER_BIN // [NEVER_BIN]
286 // Ready
287 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
288 NOW_AND_READY_TO_DRAW_BIN, // [NOW_BIN]
289 SOON_BIN, // [SOON_BIN]
290 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
291 EVENTUALLY_BIN, // [EVENTUALLY_BIN]
292 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_AND_ACTIVE_BIN]
293 AT_LAST_BIN, // [AT_LAST_BIN]
294 NEVER_BIN // [NEVER_BIN]
297 // Active works by mapping some bin stats to equivalent _ACTIVE_BIN state.
298 const ManagedTileBin kBinIsActiveMap[2][NUM_BINS] = {
299 // Inactive
300 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
301 NOW_BIN, // [NOW_BIN]
302 SOON_BIN, // [SOON_BIN]
303 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
304 EVENTUALLY_BIN, // [EVENTUALLY_BIN]
305 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_AND_ACTIVE_BIN]
306 AT_LAST_BIN, // [AT_LAST_BIN]
307 NEVER_BIN // [NEVER_BIN]
309 // Active
310 {NOW_AND_READY_TO_DRAW_BIN, // [NOW_AND_READY_TO_DRAW_BIN]
311 NOW_BIN, // [NOW_BIN]
312 SOON_BIN, // [SOON_BIN]
313 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_AND_ACTIVE_BIN]
314 EVENTUALLY_AND_ACTIVE_BIN, // [EVENTUALLY_BIN]
315 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_AND_ACTIVE_BIN]
316 AT_LAST_AND_ACTIVE_BIN, // [AT_LAST_BIN]
317 NEVER_BIN // [NEVER_BIN]
320 // Determine bin based on three categories of tiles: things we need now,
321 // things we need soon, and eventually.
322 inline ManagedTileBin BinFromTilePriority(const TilePriority& prio) {
323 if (prio.priority_bin == TilePriority::NOW)
324 return NOW_BIN;
326 if (prio.priority_bin == TilePriority::SOON)
327 return SOON_BIN;
329 if (prio.distance_to_visible == std::numeric_limits<float>::infinity())
330 return NEVER_BIN;
332 return EVENTUALLY_BIN;
335 } // namespace
337 RasterTaskCompletionStats::RasterTaskCompletionStats()
338 : completed_count(0u), canceled_count(0u) {}
340 scoped_refptr<base::debug::ConvertableToTraceFormat>
341 RasterTaskCompletionStatsAsValue(const RasterTaskCompletionStats& stats) {
342 scoped_refptr<base::debug::TracedValue> state =
343 new base::debug::TracedValue();
344 state->SetInteger("completed_count", stats.completed_count);
345 state->SetInteger("canceled_count", stats.canceled_count);
346 return state;
349 // static
350 scoped_ptr<TileManager> TileManager::Create(
351 TileManagerClient* client,
352 base::SequencedTaskRunner* task_runner,
353 ResourcePool* resource_pool,
354 Rasterizer* rasterizer,
355 RenderingStatsInstrumentation* rendering_stats_instrumentation) {
356 return make_scoped_ptr(new TileManager(client,
357 task_runner,
358 resource_pool,
359 rasterizer,
360 rendering_stats_instrumentation));
363 TileManager::TileManager(
364 TileManagerClient* client,
365 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
366 ResourcePool* resource_pool,
367 Rasterizer* rasterizer,
368 RenderingStatsInstrumentation* rendering_stats_instrumentation)
369 : client_(client),
370 task_runner_(task_runner),
371 resource_pool_(resource_pool),
372 rasterizer_(rasterizer),
373 prioritized_tiles_dirty_(false),
374 all_tiles_that_need_to_be_rasterized_have_memory_(true),
375 all_tiles_required_for_activation_have_memory_(true),
376 bytes_releasable_(0),
377 resources_releasable_(0),
378 ever_exceeded_memory_budget_(false),
379 rendering_stats_instrumentation_(rendering_stats_instrumentation),
380 did_initialize_visible_tile_(false),
381 did_check_for_completed_tasks_since_last_schedule_tasks_(true),
382 ready_to_activate_check_notifier_(
383 task_runner_.get(),
384 base::Bind(&TileManager::CheckIfReadyToActivate,
385 base::Unretained(this))) {
386 rasterizer_->SetClient(this);
389 TileManager::~TileManager() {
390 // Reset global state and manage. This should cause
391 // our memory usage to drop to zero.
392 global_state_ = GlobalStateThatImpactsTilePriority();
394 RasterTaskQueue empty;
395 rasterizer_->ScheduleTasks(&empty);
396 orphan_raster_tasks_.clear();
398 // This should finish all pending tasks and release any uninitialized
399 // resources.
400 rasterizer_->Shutdown();
401 rasterizer_->CheckForCompletedTasks();
403 prioritized_tiles_.Clear();
405 FreeResourcesForReleasedTiles();
406 CleanUpReleasedTiles();
408 DCHECK_EQ(0u, bytes_releasable_);
409 DCHECK_EQ(0u, resources_releasable_);
412 void TileManager::Release(Tile* tile) {
413 DCHECK(TilePriority() == tile->combined_priority());
415 prioritized_tiles_dirty_ = true;
416 released_tiles_.push_back(tile);
419 void TileManager::DidChangeTilePriority(Tile* tile) {
420 prioritized_tiles_dirty_ = true;
423 bool TileManager::ShouldForceTasksRequiredForActivationToComplete() const {
424 return global_state_.tree_priority != SMOOTHNESS_TAKES_PRIORITY;
427 void TileManager::FreeResourcesForReleasedTiles() {
428 for (std::vector<Tile*>::iterator it = released_tiles_.begin();
429 it != released_tiles_.end();
430 ++it) {
431 Tile* tile = *it;
432 FreeResourcesForTile(tile);
436 void TileManager::CleanUpReleasedTiles() {
437 // Make sure |prioritized_tiles_| doesn't contain any of the tiles
438 // we're about to delete.
439 DCHECK(prioritized_tiles_.IsEmpty());
441 std::vector<Tile*>::iterator it = released_tiles_.begin();
442 while (it != released_tiles_.end()) {
443 Tile* tile = *it;
445 if (tile->HasRasterTask()) {
446 ++it;
447 continue;
450 DCHECK(!tile->HasResources());
451 DCHECK(tiles_.find(tile->id()) != tiles_.end());
452 tiles_.erase(tile->id());
454 LayerCountMap::iterator layer_it =
455 used_layer_counts_.find(tile->layer_id());
456 DCHECK_GT(layer_it->second, 0);
457 if (--layer_it->second == 0) {
458 used_layer_counts_.erase(layer_it);
459 image_decode_tasks_.erase(tile->layer_id());
462 delete tile;
463 it = released_tiles_.erase(it);
467 void TileManager::UpdatePrioritizedTileSetIfNeeded() {
468 if (!prioritized_tiles_dirty_)
469 return;
471 prioritized_tiles_.Clear();
473 FreeResourcesForReleasedTiles();
474 CleanUpReleasedTiles();
476 GetTilesWithAssignedBins(&prioritized_tiles_);
477 prioritized_tiles_dirty_ = false;
480 void TileManager::DidFinishRunningTasks() {
481 TRACE_EVENT0("cc", "TileManager::DidFinishRunningTasks");
483 bool memory_usage_above_limit = resource_pool_->total_memory_usage_bytes() >
484 global_state_.soft_memory_limit_in_bytes;
486 // When OOM, keep re-assigning memory until we reach a steady state
487 // where top-priority tiles are initialized.
488 if (all_tiles_that_need_to_be_rasterized_have_memory_ &&
489 !memory_usage_above_limit)
490 return;
492 rasterizer_->CheckForCompletedTasks();
493 did_check_for_completed_tasks_since_last_schedule_tasks_ = true;
495 TileVector tiles_that_need_to_be_rasterized;
496 AssignGpuMemoryToTiles(&prioritized_tiles_,
497 &tiles_that_need_to_be_rasterized);
499 // |tiles_that_need_to_be_rasterized| will be empty when we reach a
500 // steady memory state. Keep scheduling tasks until we reach this state.
501 if (!tiles_that_need_to_be_rasterized.empty()) {
502 ScheduleTasks(tiles_that_need_to_be_rasterized);
503 return;
506 FreeResourcesForReleasedTiles();
508 resource_pool_->ReduceResourceUsage();
510 // We don't reserve memory for required-for-activation tiles during
511 // accelerated gestures, so we just postpone activation when we don't
512 // have these tiles, and activate after the accelerated gesture.
513 bool allow_rasterize_on_demand =
514 global_state_.tree_priority != SMOOTHNESS_TAKES_PRIORITY;
516 // Use on-demand raster for any required-for-activation tiles that have not
517 // been been assigned memory after reaching a steady memory state. This
518 // ensures that we activate even when OOM.
519 for (TileMap::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
520 Tile* tile = it->second;
521 ManagedTileState& mts = tile->managed_state();
522 ManagedTileState::TileVersion& tile_version =
523 mts.tile_versions[mts.raster_mode];
525 if (tile->required_for_activation() && !tile_version.IsReadyToDraw()) {
526 // If we can't raster on demand, give up early (and don't activate).
527 if (!allow_rasterize_on_demand)
528 return;
530 tile_version.set_rasterize_on_demand();
531 client_->NotifyTileStateChanged(tile);
535 DCHECK(IsReadyToActivate());
536 ready_to_activate_check_notifier_.Schedule();
539 void TileManager::DidFinishRunningTasksRequiredForActivation() {
540 // This is only a true indication that all tiles required for
541 // activation are initialized when no tiles are OOM. We need to
542 // wait for DidFinishRunningTasks() to be called, try to re-assign
543 // memory and in worst case use on-demand raster when tiles
544 // required for activation are OOM.
545 if (!all_tiles_required_for_activation_have_memory_)
546 return;
548 ready_to_activate_check_notifier_.Schedule();
551 void TileManager::GetTilesWithAssignedBins(PrioritizedTileSet* tiles) {
552 TRACE_EVENT0("cc", "TileManager::GetTilesWithAssignedBins");
554 const TileMemoryLimitPolicy memory_policy = global_state_.memory_limit_policy;
555 const TreePriority tree_priority = global_state_.tree_priority;
557 // For each tree, bin into different categories of tiles.
558 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
559 Tile* tile = it->second;
560 ManagedTileState& mts = tile->managed_state();
562 const ManagedTileState::TileVersion& tile_version =
563 tile->GetTileVersionForDrawing();
564 bool tile_is_ready_to_draw = tile_version.IsReadyToDraw();
565 bool tile_is_active = tile_is_ready_to_draw ||
566 mts.tile_versions[mts.raster_mode].raster_task_.get();
568 // Get the active priority and bin.
569 TilePriority active_priority = tile->priority(ACTIVE_TREE);
570 ManagedTileBin active_bin = BinFromTilePriority(active_priority);
572 // Get the pending priority and bin.
573 TilePriority pending_priority = tile->priority(PENDING_TREE);
574 ManagedTileBin pending_bin = BinFromTilePriority(pending_priority);
576 bool pending_is_low_res = pending_priority.resolution == LOW_RESOLUTION;
577 bool pending_is_non_ideal =
578 pending_priority.resolution == NON_IDEAL_RESOLUTION;
579 bool active_is_non_ideal =
580 active_priority.resolution == NON_IDEAL_RESOLUTION;
582 // Adjust bin state based on if ready to draw.
583 active_bin = kBinReadyToDrawMap[tile_is_ready_to_draw][active_bin];
584 pending_bin = kBinReadyToDrawMap[tile_is_ready_to_draw][pending_bin];
586 // Adjust bin state based on if active.
587 active_bin = kBinIsActiveMap[tile_is_active][active_bin];
588 pending_bin = kBinIsActiveMap[tile_is_active][pending_bin];
590 // We never want to paint new non-ideal tiles, as we always have
591 // a high-res tile covering that content (paint that instead).
592 if (!tile_is_ready_to_draw && active_is_non_ideal)
593 active_bin = NEVER_BIN;
594 if (!tile_is_ready_to_draw && pending_is_non_ideal)
595 pending_bin = NEVER_BIN;
597 ManagedTileBin tree_bin[NUM_TREES];
598 tree_bin[ACTIVE_TREE] = kBinPolicyMap[memory_policy][active_bin];
599 tree_bin[PENDING_TREE] = kBinPolicyMap[memory_policy][pending_bin];
601 // Adjust pending bin state for low res tiles. This prevents pending tree
602 // low-res tiles from being initialized before high-res tiles.
603 if (pending_is_low_res)
604 tree_bin[PENDING_TREE] = std::max(tree_bin[PENDING_TREE], EVENTUALLY_BIN);
606 TilePriority tile_priority;
607 switch (tree_priority) {
608 case SAME_PRIORITY_FOR_BOTH_TREES:
609 mts.bin = std::min(tree_bin[ACTIVE_TREE], tree_bin[PENDING_TREE]);
610 tile_priority = tile->combined_priority();
611 break;
612 case SMOOTHNESS_TAKES_PRIORITY:
613 mts.bin = tree_bin[ACTIVE_TREE];
614 tile_priority = active_priority;
615 break;
616 case NEW_CONTENT_TAKES_PRIORITY:
617 mts.bin = tree_bin[PENDING_TREE];
618 tile_priority = pending_priority;
619 break;
620 default:
621 NOTREACHED();
624 // Bump up the priority if we determined it's NEVER_BIN on one tree,
625 // but is still required on the other tree.
626 bool is_in_never_bin_on_both_trees = tree_bin[ACTIVE_TREE] == NEVER_BIN &&
627 tree_bin[PENDING_TREE] == NEVER_BIN;
629 if (mts.bin == NEVER_BIN && !is_in_never_bin_on_both_trees)
630 mts.bin = tile_is_active ? AT_LAST_AND_ACTIVE_BIN : AT_LAST_BIN;
632 mts.resolution = tile_priority.resolution;
633 mts.priority_bin = tile_priority.priority_bin;
634 mts.distance_to_visible = tile_priority.distance_to_visible;
635 mts.required_for_activation = tile_priority.required_for_activation;
637 mts.visible_and_ready_to_draw =
638 tree_bin[ACTIVE_TREE] == NOW_AND_READY_TO_DRAW_BIN;
640 // Tiles that are required for activation shouldn't be in NEVER_BIN unless
641 // smoothness takes priority or memory policy allows nothing to be
642 // initialized.
643 DCHECK(!mts.required_for_activation || mts.bin != NEVER_BIN ||
644 tree_priority == SMOOTHNESS_TAKES_PRIORITY ||
645 memory_policy == ALLOW_NOTHING);
647 // If the tile is in NEVER_BIN and it does not have an active task, then we
648 // can release the resources early. If it does have the task however, we
649 // should keep it in the prioritized tile set to ensure that AssignGpuMemory
650 // can visit it.
651 if (mts.bin == NEVER_BIN &&
652 !mts.tile_versions[mts.raster_mode].raster_task_.get()) {
653 FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(tile);
654 continue;
657 // Insert the tile into a priority set.
658 tiles->InsertTile(tile, mts.bin);
662 void TileManager::ManageTiles(const GlobalStateThatImpactsTilePriority& state) {
663 TRACE_EVENT0("cc", "TileManager::ManageTiles");
665 // Update internal state.
666 if (state != global_state_) {
667 global_state_ = state;
668 prioritized_tiles_dirty_ = true;
671 // We need to call CheckForCompletedTasks() once in-between each call
672 // to ScheduleTasks() to prevent canceled tasks from being scheduled.
673 if (!did_check_for_completed_tasks_since_last_schedule_tasks_) {
674 rasterizer_->CheckForCompletedTasks();
675 did_check_for_completed_tasks_since_last_schedule_tasks_ = true;
678 UpdatePrioritizedTileSetIfNeeded();
680 TileVector tiles_that_need_to_be_rasterized;
681 AssignGpuMemoryToTiles(&prioritized_tiles_,
682 &tiles_that_need_to_be_rasterized);
684 // Finally, schedule rasterizer tasks.
685 ScheduleTasks(tiles_that_need_to_be_rasterized);
687 TRACE_EVENT_INSTANT1("cc",
688 "DidManage",
689 TRACE_EVENT_SCOPE_THREAD,
690 "state",
691 BasicStateAsValue());
693 TRACE_COUNTER_ID1("cc",
694 "unused_memory_bytes",
695 this,
696 resource_pool_->total_memory_usage_bytes() -
697 resource_pool_->acquired_memory_usage_bytes());
700 bool TileManager::UpdateVisibleTiles() {
701 TRACE_EVENT0("cc", "TileManager::UpdateVisibleTiles");
703 rasterizer_->CheckForCompletedTasks();
704 did_check_for_completed_tasks_since_last_schedule_tasks_ = true;
706 TRACE_EVENT_INSTANT1(
707 "cc",
708 "DidUpdateVisibleTiles",
709 TRACE_EVENT_SCOPE_THREAD,
710 "stats",
711 RasterTaskCompletionStatsAsValue(update_visible_tiles_stats_));
712 update_visible_tiles_stats_ = RasterTaskCompletionStats();
714 bool did_initialize_visible_tile = did_initialize_visible_tile_;
715 did_initialize_visible_tile_ = false;
716 return did_initialize_visible_tile;
719 scoped_refptr<base::debug::ConvertableToTraceFormat>
720 TileManager::BasicStateAsValue() const {
721 scoped_refptr<base::debug::TracedValue> value =
722 new base::debug::TracedValue();
723 BasicStateAsValueInto(value.get());
724 return value;
727 void TileManager::BasicStateAsValueInto(base::debug::TracedValue* state) const {
728 state->SetInteger("tile_count", tiles_.size());
729 state->BeginDictionary("global_state");
730 global_state_.AsValueInto(state);
731 state->EndDictionary();
734 void TileManager::AssignGpuMemoryToTiles(
735 PrioritizedTileSet* tiles,
736 TileVector* tiles_that_need_to_be_rasterized) {
737 TRACE_EVENT0("cc", "TileManager::AssignGpuMemoryToTiles");
739 // Maintain the list of released resources that can potentially be re-used
740 // or deleted.
741 // If this operation becomes expensive too, only do this after some
742 // resource(s) was returned. Note that in that case, one also need to
743 // invalidate when releasing some resource from the pool.
744 resource_pool_->CheckBusyResources();
746 // Now give memory out to the tiles until we're out, and build
747 // the needs-to-be-rasterized queue.
748 all_tiles_that_need_to_be_rasterized_have_memory_ = true;
749 all_tiles_required_for_activation_have_memory_ = true;
751 // Cast to prevent overflow.
752 int64 soft_bytes_available =
753 static_cast<int64>(bytes_releasable_) +
754 static_cast<int64>(global_state_.soft_memory_limit_in_bytes) -
755 static_cast<int64>(resource_pool_->acquired_memory_usage_bytes());
756 int64 hard_bytes_available =
757 static_cast<int64>(bytes_releasable_) +
758 static_cast<int64>(global_state_.hard_memory_limit_in_bytes) -
759 static_cast<int64>(resource_pool_->acquired_memory_usage_bytes());
760 int resources_available = resources_releasable_ +
761 global_state_.num_resources_limit -
762 resource_pool_->acquired_resource_count();
763 size_t soft_bytes_allocatable =
764 std::max(static_cast<int64>(0), soft_bytes_available);
765 size_t hard_bytes_allocatable =
766 std::max(static_cast<int64>(0), hard_bytes_available);
767 size_t resources_allocatable = std::max(0, resources_available);
769 size_t bytes_that_exceeded_memory_budget = 0;
770 size_t soft_bytes_left = soft_bytes_allocatable;
771 size_t hard_bytes_left = hard_bytes_allocatable;
773 size_t resources_left = resources_allocatable;
774 bool oomed_soft = false;
775 bool oomed_hard = false;
776 bool have_hit_soft_memory = false; // Soft memory comes after hard.
778 unsigned schedule_priority = 1u;
779 for (PrioritizedTileSet::Iterator it(tiles, true); it; ++it) {
780 Tile* tile = *it;
781 ManagedTileState& mts = tile->managed_state();
783 mts.scheduled_priority = schedule_priority++;
785 mts.raster_mode = tile->DetermineOverallRasterMode();
787 ManagedTileState::TileVersion& tile_version =
788 mts.tile_versions[mts.raster_mode];
790 // If this tile doesn't need a resource, then nothing to do.
791 if (!tile_version.requires_resource())
792 continue;
794 // If the tile is not needed, free it up.
795 if (mts.bin == NEVER_BIN) {
796 FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(tile);
797 continue;
800 const bool tile_uses_hard_limit = mts.bin <= NOW_BIN;
801 const size_t bytes_if_allocated = BytesConsumedIfAllocated(tile);
802 const size_t tile_bytes_left =
803 (tile_uses_hard_limit) ? hard_bytes_left : soft_bytes_left;
805 // Hard-limit is reserved for tiles that would cause a calamity
806 // if they were to go away, so by definition they are the highest
807 // priority memory, and must be at the front of the list.
808 DCHECK(!(have_hit_soft_memory && tile_uses_hard_limit));
809 have_hit_soft_memory |= !tile_uses_hard_limit;
811 size_t tile_bytes = 0;
812 size_t tile_resources = 0;
814 // It costs to maintain a resource.
815 for (int mode = 0; mode < NUM_RASTER_MODES; ++mode) {
816 if (mts.tile_versions[mode].resource_) {
817 tile_bytes += bytes_if_allocated;
818 tile_resources++;
822 // Allow lower priority tiles with initialized resources to keep
823 // their memory by only assigning memory to new raster tasks if
824 // they can be scheduled.
825 bool reached_scheduled_raster_tasks_limit =
826 tiles_that_need_to_be_rasterized->size() >= kScheduledRasterTasksLimit;
827 if (!reached_scheduled_raster_tasks_limit) {
828 // If we don't have the required version, and it's not in flight
829 // then we'll have to pay to create a new task.
830 if (!tile_version.resource_ && !tile_version.raster_task_.get()) {
831 tile_bytes += bytes_if_allocated;
832 tile_resources++;
836 // Tile is OOM.
837 if (tile_bytes > tile_bytes_left || tile_resources > resources_left) {
838 FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(tile);
840 // This tile was already on screen and now its resources have been
841 // released. In order to prevent checkerboarding, set this tile as
842 // rasterize on demand immediately.
843 if (mts.visible_and_ready_to_draw)
844 tile_version.set_rasterize_on_demand();
846 oomed_soft = true;
847 if (tile_uses_hard_limit) {
848 oomed_hard = true;
849 bytes_that_exceeded_memory_budget += tile_bytes;
851 } else {
852 resources_left -= tile_resources;
853 hard_bytes_left -= tile_bytes;
854 soft_bytes_left =
855 (soft_bytes_left > tile_bytes) ? soft_bytes_left - tile_bytes : 0;
856 if (tile_version.resource_)
857 continue;
860 DCHECK(!tile_version.resource_);
862 // Tile shouldn't be rasterized if |tiles_that_need_to_be_rasterized|
863 // has reached it's limit or we've failed to assign gpu memory to this
864 // or any higher priority tile. Preventing tiles that fit into memory
865 // budget to be rasterized when higher priority tile is oom is
866 // important for two reasons:
867 // 1. Tile size should not impact raster priority.
868 // 2. Tiles with existing raster task could otherwise incorrectly
869 // be added as they are not affected by |bytes_allocatable|.
870 bool can_schedule_tile =
871 !oomed_soft && !reached_scheduled_raster_tasks_limit;
873 if (!can_schedule_tile) {
874 all_tiles_that_need_to_be_rasterized_have_memory_ = false;
875 if (tile->required_for_activation())
876 all_tiles_required_for_activation_have_memory_ = false;
877 it.DisablePriorityOrdering();
878 continue;
881 tiles_that_need_to_be_rasterized->push_back(tile);
884 // OOM reporting uses hard-limit, soft-OOM is normal depending on limit.
885 ever_exceeded_memory_budget_ |= oomed_hard;
886 if (ever_exceeded_memory_budget_) {
887 TRACE_COUNTER_ID2("cc",
888 "over_memory_budget",
889 this,
890 "budget",
891 global_state_.hard_memory_limit_in_bytes,
892 "over",
893 bytes_that_exceeded_memory_budget);
895 UMA_HISTOGRAM_BOOLEAN("TileManager.ExceededMemoryBudget", oomed_hard);
896 memory_stats_from_last_assign_.total_budget_in_bytes =
897 global_state_.hard_memory_limit_in_bytes;
898 memory_stats_from_last_assign_.bytes_allocated =
899 hard_bytes_allocatable - hard_bytes_left;
900 memory_stats_from_last_assign_.bytes_unreleasable =
901 resource_pool_->acquired_memory_usage_bytes() - bytes_releasable_;
902 memory_stats_from_last_assign_.bytes_over = bytes_that_exceeded_memory_budget;
905 void TileManager::FreeResourceForTile(Tile* tile, RasterMode mode) {
906 ManagedTileState& mts = tile->managed_state();
907 if (mts.tile_versions[mode].resource_) {
908 resource_pool_->ReleaseResource(mts.tile_versions[mode].resource_.Pass());
910 DCHECK_GE(bytes_releasable_, BytesConsumedIfAllocated(tile));
911 DCHECK_GE(resources_releasable_, 1u);
913 bytes_releasable_ -= BytesConsumedIfAllocated(tile);
914 --resources_releasable_;
918 void TileManager::FreeResourcesForTile(Tile* tile) {
919 for (int mode = 0; mode < NUM_RASTER_MODES; ++mode) {
920 FreeResourceForTile(tile, static_cast<RasterMode>(mode));
924 void TileManager::FreeUnusedResourcesForTile(Tile* tile) {
925 DCHECK(tile->IsReadyToDraw());
926 ManagedTileState& mts = tile->managed_state();
927 RasterMode used_mode = LOW_QUALITY_RASTER_MODE;
928 for (int mode = 0; mode < NUM_RASTER_MODES; ++mode) {
929 if (mts.tile_versions[mode].IsReadyToDraw()) {
930 used_mode = static_cast<RasterMode>(mode);
931 break;
935 for (int mode = 0; mode < NUM_RASTER_MODES; ++mode) {
936 if (mode != used_mode)
937 FreeResourceForTile(tile, static_cast<RasterMode>(mode));
941 void TileManager::FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(
942 Tile* tile) {
943 bool was_ready_to_draw = tile->IsReadyToDraw();
944 FreeResourcesForTile(tile);
945 if (was_ready_to_draw)
946 client_->NotifyTileStateChanged(tile);
949 void TileManager::ScheduleTasks(
950 const TileVector& tiles_that_need_to_be_rasterized) {
951 TRACE_EVENT1("cc",
952 "TileManager::ScheduleTasks",
953 "count",
954 tiles_that_need_to_be_rasterized.size());
956 DCHECK(did_check_for_completed_tasks_since_last_schedule_tasks_);
958 raster_queue_.Reset();
960 // Build a new task queue containing all task currently needed. Tasks
961 // are added in order of priority, highest priority task first.
962 for (TileVector::const_iterator it = tiles_that_need_to_be_rasterized.begin();
963 it != tiles_that_need_to_be_rasterized.end();
964 ++it) {
965 Tile* tile = *it;
966 ManagedTileState& mts = tile->managed_state();
967 ManagedTileState::TileVersion& tile_version =
968 mts.tile_versions[mts.raster_mode];
970 DCHECK(tile_version.requires_resource());
971 DCHECK(!tile_version.resource_);
973 if (!tile_version.raster_task_.get())
974 tile_version.raster_task_ = CreateRasterTask(tile);
976 raster_queue_.items.push_back(RasterTaskQueue::Item(
977 tile_version.raster_task_.get(), tile->required_for_activation()));
978 raster_queue_.required_for_activation_count +=
979 tile->required_for_activation();
982 // We must reduce the amount of unused resoruces before calling
983 // ScheduleTasks to prevent usage from rising above limits.
984 resource_pool_->ReduceResourceUsage();
986 // Schedule running of |raster_tasks_|. This replaces any previously
987 // scheduled tasks and effectively cancels all tasks not present
988 // in |raster_tasks_|.
989 rasterizer_->ScheduleTasks(&raster_queue_);
991 // It's now safe to clean up orphan tasks as raster worker pool is not
992 // allowed to keep around unreferenced raster tasks after ScheduleTasks() has
993 // been called.
994 orphan_raster_tasks_.clear();
996 did_check_for_completed_tasks_since_last_schedule_tasks_ = false;
999 scoped_refptr<ImageDecodeTask> TileManager::CreateImageDecodeTask(
1000 Tile* tile,
1001 SkPixelRef* pixel_ref) {
1002 return make_scoped_refptr(new ImageDecodeTaskImpl(
1003 pixel_ref,
1004 tile->layer_id(),
1005 rendering_stats_instrumentation_,
1006 base::Bind(&TileManager::OnImageDecodeTaskCompleted,
1007 base::Unretained(this),
1008 tile->layer_id(),
1009 base::Unretained(pixel_ref))));
1012 scoped_refptr<RasterTask> TileManager::CreateRasterTask(Tile* tile) {
1013 ManagedTileState& mts = tile->managed_state();
1015 scoped_ptr<ScopedResource> resource =
1016 resource_pool_->AcquireResource(tile->size());
1017 const ScopedResource* const_resource = resource.get();
1019 // Create and queue all image decode tasks that this tile depends on.
1020 ImageDecodeTask::Vector decode_tasks;
1021 PixelRefTaskMap& existing_pixel_refs = image_decode_tasks_[tile->layer_id()];
1022 for (PicturePileImpl::PixelRefIterator iter(
1023 tile->content_rect(), tile->contents_scale(), tile->picture_pile());
1024 iter;
1025 ++iter) {
1026 SkPixelRef* pixel_ref = *iter;
1027 uint32_t id = pixel_ref->getGenerationID();
1029 // Append existing image decode task if available.
1030 PixelRefTaskMap::iterator decode_task_it = existing_pixel_refs.find(id);
1031 if (decode_task_it != existing_pixel_refs.end()) {
1032 decode_tasks.push_back(decode_task_it->second);
1033 continue;
1036 // Create and append new image decode task for this pixel ref.
1037 scoped_refptr<ImageDecodeTask> decode_task =
1038 CreateImageDecodeTask(tile, pixel_ref);
1039 decode_tasks.push_back(decode_task);
1040 existing_pixel_refs[id] = decode_task;
1043 return make_scoped_refptr(
1044 new RasterTaskImpl(const_resource,
1045 tile->picture_pile(),
1046 tile->content_rect(),
1047 tile->contents_scale(),
1048 mts.raster_mode,
1049 mts.resolution,
1050 tile->layer_id(),
1051 static_cast<const void*>(tile),
1052 tile->source_frame_number(),
1053 tile->use_picture_analysis(),
1054 rendering_stats_instrumentation_,
1055 base::Bind(&TileManager::OnRasterTaskCompleted,
1056 base::Unretained(this),
1057 tile->id(),
1058 base::Passed(&resource),
1059 mts.raster_mode),
1060 &decode_tasks));
1063 void TileManager::OnImageDecodeTaskCompleted(int layer_id,
1064 SkPixelRef* pixel_ref,
1065 bool was_canceled) {
1066 // If the task was canceled, we need to clean it up
1067 // from |image_decode_tasks_|.
1068 if (!was_canceled)
1069 return;
1071 LayerPixelRefTaskMap::iterator layer_it = image_decode_tasks_.find(layer_id);
1072 if (layer_it == image_decode_tasks_.end())
1073 return;
1075 PixelRefTaskMap& pixel_ref_tasks = layer_it->second;
1076 PixelRefTaskMap::iterator task_it =
1077 pixel_ref_tasks.find(pixel_ref->getGenerationID());
1079 if (task_it != pixel_ref_tasks.end())
1080 pixel_ref_tasks.erase(task_it);
1083 void TileManager::OnRasterTaskCompleted(
1084 Tile::Id tile_id,
1085 scoped_ptr<ScopedResource> resource,
1086 RasterMode raster_mode,
1087 const PicturePileImpl::Analysis& analysis,
1088 bool was_canceled) {
1089 DCHECK(tiles_.find(tile_id) != tiles_.end());
1091 Tile* tile = tiles_[tile_id];
1092 ManagedTileState& mts = tile->managed_state();
1093 ManagedTileState::TileVersion& tile_version = mts.tile_versions[raster_mode];
1094 DCHECK(tile_version.raster_task_.get());
1095 orphan_raster_tasks_.push_back(tile_version.raster_task_);
1096 tile_version.raster_task_ = NULL;
1098 if (was_canceled) {
1099 ++update_visible_tiles_stats_.canceled_count;
1100 resource_pool_->ReleaseResource(resource.Pass());
1101 return;
1104 ++update_visible_tiles_stats_.completed_count;
1106 if (analysis.is_solid_color) {
1107 tile_version.set_solid_color(analysis.solid_color);
1108 resource_pool_->ReleaseResource(resource.Pass());
1109 } else {
1110 tile_version.set_use_resource();
1111 tile_version.resource_ = resource.Pass();
1113 bytes_releasable_ += BytesConsumedIfAllocated(tile);
1114 ++resources_releasable_;
1117 FreeUnusedResourcesForTile(tile);
1118 if (tile->priority(ACTIVE_TREE).distance_to_visible == 0.f)
1119 did_initialize_visible_tile_ = true;
1121 client_->NotifyTileStateChanged(tile);
1124 scoped_refptr<Tile> TileManager::CreateTile(PicturePileImpl* picture_pile,
1125 const gfx::Size& tile_size,
1126 const gfx::Rect& content_rect,
1127 const gfx::Rect& opaque_rect,
1128 float contents_scale,
1129 int layer_id,
1130 int source_frame_number,
1131 int flags) {
1132 scoped_refptr<Tile> tile = make_scoped_refptr(new Tile(this,
1133 picture_pile,
1134 tile_size,
1135 content_rect,
1136 opaque_rect,
1137 contents_scale,
1138 layer_id,
1139 source_frame_number,
1140 flags));
1141 DCHECK(tiles_.find(tile->id()) == tiles_.end());
1143 tiles_[tile->id()] = tile.get();
1144 used_layer_counts_[tile->layer_id()]++;
1145 prioritized_tiles_dirty_ = true;
1146 return tile;
1149 void TileManager::SetRasterizerForTesting(Rasterizer* rasterizer) {
1150 rasterizer_ = rasterizer;
1151 rasterizer_->SetClient(this);
1154 bool TileManager::IsReadyToActivate() const {
1155 const std::vector<PictureLayerImpl*>& layers = client_->GetPictureLayers();
1157 for (std::vector<PictureLayerImpl*>::const_iterator it = layers.begin();
1158 it != layers.end();
1159 ++it) {
1160 if (!(*it)->AllTilesRequiredForActivationAreReadyToDraw())
1161 return false;
1164 return true;
1167 void TileManager::CheckIfReadyToActivate() {
1168 TRACE_EVENT0("cc", "TileManager::CheckIfReadyToActivate");
1170 rasterizer_->CheckForCompletedTasks();
1171 did_check_for_completed_tasks_since_last_schedule_tasks_ = true;
1173 if (IsReadyToActivate())
1174 client_->NotifyReadyToActivate();
1177 } // namespace cc