blob: 8a8b4181bd942ec0b2ff23677810d7c3e9b89718 [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);
186 canvas->drawImageRect(image, imageSrcRect, imageDstRect, sampling, &paint,
187 SkCanvas::kFast_SrcRectConstraint);
188 canvas->restore();
189
190 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
191 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
192 // 8888 and then convert that into the destination format before giving up.
193 SkBitmap tmpBitmap;
194 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
195 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
196 !tmpBitmap.tryAllocPixels(tmpInfo) || !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
197 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(), bitmap->rowBytes(), 0, 0)) {
198 ALOGW("Unable to convert content into the provided bitmap");
199 return CopyResult::UnknownError;
200 }
201 }
202
203 bitmap->notifyPixelsChanged();
204
205 return CopyResult::Success;
206}
207
208CopyResult Readback::copySurfaceIntoLegacy(ANativeWindow* window, const Rect& srcRect,
209 SkBitmap* bitmap) {
210 // Setup the source
211 AHardwareBuffer* rawSourceBuffer;
212 int rawSourceFence;
Stan Iliev1a025a72018-09-05 16:35:11 -0400213 Matrix4 texTransform;
Alec Mouri8a82b142019-12-17 09:41:48 -0800214 status_t err = ANativeWindow_getLastQueuedBuffer(window, &rawSourceBuffer, &rawSourceFence,
215 texTransform.data);
216 base::unique_fd sourceFence(rawSourceFence);
Stan Iliev1a025a72018-09-05 16:35:11 -0400217 texTransform.invalidateType();
218 if (err != NO_ERROR) {
219 ALOGW("Failed to get last queued buffer, error = %d", err);
220 return CopyResult::UnknownError;
221 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800222 if (rawSourceBuffer == nullptr) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400223 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
224 return CopyResult::SourceEmpty;
225 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800226
Alec Mouri45238012020-01-29 11:04:40 -0800227 UniqueAHardwareBuffer sourceBuffer{rawSourceBuffer};
Alec Mouri8a82b142019-12-17 09:41:48 -0800228 AHardwareBuffer_Desc description;
229 AHardwareBuffer_describe(sourceBuffer.get(), &description);
230 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400231 ALOGW("Surface is protected, unable to copy from it");
232 return CopyResult::SourceInvalid;
233 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800234
235 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400236 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
237 return CopyResult::Timeout;
238 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400239
Alec Mouri8a82b142019-12-17 09:41:48 -0800240 sk_sp<SkColorSpace> colorSpace = DataSpaceToColorSpace(
241 static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(window)));
242 sk_sp<SkImage> image =
243 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400244 return copyImageInto(image, texTransform, srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400245}
246
247CopyResult Readback::copyHWBitmapInto(Bitmap* hwBitmap, SkBitmap* bitmap) {
248 LOG_ALWAYS_FATAL_IF(!hwBitmap->isHardware());
249
250 Rect srcRect;
251 Matrix4 transform;
252 transform.loadScale(1, -1, 1);
253 transform.translate(0, -1);
254
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400255 return copyImageInto(hwBitmap->makeImage(), transform, srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400256}
257
258CopyResult Readback::copyLayerInto(DeferredLayerUpdater* deferredLayer, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700259 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400260 if (!mRenderThread.getGrContext()) {
261 return CopyResult::UnknownError;
262 }
263
264 // acquire most recent buffer for drawing
265 deferredLayer->updateTexImage();
266 deferredLayer->apply();
267 const SkRect dstRect = SkRect::MakeIWH(bitmap->width(), bitmap->height());
268 CopyResult copyResult = CopyResult::UnknownError;
269 Layer* layer = deferredLayer->backingLayer();
270 if (layer) {
271 if (copyLayerInto(layer, nullptr, &dstRect, bitmap)) {
272 copyResult = CopyResult::Success;
273 }
274 }
275 return copyResult;
276}
277
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400278CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, Matrix4& texTransform,
Stan Iliev1a025a72018-09-05 16:35:11 -0400279 const Rect& srcRect, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700280 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400281 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
282 mRenderThread.requireGlContext();
283 } else {
Stan Iliev981afe72019-02-13 14:24:33 -0500284 mRenderThread.requireVkContext();
Stan Iliev1a025a72018-09-05 16:35:11 -0400285 }
286 if (!image.get()) {
287 return CopyResult::UnknownError;
288 }
289 int imgWidth = image->width();
290 int imgHeight = image->height();
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400291 sk_sp<GrDirectContext> grContext = sk_ref_sp(mRenderThread.getGrContext());
Stan Iliev1a025a72018-09-05 16:35:11 -0400292
Stan Iliev1a025a72018-09-05 16:35:11 -0400293 CopyResult copyResult = CopyResult::UnknownError;
294
295 int displayedWidth = imgWidth, displayedHeight = imgHeight;
296 // If this is a 90 or 270 degree rotation we need to swap width/height to get the device
297 // size.
298 if (texTransform[Matrix4::kSkewX] >= 0.5f || texTransform[Matrix4::kSkewX] <= -0.5f) {
299 std::swap(displayedWidth, displayedHeight);
300 }
301 SkRect skiaDestRect = SkRect::MakeWH(bitmap->width(), bitmap->height());
302 SkRect skiaSrcRect = srcRect.toSkRect();
303 if (skiaSrcRect.isEmpty()) {
304 skiaSrcRect = SkRect::MakeIWH(displayedWidth, displayedHeight);
305 }
306 bool srcNotEmpty = skiaSrcRect.intersect(SkRect::MakeIWH(displayedWidth, displayedHeight));
307 if (!srcNotEmpty) {
308 return copyResult;
309 }
310
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400311 Layer layer(mRenderThread.renderState(), nullptr, 255, SkBlendMode::kSrc);
Stan Iliev1a025a72018-09-05 16:35:11 -0400312 layer.setSize(displayedWidth, displayedHeight);
313 texTransform.copyTo(layer.getTexTransform());
314 layer.setImage(image);
Kazuhiro Inabaa74d6372020-03-11 00:01:53 +0900315 // Scaling filter is not explicitly set here, because it is done inside copyLayerInfo
316 // after checking the necessity based on the src/dest rect size and the transformation.
Stan Iliev1a025a72018-09-05 16:35:11 -0400317 if (copyLayerInto(&layer, &skiaSrcRect, &skiaDestRect, bitmap)) {
318 copyResult = CopyResult::Success;
319 }
320
321 return copyResult;
322}
323
324bool Readback::copyLayerInto(Layer* layer, const SkRect* srcRect, const SkRect* dstRect,
325 SkBitmap* bitmap) {
Derek Sollenbergerefcbd6d2021-03-19 12:10:28 -0400326 /* This intermediate surface is present to work around limitations that LayerDrawable expects
327 * to render into a GPU backed canvas. Additionally, the offscreen buffer solution works around
328 * a scaling issue (b/62262733) that was encountered when sampling from an EGLImage into a
329 * software buffer.
Stan Iliev1a025a72018-09-05 16:35:11 -0400330 */
331 sk_sp<SkSurface> tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500332 SkBudgeted::kYes, bitmap->info(), 0,
333 kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400334
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400335 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
336 // attempt to do the intermediate rendering step in 8888
Stan Iliev1a025a72018-09-05 16:35:11 -0400337 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400338 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
Stan Iliev1a025a72018-09-05 16:35:11 -0400339 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500340 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400341 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400342 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
Stan Iliev1a025a72018-09-05 16:35:11 -0400343 return false;
344 }
345 }
346
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400347 if (!skiapipeline::LayerDrawable::DrawLayer(mRenderThread.getGrContext(),
348 tmpSurface->getCanvas(), layer, srcRect, dstRect,
349 false)) {
350 ALOGW("Unable to draw content from GPU into the provided bitmap");
351 return false;
352 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400353
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400354 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
355 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
356 // 8888 and then convert that into the destination format before giving up.
357 SkBitmap tmpBitmap;
358 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
359 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
360 !tmpBitmap.tryAllocPixels(tmpInfo) ||
361 !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
362 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(),
363 bitmap->rowBytes(), 0, 0)) {
364 ALOGW("Unable to convert content into the provided bitmap");
365 return false;
Stan Iliev1a025a72018-09-05 16:35:11 -0400366 }
367 }
368
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400369 bitmap->notifyPixelsChanged();
370 return true;
Stan Iliev1a025a72018-09-05 16:35:11 -0400371}
372
373} /* namespace uirenderer */
374} /* namespace android */