• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 "pipeline/skia/SkiaPipeline.h"
18 
19 #include <SkCanvas.h>
20 #include <SkColor.h>
21 #include <SkColorSpace.h>
22 #include <SkData.h>
23 #include <SkImage.h>
24 #include <SkImageAndroid.h>
25 #include <SkImageInfo.h>
26 #include <SkMatrix.h>
27 #include <SkOverdrawCanvas.h>
28 #include <SkOverdrawColorFilter.h>
29 #include <SkPicture.h>
30 #include <SkPictureRecorder.h>
31 #include <SkRect.h>
32 #include <SkRefCnt.h>
33 #include <SkSerialProcs.h>
34 #include <SkStream.h>
35 #include <SkString.h>
36 #include <SkTypeface.h>
37 #include <android-base/properties.h>
38 #include <gui/TraceUtils.h>
39 #include <include/android/SkSurfaceAndroid.h>
40 #include <include/docs/SkMultiPictureDocument.h>
41 #include <include/encode/SkPngEncoder.h>
42 #include <include/gpu/ganesh/SkSurfaceGanesh.h>
43 #include <unistd.h>
44 
45 #include <sstream>
46 
47 #include "LightingInfo.h"
48 #include "VectorDrawable.h"
49 #include "include/gpu/GpuTypes.h"  // from Skia
50 #include "thread/CommonPool.h"
51 #include "tools/SkSharingProc.h"
52 #include "utils/Color.h"
53 #include "utils/String8.h"
54 
55 using namespace android::uirenderer::renderthread;
56 
57 namespace android {
58 namespace uirenderer {
59 namespace skiapipeline {
60 
SkiaPipeline(RenderThread & thread)61 SkiaPipeline::SkiaPipeline(RenderThread& thread) : mRenderThread(thread) {
62     setSurfaceColorProperties(mColorMode);
63 }
64 
~SkiaPipeline()65 SkiaPipeline::~SkiaPipeline() {}
66 
onDestroyHardwareResources()67 void SkiaPipeline::onDestroyHardwareResources() {
68     unpinImages();
69     mRenderThread.cacheManager().trimStaleResources();
70 }
71 
renderLayers(const LightGeometry & lightGeometry,LayerUpdateQueue * layerUpdateQueue,bool opaque,const LightInfo & lightInfo)72 void SkiaPipeline::renderLayers(const LightGeometry& lightGeometry,
73                                 LayerUpdateQueue* layerUpdateQueue, bool opaque,
74                                 const LightInfo& lightInfo) {
75     LightingInfo::updateLighting(lightGeometry, lightInfo);
76     ATRACE_NAME("draw layers");
77     renderLayersImpl(*layerUpdateQueue, opaque);
78     layerUpdateQueue->clear();
79 }
80 
renderLayerImpl(RenderNode * layerNode,const Rect & layerDamage)81 bool SkiaPipeline::renderLayerImpl(RenderNode* layerNode, const Rect& layerDamage) {
82     SkASSERT(layerNode->getLayerSurface());
83     SkiaDisplayList* displayList = layerNode->getDisplayList().asSkiaDl();
84     if (!displayList || displayList->isEmpty()) {
85         ALOGE("%p drawLayers(%s) : missing drawable", layerNode, layerNode->getName());
86         return false;
87     }
88 
89     SkCanvas* layerCanvas = layerNode->getLayerSurface()->getCanvas();
90 
91     int saveCount = layerCanvas->save();
92     SkASSERT(saveCount == 1);
93 
94     layerCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
95 
96     // TODO: put localized light center calculation and storage to a drawable related code.
97     // It does not seem right to store something localized in a global state
98     // fix here and in recordLayers
99     const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
100     Vector3 transformedLightCenter(savedLightCenter);
101     // map current light center into RenderNode's coordinate space
102     layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
103     LightingInfo::setLightCenterRaw(transformedLightCenter);
104 
105     const RenderProperties& properties = layerNode->properties();
106     const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight());
107     if (properties.getClipToBounds() && layerCanvas->quickReject(bounds)) {
108         return false;
109     }
110 
111     ATRACE_FORMAT("drawLayer [%s] %.1f x %.1f", layerNode->getName(), bounds.width(),
112                   bounds.height());
113 
114     layerNode->getSkiaLayer()->hasRenderedSinceRepaint = false;
115     layerCanvas->clear(SK_ColorTRANSPARENT);
116 
117     RenderNodeDrawable root(layerNode, layerCanvas, false);
118     root.forceDraw(layerCanvas);
119     layerCanvas->restoreToCount(saveCount);
120 
121     LightingInfo::setLightCenterRaw(savedLightCenter);
122     return true;
123 }
124 
savePictureAsync(const sk_sp<SkData> & data,const std::string & filename)125 static void savePictureAsync(const sk_sp<SkData>& data, const std::string& filename) {
126     CommonPool::post([data, filename] {
127         if (0 == access(filename.c_str(), F_OK)) {
128             return;
129         }
130 
131         SkFILEWStream stream(filename.c_str());
132         if (stream.isValid()) {
133             stream.write(data->data(), data->size());
134             stream.flush();
135             ALOGD("SKP Captured Drawing Output (%zu bytes) for frame. %s", stream.bytesWritten(),
136                      filename.c_str());
137         }
138     });
139 }
140 
141 // Note multiple SkiaPipeline instances may be loaded if more than one app is visible.
142 // Each instance may observe the filename changing and try to record to a file of the same name.
143 // Only the first one will succeed. There is no scope available here where we could coordinate
144 // to cause this function to return true for only one of the instances.
shouldStartNewFileCapture()145 bool SkiaPipeline::shouldStartNewFileCapture() {
146     // Don't start a new file based capture if one is currently ongoing.
147     if (mCaptureMode != CaptureMode::None) { return false; }
148 
149     // A new capture is started when the filename property changes.
150     // Read the filename property.
151     std::string prop = base::GetProperty(PROPERTY_CAPTURE_SKP_FILENAME, "0");
152     // if the filename property changed to a valid value
153     if (prop[0] != '0' && mCapturedFile != prop) {
154         // remember this new filename
155         mCapturedFile = prop;
156         // and get a property indicating how many frames to capture.
157         mCaptureSequence = base::GetIntProperty(PROPERTY_CAPTURE_SKP_FRAMES, 1);
158         if (mCaptureSequence <= 0) {
159             return false;
160         } else if (mCaptureSequence == 1) {
161             mCaptureMode = CaptureMode::SingleFrameSKP;
162         } else {
163             mCaptureMode = CaptureMode::MultiFrameSKP;
164         }
165         return true;
166     }
167     return false;
168 }
169 
170 // performs the first-frame work of a multi frame SKP capture. Returns true if successful.
setupMultiFrameCapture()171 bool SkiaPipeline::setupMultiFrameCapture() {
172     ALOGD("Set up multi-frame capture, frames = %d", mCaptureSequence);
173     // We own this stream and need to hold it until close() finishes.
174     auto stream = std::make_unique<SkFILEWStream>(mCapturedFile.c_str());
175     if (stream->isValid()) {
176         mOpenMultiPicStream = std::move(stream);
177         mSerialContext.reset(new SkSharingSerialContext());
178         // passing the GrDirectContext to the SerialContext allows us to raster/serialize GPU images
179         mSerialContext->setDirectContext(mRenderThread.getGrContext());
180         SkSerialProcs procs;
181         procs.fImageProc = SkSharingSerialContext::serializeImage;
182         procs.fImageCtx = mSerialContext.get();
183         procs.fTypefaceProc = [](SkTypeface* tf, void* ctx){
184             return tf->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
185         };
186         // SkDocuments don't take owership of the streams they write.
187         // we need to keep it until after mMultiPic.close()
188         // procs is passed as a pointer, but just as a method of having an optional default.
189         // procs doesn't need to outlive this Make call.
190         mMultiPic = SkMultiPictureDocument::Make(mOpenMultiPicStream.get(), &procs,
191             [sharingCtx = mSerialContext.get()](const SkPicture* pic) {
192                     SkSharingSerialContext::collectNonTextureImagesFromPicture(pic, sharingCtx);
193             });
194         return true;
195     } else {
196         ALOGE("Could not open \"%s\" for writing.", mCapturedFile.c_str());
197         mCaptureSequence = 0;
198         mCaptureMode = CaptureMode::None;
199         return false;
200     }
201 }
202 
203 // recurse through the rendernode's children, add any nodes which are layers to the queue.
collectLayers(RenderNode * node,LayerUpdateQueue * layers)204 static void collectLayers(RenderNode* node, LayerUpdateQueue* layers) {
205     SkiaDisplayList* dl = node->getDisplayList().asSkiaDl();
206     if (dl) {
207         const auto& prop = node->properties();
208         if (node->hasLayer()) {
209             layers->enqueueLayerWithDamage(node, Rect(prop.getWidth(), prop.getHeight()));
210         }
211         // The way to recurse through rendernodes is to call this with a lambda.
212         dl->updateChildren([&](RenderNode* child) { collectLayers(child, layers); });
213     }
214 }
215 
216 // record the provided layers to the provided canvas as self-contained skpictures.
recordLayers(const LayerUpdateQueue & layers,SkCanvas * mskpCanvas)217 static void recordLayers(const LayerUpdateQueue& layers,
218     SkCanvas* mskpCanvas) {
219     const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
220     // Record the commands to re-draw each dirty layer into an SkPicture
221     for (size_t i = 0; i < layers.entries().size(); i++) {
222         RenderNode* layerNode = layers.entries()[i].renderNode.get();
223         const Rect& layerDamage = layers.entries()[i].damage;
224         const RenderProperties& properties = layerNode->properties();
225 
226         // Temporarily map current light center into RenderNode's coordinate space
227         Vector3 transformedLightCenter(savedLightCenter);
228         layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
229         LightingInfo::setLightCenterRaw(transformedLightCenter);
230 
231         SkPictureRecorder layerRec;
232         auto* recCanvas = layerRec.beginRecording(properties.getWidth(),
233             properties.getHeight());
234         // This is not recorded but still causes clipping.
235         recCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
236         RenderNodeDrawable root(layerNode, recCanvas, false);
237         root.forceDraw(recCanvas);
238         // Now write this picture into the SKP canvas with an annotation indicating what it is
239         mskpCanvas->drawAnnotation(layerDamage.toSkRect(), String8::format(
240             "OffscreenLayerDraw|%" PRId64, layerNode->uniqueId()).c_str(), nullptr);
241         mskpCanvas->drawPicture(layerRec.finishRecordingAsPicture());
242     }
243     LightingInfo::setLightCenterRaw(savedLightCenter);
244 }
245 
tryCapture(SkSurface * surface,RenderNode * root,const LayerUpdateQueue & dirtyLayers)246 SkCanvas* SkiaPipeline::tryCapture(SkSurface* surface, RenderNode* root,
247     const LayerUpdateQueue& dirtyLayers) {
248     if (CC_LIKELY(!Properties::skpCaptureEnabled)) {
249         return surface->getCanvas(); // Bail out early when capture is not turned on.
250     }
251     // Note that shouldStartNewFileCapture tells us if this is the *first* frame of a capture.
252     bool firstFrameOfAnim = false;
253     if (shouldStartNewFileCapture() && mCaptureMode == CaptureMode::MultiFrameSKP) {
254         // set a reminder to record every layer near the end of this method, after we have set up
255         // the nway canvas.
256         firstFrameOfAnim = true;
257         if (!setupMultiFrameCapture()) {
258             return surface->getCanvas();
259         }
260     }
261 
262     // Create a canvas pointer, fill it depending on what kind of capture is requested (if any)
263     SkCanvas* pictureCanvas = nullptr;
264     switch (mCaptureMode) {
265         case CaptureMode::CallbackAPI:
266         case CaptureMode::SingleFrameSKP:
267             mRecorder.reset(new SkPictureRecorder());
268             pictureCanvas = mRecorder->beginRecording(surface->width(), surface->height());
269             break;
270         case CaptureMode::MultiFrameSKP:
271             // If a multi frame recording is active, initialize recording for a single frame of a
272             // multi frame file.
273             pictureCanvas = mMultiPic->beginPage(surface->width(), surface->height());
274             break;
275         case CaptureMode::None:
276             // Returning here in the non-capture case means we can count on pictureCanvas being
277             // non-null below.
278             return surface->getCanvas();
279     }
280 
281     // Setting up an nway canvas is common to any kind of capture.
282     mNwayCanvas = std::make_unique<SkNWayCanvas>(surface->width(), surface->height());
283     mNwayCanvas->addCanvas(surface->getCanvas());
284     mNwayCanvas->addCanvas(pictureCanvas);
285 
286     if (firstFrameOfAnim) {
287         // On the first frame of any mskp capture we want to record any layers that are needed in
288         // frame but may have been rendered offscreen before recording began.
289         // We do not maintain a list of all layers, since it isn't needed outside this rare,
290         // recording use case. Traverse the tree to find them and put them in this LayerUpdateQueue.
291         LayerUpdateQueue luq;
292         collectLayers(root, &luq);
293         recordLayers(luq, mNwayCanvas.get());
294     } else {
295         // on non-first frames, we record any normal layer draws (dirty regions)
296         recordLayers(dirtyLayers, mNwayCanvas.get());
297     }
298 
299     return mNwayCanvas.get();
300 }
301 
endCapture(SkSurface * surface)302 void SkiaPipeline::endCapture(SkSurface* surface) {
303     if (CC_LIKELY(mCaptureMode == CaptureMode::None)) { return; }
304     mNwayCanvas.reset();
305     ATRACE_CALL();
306     if (mCaptureSequence > 0 && mCaptureMode == CaptureMode::MultiFrameSKP) {
307         mMultiPic->endPage();
308         mCaptureSequence--;
309         if (mCaptureSequence == 0) {
310             mCaptureMode = CaptureMode::None;
311             // Pass mMultiPic and mOpenMultiPicStream to a background thread, which will handle
312             // the heavyweight serialization work and destroy them. mOpenMultiPicStream is released
313             // to a bare pointer because keeping it in a smart pointer makes the lambda
314             // non-copyable. The lambda is only called once, so this is safe.
315             SkFILEWStream* stream = mOpenMultiPicStream.release();
316             CommonPool::post([doc = std::move(mMultiPic), stream]{
317                 ALOGD("Finalizing multi frame SKP");
318                 doc->close();
319                 delete stream;
320                 ALOGD("Multi frame SKP complete.");
321             });
322         }
323     } else {
324         sk_sp<SkPicture> picture = mRecorder->finishRecordingAsPicture();
325         if (picture->approximateOpCount() > 0) {
326             if (mPictureCapturedCallback) {
327                 std::invoke(mPictureCapturedCallback, std::move(picture));
328             } else {
329                 // single frame skp to file
330                 SkSerialProcs procs;
331                 procs.fTypefaceProc = [](SkTypeface* tf, void* ctx){
332                     return tf->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
333                 };
334                 procs.fImageProc = [](SkImage* img, void* ctx) -> sk_sp<SkData> {
335                     GrDirectContext* dCtx = static_cast<GrDirectContext*>(ctx);
336                     return SkPngEncoder::Encode(dCtx,
337                                                 img,
338                                                 SkPngEncoder::Options{});
339                 };
340                 procs.fImageCtx = mRenderThread.getGrContext();
341                 auto data = picture->serialize(&procs);
342                 savePictureAsync(data, mCapturedFile);
343                 mCaptureSequence = 0;
344                 mCaptureMode = CaptureMode::None;
345             }
346         }
347         mRecorder.reset();
348     }
349 }
350 
renderFrame(const LayerUpdateQueue & layers,const SkRect & clip,const std::vector<sp<RenderNode>> & nodes,bool opaque,const Rect & contentDrawBounds,sk_sp<SkSurface> surface,const SkMatrix & preTransform)351 void SkiaPipeline::renderFrame(const LayerUpdateQueue& layers, const SkRect& clip,
352                                const std::vector<sp<RenderNode>>& nodes, bool opaque,
353                                const Rect& contentDrawBounds, sk_sp<SkSurface> surface,
354                                const SkMatrix& preTransform) {
355     bool previousSkpEnabled = Properties::skpCaptureEnabled;
356     if (mPictureCapturedCallback) {
357         Properties::skpCaptureEnabled = true;
358     }
359 
360     // Initialize the canvas for the current frame, that might be a recording canvas if SKP
361     // capture is enabled.
362     SkCanvas* canvas = tryCapture(surface.get(), nodes[0].get(), layers);
363 
364     // draw all layers up front
365     renderLayersImpl(layers, opaque);
366 
367     renderFrameImpl(clip, nodes, opaque, contentDrawBounds, canvas, preTransform);
368 
369     endCapture(surface.get());
370 
371     if (CC_UNLIKELY(Properties::debugOverdraw)) {
372         renderOverdraw(clip, nodes, contentDrawBounds, surface, preTransform);
373     }
374 
375     Properties::skpCaptureEnabled = previousSkpEnabled;
376 }
377 
378 namespace {
nodeBounds(RenderNode & node)379 static Rect nodeBounds(RenderNode& node) {
380     auto& props = node.properties();
381     return Rect(props.getLeft(), props.getTop(), props.getRight(), props.getBottom());
382 }
383 }  // namespace
384 
renderFrameImpl(const SkRect & clip,const std::vector<sp<RenderNode>> & nodes,bool opaque,const Rect & contentDrawBounds,SkCanvas * canvas,const SkMatrix & preTransform)385 void SkiaPipeline::renderFrameImpl(const SkRect& clip,
386                                    const std::vector<sp<RenderNode>>& nodes, bool opaque,
387                                    const Rect& contentDrawBounds, SkCanvas* canvas,
388                                    const SkMatrix& preTransform) {
389     SkAutoCanvasRestore saver(canvas, true);
390     auto clipRestriction = preTransform.mapRect(clip).roundOut();
391     if (CC_UNLIKELY(isCapturingSkp())) {
392         canvas->drawAnnotation(SkRect::Make(clipRestriction), "AndroidDeviceClipRestriction",
393             nullptr);
394     } else {
395         // clip drawing to dirty region only when not recording SKP files (which should contain all
396         // draw ops on every frame)
397         canvas->androidFramework_setDeviceClipRestriction(clipRestriction);
398     }
399     canvas->concat(preTransform);
400 
401     if (!opaque) {
402         canvas->clear(SK_ColorTRANSPARENT);
403     }
404 
405     if (1 == nodes.size()) {
406         if (!nodes[0]->nothingToDraw()) {
407             RenderNodeDrawable root(nodes[0].get(), canvas);
408             root.draw(canvas);
409         }
410     } else if (0 == nodes.size()) {
411         // nothing to draw
412     } else {
413         // It there are multiple render nodes, they are laid out as follows:
414         // #0 - backdrop (content + caption)
415         // #1 - content (local bounds are at (0,0), will be translated and clipped to backdrop)
416         // #2 - additional overlay nodes
417         // Usually the backdrop cannot be seen since it will be entirely covered by the content.
418         // While
419         // resizing however it might become partially visible. The following render loop will crop
420         // the
421         // backdrop against the content and draw the remaining part of it. It will then draw the
422         // content
423         // cropped to the backdrop (since that indicates a shrinking of the window).
424         //
425         // Additional nodes will be drawn on top with no particular clipping semantics.
426 
427         // Usually the contents bounds should be mContentDrawBounds - however - we will
428         // move it towards the fixed edge to give it a more stable appearance (for the moment).
429         // If there is no content bounds we ignore the layering as stated above and start with 2.
430 
431         // Backdrop bounds in render target space
432         const Rect backdrop = nodeBounds(*nodes[0]);
433 
434         // Bounds that content will fill in render target space (note content node bounds may be
435         // bigger)
436         Rect content(contentDrawBounds.getWidth(), contentDrawBounds.getHeight());
437         content.translate(backdrop.left, backdrop.top);
438         if (!content.contains(backdrop) && !nodes[0]->nothingToDraw()) {
439             // Content doesn't entirely overlap backdrop, so fill around content (right/bottom)
440 
441             // Note: in the future, if content doesn't snap to backdrop's left/top, this may need to
442             // also fill left/top. Currently, both 2up and freeform position content at the top/left
443             // of
444             // the backdrop, so this isn't necessary.
445             RenderNodeDrawable backdropNode(nodes[0].get(), canvas);
446             if (content.right < backdrop.right) {
447                 // draw backdrop to right side of content
448                 SkAutoCanvasRestore acr(canvas, true);
449                 canvas->clipRect(SkRect::MakeLTRB(content.right, backdrop.top, backdrop.right,
450                                                   backdrop.bottom));
451                 backdropNode.draw(canvas);
452             }
453             if (content.bottom < backdrop.bottom) {
454                 // draw backdrop to bottom of content
455                 // Note: bottom fill uses content left/right, to avoid overdrawing left/right fill
456                 SkAutoCanvasRestore acr(canvas, true);
457                 canvas->clipRect(SkRect::MakeLTRB(content.left, content.bottom, content.right,
458                                                   backdrop.bottom));
459                 backdropNode.draw(canvas);
460             }
461         }
462 
463         RenderNodeDrawable contentNode(nodes[1].get(), canvas);
464         if (!backdrop.isEmpty()) {
465             // content node translation to catch up with backdrop
466             float dx = backdrop.left - contentDrawBounds.left;
467             float dy = backdrop.top - contentDrawBounds.top;
468 
469             SkAutoCanvasRestore acr(canvas, true);
470             canvas->translate(dx, dy);
471             const SkRect contentLocalClip =
472                     SkRect::MakeXYWH(contentDrawBounds.left, contentDrawBounds.top,
473                                      backdrop.getWidth(), backdrop.getHeight());
474             canvas->clipRect(contentLocalClip);
475             contentNode.draw(canvas);
476         } else {
477             SkAutoCanvasRestore acr(canvas, true);
478             contentNode.draw(canvas);
479         }
480 
481         // remaining overlay nodes, simply defer
482         for (size_t index = 2; index < nodes.size(); index++) {
483             if (!nodes[index]->nothingToDraw()) {
484                 SkAutoCanvasRestore acr(canvas, true);
485                 RenderNodeDrawable overlayNode(nodes[index].get(), canvas);
486                 overlayNode.draw(canvas);
487             }
488         }
489     }
490 }
491 
setSurfaceColorProperties(ColorMode colorMode)492 void SkiaPipeline::setSurfaceColorProperties(ColorMode colorMode) {
493     mColorMode = colorMode;
494     switch (colorMode) {
495         case ColorMode::Default:
496             mSurfaceColorType = SkColorType::kN32_SkColorType;
497             mSurfaceColorSpace = SkColorSpace::MakeSRGB();
498             break;
499         case ColorMode::WideColorGamut:
500             mSurfaceColorType = DeviceInfo::get()->getWideColorType();
501             mSurfaceColorSpace = DeviceInfo::get()->getWideColorSpace();
502             break;
503         case ColorMode::Hdr:
504             if (DeviceInfo::get()->isSupportRgba10101010ForHdr()) {
505                 mSurfaceColorType = SkColorType::kRGBA_10x6_SkColorType;
506                 mSurfaceColorSpace = SkColorSpace::MakeRGB(
507                         GetExtendedTransferFunction(mTargetSdrHdrRatio), SkNamedGamut::kDisplayP3);
508             } else if (DeviceInfo::get()->isSupportFp16ForHdr()) {
509                 mSurfaceColorType = SkColorType::kRGBA_F16_SkColorType;
510                 mSurfaceColorSpace = SkColorSpace::MakeSRGB();
511             } else {
512                 mSurfaceColorType = SkColorType::kN32_SkColorType;
513                 mSurfaceColorSpace = SkColorSpace::MakeRGB(
514                         GetExtendedTransferFunction(mTargetSdrHdrRatio), SkNamedGamut::kDisplayP3);
515             }
516             break;
517         case ColorMode::Hdr10:
518             mSurfaceColorType = SkColorType::kRGBA_1010102_SkColorType;
519             mSurfaceColorSpace = SkColorSpace::MakeRGB(
520                     GetExtendedTransferFunction(mTargetSdrHdrRatio), SkNamedGamut::kDisplayP3);
521             break;
522         case ColorMode::A8:
523             mSurfaceColorType = SkColorType::kAlpha_8_SkColorType;
524             mSurfaceColorSpace = nullptr;
525             break;
526     }
527 }
528 
setTargetSdrHdrRatio(float ratio)529 void SkiaPipeline::setTargetSdrHdrRatio(float ratio) {
530     if (mColorMode == ColorMode::Hdr || mColorMode == ColorMode::Hdr10) {
531         mTargetSdrHdrRatio = ratio;
532 
533         if (mColorMode == ColorMode::Hdr && DeviceInfo::get()->isSupportFp16ForHdr() &&
534             !DeviceInfo::get()->isSupportRgba10101010ForHdr()) {
535             mSurfaceColorSpace = SkColorSpace::MakeSRGB();
536         } else {
537             mSurfaceColorSpace = SkColorSpace::MakeRGB(
538                     GetExtendedTransferFunction(mTargetSdrHdrRatio), SkNamedGamut::kDisplayP3);
539         }
540     } else {
541         mTargetSdrHdrRatio = 1.f;
542     }
543 }
544 
545 // Overdraw debugging
546 
547 // These colors should be kept in sync with Caches::getOverdrawColor() with a few differences.
548 // This implementation requires transparent entries for "no overdraw" and "single draws".
549 static const SkColor kOverdrawColors[2][6] = {
550     {
551         0x00000000,
552         0x00000000,
553         0x2f0000ff,
554         0x2f00ff00,
555         0x3fff0000,
556         0x7fff0000,
557     },
558     {
559         0x00000000,
560         0x00000000,
561         0x2f0000ff,
562         0x4fffff00,
563         0x5fff89d7,
564         0x7fff0000,
565     },
566 };
567 
renderOverdraw(const SkRect & clip,const std::vector<sp<RenderNode>> & nodes,const Rect & contentDrawBounds,sk_sp<SkSurface> surface,const SkMatrix & preTransform)568 void SkiaPipeline::renderOverdraw(const SkRect& clip,
569                                   const std::vector<sp<RenderNode>>& nodes,
570                                   const Rect& contentDrawBounds, sk_sp<SkSurface> surface,
571                                   const SkMatrix& preTransform) {
572     // Set up the overdraw canvas.
573     SkImageInfo offscreenInfo = SkImageInfo::MakeA8(surface->width(), surface->height());
574     sk_sp<SkSurface> offscreen = surface->makeSurface(offscreenInfo);
575     LOG_ALWAYS_FATAL_IF(!offscreen, "Failed to create offscreen SkSurface for overdraw viz.");
576     SkOverdrawCanvas overdrawCanvas(offscreen->getCanvas());
577 
578     // Fake a redraw to replay the draw commands.  This will increment the alpha channel
579     // each time a pixel would have been drawn.
580     // Pass true for opaque so we skip the clear - the overdrawCanvas is already zero
581     // initialized.
582     renderFrameImpl(clip, nodes, true, contentDrawBounds, &overdrawCanvas, preTransform);
583     sk_sp<SkImage> counts = offscreen->makeImageSnapshot();
584 
585     // Draw overdraw colors to the canvas.  The color filter will convert counts to colors.
586     SkPaint paint;
587     const SkColor* colors = kOverdrawColors[static_cast<int>(Properties::overdrawColorSet)];
588     paint.setColorFilter(SkOverdrawColorFilter::MakeWithSkColors(colors));
589     surface->getCanvas()->drawImage(counts.get(), 0.0f, 0.0f, SkSamplingOptions(), &paint);
590 }
591 
592 } /* namespace skiapipeline */
593 } /* namespace uirenderer */
594 } /* namespace android */
595