Update mojo surfaces bindings and mojo/cc/ glue
[chromium-blink-merge.git] / cc / resources / picture.cc
blob06e9cc93f1455390870be13579fda9950ba4ac64
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/picture.h"
7 #include <algorithm>
8 #include <limits>
9 #include <set>
11 #include "base/base64.h"
12 #include "base/debug/trace_event.h"
13 #include "base/debug/trace_event_argument.h"
14 #include "base/values.h"
15 #include "cc/base/math_util.h"
16 #include "cc/base/util.h"
17 #include "cc/debug/traced_picture.h"
18 #include "cc/debug/traced_value.h"
19 #include "cc/layers/content_layer_client.h"
20 #include "skia/ext/pixel_ref_utils.h"
21 #include "third_party/skia/include/core/SkCanvas.h"
22 #include "third_party/skia/include/core/SkData.h"
23 #include "third_party/skia/include/core/SkDrawFilter.h"
24 #include "third_party/skia/include/core/SkPaint.h"
25 #include "third_party/skia/include/core/SkPictureRecorder.h"
26 #include "third_party/skia/include/core/SkStream.h"
27 #include "third_party/skia/include/utils/SkNullCanvas.h"
28 #include "third_party/skia/include/utils/SkPictureUtils.h"
29 #include "ui/gfx/codec/jpeg_codec.h"
30 #include "ui/gfx/codec/png_codec.h"
31 #include "ui/gfx/rect_conversions.h"
32 #include "ui/gfx/skia_util.h"
34 namespace cc {
36 namespace {
38 SkData* EncodeBitmap(size_t* offset, const SkBitmap& bm) {
39 const int kJpegQuality = 80;
40 std::vector<unsigned char> data;
42 // If bitmap is opaque, encode as JPEG.
43 // Otherwise encode as PNG.
44 bool encoding_succeeded = false;
45 if (bm.isOpaque()) {
46 SkAutoLockPixels lock_bitmap(bm);
47 if (bm.empty())
48 return NULL;
50 encoding_succeeded = gfx::JPEGCodec::Encode(
51 reinterpret_cast<unsigned char*>(bm.getAddr32(0, 0)),
52 gfx::JPEGCodec::FORMAT_SkBitmap,
53 bm.width(),
54 bm.height(),
55 bm.rowBytes(),
56 kJpegQuality,
57 &data);
58 } else {
59 encoding_succeeded = gfx::PNGCodec::EncodeBGRASkBitmap(bm, false, &data);
62 if (encoding_succeeded) {
63 *offset = 0;
64 return SkData::NewWithCopy(&data.front(), data.size());
66 return NULL;
69 bool DecodeBitmap(const void* buffer, size_t size, SkBitmap* bm) {
70 const unsigned char* data = static_cast<const unsigned char *>(buffer);
72 // Try PNG first.
73 if (gfx::PNGCodec::Decode(data, size, bm))
74 return true;
76 // Try JPEG.
77 scoped_ptr<SkBitmap> decoded_jpeg(gfx::JPEGCodec::Decode(data, size));
78 if (decoded_jpeg) {
79 *bm = *decoded_jpeg;
80 return true;
82 return false;
85 } // namespace
87 scoped_refptr<Picture> Picture::Create(
88 const gfx::Rect& layer_rect,
89 ContentLayerClient* client,
90 const SkTileGridFactory::TileGridInfo& tile_grid_info,
91 bool gather_pixel_refs,
92 RecordingMode recording_mode) {
93 scoped_refptr<Picture> picture = make_scoped_refptr(new Picture(layer_rect));
95 picture->Record(client, tile_grid_info, recording_mode);
96 if (gather_pixel_refs)
97 picture->GatherPixelRefs(tile_grid_info);
99 return picture;
102 Picture::Picture(const gfx::Rect& layer_rect)
103 : layer_rect_(layer_rect),
104 cell_size_(layer_rect.size()) {
105 // Instead of recording a trace event for object creation here, we wait for
106 // the picture to be recorded in Picture::Record.
109 scoped_refptr<Picture> Picture::CreateFromSkpValue(const base::Value* value) {
110 // Decode the picture from base64.
111 std::string encoded;
112 if (!value->GetAsString(&encoded))
113 return NULL;
115 std::string decoded;
116 base::Base64Decode(encoded, &decoded);
117 SkMemoryStream stream(decoded.data(), decoded.size());
119 // Read the picture. This creates an empty picture on failure.
120 SkPicture* skpicture = SkPicture::CreateFromStream(&stream, &DecodeBitmap);
121 if (skpicture == NULL)
122 return NULL;
124 gfx::Rect layer_rect(skpicture->width(), skpicture->height());
125 gfx::Rect opaque_rect(skpicture->width(), skpicture->height());
127 return make_scoped_refptr(new Picture(skpicture, layer_rect, opaque_rect));
130 scoped_refptr<Picture> Picture::CreateFromValue(const base::Value* raw_value) {
131 const base::DictionaryValue* value = NULL;
132 if (!raw_value->GetAsDictionary(&value))
133 return NULL;
135 // Decode the picture from base64.
136 std::string encoded;
137 if (!value->GetString("skp64", &encoded))
138 return NULL;
140 std::string decoded;
141 base::Base64Decode(encoded, &decoded);
142 SkMemoryStream stream(decoded.data(), decoded.size());
144 const base::Value* layer_rect_value = NULL;
145 if (!value->Get("params.layer_rect", &layer_rect_value))
146 return NULL;
148 gfx::Rect layer_rect;
149 if (!MathUtil::FromValue(layer_rect_value, &layer_rect))
150 return NULL;
152 const base::Value* opaque_rect_value = NULL;
153 if (!value->Get("params.opaque_rect", &opaque_rect_value))
154 return NULL;
156 gfx::Rect opaque_rect;
157 if (!MathUtil::FromValue(opaque_rect_value, &opaque_rect))
158 return NULL;
160 // Read the picture. This creates an empty picture on failure.
161 SkPicture* skpicture = SkPicture::CreateFromStream(&stream, &DecodeBitmap);
162 if (skpicture == NULL)
163 return NULL;
165 return make_scoped_refptr(new Picture(skpicture, layer_rect, opaque_rect));
168 Picture::Picture(SkPicture* picture,
169 const gfx::Rect& layer_rect,
170 const gfx::Rect& opaque_rect) :
171 layer_rect_(layer_rect),
172 opaque_rect_(opaque_rect),
173 picture_(skia::AdoptRef(picture)),
174 cell_size_(layer_rect.size()) {
177 Picture::Picture(const skia::RefPtr<SkPicture>& picture,
178 const gfx::Rect& layer_rect,
179 const gfx::Rect& opaque_rect,
180 const PixelRefMap& pixel_refs) :
181 layer_rect_(layer_rect),
182 opaque_rect_(opaque_rect),
183 picture_(picture),
184 pixel_refs_(pixel_refs),
185 cell_size_(layer_rect.size()) {
188 Picture::~Picture() {
189 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
190 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::Picture", this);
193 bool Picture::IsSuitableForGpuRasterization() const {
194 DCHECK(picture_);
196 // TODO(alokp): SkPicture::suitableForGpuRasterization needs a GrContext.
197 // Ideally this GrContext should be the same as that for rasterizing this
198 // picture. But we are on the main thread while the rasterization context
199 // may be on the compositor or raster thread.
200 // SkPicture::suitableForGpuRasterization is not implemented yet.
201 // Pass a NULL context for now and discuss with skia folks if the context
202 // is really needed.
203 return picture_->suitableForGpuRasterization(NULL);
206 bool Picture::HasText() const {
207 DCHECK(picture_);
208 return picture_->hasText();
211 void Picture::Record(ContentLayerClient* painter,
212 const SkTileGridFactory::TileGridInfo& tile_grid_info,
213 RecordingMode recording_mode) {
214 TRACE_EVENT2("cc",
215 "Picture::Record",
216 "data",
217 AsTraceableRecordData(),
218 "recording_mode",
219 recording_mode);
221 DCHECK(!picture_);
222 DCHECK(!tile_grid_info.fTileInterval.isEmpty());
224 SkTileGridFactory factory(tile_grid_info);
225 SkPictureRecorder recorder;
227 scoped_ptr<EXPERIMENTAL::SkRecording> recording;
229 skia::RefPtr<SkCanvas> canvas;
230 canvas = skia::SharePtr(recorder.beginRecording(
231 layer_rect_.width(), layer_rect_.height(), &factory));
233 ContentLayerClient::GraphicsContextStatus graphics_context_status =
234 ContentLayerClient::GRAPHICS_CONTEXT_ENABLED;
236 switch (recording_mode) {
237 case RECORD_NORMALLY:
238 // Already setup for normal recording.
239 break;
240 case RECORD_WITH_SK_NULL_CANVAS:
241 canvas = skia::AdoptRef(SkCreateNullCanvas());
242 break;
243 case RECORD_WITH_PAINTING_DISABLED:
244 // We pass a disable flag through the paint calls when perfromance
245 // testing (the only time this case should ever arise) when we want to
246 // prevent the Blink GraphicsContext object from consuming any compute
247 // time.
248 canvas = skia::AdoptRef(SkCreateNullCanvas());
249 graphics_context_status = ContentLayerClient::GRAPHICS_CONTEXT_DISABLED;
250 break;
251 case RECORD_WITH_SKRECORD:
252 recording.reset(new EXPERIMENTAL::SkRecording(layer_rect_.width(),
253 layer_rect_.height()));
254 canvas = skia::SharePtr(recording->canvas());
255 break;
256 default:
257 NOTREACHED();
260 canvas->save();
261 canvas->translate(SkFloatToScalar(-layer_rect_.x()),
262 SkFloatToScalar(-layer_rect_.y()));
264 SkRect layer_skrect = SkRect::MakeXYWH(layer_rect_.x(),
265 layer_rect_.y(),
266 layer_rect_.width(),
267 layer_rect_.height());
268 canvas->clipRect(layer_skrect);
270 gfx::RectF opaque_layer_rect;
271 painter->PaintContents(
272 canvas.get(), layer_rect_, &opaque_layer_rect, graphics_context_status);
274 canvas->restore();
275 picture_ = skia::AdoptRef(recorder.endRecording());
276 DCHECK(picture_);
278 if (recording) {
279 // SkRecording requires it's the only one holding onto canvas before we
280 // may call releasePlayback(). (This helps enforce thread-safety.)
281 canvas.clear();
282 playback_.reset(recording->releasePlayback());
285 opaque_rect_ = gfx::ToEnclosedRect(opaque_layer_rect);
287 EmitTraceSnapshot();
290 void Picture::GatherPixelRefs(
291 const SkTileGridFactory::TileGridInfo& tile_grid_info) {
292 TRACE_EVENT2("cc", "Picture::GatherPixelRefs",
293 "width", layer_rect_.width(),
294 "height", layer_rect_.height());
296 DCHECK(picture_);
297 DCHECK(pixel_refs_.empty());
298 if (!WillPlayBackBitmaps())
299 return;
300 cell_size_ = gfx::Size(
301 tile_grid_info.fTileInterval.width() +
302 2 * tile_grid_info.fMargin.width(),
303 tile_grid_info.fTileInterval.height() +
304 2 * tile_grid_info.fMargin.height());
305 DCHECK_GT(cell_size_.width(), 0);
306 DCHECK_GT(cell_size_.height(), 0);
308 int min_x = std::numeric_limits<int>::max();
309 int min_y = std::numeric_limits<int>::max();
310 int max_x = 0;
311 int max_y = 0;
313 skia::DiscardablePixelRefList pixel_refs;
314 skia::PixelRefUtils::GatherDiscardablePixelRefs(picture_.get(), &pixel_refs);
315 for (skia::DiscardablePixelRefList::const_iterator it = pixel_refs.begin();
316 it != pixel_refs.end();
317 ++it) {
318 gfx::Point min(
319 RoundDown(static_cast<int>(it->pixel_ref_rect.x()),
320 cell_size_.width()),
321 RoundDown(static_cast<int>(it->pixel_ref_rect.y()),
322 cell_size_.height()));
323 gfx::Point max(
324 RoundDown(static_cast<int>(std::ceil(it->pixel_ref_rect.right())),
325 cell_size_.width()),
326 RoundDown(static_cast<int>(std::ceil(it->pixel_ref_rect.bottom())),
327 cell_size_.height()));
329 for (int y = min.y(); y <= max.y(); y += cell_size_.height()) {
330 for (int x = min.x(); x <= max.x(); x += cell_size_.width()) {
331 PixelRefMapKey key(x, y);
332 pixel_refs_[key].push_back(it->pixel_ref);
336 min_x = std::min(min_x, min.x());
337 min_y = std::min(min_y, min.y());
338 max_x = std::max(max_x, max.x());
339 max_y = std::max(max_y, max.y());
342 min_pixel_cell_ = gfx::Point(min_x, min_y);
343 max_pixel_cell_ = gfx::Point(max_x, max_y);
346 int Picture::Raster(SkCanvas* canvas,
347 SkDrawPictureCallback* callback,
348 const Region& negated_content_region,
349 float contents_scale) const {
350 TRACE_EVENT_BEGIN1(
351 "cc",
352 "Picture::Raster",
353 "data",
354 AsTraceableRasterData(contents_scale));
356 DCHECK(picture_);
358 canvas->save();
360 for (Region::Iterator it(negated_content_region); it.has_rect(); it.next())
361 canvas->clipRect(gfx::RectToSkRect(it.rect()), SkRegion::kDifference_Op);
363 canvas->scale(contents_scale, contents_scale);
364 canvas->translate(layer_rect_.x(), layer_rect_.y());
365 if (playback_) {
366 playback_->draw(canvas);
367 } else {
368 picture_->draw(canvas, callback);
370 SkIRect bounds;
371 canvas->getClipDeviceBounds(&bounds);
372 canvas->restore();
373 TRACE_EVENT_END1(
374 "cc", "Picture::Raster",
375 "num_pixels_rasterized", bounds.width() * bounds.height());
376 return bounds.width() * bounds.height();
379 void Picture::Replay(SkCanvas* canvas) {
380 TRACE_EVENT_BEGIN0("cc", "Picture::Replay");
381 DCHECK(picture_);
383 if (playback_) {
384 playback_->draw(canvas);
385 } else {
386 picture_->draw(canvas);
388 SkIRect bounds;
389 canvas->getClipDeviceBounds(&bounds);
390 TRACE_EVENT_END1("cc", "Picture::Replay",
391 "num_pixels_replayed", bounds.width() * bounds.height());
394 scoped_ptr<base::Value> Picture::AsValue() const {
395 SkDynamicMemoryWStream stream;
397 if (playback_) {
398 // SkPlayback can't serialize itself, so re-record into an SkPicture.
399 SkPictureRecorder recorder;
400 skia::RefPtr<SkCanvas> canvas(skia::SharePtr(recorder.beginRecording(
401 layer_rect_.width(),
402 layer_rect_.height(),
403 NULL))); // Default (no) bounding-box hierarchy is fastest.
404 playback_->draw(canvas.get());
405 skia::RefPtr<SkPicture> picture(skia::AdoptRef(recorder.endRecording()));
406 picture->serialize(&stream, &EncodeBitmap);
407 } else {
408 // Serialize the picture.
409 picture_->serialize(&stream, &EncodeBitmap);
412 // Encode the picture as base64.
413 scoped_ptr<base::DictionaryValue> res(new base::DictionaryValue());
414 res->Set("params.layer_rect", MathUtil::AsValue(layer_rect_).release());
415 res->Set("params.opaque_rect", MathUtil::AsValue(opaque_rect_).release());
417 size_t serialized_size = stream.bytesWritten();
418 scoped_ptr<char[]> serialized_picture(new char[serialized_size]);
419 stream.copyTo(serialized_picture.get());
420 std::string b64_picture;
421 base::Base64Encode(std::string(serialized_picture.get(), serialized_size),
422 &b64_picture);
423 res->SetString("skp64", b64_picture);
424 return res.PassAs<base::Value>();
427 void Picture::EmitTraceSnapshot() const {
428 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
429 TRACE_DISABLED_BY_DEFAULT("cc.debug") "," TRACE_DISABLED_BY_DEFAULT(
430 "devtools.timeline.picture"),
431 "cc::Picture",
432 this,
433 TracedPicture::AsTraceablePicture(this));
436 void Picture::EmitTraceSnapshotAlias(Picture* original) const {
437 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
438 TRACE_DISABLED_BY_DEFAULT("cc.debug") "," TRACE_DISABLED_BY_DEFAULT(
439 "devtools.timeline.picture"),
440 "cc::Picture",
441 this,
442 TracedPicture::AsTraceablePictureAlias(original));
445 base::LazyInstance<Picture::PixelRefs>
446 Picture::PixelRefIterator::empty_pixel_refs_;
448 Picture::PixelRefIterator::PixelRefIterator()
449 : picture_(NULL),
450 current_pixel_refs_(empty_pixel_refs_.Pointer()),
451 current_index_(0),
452 min_point_(-1, -1),
453 max_point_(-1, -1),
454 current_x_(0),
455 current_y_(0) {
458 Picture::PixelRefIterator::PixelRefIterator(
459 const gfx::Rect& rect,
460 const Picture* picture)
461 : picture_(picture),
462 current_pixel_refs_(empty_pixel_refs_.Pointer()),
463 current_index_(0) {
464 gfx::Rect layer_rect = picture->layer_rect_;
465 gfx::Size cell_size = picture->cell_size_;
466 DCHECK(!cell_size.IsEmpty());
468 gfx::Rect query_rect(rect);
469 // Early out if the query rect doesn't intersect this picture.
470 if (!query_rect.Intersects(layer_rect)) {
471 min_point_ = gfx::Point(0, 0);
472 max_point_ = gfx::Point(0, 0);
473 current_x_ = 1;
474 current_y_ = 1;
475 return;
478 // First, subtract the layer origin as cells are stored in layer space.
479 query_rect.Offset(-layer_rect.OffsetFromOrigin());
481 // We have to find a cell_size aligned point that corresponds to
482 // query_rect. Point is a multiple of cell_size.
483 min_point_ = gfx::Point(
484 RoundDown(query_rect.x(), cell_size.width()),
485 RoundDown(query_rect.y(), cell_size.height()));
486 max_point_ = gfx::Point(
487 RoundDown(query_rect.right() - 1, cell_size.width()),
488 RoundDown(query_rect.bottom() - 1, cell_size.height()));
490 // Limit the points to known pixel ref boundaries.
491 min_point_ = gfx::Point(
492 std::max(min_point_.x(), picture->min_pixel_cell_.x()),
493 std::max(min_point_.y(), picture->min_pixel_cell_.y()));
494 max_point_ = gfx::Point(
495 std::min(max_point_.x(), picture->max_pixel_cell_.x()),
496 std::min(max_point_.y(), picture->max_pixel_cell_.y()));
498 // Make the current x be cell_size.width() less than min point, so that
499 // the first increment will point at min_point_.
500 current_x_ = min_point_.x() - cell_size.width();
501 current_y_ = min_point_.y();
502 if (current_y_ <= max_point_.y())
503 ++(*this);
506 Picture::PixelRefIterator::~PixelRefIterator() {
509 Picture::PixelRefIterator& Picture::PixelRefIterator::operator++() {
510 ++current_index_;
511 // If we're not at the end of the list, then we have the next item.
512 if (current_index_ < current_pixel_refs_->size())
513 return *this;
515 DCHECK(current_y_ <= max_point_.y());
516 while (true) {
517 gfx::Size cell_size = picture_->cell_size_;
519 // Advance the current grid cell.
520 current_x_ += cell_size.width();
521 if (current_x_ > max_point_.x()) {
522 current_y_ += cell_size.height();
523 current_x_ = min_point_.x();
524 if (current_y_ > max_point_.y()) {
525 current_pixel_refs_ = empty_pixel_refs_.Pointer();
526 current_index_ = 0;
527 break;
531 // If there are no pixel refs at this grid cell, keep incrementing.
532 PixelRefMapKey key(current_x_, current_y_);
533 PixelRefMap::const_iterator iter = picture_->pixel_refs_.find(key);
534 if (iter == picture_->pixel_refs_.end())
535 continue;
537 // We found a non-empty list: store it and get the first pixel ref.
538 current_pixel_refs_ = &iter->second;
539 current_index_ = 0;
540 break;
542 return *this;
545 scoped_refptr<base::debug::ConvertableToTraceFormat>
546 Picture::AsTraceableRasterData(float scale) const {
547 scoped_refptr<base::debug::TracedValue> raster_data =
548 new base::debug::TracedValue();
549 TracedValue::SetIDRef(this, raster_data.get(), "picture_id");
550 raster_data->SetDouble("scale", scale);
551 return raster_data;
554 scoped_refptr<base::debug::ConvertableToTraceFormat>
555 Picture::AsTraceableRecordData() const {
556 scoped_refptr<base::debug::TracedValue> record_data =
557 new base::debug::TracedValue();
558 TracedValue::SetIDRef(this, record_data.get(), "picture_id");
559 record_data->BeginArray("layer_rect");
560 MathUtil::AddToTracedValue(layer_rect_, record_data.get());
561 record_data->EndArray();
562 return record_data;
565 } // namespace cc