blob: fbc4bb9f9a81f4f1dd8c655abbc7ab17d5a48600 [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
27#include <gui/IProducerListener.h>
28#include <gui/Surface.h>
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -070029#include <ui/PublicFormat.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080030#include <android_runtime/AndroidRuntime.h>
31#include <android_runtime/android_view_Surface.h>
Emilian Peev9c778e12020-10-29 17:36:22 -070032#include <android_runtime/android_graphics_GraphicBuffer.h>
rennbe092192018-05-07 10:18:05 -070033#include <android_runtime/android_hardware_HardwareBuffer.h>
34#include <private/android/AHardwareBufferHelpers.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080035#include <jni.h>
Steven Moreland2279b252017-07-19 09:50:45 -070036#include <nativehelper/JNIHelp.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080037
38#include <stdint.h>
39#include <inttypes.h>
rennbe092192018-05-07 10:18:05 -070040#include <android/hardware_buffer_jni.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080041
Yin-Chia Yeh6132b022019-02-14 16:40:20 -080042#include <deque>
43
Zhijun Hef6a09e52015-02-24 18:12:23 -080044#define IMAGE_BUFFER_JNI_ID "mNativeBuffer"
Zhijun Hef6a09e52015-02-24 18:12:23 -080045// ----------------------------------------------------------------------------
46
47using namespace android;
48
Zhijun Hef6a09e52015-02-24 18:12:23 -080049static struct {
50 jmethodID postEventFromNative;
51 jfieldID mWriterFormat;
52} gImageWriterClassInfo;
53
54static struct {
Sally Qiac97f992021-10-11 17:39:54 -070055 jfieldID mDataSpace;
Zhijun Hef6a09e52015-02-24 18:12:23 -080056 jfieldID mNativeBuffer;
57 jfieldID mNativeFenceFd;
58 jfieldID mPlanes;
59} gSurfaceImageClassInfo;
60
61static struct {
62 jclass clazz;
63 jmethodID ctor;
64} gSurfacePlaneClassInfo;
65
Zhijun Hef6a09e52015-02-24 18:12:23 -080066// ----------------------------------------------------------------------------
67
68class JNIImageWriterContext : public BnProducerListener {
69public:
70 JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz);
71
72 virtual ~JNIImageWriterContext();
73
74 // Implementation of IProducerListener, used to notify the ImageWriter that the consumer
75 // has returned a buffer and it is ready for ImageWriter to dequeue.
76 virtual void onBufferReleased();
77
Zhijun Hece9d6f92015-03-29 16:33:59 -070078 void setProducer(const sp<Surface>& producer) { mProducer = producer; }
79 Surface* getProducer() { return mProducer.get(); }
Zhijun Hef6a09e52015-02-24 18:12:23 -080080
81 void setBufferFormat(int format) { mFormat = format; }
82 int getBufferFormat() { return mFormat; }
83
84 void setBufferWidth(int width) { mWidth = width; }
85 int getBufferWidth() { return mWidth; }
86
87 void setBufferHeight(int height) { mHeight = height; }
88 int getBufferHeight() { return mHeight; }
89
Sally Qiac97f992021-10-11 17:39:54 -070090 void setBufferDataSpace(android_dataspace dataSpace) { mDataSpace = dataSpace; }
91 android_dataspace getBufferDataSpace() { return mDataSpace; }
92
Shuzhen Wangb9adb572020-06-24 09:33:27 -070093 void queueAttachedFlag(bool isAttached) {
94 Mutex::Autolock l(mAttachedFlagQueueLock);
95 mAttachedFlagQueue.push_back(isAttached);
96 }
97 void dequeueAttachedFlag() {
98 Mutex::Autolock l(mAttachedFlagQueueLock);
99 mAttachedFlagQueue.pop_back();
100 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800101private:
102 static JNIEnv* getJNIEnv(bool* needsDetach);
103 static void detachJNI();
104
Zhijun Hece9d6f92015-03-29 16:33:59 -0700105 sp<Surface> mProducer;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800106 jobject mWeakThiz;
107 jclass mClazz;
108 int mFormat;
109 int mWidth;
110 int mHeight;
Sally Qiac97f992021-10-11 17:39:54 -0700111 android_dataspace mDataSpace;
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800112
113 // Class for a shared thread used to detach buffers from buffer queues
114 // to discard buffers after consumers are done using them.
115 // This is needed because detaching buffers in onBufferReleased callback
116 // can lead to deadlock when consumer/producer are on the same process.
117 class BufferDetacher {
118 public:
119 // Called by JNIImageWriterContext ctor. Will start the thread for first ref.
120 void addRef();
121 // Called by JNIImageWriterContext dtor. Will stop the thread after ref goes to 0.
122 void removeRef();
123 // Called by onBufferReleased to signal this thread to detach a buffer
124 void detach(wp<Surface>);
125
126 private:
127
128 class DetachThread : public Thread {
129 public:
130 DetachThread() : Thread(/*canCallJava*/false) {};
131
132 void detach(wp<Surface>);
133
134 virtual void requestExit() override;
135
136 private:
137 virtual bool threadLoop() override;
138
139 Mutex mLock;
140 Condition mCondition;
141 std::deque<wp<Surface>> mQueue;
142
Yin-Chia Yehedace1a2019-07-30 13:02:59 -0700143 static const nsecs_t kWaitDuration = 500000000; // 500 ms
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800144 };
145 sp<DetachThread> mThread;
146
147 Mutex mLock;
148 int mRefCount = 0;
149 };
150
151 static BufferDetacher sBufferDetacher;
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700152
153 // Buffer queue guarantees both producer and consumer side buffer flows are
154 // in order. See b/19977520. As a result, we can use a queue here.
155 Mutex mAttachedFlagQueueLock;
156 std::deque<bool> mAttachedFlagQueue;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800157};
158
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800159JNIImageWriterContext::BufferDetacher JNIImageWriterContext::sBufferDetacher;
160
161void JNIImageWriterContext::BufferDetacher::addRef() {
162 Mutex::Autolock l(mLock);
163 mRefCount++;
164 if (mRefCount == 1) {
165 mThread = new DetachThread();
166 mThread->run("BufDtchThrd");
167 }
168}
169
170void JNIImageWriterContext::BufferDetacher::removeRef() {
171 Mutex::Autolock l(mLock);
172 mRefCount--;
173 if (mRefCount == 0) {
174 mThread->requestExit();
175 mThread->join();
176 mThread.clear();
177 }
178}
179
180void JNIImageWriterContext::BufferDetacher::detach(wp<Surface> bq) {
181 Mutex::Autolock l(mLock);
182 if (mThread == nullptr) {
183 ALOGE("%s: buffer detach thread is gone!", __FUNCTION__);
184 return;
185 }
186 mThread->detach(bq);
187}
188
189void JNIImageWriterContext::BufferDetacher::DetachThread::detach(wp<Surface> bq) {
190 Mutex::Autolock l(mLock);
191 mQueue.push_back(bq);
192 mCondition.signal();
193}
194
195void JNIImageWriterContext::BufferDetacher::DetachThread::requestExit() {
196 Thread::requestExit();
197 {
198 Mutex::Autolock l(mLock);
199 mQueue.clear();
200 }
201 mCondition.signal();
202}
203
204bool JNIImageWriterContext::BufferDetacher::DetachThread::threadLoop() {
205 Mutex::Autolock l(mLock);
206 mCondition.waitRelative(mLock, kWaitDuration);
207
208 while (!mQueue.empty()) {
209 if (exitPending()) {
210 return false;
211 }
212
213 wp<Surface> wbq = mQueue.front();
214 mQueue.pop_front();
215 sp<Surface> bq = wbq.promote();
216 if (bq != nullptr) {
217 sp<Fence> fence;
218 sp<GraphicBuffer> buffer;
219 ALOGV("%s: One buffer is detached", __FUNCTION__);
220 mLock.unlock();
221 bq->detachNextBuffer(&buffer, &fence);
222 mLock.lock();
223 }
224 }
225 return !exitPending();
226}
227
Zhijun Hef6a09e52015-02-24 18:12:23 -0800228JNIImageWriterContext::JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz) :
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800229 mWeakThiz(env->NewGlobalRef(weakThiz)),
230 mClazz((jclass)env->NewGlobalRef(clazz)),
231 mFormat(0),
232 mWidth(-1),
233 mHeight(-1) {
234 sBufferDetacher.addRef();
Zhijun Hef6a09e52015-02-24 18:12:23 -0800235}
236
237JNIImageWriterContext::~JNIImageWriterContext() {
238 ALOGV("%s", __FUNCTION__);
239 bool needsDetach = false;
240 JNIEnv* env = getJNIEnv(&needsDetach);
241 if (env != NULL) {
242 env->DeleteGlobalRef(mWeakThiz);
243 env->DeleteGlobalRef(mClazz);
244 } else {
245 ALOGW("leaking JNI object references");
246 }
247 if (needsDetach) {
248 detachJNI();
249 }
250
251 mProducer.clear();
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800252 sBufferDetacher.removeRef();
Zhijun Hef6a09e52015-02-24 18:12:23 -0800253}
254
255JNIEnv* JNIImageWriterContext::getJNIEnv(bool* needsDetach) {
256 ALOGV("%s", __FUNCTION__);
257 LOG_ALWAYS_FATAL_IF(needsDetach == NULL, "needsDetach is null!!!");
258 *needsDetach = false;
259 JNIEnv* env = AndroidRuntime::getJNIEnv();
260 if (env == NULL) {
261 JavaVMAttachArgs args = {JNI_VERSION_1_4, NULL, NULL};
262 JavaVM* vm = AndroidRuntime::getJavaVM();
263 int result = vm->AttachCurrentThread(&env, (void*) &args);
264 if (result != JNI_OK) {
265 ALOGE("thread attach failed: %#x", result);
266 return NULL;
267 }
268 *needsDetach = true;
269 }
270 return env;
271}
272
273void JNIImageWriterContext::detachJNI() {
274 ALOGV("%s", __FUNCTION__);
275 JavaVM* vm = AndroidRuntime::getJavaVM();
276 int result = vm->DetachCurrentThread();
277 if (result != JNI_OK) {
278 ALOGE("thread detach failed: %#x", result);
279 }
280}
281
282void JNIImageWriterContext::onBufferReleased() {
283 ALOGV("%s: buffer released", __FUNCTION__);
284 bool needsDetach = false;
285 JNIEnv* env = getJNIEnv(&needsDetach);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700286
287 bool bufferIsAttached = false;
288 {
289 Mutex::Autolock l(mAttachedFlagQueueLock);
290 if (!mAttachedFlagQueue.empty()) {
291 bufferIsAttached = mAttachedFlagQueue.front();
292 mAttachedFlagQueue.pop_front();
293 } else {
294 ALOGW("onBufferReleased called with no attached flag queued");
295 }
296 }
297
Zhijun Hef6a09e52015-02-24 18:12:23 -0800298 if (env != NULL) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700299 // Detach the buffer every time when a buffer consumption is done,
300 // need let this callback give a BufferItem, then only detach if it was attached to this
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700301 // Writer. see b/19977520
302 if (mFormat == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED || bufferIsAttached) {
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800303 sBufferDetacher.detach(mProducer);
Zhijun Hece9d6f92015-03-29 16:33:59 -0700304 }
305
Zhijun Hef6a09e52015-02-24 18:12:23 -0800306 env->CallStaticVoidMethod(mClazz, gImageWriterClassInfo.postEventFromNative, mWeakThiz);
307 } else {
308 ALOGW("onBufferReleased event will not posted");
309 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700310
Zhijun Hef6a09e52015-02-24 18:12:23 -0800311 if (needsDetach) {
312 detachJNI();
313 }
314}
315
316// ----------------------------------------------------------------------------
317
318extern "C" {
319
320// -------------------------------Private method declarations--------------
321
Zhijun Hef6a09e52015-02-24 18:12:23 -0800322static void Image_setNativeContext(JNIEnv* env, jobject thiz,
John Reckffa81f82022-02-04 17:05:30 -0500323 sp<GraphicBuffer> buffer, int fenceFd, int dataSpace);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800324static void Image_getNativeContext(JNIEnv* env, jobject thiz,
325 GraphicBuffer** buffer, int* fenceFd);
326static void Image_unlockIfLocked(JNIEnv* env, jobject thiz);
327
328// --------------------------ImageWriter methods---------------------------------------
329
330static void ImageWriter_classInit(JNIEnv* env, jclass clazz) {
331 ALOGV("%s:", __FUNCTION__);
332 jclass imageClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage");
333 LOG_ALWAYS_FATAL_IF(imageClazz == NULL,
334 "can't find android/media/ImageWriter$WriterSurfaceImage");
Sally Qiac97f992021-10-11 17:39:54 -0700335
336 gSurfaceImageClassInfo.mDataSpace = env->GetFieldID(
John Reckffa81f82022-02-04 17:05:30 -0500337 imageClazz, "mDataSpace", "I");
Sally Qiac97f992021-10-11 17:39:54 -0700338 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mDataSpace == NULL,
339 "can't find android/media/ImageWriter$WriterSurfaceImage.mDataSpace");
340
Zhijun Hef6a09e52015-02-24 18:12:23 -0800341 gSurfaceImageClassInfo.mNativeBuffer = env->GetFieldID(
342 imageClazz, IMAGE_BUFFER_JNI_ID, "J");
343 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeBuffer == NULL,
344 "can't find android/media/ImageWriter$WriterSurfaceImage.%s", IMAGE_BUFFER_JNI_ID);
345
346 gSurfaceImageClassInfo.mNativeFenceFd = env->GetFieldID(
347 imageClazz, "mNativeFenceFd", "I");
348 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeFenceFd == NULL,
349 "can't find android/media/ImageWriter$WriterSurfaceImage.mNativeFenceFd");
350
351 gSurfaceImageClassInfo.mPlanes = env->GetFieldID(
352 imageClazz, "mPlanes", "[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;");
353 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mPlanes == NULL,
354 "can't find android/media/ImageWriter$WriterSurfaceImage.mPlanes");
355
356 gImageWriterClassInfo.postEventFromNative = env->GetStaticMethodID(
357 clazz, "postEventFromNative", "(Ljava/lang/Object;)V");
358 LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.postEventFromNative == NULL,
359 "can't find android/media/ImageWriter.postEventFromNative");
360
361 gImageWriterClassInfo.mWriterFormat = env->GetFieldID(
362 clazz, "mWriterFormat", "I");
363 LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.mWriterFormat == NULL,
364 "can't find android/media/ImageWriter.mWriterFormat");
365
366 jclass planeClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage$SurfacePlane");
367 LOG_ALWAYS_FATAL_IF(planeClazz == NULL, "Can not find SurfacePlane class");
368 // FindClass only gives a local reference of jclass object.
369 gSurfacePlaneClassInfo.clazz = (jclass) env->NewGlobalRef(planeClazz);
370 gSurfacePlaneClassInfo.ctor = env->GetMethodID(gSurfacePlaneClassInfo.clazz, "<init>",
371 "(Landroid/media/ImageWriter$WriterSurfaceImage;IILjava/nio/ByteBuffer;)V");
372 LOG_ALWAYS_FATAL_IF(gSurfacePlaneClassInfo.ctor == NULL,
373 "Can not find SurfacePlane constructor");
374}
375
376static jlong ImageWriter_init(JNIEnv* env, jobject thiz, jobject weakThiz, jobject jsurface,
Sally Qidb57de32022-01-05 11:53:44 -0800377 jint maxImages, jint userWidth, jint userHeight, jboolean useSurfaceImageFormatInfo,
John Reckffa81f82022-02-04 17:05:30 -0500378 jint hardwareBufferFormat, jint dataSpace, jlong ndkUsage) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800379 status_t res;
380
381 ALOGV("%s: maxImages:%d", __FUNCTION__, maxImages);
382
383 sp<Surface> surface(android_view_Surface_getSurface(env, jsurface));
384 if (surface == NULL) {
385 jniThrowException(env,
386 "java/lang/IllegalArgumentException",
387 "The surface has been released");
388 return 0;
389 }
390 sp<IGraphicBufferProducer> bufferProducer = surface->getIGraphicBufferProducer();
391
392 jclass clazz = env->GetObjectClass(thiz);
393 if (clazz == NULL) {
394 jniThrowRuntimeException(env, "Can't find android/graphics/ImageWriter");
395 return 0;
396 }
397 sp<JNIImageWriterContext> ctx(new JNIImageWriterContext(env, weakThiz, clazz));
398
399 sp<Surface> producer = new Surface(bufferProducer, /*controlledByApp*/false);
400 ctx->setProducer(producer);
401 /**
402 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not connectable
403 * after disconnect. MEDIA or CAMERA are treated the same internally. The producer listener
404 * will be cleared after disconnect call.
405 */
Emilian Peev2adf4032018-06-05 17:52:16 +0100406 res = producer->connect(/*api*/NATIVE_WINDOW_API_CAMERA, /*listener*/ctx);
407 if (res != OK) {
408 ALOGE("%s: Connecting to surface producer interface failed: %s (%d)",
409 __FUNCTION__, strerror(-res), res);
410 jniThrowRuntimeException(env, "Failed to connect to native window");
411 return 0;
412 }
413
Zhijun Hef6a09e52015-02-24 18:12:23 -0800414 jlong nativeCtx = reinterpret_cast<jlong>(ctx.get());
415
416 // Get the dimension and format of the producer.
417 sp<ANativeWindow> anw = producer;
Zhijun He916d8ac2017-03-22 17:33:47 -0700418 int32_t width, height, surfaceFormat;
Emilian Peevab808242020-12-28 16:03:32 -0800419 if (userWidth < 0) {
420 if ((res = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, &width)) != OK) {
421 ALOGE("%s: Query Surface width failed: %s (%d)", __FUNCTION__, strerror(-res), res);
422 jniThrowRuntimeException(env, "Failed to query Surface width");
423 return 0;
424 }
425 } else {
426 width = userWidth;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800427 }
Emilian Peevab808242020-12-28 16:03:32 -0800428
Zhijun Hef6a09e52015-02-24 18:12:23 -0800429 ctx->setBufferWidth(width);
430
Emilian Peevab808242020-12-28 16:03:32 -0800431 if (userHeight < 0) {
432 if ((res = anw->query(anw.get(), NATIVE_WINDOW_HEIGHT, &height)) != OK) {
433 ALOGE("%s: Query Surface height failed: %s (%d)", __FUNCTION__, strerror(-res), res);
434 jniThrowRuntimeException(env, "Failed to query Surface height");
435 return 0;
436 }
437 } else {
438 height = userHeight;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800439 }
440 ctx->setBufferHeight(height);
441
Emilian Peevab808242020-12-28 16:03:32 -0800442 if ((userWidth > 0) && (userHeight > 0)) {
443 res = native_window_set_buffers_user_dimensions(anw.get(), userWidth, userHeight);
444 if (res != OK) {
445 ALOGE("%s: Set buffer dimensions failed: %s (%d)", __FUNCTION__, strerror(-res), res);
446 jniThrowRuntimeException(env, "Set buffer dimensions failed");
447 return 0;
448 }
449 }
450
Zhijun He916d8ac2017-03-22 17:33:47 -0700451 // Query surface format if no valid user format is specified, otherwise, override surface format
452 // with user format.
Sally Qidb57de32022-01-05 11:53:44 -0800453 if (useSurfaceImageFormatInfo) {
Zhijun He916d8ac2017-03-22 17:33:47 -0700454 if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &surfaceFormat)) != OK) {
455 ALOGE("%s: Query Surface format failed: %s (%d)", __FUNCTION__, strerror(-res), res);
456 jniThrowRuntimeException(env, "Failed to query Surface format");
457 return 0;
458 }
459 } else {
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700460 // Set consumer buffer format to user specified format
Sally Qidb57de32022-01-05 11:53:44 -0800461 android_dataspace nativeDataspace = static_cast<android_dataspace>(dataSpace);
Sally Qidb57de32022-01-05 11:53:44 -0800462 res = native_window_set_buffers_format(anw.get(), hardwareBufferFormat);
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700463 if (res != OK) {
464 ALOGE("%s: Unable to configure consumer native buffer format to %#x",
Sally Qidb57de32022-01-05 11:53:44 -0800465 __FUNCTION__, hardwareBufferFormat);
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700466 jniThrowRuntimeException(env, "Failed to set Surface format");
467 return 0;
468 }
469
470 res = native_window_set_buffers_data_space(anw.get(), nativeDataspace);
471 if (res != OK) {
472 ALOGE("%s: Unable to configure consumer dataspace %#x",
473 __FUNCTION__, nativeDataspace);
474 jniThrowRuntimeException(env, "Failed to set Surface dataspace");
475 return 0;
476 }
Sally Qiac97f992021-10-11 17:39:54 -0700477 ctx->setBufferDataSpace(nativeDataspace);
Sally Qid26f4f02022-01-21 09:53:20 -0800478 surfaceFormat = static_cast<int32_t>(mapHalFormatDataspaceToPublicFormat(
479 hardwareBufferFormat, nativeDataspace));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800480 }
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700481
Zhijun He916d8ac2017-03-22 17:33:47 -0700482 ctx->setBufferFormat(surfaceFormat);
483 env->SetIntField(thiz,
484 gImageWriterClassInfo.mWriterFormat, reinterpret_cast<jint>(surfaceFormat));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800485
Sally Qid26f4f02022-01-21 09:53:20 -0800486 // ndkUsage == -1 means setUsage in ImageWriter class is not called.
487 // skip usage setting if setUsage in ImageWriter is not called and imageformat is opaque.
488 if (!(ndkUsage == -1 && isFormatOpaque(surfaceFormat))) {
489 if (ndkUsage == -1) {
490 ndkUsage = GRALLOC_USAGE_SW_WRITE_OFTEN;
491 }
492 res = native_window_set_usage(anw.get(), ndkUsage);
493 if (res != OK) {
494 ALOGE("%s: Configure usage %08x for format %08x failed: %s (%d)",
495 __FUNCTION__, static_cast<unsigned int>(ndkUsage),
496 surfaceFormat, strerror(-res), res);
497 jniThrowRuntimeException(env,
498 "Failed to SW_WRITE_OFTEN configure usage");
499 return 0;
500 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800501 }
502
503 int minUndequeuedBufferCount = 0;
504 res = anw->query(anw.get(),
505 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufferCount);
506 if (res != OK) {
507 ALOGE("%s: Query producer undequeued buffer count failed: %s (%d)",
508 __FUNCTION__, strerror(-res), res);
509 jniThrowRuntimeException(env, "Query producer undequeued buffer count failed");
510 return 0;
511 }
512
513 size_t totalBufferCount = maxImages + minUndequeuedBufferCount;
514 res = native_window_set_buffer_count(anw.get(), totalBufferCount);
515 if (res != OK) {
516 ALOGE("%s: Set buffer count failed: %s (%d)", __FUNCTION__, strerror(-res), res);
517 jniThrowRuntimeException(env, "Set buffer count failed");
518 return 0;
519 }
520
521 if (ctx != 0) {
522 ctx->incStrong((void*)ImageWriter_init);
523 }
524 return nativeCtx;
525}
526
527static void ImageWriter_dequeueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
528 ALOGV("%s", __FUNCTION__);
529 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
530 if (ctx == NULL || thiz == NULL) {
531 jniThrowException(env, "java/lang/IllegalStateException",
532 "ImageWriterContext is not initialized");
533 return;
534 }
535
536 sp<ANativeWindow> anw = ctx->getProducer();
537 android_native_buffer_t *anb = NULL;
538 int fenceFd = -1;
539 status_t res = anw->dequeueBuffer(anw.get(), &anb, &fenceFd);
540 if (res != OK) {
Zhijun Hea5827142015-04-22 10:07:42 -0700541 ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700542 switch (res) {
543 case NO_INIT:
544 jniThrowException(env, "java/lang/IllegalStateException",
545 "Surface has been abandoned");
546 break;
547 default:
548 // TODO: handle other error cases here.
549 jniThrowRuntimeException(env, "dequeue buffer failed");
550 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800551 return;
552 }
553 // New GraphicBuffer object doesn't own the handle, thus the native buffer
554 // won't be freed when this object is destroyed.
Mathias Agopian845eef05f2017-04-03 17:51:15 -0700555 sp<GraphicBuffer> buffer(GraphicBuffer::from(anb));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800556
557 // Note that:
558 // 1. No need to lock buffer now, will only lock it when the first getPlanes() is called.
559 // 2. Fence will be saved to mNativeFenceFd, and will consumed by lock/queue/cancel buffer
560 // later.
561 // 3. need use lockAsync here, as it will handle the dequeued fence for us automatically.
562
563 // Finally, set the native info into image object.
Sally Qiac97f992021-10-11 17:39:54 -0700564 Image_setNativeContext(env, image, buffer, fenceFd, ctx->getBufferDataSpace());
Zhijun Hef6a09e52015-02-24 18:12:23 -0800565}
566
567static void ImageWriter_close(JNIEnv* env, jobject thiz, jlong nativeCtx) {
568 ALOGV("%s:", __FUNCTION__);
569 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
570 if (ctx == NULL || thiz == NULL) {
Chien-Yu Chen0375cb02015-06-18 11:55:18 -0700571 // ImageWriter is already closed.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800572 return;
573 }
574
575 ANativeWindow* producer = ctx->getProducer();
576 if (producer != NULL) {
577 /**
578 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not
579 * connectable after disconnect. MEDIA or CAMERA are treated the same internally.
580 * The producer listener will be cleared after disconnect call.
581 */
582 status_t res = native_window_api_disconnect(producer, /*api*/NATIVE_WINDOW_API_CAMERA);
583 /**
584 * This is not an error. if client calling process dies, the window will
585 * also die and all calls to it will return DEAD_OBJECT, thus it's already
586 * "disconnected"
587 */
588 if (res == DEAD_OBJECT) {
589 ALOGW("%s: While disconnecting ImageWriter from native window, the"
590 " native window died already", __FUNCTION__);
591 } else if (res != OK) {
592 ALOGE("%s: native window disconnect failed: %s (%d)",
593 __FUNCTION__, strerror(-res), res);
594 jniThrowRuntimeException(env, "Native window disconnect failed");
595 return;
596 }
597 }
598
599 ctx->decStrong((void*)ImageWriter_init);
600}
601
602static void ImageWriter_cancelImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
603 ALOGV("%s", __FUNCTION__);
604 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
605 if (ctx == NULL || thiz == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800606 ALOGW("ImageWriter#close called before Image#close, consider calling Image#close first");
Zhijun Hef6a09e52015-02-24 18:12:23 -0800607 return;
608 }
609
610 sp<ANativeWindow> anw = ctx->getProducer();
611
612 GraphicBuffer *buffer = NULL;
613 int fenceFd = -1;
614 Image_getNativeContext(env, image, &buffer, &fenceFd);
615 if (buffer == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800616 // Cancel an already cancelled image is harmless.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800617 return;
618 }
619
620 // Unlock the image if it was locked
621 Image_unlockIfLocked(env, image);
622
623 anw->cancelBuffer(anw.get(), buffer, fenceFd);
624
Sally Qiac97f992021-10-11 17:39:54 -0700625 Image_setNativeContext(env, image, NULL, -1, HAL_DATASPACE_UNKNOWN);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800626}
627
628static void ImageWriter_queueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image,
John Reckffa81f82022-02-04 17:05:30 -0500629 jlong timestampNs, jint dataSpace, jint left, jint top, jint right,
Sally Qiac97f992021-10-11 17:39:54 -0700630 jint bottom, jint transform, jint scalingMode) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800631 ALOGV("%s", __FUNCTION__);
632 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
633 if (ctx == NULL || thiz == NULL) {
634 jniThrowException(env, "java/lang/IllegalStateException",
635 "ImageWriterContext is not initialized");
636 return;
637 }
638
639 status_t res = OK;
640 sp<ANativeWindow> anw = ctx->getProducer();
641
642 GraphicBuffer *buffer = NULL;
643 int fenceFd = -1;
644 Image_getNativeContext(env, image, &buffer, &fenceFd);
645 if (buffer == NULL) {
646 jniThrowException(env, "java/lang/IllegalStateException",
647 "Image is not initialized");
648 return;
649 }
650
651 // Unlock image if it was locked.
652 Image_unlockIfLocked(env, image);
653
654 // Set timestamp
Zhijun Hed1cbc682015-03-23 10:10:04 -0700655 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800656 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
657 if (res != OK) {
658 jniThrowRuntimeException(env, "Set timestamp failed");
659 return;
660 }
661
Sally Qiac97f992021-10-11 17:39:54 -0700662 // Set dataSpace
John Reckffa81f82022-02-04 17:05:30 -0500663 ALOGV("dataSpace to be queued: %d", dataSpace);
Sally Qiac97f992021-10-11 17:39:54 -0700664 res = native_window_set_buffers_data_space(
665 anw.get(), static_cast<android_dataspace>(dataSpace));
666 if (res != OK) {
667 jniThrowRuntimeException(env, "Set dataspace failed");
668 return;
669 }
670
Zhijun Hef6a09e52015-02-24 18:12:23 -0800671 // Set crop
672 android_native_rect_t cropRect;
673 cropRect.left = left;
674 cropRect.top = top;
675 cropRect.right = right;
676 cropRect.bottom = bottom;
677 res = native_window_set_crop(anw.get(), &cropRect);
678 if (res != OK) {
679 jniThrowRuntimeException(env, "Set crop rect failed");
680 return;
681 }
682
Emilian Peev450a5ff2018-03-19 16:05:10 +0000683 res = native_window_set_buffers_transform(anw.get(), transform);
684 if (res != OK) {
685 jniThrowRuntimeException(env, "Set transform failed");
686 return;
687 }
688
Emilian Peev750aec62018-04-06 12:55:00 +0100689 res = native_window_set_scaling_mode(anw.get(), scalingMode);
690 if (res != OK) {
691 jniThrowRuntimeException(env, "Set scaling mode failed");
692 return;
693 }
694
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700695 // Finally, queue input buffer.
696 //
697 // Because onBufferReleased may be called before queueBuffer() returns,
698 // queue the "attached" flag before calling queueBuffer. In case
699 // queueBuffer() fails, remove it from the queue.
700 ctx->queueAttachedFlag(false);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800701 res = anw->queueBuffer(anw.get(), buffer, fenceFd);
702 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700703 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700704 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700705 switch (res) {
706 case NO_INIT:
707 jniThrowException(env, "java/lang/IllegalStateException",
708 "Surface has been abandoned");
709 break;
710 default:
711 // TODO: handle other error cases here.
712 jniThrowRuntimeException(env, "Queue input buffer failed");
713 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800714 return;
715 }
716
Zhijun Hece9d6f92015-03-29 16:33:59 -0700717 // Clear the image native context: end of this image's lifecycle in public API.
Sally Qiac97f992021-10-11 17:39:54 -0700718 Image_setNativeContext(env, image, NULL, -1, HAL_DATASPACE_UNKNOWN);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800719}
720
Emilian Peev9c778e12020-10-29 17:36:22 -0700721static status_t attachAndQeueuGraphicBuffer(JNIEnv* env, JNIImageWriterContext *ctx,
John Reckffa81f82022-02-04 17:05:30 -0500722 sp<Surface> surface, sp<GraphicBuffer> gb, jlong timestampNs, jint dataSpace,
Sally Qiac97f992021-10-11 17:39:54 -0700723 jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700724 status_t res = OK;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700725 // Step 1. Attach Image
Emilian Peev9c778e12020-10-29 17:36:22 -0700726 res = surface->attachBuffer(gb.get());
Zhijun Hece9d6f92015-03-29 16:33:59 -0700727 if (res != OK) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700728 ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700729 switch (res) {
730 case NO_INIT:
731 jniThrowException(env, "java/lang/IllegalStateException",
732 "Surface has been abandoned");
733 break;
734 default:
735 // TODO: handle other error cases here.
736 jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
737 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700738 return res;
739 }
740 sp < ANativeWindow > anw = surface;
741
Sally Qiac97f992021-10-11 17:39:54 -0700742 // Step 2. Set timestamp, dataspace, crop, transform and scaling mode.
743 // Note that we do not need unlock the image because it was not locked.
Zhijun Hece9d6f92015-03-29 16:33:59 -0700744 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
745 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
746 if (res != OK) {
747 jniThrowRuntimeException(env, "Set timestamp failed");
748 return res;
749 }
750
John Reckffa81f82022-02-04 17:05:30 -0500751 ALOGV("dataSpace to be queued: %" PRId32, dataSpace);
Sally Qiac97f992021-10-11 17:39:54 -0700752 res = native_window_set_buffers_data_space(
753 anw.get(), static_cast<android_dataspace>(dataSpace));
754 if (res != OK) {
755 jniThrowRuntimeException(env, "Set dataSpace failed");
756 return res;
757 }
758
Zhijun Hece9d6f92015-03-29 16:33:59 -0700759 android_native_rect_t cropRect;
760 cropRect.left = left;
761 cropRect.top = top;
762 cropRect.right = right;
763 cropRect.bottom = bottom;
764 res = native_window_set_crop(anw.get(), &cropRect);
765 if (res != OK) {
766 jniThrowRuntimeException(env, "Set crop rect failed");
767 return res;
768 }
769
Emilian Peev450a5ff2018-03-19 16:05:10 +0000770 res = native_window_set_buffers_transform(anw.get(), transform);
771 if (res != OK) {
772 jniThrowRuntimeException(env, "Set transform failed");
773 return res;
774 }
775
Emilian Peev750aec62018-04-06 12:55:00 +0100776 res = native_window_set_scaling_mode(anw.get(), scalingMode);
777 if (res != OK) {
778 jniThrowRuntimeException(env, "Set scaling mode failed");
779 return res;
780 }
781
Zhijun Hece9d6f92015-03-29 16:33:59 -0700782 // Step 3. Queue Image.
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700783 //
784 // Because onBufferReleased may be called before queueBuffer() returns,
785 // queue the "attached" flag before calling queueBuffer. In case
786 // queueBuffer() fails, remove it from the queue.
787 ctx->queueAttachedFlag(true);
Emilian Peev9c778e12020-10-29 17:36:22 -0700788 res = anw->queueBuffer(anw.get(), gb.get(), /*fenceFd*/
Zhijun Hece9d6f92015-03-29 16:33:59 -0700789 -1);
790 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700791 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700792 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700793 switch (res) {
794 case NO_INIT:
795 jniThrowException(env, "java/lang/IllegalStateException",
796 "Surface has been abandoned");
797 break;
798 default:
799 // TODO: handle other error cases here.
800 jniThrowRuntimeException(env, "Queue input buffer failed");
801 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700802 return res;
803 }
804
805 // Do not set the image native context. Since it would overwrite the existing native context
806 // of the image that is from ImageReader, the subsequent image close will run into issues.
807
808 return res;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800809}
810
Emilian Peev9c778e12020-10-29 17:36:22 -0700811static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
John Reckffa81f82022-02-04 17:05:30 -0500812 jlong nativeBuffer, jint imageFormat, jlong timestampNs, jint dataSpace,
Sally Qiac97f992021-10-11 17:39:54 -0700813 jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
Emilian Peev9c778e12020-10-29 17:36:22 -0700814 ALOGV("%s", __FUNCTION__);
815 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
816 if (ctx == NULL || thiz == NULL) {
817 jniThrowException(env, "java/lang/IllegalStateException",
818 "ImageWriterContext is not initialized");
819 return -1;
820 }
821
822 sp<Surface> surface = ctx->getProducer();
823 if (isFormatOpaque(imageFormat) != isFormatOpaque(ctx->getBufferFormat())) {
824 jniThrowException(env, "java/lang/IllegalStateException",
825 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
826 return -1;
827 }
828
829 // Image is guaranteed to be from ImageReader at this point, so it is safe to
830 // cast to BufferItem pointer.
831 BufferItem* buffer = reinterpret_cast<BufferItem*>(nativeBuffer);
832 if (buffer == NULL) {
833 jniThrowException(env, "java/lang/IllegalStateException",
834 "Image is not initialized or already closed");
835 return -1;
836 }
837
Sally Qiac97f992021-10-11 17:39:54 -0700838 return attachAndQeueuGraphicBuffer(env, ctx, surface, buffer->mGraphicBuffer, timestampNs,
839 dataSpace, left, top, right, bottom, transform, scalingMode);
Emilian Peev9c778e12020-10-29 17:36:22 -0700840}
841
842static jint ImageWriter_attachAndQueueGraphicBuffer(JNIEnv* env, jobject thiz, jlong nativeCtx,
John Reckffa81f82022-02-04 17:05:30 -0500843 jobject buffer, jint format, jlong timestampNs, jint dataSpace, jint left, jint top,
Emilian Peev9c778e12020-10-29 17:36:22 -0700844 jint right, jint bottom, jint transform, jint scalingMode) {
845 ALOGV("%s", __FUNCTION__);
846 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
847 if (ctx == NULL || thiz == NULL) {
848 jniThrowException(env, "java/lang/IllegalStateException",
849 "ImageWriterContext is not initialized");
850 return -1;
851 }
852
853 sp<Surface> surface = ctx->getProducer();
854 if (isFormatOpaque(format) != isFormatOpaque(ctx->getBufferFormat())) {
855 jniThrowException(env, "java/lang/IllegalStateException",
856 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
857 return -1;
858 }
859
860 sp<GraphicBuffer> graphicBuffer = android_graphics_GraphicBuffer_getNativeGraphicsBuffer(env,
861 buffer);
862 if (graphicBuffer.get() == NULL) {
863 jniThrowException(env, "java/lang/IllegalArgumentException",
864 "Trying to attach an invalid graphic buffer");
865 return -1;
866 }
Sally Qiac97f992021-10-11 17:39:54 -0700867 return attachAndQeueuGraphicBuffer(env, ctx, surface, graphicBuffer, timestampNs,
868 dataSpace, left, top, right, bottom, transform, scalingMode);
Emilian Peev9c778e12020-10-29 17:36:22 -0700869}
870
Zhijun Hef6a09e52015-02-24 18:12:23 -0800871// --------------------------Image methods---------------------------------------
872
873static void Image_getNativeContext(JNIEnv* env, jobject thiz,
874 GraphicBuffer** buffer, int* fenceFd) {
875 ALOGV("%s", __FUNCTION__);
876 if (buffer != NULL) {
877 GraphicBuffer *gb = reinterpret_cast<GraphicBuffer *>
878 (env->GetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer));
879 *buffer = gb;
880 }
881
882 if (fenceFd != NULL) {
883 *fenceFd = reinterpret_cast<jint>(env->GetIntField(
884 thiz, gSurfaceImageClassInfo.mNativeFenceFd));
885 }
886}
887
888static void Image_setNativeContext(JNIEnv* env, jobject thiz,
John Reckffa81f82022-02-04 17:05:30 -0500889 sp<GraphicBuffer> buffer, int fenceFd, int dataSpace) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800890 ALOGV("%s:", __FUNCTION__);
891 GraphicBuffer* p = NULL;
892 Image_getNativeContext(env, thiz, &p, /*fenceFd*/NULL);
893 if (buffer != 0) {
894 buffer->incStrong((void*)Image_setNativeContext);
895 }
896 if (p) {
897 p->decStrong((void*)Image_setNativeContext);
898 }
899 env->SetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer,
900 reinterpret_cast<jlong>(buffer.get()));
901
902 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
Sally Qiac97f992021-10-11 17:39:54 -0700903
John Recke20a7542022-02-09 08:56:56 -0500904 env->SetIntField(thiz, gSurfaceImageClassInfo.mDataSpace, dataSpace);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800905}
906
907static void Image_unlockIfLocked(JNIEnv* env, jobject thiz) {
908 ALOGV("%s", __FUNCTION__);
909 GraphicBuffer* buffer;
910 Image_getNativeContext(env, thiz, &buffer, NULL);
911 if (buffer == NULL) {
912 jniThrowException(env, "java/lang/IllegalStateException",
913 "Image is not initialized");
914 return;
915 }
916
917 // Is locked?
918 bool isLocked = false;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700919 jobject planes = NULL;
920 if (!isFormatOpaque(buffer->getPixelFormat())) {
921 planes = env->GetObjectField(thiz, gSurfaceImageClassInfo.mPlanes);
922 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800923 isLocked = (planes != NULL);
924 if (isLocked) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700925 // 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 -0800926 status_t res = buffer->unlock();
927 if (res != OK) {
928 jniThrowRuntimeException(env, "unlock buffer failed");
John Reckdcd4c582019-07-12 13:13:05 -0700929 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800930 }
931 ALOGV("Successfully unlocked the image");
932 }
933}
934
935static jint Image_getWidth(JNIEnv* env, jobject thiz) {
936 ALOGV("%s", __FUNCTION__);
937 GraphicBuffer* buffer;
938 Image_getNativeContext(env, thiz, &buffer, NULL);
939 if (buffer == NULL) {
940 jniThrowException(env, "java/lang/IllegalStateException",
941 "Image is not initialized");
942 return -1;
943 }
944
945 return buffer->getWidth();
946}
947
948static jint Image_getHeight(JNIEnv* env, jobject thiz) {
949 ALOGV("%s", __FUNCTION__);
950 GraphicBuffer* buffer;
951 Image_getNativeContext(env, thiz, &buffer, NULL);
952 if (buffer == NULL) {
953 jniThrowException(env, "java/lang/IllegalStateException",
954 "Image is not initialized");
955 return -1;
956 }
957
958 return buffer->getHeight();
959}
960
John Reckffa81f82022-02-04 17:05:30 -0500961static jint Image_getFormat(JNIEnv* env, jobject thiz, jint dataSpace) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800962 ALOGV("%s", __FUNCTION__);
963 GraphicBuffer* buffer;
964 Image_getNativeContext(env, thiz, &buffer, NULL);
965 if (buffer == NULL) {
966 jniThrowException(env, "java/lang/IllegalStateException",
967 "Image is not initialized");
968 return 0;
969 }
970
Fedor Kudasov4d027e92019-06-24 17:21:57 +0100971 PublicFormat publicFmt = mapHalFormatDataspaceToPublicFormat(buffer->getPixelFormat(),
Sally Qid26f4f02022-01-21 09:53:20 -0800972 static_cast<android_dataspace>(dataSpace));
973
Zhijun He0ab41622016-02-25 16:00:38 -0800974 return static_cast<jint>(publicFmt);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800975}
976
rennbe092192018-05-07 10:18:05 -0700977static jobject Image_getHardwareBuffer(JNIEnv* env, jobject thiz) {
978 GraphicBuffer* buffer;
979 Image_getNativeContext(env, thiz, &buffer, NULL);
980 if (buffer == NULL) {
981 jniThrowException(env, "java/lang/IllegalStateException",
982 "Image is not initialized");
983 return NULL;
984 }
985 AHardwareBuffer* b = AHardwareBuffer_from_GraphicBuffer(buffer);
986 // don't user the public AHardwareBuffer_toHardwareBuffer() because this would force us
987 // to link against libandroid.so
988 return android_hardware_HardwareBuffer_createFromAHardwareBuffer(env, b);
989}
990
Zhijun Hef6a09e52015-02-24 18:12:23 -0800991static void Image_setFenceFd(JNIEnv* env, jobject thiz, int fenceFd) {
992 ALOGV("%s:", __FUNCTION__);
Sally Qid2087e72022-01-13 14:05:16 -0800993 int curtFenceFd = reinterpret_cast<jint>(
994 env->GetIntField(thiz,gSurfaceImageClassInfo.mNativeFenceFd));
995 if (curtFenceFd != -1) {
996 close(curtFenceFd);
997 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800998 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
999}
1000
1001static void Image_getLockedImage(JNIEnv* env, jobject thiz, LockedImage *image) {
1002 ALOGV("%s", __FUNCTION__);
1003 GraphicBuffer* buffer;
1004 int fenceFd = -1;
1005 Image_getNativeContext(env, thiz, &buffer, &fenceFd);
1006 if (buffer == NULL) {
1007 jniThrowException(env, "java/lang/IllegalStateException",
1008 "Image is not initialized");
1009 return;
1010 }
1011
Zhijun He0ab41622016-02-25 16:00:38 -08001012 // ImageWriter doesn't use crop by itself, app sets it, use the no crop version.
1013 const Rect noCrop(buffer->width, buffer->height);
1014 status_t res = lockImageFromBuffer(
1015 buffer, GRALLOC_USAGE_SW_WRITE_OFTEN, noCrop, fenceFd, image);
1016 // Clear the fenceFd as it is already consumed by lock call.
Brian Kim1165c902022-09-02 08:23:06 +00001017 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, -1);
Zhijun He0ab41622016-02-25 16:00:38 -08001018 if (res != OK) {
1019 jniThrowExceptionFmt(env, "java/lang/RuntimeException",
1020 "lock buffer failed for format 0x%x",
1021 buffer->getPixelFormat());
1022 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001023 }
1024
Zhijun He0ab41622016-02-25 16:00:38 -08001025 ALOGV("%s: Successfully locked the image", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001026 // crop, transform, scalingMode, timestamp, and frameNumber should be set by producer,
1027 // and we don't set them here.
1028}
1029
John Reckdcd4c582019-07-12 13:13:05 -07001030static bool Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
Zhijun Hef6a09e52015-02-24 18:12:23 -08001031 int32_t writerFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
1032 ALOGV("%s", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001033
Zhijun He0ab41622016-02-25 16:00:38 -08001034 status_t res = getLockedImageInfo(buffer, idx, writerFormat, base, size,
1035 pixelStride, rowStride);
1036 if (res != OK) {
1037 jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
John Reck03bd07a2019-07-12 13:53:04 -07001038 "Pixel format: 0x%x is unsupported", writerFormat);
John Reckdcd4c582019-07-12 13:13:05 -07001039 return false;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001040 }
John Reckdcd4c582019-07-12 13:13:05 -07001041 return true;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001042}
1043
1044static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
John Reckffa81f82022-02-04 17:05:30 -05001045 int numPlanes, int writerFormat, int dataSpace) {
Zhijun Hef6a09e52015-02-24 18:12:23 -08001046 ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
1047 int rowStride, pixelStride;
1048 uint8_t *pData;
1049 uint32_t dataSize;
1050 jobject byteBuffer;
1051
Sally Qid26f4f02022-01-21 09:53:20 -08001052 int format = Image_getFormat(env, thiz, dataSpace);
Zhijun Hece9d6f92015-03-29 16:33:59 -07001053 if (isFormatOpaque(format) && numPlanes > 0) {
Zhijun Hef6a09e52015-02-24 18:12:23 -08001054 String8 msg;
1055 msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
1056 " must be 0", format, numPlanes);
1057 jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
1058 return NULL;
1059 }
1060
1061 jobjectArray surfacePlanes = env->NewObjectArray(numPlanes, gSurfacePlaneClassInfo.clazz,
1062 /*initial_element*/NULL);
1063 if (surfacePlanes == NULL) {
1064 jniThrowRuntimeException(env, "Failed to create SurfacePlane arrays,"
1065 " probably out of memory");
1066 return NULL;
1067 }
Zhijun Hece9d6f92015-03-29 16:33:59 -07001068 if (isFormatOpaque(format)) {
1069 return surfacePlanes;
1070 }
Zhijun Hef6a09e52015-02-24 18:12:23 -08001071
1072 // Buildup buffer info: rowStride, pixelStride and byteBuffers.
1073 LockedImage lockedImg = LockedImage();
1074 Image_getLockedImage(env, thiz, &lockedImg);
1075
1076 // Create all SurfacePlanes
Zhijun He0ab41622016-02-25 16:00:38 -08001077 PublicFormat publicWriterFormat = static_cast<PublicFormat>(writerFormat);
Fedor Kudasov4d027e92019-06-24 17:21:57 +01001078 writerFormat = mapPublicFormatToHalFormat(publicWriterFormat);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001079 for (int i = 0; i < numPlanes; i++) {
John Reckdcd4c582019-07-12 13:13:05 -07001080 if (!Image_getLockedImageInfo(env, &lockedImg, i, writerFormat,
1081 &pData, &dataSize, &pixelStride, &rowStride)) {
1082 return NULL;
1083 }
Zhijun Hef6a09e52015-02-24 18:12:23 -08001084 byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
1085 if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
1086 jniThrowException(env, "java/lang/IllegalStateException",
1087 "Failed to allocate ByteBuffer");
1088 return NULL;
1089 }
1090
1091 // Finally, create this SurfacePlane.
1092 jobject surfacePlane = env->NewObject(gSurfacePlaneClassInfo.clazz,
1093 gSurfacePlaneClassInfo.ctor, thiz, rowStride, pixelStride, byteBuffer);
1094 env->SetObjectArrayElement(surfacePlanes, i, surfacePlane);
1095 }
1096
1097 return surfacePlanes;
1098}
1099
Zhijun Hef6a09e52015-02-24 18:12:23 -08001100} // extern "C"
1101
1102// ----------------------------------------------------------------------------
1103
1104static JNINativeMethod gImageWriterMethods[] = {
1105 {"nativeClassInit", "()V", (void*)ImageWriter_classInit },
John Reckffa81f82022-02-04 17:05:30 -05001106 {"nativeInit", "(Ljava/lang/Object;Landroid/view/Surface;IIIZIIJ)J",
Zhijun Hef6a09e52015-02-24 18:12:23 -08001107 (void*)ImageWriter_init },
Zhijun Hece9d6f92015-03-29 16:33:59 -07001108 {"nativeClose", "(J)V", (void*)ImageWriter_close },
Sally Qiac97f992021-10-11 17:39:54 -07001109 {"nativeAttachAndQueueImage",
John Reckffa81f82022-02-04 17:05:30 -05001110 "(JJIJIIIIIII)I",
Sally Qiac97f992021-10-11 17:39:54 -07001111 (void*)ImageWriter_attachAndQueueImage },
Emilian Peev9c778e12020-10-29 17:36:22 -07001112 {"nativeAttachAndQueueGraphicBuffer",
John Reckffa81f82022-02-04 17:05:30 -05001113 "(JLandroid/graphics/GraphicBuffer;IJIIIIIII)I",
Emilian Peev9c778e12020-10-29 17:36:22 -07001114 (void*)ImageWriter_attachAndQueueGraphicBuffer },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001115 {"nativeDequeueInputImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_dequeueImage },
John Reckffa81f82022-02-04 17:05:30 -05001116 {"nativeQueueInputImage", "(JLandroid/media/Image;JIIIIIII)V",
Sally Qiac97f992021-10-11 17:39:54 -07001117 (void*)ImageWriter_queueImage },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001118 {"cancelImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_cancelImage },
1119};
1120
1121static JNINativeMethod gImageMethods[] = {
John Reckffa81f82022-02-04 17:05:30 -05001122 {"nativeCreatePlanes", "(III)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
rennbe092192018-05-07 10:18:05 -07001123 (void*)Image_createSurfacePlanes },
1124 {"nativeGetWidth", "()I", (void*)Image_getWidth },
1125 {"nativeGetHeight", "()I", (void*)Image_getHeight },
John Reckffa81f82022-02-04 17:05:30 -05001126 {"nativeGetFormat", "(I)I", (void*)Image_getFormat },
Sally Qid2087e72022-01-13 14:05:16 -08001127 {"nativeSetFenceFd", "(I)V", (void*)Image_setFenceFd },
rennbe092192018-05-07 10:18:05 -07001128 {"nativeGetHardwareBuffer", "()Landroid/hardware/HardwareBuffer;",
1129 (void*)Image_getHardwareBuffer },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001130};
1131
1132int register_android_media_ImageWriter(JNIEnv *env) {
1133
1134 int ret1 = AndroidRuntime::registerNativeMethods(env,
1135 "android/media/ImageWriter", gImageWriterMethods, NELEM(gImageWriterMethods));
1136
1137 int ret2 = AndroidRuntime::registerNativeMethods(env,
1138 "android/media/ImageWriter$WriterSurfaceImage", gImageMethods, NELEM(gImageMethods));
1139
1140 return (ret1 || ret2);
1141}