android_view_Surface.cpp revision 52a9a10b6b8c7b7a9f97777541841b94d4fd9754
1/*
2 * Copyright (C) 2007 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 "Surface"
18
19#include <stdio.h>
20
21#include "jni.h"
22#include "JNIHelp.h"
23#include "android_os_Parcel.h"
24#include "android/graphics/GraphicsJNI.h"
25
26#include <android_runtime/AndroidRuntime.h>
27#include <android_runtime/android_view_Surface.h>
28#include <android_runtime/android_graphics_SurfaceTexture.h>
29
30#include <binder/Parcel.h>
31
32#include <gui/Surface.h>
33#include <gui/SurfaceControl.h>
34#include <gui/GLConsumer.h>
35
36#include <ui/Rect.h>
37#include <ui/Region.h>
38
39#include <SkCanvas.h>
40#include <SkBitmap.h>
41#include <SkRegion.h>
42
43#include <utils/misc.h>
44#include <utils/Log.h>
45
46#include <ScopedUtfChars.h>
47
48// ----------------------------------------------------------------------------
49
50namespace android {
51
52static const char* const OutOfResourcesException =
53    "android/view/Surface$OutOfResourcesException";
54
55static struct {
56    jclass clazz;
57    jfieldID mNativeObject;
58    jfieldID mLock;
59    jmethodID ctor;
60} gSurfaceClassInfo;
61
62static struct {
63    jfieldID left;
64    jfieldID top;
65    jfieldID right;
66    jfieldID bottom;
67} gRectClassInfo;
68
69static struct {
70    jfieldID mFinalizer;
71    jfieldID mNativeCanvas;
72    jfieldID mSurfaceFormat;
73} gCanvasClassInfo;
74
75static struct {
76    jfieldID mNativeCanvas;
77} gCanvasFinalizerClassInfo;
78
79// ----------------------------------------------------------------------------
80
81// this is just a pointer we use to pass to inc/decStrong
82static const void *sRefBaseOwner;
83
84bool android_view_Surface_isInstanceOf(JNIEnv* env, jobject obj) {
85    return env->IsInstanceOf(obj, gSurfaceClassInfo.clazz);
86}
87
88sp<ANativeWindow> android_view_Surface_getNativeWindow(JNIEnv* env, jobject surfaceObj) {
89    return android_view_Surface_getSurface(env, surfaceObj);
90}
91
92sp<Surface> android_view_Surface_getSurface(JNIEnv* env, jobject surfaceObj) {
93    sp<Surface> sur;
94    jobject lock = env->GetObjectField(surfaceObj,
95            gSurfaceClassInfo.mLock);
96    if (env->MonitorEnter(lock) == JNI_OK) {
97        sur = reinterpret_cast<Surface *>(
98                env->GetIntField(surfaceObj, gSurfaceClassInfo.mNativeObject));
99        env->MonitorExit(lock);
100    }
101    return sur;
102}
103
104jobject android_view_Surface_createFromIGraphicBufferProducer(JNIEnv* env,
105        const sp<IGraphicBufferProducer>& bufferProducer) {
106    if (bufferProducer == NULL) {
107        return NULL;
108    }
109
110    sp<Surface> surface(new Surface(bufferProducer, true));
111    if (surface == NULL) {
112        return NULL;
113    }
114
115    jobject surfaceObj = env->NewObject(gSurfaceClassInfo.clazz, gSurfaceClassInfo.ctor, surface.get());
116    if (surfaceObj == NULL) {
117        if (env->ExceptionCheck()) {
118            ALOGE("Could not create instance of Surface from IGraphicBufferProducer.");
119            LOGE_EX(env);
120            env->ExceptionClear();
121        }
122        return NULL;
123    }
124    surface->incStrong(&sRefBaseOwner);
125    return surfaceObj;
126}
127
128// ----------------------------------------------------------------------------
129
130static inline bool isSurfaceValid(const sp<Surface>& sur) {
131    return Surface::isValid(sur);
132}
133
134// ----------------------------------------------------------------------------
135
136static jint nativeCreateFromSurfaceTexture(JNIEnv* env, jclass clazz,
137        jobject surfaceTextureObj) {
138    sp<IGraphicBufferProducer> producer(SurfaceTexture_getProducer(env, surfaceTextureObj));
139    if (producer == NULL) {
140        jniThrowException(env, "java/lang/IllegalArgumentException",
141                "SurfaceTexture has already been released");
142        return 0;
143    }
144
145    sp<Surface> surface(new Surface(producer, true));
146    if (surface == NULL) {
147        jniThrowException(env, OutOfResourcesException, NULL);
148        return 0;
149    }
150
151    surface->incStrong(&sRefBaseOwner);
152    return int(surface.get());
153}
154
155static void nativeRelease(JNIEnv* env, jclass clazz, jint nativeObject) {
156    sp<Surface> sur(reinterpret_cast<Surface *>(nativeObject));
157    sur->decStrong(&sRefBaseOwner);
158}
159
160static jboolean nativeIsValid(JNIEnv* env, jclass clazz, jint nativeObject) {
161    sp<Surface> sur(reinterpret_cast<Surface *>(nativeObject));
162    return isSurfaceValid(sur) ? JNI_TRUE : JNI_FALSE;
163}
164
165static jboolean nativeIsConsumerRunningBehind(JNIEnv* env, jclass clazz, jint nativeObject) {
166    sp<Surface> sur(reinterpret_cast<Surface *>(nativeObject));
167    if (!isSurfaceValid(sur)) {
168        doThrowIAE(env);
169        return JNI_FALSE;
170    }
171    int value = 0;
172    ANativeWindow* anw = static_cast<ANativeWindow*>(sur.get());
173    anw->query(anw, NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &value);
174    return value;
175}
176
177static inline SkBitmap::Config convertPixelFormat(PixelFormat format) {
178    /* note: if PIXEL_FORMAT_RGBX_8888 means that all alpha bytes are 0xFF, then
179        we can map to SkBitmap::kARGB_8888_Config, and optionally call
180        bitmap.setIsOpaque(true) on the resulting SkBitmap (as an accelerator)
181    */
182    switch (format) {
183    case PIXEL_FORMAT_RGBX_8888:    return SkBitmap::kARGB_8888_Config;
184    case PIXEL_FORMAT_RGBA_8888:    return SkBitmap::kARGB_8888_Config;
185    case PIXEL_FORMAT_RGB_565:      return SkBitmap::kRGB_565_Config;
186    default:                        return SkBitmap::kNo_Config;
187    }
188}
189
190static inline void swapCanvasPtr(JNIEnv* env, jobject canvasObj, SkCanvas* newCanvas) {
191  jobject canvasFinalizerObj = env->GetObjectField(canvasObj, gCanvasClassInfo.mFinalizer);
192  SkCanvas* previousCanvas = reinterpret_cast<SkCanvas*>(
193          env->GetIntField(canvasObj, gCanvasClassInfo.mNativeCanvas));
194  env->SetIntField(canvasObj, gCanvasClassInfo.mNativeCanvas, (int)newCanvas);
195  env->SetIntField(canvasFinalizerObj, gCanvasFinalizerClassInfo.mNativeCanvas, (int)newCanvas);
196  SkSafeUnref(previousCanvas);
197}
198
199static void nativeLockCanvas(JNIEnv* env, jclass clazz,
200        jint nativeObject, jobject canvasObj, jobject dirtyRectObj) {
201    sp<Surface> surface(reinterpret_cast<Surface *>(nativeObject));
202
203    if (!isSurfaceValid(surface)) {
204        doThrowIAE(env);
205        return;
206    }
207
208    Rect dirtyRect;
209    Rect* dirtyRectPtr = NULL;
210
211    if (dirtyRectObj) {
212        dirtyRect.left   = env->GetIntField(dirtyRectObj, gRectClassInfo.left);
213        dirtyRect.top    = env->GetIntField(dirtyRectObj, gRectClassInfo.top);
214        dirtyRect.right  = env->GetIntField(dirtyRectObj, gRectClassInfo.right);
215        dirtyRect.bottom = env->GetIntField(dirtyRectObj, gRectClassInfo.bottom);
216        dirtyRectPtr = &dirtyRect;
217    }
218
219    ANativeWindow_Buffer outBuffer;
220    status_t err = surface->lock(&outBuffer, dirtyRectPtr);
221    if (err < 0) {
222        const char* const exception = (err == NO_MEMORY) ?
223                OutOfResourcesException :
224                "java/lang/IllegalArgumentException";
225        jniThrowException(env, exception, NULL);
226        return;
227    }
228
229    // Associate a SkCanvas object to this surface
230    env->SetIntField(canvasObj, gCanvasClassInfo.mSurfaceFormat, outBuffer.format);
231
232    SkBitmap bitmap;
233    ssize_t bpr = outBuffer.stride * bytesPerPixel(outBuffer.format);
234    bitmap.setConfig(convertPixelFormat(outBuffer.format), outBuffer.width, outBuffer.height, bpr);
235    if (outBuffer.format == PIXEL_FORMAT_RGBX_8888) {
236        bitmap.setIsOpaque(true);
237    }
238    if (outBuffer.width > 0 && outBuffer.height > 0) {
239        bitmap.setPixels(outBuffer.bits);
240    } else {
241        // be safe with an empty bitmap.
242        bitmap.setPixels(NULL);
243    }
244
245    SkCanvas* nativeCanvas = SkNEW_ARGS(SkCanvas, (bitmap));
246    swapCanvasPtr(env, canvasObj, nativeCanvas);
247
248    if (dirtyRectPtr) {
249        nativeCanvas->clipRect( SkRect::Make(reinterpret_cast<const SkIRect&>(dirtyRect)) );
250    }
251
252    if (dirtyRectObj) {
253        env->SetIntField(dirtyRectObj, gRectClassInfo.left,   dirtyRect.left);
254        env->SetIntField(dirtyRectObj, gRectClassInfo.top,    dirtyRect.top);
255        env->SetIntField(dirtyRectObj, gRectClassInfo.right,  dirtyRect.right);
256        env->SetIntField(dirtyRectObj, gRectClassInfo.bottom, dirtyRect.bottom);
257    }
258}
259
260static void nativeUnlockCanvasAndPost(JNIEnv* env, jclass clazz,
261        jint nativeObject, jobject canvasObj) {
262    sp<Surface> surface(reinterpret_cast<Surface *>(nativeObject));
263    if (!isSurfaceValid(surface)) {
264        return;
265    }
266
267    // detach the canvas from the surface
268    SkCanvas* nativeCanvas = SkNEW(SkCanvas);
269    swapCanvasPtr(env, canvasObj, nativeCanvas);
270
271    // unlock surface
272    status_t err = surface->unlockAndPost();
273    if (err < 0) {
274        doThrowIAE(env);
275    }
276}
277
278// ----------------------------------------------------------------------------
279
280static jint nativeCreateFromSurfaceControl(JNIEnv* env, jclass clazz,
281        jint surfaceControlNativeObj) {
282    /*
283     * This is used by the WindowManagerService just after constructing
284     * a Surface and is necessary for returning the Surface reference to
285     * the caller. At this point, we should only have a SurfaceControl.
286     */
287
288    sp<SurfaceControl> ctrl(reinterpret_cast<SurfaceControl *>(surfaceControlNativeObj));
289    sp<Surface> surface(ctrl->getSurface());
290    if (surface != NULL) {
291        surface->incStrong(&sRefBaseOwner);
292    }
293    return reinterpret_cast<jint>(surface.get());
294}
295
296static jint nativeReadFromParcel(JNIEnv* env, jclass clazz,
297        jint nativeObject, jobject parcelObj) {
298    Parcel* parcel = parcelForJavaObject(env, parcelObj);
299    if (parcel == NULL) {
300        doThrowNPE(env);
301        return 0;
302    }
303
304    sp<Surface> self(reinterpret_cast<Surface *>(nativeObject));
305    sp<IBinder> binder(parcel->readStrongBinder());
306
307    // update the Surface only if the underlying IGraphicBufferProducer
308    // has changed.
309    if (self != NULL
310            && (self->getIGraphicBufferProducer()->asBinder() == binder)) {
311        // same IGraphicBufferProducer, return ourselves
312        return int(self.get());
313    }
314
315    sp<Surface> sur;
316    sp<IGraphicBufferProducer> gbp(interface_cast<IGraphicBufferProducer>(binder));
317    if (gbp != NULL) {
318        // we have a new IGraphicBufferProducer, create a new Surface for it
319        sur = new Surface(gbp, true);
320        // and keep a reference before passing to java
321        sur->incStrong(&sRefBaseOwner);
322    }
323
324    if (self != NULL) {
325        // and loose the java reference to ourselves
326        self->decStrong(&sRefBaseOwner);
327    }
328
329    return int(sur.get());
330}
331
332static void nativeWriteToParcel(JNIEnv* env, jclass clazz,
333        jint nativeObject, jobject parcelObj) {
334    Parcel* parcel = parcelForJavaObject(env, parcelObj);
335    if (parcel == NULL) {
336        doThrowNPE(env);
337        return;
338    }
339    sp<Surface> self(reinterpret_cast<Surface *>(nativeObject));
340    parcel->writeStrongBinder( self != 0 ? self->getIGraphicBufferProducer()->asBinder() : NULL);
341}
342
343// ----------------------------------------------------------------------------
344
345static JNINativeMethod gSurfaceMethods[] = {
346    {"nativeCreateFromSurfaceTexture", "(Landroid/graphics/SurfaceTexture;)I",
347            (void*)nativeCreateFromSurfaceTexture },
348    {"nativeRelease", "(I)V",
349            (void*)nativeRelease },
350    {"nativeIsValid", "(I)Z",
351            (void*)nativeIsValid },
352    {"nativeIsConsumerRunningBehind", "(I)Z",
353            (void*)nativeIsConsumerRunningBehind },
354    {"nativeLockCanvas", "(ILandroid/graphics/Canvas;Landroid/graphics/Rect;)V",
355            (void*)nativeLockCanvas },
356    {"nativeUnlockCanvasAndPost", "(ILandroid/graphics/Canvas;)V",
357            (void*)nativeUnlockCanvasAndPost },
358    {"nativeCreateFromSurfaceControl", "(I)I",
359            (void*)nativeCreateFromSurfaceControl },
360    {"nativeReadFromParcel", "(ILandroid/os/Parcel;)I",
361            (void*)nativeReadFromParcel },
362    {"nativeWriteToParcel", "(ILandroid/os/Parcel;)V",
363            (void*)nativeWriteToParcel },
364};
365
366int register_android_view_Surface(JNIEnv* env)
367{
368    int err = AndroidRuntime::registerNativeMethods(env, "android/view/Surface",
369            gSurfaceMethods, NELEM(gSurfaceMethods));
370
371    jclass clazz = env->FindClass("android/view/Surface");
372    gSurfaceClassInfo.clazz = jclass(env->NewGlobalRef(clazz));
373    gSurfaceClassInfo.mNativeObject =
374            env->GetFieldID(gSurfaceClassInfo.clazz, "mNativeObject", "I");
375    gSurfaceClassInfo.mLock =
376            env->GetFieldID(gSurfaceClassInfo.clazz, "mLock", "Ljava/lang/Object;");
377    gSurfaceClassInfo.ctor = env->GetMethodID(gSurfaceClassInfo.clazz, "<init>", "(I)V");
378
379    clazz = env->FindClass("android/graphics/Canvas");
380    gCanvasClassInfo.mFinalizer = env->GetFieldID(clazz, "mFinalizer", "Landroid/graphics/Canvas$CanvasFinalizer;");
381    gCanvasClassInfo.mNativeCanvas = env->GetFieldID(clazz, "mNativeCanvas", "I");
382    gCanvasClassInfo.mSurfaceFormat = env->GetFieldID(clazz, "mSurfaceFormat", "I");
383
384    clazz = env->FindClass("android/graphics/Canvas$CanvasFinalizer");
385    gCanvasFinalizerClassInfo.mNativeCanvas = env->GetFieldID(clazz, "mNativeCanvas", "I");
386
387    clazz = env->FindClass("android/graphics/Rect");
388    gRectClassInfo.left = env->GetFieldID(clazz, "left", "I");
389    gRectClassInfo.top = env->GetFieldID(clazz, "top", "I");
390    gRectClassInfo.right = env->GetFieldID(clazz, "right", "I");
391    gRectClassInfo.bottom = env->GetFieldID(clazz, "bottom", "I");
392
393    return err;
394}
395
396};
397