Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / content / renderer / skia_benchmarking_extension.cc
1 // Copyright (c) 2013 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.
4
5 #include "content/renderer/skia_benchmarking_extension.h"
6
7 #include "base/base64.h"
8 #include "base/time/time.h"
9 #include "base/values.h"
10 #include "cc/base/math_util.h"
11 #include "cc/resources/picture.h"
12 #include "content/public/renderer/v8_value_converter.h"
13 #include "content/renderer/render_thread_impl.h"
14 #include "gin/arguments.h"
15 #include "gin/handle.h"
16 #include "gin/object_template_builder.h"
17 #include "skia/ext/benchmarking_canvas.h"
18 #include "third_party/WebKit/public/platform/WebArrayBuffer.h"
19 #include "third_party/WebKit/public/web/WebFrame.h"
20 #include "third_party/WebKit/public/web/WebKit.h"
21 #include "third_party/skia/include/core/SkBitmapDevice.h"
22 #include "third_party/skia/include/core/SkCanvas.h"
23 #include "third_party/skia/include/core/SkColorPriv.h"
24 #include "third_party/skia/include/core/SkGraphics.h"
25 #include "third_party/skia/include/core/SkStream.h"
26 #include "third_party/skia/src/utils/debugger/SkDebugCanvas.h"
27 #include "third_party/skia/src/utils/debugger/SkDrawCommand.h"
28 #include "ui/gfx/rect_conversions.h"
29 #include "ui/gfx/skia_util.h"
30 #include "v8/include/v8.h"
31
32
33 namespace content {
34
35 namespace {
36
37 scoped_ptr<base::Value> ParsePictureArg(v8::Isolate* isolate,
38                                         v8::Handle<v8::Value> arg) {
39   scoped_ptr<content::V8ValueConverter> converter(
40       content::V8ValueConverter::create());
41   return scoped_ptr<base::Value>(
42       converter->FromV8Value(arg, isolate->GetCurrentContext()));
43 }
44
45 scoped_refptr<cc::Picture> ParsePictureStr(v8::Isolate* isolate,
46                                            v8::Handle<v8::Value> arg) {
47   scoped_ptr<base::Value> picture_value = ParsePictureArg(isolate, arg);
48   if (!picture_value)
49     return NULL;
50   return cc::Picture::CreateFromSkpValue(picture_value.get());
51 }
52
53 scoped_refptr<cc::Picture> ParsePictureHash(v8::Isolate* isolate,
54                                             v8::Handle<v8::Value> arg) {
55   scoped_ptr<base::Value> picture_value = ParsePictureArg(isolate, arg);
56   if (!picture_value)
57     return NULL;
58   return cc::Picture::CreateFromValue(picture_value.get());
59 }
60
61 }  // namespace
62
63 gin::WrapperInfo SkiaBenchmarking::kWrapperInfo = {gin::kEmbedderNativeGin};
64
65 // static
66 void SkiaBenchmarking::Install(blink::WebFrame* frame) {
67   v8::Isolate* isolate = blink::mainThreadIsolate();
68   v8::HandleScope handle_scope(isolate);
69   v8::Handle<v8::Context> context = frame->mainWorldScriptContext();
70   if (context.IsEmpty())
71     return;
72
73   v8::Context::Scope context_scope(context);
74
75   gin::Handle<SkiaBenchmarking> controller =
76       gin::CreateHandle(isolate, new SkiaBenchmarking());
77   v8::Handle<v8::Object> global = context->Global();
78   v8::Handle<v8::Object> chrome =
79       global->Get(gin::StringToV8(isolate, "chrome"))->ToObject();
80   if (chrome.IsEmpty()) {
81     chrome = v8::Object::New(isolate);
82     global->Set(gin::StringToV8(isolate, "chrome"), chrome);
83   }
84   chrome->Set(gin::StringToV8(isolate, "skiaBenchmarking"), controller.ToV8());
85 }
86
87 // static
88 void SkiaBenchmarking::Initialize() {
89   DCHECK(RenderThreadImpl::current());
90   // FIXME: remove this after Skia updates SkGraphics::Init() to be
91   //        thread-safe and idempotent.
92   static bool skia_initialized = false;
93   if (!skia_initialized) {
94     LOG(WARNING) << "Enabling unsafe Skia benchmarking extension.";
95     SkGraphics::Init();
96     skia_initialized = true;
97   }
98 }
99
100 SkiaBenchmarking::SkiaBenchmarking() {
101   Initialize();
102 }
103
104 SkiaBenchmarking::~SkiaBenchmarking() {}
105
106 gin::ObjectTemplateBuilder SkiaBenchmarking::GetObjectTemplateBuilder(
107     v8::Isolate* isolate) {
108   return gin::Wrappable<SkiaBenchmarking>::GetObjectTemplateBuilder(isolate)
109       .SetMethod("rasterize", &SkiaBenchmarking::Rasterize)
110       .SetMethod("getOps", &SkiaBenchmarking::GetOps)
111       .SetMethod("getOpTimings", &SkiaBenchmarking::GetOpTimings)
112       .SetMethod("getInfo", &SkiaBenchmarking::GetInfo);
113 }
114
115 void SkiaBenchmarking::Rasterize(gin::Arguments* args) {
116   v8::Isolate* isolate = args->isolate();
117   if (args->PeekNext().IsEmpty())
118     return;
119   v8::Handle<v8::Value> picture_handle;
120   args->GetNext(&picture_handle);
121   scoped_refptr<cc::Picture> picture =
122       ParsePictureHash(isolate, picture_handle);
123   if (!picture.get())
124     return;
125
126   double scale = 1.0;
127   gfx::Rect clip_rect(picture->LayerRect());
128   int stop_index = -1;
129   bool overdraw = false;
130
131   if (!args->PeekNext().IsEmpty()) {
132     v8::Handle<v8::Value> params;
133     args->GetNext(&params);
134     scoped_ptr<content::V8ValueConverter> converter(
135         content::V8ValueConverter::create());
136     scoped_ptr<base::Value> params_value(
137         converter->FromV8Value(params, isolate->GetCurrentContext()));
138
139     const base::DictionaryValue* params_dict = NULL;
140     if (params_value.get() && params_value->GetAsDictionary(&params_dict)) {
141       params_dict->GetDouble("scale", &scale);
142       params_dict->GetInteger("stop", &stop_index);
143       params_dict->GetBoolean("overdraw", &overdraw);
144
145       const base::Value* clip_value = NULL;
146       if (params_dict->Get("clip", &clip_value))
147         cc::MathUtil::FromValue(clip_value, &clip_rect);
148     }
149   }
150
151   gfx::RectF clip(clip_rect);
152   clip.Intersect(picture->LayerRect());
153   clip.Scale(scale);
154   gfx::Rect snapped_clip = gfx::ToEnclosingRect(clip);
155
156   const int kMaxBitmapSize = 4096;
157   if (snapped_clip.width() > kMaxBitmapSize ||
158       snapped_clip.height() > kMaxBitmapSize)
159     return;
160
161   SkBitmap bitmap;
162   bitmap.setConfig(
163       SkBitmap::kARGB_8888_Config, snapped_clip.width(), snapped_clip.height());
164   if (!bitmap.allocPixels())
165     return;
166   bitmap.eraseARGB(0, 0, 0, 0);
167
168   SkCanvas canvas(bitmap);
169   canvas.translate(SkFloatToScalar(-clip.x()), SkFloatToScalar(-clip.y()));
170   canvas.clipRect(gfx::RectToSkRect(snapped_clip));
171   canvas.scale(scale, scale);
172   canvas.translate(picture->LayerRect().x(), picture->LayerRect().y());
173
174   // First, build a debug canvas for the given picture.
175   SkDebugCanvas debug_canvas(picture->LayerRect().width(),
176                              picture->LayerRect().height());
177   picture->Replay(&debug_canvas);
178
179   // Raster the requested command subset into the bitmap-backed canvas.
180   int last_index = debug_canvas.getSize() - 1;
181   if (last_index >= 0) {
182     debug_canvas.setOverdrawViz(overdraw);
183     debug_canvas.drawTo(
184         &canvas,
185         stop_index < 0 ? last_index : std::min(last_index, stop_index));
186   }
187
188   blink::WebArrayBuffer buffer =
189       blink::WebArrayBuffer::create(bitmap.getSize(), 1);
190   uint32* packed_pixels = reinterpret_cast<uint32*>(bitmap.getPixels());
191   uint8* buffer_pixels = reinterpret_cast<uint8*>(buffer.data());
192   // Swizzle from native Skia format to RGBA as we copy out.
193   for (size_t i = 0; i < bitmap.getSize(); i += 4) {
194     uint32 c = packed_pixels[i >> 2];
195     buffer_pixels[i] = SkGetPackedR32(c);
196     buffer_pixels[i + 1] = SkGetPackedG32(c);
197     buffer_pixels[i + 2] = SkGetPackedB32(c);
198     buffer_pixels[i + 3] = SkGetPackedA32(c);
199   }
200
201   v8::Handle<v8::Object> result = v8::Object::New(isolate);
202   result->Set(v8::String::NewFromUtf8(isolate, "width"),
203               v8::Number::New(isolate, snapped_clip.width()));
204   result->Set(v8::String::NewFromUtf8(isolate, "height"),
205               v8::Number::New(isolate, snapped_clip.height()));
206   result->Set(v8::String::NewFromUtf8(isolate, "data"), buffer.toV8Value());
207
208   args->Return(result);
209 }
210
211 void SkiaBenchmarking::GetOps(gin::Arguments* args) {
212   v8::Isolate* isolate = args->isolate();
213   if (args->PeekNext().IsEmpty())
214     return;
215   v8::Handle<v8::Value> picture_handle;
216   args->GetNext(&picture_handle);
217   scoped_refptr<cc::Picture> picture =
218       ParsePictureHash(isolate, picture_handle);
219   if (!picture.get())
220     return;
221
222   gfx::Rect bounds = picture->LayerRect();
223   SkDebugCanvas canvas(bounds.width(), bounds.height());
224   picture->Replay(&canvas);
225
226   v8::Handle<v8::Array> result = v8::Array::New(isolate, canvas.getSize());
227   for (int i = 0; i < canvas.getSize(); ++i) {
228     DrawType cmd_type = canvas.getDrawCommandAt(i)->getType();
229     v8::Handle<v8::Object> cmd = v8::Object::New(isolate);
230     cmd->Set(v8::String::NewFromUtf8(isolate, "cmd_type"),
231              v8::Integer::New(isolate, cmd_type));
232     cmd->Set(v8::String::NewFromUtf8(isolate, "cmd_string"),
233              v8::String::NewFromUtf8(
234                  isolate, SkDrawCommand::GetCommandString(cmd_type)));
235
236     SkTDArray<SkString*>* info = canvas.getCommandInfo(i);
237     DCHECK(info);
238
239     v8::Local<v8::Array> v8_info = v8::Array::New(isolate, info->count());
240     for (int j = 0; j < info->count(); ++j) {
241       const SkString* info_str = (*info)[j];
242       DCHECK(info_str);
243       v8_info->Set(j, v8::String::NewFromUtf8(isolate, info_str->c_str()));
244     }
245
246     cmd->Set(v8::String::NewFromUtf8(isolate, "info"), v8_info);
247
248     result->Set(i, cmd);
249   }
250
251   args->Return(result.As<v8::Object>());
252 }
253
254 void SkiaBenchmarking::GetOpTimings(gin::Arguments* args) {
255   v8::Isolate* isolate = args->isolate();
256   if (args->PeekNext().IsEmpty())
257     return;
258   v8::Handle<v8::Value> picture_handle;
259   args->GetNext(&picture_handle);
260   scoped_refptr<cc::Picture> picture =
261       ParsePictureHash(isolate, picture_handle);
262   if (!picture.get())
263     return;
264
265   gfx::Rect bounds = picture->LayerRect();
266
267   // Measure the total time by drawing straight into a bitmap-backed canvas.
268   skia::RefPtr<SkBaseDevice> device = skia::AdoptRef(SkNEW_ARGS(
269       SkBitmapDevice,
270       (SkBitmap::kARGB_8888_Config, bounds.width(), bounds.height())));
271   SkCanvas bitmap_canvas(device.get());
272   bitmap_canvas.clear(SK_ColorTRANSPARENT);
273   base::TimeTicks t0 = base::TimeTicks::HighResNow();
274   picture->Replay(&bitmap_canvas);
275   base::TimeDelta total_time = base::TimeTicks::HighResNow() - t0;
276
277   // Gather per-op timing info by drawing into a BenchmarkingCanvas.
278   skia::BenchmarkingCanvas benchmarking_canvas(bounds.width(), bounds.height());
279   picture->Replay(&benchmarking_canvas);
280
281   v8::Local<v8::Array> op_times =
282       v8::Array::New(isolate, benchmarking_canvas.CommandCount());
283   for (size_t i = 0; i < benchmarking_canvas.CommandCount(); ++i)
284     op_times->Set(i, v8::Number::New(isolate, benchmarking_canvas.GetTime(i)));
285
286   v8::Handle<v8::Object> result = v8::Object::New(isolate);
287   result->Set(v8::String::NewFromUtf8(isolate, "total_time"),
288               v8::Number::New(isolate, total_time.InMillisecondsF()));
289   result->Set(v8::String::NewFromUtf8(isolate, "cmd_times"), op_times);
290
291   args->Return(result);
292 }
293
294 void SkiaBenchmarking::GetInfo(gin::Arguments* args) {
295   v8::Isolate* isolate = args->isolate();
296   if (args->PeekNext().IsEmpty())
297     return;
298   v8::Handle<v8::Value> picture_handle;
299   args->GetNext(&picture_handle);
300   scoped_refptr<cc::Picture> picture =
301       ParsePictureStr(isolate, picture_handle);
302   if (!picture.get())
303     return;
304
305   v8::Handle<v8::Object> result = v8::Object::New(isolate);
306   result->Set(v8::String::NewFromUtf8(isolate, "width"),
307               v8::Number::New(isolate, picture->LayerRect().width()));
308   result->Set(v8::String::NewFromUtf8(isolate, "height"),
309               v8::Number::New(isolate, picture->LayerRect().height()));
310
311   args->Return(result);
312 }
313
314 } // namespace content