blob: eca26dc14fa9abcff7361cc2e9aede4da391b210 [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 He916d8ac2017-03-22 17:33:47 -070045#define IMAGE_FORMAT_UNKNOWN 0 // This is the same value as ImageFormat#UNKNOWN.
Zhijun Hef6a09e52015-02-24 18:12:23 -080046// ----------------------------------------------------------------------------
47
48using namespace android;
49
Zhijun Hef6a09e52015-02-24 18:12:23 -080050static struct {
51 jmethodID postEventFromNative;
52 jfieldID mWriterFormat;
53} gImageWriterClassInfo;
54
55static struct {
Sally Qiac97f992021-10-11 17:39:54 -070056 jfieldID mDataSpace;
Zhijun Hef6a09e52015-02-24 18:12:23 -080057 jfieldID mNativeBuffer;
58 jfieldID mNativeFenceFd;
59 jfieldID mPlanes;
60} gSurfaceImageClassInfo;
61
62static struct {
63 jclass clazz;
64 jmethodID ctor;
65} gSurfacePlaneClassInfo;
66
Zhijun Hef6a09e52015-02-24 18:12:23 -080067// ----------------------------------------------------------------------------
68
69class JNIImageWriterContext : public BnProducerListener {
70public:
71 JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz);
72
73 virtual ~JNIImageWriterContext();
74
75 // Implementation of IProducerListener, used to notify the ImageWriter that the consumer
76 // has returned a buffer and it is ready for ImageWriter to dequeue.
77 virtual void onBufferReleased();
78
Zhijun Hece9d6f92015-03-29 16:33:59 -070079 void setProducer(const sp<Surface>& producer) { mProducer = producer; }
80 Surface* getProducer() { return mProducer.get(); }
Zhijun Hef6a09e52015-02-24 18:12:23 -080081
82 void setBufferFormat(int format) { mFormat = format; }
83 int getBufferFormat() { return mFormat; }
84
85 void setBufferWidth(int width) { mWidth = width; }
86 int getBufferWidth() { return mWidth; }
87
88 void setBufferHeight(int height) { mHeight = height; }
89 int getBufferHeight() { return mHeight; }
90
Sally Qiac97f992021-10-11 17:39:54 -070091 void setBufferDataSpace(android_dataspace dataSpace) { mDataSpace = dataSpace; }
92 android_dataspace getBufferDataSpace() { return mDataSpace; }
93
Shuzhen Wangb9adb572020-06-24 09:33:27 -070094 void queueAttachedFlag(bool isAttached) {
95 Mutex::Autolock l(mAttachedFlagQueueLock);
96 mAttachedFlagQueue.push_back(isAttached);
97 }
98 void dequeueAttachedFlag() {
99 Mutex::Autolock l(mAttachedFlagQueueLock);
100 mAttachedFlagQueue.pop_back();
101 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800102private:
103 static JNIEnv* getJNIEnv(bool* needsDetach);
104 static void detachJNI();
105
Zhijun Hece9d6f92015-03-29 16:33:59 -0700106 sp<Surface> mProducer;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800107 jobject mWeakThiz;
108 jclass mClazz;
109 int mFormat;
110 int mWidth;
111 int mHeight;
Sally Qiac97f992021-10-11 17:39:54 -0700112 android_dataspace mDataSpace;
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800113
114 // Class for a shared thread used to detach buffers from buffer queues
115 // to discard buffers after consumers are done using them.
116 // This is needed because detaching buffers in onBufferReleased callback
117 // can lead to deadlock when consumer/producer are on the same process.
118 class BufferDetacher {
119 public:
120 // Called by JNIImageWriterContext ctor. Will start the thread for first ref.
121 void addRef();
122 // Called by JNIImageWriterContext dtor. Will stop the thread after ref goes to 0.
123 void removeRef();
124 // Called by onBufferReleased to signal this thread to detach a buffer
125 void detach(wp<Surface>);
126
127 private:
128
129 class DetachThread : public Thread {
130 public:
131 DetachThread() : Thread(/*canCallJava*/false) {};
132
133 void detach(wp<Surface>);
134
135 virtual void requestExit() override;
136
137 private:
138 virtual bool threadLoop() override;
139
140 Mutex mLock;
141 Condition mCondition;
142 std::deque<wp<Surface>> mQueue;
143
Yin-Chia Yehedace1a2019-07-30 13:02:59 -0700144 static const nsecs_t kWaitDuration = 500000000; // 500 ms
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800145 };
146 sp<DetachThread> mThread;
147
148 Mutex mLock;
149 int mRefCount = 0;
150 };
151
152 static BufferDetacher sBufferDetacher;
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700153
154 // Buffer queue guarantees both producer and consumer side buffer flows are
155 // in order. See b/19977520. As a result, we can use a queue here.
156 Mutex mAttachedFlagQueueLock;
157 std::deque<bool> mAttachedFlagQueue;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800158};
159
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800160JNIImageWriterContext::BufferDetacher JNIImageWriterContext::sBufferDetacher;
161
162void JNIImageWriterContext::BufferDetacher::addRef() {
163 Mutex::Autolock l(mLock);
164 mRefCount++;
165 if (mRefCount == 1) {
166 mThread = new DetachThread();
167 mThread->run("BufDtchThrd");
168 }
169}
170
171void JNIImageWriterContext::BufferDetacher::removeRef() {
172 Mutex::Autolock l(mLock);
173 mRefCount--;
174 if (mRefCount == 0) {
175 mThread->requestExit();
176 mThread->join();
177 mThread.clear();
178 }
179}
180
181void JNIImageWriterContext::BufferDetacher::detach(wp<Surface> bq) {
182 Mutex::Autolock l(mLock);
183 if (mThread == nullptr) {
184 ALOGE("%s: buffer detach thread is gone!", __FUNCTION__);
185 return;
186 }
187 mThread->detach(bq);
188}
189
190void JNIImageWriterContext::BufferDetacher::DetachThread::detach(wp<Surface> bq) {
191 Mutex::Autolock l(mLock);
192 mQueue.push_back(bq);
193 mCondition.signal();
194}
195
196void JNIImageWriterContext::BufferDetacher::DetachThread::requestExit() {
197 Thread::requestExit();
198 {
199 Mutex::Autolock l(mLock);
200 mQueue.clear();
201 }
202 mCondition.signal();
203}
204
205bool JNIImageWriterContext::BufferDetacher::DetachThread::threadLoop() {
206 Mutex::Autolock l(mLock);
207 mCondition.waitRelative(mLock, kWaitDuration);
208
209 while (!mQueue.empty()) {
210 if (exitPending()) {
211 return false;
212 }
213
214 wp<Surface> wbq = mQueue.front();
215 mQueue.pop_front();
216 sp<Surface> bq = wbq.promote();
217 if (bq != nullptr) {
218 sp<Fence> fence;
219 sp<GraphicBuffer> buffer;
220 ALOGV("%s: One buffer is detached", __FUNCTION__);
221 mLock.unlock();
222 bq->detachNextBuffer(&buffer, &fence);
223 mLock.lock();
224 }
225 }
226 return !exitPending();
227}
228
Zhijun Hef6a09e52015-02-24 18:12:23 -0800229JNIImageWriterContext::JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz) :
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800230 mWeakThiz(env->NewGlobalRef(weakThiz)),
231 mClazz((jclass)env->NewGlobalRef(clazz)),
232 mFormat(0),
233 mWidth(-1),
234 mHeight(-1) {
235 sBufferDetacher.addRef();
Zhijun Hef6a09e52015-02-24 18:12:23 -0800236}
237
238JNIImageWriterContext::~JNIImageWriterContext() {
239 ALOGV("%s", __FUNCTION__);
240 bool needsDetach = false;
241 JNIEnv* env = getJNIEnv(&needsDetach);
242 if (env != NULL) {
243 env->DeleteGlobalRef(mWeakThiz);
244 env->DeleteGlobalRef(mClazz);
245 } else {
246 ALOGW("leaking JNI object references");
247 }
248 if (needsDetach) {
249 detachJNI();
250 }
251
252 mProducer.clear();
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800253 sBufferDetacher.removeRef();
Zhijun Hef6a09e52015-02-24 18:12:23 -0800254}
255
256JNIEnv* JNIImageWriterContext::getJNIEnv(bool* needsDetach) {
257 ALOGV("%s", __FUNCTION__);
258 LOG_ALWAYS_FATAL_IF(needsDetach == NULL, "needsDetach is null!!!");
259 *needsDetach = false;
260 JNIEnv* env = AndroidRuntime::getJNIEnv();
261 if (env == NULL) {
262 JavaVMAttachArgs args = {JNI_VERSION_1_4, NULL, NULL};
263 JavaVM* vm = AndroidRuntime::getJavaVM();
264 int result = vm->AttachCurrentThread(&env, (void*) &args);
265 if (result != JNI_OK) {
266 ALOGE("thread attach failed: %#x", result);
267 return NULL;
268 }
269 *needsDetach = true;
270 }
271 return env;
272}
273
274void JNIImageWriterContext::detachJNI() {
275 ALOGV("%s", __FUNCTION__);
276 JavaVM* vm = AndroidRuntime::getJavaVM();
277 int result = vm->DetachCurrentThread();
278 if (result != JNI_OK) {
279 ALOGE("thread detach failed: %#x", result);
280 }
281}
282
283void JNIImageWriterContext::onBufferReleased() {
284 ALOGV("%s: buffer released", __FUNCTION__);
285 bool needsDetach = false;
286 JNIEnv* env = getJNIEnv(&needsDetach);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700287
288 bool bufferIsAttached = false;
289 {
290 Mutex::Autolock l(mAttachedFlagQueueLock);
291 if (!mAttachedFlagQueue.empty()) {
292 bufferIsAttached = mAttachedFlagQueue.front();
293 mAttachedFlagQueue.pop_front();
294 } else {
295 ALOGW("onBufferReleased called with no attached flag queued");
296 }
297 }
298
Zhijun Hef6a09e52015-02-24 18:12:23 -0800299 if (env != NULL) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700300 // Detach the buffer every time when a buffer consumption is done,
301 // need let this callback give a BufferItem, then only detach if it was attached to this
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700302 // Writer. see b/19977520
303 if (mFormat == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED || bufferIsAttached) {
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800304 sBufferDetacher.detach(mProducer);
Zhijun Hece9d6f92015-03-29 16:33:59 -0700305 }
306
Zhijun Hef6a09e52015-02-24 18:12:23 -0800307 env->CallStaticVoidMethod(mClazz, gImageWriterClassInfo.postEventFromNative, mWeakThiz);
308 } else {
309 ALOGW("onBufferReleased event will not posted");
310 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700311
Zhijun Hef6a09e52015-02-24 18:12:23 -0800312 if (needsDetach) {
313 detachJNI();
314 }
315}
316
317// ----------------------------------------------------------------------------
318
319extern "C" {
320
321// -------------------------------Private method declarations--------------
322
Zhijun Hef6a09e52015-02-24 18:12:23 -0800323static void Image_setNativeContext(JNIEnv* env, jobject thiz,
Sally Qiac97f992021-10-11 17:39:54 -0700324 sp<GraphicBuffer> buffer, int fenceFd, long dataSpace);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800325static void Image_getNativeContext(JNIEnv* env, jobject thiz,
326 GraphicBuffer** buffer, int* fenceFd);
327static void Image_unlockIfLocked(JNIEnv* env, jobject thiz);
328
329// --------------------------ImageWriter methods---------------------------------------
330
331static void ImageWriter_classInit(JNIEnv* env, jclass clazz) {
332 ALOGV("%s:", __FUNCTION__);
333 jclass imageClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage");
334 LOG_ALWAYS_FATAL_IF(imageClazz == NULL,
335 "can't find android/media/ImageWriter$WriterSurfaceImage");
Sally Qiac97f992021-10-11 17:39:54 -0700336
337 gSurfaceImageClassInfo.mDataSpace = env->GetFieldID(
338 imageClazz, "mDataSpace", "J");
339 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mDataSpace == NULL,
340 "can't find android/media/ImageWriter$WriterSurfaceImage.mDataSpace");
341
Zhijun Hef6a09e52015-02-24 18:12:23 -0800342 gSurfaceImageClassInfo.mNativeBuffer = env->GetFieldID(
343 imageClazz, IMAGE_BUFFER_JNI_ID, "J");
344 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeBuffer == NULL,
345 "can't find android/media/ImageWriter$WriterSurfaceImage.%s", IMAGE_BUFFER_JNI_ID);
346
347 gSurfaceImageClassInfo.mNativeFenceFd = env->GetFieldID(
348 imageClazz, "mNativeFenceFd", "I");
349 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeFenceFd == NULL,
350 "can't find android/media/ImageWriter$WriterSurfaceImage.mNativeFenceFd");
351
352 gSurfaceImageClassInfo.mPlanes = env->GetFieldID(
353 imageClazz, "mPlanes", "[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;");
354 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mPlanes == NULL,
355 "can't find android/media/ImageWriter$WriterSurfaceImage.mPlanes");
356
357 gImageWriterClassInfo.postEventFromNative = env->GetStaticMethodID(
358 clazz, "postEventFromNative", "(Ljava/lang/Object;)V");
359 LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.postEventFromNative == NULL,
360 "can't find android/media/ImageWriter.postEventFromNative");
361
362 gImageWriterClassInfo.mWriterFormat = env->GetFieldID(
363 clazz, "mWriterFormat", "I");
364 LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.mWriterFormat == NULL,
365 "can't find android/media/ImageWriter.mWriterFormat");
366
367 jclass planeClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage$SurfacePlane");
368 LOG_ALWAYS_FATAL_IF(planeClazz == NULL, "Can not find SurfacePlane class");
369 // FindClass only gives a local reference of jclass object.
370 gSurfacePlaneClassInfo.clazz = (jclass) env->NewGlobalRef(planeClazz);
371 gSurfacePlaneClassInfo.ctor = env->GetMethodID(gSurfacePlaneClassInfo.clazz, "<init>",
372 "(Landroid/media/ImageWriter$WriterSurfaceImage;IILjava/nio/ByteBuffer;)V");
373 LOG_ALWAYS_FATAL_IF(gSurfacePlaneClassInfo.ctor == NULL,
374 "Can not find SurfacePlane constructor");
375}
376
377static jlong ImageWriter_init(JNIEnv* env, jobject thiz, jobject weakThiz, jobject jsurface,
Sally Qidb57de32022-01-05 11:53:44 -0800378 jint maxImages, jint userWidth, jint userHeight, jboolean useSurfaceImageFormatInfo,
379 jint hardwareBufferFormat, jlong dataSpace, jlong ndkUsage) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800380 status_t res;
381
382 ALOGV("%s: maxImages:%d", __FUNCTION__, maxImages);
383
384 sp<Surface> surface(android_view_Surface_getSurface(env, jsurface));
385 if (surface == NULL) {
386 jniThrowException(env,
387 "java/lang/IllegalArgumentException",
388 "The surface has been released");
389 return 0;
390 }
391 sp<IGraphicBufferProducer> bufferProducer = surface->getIGraphicBufferProducer();
392
393 jclass clazz = env->GetObjectClass(thiz);
394 if (clazz == NULL) {
395 jniThrowRuntimeException(env, "Can't find android/graphics/ImageWriter");
396 return 0;
397 }
398 sp<JNIImageWriterContext> ctx(new JNIImageWriterContext(env, weakThiz, clazz));
399
400 sp<Surface> producer = new Surface(bufferProducer, /*controlledByApp*/false);
401 ctx->setProducer(producer);
402 /**
403 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not connectable
404 * after disconnect. MEDIA or CAMERA are treated the same internally. The producer listener
405 * will be cleared after disconnect call.
406 */
Emilian Peev2adf4032018-06-05 17:52:16 +0100407 res = producer->connect(/*api*/NATIVE_WINDOW_API_CAMERA, /*listener*/ctx);
408 if (res != OK) {
409 ALOGE("%s: Connecting to surface producer interface failed: %s (%d)",
410 __FUNCTION__, strerror(-res), res);
411 jniThrowRuntimeException(env, "Failed to connect to native window");
412 return 0;
413 }
414
Zhijun Hef6a09e52015-02-24 18:12:23 -0800415 jlong nativeCtx = reinterpret_cast<jlong>(ctx.get());
416
417 // Get the dimension and format of the producer.
418 sp<ANativeWindow> anw = producer;
Zhijun He916d8ac2017-03-22 17:33:47 -0700419 int32_t width, height, surfaceFormat;
Emilian Peevab808242020-12-28 16:03:32 -0800420 if (userWidth < 0) {
421 if ((res = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, &width)) != OK) {
422 ALOGE("%s: Query Surface width failed: %s (%d)", __FUNCTION__, strerror(-res), res);
423 jniThrowRuntimeException(env, "Failed to query Surface width");
424 return 0;
425 }
426 } else {
427 width = userWidth;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800428 }
Emilian Peevab808242020-12-28 16:03:32 -0800429
Zhijun Hef6a09e52015-02-24 18:12:23 -0800430 ctx->setBufferWidth(width);
431
Emilian Peevab808242020-12-28 16:03:32 -0800432 if (userHeight < 0) {
433 if ((res = anw->query(anw.get(), NATIVE_WINDOW_HEIGHT, &height)) != OK) {
434 ALOGE("%s: Query Surface height failed: %s (%d)", __FUNCTION__, strerror(-res), res);
435 jniThrowRuntimeException(env, "Failed to query Surface height");
436 return 0;
437 }
438 } else {
439 height = userHeight;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800440 }
441 ctx->setBufferHeight(height);
442
Emilian Peevab808242020-12-28 16:03:32 -0800443 if ((userWidth > 0) && (userHeight > 0)) {
444 res = native_window_set_buffers_user_dimensions(anw.get(), userWidth, userHeight);
445 if (res != OK) {
446 ALOGE("%s: Set buffer dimensions failed: %s (%d)", __FUNCTION__, strerror(-res), res);
447 jniThrowRuntimeException(env, "Set buffer dimensions failed");
448 return 0;
449 }
450 }
451
Zhijun He916d8ac2017-03-22 17:33:47 -0700452 // Query surface format if no valid user format is specified, otherwise, override surface format
453 // with user format.
Sally Qidb57de32022-01-05 11:53:44 -0800454 if (useSurfaceImageFormatInfo) {
Zhijun He916d8ac2017-03-22 17:33:47 -0700455 if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &surfaceFormat)) != OK) {
456 ALOGE("%s: Query Surface format failed: %s (%d)", __FUNCTION__, strerror(-res), res);
457 jniThrowRuntimeException(env, "Failed to query Surface format");
458 return 0;
459 }
460 } else {
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700461 // Set consumer buffer format to user specified format
Sally Qidb57de32022-01-05 11:53:44 -0800462 android_dataspace nativeDataspace = static_cast<android_dataspace>(dataSpace);
Sally Qidb57de32022-01-05 11:53:44 -0800463 res = native_window_set_buffers_format(anw.get(), hardwareBufferFormat);
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700464 if (res != OK) {
465 ALOGE("%s: Unable to configure consumer native buffer format to %#x",
Sally Qidb57de32022-01-05 11:53:44 -0800466 __FUNCTION__, hardwareBufferFormat);
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700467 jniThrowRuntimeException(env, "Failed to set Surface format");
468 return 0;
469 }
470
471 res = native_window_set_buffers_data_space(anw.get(), nativeDataspace);
472 if (res != OK) {
473 ALOGE("%s: Unable to configure consumer dataspace %#x",
474 __FUNCTION__, nativeDataspace);
475 jniThrowRuntimeException(env, "Failed to set Surface dataspace");
476 return 0;
477 }
Sally Qiac97f992021-10-11 17:39:54 -0700478 ctx->setBufferDataSpace(nativeDataspace);
Sally Qid26f4f02022-01-21 09:53:20 -0800479 surfaceFormat = static_cast<int32_t>(mapHalFormatDataspaceToPublicFormat(
480 hardwareBufferFormat, nativeDataspace));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800481 }
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700482
Zhijun He916d8ac2017-03-22 17:33:47 -0700483 ctx->setBufferFormat(surfaceFormat);
484 env->SetIntField(thiz,
485 gImageWriterClassInfo.mWriterFormat, reinterpret_cast<jint>(surfaceFormat));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800486
Sally Qid26f4f02022-01-21 09:53:20 -0800487 // ndkUsage == -1 means setUsage in ImageWriter class is not called.
488 // skip usage setting if setUsage in ImageWriter is not called and imageformat is opaque.
489 if (!(ndkUsage == -1 && isFormatOpaque(surfaceFormat))) {
490 if (ndkUsage == -1) {
491 ndkUsage = GRALLOC_USAGE_SW_WRITE_OFTEN;
492 }
493 res = native_window_set_usage(anw.get(), ndkUsage);
494 if (res != OK) {
495 ALOGE("%s: Configure usage %08x for format %08x failed: %s (%d)",
496 __FUNCTION__, static_cast<unsigned int>(ndkUsage),
497 surfaceFormat, strerror(-res), res);
498 jniThrowRuntimeException(env,
499 "Failed to SW_WRITE_OFTEN configure usage");
500 return 0;
501 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800502 }
503
504 int minUndequeuedBufferCount = 0;
505 res = anw->query(anw.get(),
506 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufferCount);
507 if (res != OK) {
508 ALOGE("%s: Query producer undequeued buffer count failed: %s (%d)",
509 __FUNCTION__, strerror(-res), res);
510 jniThrowRuntimeException(env, "Query producer undequeued buffer count failed");
511 return 0;
512 }
513
514 size_t totalBufferCount = maxImages + minUndequeuedBufferCount;
515 res = native_window_set_buffer_count(anw.get(), totalBufferCount);
516 if (res != OK) {
517 ALOGE("%s: Set buffer count failed: %s (%d)", __FUNCTION__, strerror(-res), res);
518 jniThrowRuntimeException(env, "Set buffer count failed");
519 return 0;
520 }
521
522 if (ctx != 0) {
523 ctx->incStrong((void*)ImageWriter_init);
524 }
525 return nativeCtx;
526}
527
528static void ImageWriter_dequeueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
529 ALOGV("%s", __FUNCTION__);
530 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
531 if (ctx == NULL || thiz == NULL) {
532 jniThrowException(env, "java/lang/IllegalStateException",
533 "ImageWriterContext is not initialized");
534 return;
535 }
536
537 sp<ANativeWindow> anw = ctx->getProducer();
538 android_native_buffer_t *anb = NULL;
539 int fenceFd = -1;
540 status_t res = anw->dequeueBuffer(anw.get(), &anb, &fenceFd);
541 if (res != OK) {
Zhijun Hea5827142015-04-22 10:07:42 -0700542 ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700543 switch (res) {
544 case NO_INIT:
545 jniThrowException(env, "java/lang/IllegalStateException",
546 "Surface has been abandoned");
547 break;
548 default:
549 // TODO: handle other error cases here.
550 jniThrowRuntimeException(env, "dequeue buffer failed");
551 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800552 return;
553 }
554 // New GraphicBuffer object doesn't own the handle, thus the native buffer
555 // won't be freed when this object is destroyed.
Mathias Agopian845eef05f2017-04-03 17:51:15 -0700556 sp<GraphicBuffer> buffer(GraphicBuffer::from(anb));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800557
558 // Note that:
559 // 1. No need to lock buffer now, will only lock it when the first getPlanes() is called.
560 // 2. Fence will be saved to mNativeFenceFd, and will consumed by lock/queue/cancel buffer
561 // later.
562 // 3. need use lockAsync here, as it will handle the dequeued fence for us automatically.
563
564 // Finally, set the native info into image object.
Sally Qiac97f992021-10-11 17:39:54 -0700565 Image_setNativeContext(env, image, buffer, fenceFd, ctx->getBufferDataSpace());
Zhijun Hef6a09e52015-02-24 18:12:23 -0800566}
567
568static void ImageWriter_close(JNIEnv* env, jobject thiz, jlong nativeCtx) {
569 ALOGV("%s:", __FUNCTION__);
570 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
571 if (ctx == NULL || thiz == NULL) {
Chien-Yu Chen0375cb02015-06-18 11:55:18 -0700572 // ImageWriter is already closed.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800573 return;
574 }
575
576 ANativeWindow* producer = ctx->getProducer();
577 if (producer != NULL) {
578 /**
579 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not
580 * connectable after disconnect. MEDIA or CAMERA are treated the same internally.
581 * The producer listener will be cleared after disconnect call.
582 */
583 status_t res = native_window_api_disconnect(producer, /*api*/NATIVE_WINDOW_API_CAMERA);
584 /**
585 * This is not an error. if client calling process dies, the window will
586 * also die and all calls to it will return DEAD_OBJECT, thus it's already
587 * "disconnected"
588 */
589 if (res == DEAD_OBJECT) {
590 ALOGW("%s: While disconnecting ImageWriter from native window, the"
591 " native window died already", __FUNCTION__);
592 } else if (res != OK) {
593 ALOGE("%s: native window disconnect failed: %s (%d)",
594 __FUNCTION__, strerror(-res), res);
595 jniThrowRuntimeException(env, "Native window disconnect failed");
596 return;
597 }
598 }
599
600 ctx->decStrong((void*)ImageWriter_init);
601}
602
603static void ImageWriter_cancelImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
604 ALOGV("%s", __FUNCTION__);
605 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
606 if (ctx == NULL || thiz == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800607 ALOGW("ImageWriter#close called before Image#close, consider calling Image#close first");
Zhijun Hef6a09e52015-02-24 18:12:23 -0800608 return;
609 }
610
611 sp<ANativeWindow> anw = ctx->getProducer();
612
613 GraphicBuffer *buffer = NULL;
614 int fenceFd = -1;
615 Image_getNativeContext(env, image, &buffer, &fenceFd);
616 if (buffer == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800617 // Cancel an already cancelled image is harmless.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800618 return;
619 }
620
621 // Unlock the image if it was locked
622 Image_unlockIfLocked(env, image);
623
624 anw->cancelBuffer(anw.get(), buffer, fenceFd);
625
Sally Qiac97f992021-10-11 17:39:54 -0700626 Image_setNativeContext(env, image, NULL, -1, HAL_DATASPACE_UNKNOWN);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800627}
628
629static void ImageWriter_queueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image,
Sally Qiac97f992021-10-11 17:39:54 -0700630 jlong timestampNs, jlong dataSpace, jint left, jint top, jint right,
631 jint bottom, jint transform, jint scalingMode) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800632 ALOGV("%s", __FUNCTION__);
633 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
634 if (ctx == NULL || thiz == NULL) {
635 jniThrowException(env, "java/lang/IllegalStateException",
636 "ImageWriterContext is not initialized");
637 return;
638 }
639
640 status_t res = OK;
641 sp<ANativeWindow> anw = ctx->getProducer();
642
643 GraphicBuffer *buffer = NULL;
644 int fenceFd = -1;
645 Image_getNativeContext(env, image, &buffer, &fenceFd);
646 if (buffer == NULL) {
647 jniThrowException(env, "java/lang/IllegalStateException",
648 "Image is not initialized");
649 return;
650 }
651
652 // Unlock image if it was locked.
653 Image_unlockIfLocked(env, image);
654
655 // Set timestamp
Zhijun Hed1cbc682015-03-23 10:10:04 -0700656 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800657 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
658 if (res != OK) {
659 jniThrowRuntimeException(env, "Set timestamp failed");
660 return;
661 }
662
Sally Qiac97f992021-10-11 17:39:54 -0700663 // Set dataSpace
664 ALOGV("dataSpace to be queued: %" PRId64, dataSpace);
665 res = native_window_set_buffers_data_space(
666 anw.get(), static_cast<android_dataspace>(dataSpace));
667 if (res != OK) {
668 jniThrowRuntimeException(env, "Set dataspace failed");
669 return;
670 }
671
Zhijun Hef6a09e52015-02-24 18:12:23 -0800672 // Set crop
673 android_native_rect_t cropRect;
674 cropRect.left = left;
675 cropRect.top = top;
676 cropRect.right = right;
677 cropRect.bottom = bottom;
678 res = native_window_set_crop(anw.get(), &cropRect);
679 if (res != OK) {
680 jniThrowRuntimeException(env, "Set crop rect failed");
681 return;
682 }
683
Emilian Peev450a5ff2018-03-19 16:05:10 +0000684 res = native_window_set_buffers_transform(anw.get(), transform);
685 if (res != OK) {
686 jniThrowRuntimeException(env, "Set transform failed");
687 return;
688 }
689
Emilian Peev750aec62018-04-06 12:55:00 +0100690 res = native_window_set_scaling_mode(anw.get(), scalingMode);
691 if (res != OK) {
692 jniThrowRuntimeException(env, "Set scaling mode failed");
693 return;
694 }
695
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700696 // Finally, queue input buffer.
697 //
698 // Because onBufferReleased may be called before queueBuffer() returns,
699 // queue the "attached" flag before calling queueBuffer. In case
700 // queueBuffer() fails, remove it from the queue.
701 ctx->queueAttachedFlag(false);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800702 res = anw->queueBuffer(anw.get(), buffer, fenceFd);
703 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700704 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700705 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700706 switch (res) {
707 case NO_INIT:
708 jniThrowException(env, "java/lang/IllegalStateException",
709 "Surface has been abandoned");
710 break;
711 default:
712 // TODO: handle other error cases here.
713 jniThrowRuntimeException(env, "Queue input buffer failed");
714 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800715 return;
716 }
717
Zhijun Hece9d6f92015-03-29 16:33:59 -0700718 // Clear the image native context: end of this image's lifecycle in public API.
Sally Qiac97f992021-10-11 17:39:54 -0700719 Image_setNativeContext(env, image, NULL, -1, HAL_DATASPACE_UNKNOWN);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800720}
721
Emilian Peev9c778e12020-10-29 17:36:22 -0700722static status_t attachAndQeueuGraphicBuffer(JNIEnv* env, JNIImageWriterContext *ctx,
Sally Qiac97f992021-10-11 17:39:54 -0700723 sp<Surface> surface, sp<GraphicBuffer> gb, jlong timestampNs, jlong dataSpace,
724 jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700725 status_t res = OK;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700726 // Step 1. Attach Image
Emilian Peev9c778e12020-10-29 17:36:22 -0700727 res = surface->attachBuffer(gb.get());
Zhijun Hece9d6f92015-03-29 16:33:59 -0700728 if (res != OK) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700729 ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700730 switch (res) {
731 case NO_INIT:
732 jniThrowException(env, "java/lang/IllegalStateException",
733 "Surface has been abandoned");
734 break;
735 default:
736 // TODO: handle other error cases here.
737 jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
738 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700739 return res;
740 }
741 sp < ANativeWindow > anw = surface;
742
Sally Qiac97f992021-10-11 17:39:54 -0700743 // Step 2. Set timestamp, dataspace, crop, transform and scaling mode.
744 // Note that we do not need unlock the image because it was not locked.
Zhijun Hece9d6f92015-03-29 16:33:59 -0700745 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
746 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
747 if (res != OK) {
748 jniThrowRuntimeException(env, "Set timestamp failed");
749 return res;
750 }
751
Sally Qiac97f992021-10-11 17:39:54 -0700752 ALOGV("dataSpace to be queued: %" PRId64, dataSpace);
753 res = native_window_set_buffers_data_space(
754 anw.get(), static_cast<android_dataspace>(dataSpace));
755 if (res != OK) {
756 jniThrowRuntimeException(env, "Set dataSpace failed");
757 return res;
758 }
759
Zhijun Hece9d6f92015-03-29 16:33:59 -0700760 android_native_rect_t cropRect;
761 cropRect.left = left;
762 cropRect.top = top;
763 cropRect.right = right;
764 cropRect.bottom = bottom;
765 res = native_window_set_crop(anw.get(), &cropRect);
766 if (res != OK) {
767 jniThrowRuntimeException(env, "Set crop rect failed");
768 return res;
769 }
770
Emilian Peev450a5ff2018-03-19 16:05:10 +0000771 res = native_window_set_buffers_transform(anw.get(), transform);
772 if (res != OK) {
773 jniThrowRuntimeException(env, "Set transform failed");
774 return res;
775 }
776
Emilian Peev750aec62018-04-06 12:55:00 +0100777 res = native_window_set_scaling_mode(anw.get(), scalingMode);
778 if (res != OK) {
779 jniThrowRuntimeException(env, "Set scaling mode failed");
780 return res;
781 }
782
Zhijun Hece9d6f92015-03-29 16:33:59 -0700783 // Step 3. Queue Image.
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700784 //
785 // Because onBufferReleased may be called before queueBuffer() returns,
786 // queue the "attached" flag before calling queueBuffer. In case
787 // queueBuffer() fails, remove it from the queue.
788 ctx->queueAttachedFlag(true);
Emilian Peev9c778e12020-10-29 17:36:22 -0700789 res = anw->queueBuffer(anw.get(), gb.get(), /*fenceFd*/
Zhijun Hece9d6f92015-03-29 16:33:59 -0700790 -1);
791 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700792 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700793 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700794 switch (res) {
795 case NO_INIT:
796 jniThrowException(env, "java/lang/IllegalStateException",
797 "Surface has been abandoned");
798 break;
799 default:
800 // TODO: handle other error cases here.
801 jniThrowRuntimeException(env, "Queue input buffer failed");
802 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700803 return res;
804 }
805
806 // Do not set the image native context. Since it would overwrite the existing native context
807 // of the image that is from ImageReader, the subsequent image close will run into issues.
808
809 return res;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800810}
811
Emilian Peev9c778e12020-10-29 17:36:22 -0700812static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
Sally Qiac97f992021-10-11 17:39:54 -0700813 jlong nativeBuffer, jint imageFormat, jlong timestampNs, jlong dataSpace,
814 jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
Emilian Peev9c778e12020-10-29 17:36:22 -0700815 ALOGV("%s", __FUNCTION__);
816 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
817 if (ctx == NULL || thiz == NULL) {
818 jniThrowException(env, "java/lang/IllegalStateException",
819 "ImageWriterContext is not initialized");
820 return -1;
821 }
822
823 sp<Surface> surface = ctx->getProducer();
824 if (isFormatOpaque(imageFormat) != isFormatOpaque(ctx->getBufferFormat())) {
825 jniThrowException(env, "java/lang/IllegalStateException",
826 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
827 return -1;
828 }
829
830 // Image is guaranteed to be from ImageReader at this point, so it is safe to
831 // cast to BufferItem pointer.
832 BufferItem* buffer = reinterpret_cast<BufferItem*>(nativeBuffer);
833 if (buffer == NULL) {
834 jniThrowException(env, "java/lang/IllegalStateException",
835 "Image is not initialized or already closed");
836 return -1;
837 }
838
Sally Qiac97f992021-10-11 17:39:54 -0700839 return attachAndQeueuGraphicBuffer(env, ctx, surface, buffer->mGraphicBuffer, timestampNs,
840 dataSpace, left, top, right, bottom, transform, scalingMode);
Emilian Peev9c778e12020-10-29 17:36:22 -0700841}
842
843static jint ImageWriter_attachAndQueueGraphicBuffer(JNIEnv* env, jobject thiz, jlong nativeCtx,
Sally Qiac97f992021-10-11 17:39:54 -0700844 jobject buffer, jint format, jlong timestampNs, jlong dataSpace, jint left, jint top,
Emilian Peev9c778e12020-10-29 17:36:22 -0700845 jint right, jint bottom, jint transform, jint scalingMode) {
846 ALOGV("%s", __FUNCTION__);
847 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
848 if (ctx == NULL || thiz == NULL) {
849 jniThrowException(env, "java/lang/IllegalStateException",
850 "ImageWriterContext is not initialized");
851 return -1;
852 }
853
854 sp<Surface> surface = ctx->getProducer();
855 if (isFormatOpaque(format) != isFormatOpaque(ctx->getBufferFormat())) {
856 jniThrowException(env, "java/lang/IllegalStateException",
857 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
858 return -1;
859 }
860
861 sp<GraphicBuffer> graphicBuffer = android_graphics_GraphicBuffer_getNativeGraphicsBuffer(env,
862 buffer);
863 if (graphicBuffer.get() == NULL) {
864 jniThrowException(env, "java/lang/IllegalArgumentException",
865 "Trying to attach an invalid graphic buffer");
866 return -1;
867 }
Sally Qiac97f992021-10-11 17:39:54 -0700868 return attachAndQeueuGraphicBuffer(env, ctx, surface, graphicBuffer, timestampNs,
869 dataSpace, left, top, right, bottom, transform, scalingMode);
Emilian Peev9c778e12020-10-29 17:36:22 -0700870}
871
Zhijun Hef6a09e52015-02-24 18:12:23 -0800872// --------------------------Image methods---------------------------------------
873
874static void Image_getNativeContext(JNIEnv* env, jobject thiz,
875 GraphicBuffer** buffer, int* fenceFd) {
876 ALOGV("%s", __FUNCTION__);
877 if (buffer != NULL) {
878 GraphicBuffer *gb = reinterpret_cast<GraphicBuffer *>
879 (env->GetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer));
880 *buffer = gb;
881 }
882
883 if (fenceFd != NULL) {
884 *fenceFd = reinterpret_cast<jint>(env->GetIntField(
885 thiz, gSurfaceImageClassInfo.mNativeFenceFd));
886 }
887}
888
889static void Image_setNativeContext(JNIEnv* env, jobject thiz,
Sally Qiac97f992021-10-11 17:39:54 -0700890 sp<GraphicBuffer> buffer, int fenceFd, long dataSpace) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800891 ALOGV("%s:", __FUNCTION__);
892 GraphicBuffer* p = NULL;
893 Image_getNativeContext(env, thiz, &p, /*fenceFd*/NULL);
894 if (buffer != 0) {
895 buffer->incStrong((void*)Image_setNativeContext);
896 }
897 if (p) {
898 p->decStrong((void*)Image_setNativeContext);
899 }
900 env->SetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer,
901 reinterpret_cast<jlong>(buffer.get()));
902
903 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
Sally Qiac97f992021-10-11 17:39:54 -0700904
905 env->SetLongField(thiz, gSurfaceImageClassInfo.mDataSpace, dataSpace);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800906}
907
908static void Image_unlockIfLocked(JNIEnv* env, jobject thiz) {
909 ALOGV("%s", __FUNCTION__);
910 GraphicBuffer* buffer;
911 Image_getNativeContext(env, thiz, &buffer, NULL);
912 if (buffer == NULL) {
913 jniThrowException(env, "java/lang/IllegalStateException",
914 "Image is not initialized");
915 return;
916 }
917
918 // Is locked?
919 bool isLocked = false;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700920 jobject planes = NULL;
921 if (!isFormatOpaque(buffer->getPixelFormat())) {
922 planes = env->GetObjectField(thiz, gSurfaceImageClassInfo.mPlanes);
923 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800924 isLocked = (planes != NULL);
925 if (isLocked) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700926 // 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 -0800927 status_t res = buffer->unlock();
928 if (res != OK) {
929 jniThrowRuntimeException(env, "unlock buffer failed");
John Reckdcd4c582019-07-12 13:13:05 -0700930 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800931 }
932 ALOGV("Successfully unlocked the image");
933 }
934}
935
936static jint Image_getWidth(JNIEnv* env, jobject thiz) {
937 ALOGV("%s", __FUNCTION__);
938 GraphicBuffer* buffer;
939 Image_getNativeContext(env, thiz, &buffer, NULL);
940 if (buffer == NULL) {
941 jniThrowException(env, "java/lang/IllegalStateException",
942 "Image is not initialized");
943 return -1;
944 }
945
946 return buffer->getWidth();
947}
948
949static jint Image_getHeight(JNIEnv* env, jobject thiz) {
950 ALOGV("%s", __FUNCTION__);
951 GraphicBuffer* buffer;
952 Image_getNativeContext(env, thiz, &buffer, NULL);
953 if (buffer == NULL) {
954 jniThrowException(env, "java/lang/IllegalStateException",
955 "Image is not initialized");
956 return -1;
957 }
958
959 return buffer->getHeight();
960}
961
Sally Qid26f4f02022-01-21 09:53:20 -0800962static jint Image_getFormat(JNIEnv* env, jobject thiz, jlong dataSpace) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800963 ALOGV("%s", __FUNCTION__);
964 GraphicBuffer* buffer;
965 Image_getNativeContext(env, thiz, &buffer, NULL);
966 if (buffer == NULL) {
967 jniThrowException(env, "java/lang/IllegalStateException",
968 "Image is not initialized");
969 return 0;
970 }
971
Fedor Kudasov4d027e92019-06-24 17:21:57 +0100972 PublicFormat publicFmt = mapHalFormatDataspaceToPublicFormat(buffer->getPixelFormat(),
Sally Qid26f4f02022-01-21 09:53:20 -0800973 static_cast<android_dataspace>(dataSpace));
974
Zhijun He0ab41622016-02-25 16:00:38 -0800975 return static_cast<jint>(publicFmt);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800976}
977
rennbe092192018-05-07 10:18:05 -0700978static jobject Image_getHardwareBuffer(JNIEnv* env, jobject thiz) {
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 NULL;
985 }
986 AHardwareBuffer* b = AHardwareBuffer_from_GraphicBuffer(buffer);
987 // don't user the public AHardwareBuffer_toHardwareBuffer() because this would force us
988 // to link against libandroid.so
989 return android_hardware_HardwareBuffer_createFromAHardwareBuffer(env, b);
990}
991
Zhijun Hef6a09e52015-02-24 18:12:23 -0800992static void Image_setFenceFd(JNIEnv* env, jobject thiz, int fenceFd) {
993 ALOGV("%s:", __FUNCTION__);
994 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
995}
996
997static void Image_getLockedImage(JNIEnv* env, jobject thiz, LockedImage *image) {
998 ALOGV("%s", __FUNCTION__);
999 GraphicBuffer* buffer;
1000 int fenceFd = -1;
1001 Image_getNativeContext(env, thiz, &buffer, &fenceFd);
1002 if (buffer == NULL) {
1003 jniThrowException(env, "java/lang/IllegalStateException",
1004 "Image is not initialized");
1005 return;
1006 }
1007
Zhijun He0ab41622016-02-25 16:00:38 -08001008 // ImageWriter doesn't use crop by itself, app sets it, use the no crop version.
1009 const Rect noCrop(buffer->width, buffer->height);
1010 status_t res = lockImageFromBuffer(
1011 buffer, GRALLOC_USAGE_SW_WRITE_OFTEN, noCrop, fenceFd, image);
1012 // Clear the fenceFd as it is already consumed by lock call.
1013 Image_setFenceFd(env, thiz, /*fenceFd*/-1);
1014 if (res != OK) {
1015 jniThrowExceptionFmt(env, "java/lang/RuntimeException",
1016 "lock buffer failed for format 0x%x",
1017 buffer->getPixelFormat());
1018 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001019 }
1020
Zhijun He0ab41622016-02-25 16:00:38 -08001021 ALOGV("%s: Successfully locked the image", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001022 // crop, transform, scalingMode, timestamp, and frameNumber should be set by producer,
1023 // and we don't set them here.
1024}
1025
John Reckdcd4c582019-07-12 13:13:05 -07001026static bool Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
Zhijun Hef6a09e52015-02-24 18:12:23 -08001027 int32_t writerFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
1028 ALOGV("%s", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001029
Zhijun He0ab41622016-02-25 16:00:38 -08001030 status_t res = getLockedImageInfo(buffer, idx, writerFormat, base, size,
1031 pixelStride, rowStride);
1032 if (res != OK) {
1033 jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
John Reck03bd07a2019-07-12 13:53:04 -07001034 "Pixel format: 0x%x is unsupported", writerFormat);
John Reckdcd4c582019-07-12 13:13:05 -07001035 return false;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001036 }
John Reckdcd4c582019-07-12 13:13:05 -07001037 return true;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001038}
1039
1040static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
Sally Qid26f4f02022-01-21 09:53:20 -08001041 int numPlanes, int writerFormat, long dataSpace) {
Zhijun Hef6a09e52015-02-24 18:12:23 -08001042 ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
1043 int rowStride, pixelStride;
1044 uint8_t *pData;
1045 uint32_t dataSize;
1046 jobject byteBuffer;
1047
Sally Qid26f4f02022-01-21 09:53:20 -08001048 int format = Image_getFormat(env, thiz, dataSpace);
Zhijun Hece9d6f92015-03-29 16:33:59 -07001049 if (isFormatOpaque(format) && numPlanes > 0) {
Zhijun Hef6a09e52015-02-24 18:12:23 -08001050 String8 msg;
1051 msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
1052 " must be 0", format, numPlanes);
1053 jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
1054 return NULL;
1055 }
1056
1057 jobjectArray surfacePlanes = env->NewObjectArray(numPlanes, gSurfacePlaneClassInfo.clazz,
1058 /*initial_element*/NULL);
1059 if (surfacePlanes == NULL) {
1060 jniThrowRuntimeException(env, "Failed to create SurfacePlane arrays,"
1061 " probably out of memory");
1062 return NULL;
1063 }
Zhijun Hece9d6f92015-03-29 16:33:59 -07001064 if (isFormatOpaque(format)) {
1065 return surfacePlanes;
1066 }
Zhijun Hef6a09e52015-02-24 18:12:23 -08001067
1068 // Buildup buffer info: rowStride, pixelStride and byteBuffers.
1069 LockedImage lockedImg = LockedImage();
1070 Image_getLockedImage(env, thiz, &lockedImg);
1071
1072 // Create all SurfacePlanes
Zhijun He0ab41622016-02-25 16:00:38 -08001073 PublicFormat publicWriterFormat = static_cast<PublicFormat>(writerFormat);
Fedor Kudasov4d027e92019-06-24 17:21:57 +01001074 writerFormat = mapPublicFormatToHalFormat(publicWriterFormat);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001075 for (int i = 0; i < numPlanes; i++) {
John Reckdcd4c582019-07-12 13:13:05 -07001076 if (!Image_getLockedImageInfo(env, &lockedImg, i, writerFormat,
1077 &pData, &dataSize, &pixelStride, &rowStride)) {
1078 return NULL;
1079 }
Zhijun Hef6a09e52015-02-24 18:12:23 -08001080 byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
1081 if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
1082 jniThrowException(env, "java/lang/IllegalStateException",
1083 "Failed to allocate ByteBuffer");
1084 return NULL;
1085 }
1086
1087 // Finally, create this SurfacePlane.
1088 jobject surfacePlane = env->NewObject(gSurfacePlaneClassInfo.clazz,
1089 gSurfacePlaneClassInfo.ctor, thiz, rowStride, pixelStride, byteBuffer);
1090 env->SetObjectArrayElement(surfacePlanes, i, surfacePlane);
1091 }
1092
1093 return surfacePlanes;
1094}
1095
Zhijun Hef6a09e52015-02-24 18:12:23 -08001096} // extern "C"
1097
1098// ----------------------------------------------------------------------------
1099
1100static JNINativeMethod gImageWriterMethods[] = {
1101 {"nativeClassInit", "()V", (void*)ImageWriter_classInit },
Sally Qidb57de32022-01-05 11:53:44 -08001102 {"nativeInit", "(Ljava/lang/Object;Landroid/view/Surface;IIIZIJJ)J",
Zhijun Hef6a09e52015-02-24 18:12:23 -08001103 (void*)ImageWriter_init },
Zhijun Hece9d6f92015-03-29 16:33:59 -07001104 {"nativeClose", "(J)V", (void*)ImageWriter_close },
Sally Qiac97f992021-10-11 17:39:54 -07001105 {"nativeAttachAndQueueImage",
1106 "(JJIJJIIIIII)I",
1107 (void*)ImageWriter_attachAndQueueImage },
Emilian Peev9c778e12020-10-29 17:36:22 -07001108 {"nativeAttachAndQueueGraphicBuffer",
Sally Qiac97f992021-10-11 17:39:54 -07001109 "(JLandroid/graphics/GraphicBuffer;IJJIIIIII)I",
Emilian Peev9c778e12020-10-29 17:36:22 -07001110 (void*)ImageWriter_attachAndQueueGraphicBuffer },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001111 {"nativeDequeueInputImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_dequeueImage },
Sally Qiac97f992021-10-11 17:39:54 -07001112 {"nativeQueueInputImage", "(JLandroid/media/Image;JJIIIIII)V",
1113 (void*)ImageWriter_queueImage },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001114 {"cancelImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_cancelImage },
1115};
1116
1117static JNINativeMethod gImageMethods[] = {
Sally Qid26f4f02022-01-21 09:53:20 -08001118 {"nativeCreatePlanes", "(IIJ)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
rennbe092192018-05-07 10:18:05 -07001119 (void*)Image_createSurfacePlanes },
1120 {"nativeGetWidth", "()I", (void*)Image_getWidth },
1121 {"nativeGetHeight", "()I", (void*)Image_getHeight },
Sally Qid26f4f02022-01-21 09:53:20 -08001122 {"nativeGetFormat", "(J)I", (void*)Image_getFormat },
rennbe092192018-05-07 10:18:05 -07001123 {"nativeGetHardwareBuffer", "()Landroid/hardware/HardwareBuffer;",
1124 (void*)Image_getHardwareBuffer },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001125};
1126
1127int register_android_media_ImageWriter(JNIEnv *env) {
1128
1129 int ret1 = AndroidRuntime::registerNativeMethods(env,
1130 "android/media/ImageWriter", gImageWriterMethods, NELEM(gImageWriterMethods));
1131
1132 int ret2 = AndroidRuntime::registerNativeMethods(env,
1133 "android/media/ImageWriter$WriterSurfaceImage", gImageMethods, NELEM(gImageMethods));
1134
1135 return (ret1 || ret2);
1136}