blob: 88293db193f8894212a04a97a94e446b7228bfe7 [file] [log] [blame]
Stan Iliev500a0c32016-10-26 10:30:09 -04001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "SkiaPipeline.h"
18
19#include "utils/TraceUtils.h"
Hal Canary10219fb2016-11-23 20:41:22 -050020#include <SkImageEncoder.h>
Leon Scroggins IIIee708fa2016-12-12 15:31:39 -050021#include <SkImagePriv.h>
Matt Sarettf58cc922016-11-14 18:33:38 -050022#include <SkOverdrawCanvas.h>
23#include <SkOverdrawColorFilter.h>
Stan Iliev500a0c32016-10-26 10:30:09 -040024#include <SkPicture.h>
25#include <SkPictureRecorder.h>
26#include <SkPixelSerializer.h>
27#include <SkStream.h>
Stan Iliev23c38a92017-03-23 00:12:50 -040028#include "VectorDrawable.h"
Stan Iliev500a0c32016-10-26 10:30:09 -040029
Ben Wagner3aeda5c2017-03-17 17:22:01 -040030#include <unistd.h>
31
Stan Iliev500a0c32016-10-26 10:30:09 -040032using namespace android::uirenderer::renderthread;
33
34namespace android {
35namespace uirenderer {
36namespace skiapipeline {
37
38float SkiaPipeline::mLightRadius = 0;
39uint8_t SkiaPipeline::mAmbientShadowAlpha = 0;
40uint8_t SkiaPipeline::mSpotShadowAlpha = 0;
41
42Vector3 SkiaPipeline::mLightCenter = {FLT_MIN, FLT_MIN, FLT_MIN};
43
Stan Iliev23c38a92017-03-23 00:12:50 -040044SkiaPipeline::SkiaPipeline(RenderThread& thread) : mRenderThread(thread) {
45 mVectorDrawables.reserve(30);
46}
Stan Iliev500a0c32016-10-26 10:30:09 -040047
48TaskManager* SkiaPipeline::getTaskManager() {
49 return &mTaskManager;
50}
51
52void SkiaPipeline::onDestroyHardwareResources() {
53 // No need to flush the caches here. There is a timer
54 // which will flush temporary resources over time.
55}
56
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040057bool SkiaPipeline::pinImages(std::vector<SkImage*>& mutableImages) {
58 for (SkImage* image : mutableImages) {
Derek Sollenberger189e8742016-11-16 16:00:17 -050059 if (SkImage_pinAsTexture(image, mRenderThread.getGrContext())) {
60 mPinnedImages.emplace_back(sk_ref_sp(image));
61 } else {
62 return false;
63 }
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040064 }
65 return true;
66}
67
68void SkiaPipeline::unpinImages() {
69 for (auto& image : mPinnedImages) {
70 SkImage_unpinAsTexture(image.get(), mRenderThread.getGrContext());
71 }
72 mPinnedImages.clear();
73}
74
Stan Iliev500a0c32016-10-26 10:30:09 -040075void SkiaPipeline::renderLayers(const FrameBuilder::LightGeometry& lightGeometry,
76 LayerUpdateQueue* layerUpdateQueue, bool opaque,
77 const BakedOpRenderer::LightInfo& lightInfo) {
78 updateLighting(lightGeometry, lightInfo);
79 ATRACE_NAME("draw layers");
Stan Iliev23c38a92017-03-23 00:12:50 -040080 renderVectorDrawableCache();
Stan Iliev500a0c32016-10-26 10:30:09 -040081 renderLayersImpl(*layerUpdateQueue, opaque);
82 layerUpdateQueue->clear();
83}
84
85void SkiaPipeline::renderLayersImpl(const LayerUpdateQueue& layers, bool opaque) {
86 // Render all layers that need to be updated, in order.
87 for (size_t i = 0; i < layers.entries().size(); i++) {
John Reckfc29f7acd2017-03-02 13:23:16 -080088 RenderNode* layerNode = layers.entries()[i].renderNode.get();
Stan Iliev500a0c32016-10-26 10:30:09 -040089 // only schedule repaint if node still on layer - possible it may have been
90 // removed during a dropped frame, but layers may still remain scheduled so
91 // as not to lose info on what portion is damaged
92 if (CC_LIKELY(layerNode->getLayerSurface() != nullptr)) {
93 SkASSERT(layerNode->getLayerSurface());
94 SkASSERT(layerNode->getDisplayList()->isSkiaDL());
95 SkiaDisplayList* displayList = (SkiaDisplayList*)layerNode->getDisplayList();
96 if (!displayList || displayList->isEmpty()) {
97 SkDEBUGF(("%p drawLayers(%s) : missing drawable", this, layerNode->getName()));
98 return;
99 }
100
101 const Rect& layerDamage = layers.entries()[i].damage;
102
103 SkCanvas* layerCanvas = layerNode->getLayerSurface()->getCanvas();
104
105 int saveCount = layerCanvas->save();
106 SkASSERT(saveCount == 1);
107
Stan Ilievb66b8bb2016-12-15 18:17:42 -0500108 layerCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
Stan Iliev500a0c32016-10-26 10:30:09 -0400109
110 auto savedLightCenter = mLightCenter;
111 // map current light center into RenderNode's coordinate space
112 layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(mLightCenter);
113
114 const RenderProperties& properties = layerNode->properties();
115 const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight());
116 if (properties.getClipToBounds() && layerCanvas->quickReject(bounds)) {
117 return;
118 }
119
Matt Sarett79756be2016-11-09 16:13:54 -0500120 layerNode->getSkiaLayer()->hasRenderedSinceRepaint = false;
Stan Iliev500a0c32016-10-26 10:30:09 -0400121 layerCanvas->clear(SK_ColorTRANSPARENT);
122
123 RenderNodeDrawable root(layerNode, layerCanvas, false);
124 root.forceDraw(layerCanvas);
125 layerCanvas->restoreToCount(saveCount);
126 layerCanvas->flush();
127 mLightCenter = savedLightCenter;
128 }
129 }
130}
131
132bool SkiaPipeline::createOrUpdateLayer(RenderNode* node,
133 const DamageAccumulator& damageAccumulator) {
134 SkSurface* layer = node->getLayerSurface();
135 if (!layer || layer->width() != node->getWidth() || layer->height() != node->getHeight()) {
136 SkImageInfo info = SkImageInfo::MakeN32Premul(node->getWidth(), node->getHeight());
137 SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
138 SkASSERT(mRenderThread.getGrContext() != nullptr);
139 node->setLayerSurface(
140 SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
141 info, 0, &props));
142 if (node->getLayerSurface()) {
143 // update the transform in window of the layer to reset its origin wrt light source
144 // position
145 Matrix4 windowTransform;
146 damageAccumulator.computeCurrentTransform(&windowTransform);
147 node->getSkiaLayer()->inverseTransformInWindow = windowTransform;
148 }
149 return true;
150 }
151 return false;
152}
153
154void SkiaPipeline::destroyLayer(RenderNode* node) {
155 node->setLayerSurface(nullptr);
156}
157
158void SkiaPipeline::prepareToDraw(const RenderThread& thread, Bitmap* bitmap) {
159 GrContext* context = thread.getGrContext();
160 if (context) {
161 ATRACE_FORMAT("Bitmap#prepareToDraw %dx%d", bitmap->width(), bitmap->height());
Stan Iliev7bc3bc62017-05-24 13:28:36 -0400162 auto image = bitmap->makeImage();
163 if (image.get() && !bitmap->isHardware()) {
164 SkImage_pinAsTexture(image.get(), context);
165 SkImage_unpinAsTexture(image.get(), context);
166 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400167 }
168}
169
170// Encodes to PNG, unless there is already encoded data, in which case that gets
171// used.
172class PngPixelSerializer : public SkPixelSerializer {
173public:
174 bool onUseEncodedData(const void*, size_t) override { return true; }
175 SkData* onEncode(const SkPixmap& pixmap) override {
Hal Canary10219fb2016-11-23 20:41:22 -0500176 SkDynamicMemoryWStream buf;
177 return SkEncodeImage(&buf, pixmap, SkEncodedImageFormat::kPNG, 100)
178 ? buf.detachAsData().release()
179 : nullptr;
Stan Iliev500a0c32016-10-26 10:30:09 -0400180 }
181};
182
Stan Iliev23c38a92017-03-23 00:12:50 -0400183void SkiaPipeline::renderVectorDrawableCache() {
184 //render VectorDrawables into offscreen buffers
185 for (auto vd : mVectorDrawables) {
186 sk_sp<SkSurface> surface;
187 if (!vd->canReuseSurface()) {
188#ifndef ANDROID_ENABLE_LINEAR_BLENDING
189 sk_sp<SkColorSpace> colorSpace = nullptr;
190#else
191 sk_sp<SkColorSpace> colorSpace = SkColorSpace::MakeSRGB();
192#endif
193 int scaledWidth = SkScalarCeilToInt(vd->properties().getScaledWidth());
194 int scaledHeight = SkScalarCeilToInt(vd->properties().getScaledHeight());
195 SkImageInfo info = SkImageInfo::MakeN32(scaledWidth, scaledHeight,
196 kPremul_SkAlphaType, colorSpace);
197 SkASSERT(mRenderThread.getGrContext() != nullptr);
198 surface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
199 info);
200 }
201 vd->updateCache(surface);
202 }
203 mVectorDrawables.clear();
204}
205
Stan Iliev500a0c32016-10-26 10:30:09 -0400206void SkiaPipeline::renderFrame(const LayerUpdateQueue& layers, const SkRect& clip,
207 const std::vector<sp<RenderNode>>& nodes, bool opaque, const Rect &contentDrawBounds,
208 sk_sp<SkSurface> surface) {
209
Stan Iliev23c38a92017-03-23 00:12:50 -0400210 renderVectorDrawableCache();
211
Stan Iliev500a0c32016-10-26 10:30:09 -0400212 // draw all layers up front
213 renderLayersImpl(layers, opaque);
214
215 // initialize the canvas for the current frame
216 SkCanvas* canvas = surface->getCanvas();
217
218 std::unique_ptr<SkPictureRecorder> recorder;
219 bool recordingPicture = false;
220 char prop[PROPERTY_VALUE_MAX];
221 if (skpCaptureEnabled()) {
222 property_get("debug.hwui.capture_frame_as_skp", prop, "0");
Ben Wagner3aeda5c2017-03-17 17:22:01 -0400223 recordingPicture = prop[0] != '0' && access(prop, F_OK) != 0;
Stan Iliev500a0c32016-10-26 10:30:09 -0400224 if (recordingPicture) {
225 recorder.reset(new SkPictureRecorder());
226 canvas = recorder->beginRecording(surface->width(), surface->height(),
227 nullptr, SkPictureRecorder::kPlaybackDrawPicture_RecordFlag);
228 }
229 }
230
Matt Sarettf58cc922016-11-14 18:33:38 -0500231 renderFrameImpl(layers, clip, nodes, opaque, contentDrawBounds, canvas);
232
233 if (skpCaptureEnabled() && recordingPicture) {
234 sk_sp<SkPicture> picture = recorder->finishRecordingAsPicture();
235 if (picture->approximateOpCount() > 0) {
236 SkFILEWStream stream(prop);
237 if (stream.isValid()) {
238 PngPixelSerializer serializer;
239 picture->serialize(&stream, &serializer);
240 stream.flush();
241 SkDebugf("Captured Drawing Output (%d bytes) for frame. %s", stream.bytesWritten(), prop);
242 }
243 }
244 surface->getCanvas()->drawPicture(picture);
245 }
246
247 if (CC_UNLIKELY(Properties::debugOverdraw)) {
248 renderOverdraw(layers, clip, nodes, contentDrawBounds, surface);
249 }
250
251 ATRACE_NAME("flush commands");
252 canvas->flush();
253}
254
Stan Iliev52771272016-11-17 09:54:38 -0500255namespace {
256static Rect nodeBounds(RenderNode& node) {
257 auto& props = node.properties();
258 return Rect(props.getLeft(), props.getTop(),
259 props.getRight(), props.getBottom());
260}
261}
262
Matt Sarettf58cc922016-11-14 18:33:38 -0500263void SkiaPipeline::renderFrameImpl(const LayerUpdateQueue& layers, const SkRect& clip,
264 const std::vector<sp<RenderNode>>& nodes, bool opaque, const Rect &contentDrawBounds,
265 SkCanvas* canvas) {
Stan Ilievb66b8bb2016-12-15 18:17:42 -0500266 SkAutoCanvasRestore saver(canvas, true);
267 canvas->androidFramework_setDeviceClipRestriction(clip.roundOut());
Stan Iliev500a0c32016-10-26 10:30:09 -0400268
269 if (!opaque) {
270 canvas->clear(SK_ColorTRANSPARENT);
271 }
272
Stan Iliev52771272016-11-17 09:54:38 -0500273 if (1 == nodes.size()) {
274 if (!nodes[0]->nothingToDraw()) {
Stan Iliev52771272016-11-17 09:54:38 -0500275 RenderNodeDrawable root(nodes[0].get(), canvas);
276 root.draw(canvas);
277 }
278 } else if (0 == nodes.size()) {
279 //nothing to draw
280 } else {
281 // It there are multiple render nodes, they are laid out as follows:
282 // #0 - backdrop (content + caption)
283 // #1 - content (local bounds are at (0,0), will be translated and clipped to backdrop)
284 // #2 - additional overlay nodes
285 // Usually the backdrop cannot be seen since it will be entirely covered by the content. While
286 // resizing however it might become partially visible. The following render loop will crop the
287 // backdrop against the content and draw the remaining part of it. It will then draw the content
288 // cropped to the backdrop (since that indicates a shrinking of the window).
289 //
290 // Additional nodes will be drawn on top with no particular clipping semantics.
Stan Iliev500a0c32016-10-26 10:30:09 -0400291
Stan Iliev52771272016-11-17 09:54:38 -0500292 // Usually the contents bounds should be mContentDrawBounds - however - we will
293 // move it towards the fixed edge to give it a more stable appearance (for the moment).
294 // If there is no content bounds we ignore the layering as stated above and start with 2.
Stan Iliev500a0c32016-10-26 10:30:09 -0400295
Stan Iliev52771272016-11-17 09:54:38 -0500296 // Backdrop bounds in render target space
297 const Rect backdrop = nodeBounds(*nodes[0]);
Stan Iliev500a0c32016-10-26 10:30:09 -0400298
Stan Iliev52771272016-11-17 09:54:38 -0500299 // Bounds that content will fill in render target space (note content node bounds may be bigger)
300 Rect content(contentDrawBounds.getWidth(), contentDrawBounds.getHeight());
301 content.translate(backdrop.left, backdrop.top);
302 if (!content.contains(backdrop) && !nodes[0]->nothingToDraw()) {
303 // Content doesn't entirely overlap backdrop, so fill around content (right/bottom)
Stan Iliev500a0c32016-10-26 10:30:09 -0400304
Stan Iliev52771272016-11-17 09:54:38 -0500305 // Note: in the future, if content doesn't snap to backdrop's left/top, this may need to
306 // also fill left/top. Currently, both 2up and freeform position content at the top/left of
307 // the backdrop, so this isn't necessary.
308 RenderNodeDrawable backdropNode(nodes[0].get(), canvas);
309 if (content.right < backdrop.right) {
310 // draw backdrop to right side of content
311 SkAutoCanvasRestore acr(canvas, true);
312 canvas->clipRect(SkRect::MakeLTRB(content.right, backdrop.top,
313 backdrop.right, backdrop.bottom));
314 backdropNode.draw(canvas);
315 }
316 if (content.bottom < backdrop.bottom) {
317 // draw backdrop to bottom of content
318 // Note: bottom fill uses content left/right, to avoid overdrawing left/right fill
319 SkAutoCanvasRestore acr(canvas, true);
320 canvas->clipRect(SkRect::MakeLTRB(content.left, content.bottom,
321 content.right, backdrop.bottom));
322 backdropNode.draw(canvas);
323 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400324 }
325
Stan Iliev52771272016-11-17 09:54:38 -0500326 RenderNodeDrawable contentNode(nodes[1].get(), canvas);
327 if (!backdrop.isEmpty()) {
328 // content node translation to catch up with backdrop
329 float dx = backdrop.left - contentDrawBounds.left;
330 float dy = backdrop.top - contentDrawBounds.top;
331
332 SkAutoCanvasRestore acr(canvas, true);
333 canvas->translate(dx, dy);
334 const SkRect contentLocalClip = SkRect::MakeXYWH(contentDrawBounds.left,
335 contentDrawBounds.top, backdrop.getWidth(), backdrop.getHeight());
336 canvas->clipRect(contentLocalClip);
337 contentNode.draw(canvas);
338 } else {
339 SkAutoCanvasRestore acr(canvas, true);
340 contentNode.draw(canvas);
341 }
342
343 // remaining overlay nodes, simply defer
344 for (size_t index = 2; index < nodes.size(); index++) {
345 if (!nodes[index]->nothingToDraw()) {
346 SkAutoCanvasRestore acr(canvas, true);
347 RenderNodeDrawable overlayNode(nodes[index].get(), canvas);
348 overlayNode.draw(canvas);
349 }
350 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400351 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400352}
353
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500354void SkiaPipeline::dumpResourceCacheUsage() const {
355 int resources, maxResources;
356 size_t bytes, maxBytes;
357 mRenderThread.getGrContext()->getResourceCacheUsage(&resources, &bytes);
358 mRenderThread.getGrContext()->getResourceCacheLimits(&maxResources, &maxBytes);
359
360 SkString log("Resource Cache Usage:\n");
361 log.appendf("%8d items out of %d maximum items\n", resources, maxResources);
362 log.appendf("%8zu bytes (%.2f MB) out of %.2f MB maximum\n",
363 bytes, bytes * (1.0f / (1024.0f * 1024.0f)), maxBytes * (1.0f / (1024.0f * 1024.0f)));
364
365 ALOGD("%s", log.c_str());
366}
367
Matt Sarettf58cc922016-11-14 18:33:38 -0500368// Overdraw debugging
369
370// These colors should be kept in sync with Caches::getOverdrawColor() with a few differences.
371// This implementation:
372// (1) Requires transparent entries for "no overdraw" and "single draws".
373// (2) Requires premul colors (instead of unpremul).
374// (3) Requires RGBA colors (instead of BGRA).
375static const uint32_t kOverdrawColors[2][6] = {
376 { 0x00000000, 0x00000000, 0x2f2f0000, 0x2f002f00, 0x3f00003f, 0x7f00007f, },
377 { 0x00000000, 0x00000000, 0x2f2f0000, 0x4f004f4f, 0x5f50335f, 0x7f00007f, },
378};
379
380void SkiaPipeline::renderOverdraw(const LayerUpdateQueue& layers, const SkRect& clip,
381 const std::vector<sp<RenderNode>>& nodes, const Rect &contentDrawBounds,
382 sk_sp<SkSurface> surface) {
383 // Set up the overdraw canvas.
384 SkImageInfo offscreenInfo = SkImageInfo::MakeA8(surface->width(), surface->height());
385 sk_sp<SkSurface> offscreen = surface->makeSurface(offscreenInfo);
386 SkOverdrawCanvas overdrawCanvas(offscreen->getCanvas());
387
388 // Fake a redraw to replay the draw commands. This will increment the alpha channel
389 // each time a pixel would have been drawn.
390 // Pass true for opaque so we skip the clear - the overdrawCanvas is already zero
391 // initialized.
392 renderFrameImpl(layers, clip, nodes, true, contentDrawBounds, &overdrawCanvas);
393 sk_sp<SkImage> counts = offscreen->makeImageSnapshot();
394
395 // Draw overdraw colors to the canvas. The color filter will convert counts to colors.
396 SkPaint paint;
397 const SkPMColor* colors = kOverdrawColors[static_cast<int>(Properties::overdrawColorSet)];
398 paint.setColorFilter(SkOverdrawColorFilter::Make(colors));
399 surface->getCanvas()->drawImage(counts.get(), 0.0f, 0.0f, &paint);
400}
401
Stan Iliev500a0c32016-10-26 10:30:09 -0400402} /* namespace skiapipeline */
403} /* namespace uirenderer */
404} /* namespace android */