blob: 44a6e435460811f12d0be313e359f0041c52d2b7 [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) {
Greg Danielf8cb5252021-06-30 10:40:34 -040062 if (!mRenderThread.getGrContext()) {
63 ALOGD("Trying to pin an image with an invalid GrContext");
64 return false;
65 }
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040066 for (SkImage* image : mutableImages) {
Derek Sollenberger189e8742016-11-16 16:00:17 -050067 if (SkImage_pinAsTexture(image, mRenderThread.getGrContext())) {
68 mPinnedImages.emplace_back(sk_ref_sp(image));
69 } else {
70 return false;
71 }
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040072 }
73 return true;
74}
75
76void SkiaPipeline::unpinImages() {
77 for (auto& image : mPinnedImages) {
78 SkImage_unpinAsTexture(image.get(), mRenderThread.getGrContext());
79 }
80 mPinnedImages.clear();
81}
82
John Reckd9d7f122018-05-03 14:40:56 -070083void SkiaPipeline::renderLayers(const LightGeometry& lightGeometry,
John Reck1bcacfd2017-11-03 10:12:19 -070084 LayerUpdateQueue* layerUpdateQueue, bool opaque,
Peiyong Lin1f6aa122018-09-10 16:28:08 -070085 const LightInfo& lightInfo) {
Fedor Kudasov90df0562019-06-19 11:41:34 +010086 LightingInfo::updateLighting(lightGeometry, lightInfo);
Stan Iliev500a0c32016-10-26 10:30:09 -040087 ATRACE_NAME("draw layers");
Peiyong Lin1f6aa122018-09-10 16:28:08 -070088 renderLayersImpl(*layerUpdateQueue, opaque);
Stan Iliev500a0c32016-10-26 10:30:09 -040089 layerUpdateQueue->clear();
90}
91
Peiyong Lin1f6aa122018-09-10 16:28:08 -070092void SkiaPipeline::renderLayersImpl(const LayerUpdateQueue& layers, bool opaque) {
Adlai Hollerab762152020-09-16 10:37:19 -040093 sk_sp<GrDirectContext> cachedContext;
Derek Sollenbergerf7df1842017-09-05 11:15:58 -040094
Stan Iliev500a0c32016-10-26 10:30:09 -040095 // Render all layers that need to be updated, in order.
96 for (size_t i = 0; i < layers.entries().size(); i++) {
John Reckfc29f7acd2017-03-02 13:23:16 -080097 RenderNode* layerNode = layers.entries()[i].renderNode.get();
Stan Iliev500a0c32016-10-26 10:30:09 -040098 // only schedule repaint if node still on layer - possible it may have been
99 // removed during a dropped frame, but layers may still remain scheduled so
100 // as not to lose info on what portion is damaged
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500101 if (CC_UNLIKELY(layerNode->getLayerSurface() == nullptr)) {
102 continue;
103 }
104 SkASSERT(layerNode->getLayerSurface());
John Reckbe671952021-01-13 22:39:32 -0500105 SkiaDisplayList* displayList = layerNode->getDisplayList().asSkiaDl();
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500106 if (!displayList || displayList->isEmpty()) {
107 ALOGE("%p drawLayers(%s) : missing drawable", layerNode, layerNode->getName());
108 return;
109 }
110
111 const Rect& layerDamage = layers.entries()[i].damage;
112
113 SkCanvas* layerCanvas = layerNode->getLayerSurface()->getCanvas();
114
115 int saveCount = layerCanvas->save();
116 SkASSERT(saveCount == 1);
117
118 layerCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
119
120 // TODO: put localized light center calculation and storage to a drawable related code.
121 // It does not seem right to store something localized in a global state
122 // fix here and in recordLayers
123 const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
124 Vector3 transformedLightCenter(savedLightCenter);
125 // map current light center into RenderNode's coordinate space
126 layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
127 LightingInfo::setLightCenterRaw(transformedLightCenter);
128
129 const RenderProperties& properties = layerNode->properties();
130 const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight());
131 if (properties.getClipToBounds() && layerCanvas->quickReject(bounds)) {
132 return;
133 }
134
135 ATRACE_FORMAT("drawLayer [%s] %.1f x %.1f", layerNode->getName(), bounds.width(),
136 bounds.height());
137
138 layerNode->getSkiaLayer()->hasRenderedSinceRepaint = false;
139 layerCanvas->clear(SK_ColorTRANSPARENT);
140
141 RenderNodeDrawable root(layerNode, layerCanvas, false);
142 root.forceDraw(layerCanvas);
143 layerCanvas->restoreToCount(saveCount);
144
145 LightingInfo::setLightCenterRaw(savedLightCenter);
146
147 // cache the current context so that we can defer flushing it until
148 // either all the layers have been rendered or the context changes
Adlai Hollerab762152020-09-16 10:37:19 -0400149 GrDirectContext* currentContext =
150 GrAsDirectContext(layerNode->getLayerSurface()->getCanvas()->recordingContext());
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500151 if (cachedContext.get() != currentContext) {
152 if (cachedContext.get()) {
153 ATRACE_NAME("flush layers (context changed)");
Greg Danielc7ad4082020-05-14 15:38:26 -0400154 cachedContext->flushAndSubmit();
Stan Iliev500a0c32016-10-26 10:30:09 -0400155 }
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500156 cachedContext.reset(SkSafeRef(currentContext));
Stan Iliev500a0c32016-10-26 10:30:09 -0400157 }
158 }
Derek Sollenbergerf7df1842017-09-05 11:15:58 -0400159
160 if (cachedContext.get()) {
Derek Sollenbergerbe3876c2018-04-20 16:13:31 -0400161 ATRACE_NAME("flush layers");
Greg Danielc7ad4082020-05-14 15:38:26 -0400162 cachedContext->flushAndSubmit();
Derek Sollenbergerf7df1842017-09-05 11:15:58 -0400163 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400164}
165
John Reck1bcacfd2017-11-03 10:12:19 -0700166bool SkiaPipeline::createOrUpdateLayer(RenderNode* node, const DamageAccumulator& damageAccumulator,
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700167 ErrorHandler* errorHandler) {
Derek Sollenberger03e6cff72017-12-04 15:07:08 -0500168 // compute the size of the surface (i.e. texture) to be allocated for this layer
169 const int surfaceWidth = ceilf(node->getWidth() / float(LAYER_SIZE)) * LAYER_SIZE;
170 const int surfaceHeight = ceilf(node->getHeight() / float(LAYER_SIZE)) * LAYER_SIZE;
171
Stan Iliev500a0c32016-10-26 10:30:09 -0400172 SkSurface* layer = node->getLayerSurface();
Derek Sollenberger03e6cff72017-12-04 15:07:08 -0500173 if (!layer || layer->width() != surfaceWidth || layer->height() != surfaceHeight) {
Stan Iliev08fc19a2017-07-24 10:20:33 -0400174 SkImageInfo info;
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700175 info = SkImageInfo::Make(surfaceWidth, surfaceHeight, getSurfaceColorType(),
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400176 kPremul_SkAlphaType, getSurfaceColorSpace());
Stan Iliev500a0c32016-10-26 10:30:09 -0400177 SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
178 SkASSERT(mRenderThread.getGrContext() != nullptr);
John Reck1bcacfd2017-11-03 10:12:19 -0700179 node->setLayerSurface(SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Derek Sollenberger25833d22019-01-14 13:55:55 -0500180 SkBudgeted::kYes, info, 0,
181 this->getSurfaceOrigin(), &props));
Stan Iliev500a0c32016-10-26 10:30:09 -0400182 if (node->getLayerSurface()) {
183 // update the transform in window of the layer to reset its origin wrt light source
184 // position
185 Matrix4 windowTransform;
186 damageAccumulator.computeCurrentTransform(&windowTransform);
Stan Ilievda7c19c2019-05-22 14:43:44 -0400187 node->getSkiaLayer()->inverseTransformInWindow.loadInverse(windowTransform);
Stan Iliev216b1572018-03-26 14:29:50 -0400188 } else {
189 String8 cachesOutput;
190 mRenderThread.cacheManager().dumpMemoryUsage(cachesOutput,
John Reck283bb462018-12-13 16:40:14 -0800191 &mRenderThread.renderState());
Stan Iliev216b1572018-03-26 14:29:50 -0400192 ALOGE("%s", cachesOutput.string());
193 if (errorHandler) {
194 std::ostringstream err;
195 err << "Unable to create layer for " << node->getName();
196 const int maxTextureSize = DeviceInfo::get()->maxTextureSize();
197 err << ", size " << info.width() << "x" << info.height() << " max size "
John Reck283bb462018-12-13 16:40:14 -0800198 << maxTextureSize << " color type " << (int)info.colorType() << " has context "
199 << (int)(mRenderThread.getGrContext() != nullptr);
Stan Iliev216b1572018-03-26 14:29:50 -0400200 errorHandler->onError(err.str());
201 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400202 }
203 return true;
204 }
205 return false;
206}
207
Stan Iliev500a0c32016-10-26 10:30:09 -0400208void SkiaPipeline::prepareToDraw(const RenderThread& thread, Bitmap* bitmap) {
Adlai Hollerab762152020-09-16 10:37:19 -0400209 GrDirectContext* context = thread.getGrContext();
Stan Iliev500a0c32016-10-26 10:30:09 -0400210 if (context) {
211 ATRACE_FORMAT("Bitmap#prepareToDraw %dx%d", bitmap->width(), bitmap->height());
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400212 auto image = bitmap->makeImage();
Stan Iliev7bc3bc62017-05-24 13:28:36 -0400213 if (image.get() && !bitmap->isHardware()) {
214 SkImage_pinAsTexture(image.get(), context);
215 SkImage_unpinAsTexture(image.get(), context);
216 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400217 }
218}
219
John Reck322b8ab2019-03-14 13:15:28 -0700220static void savePictureAsync(const sk_sp<SkData>& data, const std::string& filename) {
221 CommonPool::post([data, filename] {
222 if (0 == access(filename.c_str(), F_OK)) {
Stan Ilieve9d00122017-09-19 12:07:10 -0400223 return;
224 }
225
John Reck322b8ab2019-03-14 13:15:28 -0700226 SkFILEWStream stream(filename.c_str());
Stan Ilieve9d00122017-09-19 12:07:10 -0400227 if (stream.isValid()) {
John Reck322b8ab2019-03-14 13:15:28 -0700228 stream.write(data->data(), data->size());
Stan Ilieve9d00122017-09-19 12:07:10 -0400229 stream.flush();
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400230 ALOGD("SKP Captured Drawing Output (%zu bytes) for frame. %s", stream.bytesWritten(),
John Reck322b8ab2019-03-14 13:15:28 -0700231 filename.c_str());
Stan Ilieve9d00122017-09-19 12:07:10 -0400232 }
John Reck322b8ab2019-03-14 13:15:28 -0700233 });
234}
Stan Ilieve9d00122017-09-19 12:07:10 -0400235
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400236// Note multiple SkiaPipeline instances may be loaded if more than one app is visible.
237// Each instance may observe the filename changing and try to record to a file of the same name.
238// Only the first one will succeed. There is no scope available here where we could coordinate
239// to cause this function to return true for only one of the instances.
240bool SkiaPipeline::shouldStartNewFileCapture() {
241 // Don't start a new file based capture if one is currently ongoing.
242 if (mCaptureMode != CaptureMode::None) { return false; }
243
244 // A new capture is started when the filename property changes.
245 // Read the filename property.
246 std::string prop = base::GetProperty(PROPERTY_CAPTURE_SKP_FILENAME, "0");
247 // if the filename property changed to a valid value
248 if (prop[0] != '0' && mCapturedFile != prop) {
249 // remember this new filename
250 mCapturedFile = prop;
251 // and get a property indicating how many frames to capture.
252 mCaptureSequence = base::GetIntProperty(PROPERTY_CAPTURE_SKP_FRAMES, 1);
John Reck5cca8f22018-12-10 17:06:22 -0800253 if (mCaptureSequence <= 0) {
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400254 return false;
255 } else if (mCaptureSequence == 1) {
256 mCaptureMode = CaptureMode::SingleFrameSKP;
257 } else {
258 mCaptureMode = CaptureMode::MultiFrameSKP;
Stan Ilieve9d00122017-09-19 12:07:10 -0400259 }
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400260 return true;
261 }
262 return false;
263}
264
265// performs the first-frame work of a multi frame SKP capture. Returns true if successful.
266bool SkiaPipeline::setupMultiFrameCapture() {
267 ALOGD("Set up multi-frame capture, frames = %d", mCaptureSequence);
268 // We own this stream and need to hold it until close() finishes.
269 auto stream = std::make_unique<SkFILEWStream>(mCapturedFile.c_str());
270 if (stream->isValid()) {
271 mOpenMultiPicStream = std::move(stream);
272 mSerialContext.reset(new SkSharingSerialContext());
273 SkSerialProcs procs;
274 procs.fImageProc = SkSharingSerialContext::serializeImage;
275 procs.fImageCtx = mSerialContext.get();
Nathaniel Nifong429fff42020-01-30 14:38:21 -0500276 procs.fTypefaceProc = [](SkTypeface* tf, void* ctx){
277 return tf->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
278 };
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400279 // SkDocuments don't take owership of the streams they write.
280 // we need to keep it until after mMultiPic.close()
281 // procs is passed as a pointer, but just as a method of having an optional default.
282 // procs doesn't need to outlive this Make call.
Nathaniel Nifong7c216772021-01-22 13:23:25 -0500283 mMultiPic = SkMakeMultiPictureDocument(mOpenMultiPicStream.get(), &procs,
284 [sharingCtx = mSerialContext.get()](const SkPicture* pic) {
285 SkSharingSerialContext::collectNonTextureImagesFromPicture(pic, sharingCtx);
286 });
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400287 return true;
288 } else {
289 ALOGE("Could not open \"%s\" for writing.", mCapturedFile.c_str());
290 mCaptureSequence = 0;
291 mCaptureMode = CaptureMode::None;
292 return false;
293 }
294}
295
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500296// recurse through the rendernode's children, add any nodes which are layers to the queue.
297static void collectLayers(RenderNode* node, LayerUpdateQueue* layers) {
John Reckbe671952021-01-13 22:39:32 -0500298 SkiaDisplayList* dl = node->getDisplayList().asSkiaDl();
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500299 if (dl) {
300 const auto& prop = node->properties();
301 if (node->hasLayer()) {
302 layers->enqueueLayerWithDamage(node, Rect(prop.getWidth(), prop.getHeight()));
303 }
304 // The way to recurse through rendernodes is to call this with a lambda.
305 dl->updateChildren([&](RenderNode* child) { collectLayers(child, layers); });
306 }
307}
308
309// record the provided layers to the provided canvas as self-contained skpictures.
310static void recordLayers(const LayerUpdateQueue& layers,
311 SkCanvas* mskpCanvas) {
312 const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
313 // Record the commands to re-draw each dirty layer into an SkPicture
314 for (size_t i = 0; i < layers.entries().size(); i++) {
315 RenderNode* layerNode = layers.entries()[i].renderNode.get();
316 const Rect& layerDamage = layers.entries()[i].damage;
317 const RenderProperties& properties = layerNode->properties();
318
319 // Temporarily map current light center into RenderNode's coordinate space
320 Vector3 transformedLightCenter(savedLightCenter);
321 layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
322 LightingInfo::setLightCenterRaw(transformedLightCenter);
323
324 SkPictureRecorder layerRec;
325 auto* recCanvas = layerRec.beginRecording(properties.getWidth(),
326 properties.getHeight());
327 // This is not recorded but still causes clipping.
328 recCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
329 RenderNodeDrawable root(layerNode, recCanvas, false);
330 root.forceDraw(recCanvas);
331 // Now write this picture into the SKP canvas with an annotation indicating what it is
332 mskpCanvas->drawAnnotation(layerDamage.toSkRect(), String8::format(
333 "OffscreenLayerDraw|%" PRId64, layerNode->uniqueId()).c_str(), nullptr);
334 mskpCanvas->drawPicture(layerRec.finishRecordingAsPicture());
335 }
336 LightingInfo::setLightCenterRaw(savedLightCenter);
337}
338
339SkCanvas* SkiaPipeline::tryCapture(SkSurface* surface, RenderNode* root,
340 const LayerUpdateQueue& dirtyLayers) {
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400341 if (CC_LIKELY(!Properties::skpCaptureEnabled)) {
342 return surface->getCanvas(); // Bail out early when capture is not turned on.
343 }
344 // Note that shouldStartNewFileCapture tells us if this is the *first* frame of a capture.
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500345 bool firstFrameOfAnim = false;
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400346 if (shouldStartNewFileCapture() && mCaptureMode == CaptureMode::MultiFrameSKP) {
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500347 // set a reminder to record every layer near the end of this method, after we have set up
348 // the nway canvas.
349 firstFrameOfAnim = true;
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400350 if (!setupMultiFrameCapture()) {
351 return surface->getCanvas();
Stan Ilieve9d00122017-09-19 12:07:10 -0400352 }
353 }
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400354
355 // Create a canvas pointer, fill it depending on what kind of capture is requested (if any)
356 SkCanvas* pictureCanvas = nullptr;
357 switch (mCaptureMode) {
358 case CaptureMode::CallbackAPI:
359 case CaptureMode::SingleFrameSKP:
360 mRecorder.reset(new SkPictureRecorder());
Nathaniel Nifong31fee3a2019-07-11 16:27:14 -0400361 pictureCanvas = mRecorder->beginRecording(surface->width(), surface->height());
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400362 break;
363 case CaptureMode::MultiFrameSKP:
364 // If a multi frame recording is active, initialize recording for a single frame of a
365 // multi frame file.
366 pictureCanvas = mMultiPic->beginPage(surface->width(), surface->height());
367 break;
368 case CaptureMode::None:
369 // Returning here in the non-capture case means we can count on pictureCanvas being
370 // non-null below.
371 return surface->getCanvas();
372 }
373
374 // Setting up an nway canvas is common to any kind of capture.
375 mNwayCanvas = std::make_unique<SkNWayCanvas>(surface->width(), surface->height());
376 mNwayCanvas->addCanvas(surface->getCanvas());
377 mNwayCanvas->addCanvas(pictureCanvas);
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500378
379 if (firstFrameOfAnim) {
380 // On the first frame of any mskp capture we want to record any layers that are needed in
381 // frame but may have been rendered offscreen before recording began.
382 // We do not maintain a list of all layers, since it isn't needed outside this rare,
383 // recording use case. Traverse the tree to find them and put them in this LayerUpdateQueue.
384 LayerUpdateQueue luq;
385 collectLayers(root, &luq);
386 recordLayers(luq, mNwayCanvas.get());
387 } else {
388 // on non-first frames, we record any normal layer draws (dirty regions)
389 recordLayers(dirtyLayers, mNwayCanvas.get());
390 }
391
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400392 return mNwayCanvas.get();
Stan Ilieve9d00122017-09-19 12:07:10 -0400393}
394
395void SkiaPipeline::endCapture(SkSurface* surface) {
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400396 if (CC_LIKELY(mCaptureMode == CaptureMode::None)) { return; }
John Reck5cca8f22018-12-10 17:06:22 -0800397 mNwayCanvas.reset();
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400398 ATRACE_CALL();
399 if (mCaptureSequence > 0 && mCaptureMode == CaptureMode::MultiFrameSKP) {
400 mMultiPic->endPage();
401 mCaptureSequence--;
402 if (mCaptureSequence == 0) {
403 mCaptureMode = CaptureMode::None;
404 // Pass mMultiPic and mOpenMultiPicStream to a background thread, which will handle
405 // the heavyweight serialization work and destroy them. mOpenMultiPicStream is released
406 // to a bare pointer because keeping it in a smart pointer makes the lambda
407 // non-copyable. The lambda is only called once, so this is safe.
408 SkFILEWStream* stream = mOpenMultiPicStream.release();
409 CommonPool::post([doc = std::move(mMultiPic), stream]{
410 ALOGD("Finalizing multi frame SKP");
411 doc->close();
412 delete stream;
413 ALOGD("Multi frame SKP complete.");
414 });
415 }
416 } else {
Stan Ilieve9d00122017-09-19 12:07:10 -0400417 sk_sp<SkPicture> picture = mRecorder->finishRecordingAsPicture();
Stan Ilieve9d00122017-09-19 12:07:10 -0400418 if (picture->approximateOpCount() > 0) {
John Reck5cca8f22018-12-10 17:06:22 -0800419 if (mPictureCapturedCallback) {
420 std::invoke(mPictureCapturedCallback, std::move(picture));
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400421 } else {
422 // single frame skp to file
Nathaniel Nifong429fff42020-01-30 14:38:21 -0500423 SkSerialProcs procs;
424 procs.fTypefaceProc = [](SkTypeface* tf, void* ctx){
425 return tf->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
426 };
John Reck76005182021-06-09 22:43:05 -0400427 auto data = picture->serialize(&procs);
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400428 savePictureAsync(data, mCapturedFile);
429 mCaptureSequence = 0;
Derek Sollenberger5f9753d2020-04-01 15:59:02 -0400430 mCaptureMode = CaptureMode::None;
Stan Ilieve9d00122017-09-19 12:07:10 -0400431 }
Stan Ilieve9d00122017-09-19 12:07:10 -0400432 }
433 mRecorder.reset();
434 }
435}
436
Stan Iliev500a0c32016-10-26 10:30:09 -0400437void SkiaPipeline::renderFrame(const LayerUpdateQueue& layers, const SkRect& clip,
John Reck1bcacfd2017-11-03 10:12:19 -0700438 const std::vector<sp<RenderNode>>& nodes, bool opaque,
Greg Danielc4076782019-01-08 16:01:18 -0500439 const Rect& contentDrawBounds, sk_sp<SkSurface> surface,
440 const SkMatrix& preTransform) {
John Reck5cca8f22018-12-10 17:06:22 -0800441 bool previousSkpEnabled = Properties::skpCaptureEnabled;
442 if (mPictureCapturedCallback) {
443 Properties::skpCaptureEnabled = true;
444 }
445
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500446 // Initialize the canvas for the current frame, that might be a recording canvas if SKP
447 // capture is enabled.
448 SkCanvas* canvas = tryCapture(surface.get(), nodes[0].get(), layers);
449
Stan Iliev500a0c32016-10-26 10:30:09 -0400450 // draw all layers up front
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700451 renderLayersImpl(layers, opaque);
Stan Iliev500a0c32016-10-26 10:30:09 -0400452
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500453 renderFrameImpl(clip, nodes, opaque, contentDrawBounds, canvas, preTransform);
Matt Sarettf58cc922016-11-14 18:33:38 -0500454
Stan Ilieve9d00122017-09-19 12:07:10 -0400455 endCapture(surface.get());
Matt Sarettf58cc922016-11-14 18:33:38 -0500456
457 if (CC_UNLIKELY(Properties::debugOverdraw)) {
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500458 renderOverdraw(clip, nodes, contentDrawBounds, surface, preTransform);
Matt Sarettf58cc922016-11-14 18:33:38 -0500459 }
460
John Reck5cca8f22018-12-10 17:06:22 -0800461 Properties::skpCaptureEnabled = previousSkpEnabled;
Matt Sarettf58cc922016-11-14 18:33:38 -0500462}
463
Stan Iliev52771272016-11-17 09:54:38 -0500464namespace {
465static Rect nodeBounds(RenderNode& node) {
466 auto& props = node.properties();
John Reck1bcacfd2017-11-03 10:12:19 -0700467 return Rect(props.getLeft(), props.getTop(), props.getRight(), props.getBottom());
Stan Iliev52771272016-11-17 09:54:38 -0500468}
John Reck0fa0cbc2019-04-05 16:57:46 -0700469} // namespace
Stan Iliev52771272016-11-17 09:54:38 -0500470
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500471void SkiaPipeline::renderFrameImpl(const SkRect& clip,
John Reck1bcacfd2017-11-03 10:12:19 -0700472 const std::vector<sp<RenderNode>>& nodes, bool opaque,
Greg Danielc4076782019-01-08 16:01:18 -0500473 const Rect& contentDrawBounds, SkCanvas* canvas,
474 const SkMatrix& preTransform) {
Stan Ilievb66b8bb2016-12-15 18:17:42 -0500475 SkAutoCanvasRestore saver(canvas, true);
Nathaniel Nifongcff969f2020-01-09 14:03:49 -0500476 auto clipRestriction = preTransform.mapRect(clip).roundOut();
John Reck76005182021-06-09 22:43:05 -0400477 if (CC_UNLIKELY(isCapturingSkp())) {
Nathaniel Nifong89a5dc52020-01-17 15:32:17 -0500478 canvas->drawAnnotation(SkRect::Make(clipRestriction), "AndroidDeviceClipRestriction",
479 nullptr);
480 } else {
481 // clip drawing to dirty region only when not recording SKP files (which should contain all
482 // draw ops on every frame)
483 canvas->androidFramework_setDeviceClipRestriction(clipRestriction);
484 }
Greg Danielc4076782019-01-08 16:01:18 -0500485 canvas->concat(preTransform);
Stan Iliev500a0c32016-10-26 10:30:09 -0400486
Stan Ilievaadc0322018-03-23 10:50:11 -0400487 // STOPSHIP: Revert, temporary workaround to clear always F16 frame buffer for b/74976293
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700488 if (!opaque || getSurfaceColorType() == kRGBA_F16_SkColorType) {
Stan Iliev500a0c32016-10-26 10:30:09 -0400489 canvas->clear(SK_ColorTRANSPARENT);
490 }
491
Stan Iliev52771272016-11-17 09:54:38 -0500492 if (1 == nodes.size()) {
493 if (!nodes[0]->nothingToDraw()) {
Stan Iliev52771272016-11-17 09:54:38 -0500494 RenderNodeDrawable root(nodes[0].get(), canvas);
495 root.draw(canvas);
496 }
497 } else if (0 == nodes.size()) {
John Reck1bcacfd2017-11-03 10:12:19 -0700498 // nothing to draw
Stan Iliev52771272016-11-17 09:54:38 -0500499 } else {
500 // It there are multiple render nodes, they are laid out as follows:
501 // #0 - backdrop (content + caption)
502 // #1 - content (local bounds are at (0,0), will be translated and clipped to backdrop)
503 // #2 - additional overlay nodes
John Reck1bcacfd2017-11-03 10:12:19 -0700504 // Usually the backdrop cannot be seen since it will be entirely covered by the content.
505 // While
506 // resizing however it might become partially visible. The following render loop will crop
507 // the
508 // backdrop against the content and draw the remaining part of it. It will then draw the
509 // content
Stan Iliev52771272016-11-17 09:54:38 -0500510 // cropped to the backdrop (since that indicates a shrinking of the window).
511 //
512 // Additional nodes will be drawn on top with no particular clipping semantics.
Stan Iliev500a0c32016-10-26 10:30:09 -0400513
Stan Iliev52771272016-11-17 09:54:38 -0500514 // Usually the contents bounds should be mContentDrawBounds - however - we will
515 // move it towards the fixed edge to give it a more stable appearance (for the moment).
516 // If there is no content bounds we ignore the layering as stated above and start with 2.
Stan Iliev500a0c32016-10-26 10:30:09 -0400517
Stan Iliev52771272016-11-17 09:54:38 -0500518 // Backdrop bounds in render target space
519 const Rect backdrop = nodeBounds(*nodes[0]);
Stan Iliev500a0c32016-10-26 10:30:09 -0400520
John Reck1bcacfd2017-11-03 10:12:19 -0700521 // Bounds that content will fill in render target space (note content node bounds may be
522 // bigger)
Stan Iliev52771272016-11-17 09:54:38 -0500523 Rect content(contentDrawBounds.getWidth(), contentDrawBounds.getHeight());
524 content.translate(backdrop.left, backdrop.top);
525 if (!content.contains(backdrop) && !nodes[0]->nothingToDraw()) {
526 // Content doesn't entirely overlap backdrop, so fill around content (right/bottom)
Stan Iliev500a0c32016-10-26 10:30:09 -0400527
Stan Iliev52771272016-11-17 09:54:38 -0500528 // 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 -0700529 // also fill left/top. Currently, both 2up and freeform position content at the top/left
530 // of
Stan Iliev52771272016-11-17 09:54:38 -0500531 // the backdrop, so this isn't necessary.
532 RenderNodeDrawable backdropNode(nodes[0].get(), canvas);
533 if (content.right < backdrop.right) {
534 // draw backdrop to right side of content
535 SkAutoCanvasRestore acr(canvas, true);
John Reck1bcacfd2017-11-03 10:12:19 -0700536 canvas->clipRect(SkRect::MakeLTRB(content.right, backdrop.top, backdrop.right,
537 backdrop.bottom));
Stan Iliev52771272016-11-17 09:54:38 -0500538 backdropNode.draw(canvas);
539 }
540 if (content.bottom < backdrop.bottom) {
541 // draw backdrop to bottom of content
542 // Note: bottom fill uses content left/right, to avoid overdrawing left/right fill
543 SkAutoCanvasRestore acr(canvas, true);
John Reck1bcacfd2017-11-03 10:12:19 -0700544 canvas->clipRect(SkRect::MakeLTRB(content.left, content.bottom, content.right,
545 backdrop.bottom));
Stan Iliev52771272016-11-17 09:54:38 -0500546 backdropNode.draw(canvas);
547 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400548 }
549
Stan Iliev52771272016-11-17 09:54:38 -0500550 RenderNodeDrawable contentNode(nodes[1].get(), canvas);
551 if (!backdrop.isEmpty()) {
552 // content node translation to catch up with backdrop
553 float dx = backdrop.left - contentDrawBounds.left;
554 float dy = backdrop.top - contentDrawBounds.top;
555
556 SkAutoCanvasRestore acr(canvas, true);
557 canvas->translate(dx, dy);
John Reck1bcacfd2017-11-03 10:12:19 -0700558 const SkRect contentLocalClip =
559 SkRect::MakeXYWH(contentDrawBounds.left, contentDrawBounds.top,
560 backdrop.getWidth(), backdrop.getHeight());
Stan Iliev52771272016-11-17 09:54:38 -0500561 canvas->clipRect(contentLocalClip);
562 contentNode.draw(canvas);
563 } else {
564 SkAutoCanvasRestore acr(canvas, true);
565 contentNode.draw(canvas);
566 }
567
568 // remaining overlay nodes, simply defer
569 for (size_t index = 2; index < nodes.size(); index++) {
570 if (!nodes[index]->nothingToDraw()) {
571 SkAutoCanvasRestore acr(canvas, true);
572 RenderNodeDrawable overlayNode(nodes[index].get(), canvas);
573 overlayNode.draw(canvas);
574 }
575 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400576 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400577}
578
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500579void SkiaPipeline::dumpResourceCacheUsage() const {
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400580 int resources;
581 size_t bytes;
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500582 mRenderThread.getGrContext()->getResourceCacheUsage(&resources, &bytes);
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400583 size_t maxBytes = mRenderThread.getGrContext()->getResourceCacheLimit();
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500584
585 SkString log("Resource Cache Usage:\n");
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400586 log.appendf("%8d items\n", resources);
John Reck1bcacfd2017-11-03 10:12:19 -0700587 log.appendf("%8zu bytes (%.2f MB) out of %.2f MB maximum\n", bytes,
588 bytes * (1.0f / (1024.0f * 1024.0f)), maxBytes * (1.0f / (1024.0f * 1024.0f)));
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500589
590 ALOGD("%s", log.c_str());
591}
592
Peiyong Lin3bff1352018-12-11 07:56:07 -0800593void SkiaPipeline::setSurfaceColorProperties(ColorMode colorMode) {
Derek Sollenberger1863d942020-02-05 15:41:51 -0500594 mColorMode = colorMode;
John Reckb36bfdd2020-07-23 13:47:49 -0700595 switch (colorMode) {
596 case ColorMode::Default:
597 mSurfaceColorType = SkColorType::kN32_SkColorType;
598 mSurfaceColorSpace = SkColorSpace::MakeSRGB();
599 break;
600 case ColorMode::WideColorGamut:
601 mSurfaceColorType = DeviceInfo::get()->getWideColorType();
602 mSurfaceColorSpace = DeviceInfo::get()->getWideColorSpace();
603 break;
604 case ColorMode::Hdr:
605 mSurfaceColorType = SkColorType::kRGBA_F16_SkColorType;
606 mSurfaceColorSpace = SkColorSpace::MakeRGB(GetPQSkTransferFunction(), SkNamedGamut::kRec2020);
607 break;
608 case ColorMode::Hdr10:
609 mSurfaceColorType = SkColorType::kRGBA_1010102_SkColorType;
610 mSurfaceColorSpace = SkColorSpace::MakeRGB(GetPQSkTransferFunction(), SkNamedGamut::kRec2020);
611 break;
Peiyong Lin3bff1352018-12-11 07:56:07 -0800612 }
613}
614
Matt Sarettf58cc922016-11-14 18:33:38 -0500615// Overdraw debugging
616
617// These colors should be kept in sync with Caches::getOverdrawColor() with a few differences.
Mike Reed331c4e12020-02-13 10:21:54 -0500618// This implementation requires transparent entries for "no overdraw" and "single draws".
619static const SkColor kOverdrawColors[2][6] = {
620 {
621 0x00000000,
622 0x00000000,
623 0x2f0000ff,
624 0x2f00ff00,
625 0x3fff0000,
626 0x7fff0000,
627 },
628 {
629 0x00000000,
630 0x00000000,
631 0x2f0000ff,
632 0x4fffff00,
633 0x5fff89d7,
634 0x7fff0000,
635 },
Matt Sarettf58cc922016-11-14 18:33:38 -0500636};
637
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500638void SkiaPipeline::renderOverdraw(const SkRect& clip,
John Reck1bcacfd2017-11-03 10:12:19 -0700639 const std::vector<sp<RenderNode>>& nodes,
Greg Danielc4076782019-01-08 16:01:18 -0500640 const Rect& contentDrawBounds, sk_sp<SkSurface> surface,
641 const SkMatrix& preTransform) {
Matt Sarettf58cc922016-11-14 18:33:38 -0500642 // Set up the overdraw canvas.
643 SkImageInfo offscreenInfo = SkImageInfo::MakeA8(surface->width(), surface->height());
644 sk_sp<SkSurface> offscreen = surface->makeSurface(offscreenInfo);
Nathaniel Nifongfe05b7c2019-09-17 12:52:52 -0400645 LOG_ALWAYS_FATAL_IF(!offscreen, "Failed to create offscreen SkSurface for overdraw viz.");
Matt Sarettf58cc922016-11-14 18:33:38 -0500646 SkOverdrawCanvas overdrawCanvas(offscreen->getCanvas());
647
648 // Fake a redraw to replay the draw commands. This will increment the alpha channel
649 // each time a pixel would have been drawn.
650 // Pass true for opaque so we skip the clear - the overdrawCanvas is already zero
651 // initialized.
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500652 renderFrameImpl(clip, nodes, true, contentDrawBounds, &overdrawCanvas, preTransform);
Matt Sarettf58cc922016-11-14 18:33:38 -0500653 sk_sp<SkImage> counts = offscreen->makeImageSnapshot();
654
655 // Draw overdraw colors to the canvas. The color filter will convert counts to colors.
656 SkPaint paint;
Mike Reed331c4e12020-02-13 10:21:54 -0500657 const SkColor* colors = kOverdrawColors[static_cast<int>(Properties::overdrawColorSet)];
658 paint.setColorFilter(SkOverdrawColorFilter::MakeWithSkColors(colors));
Mike Reed7994a312021-01-28 18:06:26 -0500659 surface->getCanvas()->drawImage(counts.get(), 0.0f, 0.0f, SkSamplingOptions(), &paint);
Matt Sarettf58cc922016-11-14 18:33:38 -0500660}
661
Stan Iliev500a0c32016-10-26 10:30:09 -0400662} /* namespace skiapipeline */
663} /* namespace uirenderer */
664} /* namespace android */