1 /*
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
19 #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>
31 #include "include/gpu/GpuTypes.h" // from Skia
32 #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"
45 #include "utils/Color.h"
46 #include "utils/MathUtils.h"
47 #include "utils/NdkUtils.h"
48
49 using namespace android::uirenderer::renderthread;
50
51 namespace android {
52 namespace uirenderer {
53
54 #define ARECT_ARGS(r) float((r).left), float((r).top), float((r).right), float((r).bottom)
55
copySurfaceInto(ANativeWindow * window,const std::shared_ptr<CopyRequest> & request)56 void Readback::copySurfaceInto(ANativeWindow* window, const std::shared_ptr<CopyRequest>& request) {
57 ATRACE_CALL();
58 // Setup the source
59 AHardwareBuffer* rawSourceBuffer;
60 int rawSourceFence;
61 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?");
69 return request->onCopyFinished(CopyResult::SourceInvalid);
70 }
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);
76 return request->onCopyFinished(CopyResult::SourceInvalid);
77 }
78 if (rawSourceBuffer == nullptr) {
79 ALOGW("Surface doesn't have any previously queued frames, nothing to readback from");
80 return request->onCopyFinished(CopyResult::SourceEmpty);
81 }
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");
87 return request->onCopyFinished(CopyResult::SourceInvalid);
88 }
89
90 {
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 }
96 }
97
98 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));
110 sk_sp<SkImage> image =
111 SkImage::MakeFromAHardwareBuffer(sourceBuffer.get(), kPremul_SkAlphaType, colorSpace);
112
113 if (!image.get()) {
114 return request->onCopyFinished(CopyResult::UnknownError);
115 }
116
117 sk_sp<GrDirectContext> grContext = mRenderThread.requireGrContext();
118
119 SkRect srcRect = request->srcRect.toSkRect();
120
121 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);
149 }
150
151 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)) {
167 return request->onCopyFinished(CopyResult::UnknownError);
168 }
169 }
170
171 SkBitmap skBitmap = request->getDestinationBitmap(srcRect.width(), srcRect.height());
172 SkBitmap* bitmap = &skBitmap;
173 sk_sp<SkSurface> tmpSurface =
174 SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), skgpu::Budgeted::kYes,
175 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);
181 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
182 skgpu::Budgeted::kYes,
183 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
184 if (!tmpSurface.get()) {
185 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
186 return request->onCopyFinished(CopyResult::UnknownError);
187 }
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;
212 const SkRect imageDstRect = SkRect::Make(imageWH);
213 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);
242 const bool hasBufferCrop = cropRect.left < cropRect.right && cropRect.top < cropRect.bottom;
243 auto constraint =
244 hasBufferCrop ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint;
245
246 static constexpr float kMaxLuminanceNits = 4000.f;
247 tonemapPaint(image->imageInfo(), canvas->imageInfo(), kMaxLuminanceNits, paint);
248
249 canvas->drawImageRect(image, imageSrcRect, imageDstRect, sampling, &paint, constraint);
250 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");
261 return request->onCopyFinished(CopyResult::UnknownError);
262 }
263 }
264
265 bitmap->notifyPixelsChanged();
266
267 return request->onCopyFinished(CopyResult::Success);
268 }
269
copyHWBitmapInto(Bitmap * hwBitmap,SkBitmap * bitmap)270 CopyResult Readback::copyHWBitmapInto(Bitmap* hwBitmap, SkBitmap* bitmap) {
271 LOG_ALWAYS_FATAL_IF(!hwBitmap->isHardware());
272
273 Rect srcRect;
274 return copyImageInto(hwBitmap->makeImage(), srcRect, bitmap);
275 }
276
copyLayerInto(DeferredLayerUpdater * deferredLayer,SkBitmap * bitmap)277 CopyResult Readback::copyLayerInto(DeferredLayerUpdater* deferredLayer, SkBitmap* bitmap) {
278 ATRACE_CALL();
279 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
copyImageInto(const sk_sp<SkImage> & image,SkBitmap * bitmap)297 CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, SkBitmap* bitmap) {
298 Rect srcRect;
299 return copyImageInto(image, srcRect, bitmap);
300 }
301
copyImageInto(const sk_sp<SkImage> & image,const Rect & srcRect,SkBitmap * bitmap)302 CopyResult Readback::copyImageInto(const sk_sp<SkImage>& image, const Rect& srcRect,
303 SkBitmap* bitmap) {
304 ATRACE_CALL();
305 if (!image.get()) {
306 return CopyResult::UnknownError;
307 }
308 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
309 mRenderThread.requireGlContext();
310 } else {
311 mRenderThread.requireVkContext();
312 }
313 int imgWidth = image->width();
314 int imgHeight = image->height();
315 sk_sp<GrDirectContext> grContext = sk_ref_sp(mRenderThread.getGrContext());
316
317 CopyResult copyResult = CopyResult::UnknownError;
318
319 int displayedWidth = imgWidth, displayedHeight = imgHeight;
320 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
330 Layer layer(mRenderThread.renderState(), nullptr, 255, SkBlendMode::kSrc);
331 layer.setSize(displayedWidth, displayedHeight);
332 layer.setImage(image);
333 // 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.
335 if (copyLayerInto(&layer, &skiaSrcRect, &skiaDestRect, bitmap)) {
336 copyResult = CopyResult::Success;
337 }
338
339 return copyResult;
340 }
341
copyLayerInto(Layer * layer,const SkRect * srcRect,const SkRect * dstRect,SkBitmap * bitmap)342 bool Readback::copyLayerInto(Layer* layer, const SkRect* srcRect, const SkRect* dstRect,
343 SkBitmap* bitmap) {
344 /* 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.
348 */
349 sk_sp<SkSurface> tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
350 skgpu::Budgeted::kYes,
351 bitmap->info(),
352 0,
353 kTopLeft_GrSurfaceOrigin, nullptr);
354
355 // 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
357 if (!tmpSurface.get()) {
358 SkImageInfo tmpInfo = bitmap->info().makeColorType(SkColorType::kN32_SkColorType);
359 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
360 skgpu::Budgeted::kYes,
361 tmpInfo, 0, kTopLeft_GrSurfaceOrigin, nullptr);
362 if (!tmpSurface.get()) {
363 ALOGW("Unable to generate GPU buffer in a format compatible with the provided bitmap");
364 return false;
365 }
366 }
367
368 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 }
374
375 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;
387 }
388 }
389
390 bitmap->notifyPixelsChanged();
391 return true;
392 }
393
394 } /* namespace uirenderer */
395 } /* namespace android */
396