blob: f8d6c07b980d9c58fd89fa4a1437be36389ad44e [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
John Reckb48d4d12021-10-01 16:30:11 -040035static constexpr bool sEnableExtraCropInset = true;
36
Stan Iliev1a025a72018-09-05 16:35:11 -040037namespace android {
38namespace uirenderer {
39
John Reck2abc5492021-05-18 00:34:26 -040040#define ARECT_ARGS(r) float((r).left), float((r).top), float((r).right), float((r).bottom)
41
42CopyResult Readback::copySurfaceInto(ANativeWindow* window, const Rect& inSrcRect,
43 SkBitmap* bitmap) {
Stan Iliev1a025a72018-09-05 16:35:11 -040044 ATRACE_CALL();
45 // Setup the source
Alec Mouri8a82b142019-12-17 09:41:48 -080046 AHardwareBuffer* rawSourceBuffer;
47 int rawSourceFence;
John Reck2abc5492021-05-18 00:34:26 -040048 ARect cropRect;
49 uint32_t windowTransform;
50 status_t err = ANativeWindow_getLastQueuedBuffer2(window, &rawSourceBuffer, &rawSourceFence,
51 &cropRect, &windowTransform);
52 base::unique_fd sourceFence(rawSourceFence);
53 // Really this shouldn't ever happen, but better safe than sorry.
54 if (err == UNKNOWN_TRANSACTION) {
55 ALOGW("Readback failed to ANativeWindow_getLastQueuedBuffer2 - who are we talking to?");
56 return copySurfaceIntoLegacy(window, inSrcRect, bitmap);
57 }
58 ALOGV("Using new path, cropRect=" RECT_STRING ", transform=%x", ARECT_ARGS(cropRect),
59 windowTransform);
60
61 if (err != NO_ERROR) {
62 ALOGW("Failed to get last queued buffer, error = %d", err);
63 return CopyResult::UnknownError;
64 }
65 if (rawSourceBuffer == nullptr) {
66 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
67 return CopyResult::SourceEmpty;
68 }
John Reckb48d4d12021-10-01 16:30:11 -040069
70 if (sEnableExtraCropInset &&
71 (cropRect.right - cropRect.left != bitmap->width() ||
72 cropRect.bottom - cropRect.top != bitmap->height())) {
73 /*
74 * When we need use filtering, we should also make border shrink here like gui.
75 * But we could not check format for YUV or RGB here... Just use 1 pix.
76 */
77 cropRect.left += 0.5f;
78 cropRect.top += 0.5f;
79 cropRect.right -= 0.5f;
80 cropRect.bottom -= 0.5f;
81 }
82
John Reck2abc5492021-05-18 00:34:26 -040083 UniqueAHardwareBuffer sourceBuffer{rawSourceBuffer};
84 AHardwareBuffer_Desc description;
85 AHardwareBuffer_describe(sourceBuffer.get(), &description);
86 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
87 ALOGW("Surface is protected, unable to copy from it");
88 return CopyResult::SourceInvalid;
89 }
90
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 CopyResult::Timeout;
94 }
95
96 sk_sp<SkColorSpace> colorSpace = DataSpaceToColorSpace(
97 static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(window)));
98 sk_sp<SkImage> image =
99 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
100
101 if (!image.get()) {
102 return CopyResult::UnknownError;
103 }
104
105 sk_sp<GrDirectContext> grContext = mRenderThread.requireGrContext();
106
107 SkRect srcRect = inSrcRect.toSkRect();
108
109 SkRect imageSrcRect =
110 SkRect::MakeLTRB(cropRect.left, cropRect.top, cropRect.right, cropRect.bottom);
111 if (imageSrcRect.isEmpty()) {
112 imageSrcRect = SkRect::MakeIWH(description.width, description.height);
113 }
114 ALOGV("imageSrcRect = " RECT_STRING, SK_RECT_ARGS(imageSrcRect));
115
116 // Represents the "logical" width/height of the texture. That is, the dimensions of the buffer
117 // after respecting crop & rotate. flipV/flipH still result in the same width & height
118 // so we can ignore those for this.
119 const SkRect textureRect =
120 (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90)
121 ? SkRect::MakeIWH(imageSrcRect.height(), imageSrcRect.width())
122 : SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
123
124 if (srcRect.isEmpty()) {
125 srcRect = textureRect;
126 } else {
127 ALOGV("intersecting " RECT_STRING " with " RECT_STRING, SK_RECT_ARGS(srcRect),
128 SK_RECT_ARGS(textureRect));
129 if (!srcRect.intersect(textureRect)) {
130 return CopyResult::UnknownError;
131 }
132 }
133
134 sk_sp<SkSurface> tmpSurface =
135 SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
136 bitmap->info(), 0, kTopLeft_GrSurfaceOrigin, nullptr);
137
138 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
139 // attempt to do the intermediate rendering step in 8888
140 if (!tmpSurface.get()) {
141 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
142 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
143 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
144 if (!tmpSurface.get()) {
145 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
146 return CopyResult::UnknownError;
147 }
148 }
149
150 /*
151 * The grand ordering of events.
152 * First we apply the buffer's crop, done by using a srcRect of the crop with a dstRect of the
153 * same width/height as the srcRect but with a 0x0 origin
154 *
155 * Second we apply the window transform via a Canvas matrix. Ordering for that is as follows:
156 * 1) FLIP_H
157 * 2) FLIP_V
158 * 3) ROT_90
159 * as per GLConsumer::computeTransformMatrix
160 *
161 * Third we apply the user's supplied cropping & scale to the output by doing a RectToRect
162 * matrix transform from srcRect to {0,0, bitmapWidth, bitmapHeight}
163 *
164 * Finally we're done messing with this bloody thing for hopefully the last time.
165 *
166 * That's a lie since...
167 * TODO: Do all this same stuff for TextureView as it's strictly more correct & easier
168 * to rationalize. And we can fix the 1-px crop bug.
169 */
170
171 SkMatrix m;
172 const SkRect imageDstRect = SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
173 const float px = imageDstRect.centerX();
174 const float py = imageDstRect.centerY();
175 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
176 m.postScale(-1.f, 1.f, px, py);
177 }
178 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
179 m.postScale(1.f, -1.f, px, py);
180 }
181 if (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
182 m.postRotate(90, 0, 0);
183 m.postTranslate(imageDstRect.height(), 0);
184 }
185
186 SkSamplingOptions sampling(SkFilterMode::kNearest);
187 ALOGV("Mapping from " RECT_STRING " to " RECT_STRING, SK_RECT_ARGS(srcRect),
188 SK_RECT_ARGS(SkRect::MakeWH(bitmap->width(), bitmap->height())));
189 m.postConcat(SkMatrix::MakeRectToRect(srcRect,
190 SkRect::MakeWH(bitmap->width(), bitmap->height()),
191 SkMatrix::kFill_ScaleToFit));
192 if (srcRect.width() != bitmap->width() || srcRect.height() != bitmap->height()) {
193 sampling = SkSamplingOptions(SkFilterMode::kLinear);
194 }
195
196 SkCanvas* canvas = tmpSurface->getCanvas();
197 canvas->save();
198 canvas->concat(m);
199 SkPaint paint;
200 paint.setAlpha(255);
201 paint.setBlendMode(SkBlendMode::kSrc);
John Reck0f284da2021-07-14 14:24:51 -0400202 const bool hasBufferCrop = cropRect.left < cropRect.right && cropRect.top < cropRect.bottom;
203 auto constraint =
204 hasBufferCrop ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint;
205 canvas->drawImageRect(image, imageSrcRect, imageDstRect, sampling, &paint, constraint);
John Reck2abc5492021-05-18 00:34:26 -0400206 canvas->restore();
207
208 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
209 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
210 // 8888 and then convert that into the destination format before giving up.
211 SkBitmap tmpBitmap;
212 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
213 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
214 !tmpBitmap.tryAllocPixels(tmpInfo) || !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
215 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(), bitmap->rowBytes(), 0, 0)) {
216 ALOGW("Unable to convert content into the provided bitmap");
217 return CopyResult::UnknownError;
218 }
219 }
220
221 bitmap->notifyPixelsChanged();
222
223 return CopyResult::Success;
224}
225
226CopyResult Readback::copySurfaceIntoLegacy(ANativeWindow* window, const Rect& srcRect,
227 SkBitmap* bitmap) {
228 // Setup the source
229 AHardwareBuffer* rawSourceBuffer;
230 int rawSourceFence;
Stan Iliev1a025a72018-09-05 16:35:11 -0400231 Matrix4 texTransform;
Alec Mouri8a82b142019-12-17 09:41:48 -0800232 status_t err = ANativeWindow_getLastQueuedBuffer(window, &rawSourceBuffer, &rawSourceFence,
233 texTransform.data);
234 base::unique_fd sourceFence(rawSourceFence);
Stan Iliev1a025a72018-09-05 16:35:11 -0400235 texTransform.invalidateType();
236 if (err != NO_ERROR) {
237 ALOGW("Failed to get last queued buffer, error = %d", err);
238 return CopyResult::UnknownError;
239 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800240 if (rawSourceBuffer == nullptr) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400241 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
242 return CopyResult::SourceEmpty;
243 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800244
Alec Mouri45238012020-01-29 11:04:40 -0800245 UniqueAHardwareBuffer sourceBuffer{rawSourceBuffer};
Alec Mouri8a82b142019-12-17 09:41:48 -0800246 AHardwareBuffer_Desc description;
247 AHardwareBuffer_describe(sourceBuffer.get(), &description);
248 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400249 ALOGW("Surface is protected, unable to copy from it");
250 return CopyResult::SourceInvalid;
251 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800252
253 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400254 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
255 return CopyResult::Timeout;
256 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400257
Alec Mouri8a82b142019-12-17 09:41:48 -0800258 sk_sp<SkColorSpace> colorSpace = DataSpaceToColorSpace(
259 static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(window)));
260 sk_sp<SkImage> image =
261 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400262 return copyImageInto(image, texTransform, srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400263}
264
265CopyResult Readback::copyHWBitmapInto(Bitmap* hwBitmap, SkBitmap* bitmap) {
266 LOG_ALWAYS_FATAL_IF(!hwBitmap->isHardware());
267
268 Rect srcRect;
269 Matrix4 transform;
270 transform.loadScale(1, -1, 1);
271 transform.translate(0, -1);
272
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400273 return copyImageInto(hwBitmap->makeImage(), transform, srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400274}
275
276CopyResult Readback::copyLayerInto(DeferredLayerUpdater* deferredLayer, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700277 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400278 if (!mRenderThread.getGrContext()) {
279 return CopyResult::UnknownError;
280 }
281
282 // acquire most recent buffer for drawing
283 deferredLayer->updateTexImage();
284 deferredLayer->apply();
285 const SkRect dstRect = SkRect::MakeIWH(bitmap->width(), bitmap->height());
286 CopyResult copyResult = CopyResult::UnknownError;
287 Layer* layer = deferredLayer->backingLayer();
288 if (layer) {
289 if (copyLayerInto(layer, nullptr, &dstRect, bitmap)) {
290 copyResult = CopyResult::Success;
291 }
292 }
293 return copyResult;
294}
295
John Reck76005182021-06-09 22:43:05 -0400296CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, SkBitmap* bitmap) {
297 Rect srcRect;
298 Matrix4 transform;
299 transform.loadScale(1, -1, 1);
300 transform.translate(0, -1);
301 return copyImageInto(image, transform, srcRect, bitmap);
302}
303
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400304CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, Matrix4& texTransform,
Stan Iliev1a025a72018-09-05 16:35:11 -0400305 const Rect& srcRect, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700306 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400307 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
308 mRenderThread.requireGlContext();
309 } else {
Stan Iliev981afe72019-02-13 14:24:33 -0500310 mRenderThread.requireVkContext();
Stan Iliev1a025a72018-09-05 16:35:11 -0400311 }
312 if (!image.get()) {
313 return CopyResult::UnknownError;
314 }
315 int imgWidth = image->width();
316 int imgHeight = image->height();
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400317 sk_sp<GrDirectContext> grContext = sk_ref_sp(mRenderThread.getGrContext());
Stan Iliev1a025a72018-09-05 16:35:11 -0400318
Stan Iliev1a025a72018-09-05 16:35:11 -0400319 CopyResult copyResult = CopyResult::UnknownError;
320
321 int displayedWidth = imgWidth, displayedHeight = imgHeight;
322 // If this is a 90 or 270 degree rotation we need to swap width/height to get the device
323 // size.
324 if (texTransform[Matrix4::kSkewX] >= 0.5f || texTransform[Matrix4::kSkewX] <= -0.5f) {
325 std::swap(displayedWidth, displayedHeight);
326 }
327 SkRect skiaDestRect = SkRect::MakeWH(bitmap->width(), bitmap->height());
328 SkRect skiaSrcRect = srcRect.toSkRect();
329 if (skiaSrcRect.isEmpty()) {
330 skiaSrcRect = SkRect::MakeIWH(displayedWidth, displayedHeight);
331 }
332 bool srcNotEmpty = skiaSrcRect.intersect(SkRect::MakeIWH(displayedWidth, displayedHeight));
333 if (!srcNotEmpty) {
334 return copyResult;
335 }
336
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400337 Layer layer(mRenderThread.renderState(), nullptr, 255, SkBlendMode::kSrc);
Stan Iliev1a025a72018-09-05 16:35:11 -0400338 layer.setSize(displayedWidth, displayedHeight);
339 texTransform.copyTo(layer.getTexTransform());
340 layer.setImage(image);
Kazuhiro Inabaa74d6372020-03-11 00:01:53 +0900341 // Scaling filter is not explicitly set here, because it is done inside copyLayerInfo
342 // after checking the necessity based on the src/dest rect size and the transformation.
Stan Iliev1a025a72018-09-05 16:35:11 -0400343 if (copyLayerInto(&layer, &skiaSrcRect, &skiaDestRect, bitmap)) {
344 copyResult = CopyResult::Success;
345 }
346
347 return copyResult;
348}
349
350bool Readback::copyLayerInto(Layer* layer, const SkRect* srcRect, const SkRect* dstRect,
351 SkBitmap* bitmap) {
Derek Sollenbergerefcbd6d2021-03-19 12:10:28 -0400352 /* This intermediate surface is present to work around limitations that LayerDrawable expects
353 * to render into a GPU backed canvas. Additionally, the offscreen buffer solution works around
354 * a scaling issue (b/62262733) that was encountered when sampling from an EGLImage into a
355 * software buffer.
Stan Iliev1a025a72018-09-05 16:35:11 -0400356 */
357 sk_sp<SkSurface> tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500358 SkBudgeted::kYes, bitmap->info(), 0,
359 kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400360
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400361 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
362 // attempt to do the intermediate rendering step in 8888
Stan Iliev1a025a72018-09-05 16:35:11 -0400363 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400364 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
Stan Iliev1a025a72018-09-05 16:35:11 -0400365 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500366 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400367 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400368 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
Stan Iliev1a025a72018-09-05 16:35:11 -0400369 return false;
370 }
371 }
372
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400373 if (!skiapipeline::LayerDrawable::DrawLayer(mRenderThread.getGrContext(),
374 tmpSurface->getCanvas(), layer, srcRect, dstRect,
375 false)) {
376 ALOGW("Unable to draw content from GPU into the provided bitmap");
377 return false;
378 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400379
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400380 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
381 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
382 // 8888 and then convert that into the destination format before giving up.
383 SkBitmap tmpBitmap;
384 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
385 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
386 !tmpBitmap.tryAllocPixels(tmpInfo) ||
387 !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
388 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(),
389 bitmap->rowBytes(), 0, 0)) {
390 ALOGW("Unable to convert content into the provided bitmap");
391 return false;
Stan Iliev1a025a72018-09-05 16:35:11 -0400392 }
393 }
394
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400395 bitmap->notifyPixelsChanged();
396 return true;
Stan Iliev1a025a72018-09-05 16:35:11 -0400397}
398
399} /* namespace uirenderer */
400} /* namespace android */