blob: 25d57f61654d7cb063a3fcb504d39f1db83690dc [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 }
192 canvas->drawImageRect(image, imageSrcRect, imageDstRect, &paint,
193 SkCanvas::kFast_SrcRectConstraint);
194 canvas->restore();
195
196 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
197 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
198 // 8888 and then convert that into the destination format before giving up.
199 SkBitmap tmpBitmap;
200 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
201 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
202 !tmpBitmap.tryAllocPixels(tmpInfo) || !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
203 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(), bitmap->rowBytes(), 0, 0)) {
204 ALOGW("Unable to convert content into the provided bitmap");
205 return CopyResult::UnknownError;
206 }
207 }
208
209 bitmap->notifyPixelsChanged();
210
211 return CopyResult::Success;
212}
213
214CopyResult Readback::copySurfaceIntoLegacy(ANativeWindow* window, const Rect& srcRect,
215 SkBitmap* bitmap) {
216 // Setup the source
217 AHardwareBuffer* rawSourceBuffer;
218 int rawSourceFence;
Stan Iliev1a025a72018-09-05 16:35:11 -0400219 Matrix4 texTransform;
Alec Mouri8a82b142019-12-17 09:41:48 -0800220 status_t err = ANativeWindow_getLastQueuedBuffer(window, &rawSourceBuffer, &rawSourceFence,
221 texTransform.data);
222 base::unique_fd sourceFence(rawSourceFence);
Stan Iliev1a025a72018-09-05 16:35:11 -0400223 texTransform.invalidateType();
224 if (err != NO_ERROR) {
225 ALOGW("Failed to get last queued buffer, error = %d", err);
226 return CopyResult::UnknownError;
227 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800228 if (rawSourceBuffer == nullptr) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400229 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
230 return CopyResult::SourceEmpty;
231 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800232
233 std::unique_ptr<AHardwareBuffer, decltype(&AHardwareBuffer_release)> sourceBuffer(
234 rawSourceBuffer, AHardwareBuffer_release);
235 AHardwareBuffer_Desc description;
236 AHardwareBuffer_describe(sourceBuffer.get(), &description);
237 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400238 ALOGW("Surface is protected, unable to copy from it");
239 return CopyResult::SourceInvalid;
240 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800241
242 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400243 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
244 return CopyResult::Timeout;
245 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400246
Alec Mouri8a82b142019-12-17 09:41:48 -0800247 sk_sp<SkColorSpace> colorSpace = DataSpaceToColorSpace(
248 static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(window)));
249 sk_sp<SkImage> image =
250 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400251 return copyImageInto(image, texTransform, srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400252}
253
254CopyResult Readback::copyHWBitmapInto(Bitmap* hwBitmap, SkBitmap* bitmap) {
255 LOG_ALWAYS_FATAL_IF(!hwBitmap->isHardware());
256
257 Rect srcRect;
258 Matrix4 transform;
259 transform.loadScale(1, -1, 1);
260 transform.translate(0, -1);
261
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400262 return copyImageInto(hwBitmap->makeImage(), transform, srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400263}
264
265CopyResult Readback::copyLayerInto(DeferredLayerUpdater* deferredLayer, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700266 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400267 if (!mRenderThread.getGrContext()) {
268 return CopyResult::UnknownError;
269 }
270
271 // acquire most recent buffer for drawing
272 deferredLayer->updateTexImage();
273 deferredLayer->apply();
274 const SkRect dstRect = SkRect::MakeIWH(bitmap->width(), bitmap->height());
275 CopyResult copyResult = CopyResult::UnknownError;
276 Layer* layer = deferredLayer->backingLayer();
277 if (layer) {
278 if (copyLayerInto(layer, nullptr, &dstRect, bitmap)) {
279 copyResult = CopyResult::Success;
280 }
281 }
282 return copyResult;
283}
284
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400285CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, Matrix4& texTransform,
Stan Iliev1a025a72018-09-05 16:35:11 -0400286 const Rect& srcRect, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700287 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400288 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
289 mRenderThread.requireGlContext();
290 } else {
Stan Iliev981afe72019-02-13 14:24:33 -0500291 mRenderThread.requireVkContext();
Stan Iliev1a025a72018-09-05 16:35:11 -0400292 }
293 if (!image.get()) {
294 return CopyResult::UnknownError;
295 }
296 int imgWidth = image->width();
297 int imgHeight = image->height();
298 sk_sp<GrContext> grContext = sk_ref_sp(mRenderThread.getGrContext());
299
300 if (bitmap->colorType() == kRGBA_F16_SkColorType &&
301 !grContext->colorTypeSupportedAsSurface(bitmap->colorType())) {
302 ALOGW("Can't copy surface into bitmap, RGBA_F16 config is not supported");
303 return CopyResult::DestinationInvalid;
304 }
305
306 CopyResult copyResult = CopyResult::UnknownError;
307
308 int displayedWidth = imgWidth, displayedHeight = imgHeight;
309 // If this is a 90 or 270 degree rotation we need to swap width/height to get the device
310 // size.
311 if (texTransform[Matrix4::kSkewX] >= 0.5f || texTransform[Matrix4::kSkewX] <= -0.5f) {
312 std::swap(displayedWidth, displayedHeight);
313 }
314 SkRect skiaDestRect = SkRect::MakeWH(bitmap->width(), bitmap->height());
315 SkRect skiaSrcRect = srcRect.toSkRect();
316 if (skiaSrcRect.isEmpty()) {
317 skiaSrcRect = SkRect::MakeIWH(displayedWidth, displayedHeight);
318 }
319 bool srcNotEmpty = skiaSrcRect.intersect(SkRect::MakeIWH(displayedWidth, displayedHeight));
320 if (!srcNotEmpty) {
321 return copyResult;
322 }
323
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400324 Layer layer(mRenderThread.renderState(), nullptr, 255, SkBlendMode::kSrc);
Stan Iliev1a025a72018-09-05 16:35:11 -0400325 layer.setSize(displayedWidth, displayedHeight);
326 texTransform.copyTo(layer.getTexTransform());
327 layer.setImage(image);
Kazuhiro Inabaa74d6372020-03-11 00:01:53 +0900328 // Scaling filter is not explicitly set here, because it is done inside copyLayerInfo
329 // after checking the necessity based on the src/dest rect size and the transformation.
Stan Iliev1a025a72018-09-05 16:35:11 -0400330 if (copyLayerInto(&layer, &skiaSrcRect, &skiaDestRect, bitmap)) {
331 copyResult = CopyResult::Success;
332 }
333
334 return copyResult;
335}
336
337bool Readback::copyLayerInto(Layer* layer, const SkRect* srcRect, const SkRect* dstRect,
338 SkBitmap* bitmap) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400339 /* This intermediate surface is present to work around a bug in SwiftShader that
340 * prevents us from reading the contents of the layer's texture directly. The
341 * workaround involves first rendering that texture into an intermediate buffer and
342 * then reading from the intermediate buffer into the bitmap.
343 * Another reason to render in an offscreen buffer is to scale and to avoid an issue b/62262733
344 * with reading incorrect data from EGLImage backed SkImage (likely a driver bug).
345 */
346 sk_sp<SkSurface> tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500347 SkBudgeted::kYes, bitmap->info(), 0,
348 kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400349
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400350 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
351 // attempt to do the intermediate rendering step in 8888
Stan Iliev1a025a72018-09-05 16:35:11 -0400352 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400353 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
Stan Iliev1a025a72018-09-05 16:35:11 -0400354 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500355 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400356 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400357 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
Stan Iliev1a025a72018-09-05 16:35:11 -0400358 return false;
359 }
360 }
361
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400362 if (!skiapipeline::LayerDrawable::DrawLayer(mRenderThread.getGrContext(),
363 tmpSurface->getCanvas(), layer, srcRect, dstRect,
364 false)) {
365 ALOGW("Unable to draw content from GPU into the provided bitmap");
366 return false;
367 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400368
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400369 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
370 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
371 // 8888 and then convert that into the destination format before giving up.
372 SkBitmap tmpBitmap;
373 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
374 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
375 !tmpBitmap.tryAllocPixels(tmpInfo) ||
376 !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
377 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(),
378 bitmap->rowBytes(), 0, 0)) {
379 ALOGW("Unable to convert content into the provided bitmap");
380 return false;
Stan Iliev1a025a72018-09-05 16:35:11 -0400381 }
382 }
383
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400384 bitmap->notifyPixelsChanged();
385 return true;
Stan Iliev1a025a72018-09-05 16:35:11 -0400386}
387
388} /* namespace uirenderer */
389} /* namespace android */