1 /*
2  * Copyright 2020 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 <android/native_window_jni.h>
18 
19 #include <cassert>
20 #include <cerrno>
21 #include <dlfcn.h>
22 
23 extern "C" {
24 
25 JNIEXPORT jint JNICALL
Java_androidx_camera_testing_impl_SurfaceUtil_nativeGetSurfaceFormat(JNIEnv * env,jclass clazz,jobject jsurface)26 Java_androidx_camera_testing_impl_SurfaceUtil_nativeGetSurfaceFormat(JNIEnv *env, jclass clazz,
27                                                            jobject jsurface) {
28     ANativeWindow *nativeWindow = ANativeWindow_fromSurface(env, jsurface);
29     assert(nativeWindow != nullptr);
30     int32_t format = ANativeWindow_getFormat(nativeWindow);
31     ANativeWindow_release(nativeWindow);
32     return format;
33 }
34 
35 JNIEXPORT jint JNICALL
Java_androidx_camera_testing_impl_SurfaceUtil_nativeSetBuffersTransform(JNIEnv * env,jclass clazz,jobject jsurface,jint transform)36 Java_androidx_camera_testing_impl_SurfaceUtil_nativeSetBuffersTransform(
37         JNIEnv *env,
38         jclass clazz,
39         jobject jsurface,
40         jint transform) {
41     // Load libnativewindow for newer APIs
42     void* libnativewindow = dlopen("libnativewindow.so", RTLD_NOW);
43     if (!libnativewindow) {
44         // Unable to load libnativewindow
45         return -ENOENT;
46     }
47 
48     // Load ANativeWindow_setBuffersTransform which was added in API 26
49     int32_t (*ANativeWindow_setBuffersTransform)(ANativeWindow*, int32_t);
50 
51     ANativeWindow_setBuffersTransform = (int32_t(*)(ANativeWindow*, int32_t))
52             dlsym(libnativewindow, "ANativeWindow_setBuffersTransform");
53 
54     if (!ANativeWindow_setBuffersTransform) {
55         dlclose(libnativewindow);
56         // Unable to load ANativeWindow_setBuffersTransform
57         return -ENOSYS;
58     }
59 
60     ANativeWindow *nativeWindow = ANativeWindow_fromSurface(env, jsurface);
61     auto transformValue = (ANativeWindowTransform)transform;
62     assert(nativeWindow != nullptr);
63     int32_t result = ANativeWindow_setBuffersTransform(nativeWindow, transformValue);
64     ANativeWindow_release(nativeWindow);
65     return result;
66 }
67 
68 }  // extern "C"
69