blob: 045de35c1d97a8604599095d1721943003d82e1d [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
Kevin Lubick1175dc02022-02-28 12:41:27 -050019#include <SkBitmap.h>
20#include <SkBlendMode.h>
21#include <SkCanvas.h>
22#include <SkColorSpace.h>
23#include <SkImage.h>
24#include <SkImageInfo.h>
25#include <SkMatrix.h>
26#include <SkPaint.h>
27#include <SkRect.h>
28#include <SkRefCnt.h>
29#include <SkSamplingOptions.h>
30#include <SkSurface.h>
Kevin Lubick8099b672023-01-09 14:48:45 +000031#include "include/gpu/GpuTypes.h" // from Skia
Alec Mouri97326742022-11-04 01:32:24 +000032#include <gui/TraceUtils.h>
33#include <private/android/AHardwareBufferHelpers.h>
34#include <shaders/shaders.h>
35#include <sync/sync.h>
36#include <system/window.h>
37
38#include "DeferredLayerUpdater.h"
39#include "Properties.h"
40#include "Tonemapper.h"
41#include "hwui/Bitmap.h"
42#include "pipeline/skia/LayerDrawable.h"
43#include "renderthread/EglManager.h"
44#include "renderthread/VulkanManager.h"
Stan Iliev1a025a72018-09-05 16:35:11 -040045#include "utils/Color.h"
46#include "utils/MathUtils.h"
Alec Mouri45238012020-01-29 11:04:40 -080047#include "utils/NdkUtils.h"
Stan Iliev1a025a72018-09-05 16:35:11 -040048
49using namespace android::uirenderer::renderthread;
50
51namespace android {
52namespace uirenderer {
53
John Reck2abc5492021-05-18 00:34:26 -040054#define ARECT_ARGS(r) float((r).left), float((r).top), float((r).right), float((r).bottom)
55
John Reck4d73cb12022-07-27 10:32:52 -040056void Readback::copySurfaceInto(ANativeWindow* window, const std::shared_ptr<CopyRequest>& request) {
Stan Iliev1a025a72018-09-05 16:35:11 -040057 ATRACE_CALL();
58 // Setup the source
Alec Mouri8a82b142019-12-17 09:41:48 -080059 AHardwareBuffer* rawSourceBuffer;
60 int rawSourceFence;
John Reck2abc5492021-05-18 00:34:26 -040061 ARect cropRect;
62 uint32_t windowTransform;
63 status_t err = ANativeWindow_getLastQueuedBuffer2(window, &rawSourceBuffer, &rawSourceFence,
64 &cropRect, &windowTransform);
65 base::unique_fd sourceFence(rawSourceFence);
66 // Really this shouldn't ever happen, but better safe than sorry.
67 if (err == UNKNOWN_TRANSACTION) {
68 ALOGW("Readback failed to ANativeWindow_getLastQueuedBuffer2 - who are we talking to?");
John Reck4d73cb12022-07-27 10:32:52 -040069 return request->onCopyFinished(CopyResult::SourceInvalid);
John Reck2abc5492021-05-18 00:34:26 -040070 }
71 ALOGV("Using new path, cropRect=" RECT_STRING ", transform=%x", ARECT_ARGS(cropRect),
72 windowTransform);
73
74 if (err != NO_ERROR) {
75 ALOGW("Failed to get last queued buffer, error = %d", err);
John Reck4d73cb12022-07-27 10:32:52 -040076 return request->onCopyFinished(CopyResult::SourceInvalid);
John Reck2abc5492021-05-18 00:34:26 -040077 }
78 if (rawSourceBuffer == nullptr) {
79 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
John Reck4d73cb12022-07-27 10:32:52 -040080 return request->onCopyFinished(CopyResult::SourceEmpty);
John Reck2abc5492021-05-18 00:34:26 -040081 }
82 UniqueAHardwareBuffer sourceBuffer{rawSourceBuffer};
83 AHardwareBuffer_Desc description;
84 AHardwareBuffer_describe(sourceBuffer.get(), &description);
85 if (description.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) {
86 ALOGW("Surface is protected, unable to copy from it");
John Reck4d73cb12022-07-27 10:32:52 -040087 return request->onCopyFinished(CopyResult::SourceInvalid);
John Reck2abc5492021-05-18 00:34:26 -040088 }
89
John Reck4d73cb12022-07-27 10:32:52 -040090 {
91 ATRACE_NAME("sync_wait");
92 if (sourceFence != -1 && sync_wait(sourceFence.get(), 500 /* ms */) != NO_ERROR) {
93 ALOGE("Timeout (500ms) exceeded waiting for buffer fence, abandoning readback attempt");
94 return request->onCopyFinished(CopyResult::Timeout);
95 }
John Reck2abc5492021-05-18 00:34:26 -040096 }
97
Alec Mouri97326742022-11-04 01:32:24 +000098 int32_t dataspace = ANativeWindow_getBuffersDataSpace(window);
99
100 // If the application is not updating the Surface themselves, e.g., another
101 // process is producing buffers for the application to display, then
102 // ANativeWindow_getBuffersDataSpace will return an unknown answer, so grab
103 // the dataspace from buffer metadata instead, if it exists.
104 if (dataspace == 0) {
105 dataspace = AHardwareBuffer_getDataSpace(sourceBuffer.get());
106 }
107
108 sk_sp<SkColorSpace> colorSpace =
109 DataSpaceToColorSpace(static_cast<android_dataspace>(dataspace));
John Reck2abc5492021-05-18 00:34:26 -0400110 sk_sp<SkImage> image =
111 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
112
113 if (!image.get()) {
John Reck4d73cb12022-07-27 10:32:52 -0400114 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400115 }
116
117 sk_sp<GrDirectContext> grContext = mRenderThread.requireGrContext();
118
John Reck4d73cb12022-07-27 10:32:52 -0400119 SkRect srcRect = request->srcRect.toSkRect();
John Reck2abc5492021-05-18 00:34:26 -0400120
Yiwei Zhang6cf96a52022-07-03 05:53:04 +0000121 SkRect imageSrcRect = SkRect::MakeIWH(description.width, description.height);
122 SkISize imageWH = SkISize::Make(description.width, description.height);
123 if (cropRect.left < cropRect.right && cropRect.top < cropRect.bottom) {
124 imageSrcRect =
125 SkRect::MakeLTRB(cropRect.left, cropRect.top, cropRect.right, cropRect.bottom);
126 imageWH = SkISize::Make(cropRect.right - cropRect.left, cropRect.bottom - cropRect.top);
127
128 // Chroma channels of YUV420 images are subsampled we may need to shrink the crop region by
129 // a whole texel on each side. Since skia still adds its own 0.5 inset, we apply an
130 // additional 0.5 inset. See GLConsumer::computeTransformMatrix for details.
131 float shrinkAmount = 0.0f;
132 switch (description.format) {
133 // Use HAL formats since some AHB formats are only available in vndk
134 case HAL_PIXEL_FORMAT_YCBCR_420_888:
135 case HAL_PIXEL_FORMAT_YV12:
136 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
137 shrinkAmount = 0.5f;
138 break;
139 default:
140 break;
141 }
142
143 // Shrink the crop if it has more than 1-px and differs from the buffer size.
144 if (imageWH.width() > 1 && imageWH.width() < (int32_t)description.width)
145 imageSrcRect = imageSrcRect.makeInset(shrinkAmount, 0);
146
147 if (imageWH.height() > 1 && imageWH.height() < (int32_t)description.height)
148 imageSrcRect = imageSrcRect.makeInset(0, shrinkAmount);
John Reck2abc5492021-05-18 00:34:26 -0400149 }
Yiwei Zhang6cf96a52022-07-03 05:53:04 +0000150
John Reck2abc5492021-05-18 00:34:26 -0400151 ALOGV("imageSrcRect = " RECT_STRING, SK_RECT_ARGS(imageSrcRect));
152
153 // Represents the "logical" width/height of the texture. That is, the dimensions of the buffer
154 // after respecting crop & rotate. flipV/flipH still result in the same width & height
155 // so we can ignore those for this.
156 const SkRect textureRect =
157 (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90)
158 ? SkRect::MakeIWH(imageSrcRect.height(), imageSrcRect.width())
159 : SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
160
161 if (srcRect.isEmpty()) {
162 srcRect = textureRect;
163 } else {
164 ALOGV("intersecting " RECT_STRING " with " RECT_STRING, SK_RECT_ARGS(srcRect),
165 SK_RECT_ARGS(textureRect));
166 if (!srcRect.intersect(textureRect)) {
John Reck4d73cb12022-07-27 10:32:52 -0400167 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400168 }
169 }
170
John Reck4d73cb12022-07-27 10:32:52 -0400171 SkBitmap skBitmap = request->getDestinationBitmap(srcRect.width(), srcRect.height());
172 SkBitmap* bitmap = &skBitmap;
John Reck2abc5492021-05-18 00:34:26 -0400173 sk_sp<SkSurface> tmpSurface =
Kevin Lubick8099b672023-01-09 14:48:45 +0000174 SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), skgpu::Budgeted::kYes,
John Reck2abc5492021-05-18 00:34:26 -0400175 bitmap->info(), 0, kTopLeft_GrSurfaceOrigin, nullptr);
176
177 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
178 // attempt to do the intermediate rendering step in 8888
179 if (!tmpSurface.get()) {
180 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
Kevin Lubick8099b672023-01-09 14:48:45 +0000181 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
182 skgpu::Budgeted::kYes,
John Reck2abc5492021-05-18 00:34:26 -0400183 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
184 if (!tmpSurface.get()) {
185 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
John Reck4d73cb12022-07-27 10:32:52 -0400186 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400187 }
188 }
189
190 /*
191 * The grand ordering of events.
192 * First we apply the buffer's crop, done by using a srcRect of the crop with a dstRect of the
193 * same width/height as the srcRect but with a 0x0 origin
194 *
195 * Second we apply the window transform via a Canvas matrix. Ordering for that is as follows:
196 * 1) FLIP_H
197 * 2) FLIP_V
198 * 3) ROT_90
199 * as per GLConsumer::computeTransformMatrix
200 *
201 * Third we apply the user's supplied cropping & scale to the output by doing a RectToRect
202 * matrix transform from srcRect to {0,0, bitmapWidth, bitmapHeight}
203 *
204 * Finally we're done messing with this bloody thing for hopefully the last time.
205 *
206 * That's a lie since...
207 * TODO: Do all this same stuff for TextureView as it's strictly more correct & easier
208 * to rationalize. And we can fix the 1-px crop bug.
209 */
210
211 SkMatrix m;
Yiwei Zhang6cf96a52022-07-03 05:53:04 +0000212 const SkRect imageDstRect = SkRect::Make(imageWH);
John Reck2abc5492021-05-18 00:34:26 -0400213 const float px = imageDstRect.centerX();
214 const float py = imageDstRect.centerY();
215 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
216 m.postScale(-1.f, 1.f, px, py);
217 }
218 if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
219 m.postScale(1.f, -1.f, px, py);
220 }
221 if (windowTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
222 m.postRotate(90, 0, 0);
223 m.postTranslate(imageDstRect.height(), 0);
224 }
225
226 SkSamplingOptions sampling(SkFilterMode::kNearest);
227 ALOGV("Mapping from " RECT_STRING " to " RECT_STRING, SK_RECT_ARGS(srcRect),
228 SK_RECT_ARGS(SkRect::MakeWH(bitmap->width(), bitmap->height())));
229 m.postConcat(SkMatrix::MakeRectToRect(srcRect,
230 SkRect::MakeWH(bitmap->width(), bitmap->height()),
231 SkMatrix::kFill_ScaleToFit));
232 if (srcRect.width() != bitmap->width() || srcRect.height() != bitmap->height()) {
233 sampling = SkSamplingOptions(SkFilterMode::kLinear);
234 }
235
236 SkCanvas* canvas = tmpSurface->getCanvas();
237 canvas->save();
238 canvas->concat(m);
239 SkPaint paint;
240 paint.setAlpha(255);
241 paint.setBlendMode(SkBlendMode::kSrc);
John Reck0f284da2021-07-14 14:24:51 -0400242 const bool hasBufferCrop = cropRect.left < cropRect.right && cropRect.top < cropRect.bottom;
243 auto constraint =
244 hasBufferCrop ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint;
Alec Mouri97326742022-11-04 01:32:24 +0000245
246 static constexpr float kMaxLuminanceNits = 4000.f;
247 tonemapPaint(image->imageInfo(), canvas->imageInfo(), kMaxLuminanceNits, paint);
248
John Reck0f284da2021-07-14 14:24:51 -0400249 canvas->drawImageRect(image, imageSrcRect, imageDstRect, sampling, &paint, constraint);
John Reck2abc5492021-05-18 00:34:26 -0400250 canvas->restore();
251
252 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
253 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
254 // 8888 and then convert that into the destination format before giving up.
255 SkBitmap tmpBitmap;
256 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
257 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
258 !tmpBitmap.tryAllocPixels(tmpInfo) || !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
259 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(), bitmap->rowBytes(), 0, 0)) {
260 ALOGW("Unable to convert content into the provided bitmap");
John Reck4d73cb12022-07-27 10:32:52 -0400261 return request->onCopyFinished(CopyResult::UnknownError);
John Reck2abc5492021-05-18 00:34:26 -0400262 }
263 }
264
265 bitmap->notifyPixelsChanged();
266
John Reck4d73cb12022-07-27 10:32:52 -0400267 return request->onCopyFinished(CopyResult::Success);
Stan Iliev1a025a72018-09-05 16:35:11 -0400268}
269
270CopyResult Readback::copyHWBitmapInto(Bitmap* hwBitmap, SkBitmap* bitmap) {
271 LOG_ALWAYS_FATAL_IF(!hwBitmap->isHardware());
272
273 Rect srcRect;
ramindani3952ed62021-08-12 15:55:12 +0000274 return copyImageInto(hwBitmap->makeImage(), srcRect, bitmap);
Stan Iliev1a025a72018-09-05 16:35:11 -0400275}
276
277CopyResult Readback::copyLayerInto(DeferredLayerUpdater* deferredLayer, SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700278 ATRACE_CALL();
Stan Iliev1a025a72018-09-05 16:35:11 -0400279 if (!mRenderThread.getGrContext()) {
280 return CopyResult::UnknownError;
281 }
282
283 // acquire most recent buffer for drawing
284 deferredLayer->updateTexImage();
285 deferredLayer->apply();
286 const SkRect dstRect = SkRect::MakeIWH(bitmap->width(), bitmap->height());
287 CopyResult copyResult = CopyResult::UnknownError;
288 Layer* layer = deferredLayer->backingLayer();
289 if (layer) {
290 if (copyLayerInto(layer, nullptr, &dstRect, bitmap)) {
291 copyResult = CopyResult::Success;
292 }
293 }
294 return copyResult;
295}
296
John Reck76005182021-06-09 22:43:05 -0400297CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, SkBitmap* bitmap) {
298 Rect srcRect;
ramindani3952ed62021-08-12 15:55:12 +0000299 return copyImageInto(image, srcRect, bitmap);
John Reck76005182021-06-09 22:43:05 -0400300}
301
ramindani3952ed62021-08-12 15:55:12 +0000302CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, const Rect& srcRect,
303 SkBitmap* bitmap) {
John Reckfbeac3c2019-03-29 11:24:56 -0700304 ATRACE_CALL();
John Reck4d73cb12022-07-27 10:32:52 -0400305 if (!image.get()) {
306 return CopyResult::UnknownError;
307 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400308 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
309 mRenderThread.requireGlContext();
310 } else {
Stan Iliev981afe72019-02-13 14:24:33 -0500311 mRenderThread.requireVkContext();
Stan Iliev1a025a72018-09-05 16:35:11 -0400312 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400313 int imgWidth = image->width();
314 int imgHeight = image->height();
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400315 sk_sp<GrDirectContext> grContext = sk_ref_sp(mRenderThread.getGrContext());
Stan Iliev1a025a72018-09-05 16:35:11 -0400316
Stan Iliev1a025a72018-09-05 16:35:11 -0400317 CopyResult copyResult = CopyResult::UnknownError;
318
319 int displayedWidth = imgWidth, displayedHeight = imgHeight;
Stan Iliev1a025a72018-09-05 16:35:11 -0400320 SkRect skiaDestRect = SkRect::MakeWH(bitmap->width(), bitmap->height());
321 SkRect skiaSrcRect = srcRect.toSkRect();
322 if (skiaSrcRect.isEmpty()) {
323 skiaSrcRect = SkRect::MakeIWH(displayedWidth, displayedHeight);
324 }
325 bool srcNotEmpty = skiaSrcRect.intersect(SkRect::MakeIWH(displayedWidth, displayedHeight));
326 if (!srcNotEmpty) {
327 return copyResult;
328 }
329
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400330 Layer layer(mRenderThread.renderState(), nullptr, 255, SkBlendMode::kSrc);
Stan Iliev1a025a72018-09-05 16:35:11 -0400331 layer.setSize(displayedWidth, displayedHeight);
Stan Iliev1a025a72018-09-05 16:35:11 -0400332 layer.setImage(image);
Kazuhiro Inabaa74d6372020-03-11 00:01:53 +0900333 // Scaling filter is not explicitly set here, because it is done inside copyLayerInfo
334 // after checking the necessity based on the src/dest rect size and the transformation.
Stan Iliev1a025a72018-09-05 16:35:11 -0400335 if (copyLayerInto(&layer, &skiaSrcRect, &skiaDestRect, bitmap)) {
336 copyResult = CopyResult::Success;
337 }
338
339 return copyResult;
340}
341
342bool Readback::copyLayerInto(Layer* layer, const SkRect* srcRect, const SkRect* dstRect,
343 SkBitmap* bitmap) {
Derek Sollenbergerefcbd6d2021-03-19 12:10:28 -0400344 /* This intermediate surface is present to work around limitations that LayerDrawable expects
345 * to render into a GPU backed canvas. Additionally, the offscreen buffer solution works around
346 * a scaling issue (b/62262733) that was encountered when sampling from an EGLImage into a
347 * software buffer.
Stan Iliev1a025a72018-09-05 16:35:11 -0400348 */
349 sk_sp<SkSurface> tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
Kevin Lubick8099b672023-01-09 14:48:45 +0000350 skgpu::Budgeted::kYes,
351 bitmap->info(),
352 0,
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500353 kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400354
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400355 // if we can't generate a GPU surface that matches the destination bitmap (e.g. 565) then we
356 // attempt to do the intermediate rendering step in 8888
Stan Iliev1a025a72018-09-05 16:35:11 -0400357 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400358 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
Kevin Lubick8099b672023-01-09 14:48:45 +0000359 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
360 skgpu::Budgeted::kYes,
Derek Sollenbergerf4795f52019-02-06 13:54:12 -0500361 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
Stan Iliev1a025a72018-09-05 16:35:11 -0400362 if (!tmpSurface.get()) {
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400363 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
Stan Iliev1a025a72018-09-05 16:35:11 -0400364 return false;
365 }
366 }
367
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400368 if (!skiapipeline::LayerDrawable::DrawLayer(mRenderThread.getGrContext(),
369 tmpSurface->getCanvas(), layer, srcRect, dstRect,
370 false)) {
371 ALOGW("Unable to draw content from GPU into the provided bitmap");
372 return false;
373 }
Stan Iliev1a025a72018-09-05 16:35:11 -0400374
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400375 if (!tmpSurface->readPixels(*bitmap, 0, 0)) {
376 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into
377 // 8888 and then convert that into the destination format before giving up.
378 SkBitmap tmpBitmap;
379 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
380 if (bitmap->info().colorType() == SkColorType::kN32_SkColorType ||
381 !tmpBitmap.tryAllocPixels(tmpInfo) ||
382 !tmpSurface->readPixels(tmpBitmap, 0, 0) ||
383 !tmpBitmap.readPixels(bitmap->info(), bitmap->getPixels(),
384 bitmap->rowBytes(), 0, 0)) {
385 ALOGW("Unable to convert content into the provided bitmap");
386 return false;
Stan Iliev1a025a72018-09-05 16:35:11 -0400387 }
388 }
389
Derek Sollenbergerd01b5912018-10-19 15:55:33 -0400390 bitmap->notifyPixelsChanged();
391 return true;
Stan Iliev1a025a72018-09-05 16:35:11 -0400392}
393
394} /* namespace uirenderer */
395} /* namespace android */