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 SkSerialProcs procs;
179 procs.fImageProc = SkSharingSerialContext::serializeImage;
180 procs.fImageCtx = mSerialContext.get();
181 procs.fTypefaceProc = [](SkTypeface* tf, void* ctx){
182 return tf->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
183 };
184 // SkDocuments don't take owership of the streams they write.
185 // we need to keep it until after mMultiPic.close()
186 // procs is passed as a pointer, but just as a method of having an optional default.
187 // procs doesn't need to outlive this Make call.
188 mMultiPic = SkMultiPictureDocument::Make(mOpenMultiPicStream.get(), &procs,
189 [sharingCtx = mSerialContext.get()](const SkPicture* pic) {
190 SkSharingSerialContext::collectNonTextureImagesFromPicture(pic, sharingCtx);
191 });
192 return true;
193 } else {
194 ALOGE("Could not open \"%s\" for writing.", mCapturedFile.c_str());
195 mCaptureSequence = 0;
196 mCaptureMode = CaptureMode::None;
197 return false;
198 }
199 }
200
201 // recurse through the rendernode's children, add any nodes which are layers to the queue.
collectLayers(RenderNode * node,LayerUpdateQueue * layers)202 static void collectLayers(RenderNode* node, LayerUpdateQueue* layers) {
203 SkiaDisplayList* dl = node->getDisplayList().asSkiaDl();
204 if (dl) {
205 const auto& prop = node->properties();
206 if (node->hasLayer()) {
207 layers->enqueueLayerWithDamage(node, Rect(prop.getWidth(), prop.getHeight()));
208 }
209 // The way to recurse through rendernodes is to call this with a lambda.
210 dl->updateChildren([&](RenderNode* child) { collectLayers(child, layers); });
211 }
212 }
213
214 // record the provided layers to the provided canvas as self-contained skpictures.
recordLayers(const LayerUpdateQueue & layers,SkCanvas * mskpCanvas)215 static void recordLayers(const LayerUpdateQueue& layers,
216 SkCanvas* mskpCanvas) {
217 const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
218 // Record the commands to re-draw each dirty layer into an SkPicture
219 for (size_t i = 0; i < layers.entries().size(); i++) {
220 RenderNode* layerNode = layers.entries()[i].renderNode.get();
221 const Rect& layerDamage = layers.entries()[i].damage;
222 const RenderProperties& properties = layerNode->properties();
223
224 // Temporarily map current light center into RenderNode's coordinate space
225 Vector3 transformedLightCenter(savedLightCenter);
226 layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
227 LightingInfo::setLightCenterRaw(transformedLightCenter);
228
229 SkPictureRecorder layerRec;
230 auto* recCanvas = layerRec.beginRecording(properties.getWidth(),
231 properties.getHeight());
232 // This is not recorded but still causes clipping.
233 recCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
234 RenderNodeDrawable root(layerNode, recCanvas, false);
235 root.forceDraw(recCanvas);
236 // Now write this picture into the SKP canvas with an annotation indicating what it is
237 mskpCanvas->drawAnnotation(layerDamage.toSkRect(), String8::format(
238 "OffscreenLayerDraw|%" PRId64, layerNode->uniqueId()).c_str(), nullptr);
239 mskpCanvas->drawPicture(layerRec.finishRecordingAsPicture());
240 }
241 LightingInfo::setLightCenterRaw(savedLightCenter);
242 }
243
tryCapture(SkSurface * surface,RenderNode * root,const LayerUpdateQueue & dirtyLayers)244 SkCanvas* SkiaPipeline::tryCapture(SkSurface* surface, RenderNode* root,
245 const LayerUpdateQueue& dirtyLayers) {
246 if (CC_LIKELY(!Properties::skpCaptureEnabled)) {
247 return surface->getCanvas(); // Bail out early when capture is not turned on.
248 }
249 // Note that shouldStartNewFileCapture tells us if this is the *first* frame of a capture.
250 bool firstFrameOfAnim = false;
251 if (shouldStartNewFileCapture() && mCaptureMode == CaptureMode::MultiFrameSKP) {
252 // set a reminder to record every layer near the end of this method, after we have set up
253 // the nway canvas.
254 firstFrameOfAnim = true;
255 if (!setupMultiFrameCapture()) {
256 return surface->getCanvas();
257 }
258 }
259
260 // Create a canvas pointer, fill it depending on what kind of capture is requested (if any)
261 SkCanvas* pictureCanvas = nullptr;
262 switch (mCaptureMode) {
263 case CaptureMode::CallbackAPI:
264 case CaptureMode::SingleFrameSKP:
265 mRecorder.reset(new SkPictureRecorder());
266 pictureCanvas = mRecorder->beginRecording(surface->width(), surface->height());
267 break;
268 case CaptureMode::MultiFrameSKP:
269 // If a multi frame recording is active, initialize recording for a single frame of a
270 // multi frame file.
271 pictureCanvas = mMultiPic->beginPage(surface->width(), surface->height());
272 break;
273 case CaptureMode::None:
274 // Returning here in the non-capture case means we can count on pictureCanvas being
275 // non-null below.
276 return surface->getCanvas();
277 }
278
279 // Setting up an nway canvas is common to any kind of capture.
280 mNwayCanvas = std::make_unique<SkNWayCanvas>(surface->width(), surface->height());
281 mNwayCanvas->addCanvas(surface->getCanvas());
282 mNwayCanvas->addCanvas(pictureCanvas);
283
284 if (firstFrameOfAnim) {
285 // On the first frame of any mskp capture we want to record any layers that are needed in
286 // frame but may have been rendered offscreen before recording began.
287 // We do not maintain a list of all layers, since it isn't needed outside this rare,
288 // recording use case. Traverse the tree to find them and put them in this LayerUpdateQueue.
289 LayerUpdateQueue luq;
290 collectLayers(root, &luq);
291 recordLayers(luq, mNwayCanvas.get());
292 } else {
293 // on non-first frames, we record any normal layer draws (dirty regions)
294 recordLayers(dirtyLayers, mNwayCanvas.get());
295 }
296
297 return mNwayCanvas.get();
298 }
299
endCapture(SkSurface * surface)300 void SkiaPipeline::endCapture(SkSurface* surface) {
301 if (CC_LIKELY(mCaptureMode == CaptureMode::None)) { return; }
302 mNwayCanvas.reset();
303 ATRACE_CALL();
304 if (mCaptureSequence > 0 && mCaptureMode == CaptureMode::MultiFrameSKP) {
305 mMultiPic->endPage();
306 mCaptureSequence--;
307 if (mCaptureSequence == 0) {
308 mCaptureMode = CaptureMode::None;
309 // Pass mMultiPic and mOpenMultiPicStream to a background thread, which will handle
310 // the heavyweight serialization work and destroy them. mOpenMultiPicStream is released
311 // to a bare pointer because keeping it in a smart pointer makes the lambda
312 // non-copyable. The lambda is only called once, so this is safe.
313 SkFILEWStream* stream = mOpenMultiPicStream.release();
314 CommonPool::post([doc = std::move(mMultiPic), stream]{
315 ALOGD("Finalizing multi frame SKP");
316 doc->close();
317 delete stream;
318 ALOGD("Multi frame SKP complete.");
319 });
320 }
321 } else {
322 sk_sp<SkPicture> picture = mRecorder->finishRecordingAsPicture();
323 if (picture->approximateOpCount() > 0) {
324 if (mPictureCapturedCallback) {
325 std::invoke(mPictureCapturedCallback, std::move(picture));
326 } else {
327 // single frame skp to file
328 SkSerialProcs procs;
329 procs.fTypefaceProc = [](SkTypeface* tf, void* ctx){
330 return tf->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
331 };
332 procs.fImageProc = [](SkImage* img, void* ctx) -> sk_sp<SkData> {
333 GrDirectContext* dCtx = static_cast<GrDirectContext*>(ctx);
334 return SkPngEncoder::Encode(dCtx,
335 img,
336 SkPngEncoder::Options{});
337 };
338 procs.fImageCtx = mRenderThread.getGrContext();
339 auto data = picture->serialize(&procs);
340 savePictureAsync(data, mCapturedFile);
341 mCaptureSequence = 0;
342 mCaptureMode = CaptureMode::None;
343 }
344 }
345 mRecorder.reset();
346 }
347 }
348
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)349 void SkiaPipeline::renderFrame(const LayerUpdateQueue& layers, const SkRect& clip,
350 const std::vector<sp<RenderNode>>& nodes, bool opaque,
351 const Rect& contentDrawBounds, sk_sp<SkSurface> surface,
352 const SkMatrix& preTransform) {
353 bool previousSkpEnabled = Properties::skpCaptureEnabled;
354 if (mPictureCapturedCallback) {
355 Properties::skpCaptureEnabled = true;
356 }
357
358 // Initialize the canvas for the current frame, that might be a recording canvas if SKP
359 // capture is enabled.
360 SkCanvas* canvas = tryCapture(surface.get(), nodes[0].get(), layers);
361
362 // draw all layers up front
363 renderLayersImpl(layers, opaque);
364
365 renderFrameImpl(clip, nodes, opaque, contentDrawBounds, canvas, preTransform);
366
367 endCapture(surface.get());
368
369 if (CC_UNLIKELY(Properties::debugOverdraw)) {
370 renderOverdraw(clip, nodes, contentDrawBounds, surface, preTransform);
371 }
372
373 Properties::skpCaptureEnabled = previousSkpEnabled;
374 }
375
376 namespace {
nodeBounds(RenderNode & node)377 static Rect nodeBounds(RenderNode& node) {
378 auto& props = node.properties();
379 return Rect(props.getLeft(), props.getTop(), props.getRight(), props.getBottom());
380 }
381 } // namespace
382
renderFrameImpl(const SkRect & clip,const std::vector<sp<RenderNode>> & nodes,bool opaque,const Rect & contentDrawBounds,SkCanvas * canvas,const SkMatrix & preTransform)383 void SkiaPipeline::renderFrameImpl(const SkRect& clip,
384 const std::vector<sp<RenderNode>>& nodes, bool opaque,
385 const Rect& contentDrawBounds, SkCanvas* canvas,
386 const SkMatrix& preTransform) {
387 SkAutoCanvasRestore saver(canvas, true);
388 auto clipRestriction = preTransform.mapRect(clip).roundOut();
389 if (CC_UNLIKELY(isCapturingSkp())) {
390 canvas->drawAnnotation(SkRect::Make(clipRestriction), "AndroidDeviceClipRestriction",
391 nullptr);
392 } else {
393 // clip drawing to dirty region only when not recording SKP files (which should contain all
394 // draw ops on every frame)
395 canvas->androidFramework_setDeviceClipRestriction(clipRestriction);
396 }
397 canvas->concat(preTransform);
398
399 if (!opaque) {
400 canvas->clear(SK_ColorTRANSPARENT);
401 }
402
403 if (1 == nodes.size()) {
404 if (!nodes[0]->nothingToDraw()) {
405 RenderNodeDrawable root(nodes[0].get(), canvas);
406 root.draw(canvas);
407 }
408 } else if (0 == nodes.size()) {
409 // nothing to draw
410 } else {
411 // It there are multiple render nodes, they are laid out as follows:
412 // #0 - backdrop (content + caption)
413 // #1 - content (local bounds are at (0,0), will be translated and clipped to backdrop)
414 // #2 - additional overlay nodes
415 // Usually the backdrop cannot be seen since it will be entirely covered by the content.
416 // While
417 // resizing however it might become partially visible. The following render loop will crop
418 // the
419 // backdrop against the content and draw the remaining part of it. It will then draw the
420 // content
421 // cropped to the backdrop (since that indicates a shrinking of the window).
422 //
423 // Additional nodes will be drawn on top with no particular clipping semantics.
424
425 // Usually the contents bounds should be mContentDrawBounds - however - we will
426 // move it towards the fixed edge to give it a more stable appearance (for the moment).
427 // If there is no content bounds we ignore the layering as stated above and start with 2.
428
429 // Backdrop bounds in render target space
430 const Rect backdrop = nodeBounds(*nodes[0]);
431
432 // Bounds that content will fill in render target space (note content node bounds may be
433 // bigger)
434 Rect content(contentDrawBounds.getWidth(), contentDrawBounds.getHeight());
435 content.translate(backdrop.left, backdrop.top);
436 if (!content.contains(backdrop) && !nodes[0]->nothingToDraw()) {
437 // Content doesn't entirely overlap backdrop, so fill around content (right/bottom)
438
439 // Note: in the future, if content doesn't snap to backdrop's left/top, this may need to
440 // also fill left/top. Currently, both 2up and freeform position content at the top/left
441 // of
442 // the backdrop, so this isn't necessary.
443 RenderNodeDrawable backdropNode(nodes[0].get(), canvas);
444 if (content.right < backdrop.right) {
445 // draw backdrop to right side of content
446 SkAutoCanvasRestore acr(canvas, true);
447 canvas->clipRect(SkRect::MakeLTRB(content.right, backdrop.top, backdrop.right,
448 backdrop.bottom));
449 backdropNode.draw(canvas);
450 }
451 if (content.bottom < backdrop.bottom) {
452 // draw backdrop to bottom of content
453 // Note: bottom fill uses content left/right, to avoid overdrawing left/right fill
454 SkAutoCanvasRestore acr(canvas, true);
455 canvas->clipRect(SkRect::MakeLTRB(content.left, content.bottom, content.right,
456 backdrop.bottom));
457 backdropNode.draw(canvas);
458 }
459 }
460
461 RenderNodeDrawable contentNode(nodes[1].get(), canvas);
462 if (!backdrop.isEmpty()) {
463 // content node translation to catch up with backdrop
464 float dx = backdrop.left - contentDrawBounds.left;
465 float dy = backdrop.top - contentDrawBounds.top;
466
467 SkAutoCanvasRestore acr(canvas, true);
468 canvas->translate(dx, dy);
469 const SkRect contentLocalClip =
470 SkRect::MakeXYWH(contentDrawBounds.left, contentDrawBounds.top,
471 backdrop.getWidth(), backdrop.getHeight());
472 canvas->clipRect(contentLocalClip);
473 contentNode.draw(canvas);
474 } else {
475 SkAutoCanvasRestore acr(canvas, true);
476 contentNode.draw(canvas);
477 }
478
479 // remaining overlay nodes, simply defer
480 for (size_t index = 2; index < nodes.size(); index++) {
481 if (!nodes[index]->nothingToDraw()) {
482 SkAutoCanvasRestore acr(canvas, true);
483 RenderNodeDrawable overlayNode(nodes[index].get(), canvas);
484 overlayNode.draw(canvas);
485 }
486 }
487 }
488 }
489
setSurfaceColorProperties(ColorMode colorMode)490 void SkiaPipeline::setSurfaceColorProperties(ColorMode colorMode) {
491 mColorMode = colorMode;
492 switch (colorMode) {
493 case ColorMode::Default:
494 mSurfaceColorType = SkColorType::kN32_SkColorType;
495 mSurfaceColorSpace = SkColorSpace::MakeSRGB();
496 break;
497 case ColorMode::WideColorGamut:
498 mSurfaceColorType = DeviceInfo::get()->getWideColorType();
499 mSurfaceColorSpace = DeviceInfo::get()->getWideColorSpace();
500 break;
501 case ColorMode::Hdr:
502 if (DeviceInfo::get()->isSupportRgba10101010ForHdr()) {
503 mSurfaceColorType = SkColorType::kRGBA_10x6_SkColorType;
504 mSurfaceColorSpace = SkColorSpace::MakeRGB(
505 GetExtendedTransferFunction(mTargetSdrHdrRatio), SkNamedGamut::kDisplayP3);
506 } else if (DeviceInfo::get()->isSupportFp16ForHdr()) {
507 mSurfaceColorType = SkColorType::kRGBA_F16_SkColorType;
508 mSurfaceColorSpace = SkColorSpace::MakeSRGB();
509 } else {
510 mSurfaceColorType = SkColorType::kN32_SkColorType;
511 mSurfaceColorSpace = SkColorSpace::MakeRGB(
512 GetExtendedTransferFunction(mTargetSdrHdrRatio), SkNamedGamut::kDisplayP3);
513 }
514 break;
515 case ColorMode::Hdr10:
516 mSurfaceColorType = SkColorType::kRGBA_1010102_SkColorType;
517 mSurfaceColorSpace = SkColorSpace::MakeRGB(
518 GetExtendedTransferFunction(mTargetSdrHdrRatio), SkNamedGamut::kDisplayP3);
519 break;
520 case ColorMode::A8:
521 mSurfaceColorType = SkColorType::kAlpha_8_SkColorType;
522 mSurfaceColorSpace = nullptr;
523 break;
524 }
525 }
526
setTargetSdrHdrRatio(float ratio)527 void SkiaPipeline::setTargetSdrHdrRatio(float ratio) {
528 if (mColorMode == ColorMode::Hdr || mColorMode == ColorMode::Hdr10) {
529 mTargetSdrHdrRatio = ratio;
530
531 if (mColorMode == ColorMode::Hdr && DeviceInfo::get()->isSupportFp16ForHdr() &&
532 !DeviceInfo::get()->isSupportRgba10101010ForHdr()) {
533 mSurfaceColorSpace = SkColorSpace::MakeSRGB();
534 } else {
535 mSurfaceColorSpace = SkColorSpace::MakeRGB(
536 GetExtendedTransferFunction(mTargetSdrHdrRatio), SkNamedGamut::kDisplayP3);
537 }
538 } else {
539 mTargetSdrHdrRatio = 1.f;
540 }
541 }
542
543 // Overdraw debugging
544
545 // These colors should be kept in sync with Caches::getOverdrawColor() with a few differences.
546 // This implementation requires transparent entries for "no overdraw" and "single draws".
547 static const SkColor kOverdrawColors[2][6] = {
548 {
549 0x00000000,
550 0x00000000,
551 0x2f0000ff,
552 0x2f00ff00,
553 0x3fff0000,
554 0x7fff0000,
555 },
556 {
557 0x00000000,
558 0x00000000,
559 0x2f0000ff,
560 0x4fffff00,
561 0x5fff89d7,
562 0x7fff0000,
563 },
564 };
565
renderOverdraw(const SkRect & clip,const std::vector<sp<RenderNode>> & nodes,const Rect & contentDrawBounds,sk_sp<SkSurface> surface,const SkMatrix & preTransform)566 void SkiaPipeline::renderOverdraw(const SkRect& clip,
567 const std::vector<sp<RenderNode>>& nodes,
568 const Rect& contentDrawBounds, sk_sp<SkSurface> surface,
569 const SkMatrix& preTransform) {
570 // Set up the overdraw canvas.
571 SkImageInfo offscreenInfo = SkImageInfo::MakeA8(surface->width(), surface->height());
572 sk_sp<SkSurface> offscreen = surface->makeSurface(offscreenInfo);
573 LOG_ALWAYS_FATAL_IF(!offscreen, "Failed to create offscreen SkSurface for overdraw viz.");
574 SkOverdrawCanvas overdrawCanvas(offscreen->getCanvas());
575
576 // Fake a redraw to replay the draw commands. This will increment the alpha channel
577 // each time a pixel would have been drawn.
578 // Pass true for opaque so we skip the clear - the overdrawCanvas is already zero
579 // initialized.
580 renderFrameImpl(clip, nodes, true, contentDrawBounds, &overdrawCanvas, preTransform);
581 sk_sp<SkImage> counts = offscreen->makeImageSnapshot();
582
583 // Draw overdraw colors to the canvas. The color filter will convert counts to colors.
584 SkPaint paint;
585 const SkColor* colors = kOverdrawColors[static_cast<int>(Properties::overdrawColorSet)];
586 paint.setColorFilter(SkOverdrawColorFilter::MakeWithSkColors(colors));
587 surface->getCanvas()->drawImage(counts.get(), 0.0f, 0.0f, SkSamplingOptions(), &paint);
588 }
589
590 } /* namespace skiapipeline */
591 } /* namespace uirenderer */
592 } /* namespace android */
593