blob: 2e419a61de91ba44f4f3ac8e7880becd808d0be8 [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);
463 int userFormat = static_cast<int>(mapHalFormatDataspaceToPublicFormat(
464 hardwareBufferFormat, nativeDataspace));
465 res = native_window_set_buffers_format(anw.get(), hardwareBufferFormat);
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700466 if (res != OK) {
467 ALOGE("%s: Unable to configure consumer native buffer format to %#x",
Sally Qidb57de32022-01-05 11:53:44 -0800468 __FUNCTION__, hardwareBufferFormat);
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700469 jniThrowRuntimeException(env, "Failed to set Surface format");
470 return 0;
471 }
472
473 res = native_window_set_buffers_data_space(anw.get(), nativeDataspace);
474 if (res != OK) {
475 ALOGE("%s: Unable to configure consumer dataspace %#x",
476 __FUNCTION__, nativeDataspace);
477 jniThrowRuntimeException(env, "Failed to set Surface dataspace");
478 return 0;
479 }
Sally Qiac97f992021-10-11 17:39:54 -0700480 ctx->setBufferDataSpace(nativeDataspace);
Zhijun He916d8ac2017-03-22 17:33:47 -0700481 surfaceFormat = userFormat;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800482 }
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700483
Zhijun He916d8ac2017-03-22 17:33:47 -0700484 ctx->setBufferFormat(surfaceFormat);
485 env->SetIntField(thiz,
486 gImageWriterClassInfo.mWriterFormat, reinterpret_cast<jint>(surfaceFormat));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800487
Sally Qidb57de32022-01-05 11:53:44 -0800488 res = native_window_set_usage(anw.get(), ndkUsage);
489 if (res != OK) {
490 ALOGE("%s: Configure usage %08x for format %08x failed: %s (%d)",
491 __FUNCTION__, static_cast<unsigned int>(ndkUsage),
492 surfaceFormat, strerror(-res), res);
493 jniThrowRuntimeException(env, "Failed to SW_WRITE_OFTEN configure usage");
494 return 0;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800495 }
496
497 int minUndequeuedBufferCount = 0;
498 res = anw->query(anw.get(),
499 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufferCount);
500 if (res != OK) {
501 ALOGE("%s: Query producer undequeued buffer count failed: %s (%d)",
502 __FUNCTION__, strerror(-res), res);
503 jniThrowRuntimeException(env, "Query producer undequeued buffer count failed");
504 return 0;
505 }
506
507 size_t totalBufferCount = maxImages + minUndequeuedBufferCount;
508 res = native_window_set_buffer_count(anw.get(), totalBufferCount);
509 if (res != OK) {
510 ALOGE("%s: Set buffer count failed: %s (%d)", __FUNCTION__, strerror(-res), res);
511 jniThrowRuntimeException(env, "Set buffer count failed");
512 return 0;
513 }
514
515 if (ctx != 0) {
516 ctx->incStrong((void*)ImageWriter_init);
517 }
518 return nativeCtx;
519}
520
521static void ImageWriter_dequeueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
522 ALOGV("%s", __FUNCTION__);
523 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
524 if (ctx == NULL || thiz == NULL) {
525 jniThrowException(env, "java/lang/IllegalStateException",
526 "ImageWriterContext is not initialized");
527 return;
528 }
529
530 sp<ANativeWindow> anw = ctx->getProducer();
531 android_native_buffer_t *anb = NULL;
532 int fenceFd = -1;
533 status_t res = anw->dequeueBuffer(anw.get(), &anb, &fenceFd);
534 if (res != OK) {
Zhijun Hea5827142015-04-22 10:07:42 -0700535 ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700536 switch (res) {
537 case NO_INIT:
538 jniThrowException(env, "java/lang/IllegalStateException",
539 "Surface has been abandoned");
540 break;
541 default:
542 // TODO: handle other error cases here.
543 jniThrowRuntimeException(env, "dequeue buffer failed");
544 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800545 return;
546 }
547 // New GraphicBuffer object doesn't own the handle, thus the native buffer
548 // won't be freed when this object is destroyed.
Mathias Agopian845eef05f2017-04-03 17:51:15 -0700549 sp<GraphicBuffer> buffer(GraphicBuffer::from(anb));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800550
551 // Note that:
552 // 1. No need to lock buffer now, will only lock it when the first getPlanes() is called.
553 // 2. Fence will be saved to mNativeFenceFd, and will consumed by lock/queue/cancel buffer
554 // later.
555 // 3. need use lockAsync here, as it will handle the dequeued fence for us automatically.
556
557 // Finally, set the native info into image object.
Sally Qiac97f992021-10-11 17:39:54 -0700558 Image_setNativeContext(env, image, buffer, fenceFd, ctx->getBufferDataSpace());
Zhijun Hef6a09e52015-02-24 18:12:23 -0800559}
560
561static void ImageWriter_close(JNIEnv* env, jobject thiz, jlong nativeCtx) {
562 ALOGV("%s:", __FUNCTION__);
563 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
564 if (ctx == NULL || thiz == NULL) {
Chien-Yu Chen0375cb02015-06-18 11:55:18 -0700565 // ImageWriter is already closed.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800566 return;
567 }
568
569 ANativeWindow* producer = ctx->getProducer();
570 if (producer != NULL) {
571 /**
572 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not
573 * connectable after disconnect. MEDIA or CAMERA are treated the same internally.
574 * The producer listener will be cleared after disconnect call.
575 */
576 status_t res = native_window_api_disconnect(producer, /*api*/NATIVE_WINDOW_API_CAMERA);
577 /**
578 * This is not an error. if client calling process dies, the window will
579 * also die and all calls to it will return DEAD_OBJECT, thus it's already
580 * "disconnected"
581 */
582 if (res == DEAD_OBJECT) {
583 ALOGW("%s: While disconnecting ImageWriter from native window, the"
584 " native window died already", __FUNCTION__);
585 } else if (res != OK) {
586 ALOGE("%s: native window disconnect failed: %s (%d)",
587 __FUNCTION__, strerror(-res), res);
588 jniThrowRuntimeException(env, "Native window disconnect failed");
589 return;
590 }
591 }
592
593 ctx->decStrong((void*)ImageWriter_init);
594}
595
596static void ImageWriter_cancelImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
597 ALOGV("%s", __FUNCTION__);
598 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
599 if (ctx == NULL || thiz == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800600 ALOGW("ImageWriter#close called before Image#close, consider calling Image#close first");
Zhijun Hef6a09e52015-02-24 18:12:23 -0800601 return;
602 }
603
604 sp<ANativeWindow> anw = ctx->getProducer();
605
606 GraphicBuffer *buffer = NULL;
607 int fenceFd = -1;
608 Image_getNativeContext(env, image, &buffer, &fenceFd);
609 if (buffer == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800610 // Cancel an already cancelled image is harmless.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800611 return;
612 }
613
614 // Unlock the image if it was locked
615 Image_unlockIfLocked(env, image);
616
617 anw->cancelBuffer(anw.get(), buffer, fenceFd);
618
Sally Qiac97f992021-10-11 17:39:54 -0700619 Image_setNativeContext(env, image, NULL, -1, HAL_DATASPACE_UNKNOWN);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800620}
621
622static void ImageWriter_queueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image,
Sally Qiac97f992021-10-11 17:39:54 -0700623 jlong timestampNs, jlong dataSpace, jint left, jint top, jint right,
624 jint bottom, jint transform, jint scalingMode) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800625 ALOGV("%s", __FUNCTION__);
626 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
627 if (ctx == NULL || thiz == NULL) {
628 jniThrowException(env, "java/lang/IllegalStateException",
629 "ImageWriterContext is not initialized");
630 return;
631 }
632
633 status_t res = OK;
634 sp<ANativeWindow> anw = ctx->getProducer();
635
636 GraphicBuffer *buffer = NULL;
637 int fenceFd = -1;
638 Image_getNativeContext(env, image, &buffer, &fenceFd);
639 if (buffer == NULL) {
640 jniThrowException(env, "java/lang/IllegalStateException",
641 "Image is not initialized");
642 return;
643 }
644
645 // Unlock image if it was locked.
646 Image_unlockIfLocked(env, image);
647
648 // Set timestamp
Zhijun Hed1cbc682015-03-23 10:10:04 -0700649 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800650 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
651 if (res != OK) {
652 jniThrowRuntimeException(env, "Set timestamp failed");
653 return;
654 }
655
Sally Qiac97f992021-10-11 17:39:54 -0700656 // Set dataSpace
657 ALOGV("dataSpace to be queued: %" PRId64, dataSpace);
658 res = native_window_set_buffers_data_space(
659 anw.get(), static_cast<android_dataspace>(dataSpace));
660 if (res != OK) {
661 jniThrowRuntimeException(env, "Set dataspace failed");
662 return;
663 }
664
Zhijun Hef6a09e52015-02-24 18:12:23 -0800665 // Set crop
666 android_native_rect_t cropRect;
667 cropRect.left = left;
668 cropRect.top = top;
669 cropRect.right = right;
670 cropRect.bottom = bottom;
671 res = native_window_set_crop(anw.get(), &cropRect);
672 if (res != OK) {
673 jniThrowRuntimeException(env, "Set crop rect failed");
674 return;
675 }
676
Emilian Peev450a5ff2018-03-19 16:05:10 +0000677 res = native_window_set_buffers_transform(anw.get(), transform);
678 if (res != OK) {
679 jniThrowRuntimeException(env, "Set transform failed");
680 return;
681 }
682
Emilian Peev750aec62018-04-06 12:55:00 +0100683 res = native_window_set_scaling_mode(anw.get(), scalingMode);
684 if (res != OK) {
685 jniThrowRuntimeException(env, "Set scaling mode failed");
686 return;
687 }
688
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700689 // Finally, queue input buffer.
690 //
691 // Because onBufferReleased may be called before queueBuffer() returns,
692 // queue the "attached" flag before calling queueBuffer. In case
693 // queueBuffer() fails, remove it from the queue.
694 ctx->queueAttachedFlag(false);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800695 res = anw->queueBuffer(anw.get(), buffer, fenceFd);
696 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700697 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700698 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700699 switch (res) {
700 case NO_INIT:
701 jniThrowException(env, "java/lang/IllegalStateException",
702 "Surface has been abandoned");
703 break;
704 default:
705 // TODO: handle other error cases here.
706 jniThrowRuntimeException(env, "Queue input buffer failed");
707 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800708 return;
709 }
710
Zhijun Hece9d6f92015-03-29 16:33:59 -0700711 // Clear the image native context: end of this image's lifecycle in public API.
Sally Qiac97f992021-10-11 17:39:54 -0700712 Image_setNativeContext(env, image, NULL, -1, HAL_DATASPACE_UNKNOWN);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800713}
714
Emilian Peev9c778e12020-10-29 17:36:22 -0700715static status_t attachAndQeueuGraphicBuffer(JNIEnv* env, JNIImageWriterContext *ctx,
Sally Qiac97f992021-10-11 17:39:54 -0700716 sp<Surface> surface, sp<GraphicBuffer> gb, jlong timestampNs, jlong dataSpace,
717 jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700718 status_t res = OK;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700719 // Step 1. Attach Image
Emilian Peev9c778e12020-10-29 17:36:22 -0700720 res = surface->attachBuffer(gb.get());
Zhijun Hece9d6f92015-03-29 16:33:59 -0700721 if (res != OK) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700722 ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700723 switch (res) {
724 case NO_INIT:
725 jniThrowException(env, "java/lang/IllegalStateException",
726 "Surface has been abandoned");
727 break;
728 default:
729 // TODO: handle other error cases here.
730 jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
731 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700732 return res;
733 }
734 sp < ANativeWindow > anw = surface;
735
Sally Qiac97f992021-10-11 17:39:54 -0700736 // Step 2. Set timestamp, dataspace, crop, transform and scaling mode.
737 // Note that we do not need unlock the image because it was not locked.
Zhijun Hece9d6f92015-03-29 16:33:59 -0700738 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
739 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
740 if (res != OK) {
741 jniThrowRuntimeException(env, "Set timestamp failed");
742 return res;
743 }
744
Sally Qiac97f992021-10-11 17:39:54 -0700745 ALOGV("dataSpace to be queued: %" PRId64, dataSpace);
746 res = native_window_set_buffers_data_space(
747 anw.get(), static_cast<android_dataspace>(dataSpace));
748 if (res != OK) {
749 jniThrowRuntimeException(env, "Set dataSpace failed");
750 return res;
751 }
752
Zhijun Hece9d6f92015-03-29 16:33:59 -0700753 android_native_rect_t cropRect;
754 cropRect.left = left;
755 cropRect.top = top;
756 cropRect.right = right;
757 cropRect.bottom = bottom;
758 res = native_window_set_crop(anw.get(), &cropRect);
759 if (res != OK) {
760 jniThrowRuntimeException(env, "Set crop rect failed");
761 return res;
762 }
763
Emilian Peev450a5ff2018-03-19 16:05:10 +0000764 res = native_window_set_buffers_transform(anw.get(), transform);
765 if (res != OK) {
766 jniThrowRuntimeException(env, "Set transform failed");
767 return res;
768 }
769
Emilian Peev750aec62018-04-06 12:55:00 +0100770 res = native_window_set_scaling_mode(anw.get(), scalingMode);
771 if (res != OK) {
772 jniThrowRuntimeException(env, "Set scaling mode failed");
773 return res;
774 }
775
Zhijun Hece9d6f92015-03-29 16:33:59 -0700776 // Step 3. Queue Image.
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700777 //
778 // Because onBufferReleased may be called before queueBuffer() returns,
779 // queue the "attached" flag before calling queueBuffer. In case
780 // queueBuffer() fails, remove it from the queue.
781 ctx->queueAttachedFlag(true);
Emilian Peev9c778e12020-10-29 17:36:22 -0700782 res = anw->queueBuffer(anw.get(), gb.get(), /*fenceFd*/
Zhijun Hece9d6f92015-03-29 16:33:59 -0700783 -1);
784 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700785 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700786 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700787 switch (res) {
788 case NO_INIT:
789 jniThrowException(env, "java/lang/IllegalStateException",
790 "Surface has been abandoned");
791 break;
792 default:
793 // TODO: handle other error cases here.
794 jniThrowRuntimeException(env, "Queue input buffer failed");
795 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700796 return res;
797 }
798
799 // Do not set the image native context. Since it would overwrite the existing native context
800 // of the image that is from ImageReader, the subsequent image close will run into issues.
801
802 return res;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800803}
804
Emilian Peev9c778e12020-10-29 17:36:22 -0700805static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
Sally Qiac97f992021-10-11 17:39:54 -0700806 jlong nativeBuffer, jint imageFormat, jlong timestampNs, jlong dataSpace,
807 jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
Emilian Peev9c778e12020-10-29 17:36:22 -0700808 ALOGV("%s", __FUNCTION__);
809 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
810 if (ctx == NULL || thiz == NULL) {
811 jniThrowException(env, "java/lang/IllegalStateException",
812 "ImageWriterContext is not initialized");
813 return -1;
814 }
815
816 sp<Surface> surface = ctx->getProducer();
817 if (isFormatOpaque(imageFormat) != isFormatOpaque(ctx->getBufferFormat())) {
818 jniThrowException(env, "java/lang/IllegalStateException",
819 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
820 return -1;
821 }
822
823 // Image is guaranteed to be from ImageReader at this point, so it is safe to
824 // cast to BufferItem pointer.
825 BufferItem* buffer = reinterpret_cast<BufferItem*>(nativeBuffer);
826 if (buffer == NULL) {
827 jniThrowException(env, "java/lang/IllegalStateException",
828 "Image is not initialized or already closed");
829 return -1;
830 }
831
Sally Qiac97f992021-10-11 17:39:54 -0700832 return attachAndQeueuGraphicBuffer(env, ctx, surface, buffer->mGraphicBuffer, timestampNs,
833 dataSpace, left, top, right, bottom, transform, scalingMode);
Emilian Peev9c778e12020-10-29 17:36:22 -0700834}
835
836static jint ImageWriter_attachAndQueueGraphicBuffer(JNIEnv* env, jobject thiz, jlong nativeCtx,
Sally Qiac97f992021-10-11 17:39:54 -0700837 jobject buffer, jint format, jlong timestampNs, jlong dataSpace, jint left, jint top,
Emilian Peev9c778e12020-10-29 17:36:22 -0700838 jint right, jint bottom, jint transform, jint scalingMode) {
839 ALOGV("%s", __FUNCTION__);
840 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
841 if (ctx == NULL || thiz == NULL) {
842 jniThrowException(env, "java/lang/IllegalStateException",
843 "ImageWriterContext is not initialized");
844 return -1;
845 }
846
847 sp<Surface> surface = ctx->getProducer();
848 if (isFormatOpaque(format) != isFormatOpaque(ctx->getBufferFormat())) {
849 jniThrowException(env, "java/lang/IllegalStateException",
850 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
851 return -1;
852 }
853
854 sp<GraphicBuffer> graphicBuffer = android_graphics_GraphicBuffer_getNativeGraphicsBuffer(env,
855 buffer);
856 if (graphicBuffer.get() == NULL) {
857 jniThrowException(env, "java/lang/IllegalArgumentException",
858 "Trying to attach an invalid graphic buffer");
859 return -1;
860 }
Sally Qiac97f992021-10-11 17:39:54 -0700861 return attachAndQeueuGraphicBuffer(env, ctx, surface, graphicBuffer, timestampNs,
862 dataSpace, left, top, right, bottom, transform, scalingMode);
Emilian Peev9c778e12020-10-29 17:36:22 -0700863}
864
Zhijun Hef6a09e52015-02-24 18:12:23 -0800865// --------------------------Image methods---------------------------------------
866
867static void Image_getNativeContext(JNIEnv* env, jobject thiz,
868 GraphicBuffer** buffer, int* fenceFd) {
869 ALOGV("%s", __FUNCTION__);
870 if (buffer != NULL) {
871 GraphicBuffer *gb = reinterpret_cast<GraphicBuffer *>
872 (env->GetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer));
873 *buffer = gb;
874 }
875
876 if (fenceFd != NULL) {
877 *fenceFd = reinterpret_cast<jint>(env->GetIntField(
878 thiz, gSurfaceImageClassInfo.mNativeFenceFd));
879 }
880}
881
882static void Image_setNativeContext(JNIEnv* env, jobject thiz,
Sally Qiac97f992021-10-11 17:39:54 -0700883 sp<GraphicBuffer> buffer, int fenceFd, long dataSpace) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800884 ALOGV("%s:", __FUNCTION__);
885 GraphicBuffer* p = NULL;
886 Image_getNativeContext(env, thiz, &p, /*fenceFd*/NULL);
887 if (buffer != 0) {
888 buffer->incStrong((void*)Image_setNativeContext);
889 }
890 if (p) {
891 p->decStrong((void*)Image_setNativeContext);
892 }
893 env->SetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer,
894 reinterpret_cast<jlong>(buffer.get()));
895
896 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
Sally Qiac97f992021-10-11 17:39:54 -0700897
898 env->SetLongField(thiz, gSurfaceImageClassInfo.mDataSpace, dataSpace);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800899}
900
901static void Image_unlockIfLocked(JNIEnv* env, jobject thiz) {
902 ALOGV("%s", __FUNCTION__);
903 GraphicBuffer* buffer;
904 Image_getNativeContext(env, thiz, &buffer, NULL);
905 if (buffer == NULL) {
906 jniThrowException(env, "java/lang/IllegalStateException",
907 "Image is not initialized");
908 return;
909 }
910
911 // Is locked?
912 bool isLocked = false;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700913 jobject planes = NULL;
914 if (!isFormatOpaque(buffer->getPixelFormat())) {
915 planes = env->GetObjectField(thiz, gSurfaceImageClassInfo.mPlanes);
916 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800917 isLocked = (planes != NULL);
918 if (isLocked) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700919 // 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 -0800920 status_t res = buffer->unlock();
921 if (res != OK) {
922 jniThrowRuntimeException(env, "unlock buffer failed");
John Reckdcd4c582019-07-12 13:13:05 -0700923 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800924 }
925 ALOGV("Successfully unlocked the image");
926 }
927}
928
929static jint Image_getWidth(JNIEnv* env, jobject thiz) {
930 ALOGV("%s", __FUNCTION__);
931 GraphicBuffer* buffer;
932 Image_getNativeContext(env, thiz, &buffer, NULL);
933 if (buffer == NULL) {
934 jniThrowException(env, "java/lang/IllegalStateException",
935 "Image is not initialized");
936 return -1;
937 }
938
939 return buffer->getWidth();
940}
941
942static jint Image_getHeight(JNIEnv* env, jobject thiz) {
943 ALOGV("%s", __FUNCTION__);
944 GraphicBuffer* buffer;
945 Image_getNativeContext(env, thiz, &buffer, NULL);
946 if (buffer == NULL) {
947 jniThrowException(env, "java/lang/IllegalStateException",
948 "Image is not initialized");
949 return -1;
950 }
951
952 return buffer->getHeight();
953}
954
Zhijun Hef6a09e52015-02-24 18:12:23 -0800955static jint Image_getFormat(JNIEnv* env, jobject thiz) {
956 ALOGV("%s", __FUNCTION__);
957 GraphicBuffer* buffer;
958 Image_getNativeContext(env, thiz, &buffer, NULL);
959 if (buffer == NULL) {
960 jniThrowException(env, "java/lang/IllegalStateException",
961 "Image is not initialized");
962 return 0;
963 }
964
Zhijun He0ab41622016-02-25 16:00:38 -0800965 // ImageWriter doesn't support data space yet, assuming it is unknown.
Fedor Kudasov4d027e92019-06-24 17:21:57 +0100966 PublicFormat publicFmt = mapHalFormatDataspaceToPublicFormat(buffer->getPixelFormat(),
967 HAL_DATASPACE_UNKNOWN);
Zhijun He0ab41622016-02-25 16:00:38 -0800968 return static_cast<jint>(publicFmt);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800969}
970
rennbe092192018-05-07 10:18:05 -0700971static jobject Image_getHardwareBuffer(JNIEnv* env, jobject thiz) {
972 GraphicBuffer* buffer;
973 Image_getNativeContext(env, thiz, &buffer, NULL);
974 if (buffer == NULL) {
975 jniThrowException(env, "java/lang/IllegalStateException",
976 "Image is not initialized");
977 return NULL;
978 }
979 AHardwareBuffer* b = AHardwareBuffer_from_GraphicBuffer(buffer);
980 // don't user the public AHardwareBuffer_toHardwareBuffer() because this would force us
981 // to link against libandroid.so
982 return android_hardware_HardwareBuffer_createFromAHardwareBuffer(env, b);
983}
984
Zhijun Hef6a09e52015-02-24 18:12:23 -0800985static void Image_setFenceFd(JNIEnv* env, jobject thiz, int fenceFd) {
986 ALOGV("%s:", __FUNCTION__);
987 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
988}
989
990static void Image_getLockedImage(JNIEnv* env, jobject thiz, LockedImage *image) {
991 ALOGV("%s", __FUNCTION__);
992 GraphicBuffer* buffer;
993 int fenceFd = -1;
994 Image_getNativeContext(env, thiz, &buffer, &fenceFd);
995 if (buffer == NULL) {
996 jniThrowException(env, "java/lang/IllegalStateException",
997 "Image is not initialized");
998 return;
999 }
1000
Zhijun He0ab41622016-02-25 16:00:38 -08001001 // ImageWriter doesn't use crop by itself, app sets it, use the no crop version.
1002 const Rect noCrop(buffer->width, buffer->height);
1003 status_t res = lockImageFromBuffer(
1004 buffer, GRALLOC_USAGE_SW_WRITE_OFTEN, noCrop, fenceFd, image);
1005 // Clear the fenceFd as it is already consumed by lock call.
1006 Image_setFenceFd(env, thiz, /*fenceFd*/-1);
1007 if (res != OK) {
1008 jniThrowExceptionFmt(env, "java/lang/RuntimeException",
1009 "lock buffer failed for format 0x%x",
1010 buffer->getPixelFormat());
1011 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001012 }
1013
Zhijun He0ab41622016-02-25 16:00:38 -08001014 ALOGV("%s: Successfully locked the image", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001015 // crop, transform, scalingMode, timestamp, and frameNumber should be set by producer,
1016 // and we don't set them here.
1017}
1018
John Reckdcd4c582019-07-12 13:13:05 -07001019static bool Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
Zhijun Hef6a09e52015-02-24 18:12:23 -08001020 int32_t writerFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
1021 ALOGV("%s", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001022
Zhijun He0ab41622016-02-25 16:00:38 -08001023 status_t res = getLockedImageInfo(buffer, idx, writerFormat, base, size,
1024 pixelStride, rowStride);
1025 if (res != OK) {
1026 jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
John Reck03bd07a2019-07-12 13:53:04 -07001027 "Pixel format: 0x%x is unsupported", writerFormat);
John Reckdcd4c582019-07-12 13:13:05 -07001028 return false;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001029 }
John Reckdcd4c582019-07-12 13:13:05 -07001030 return true;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001031}
1032
1033static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
1034 int numPlanes, int writerFormat) {
1035 ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
1036 int rowStride, pixelStride;
1037 uint8_t *pData;
1038 uint32_t dataSize;
1039 jobject byteBuffer;
1040
1041 int format = Image_getFormat(env, thiz);
Zhijun Hece9d6f92015-03-29 16:33:59 -07001042 if (isFormatOpaque(format) && numPlanes > 0) {
Zhijun Hef6a09e52015-02-24 18:12:23 -08001043 String8 msg;
1044 msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
1045 " must be 0", format, numPlanes);
1046 jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
1047 return NULL;
1048 }
1049
1050 jobjectArray surfacePlanes = env->NewObjectArray(numPlanes, gSurfacePlaneClassInfo.clazz,
1051 /*initial_element*/NULL);
1052 if (surfacePlanes == NULL) {
1053 jniThrowRuntimeException(env, "Failed to create SurfacePlane arrays,"
1054 " probably out of memory");
1055 return NULL;
1056 }
Zhijun Hece9d6f92015-03-29 16:33:59 -07001057 if (isFormatOpaque(format)) {
1058 return surfacePlanes;
1059 }
Zhijun Hef6a09e52015-02-24 18:12:23 -08001060
1061 // Buildup buffer info: rowStride, pixelStride and byteBuffers.
1062 LockedImage lockedImg = LockedImage();
1063 Image_getLockedImage(env, thiz, &lockedImg);
1064
1065 // Create all SurfacePlanes
Zhijun He0ab41622016-02-25 16:00:38 -08001066 PublicFormat publicWriterFormat = static_cast<PublicFormat>(writerFormat);
Fedor Kudasov4d027e92019-06-24 17:21:57 +01001067 writerFormat = mapPublicFormatToHalFormat(publicWriterFormat);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001068 for (int i = 0; i < numPlanes; i++) {
John Reckdcd4c582019-07-12 13:13:05 -07001069 if (!Image_getLockedImageInfo(env, &lockedImg, i, writerFormat,
1070 &pData, &dataSize, &pixelStride, &rowStride)) {
1071 return NULL;
1072 }
Zhijun Hef6a09e52015-02-24 18:12:23 -08001073 byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
1074 if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
1075 jniThrowException(env, "java/lang/IllegalStateException",
1076 "Failed to allocate ByteBuffer");
1077 return NULL;
1078 }
1079
1080 // Finally, create this SurfacePlane.
1081 jobject surfacePlane = env->NewObject(gSurfacePlaneClassInfo.clazz,
1082 gSurfacePlaneClassInfo.ctor, thiz, rowStride, pixelStride, byteBuffer);
1083 env->SetObjectArrayElement(surfacePlanes, i, surfacePlane);
1084 }
1085
1086 return surfacePlanes;
1087}
1088
Zhijun Hef6a09e52015-02-24 18:12:23 -08001089} // extern "C"
1090
1091// ----------------------------------------------------------------------------
1092
1093static JNINativeMethod gImageWriterMethods[] = {
1094 {"nativeClassInit", "()V", (void*)ImageWriter_classInit },
Sally Qidb57de32022-01-05 11:53:44 -08001095 {"nativeInit", "(Ljava/lang/Object;Landroid/view/Surface;IIIZIJJ)J",
Zhijun Hef6a09e52015-02-24 18:12:23 -08001096 (void*)ImageWriter_init },
Zhijun Hece9d6f92015-03-29 16:33:59 -07001097 {"nativeClose", "(J)V", (void*)ImageWriter_close },
Sally Qiac97f992021-10-11 17:39:54 -07001098 {"nativeAttachAndQueueImage",
1099 "(JJIJJIIIIII)I",
1100 (void*)ImageWriter_attachAndQueueImage },
Emilian Peev9c778e12020-10-29 17:36:22 -07001101 {"nativeAttachAndQueueGraphicBuffer",
Sally Qiac97f992021-10-11 17:39:54 -07001102 "(JLandroid/graphics/GraphicBuffer;IJJIIIIII)I",
Emilian Peev9c778e12020-10-29 17:36:22 -07001103 (void*)ImageWriter_attachAndQueueGraphicBuffer },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001104 {"nativeDequeueInputImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_dequeueImage },
Sally Qiac97f992021-10-11 17:39:54 -07001105 {"nativeQueueInputImage", "(JLandroid/media/Image;JJIIIIII)V",
1106 (void*)ImageWriter_queueImage },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001107 {"cancelImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_cancelImage },
1108};
1109
1110static JNINativeMethod gImageMethods[] = {
1111 {"nativeCreatePlanes", "(II)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
rennbe092192018-05-07 10:18:05 -07001112 (void*)Image_createSurfacePlanes },
1113 {"nativeGetWidth", "()I", (void*)Image_getWidth },
1114 {"nativeGetHeight", "()I", (void*)Image_getHeight },
1115 {"nativeGetFormat", "()I", (void*)Image_getFormat },
1116 {"nativeGetHardwareBuffer", "()Landroid/hardware/HardwareBuffer;",
1117 (void*)Image_getHardwareBuffer },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001118};
1119
1120int register_android_media_ImageWriter(JNIEnv *env) {
1121
1122 int ret1 = AndroidRuntime::registerNativeMethods(env,
1123 "android/media/ImageWriter", gImageWriterMethods, NELEM(gImageWriterMethods));
1124
1125 int ret2 = AndroidRuntime::registerNativeMethods(env,
1126 "android/media/ImageWriter$WriterSurfaceImage", gImageMethods, NELEM(gImageMethods));
1127
1128 return (ret1 || ret2);
1129}