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"
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/rasterizer_delegate.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"
30 // Flag to indicate whether we should try and detect that
31 // a tile is of solid color.
32 const bool kUseColorEstimator
= true;
34 // Minimum width/height of a pile that would require analysis for tiles.
35 const int kMinDimensionsForAnalysis
= 256;
37 class DisableLCDTextFilter
: public SkDrawFilter
{
39 // SkDrawFilter interface.
40 virtual bool filter(SkPaint
* paint
, SkDrawFilter::Type type
) OVERRIDE
{
41 if (type
!= SkDrawFilter::kText_Type
)
44 paint
->setLCDRenderText(false);
49 class RasterTaskImpl
: public RasterTask
{
52 const Resource
* resource
,
53 PicturePileImpl
* picture_pile
,
54 const gfx::Rect
& content_rect
,
56 RasterMode raster_mode
,
57 TileResolution tile_resolution
,
60 int source_frame_number
,
62 RenderingStatsInstrumentation
* rendering_stats
,
63 const base::Callback
<void(const PicturePileImpl::Analysis
&, bool)>& reply
,
64 ImageDecodeTask::Vector
* dependencies
)
65 : RasterTask(resource
, dependencies
),
66 picture_pile_(picture_pile
),
67 content_rect_(content_rect
),
68 contents_scale_(contents_scale
),
69 raster_mode_(raster_mode
),
70 tile_resolution_(tile_resolution
),
73 source_frame_number_(source_frame_number
),
74 analyze_picture_(analyze_picture
),
75 rendering_stats_(rendering_stats
),
79 // Overridden from Task:
80 virtual void RunOnWorkerThread() OVERRIDE
{
81 TRACE_EVENT0("cc", "RasterizerTaskImpl::RunOnWorkerThread");
83 DCHECK(picture_pile_
);
85 AnalyzeAndRaster(picture_pile_
->GetCloneForDrawingOnThread(
86 RasterWorkerPool::GetPictureCloneIndexForCurrentThread()));
90 // Overridden from RasterizerTask:
91 virtual void ScheduleOnOriginThread(RasterizerTaskClient
* client
) OVERRIDE
{
93 canvas_
= client
->AcquireCanvasForRaster(this);
95 virtual void CompleteOnOriginThread(RasterizerTaskClient
* client
) OVERRIDE
{
97 client
->ReleaseCanvasForRaster(this);
99 virtual void RunReplyOnOriginThread() OVERRIDE
{
101 reply_
.Run(analysis_
, !HasFinishedRunning());
105 virtual ~RasterTaskImpl() { DCHECK(!canvas_
); }
108 void AnalyzeAndRaster(PicturePileImpl
* picture_pile
) {
109 DCHECK(picture_pile
);
112 if (analyze_picture_
) {
113 Analyze(picture_pile
);
114 if (analysis_
.is_solid_color
)
118 Raster(picture_pile
);
121 void Analyze(PicturePileImpl
* picture_pile
) {
122 frame_viewer_instrumentation::ScopedAnalyzeTask
analyze_task(
123 tile_id_
, tile_resolution_
, source_frame_number_
, layer_id_
);
125 DCHECK(picture_pile
);
127 picture_pile
->AnalyzeInRect(
128 content_rect_
, contents_scale_
, &analysis_
, rendering_stats_
);
130 // Record the solid color prediction.
131 UMA_HISTOGRAM_BOOLEAN("Renderer4.SolidColorTilesAnalyzed",
132 analysis_
.is_solid_color
);
134 // Clear the flag if we're not using the estimator.
135 analysis_
.is_solid_color
&= kUseColorEstimator
;
138 void Raster(PicturePileImpl
* picture_pile
) {
139 frame_viewer_instrumentation::ScopedRasterTask
raster_task(
142 source_frame_number_
,
145 devtools_instrumentation::ScopedLayerTask
layer_task(
146 devtools_instrumentation::kRasterTask
, layer_id_
);
148 skia::RefPtr
<SkDrawFilter
> draw_filter
;
149 switch (raster_mode_
) {
150 case LOW_QUALITY_RASTER_MODE
:
151 draw_filter
= skia::AdoptRef(new skia::PaintSimplifier
);
153 case HIGH_QUALITY_NO_LCD_RASTER_MODE
:
154 draw_filter
= skia::AdoptRef(new DisableLCDTextFilter
);
156 case HIGH_QUALITY_RASTER_MODE
:
158 case NUM_RASTER_MODES
:
162 canvas_
->setDrawFilter(draw_filter
.get());
164 base::TimeDelta prev_rasterize_time
=
165 rendering_stats_
->impl_thread_rendering_stats().rasterize_time
;
167 // Only record rasterization time for highres tiles, because
168 // lowres tiles are not required for activation and therefore
169 // introduce noise in the measurement (sometimes they get rasterized
170 // before we draw and sometimes they aren't)
171 RenderingStatsInstrumentation
* stats
=
172 tile_resolution_
== HIGH_RESOLUTION
? rendering_stats_
: NULL
;
173 DCHECK(picture_pile
);
174 picture_pile
->RasterToBitmap(
175 canvas_
, content_rect_
, contents_scale_
, stats
);
177 if (rendering_stats_
->record_rendering_stats()) {
178 base::TimeDelta current_rasterize_time
=
179 rendering_stats_
->impl_thread_rendering_stats().rasterize_time
;
180 HISTOGRAM_CUSTOM_COUNTS(
181 "Renderer4.PictureRasterTimeUS",
182 (current_rasterize_time
- prev_rasterize_time
).InMicroseconds(),
189 PicturePileImpl::Analysis analysis_
;
190 scoped_refptr
<PicturePileImpl
> picture_pile_
;
191 gfx::Rect content_rect_
;
192 float contents_scale_
;
193 RasterMode raster_mode_
;
194 TileResolution tile_resolution_
;
196 const void* tile_id_
;
197 int source_frame_number_
;
198 bool analyze_picture_
;
199 RenderingStatsInstrumentation
* rendering_stats_
;
200 const base::Callback
<void(const PicturePileImpl::Analysis
&, bool)> reply_
;
203 DISALLOW_COPY_AND_ASSIGN(RasterTaskImpl
);
206 class ImageDecodeTaskImpl
: public ImageDecodeTask
{
208 ImageDecodeTaskImpl(SkPixelRef
* pixel_ref
,
210 RenderingStatsInstrumentation
* rendering_stats
,
211 const base::Callback
<void(bool was_canceled
)>& reply
)
212 : pixel_ref_(skia::SharePtr(pixel_ref
)),
214 rendering_stats_(rendering_stats
),
217 // Overridden from Task:
218 virtual void RunOnWorkerThread() OVERRIDE
{
219 TRACE_EVENT0("cc", "ImageDecodeTaskImpl::RunOnWorkerThread");
221 devtools_instrumentation::ScopedImageDecodeTask
image_decode_task(
223 // This will cause the image referred to by pixel ref to be decoded.
224 pixel_ref_
->lockPixels();
225 pixel_ref_
->unlockPixels();
228 // Overridden from RasterizerTask:
229 virtual void ScheduleOnOriginThread(RasterizerTaskClient
* client
) OVERRIDE
{}
230 virtual void CompleteOnOriginThread(RasterizerTaskClient
* client
) OVERRIDE
{}
231 virtual void RunReplyOnOriginThread() OVERRIDE
{
232 reply_
.Run(!HasFinishedRunning());
236 virtual ~ImageDecodeTaskImpl() {}
239 skia::RefPtr
<SkPixelRef
> pixel_ref_
;
241 RenderingStatsInstrumentation
* rendering_stats_
;
242 const base::Callback
<void(bool was_canceled
)> reply_
;
244 DISALLOW_COPY_AND_ASSIGN(ImageDecodeTaskImpl
);
247 const size_t kScheduledRasterTasksLimit
= 32u;
249 // Memory limit policy works by mapping some bin states to the NEVER bin.
250 const ManagedTileBin kBinPolicyMap
[NUM_TILE_MEMORY_LIMIT_POLICIES
][NUM_BINS
] = {
252 {NEVER_BIN
, // [NOW_AND_READY_TO_DRAW_BIN]
253 NEVER_BIN
, // [NOW_BIN]
254 NEVER_BIN
, // [SOON_BIN]
255 NEVER_BIN
, // [EVENTUALLY_AND_ACTIVE_BIN]
256 NEVER_BIN
, // [EVENTUALLY_BIN]
257 NEVER_BIN
, // [AT_LAST_AND_ACTIVE_BIN]
258 NEVER_BIN
, // [AT_LAST_BIN]
259 NEVER_BIN
// [NEVER_BIN]
261 // [ALLOW_ABSOLUTE_MINIMUM]
262 {NOW_AND_READY_TO_DRAW_BIN
, // [NOW_AND_READY_TO_DRAW_BIN]
263 NOW_BIN
, // [NOW_BIN]
264 NEVER_BIN
, // [SOON_BIN]
265 NEVER_BIN
, // [EVENTUALLY_AND_ACTIVE_BIN]
266 NEVER_BIN
, // [EVENTUALLY_BIN]
267 NEVER_BIN
, // [AT_LAST_AND_ACTIVE_BIN]
268 NEVER_BIN
, // [AT_LAST_BIN]
269 NEVER_BIN
// [NEVER_BIN]
271 // [ALLOW_PREPAINT_ONLY]
272 {NOW_AND_READY_TO_DRAW_BIN
, // [NOW_AND_READY_TO_DRAW_BIN]
273 NOW_BIN
, // [NOW_BIN]
274 SOON_BIN
, // [SOON_BIN]
275 NEVER_BIN
, // [EVENTUALLY_AND_ACTIVE_BIN]
276 NEVER_BIN
, // [EVENTUALLY_BIN]
277 NEVER_BIN
, // [AT_LAST_AND_ACTIVE_BIN]
278 NEVER_BIN
, // [AT_LAST_BIN]
279 NEVER_BIN
// [NEVER_BIN]
282 {NOW_AND_READY_TO_DRAW_BIN
, // [NOW_AND_READY_TO_DRAW_BIN]
283 NOW_BIN
, // [NOW_BIN]
284 SOON_BIN
, // [SOON_BIN]
285 EVENTUALLY_AND_ACTIVE_BIN
, // [EVENTUALLY_AND_ACTIVE_BIN]
286 EVENTUALLY_BIN
, // [EVENTUALLY_BIN]
287 AT_LAST_AND_ACTIVE_BIN
, // [AT_LAST_AND_ACTIVE_BIN]
288 AT_LAST_BIN
, // [AT_LAST_BIN]
289 NEVER_BIN
// [NEVER_BIN]
292 // Ready to draw works by mapping NOW_BIN to NOW_AND_READY_TO_DRAW_BIN.
293 const ManagedTileBin kBinReadyToDrawMap
[2][NUM_BINS
] = {
295 {NOW_AND_READY_TO_DRAW_BIN
, // [NOW_AND_READY_TO_DRAW_BIN]
296 NOW_BIN
, // [NOW_BIN]
297 SOON_BIN
, // [SOON_BIN]
298 EVENTUALLY_AND_ACTIVE_BIN
, // [EVENTUALLY_AND_ACTIVE_BIN]
299 EVENTUALLY_BIN
, // [EVENTUALLY_BIN]
300 AT_LAST_AND_ACTIVE_BIN
, // [AT_LAST_AND_ACTIVE_BIN]
301 AT_LAST_BIN
, // [AT_LAST_BIN]
302 NEVER_BIN
// [NEVER_BIN]
305 {NOW_AND_READY_TO_DRAW_BIN
, // [NOW_AND_READY_TO_DRAW_BIN]
306 NOW_AND_READY_TO_DRAW_BIN
, // [NOW_BIN]
307 SOON_BIN
, // [SOON_BIN]
308 EVENTUALLY_AND_ACTIVE_BIN
, // [EVENTUALLY_AND_ACTIVE_BIN]
309 EVENTUALLY_BIN
, // [EVENTUALLY_BIN]
310 AT_LAST_AND_ACTIVE_BIN
, // [AT_LAST_AND_ACTIVE_BIN]
311 AT_LAST_BIN
, // [AT_LAST_BIN]
312 NEVER_BIN
// [NEVER_BIN]
315 // Active works by mapping some bin stats to equivalent _ACTIVE_BIN state.
316 const ManagedTileBin kBinIsActiveMap
[2][NUM_BINS
] = {
318 {NOW_AND_READY_TO_DRAW_BIN
, // [NOW_AND_READY_TO_DRAW_BIN]
319 NOW_BIN
, // [NOW_BIN]
320 SOON_BIN
, // [SOON_BIN]
321 EVENTUALLY_AND_ACTIVE_BIN
, // [EVENTUALLY_AND_ACTIVE_BIN]
322 EVENTUALLY_BIN
, // [EVENTUALLY_BIN]
323 AT_LAST_AND_ACTIVE_BIN
, // [AT_LAST_AND_ACTIVE_BIN]
324 AT_LAST_BIN
, // [AT_LAST_BIN]
325 NEVER_BIN
// [NEVER_BIN]
328 {NOW_AND_READY_TO_DRAW_BIN
, // [NOW_AND_READY_TO_DRAW_BIN]
329 NOW_BIN
, // [NOW_BIN]
330 SOON_BIN
, // [SOON_BIN]
331 EVENTUALLY_AND_ACTIVE_BIN
, // [EVENTUALLY_AND_ACTIVE_BIN]
332 EVENTUALLY_AND_ACTIVE_BIN
, // [EVENTUALLY_BIN]
333 AT_LAST_AND_ACTIVE_BIN
, // [AT_LAST_AND_ACTIVE_BIN]
334 AT_LAST_AND_ACTIVE_BIN
, // [AT_LAST_BIN]
335 NEVER_BIN
// [NEVER_BIN]
338 // Determine bin based on three categories of tiles: things we need now,
339 // things we need soon, and eventually.
340 inline ManagedTileBin
BinFromTilePriority(const TilePriority
& prio
) {
341 const float kBackflingGuardDistancePixels
= 314.0f
;
343 if (prio
.priority_bin
== TilePriority::NOW
)
346 if (prio
.priority_bin
== TilePriority::SOON
||
347 prio
.distance_to_visible
< kBackflingGuardDistancePixels
)
350 if (prio
.distance_to_visible
== std::numeric_limits
<float>::infinity())
353 return EVENTUALLY_BIN
;
358 RasterTaskCompletionStats::RasterTaskCompletionStats()
359 : completed_count(0u), canceled_count(0u) {}
361 scoped_ptr
<base::Value
> RasterTaskCompletionStatsAsValue(
362 const RasterTaskCompletionStats
& stats
) {
363 scoped_ptr
<base::DictionaryValue
> state(new base::DictionaryValue());
364 state
->SetInteger("completed_count", stats
.completed_count
);
365 state
->SetInteger("canceled_count", stats
.canceled_count
);
366 return state
.PassAs
<base::Value
>();
370 scoped_ptr
<TileManager
> TileManager::Create(
371 TileManagerClient
* client
,
372 ResourcePool
* resource_pool
,
373 Rasterizer
* rasterizer
,
374 Rasterizer
* gpu_rasterizer
,
375 size_t max_raster_usage_bytes
,
376 bool use_rasterize_on_demand
,
377 RenderingStatsInstrumentation
* rendering_stats_instrumentation
) {
378 return make_scoped_ptr(new TileManager(client
,
382 max_raster_usage_bytes
,
383 use_rasterize_on_demand
,
384 rendering_stats_instrumentation
));
387 TileManager::TileManager(
388 TileManagerClient
* client
,
389 ResourcePool
* resource_pool
,
390 Rasterizer
* rasterizer
,
391 Rasterizer
* gpu_rasterizer
,
392 size_t max_raster_usage_bytes
,
393 bool use_rasterize_on_demand
,
394 RenderingStatsInstrumentation
* rendering_stats_instrumentation
)
396 resource_pool_(resource_pool
),
397 prioritized_tiles_dirty_(false),
398 all_tiles_that_need_to_be_rasterized_have_memory_(true),
399 all_tiles_required_for_activation_have_memory_(true),
400 memory_required_bytes_(0),
401 memory_nice_to_have_bytes_(0),
402 bytes_releasable_(0),
403 resources_releasable_(0),
404 max_raster_usage_bytes_(max_raster_usage_bytes
),
405 ever_exceeded_memory_budget_(false),
406 rendering_stats_instrumentation_(rendering_stats_instrumentation
),
407 did_initialize_visible_tile_(false),
408 did_check_for_completed_tasks_since_last_schedule_tasks_(true),
409 use_rasterize_on_demand_(use_rasterize_on_demand
) {
410 Rasterizer
* rasterizers
[NUM_RASTERIZER_TYPES
] = {
411 rasterizer
, // RASTERIZER_TYPE_DEFAULT
412 gpu_rasterizer
, // RASTERIZER_TYPE_GPU
414 rasterizer_delegate_
=
415 RasterizerDelegate::Create(this, rasterizers
, arraysize(rasterizers
));
418 TileManager::~TileManager() {
419 // Reset global state and manage. This should cause
420 // our memory usage to drop to zero.
421 global_state_
= GlobalStateThatImpactsTilePriority();
423 CleanUpReleasedTiles();
424 DCHECK_EQ(0u, tiles_
.size());
426 RasterTaskQueue empty
[NUM_RASTERIZER_TYPES
];
427 rasterizer_delegate_
->ScheduleTasks(empty
);
428 orphan_raster_tasks_
.clear();
430 // This should finish all pending tasks and release any uninitialized
432 rasterizer_delegate_
->Shutdown();
433 rasterizer_delegate_
->CheckForCompletedTasks();
435 DCHECK_EQ(0u, bytes_releasable_
);
436 DCHECK_EQ(0u, resources_releasable_
);
438 for (std::vector
<PictureLayerImpl
*>::iterator it
= layers_
.begin();
441 (*it
)->DidUnregisterLayer();
446 void TileManager::Release(Tile
* tile
) {
447 prioritized_tiles_dirty_
= true;
448 released_tiles_
.push_back(tile
);
451 void TileManager::DidChangeTilePriority(Tile
* tile
) {
452 prioritized_tiles_dirty_
= true;
455 bool TileManager::ShouldForceTasksRequiredForActivationToComplete() const {
456 return global_state_
.tree_priority
!= SMOOTHNESS_TAKES_PRIORITY
;
459 void TileManager::CleanUpReleasedTiles() {
460 for (std::vector
<Tile
*>::iterator it
= released_tiles_
.begin();
461 it
!= released_tiles_
.end();
464 ManagedTileState
& mts
= tile
->managed_state();
466 for (int mode
= 0; mode
< NUM_RASTER_MODES
; ++mode
) {
467 FreeResourceForTile(tile
, static_cast<RasterMode
>(mode
));
468 orphan_raster_tasks_
.push_back(mts
.tile_versions
[mode
].raster_task_
);
471 DCHECK(tiles_
.find(tile
->id()) != tiles_
.end());
472 tiles_
.erase(tile
->id());
474 LayerCountMap::iterator layer_it
=
475 used_layer_counts_
.find(tile
->layer_id());
476 DCHECK_GT(layer_it
->second
, 0);
477 if (--layer_it
->second
== 0) {
478 used_layer_counts_
.erase(layer_it
);
479 image_decode_tasks_
.erase(tile
->layer_id());
485 released_tiles_
.clear();
488 void TileManager::UpdatePrioritizedTileSetIfNeeded() {
489 if (!prioritized_tiles_dirty_
)
492 CleanUpReleasedTiles();
494 prioritized_tiles_
.Clear();
495 GetTilesWithAssignedBins(&prioritized_tiles_
);
496 prioritized_tiles_dirty_
= false;
499 void TileManager::DidFinishRunningTasks() {
500 TRACE_EVENT0("cc", "TileManager::DidFinishRunningTasks");
502 bool memory_usage_above_limit
= resource_pool_
->total_memory_usage_bytes() >
503 global_state_
.soft_memory_limit_in_bytes
;
505 // When OOM, keep re-assigning memory until we reach a steady state
506 // where top-priority tiles are initialized.
507 if (all_tiles_that_need_to_be_rasterized_have_memory_
&&
508 !memory_usage_above_limit
)
511 rasterizer_delegate_
->CheckForCompletedTasks();
512 did_check_for_completed_tasks_since_last_schedule_tasks_
= true;
514 TileVector tiles_that_need_to_be_rasterized
;
515 AssignGpuMemoryToTiles(&prioritized_tiles_
,
516 &tiles_that_need_to_be_rasterized
);
518 // |tiles_that_need_to_be_rasterized| will be empty when we reach a
519 // steady memory state. Keep scheduling tasks until we reach this state.
520 if (!tiles_that_need_to_be_rasterized
.empty()) {
521 ScheduleTasks(tiles_that_need_to_be_rasterized
);
525 resource_pool_
->ReduceResourceUsage();
527 // We don't reserve memory for required-for-activation tiles during
528 // accelerated gestures, so we just postpone activation when we don't
529 // have these tiles, and activate after the accelerated gesture.
530 bool allow_rasterize_on_demand
=
531 global_state_
.tree_priority
!= SMOOTHNESS_TAKES_PRIORITY
;
533 // Use on-demand raster for any required-for-activation tiles that have not
534 // been been assigned memory after reaching a steady memory state. This
535 // ensures that we activate even when OOM.
536 for (TileMap::iterator it
= tiles_
.begin(); it
!= tiles_
.end(); ++it
) {
537 Tile
* tile
= it
->second
;
538 ManagedTileState
& mts
= tile
->managed_state();
539 ManagedTileState::TileVersion
& tile_version
=
540 mts
.tile_versions
[mts
.raster_mode
];
542 if (tile
->required_for_activation() && !tile_version
.IsReadyToDraw()) {
543 // If we can't raster on demand, give up early (and don't activate).
544 if (!allow_rasterize_on_demand
)
546 if (use_rasterize_on_demand_
)
547 tile_version
.set_rasterize_on_demand();
551 client_
->NotifyReadyToActivate();
554 void TileManager::DidFinishRunningTasksRequiredForActivation() {
555 // This is only a true indication that all tiles required for
556 // activation are initialized when no tiles are OOM. We need to
557 // wait for DidFinishRunningTasks() to be called, try to re-assign
558 // memory and in worst case use on-demand raster when tiles
559 // required for activation are OOM.
560 if (!all_tiles_required_for_activation_have_memory_
)
563 client_
->NotifyReadyToActivate();
566 void TileManager::GetTilesWithAssignedBins(PrioritizedTileSet
* tiles
) {
567 TRACE_EVENT0("cc", "TileManager::GetTilesWithAssignedBins");
569 // Compute new stats to be return by GetMemoryStats().
570 memory_required_bytes_
= 0;
571 memory_nice_to_have_bytes_
= 0;
573 const TileMemoryLimitPolicy memory_policy
= global_state_
.memory_limit_policy
;
574 const TreePriority tree_priority
= global_state_
.tree_priority
;
576 // For each tree, bin into different categories of tiles.
577 for (TileMap::const_iterator it
= tiles_
.begin(); it
!= tiles_
.end(); ++it
) {
578 Tile
* tile
= it
->second
;
579 ManagedTileState
& mts
= tile
->managed_state();
581 const ManagedTileState::TileVersion
& tile_version
=
582 tile
->GetTileVersionForDrawing();
583 bool tile_is_ready_to_draw
= tile_version
.IsReadyToDraw();
584 bool tile_is_active
= tile_is_ready_to_draw
||
585 mts
.tile_versions
[mts
.raster_mode
].raster_task_
;
587 // Get the active priority and bin.
588 TilePriority active_priority
= tile
->priority(ACTIVE_TREE
);
589 ManagedTileBin active_bin
= BinFromTilePriority(active_priority
);
591 // Get the pending priority and bin.
592 TilePriority pending_priority
= tile
->priority(PENDING_TREE
);
593 ManagedTileBin pending_bin
= BinFromTilePriority(pending_priority
);
595 bool pending_is_low_res
= pending_priority
.resolution
== LOW_RESOLUTION
;
596 bool pending_is_non_ideal
=
597 pending_priority
.resolution
== NON_IDEAL_RESOLUTION
;
598 bool active_is_non_ideal
=
599 active_priority
.resolution
== NON_IDEAL_RESOLUTION
;
601 // Adjust pending bin state for low res tiles. This prevents
602 // pending tree low-res tiles from being initialized before
604 if (pending_is_low_res
)
605 pending_bin
= std::max(pending_bin
, EVENTUALLY_BIN
);
607 // Adjust bin state based on if ready to draw.
608 active_bin
= kBinReadyToDrawMap
[tile_is_ready_to_draw
][active_bin
];
609 pending_bin
= kBinReadyToDrawMap
[tile_is_ready_to_draw
][pending_bin
];
611 // Adjust bin state based on if active.
612 active_bin
= kBinIsActiveMap
[tile_is_active
][active_bin
];
613 pending_bin
= kBinIsActiveMap
[tile_is_active
][pending_bin
];
615 // We never want to paint new non-ideal tiles, as we always have
616 // a high-res tile covering that content (paint that instead).
617 if (!tile_is_ready_to_draw
&& active_is_non_ideal
)
618 active_bin
= NEVER_BIN
;
619 if (!tile_is_ready_to_draw
&& pending_is_non_ideal
)
620 pending_bin
= NEVER_BIN
;
622 // Compute combined bin.
623 ManagedTileBin combined_bin
= std::min(active_bin
, pending_bin
);
625 if (!tile_is_ready_to_draw
|| tile_version
.requires_resource()) {
626 // The bin that the tile would have if the GPU memory manager had
627 // a maximally permissive policy, send to the GPU memory manager
628 // to determine policy.
629 ManagedTileBin gpu_memmgr_stats_bin
= combined_bin
;
630 if ((gpu_memmgr_stats_bin
== NOW_BIN
) ||
631 (gpu_memmgr_stats_bin
== NOW_AND_READY_TO_DRAW_BIN
))
632 memory_required_bytes_
+= BytesConsumedIfAllocated(tile
);
633 if (gpu_memmgr_stats_bin
!= NEVER_BIN
)
634 memory_nice_to_have_bytes_
+= BytesConsumedIfAllocated(tile
);
637 ManagedTileBin tree_bin
[NUM_TREES
];
638 tree_bin
[ACTIVE_TREE
] = kBinPolicyMap
[memory_policy
][active_bin
];
639 tree_bin
[PENDING_TREE
] = kBinPolicyMap
[memory_policy
][pending_bin
];
641 TilePriority tile_priority
;
642 switch (tree_priority
) {
643 case SAME_PRIORITY_FOR_BOTH_TREES
:
644 mts
.bin
= kBinPolicyMap
[memory_policy
][combined_bin
];
645 tile_priority
= tile
->combined_priority();
647 case SMOOTHNESS_TAKES_PRIORITY
:
648 mts
.bin
= tree_bin
[ACTIVE_TREE
];
649 tile_priority
= active_priority
;
651 case NEW_CONTENT_TAKES_PRIORITY
:
652 mts
.bin
= tree_bin
[PENDING_TREE
];
653 tile_priority
= pending_priority
;
657 // Bump up the priority if we determined it's NEVER_BIN on one tree,
658 // but is still required on the other tree.
659 bool is_in_never_bin_on_both_trees
= tree_bin
[ACTIVE_TREE
] == NEVER_BIN
&&
660 tree_bin
[PENDING_TREE
] == NEVER_BIN
;
662 if (mts
.bin
== NEVER_BIN
&& !is_in_never_bin_on_both_trees
)
663 mts
.bin
= tile_is_active
? AT_LAST_AND_ACTIVE_BIN
: AT_LAST_BIN
;
665 mts
.resolution
= tile_priority
.resolution
;
666 mts
.priority_bin
= tile_priority
.priority_bin
;
667 mts
.distance_to_visible
= tile_priority
.distance_to_visible
;
668 mts
.required_for_activation
= tile_priority
.required_for_activation
;
670 mts
.visible_and_ready_to_draw
=
671 tree_bin
[ACTIVE_TREE
] == NOW_AND_READY_TO_DRAW_BIN
;
673 // If the tile is in NEVER_BIN and it does not have an active task, then we
674 // can release the resources early. If it does have the task however, we
675 // should keep it in the prioritized tile set to ensure that AssignGpuMemory
677 if (mts
.bin
== NEVER_BIN
&&
678 !mts
.tile_versions
[mts
.raster_mode
].raster_task_
) {
679 FreeResourcesForTile(tile
);
683 // Insert the tile into a priority set.
684 tiles
->InsertTile(tile
, mts
.bin
);
688 void TileManager::ManageTiles(const GlobalStateThatImpactsTilePriority
& state
) {
689 TRACE_EVENT0("cc", "TileManager::ManageTiles");
691 // Update internal state.
692 if (state
!= global_state_
) {
693 global_state_
= state
;
694 prioritized_tiles_dirty_
= true;
697 // We need to call CheckForCompletedTasks() once in-between each call
698 // to ScheduleTasks() to prevent canceled tasks from being scheduled.
699 if (!did_check_for_completed_tasks_since_last_schedule_tasks_
) {
700 rasterizer_delegate_
->CheckForCompletedTasks();
701 did_check_for_completed_tasks_since_last_schedule_tasks_
= true;
704 UpdatePrioritizedTileSetIfNeeded();
706 TileVector tiles_that_need_to_be_rasterized
;
707 AssignGpuMemoryToTiles(&prioritized_tiles_
,
708 &tiles_that_need_to_be_rasterized
);
710 // Finally, schedule rasterizer tasks.
711 ScheduleTasks(tiles_that_need_to_be_rasterized
);
713 TRACE_EVENT_INSTANT1("cc",
715 TRACE_EVENT_SCOPE_THREAD
,
717 TracedValue::FromValue(BasicStateAsValue().release()));
719 TRACE_COUNTER_ID1("cc",
720 "unused_memory_bytes",
722 resource_pool_
->total_memory_usage_bytes() -
723 resource_pool_
->acquired_memory_usage_bytes());
726 bool TileManager::UpdateVisibleTiles() {
727 TRACE_EVENT0("cc", "TileManager::UpdateVisibleTiles");
729 rasterizer_delegate_
->CheckForCompletedTasks();
730 did_check_for_completed_tasks_since_last_schedule_tasks_
= true;
732 TRACE_EVENT_INSTANT1(
734 "DidUpdateVisibleTiles",
735 TRACE_EVENT_SCOPE_THREAD
,
737 TracedValue::FromValue(RasterTaskCompletionStatsAsValue(
738 update_visible_tiles_stats_
).release()));
739 update_visible_tiles_stats_
= RasterTaskCompletionStats();
741 bool did_initialize_visible_tile
= did_initialize_visible_tile_
;
742 did_initialize_visible_tile_
= false;
743 return did_initialize_visible_tile
;
746 void TileManager::GetMemoryStats(size_t* memory_required_bytes
,
747 size_t* memory_nice_to_have_bytes
,
748 size_t* memory_allocated_bytes
,
749 size_t* memory_used_bytes
) const {
750 *memory_required_bytes
= memory_required_bytes_
;
751 *memory_nice_to_have_bytes
= memory_nice_to_have_bytes_
;
752 *memory_allocated_bytes
= resource_pool_
->total_memory_usage_bytes();
753 *memory_used_bytes
= resource_pool_
->acquired_memory_usage_bytes();
756 scoped_ptr
<base::Value
> TileManager::BasicStateAsValue() const {
757 scoped_ptr
<base::DictionaryValue
> state(new base::DictionaryValue());
758 state
->SetInteger("tile_count", tiles_
.size());
759 state
->Set("global_state", global_state_
.AsValue().release());
760 state
->Set("memory_requirements", GetMemoryRequirementsAsValue().release());
761 return state
.PassAs
<base::Value
>();
764 scoped_ptr
<base::Value
> TileManager::AllTilesAsValue() const {
765 scoped_ptr
<base::ListValue
> state(new base::ListValue());
766 for (TileMap::const_iterator it
= tiles_
.begin(); it
!= tiles_
.end(); ++it
)
767 state
->Append(it
->second
->AsValue().release());
769 return state
.PassAs
<base::Value
>();
772 scoped_ptr
<base::Value
> TileManager::GetMemoryRequirementsAsValue() const {
773 scoped_ptr
<base::DictionaryValue
> requirements(new base::DictionaryValue());
775 size_t memory_required_bytes
;
776 size_t memory_nice_to_have_bytes
;
777 size_t memory_allocated_bytes
;
778 size_t memory_used_bytes
;
779 GetMemoryStats(&memory_required_bytes
,
780 &memory_nice_to_have_bytes
,
781 &memory_allocated_bytes
,
783 requirements
->SetInteger("memory_required_bytes", memory_required_bytes
);
784 requirements
->SetInteger("memory_nice_to_have_bytes",
785 memory_nice_to_have_bytes
);
786 requirements
->SetInteger("memory_allocated_bytes", memory_allocated_bytes
);
787 requirements
->SetInteger("memory_used_bytes", memory_used_bytes
);
788 return requirements
.PassAs
<base::Value
>();
791 void TileManager::AssignGpuMemoryToTiles(
792 PrioritizedTileSet
* tiles
,
793 TileVector
* tiles_that_need_to_be_rasterized
) {
794 TRACE_EVENT0("cc", "TileManager::AssignGpuMemoryToTiles");
796 // Maintain the list of released resources that can potentially be re-used
798 // If this operation becomes expensive too, only do this after some
799 // resource(s) was returned. Note that in that case, one also need to
800 // invalidate when releasing some resource from the pool.
801 resource_pool_
->CheckBusyResources();
803 // Now give memory out to the tiles until we're out, and build
804 // the needs-to-be-rasterized queue.
805 all_tiles_that_need_to_be_rasterized_have_memory_
= true;
806 all_tiles_required_for_activation_have_memory_
= true;
808 // Cast to prevent overflow.
809 int64 soft_bytes_available
=
810 static_cast<int64
>(bytes_releasable_
) +
811 static_cast<int64
>(global_state_
.soft_memory_limit_in_bytes
) -
812 static_cast<int64
>(resource_pool_
->acquired_memory_usage_bytes());
813 int64 hard_bytes_available
=
814 static_cast<int64
>(bytes_releasable_
) +
815 static_cast<int64
>(global_state_
.hard_memory_limit_in_bytes
) -
816 static_cast<int64
>(resource_pool_
->acquired_memory_usage_bytes());
817 int resources_available
= resources_releasable_
+
818 global_state_
.num_resources_limit
-
819 resource_pool_
->acquired_resource_count();
820 size_t soft_bytes_allocatable
=
821 std::max(static_cast<int64
>(0), soft_bytes_available
);
822 size_t hard_bytes_allocatable
=
823 std::max(static_cast<int64
>(0), hard_bytes_available
);
824 size_t resources_allocatable
= std::max(0, resources_available
);
826 size_t bytes_that_exceeded_memory_budget
= 0;
827 size_t soft_bytes_left
= soft_bytes_allocatable
;
828 size_t hard_bytes_left
= hard_bytes_allocatable
;
830 size_t resources_left
= resources_allocatable
;
831 bool oomed_soft
= false;
832 bool oomed_hard
= false;
833 bool have_hit_soft_memory
= false; // Soft memory comes after hard.
835 // Memory we assign to raster tasks now will be deducted from our memory
836 // in future iterations if priorities change. By assigning at most half
837 // the raster limit, we will always have another 50% left even if priorities
838 // change completely (assuming we check for completed/cancelled rasters
839 // between each call to this function).
840 size_t max_raster_bytes
= max_raster_usage_bytes_
/ 2;
841 size_t raster_bytes
= 0;
843 unsigned schedule_priority
= 1u;
844 for (PrioritizedTileSet::Iterator
it(tiles
, true); it
; ++it
) {
846 ManagedTileState
& mts
= tile
->managed_state();
848 mts
.scheduled_priority
= schedule_priority
++;
850 mts
.raster_mode
= tile
->DetermineOverallRasterMode();
852 ManagedTileState::TileVersion
& tile_version
=
853 mts
.tile_versions
[mts
.raster_mode
];
855 // If this tile doesn't need a resource, then nothing to do.
856 if (!tile_version
.requires_resource())
859 // If the tile is not needed, free it up.
860 if (mts
.bin
== NEVER_BIN
) {
861 FreeResourcesForTile(tile
);
865 const bool tile_uses_hard_limit
= mts
.bin
<= NOW_BIN
;
866 const size_t bytes_if_allocated
= BytesConsumedIfAllocated(tile
);
867 const size_t raster_bytes_if_rastered
= raster_bytes
+ bytes_if_allocated
;
868 const size_t tile_bytes_left
=
869 (tile_uses_hard_limit
) ? hard_bytes_left
: soft_bytes_left
;
871 // Hard-limit is reserved for tiles that would cause a calamity
872 // if they were to go away, so by definition they are the highest
873 // priority memory, and must be at the front of the list.
874 DCHECK(!(have_hit_soft_memory
&& tile_uses_hard_limit
));
875 have_hit_soft_memory
|= !tile_uses_hard_limit
;
877 size_t tile_bytes
= 0;
878 size_t tile_resources
= 0;
880 // It costs to maintain a resource.
881 for (int mode
= 0; mode
< NUM_RASTER_MODES
; ++mode
) {
882 if (mts
.tile_versions
[mode
].resource_
) {
883 tile_bytes
+= bytes_if_allocated
;
888 // Allow lower priority tiles with initialized resources to keep
889 // their memory by only assigning memory to new raster tasks if
890 // they can be scheduled.
891 if (raster_bytes_if_rastered
<= max_raster_bytes
) {
892 // If we don't have the required version, and it's not in flight
893 // then we'll have to pay to create a new task.
894 if (!tile_version
.resource_
&& !tile_version
.raster_task_
) {
895 tile_bytes
+= bytes_if_allocated
;
901 if (tile_bytes
> tile_bytes_left
|| tile_resources
> resources_left
) {
902 FreeResourcesForTile(tile
);
904 // This tile was already on screen and now its resources have been
905 // released. In order to prevent checkerboarding, set this tile as
906 // rasterize on demand immediately.
907 if (mts
.visible_and_ready_to_draw
&& use_rasterize_on_demand_
)
908 tile_version
.set_rasterize_on_demand();
911 if (tile_uses_hard_limit
) {
913 bytes_that_exceeded_memory_budget
+= tile_bytes
;
916 resources_left
-= tile_resources
;
917 hard_bytes_left
-= tile_bytes
;
919 (soft_bytes_left
> tile_bytes
) ? soft_bytes_left
- tile_bytes
: 0;
920 if (tile_version
.resource_
)
924 DCHECK(!tile_version
.resource_
);
926 // Tile shouldn't be rasterized if |tiles_that_need_to_be_rasterized|
927 // has reached it's limit or we've failed to assign gpu memory to this
928 // or any higher priority tile. Preventing tiles that fit into memory
929 // budget to be rasterized when higher priority tile is oom is
930 // important for two reasons:
931 // 1. Tile size should not impact raster priority.
932 // 2. Tiles with existing raster task could otherwise incorrectly
933 // be added as they are not affected by |bytes_allocatable|.
934 bool can_schedule_tile
=
935 !oomed_soft
&& raster_bytes_if_rastered
<= max_raster_bytes
&&
936 tiles_that_need_to_be_rasterized
->size() < kScheduledRasterTasksLimit
;
938 if (!can_schedule_tile
) {
939 all_tiles_that_need_to_be_rasterized_have_memory_
= false;
940 if (tile
->required_for_activation())
941 all_tiles_required_for_activation_have_memory_
= false;
942 it
.DisablePriorityOrdering();
946 raster_bytes
= raster_bytes_if_rastered
;
947 tiles_that_need_to_be_rasterized
->push_back(tile
);
950 // OOM reporting uses hard-limit, soft-OOM is normal depending on limit.
951 ever_exceeded_memory_budget_
|= oomed_hard
;
952 if (ever_exceeded_memory_budget_
) {
953 TRACE_COUNTER_ID2("cc",
954 "over_memory_budget",
957 global_state_
.hard_memory_limit_in_bytes
,
959 bytes_that_exceeded_memory_budget
);
961 memory_stats_from_last_assign_
.total_budget_in_bytes
=
962 global_state_
.hard_memory_limit_in_bytes
;
963 memory_stats_from_last_assign_
.bytes_allocated
=
964 hard_bytes_allocatable
- hard_bytes_left
;
965 memory_stats_from_last_assign_
.bytes_unreleasable
=
966 resource_pool_
->acquired_memory_usage_bytes() - bytes_releasable_
;
967 memory_stats_from_last_assign_
.bytes_over
= bytes_that_exceeded_memory_budget
;
970 void TileManager::FreeResourceForTile(Tile
* tile
, RasterMode mode
) {
971 ManagedTileState
& mts
= tile
->managed_state();
972 if (mts
.tile_versions
[mode
].resource_
) {
973 resource_pool_
->ReleaseResource(mts
.tile_versions
[mode
].resource_
.Pass());
975 DCHECK_GE(bytes_releasable_
, BytesConsumedIfAllocated(tile
));
976 DCHECK_GE(resources_releasable_
, 1u);
978 bytes_releasable_
-= BytesConsumedIfAllocated(tile
);
979 --resources_releasable_
;
983 void TileManager::FreeResourcesForTile(Tile
* tile
) {
984 for (int mode
= 0; mode
< NUM_RASTER_MODES
; ++mode
) {
985 FreeResourceForTile(tile
, static_cast<RasterMode
>(mode
));
989 void TileManager::FreeUnusedResourcesForTile(Tile
* tile
) {
990 DCHECK(tile
->IsReadyToDraw());
991 ManagedTileState
& mts
= tile
->managed_state();
992 RasterMode used_mode
= HIGH_QUALITY_NO_LCD_RASTER_MODE
;
993 for (int mode
= 0; mode
< NUM_RASTER_MODES
; ++mode
) {
994 if (mts
.tile_versions
[mode
].IsReadyToDraw()) {
995 used_mode
= static_cast<RasterMode
>(mode
);
1000 for (int mode
= 0; mode
< NUM_RASTER_MODES
; ++mode
) {
1001 if (mode
!= used_mode
)
1002 FreeResourceForTile(tile
, static_cast<RasterMode
>(mode
));
1006 void TileManager::ScheduleTasks(
1007 const TileVector
& tiles_that_need_to_be_rasterized
) {
1009 "TileManager::ScheduleTasks",
1011 tiles_that_need_to_be_rasterized
.size());
1013 DCHECK(did_check_for_completed_tasks_since_last_schedule_tasks_
);
1015 for (size_t i
= 0; i
< NUM_RASTERIZER_TYPES
; ++i
)
1016 raster_queue_
[i
].Reset();
1018 // Build a new task queue containing all task currently needed. Tasks
1019 // are added in order of priority, highest priority task first.
1020 for (TileVector::const_iterator it
= tiles_that_need_to_be_rasterized
.begin();
1021 it
!= tiles_that_need_to_be_rasterized
.end();
1024 ManagedTileState
& mts
= tile
->managed_state();
1025 ManagedTileState::TileVersion
& tile_version
=
1026 mts
.tile_versions
[mts
.raster_mode
];
1028 DCHECK(tile_version
.requires_resource());
1029 DCHECK(!tile_version
.resource_
);
1031 if (!tile_version
.raster_task_
)
1032 tile_version
.raster_task_
= CreateRasterTask(tile
);
1034 size_t pool_type
= tile
->use_gpu_rasterization() ? RASTERIZER_TYPE_GPU
1035 : RASTERIZER_TYPE_DEFAULT
;
1037 raster_queue_
[pool_type
].items
.push_back(RasterTaskQueue::Item(
1038 tile_version
.raster_task_
.get(), tile
->required_for_activation()));
1039 raster_queue_
[pool_type
].required_for_activation_count
+=
1040 tile
->required_for_activation();
1043 // We must reduce the amount of unused resoruces before calling
1044 // ScheduleTasks to prevent usage from rising above limits.
1045 resource_pool_
->ReduceResourceUsage();
1047 // Schedule running of |raster_tasks_|. This replaces any previously
1048 // scheduled tasks and effectively cancels all tasks not present
1049 // in |raster_tasks_|.
1050 rasterizer_delegate_
->ScheduleTasks(raster_queue_
);
1052 // It's now safe to clean up orphan tasks as raster worker pool is not
1053 // allowed to keep around unreferenced raster tasks after ScheduleTasks() has
1055 orphan_raster_tasks_
.clear();
1057 did_check_for_completed_tasks_since_last_schedule_tasks_
= false;
1060 scoped_refptr
<ImageDecodeTask
> TileManager::CreateImageDecodeTask(
1062 SkPixelRef
* pixel_ref
) {
1063 return make_scoped_refptr(new ImageDecodeTaskImpl(
1066 rendering_stats_instrumentation_
,
1067 base::Bind(&TileManager::OnImageDecodeTaskCompleted
,
1068 base::Unretained(this),
1070 base::Unretained(pixel_ref
))));
1073 scoped_refptr
<RasterTask
> TileManager::CreateRasterTask(Tile
* tile
) {
1074 ManagedTileState
& mts
= tile
->managed_state();
1076 scoped_ptr
<ScopedResource
> resource
=
1077 resource_pool_
->AcquireResource(tile
->tile_size_
.size());
1078 const ScopedResource
* const_resource
= resource
.get();
1080 // Create and queue all image decode tasks that this tile depends on.
1081 ImageDecodeTask::Vector decode_tasks
;
1082 PixelRefTaskMap
& existing_pixel_refs
= image_decode_tasks_
[tile
->layer_id()];
1083 for (PicturePileImpl::PixelRefIterator
iter(
1084 tile
->content_rect(), tile
->contents_scale(), tile
->picture_pile());
1087 SkPixelRef
* pixel_ref
= *iter
;
1088 uint32_t id
= pixel_ref
->getGenerationID();
1090 // Append existing image decode task if available.
1091 PixelRefTaskMap::iterator decode_task_it
= existing_pixel_refs
.find(id
);
1092 if (decode_task_it
!= existing_pixel_refs
.end()) {
1093 decode_tasks
.push_back(decode_task_it
->second
);
1097 // Create and append new image decode task for this pixel ref.
1098 scoped_refptr
<ImageDecodeTask
> decode_task
=
1099 CreateImageDecodeTask(tile
, pixel_ref
);
1100 decode_tasks
.push_back(decode_task
);
1101 existing_pixel_refs
[id
] = decode_task
;
1104 // We analyze picture before rasterization to detect solid-color tiles.
1105 // If the tile is detected as such there is no need to raster or upload.
1106 // It is drawn directly as a solid-color quad saving raster and upload cost.
1107 // The analysis step is however expensive and is not justified when doing
1108 // gpu rasterization where there is no upload.
1110 // Additionally, we do not want to do the analysis if the layer that produced
1111 // this tile is narrow, since more likely than not the tile would not be
1112 // solid. We use the picture pile size as a proxy for layer size, since it
1113 // represents the recorded (and thus rasterizable) content.
1114 // Note that this last optimization is a heuristic that ensures that we don't
1115 // spend too much time analyzing tiles on a multitude of small layers, as it
1116 // is likely that these layers have some non-solid content.
1117 gfx::Size pile_size
= tile
->picture_pile()->tiling_rect().size();
1118 bool analyze_picture
= !tile
->use_gpu_rasterization() &&
1119 std::min(pile_size
.width(), pile_size
.height()) >=
1120 kMinDimensionsForAnalysis
;
1122 return make_scoped_refptr(
1123 new RasterTaskImpl(const_resource
,
1124 tile
->picture_pile(),
1125 tile
->content_rect(),
1126 tile
->contents_scale(),
1130 static_cast<const void*>(tile
),
1131 tile
->source_frame_number(),
1133 rendering_stats_instrumentation_
,
1134 base::Bind(&TileManager::OnRasterTaskCompleted
,
1135 base::Unretained(this),
1137 base::Passed(&resource
),
1142 void TileManager::OnImageDecodeTaskCompleted(int layer_id
,
1143 SkPixelRef
* pixel_ref
,
1144 bool was_canceled
) {
1145 // If the task was canceled, we need to clean it up
1146 // from |image_decode_tasks_|.
1150 LayerPixelRefTaskMap::iterator layer_it
= image_decode_tasks_
.find(layer_id
);
1151 if (layer_it
== image_decode_tasks_
.end())
1154 PixelRefTaskMap
& pixel_ref_tasks
= layer_it
->second
;
1155 PixelRefTaskMap::iterator task_it
=
1156 pixel_ref_tasks
.find(pixel_ref
->getGenerationID());
1158 if (task_it
!= pixel_ref_tasks
.end())
1159 pixel_ref_tasks
.erase(task_it
);
1162 void TileManager::OnRasterTaskCompleted(
1164 scoped_ptr
<ScopedResource
> resource
,
1165 RasterMode raster_mode
,
1166 const PicturePileImpl::Analysis
& analysis
,
1167 bool was_canceled
) {
1168 TileMap::iterator it
= tiles_
.find(tile_id
);
1169 if (it
== tiles_
.end()) {
1170 ++update_visible_tiles_stats_
.canceled_count
;
1171 resource_pool_
->ReleaseResource(resource
.Pass());
1175 Tile
* tile
= it
->second
;
1176 ManagedTileState
& mts
= tile
->managed_state();
1177 ManagedTileState::TileVersion
& tile_version
= mts
.tile_versions
[raster_mode
];
1178 DCHECK(tile_version
.raster_task_
);
1179 orphan_raster_tasks_
.push_back(tile_version
.raster_task_
);
1180 tile_version
.raster_task_
= NULL
;
1183 ++update_visible_tiles_stats_
.canceled_count
;
1184 resource_pool_
->ReleaseResource(resource
.Pass());
1188 ++update_visible_tiles_stats_
.completed_count
;
1190 tile_version
.set_has_text(analysis
.has_text
);
1191 if (analysis
.is_solid_color
) {
1192 tile_version
.set_solid_color(analysis
.solid_color
);
1193 resource_pool_
->ReleaseResource(resource
.Pass());
1195 tile_version
.set_use_resource();
1196 tile_version
.resource_
= resource
.Pass();
1198 bytes_releasable_
+= BytesConsumedIfAllocated(tile
);
1199 ++resources_releasable_
;
1202 client_
->NotifyTileInitialized(tile
);
1204 FreeUnusedResourcesForTile(tile
);
1205 if (tile
->priority(ACTIVE_TREE
).distance_to_visible
== 0.f
)
1206 did_initialize_visible_tile_
= true;
1209 scoped_refptr
<Tile
> TileManager::CreateTile(PicturePileImpl
* picture_pile
,
1210 const gfx::Size
& tile_size
,
1211 const gfx::Rect
& content_rect
,
1212 const gfx::Rect
& opaque_rect
,
1213 float contents_scale
,
1215 int source_frame_number
,
1217 scoped_refptr
<Tile
> tile
= make_scoped_refptr(new Tile(this,
1224 source_frame_number
,
1226 DCHECK(tiles_
.find(tile
->id()) == tiles_
.end());
1228 tiles_
[tile
->id()] = tile
;
1229 used_layer_counts_
[tile
->layer_id()]++;
1230 prioritized_tiles_dirty_
= true;
1234 void TileManager::RegisterPictureLayerImpl(PictureLayerImpl
* layer
) {
1235 DCHECK(std::find(layers_
.begin(), layers_
.end(), layer
) == layers_
.end());
1236 layers_
.push_back(layer
);
1239 void TileManager::UnregisterPictureLayerImpl(PictureLayerImpl
* layer
) {
1240 std::vector
<PictureLayerImpl
*>::iterator it
=
1241 std::find(layers_
.begin(), layers_
.end(), layer
);
1242 DCHECK(it
!= layers_
.end());
1246 void TileManager::GetPairedPictureLayers(
1247 std::vector
<PairedPictureLayer
>* paired_layers
) const {
1248 paired_layers
->clear();
1249 // Reserve a maximum possible paired layers.
1250 paired_layers
->reserve(layers_
.size());
1252 for (std::vector
<PictureLayerImpl
*>::const_iterator it
= layers_
.begin();
1253 it
!= layers_
.end();
1255 PictureLayerImpl
* layer
= *it
;
1257 // This is a recycle tree layer, we can safely skip since the tiles on this
1258 // layer have to be accessible via the active tree.
1259 if (!layer
->IsOnActiveOrPendingTree())
1262 PictureLayerImpl
* twin_layer
= layer
->GetTwinLayer();
1264 // If the twin layer is recycled, it is not a valid twin.
1265 if (twin_layer
&& !twin_layer
->IsOnActiveOrPendingTree())
1268 PairedPictureLayer paired_layer
;
1269 WhichTree tree
= layer
->GetTree();
1271 // If the current tree is ACTIVE_TREE, then always generate a paired_layer.
1272 // If current tree is PENDING_TREE, then only generate a paired_layer if
1273 // there is no twin layer.
1274 if (tree
== ACTIVE_TREE
) {
1275 DCHECK(!twin_layer
|| twin_layer
->GetTree() == PENDING_TREE
);
1276 paired_layer
.active_layer
= layer
;
1277 paired_layer
.pending_layer
= twin_layer
;
1278 paired_layers
->push_back(paired_layer
);
1279 } else if (!twin_layer
) {
1280 paired_layer
.active_layer
= NULL
;
1281 paired_layer
.pending_layer
= layer
;
1282 paired_layers
->push_back(paired_layer
);
1287 TileManager::PairedPictureLayer::PairedPictureLayer()
1288 : active_layer(NULL
), pending_layer(NULL
) {}
1290 TileManager::PairedPictureLayer::~PairedPictureLayer() {}
1292 TileManager::RasterTileIterator::RasterTileIterator(TileManager
* tile_manager
,
1293 TreePriority tree_priority
)
1294 : tree_priority_(tree_priority
), comparator_(tree_priority
) {
1295 std::vector
<TileManager::PairedPictureLayer
> paired_layers
;
1296 tile_manager
->GetPairedPictureLayers(&paired_layers
);
1297 bool prioritize_low_res
= tree_priority_
== SMOOTHNESS_TAKES_PRIORITY
;
1299 paired_iterators_
.reserve(paired_layers
.size());
1300 iterator_heap_
.reserve(paired_layers
.size());
1301 for (std::vector
<TileManager::PairedPictureLayer
>::iterator it
=
1302 paired_layers
.begin();
1303 it
!= paired_layers
.end();
1305 PairedPictureLayerIterator paired_iterator
;
1306 if (it
->active_layer
) {
1307 paired_iterator
.active_iterator
=
1308 PictureLayerImpl::LayerRasterTileIterator(it
->active_layer
,
1309 prioritize_low_res
);
1312 if (it
->pending_layer
) {
1313 paired_iterator
.pending_iterator
=
1314 PictureLayerImpl::LayerRasterTileIterator(it
->pending_layer
,
1315 prioritize_low_res
);
1318 if (paired_iterator
.PeekTile(tree_priority_
) != NULL
) {
1319 paired_iterators_
.push_back(paired_iterator
);
1320 iterator_heap_
.push_back(&paired_iterators_
.back());
1324 std::make_heap(iterator_heap_
.begin(), iterator_heap_
.end(), comparator_
);
1327 TileManager::RasterTileIterator::~RasterTileIterator() {}
1329 TileManager::RasterTileIterator
& TileManager::RasterTileIterator::operator++() {
1332 std::pop_heap(iterator_heap_
.begin(), iterator_heap_
.end(), comparator_
);
1333 PairedPictureLayerIterator
* paired_iterator
= iterator_heap_
.back();
1334 iterator_heap_
.pop_back();
1336 paired_iterator
->PopTile(tree_priority_
);
1337 if (paired_iterator
->PeekTile(tree_priority_
) != NULL
) {
1338 iterator_heap_
.push_back(paired_iterator
);
1339 std::push_heap(iterator_heap_
.begin(), iterator_heap_
.end(), comparator_
);
1344 TileManager::RasterTileIterator::operator bool() const {
1345 return !iterator_heap_
.empty();
1348 Tile
* TileManager::RasterTileIterator::operator*() {
1350 return iterator_heap_
.front()->PeekTile(tree_priority_
);
1353 TileManager::RasterTileIterator::PairedPictureLayerIterator::
1354 PairedPictureLayerIterator() {}
1356 TileManager::RasterTileIterator::PairedPictureLayerIterator::
1357 ~PairedPictureLayerIterator() {}
1359 Tile
* TileManager::RasterTileIterator::PairedPictureLayerIterator::PeekTile(
1360 TreePriority tree_priority
) {
1361 PictureLayerImpl::LayerRasterTileIterator
* next_iterator
=
1362 NextTileIterator(tree_priority
).first
;
1366 DCHECK(*next_iterator
);
1367 DCHECK(std::find(returned_shared_tiles
.begin(),
1368 returned_shared_tiles
.end(),
1369 **next_iterator
) == returned_shared_tiles
.end());
1370 return **next_iterator
;
1373 void TileManager::RasterTileIterator::PairedPictureLayerIterator::PopTile(
1374 TreePriority tree_priority
) {
1375 PictureLayerImpl::LayerRasterTileIterator
* next_iterator
=
1376 NextTileIterator(tree_priority
).first
;
1377 DCHECK(next_iterator
);
1378 DCHECK(*next_iterator
);
1379 returned_shared_tiles
.push_back(**next_iterator
);
1382 next_iterator
= NextTileIterator(tree_priority
).first
;
1383 while (next_iterator
&&
1384 std::find(returned_shared_tiles
.begin(),
1385 returned_shared_tiles
.end(),
1386 **next_iterator
) != returned_shared_tiles
.end()) {
1388 next_iterator
= NextTileIterator(tree_priority
).first
;
1392 std::pair
<PictureLayerImpl::LayerRasterTileIterator
*, WhichTree
>
1393 TileManager::RasterTileIterator::PairedPictureLayerIterator::NextTileIterator(
1394 TreePriority tree_priority
) {
1395 // If both iterators are out of tiles, return NULL.
1396 if (!active_iterator
&& !pending_iterator
) {
1397 return std::pair
<PictureLayerImpl::LayerRasterTileIterator
*, WhichTree
>(
1401 // If we only have one iterator with tiles, return it.
1402 if (!active_iterator
)
1403 return std::make_pair(&pending_iterator
, PENDING_TREE
);
1404 if (!pending_iterator
)
1405 return std::make_pair(&active_iterator
, ACTIVE_TREE
);
1407 // Now both iterators have tiles, so we have to decide based on tree priority.
1408 switch (tree_priority
) {
1409 case SMOOTHNESS_TAKES_PRIORITY
:
1410 return std::make_pair(&active_iterator
, ACTIVE_TREE
);
1411 case NEW_CONTENT_TAKES_PRIORITY
:
1412 return std::make_pair(&pending_iterator
, ACTIVE_TREE
);
1413 case SAME_PRIORITY_FOR_BOTH_TREES
: {
1414 Tile
* active_tile
= *active_iterator
;
1415 Tile
* pending_tile
= *pending_iterator
;
1416 if (active_tile
== pending_tile
)
1417 return std::make_pair(&active_iterator
, ACTIVE_TREE
);
1419 const TilePriority
& active_priority
= active_tile
->priority(ACTIVE_TREE
);
1420 const TilePriority
& pending_priority
=
1421 pending_tile
->priority(PENDING_TREE
);
1423 if (active_priority
.IsHigherPriorityThan(pending_priority
))
1424 return std::make_pair(&active_iterator
, ACTIVE_TREE
);
1425 return std::make_pair(&pending_iterator
, PENDING_TREE
);
1430 // Keep the compiler happy.
1431 return std::pair
<PictureLayerImpl::LayerRasterTileIterator
*, WhichTree
>(
1435 TileManager::RasterTileIterator::RasterOrderComparator::RasterOrderComparator(
1436 TreePriority tree_priority
)
1437 : tree_priority_(tree_priority
) {}
1439 bool TileManager::RasterTileIterator::RasterOrderComparator::operator()(
1440 PairedPictureLayerIterator
* a
,
1441 PairedPictureLayerIterator
* b
) const {
1442 std::pair
<PictureLayerImpl::LayerRasterTileIterator
*, WhichTree
> a_pair
=
1443 a
->NextTileIterator(tree_priority_
);
1444 DCHECK(a_pair
.first
);
1445 DCHECK(*a_pair
.first
);
1447 std::pair
<PictureLayerImpl::LayerRasterTileIterator
*, WhichTree
> b_pair
=
1448 b
->NextTileIterator(tree_priority_
);
1449 DCHECK(b_pair
.first
);
1450 DCHECK(*b_pair
.first
);
1452 Tile
* a_tile
= **a_pair
.first
;
1453 Tile
* b_tile
= **b_pair
.first
;
1455 const TilePriority
& a_priority
=
1456 a_tile
->priority_for_tree_priority(tree_priority_
);
1457 const TilePriority
& b_priority
=
1458 b_tile
->priority_for_tree_priority(tree_priority_
);
1459 bool prioritize_low_res
= tree_priority_
== SMOOTHNESS_TAKES_PRIORITY
;
1461 if (b_priority
.resolution
!= a_priority
.resolution
) {
1462 return (prioritize_low_res
&& b_priority
.resolution
== LOW_RESOLUTION
) ||
1463 (!prioritize_low_res
&& b_priority
.resolution
== HIGH_RESOLUTION
) ||
1464 (a_priority
.resolution
== NON_IDEAL_RESOLUTION
);
1467 return b_priority
.IsHigherPriorityThan(a_priority
);
1470 TileManager::EvictionTileIterator::EvictionTileIterator()
1471 : comparator_(SAME_PRIORITY_FOR_BOTH_TREES
) {}
1473 TileManager::EvictionTileIterator::EvictionTileIterator(
1474 TileManager
* tile_manager
,
1475 TreePriority tree_priority
)
1476 : tree_priority_(tree_priority
), comparator_(tree_priority
) {
1477 std::vector
<TileManager::PairedPictureLayer
> paired_layers
;
1479 tile_manager
->GetPairedPictureLayers(&paired_layers
);
1481 paired_iterators_
.reserve(paired_layers
.size());
1482 iterator_heap_
.reserve(paired_layers
.size());
1483 for (std::vector
<TileManager::PairedPictureLayer
>::iterator it
=
1484 paired_layers
.begin();
1485 it
!= paired_layers
.end();
1487 PairedPictureLayerIterator paired_iterator
;
1488 if (it
->active_layer
) {
1489 paired_iterator
.active_iterator
=
1490 PictureLayerImpl::LayerEvictionTileIterator(it
->active_layer
,
1494 if (it
->pending_layer
) {
1495 paired_iterator
.pending_iterator
=
1496 PictureLayerImpl::LayerEvictionTileIterator(it
->pending_layer
,
1500 if (paired_iterator
.PeekTile(tree_priority_
) != NULL
) {
1501 paired_iterators_
.push_back(paired_iterator
);
1502 iterator_heap_
.push_back(&paired_iterators_
.back());
1506 std::make_heap(iterator_heap_
.begin(), iterator_heap_
.end(), comparator_
);
1509 TileManager::EvictionTileIterator::~EvictionTileIterator() {}
1511 TileManager::EvictionTileIterator
& TileManager::EvictionTileIterator::
1513 std::pop_heap(iterator_heap_
.begin(), iterator_heap_
.end(), comparator_
);
1514 PairedPictureLayerIterator
* paired_iterator
= iterator_heap_
.back();
1515 iterator_heap_
.pop_back();
1517 paired_iterator
->PopTile(tree_priority_
);
1518 if (paired_iterator
->PeekTile(tree_priority_
) != NULL
) {
1519 iterator_heap_
.push_back(paired_iterator
);
1520 std::push_heap(iterator_heap_
.begin(), iterator_heap_
.end(), comparator_
);
1525 TileManager::EvictionTileIterator::operator bool() const {
1526 return !iterator_heap_
.empty();
1529 Tile
* TileManager::EvictionTileIterator::operator*() {
1531 return iterator_heap_
.front()->PeekTile(tree_priority_
);
1534 TileManager::EvictionTileIterator::PairedPictureLayerIterator::
1535 PairedPictureLayerIterator() {}
1537 TileManager::EvictionTileIterator::PairedPictureLayerIterator::
1538 ~PairedPictureLayerIterator() {}
1540 Tile
* TileManager::EvictionTileIterator::PairedPictureLayerIterator::PeekTile(
1541 TreePriority tree_priority
) {
1542 PictureLayerImpl::LayerEvictionTileIterator
* next_iterator
=
1543 NextTileIterator(tree_priority
);
1547 DCHECK(*next_iterator
);
1548 DCHECK(std::find(returned_shared_tiles
.begin(),
1549 returned_shared_tiles
.end(),
1550 **next_iterator
) == returned_shared_tiles
.end());
1551 return **next_iterator
;
1554 void TileManager::EvictionTileIterator::PairedPictureLayerIterator::PopTile(
1555 TreePriority tree_priority
) {
1556 PictureLayerImpl::LayerEvictionTileIterator
* next_iterator
=
1557 NextTileIterator(tree_priority
);
1558 DCHECK(next_iterator
);
1559 DCHECK(*next_iterator
);
1560 returned_shared_tiles
.push_back(**next_iterator
);
1563 next_iterator
= NextTileIterator(tree_priority
);
1564 while (next_iterator
&&
1565 std::find(returned_shared_tiles
.begin(),
1566 returned_shared_tiles
.end(),
1567 **next_iterator
) != returned_shared_tiles
.end()) {
1569 next_iterator
= NextTileIterator(tree_priority
);
1573 PictureLayerImpl::LayerEvictionTileIterator
*
1574 TileManager::EvictionTileIterator::PairedPictureLayerIterator::NextTileIterator(
1575 TreePriority tree_priority
) {
1576 // If both iterators are out of tiles, return NULL.
1577 if (!active_iterator
&& !pending_iterator
)
1580 // If we only have one iterator with tiles, return it.
1581 if (!active_iterator
)
1582 return &pending_iterator
;
1583 if (!pending_iterator
)
1584 return &active_iterator
;
1586 Tile
* active_tile
= *active_iterator
;
1587 Tile
* pending_tile
= *pending_iterator
;
1588 if (active_tile
== pending_tile
)
1589 return &active_iterator
;
1591 const TilePriority
& active_priority
=
1592 active_tile
->priority_for_tree_priority(tree_priority
);
1593 const TilePriority
& pending_priority
=
1594 pending_tile
->priority_for_tree_priority(tree_priority
);
1596 if (pending_priority
.IsHigherPriorityThan(active_priority
))
1597 return &active_iterator
;
1598 return &pending_iterator
;
1601 TileManager::EvictionTileIterator::EvictionOrderComparator::
1602 EvictionOrderComparator(TreePriority tree_priority
)
1603 : tree_priority_(tree_priority
) {}
1605 bool TileManager::EvictionTileIterator::EvictionOrderComparator::operator()(
1606 PairedPictureLayerIterator
* a
,
1607 PairedPictureLayerIterator
* b
) const {
1608 PictureLayerImpl::LayerEvictionTileIterator
* a_iterator
=
1609 a
->NextTileIterator(tree_priority_
);
1611 DCHECK(*a_iterator
);
1613 PictureLayerImpl::LayerEvictionTileIterator
* b_iterator
=
1614 b
->NextTileIterator(tree_priority_
);
1616 DCHECK(*b_iterator
);
1618 Tile
* a_tile
= **a_iterator
;
1619 Tile
* b_tile
= **b_iterator
;
1621 const TilePriority
& a_priority
=
1622 a_tile
->priority_for_tree_priority(tree_priority_
);
1623 const TilePriority
& b_priority
=
1624 b_tile
->priority_for_tree_priority(tree_priority_
);
1625 bool prioritize_low_res
= tree_priority_
!= SMOOTHNESS_TAKES_PRIORITY
;
1627 if (b_priority
.resolution
!= a_priority
.resolution
) {
1628 return (prioritize_low_res
&& b_priority
.resolution
== LOW_RESOLUTION
) ||
1629 (!prioritize_low_res
&& b_priority
.resolution
== HIGH_RESOLUTION
) ||
1630 (a_priority
.resolution
== NON_IDEAL_RESOLUTION
);
1632 return a_priority
.IsHigherPriorityThan(b_priority
);