blob: b9860ada18fcc65220a5b2463290fcb7210f6246 [file] [log] [blame]
John Recke170fb62018-05-07 08:12:07 -07001/*
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 "HardwareBitmapUploader.h"
18
19#include "hwui/Bitmap.h"
20#include "renderthread/EglManager.h"
21#include "thread/ThreadBase.h"
22#include "utils/TimeUtils.h"
23
24#include <EGL/eglext.h>
25#include <GLES2/gl2.h>
26#include <GLES2/gl2ext.h>
27#include <GLES3/gl3.h>
28#include <SkCanvas.h>
29#include <utils/GLUtils.h>
30#include <utils/Trace.h>
31#include <utils/TraceUtils.h>
32#include <thread>
33
34namespace android::uirenderer {
35
36static std::mutex sLock{};
37static ThreadBase* sUploadThread = nullptr;
38static renderthread::EglManager sEglManager;
39static int sPendingUploads = 0;
40static nsecs_t sLastUpload = 0;
41
42static bool shouldTimeOutLocked() {
43 nsecs_t durationSince = systemTime() - sLastUpload;
44 return durationSince > 2000_ms;
45}
46
47static void checkIdleTimeout() {
John Reckd1a491f2018-09-17 15:01:58 -070048 std::lock_guard _lock{sLock};
John Recke170fb62018-05-07 08:12:07 -070049 if (sPendingUploads == 0 && shouldTimeOutLocked()) {
50 sEglManager.destroy();
51 } else {
52 sUploadThread->queue().postDelayed(5000_ms, checkIdleTimeout);
53 }
54}
55
56static void beginUpload() {
John Reckd1a491f2018-09-17 15:01:58 -070057 std::lock_guard _lock{sLock};
John Recke170fb62018-05-07 08:12:07 -070058 sPendingUploads++;
59
60 if (!sUploadThread) {
61 sUploadThread = new ThreadBase{};
62 }
63
64 if (!sUploadThread->isRunning()) {
65 sUploadThread->start("GrallocUploadThread");
66 }
67
68 if (!sEglManager.hasEglContext()) {
69 sUploadThread->queue().runSync([]() {
70 sEglManager.initialize();
71 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
72 });
73 sUploadThread->queue().postDelayed(5000_ms, checkIdleTimeout);
74 }
75}
76
77static void endUpload() {
John Reckd1a491f2018-09-17 15:01:58 -070078 std::lock_guard _lock{sLock};
John Recke170fb62018-05-07 08:12:07 -070079 sPendingUploads--;
80 sLastUpload = systemTime();
81}
82
83static EGLDisplay getUploadEglDisplay() {
John Reckd1a491f2018-09-17 15:01:58 -070084 std::lock_guard _lock{sLock};
John Recke170fb62018-05-07 08:12:07 -070085 LOG_ALWAYS_FATAL_IF(!sEglManager.hasEglContext(), "Forgot to begin an upload?");
86 return sEglManager.eglDisplay();
87}
88
89static bool hasFP16Support() {
90 static std::once_flag sOnce;
91 static bool hasFP16Support = false;
92
93 // Gralloc shouldn't let us create a USAGE_HW_TEXTURE if GLES is unable to consume it, so
94 // we don't need to double-check the GLES version/extension.
95 std::call_once(sOnce, []() {
96 sp<GraphicBuffer> buffer = new GraphicBuffer(1, 1, PIXEL_FORMAT_RGBA_FP16,
97 GraphicBuffer::USAGE_HW_TEXTURE |
98 GraphicBuffer::USAGE_SW_WRITE_NEVER |
99 GraphicBuffer::USAGE_SW_READ_NEVER,
100 "tempFp16Buffer");
101 status_t error = buffer->initCheck();
102 hasFP16Support = !error;
103 });
104
105 return hasFP16Support;
106}
107
108#define FENCE_TIMEOUT 2000000000
109
John Recke170fb62018-05-07 08:12:07 -0700110struct FormatInfo {
111 PixelFormat pixelFormat;
112 GLint format, type;
113 bool isSupported = false;
114 bool valid = true;
115};
116
117static FormatInfo determineFormat(const SkBitmap& skBitmap) {
118 FormatInfo formatInfo;
119 // TODO: add support for linear blending (when ANDROID_ENABLE_LINEAR_BLENDING is defined)
120 switch (skBitmap.info().colorType()) {
121 case kRGBA_8888_SkColorType:
122 formatInfo.isSupported = true;
123 // ARGB_4444 is upconverted to RGBA_8888
124 case kARGB_4444_SkColorType:
125 formatInfo.pixelFormat = PIXEL_FORMAT_RGBA_8888;
126 formatInfo.format = GL_RGBA;
127 formatInfo.type = GL_UNSIGNED_BYTE;
128 break;
129 case kRGBA_F16_SkColorType:
130 formatInfo.isSupported = hasFP16Support();
131 if (formatInfo.isSupported) {
132 formatInfo.type = GL_HALF_FLOAT;
133 formatInfo.pixelFormat = PIXEL_FORMAT_RGBA_FP16;
134 } else {
135 formatInfo.type = GL_UNSIGNED_BYTE;
136 formatInfo.pixelFormat = PIXEL_FORMAT_RGBA_8888;
137 }
138 formatInfo.format = GL_RGBA;
139 break;
140 case kRGB_565_SkColorType:
141 formatInfo.isSupported = true;
142 formatInfo.pixelFormat = PIXEL_FORMAT_RGB_565;
143 formatInfo.format = GL_RGB;
144 formatInfo.type = GL_UNSIGNED_SHORT_5_6_5;
145 break;
146 case kGray_8_SkColorType:
147 formatInfo.isSupported = true;
148 formatInfo.pixelFormat = PIXEL_FORMAT_RGBA_8888;
149 formatInfo.format = GL_LUMINANCE;
150 formatInfo.type = GL_UNSIGNED_BYTE;
151 break;
152 default:
153 ALOGW("unable to create hardware bitmap of colortype: %d", skBitmap.info().colorType());
154 formatInfo.valid = false;
155 }
156 return formatInfo;
157}
158
159static SkBitmap makeHwCompatible(const FormatInfo& format, const SkBitmap& source) {
160 if (format.isSupported) {
161 return source;
162 } else {
163 SkBitmap bitmap;
164 const SkImageInfo& info = source.info();
165 bitmap.allocPixels(
166 SkImageInfo::MakeN32(info.width(), info.height(), info.alphaType(), nullptr));
167 bitmap.eraseColor(0);
168 if (info.colorType() == kRGBA_F16_SkColorType) {
169 // Drawing RGBA_F16 onto ARGB_8888 is not supported
170 source.readPixels(bitmap.info().makeColorSpace(SkColorSpace::MakeSRGB()),
171 bitmap.getPixels(), bitmap.rowBytes(), 0, 0);
172 } else {
173 SkCanvas canvas(bitmap);
174 canvas.drawBitmap(source, 0.0f, 0.0f, nullptr);
175 }
176 return bitmap;
177 }
178}
179
180class ScopedUploadRequest {
181public:
182 ScopedUploadRequest() { beginUpload(); }
183 ~ScopedUploadRequest() { endUpload(); }
184};
185
186sk_sp<Bitmap> HardwareBitmapUploader::allocateHardwareBitmap(const SkBitmap& sourceBitmap) {
187 ATRACE_CALL();
188
189 FormatInfo format = determineFormat(sourceBitmap);
190 if (!format.valid) {
191 return nullptr;
192 }
193
194 ScopedUploadRequest _uploadRequest{};
195
196 SkBitmap bitmap = makeHwCompatible(format, sourceBitmap);
197 sp<GraphicBuffer> buffer = new GraphicBuffer(
198 static_cast<uint32_t>(bitmap.width()), static_cast<uint32_t>(bitmap.height()),
199 format.pixelFormat,
200 GraphicBuffer::USAGE_HW_TEXTURE | GraphicBuffer::USAGE_SW_WRITE_NEVER |
201 GraphicBuffer::USAGE_SW_READ_NEVER,
202 std::string("Bitmap::allocateSkiaHardwareBitmap pid [") + std::to_string(getpid()) +
203 "]");
204
205 status_t error = buffer->initCheck();
206 if (error < 0) {
207 ALOGW("createGraphicBuffer() failed in GraphicBuffer.create()");
208 return nullptr;
209 }
210
211 EGLDisplay display = getUploadEglDisplay();
212
213 LOG_ALWAYS_FATAL_IF(display == EGL_NO_DISPLAY, "Failed to get EGL_DEFAULT_DISPLAY! err=%s",
214 uirenderer::renderthread::EglManager::eglErrorString());
215 // We use an EGLImage to access the content of the GraphicBuffer
216 // The EGL image is later bound to a 2D texture
217 EGLClientBuffer clientBuffer = (EGLClientBuffer)buffer->getNativeBuffer();
218 AutoEglImage autoImage(display, clientBuffer);
219 if (autoImage.image == EGL_NO_IMAGE_KHR) {
220 ALOGW("Could not create EGL image, err =%s",
221 uirenderer::renderthread::EglManager::eglErrorString());
222 return nullptr;
223 }
224
225 {
226 ATRACE_FORMAT("CPU -> gralloc transfer (%dx%d)", bitmap.width(), bitmap.height());
227 EGLSyncKHR fence = sUploadThread->queue().runSync([&]() -> EGLSyncKHR {
228 AutoSkiaGlTexture glTexture;
229 glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, autoImage.image);
230 GL_CHECKPOINT(MODERATE);
231
232 // glTexSubImage2D is synchronous in sense that it memcpy() from pointer that we
233 // provide.
234 // But asynchronous in sense that driver may upload texture onto hardware buffer when we
235 // first
236 // use it in drawing
237 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bitmap.width(), bitmap.height(), format.format,
238 format.type, bitmap.getPixels());
239 GL_CHECKPOINT(MODERATE);
240
241 EGLSyncKHR uploadFence =
242 eglCreateSyncKHR(eglGetCurrentDisplay(), EGL_SYNC_FENCE_KHR, NULL);
243 LOG_ALWAYS_FATAL_IF(uploadFence == EGL_NO_SYNC_KHR, "Could not create sync fence %#x",
244 eglGetError());
245 glFlush();
246 return uploadFence;
247 });
248
249 EGLint waitStatus = eglClientWaitSyncKHR(display, fence, 0, FENCE_TIMEOUT);
250 LOG_ALWAYS_FATAL_IF(waitStatus != EGL_CONDITION_SATISFIED_KHR,
251 "Failed to wait for the fence %#x", eglGetError());
252
253 eglDestroySyncKHR(display, fence);
254 }
255
Derek Sollenbergere2169482018-11-20 10:57:20 -0500256 return Bitmap::createFrom(buffer.get(), bitmap.refColorSpace(), bitmap.alphaType(),
257 Bitmap::computePalette(bitmap));
John Recke170fb62018-05-07 08:12:07 -0700258}
259
Chris Blume7b8a8082018-11-30 15:51:58 -0800260} // namespace android::uirenderer