blob: 62e950fb48f03ba368723d9a2e8eb091c04a69dc [file] [log] [blame]
Romain Guy3b748a42013-04-17 18:54:38 -07001/*
2 * Copyright (C) 2013 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#define LOG_TAG "AssetAtlasService"
18
19#include "jni.h"
20#include "JNIHelp.h"
21
22#include <android_view_GraphicBuffer.h>
23
24#include <GLES2/gl2.h>
25#include <GLES2/gl2ext.h>
26
27#include <EGL/egl.h>
28#include <EGL/eglext.h>
29
30#include <SkCanvas.h>
31#include <SkBitmap.h>
32
33namespace android {
34
35// ----------------------------------------------------------------------------
36// Defines
37// ----------------------------------------------------------------------------
38
39// Defines how long to wait for the GPU when uploading the atlas
40// This timeout is defined in nanoseconds (see EGL_KHR_fence_sync extension)
41#define FENCE_TIMEOUT 2000000000
42
43// ----------------------------------------------------------------------------
44// JNI Helpers
45// ----------------------------------------------------------------------------
46
47static struct {
48 jfieldID mFinalizer;
49 jfieldID mNativeCanvas;
50} gCanvasClassInfo;
51
52static struct {
53 jfieldID mNativeCanvas;
54} gCanvasFinalizerClassInfo;
55
56#define GET_INT(object, field) \
57 env->GetIntField(object, field)
58
59#define SET_INT(object, field, value) \
60 env->SetIntField(object, field, value)
61
62// ----------------------------------------------------------------------------
63// Canvas management
64// ----------------------------------------------------------------------------
65
66static inline void swapCanvasPtr(JNIEnv* env, jobject canvasObj, SkCanvas* newCanvas) {
67 jobject canvasFinalizerObj = env->GetObjectField(canvasObj, gCanvasClassInfo.mFinalizer);
68 SkCanvas* previousCanvas = reinterpret_cast<SkCanvas*>(
69 GET_INT(canvasObj, gCanvasClassInfo.mNativeCanvas));
70 SET_INT(canvasObj, gCanvasClassInfo.mNativeCanvas, (int) newCanvas);
71 SET_INT(canvasFinalizerObj, gCanvasFinalizerClassInfo.mNativeCanvas, (int) newCanvas);
72 SkSafeUnref(previousCanvas);
73}
74
75static SkBitmap* com_android_server_AssetAtlasService_acquireCanvas(JNIEnv* env, jobject,
76 jobject canvas, jint width, jint height) {
77
78 SkBitmap* bitmap = new SkBitmap;
79 bitmap->setConfig(SkBitmap::kARGB_8888_Config, width, height);
80 bitmap->allocPixels();
81 bitmap->eraseColor(0);
82
83 SkCanvas* nativeCanvas = SkNEW_ARGS(SkCanvas, (*bitmap));
84 swapCanvasPtr(env, canvas, nativeCanvas);
85
86 return bitmap;
87}
88
89static void com_android_server_AssetAtlasService_releaseCanvas(JNIEnv* env, jobject,
90 jobject canvas, SkBitmap* bitmap) {
91
92 SkCanvas* nativeCanvas = SkNEW(SkCanvas);
93 swapCanvasPtr(env, canvas, nativeCanvas);
94
95 delete bitmap;
96}
97
98#define CLEANUP_GL_AND_RETURN(result) \
99 if (fence != EGL_NO_SYNC_KHR) eglDestroySyncKHR(display, fence); \
100 if (image) eglDestroyImageKHR(display, image); \
101 if (texture) glDeleteTextures(1, &texture); \
102 if (surface != EGL_NO_SURFACE) eglDestroySurface(display, surface); \
103 if (context != EGL_NO_CONTEXT) eglDestroyContext(display, context); \
104 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); \
105 eglReleaseThread(); \
106 eglTerminate(display); \
107 return result;
108
109static jboolean com_android_server_AssetAtlasService_upload(JNIEnv* env, jobject,
110 jobject graphicBuffer, SkBitmap* bitmap) {
111
112 // The goal of this method is to copy the bitmap into the GraphicBuffer
113 // using the GPU to swizzle the texture content
114 sp<GraphicBuffer> buffer(graphicBufferForJavaObject(env, graphicBuffer));
115
116 if (buffer != NULL) {
117 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
118 if (display == EGL_NO_DISPLAY) return false;
119
120 EGLint major;
121 EGLint minor;
122 if (!eglInitialize(display, &major, &minor)) {
123 ALOGW("Could not initialize EGL");
124 return false;
125 }
126
127 // We're going to use a 1x1 pbuffer surface later on
128 // The configuration doesn't really matter for what we're trying to do
129 EGLint configAttrs[] = {
130 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
131 EGL_RED_SIZE, 8,
132 EGL_GREEN_SIZE, 8,
133 EGL_BLUE_SIZE, 8,
134 EGL_ALPHA_SIZE, 0,
135 EGL_DEPTH_SIZE, 0,
136 EGL_STENCIL_SIZE, 0,
137 EGL_NONE
138 };
139 EGLConfig configs[1];
140 EGLint configCount;
141 if (!eglChooseConfig(display, configAttrs, configs, 1, &configCount)) {
142 ALOGW("Could not select EGL configuration");
143 eglReleaseThread();
144 eglTerminate(display);
145 return false;
146 }
147 if (configCount <= 0) {
148 ALOGW("Could not find EGL configuration");
149 eglReleaseThread();
150 eglTerminate(display);
151 return false;
152 }
153
154 // These objects are initialized below but the default "null"
155 // values are used to cleanup properly at any point in the
156 // initialization sequence
157 GLuint texture = 0;
158 EGLImageKHR image = EGL_NO_IMAGE_KHR;
159 EGLSurface surface = EGL_NO_SURFACE;
160 EGLSyncKHR fence = EGL_NO_SYNC_KHR;
161
162 EGLint attrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
163 EGLContext context = eglCreateContext(display, configs[0], EGL_NO_CONTEXT, attrs);
164 if (context == EGL_NO_CONTEXT) {
165 ALOGW("Could not create EGL context");
166 CLEANUP_GL_AND_RETURN(false);
167 }
168
169 // Create the 1x1 pbuffer
170 EGLint surfaceAttrs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE };
171 surface = eglCreatePbufferSurface(display, configs[0], surfaceAttrs);
172 if (surface == EGL_NO_SURFACE) {
173 ALOGW("Could not create EGL surface");
174 CLEANUP_GL_AND_RETURN(false);
175 }
176
177 if (!eglMakeCurrent(display, surface, surface, context)) {
178 ALOGW("Could not change current EGL context");
179 CLEANUP_GL_AND_RETURN(false);
180 }
181
182 // We use an EGLImage to access the content of the GraphicBuffer
183 // The EGL image is later bound to a 2D texture
184 EGLClientBuffer clientBuffer = (EGLClientBuffer) buffer->getNativeBuffer();
185 EGLint imageAttrs[] = { EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE };
186 image = eglCreateImageKHR(display, EGL_NO_CONTEXT,
187 EGL_NATIVE_BUFFER_ANDROID, clientBuffer, imageAttrs);
188 if (image == EGL_NO_IMAGE_KHR) {
189 ALOGW("Could not create EGL image");
190 CLEANUP_GL_AND_RETURN(false);
191 }
192
193 glGenTextures(1, &texture);
194 glBindTexture(GL_TEXTURE_2D, texture);
195 glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image);
196 if (glGetError() != GL_NO_ERROR) {
197 ALOGW("Could not create/bind texture");
198 CLEANUP_GL_AND_RETURN(false);
199 }
200
201 // Upload the content of the bitmap in the GraphicBuffer
202 glPixelStorei(GL_UNPACK_ALIGNMENT, bitmap->bytesPerPixel());
203 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bitmap->width(), bitmap->height(),
204 GL_RGBA, GL_UNSIGNED_BYTE, bitmap->getPixels());
205 if (glGetError() != GL_NO_ERROR) {
206 ALOGW("Could not upload to texture");
207 CLEANUP_GL_AND_RETURN(false);
208 }
209
210 // The fence is used to wait for the texture upload to finish
211 // properly. We cannot rely on glFlush() and glFinish() as
212 // some drivers completely ignore these API calls
213 fence = eglCreateSyncKHR(display, EGL_SYNC_FENCE_KHR, NULL);
214 if (fence == EGL_NO_SYNC_KHR) {
215 ALOGW("Could not create sync fence %#x", eglGetError());
216 CLEANUP_GL_AND_RETURN(false);
217 }
218
219 // The flag EGL_SYNC_FLUSH_COMMANDS_BIT_KHR will trigger a
220 // pipeline flush (similar to what a glFlush() would do.)
221 EGLint waitStatus = eglClientWaitSyncKHR(display, fence,
222 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, FENCE_TIMEOUT);
223 if (waitStatus != EGL_CONDITION_SATISFIED_KHR) {
224 ALOGW("Failed to wait for the fence %#x", eglGetError());
225 CLEANUP_GL_AND_RETURN(false);
226 }
227
228 CLEANUP_GL_AND_RETURN(true);
229 }
230
231 return false;
232}
233
234// ----------------------------------------------------------------------------
235// JNI Glue
236// ----------------------------------------------------------------------------
237
238#define FIND_CLASS(var, className) \
239 var = env->FindClass(className); \
240 LOG_FATAL_IF(! var, "Unable to find class " className);
241
242#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \
243 var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \
244 LOG_FATAL_IF(! var, "Unable to find field " fieldName);
245
246const char* const kClassPathName = "com/android/server/AssetAtlasService";
247
248static JNINativeMethod gMethods[] = {
249 { "nAcquireAtlasCanvas", "(Landroid/graphics/Canvas;II)I",
250 (void*) com_android_server_AssetAtlasService_acquireCanvas },
251 { "nReleaseAtlasCanvas", "(Landroid/graphics/Canvas;I)V",
252 (void*) com_android_server_AssetAtlasService_releaseCanvas },
253 { "nUploadAtlas", "(Landroid/view/GraphicBuffer;I)Z",
254 (void*) com_android_server_AssetAtlasService_upload },
255};
256
257int register_android_server_AssetAtlasService(JNIEnv* env) {
258 jclass clazz;
259
260 FIND_CLASS(clazz, "android/graphics/Canvas");
261 GET_FIELD_ID(gCanvasClassInfo.mFinalizer, clazz, "mFinalizer",
262 "Landroid/graphics/Canvas$CanvasFinalizer;");
263 GET_FIELD_ID(gCanvasClassInfo.mNativeCanvas, clazz, "mNativeCanvas", "I");
264
265 FIND_CLASS(clazz, "android/graphics/Canvas$CanvasFinalizer");
266 GET_FIELD_ID(gCanvasFinalizerClassInfo.mNativeCanvas, clazz, "mNativeCanvas", "I");
267
268 return jniRegisterNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods));
269}
270
271};