blob: 79953aa6adc931c5c329a8abc5eaa014927d87d9 [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"
Kevin Lubick1175dc02022-02-28 12:41:27 -050029#include <SkBitmap.h>
30#include <SkBlendMode.h>
31#include <SkCanvas.h>
32#include <SkColorSpace.h>
33#include <SkImage.h>
34#include <SkImageInfo.h>
35#include <SkMatrix.h>
36#include <SkPaint.h>
37#include <SkRect.h>
38#include <SkRefCnt.h>
39#include <SkSamplingOptions.h>
40#include <SkSurface.h>
Stan Iliev1a025a72018-09-05 16:35:11 -040041#include "utils/Color.h"
42#include "utils/MathUtils.h"
Alec Mouri45238012020-01-29 11:04:40 -080043#include "utils/NdkUtils.h"
Stan Iliev1a025a72018-09-05 16:35:11 -040044
45using namespace android::uirenderer::renderthread;
46
47namespace android {
48namespace uirenderer {
49
John Reck2abc5492021-05-18 00:34:26 -040050#define ARECT_ARGS(r) float((r).left), float((r).top), float((r).right), float((r).bottom)
51
52CopyResult Readback::copySurfaceInto(ANativeWindow* window, const Rect& inSrcRect,
53 SkBitmap* bitmap) {
Stan Iliev1a025a72018-09-05 16:35:11 -040054 ATRACE_CALL();
55 // Setup the source
Alec Mouri8a82b142019-12-17 09:41:48 -080056 AHardwareBuffer* rawSourceBuffer;
57 int rawSourceFence;
John Reck2abc5492021-05-18 00:34:26 -040058 ARect cropRect;
59 uint32_t windowTransform;
60 status_t err = ANativeWindow_getLastQueuedBuffer2(window, &rawSourceBuffer, &rawSourceFence,
61 &cropRect, &windowTransform);
62 base::unique_fd sourceFence(rawSourceFence);
63 // Really this shouldn't ever happen, but better safe than sorry.
64 if (err == UNKNOWN_TRANSACTION) {
65 ALOGW("Readback failed to ANativeWindow_getLastQueuedBuffer2 - who are we talking to?");
66 return copySurfaceIntoLegacy(window, inSrcRect, bitmap);
67 }
68 ALOGV("Using new path, cropRect=" RECT_STRING ", transform=%x", ARECT_ARGS(cropRect),
69 windowTransform);
70
71 if (err != NO_ERROR) {
72 ALOGW("Failed to get last queued buffer, error = %d", err);
73 return CopyResult::UnknownError;
74 }
75 if (rawSourceBuffer == nullptr) {
76 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
77 return CopyResult::SourceEmpty;
78 }
79 UniqueAHardwareBuffer sourceBuffer{rawSourceBuffer};
80 AHardwareBuffer_Desc description;
81 AHardwareBuffer_describe(sourceBuffer.get(), &description);
82 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
83 ALOGW("Surface is protected, unable to copy from it");
84 return CopyResult::SourceInvalid;
85 }
86
87 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
88 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
89 return CopyResult::Timeout;
90 }
91
92 sk_sp<SkColorSpace> colorSpace = DataSpaceToColorSpace(
93 static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(window)));
94 sk_sp<SkImage> image =
95 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
96
97 if (!image.get()) {
98 return CopyResult::UnknownError;
99 }
100
101 sk_sp<GrDirectContext> grContext = mRenderThread.requireGrContext();
102
103 SkRect srcRect = inSrcRect.toSkRect();
104
105 SkRect imageSrcRect =
106 SkRect::MakeLTRB(cropRect.left, cropRect.top, cropRect.right, cropRect.bottom);
107 if (imageSrcRect.isEmpty()) {
108 imageSrcRect = SkRect::MakeIWH(description.width, description.height);
109 }
110 ALOGV("imageSrcRect = " RECT_STRING, SK_RECT_ARGS(imageSrcRect));
111
112 // Represents the "logical" width/height of the texture. That is, the dimensions of the buffer
113 // after respecting crop & rotate. flipV/flipH still result in the same width & height
114 // so we can ignore those for this.
115 const SkRect textureRect =
116 (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90)
117 ? SkRect::MakeIWH(imageSrcRect.height(), imageSrcRect.width())
118 : SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
119
120 if (srcRect.isEmpty()) {
121 srcRect = textureRect;
122 } else {
123 ALOGV("intersecting " RECT_STRING " with " RECT_STRING, SK_RECT_ARGS(srcRect),
124 SK_RECT_ARGS(textureRect));
125 if (!srcRect.intersect(textureRect)) {
126 return CopyResult::UnknownError;
127 }
128 }
129
130 sk_sp<SkSurface> tmpSurface =
131 SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
132 bitmap->info(), 0, kTopLeft_GrSurfaceOrigin, nullptr);
133
134 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
135 // attempt to do the intermediate rendering step in 8888
136 if (!tmpSurface.get()) {
137 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
138 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
139 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
140 if (!tmpSurface.get()) {
141 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
142 return CopyResult::UnknownError;
143 }
144 }
145
146 /*
147 * The grand ordering of events.
148 * First we apply the buffer's crop, done by using a srcRect of the crop with a dstRect of the
149 * same width/height as the srcRect but with a 0x0 origin
150 *
151 * Second we apply the window transform via a Canvas matrix. Ordering for that is as follows:
152 * 1) FLIP_H
153 * 2) FLIP_V
154 * 3) ROT_90
155 * as per GLConsumer::computeTransformMatrix
156 *
157 * Third we apply the user's supplied cropping & scale to the output by doing a RectToRect
158 * matrix transform from srcRect to {0,0, bitmapWidth, bitmapHeight}
159 *
160 * Finally we're done messing with this bloody thing for hopefully the last time.
161 *
162 * That's a lie since...
163 * TODO: Do all this same stuff for TextureView as it's strictly more correct & easier
164 * to rationalize. And we can fix the 1-px crop bug.
165 */
166
167 SkMatrix m;
168 const SkRect imageDstRect = SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
169 const float px = imageDstRect.centerX();
170 const float py = imageDstRect.centerY();
171 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
172 m.postScale(-1.f, 1.f, px, py);
173 }
174 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
175 m.postScale(1.f, -1.f, px, py);
176 }
177 if (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
178 m.postRotate(90, 0, 0);
179 m.postTranslate(imageDstRect.height(), 0);
180 }
181
182 SkSamplingOptions sampling(SkFilterMode::kNearest);
183 ALOGV("Mapping from " RECT_STRING " to " RECT_STRING, SK_RECT_ARGS(srcRect),
184 SK_RECT_ARGS(SkRect::MakeWH(bitmap->width(), bitmap->height())));
185 m.postConcat(SkMatrix::MakeRectToRect(srcRect,
186 SkRect::MakeWH(bitmap->width(), bitmap->height()),
187 SkMatrix::kFill_ScaleToFit));
188 if (srcRect.width() != bitmap->width() || srcRect.height() != bitmap->height()) {
189 sampling = SkSamplingOptions(SkFilterMode::kLinear);
190 }
191
192 SkCanvas* canvas = tmpSurface->getCanvas();
193 canvas->save();
194 canvas->concat(m);
195 SkPaint paint;
196 paint.setAlpha(255);
197 paint.setBlendMode(SkBlendMode::kSrc);
John Reck0f284da2021-07-14 14:24:51 -0400198 const bool hasBufferCrop = cropRect.left < cropRect.right && cropRect.top < cropRect.bottom;
199 auto constraint =
200 hasBufferCrop ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint;
201 canvas->drawImageRect(image, imageSrcRect, imageDstRect, sampling, &paint, constraint);
John Reck2abc5492021-05-18 00:34:26 -0400202 canvas->restore();
203
204 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
205 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
206 // 8888 and then convert that into the destination format before giving up.
207 SkBitmap tmpBitmap;
208 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
209 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
210 !tmpBitmap.tryAllocPixels(tmpInfo) || !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
211 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(), bitmap->rowBytes(), 0, 0)) {
212 ALOGW("Unable to convert content into the provided bitmap");
213 return CopyResult::UnknownError;
214 }
215 }
216
217 bitmap->notifyPixelsChanged();
218
219 return CopyResult::Success;
220}
221
222CopyResult Readback::copySurfaceIntoLegacy(ANativeWindow* window, const Rect& srcRect,
223 SkBitmap* bitmap) {
224 // Setup the source
225 AHardwareBuffer* rawSourceBuffer;
226 int rawSourceFence;
Stan Iliev1a025a72018-09-05 16:35:11 -0400227 Matrix4 texTransform;
Alec Mouri8a82b142019-12-17 09:41:48 -0800228 status_t err = ANativeWindow_getLastQueuedBuffer(window, &rawSourceBuffer, &rawSourceFence,
229 texTransform.data);
230 base::unique_fd sourceFence(rawSourceFence);
Stan Iliev1a025a72018-09-05 16:35:11 -0400231 texTransform.invalidateType();
232 if (err != NO_ERROR) {
233 ALOGW("Failed to get last queued buffer, error = %d", err);
234 return CopyResult::UnknownError;
235 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800236 if (rawSourceBuffer == nullptr) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400237 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
238 return CopyResult::SourceEmpty;
239 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800240
Alec Mouri45238012020-01-29 11:04:40 -0800241 UniqueAHardwareBuffer sourceBuffer{rawSourceBuffer};
Alec Mouri8a82b142019-12-17 09:41:48 -0800242 AHardwareBuffer_Desc description;
243 AHardwareBuffer_describe(sourceBuffer.get(), &description);
244 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400245 ALOGW("Surface is protected, unable to copy from it");
246 return CopyResult::SourceInvalid;
247 }
Alec Mouri8a82b142019-12-17 09:41:48 -0800248
249 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
Stan Iliev1a025a72018-09-05 16:35:11 -0400250 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
251 return CopyResult::Timeout;
252 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400253
Alec Mouri8a82b142019-12-17 09:41:48 -0800254 sk_sp<SkColorSpace> colorSpace = DataSpaceToColorSpace(
255 static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(window)));
256 sk_sp<SkImage> image =
257 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
ramindani3952ed62021-08-12 15:55:12 +0000258 return copyImageInto(image, srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400259}
260
261CopyResult Readback::copyHWBitmapInto(Bitmap* hwBitmap, SkBitmap* bitmap) {
262 LOG_ALWAYS_FATAL_IF(!hwBitmap->isHardware());
263
264 Rect srcRect;
ramindani3952ed62021-08-12 15:55:12 +0000265 return copyImageInto(hwBitmap->makeImage(), srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400266}
267
268CopyResult Readback::copyLayerInto(DeferredLayerUpdater* deferredLayer, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700269 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400270 if (!mRenderThread.getGrContext()) {
271 return CopyResult::UnknownError;
272 }
273
274 // acquire most recent buffer for drawing
275 deferredLayer->updateTexImage();
276 deferredLayer->apply();
277 const SkRect dstRect = SkRect::MakeIWH(bitmap->width(), bitmap->height());
278 CopyResult copyResult = CopyResult::UnknownError;
279 Layer* layer = deferredLayer->backingLayer();
280 if (layer) {
281 if (copyLayerInto(layer, nullptr, &dstRect, bitmap)) {
282 copyResult = CopyResult::Success;
283 }
284 }
285 return copyResult;
286}
287
John Reck76005182021-06-09 22:43:05 -0400288CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, SkBitmap* bitmap) {
289 Rect srcRect;
ramindani3952ed62021-08-12 15:55:12 +0000290 return copyImageInto(image, srcRect, bitmap);
John Reck76005182021-06-09 22:43:05 -0400291}
292
ramindani3952ed62021-08-12 15:55:12 +0000293CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, const Rect& srcRect,
294 SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700295 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400296 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
297 mRenderThread.requireGlContext();
298 } else {
Stan Iliev981afe72019-02-13 14:24:33 -0500299 mRenderThread.requireVkContext();
Stan Iliev1a025a72018-09-05 16:35:11 -0400300 }
301 if (!image.get()) {
302 return CopyResult::UnknownError;
303 }
304 int imgWidth = image->width();
305 int imgHeight = image->height();
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400306 sk_sp<GrDirectContext> grContext = sk_ref_sp(mRenderThread.getGrContext());
Stan Iliev1a025a72018-09-05 16:35:11 -0400307
Stan Iliev1a025a72018-09-05 16:35:11 -0400308 CopyResult copyResult = CopyResult::UnknownError;
309
310 int displayedWidth = imgWidth, displayedHeight = imgHeight;
Stan Iliev1a025a72018-09-05 16:35:11 -0400311 SkRect skiaDestRect = SkRect::MakeWH(bitmap->width(), bitmap->height());
312 SkRect skiaSrcRect = srcRect.toSkRect();
313 if (skiaSrcRect.isEmpty()) {
314 skiaSrcRect = SkRect::MakeIWH(displayedWidth, displayedHeight);
315 }
316 bool srcNotEmpty = skiaSrcRect.intersect(SkRect::MakeIWH(displayedWidth, displayedHeight));
317 if (!srcNotEmpty) {
318 return copyResult;
319 }
320
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400321 Layer layer(mRenderThread.renderState(), nullptr, 255, SkBlendMode::kSrc);
Stan Iliev1a025a72018-09-05 16:35:11 -0400322 layer.setSize(displayedWidth, displayedHeight);
Stan Iliev1a025a72018-09-05 16:35:11 -0400323 layer.setImage(image);
Kazuhiro Inabaa74d6372020-03-11 00:01:53 +0900324 // Scaling filter is not explicitly set here, because it is done inside copyLayerInfo
325 // after checking the necessity based on the src/dest rect size and the transformation.
Stan Iliev1a025a72018-09-05 16:35:11 -0400326 if (copyLayerInto(&layer, &skiaSrcRect, &skiaDestRect, bitmap)) {
327 copyResult = CopyResult::Success;
328 }
329
330 return copyResult;
331}
332
333bool Readback::copyLayerInto(Layer* layer, const SkRect* srcRect, const SkRect* dstRect,
334 SkBitmap* bitmap) {
Derek Sollenbergerefcbd6d2021-03-19 12:10:28 -0400335 /* This intermediate surface is present to work around limitations that LayerDrawable expects
336 * to render into a GPU backed canvas. Additionally, the offscreen buffer solution works around
337 * a scaling issue (b/62262733) that was encountered when sampling from an EGLImage into a
338 * software buffer.
Stan Iliev1a025a72018-09-05 16:35:11 -0400339 */
340 sk_sp<SkSurface> tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500341 SkBudgeted::kYes, bitmap->info(), 0,
342 kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400343
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400344 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
345 // attempt to do the intermediate rendering step in 8888
Stan Iliev1a025a72018-09-05 16:35:11 -0400346 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400347 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
Stan Iliev1a025a72018-09-05 16:35:11 -0400348 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500349 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400350 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400351 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
Stan Iliev1a025a72018-09-05 16:35:11 -0400352 return false;
353 }
354 }
355
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400356 if (!skiapipeline::LayerDrawable::DrawLayer(mRenderThread.getGrContext(),
357 tmpSurface->getCanvas(), layer, srcRect, dstRect,
358 false)) {
359 ALOGW("Unable to draw content from GPU into the provided bitmap");
360 return false;
361 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400362
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400363 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
364 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
365 // 8888 and then convert that into the destination format before giving up.
366 SkBitmap tmpBitmap;
367 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
368 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
369 !tmpBitmap.tryAllocPixels(tmpInfo) ||
370 !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
371 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(),
372 bitmap->rowBytes(), 0, 0)) {
373 ALOGW("Unable to convert content into the provided bitmap");
374 return false;
Stan Iliev1a025a72018-09-05 16:35:11 -0400375 }
376 }
377
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400378 bitmap->notifyPixelsChanged();
379 return true;
Stan Iliev1a025a72018-09-05 16:35:11 -0400380}
381
382} /* namespace uirenderer */
383} /* namespace android */