blob: 6776f611559ce2fb997c1798ebdca687691d88bb [file] [log] [blame]
Zhijun Hef6a09e52015-02-24 18:12:23 -08001/*
2 * Copyright 2015 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_NDEBUG 0
18#define LOG_TAG "ImageWriter_JNI"
Zhijun He0ab41622016-02-25 16:00:38 -080019#include "android_media_Utils.h"
20
Yin-Chia Yeh6132b022019-02-14 16:40:20 -080021#include <utils/Condition.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080022#include <utils/Log.h>
Yin-Chia Yeh6132b022019-02-14 16:40:20 -080023#include <utils/Mutex.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080024#include <utils/String8.h>
Yin-Chia Yeh6132b022019-02-14 16:40:20 -080025#include <utils/Thread.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080026
Zhijun Hef6a09e52015-02-24 18:12:23 -080027#include <gui/Surface.h>
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -070028#include <ui/PublicFormat.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080029#include <android_runtime/AndroidRuntime.h>
30#include <android_runtime/android_view_Surface.h>
Emilian Peev9c778e12020-10-29 17:36:22 -070031#include <android_runtime/android_graphics_GraphicBuffer.h>
rennbe092192018-05-07 10:18:05 -070032#include <android_runtime/android_hardware_HardwareBuffer.h>
33#include <private/android/AHardwareBufferHelpers.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080034#include <jni.h>
Steven Moreland2279b252017-07-19 09:50:45 -070035#include <nativehelper/JNIHelp.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080036
37#include <stdint.h>
38#include <inttypes.h>
rennbe092192018-05-07 10:18:05 -070039#include <android/hardware_buffer_jni.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080040
Yin-Chia Yeh6132b022019-02-14 16:40:20 -080041#include <deque>
42
Zhijun Hef6a09e52015-02-24 18:12:23 -080043#define IMAGE_BUFFER_JNI_ID "mNativeBuffer"
Zhijun Hef6a09e52015-02-24 18:12:23 -080044// ----------------------------------------------------------------------------
45
46using namespace android;
47
Zhijun Hef6a09e52015-02-24 18:12:23 -080048static struct {
49 jmethodID postEventFromNative;
50 jfieldID mWriterFormat;
51} gImageWriterClassInfo;
52
53static struct {
Sally Qiac97f992021-10-11 17:39:54 -070054 jfieldID mDataSpace;
Zhijun Hef6a09e52015-02-24 18:12:23 -080055 jfieldID mNativeBuffer;
56 jfieldID mNativeFenceFd;
57 jfieldID mPlanes;
58} gSurfaceImageClassInfo;
59
60static struct {
61 jclass clazz;
62 jmethodID ctor;
63} gSurfacePlaneClassInfo;
64
Zhijun Hef6a09e52015-02-24 18:12:23 -080065// ----------------------------------------------------------------------------
66
Carlos Martinez Romero986b15a2024-07-03 13:39:46 -070067class JNIImageWriterContext : public SurfaceListener {
Zhijun Hef6a09e52015-02-24 18:12:23 -080068public:
69 JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz);
70
71 virtual ~JNIImageWriterContext();
72
Carlos Martinez Romero986b15a2024-07-03 13:39:46 -070073 // Implementation of SurfaceListener, used to notify the ImageWriter that the consumer
Zhijun Hef6a09e52015-02-24 18:12:23 -080074 // has returned a buffer and it is ready for ImageWriter to dequeue.
75 virtual void onBufferReleased();
Carlos Martinez Romero986b15a2024-07-03 13:39:46 -070076 virtual bool needsReleaseNotify() override { return true; };
77 virtual void onBuffersDiscarded(const std::vector<sp<GraphicBuffer>>& /*buffers*/) override {};
78 virtual void onBufferDetached(int /*slot*/) override {};
Zhijun Hef6a09e52015-02-24 18:12:23 -080079
Zhijun Hece9d6f92015-03-29 16:33:59 -070080 void setProducer(const sp<Surface>& producer) { mProducer = producer; }
81 Surface* getProducer() { return mProducer.get(); }
Zhijun Hef6a09e52015-02-24 18:12:23 -080082
83 void setBufferFormat(int format) { mFormat = format; }
84 int getBufferFormat() { return mFormat; }
85
86 void setBufferWidth(int width) { mWidth = width; }
87 int getBufferWidth() { return mWidth; }
88
89 void setBufferHeight(int height) { mHeight = height; }
90 int getBufferHeight() { return mHeight; }
91
Sally Qiac97f992021-10-11 17:39:54 -070092 void setBufferDataSpace(android_dataspace dataSpace) { mDataSpace = dataSpace; }
93 android_dataspace getBufferDataSpace() { return mDataSpace; }
94
Shuzhen Wangb9adb572020-06-24 09:33:27 -070095 void queueAttachedFlag(bool isAttached) {
96 Mutex::Autolock l(mAttachedFlagQueueLock);
97 mAttachedFlagQueue.push_back(isAttached);
98 }
99 void dequeueAttachedFlag() {
100 Mutex::Autolock l(mAttachedFlagQueueLock);
101 mAttachedFlagQueue.pop_back();
102 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800103private:
104 static JNIEnv* getJNIEnv(bool* needsDetach);
105 static void detachJNI();
106
Zhijun Hece9d6f92015-03-29 16:33:59 -0700107 sp<Surface> mProducer;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800108 jobject mWeakThiz;
109 jclass mClazz;
110 int mFormat;
111 int mWidth;
112 int mHeight;
Sally Qiac97f992021-10-11 17:39:54 -0700113 android_dataspace mDataSpace;
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800114
115 // Class for a shared thread used to detach buffers from buffer queues
116 // to discard buffers after consumers are done using them.
117 // This is needed because detaching buffers in onBufferReleased callback
118 // can lead to deadlock when consumer/producer are on the same process.
119 class BufferDetacher {
120 public:
121 // Called by JNIImageWriterContext ctor. Will start the thread for first ref.
122 void addRef();
123 // Called by JNIImageWriterContext dtor. Will stop the thread after ref goes to 0.
124 void removeRef();
125 // Called by onBufferReleased to signal this thread to detach a buffer
126 void detach(wp<Surface>);
127
128 private:
129
130 class DetachThread : public Thread {
131 public:
132 DetachThread() : Thread(/*canCallJava*/false) {};
133
134 void detach(wp<Surface>);
135
136 virtual void requestExit() override;
137
138 private:
139 virtual bool threadLoop() override;
140
141 Mutex mLock;
142 Condition mCondition;
143 std::deque<wp<Surface>> mQueue;
144
Yin-Chia Yehedace1a2019-07-30 13:02:59 -0700145 static const nsecs_t kWaitDuration = 500000000; // 500 ms
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800146 };
147 sp<DetachThread> mThread;
148
149 Mutex mLock;
150 int mRefCount = 0;
151 };
152
153 static BufferDetacher sBufferDetacher;
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700154
155 // Buffer queue guarantees both producer and consumer side buffer flows are
156 // in order. See b/19977520. As a result, we can use a queue here.
157 Mutex mAttachedFlagQueueLock;
158 std::deque<bool> mAttachedFlagQueue;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800159};
160
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800161JNIImageWriterContext::BufferDetacher JNIImageWriterContext::sBufferDetacher;
162
163void JNIImageWriterContext::BufferDetacher::addRef() {
164 Mutex::Autolock l(mLock);
165 mRefCount++;
166 if (mRefCount == 1) {
167 mThread = new DetachThread();
168 mThread->run("BufDtchThrd");
169 }
170}
171
172void JNIImageWriterContext::BufferDetacher::removeRef() {
173 Mutex::Autolock l(mLock);
174 mRefCount--;
175 if (mRefCount == 0) {
176 mThread->requestExit();
177 mThread->join();
178 mThread.clear();
179 }
180}
181
182void JNIImageWriterContext::BufferDetacher::detach(wp<Surface> bq) {
183 Mutex::Autolock l(mLock);
184 if (mThread == nullptr) {
185 ALOGE("%s: buffer detach thread is gone!", __FUNCTION__);
186 return;
187 }
188 mThread->detach(bq);
189}
190
191void JNIImageWriterContext::BufferDetacher::DetachThread::detach(wp<Surface> bq) {
192 Mutex::Autolock l(mLock);
193 mQueue.push_back(bq);
194 mCondition.signal();
195}
196
197void JNIImageWriterContext::BufferDetacher::DetachThread::requestExit() {
198 Thread::requestExit();
199 {
200 Mutex::Autolock l(mLock);
201 mQueue.clear();
202 }
203 mCondition.signal();
204}
205
206bool JNIImageWriterContext::BufferDetacher::DetachThread::threadLoop() {
207 Mutex::Autolock l(mLock);
208 mCondition.waitRelative(mLock, kWaitDuration);
209
210 while (!mQueue.empty()) {
211 if (exitPending()) {
212 return false;
213 }
214
215 wp<Surface> wbq = mQueue.front();
216 mQueue.pop_front();
217 sp<Surface> bq = wbq.promote();
218 if (bq != nullptr) {
219 sp<Fence> fence;
220 sp<GraphicBuffer> buffer;
221 ALOGV("%s: One buffer is detached", __FUNCTION__);
222 mLock.unlock();
223 bq->detachNextBuffer(&buffer, &fence);
224 mLock.lock();
225 }
226 }
227 return !exitPending();
228}
229
Zhijun Hef6a09e52015-02-24 18:12:23 -0800230JNIImageWriterContext::JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz) :
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800231 mWeakThiz(env->NewGlobalRef(weakThiz)),
232 mClazz((jclass)env->NewGlobalRef(clazz)),
233 mFormat(0),
234 mWidth(-1),
235 mHeight(-1) {
236 sBufferDetacher.addRef();
Zhijun Hef6a09e52015-02-24 18:12:23 -0800237}
238
239JNIImageWriterContext::~JNIImageWriterContext() {
240 ALOGV("%s", __FUNCTION__);
241 bool needsDetach = false;
242 JNIEnv* env = getJNIEnv(&needsDetach);
243 if (env != NULL) {
244 env->DeleteGlobalRef(mWeakThiz);
245 env->DeleteGlobalRef(mClazz);
246 } else {
247 ALOGW("leaking JNI object references");
248 }
249 if (needsDetach) {
250 detachJNI();
251 }
252
253 mProducer.clear();
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800254 sBufferDetacher.removeRef();
Zhijun Hef6a09e52015-02-24 18:12:23 -0800255}
256
257JNIEnv* JNIImageWriterContext::getJNIEnv(bool* needsDetach) {
258 ALOGV("%s", __FUNCTION__);
259 LOG_ALWAYS_FATAL_IF(needsDetach == NULL, "needsDetach is null!!!");
260 *needsDetach = false;
261 JNIEnv* env = AndroidRuntime::getJNIEnv();
262 if (env == NULL) {
263 JavaVMAttachArgs args = {JNI_VERSION_1_4, NULL, NULL};
264 JavaVM* vm = AndroidRuntime::getJavaVM();
265 int result = vm->AttachCurrentThread(&env, (void*) &args);
266 if (result != JNI_OK) {
267 ALOGE("thread attach failed: %#x", result);
268 return NULL;
269 }
270 *needsDetach = true;
271 }
272 return env;
273}
274
275void JNIImageWriterContext::detachJNI() {
276 ALOGV("%s", __FUNCTION__);
277 JavaVM* vm = AndroidRuntime::getJavaVM();
278 int result = vm->DetachCurrentThread();
279 if (result != JNI_OK) {
280 ALOGE("thread detach failed: %#x", result);
281 }
282}
283
284void JNIImageWriterContext::onBufferReleased() {
285 ALOGV("%s: buffer released", __FUNCTION__);
286 bool needsDetach = false;
287 JNIEnv* env = getJNIEnv(&needsDetach);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700288
289 bool bufferIsAttached = false;
290 {
291 Mutex::Autolock l(mAttachedFlagQueueLock);
292 if (!mAttachedFlagQueue.empty()) {
293 bufferIsAttached = mAttachedFlagQueue.front();
294 mAttachedFlagQueue.pop_front();
295 } else {
296 ALOGW("onBufferReleased called with no attached flag queued");
297 }
298 }
299
Zhijun Hef6a09e52015-02-24 18:12:23 -0800300 if (env != NULL) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700301 // Detach the buffer every time when a buffer consumption is done,
302 // need let this callback give a BufferItem, then only detach if it was attached to this
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700303 // Writer. see b/19977520
304 if (mFormat == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED || bufferIsAttached) {
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800305 sBufferDetacher.detach(mProducer);
Zhijun Hece9d6f92015-03-29 16:33:59 -0700306 }
307
Zhijun Hef6a09e52015-02-24 18:12:23 -0800308 env->CallStaticVoidMethod(mClazz, gImageWriterClassInfo.postEventFromNative, mWeakThiz);
309 } else {
310 ALOGW("onBufferReleased event will not posted");
311 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700312
Zhijun Hef6a09e52015-02-24 18:12:23 -0800313 if (needsDetach) {
314 detachJNI();
315 }
316}
317
318// ----------------------------------------------------------------------------
319
320extern "C" {
321
322// -------------------------------Private method declarations--------------
323
Zhijun Hef6a09e52015-02-24 18:12:23 -0800324static void Image_setNativeContext(JNIEnv* env, jobject thiz,
John Reckffa81f82022-02-04 17:05:30 -0500325 sp<GraphicBuffer> buffer, int fenceFd, int dataSpace);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800326static void Image_getNativeContext(JNIEnv* env, jobject thiz,
327 GraphicBuffer** buffer, int* fenceFd);
328static void Image_unlockIfLocked(JNIEnv* env, jobject thiz);
329
330// --------------------------ImageWriter methods---------------------------------------
331
332static void ImageWriter_classInit(JNIEnv* env, jclass clazz) {
333 ALOGV("%s:", __FUNCTION__);
334 jclass imageClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage");
335 LOG_ALWAYS_FATAL_IF(imageClazz == NULL,
336 "can't find android/media/ImageWriter$WriterSurfaceImage");
Sally Qiac97f992021-10-11 17:39:54 -0700337
338 gSurfaceImageClassInfo.mDataSpace = env->GetFieldID(
John Reckffa81f82022-02-04 17:05:30 -0500339 imageClazz, "mDataSpace", "I");
Sally Qiac97f992021-10-11 17:39:54 -0700340 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mDataSpace == NULL,
341 "can't find android/media/ImageWriter$WriterSurfaceImage.mDataSpace");
342
Zhijun Hef6a09e52015-02-24 18:12:23 -0800343 gSurfaceImageClassInfo.mNativeBuffer = env->GetFieldID(
344 imageClazz, IMAGE_BUFFER_JNI_ID, "J");
345 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeBuffer == NULL,
346 "can't find android/media/ImageWriter$WriterSurfaceImage.%s", IMAGE_BUFFER_JNI_ID);
347
348 gSurfaceImageClassInfo.mNativeFenceFd = env->GetFieldID(
349 imageClazz, "mNativeFenceFd", "I");
350 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeFenceFd == NULL,
351 "can't find android/media/ImageWriter$WriterSurfaceImage.mNativeFenceFd");
352
353 gSurfaceImageClassInfo.mPlanes = env->GetFieldID(
354 imageClazz, "mPlanes", "[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;");
355 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mPlanes == NULL,
356 "can't find android/media/ImageWriter$WriterSurfaceImage.mPlanes");
357
358 gImageWriterClassInfo.postEventFromNative = env->GetStaticMethodID(
359 clazz, "postEventFromNative", "(Ljava/lang/Object;)V");
360 LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.postEventFromNative == NULL,
361 "can't find android/media/ImageWriter.postEventFromNative");
362
363 gImageWriterClassInfo.mWriterFormat = env->GetFieldID(
364 clazz, "mWriterFormat", "I");
365 LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.mWriterFormat == NULL,
366 "can't find android/media/ImageWriter.mWriterFormat");
367
368 jclass planeClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage$SurfacePlane");
369 LOG_ALWAYS_FATAL_IF(planeClazz == NULL, "Can not find SurfacePlane class");
370 // FindClass only gives a local reference of jclass object.
371 gSurfacePlaneClassInfo.clazz = (jclass) env->NewGlobalRef(planeClazz);
372 gSurfacePlaneClassInfo.ctor = env->GetMethodID(gSurfacePlaneClassInfo.clazz, "<init>",
373 "(Landroid/media/ImageWriter$WriterSurfaceImage;IILjava/nio/ByteBuffer;)V");
374 LOG_ALWAYS_FATAL_IF(gSurfacePlaneClassInfo.ctor == NULL,
375 "Can not find SurfacePlane constructor");
376}
377
378static jlong ImageWriter_init(JNIEnv* env, jobject thiz, jobject weakThiz, jobject jsurface,
Sally Qidb57de32022-01-05 11:53:44 -0800379 jint maxImages, jint userWidth, jint userHeight, jboolean useSurfaceImageFormatInfo,
John Reckffa81f82022-02-04 17:05:30 -0500380 jint hardwareBufferFormat, jint dataSpace, jlong ndkUsage) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800381 status_t res;
382
383 ALOGV("%s: maxImages:%d", __FUNCTION__, maxImages);
384
385 sp<Surface> surface(android_view_Surface_getSurface(env, jsurface));
386 if (surface == NULL) {
387 jniThrowException(env,
388 "java/lang/IllegalArgumentException",
389 "The surface has been released");
390 return 0;
391 }
392 sp<IGraphicBufferProducer> bufferProducer = surface->getIGraphicBufferProducer();
393
394 jclass clazz = env->GetObjectClass(thiz);
395 if (clazz == NULL) {
396 jniThrowRuntimeException(env, "Can't find android/graphics/ImageWriter");
397 return 0;
398 }
399 sp<JNIImageWriterContext> ctx(new JNIImageWriterContext(env, weakThiz, clazz));
400
401 sp<Surface> producer = new Surface(bufferProducer, /*controlledByApp*/false);
402 ctx->setProducer(producer);
403 /**
404 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not connectable
405 * after disconnect. MEDIA or CAMERA are treated the same internally. The producer listener
406 * will be cleared after disconnect call.
407 */
Emilian Peev2adf4032018-06-05 17:52:16 +0100408 res = producer->connect(/*api*/NATIVE_WINDOW_API_CAMERA, /*listener*/ctx);
409 if (res != OK) {
410 ALOGE("%s: Connecting to surface producer interface failed: %s (%d)",
411 __FUNCTION__, strerror(-res), res);
412 jniThrowRuntimeException(env, "Failed to connect to native window");
413 return 0;
414 }
415
Zhijun Hef6a09e52015-02-24 18:12:23 -0800416 jlong nativeCtx = reinterpret_cast<jlong>(ctx.get());
417
418 // Get the dimension and format of the producer.
419 sp<ANativeWindow> anw = producer;
Sally Qi42bd6a62022-09-13 08:14:16 -0700420 int32_t width, height, surfaceHalFormat;
421 int32_t surfaceFormat = 0;
422 int32_t surfaceDataspace = 0;
Emilian Peevab808242020-12-28 16:03:32 -0800423 if (userWidth < 0) {
424 if ((res = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, &width)) != OK) {
425 ALOGE("%s: Query Surface width failed: %s (%d)", __FUNCTION__, strerror(-res), res);
426 jniThrowRuntimeException(env, "Failed to query Surface width");
427 return 0;
428 }
429 } else {
430 width = userWidth;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800431 }
Emilian Peevab808242020-12-28 16:03:32 -0800432
Zhijun Hef6a09e52015-02-24 18:12:23 -0800433 ctx->setBufferWidth(width);
434
Emilian Peevab808242020-12-28 16:03:32 -0800435 if (userHeight < 0) {
436 if ((res = anw->query(anw.get(), NATIVE_WINDOW_HEIGHT, &height)) != OK) {
437 ALOGE("%s: Query Surface height failed: %s (%d)", __FUNCTION__, strerror(-res), res);
438 jniThrowRuntimeException(env, "Failed to query Surface height");
439 return 0;
440 }
441 } else {
442 height = userHeight;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800443 }
444 ctx->setBufferHeight(height);
445
Emilian Peevab808242020-12-28 16:03:32 -0800446 if ((userWidth > 0) && (userHeight > 0)) {
447 res = native_window_set_buffers_user_dimensions(anw.get(), userWidth, userHeight);
448 if (res != OK) {
449 ALOGE("%s: Set buffer dimensions failed: %s (%d)", __FUNCTION__, strerror(-res), res);
450 jniThrowRuntimeException(env, "Set buffer dimensions failed");
451 return 0;
452 }
453 }
454
Zhijun He916d8ac2017-03-22 17:33:47 -0700455 // Query surface format if no valid user format is specified, otherwise, override surface format
456 // with user format.
Sally Qidb57de32022-01-05 11:53:44 -0800457 if (useSurfaceImageFormatInfo) {
Sally Qi42bd6a62022-09-13 08:14:16 -0700458 // retrieve hal format
459 if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &surfaceHalFormat)) != OK) {
Zhijun He916d8ac2017-03-22 17:33:47 -0700460 ALOGE("%s: Query Surface format failed: %s (%d)", __FUNCTION__, strerror(-res), res);
461 jniThrowRuntimeException(env, "Failed to query Surface format");
462 return 0;
463 }
Sally Qi42bd6a62022-09-13 08:14:16 -0700464 if ((res = anw->query(
465 anw.get(), NATIVE_WINDOW_DEFAULT_DATASPACE, &surfaceDataspace)) != OK) {
466 ALOGE("%s: Query Surface dataspace failed: %s (%d)", __FUNCTION__, strerror(-res), res);
467 jniThrowRuntimeException(env, "Failed to query Surface dataspace");
468 return 0;
469 }
Zhijun He916d8ac2017-03-22 17:33:47 -0700470 } else {
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700471 // Set consumer buffer format to user specified format
Sally Qidb57de32022-01-05 11:53:44 -0800472 android_dataspace nativeDataspace = static_cast<android_dataspace>(dataSpace);
Sally Qidb57de32022-01-05 11:53:44 -0800473 res = native_window_set_buffers_format(anw.get(), hardwareBufferFormat);
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700474 if (res != OK) {
475 ALOGE("%s: Unable to configure consumer native buffer format to %#x",
Sally Qidb57de32022-01-05 11:53:44 -0800476 __FUNCTION__, hardwareBufferFormat);
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700477 jniThrowRuntimeException(env, "Failed to set Surface format");
478 return 0;
479 }
480
481 res = native_window_set_buffers_data_space(anw.get(), nativeDataspace);
482 if (res != OK) {
483 ALOGE("%s: Unable to configure consumer dataspace %#x",
484 __FUNCTION__, nativeDataspace);
485 jniThrowRuntimeException(env, "Failed to set Surface dataspace");
486 return 0;
487 }
Sally Qiac97f992021-10-11 17:39:54 -0700488 ctx->setBufferDataSpace(nativeDataspace);
Sally Qi42bd6a62022-09-13 08:14:16 -0700489 surfaceDataspace = dataSpace;
490 surfaceHalFormat = hardwareBufferFormat;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800491 }
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700492
Sally Qi42bd6a62022-09-13 08:14:16 -0700493 ctx->setBufferFormat(surfaceHalFormat);
494 ctx->setBufferDataSpace(static_cast<android_dataspace>(surfaceDataspace));
495
496 // update class.mWriterFormat
497 surfaceFormat = static_cast<int32_t>(mapHalFormatDataspaceToPublicFormat(
498 surfaceHalFormat, static_cast<android_dataspace>(surfaceDataspace)));
Zhijun He916d8ac2017-03-22 17:33:47 -0700499 env->SetIntField(thiz,
500 gImageWriterClassInfo.mWriterFormat, reinterpret_cast<jint>(surfaceFormat));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800501
Sally Qid26f4f02022-01-21 09:53:20 -0800502 // ndkUsage == -1 means setUsage in ImageWriter class is not called.
503 // skip usage setting if setUsage in ImageWriter is not called and imageformat is opaque.
Sally Qi42bd6a62022-09-13 08:14:16 -0700504 if (!(ndkUsage == -1 && isFormatOpaque(surfaceHalFormat))) {
Sally Qid26f4f02022-01-21 09:53:20 -0800505 if (ndkUsage == -1) {
506 ndkUsage = GRALLOC_USAGE_SW_WRITE_OFTEN;
507 }
508 res = native_window_set_usage(anw.get(), ndkUsage);
509 if (res != OK) {
510 ALOGE("%s: Configure usage %08x for format %08x failed: %s (%d)",
511 __FUNCTION__, static_cast<unsigned int>(ndkUsage),
512 surfaceFormat, strerror(-res), res);
513 jniThrowRuntimeException(env,
514 "Failed to SW_WRITE_OFTEN configure usage");
515 return 0;
516 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800517 }
518
519 int minUndequeuedBufferCount = 0;
520 res = anw->query(anw.get(),
521 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufferCount);
522 if (res != OK) {
523 ALOGE("%s: Query producer undequeued buffer count failed: %s (%d)",
524 __FUNCTION__, strerror(-res), res);
525 jniThrowRuntimeException(env, "Query producer undequeued buffer count failed");
526 return 0;
527 }
528
529 size_t totalBufferCount = maxImages + minUndequeuedBufferCount;
530 res = native_window_set_buffer_count(anw.get(), totalBufferCount);
531 if (res != OK) {
532 ALOGE("%s: Set buffer count failed: %s (%d)", __FUNCTION__, strerror(-res), res);
533 jniThrowRuntimeException(env, "Set buffer count failed");
534 return 0;
535 }
536
537 if (ctx != 0) {
538 ctx->incStrong((void*)ImageWriter_init);
539 }
540 return nativeCtx;
541}
542
543static void ImageWriter_dequeueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
544 ALOGV("%s", __FUNCTION__);
545 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
546 if (ctx == NULL || thiz == NULL) {
547 jniThrowException(env, "java/lang/IllegalStateException",
548 "ImageWriterContext is not initialized");
549 return;
550 }
551
552 sp<ANativeWindow> anw = ctx->getProducer();
553 android_native_buffer_t *anb = NULL;
554 int fenceFd = -1;
555 status_t res = anw->dequeueBuffer(anw.get(), &anb, &fenceFd);
556 if (res != OK) {
Zhijun Hea5827142015-04-22 10:07:42 -0700557 ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700558 switch (res) {
559 case NO_INIT:
560 jniThrowException(env, "java/lang/IllegalStateException",
561 "Surface has been abandoned");
562 break;
563 default:
564 // TODO: handle other error cases here.
565 jniThrowRuntimeException(env, "dequeue buffer failed");
566 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800567 return;
568 }
569 // New GraphicBuffer object doesn't own the handle, thus the native buffer
570 // won't be freed when this object is destroyed.
Mathias Agopian845eef05f2017-04-03 17:51:15 -0700571 sp<GraphicBuffer> buffer(GraphicBuffer::from(anb));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800572
573 // Note that:
574 // 1. No need to lock buffer now, will only lock it when the first getPlanes() is called.
575 // 2. Fence will be saved to mNativeFenceFd, and will consumed by lock/queue/cancel buffer
576 // later.
577 // 3. need use lockAsync here, as it will handle the dequeued fence for us automatically.
578
579 // Finally, set the native info into image object.
Sally Qiac97f992021-10-11 17:39:54 -0700580 Image_setNativeContext(env, image, buffer, fenceFd, ctx->getBufferDataSpace());
Zhijun Hef6a09e52015-02-24 18:12:23 -0800581}
582
583static void ImageWriter_close(JNIEnv* env, jobject thiz, jlong nativeCtx) {
584 ALOGV("%s:", __FUNCTION__);
585 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
586 if (ctx == NULL || thiz == NULL) {
Chien-Yu Chen0375cb02015-06-18 11:55:18 -0700587 // ImageWriter is already closed.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800588 return;
589 }
590
591 ANativeWindow* producer = ctx->getProducer();
592 if (producer != NULL) {
593 /**
594 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not
595 * connectable after disconnect. MEDIA or CAMERA are treated the same internally.
596 * The producer listener will be cleared after disconnect call.
597 */
598 status_t res = native_window_api_disconnect(producer, /*api*/NATIVE_WINDOW_API_CAMERA);
599 /**
600 * This is not an error. if client calling process dies, the window will
601 * also die and all calls to it will return DEAD_OBJECT, thus it's already
602 * "disconnected"
603 */
604 if (res == DEAD_OBJECT) {
605 ALOGW("%s: While disconnecting ImageWriter from native window, the"
606 " native window died already", __FUNCTION__);
607 } else if (res != OK) {
608 ALOGE("%s: native window disconnect failed: %s (%d)",
609 __FUNCTION__, strerror(-res), res);
610 jniThrowRuntimeException(env, "Native window disconnect failed");
611 return;
612 }
613 }
614
615 ctx->decStrong((void*)ImageWriter_init);
616}
617
618static void ImageWriter_cancelImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
619 ALOGV("%s", __FUNCTION__);
620 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
621 if (ctx == NULL || thiz == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800622 ALOGW("ImageWriter#close called before Image#close, consider calling Image#close first");
Zhijun Hef6a09e52015-02-24 18:12:23 -0800623 return;
624 }
625
626 sp<ANativeWindow> anw = ctx->getProducer();
627
628 GraphicBuffer *buffer = NULL;
629 int fenceFd = -1;
630 Image_getNativeContext(env, image, &buffer, &fenceFd);
631 if (buffer == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800632 // Cancel an already cancelled image is harmless.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800633 return;
634 }
635
636 // Unlock the image if it was locked
637 Image_unlockIfLocked(env, image);
638
639 anw->cancelBuffer(anw.get(), buffer, fenceFd);
640
Sally Qiac97f992021-10-11 17:39:54 -0700641 Image_setNativeContext(env, image, NULL, -1, HAL_DATASPACE_UNKNOWN);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800642}
643
644static void ImageWriter_queueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image,
John Reckffa81f82022-02-04 17:05:30 -0500645 jlong timestampNs, jint dataSpace, jint left, jint top, jint right,
Sally Qiac97f992021-10-11 17:39:54 -0700646 jint bottom, jint transform, jint scalingMode) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800647 ALOGV("%s", __FUNCTION__);
648 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
649 if (ctx == NULL || thiz == NULL) {
650 jniThrowException(env, "java/lang/IllegalStateException",
651 "ImageWriterContext is not initialized");
652 return;
653 }
654
655 status_t res = OK;
656 sp<ANativeWindow> anw = ctx->getProducer();
657
658 GraphicBuffer *buffer = NULL;
659 int fenceFd = -1;
660 Image_getNativeContext(env, image, &buffer, &fenceFd);
661 if (buffer == NULL) {
662 jniThrowException(env, "java/lang/IllegalStateException",
663 "Image is not initialized");
664 return;
665 }
666
667 // Unlock image if it was locked.
668 Image_unlockIfLocked(env, image);
669
670 // Set timestamp
Zhijun Hed1cbc682015-03-23 10:10:04 -0700671 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800672 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
673 if (res != OK) {
674 jniThrowRuntimeException(env, "Set timestamp failed");
675 return;
676 }
677
Sally Qiac97f992021-10-11 17:39:54 -0700678 // Set dataSpace
John Reckffa81f82022-02-04 17:05:30 -0500679 ALOGV("dataSpace to be queued: %d", dataSpace);
Sally Qiac97f992021-10-11 17:39:54 -0700680 res = native_window_set_buffers_data_space(
681 anw.get(), static_cast<android_dataspace>(dataSpace));
682 if (res != OK) {
683 jniThrowRuntimeException(env, "Set dataspace failed");
684 return;
685 }
686
Zhijun Hef6a09e52015-02-24 18:12:23 -0800687 // Set crop
688 android_native_rect_t cropRect;
689 cropRect.left = left;
690 cropRect.top = top;
691 cropRect.right = right;
692 cropRect.bottom = bottom;
693 res = native_window_set_crop(anw.get(), &cropRect);
694 if (res != OK) {
695 jniThrowRuntimeException(env, "Set crop rect failed");
696 return;
697 }
698
Emilian Peev450a5ff2018-03-19 16:05:10 +0000699 res = native_window_set_buffers_transform(anw.get(), transform);
700 if (res != OK) {
701 jniThrowRuntimeException(env, "Set transform failed");
702 return;
703 }
704
Emilian Peev750aec62018-04-06 12:55:00 +0100705 res = native_window_set_scaling_mode(anw.get(), scalingMode);
706 if (res != OK) {
707 jniThrowRuntimeException(env, "Set scaling mode failed");
708 return;
709 }
710
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700711 // Finally, queue input buffer.
712 //
713 // Because onBufferReleased may be called before queueBuffer() returns,
714 // queue the "attached" flag before calling queueBuffer. In case
715 // queueBuffer() fails, remove it from the queue.
716 ctx->queueAttachedFlag(false);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800717 res = anw->queueBuffer(anw.get(), buffer, fenceFd);
718 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700719 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700720 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700721 switch (res) {
722 case NO_INIT:
723 jniThrowException(env, "java/lang/IllegalStateException",
724 "Surface has been abandoned");
725 break;
726 default:
727 // TODO: handle other error cases here.
728 jniThrowRuntimeException(env, "Queue input buffer failed");
729 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800730 return;
731 }
732
Zhijun Hece9d6f92015-03-29 16:33:59 -0700733 // Clear the image native context: end of this image's lifecycle in public API.
Sally Qiac97f992021-10-11 17:39:54 -0700734 Image_setNativeContext(env, image, NULL, -1, HAL_DATASPACE_UNKNOWN);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800735}
736
Emilian Peev9c778e12020-10-29 17:36:22 -0700737static status_t attachAndQeueuGraphicBuffer(JNIEnv* env, JNIImageWriterContext *ctx,
John Reckffa81f82022-02-04 17:05:30 -0500738 sp<Surface> surface, sp<GraphicBuffer> gb, jlong timestampNs, jint dataSpace,
Sally Qiac97f992021-10-11 17:39:54 -0700739 jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700740 status_t res = OK;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700741 // Step 1. Attach Image
Emilian Peev9c778e12020-10-29 17:36:22 -0700742 res = surface->attachBuffer(gb.get());
Zhijun Hece9d6f92015-03-29 16:33:59 -0700743 if (res != OK) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700744 ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700745 switch (res) {
746 case NO_INIT:
747 jniThrowException(env, "java/lang/IllegalStateException",
748 "Surface has been abandoned");
749 break;
750 default:
751 // TODO: handle other error cases here.
752 jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
753 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700754 return res;
755 }
756 sp < ANativeWindow > anw = surface;
757
Sally Qiac97f992021-10-11 17:39:54 -0700758 // Step 2. Set timestamp, dataspace, crop, transform and scaling mode.
759 // Note that we do not need unlock the image because it was not locked.
Zhijun Hece9d6f92015-03-29 16:33:59 -0700760 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
761 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
762 if (res != OK) {
763 jniThrowRuntimeException(env, "Set timestamp failed");
764 return res;
765 }
766
John Reckffa81f82022-02-04 17:05:30 -0500767 ALOGV("dataSpace to be queued: %" PRId32, dataSpace);
Sally Qiac97f992021-10-11 17:39:54 -0700768 res = native_window_set_buffers_data_space(
769 anw.get(), static_cast<android_dataspace>(dataSpace));
770 if (res != OK) {
771 jniThrowRuntimeException(env, "Set dataSpace failed");
772 return res;
773 }
774
Zhijun Hece9d6f92015-03-29 16:33:59 -0700775 android_native_rect_t cropRect;
776 cropRect.left = left;
777 cropRect.top = top;
778 cropRect.right = right;
779 cropRect.bottom = bottom;
780 res = native_window_set_crop(anw.get(), &cropRect);
781 if (res != OK) {
782 jniThrowRuntimeException(env, "Set crop rect failed");
783 return res;
784 }
785
Emilian Peev450a5ff2018-03-19 16:05:10 +0000786 res = native_window_set_buffers_transform(anw.get(), transform);
787 if (res != OK) {
788 jniThrowRuntimeException(env, "Set transform failed");
789 return res;
790 }
791
Emilian Peev750aec62018-04-06 12:55:00 +0100792 res = native_window_set_scaling_mode(anw.get(), scalingMode);
793 if (res != OK) {
794 jniThrowRuntimeException(env, "Set scaling mode failed");
795 return res;
796 }
797
Zhijun Hece9d6f92015-03-29 16:33:59 -0700798 // Step 3. Queue Image.
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700799 //
800 // Because onBufferReleased may be called before queueBuffer() returns,
801 // queue the "attached" flag before calling queueBuffer. In case
802 // queueBuffer() fails, remove it from the queue.
803 ctx->queueAttachedFlag(true);
Emilian Peev9c778e12020-10-29 17:36:22 -0700804 res = anw->queueBuffer(anw.get(), gb.get(), /*fenceFd*/
Zhijun Hece9d6f92015-03-29 16:33:59 -0700805 -1);
806 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700807 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700808 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700809 switch (res) {
810 case NO_INIT:
811 jniThrowException(env, "java/lang/IllegalStateException",
812 "Surface has been abandoned");
813 break;
814 default:
815 // TODO: handle other error cases here.
816 jniThrowRuntimeException(env, "Queue input buffer failed");
817 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700818 return res;
819 }
820
821 // Do not set the image native context. Since it would overwrite the existing native context
822 // of the image that is from ImageReader, the subsequent image close will run into issues.
823
824 return res;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800825}
826
Emilian Peev9c778e12020-10-29 17:36:22 -0700827static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
Sally Qi42bd6a62022-09-13 08:14:16 -0700828 jlong nativeBuffer, jint nativeHalFormat, jlong timestampNs, jint dataSpace,
Sally Qiac97f992021-10-11 17:39:54 -0700829 jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
Emilian Peev9c778e12020-10-29 17:36:22 -0700830 ALOGV("%s", __FUNCTION__);
831 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
832 if (ctx == NULL || thiz == NULL) {
833 jniThrowException(env, "java/lang/IllegalStateException",
834 "ImageWriterContext is not initialized");
835 return -1;
836 }
837
838 sp<Surface> surface = ctx->getProducer();
Sally Qi42bd6a62022-09-13 08:14:16 -0700839 if (isFormatOpaque(ctx->getBufferFormat()) != isFormatOpaque(nativeHalFormat)) {
Emilian Peev9c778e12020-10-29 17:36:22 -0700840 jniThrowException(env, "java/lang/IllegalStateException",
841 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
842 return -1;
843 }
844
845 // Image is guaranteed to be from ImageReader at this point, so it is safe to
846 // cast to BufferItem pointer.
847 BufferItem* buffer = reinterpret_cast<BufferItem*>(nativeBuffer);
848 if (buffer == NULL) {
849 jniThrowException(env, "java/lang/IllegalStateException",
850 "Image is not initialized or already closed");
851 return -1;
852 }
853
Sally Qiac97f992021-10-11 17:39:54 -0700854 return attachAndQeueuGraphicBuffer(env, ctx, surface, buffer->mGraphicBuffer, timestampNs,
855 dataSpace, left, top, right, bottom, transform, scalingMode);
Emilian Peev9c778e12020-10-29 17:36:22 -0700856}
857
858static jint ImageWriter_attachAndQueueGraphicBuffer(JNIEnv* env, jobject thiz, jlong nativeCtx,
Sally Qi42bd6a62022-09-13 08:14:16 -0700859 jobject buffer, jint nativeHalFormat, jlong timestampNs, jint dataSpace,
860 jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
Emilian Peev9c778e12020-10-29 17:36:22 -0700861 ALOGV("%s", __FUNCTION__);
862 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
863 if (ctx == NULL || thiz == NULL) {
864 jniThrowException(env, "java/lang/IllegalStateException",
865 "ImageWriterContext is not initialized");
866 return -1;
867 }
868
869 sp<Surface> surface = ctx->getProducer();
Sally Qi42bd6a62022-09-13 08:14:16 -0700870 if (isFormatOpaque(ctx->getBufferFormat()) != isFormatOpaque(nativeHalFormat)) {
Emilian Peev9c778e12020-10-29 17:36:22 -0700871 jniThrowException(env, "java/lang/IllegalStateException",
872 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
873 return -1;
874 }
875
876 sp<GraphicBuffer> graphicBuffer = android_graphics_GraphicBuffer_getNativeGraphicsBuffer(env,
877 buffer);
878 if (graphicBuffer.get() == NULL) {
879 jniThrowException(env, "java/lang/IllegalArgumentException",
880 "Trying to attach an invalid graphic buffer");
881 return -1;
882 }
Sally Qiac97f992021-10-11 17:39:54 -0700883 return attachAndQeueuGraphicBuffer(env, ctx, surface, graphicBuffer, timestampNs,
884 dataSpace, left, top, right, bottom, transform, scalingMode);
Emilian Peev9c778e12020-10-29 17:36:22 -0700885}
886
Zhijun Hef6a09e52015-02-24 18:12:23 -0800887// --------------------------Image methods---------------------------------------
888
889static void Image_getNativeContext(JNIEnv* env, jobject thiz,
890 GraphicBuffer** buffer, int* fenceFd) {
891 ALOGV("%s", __FUNCTION__);
892 if (buffer != NULL) {
893 GraphicBuffer *gb = reinterpret_cast<GraphicBuffer *>
894 (env->GetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer));
895 *buffer = gb;
896 }
897
898 if (fenceFd != NULL) {
899 *fenceFd = reinterpret_cast<jint>(env->GetIntField(
900 thiz, gSurfaceImageClassInfo.mNativeFenceFd));
901 }
902}
903
904static void Image_setNativeContext(JNIEnv* env, jobject thiz,
John Reckffa81f82022-02-04 17:05:30 -0500905 sp<GraphicBuffer> buffer, int fenceFd, int dataSpace) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800906 ALOGV("%s:", __FUNCTION__);
907 GraphicBuffer* p = NULL;
908 Image_getNativeContext(env, thiz, &p, /*fenceFd*/NULL);
909 if (buffer != 0) {
910 buffer->incStrong((void*)Image_setNativeContext);
911 }
912 if (p) {
913 p->decStrong((void*)Image_setNativeContext);
914 }
915 env->SetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer,
916 reinterpret_cast<jlong>(buffer.get()));
917
918 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
Sally Qiac97f992021-10-11 17:39:54 -0700919
John Recke20a7542022-02-09 08:56:56 -0500920 env->SetIntField(thiz, gSurfaceImageClassInfo.mDataSpace, dataSpace);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800921}
922
923static void Image_unlockIfLocked(JNIEnv* env, jobject thiz) {
924 ALOGV("%s", __FUNCTION__);
925 GraphicBuffer* buffer;
926 Image_getNativeContext(env, thiz, &buffer, NULL);
927 if (buffer == NULL) {
928 jniThrowException(env, "java/lang/IllegalStateException",
929 "Image is not initialized");
930 return;
931 }
932
933 // Is locked?
934 bool isLocked = false;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700935 jobject planes = NULL;
936 if (!isFormatOpaque(buffer->getPixelFormat())) {
937 planes = env->GetObjectField(thiz, gSurfaceImageClassInfo.mPlanes);
938 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800939 isLocked = (planes != NULL);
940 if (isLocked) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700941 // no need to use fence here, as we it will be consumed by either cancel or queue buffer.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800942 status_t res = buffer->unlock();
943 if (res != OK) {
944 jniThrowRuntimeException(env, "unlock buffer failed");
John Reckdcd4c582019-07-12 13:13:05 -0700945 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800946 }
947 ALOGV("Successfully unlocked the image");
948 }
949}
950
951static jint Image_getWidth(JNIEnv* env, jobject thiz) {
952 ALOGV("%s", __FUNCTION__);
953 GraphicBuffer* buffer;
954 Image_getNativeContext(env, thiz, &buffer, NULL);
955 if (buffer == NULL) {
956 jniThrowException(env, "java/lang/IllegalStateException",
957 "Image is not initialized");
958 return -1;
959 }
960
961 return buffer->getWidth();
962}
963
964static jint Image_getHeight(JNIEnv* env, jobject thiz) {
965 ALOGV("%s", __FUNCTION__);
966 GraphicBuffer* buffer;
967 Image_getNativeContext(env, thiz, &buffer, NULL);
968 if (buffer == NULL) {
969 jniThrowException(env, "java/lang/IllegalStateException",
970 "Image is not initialized");
971 return -1;
972 }
973
974 return buffer->getHeight();
975}
976
John Reckffa81f82022-02-04 17:05:30 -0500977static jint Image_getFormat(JNIEnv* env, jobject thiz, jint dataSpace) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800978 ALOGV("%s", __FUNCTION__);
979 GraphicBuffer* buffer;
980 Image_getNativeContext(env, thiz, &buffer, NULL);
981 if (buffer == NULL) {
982 jniThrowException(env, "java/lang/IllegalStateException",
983 "Image is not initialized");
984 return 0;
985 }
986
Fedor Kudasov4d027e92019-06-24 17:21:57 +0100987 PublicFormat publicFmt = mapHalFormatDataspaceToPublicFormat(buffer->getPixelFormat(),
Sally Qid26f4f02022-01-21 09:53:20 -0800988 static_cast<android_dataspace>(dataSpace));
989
Zhijun He0ab41622016-02-25 16:00:38 -0800990 return static_cast<jint>(publicFmt);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800991}
992
rennbe092192018-05-07 10:18:05 -0700993static jobject Image_getHardwareBuffer(JNIEnv* env, jobject thiz) {
994 GraphicBuffer* buffer;
995 Image_getNativeContext(env, thiz, &buffer, NULL);
996 if (buffer == NULL) {
997 jniThrowException(env, "java/lang/IllegalStateException",
998 "Image is not initialized");
999 return NULL;
1000 }
1001 AHardwareBuffer* b = AHardwareBuffer_from_GraphicBuffer(buffer);
1002 // don't user the public AHardwareBuffer_toHardwareBuffer() because this would force us
1003 // to link against libandroid.so
1004 return android_hardware_HardwareBuffer_createFromAHardwareBuffer(env, b);
1005}
1006
Zhijun Hef6a09e52015-02-24 18:12:23 -08001007static void Image_setFenceFd(JNIEnv* env, jobject thiz, int fenceFd) {
1008 ALOGV("%s:", __FUNCTION__);
Sally Qid2087e72022-01-13 14:05:16 -08001009 int curtFenceFd = reinterpret_cast<jint>(
1010 env->GetIntField(thiz,gSurfaceImageClassInfo.mNativeFenceFd));
1011 if (curtFenceFd != -1) {
1012 close(curtFenceFd);
1013 }
Zhijun Hef6a09e52015-02-24 18:12:23 -08001014 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
1015}
1016
1017static void Image_getLockedImage(JNIEnv* env, jobject thiz, LockedImage *image) {
1018 ALOGV("%s", __FUNCTION__);
1019 GraphicBuffer* buffer;
1020 int fenceFd = -1;
1021 Image_getNativeContext(env, thiz, &buffer, &fenceFd);
1022 if (buffer == NULL) {
1023 jniThrowException(env, "java/lang/IllegalStateException",
1024 "Image is not initialized");
1025 return;
1026 }
1027
Zhijun He0ab41622016-02-25 16:00:38 -08001028 // ImageWriter doesn't use crop by itself, app sets it, use the no crop version.
1029 const Rect noCrop(buffer->width, buffer->height);
1030 status_t res = lockImageFromBuffer(
1031 buffer, GRALLOC_USAGE_SW_WRITE_OFTEN, noCrop, fenceFd, image);
1032 // Clear the fenceFd as it is already consumed by lock call.
Brian Kim1165c902022-09-02 08:23:06 +00001033 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, -1);
Zhijun He0ab41622016-02-25 16:00:38 -08001034 if (res != OK) {
1035 jniThrowExceptionFmt(env, "java/lang/RuntimeException",
1036 "lock buffer failed for format 0x%x",
1037 buffer->getPixelFormat());
1038 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001039 }
1040
Zhijun He0ab41622016-02-25 16:00:38 -08001041 ALOGV("%s: Successfully locked the image", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001042 // crop, transform, scalingMode, timestamp, and frameNumber should be set by producer,
1043 // and we don't set them here.
1044}
1045
John Reckdcd4c582019-07-12 13:13:05 -07001046static bool Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
Sally Qi42bd6a62022-09-13 08:14:16 -07001047 int32_t halFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
Zhijun Hef6a09e52015-02-24 18:12:23 -08001048 ALOGV("%s", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001049
Sally Qi42bd6a62022-09-13 08:14:16 -07001050 status_t res = getLockedImageInfo(buffer, idx, halFormat, base, size,
Zhijun He0ab41622016-02-25 16:00:38 -08001051 pixelStride, rowStride);
1052 if (res != OK) {
1053 jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
Sally Qi42bd6a62022-09-13 08:14:16 -07001054 "Pixel format: 0x%x is unsupported", halFormat);
John Reckdcd4c582019-07-12 13:13:05 -07001055 return false;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001056 }
John Reckdcd4c582019-07-12 13:13:05 -07001057 return true;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001058}
1059
1060static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
Sally Qi42bd6a62022-09-13 08:14:16 -07001061 int numPlanes, int writerFormat) {
Zhijun Hef6a09e52015-02-24 18:12:23 -08001062 ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
1063 int rowStride, pixelStride;
1064 uint8_t *pData;
1065 uint32_t dataSize;
1066 jobject byteBuffer;
Sally Qi42bd6a62022-09-13 08:14:16 -07001067 int halFormat = mapPublicFormatToHalFormat(static_cast<PublicFormat>(writerFormat));
Zhijun Hef6a09e52015-02-24 18:12:23 -08001068
Sally Qi42bd6a62022-09-13 08:14:16 -07001069 if (isFormatOpaque(halFormat) && numPlanes > 0) {
Zhijun Hef6a09e52015-02-24 18:12:23 -08001070 String8 msg;
1071 msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
Sally Qi42bd6a62022-09-13 08:14:16 -07001072 " must be 0", writerFormat, numPlanes);
Tomasz Wasilczyk3815d342023-08-10 23:54:44 +00001073 jniThrowException(env, "java/lang/IllegalArgumentException", msg.c_str());
Zhijun Hef6a09e52015-02-24 18:12:23 -08001074 return NULL;
1075 }
1076
1077 jobjectArray surfacePlanes = env->NewObjectArray(numPlanes, gSurfacePlaneClassInfo.clazz,
1078 /*initial_element*/NULL);
1079 if (surfacePlanes == NULL) {
1080 jniThrowRuntimeException(env, "Failed to create SurfacePlane arrays,"
1081 " probably out of memory");
1082 return NULL;
1083 }
Sally Qi42bd6a62022-09-13 08:14:16 -07001084
1085 if (isFormatOpaque(halFormat)) {
Zhijun Hece9d6f92015-03-29 16:33:59 -07001086 return surfacePlanes;
1087 }
Zhijun Hef6a09e52015-02-24 18:12:23 -08001088
1089 // Buildup buffer info: rowStride, pixelStride and byteBuffers.
1090 LockedImage lockedImg = LockedImage();
1091 Image_getLockedImage(env, thiz, &lockedImg);
1092
1093 // Create all SurfacePlanes
Zhijun Hef6a09e52015-02-24 18:12:23 -08001094 for (int i = 0; i < numPlanes; i++) {
Sally Qi42bd6a62022-09-13 08:14:16 -07001095 if (!Image_getLockedImageInfo(env, &lockedImg, i, halFormat,
John Reckdcd4c582019-07-12 13:13:05 -07001096 &pData, &dataSize, &pixelStride, &rowStride)) {
1097 return NULL;
1098 }
Zhijun Hef6a09e52015-02-24 18:12:23 -08001099 byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
1100 if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
1101 jniThrowException(env, "java/lang/IllegalStateException",
1102 "Failed to allocate ByteBuffer");
1103 return NULL;
1104 }
1105
1106 // Finally, create this SurfacePlane.
1107 jobject surfacePlane = env->NewObject(gSurfacePlaneClassInfo.clazz,
1108 gSurfacePlaneClassInfo.ctor, thiz, rowStride, pixelStride, byteBuffer);
1109 env->SetObjectArrayElement(surfacePlanes, i, surfacePlane);
1110 }
1111
1112 return surfacePlanes;
1113}
1114
Zhijun Hef6a09e52015-02-24 18:12:23 -08001115} // extern "C"
1116
1117// ----------------------------------------------------------------------------
1118
1119static JNINativeMethod gImageWriterMethods[] = {
1120 {"nativeClassInit", "()V", (void*)ImageWriter_classInit },
John Reckffa81f82022-02-04 17:05:30 -05001121 {"nativeInit", "(Ljava/lang/Object;Landroid/view/Surface;IIIZIIJ)J",
Zhijun Hef6a09e52015-02-24 18:12:23 -08001122 (void*)ImageWriter_init },
Zhijun Hece9d6f92015-03-29 16:33:59 -07001123 {"nativeClose", "(J)V", (void*)ImageWriter_close },
Sally Qiac97f992021-10-11 17:39:54 -07001124 {"nativeAttachAndQueueImage",
John Reckffa81f82022-02-04 17:05:30 -05001125 "(JJIJIIIIIII)I",
Sally Qiac97f992021-10-11 17:39:54 -07001126 (void*)ImageWriter_attachAndQueueImage },
Emilian Peev9c778e12020-10-29 17:36:22 -07001127 {"nativeAttachAndQueueGraphicBuffer",
John Reckffa81f82022-02-04 17:05:30 -05001128 "(JLandroid/graphics/GraphicBuffer;IJIIIIIII)I",
Emilian Peev9c778e12020-10-29 17:36:22 -07001129 (void*)ImageWriter_attachAndQueueGraphicBuffer },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001130 {"nativeDequeueInputImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_dequeueImage },
John Reckffa81f82022-02-04 17:05:30 -05001131 {"nativeQueueInputImage", "(JLandroid/media/Image;JIIIIIII)V",
Sally Qiac97f992021-10-11 17:39:54 -07001132 (void*)ImageWriter_queueImage },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001133 {"cancelImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_cancelImage },
1134};
1135
1136static JNINativeMethod gImageMethods[] = {
Sally Qi42bd6a62022-09-13 08:14:16 -07001137 {"nativeCreatePlanes", "(II)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
rennbe092192018-05-07 10:18:05 -07001138 (void*)Image_createSurfacePlanes },
1139 {"nativeGetWidth", "()I", (void*)Image_getWidth },
1140 {"nativeGetHeight", "()I", (void*)Image_getHeight },
John Reckffa81f82022-02-04 17:05:30 -05001141 {"nativeGetFormat", "(I)I", (void*)Image_getFormat },
Sally Qid2087e72022-01-13 14:05:16 -08001142 {"nativeSetFenceFd", "(I)V", (void*)Image_setFenceFd },
rennbe092192018-05-07 10:18:05 -07001143 {"nativeGetHardwareBuffer", "()Landroid/hardware/HardwareBuffer;",
1144 (void*)Image_getHardwareBuffer },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001145};
1146
1147int register_android_media_ImageWriter(JNIEnv *env) {
1148
1149 int ret1 = AndroidRuntime::registerNativeMethods(env,
1150 "android/media/ImageWriter", gImageWriterMethods, NELEM(gImageWriterMethods));
1151
1152 int ret2 = AndroidRuntime::registerNativeMethods(env,
1153 "android/media/ImageWriter$WriterSurfaceImage", gImageMethods, NELEM(gImageMethods));
1154
1155 return (ret1 || ret2);
1156}