forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtile_manager.cc
1273 lines (1082 loc) · 46.9 KB
/
tile_manager.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/tiles/tile_manager.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <limits>
#include <string>
#include "base/bind.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram.h"
#include "base/numerics/safe_conversions.h"
#include "base/trace_event/trace_event_argument.h"
#include "cc/base/histograms.h"
#include "cc/debug/devtools_instrumentation.h"
#include "cc/debug/frame_viewer_instrumentation.h"
#include "cc/debug/traced_value.h"
#include "cc/layers/picture_layer_impl.h"
#include "cc/raster/raster_buffer.h"
#include "cc/raster/task_category.h"
#include "cc/tiles/tile.h"
#include "ui/gfx/geometry/rect_conversions.h"
namespace cc {
namespace {
// Flag to indicate whether we should try and detect that
// a tile is of solid color.
const bool kUseColorEstimator = true;
DEFINE_SCOPED_UMA_HISTOGRAM_AREA_TIMER(
ScopedRasterTaskTimer,
"Compositing.%s.RasterTask.RasterUs",
"Compositing.%s.RasterTask.RasterPixelsPerMs");
class RasterTaskImpl : public TileTask {
public:
RasterTaskImpl(const Resource* resource,
scoped_refptr<RasterSource> raster_source,
const gfx::Rect& content_rect,
const gfx::Rect& invalid_content_rect,
float contents_scale,
const RasterSource::PlaybackSettings& playback_settings,
TileResolution tile_resolution,
int layer_id,
uint64_t source_prepare_tiles_id,
const void* tile,
uint64_t new_content_id,
uint64_t previous_content_id,
uint64_t resource_content_id,
int source_frame_number,
const base::Callback<void(bool)>& reply,
TileTask::Vector* dependencies,
bool supports_concurrent_execution)
: TileTask(supports_concurrent_execution, dependencies),
resource_(resource),
raster_source_(std::move(raster_source)),
content_rect_(content_rect),
invalid_content_rect_(invalid_content_rect),
contents_scale_(contents_scale),
playback_settings_(playback_settings),
tile_resolution_(tile_resolution),
layer_id_(layer_id),
source_prepare_tiles_id_(source_prepare_tiles_id),
tile_(tile),
new_content_id_(new_content_id),
previous_content_id_(previous_content_id),
resource_content_id_(resource_content_id),
source_frame_number_(source_frame_number),
reply_(reply) {}
// Overridden from Task:
void RunOnWorkerThread() override {
TRACE_EVENT1("cc", "RasterizerTaskImpl::RunOnWorkerThread",
"source_prepare_tiles_id", source_prepare_tiles_id_);
DCHECK(raster_source_.get());
DCHECK(raster_buffer_);
frame_viewer_instrumentation::ScopedRasterTask raster_task(
tile_, tile_resolution_, source_frame_number_, layer_id_);
ScopedRasterTaskTimer timer;
timer.SetArea(content_rect_.size().GetArea());
DCHECK(raster_source_);
raster_buffer_->Playback(raster_source_.get(), content_rect_,
invalid_content_rect_, new_content_id_,
contents_scale_, playback_settings_);
}
// Overridden from TileTask:
void ScheduleOnOriginThread(RasterBufferProvider* provider) override {
DCHECK(!raster_buffer_);
raster_buffer_ = provider->AcquireBufferForRaster(
resource_, resource_content_id_, previous_content_id_);
}
void CompleteOnOriginThread(RasterBufferProvider* provider) override {
provider->ReleaseBufferForRaster(std::move(raster_buffer_));
reply_.Run(!state().IsFinished());
}
protected:
~RasterTaskImpl() override { DCHECK(!raster_buffer_); }
private:
const Resource* resource_;
scoped_refptr<RasterSource> raster_source_;
gfx::Rect content_rect_;
gfx::Rect invalid_content_rect_;
float contents_scale_;
RasterSource::PlaybackSettings playback_settings_;
TileResolution tile_resolution_;
int layer_id_;
uint64_t source_prepare_tiles_id_;
const void* tile_;
uint64_t new_content_id_;
uint64_t previous_content_id_;
uint64_t resource_content_id_;
int source_frame_number_;
const base::Callback<void(bool)> reply_;
std::unique_ptr<RasterBuffer> raster_buffer_;
DISALLOW_COPY_AND_ASSIGN(RasterTaskImpl);
};
TaskCategory TaskCategoryForTileTask(TileTask* task,
bool use_foreground_category) {
if (!task->supports_concurrent_execution())
return TASK_CATEGORY_NONCONCURRENT_FOREGROUND;
if (use_foreground_category)
return TASK_CATEGORY_FOREGROUND;
return TASK_CATEGORY_BACKGROUND;
}
bool IsForegroundCategory(uint16_t category) {
TaskCategory enum_category = static_cast<TaskCategory>(category);
switch (enum_category) {
case TASK_CATEGORY_NONCONCURRENT_FOREGROUND:
case TASK_CATEGORY_FOREGROUND:
return true;
case TASK_CATEGORY_BACKGROUND:
return false;
}
DCHECK(false);
return false;
}
// Task priorities that make sure that the task set done tasks run before any
// other remaining tasks.
const size_t kRequiredForActivationDoneTaskPriority = 1u;
const size_t kRequiredForDrawDoneTaskPriority = 2u;
const size_t kAllDoneTaskPriority = 3u;
// For correctness, |kTileTaskPriorityBase| must be greater than
// all task set done task priorities.
size_t kTileTaskPriorityBase = 10u;
void InsertNodeForTask(TaskGraph* graph,
TileTask* task,
uint16_t category,
uint16_t priority,
size_t dependencies) {
DCHECK(std::find_if(graph->nodes.begin(), graph->nodes.end(),
[task](const TaskGraph::Node& node) {
return node.task == task;
}) == graph->nodes.end());
graph->nodes.push_back(
TaskGraph::Node(task, category, priority, dependencies));
}
void InsertNodeForDecodeTask(TaskGraph* graph,
TileTask* task,
bool use_foreground_category,
uint16_t priority) {
uint32_t dependency_count = 0u;
if (task->dependencies().size()) {
DCHECK_EQ(task->dependencies().size(), 1u);
auto* dependency = task->dependencies()[0].get();
if (!dependency->HasCompleted()) {
InsertNodeForDecodeTask(graph, dependency, use_foreground_category,
priority);
graph->edges.push_back(TaskGraph::Edge(dependency, task));
dependency_count = 1u;
}
}
InsertNodeForTask(graph, task,
TaskCategoryForTileTask(task, use_foreground_category),
priority, dependency_count);
}
void InsertNodesForRasterTask(TaskGraph* graph,
TileTask* raster_task,
const TileTask::Vector& decode_tasks,
size_t priority,
bool use_foreground_category) {
size_t dependencies = 0u;
// Insert image decode tasks.
for (TileTask::Vector::const_iterator it = decode_tasks.begin();
it != decode_tasks.end(); ++it) {
TileTask* decode_task = it->get();
// Skip if already decoded.
if (decode_task->HasCompleted())
continue;
dependencies++;
// Add decode task if it doesn't already exist in graph.
TaskGraph::Node::Vector::iterator decode_it =
std::find_if(graph->nodes.begin(), graph->nodes.end(),
[decode_task](const TaskGraph::Node& node) {
return node.task == decode_task;
});
// In rare circumstances, a background category task may come in before a
// foreground category task. In these cases, upgrade any background category
// dependencies of the current task.
// TODO(ericrk): Task iterators should be updated to avoid this.
// crbug.com/594851
// TODO(ericrk): This should handle dependencies recursively.
// crbug.com/605234
if (decode_it != graph->nodes.end() && use_foreground_category &&
!IsForegroundCategory(decode_it->category)) {
decode_it->category = TASK_CATEGORY_FOREGROUND;
}
if (decode_it == graph->nodes.end()) {
InsertNodeForDecodeTask(graph, decode_task, use_foreground_category,
priority);
}
graph->edges.push_back(TaskGraph::Edge(decode_task, raster_task));
}
InsertNodeForTask(
graph, raster_task,
TaskCategoryForTileTask(raster_task, use_foreground_category), priority,
dependencies);
}
class TaskSetFinishedTaskImpl : public TileTask {
public:
explicit TaskSetFinishedTaskImpl(
base::SequencedTaskRunner* task_runner,
const base::Closure& on_task_set_finished_callback)
: TileTask(true),
task_runner_(task_runner),
on_task_set_finished_callback_(on_task_set_finished_callback) {}
// Overridden from Task:
void RunOnWorkerThread() override {
TRACE_EVENT0("cc", "TaskSetFinishedTaskImpl::RunOnWorkerThread");
TaskSetFinished();
}
// Overridden from TileTask:
void ScheduleOnOriginThread(RasterBufferProvider* provider) override {}
void CompleteOnOriginThread(RasterBufferProvider* provider) override {}
protected:
~TaskSetFinishedTaskImpl() override {}
void TaskSetFinished() {
task_runner_->PostTask(FROM_HERE, on_task_set_finished_callback_);
}
private:
scoped_refptr<base::SequencedTaskRunner> task_runner_;
const base::Closure on_task_set_finished_callback_;
DISALLOW_COPY_AND_ASSIGN(TaskSetFinishedTaskImpl);
};
} // namespace
RasterTaskCompletionStats::RasterTaskCompletionStats()
: completed_count(0u), canceled_count(0u) {}
std::unique_ptr<base::trace_event::ConvertableToTraceFormat>
RasterTaskCompletionStatsAsValue(const RasterTaskCompletionStats& stats) {
std::unique_ptr<base::trace_event::TracedValue> state(
new base::trace_event::TracedValue());
state->SetInteger("completed_count",
base::saturated_cast<int>(stats.completed_count));
state->SetInteger("canceled_count",
base::saturated_cast<int>(stats.canceled_count));
return std::move(state);
}
// static
std::unique_ptr<TileManager> TileManager::Create(
TileManagerClient* client,
base::SequencedTaskRunner* task_runner,
size_t scheduled_raster_task_limit,
bool use_partial_raster) {
// TODO(vmpstr): |task_runner| is a raw pointer that is implicitly converted
// into a scoped_refptr. Figure out whether to plumb a ref pointer or whether
// tile manager can have a non-owning pointer and fix.
return base::WrapUnique(new TileManager(
client, task_runner, scheduled_raster_task_limit, use_partial_raster));
}
TileManager::TileManager(TileManagerClient* client,
scoped_refptr<base::SequencedTaskRunner> task_runner,
size_t scheduled_raster_task_limit,
bool use_partial_raster)
: client_(client),
task_runner_(std::move(task_runner)),
resource_pool_(nullptr),
tile_task_manager_(nullptr),
scheduled_raster_task_limit_(scheduled_raster_task_limit),
use_partial_raster_(use_partial_raster),
use_gpu_rasterization_(false),
all_tiles_that_need_to_be_rasterized_are_scheduled_(true),
did_check_for_completed_tasks_since_last_schedule_tasks_(true),
did_oom_on_last_assign_(false),
more_tiles_need_prepare_check_notifier_(
task_runner_.get(),
base::Bind(&TileManager::CheckIfMoreTilesNeedToBePrepared,
base::Unretained(this))),
signals_check_notifier_(task_runner_.get(),
base::Bind(&TileManager::CheckAndIssueSignals,
base::Unretained(this))),
has_scheduled_tile_tasks_(false),
prepare_tiles_count_(0u),
next_tile_id_(0u),
task_set_finished_weak_ptr_factory_(this) {}
TileManager::~TileManager() {
FinishTasksAndCleanUp();
}
void TileManager::FinishTasksAndCleanUp() {
if (!tile_task_manager_)
return;
global_state_ = GlobalStateThatImpactsTilePriority();
// This cancels tasks if possible, finishes pending tasks, and release any
// uninitialized resources.
tile_task_manager_->Shutdown();
// Now that all tasks have been finished, we can clear any
// |orphan_tasks_|.
orphan_tasks_.clear();
tile_task_manager_->CheckForCompletedTasks();
FreeResourcesForReleasedTiles();
CleanUpReleasedTiles();
tile_task_manager_ = nullptr;
resource_pool_ = nullptr;
more_tiles_need_prepare_check_notifier_.Cancel();
signals_check_notifier_.Cancel();
task_set_finished_weak_ptr_factory_.InvalidateWeakPtrs();
}
void TileManager::SetResources(ResourcePool* resource_pool,
ImageDecodeController* image_decode_controller,
TileTaskManager* tile_task_manager,
size_t scheduled_raster_task_limit,
bool use_gpu_rasterization) {
DCHECK(!tile_task_manager_);
DCHECK(tile_task_manager);
use_gpu_rasterization_ = use_gpu_rasterization;
scheduled_raster_task_limit_ = scheduled_raster_task_limit;
resource_pool_ = resource_pool;
image_decode_controller_ = image_decode_controller;
tile_task_manager_ = tile_task_manager;
}
void TileManager::Release(Tile* tile) {
released_tiles_.push_back(tile);
}
void TileManager::FreeResourcesForReleasedTiles() {
for (auto* tile : released_tiles_)
FreeResourcesForTile(tile);
}
void TileManager::CleanUpReleasedTiles() {
std::vector<Tile*> tiles_to_retain;
for (auto* tile : released_tiles_) {
if (tile->HasRasterTask()) {
tiles_to_retain.push_back(tile);
continue;
}
DCHECK(!tile->draw_info().has_resource());
DCHECK(tiles_.find(tile->id()) != tiles_.end());
tiles_.erase(tile->id());
delete tile;
}
released_tiles_.swap(tiles_to_retain);
}
void TileManager::DidFinishRunningTileTasksRequiredForActivation() {
TRACE_EVENT0("cc",
"TileManager::DidFinishRunningTileTasksRequiredForActivation");
TRACE_EVENT_ASYNC_STEP_INTO1("cc", "ScheduledTasks", this, "running", "state",
ScheduledTasksStateAsValue());
signals_.ready_to_activate = true;
signals_check_notifier_.Schedule();
}
void TileManager::DidFinishRunningTileTasksRequiredForDraw() {
TRACE_EVENT0("cc", "TileManager::DidFinishRunningTileTasksRequiredForDraw");
TRACE_EVENT_ASYNC_STEP_INTO1("cc", "ScheduledTasks", this, "running", "state",
ScheduledTasksStateAsValue());
signals_.ready_to_draw = true;
signals_check_notifier_.Schedule();
}
void TileManager::DidFinishRunningAllTileTasks() {
TRACE_EVENT0("cc", "TileManager::DidFinishRunningAllTileTasks");
TRACE_EVENT_ASYNC_END0("cc", "ScheduledTasks", this);
DCHECK(resource_pool_);
DCHECK(tile_task_manager_);
has_scheduled_tile_tasks_ = false;
bool memory_usage_above_limit = resource_pool_->memory_usage_bytes() >
global_state_.soft_memory_limit_in_bytes;
if (all_tiles_that_need_to_be_rasterized_are_scheduled_ &&
!memory_usage_above_limit) {
// TODO(ericrk): We should find a better way to safely handle re-entrant
// notifications than always having to schedule a new task.
// http://crbug.com/498439
signals_.all_tile_tasks_completed = true;
signals_check_notifier_.Schedule();
return;
}
more_tiles_need_prepare_check_notifier_.Schedule();
}
bool TileManager::PrepareTiles(
const GlobalStateThatImpactsTilePriority& state) {
++prepare_tiles_count_;
TRACE_EVENT1("cc", "TileManager::PrepareTiles", "prepare_tiles_id",
prepare_tiles_count_);
if (!tile_task_manager_) {
TRACE_EVENT_INSTANT0("cc", "PrepareTiles aborted",
TRACE_EVENT_SCOPE_THREAD);
return false;
}
signals_.reset();
global_state_ = state;
// We need to call CheckForCompletedTasks() once in-between each call
// to ScheduleTasks() to prevent canceled tasks from being scheduled.
if (!did_check_for_completed_tasks_since_last_schedule_tasks_) {
tile_task_manager_->CheckForCompletedTasks();
did_check_for_completed_tasks_since_last_schedule_tasks_ = true;
}
FreeResourcesForReleasedTiles();
CleanUpReleasedTiles();
PrioritizedTileVector tiles_that_need_to_be_rasterized;
std::unique_ptr<RasterTilePriorityQueue> raster_priority_queue(
client_->BuildRasterQueue(global_state_.tree_priority,
RasterTilePriorityQueue::Type::ALL));
AssignGpuMemoryToTiles(raster_priority_queue.get(),
scheduled_raster_task_limit_,
&tiles_that_need_to_be_rasterized);
// Inform the client that will likely require a draw if the highest priority
// tile that will be rasterized is required for draw.
client_->SetIsLikelyToRequireADraw(
!tiles_that_need_to_be_rasterized.empty() &&
tiles_that_need_to_be_rasterized.front().tile()->required_for_draw());
// Schedule tile tasks.
ScheduleTasks(tiles_that_need_to_be_rasterized);
TRACE_EVENT_INSTANT1("cc", "DidPrepareTiles", TRACE_EVENT_SCOPE_THREAD,
"state", BasicStateAsValue());
return true;
}
void TileManager::Flush() {
TRACE_EVENT0("cc", "TileManager::Flush");
if (!tile_task_manager_) {
TRACE_EVENT_INSTANT0("cc", "Flush aborted", TRACE_EVENT_SCOPE_THREAD);
return;
}
tile_task_manager_->CheckForCompletedTasks();
did_check_for_completed_tasks_since_last_schedule_tasks_ = true;
TRACE_EVENT_INSTANT1("cc", "DidFlush", TRACE_EVENT_SCOPE_THREAD, "stats",
RasterTaskCompletionStatsAsValue(flush_stats_));
flush_stats_ = RasterTaskCompletionStats();
}
std::unique_ptr<base::trace_event::ConvertableToTraceFormat>
TileManager::BasicStateAsValue() const {
std::unique_ptr<base::trace_event::TracedValue> value(
new base::trace_event::TracedValue());
BasicStateAsValueInto(value.get());
return std::move(value);
}
void TileManager::BasicStateAsValueInto(
base::trace_event::TracedValue* state) const {
state->SetInteger("tile_count", base::saturated_cast<int>(tiles_.size()));
state->SetBoolean("did_oom_on_last_assign", did_oom_on_last_assign_);
state->BeginDictionary("global_state");
global_state_.AsValueInto(state);
state->EndDictionary();
}
std::unique_ptr<EvictionTilePriorityQueue>
TileManager::FreeTileResourcesUntilUsageIsWithinLimit(
std::unique_ptr<EvictionTilePriorityQueue> eviction_priority_queue,
const MemoryUsage& limit,
MemoryUsage* usage) {
while (usage->Exceeds(limit)) {
if (!eviction_priority_queue) {
eviction_priority_queue =
client_->BuildEvictionQueue(global_state_.tree_priority);
}
if (eviction_priority_queue->IsEmpty())
break;
Tile* tile = eviction_priority_queue->Top().tile();
*usage -= MemoryUsage::FromTile(tile);
FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(tile);
eviction_priority_queue->Pop();
}
return eviction_priority_queue;
}
std::unique_ptr<EvictionTilePriorityQueue>
TileManager::FreeTileResourcesWithLowerPriorityUntilUsageIsWithinLimit(
std::unique_ptr<EvictionTilePriorityQueue> eviction_priority_queue,
const MemoryUsage& limit,
const TilePriority& other_priority,
MemoryUsage* usage) {
while (usage->Exceeds(limit)) {
if (!eviction_priority_queue) {
eviction_priority_queue =
client_->BuildEvictionQueue(global_state_.tree_priority);
}
if (eviction_priority_queue->IsEmpty())
break;
const PrioritizedTile& prioritized_tile = eviction_priority_queue->Top();
if (!other_priority.IsHigherPriorityThan(prioritized_tile.priority()))
break;
Tile* tile = prioritized_tile.tile();
*usage -= MemoryUsage::FromTile(tile);
FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(tile);
eviction_priority_queue->Pop();
}
return eviction_priority_queue;
}
bool TileManager::TilePriorityViolatesMemoryPolicy(
const TilePriority& priority) {
switch (global_state_.memory_limit_policy) {
case ALLOW_NOTHING:
return true;
case ALLOW_ABSOLUTE_MINIMUM:
return priority.priority_bin > TilePriority::NOW;
case ALLOW_PREPAINT_ONLY:
return priority.priority_bin > TilePriority::SOON;
case ALLOW_ANYTHING:
return priority.distance_to_visible ==
std::numeric_limits<float>::infinity();
}
NOTREACHED();
return true;
}
void TileManager::AssignGpuMemoryToTiles(
RasterTilePriorityQueue* raster_priority_queue,
size_t scheduled_raster_task_limit,
PrioritizedTileVector* tiles_that_need_to_be_rasterized) {
TRACE_EVENT_BEGIN0("cc", "TileManager::AssignGpuMemoryToTiles");
DCHECK(resource_pool_);
DCHECK(tile_task_manager_);
// Maintain the list of released resources that can potentially be re-used
// or deleted. If this operation becomes expensive too, only do this after
// some resource(s) was returned. Note that in that case, one also need to
// invalidate when releasing some resource from the pool.
resource_pool_->CheckBusyResources();
// Now give memory out to the tiles until we're out, and build
// the needs-to-be-rasterized queue.
unsigned schedule_priority = 1u;
all_tiles_that_need_to_be_rasterized_are_scheduled_ = true;
bool had_enough_memory_to_schedule_tiles_needed_now = true;
MemoryUsage hard_memory_limit(global_state_.hard_memory_limit_in_bytes,
global_state_.num_resources_limit);
MemoryUsage soft_memory_limit(global_state_.soft_memory_limit_in_bytes,
global_state_.num_resources_limit);
MemoryUsage memory_usage(resource_pool_->memory_usage_bytes(),
resource_pool_->resource_count());
std::unique_ptr<EvictionTilePriorityQueue> eviction_priority_queue;
for (; !raster_priority_queue->IsEmpty(); raster_priority_queue->Pop()) {
const PrioritizedTile& prioritized_tile = raster_priority_queue->Top();
Tile* tile = prioritized_tile.tile();
TilePriority priority = prioritized_tile.priority();
if (TilePriorityViolatesMemoryPolicy(priority)) {
TRACE_EVENT_INSTANT0(
"cc", "TileManager::AssignGpuMemory tile violates memory policy",
TRACE_EVENT_SCOPE_THREAD);
break;
}
bool tile_is_needed_now = priority.priority_bin == TilePriority::NOW;
if (tile->use_picture_analysis() && kUseColorEstimator) {
// We analyze for solid color here, to decide to continue
// or drop the tile for scheduling and raster.
// TODO(sohanjg): Check if we could use a shared analysis
// canvas which is reset between tiles.
SkColor color = SK_ColorTRANSPARENT;
bool is_solid_color =
prioritized_tile.raster_source()->PerformSolidColorAnalysis(
tile->content_rect(), tile->contents_scale(), &color);
if (is_solid_color) {
tile->draw_info().set_solid_color(color);
tile->draw_info().set_was_ever_ready_to_draw();
if (!tile_is_needed_now)
tile->draw_info().set_was_a_prepaint_tile();
client_->NotifyTileStateChanged(tile);
continue;
}
}
// We won't be able to schedule this tile, so break out early.
if (tiles_that_need_to_be_rasterized->size() >=
scheduled_raster_task_limit) {
all_tiles_that_need_to_be_rasterized_are_scheduled_ = false;
break;
}
tile->scheduled_priority_ = schedule_priority++;
DCHECK(tile->draw_info().mode() == TileDrawInfo::OOM_MODE ||
!tile->draw_info().IsReadyToDraw());
// If the tile already has a raster_task, then the memory used by it is
// already accounted for in memory_usage. Otherwise, we'll have to acquire
// more memory to create a raster task.
MemoryUsage memory_required_by_tile_to_be_scheduled;
if (!tile->raster_task_.get()) {
memory_required_by_tile_to_be_scheduled = MemoryUsage::FromConfig(
tile->desired_texture_size(), DetermineResourceFormat(tile));
}
// This is the memory limit that will be used by this tile. Depending on
// the tile priority, it will be one of hard_memory_limit or
// soft_memory_limit.
MemoryUsage& tile_memory_limit =
tile_is_needed_now ? hard_memory_limit : soft_memory_limit;
const MemoryUsage& scheduled_tile_memory_limit =
tile_memory_limit - memory_required_by_tile_to_be_scheduled;
eviction_priority_queue =
FreeTileResourcesWithLowerPriorityUntilUsageIsWithinLimit(
std::move(eviction_priority_queue), scheduled_tile_memory_limit,
priority, &memory_usage);
bool memory_usage_is_within_limit =
!memory_usage.Exceeds(scheduled_tile_memory_limit);
// If we couldn't fit the tile into our current memory limit, then we're
// done.
if (!memory_usage_is_within_limit) {
if (tile_is_needed_now)
had_enough_memory_to_schedule_tiles_needed_now = false;
all_tiles_that_need_to_be_rasterized_are_scheduled_ = false;
break;
}
memory_usage += memory_required_by_tile_to_be_scheduled;
tiles_that_need_to_be_rasterized->push_back(prioritized_tile);
// Since we scheduled the tile, set whether it was a prepaint or not
// assuming that the tile will successfully finish running. We don't have
// priority information at the time the tile completes, so it should be done
// here.
if (!tile_is_needed_now)
tile->draw_info().set_was_a_prepaint_tile();
}
// Note that we should try and further reduce memory in case the above loop
// didn't reduce memory. This ensures that we always release as many resources
// as possible to stay within the memory limit.
eviction_priority_queue = FreeTileResourcesUntilUsageIsWithinLimit(
std::move(eviction_priority_queue), hard_memory_limit, &memory_usage);
UMA_HISTOGRAM_BOOLEAN("TileManager.ExceededMemoryBudget",
!had_enough_memory_to_schedule_tiles_needed_now);
did_oom_on_last_assign_ = !had_enough_memory_to_schedule_tiles_needed_now;
memory_stats_from_last_assign_.total_budget_in_bytes =
global_state_.hard_memory_limit_in_bytes;
memory_stats_from_last_assign_.total_bytes_used = memory_usage.memory_bytes();
DCHECK_GE(memory_stats_from_last_assign_.total_bytes_used, 0);
memory_stats_from_last_assign_.had_enough_memory =
had_enough_memory_to_schedule_tiles_needed_now;
TRACE_EVENT_END2("cc", "TileManager::AssignGpuMemoryToTiles",
"all_tiles_that_need_to_be_rasterized_are_scheduled",
all_tiles_that_need_to_be_rasterized_are_scheduled_,
"had_enough_memory_to_schedule_tiles_needed_now",
had_enough_memory_to_schedule_tiles_needed_now);
}
void TileManager::FreeResourcesForTile(Tile* tile) {
TileDrawInfo& draw_info = tile->draw_info();
if (draw_info.resource_) {
resource_pool_->ReleaseResource(draw_info.resource_, tile->id());
draw_info.resource_ = nullptr;
}
}
void TileManager::FreeResourcesForTileAndNotifyClientIfTileWasReadyToDraw(
Tile* tile) {
bool was_ready_to_draw = tile->draw_info().IsReadyToDraw();
FreeResourcesForTile(tile);
if (was_ready_to_draw)
client_->NotifyTileStateChanged(tile);
}
void TileManager::ScheduleTasks(
const PrioritizedTileVector& tiles_that_need_to_be_rasterized) {
TRACE_EVENT1("cc", "TileManager::ScheduleTasks", "count",
tiles_that_need_to_be_rasterized.size());
DCHECK(did_check_for_completed_tasks_since_last_schedule_tasks_);
if (!has_scheduled_tile_tasks_) {
TRACE_EVENT_ASYNC_BEGIN0("cc", "ScheduledTasks", this);
}
// Cancel existing OnTaskSetFinished callbacks.
task_set_finished_weak_ptr_factory_.InvalidateWeakPtrs();
// Even when scheduling an empty set of tiles, the TTWP does some work, and
// will always trigger a DidFinishRunningTileTasks notification. Because of
// this we unconditionally set |has_scheduled_tile_tasks_| to true.
has_scheduled_tile_tasks_ = true;
// Track the number of dependents for each *_done task.
size_t required_for_activate_count = 0;
size_t required_for_draw_count = 0;
size_t all_count = 0;
size_t priority = kTileTaskPriorityBase;
graph_.Reset();
scoped_refptr<TileTask> required_for_activation_done_task =
CreateTaskSetFinishedTask(
&TileManager::DidFinishRunningTileTasksRequiredForActivation);
scoped_refptr<TileTask> required_for_draw_done_task =
CreateTaskSetFinishedTask(
&TileManager::DidFinishRunningTileTasksRequiredForDraw);
scoped_refptr<TileTask> all_done_task =
CreateTaskSetFinishedTask(&TileManager::DidFinishRunningAllTileTasks);
// Build a new task queue containing all task currently needed. Tasks
// are added in order of priority, highest priority task first.
for (auto& prioritized_tile : tiles_that_need_to_be_rasterized) {
Tile* tile = prioritized_tile.tile();
DCHECK(tile->draw_info().requires_resource());
DCHECK(!tile->draw_info().resource_);
if (!tile->raster_task_)
tile->raster_task_ = CreateRasterTask(prioritized_tile);
TileTask* task = tile->raster_task_.get();
DCHECK(!task->HasCompleted());
if (tile->required_for_activation()) {
required_for_activate_count++;
graph_.edges.push_back(
TaskGraph::Edge(task, required_for_activation_done_task.get()));
}
if (tile->required_for_draw()) {
required_for_draw_count++;
graph_.edges.push_back(
TaskGraph::Edge(task, required_for_draw_done_task.get()));
}
all_count++;
graph_.edges.push_back(TaskGraph::Edge(task, all_done_task.get()));
// A tile should use a foreground task cateogry if it is either blocking
// future compositing (required for draw or required for activation), or if
// it has a priority bin of NOW for another reason (low resolution tiles).
bool use_foreground_category =
tile->required_for_draw() || tile->required_for_activation() ||
prioritized_tile.priority().priority_bin == TilePriority::NOW;
InsertNodesForRasterTask(&graph_, task, task->dependencies(), priority++,
use_foreground_category);
}
// Insert nodes for our task completion tasks. We enqueue these using
// NONCONCURRENT_FOREGROUND category this is the highest prioirty category and
// we'd like to run these tasks as soon as possible.
InsertNodeForTask(&graph_, required_for_activation_done_task.get(),
TASK_CATEGORY_NONCONCURRENT_FOREGROUND,
kRequiredForActivationDoneTaskPriority,
required_for_activate_count);
InsertNodeForTask(&graph_, required_for_draw_done_task.get(),
TASK_CATEGORY_NONCONCURRENT_FOREGROUND,
kRequiredForDrawDoneTaskPriority, required_for_draw_count);
InsertNodeForTask(&graph_, all_done_task.get(),
TASK_CATEGORY_NONCONCURRENT_FOREGROUND,
kAllDoneTaskPriority, all_count);
// We must reduce the amount of unused resoruces before calling
// ScheduleTasks to prevent usage from rising above limits.
resource_pool_->ReduceResourceUsage();
image_decode_controller_->ReduceCacheUsage();
// Schedule running of |raster_queue_|. This replaces any previously
// scheduled tasks and effectively cancels all tasks not present
// in |raster_queue_|.
tile_task_manager_->ScheduleTasks(&graph_);
// It's now safe to clean up orphan tasks as raster worker pool is not
// allowed to keep around unreferenced raster tasks after ScheduleTasks() has
// been called.
orphan_tasks_.clear();
// It's also now safe to replace our *_done_task_ tasks.
required_for_activation_done_task_ =
std::move(required_for_activation_done_task);
required_for_draw_done_task_ = std::move(required_for_draw_done_task);
all_done_task_ = std::move(all_done_task);
did_check_for_completed_tasks_since_last_schedule_tasks_ = false;
TRACE_EVENT_ASYNC_STEP_INTO1("cc", "ScheduledTasks", this, "running", "state",
ScheduledTasksStateAsValue());
}
scoped_refptr<TileTask> TileManager::CreateRasterTask(
const PrioritizedTile& prioritized_tile) {
Tile* tile = prioritized_tile.tile();
// Get the resource.
uint64_t resource_content_id = 0;
Resource* resource = nullptr;
if (use_partial_raster_ && tile->invalidated_id()) {
// TODO(danakj): For resources that are in use, we should still grab them
// and copy from them instead of rastering everything. crbug.com/492754
resource =
resource_pool_->TryAcquireResourceWithContentId(tile->invalidated_id());
}
if (resource) {
resource_content_id = tile->invalidated_id();
DCHECK_EQ(DetermineResourceFormat(tile), resource->format());
} else {
resource = resource_pool_->AcquireResource(tile->desired_texture_size(),
DetermineResourceFormat(tile));
}
// For LOW_RESOLUTION tiles, we don't draw or predecode images.
RasterSource::PlaybackSettings playback_settings;
playback_settings.skip_images =
prioritized_tile.priority().resolution == LOW_RESOLUTION;
// Create and queue all image decode tasks that this tile depends on.
TileTask::Vector decode_tasks;
std::vector<DrawImage>& images = scheduled_draw_images_[tile->id()];
images.clear();
if (!playback_settings.skip_images) {
prioritized_tile.raster_source()->GetDiscardableImagesInRect(
tile->enclosing_layer_rect(), tile->contents_scale(), &images);
}
// We can skip the image hijack canvas if we have no images.
playback_settings.use_image_hijack_canvas = !images.empty();
ImageDecodeController::TracingInfo tracing_info(
prepare_tiles_count_, prioritized_tile.priority().priority_bin);
for (auto it = images.begin(); it != images.end();) {
scoped_refptr<TileTask> task;
bool need_to_unref_when_finished =
image_decode_controller_->GetTaskForImageAndRef(*it, tracing_info,
&task);
if (task)
decode_tasks.push_back(task);
if (need_to_unref_when_finished)
++it;
else
it = images.erase(it);
}
bool supports_concurrent_execution = !use_gpu_rasterization_;
return make_scoped_refptr(new RasterTaskImpl(
resource, prioritized_tile.raster_source(), tile->content_rect(),
tile->invalidated_content_rect(), tile->contents_scale(),
playback_settings, prioritized_tile.priority().resolution,
tile->layer_id(), prepare_tiles_count_, static_cast<const void*>(tile),
tile->id(), tile->invalidated_id(), resource_content_id,
tile->source_frame_number(),
base::Bind(&TileManager::OnRasterTaskCompleted, base::Unretained(this),
tile->id(), resource),
&decode_tasks, supports_concurrent_execution));
}
void TileManager::OnRasterTaskCompleted(
Tile::Id tile_id,
Resource* resource,
bool was_canceled) {
DCHECK(tiles_.find(tile_id) != tiles_.end());
Tile* tile = tiles_[tile_id];
TileDrawInfo& draw_info = tile->draw_info();
DCHECK(tile->raster_task_.get());
orphan_tasks_.push_back(tile->raster_task_);
tile->raster_task_ = nullptr;
// Unref all the images.
auto images_it = scheduled_draw_images_.find(tile->id());
const std::vector<DrawImage>& images = images_it->second;
for (const auto& image : images)
image_decode_controller_->UnrefImage(image);
scheduled_draw_images_.erase(images_it);
if (was_canceled) {
++flush_stats_.canceled_count;
// TODO(ericrk): If more partial raster work is done in the future, it may
// be worth returning the resource to the pool with its previous ID (not
// currently tracked). crrev.com/1370333002/#ps40001 has a possible method
// of achieving this.
resource_pool_->ReleaseResource(resource, 0 /* content_id */);
return;
}
++flush_stats_.completed_count;
draw_info.set_use_resource();
draw_info.resource_ = resource;
draw_info.contents_swizzled_ = DetermineResourceRequiresSwizzle(tile);
DCHECK(draw_info.IsReadyToDraw());
draw_info.set_was_ever_ready_to_draw();
client_->NotifyTileStateChanged(tile);
}
ScopedTilePtr TileManager::CreateTile(const Tile::CreateInfo& info,
int layer_id,
int source_frame_number,
int flags) {
// We need to have a tile task worker pool to do anything meaningful with
// tiles.
DCHECK(tile_task_manager_);
ScopedTilePtr tile(
new Tile(this, info, layer_id, source_frame_number, flags));
DCHECK(tiles_.find(tile->id()) == tiles_.end());
tiles_[tile->id()] = tile.get();
return tile;
}
void TileManager::SetTileTaskManagerForTesting(
TileTaskManager* tile_task_manager) {
tile_task_manager_ = tile_task_manager;
}
bool TileManager::AreRequiredTilesReadyToDraw(
RasterTilePriorityQueue::Type type) const {