blob: e08b99d52cdbdaa8406465d135f901152bc16e82 [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>
Stan Iliev1a025a72018-09-05 16:35:11 -040021#include <ui/GraphicBuffer.h>
Alec Mouri8a82b142019-12-17 09:41:48 -080022
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"
John Reck322b8ab2019-03-14 13:15:28 -070031#include "utils/TraceUtils.h"
Stan Iliev1a025a72018-09-05 16:35:11 -040032
33using namespace android::uirenderer::renderthread;
34
35namespace android {
36namespace uirenderer {
37
John Reck4464e462021-05-18 00:34:26 -040038// Deleter for an AHardwareBuffer, to be passed to an std::unique_ptr.
39struct AHardwareBuffer_deleter {
40 void operator()(AHardwareBuffer* ahb) const { AHardwareBuffer_release(ahb); }
41};
42
43using UniqueAHardwareBuffer = std::unique_ptr<AHardwareBuffer, AHardwareBuffer_deleter>;
44
45#define ARECT_ARGS(r) float((r).left), float((r).top), float((r).right), float((r).bottom)
46
47CopyResult Readback::copySurfaceInto(ANativeWindow* window, const Rect& inSrcRect,
48 SkBitmap* bitmap) {
Stan Iliev1a025a72018-09-05 16:35:11 -040049 ATRACE_CALL();
50 // Setup the source
Alec Mouri8a82b142019-12-17 09:41:48 -080051 AHardwareBuffer* rawSourceBuffer;
52 int rawSourceFence;
John Reck4464e462021-05-18 00:34:26 -040053 ARect cropRect;
54 uint32_t windowTransform;
55 status_t err = ANativeWindow_getLastQueuedBuffer2(window, &rawSourceBuffer, &rawSourceFence,
56 &cropRect, &windowTransform);
57 base::unique_fd sourceFence(rawSourceFence);
58 // Really this shouldn't ever happen, but better safe than sorry.
59 if (err == UNKNOWN_TRANSACTION) {
60 ALOGW("Readback failed to ANativeWindow_getLastQueuedBuffer2 - who are we talking to?");
61 return copySurfaceIntoLegacy(window, inSrcRect, bitmap);
62 }
63 ALOGV("Using new path, cropRect=" RECT_STRING ", transform=%x", ARECT_ARGS(cropRect),
64 windowTransform);
65
66 if (err != NO_ERROR) {
67 ALOGW("Failed to get last queued buffer, error = %d", err);
68 return CopyResult::UnknownError;
69 }
70 if (rawSourceBuffer == nullptr) {
71 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
72 return CopyResult::SourceEmpty;
73 }
74 UniqueAHardwareBuffer sourceBuffer{rawSourceBuffer};
75 AHardwareBuffer_Desc description;
76 AHardwareBuffer_describe(sourceBuffer.get(), &description);
77 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
78 ALOGW("Surface is protected, unable to copy from it");
79 return CopyResult::SourceInvalid;
80 }
81
82 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
83 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
84 return CopyResult::Timeout;
85 }
86
87 sk_sp<SkColorSpace> colorSpace = DataSpaceToColorSpace(
88 static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(window)));
89 sk_sp<SkImage> image =
90 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
91
92 if (!image.get()) {
93 return CopyResult::UnknownError;
94 }
95
96 sk_sp<GrContext> grContext = mRenderThread.requireGrContext();
97
98 SkRect srcRect = inSrcRect.toSkRect();
99
100 SkRect imageSrcRect =
101 SkRect::MakeLTRB(cropRect.left, cropRect.top, cropRect.right, cropRect.bottom);
102 if (imageSrcRect.isEmpty()) {
103 imageSrcRect = SkRect::MakeIWH(description.width, description.height);
104 }
105 ALOGV("imageSrcRect = " RECT_STRING, SK_RECT_ARGS(imageSrcRect));
106
107 // Represents the "logical" width/height of the texture. That is, the dimensions of the buffer
108 // after respecting crop & rotate. flipV/flipH still result in the same width & height
109 // so we can ignore those for this.
110 const SkRect textureRect =
111 (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90)
112 ? SkRect::MakeIWH(imageSrcRect.height(), imageSrcRect.width())
113 : SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
114
115 if (srcRect.isEmpty()) {
116 srcRect = textureRect;
117 } else {
118 ALOGV("intersecting " RECT_STRING " with " RECT_STRING, SK_RECT_ARGS(srcRect),
119 SK_RECT_ARGS(textureRect));
120 if (!srcRect.intersect(textureRect)) {
121 return CopyResult::UnknownError;
122 }
123 }
124
125 sk_sp<SkSurface> tmpSurface =
126 SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
127 bitmap->info(), 0, kTopLeft_GrSurfaceOrigin, nullptr);
128
129 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
130 // attempt to do the intermediate rendering step in 8888
131 if (!tmpSurface.get()) {
132 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
133 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
134 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
135 if (!tmpSurface.get()) {
136 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
137 return CopyResult::UnknownError;
138 }
139 }
140
141 /*
142 * The grand ordering of events.
143 * First we apply the buffer's crop, done by using a srcRect of the crop with a dstRect of the
144 * same width/height as the srcRect but with a 0x0 origin
145 *
146 * Second we apply the window transform via a Canvas matrix. Ordering for that is as follows:
147 * 1) FLIP_H
148 * 2) FLIP_V
149 * 3) ROT_90
150 * as per GLConsumer::computeTransformMatrix
151 *
152 * Third we apply the user's supplied cropping & scale to the output by doing a RectToRect
153 * matrix transform from srcRect to {0,0, bitmapWidth, bitmapHeight}
154 *
155 * Finally we're done messing with this bloody thing for hopefully the last time.
156 *
157 * That's a lie since...
158 * TODO: Do all this same stuff for TextureView as it's strictly more correct & easier
159 * to rationalize. And we can fix the 1-px crop bug.
160 */
161
162 SkMatrix m;
163 const SkRect imageDstRect = SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
164 const float px = imageDstRect.centerX();
165 const float py = imageDstRect.centerY();
166 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
167 m.postScale(-1.f, 1.f, px, py);
168 }
169 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
170 m.postScale(1.f, -1.f, px, py);
171 }
172 if (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
173 m.postRotate(90, 0, 0);
174 m.postTranslate(imageDstRect.height(), 0);
175 }
176
177 ALOGV("Mapping from " RECT_STRING " to " RECT_STRING, SK_RECT_ARGS(srcRect),
178 SK_RECT_ARGS(SkRect::MakeWH(bitmap->width(), bitmap->height())));
179 m.postConcat(SkMatrix::MakeRectToRect(srcRect,
180 SkRect::MakeWH(bitmap->width(), bitmap->height()),
181 SkMatrix::kFill_ScaleToFit));
182
183 SkCanvas* canvas = tmpSurface->getCanvas();
184 canvas->save();
185 canvas->concat(m);
186 SkPaint paint;
187 paint.setAlpha(255);
188 paint.setBlendMode(SkBlendMode::kSrc);
189 if (srcRect.width() != bitmap->width() || srcRect.height() != bitmap->height()) {
190 paint.setFilterQuality(kLow_SkFilterQuality);
191 }
John Reckf1344702021-07-14 14:24:51 -0400192 const bool hasBufferCrop = cropRect.left < cropRect.right && cropRect.top < cropRect.bottom;
193 auto constraint =
194 hasBufferCrop ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint;
195 canvas->drawImageRect(image, imageSrcRect, imageDstRect, &paint, constraint);
John Reck4464e462021-05-18 00:34:26 -0400196 canvas->restore();
197
198 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
199 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
200 // 8888 and then convert that into the destination format before giving up.
201 SkBitmap tmpBitmap;
202 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
203 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
204 !tmpBitmap.tryAllocPixels(tmpInfo) || !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
205 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(), bitmap->rowBytes(), 0, 0)) {
206 ALOGW("Unable to convert content into the provided bitmap");
207 return CopyResult::UnknownError;
208 }
209 }
210
211 bitmap->notifyPixelsChanged();
212
213 return CopyResult::Success;
214}
215
216CopyResult Readback::copySurfaceIntoLegacy(ANativeWindow* window, const Rect& srcRect,
217 SkBitmap* bitmap) {
218 // Setup the source
219 AHardwareBuffer* rawSourceBuffer;
220 int rawSourceFence;
Stan Iliev1a025a72018-09-05 16:35:11 -0400221 Matrix4 texTransform;
Alec Mouri8a82b142019-12-17 09:41:48 -0800222 status_t err = ANativeWindow_getLastQueuedBuffer(window, &rawSourceBuffer, &rawSourceFence,
223 texTransform.data);
224 base::unique_fd sourceFence(rawSourceFence);
Stan Iliev1a025a72018-09-05 16:35:11 -0400225 texTransform.invalidateType();
226 if (err != NO_ERROR) {
227 ALOGW("Failed to get last queued buffer, error = %d", err);
228 return CopyResult::UnknownError;
229 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800230 if (rawSourceBuffer == nullptr) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400231 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
232 return CopyResult::SourceEmpty;
233 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800234
235 std::unique_ptr<AHardwareBuffer, decltype(&AHardwareBuffer_release)> sourceBuffer(
236 rawSourceBuffer, AHardwareBuffer_release);
237 AHardwareBuffer_Desc description;
238 AHardwareBuffer_describe(sourceBuffer.get(), &description);
239 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400240 ALOGW("Surface is protected, unable to copy from it");
241 return CopyResult::SourceInvalid;
242 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800243
244 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400245 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
246 return CopyResult::Timeout;
247 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400248
Alec Mouri8a82b142019-12-17 09:41:48 -0800249 sk_sp<SkColorSpace> colorSpace = DataSpaceToColorSpace(
250 static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(window)));
251 sk_sp<SkImage> image =
252 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400253 return copyImageInto(image, texTransform, srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400254}
255
256CopyResult Readback::copyHWBitmapInto(Bitmap* hwBitmap, SkBitmap* bitmap) {
257 LOG_ALWAYS_FATAL_IF(!hwBitmap->isHardware());
258
259 Rect srcRect;
260 Matrix4 transform;
261 transform.loadScale(1, -1, 1);
262 transform.translate(0, -1);
263
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400264 return copyImageInto(hwBitmap->makeImage(), transform, srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400265}
266
267CopyResult Readback::copyLayerInto(DeferredLayerUpdater* deferredLayer, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700268 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400269 if (!mRenderThread.getGrContext()) {
270 return CopyResult::UnknownError;
271 }
272
273 // acquire most recent buffer for drawing
274 deferredLayer->updateTexImage();
275 deferredLayer->apply();
276 const SkRect dstRect = SkRect::MakeIWH(bitmap->width(), bitmap->height());
277 CopyResult copyResult = CopyResult::UnknownError;
278 Layer* layer = deferredLayer->backingLayer();
279 if (layer) {
280 if (copyLayerInto(layer, nullptr, &dstRect, bitmap)) {
281 copyResult = CopyResult::Success;
282 }
283 }
284 return copyResult;
285}
286
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400287CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, Matrix4& texTransform,
Stan Iliev1a025a72018-09-05 16:35:11 -0400288 const Rect& srcRect, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700289 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400290 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
291 mRenderThread.requireGlContext();
292 } else {
Stan Iliev981afe72019-02-13 14:24:33 -0500293 mRenderThread.requireVkContext();
Stan Iliev1a025a72018-09-05 16:35:11 -0400294 }
295 if (!image.get()) {
296 return CopyResult::UnknownError;
297 }
298 int imgWidth = image->width();
299 int imgHeight = image->height();
300 sk_sp<GrContext> grContext = sk_ref_sp(mRenderThread.getGrContext());
301
302 if (bitmap->colorType() == kRGBA_F16_SkColorType &&
303 !grContext->colorTypeSupportedAsSurface(bitmap->colorType())) {
304 ALOGW("Can't copy surface into bitmap, RGBA_F16 config is not supported");
305 return CopyResult::DestinationInvalid;
306 }
307
308 CopyResult copyResult = CopyResult::UnknownError;
309
310 int displayedWidth = imgWidth, displayedHeight = imgHeight;
311 // If this is a 90 or 270 degree rotation we need to swap width/height to get the device
312 // size.
313 if (texTransform[Matrix4::kSkewX] >= 0.5f || texTransform[Matrix4::kSkewX] <= -0.5f) {
314 std::swap(displayedWidth, displayedHeight);
315 }
316 SkRect skiaDestRect = SkRect::MakeWH(bitmap->width(), bitmap->height());
317 SkRect skiaSrcRect = srcRect.toSkRect();
318 if (skiaSrcRect.isEmpty()) {
319 skiaSrcRect = SkRect::MakeIWH(displayedWidth, displayedHeight);
320 }
321 bool srcNotEmpty = skiaSrcRect.intersect(SkRect::MakeIWH(displayedWidth, displayedHeight));
322 if (!srcNotEmpty) {
323 return copyResult;
324 }
325
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400326 Layer layer(mRenderThread.renderState(), nullptr, 255, SkBlendMode::kSrc);
Stan Iliev1a025a72018-09-05 16:35:11 -0400327 layer.setSize(displayedWidth, displayedHeight);
328 texTransform.copyTo(layer.getTexTransform());
329 layer.setImage(image);
Kazuhiro Inabaa74d6372020-03-11 00:01:53 +0900330 // Scaling filter is not explicitly set here, because it is done inside copyLayerInfo
331 // after checking the necessity based on the src/dest rect size and the transformation.
Stan Iliev1a025a72018-09-05 16:35:11 -0400332 if (copyLayerInto(&layer, &skiaSrcRect, &skiaDestRect, bitmap)) {
333 copyResult = CopyResult::Success;
334 }
335
336 return copyResult;
337}
338
339bool Readback::copyLayerInto(Layer* layer, const SkRect* srcRect, const SkRect* dstRect,
340 SkBitmap* bitmap) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400341 /* This intermediate surface is present to work around a bug in SwiftShader that
342 * prevents us from reading the contents of the layer's texture directly. The
343 * workaround involves first rendering that texture into an intermediate buffer and
344 * then reading from the intermediate buffer into the bitmap.
345 * Another reason to render in an offscreen buffer is to scale and to avoid an issue b/62262733
346 * with reading incorrect data from EGLImage backed SkImage (likely a driver bug).
347 */
348 sk_sp<SkSurface> tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500349 SkBudgeted::kYes, bitmap->info(), 0,
350 kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400351
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400352 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
353 // attempt to do the intermediate rendering step in 8888
Stan Iliev1a025a72018-09-05 16:35:11 -0400354 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400355 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
Stan Iliev1a025a72018-09-05 16:35:11 -0400356 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500357 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400358 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400359 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
Stan Iliev1a025a72018-09-05 16:35:11 -0400360 return false;
361 }
362 }
363
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400364 if (!skiapipeline::LayerDrawable::DrawLayer(mRenderThread.getGrContext(),
365 tmpSurface->getCanvas(), layer, srcRect, dstRect,
366 false)) {
367 ALOGW("Unable to draw content from GPU into the provided bitmap");
368 return false;
369 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400370
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400371 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
372 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
373 // 8888 and then convert that into the destination format before giving up.
374 SkBitmap tmpBitmap;
375 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
376 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
377 !tmpBitmap.tryAllocPixels(tmpInfo) ||
378 !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
379 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(),
380 bitmap->rowBytes(), 0, 0)) {
381 ALOGW("Unable to convert content into the provided bitmap");
382 return false;
Stan Iliev1a025a72018-09-05 16:35:11 -0400383 }
384 }
385
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400386 bitmap->notifyPixelsChanged();
387 return true;
Stan Iliev1a025a72018-09-05 16:35:11 -0400388}
389
390} /* namespace uirenderer */
391} /* namespace android */