blob: 5462623e75ff3392fd236e68039f4d6bf4b695fa [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
Hal Canary10219fb2016-11-23 20:41:22 -050019#include <SkImageEncoder.h>
Peiyong Lin3bff1352018-12-11 07:56:07 -080020#include <SkImageInfo.h>
Leon Scroggins IIIee708fa2016-12-12 15:31:39 -050021#include <SkImagePriv.h>
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -040022#include <SkMultiPictureDocument.h>
Matt Sarettf58cc922016-11-14 18:33:38 -050023#include <SkOverdrawCanvas.h>
24#include <SkOverdrawColorFilter.h>
Stan Iliev500a0c32016-10-26 10:30:09 -040025#include <SkPicture.h>
26#include <SkPictureRecorder.h>
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -040027#include <SkSerialProcs.h>
Alec Mouri43fe6fc2019-12-23 07:46:19 -080028#include <SkTypeface.h>
29#include <android-base/properties.h>
30#include <unistd.h>
31
32#include <sstream>
33
rnleece9762b2021-05-21 15:40:53 -070034#include <gui/TraceUtils.h>
Fedor Kudasov90df0562019-06-19 11:41:34 +010035#include "LightingInfo.h"
Stan Iliev23c38a92017-03-23 00:12:50 -040036#include "VectorDrawable.h"
John Reck322b8ab2019-03-14 13:15:28 -070037#include "thread/CommonPool.h"
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -040038#include "tools/SkSharingProc.h"
John Reckb36bfdd2020-07-23 13:47:49 -070039#include "utils/Color.h"
Nathaniel Nifong2945bff2019-11-25 09:34:21 -050040#include "utils/String8.h"
Jerome Gaillarda02a12d2019-05-28 18:07:56 +010041
Stan Iliev500a0c32016-10-26 10:30:09 -040042using namespace android::uirenderer::renderthread;
43
44namespace android {
45namespace uirenderer {
46namespace skiapipeline {
47
John Reck1bcacfd2017-11-03 10:12:19 -070048SkiaPipeline::SkiaPipeline(RenderThread& thread) : mRenderThread(thread) {
Derek Sollenberger1863d942020-02-05 15:41:51 -050049 setSurfaceColorProperties(mColorMode);
Stan Iliev23c38a92017-03-23 00:12:50 -040050}
Stan Iliev500a0c32016-10-26 10:30:09 -040051
Stan Iliev232f3622017-08-23 17:15:09 -040052SkiaPipeline::~SkiaPipeline() {
53 unpinImages();
54}
55
Stan Iliev500a0c32016-10-26 10:30:09 -040056void SkiaPipeline::onDestroyHardwareResources() {
Derek Sollenberger92a9eb92018-04-12 13:42:19 -040057 unpinImages();
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040058 mRenderThread.cacheManager().trimStaleResources();
Stan Iliev500a0c32016-10-26 10:30:09 -040059}
60
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040061bool SkiaPipeline::pinImages(std::vector<SkImage*>& mutableImages) {
62 for (SkImage* image : mutableImages) {
Derek Sollenberger189e8742016-11-16 16:00:17 -050063 if (SkImage_pinAsTexture(image, mRenderThread.getGrContext())) {
64 mPinnedImages.emplace_back(sk_ref_sp(image));
65 } else {
66 return false;
67 }
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040068 }
69 return true;
70}
71
72void SkiaPipeline::unpinImages() {
73 for (auto& image : mPinnedImages) {
74 SkImage_unpinAsTexture(image.get(), mRenderThread.getGrContext());
75 }
76 mPinnedImages.clear();
77}
78
John Reckd9d7f122018-05-03 14:40:56 -070079void SkiaPipeline::renderLayers(const LightGeometry& lightGeometry,
John Reck1bcacfd2017-11-03 10:12:19 -070080 LayerUpdateQueue* layerUpdateQueue, bool opaque,
Peiyong Lin1f6aa122018-09-10 16:28:08 -070081 const LightInfo& lightInfo) {
Fedor Kudasov90df0562019-06-19 11:41:34 +010082 LightingInfo::updateLighting(lightGeometry, lightInfo);
Stan Iliev500a0c32016-10-26 10:30:09 -040083 ATRACE_NAME("draw layers");
Peiyong Lin1f6aa122018-09-10 16:28:08 -070084 renderLayersImpl(*layerUpdateQueue, opaque);
Stan Iliev500a0c32016-10-26 10:30:09 -040085 layerUpdateQueue->clear();
86}
87
Peiyong Lin1f6aa122018-09-10 16:28:08 -070088void SkiaPipeline::renderLayersImpl(const LayerUpdateQueue& layers, bool opaque) {
Adlai Hollerab762152020-09-16 10:37:19 -040089 sk_sp<GrDirectContext> cachedContext;
Derek Sollenbergerf7df1842017-09-05 11:15:58 -040090
Stan Iliev500a0c32016-10-26 10:30:09 -040091 // Render all layers that need to be updated, in order.
92 for (size_t i = 0; i < layers.entries().size(); i++) {
John Reckfc29f7acd2017-03-02 13:23:16 -080093 RenderNode* layerNode = layers.entries()[i].renderNode.get();
Stan Iliev500a0c32016-10-26 10:30:09 -040094 // only schedule repaint if node still on layer - possible it may have been
95 // removed during a dropped frame, but layers may still remain scheduled so
96 // as not to lose info on what portion is damaged
Nathaniel Nifong2945bff2019-11-25 09:34:21 -050097 if (CC_UNLIKELY(layerNode->getLayerSurface() == nullptr)) {
98 continue;
99 }
100 SkASSERT(layerNode->getLayerSurface());
John Reckbe671952021-01-13 22:39:32 -0500101 SkiaDisplayList* displayList = layerNode->getDisplayList().asSkiaDl();
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500102 if (!displayList || displayList->isEmpty()) {
103 ALOGE("%p drawLayers(%s) : missing drawable", layerNode, layerNode->getName());
104 return;
105 }
106
107 const Rect& layerDamage = layers.entries()[i].damage;
108
109 SkCanvas* layerCanvas = layerNode->getLayerSurface()->getCanvas();
110
111 int saveCount = layerCanvas->save();
112 SkASSERT(saveCount == 1);
113
114 layerCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
115
116 // TODO: put localized light center calculation and storage to a drawable related code.
117 // It does not seem right to store something localized in a global state
118 // fix here and in recordLayers
119 const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
120 Vector3 transformedLightCenter(savedLightCenter);
121 // map current light center into RenderNode's coordinate space
122 layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
123 LightingInfo::setLightCenterRaw(transformedLightCenter);
124
125 const RenderProperties& properties = layerNode->properties();
126 const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight());
127 if (properties.getClipToBounds() && layerCanvas->quickReject(bounds)) {
128 return;
129 }
130
131 ATRACE_FORMAT("drawLayer [%s] %.1f x %.1f", layerNode->getName(), bounds.width(),
132 bounds.height());
133
134 layerNode->getSkiaLayer()->hasRenderedSinceRepaint = false;
135 layerCanvas->clear(SK_ColorTRANSPARENT);
136
137 RenderNodeDrawable root(layerNode, layerCanvas, false);
138 root.forceDraw(layerCanvas);
139 layerCanvas->restoreToCount(saveCount);
140
141 LightingInfo::setLightCenterRaw(savedLightCenter);
142
143 // cache the current context so that we can defer flushing it until
144 // either all the layers have been rendered or the context changes
Adlai Hollerab762152020-09-16 10:37:19 -0400145 GrDirectContext* currentContext =
146 GrAsDirectContext(layerNode->getLayerSurface()->getCanvas()->recordingContext());
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500147 if (cachedContext.get() != currentContext) {
148 if (cachedContext.get()) {
149 ATRACE_NAME("flush layers (context changed)");
Greg Danielc7ad4082020-05-14 15:38:26 -0400150 cachedContext->flushAndSubmit();
Stan Iliev500a0c32016-10-26 10:30:09 -0400151 }
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500152 cachedContext.reset(SkSafeRef(currentContext));
Stan Iliev500a0c32016-10-26 10:30:09 -0400153 }
154 }
Derek Sollenbergerf7df1842017-09-05 11:15:58 -0400155
156 if (cachedContext.get()) {
Derek Sollenbergerbe3876c2018-04-20 16:13:31 -0400157 ATRACE_NAME("flush layers");
Greg Danielc7ad4082020-05-14 15:38:26 -0400158 cachedContext->flushAndSubmit();
Derek Sollenbergerf7df1842017-09-05 11:15:58 -0400159 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400160}
161
John Reck1bcacfd2017-11-03 10:12:19 -0700162bool SkiaPipeline::createOrUpdateLayer(RenderNode* node, const DamageAccumulator& damageAccumulator,
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700163 ErrorHandler* errorHandler) {
Derek Sollenberger03e6cff72017-12-04 15:07:08 -0500164 // compute the size of the surface (i.e. texture) to be allocated for this layer
165 const int surfaceWidth = ceilf(node->getWidth() / float(LAYER_SIZE)) * LAYER_SIZE;
166 const int surfaceHeight = ceilf(node->getHeight() / float(LAYER_SIZE)) * LAYER_SIZE;
167
Stan Iliev500a0c32016-10-26 10:30:09 -0400168 SkSurface* layer = node->getLayerSurface();
Derek Sollenberger03e6cff72017-12-04 15:07:08 -0500169 if (!layer || layer->width() != surfaceWidth || layer->height() != surfaceHeight) {
Stan Iliev08fc19a2017-07-24 10:20:33 -0400170 SkImageInfo info;
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700171 info = SkImageInfo::Make(surfaceWidth, surfaceHeight, getSurfaceColorType(),
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400172 kPremul_SkAlphaType, getSurfaceColorSpace());
Stan Iliev500a0c32016-10-26 10:30:09 -0400173 SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
174 SkASSERT(mRenderThread.getGrContext() != nullptr);
John Reck1bcacfd2017-11-03 10:12:19 -0700175 node->setLayerSurface(SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Derek Sollenberger25833d22019-01-14 13:55:55 -0500176 SkBudgeted::kYes, info, 0,
177 this->getSurfaceOrigin(), &props));
Stan Iliev500a0c32016-10-26 10:30:09 -0400178 if (node->getLayerSurface()) {
179 // update the transform in window of the layer to reset its origin wrt light source
180 // position
181 Matrix4 windowTransform;
182 damageAccumulator.computeCurrentTransform(&windowTransform);
Stan Ilievda7c19c2019-05-22 14:43:44 -0400183 node->getSkiaLayer()->inverseTransformInWindow.loadInverse(windowTransform);
Stan Iliev216b1572018-03-26 14:29:50 -0400184 } else {
185 String8 cachesOutput;
186 mRenderThread.cacheManager().dumpMemoryUsage(cachesOutput,
John Reck283bb462018-12-13 16:40:14 -0800187 &mRenderThread.renderState());
Stan Iliev216b1572018-03-26 14:29:50 -0400188 ALOGE("%s", cachesOutput.string());
189 if (errorHandler) {
190 std::ostringstream err;
191 err << "Unable to create layer for " << node->getName();
192 const int maxTextureSize = DeviceInfo::get()->maxTextureSize();
193 err << ", size " << info.width() << "x" << info.height() << " max size "
John Reck283bb462018-12-13 16:40:14 -0800194 << maxTextureSize << " color type " << (int)info.colorType() << " has context "
195 << (int)(mRenderThread.getGrContext() != nullptr);
Stan Iliev216b1572018-03-26 14:29:50 -0400196 errorHandler->onError(err.str());
197 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400198 }
199 return true;
200 }
201 return false;
202}
203
Stan Iliev500a0c32016-10-26 10:30:09 -0400204void SkiaPipeline::prepareToDraw(const RenderThread& thread, Bitmap* bitmap) {
Adlai Hollerab762152020-09-16 10:37:19 -0400205 GrDirectContext* context = thread.getGrContext();
Stan Iliev500a0c32016-10-26 10:30:09 -0400206 if (context) {
207 ATRACE_FORMAT("Bitmap#prepareToDraw %dx%d", bitmap->width(), bitmap->height());
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400208 auto image = bitmap->makeImage();
Stan Iliev7bc3bc62017-05-24 13:28:36 -0400209 if (image.get() && !bitmap->isHardware()) {
210 SkImage_pinAsTexture(image.get(), context);
211 SkImage_unpinAsTexture(image.get(), context);
212 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400213 }
214}
215
John Reck322b8ab2019-03-14 13:15:28 -0700216static void savePictureAsync(const sk_sp<SkData>& data, const std::string& filename) {
217 CommonPool::post([data, filename] {
218 if (0 == access(filename.c_str(), F_OK)) {
Stan Ilieve9d00122017-09-19 12:07:10 -0400219 return;
220 }
221
John Reck322b8ab2019-03-14 13:15:28 -0700222 SkFILEWStream stream(filename.c_str());
Stan Ilieve9d00122017-09-19 12:07:10 -0400223 if (stream.isValid()) {
John Reck322b8ab2019-03-14 13:15:28 -0700224 stream.write(data->data(), data->size());
Stan Ilieve9d00122017-09-19 12:07:10 -0400225 stream.flush();
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400226 ALOGD("SKP Captured Drawing Output (%zu bytes) for frame. %s", stream.bytesWritten(),
John Reck322b8ab2019-03-14 13:15:28 -0700227 filename.c_str());
Stan Ilieve9d00122017-09-19 12:07:10 -0400228 }
John Reck322b8ab2019-03-14 13:15:28 -0700229 });
230}
Stan Ilieve9d00122017-09-19 12:07:10 -0400231
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400232// Note multiple SkiaPipeline instances may be loaded if more than one app is visible.
233// Each instance may observe the filename changing and try to record to a file of the same name.
234// Only the first one will succeed. There is no scope available here where we could coordinate
235// to cause this function to return true for only one of the instances.
236bool SkiaPipeline::shouldStartNewFileCapture() {
237 // Don't start a new file based capture if one is currently ongoing.
238 if (mCaptureMode != CaptureMode::None) { return false; }
239
240 // A new capture is started when the filename property changes.
241 // Read the filename property.
242 std::string prop = base::GetProperty(PROPERTY_CAPTURE_SKP_FILENAME, "0");
243 // if the filename property changed to a valid value
244 if (prop[0] != '0' && mCapturedFile != prop) {
245 // remember this new filename
246 mCapturedFile = prop;
247 // and get a property indicating how many frames to capture.
248 mCaptureSequence = base::GetIntProperty(PROPERTY_CAPTURE_SKP_FRAMES, 1);
John Reck5cca8f22018-12-10 17:06:22 -0800249 if (mCaptureSequence <= 0) {
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400250 return false;
251 } else if (mCaptureSequence == 1) {
252 mCaptureMode = CaptureMode::SingleFrameSKP;
253 } else {
254 mCaptureMode = CaptureMode::MultiFrameSKP;
Stan Ilieve9d00122017-09-19 12:07:10 -0400255 }
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400256 return true;
257 }
258 return false;
259}
260
261// performs the first-frame work of a multi frame SKP capture. Returns true if successful.
262bool SkiaPipeline::setupMultiFrameCapture() {
263 ALOGD("Set up multi-frame capture, frames = %d", mCaptureSequence);
264 // We own this stream and need to hold it until close() finishes.
265 auto stream = std::make_unique<SkFILEWStream>(mCapturedFile.c_str());
266 if (stream->isValid()) {
267 mOpenMultiPicStream = std::move(stream);
268 mSerialContext.reset(new SkSharingSerialContext());
269 SkSerialProcs procs;
270 procs.fImageProc = SkSharingSerialContext::serializeImage;
271 procs.fImageCtx = mSerialContext.get();
Nathaniel Nifong429fff42020-01-30 14:38:21 -0500272 procs.fTypefaceProc = [](SkTypeface* tf, void* ctx){
273 return tf->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
274 };
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400275 // SkDocuments don't take owership of the streams they write.
276 // we need to keep it until after mMultiPic.close()
277 // procs is passed as a pointer, but just as a method of having an optional default.
278 // procs doesn't need to outlive this Make call.
Nathaniel Nifong7c216772021-01-22 13:23:25 -0500279 mMultiPic = SkMakeMultiPictureDocument(mOpenMultiPicStream.get(), &procs,
280 [sharingCtx = mSerialContext.get()](const SkPicture* pic) {
281 SkSharingSerialContext::collectNonTextureImagesFromPicture(pic, sharingCtx);
282 });
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400283 return true;
284 } else {
285 ALOGE("Could not open \"%s\" for writing.", mCapturedFile.c_str());
286 mCaptureSequence = 0;
287 mCaptureMode = CaptureMode::None;
288 return false;
289 }
290}
291
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500292// recurse through the rendernode's children, add any nodes which are layers to the queue.
293static void collectLayers(RenderNode* node, LayerUpdateQueue* layers) {
John Reckbe671952021-01-13 22:39:32 -0500294 SkiaDisplayList* dl = node->getDisplayList().asSkiaDl();
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500295 if (dl) {
296 const auto& prop = node->properties();
297 if (node->hasLayer()) {
298 layers->enqueueLayerWithDamage(node, Rect(prop.getWidth(), prop.getHeight()));
299 }
300 // The way to recurse through rendernodes is to call this with a lambda.
301 dl->updateChildren([&](RenderNode* child) { collectLayers(child, layers); });
302 }
303}
304
305// record the provided layers to the provided canvas as self-contained skpictures.
306static void recordLayers(const LayerUpdateQueue& layers,
307 SkCanvas* mskpCanvas) {
308 const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
309 // Record the commands to re-draw each dirty layer into an SkPicture
310 for (size_t i = 0; i < layers.entries().size(); i++) {
311 RenderNode* layerNode = layers.entries()[i].renderNode.get();
312 const Rect& layerDamage = layers.entries()[i].damage;
313 const RenderProperties& properties = layerNode->properties();
314
315 // Temporarily map current light center into RenderNode's coordinate space
316 Vector3 transformedLightCenter(savedLightCenter);
317 layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
318 LightingInfo::setLightCenterRaw(transformedLightCenter);
319
320 SkPictureRecorder layerRec;
321 auto* recCanvas = layerRec.beginRecording(properties.getWidth(),
322 properties.getHeight());
323 // This is not recorded but still causes clipping.
324 recCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
325 RenderNodeDrawable root(layerNode, recCanvas, false);
326 root.forceDraw(recCanvas);
327 // Now write this picture into the SKP canvas with an annotation indicating what it is
328 mskpCanvas->drawAnnotation(layerDamage.toSkRect(), String8::format(
329 "OffscreenLayerDraw|%" PRId64, layerNode->uniqueId()).c_str(), nullptr);
330 mskpCanvas->drawPicture(layerRec.finishRecordingAsPicture());
331 }
332 LightingInfo::setLightCenterRaw(savedLightCenter);
333}
334
335SkCanvas* SkiaPipeline::tryCapture(SkSurface* surface, RenderNode* root,
336 const LayerUpdateQueue& dirtyLayers) {
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400337 if (CC_LIKELY(!Properties::skpCaptureEnabled)) {
338 return surface->getCanvas(); // Bail out early when capture is not turned on.
339 }
340 // Note that shouldStartNewFileCapture tells us if this is the *first* frame of a capture.
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500341 bool firstFrameOfAnim = false;
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400342 if (shouldStartNewFileCapture() && mCaptureMode == CaptureMode::MultiFrameSKP) {
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500343 // set a reminder to record every layer near the end of this method, after we have set up
344 // the nway canvas.
345 firstFrameOfAnim = true;
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400346 if (!setupMultiFrameCapture()) {
347 return surface->getCanvas();
Stan Ilieve9d00122017-09-19 12:07:10 -0400348 }
349 }
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400350
351 // Create a canvas pointer, fill it depending on what kind of capture is requested (if any)
352 SkCanvas* pictureCanvas = nullptr;
353 switch (mCaptureMode) {
354 case CaptureMode::CallbackAPI:
355 case CaptureMode::SingleFrameSKP:
356 mRecorder.reset(new SkPictureRecorder());
Nathaniel Nifong31fee3a2019-07-11 16:27:14 -0400357 pictureCanvas = mRecorder->beginRecording(surface->width(), surface->height());
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400358 break;
359 case CaptureMode::MultiFrameSKP:
360 // If a multi frame recording is active, initialize recording for a single frame of a
361 // multi frame file.
362 pictureCanvas = mMultiPic->beginPage(surface->width(), surface->height());
363 break;
364 case CaptureMode::None:
365 // Returning here in the non-capture case means we can count on pictureCanvas being
366 // non-null below.
367 return surface->getCanvas();
368 }
369
370 // Setting up an nway canvas is common to any kind of capture.
371 mNwayCanvas = std::make_unique<SkNWayCanvas>(surface->width(), surface->height());
372 mNwayCanvas->addCanvas(surface->getCanvas());
373 mNwayCanvas->addCanvas(pictureCanvas);
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500374
375 if (firstFrameOfAnim) {
376 // On the first frame of any mskp capture we want to record any layers that are needed in
377 // frame but may have been rendered offscreen before recording began.
378 // We do not maintain a list of all layers, since it isn't needed outside this rare,
379 // recording use case. Traverse the tree to find them and put them in this LayerUpdateQueue.
380 LayerUpdateQueue luq;
381 collectLayers(root, &luq);
382 recordLayers(luq, mNwayCanvas.get());
383 } else {
384 // on non-first frames, we record any normal layer draws (dirty regions)
385 recordLayers(dirtyLayers, mNwayCanvas.get());
386 }
387
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400388 return mNwayCanvas.get();
Stan Ilieve9d00122017-09-19 12:07:10 -0400389}
390
391void SkiaPipeline::endCapture(SkSurface* surface) {
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400392 if (CC_LIKELY(mCaptureMode == CaptureMode::None)) { return; }
John Reck5cca8f22018-12-10 17:06:22 -0800393 mNwayCanvas.reset();
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400394 ATRACE_CALL();
395 if (mCaptureSequence > 0 && mCaptureMode == CaptureMode::MultiFrameSKP) {
396 mMultiPic->endPage();
397 mCaptureSequence--;
398 if (mCaptureSequence == 0) {
399 mCaptureMode = CaptureMode::None;
400 // Pass mMultiPic and mOpenMultiPicStream to a background thread, which will handle
401 // the heavyweight serialization work and destroy them. mOpenMultiPicStream is released
402 // to a bare pointer because keeping it in a smart pointer makes the lambda
403 // non-copyable. The lambda is only called once, so this is safe.
404 SkFILEWStream* stream = mOpenMultiPicStream.release();
405 CommonPool::post([doc = std::move(mMultiPic), stream]{
406 ALOGD("Finalizing multi frame SKP");
407 doc->close();
408 delete stream;
409 ALOGD("Multi frame SKP complete.");
410 });
411 }
412 } else {
Stan Ilieve9d00122017-09-19 12:07:10 -0400413 sk_sp<SkPicture> picture = mRecorder->finishRecordingAsPicture();
Stan Ilieve9d00122017-09-19 12:07:10 -0400414 if (picture->approximateOpCount() > 0) {
John Reck5cca8f22018-12-10 17:06:22 -0800415 if (mPictureCapturedCallback) {
416 std::invoke(mPictureCapturedCallback, std::move(picture));
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400417 } else {
418 // single frame skp to file
Nathaniel Nifong429fff42020-01-30 14:38:21 -0500419 SkSerialProcs procs;
420 procs.fTypefaceProc = [](SkTypeface* tf, void* ctx){
421 return tf->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
422 };
John Reck76005182021-06-09 22:43:05 -0400423 auto data = picture->serialize(&procs);
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400424 savePictureAsync(data, mCapturedFile);
425 mCaptureSequence = 0;
Derek Sollenberger5f9753d2020-04-01 15:59:02 -0400426 mCaptureMode = CaptureMode::None;
Stan Ilieve9d00122017-09-19 12:07:10 -0400427 }
Stan Ilieve9d00122017-09-19 12:07:10 -0400428 }
429 mRecorder.reset();
430 }
431}
432
Stan Iliev500a0c32016-10-26 10:30:09 -0400433void SkiaPipeline::renderFrame(const LayerUpdateQueue& layers, const SkRect& clip,
John Reck1bcacfd2017-11-03 10:12:19 -0700434 const std::vector<sp<RenderNode>>& nodes, bool opaque,
Greg Danielc4076782019-01-08 16:01:18 -0500435 const Rect& contentDrawBounds, sk_sp<SkSurface> surface,
436 const SkMatrix& preTransform) {
John Reck5cca8f22018-12-10 17:06:22 -0800437 bool previousSkpEnabled = Properties::skpCaptureEnabled;
438 if (mPictureCapturedCallback) {
439 Properties::skpCaptureEnabled = true;
440 }
441
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500442 // Initialize the canvas for the current frame, that might be a recording canvas if SKP
443 // capture is enabled.
444 SkCanvas* canvas = tryCapture(surface.get(), nodes[0].get(), layers);
445
Stan Iliev500a0c32016-10-26 10:30:09 -0400446 // draw all layers up front
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700447 renderLayersImpl(layers, opaque);
Stan Iliev500a0c32016-10-26 10:30:09 -0400448
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500449 renderFrameImpl(clip, nodes, opaque, contentDrawBounds, canvas, preTransform);
Matt Sarettf58cc922016-11-14 18:33:38 -0500450
Stan Ilieve9d00122017-09-19 12:07:10 -0400451 endCapture(surface.get());
Matt Sarettf58cc922016-11-14 18:33:38 -0500452
453 if (CC_UNLIKELY(Properties::debugOverdraw)) {
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500454 renderOverdraw(clip, nodes, contentDrawBounds, surface, preTransform);
Matt Sarettf58cc922016-11-14 18:33:38 -0500455 }
456
John Reck5cca8f22018-12-10 17:06:22 -0800457 Properties::skpCaptureEnabled = previousSkpEnabled;
Matt Sarettf58cc922016-11-14 18:33:38 -0500458}
459
Stan Iliev52771272016-11-17 09:54:38 -0500460namespace {
461static Rect nodeBounds(RenderNode& node) {
462 auto& props = node.properties();
John Reck1bcacfd2017-11-03 10:12:19 -0700463 return Rect(props.getLeft(), props.getTop(), props.getRight(), props.getBottom());
Stan Iliev52771272016-11-17 09:54:38 -0500464}
John Reck0fa0cbc2019-04-05 16:57:46 -0700465} // namespace
Stan Iliev52771272016-11-17 09:54:38 -0500466
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500467void SkiaPipeline::renderFrameImpl(const SkRect& clip,
John Reck1bcacfd2017-11-03 10:12:19 -0700468 const std::vector<sp<RenderNode>>& nodes, bool opaque,
Greg Danielc4076782019-01-08 16:01:18 -0500469 const Rect& contentDrawBounds, SkCanvas* canvas,
470 const SkMatrix& preTransform) {
Stan Ilievb66b8bb2016-12-15 18:17:42 -0500471 SkAutoCanvasRestore saver(canvas, true);
Nathaniel Nifongcff969f2020-01-09 14:03:49 -0500472 auto clipRestriction = preTransform.mapRect(clip).roundOut();
John Reck76005182021-06-09 22:43:05 -0400473 if (CC_UNLIKELY(isCapturingSkp())) {
Nathaniel Nifong89a5dc52020-01-17 15:32:17 -0500474 canvas->drawAnnotation(SkRect::Make(clipRestriction), "AndroidDeviceClipRestriction",
475 nullptr);
476 } else {
477 // clip drawing to dirty region only when not recording SKP files (which should contain all
478 // draw ops on every frame)
479 canvas->androidFramework_setDeviceClipRestriction(clipRestriction);
480 }
Greg Danielc4076782019-01-08 16:01:18 -0500481 canvas->concat(preTransform);
Stan Iliev500a0c32016-10-26 10:30:09 -0400482
Stan Ilievaadc0322018-03-23 10:50:11 -0400483 // STOPSHIP: Revert, temporary workaround to clear always F16 frame buffer for b/74976293
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700484 if (!opaque || getSurfaceColorType() == kRGBA_F16_SkColorType) {
Stan Iliev500a0c32016-10-26 10:30:09 -0400485 canvas->clear(SK_ColorTRANSPARENT);
486 }
487
Stan Iliev52771272016-11-17 09:54:38 -0500488 if (1 == nodes.size()) {
489 if (!nodes[0]->nothingToDraw()) {
Stan Iliev52771272016-11-17 09:54:38 -0500490 RenderNodeDrawable root(nodes[0].get(), canvas);
491 root.draw(canvas);
492 }
493 } else if (0 == nodes.size()) {
John Reck1bcacfd2017-11-03 10:12:19 -0700494 // nothing to draw
Stan Iliev52771272016-11-17 09:54:38 -0500495 } else {
496 // It there are multiple render nodes, they are laid out as follows:
497 // #0 - backdrop (content + caption)
498 // #1 - content (local bounds are at (0,0), will be translated and clipped to backdrop)
499 // #2 - additional overlay nodes
John Reck1bcacfd2017-11-03 10:12:19 -0700500 // Usually the backdrop cannot be seen since it will be entirely covered by the content.
501 // While
502 // resizing however it might become partially visible. The following render loop will crop
503 // the
504 // backdrop against the content and draw the remaining part of it. It will then draw the
505 // content
Stan Iliev52771272016-11-17 09:54:38 -0500506 // cropped to the backdrop (since that indicates a shrinking of the window).
507 //
508 // Additional nodes will be drawn on top with no particular clipping semantics.
Stan Iliev500a0c32016-10-26 10:30:09 -0400509
Stan Iliev52771272016-11-17 09:54:38 -0500510 // Usually the contents bounds should be mContentDrawBounds - however - we will
511 // move it towards the fixed edge to give it a more stable appearance (for the moment).
512 // If there is no content bounds we ignore the layering as stated above and start with 2.
Stan Iliev500a0c32016-10-26 10:30:09 -0400513
Stan Iliev52771272016-11-17 09:54:38 -0500514 // Backdrop bounds in render target space
515 const Rect backdrop = nodeBounds(*nodes[0]);
Stan Iliev500a0c32016-10-26 10:30:09 -0400516
John Reck1bcacfd2017-11-03 10:12:19 -0700517 // Bounds that content will fill in render target space (note content node bounds may be
518 // bigger)
Stan Iliev52771272016-11-17 09:54:38 -0500519 Rect content(contentDrawBounds.getWidth(), contentDrawBounds.getHeight());
520 content.translate(backdrop.left, backdrop.top);
521 if (!content.contains(backdrop) && !nodes[0]->nothingToDraw()) {
522 // Content doesn't entirely overlap backdrop, so fill around content (right/bottom)
Stan Iliev500a0c32016-10-26 10:30:09 -0400523
Stan Iliev52771272016-11-17 09:54:38 -0500524 // Note: in the future, if content doesn't snap to backdrop's left/top, this may need to
John Reck1bcacfd2017-11-03 10:12:19 -0700525 // also fill left/top. Currently, both 2up and freeform position content at the top/left
526 // of
Stan Iliev52771272016-11-17 09:54:38 -0500527 // the backdrop, so this isn't necessary.
528 RenderNodeDrawable backdropNode(nodes[0].get(), canvas);
529 if (content.right < backdrop.right) {
530 // draw backdrop to right side of content
531 SkAutoCanvasRestore acr(canvas, true);
John Reck1bcacfd2017-11-03 10:12:19 -0700532 canvas->clipRect(SkRect::MakeLTRB(content.right, backdrop.top, backdrop.right,
533 backdrop.bottom));
Stan Iliev52771272016-11-17 09:54:38 -0500534 backdropNode.draw(canvas);
535 }
536 if (content.bottom < backdrop.bottom) {
537 // draw backdrop to bottom of content
538 // Note: bottom fill uses content left/right, to avoid overdrawing left/right fill
539 SkAutoCanvasRestore acr(canvas, true);
John Reck1bcacfd2017-11-03 10:12:19 -0700540 canvas->clipRect(SkRect::MakeLTRB(content.left, content.bottom, content.right,
541 backdrop.bottom));
Stan Iliev52771272016-11-17 09:54:38 -0500542 backdropNode.draw(canvas);
543 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400544 }
545
Stan Iliev52771272016-11-17 09:54:38 -0500546 RenderNodeDrawable contentNode(nodes[1].get(), canvas);
547 if (!backdrop.isEmpty()) {
548 // content node translation to catch up with backdrop
549 float dx = backdrop.left - contentDrawBounds.left;
550 float dy = backdrop.top - contentDrawBounds.top;
551
552 SkAutoCanvasRestore acr(canvas, true);
553 canvas->translate(dx, dy);
John Reck1bcacfd2017-11-03 10:12:19 -0700554 const SkRect contentLocalClip =
555 SkRect::MakeXYWH(contentDrawBounds.left, contentDrawBounds.top,
556 backdrop.getWidth(), backdrop.getHeight());
Stan Iliev52771272016-11-17 09:54:38 -0500557 canvas->clipRect(contentLocalClip);
558 contentNode.draw(canvas);
559 } else {
560 SkAutoCanvasRestore acr(canvas, true);
561 contentNode.draw(canvas);
562 }
563
564 // remaining overlay nodes, simply defer
565 for (size_t index = 2; index < nodes.size(); index++) {
566 if (!nodes[index]->nothingToDraw()) {
567 SkAutoCanvasRestore acr(canvas, true);
568 RenderNodeDrawable overlayNode(nodes[index].get(), canvas);
569 overlayNode.draw(canvas);
570 }
571 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400572 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400573}
574
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500575void SkiaPipeline::dumpResourceCacheUsage() const {
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400576 int resources;
577 size_t bytes;
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500578 mRenderThread.getGrContext()->getResourceCacheUsage(&resources, &bytes);
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400579 size_t maxBytes = mRenderThread.getGrContext()->getResourceCacheLimit();
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500580
581 SkString log("Resource Cache Usage:\n");
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400582 log.appendf("%8d items\n", resources);
John Reck1bcacfd2017-11-03 10:12:19 -0700583 log.appendf("%8zu bytes (%.2f MB) out of %.2f MB maximum\n", bytes,
584 bytes * (1.0f / (1024.0f * 1024.0f)), maxBytes * (1.0f / (1024.0f * 1024.0f)));
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500585
586 ALOGD("%s", log.c_str());
587}
588
Peiyong Lin3bff1352018-12-11 07:56:07 -0800589void SkiaPipeline::setSurfaceColorProperties(ColorMode colorMode) {
Derek Sollenberger1863d942020-02-05 15:41:51 -0500590 mColorMode = colorMode;
John Reckb36bfdd2020-07-23 13:47:49 -0700591 switch (colorMode) {
592 case ColorMode::Default:
593 mSurfaceColorType = SkColorType::kN32_SkColorType;
594 mSurfaceColorSpace = SkColorSpace::MakeSRGB();
595 break;
596 case ColorMode::WideColorGamut:
597 mSurfaceColorType = DeviceInfo::get()->getWideColorType();
598 mSurfaceColorSpace = DeviceInfo::get()->getWideColorSpace();
599 break;
600 case ColorMode::Hdr:
601 mSurfaceColorType = SkColorType::kRGBA_F16_SkColorType;
602 mSurfaceColorSpace = SkColorSpace::MakeRGB(GetPQSkTransferFunction(), SkNamedGamut::kRec2020);
603 break;
604 case ColorMode::Hdr10:
605 mSurfaceColorType = SkColorType::kRGBA_1010102_SkColorType;
606 mSurfaceColorSpace = SkColorSpace::MakeRGB(GetPQSkTransferFunction(), SkNamedGamut::kRec2020);
607 break;
Peiyong Lin3bff1352018-12-11 07:56:07 -0800608 }
609}
610
Matt Sarettf58cc922016-11-14 18:33:38 -0500611// Overdraw debugging
612
613// These colors should be kept in sync with Caches::getOverdrawColor() with a few differences.
Mike Reed331c4e12020-02-13 10:21:54 -0500614// This implementation requires transparent entries for "no overdraw" and "single draws".
615static const SkColor kOverdrawColors[2][6] = {
616 {
617 0x00000000,
618 0x00000000,
619 0x2f0000ff,
620 0x2f00ff00,
621 0x3fff0000,
622 0x7fff0000,
623 },
624 {
625 0x00000000,
626 0x00000000,
627 0x2f0000ff,
628 0x4fffff00,
629 0x5fff89d7,
630 0x7fff0000,
631 },
Matt Sarettf58cc922016-11-14 18:33:38 -0500632};
633
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500634void SkiaPipeline::renderOverdraw(const SkRect& clip,
John Reck1bcacfd2017-11-03 10:12:19 -0700635 const std::vector<sp<RenderNode>>& nodes,
Greg Danielc4076782019-01-08 16:01:18 -0500636 const Rect& contentDrawBounds, sk_sp<SkSurface> surface,
637 const SkMatrix& preTransform) {
Matt Sarettf58cc922016-11-14 18:33:38 -0500638 // Set up the overdraw canvas.
639 SkImageInfo offscreenInfo = SkImageInfo::MakeA8(surface->width(), surface->height());
640 sk_sp<SkSurface> offscreen = surface->makeSurface(offscreenInfo);
Nathaniel Nifongfe05b7c2019-09-17 12:52:52 -0400641 LOG_ALWAYS_FATAL_IF(!offscreen, "Failed to create offscreen SkSurface for overdraw viz.");
Matt Sarettf58cc922016-11-14 18:33:38 -0500642 SkOverdrawCanvas overdrawCanvas(offscreen->getCanvas());
643
644 // Fake a redraw to replay the draw commands. This will increment the alpha channel
645 // each time a pixel would have been drawn.
646 // Pass true for opaque so we skip the clear - the overdrawCanvas is already zero
647 // initialized.
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500648 renderFrameImpl(clip, nodes, true, contentDrawBounds, &overdrawCanvas, preTransform);
Matt Sarettf58cc922016-11-14 18:33:38 -0500649 sk_sp<SkImage> counts = offscreen->makeImageSnapshot();
650
651 // Draw overdraw colors to the canvas. The color filter will convert counts to colors.
652 SkPaint paint;
Mike Reed331c4e12020-02-13 10:21:54 -0500653 const SkColor* colors = kOverdrawColors[static_cast<int>(Properties::overdrawColorSet)];
654 paint.setColorFilter(SkOverdrawColorFilter::MakeWithSkColors(colors));
Mike Reed7994a312021-01-28 18:06:26 -0500655 surface->getCanvas()->drawImage(counts.get(), 0.0f, 0.0f, SkSamplingOptions(), &paint);
Matt Sarettf58cc922016-11-14 18:33:38 -0500656}
657
Stan Iliev500a0c32016-10-26 10:30:09 -0400658} /* namespace skiapipeline */
659} /* namespace uirenderer */
660} /* namespace android */