blob: 494633d57210b38c37ff192dd280d13115e43f89 [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
Kevin Lubick1175dc02022-02-28 12:41:27 -050019#include <SkCanvas.h>
20#include <SkColor.h>
21#include <SkColorSpace.h>
22#include <SkData.h>
23#include <SkImage.h>
Kevin Lubick93671082023-03-13 18:30:55 +000024#include <SkImageAndroid.h>
Peiyong Lin3bff1352018-12-11 07:56:07 -080025#include <SkImageInfo.h>
Kevin Lubick1175dc02022-02-28 12:41:27 -050026#include <SkMatrix.h>
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -040027#include <SkMultiPictureDocument.h>
Matt Sarettf58cc922016-11-14 18:33:38 -050028#include <SkOverdrawCanvas.h>
29#include <SkOverdrawColorFilter.h>
Stan Iliev500a0c32016-10-26 10:30:09 -040030#include <SkPicture.h>
31#include <SkPictureRecorder.h>
Kevin Lubick1175dc02022-02-28 12:41:27 -050032#include <SkRect.h>
33#include <SkRefCnt.h>
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -040034#include <SkSerialProcs.h>
Kevin Lubick1175dc02022-02-28 12:41:27 -050035#include <SkStream.h>
36#include <SkString.h>
Alec Mouri43fe6fc2019-12-23 07:46:19 -080037#include <SkTypeface.h>
38#include <android-base/properties.h>
John Reck29b1ee02023-04-04 17:44:23 -040039#include <gui/TraceUtils.h>
Alec Mouri43fe6fc2019-12-23 07:46:19 -080040#include <unistd.h>
41
42#include <sstream>
43
Fedor Kudasov90df0562019-06-19 11:41:34 +010044#include "LightingInfo.h"
Stan Iliev23c38a92017-03-23 00:12:50 -040045#include "VectorDrawable.h"
John Reck29b1ee02023-04-04 17:44:23 -040046#include "include/gpu/GpuTypes.h" // from Skia
John Reck322b8ab2019-03-14 13:15:28 -070047#include "thread/CommonPool.h"
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -040048#include "tools/SkSharingProc.h"
John Reckb36bfdd2020-07-23 13:47:49 -070049#include "utils/Color.h"
Nathaniel Nifong2945bff2019-11-25 09:34:21 -050050#include "utils/String8.h"
Jerome Gaillarda02a12d2019-05-28 18:07:56 +010051
Stan Iliev500a0c32016-10-26 10:30:09 -040052using namespace android::uirenderer::renderthread;
53
54namespace android {
55namespace uirenderer {
56namespace skiapipeline {
57
John Reck1bcacfd2017-11-03 10:12:19 -070058SkiaPipeline::SkiaPipeline(RenderThread& thread) : mRenderThread(thread) {
Derek Sollenberger1863d942020-02-05 15:41:51 -050059 setSurfaceColorProperties(mColorMode);
Stan Iliev23c38a92017-03-23 00:12:50 -040060}
Stan Iliev500a0c32016-10-26 10:30:09 -040061
Stan Iliev232f3622017-08-23 17:15:09 -040062SkiaPipeline::~SkiaPipeline() {
63 unpinImages();
64}
65
Stan Iliev500a0c32016-10-26 10:30:09 -040066void SkiaPipeline::onDestroyHardwareResources() {
Derek Sollenberger92a9eb92018-04-12 13:42:19 -040067 unpinImages();
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040068 mRenderThread.cacheManager().trimStaleResources();
Stan Iliev500a0c32016-10-26 10:30:09 -040069}
70
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040071bool SkiaPipeline::pinImages(std::vector<SkImage*>& mutableImages) {
Greg Danielf8cb5252021-06-30 10:40:34 -040072 if (!mRenderThread.getGrContext()) {
73 ALOGD("Trying to pin an image with an invalid GrContext");
74 return false;
75 }
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040076 for (SkImage* image : mutableImages) {
Kevin Lubick93671082023-03-13 18:30:55 +000077 if (skgpu::ganesh::PinAsTexture(mRenderThread.getGrContext(), image)) {
Derek Sollenberger189e8742016-11-16 16:00:17 -050078 mPinnedImages.emplace_back(sk_ref_sp(image));
79 } else {
80 return false;
81 }
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040082 }
83 return true;
84}
85
86void SkiaPipeline::unpinImages() {
87 for (auto& image : mPinnedImages) {
Kevin Lubick93671082023-03-13 18:30:55 +000088 skgpu::ganesh::UnpinTexture(mRenderThread.getGrContext(), image.get());
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040089 }
90 mPinnedImages.clear();
91}
92
John Reckd9d7f122018-05-03 14:40:56 -070093void SkiaPipeline::renderLayers(const LightGeometry& lightGeometry,
John Reck1bcacfd2017-11-03 10:12:19 -070094 LayerUpdateQueue* layerUpdateQueue, bool opaque,
Peiyong Lin1f6aa122018-09-10 16:28:08 -070095 const LightInfo& lightInfo) {
Fedor Kudasov90df0562019-06-19 11:41:34 +010096 LightingInfo::updateLighting(lightGeometry, lightInfo);
Stan Iliev500a0c32016-10-26 10:30:09 -040097 ATRACE_NAME("draw layers");
Peiyong Lin1f6aa122018-09-10 16:28:08 -070098 renderLayersImpl(*layerUpdateQueue, opaque);
Stan Iliev500a0c32016-10-26 10:30:09 -040099 layerUpdateQueue->clear();
100}
101
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700102void SkiaPipeline::renderLayersImpl(const LayerUpdateQueue& layers, bool opaque) {
Adlai Hollerab762152020-09-16 10:37:19 -0400103 sk_sp<GrDirectContext> cachedContext;
Derek Sollenbergerf7df1842017-09-05 11:15:58 -0400104
Stan Iliev500a0c32016-10-26 10:30:09 -0400105 // Render all layers that need to be updated, in order.
106 for (size_t i = 0; i < layers.entries().size(); i++) {
John Reckfc29f7acd2017-03-02 13:23:16 -0800107 RenderNode* layerNode = layers.entries()[i].renderNode.get();
Stan Iliev500a0c32016-10-26 10:30:09 -0400108 // only schedule repaint if node still on layer - possible it may have been
109 // removed during a dropped frame, but layers may still remain scheduled so
110 // as not to lose info on what portion is damaged
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500111 if (CC_UNLIKELY(layerNode->getLayerSurface() == nullptr)) {
112 continue;
113 }
114 SkASSERT(layerNode->getLayerSurface());
John Reckbe671952021-01-13 22:39:32 -0500115 SkiaDisplayList* displayList = layerNode->getDisplayList().asSkiaDl();
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500116 if (!displayList || displayList->isEmpty()) {
117 ALOGE("%p drawLayers(%s) : missing drawable", layerNode, layerNode->getName());
118 return;
119 }
120
121 const Rect& layerDamage = layers.entries()[i].damage;
122
123 SkCanvas* layerCanvas = layerNode->getLayerSurface()->getCanvas();
124
125 int saveCount = layerCanvas->save();
126 SkASSERT(saveCount == 1);
127
128 layerCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
129
130 // TODO: put localized light center calculation and storage to a drawable related code.
131 // It does not seem right to store something localized in a global state
132 // fix here and in recordLayers
133 const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
134 Vector3 transformedLightCenter(savedLightCenter);
135 // map current light center into RenderNode's coordinate space
136 layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
137 LightingInfo::setLightCenterRaw(transformedLightCenter);
138
139 const RenderProperties& properties = layerNode->properties();
140 const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight());
141 if (properties.getClipToBounds() && layerCanvas->quickReject(bounds)) {
142 return;
143 }
144
145 ATRACE_FORMAT("drawLayer [%s] %.1f x %.1f", layerNode->getName(), bounds.width(),
146 bounds.height());
147
148 layerNode->getSkiaLayer()->hasRenderedSinceRepaint = false;
149 layerCanvas->clear(SK_ColorTRANSPARENT);
150
151 RenderNodeDrawable root(layerNode, layerCanvas, false);
152 root.forceDraw(layerCanvas);
153 layerCanvas->restoreToCount(saveCount);
154
155 LightingInfo::setLightCenterRaw(savedLightCenter);
156
157 // cache the current context so that we can defer flushing it until
158 // either all the layers have been rendered or the context changes
Adlai Hollerab762152020-09-16 10:37:19 -0400159 GrDirectContext* currentContext =
160 GrAsDirectContext(layerNode->getLayerSurface()->getCanvas()->recordingContext());
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500161 if (cachedContext.get() != currentContext) {
162 if (cachedContext.get()) {
163 ATRACE_NAME("flush layers (context changed)");
Greg Danielc7ad4082020-05-14 15:38:26 -0400164 cachedContext->flushAndSubmit();
Stan Iliev500a0c32016-10-26 10:30:09 -0400165 }
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500166 cachedContext.reset(SkSafeRef(currentContext));
Stan Iliev500a0c32016-10-26 10:30:09 -0400167 }
168 }
Derek Sollenbergerf7df1842017-09-05 11:15:58 -0400169
170 if (cachedContext.get()) {
Derek Sollenbergerbe3876c2018-04-20 16:13:31 -0400171 ATRACE_NAME("flush layers");
Greg Danielc7ad4082020-05-14 15:38:26 -0400172 cachedContext->flushAndSubmit();
Derek Sollenbergerf7df1842017-09-05 11:15:58 -0400173 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400174}
175
John Reck1bcacfd2017-11-03 10:12:19 -0700176bool SkiaPipeline::createOrUpdateLayer(RenderNode* node, const DamageAccumulator& damageAccumulator,
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700177 ErrorHandler* errorHandler) {
Derek Sollenberger03e6cff72017-12-04 15:07:08 -0500178 // compute the size of the surface (i.e. texture) to be allocated for this layer
179 const int surfaceWidth = ceilf(node->getWidth() / float(LAYER_SIZE)) * LAYER_SIZE;
180 const int surfaceHeight = ceilf(node->getHeight() / float(LAYER_SIZE)) * LAYER_SIZE;
181
Stan Iliev500a0c32016-10-26 10:30:09 -0400182 SkSurface* layer = node->getLayerSurface();
Derek Sollenberger03e6cff72017-12-04 15:07:08 -0500183 if (!layer || layer->width() != surfaceWidth || layer->height() != surfaceHeight) {
Stan Iliev08fc19a2017-07-24 10:20:33 -0400184 SkImageInfo info;
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700185 info = SkImageInfo::Make(surfaceWidth, surfaceHeight, getSurfaceColorType(),
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400186 kPremul_SkAlphaType, getSurfaceColorSpace());
Stan Iliev500a0c32016-10-26 10:30:09 -0400187 SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
188 SkASSERT(mRenderThread.getGrContext() != nullptr);
John Reck1bcacfd2017-11-03 10:12:19 -0700189 node->setLayerSurface(SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Kevin Lubick8099b672023-01-09 14:48:45 +0000190 skgpu::Budgeted::kYes, info, 0,
Derek Sollenberger25833d22019-01-14 13:55:55 -0500191 this->getSurfaceOrigin(), &props));
Stan Iliev500a0c32016-10-26 10:30:09 -0400192 if (node->getLayerSurface()) {
193 // update the transform in window of the layer to reset its origin wrt light source
194 // position
195 Matrix4 windowTransform;
196 damageAccumulator.computeCurrentTransform(&windowTransform);
Stan Ilievda7c19c2019-05-22 14:43:44 -0400197 node->getSkiaLayer()->inverseTransformInWindow.loadInverse(windowTransform);
Stan Iliev216b1572018-03-26 14:29:50 -0400198 } else {
199 String8 cachesOutput;
200 mRenderThread.cacheManager().dumpMemoryUsage(cachesOutput,
John Reck283bb462018-12-13 16:40:14 -0800201 &mRenderThread.renderState());
Stan Iliev216b1572018-03-26 14:29:50 -0400202 ALOGE("%s", cachesOutput.string());
203 if (errorHandler) {
204 std::ostringstream err;
205 err << "Unable to create layer for " << node->getName();
206 const int maxTextureSize = DeviceInfo::get()->maxTextureSize();
207 err << ", size " << info.width() << "x" << info.height() << " max size "
John Reck283bb462018-12-13 16:40:14 -0800208 << maxTextureSize << " color type " << (int)info.colorType() << " has context "
209 << (int)(mRenderThread.getGrContext() != nullptr);
Stan Iliev216b1572018-03-26 14:29:50 -0400210 errorHandler->onError(err.str());
211 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400212 }
213 return true;
214 }
215 return false;
216}
217
Stan Iliev500a0c32016-10-26 10:30:09 -0400218void SkiaPipeline::prepareToDraw(const RenderThread& thread, Bitmap* bitmap) {
Adlai Hollerab762152020-09-16 10:37:19 -0400219 GrDirectContext* context = thread.getGrContext();
John Reckcf1170f2021-07-14 15:52:19 -0400220 if (context && !bitmap->isHardware()) {
Stan Iliev500a0c32016-10-26 10:30:09 -0400221 ATRACE_FORMAT("Bitmap#prepareToDraw %dx%d", bitmap->width(), bitmap->height());
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400222 auto image = bitmap->makeImage();
John Reckcf1170f2021-07-14 15:52:19 -0400223 if (image.get()) {
Kevin Lubick93671082023-03-13 18:30:55 +0000224 skgpu::ganesh::PinAsTexture(context, image.get());
225 skgpu::ganesh::UnpinTexture(context, image.get());
John Reckcf1170f2021-07-14 15:52:19 -0400226 // A submit is necessary as there may not be a frame coming soon, so without a call
227 // to submit these texture uploads can just sit in the queue building up until
228 // we run out of RAM
229 context->flushAndSubmit();
Stan Iliev7bc3bc62017-05-24 13:28:36 -0400230 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400231 }
232}
233
John Reck322b8ab2019-03-14 13:15:28 -0700234static void savePictureAsync(const sk_sp<SkData>& data, const std::string& filename) {
235 CommonPool::post([data, filename] {
236 if (0 == access(filename.c_str(), F_OK)) {
Stan Ilieve9d00122017-09-19 12:07:10 -0400237 return;
238 }
239
John Reck322b8ab2019-03-14 13:15:28 -0700240 SkFILEWStream stream(filename.c_str());
Stan Ilieve9d00122017-09-19 12:07:10 -0400241 if (stream.isValid()) {
John Reck322b8ab2019-03-14 13:15:28 -0700242 stream.write(data->data(), data->size());
Stan Ilieve9d00122017-09-19 12:07:10 -0400243 stream.flush();
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400244 ALOGD("SKP Captured Drawing Output (%zu bytes) for frame. %s", stream.bytesWritten(),
John Reck322b8ab2019-03-14 13:15:28 -0700245 filename.c_str());
Stan Ilieve9d00122017-09-19 12:07:10 -0400246 }
John Reck322b8ab2019-03-14 13:15:28 -0700247 });
248}
Stan Ilieve9d00122017-09-19 12:07:10 -0400249
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400250// Note multiple SkiaPipeline instances may be loaded if more than one app is visible.
251// Each instance may observe the filename changing and try to record to a file of the same name.
252// Only the first one will succeed. There is no scope available here where we could coordinate
253// to cause this function to return true for only one of the instances.
254bool SkiaPipeline::shouldStartNewFileCapture() {
255 // Don't start a new file based capture if one is currently ongoing.
256 if (mCaptureMode != CaptureMode::None) { return false; }
257
258 // A new capture is started when the filename property changes.
259 // Read the filename property.
260 std::string prop = base::GetProperty(PROPERTY_CAPTURE_SKP_FILENAME, "0");
261 // if the filename property changed to a valid value
262 if (prop[0] != '0' && mCapturedFile != prop) {
263 // remember this new filename
264 mCapturedFile = prop;
265 // and get a property indicating how many frames to capture.
266 mCaptureSequence = base::GetIntProperty(PROPERTY_CAPTURE_SKP_FRAMES, 1);
John Reck5cca8f22018-12-10 17:06:22 -0800267 if (mCaptureSequence <= 0) {
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400268 return false;
269 } else if (mCaptureSequence == 1) {
270 mCaptureMode = CaptureMode::SingleFrameSKP;
271 } else {
272 mCaptureMode = CaptureMode::MultiFrameSKP;
Stan Ilieve9d00122017-09-19 12:07:10 -0400273 }
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400274 return true;
275 }
276 return false;
277}
278
279// performs the first-frame work of a multi frame SKP capture. Returns true if successful.
280bool SkiaPipeline::setupMultiFrameCapture() {
281 ALOGD("Set up multi-frame capture, frames = %d", mCaptureSequence);
282 // We own this stream and need to hold it until close() finishes.
283 auto stream = std::make_unique<SkFILEWStream>(mCapturedFile.c_str());
284 if (stream->isValid()) {
285 mOpenMultiPicStream = std::move(stream);
286 mSerialContext.reset(new SkSharingSerialContext());
287 SkSerialProcs procs;
288 procs.fImageProc = SkSharingSerialContext::serializeImage;
289 procs.fImageCtx = mSerialContext.get();
Nathaniel Nifong429fff42020-01-30 14:38:21 -0500290 procs.fTypefaceProc = [](SkTypeface* tf, void* ctx){
291 return tf->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
292 };
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400293 // SkDocuments don't take owership of the streams they write.
294 // we need to keep it until after mMultiPic.close()
295 // procs is passed as a pointer, but just as a method of having an optional default.
296 // procs doesn't need to outlive this Make call.
Nathaniel Nifong7c216772021-01-22 13:23:25 -0500297 mMultiPic = SkMakeMultiPictureDocument(mOpenMultiPicStream.get(), &procs,
298 [sharingCtx = mSerialContext.get()](const SkPicture* pic) {
299 SkSharingSerialContext::collectNonTextureImagesFromPicture(pic, sharingCtx);
300 });
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400301 return true;
302 } else {
303 ALOGE("Could not open \"%s\" for writing.", mCapturedFile.c_str());
304 mCaptureSequence = 0;
305 mCaptureMode = CaptureMode::None;
306 return false;
307 }
308}
309
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500310// recurse through the rendernode's children, add any nodes which are layers to the queue.
311static void collectLayers(RenderNode* node, LayerUpdateQueue* layers) {
John Reckbe671952021-01-13 22:39:32 -0500312 SkiaDisplayList* dl = node->getDisplayList().asSkiaDl();
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500313 if (dl) {
314 const auto& prop = node->properties();
315 if (node->hasLayer()) {
316 layers->enqueueLayerWithDamage(node, Rect(prop.getWidth(), prop.getHeight()));
317 }
318 // The way to recurse through rendernodes is to call this with a lambda.
319 dl->updateChildren([&](RenderNode* child) { collectLayers(child, layers); });
320 }
321}
322
323// record the provided layers to the provided canvas as self-contained skpictures.
324static void recordLayers(const LayerUpdateQueue& layers,
325 SkCanvas* mskpCanvas) {
326 const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
327 // Record the commands to re-draw each dirty layer into an SkPicture
328 for (size_t i = 0; i < layers.entries().size(); i++) {
329 RenderNode* layerNode = layers.entries()[i].renderNode.get();
330 const Rect& layerDamage = layers.entries()[i].damage;
331 const RenderProperties& properties = layerNode->properties();
332
333 // Temporarily map current light center into RenderNode's coordinate space
334 Vector3 transformedLightCenter(savedLightCenter);
335 layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
336 LightingInfo::setLightCenterRaw(transformedLightCenter);
337
338 SkPictureRecorder layerRec;
339 auto* recCanvas = layerRec.beginRecording(properties.getWidth(),
340 properties.getHeight());
341 // This is not recorded but still causes clipping.
342 recCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
343 RenderNodeDrawable root(layerNode, recCanvas, false);
344 root.forceDraw(recCanvas);
345 // Now write this picture into the SKP canvas with an annotation indicating what it is
346 mskpCanvas->drawAnnotation(layerDamage.toSkRect(), String8::format(
347 "OffscreenLayerDraw|%" PRId64, layerNode->uniqueId()).c_str(), nullptr);
348 mskpCanvas->drawPicture(layerRec.finishRecordingAsPicture());
349 }
350 LightingInfo::setLightCenterRaw(savedLightCenter);
351}
352
353SkCanvas* SkiaPipeline::tryCapture(SkSurface* surface, RenderNode* root,
354 const LayerUpdateQueue& dirtyLayers) {
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400355 if (CC_LIKELY(!Properties::skpCaptureEnabled)) {
356 return surface->getCanvas(); // Bail out early when capture is not turned on.
357 }
358 // Note that shouldStartNewFileCapture tells us if this is the *first* frame of a capture.
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500359 bool firstFrameOfAnim = false;
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400360 if (shouldStartNewFileCapture() && mCaptureMode == CaptureMode::MultiFrameSKP) {
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500361 // set a reminder to record every layer near the end of this method, after we have set up
362 // the nway canvas.
363 firstFrameOfAnim = true;
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400364 if (!setupMultiFrameCapture()) {
365 return surface->getCanvas();
Stan Ilieve9d00122017-09-19 12:07:10 -0400366 }
367 }
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400368
369 // Create a canvas pointer, fill it depending on what kind of capture is requested (if any)
370 SkCanvas* pictureCanvas = nullptr;
371 switch (mCaptureMode) {
372 case CaptureMode::CallbackAPI:
373 case CaptureMode::SingleFrameSKP:
374 mRecorder.reset(new SkPictureRecorder());
Nathaniel Nifong31fee3a2019-07-11 16:27:14 -0400375 pictureCanvas = mRecorder->beginRecording(surface->width(), surface->height());
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400376 break;
377 case CaptureMode::MultiFrameSKP:
378 // If a multi frame recording is active, initialize recording for a single frame of a
379 // multi frame file.
380 pictureCanvas = mMultiPic->beginPage(surface->width(), surface->height());
381 break;
382 case CaptureMode::None:
383 // Returning here in the non-capture case means we can count on pictureCanvas being
384 // non-null below.
385 return surface->getCanvas();
386 }
387
388 // Setting up an nway canvas is common to any kind of capture.
389 mNwayCanvas = std::make_unique<SkNWayCanvas>(surface->width(), surface->height());
390 mNwayCanvas->addCanvas(surface->getCanvas());
391 mNwayCanvas->addCanvas(pictureCanvas);
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500392
393 if (firstFrameOfAnim) {
394 // On the first frame of any mskp capture we want to record any layers that are needed in
395 // frame but may have been rendered offscreen before recording began.
396 // We do not maintain a list of all layers, since it isn't needed outside this rare,
397 // recording use case. Traverse the tree to find them and put them in this LayerUpdateQueue.
398 LayerUpdateQueue luq;
399 collectLayers(root, &luq);
400 recordLayers(luq, mNwayCanvas.get());
401 } else {
402 // on non-first frames, we record any normal layer draws (dirty regions)
403 recordLayers(dirtyLayers, mNwayCanvas.get());
404 }
405
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400406 return mNwayCanvas.get();
Stan Ilieve9d00122017-09-19 12:07:10 -0400407}
408
409void SkiaPipeline::endCapture(SkSurface* surface) {
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400410 if (CC_LIKELY(mCaptureMode == CaptureMode::None)) { return; }
John Reck5cca8f22018-12-10 17:06:22 -0800411 mNwayCanvas.reset();
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400412 ATRACE_CALL();
413 if (mCaptureSequence > 0 && mCaptureMode == CaptureMode::MultiFrameSKP) {
414 mMultiPic->endPage();
415 mCaptureSequence--;
416 if (mCaptureSequence == 0) {
417 mCaptureMode = CaptureMode::None;
418 // Pass mMultiPic and mOpenMultiPicStream to a background thread, which will handle
419 // the heavyweight serialization work and destroy them. mOpenMultiPicStream is released
420 // to a bare pointer because keeping it in a smart pointer makes the lambda
421 // non-copyable. The lambda is only called once, so this is safe.
422 SkFILEWStream* stream = mOpenMultiPicStream.release();
423 CommonPool::post([doc = std::move(mMultiPic), stream]{
424 ALOGD("Finalizing multi frame SKP");
425 doc->close();
426 delete stream;
427 ALOGD("Multi frame SKP complete.");
428 });
429 }
430 } else {
Stan Ilieve9d00122017-09-19 12:07:10 -0400431 sk_sp<SkPicture> picture = mRecorder->finishRecordingAsPicture();
Stan Ilieve9d00122017-09-19 12:07:10 -0400432 if (picture->approximateOpCount() > 0) {
John Reck5cca8f22018-12-10 17:06:22 -0800433 if (mPictureCapturedCallback) {
434 std::invoke(mPictureCapturedCallback, std::move(picture));
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400435 } else {
436 // single frame skp to file
Nathaniel Nifong429fff42020-01-30 14:38:21 -0500437 SkSerialProcs procs;
438 procs.fTypefaceProc = [](SkTypeface* tf, void* ctx){
439 return tf->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
440 };
John Reck76005182021-06-09 22:43:05 -0400441 auto data = picture->serialize(&procs);
Nathaniel Nifongd2e49a22019-06-24 15:07:34 -0400442 savePictureAsync(data, mCapturedFile);
443 mCaptureSequence = 0;
Derek Sollenberger5f9753d2020-04-01 15:59:02 -0400444 mCaptureMode = CaptureMode::None;
Stan Ilieve9d00122017-09-19 12:07:10 -0400445 }
Stan Ilieve9d00122017-09-19 12:07:10 -0400446 }
447 mRecorder.reset();
448 }
449}
450
Stan Iliev500a0c32016-10-26 10:30:09 -0400451void SkiaPipeline::renderFrame(const LayerUpdateQueue& layers, const SkRect& clip,
John Reck1bcacfd2017-11-03 10:12:19 -0700452 const std::vector<sp<RenderNode>>& nodes, bool opaque,
Greg Danielc4076782019-01-08 16:01:18 -0500453 const Rect& contentDrawBounds, sk_sp<SkSurface> surface,
454 const SkMatrix& preTransform) {
John Reck5cca8f22018-12-10 17:06:22 -0800455 bool previousSkpEnabled = Properties::skpCaptureEnabled;
456 if (mPictureCapturedCallback) {
457 Properties::skpCaptureEnabled = true;
458 }
459
Nathaniel Nifong2945bff2019-11-25 09:34:21 -0500460 // Initialize the canvas for the current frame, that might be a recording canvas if SKP
461 // capture is enabled.
462 SkCanvas* canvas = tryCapture(surface.get(), nodes[0].get(), layers);
463
Stan Iliev500a0c32016-10-26 10:30:09 -0400464 // draw all layers up front
Peiyong Lin1f6aa122018-09-10 16:28:08 -0700465 renderLayersImpl(layers, opaque);
Stan Iliev500a0c32016-10-26 10:30:09 -0400466
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500467 renderFrameImpl(clip, nodes, opaque, contentDrawBounds, canvas, preTransform);
Matt Sarettf58cc922016-11-14 18:33:38 -0500468
Stan Ilieve9d00122017-09-19 12:07:10 -0400469 endCapture(surface.get());
Matt Sarettf58cc922016-11-14 18:33:38 -0500470
471 if (CC_UNLIKELY(Properties::debugOverdraw)) {
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500472 renderOverdraw(clip, nodes, contentDrawBounds, surface, preTransform);
Matt Sarettf58cc922016-11-14 18:33:38 -0500473 }
474
John Reck5cca8f22018-12-10 17:06:22 -0800475 Properties::skpCaptureEnabled = previousSkpEnabled;
Matt Sarettf58cc922016-11-14 18:33:38 -0500476}
477
Stan Iliev52771272016-11-17 09:54:38 -0500478namespace {
479static Rect nodeBounds(RenderNode& node) {
480 auto& props = node.properties();
John Reck1bcacfd2017-11-03 10:12:19 -0700481 return Rect(props.getLeft(), props.getTop(), props.getRight(), props.getBottom());
Stan Iliev52771272016-11-17 09:54:38 -0500482}
John Reck0fa0cbc2019-04-05 16:57:46 -0700483} // namespace
Stan Iliev52771272016-11-17 09:54:38 -0500484
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500485void SkiaPipeline::renderFrameImpl(const SkRect& clip,
John Reck1bcacfd2017-11-03 10:12:19 -0700486 const std::vector<sp<RenderNode>>& nodes, bool opaque,
Greg Danielc4076782019-01-08 16:01:18 -0500487 const Rect& contentDrawBounds, SkCanvas* canvas,
488 const SkMatrix& preTransform) {
Stan Ilievb66b8bb2016-12-15 18:17:42 -0500489 SkAutoCanvasRestore saver(canvas, true);
Nathaniel Nifongcff969f2020-01-09 14:03:49 -0500490 auto clipRestriction = preTransform.mapRect(clip).roundOut();
John Reck76005182021-06-09 22:43:05 -0400491 if (CC_UNLIKELY(isCapturingSkp())) {
Nathaniel Nifong89a5dc52020-01-17 15:32:17 -0500492 canvas->drawAnnotation(SkRect::Make(clipRestriction), "AndroidDeviceClipRestriction",
493 nullptr);
494 } else {
495 // clip drawing to dirty region only when not recording SKP files (which should contain all
496 // draw ops on every frame)
497 canvas->androidFramework_setDeviceClipRestriction(clipRestriction);
498 }
Greg Danielc4076782019-01-08 16:01:18 -0500499 canvas->concat(preTransform);
Stan Iliev500a0c32016-10-26 10:30:09 -0400500
Nader Jawadf5ce4522023-03-27 13:02:41 -0700501 if (!opaque) {
Stan Iliev500a0c32016-10-26 10:30:09 -0400502 canvas->clear(SK_ColorTRANSPARENT);
503 }
504
Stan Iliev52771272016-11-17 09:54:38 -0500505 if (1 == nodes.size()) {
506 if (!nodes[0]->nothingToDraw()) {
Stan Iliev52771272016-11-17 09:54:38 -0500507 RenderNodeDrawable root(nodes[0].get(), canvas);
508 root.draw(canvas);
509 }
510 } else if (0 == nodes.size()) {
John Reck1bcacfd2017-11-03 10:12:19 -0700511 // nothing to draw
Stan Iliev52771272016-11-17 09:54:38 -0500512 } else {
513 // It there are multiple render nodes, they are laid out as follows:
514 // #0 - backdrop (content + caption)
515 // #1 - content (local bounds are at (0,0), will be translated and clipped to backdrop)
516 // #2 - additional overlay nodes
John Reck1bcacfd2017-11-03 10:12:19 -0700517 // Usually the backdrop cannot be seen since it will be entirely covered by the content.
518 // While
519 // resizing however it might become partially visible. The following render loop will crop
520 // the
521 // backdrop against the content and draw the remaining part of it. It will then draw the
522 // content
Stan Iliev52771272016-11-17 09:54:38 -0500523 // cropped to the backdrop (since that indicates a shrinking of the window).
524 //
525 // Additional nodes will be drawn on top with no particular clipping semantics.
Stan Iliev500a0c32016-10-26 10:30:09 -0400526
Stan Iliev52771272016-11-17 09:54:38 -0500527 // Usually the contents bounds should be mContentDrawBounds - however - we will
528 // move it towards the fixed edge to give it a more stable appearance (for the moment).
529 // If there is no content bounds we ignore the layering as stated above and start with 2.
Stan Iliev500a0c32016-10-26 10:30:09 -0400530
Stan Iliev52771272016-11-17 09:54:38 -0500531 // Backdrop bounds in render target space
532 const Rect backdrop = nodeBounds(*nodes[0]);
Stan Iliev500a0c32016-10-26 10:30:09 -0400533
John Reck1bcacfd2017-11-03 10:12:19 -0700534 // Bounds that content will fill in render target space (note content node bounds may be
535 // bigger)
Stan Iliev52771272016-11-17 09:54:38 -0500536 Rect content(contentDrawBounds.getWidth(), contentDrawBounds.getHeight());
537 content.translate(backdrop.left, backdrop.top);
538 if (!content.contains(backdrop) && !nodes[0]->nothingToDraw()) {
539 // Content doesn't entirely overlap backdrop, so fill around content (right/bottom)
Stan Iliev500a0c32016-10-26 10:30:09 -0400540
Stan Iliev52771272016-11-17 09:54:38 -0500541 // 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 -0700542 // also fill left/top. Currently, both 2up and freeform position content at the top/left
543 // of
Stan Iliev52771272016-11-17 09:54:38 -0500544 // the backdrop, so this isn't necessary.
545 RenderNodeDrawable backdropNode(nodes[0].get(), canvas);
546 if (content.right < backdrop.right) {
547 // draw backdrop to right side of content
548 SkAutoCanvasRestore acr(canvas, true);
John Reck1bcacfd2017-11-03 10:12:19 -0700549 canvas->clipRect(SkRect::MakeLTRB(content.right, backdrop.top, backdrop.right,
550 backdrop.bottom));
Stan Iliev52771272016-11-17 09:54:38 -0500551 backdropNode.draw(canvas);
552 }
553 if (content.bottom < backdrop.bottom) {
554 // draw backdrop to bottom of content
555 // Note: bottom fill uses content left/right, to avoid overdrawing left/right fill
556 SkAutoCanvasRestore acr(canvas, true);
John Reck1bcacfd2017-11-03 10:12:19 -0700557 canvas->clipRect(SkRect::MakeLTRB(content.left, content.bottom, content.right,
558 backdrop.bottom));
Stan Iliev52771272016-11-17 09:54:38 -0500559 backdropNode.draw(canvas);
560 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400561 }
562
Stan Iliev52771272016-11-17 09:54:38 -0500563 RenderNodeDrawable contentNode(nodes[1].get(), canvas);
564 if (!backdrop.isEmpty()) {
565 // content node translation to catch up with backdrop
566 float dx = backdrop.left - contentDrawBounds.left;
567 float dy = backdrop.top - contentDrawBounds.top;
568
569 SkAutoCanvasRestore acr(canvas, true);
570 canvas->translate(dx, dy);
John Reck1bcacfd2017-11-03 10:12:19 -0700571 const SkRect contentLocalClip =
572 SkRect::MakeXYWH(contentDrawBounds.left, contentDrawBounds.top,
573 backdrop.getWidth(), backdrop.getHeight());
Stan Iliev52771272016-11-17 09:54:38 -0500574 canvas->clipRect(contentLocalClip);
575 contentNode.draw(canvas);
576 } else {
577 SkAutoCanvasRestore acr(canvas, true);
578 contentNode.draw(canvas);
579 }
580
581 // remaining overlay nodes, simply defer
582 for (size_t index = 2; index < nodes.size(); index++) {
583 if (!nodes[index]->nothingToDraw()) {
584 SkAutoCanvasRestore acr(canvas, true);
585 RenderNodeDrawable overlayNode(nodes[index].get(), canvas);
586 overlayNode.draw(canvas);
587 }
588 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400589 }
Stan Iliev500a0c32016-10-26 10:30:09 -0400590}
591
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500592void SkiaPipeline::dumpResourceCacheUsage() const {
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400593 int resources;
594 size_t bytes;
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500595 mRenderThread.getGrContext()->getResourceCacheUsage(&resources, &bytes);
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400596 size_t maxBytes = mRenderThread.getGrContext()->getResourceCacheLimit();
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500597
598 SkString log("Resource Cache Usage:\n");
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400599 log.appendf("%8d items\n", resources);
John Reck1bcacfd2017-11-03 10:12:19 -0700600 log.appendf("%8zu bytes (%.2f MB) out of %.2f MB maximum\n", bytes,
601 bytes * (1.0f / (1024.0f * 1024.0f)), maxBytes * (1.0f / (1024.0f * 1024.0f)));
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500602
603 ALOGD("%s", log.c_str());
604}
605
Nader Jawada3521852023-01-30 20:23:46 -0800606void SkiaPipeline::setHardwareBuffer(AHardwareBuffer* buffer) {
607 if (mHardwareBuffer) {
608 AHardwareBuffer_release(mHardwareBuffer);
609 mHardwareBuffer = nullptr;
610 }
611
612 if (buffer) {
613 AHardwareBuffer_acquire(buffer);
614 mHardwareBuffer = buffer;
615 }
616}
617
618sk_sp<SkSurface> SkiaPipeline::getBufferSkSurface(
619 const renderthread::HardwareBufferRenderParams& bufferParams) {
620 auto bufferColorSpace = bufferParams.getColorSpace();
621 if (mBufferSurface == nullptr || mBufferColorSpace == nullptr ||
622 !SkColorSpace::Equals(mBufferColorSpace.get(), bufferColorSpace.get())) {
623 mBufferSurface = SkSurface::MakeFromAHardwareBuffer(
624 mRenderThread.getGrContext(), mHardwareBuffer, kTopLeft_GrSurfaceOrigin,
625 bufferColorSpace, nullptr, true);
626 mBufferColorSpace = bufferColorSpace;
627 }
628 return mBufferSurface;
629}
630
Peiyong Lin3bff1352018-12-11 07:56:07 -0800631void SkiaPipeline::setSurfaceColorProperties(ColorMode colorMode) {
Derek Sollenberger1863d942020-02-05 15:41:51 -0500632 mColorMode = colorMode;
John Reckb36bfdd2020-07-23 13:47:49 -0700633 switch (colorMode) {
634 case ColorMode::Default:
635 mSurfaceColorType = SkColorType::kN32_SkColorType;
636 mSurfaceColorSpace = SkColorSpace::MakeSRGB();
637 break;
638 case ColorMode::WideColorGamut:
639 mSurfaceColorType = DeviceInfo::get()->getWideColorType();
640 mSurfaceColorSpace = DeviceInfo::get()->getWideColorSpace();
641 break;
642 case ColorMode::Hdr:
John Reck55887762023-01-25 16:51:18 -0500643 mSurfaceColorType = SkColorType::kN32_SkColorType;
644 mSurfaceColorSpace = SkColorSpace::MakeRGB(
645 GetExtendedTransferFunction(mTargetSdrHdrRatio), SkNamedGamut::kDisplayP3);
John Reckb36bfdd2020-07-23 13:47:49 -0700646 break;
John Reck0b3f3312023-01-31 16:21:28 -0500647 case ColorMode::Hdr10:
648 mSurfaceColorType = SkColorType::kRGBA_1010102_SkColorType;
649 mSurfaceColorSpace = SkColorSpace::MakeRGB(
650 GetExtendedTransferFunction(mTargetSdrHdrRatio), SkNamedGamut::kDisplayP3);
651 break;
Leon Scroggins IIIcbdbb662021-11-30 13:59:00 -0500652 case ColorMode::A8:
653 mSurfaceColorType = SkColorType::kAlpha_8_SkColorType;
654 mSurfaceColorSpace = nullptr;
655 break;
Peiyong Lin3bff1352018-12-11 07:56:07 -0800656 }
657}
658
John Reck55887762023-01-25 16:51:18 -0500659void SkiaPipeline::setTargetSdrHdrRatio(float ratio) {
John Reck0b3f3312023-01-31 16:21:28 -0500660 if (mColorMode == ColorMode::Hdr || mColorMode == ColorMode::Hdr10) {
John Reck55887762023-01-25 16:51:18 -0500661 mTargetSdrHdrRatio = ratio;
662 mSurfaceColorSpace = SkColorSpace::MakeRGB(GetExtendedTransferFunction(mTargetSdrHdrRatio),
663 SkNamedGamut::kDisplayP3);
664 } else {
665 mTargetSdrHdrRatio = 1.f;
666 }
667}
668
Matt Sarettf58cc922016-11-14 18:33:38 -0500669// Overdraw debugging
670
671// These colors should be kept in sync with Caches::getOverdrawColor() with a few differences.
Mike Reed331c4e12020-02-13 10:21:54 -0500672// This implementation requires transparent entries for "no overdraw" and "single draws".
673static const SkColor kOverdrawColors[2][6] = {
674 {
675 0x00000000,
676 0x00000000,
677 0x2f0000ff,
678 0x2f00ff00,
679 0x3fff0000,
680 0x7fff0000,
681 },
682 {
683 0x00000000,
684 0x00000000,
685 0x2f0000ff,
686 0x4fffff00,
687 0x5fff89d7,
688 0x7fff0000,
689 },
Matt Sarettf58cc922016-11-14 18:33:38 -0500690};
691
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500692void SkiaPipeline::renderOverdraw(const SkRect& clip,
John Reck1bcacfd2017-11-03 10:12:19 -0700693 const std::vector<sp<RenderNode>>& nodes,
Greg Danielc4076782019-01-08 16:01:18 -0500694 const Rect& contentDrawBounds, sk_sp<SkSurface> surface,
695 const SkMatrix& preTransform) {
Matt Sarettf58cc922016-11-14 18:33:38 -0500696 // Set up the overdraw canvas.
697 SkImageInfo offscreenInfo = SkImageInfo::MakeA8(surface->width(), surface->height());
698 sk_sp<SkSurface> offscreen = surface->makeSurface(offscreenInfo);
Nathaniel Nifongfe05b7c2019-09-17 12:52:52 -0400699 LOG_ALWAYS_FATAL_IF(!offscreen, "Failed to create offscreen SkSurface for overdraw viz.");
Matt Sarettf58cc922016-11-14 18:33:38 -0500700 SkOverdrawCanvas overdrawCanvas(offscreen->getCanvas());
701
702 // Fake a redraw to replay the draw commands. This will increment the alpha channel
703 // each time a pixel would have been drawn.
704 // Pass true for opaque so we skip the clear - the overdrawCanvas is already zero
705 // initialized.
Nathaniel Nifongdc19a652019-11-11 11:47:50 -0500706 renderFrameImpl(clip, nodes, true, contentDrawBounds, &overdrawCanvas, preTransform);
Matt Sarettf58cc922016-11-14 18:33:38 -0500707 sk_sp<SkImage> counts = offscreen->makeImageSnapshot();
708
709 // Draw overdraw colors to the canvas. The color filter will convert counts to colors.
710 SkPaint paint;
Mike Reed331c4e12020-02-13 10:21:54 -0500711 const SkColor* colors = kOverdrawColors[static_cast<int>(Properties::overdrawColorSet)];
712 paint.setColorFilter(SkOverdrawColorFilter::MakeWithSkColors(colors));
Mike Reed7994a312021-01-28 18:06:26 -0500713 surface->getCanvas()->drawImage(counts.get(), 0.0f, 0.0f, SkSamplingOptions(), &paint);
Matt Sarettf58cc922016-11-14 18:33:38 -0500714}
715
Stan Iliev500a0c32016-10-26 10:30:09 -0400716} /* namespace skiapipeline */
717} /* namespace uirenderer */
718} /* namespace android */