blob: 4cce87ad1a2ffcbddc30e998ed99a9d064ee9ac1 [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
Alec Mouri8a82b142019-12-17 09:41:48 -080019#include <sync/sync.h>
20#include <system/window.h>
Alec Mouri8a82b142019-12-17 09:41:48 -080021
rnleece9762b2021-05-21 15:40:53 -070022#include <gui/TraceUtils.h>
Stan Iliev1a025a72018-09-05 16:35:11 -040023#include "DeferredLayerUpdater.h"
24#include "Properties.h"
25#include "hwui/Bitmap.h"
Alec Mouri8a82b142019-12-17 09:41:48 -080026#include "pipeline/skia/LayerDrawable.h"
27#include "renderthread/EglManager.h"
28#include "renderthread/VulkanManager.h"
Stan Iliev1a025a72018-09-05 16:35:11 -040029#include "utils/Color.h"
30#include "utils/MathUtils.h"
Alec Mouri45238012020-01-29 11:04:40 -080031#include "utils/NdkUtils.h"
Stan Iliev1a025a72018-09-05 16:35:11 -040032
33using namespace android::uirenderer::renderthread;
34
35namespace android {
36namespace uirenderer {
37
John Reck2abc5492021-05-18 00:34:26 -040038#define ARECT_ARGS(r) float((r).left), float((r).top), float((r).right), float((r).bottom)
39
40CopyResult Readback::copySurfaceInto(ANativeWindow* window, const Rect& inSrcRect,
41 SkBitmap* bitmap) {
Stan Iliev1a025a72018-09-05 16:35:11 -040042 ATRACE_CALL();
43 // Setup the source
Alec Mouri8a82b142019-12-17 09:41:48 -080044 AHardwareBuffer* rawSourceBuffer;
45 int rawSourceFence;
John Reck2abc5492021-05-18 00:34:26 -040046 ARect cropRect;
47 uint32_t windowTransform;
48 status_t err = ANativeWindow_getLastQueuedBuffer2(window, &rawSourceBuffer, &rawSourceFence,
49 &cropRect, &windowTransform);
50 base::unique_fd sourceFence(rawSourceFence);
51 // Really this shouldn't ever happen, but better safe than sorry.
52 if (err == UNKNOWN_TRANSACTION) {
53 ALOGW("Readback failed to ANativeWindow_getLastQueuedBuffer2 - who are we talking to?");
54 return copySurfaceIntoLegacy(window, inSrcRect, bitmap);
55 }
56 ALOGV("Using new path, cropRect=" RECT_STRING ", transform=%x", ARECT_ARGS(cropRect),
57 windowTransform);
58
59 if (err != NO_ERROR) {
60 ALOGW("Failed to get last queued buffer, error = %d", err);
61 return CopyResult::UnknownError;
62 }
63 if (rawSourceBuffer == nullptr) {
64 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
65 return CopyResult::SourceEmpty;
66 }
67 UniqueAHardwareBuffer sourceBuffer{rawSourceBuffer};
68 AHardwareBuffer_Desc description;
69 AHardwareBuffer_describe(sourceBuffer.get(), &description);
70 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
71 ALOGW("Surface is protected, unable to copy from it");
72 return CopyResult::SourceInvalid;
73 }
74
75 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
76 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
77 return CopyResult::Timeout;
78 }
79
80 sk_sp<SkColorSpace> colorSpace = DataSpaceToColorSpace(
81 static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(window)));
82 sk_sp<SkImage> image =
83 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
84
85 if (!image.get()) {
86 return CopyResult::UnknownError;
87 }
88
89 sk_sp<GrDirectContext> grContext = mRenderThread.requireGrContext();
90
91 SkRect srcRect = inSrcRect.toSkRect();
92
93 SkRect imageSrcRect =
94 SkRect::MakeLTRB(cropRect.left, cropRect.top, cropRect.right, cropRect.bottom);
95 if (imageSrcRect.isEmpty()) {
96 imageSrcRect = SkRect::MakeIWH(description.width, description.height);
97 }
98 ALOGV("imageSrcRect = " RECT_STRING, SK_RECT_ARGS(imageSrcRect));
99
100 // Represents the "logical" width/height of the texture. That is, the dimensions of the buffer
101 // after respecting crop & rotate. flipV/flipH still result in the same width & height
102 // so we can ignore those for this.
103 const SkRect textureRect =
104 (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90)
105 ? SkRect::MakeIWH(imageSrcRect.height(), imageSrcRect.width())
106 : SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
107
108 if (srcRect.isEmpty()) {
109 srcRect = textureRect;
110 } else {
111 ALOGV("intersecting " RECT_STRING " with " RECT_STRING, SK_RECT_ARGS(srcRect),
112 SK_RECT_ARGS(textureRect));
113 if (!srcRect.intersect(textureRect)) {
114 return CopyResult::UnknownError;
115 }
116 }
117
118 sk_sp<SkSurface> tmpSurface =
119 SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
120 bitmap->info(), 0, kTopLeft_GrSurfaceOrigin, nullptr);
121
122 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
123 // attempt to do the intermediate rendering step in 8888
124 if (!tmpSurface.get()) {
125 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
126 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
127 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
128 if (!tmpSurface.get()) {
129 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
130 return CopyResult::UnknownError;
131 }
132 }
133
134 /*
135 * The grand ordering of events.
136 * First we apply the buffer's crop, done by using a srcRect of the crop with a dstRect of the
137 * same width/height as the srcRect but with a 0x0 origin
138 *
139 * Second we apply the window transform via a Canvas matrix. Ordering for that is as follows:
140 * 1) FLIP_H
141 * 2) FLIP_V
142 * 3) ROT_90
143 * as per GLConsumer::computeTransformMatrix
144 *
145 * Third we apply the user's supplied cropping & scale to the output by doing a RectToRect
146 * matrix transform from srcRect to {0,0, bitmapWidth, bitmapHeight}
147 *
148 * Finally we're done messing with this bloody thing for hopefully the last time.
149 *
150 * That's a lie since...
151 * TODO: Do all this same stuff for TextureView as it's strictly more correct & easier
152 * to rationalize. And we can fix the 1-px crop bug.
153 */
154
155 SkMatrix m;
156 const SkRect imageDstRect = SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
157 const float px = imageDstRect.centerX();
158 const float py = imageDstRect.centerY();
159 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
160 m.postScale(-1.f, 1.f, px, py);
161 }
162 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
163 m.postScale(1.f, -1.f, px, py);
164 }
165 if (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
166 m.postRotate(90, 0, 0);
167 m.postTranslate(imageDstRect.height(), 0);
168 }
169
170 SkSamplingOptions sampling(SkFilterMode::kNearest);
171 ALOGV("Mapping from " RECT_STRING " to " RECT_STRING, SK_RECT_ARGS(srcRect),
172 SK_RECT_ARGS(SkRect::MakeWH(bitmap->width(), bitmap->height())));
173 m.postConcat(SkMatrix::MakeRectToRect(srcRect,
174 SkRect::MakeWH(bitmap->width(), bitmap->height()),
175 SkMatrix::kFill_ScaleToFit));
176 if (srcRect.width() != bitmap->width() || srcRect.height() != bitmap->height()) {
177 sampling = SkSamplingOptions(SkFilterMode::kLinear);
178 }
179
180 SkCanvas* canvas = tmpSurface->getCanvas();
181 canvas->save();
182 canvas->concat(m);
183 SkPaint paint;
184 paint.setAlpha(255);
185 paint.setBlendMode(SkBlendMode::kSrc);
John Reck0f284da2021-07-14 14:24:51 -0400186 const bool hasBufferCrop = cropRect.left < cropRect.right && cropRect.top < cropRect.bottom;
187 auto constraint =
188 hasBufferCrop ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint;
189 canvas->drawImageRect(image, imageSrcRect, imageDstRect, sampling, &paint, constraint);
John Reck2abc5492021-05-18 00:34:26 -0400190 canvas->restore();
191
192 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
193 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
194 // 8888 and then convert that into the destination format before giving up.
195 SkBitmap tmpBitmap;
196 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
197 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
198 !tmpBitmap.tryAllocPixels(tmpInfo) || !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
199 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(), bitmap->rowBytes(), 0, 0)) {
200 ALOGW("Unable to convert content into the provided bitmap");
201 return CopyResult::UnknownError;
202 }
203 }
204
205 bitmap->notifyPixelsChanged();
206
207 return CopyResult::Success;
208}
209
210CopyResult Readback::copySurfaceIntoLegacy(ANativeWindow* window, const Rect& srcRect,
211 SkBitmap* bitmap) {
212 // Setup the source
213 AHardwareBuffer* rawSourceBuffer;
214 int rawSourceFence;
Stan Iliev1a025a72018-09-05 16:35:11 -0400215 Matrix4 texTransform;
Alec Mouri8a82b142019-12-17 09:41:48 -0800216 status_t err = ANativeWindow_getLastQueuedBuffer(window, &rawSourceBuffer, &rawSourceFence,
217 texTransform.data);
218 base::unique_fd sourceFence(rawSourceFence);
Stan Iliev1a025a72018-09-05 16:35:11 -0400219 texTransform.invalidateType();
220 if (err != NO_ERROR) {
221 ALOGW("Failed to get last queued buffer, error = %d", err);
222 return CopyResult::UnknownError;
223 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800224 if (rawSourceBuffer == nullptr) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400225 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
226 return CopyResult::SourceEmpty;
227 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800228
Alec Mouri45238012020-01-29 11:04:40 -0800229 UniqueAHardwareBuffer sourceBuffer{rawSourceBuffer};
Alec Mouri8a82b142019-12-17 09:41:48 -0800230 AHardwareBuffer_Desc description;
231 AHardwareBuffer_describe(sourceBuffer.get(), &description);
232 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400233 ALOGW("Surface is protected, unable to copy from it");
234 return CopyResult::SourceInvalid;
235 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800236
237 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400238 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
239 return CopyResult::Timeout;
240 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400241
Alec Mouri8a82b142019-12-17 09:41:48 -0800242 sk_sp<SkColorSpace> colorSpace = DataSpaceToColorSpace(
243 static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(window)));
244 sk_sp<SkImage> image =
245 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
ramindani3952ed62021-08-12 15:55:12 +0000246 return copyImageInto(image, srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400247}
248
249CopyResult Readback::copyHWBitmapInto(Bitmap* hwBitmap, SkBitmap* bitmap) {
250 LOG_ALWAYS_FATAL_IF(!hwBitmap->isHardware());
251
252 Rect srcRect;
ramindani3952ed62021-08-12 15:55:12 +0000253 return copyImageInto(hwBitmap->makeImage(), srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400254}
255
256CopyResult Readback::copyLayerInto(DeferredLayerUpdater* deferredLayer, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700257 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400258 if (!mRenderThread.getGrContext()) {
259 return CopyResult::UnknownError;
260 }
261
262 // acquire most recent buffer for drawing
263 deferredLayer->updateTexImage();
264 deferredLayer->apply();
265 const SkRect dstRect = SkRect::MakeIWH(bitmap->width(), bitmap->height());
266 CopyResult copyResult = CopyResult::UnknownError;
267 Layer* layer = deferredLayer->backingLayer();
268 if (layer) {
269 if (copyLayerInto(layer, nullptr, &dstRect, bitmap)) {
270 copyResult = CopyResult::Success;
271 }
272 }
273 return copyResult;
274}
275
John Reck76005182021-06-09 22:43:05 -0400276CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, SkBitmap* bitmap) {
277 Rect srcRect;
ramindani3952ed62021-08-12 15:55:12 +0000278 return copyImageInto(image, srcRect, bitmap);
John Reck76005182021-06-09 22:43:05 -0400279}
280
ramindani3952ed62021-08-12 15:55:12 +0000281CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, const Rect& srcRect,
282 SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700283 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400284 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
285 mRenderThread.requireGlContext();
286 } else {
Stan Iliev981afe72019-02-13 14:24:33 -0500287 mRenderThread.requireVkContext();
Stan Iliev1a025a72018-09-05 16:35:11 -0400288 }
289 if (!image.get()) {
290 return CopyResult::UnknownError;
291 }
292 int imgWidth = image->width();
293 int imgHeight = image->height();
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400294 sk_sp<GrDirectContext> grContext = sk_ref_sp(mRenderThread.getGrContext());
Stan Iliev1a025a72018-09-05 16:35:11 -0400295
Stan Iliev1a025a72018-09-05 16:35:11 -0400296 CopyResult copyResult = CopyResult::UnknownError;
297
298 int displayedWidth = imgWidth, displayedHeight = imgHeight;
Stan Iliev1a025a72018-09-05 16:35:11 -0400299 SkRect skiaDestRect = SkRect::MakeWH(bitmap->width(), bitmap->height());
300 SkRect skiaSrcRect = srcRect.toSkRect();
301 if (skiaSrcRect.isEmpty()) {
302 skiaSrcRect = SkRect::MakeIWH(displayedWidth, displayedHeight);
303 }
304 bool srcNotEmpty = skiaSrcRect.intersect(SkRect::MakeIWH(displayedWidth, displayedHeight));
305 if (!srcNotEmpty) {
306 return copyResult;
307 }
308
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400309 Layer layer(mRenderThread.renderState(), nullptr, 255, SkBlendMode::kSrc);
Stan Iliev1a025a72018-09-05 16:35:11 -0400310 layer.setSize(displayedWidth, displayedHeight);
Stan Iliev1a025a72018-09-05 16:35:11 -0400311 layer.setImage(image);
Kazuhiro Inabaa74d6372020-03-11 00:01:53 +0900312 // Scaling filter is not explicitly set here, because it is done inside copyLayerInfo
313 // after checking the necessity based on the src/dest rect size and the transformation.
Stan Iliev1a025a72018-09-05 16:35:11 -0400314 if (copyLayerInto(&layer, &skiaSrcRect, &skiaDestRect, bitmap)) {
315 copyResult = CopyResult::Success;
316 }
317
318 return copyResult;
319}
320
321bool Readback::copyLayerInto(Layer* layer, const SkRect* srcRect, const SkRect* dstRect,
322 SkBitmap* bitmap) {
Derek Sollenbergerefcbd6d2021-03-19 12:10:28 -0400323 /* This intermediate surface is present to work around limitations that LayerDrawable expects
324 * to render into a GPU backed canvas. Additionally, the offscreen buffer solution works around
325 * a scaling issue (b/62262733) that was encountered when sampling from an EGLImage into a
326 * software buffer.
Stan Iliev1a025a72018-09-05 16:35:11 -0400327 */
328 sk_sp<SkSurface> tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500329 SkBudgeted::kYes, bitmap->info(), 0,
330 kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400331
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400332 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
333 // attempt to do the intermediate rendering step in 8888
Stan Iliev1a025a72018-09-05 16:35:11 -0400334 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400335 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
Stan Iliev1a025a72018-09-05 16:35:11 -0400336 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500337 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400338 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400339 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
Stan Iliev1a025a72018-09-05 16:35:11 -0400340 return false;
341 }
342 }
343
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400344 if (!skiapipeline::LayerDrawable::DrawLayer(mRenderThread.getGrContext(),
345 tmpSurface->getCanvas(), layer, srcRect, dstRect,
346 false)) {
347 ALOGW("Unable to draw content from GPU into the provided bitmap");
348 return false;
349 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400350
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400351 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
352 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
353 // 8888 and then convert that into the destination format before giving up.
354 SkBitmap tmpBitmap;
355 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
356 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
357 !tmpBitmap.tryAllocPixels(tmpInfo) ||
358 !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
359 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(),
360 bitmap->rowBytes(), 0, 0)) {
361 ALOGW("Unable to convert content into the provided bitmap");
362 return false;
Stan Iliev1a025a72018-09-05 16:35:11 -0400363 }
364 }
365
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400366 bitmap->notifyPixelsChanged();
367 return true;
Stan Iliev1a025a72018-09-05 16:35:11 -0400368}
369
370} /* namespace uirenderer */
371} /* namespace android */