GPU workaround to simulate Out of Memory errors with large textures
[chromium-blink-merge.git] / cc / resources / picture_pile_impl.cc
blobbe0535846e689d07b37634dadbc34249428bce8e
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 <algorithm>
6 #include <limits>
7 #include <set>
9 #include "base/trace_event/trace_event.h"
10 #include "cc/base/region.h"
11 #include "cc/debug/debug_colors.h"
12 #include "cc/resources/picture_pile_impl.h"
13 #include "cc/resources/raster_source_helper.h"
14 #include "skia/ext/analysis_canvas.h"
15 #include "third_party/skia/include/core/SkCanvas.h"
16 #include "third_party/skia/include/core/SkPictureRecorder.h"
17 #include "ui/gfx/geometry/rect_conversions.h"
19 namespace cc {
21 scoped_refptr<PicturePileImpl> PicturePileImpl::CreateFromPicturePile(
22 const PicturePile* other,
23 bool can_use_lcd_text) {
24 return make_scoped_refptr(new PicturePileImpl(other, can_use_lcd_text));
27 PicturePileImpl::PicturePileImpl()
28 : background_color_(SK_ColorTRANSPARENT),
29 requires_clear_(true),
30 can_use_lcd_text_(true),
31 is_solid_color_(false),
32 solid_color_(SK_ColorTRANSPARENT),
33 has_any_recordings_(false),
34 clear_canvas_with_debug_color_(false),
35 min_contents_scale_(0.f),
36 slow_down_raster_scale_factor_for_debug_(0),
37 should_attempt_to_use_distance_field_text_(false) {
40 PicturePileImpl::PicturePileImpl(const PicturePile* other,
41 bool can_use_lcd_text)
42 : picture_map_(other->picture_map_),
43 tiling_(other->tiling_),
44 background_color_(other->background_color_),
45 requires_clear_(other->requires_clear_),
46 can_use_lcd_text_(can_use_lcd_text),
47 is_solid_color_(other->is_solid_color_),
48 solid_color_(other->solid_color_),
49 recorded_viewport_(other->recorded_viewport_),
50 has_any_recordings_(other->has_any_recordings_),
51 clear_canvas_with_debug_color_(other->clear_canvas_with_debug_color_),
52 min_contents_scale_(other->min_contents_scale_),
53 slow_down_raster_scale_factor_for_debug_(
54 other->slow_down_raster_scale_factor_for_debug_),
55 should_attempt_to_use_distance_field_text_(false) {
58 PicturePileImpl::PicturePileImpl(const PicturePileImpl* other,
59 bool can_use_lcd_text)
60 : picture_map_(other->picture_map_),
61 tiling_(other->tiling_),
62 background_color_(other->background_color_),
63 requires_clear_(other->requires_clear_),
64 can_use_lcd_text_(can_use_lcd_text),
65 is_solid_color_(other->is_solid_color_),
66 solid_color_(other->solid_color_),
67 recorded_viewport_(other->recorded_viewport_),
68 has_any_recordings_(other->has_any_recordings_),
69 clear_canvas_with_debug_color_(other->clear_canvas_with_debug_color_),
70 min_contents_scale_(other->min_contents_scale_),
71 slow_down_raster_scale_factor_for_debug_(
72 other->slow_down_raster_scale_factor_for_debug_),
73 should_attempt_to_use_distance_field_text_(
74 other->should_attempt_to_use_distance_field_text_) {
77 PicturePileImpl::~PicturePileImpl() {
80 void PicturePileImpl::PlaybackToSharedCanvas(SkCanvas* canvas,
81 const gfx::Rect& canvas_rect,
82 float contents_scale) const {
83 RasterCommon(canvas, NULL, canvas_rect, contents_scale);
86 void PicturePileImpl::RasterForAnalysis(skia::AnalysisCanvas* canvas,
87 const gfx::Rect& canvas_rect,
88 float contents_scale) const {
89 RasterCommon(canvas, canvas, canvas_rect, contents_scale);
92 void PicturePileImpl::PlaybackToCanvas(SkCanvas* canvas,
93 const gfx::Rect& canvas_rect,
94 float contents_scale) const {
95 RasterSourceHelper::PrepareForPlaybackToCanvas(
96 canvas, canvas_rect, gfx::Rect(tiling_.tiling_size()), contents_scale,
97 background_color_, clear_canvas_with_debug_color_, requires_clear_);
98 RasterCommon(canvas, NULL, canvas_rect, contents_scale);
101 void PicturePileImpl::CoalesceRasters(const gfx::Rect& canvas_rect,
102 const gfx::Rect& content_rect,
103 float contents_scale,
104 PictureRegionMap* results) const {
105 DCHECK(results);
106 // Rasterize the collection of relevant picture piles.
107 gfx::Rect layer_rect = gfx::ScaleToEnclosingRect(
108 content_rect, 1.f / contents_scale);
110 // Make sure pictures don't overlap by keeping track of previous right/bottom.
111 int min_content_left = -1;
112 int min_content_top = -1;
113 int last_row_index = -1;
114 int last_col_index = -1;
115 gfx::Rect last_content_rect;
117 // Coalesce rasters of the same picture into different rects:
118 // - Compute the clip of each of the pile chunks,
119 // - Subtract it from the canvas rect to get difference region
120 // - Later, use the difference region to subtract each of the comprising
121 // rects from the canvas.
122 // Note that in essence, we're trying to mimic clipRegion with intersect op
123 // that also respects the current canvas transform and clip. In order to use
124 // the canvas transform, we must stick to clipRect operations (clipRegion
125 // ignores the transform). Intersect then can be written as subtracting the
126 // negation of the region we're trying to intersect. Luckily, we know that all
127 // of the rects will have to fit into |content_rect|, so we can start with
128 // that and subtract chunk rects to get the region that we need to subtract
129 // from the canvas. Then, we can use clipRect with difference op to subtract
130 // each rect in the region.
131 bool include_borders = true;
132 for (TilingData::Iterator tile_iter(&tiling_, layer_rect, include_borders);
133 tile_iter;
134 ++tile_iter) {
135 PictureMap::const_iterator map_iter = picture_map_.find(tile_iter.index());
136 if (map_iter == picture_map_.end())
137 continue;
138 const Picture* picture = map_iter->second.get();
139 DCHECK(picture);
141 // This is intentionally *enclosed* rect, so that the clip is aligned on
142 // integral post-scale content pixels and does not extend past the edges
143 // of the picture chunk's layer rect. The min_contents_scale enforces that
144 // enough buffer pixels have been added such that the enclosed rect
145 // encompasses all invalidated pixels at any larger scale level.
146 gfx::Rect chunk_rect = PaddedRect(tile_iter.index());
147 gfx::Rect content_clip =
148 gfx::ScaleToEnclosedRect(chunk_rect, contents_scale);
149 DCHECK(!content_clip.IsEmpty()) << "Layer rect: "
150 << picture->LayerRect().ToString()
151 << "Contents scale: " << contents_scale;
152 content_clip.Intersect(canvas_rect);
154 // Make sure iterator goes top->bottom.
155 DCHECK_GE(tile_iter.index_y(), last_row_index);
156 if (tile_iter.index_y() > last_row_index) {
157 // First tile in a new row.
158 min_content_left = content_clip.x();
159 min_content_top = last_content_rect.bottom();
160 } else {
161 // Make sure iterator goes left->right.
162 DCHECK_GT(tile_iter.index_x(), last_col_index);
163 min_content_left = last_content_rect.right();
164 min_content_top = last_content_rect.y();
167 last_col_index = tile_iter.index_x();
168 last_row_index = tile_iter.index_y();
170 // Only inset if the content_clip is less than then previous min.
171 int inset_left = std::max(0, min_content_left - content_clip.x());
172 int inset_top = std::max(0, min_content_top - content_clip.y());
173 content_clip.Inset(inset_left, inset_top, 0, 0);
175 PictureRegionMap::iterator it = results->find(picture);
176 Region* clip_region;
177 if (it == results->end()) {
178 // The clip for a set of coalesced pictures starts out clipping the entire
179 // canvas. Each picture added to the set must subtract its own bounds
180 // from the clip region, poking a hole so that the picture is unclipped.
181 clip_region = &(*results)[picture];
182 *clip_region = canvas_rect;
183 } else {
184 clip_region = &it->second;
187 DCHECK(clip_region->Contains(content_clip))
188 << "Content clips should not overlap.";
189 clip_region->Subtract(content_clip);
190 last_content_rect = content_clip;
194 void PicturePileImpl::RasterCommon(SkCanvas* canvas,
195 SkDrawPictureCallback* callback,
196 const gfx::Rect& canvas_rect,
197 float contents_scale) const {
198 DCHECK(contents_scale >= min_contents_scale_);
200 canvas->translate(-canvas_rect.x(), -canvas_rect.y());
201 gfx::Rect content_tiling_rect = gfx::ToEnclosingRect(
202 gfx::ScaleRect(gfx::Rect(tiling_.tiling_size()), contents_scale));
203 content_tiling_rect.Intersect(canvas_rect);
205 canvas->clipRect(gfx::RectToSkRect(content_tiling_rect),
206 SkRegion::kIntersect_Op);
208 PictureRegionMap picture_region_map;
209 CoalesceRasters(
210 canvas_rect, content_tiling_rect, contents_scale, &picture_region_map);
212 #ifndef NDEBUG
213 Region total_clip;
214 #endif // NDEBUG
216 // Iterate the coalesced map and use each picture's region
217 // to clip the canvas.
218 for (PictureRegionMap::iterator it = picture_region_map.begin();
219 it != picture_region_map.end();
220 ++it) {
221 const Picture* picture = it->first;
222 Region negated_clip_region = it->second;
224 #ifndef NDEBUG
225 Region positive_clip = content_tiling_rect;
226 positive_clip.Subtract(negated_clip_region);
227 // Make sure we never rasterize the same region twice.
228 DCHECK(!total_clip.Intersects(positive_clip));
229 total_clip.Union(positive_clip);
230 #endif // NDEBUG
232 int repeat_count = std::max(1, slow_down_raster_scale_factor_for_debug_);
234 for (int j = 0; j < repeat_count; ++j)
235 picture->Raster(canvas, callback, negated_clip_region, contents_scale);
238 #ifndef NDEBUG
239 // Fill the clip with debug color. This allows us to
240 // distinguish between non painted areas and problems with missing
241 // pictures.
242 SkPaint paint;
243 for (Region::Iterator it(total_clip); it.has_rect(); it.next())
244 canvas->clipRect(gfx::RectToSkRect(it.rect()), SkRegion::kDifference_Op);
245 paint.setColor(DebugColors::MissingPictureFillColor());
246 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
247 canvas->drawPaint(paint);
248 #endif // NDEBUG
251 skia::RefPtr<SkPicture> PicturePileImpl::GetFlattenedPicture() {
252 TRACE_EVENT0("cc", "PicturePileImpl::GetFlattenedPicture");
254 gfx::Rect tiling_rect(tiling_.tiling_size());
255 SkPictureRecorder recorder;
256 SkCanvas* canvas =
257 recorder.beginRecording(tiling_rect.width(), tiling_rect.height());
258 if (!tiling_rect.IsEmpty())
259 PlaybackToCanvas(canvas, tiling_rect, 1.0);
260 skia::RefPtr<SkPicture> picture = skia::AdoptRef(recorder.endRecording());
262 return picture;
265 size_t PicturePileImpl::GetPictureMemoryUsage() const {
266 // Place all pictures in a set to de-dupe.
267 size_t total_size = 0;
268 std::set<const Picture*> pictures_seen;
269 for (const auto& map_value : picture_map_) {
270 const Picture* picture = map_value.second.get();
271 if (pictures_seen.insert(picture).second)
272 total_size += picture->ApproximateMemoryUsage();
275 return total_size;
278 void PicturePileImpl::PerformSolidColorAnalysis(
279 const gfx::Rect& content_rect,
280 float contents_scale,
281 RasterSource::SolidColorAnalysis* analysis) const {
282 DCHECK(analysis);
283 TRACE_EVENT0("cc", "PicturePileImpl::PerformSolidColorAnalysis");
285 gfx::Rect layer_rect = gfx::ScaleToEnclosingRect(
286 content_rect, 1.0f / contents_scale);
288 layer_rect.Intersect(gfx::Rect(tiling_.tiling_size()));
290 skia::AnalysisCanvas canvas(layer_rect.width(), layer_rect.height());
292 RasterForAnalysis(&canvas, layer_rect, 1.0f);
294 analysis->is_solid_color = canvas.GetColorIfSolid(&analysis->solid_color);
297 void PicturePileImpl::GatherPixelRefs(
298 const gfx::Rect& content_rect,
299 float contents_scale,
300 std::vector<SkPixelRef*>* pixel_refs) const {
301 DCHECK_EQ(0u, pixel_refs->size());
302 for (PixelRefIterator iter(content_rect, contents_scale, this); iter;
303 ++iter) {
304 pixel_refs->push_back(*iter);
308 bool PicturePileImpl::CoversRect(const gfx::Rect& content_rect,
309 float contents_scale) const {
310 if (tiling_.tiling_size().IsEmpty())
311 return false;
312 gfx::Rect layer_rect =
313 gfx::ScaleToEnclosingRect(content_rect, 1.f / contents_scale);
314 layer_rect.Intersect(gfx::Rect(tiling_.tiling_size()));
316 // Common case inside of viewport to avoid the slower map lookups.
317 if (recorded_viewport_.Contains(layer_rect)) {
318 // Sanity check that there are no false positives in recorded_viewport_.
319 DCHECK(CanRasterSlowTileCheck(layer_rect));
320 return true;
323 return CanRasterSlowTileCheck(layer_rect);
326 gfx::Size PicturePileImpl::GetSize() const {
327 return tiling_.tiling_size();
330 bool PicturePileImpl::IsSolidColor() const {
331 return is_solid_color_;
334 SkColor PicturePileImpl::GetSolidColor() const {
335 DCHECK(IsSolidColor());
336 return solid_color_;
339 bool PicturePileImpl::HasRecordings() const {
340 return has_any_recordings_;
343 gfx::Rect PicturePileImpl::PaddedRect(const PictureMapKey& key) const {
344 gfx::Rect padded_rect = tiling_.TileBounds(key.first, key.second);
345 padded_rect.Inset(-buffer_pixels(), -buffer_pixels(), -buffer_pixels(),
346 -buffer_pixels());
347 return padded_rect;
350 bool PicturePileImpl::CanRasterSlowTileCheck(
351 const gfx::Rect& layer_rect) const {
352 bool include_borders = false;
353 for (TilingData::Iterator tile_iter(&tiling_, layer_rect, include_borders);
354 tile_iter; ++tile_iter) {
355 PictureMap::const_iterator map_iter = picture_map_.find(tile_iter.index());
356 if (map_iter == picture_map_.end())
357 return false;
359 return true;
362 void PicturePileImpl::SetShouldAttemptToUseDistanceFieldText() {
363 should_attempt_to_use_distance_field_text_ = true;
366 bool PicturePileImpl::ShouldAttemptToUseDistanceFieldText() const {
367 return should_attempt_to_use_distance_field_text_;
370 void PicturePileImpl::AsValueInto(
371 base::trace_event::TracedValue* pictures) const {
372 gfx::Rect tiling_rect(tiling_.tiling_size());
373 std::set<const void*> appended_pictures;
374 bool include_borders = true;
375 for (TilingData::Iterator tile_iter(&tiling_, tiling_rect, include_borders);
376 tile_iter; ++tile_iter) {
377 PictureMap::const_iterator map_iter = picture_map_.find(tile_iter.index());
378 if (map_iter == picture_map_.end())
379 continue;
381 const Picture* picture = map_iter->second.get();
382 if (appended_pictures.count(picture) == 0) {
383 appended_pictures.insert(picture);
384 TracedValue::AppendIDRef(picture, pictures);
389 bool PicturePileImpl::CanUseLCDText() const {
390 return can_use_lcd_text_;
393 scoped_refptr<RasterSource> PicturePileImpl::CreateCloneWithoutLCDText() const {
394 DCHECK(CanUseLCDText());
395 bool can_use_lcd_text = false;
396 return scoped_refptr<RasterSource>(
397 new PicturePileImpl(this, can_use_lcd_text));
400 PicturePileImpl::PixelRefIterator::PixelRefIterator(
401 const gfx::Rect& content_rect,
402 float contents_scale,
403 const PicturePileImpl* picture_pile)
404 : picture_pile_(picture_pile),
405 layer_rect_(
406 gfx::ScaleToEnclosingRect(content_rect, 1.f / contents_scale)),
407 tile_iterator_(&picture_pile_->tiling_,
408 layer_rect_,
409 false /* include_borders */) {
410 // Early out if there isn't a single tile.
411 if (!tile_iterator_)
412 return;
414 AdvanceToTilePictureWithPixelRefs();
417 PicturePileImpl::PixelRefIterator::~PixelRefIterator() {
420 PicturePileImpl::PixelRefIterator&
421 PicturePileImpl::PixelRefIterator::operator++() {
422 ++pixel_ref_iterator_;
423 if (pixel_ref_iterator_)
424 return *this;
426 ++tile_iterator_;
427 AdvanceToTilePictureWithPixelRefs();
428 return *this;
431 void PicturePileImpl::PixelRefIterator::AdvanceToTilePictureWithPixelRefs() {
432 for (; tile_iterator_; ++tile_iterator_) {
433 PictureMap::const_iterator it =
434 picture_pile_->picture_map_.find(tile_iterator_.index());
435 if (it == picture_pile_->picture_map_.end())
436 continue;
438 const Picture* picture = it->second.get();
439 if ((processed_pictures_.count(picture) != 0) ||
440 !picture->WillPlayBackBitmaps())
441 continue;
443 processed_pictures_.insert(picture);
444 pixel_ref_iterator_ = picture->GetPixelRefMapIterator(layer_rect_);
445 if (pixel_ref_iterator_)
446 break;
450 void PicturePileImpl::DidBeginTracing() {
451 std::set<const void*> processed_pictures;
452 for (const auto& map_pair : picture_map_) {
453 const Picture* picture = map_pair.second.get();
454 if (processed_pictures.count(picture) == 0) {
455 picture->EmitTraceSnapshot();
456 processed_pictures.insert(picture);
461 } // namespace cc