blob: 8dcd6dbe64213946e1174b3a0dd64f026189db42 [file] [log] [blame]
Stan Iliev1a025a72018-09-05 16:35:11 -04001/*
2 * Copyright (C) 2018 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 "Readback.h"
18
Kevin Lubick1175dc02022-02-28 12:41:27 -050019#include <SkBitmap.h>
20#include <SkBlendMode.h>
21#include <SkCanvas.h>
22#include <SkColorSpace.h>
23#include <SkImage.h>
24#include <SkImageInfo.h>
25#include <SkMatrix.h>
26#include <SkPaint.h>
27#include <SkRect.h>
28#include <SkRefCnt.h>
29#include <SkSamplingOptions.h>
30#include <SkSurface.h>
Alec Mouri97326742022-11-04 01:32:24 +000031#include <gui/TraceUtils.h>
32#include <private/android/AHardwareBufferHelpers.h>
33#include <shaders/shaders.h>
34#include <sync/sync.h>
35#include <system/window.h>
36
37#include "DeferredLayerUpdater.h"
38#include "Properties.h"
39#include "Tonemapper.h"
40#include "hwui/Bitmap.h"
41#include "pipeline/skia/LayerDrawable.h"
42#include "renderthread/EglManager.h"
43#include "renderthread/VulkanManager.h"
Stan Iliev1a025a72018-09-05 16:35:11 -040044#include "utils/Color.h"
45#include "utils/MathUtils.h"
Alec Mouri45238012020-01-29 11:04:40 -080046#include "utils/NdkUtils.h"
Stan Iliev1a025a72018-09-05 16:35:11 -040047
48using namespace android::uirenderer::renderthread;
49
50namespace android {
51namespace uirenderer {
52
John Reck2abc5492021-05-18 00:34:26 -040053#define ARECT_ARGS(r) float((r).left), float((r).top), float((r).right), float((r).bottom)
54
John Reck4d73cb12022-07-27 10:32:52 -040055void Readback::copySurfaceInto(ANativeWindow* window, const std::shared_ptr<CopyRequest>& request) {
Stan Iliev1a025a72018-09-05 16:35:11 -040056 ATRACE_CALL();
57 // Setup the source
Alec Mouri8a82b142019-12-17 09:41:48 -080058 AHardwareBuffer* rawSourceBuffer;
59 int rawSourceFence;
John Reck2abc5492021-05-18 00:34:26 -040060 ARect cropRect;
61 uint32_t windowTransform;
62 status_t err = ANativeWindow_getLastQueuedBuffer2(window, &rawSourceBuffer, &rawSourceFence,
63 &cropRect, &windowTransform);
64 base::unique_fd sourceFence(rawSourceFence);
65 // Really this shouldn't ever happen, but better safe than sorry.
66 if (err == UNKNOWN_TRANSACTION) {
67 ALOGW("Readback failed to ANativeWindow_getLastQueuedBuffer2 - who are we talking to?");
John Reck4d73cb12022-07-27 10:32:52 -040068 return request->onCopyFinished(CopyResult::SourceInvalid);
John Reck2abc5492021-05-18 00:34:26 -040069 }
70 ALOGV("Using new path, cropRect=" RECT_STRING ", transform=%x", ARECT_ARGS(cropRect),
71 windowTransform);
72
73 if (err != NO_ERROR) {
74 ALOGW("Failed to get last queued buffer, error = %d", err);
John Reck4d73cb12022-07-27 10:32:52 -040075 return request->onCopyFinished(CopyResult::SourceInvalid);
John Reck2abc5492021-05-18 00:34:26 -040076 }
77 if (rawSourceBuffer == nullptr) {
78 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
John Reck4d73cb12022-07-27 10:32:52 -040079 return request->onCopyFinished(CopyResult::SourceEmpty);
John Reck2abc5492021-05-18 00:34:26 -040080 }
81 UniqueAHardwareBuffer sourceBuffer{rawSourceBuffer};
82 AHardwareBuffer_Desc description;
83 AHardwareBuffer_describe(sourceBuffer.get(), &description);
84 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
85 ALOGW("Surface is protected, unable to copy from it");
John Reck4d73cb12022-07-27 10:32:52 -040086 return request->onCopyFinished(CopyResult::SourceInvalid);
John Reck2abc5492021-05-18 00:34:26 -040087 }
88
John Reck4d73cb12022-07-27 10:32:52 -040089 {
90 ATRACE_NAME("sync_wait");
91 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
92 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
93 return request->onCopyFinished(CopyResult::Timeout);
94 }
John Reck2abc5492021-05-18 00:34:26 -040095 }
96
Alec Mouri97326742022-11-04 01:32:24 +000097 int32_t dataspace = ANativeWindow_getBuffersDataSpace(window);
98
99 // If the application is not updating the Surface themselves, e.g., another
100 // process is producing buffers for the application to display, then
101 // ANativeWindow_getBuffersDataSpace will return an unknown answer, so grab
102 // the dataspace from buffer metadata instead, if it exists.
103 if (dataspace == 0) {
104 dataspace = AHardwareBuffer_getDataSpace(sourceBuffer.get());
105 }
106
107 sk_sp<SkColorSpace> colorSpace =
108 DataSpaceToColorSpace(static_cast<android_dataspace>(dataspace));
John Reck2abc5492021-05-18 00:34:26 -0400109 sk_sp<SkImage> image =
110 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
111
112 if (!image.get()) {
John Reck4d73cb12022-07-27 10:32:52 -0400113 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400114 }
115
116 sk_sp<GrDirectContext> grContext = mRenderThread.requireGrContext();
117
John Reck4d73cb12022-07-27 10:32:52 -0400118 SkRect srcRect = request->srcRect.toSkRect();
John Reck2abc5492021-05-18 00:34:26 -0400119
Yiwei Zhang6cf96a52022-07-03 05:53:04 +0000120 SkRect imageSrcRect = SkRect::MakeIWH(description.width, description.height);
121 SkISize imageWH = SkISize::Make(description.width, description.height);
122 if (cropRect.left < cropRect.right && cropRect.top < cropRect.bottom) {
123 imageSrcRect =
124 SkRect::MakeLTRB(cropRect.left, cropRect.top, cropRect.right, cropRect.bottom);
125 imageWH = SkISize::Make(cropRect.right - cropRect.left, cropRect.bottom - cropRect.top);
126
127 // Chroma channels of YUV420 images are subsampled we may need to shrink the crop region by
128 // a whole texel on each side. Since skia still adds its own 0.5 inset, we apply an
129 // additional 0.5 inset. See GLConsumer::computeTransformMatrix for details.
130 float shrinkAmount = 0.0f;
131 switch (description.format) {
132 // Use HAL formats since some AHB formats are only available in vndk
133 case HAL_PIXEL_FORMAT_YCBCR_420_888:
134 case HAL_PIXEL_FORMAT_YV12:
135 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
136 shrinkAmount = 0.5f;
137 break;
138 default:
139 break;
140 }
141
142 // Shrink the crop if it has more than 1-px and differs from the buffer size.
143 if (imageWH.width() > 1 && imageWH.width() < (int32_t)description.width)
144 imageSrcRect = imageSrcRect.makeInset(shrinkAmount, 0);
145
146 if (imageWH.height() > 1 && imageWH.height() < (int32_t)description.height)
147 imageSrcRect = imageSrcRect.makeInset(0, shrinkAmount);
John Reck2abc5492021-05-18 00:34:26 -0400148 }
Yiwei Zhang6cf96a52022-07-03 05:53:04 +0000149
John Reck2abc5492021-05-18 00:34:26 -0400150 ALOGV("imageSrcRect = " RECT_STRING, SK_RECT_ARGS(imageSrcRect));
151
152 // Represents the "logical" width/height of the texture. That is, the dimensions of the buffer
153 // after respecting crop & rotate. flipV/flipH still result in the same width & height
154 // so we can ignore those for this.
155 const SkRect textureRect =
156 (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90)
157 ? SkRect::MakeIWH(imageSrcRect.height(), imageSrcRect.width())
158 : SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
159
160 if (srcRect.isEmpty()) {
161 srcRect = textureRect;
162 } else {
163 ALOGV("intersecting " RECT_STRING " with " RECT_STRING, SK_RECT_ARGS(srcRect),
164 SK_RECT_ARGS(textureRect));
165 if (!srcRect.intersect(textureRect)) {
John Reck4d73cb12022-07-27 10:32:52 -0400166 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400167 }
168 }
169
John Reck4d73cb12022-07-27 10:32:52 -0400170 SkBitmap skBitmap = request->getDestinationBitmap(srcRect.width(), srcRect.height());
171 SkBitmap* bitmap = &skBitmap;
John Reck2abc5492021-05-18 00:34:26 -0400172 sk_sp<SkSurface> tmpSurface =
173 SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
174 bitmap->info(), 0, kTopLeft_GrSurfaceOrigin, nullptr);
175
176 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
177 // attempt to do the intermediate rendering step in 8888
178 if (!tmpSurface.get()) {
179 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
180 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
181 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
182 if (!tmpSurface.get()) {
183 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
John Reck4d73cb12022-07-27 10:32:52 -0400184 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400185 }
186 }
187
188 /*
189 * The grand ordering of events.
190 * First we apply the buffer's crop, done by using a srcRect of the crop with a dstRect of the
191 * same width/height as the srcRect but with a 0x0 origin
192 *
193 * Second we apply the window transform via a Canvas matrix. Ordering for that is as follows:
194 * 1) FLIP_H
195 * 2) FLIP_V
196 * 3) ROT_90
197 * as per GLConsumer::computeTransformMatrix
198 *
199 * Third we apply the user's supplied cropping & scale to the output by doing a RectToRect
200 * matrix transform from srcRect to {0,0, bitmapWidth, bitmapHeight}
201 *
202 * Finally we're done messing with this bloody thing for hopefully the last time.
203 *
204 * That's a lie since...
205 * TODO: Do all this same stuff for TextureView as it's strictly more correct & easier
206 * to rationalize. And we can fix the 1-px crop bug.
207 */
208
209 SkMatrix m;
Yiwei Zhang6cf96a52022-07-03 05:53:04 +0000210 const SkRect imageDstRect = SkRect::Make(imageWH);
John Reck2abc5492021-05-18 00:34:26 -0400211 const float px = imageDstRect.centerX();
212 const float py = imageDstRect.centerY();
213 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
214 m.postScale(-1.f, 1.f, px, py);
215 }
216 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
217 m.postScale(1.f, -1.f, px, py);
218 }
219 if (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
220 m.postRotate(90, 0, 0);
221 m.postTranslate(imageDstRect.height(), 0);
222 }
223
224 SkSamplingOptions sampling(SkFilterMode::kNearest);
225 ALOGV("Mapping from " RECT_STRING " to " RECT_STRING, SK_RECT_ARGS(srcRect),
226 SK_RECT_ARGS(SkRect::MakeWH(bitmap->width(), bitmap->height())));
227 m.postConcat(SkMatrix::MakeRectToRect(srcRect,
228 SkRect::MakeWH(bitmap->width(), bitmap->height()),
229 SkMatrix::kFill_ScaleToFit));
230 if (srcRect.width() != bitmap->width() || srcRect.height() != bitmap->height()) {
231 sampling = SkSamplingOptions(SkFilterMode::kLinear);
232 }
233
234 SkCanvas* canvas = tmpSurface->getCanvas();
235 canvas->save();
236 canvas->concat(m);
237 SkPaint paint;
238 paint.setAlpha(255);
239 paint.setBlendMode(SkBlendMode::kSrc);
John Reck0f284da2021-07-14 14:24:51 -0400240 const bool hasBufferCrop = cropRect.left < cropRect.right && cropRect.top < cropRect.bottom;
241 auto constraint =
242 hasBufferCrop ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint;
Alec Mouri97326742022-11-04 01:32:24 +0000243
244 static constexpr float kMaxLuminanceNits = 4000.f;
245 tonemapPaint(image->imageInfo(), canvas->imageInfo(), kMaxLuminanceNits, paint);
246
John Reck0f284da2021-07-14 14:24:51 -0400247 canvas->drawImageRect(image, imageSrcRect, imageDstRect, sampling, &paint, constraint);
John Reck2abc5492021-05-18 00:34:26 -0400248 canvas->restore();
249
250 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
251 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
252 // 8888 and then convert that into the destination format before giving up.
253 SkBitmap tmpBitmap;
254 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
255 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
256 !tmpBitmap.tryAllocPixels(tmpInfo) || !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
257 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(), bitmap->rowBytes(), 0, 0)) {
258 ALOGW("Unable to convert content into the provided bitmap");
John Reck4d73cb12022-07-27 10:32:52 -0400259 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400260 }
261 }
262
263 bitmap->notifyPixelsChanged();
264
John Reck4d73cb12022-07-27 10:32:52 -0400265 return request->onCopyFinished(CopyResult::Success);
Stan Iliev1a025a72018-09-05 16:35:11 -0400266}
267
268CopyResult Readback::copyHWBitmapInto(Bitmap* hwBitmap, SkBitmap* bitmap) {
269 LOG_ALWAYS_FATAL_IF(!hwBitmap->isHardware());
270
271 Rect srcRect;
ramindani3952ed62021-08-12 15:55:12 +0000272 return copyImageInto(hwBitmap->makeImage(), srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400273}
274
275CopyResult Readback::copyLayerInto(DeferredLayerUpdater* deferredLayer, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700276 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400277 if (!mRenderThread.getGrContext()) {
278 return CopyResult::UnknownError;
279 }
280
281 // acquire most recent buffer for drawing
282 deferredLayer->updateTexImage();
283 deferredLayer->apply();
284 const SkRect dstRect = SkRect::MakeIWH(bitmap->width(), bitmap->height());
285 CopyResult copyResult = CopyResult::UnknownError;
286 Layer* layer = deferredLayer->backingLayer();
287 if (layer) {
288 if (copyLayerInto(layer, nullptr, &dstRect, bitmap)) {
289 copyResult = CopyResult::Success;
290 }
291 }
292 return copyResult;
293}
294
John Reck76005182021-06-09 22:43:05 -0400295CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, SkBitmap* bitmap) {
296 Rect srcRect;
ramindani3952ed62021-08-12 15:55:12 +0000297 return copyImageInto(image, srcRect, bitmap);
John Reck76005182021-06-09 22:43:05 -0400298}
299
ramindani3952ed62021-08-12 15:55:12 +0000300CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, const Rect& srcRect,
301 SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700302 ATRACE_CALL();
John Reck4d73cb12022-07-27 10:32:52 -0400303 if (!image.get()) {
304 return CopyResult::UnknownError;
305 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400306 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
307 mRenderThread.requireGlContext();
308 } else {
Stan Iliev981afe72019-02-13 14:24:33 -0500309 mRenderThread.requireVkContext();
Stan Iliev1a025a72018-09-05 16:35:11 -0400310 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400311 int imgWidth = image->width();
312 int imgHeight = image->height();
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400313 sk_sp<GrDirectContext> grContext = sk_ref_sp(mRenderThread.getGrContext());
Stan Iliev1a025a72018-09-05 16:35:11 -0400314
Stan Iliev1a025a72018-09-05 16:35:11 -0400315 CopyResult copyResult = CopyResult::UnknownError;
316
317 int displayedWidth = imgWidth, displayedHeight = imgHeight;
Stan Iliev1a025a72018-09-05 16:35:11 -0400318 SkRect skiaDestRect = SkRect::MakeWH(bitmap->width(), bitmap->height());
319 SkRect skiaSrcRect = srcRect.toSkRect();
320 if (skiaSrcRect.isEmpty()) {
321 skiaSrcRect = SkRect::MakeIWH(displayedWidth, displayedHeight);
322 }
323 bool srcNotEmpty = skiaSrcRect.intersect(SkRect::MakeIWH(displayedWidth, displayedHeight));
324 if (!srcNotEmpty) {
325 return copyResult;
326 }
327
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400328 Layer layer(mRenderThread.renderState(), nullptr, 255, SkBlendMode::kSrc);
Stan Iliev1a025a72018-09-05 16:35:11 -0400329 layer.setSize(displayedWidth, displayedHeight);
Stan Iliev1a025a72018-09-05 16:35:11 -0400330 layer.setImage(image);
Kazuhiro Inabaa74d6372020-03-11 00:01:53 +0900331 // Scaling filter is not explicitly set here, because it is done inside copyLayerInfo
332 // after checking the necessity based on the src/dest rect size and the transformation.
Stan Iliev1a025a72018-09-05 16:35:11 -0400333 if (copyLayerInto(&layer, &skiaSrcRect, &skiaDestRect, bitmap)) {
334 copyResult = CopyResult::Success;
335 }
336
337 return copyResult;
338}
339
340bool Readback::copyLayerInto(Layer* layer, const SkRect* srcRect, const SkRect* dstRect,
341 SkBitmap* bitmap) {
Derek Sollenbergerefcbd6d2021-03-19 12:10:28 -0400342 /* This intermediate surface is present to work around limitations that LayerDrawable expects
343 * to render into a GPU backed canvas. Additionally, the offscreen buffer solution works around
344 * a scaling issue (b/62262733) that was encountered when sampling from an EGLImage into a
345 * software buffer.
Stan Iliev1a025a72018-09-05 16:35:11 -0400346 */
347 sk_sp<SkSurface> tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500348 SkBudgeted::kYes, bitmap->info(), 0,
349 kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400350
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400351 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
352 // attempt to do the intermediate rendering step in 8888
Stan Iliev1a025a72018-09-05 16:35:11 -0400353 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400354 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
Stan Iliev1a025a72018-09-05 16:35:11 -0400355 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500356 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400357 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400358 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
Stan Iliev1a025a72018-09-05 16:35:11 -0400359 return false;
360 }
361 }
362
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400363 if (!skiapipeline::LayerDrawable::DrawLayer(mRenderThread.getGrContext(),
364 tmpSurface->getCanvas(), layer, srcRect, dstRect,
365 false)) {
366 ALOGW("Unable to draw content from GPU into the provided bitmap");
367 return false;
368 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400369
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400370 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
371 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
372 // 8888 and then convert that into the destination format before giving up.
373 SkBitmap tmpBitmap;
374 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
375 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
376 !tmpBitmap.tryAllocPixels(tmpInfo) ||
377 !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
378 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(),
379 bitmap->rowBytes(), 0, 0)) {
380 ALOGW("Unable to convert content into the provided bitmap");
381 return false;
Stan Iliev1a025a72018-09-05 16:35:11 -0400382 }
383 }
384
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400385 bitmap->notifyPixelsChanged();
386 return true;
Stan Iliev1a025a72018-09-05 16:35:11 -0400387}
388
389} /* namespace uirenderer */
390} /* namespace android */