blob: 02c2e67a319bba9146567c3883c533f827800c26 [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
John Reck4d73cb12022-07-27 10:32:52 -040052void Readback::copySurfaceInto(ANativeWindow* window, const std::shared_ptr<CopyRequest>& request) {
Stan Iliev1a025a72018-09-05 16:35:11 -040053 ATRACE_CALL();
54 // Setup the source
Alec Mouri8a82b142019-12-17 09:41:48 -080055 AHardwareBuffer* rawSourceBuffer;
56 int rawSourceFence;
John Reck2abc5492021-05-18 00:34:26 -040057 ARect cropRect;
58 uint32_t windowTransform;
59 status_t err = ANativeWindow_getLastQueuedBuffer2(window, &rawSourceBuffer, &rawSourceFence,
60 &cropRect, &windowTransform);
61 base::unique_fd sourceFence(rawSourceFence);
62 // Really this shouldn't ever happen, but better safe than sorry.
63 if (err == UNKNOWN_TRANSACTION) {
64 ALOGW("Readback failed to ANativeWindow_getLastQueuedBuffer2 - who are we talking to?");
John Reck4d73cb12022-07-27 10:32:52 -040065 return request->onCopyFinished(CopyResult::SourceInvalid);
John Reck2abc5492021-05-18 00:34:26 -040066 }
67 ALOGV("Using new path, cropRect=" RECT_STRING ", transform=%x", ARECT_ARGS(cropRect),
68 windowTransform);
69
70 if (err != NO_ERROR) {
71 ALOGW("Failed to get last queued buffer, error = %d", err);
John Reck4d73cb12022-07-27 10:32:52 -040072 return request->onCopyFinished(CopyResult::SourceInvalid);
John Reck2abc5492021-05-18 00:34:26 -040073 }
74 if (rawSourceBuffer == nullptr) {
75 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
John Reck4d73cb12022-07-27 10:32:52 -040076 return request->onCopyFinished(CopyResult::SourceEmpty);
John Reck2abc5492021-05-18 00:34:26 -040077 }
78 UniqueAHardwareBuffer sourceBuffer{rawSourceBuffer};
79 AHardwareBuffer_Desc description;
80 AHardwareBuffer_describe(sourceBuffer.get(), &description);
81 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
82 ALOGW("Surface is protected, unable to copy from it");
John Reck4d73cb12022-07-27 10:32:52 -040083 return request->onCopyFinished(CopyResult::SourceInvalid);
John Reck2abc5492021-05-18 00:34:26 -040084 }
85
John Reck4d73cb12022-07-27 10:32:52 -040086 {
87 ATRACE_NAME("sync_wait");
88 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
89 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
90 return request->onCopyFinished(CopyResult::Timeout);
91 }
John Reck2abc5492021-05-18 00:34:26 -040092 }
93
94 sk_sp<SkColorSpace> colorSpace = DataSpaceToColorSpace(
95 static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(window)));
96 sk_sp<SkImage> image =
97 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
98
99 if (!image.get()) {
John Reck4d73cb12022-07-27 10:32:52 -0400100 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400101 }
102
103 sk_sp<GrDirectContext> grContext = mRenderThread.requireGrContext();
104
John Reck4d73cb12022-07-27 10:32:52 -0400105 SkRect srcRect = request->srcRect.toSkRect();
John Reck2abc5492021-05-18 00:34:26 -0400106
Yiwei Zhang6cf96a52022-07-03 05:53:04 +0000107 SkRect imageSrcRect = SkRect::MakeIWH(description.width, description.height);
108 SkISize imageWH = SkISize::Make(description.width, description.height);
109 if (cropRect.left < cropRect.right && cropRect.top < cropRect.bottom) {
110 imageSrcRect =
111 SkRect::MakeLTRB(cropRect.left, cropRect.top, cropRect.right, cropRect.bottom);
112 imageWH = SkISize::Make(cropRect.right - cropRect.left, cropRect.bottom - cropRect.top);
113
114 // Chroma channels of YUV420 images are subsampled we may need to shrink the crop region by
115 // a whole texel on each side. Since skia still adds its own 0.5 inset, we apply an
116 // additional 0.5 inset. See GLConsumer::computeTransformMatrix for details.
117 float shrinkAmount = 0.0f;
118 switch (description.format) {
119 // Use HAL formats since some AHB formats are only available in vndk
120 case HAL_PIXEL_FORMAT_YCBCR_420_888:
121 case HAL_PIXEL_FORMAT_YV12:
122 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
123 shrinkAmount = 0.5f;
124 break;
125 default:
126 break;
127 }
128
129 // Shrink the crop if it has more than 1-px and differs from the buffer size.
130 if (imageWH.width() > 1 && imageWH.width() < (int32_t)description.width)
131 imageSrcRect = imageSrcRect.makeInset(shrinkAmount, 0);
132
133 if (imageWH.height() > 1 && imageWH.height() < (int32_t)description.height)
134 imageSrcRect = imageSrcRect.makeInset(0, shrinkAmount);
John Reck2abc5492021-05-18 00:34:26 -0400135 }
Yiwei Zhang6cf96a52022-07-03 05:53:04 +0000136
John Reck2abc5492021-05-18 00:34:26 -0400137 ALOGV("imageSrcRect = " RECT_STRING, SK_RECT_ARGS(imageSrcRect));
138
139 // Represents the "logical" width/height of the texture. That is, the dimensions of the buffer
140 // after respecting crop & rotate. flipV/flipH still result in the same width & height
141 // so we can ignore those for this.
142 const SkRect textureRect =
143 (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90)
144 ? SkRect::MakeIWH(imageSrcRect.height(), imageSrcRect.width())
145 : SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
146
147 if (srcRect.isEmpty()) {
148 srcRect = textureRect;
149 } else {
150 ALOGV("intersecting " RECT_STRING " with " RECT_STRING, SK_RECT_ARGS(srcRect),
151 SK_RECT_ARGS(textureRect));
152 if (!srcRect.intersect(textureRect)) {
John Reck4d73cb12022-07-27 10:32:52 -0400153 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400154 }
155 }
156
John Reck4d73cb12022-07-27 10:32:52 -0400157 SkBitmap skBitmap = request->getDestinationBitmap(srcRect.width(), srcRect.height());
158 SkBitmap* bitmap = &skBitmap;
John Reck2abc5492021-05-18 00:34:26 -0400159 sk_sp<SkSurface> tmpSurface =
160 SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
161 bitmap->info(), 0, kTopLeft_GrSurfaceOrigin, nullptr);
162
163 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
164 // attempt to do the intermediate rendering step in 8888
165 if (!tmpSurface.get()) {
166 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
167 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
168 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
169 if (!tmpSurface.get()) {
170 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
John Reck4d73cb12022-07-27 10:32:52 -0400171 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400172 }
173 }
174
175 /*
176 * The grand ordering of events.
177 * First we apply the buffer's crop, done by using a srcRect of the crop with a dstRect of the
178 * same width/height as the srcRect but with a 0x0 origin
179 *
180 * Second we apply the window transform via a Canvas matrix. Ordering for that is as follows:
181 * 1) FLIP_H
182 * 2) FLIP_V
183 * 3) ROT_90
184 * as per GLConsumer::computeTransformMatrix
185 *
186 * Third we apply the user's supplied cropping & scale to the output by doing a RectToRect
187 * matrix transform from srcRect to {0,0, bitmapWidth, bitmapHeight}
188 *
189 * Finally we're done messing with this bloody thing for hopefully the last time.
190 *
191 * That's a lie since...
192 * TODO: Do all this same stuff for TextureView as it's strictly more correct & easier
193 * to rationalize. And we can fix the 1-px crop bug.
194 */
195
196 SkMatrix m;
Yiwei Zhang6cf96a52022-07-03 05:53:04 +0000197 const SkRect imageDstRect = SkRect::Make(imageWH);
John Reck2abc5492021-05-18 00:34:26 -0400198 const float px = imageDstRect.centerX();
199 const float py = imageDstRect.centerY();
200 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
201 m.postScale(-1.f, 1.f, px, py);
202 }
203 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
204 m.postScale(1.f, -1.f, px, py);
205 }
206 if (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
207 m.postRotate(90, 0, 0);
208 m.postTranslate(imageDstRect.height(), 0);
209 }
210
211 SkSamplingOptions sampling(SkFilterMode::kNearest);
212 ALOGV("Mapping from " RECT_STRING " to " RECT_STRING, SK_RECT_ARGS(srcRect),
213 SK_RECT_ARGS(SkRect::MakeWH(bitmap->width(), bitmap->height())));
214 m.postConcat(SkMatrix::MakeRectToRect(srcRect,
215 SkRect::MakeWH(bitmap->width(), bitmap->height()),
216 SkMatrix::kFill_ScaleToFit));
217 if (srcRect.width() != bitmap->width() || srcRect.height() != bitmap->height()) {
218 sampling = SkSamplingOptions(SkFilterMode::kLinear);
219 }
220
221 SkCanvas* canvas = tmpSurface->getCanvas();
222 canvas->save();
223 canvas->concat(m);
224 SkPaint paint;
225 paint.setAlpha(255);
226 paint.setBlendMode(SkBlendMode::kSrc);
John Reck0f284da2021-07-14 14:24:51 -0400227 const bool hasBufferCrop = cropRect.left < cropRect.right && cropRect.top < cropRect.bottom;
228 auto constraint =
229 hasBufferCrop ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint;
230 canvas->drawImageRect(image, imageSrcRect, imageDstRect, sampling, &paint, constraint);
John Reck2abc5492021-05-18 00:34:26 -0400231 canvas->restore();
232
233 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
234 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
235 // 8888 and then convert that into the destination format before giving up.
236 SkBitmap tmpBitmap;
237 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
238 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
239 !tmpBitmap.tryAllocPixels(tmpInfo) || !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
240 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(), bitmap->rowBytes(), 0, 0)) {
241 ALOGW("Unable to convert content into the provided bitmap");
John Reck4d73cb12022-07-27 10:32:52 -0400242 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400243 }
244 }
245
246 bitmap->notifyPixelsChanged();
247
John Reck4d73cb12022-07-27 10:32:52 -0400248 return request->onCopyFinished(CopyResult::Success);
Stan Iliev1a025a72018-09-05 16:35:11 -0400249}
250
251CopyResult Readback::copyHWBitmapInto(Bitmap* hwBitmap, SkBitmap* bitmap) {
252 LOG_ALWAYS_FATAL_IF(!hwBitmap->isHardware());
253
254 Rect srcRect;
ramindani3952ed62021-08-12 15:55:12 +0000255 return copyImageInto(hwBitmap->makeImage(), 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
John Reck76005182021-06-09 22:43:05 -0400278CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, SkBitmap* bitmap) {
279 Rect srcRect;
ramindani3952ed62021-08-12 15:55:12 +0000280 return copyImageInto(image, srcRect, bitmap);
John Reck76005182021-06-09 22:43:05 -0400281}
282
ramindani3952ed62021-08-12 15:55:12 +0000283CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, const Rect& srcRect,
284 SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700285 ATRACE_CALL();
John Reck4d73cb12022-07-27 10:32:52 -0400286 if (!image.get()) {
287 return CopyResult::UnknownError;
288 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400289 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
290 mRenderThread.requireGlContext();
291 } else {
Stan Iliev981afe72019-02-13 14:24:33 -0500292 mRenderThread.requireVkContext();
Stan Iliev1a025a72018-09-05 16:35:11 -0400293 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400294 int imgWidth = image->width();
295 int imgHeight = image->height();
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400296 sk_sp<GrDirectContext> grContext = sk_ref_sp(mRenderThread.getGrContext());
Stan Iliev1a025a72018-09-05 16:35:11 -0400297
Stan Iliev1a025a72018-09-05 16:35:11 -0400298 CopyResult copyResult = CopyResult::UnknownError;
299
300 int displayedWidth = imgWidth, displayedHeight = imgHeight;
Stan Iliev1a025a72018-09-05 16:35:11 -0400301 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);
Stan Iliev1a025a72018-09-05 16:35:11 -0400313 layer.setImage(image);
Kazuhiro Inabaa74d6372020-03-11 00:01:53 +0900314 // Scaling filter is not explicitly set here, because it is done inside copyLayerInfo
315 // after checking the necessity based on the src/dest rect size and the transformation.
Stan Iliev1a025a72018-09-05 16:35:11 -0400316 if (copyLayerInto(&layer, &skiaSrcRect, &skiaDestRect, bitmap)) {
317 copyResult = CopyResult::Success;
318 }
319
320 return copyResult;
321}
322
323bool Readback::copyLayerInto(Layer* layer, const SkRect* srcRect, const SkRect* dstRect,
324 SkBitmap* bitmap) {
Derek Sollenbergerefcbd6d2021-03-19 12:10:28 -0400325 /* This intermediate surface is present to work around limitations that LayerDrawable expects
326 * to render into a GPU backed canvas. Additionally, the offscreen buffer solution works around
327 * a scaling issue (b/62262733) that was encountered when sampling from an EGLImage into a
328 * software buffer.
Stan Iliev1a025a72018-09-05 16:35:11 -0400329 */
330 sk_sp<SkSurface> tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500331 SkBudgeted::kYes, bitmap->info(), 0,
332 kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400333
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400334 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
335 // attempt to do the intermediate rendering step in 8888
Stan Iliev1a025a72018-09-05 16:35:11 -0400336 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400337 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
Stan Iliev1a025a72018-09-05 16:35:11 -0400338 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500339 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400340 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400341 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
Stan Iliev1a025a72018-09-05 16:35:11 -0400342 return false;
343 }
344 }
345
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400346 if (!skiapipeline::LayerDrawable::DrawLayer(mRenderThread.getGrContext(),
347 tmpSurface->getCanvas(), layer, srcRect, dstRect,
348 false)) {
349 ALOGW("Unable to draw content from GPU into the provided bitmap");
350 return false;
351 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400352
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400353 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
354 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
355 // 8888 and then convert that into the destination format before giving up.
356 SkBitmap tmpBitmap;
357 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
358 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
359 !tmpBitmap.tryAllocPixels(tmpInfo) ||
360 !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
361 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(),
362 bitmap->rowBytes(), 0, 0)) {
363 ALOGW("Unable to convert content into the provided bitmap");
364 return false;
Stan Iliev1a025a72018-09-05 16:35:11 -0400365 }
366 }
367
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400368 bitmap->notifyPixelsChanged();
369 return true;
Stan Iliev1a025a72018-09-05 16:35:11 -0400370}
371
372} /* namespace uirenderer */
373} /* namespace android */